From b8ae535822b2e7f5754dbc4692bee8bbca82759c Mon Sep 17 00:00:00 2001 From: teomrd Date: Fri, 11 Oct 2024 14:59:29 +0100 Subject: [PATCH] 2.15.16 --- out/index.js | 44 +++++++++++++++++++++---------------------- out/index.js.map | 6 +++--- out/service-worker.js | 2 +- out/version | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 6 files changed, 30 insertions(+), 30 deletions(-) diff --git a/out/index.js b/out/index.js index c212c45..a183c2c 100644 --- a/out/index.js +++ b/out/index.js @@ -127,27 +127,27 @@ `);break;case"code":E=t.subParser("makeMarkdown.codeSpan")(m,y);break;case"em":case"i":E=t.subParser("makeMarkdown.emphasis")(m,y);break;case"strong":case"b":E=t.subParser("makeMarkdown.strong")(m,y);break;case"del":E=t.subParser("makeMarkdown.strikethrough")(m,y);break;case"a":E=t.subParser("makeMarkdown.links")(m,y);break;case"img":E=t.subParser("makeMarkdown.image")(m,y);break;default:E=m.outerHTML+` `}return E}),t.subParser("makeMarkdown.paragraph",function(m,y){"use strict";var b="";if(m.hasChildNodes())for(var E=m.childNodes,v=E.length,S=0;S"+y.preList[b]+""}),t.subParser("makeMarkdown.strikethrough",function(m,y){"use strict";var b="";if(m.hasChildNodes()){b+="~~";for(var E=m.childNodes,v=E.length,S=0;Str>th"),S=m.querySelectorAll("tbody>tr"),A,I;for(A=0;AU&&(U=te)}for(A=0;A/g,"\\$1>"),y=y.replace(/^#/gm,"\\#"),y=y.replace(/^(\s*)([-=]{3,})(\s*)$/,"$1\\$2$3"),y=y.replace(/^( {0,3}\d+)\./gm,"$1\\."),y=y.replace(/^( {0,3})([+-])/gm,"$1\\$2"),y=y.replace(/]([\s]*)\(/g,"\\]$1\\("),y=y.replace(/^ {0,3}\[([\S \t]*?)]:/gm,"\\[$1]:"),y});var x=this;typeof define=="function"&&define.amd?define(function(){"use strict";return t}):typeof x6<"u"&&x6.exports?x6.exports=t:x.showdown=t}).call(wF)});var GF=P((aWe,HF)=>{"use strict";HF.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var _A=P((QF,XF)=>{"use strict";var T6=GF(),{hasOwnProperty:WF}=Object.prototype,{propertyIsEnumerable:Dwe}=Object,F0=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Owe=QF,jF={concatArrays:!1,ignoreUndefined:!1},I6=r=>{let e=[];for(let t in r)WF.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Dwe.call(r,n)&&e.push(n)}return e};function z0(r){return Array.isArray(r)?Lwe(r):T6(r)?Bwe(r):r}function Lwe(r){let e=r.slice(0,0);return I6(r).forEach(t=>{F0(e,t,z0(r[t]))}),e}function Bwe(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return I6(r).forEach(t=>{F0(e,t,z0(r[t]))}),e}var YF=(r,e,t,n)=>(t.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in r&&r[i]!==Object.getPrototypeOf(r)?F0(r,i,bA(r[i],e[i],n)):F0(r,i,z0(e[i])))}),r),Mwe=(r,e,t)=>{let n=r.slice(0,0),i=0;return[r,e].forEach(o=>{let s=[];for(let a=0;a!s.includes(a)),t)}),n};function bA(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Mwe(r,e,t):!T6(e)||!T6(r)?z0(e):YF(r,e,I6(e),t)}XF.exports=function(...r){let e=bA(z0(jF),this!==Owe&&this||{},jF),t={_:{}};for(let n of r)if(n!==void 0){if(!T6(n))throw new TypeError("`"+n+"` is not an Option Object");t=bA(t,{_:n},e)}return t._}});var EA=P((uWe,JF)=>{function Uwe(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}JF.exports=Uwe});var C6=P((lWe,ez)=>{"use strict";var Fwe=EA(),R6=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Hg=Fwe(),zwe=R6&&!Hg,Vwe=Hg&&!R6,Kwe=Hg&&R6,$we=typeof k0=="function"&&typeof process<"u"&&typeof process.release<"u"&&process.release.name==="node"&&!Hg,qwe=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Hwe=typeof process<"u"&&typeof process.env<"u"&&!1,Gwe=typeof navigator<"u"&&navigator.product==="ReactNative";ez.exports={isTest:Hwe,isElectron:Hg,isElectronMain:Vwe,isElectronRenderer:Kwe,isNode:$we,isBrowser:zwe,isWebWorker:qwe,isEnvWithDom:R6,isReactNative:Gwe}});var vA=P((dWe,tz)=>{var V0=1e3,K0=V0*60,$0=K0*60,lh=$0*24,jwe=lh*7,Wwe=lh*365.25;tz.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Ywe(r);if(t==="number"&&isFinite(r))return e.long?Xwe(r):Qwe(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Ywe(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Wwe;case"weeks":case"week":case"w":return t*jwe;case"days":case"day":case"d":return t*lh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*$0;case"minutes":case"minute":case"mins":case"min":case"m":return t*K0;case"seconds":case"second":case"secs":case"sec":case"s":return t*V0;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Qwe(r){var e=Math.abs(r);return e>=lh?Math.round(r/lh)+"d":e>=$0?Math.round(r/$0)+"h":e>=K0?Math.round(r/K0)+"m":e>=V0?Math.round(r/V0)+"s":r+"ms"}function Xwe(r){var e=Math.abs(r);return e>=lh?P6(r,e,lh,"day"):e>=$0?P6(r,e,$0,"hour"):e>=K0?P6(r,e,K0,"minute"):e>=V0?P6(r,e,V0,"second"):r+" ms"}function P6(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var nz=P((hWe,rz)=>{function Zwe(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=vA(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let h=0;h{if(E==="%%")return"%";y++;let S=t.formatters[v];if(typeof S=="function"){let A=w[y];E=S.call(_,A),w.splice(y,1),y--}return E}),t.formatArgs.call(_,w),(_.log||t.log).apply(_,w)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:w=>{h=w}}),typeof t.init=="function"&&t.init(g),g}function n(l,f){let h=t(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=t.skips.length;f{Ro.formatArgs=e5e;Ro.save=t5e;Ro.load=r5e;Ro.useColors=Jwe;Ro.storage=n5e();Ro.destroy=(()=>{let r=!1;return()=>{r||(r=!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`."))}})();Ro.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"];function Jwe(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function e5e(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+k6.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Ro.log=console.debug||console.log||(()=>{});function t5e(r){try{r?Ro.storage.setItem("debug",r):Ro.storage.removeItem("debug")}catch{}}function r5e(){let r;try{r=Ro.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function n5e(){try{return localStorage}catch{}}k6.exports=nz()(Ro);var{formatters:i5e}=k6.exports;i5e.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ee=P((bWe,oz)=>{"use strict";function iz(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function c5e(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return iz(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),iz(new i,t)}}oz.exports=c5e});var N6=P((_We,sz)=>{"use strict";sz.exports=u5e;function u5e(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,o=!0;i{"use strict";var D6=uz;D6.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var q0=new Array(64),cz=new Array(123);for(xa=0;xa<64;)cz[q0[xa]=xa<26?xa+65:xa<52?xa+71:xa<62?xa-4:xa-59|43]=xa++;var xa;D6.encode=function(e,t,n){for(var i=null,o=[],s=0,a=0,c;t>2],c=(u&3)<<4,a=1;break;case 1:o[s++]=q0[c|u>>4],c=(u&15)<<2,a=2;break;case 2:o[s++]=q0[c|u>>6],o[s++]=q0[u&63],a=0;break}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0)}return a&&(o[s++]=q0[c],o[s++]=61,a===1&&(o[s++]=61)),i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))};var az="invalid encoding";D6.decode=function(e,t,n){for(var i=n,o=0,s,a=0;a1)break;if((c=cz[c])===void 0)throw Error(az);switch(o){case 0:s=c,o=1;break;case 1:t[n++]=s<<2|(c&48)>>4,s=c,o=2;break;case 2:t[n++]=(s&15)<<4|(c&60)>>2,s=c,o=3;break;case 3:t[n++]=(s&3)<<6|c,o=0;break}}if(o===1)throw Error(az);return n-i};D6.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var B6=P((vWe,lz)=>{"use strict";lz.exports=L6;function L6(){this._listeners={}}L6.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};L6.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";gz.exports=fz(fz);function fz(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3]}function o(c,u,l){e[0]=c,u[l]=t[3],u[l+1]=t[2],u[l+2]=t[1],u[l+3]=t[0]}r.writeFloatLE=n?i:o,r.writeFloatBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],e[0]}function a(c,u){return t[3]=c[u],t[2]=c[u+1],t[1]=c[u+2],t[0]=c[u+3],e[0]}r.readFloatLE=n?s:a,r.readFloatBE=n?a:s}():function(){function e(n,i,o,s){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,o,s);else if(isNaN(i))n(2143289344,o,s);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,o,s);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,o,s);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,o,s)}}r.writeFloatLE=e.bind(null,dz),r.writeFloatBE=e.bind(null,hz);function t(n,i,o){var s=n(i,o),a=(s>>31)*2+1,c=s>>>23&255,u=s&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}r.readFloatLE=t.bind(null,pz),r.readFloatBE=t.bind(null,mz)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3],u[l+4]=t[4],u[l+5]=t[5],u[l+6]=t[6],u[l+7]=t[7]}function o(c,u,l){e[0]=c,u[l]=t[7],u[l+1]=t[6],u[l+2]=t[5],u[l+3]=t[4],u[l+4]=t[3],u[l+5]=t[2],u[l+6]=t[1],u[l+7]=t[0]}r.writeDoubleLE=n?i:o,r.writeDoubleBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],t[4]=c[u+4],t[5]=c[u+5],t[6]=c[u+6],t[7]=c[u+7],e[0]}function a(c,u){return t[7]=c[u],t[6]=c[u+1],t[5]=c[u+2],t[4]=c[u+3],t[3]=c[u+4],t[2]=c[u+5],t[1]=c[u+6],t[0]=c[u+7],e[0]}r.readDoubleLE=n?s:a,r.readDoubleBE=n?a:s}():function(){function e(n,i,o,s,a,c){var u=s<0?1:0;if(u&&(s=-s),s===0)n(0,a,c+i),n(1/s>0?0:2147483648,a,c+o);else if(isNaN(s))n(0,a,c+i),n(2146959360,a,c+o);else if(s>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+o);else{var l;if(s<22250738585072014e-324)l=s/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+o);else{var f=Math.floor(Math.log(s)/Math.LN2);f===1024&&(f=1023),l=s*Math.pow(2,-f),n(l*4503599627370496>>>0,a,c+i),n((u<<31|f+1023<<20|l*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,dz,0,4),r.writeDoubleBE=e.bind(null,hz,4,0);function t(n,i,o,s,a){var c=n(s,a+i),u=n(s,a+o),l=(u>>31)*2+1,f=u>>>20&2047,h=4294967296*(u&1048575)+c;return f===2047?h?NaN:l*(1/0):f===0?l*5e-324*h:l*Math.pow(2,f-1075)*(h+4503599627370496)}r.readDoubleLE=t.bind(null,pz,0,4),r.readDoubleBE=t.bind(null,mz,4,0)}(),r}function dz(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function hz(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function pz(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function mz(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var U6=P((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var F6=P(yz=>{"use strict";var AA=yz;AA.length=function(e){for(var t=0,n=0,i=0;i191&&c<224?s[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[a++]=55296+(c>>10),s[a++]=56320+(c&1023)):s[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};AA.write=function(e,t,n){for(var i=n,o,s,a=0;a>6|192,t[n++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-i}});var z6=P((AWe,wz)=>{"use strict";wz.exports=l5e;function l5e(r,e,t){var n=t||8192,i=n>>>1,o=null,s=n;return function(c){if(c<1||c>i)return r(c);s+c>n&&(o=r(n),s=0);var u=e.call(o,s,s+=c);return s&7&&(s=(s|7)+1),u}}});var _z=P((TWe,bz)=>{"use strict";bz.exports=Qn;var jg=Du();function Qn(r,e){this.lo=r>>>0,this.hi=e>>>0}var dh=Qn.zero=new Qn(0,0);dh.toNumber=function(){return 0};dh.zzEncode=dh.zzDecode=function(){return this};dh.length=function(){return 1};var f5e=Qn.zeroHash="\0\0\0\0\0\0\0\0";Qn.fromNumber=function(e){if(e===0)return dh;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Qn(n,i)};Qn.from=function(e){if(typeof e=="number")return Qn.fromNumber(e);if(jg.isString(e))if(jg.Long)e=jg.Long.fromString(e);else return Qn.fromNumber(parseInt(e,10));return e.low||e.high?new Qn(e.low>>>0,e.high>>>0):dh};Qn.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};Qn.prototype.toLong=function(e){return jg.Long?new jg.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var of=String.prototype.charCodeAt;Qn.fromHash=function(e){return e===f5e?dh:new Qn((of.call(e,0)|of.call(e,1)<<8|of.call(e,2)<<16|of.call(e,3)<<24)>>>0,(of.call(e,4)|of.call(e,5)<<8|of.call(e,6)<<16|of.call(e,7)<<24)>>>0)};Qn.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};Qn.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};Qn.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};Qn.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var Du=P(TA=>{"use strict";var Le=TA;Le.asPromise=N6();Le.base64=O6();Le.EventEmitter=B6();Le.float=M6();Le.inquire=U6();Le.utf8=F6();Le.pool=z6();Le.LongBits=_z();Le.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Le.global=Le.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||TA;Le.emptyArray=Object.freeze?Object.freeze([]):[];Le.emptyObject=Object.freeze?Object.freeze({}):{};Le.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Le.isString=function(e){return typeof e=="string"||e instanceof String};Le.isObject=function(e){return e&&typeof e=="object"};Le.isset=Le.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Le.Buffer=function(){try{var r=Le.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Le._Buffer_from=null;Le._Buffer_allocUnsafe=null;Le.newBuffer=function(e){return typeof e=="number"?Le.Buffer?Le._Buffer_allocUnsafe(e):new Le.Array(e):Le.Buffer?Le._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Le.Array=typeof Uint8Array<"u"?Uint8Array:Array;Le.Long=Le.global.dcodeIO&&Le.global.dcodeIO.Long||Le.global.Long||Le.inquire("long");Le.key2Re=/^true|false|0|1$/;Le.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Le.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Le.longToHash=function(e){return e?Le.LongBits.from(e).toHash():Le.LongBits.zeroHash};Le.longFromHash=function(e,t){var n=Le.LongBits.fromHash(e);return Le.Long?Le.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Ez(r,e,t){for(var n=Object.keys(e),i=0;i-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Le.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";Tz.exports=Ht;var As=Du(),IA,V6=As.LongBits,xz=As.base64,Sz=As.utf8;function Wg(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function CA(){}function d5e(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Ht(){this.len=0,this.head=new Wg(CA,0,0),this.tail=this.head,this.states=null}var Az=function(){return As.Buffer?function(){return(Ht.create=function(){return new IA})()}:function(){return new Ht}};Ht.create=Az();Ht.alloc=function(e){return new As.Array(e)};As.Array!==Array&&(Ht.alloc=As.pool(Ht.alloc,As.Array.prototype.subarray));Ht.prototype._push=function(e,t,n){return this.tail=this.tail.next=new Wg(e,t,n),this.len+=t,this};function PA(r,e,t){e[t]=r&255}function h5e(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function kA(r,e){this.len=r,this.next=void 0,this.val=e}kA.prototype=Object.create(Wg.prototype);kA.prototype.fn=h5e;Ht.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new kA((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ht.prototype.int32=function(e){return e<0?this._push(NA,10,V6.fromNumber(e)):this.uint32(e)};Ht.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function NA(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Ht.prototype.uint64=function(e){var t=V6.from(e);return this._push(NA,t.length(),t)};Ht.prototype.int64=Ht.prototype.uint64;Ht.prototype.sint64=function(e){var t=V6.from(e).zzEncode();return this._push(NA,t.length(),t)};Ht.prototype.bool=function(e){return this._push(PA,1,e?1:0)};function RA(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Ht.prototype.fixed32=function(e){return this._push(RA,4,e>>>0)};Ht.prototype.sfixed32=Ht.prototype.fixed32;Ht.prototype.fixed64=function(e){var t=V6.from(e);return this._push(RA,4,t.lo)._push(RA,4,t.hi)};Ht.prototype.sfixed64=Ht.prototype.fixed64;Ht.prototype.float=function(e){return this._push(As.float.writeFloatLE,4,e)};Ht.prototype.double=function(e){return this._push(As.float.writeDoubleLE,8,e)};var p5e=As.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(PA,1,0);if(As.isString(e)){var n=Ht.alloc(t=xz.length(e));xz.decode(e,n,0),e=n}return this.uint32(t)._push(p5e,t,e)};Ht.prototype.string=function(e){var t=Sz.length(e);return t?this.uint32(t)._push(Sz.write,t,e):this._push(PA,1,0)};Ht.prototype.fork=function(){return this.states=new d5e(this),this.head=this.tail=new Wg(CA,0,0),this.len=0,this};Ht.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 Wg(CA,0,0),this.len=0),this};Ht.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Ht.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Ht._configure=function(r){IA=r,Ht.create=Az(),IA._configure()}});var DA=P((CWe,Rz)=>{"use strict";Rz.exports=pc;var Iz=K6();(pc.prototype=Object.create(Iz.prototype)).constructor=pc;var sf=Du();function pc(){Iz.call(this)}pc._configure=function(){pc.alloc=sf._Buffer_allocUnsafe,pc.writeBytesBuffer=sf.Buffer&&sf.Buffer.prototype instanceof Uint8Array&&sf.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(pc.writeBytesBuffer,t,e),this};function m5e(r,e,t){r.length<40?sf.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}pc.prototype.string=function(e){var t=sf.Buffer.byteLength(e);return this.uint32(t),t&&this._push(m5e,t,e),this};pc._configure()});var q6=P((PWe,Dz)=>{"use strict";Dz.exports=pn;var mc=Du(),LA,kz=mc.LongBits,g5e=mc.utf8;function Sa(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function pn(r){this.buf=r,this.pos=0,this.len=r.length}var Cz=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new pn(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new pn(e);throw Error("illegal buffer")},Nz=function(){return mc.Buffer?function(t){return(pn.create=function(i){return mc.Buffer.isBuffer(i)?new LA(i):Cz(i)})(t)}:Cz};pn.create=Nz();pn.prototype._slice=mc.Array.prototype.subarray||mc.Array.prototype.slice;pn.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Sa(this,10);return e}}();pn.prototype.int32=function(){return this.uint32()|0};pn.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function OA(){var r=new kz(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Sa(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw Sa(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}pn.prototype.bool=function(){return this.uint32()!==0};function $6(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}pn.prototype.fixed32=function(){if(this.pos+4>this.len)throw Sa(this,4);return $6(this.buf,this.pos+=4)};pn.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Sa(this,4);return $6(this.buf,this.pos+=4)|0};function Pz(){if(this.pos+8>this.len)throw Sa(this,8);return new kz($6(this.buf,this.pos+=4),$6(this.buf,this.pos+=4))}pn.prototype.float=function(){if(this.pos+4>this.len)throw Sa(this,4);var e=mc.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};pn.prototype.double=function(){if(this.pos+8>this.len)throw Sa(this,4);var e=mc.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};pn.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Sa(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};pn.prototype.string=function(){var e=this.bytes();return g5e.read(e,0,e.length)};pn.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Sa(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Sa(this);while(this.buf[this.pos++]&128);return this};pn.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};pn._configure=function(r){LA=r,pn.create=Nz(),LA._configure();var e=mc.Long?"toLong":"toNumber";mc.merge(pn.prototype,{int64:function(){return OA.call(this)[e](!1)},uint64:function(){return OA.call(this)[e](!0)},sint64:function(){return OA.call(this).zzDecode()[e](!1)},fixed64:function(){return Pz.call(this)[e](!0)},sfixed64:function(){return Pz.call(this)[e](!1)}})}});var BA=P((kWe,Bz)=>{"use strict";Bz.exports=hh;var Lz=q6();(hh.prototype=Object.create(Lz.prototype)).constructor=hh;var Oz=Du();function hh(r){Lz.call(this,r)}hh._configure=function(){Oz.Buffer&&(hh.prototype._slice=Oz.Buffer.prototype.slice)};hh.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))};hh._configure()});var Uz=P((NWe,Mz)=>{"use strict";Mz.exports=Yg;var MA=Du();(Yg.prototype=Object.create(MA.EventEmitter.prototype)).constructor=Yg;function Yg(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");MA.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}Yg.prototype.rpcCall=function r(e,t,n,i,o){if(!i)throw TypeError("request must be specified");var s=this;if(!o)return MA.asPromise(r,s,e,t,n,i);if(!s.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return s.rpcImpl(e,t[s.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return s.emit("error",c,e),o(c);if(u===null){s.end(!0);return}if(!(u instanceof n))try{u=n[s.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return s.emit("error",l,e),o(l)}return s.emit("data",u,e),o(null,u)})}catch(a){s.emit("error",a,e),setTimeout(function(){o(a)},0);return}};Yg.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var zz=P(Fz=>{"use strict";var y5e=Fz;y5e.Service=Uz()});var Kz=P((OWe,Vz)=>{"use strict";Vz.exports={}});var Hz=P(qz=>{"use strict";var fo=qz;fo.build="minimal";fo.Writer=K6();fo.BufferWriter=DA();fo.Reader=q6();fo.BufferReader=BA();fo.util=Du();fo.rpc=zz();fo.roots=Kz();fo.configure=$z;function $z(){fo.util._configure(),fo.Writer._configure(fo.BufferWriter),fo.Reader._configure(fo.BufferReader)}$z()});var gc=P((BWe,Gz)=>{"use strict";Gz.exports=Hz()});var xq=P((cJe,vq)=>{"use strict";vq.exports=function(){return Date.now()}});var vI=P((uJe,Sq)=>{"use strict";var R8=xq(),EI=class{constructor(e,t,n){let i=this;this._started=R8(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(R8()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,t)}reschedule(e){e||(e=this._scheduled);let t=R8();t+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=t,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=R8(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function w_e(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var e=0;e{"use strict";var{AbortController:b_e}=globalThis,Aq=vI(),vy=class extends b_e{constructor(e){super(),this._ms=e,this._timer=Aq(()=>this.abort(),e),Object.setPrototypeOf(this,vy.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=Aq(()=>this.abort(),this._ms)}};Tq.exports={TimeoutController:vy}});var iR=P((mtt,nH)=>{"use strict";var yEe=typeof navigator<"u"&&navigator.product==="ReactNative";function wEe(){return yEe?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}var Iy=self.URL,rH=wEe(),nR=class{constructor(e="",t=rH){this.super=new Iy(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return Iy.createObjectURL(e)}static revokeObjectURL(e){Iy.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}};function bEe(r){if(typeof r=="string")return new Iy(r).toString();if(!(r instanceof Iy)){let e=r.username&&r.password?`${r.username}:${r.password}@`:"",t=r.auth?r.auth+"@":"",n=r.port?":"+r.port:"",i=r.protocol?r.protocol+"//":"",o=r.host||"",s=r.hostname||"",a=r.search||(r.query?"?"+r.query:""),c=r.hash||"",u=r.pathname||"",l=r.path||u+a;return`${i}${e||t}${o||s+n}${l}${c}`}}nH.exports={URLWithLegacySupport:nR,URLSearchParams:self.URLSearchParams,defaultBase:rH,format:bEe}});var sH=P((gtt,oH)=>{"use strict";var{URLWithLegacySupport:iH,format:_Ee}=iR();oH.exports=(r,e={},t={},n)=>{let i=e.protocol?e.protocol.replace(":",""):"http";i=(t[i]||n||i)+":";let o;try{o=new iH(r)}catch{o={}}let s=Object.assign({},e,{protocol:i||o.protocol,host:e.host||o.host});return new iH(r,_Ee(s)).toString()}});var F8=P((ytt,aH)=>{"use strict";var{URLWithLegacySupport:EEe,format:vEe,URLSearchParams:xEe,defaultBase:SEe}=iR(),AEe=sH();aH.exports={URL:EEe,URLSearchParams:xEe,format:vEe,relative:AEe,defaultBase:SEe}});var Da=P((irt,gR)=>{function AH(r){let e=new globalThis.AbortController;function t(){e.abort();for(let n of r)!n||!n.removeEventListener||n.removeEventListener("abort",t)}for(let n of r)if(!(!n||!n.addEventListener)){if(n.aborted){t();break}n.addEventListener("abort",t)}return e.signal}gR.exports=AH;gR.exports.anySignal=AH});var Cy=P((Srt,LH)=>{LH.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var UH=P((Trt,bR)=>{"use strict";var QEe=Object.prototype.hasOwnProperty,Zi="~";function Py(){}Object.create&&(Py.prototype=Object.create(null),new Py().__proto__||(Zi=!1));function XEe(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function MH(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new XEe(t,n||r,i),s=Zi?Zi+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function Q8(r,e){--r._eventsCount===0?r._events=new Py:delete r._events[e]}function ki(){this._events=new Py,this._eventsCount=0}ki.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)QEe.call(t,n)&&e.push(Zi?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ki.prototype.listeners=function(e){var t=Zi?Zi+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i{"use strict";var TR=class extends Error{constructor(e="Request timed out"){super(e),this.name="TimeoutError"}};ob.TimeoutError=TR;var IR=class extends Error{constructor(e="The operation was aborted."){super(e),this.name="AbortError"}};ob.AbortError=IR;var RR=class extends Error{constructor(e){super(e.statusText),this.name="HTTPError",this.response=e}};ob.HTTPError=RR});var My=P((D1,WH)=>{"use strict";var ZEe=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof globalThis<"u")return globalThis;throw new Error("unable to locate global object")},Ch=ZEe();WH.exports=D1=Ch.fetch;Ch.fetch&&(D1.default=Ch.fetch.bind(Ch));D1.Headers=Ch.Headers;D1.Request=Ch.Request;D1.Response=Ch.Response});var YH=P((Mrt,PR)=>{"use strict";globalThis.fetch&&globalThis.Headers&&globalThis.Request&&globalThis.Response?PR.exports={default:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response}:PR.exports={default:My().default,Headers:My().Headers,Request:My().Request,Response:My().Response}});var XH=P((Urt,QH)=>{"use strict";QH.exports=YH()});var eG=P((Frt,JH)=>{"use strict";var{TimeoutError:JEe,AbortError:e7e}=CR(),{Response:ZH,Request:t7e,Headers:NR,default:r7e}=XH(),n7e=(r,e={})=>{let t=new XMLHttpRequest;t.open(e.method||"GET",r.toString(),!0);let{timeout:n,headers:i}=e;if(n&&n>0&&n<1/0&&(t.timeout=n),e.overrideMimeType!=null&&t.overrideMimeType(e.overrideMimeType),i)for(let[o,s]of new NR(i))t.setRequestHeader(o,s);return e.signal&&(e.signal.onabort=()=>t.abort()),e.onUploadProgress&&(t.upload.onprogress=e.onUploadProgress),t.responseType="arraybuffer",new Promise((o,s)=>{let a=c=>{switch(c.type){case"error":{o(ZH.error());break}case"load":{o(new kR(t.responseURL,t.response,{status:t.status,statusText:t.statusText,headers:s7e(t.getAllResponseHeaders())}));break}case"timeout":{s(new JEe);break}case"abort":{s(new e7e);break}default:break}};t.onerror=a,t.onload=a,t.ontimeout=a,t.onabort=a,t.send(e.body)})},i7e=r7e,o7e=(r,e={})=>e.onUploadProgress!=null?n7e(r,e):i7e(r,e),s7e=r=>{let e=new NR;for(let t of r.trim().split(/[\r\n]+/)){let n=t.indexOf(": ");n>0&&e.set(t.slice(0,n),t.slice(n+1))}return e},kR=class extends ZH{constructor(e,t,n){super(t,n),Object.defineProperty(this,"url",{value:e})}};JH.exports={fetch:o7e,Request:t7e,Headers:NR}});var rG=P((zrt,tG)=>{"use strict";async function*a7e(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&t.cancel(),t.releaseLock()}}tG.exports=a7e});var iG=P((Vrt,nG)=>{"use strict";var c7e=async r=>{let e=[];for await(let t of r)e.push(t);return e};nG.exports=c7e});var O1=P((Krt,lG)=>{"use strict";var{fetch:u7e,Request:l7e,Headers:f7e}=eG(),{TimeoutError:DR,HTTPError:cG}=CR(),oG=_A().bind({ignoreUndefined:!0}),{URL:sG,URLSearchParams:aG}=F8(),d7e=Da(),h7e=rG(),{isBrowser:p7e,isWebWorker:m7e}=C6(),g7e=iG(),y7e=(r,e,t)=>{if(e===void 0)return r;let n=Date.now(),i=()=>Date.now()-n>=e;return new Promise((o,s)=>{let a=setTimeout(()=>{i()&&(s(new DR),t.abort())},e),c=u=>f=>{if(clearTimeout(a),i()){s(new DR);return}u(f)};r.then(c(o),c(s))})},w7e={throwHttpErrors:!0,credentials:"same-origin"},Ni=class{constructor(e={}){this.opts=oG(w7e,e)}async fetch(e,t={}){let n=oG(this.opts,t),i=new f7e(n.headers);if(typeof e!="string"&&!(e instanceof sG||e instanceof l7e))throw new TypeError("`resource` must be a string, URL, or Request");let o=new sG(e.toString(),n.base),{searchParams:s,transformSearchParams:a,json:c}=n;s&&(typeof a=="function"?o.search=a(new aG(n.searchParams)):o.search=new aG(n.searchParams)),c&&(n.body=JSON.stringify(n.json),i.set("content-type","application/json"));let u=new AbortController,l=d7e([u.signal,n.signal]);globalThis.ReadableStream!=null&&n.body instanceof globalThis.ReadableStream&&(p7e||m7e)&&(n.body=new Blob(await g7e(h7e(n.body))));let f=await y7e(u7e(o.toString(),{...n,signal:l,timeout:void 0,headers:i,duplex:"half"}),n.timeout,u);if(!f.ok&&n.throwHttpErrors)throw n.handleError&&await n.handleError(f),new cG(f);return f.iterator=async function*(){yield*uG(f.body)},f.ndjson=async function*(){for await(let h of b7e(f.iterator()))t.transform?yield t.transform(h):yield h},f}post(e,t={}){return this.fetch(e,{...t,method:"POST"})}get(e,t={}){return this.fetch(e,{...t,method:"GET"})}put(e,t={}){return this.fetch(e,{...t,method:"PUT"})}delete(e,t={}){return this.fetch(e,{...t,method:"DELETE"})}options(e,t={}){return this.fetch(e,{...t,method:"OPTIONS"})}},b7e=async function*(r){let e=new TextDecoder,t="";for await(let n of r){t+=e.decode(n,{stream:!0});let i=t.split(/\r?\n/);for(let o=0;o0&&(yield JSON.parse(s))}t=i[i.length-1]}t+=e.decode(),t=t.trim(),t.length!==0&&(yield JSON.parse(t))},uG=r=>{if(_7e(r))return r;if(v7e(r)){let e=r[Symbol.asyncIterator]();return{[Symbol.asyncIterator](){return{next:e.next.bind(e),return(t){return r.destroy(),typeof e.return=="function"?e.return():Promise.resolve({done:!0,value:t})}}}}}if(E7e(r)){let e=r.getReader();return async function*(){try{for(;;){let{done:t,value:n}=await e.read();if(t)return;n&&(yield n)}}finally{e.releaseLock()}}()}throw new TypeError("Body can't be converted to AsyncIterable")},_7e=r=>typeof r=="object"&&r!==null&&typeof r[Symbol.asyncIterator]=="function",E7e=r=>r&&typeof r.getReader=="function",v7e=r=>Object.prototype.hasOwnProperty.call(r,"readable")&&Object.prototype.hasOwnProperty.call(r,"writable");Ni.HTTPError=cG;Ni.TimeoutError=DR;Ni.streamToAsyncIterator=uG;Ni.post=(r,e)=>new Ni(e).post(r,e);Ni.get=(r,e)=>new Ni(e).get(r,e);Ni.put=(r,e)=>new Ni(e).put(r,e);Ni.delete=(r,e)=>new Ni(e).delete(r,e);Ni.options=(r,e)=>new Ni(e).options(r,e);lG.exports=Ni});var AG=P((Wnt,FR)=>{var jnt=function(){typeof FR<"u"&&(FR.exports=g);var r=86400,e=3200,t=146097*e/400,n=r*t,i=1e3*n,o=864e13,s=4294967296,a=1e6,c="000000000",u=Math.trunc||function(S){var A=S-S%1;return A==0&&(S<0||S===0&&1/S!=1/0)?-0:A},l=g.prototype,f=(g.fromDate=function(S){return new g(+S)},g.fromInt64BE=y(0,1,2,3,0,4),g.fromInt64LE=y(3,2,1,0,4,0),g.fromString=function(k){var A,I=new g,k=(k+="").replace(/^\s*[+\-]?\d+/,function(O){var O=+O,G=1970+(O-1970)%400;return I.year=O-G,G}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(N,O,G){return O<0&&(G*=-1),A=6e4*(60*+O+ +G),""}).replace(/\.\d+$/,function(N){return I.nano=+(N+c).substr(1,9),""}).split(/\D+/);if(1>24&255,R[K+A]=U>>16&255,R[K+I]=U>>8&255,R[K+k]=255&U}}function y(S,A,I,k,N,O){return function(R,K){b(R,K|=0);var U=G(R,K+N);return x(G(R,K+O),U)};function G(R,K){return 16777216*R[K+S]+(R[K+A]<<16|R[K+I]<<8|R[K+k])}}function b(S,A){if(S=S&&S.length,S==null)throw new TypeError("Invalid Buffer");if(S{TG.exports={options:{usePureJavaScript:!1}}});var CG=P((Qnt,RG)=>{var zR={};RG.exports=zR;var IG={};zR.encode=function(r,e,t){if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');if(t!==void 0&&typeof t!="number")throw new TypeError('"maxline" must be a number.');var n="";if(!(r instanceof Uint8Array))n=O7e(r,e);else{var i=0,o=e.length,s=e.charAt(0),a=[0];for(i=0;i0;)a.push(u%o),u=u/o|0}for(i=0;r[i]===0&&i=0;--i)n+=e[a[i]]}if(t){var l=new RegExp(".{1,"+t+"}","g");n=n.match(l).join(`\r -`)}return n};zR.decode=function(r,e){if(typeof r!="string")throw new TypeError('"input" must be a string.');if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');var t=IG[e];if(!t){t=IG[e]=[];for(var n=0;n>=8;for(;u>0;)s.push(u&255),u>>=8}for(var l=0;r[l]===o&&l0;)o.push(a%n),a=a/n|0}var c="";for(t=0;r.at(t)===0&&t=0;--t)c+=e[o[t]];return c}});var gr=P((Xnt,DG)=>{var PG=at(),kG=CG(),F=DG.exports=PG.util=PG.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){F.nextTick=process.nextTick,typeof setImmediate=="function"?F.setImmediate=setImmediate:F.setImmediate=F.nextTick;return}if(typeof setImmediate=="function"){F.setImmediate=function(){return setImmediate.apply(void 0,arguments)},F.nextTick=function(a){return setImmediate(a)};return}if(F.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage=="function"){let a=function(c){if(c.source===window&&c.data===r){c.stopPropagation();var u=e.slice();e.length=0,u.forEach(function(l){l()})}};var s=a,r="forge.setImmediate",e=[];F.setImmediate=function(c){e.push(c),e.length===1&&window.postMessage(r,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var t=Date.now(),n=!0,i=document.createElement("div"),e=[];new MutationObserver(function(){var c=e.slice();e.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var o=F.setImmediate;F.setImmediate=function(c){Date.now()-t>15?(t=Date.now(),o(c)):(e.push(c),e.length===1&&i.setAttribute("a",n=!n))}}F.nextTick=F.setImmediate})();F.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;F.globalScope=function(){return F.isNodejs?globalThis:typeof self>"u"?window:self}();F.isArray=Array.isArray||function(r){return Object.prototype.toString.call(r)==="[object Array]"};F.isArrayBuffer=function(r){return typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer};F.isArrayBufferView=function(r){return r&&F.isArrayBuffer(r.buffer)&&r.byteLength!==void 0};function zy(r){if(!(r===8||r===16||r===24||r===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+r)}F.ByteBuffer=VR;function VR(r){if(this.data="",this.read=0,typeof r=="string")this.data=r;else if(F.isArrayBuffer(r)||F.isArrayBufferView(r))if(typeof Buffer<"u"&&r instanceof Buffer)this.data=r.toString("binary");else{var e=new Uint8Array(r);try{this.data=String.fromCharCode.apply(null,e)}catch{for(var t=0;tL7e&&(this.data.substr(0,1),this._constructedStringLength=0)};F.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};F.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};F.ByteStringBuffer.prototype.putByte=function(r){return this.putBytes(String.fromCharCode(r))};F.ByteStringBuffer.prototype.fillWithByte=function(r,e){r=String.fromCharCode(r);for(var t=this.data;e>0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return this.data=t,this._optimizeConstructedString(e),this};F.ByteStringBuffer.prototype.putBytes=function(r){return this.data+=r,this._optimizeConstructedString(r.length),this};F.ByteStringBuffer.prototype.putString=function(r){return this.putBytes(F.encodeUtf8(r))};F.ByteStringBuffer.prototype.putInt16=function(r){return this.putBytes(String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};F.ByteStringBuffer.prototype.putInt24=function(r){return this.putBytes(String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};F.ByteStringBuffer.prototype.putInt32=function(r){return this.putBytes(String.fromCharCode(r>>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};F.ByteStringBuffer.prototype.putInt16Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255))};F.ByteStringBuffer.prototype.putInt24Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255))};F.ByteStringBuffer.prototype.putInt32Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>24&255))};F.ByteStringBuffer.prototype.putInt=function(r,e){zy(e);var t="";do e-=8,t+=String.fromCharCode(r>>e&255);while(e>0);return this.putBytes(t)};F.ByteStringBuffer.prototype.putSignedInt=function(r,e){return r<0&&(r+=2<0);return e};F.ByteStringBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<=t&&(e-=t<<1),e};F.ByteStringBuffer.prototype.getBytes=function(r){var e;return r?(r=Math.min(this.length(),r),e=this.data.slice(this.read,this.read+r),this.read+=r):r===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};F.ByteStringBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};F.ByteStringBuffer.prototype.at=function(r){return this.data.charCodeAt(this.read+r)};F.ByteStringBuffer.prototype.setAt=function(r,e){return this.data=this.data.substr(0,this.read+r)+String.fromCharCode(e)+this.data.substr(this.read+r+1),this};F.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};F.ByteStringBuffer.prototype.copy=function(){var r=F.createBuffer(this.data);return r.read=this.read,r};F.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};F.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};F.ByteStringBuffer.prototype.truncate=function(r){var e=Math.max(0,this.length()-r);return this.data=this.data.substr(this.read,e),this.read=0,this};F.ByteStringBuffer.prototype.toHex=function(){for(var r="",e=this.read;e=r)return this;e=Math.max(e||this.growSize,r);var t=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+e);return n.set(t),this.data=new DataView(n.buffer),this};F.DataBuffer.prototype.putByte=function(r){return this.accommodate(1),this.data.setUint8(this.write++,r),this};F.DataBuffer.prototype.fillWithByte=function(r,e){this.accommodate(e);for(var t=0;t>8&65535),this.data.setInt8(this.write,r>>16&255),this.write+=3,this};F.DataBuffer.prototype.putInt32=function(r){return this.accommodate(4),this.data.setInt32(this.write,r),this.write+=4,this};F.DataBuffer.prototype.putInt16Le=function(r){return this.accommodate(2),this.data.setInt16(this.write,r,!0),this.write+=2,this};F.DataBuffer.prototype.putInt24Le=function(r){return this.accommodate(3),this.data.setInt8(this.write,r>>16&255),this.data.setInt16(this.write,r>>8&65535,!0),this.write+=3,this};F.DataBuffer.prototype.putInt32Le=function(r){return this.accommodate(4),this.data.setInt32(this.write,r,!0),this.write+=4,this};F.DataBuffer.prototype.putInt=function(r,e){zy(e),this.accommodate(e/8);do e-=8,this.data.setInt8(this.write++,r>>e&255);while(e>0);return this};F.DataBuffer.prototype.putSignedInt=function(r,e){return zy(e),this.accommodate(e/8),r<0&&(r+=2<0);return e};F.DataBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<=t&&(e-=t<<1),e};F.DataBuffer.prototype.getBytes=function(r){var e;return r?(r=Math.min(this.length(),r),e=this.data.slice(this.read,this.read+r),this.read+=r):r===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};F.DataBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};F.DataBuffer.prototype.at=function(r){return this.data.getUint8(this.read+r)};F.DataBuffer.prototype.setAt=function(r,e){return this.data.setUint8(r,e),this};F.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};F.DataBuffer.prototype.copy=function(){return new F.DataBuffer(this)};F.DataBuffer.prototype.compact=function(){if(this.read>0){var r=new Uint8Array(this.data.buffer,this.read),e=new Uint8Array(r.byteLength);e.set(r),this.data=new DataView(e),this.write-=this.read,this.read=0}return this};F.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};F.DataBuffer.prototype.truncate=function(r){return this.write=Math.max(0,this.length()-r),this.read=Math.min(this.read,this.write),this};F.DataBuffer.prototype.toHex=function(){for(var r="",e=this.read;e0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return t};F.xorBytes=function(r,e,t){for(var n="",i="",o="",s=0,a=0;t>0;--t,++s)i=r.charCodeAt(s)^e.charCodeAt(s),a>=10&&(n+=o,o="",a=0),o+=String.fromCharCode(i),++a;return n+=o,n};F.hexToBytes=function(r){var e="",t=0;for(r.length&!0&&(t=1,e+=String.fromCharCode(parseInt(r[0],16)));t>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255)};var Bf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Mf=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],NG="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";F.encode64=function(r,e){for(var t="",n="",i,o,s,a=0;a>2),t+=Bf.charAt((i&3)<<4|o>>4),isNaN(o)?t+="==":(t+=Bf.charAt((o&15)<<2|s>>6),t+=isNaN(s)?"=":Bf.charAt(s&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r +`}return b.trim()}),t.subParser("makeMarkdown.tableCell",function(m,y){"use strict";var b="";if(!m.hasChildNodes())return"";for(var E=m.childNodes,v=E.length,S=0;S/g,"\\$1>"),y=y.replace(/^#/gm,"\\#"),y=y.replace(/^(\s*)([-=]{3,})(\s*)$/,"$1\\$2$3"),y=y.replace(/^( {0,3}\d+)\./gm,"$1\\."),y=y.replace(/^( {0,3})([+-])/gm,"$1\\$2"),y=y.replace(/]([\s]*)\(/g,"\\]$1\\("),y=y.replace(/^ {0,3}\[([\S \t]*?)]:/gm,"\\[$1]:"),y});var x=this;typeof define=="function"&&define.amd?define(function(){"use strict";return t}):typeof x6<"u"&&x6.exports?x6.exports=t:x.showdown=t}).call(wF)});var GF=P((cWe,HF)=>{"use strict";HF.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var _A=P((QF,XF)=>{"use strict";var T6=GF(),{hasOwnProperty:WF}=Object.prototype,{propertyIsEnumerable:Dwe}=Object,F0=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Owe=QF,jF={concatArrays:!1,ignoreUndefined:!1},I6=r=>{let e=[];for(let t in r)WF.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Dwe.call(r,n)&&e.push(n)}return e};function z0(r){return Array.isArray(r)?Lwe(r):T6(r)?Bwe(r):r}function Lwe(r){let e=r.slice(0,0);return I6(r).forEach(t=>{F0(e,t,z0(r[t]))}),e}function Bwe(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return I6(r).forEach(t=>{F0(e,t,z0(r[t]))}),e}var YF=(r,e,t,n)=>(t.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in r&&r[i]!==Object.getPrototypeOf(r)?F0(r,i,bA(r[i],e[i],n)):F0(r,i,z0(e[i])))}),r),Mwe=(r,e,t)=>{let n=r.slice(0,0),i=0;return[r,e].forEach(o=>{let s=[];for(let a=0;a!s.includes(a)),t)}),n};function bA(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Mwe(r,e,t):!T6(e)||!T6(r)?z0(e):YF(r,e,I6(e),t)}XF.exports=function(...r){let e=bA(z0(jF),this!==Owe&&this||{},jF),t={_:{}};for(let n of r)if(n!==void 0){if(!T6(n))throw new TypeError("`"+n+"` is not an Option Object");t=bA(t,{_:n},e)}return t._}});var EA=P((lWe,JF)=>{function Uwe(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}JF.exports=Uwe});var C6=P((fWe,ez)=>{"use strict";var Fwe=EA(),R6=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Hg=Fwe(),zwe=R6&&!Hg,Vwe=Hg&&!R6,Kwe=Hg&&R6,$we=typeof k0=="function"&&typeof process<"u"&&typeof process.release<"u"&&process.release.name==="node"&&!Hg,qwe=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Hwe=typeof process<"u"&&typeof process.env<"u"&&!1,Gwe=typeof navigator<"u"&&navigator.product==="ReactNative";ez.exports={isTest:Hwe,isElectron:Hg,isElectronMain:Vwe,isElectronRenderer:Kwe,isNode:$we,isBrowser:zwe,isWebWorker:qwe,isEnvWithDom:R6,isReactNative:Gwe}});var vA=P((hWe,tz)=>{var V0=1e3,K0=V0*60,$0=K0*60,lh=$0*24,jwe=lh*7,Wwe=lh*365.25;tz.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Ywe(r);if(t==="number"&&isFinite(r))return e.long?Xwe(r):Qwe(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Ywe(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Wwe;case"weeks":case"week":case"w":return t*jwe;case"days":case"day":case"d":return t*lh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*$0;case"minutes":case"minute":case"mins":case"min":case"m":return t*K0;case"seconds":case"second":case"secs":case"sec":case"s":return t*V0;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Qwe(r){var e=Math.abs(r);return e>=lh?Math.round(r/lh)+"d":e>=$0?Math.round(r/$0)+"h":e>=K0?Math.round(r/K0)+"m":e>=V0?Math.round(r/V0)+"s":r+"ms"}function Xwe(r){var e=Math.abs(r);return e>=lh?P6(r,e,lh,"day"):e>=$0?P6(r,e,$0,"hour"):e>=K0?P6(r,e,K0,"minute"):e>=V0?P6(r,e,V0,"second"):r+" ms"}function P6(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var nz=P((pWe,rz)=>{function Zwe(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=vA(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let h=0;h{if(E==="%%")return"%";y++;let S=t.formatters[v];if(typeof S=="function"){let A=w[y];E=S.call(_,A),w.splice(y,1),y--}return E}),t.formatArgs.call(_,w),(_.log||t.log).apply(_,w)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:w=>{h=w}}),typeof t.init=="function"&&t.init(g),g}function n(l,f){let h=t(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=t.skips.length;f{Ro.formatArgs=e5e;Ro.save=t5e;Ro.load=r5e;Ro.useColors=Jwe;Ro.storage=n5e();Ro.destroy=(()=>{let r=!1;return()=>{r||(r=!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`."))}})();Ro.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"];function Jwe(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function e5e(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+k6.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Ro.log=console.debug||console.log||(()=>{});function t5e(r){try{r?Ro.storage.setItem("debug",r):Ro.storage.removeItem("debug")}catch{}}function r5e(){let r;try{r=Ro.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function n5e(){try{return localStorage}catch{}}k6.exports=nz()(Ro);var{formatters:i5e}=k6.exports;i5e.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ee=P((_We,oz)=>{"use strict";function iz(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function c5e(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return iz(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),iz(new i,t)}}oz.exports=c5e});var N6=P((EWe,sz)=>{"use strict";sz.exports=u5e;function u5e(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,o=!0;i{"use strict";var D6=uz;D6.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var q0=new Array(64),cz=new Array(123);for(xa=0;xa<64;)cz[q0[xa]=xa<26?xa+65:xa<52?xa+71:xa<62?xa-4:xa-59|43]=xa++;var xa;D6.encode=function(e,t,n){for(var i=null,o=[],s=0,a=0,c;t>2],c=(u&3)<<4,a=1;break;case 1:o[s++]=q0[c|u>>4],c=(u&15)<<2,a=2;break;case 2:o[s++]=q0[c|u>>6],o[s++]=q0[u&63],a=0;break}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0)}return a&&(o[s++]=q0[c],o[s++]=61,a===1&&(o[s++]=61)),i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))};var az="invalid encoding";D6.decode=function(e,t,n){for(var i=n,o=0,s,a=0;a1)break;if((c=cz[c])===void 0)throw Error(az);switch(o){case 0:s=c,o=1;break;case 1:t[n++]=s<<2|(c&48)>>4,s=c,o=2;break;case 2:t[n++]=(s&15)<<4|(c&60)>>2,s=c,o=3;break;case 3:t[n++]=(s&3)<<6|c,o=0;break}}if(o===1)throw Error(az);return n-i};D6.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var B6=P((xWe,lz)=>{"use strict";lz.exports=L6;function L6(){this._listeners={}}L6.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};L6.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";gz.exports=fz(fz);function fz(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3]}function o(c,u,l){e[0]=c,u[l]=t[3],u[l+1]=t[2],u[l+2]=t[1],u[l+3]=t[0]}r.writeFloatLE=n?i:o,r.writeFloatBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],e[0]}function a(c,u){return t[3]=c[u],t[2]=c[u+1],t[1]=c[u+2],t[0]=c[u+3],e[0]}r.readFloatLE=n?s:a,r.readFloatBE=n?a:s}():function(){function e(n,i,o,s){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,o,s);else if(isNaN(i))n(2143289344,o,s);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,o,s);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,o,s);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,o,s)}}r.writeFloatLE=e.bind(null,dz),r.writeFloatBE=e.bind(null,hz);function t(n,i,o){var s=n(i,o),a=(s>>31)*2+1,c=s>>>23&255,u=s&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}r.readFloatLE=t.bind(null,pz),r.readFloatBE=t.bind(null,mz)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3],u[l+4]=t[4],u[l+5]=t[5],u[l+6]=t[6],u[l+7]=t[7]}function o(c,u,l){e[0]=c,u[l]=t[7],u[l+1]=t[6],u[l+2]=t[5],u[l+3]=t[4],u[l+4]=t[3],u[l+5]=t[2],u[l+6]=t[1],u[l+7]=t[0]}r.writeDoubleLE=n?i:o,r.writeDoubleBE=n?o:i;function s(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],t[4]=c[u+4],t[5]=c[u+5],t[6]=c[u+6],t[7]=c[u+7],e[0]}function a(c,u){return t[7]=c[u],t[6]=c[u+1],t[5]=c[u+2],t[4]=c[u+3],t[3]=c[u+4],t[2]=c[u+5],t[1]=c[u+6],t[0]=c[u+7],e[0]}r.readDoubleLE=n?s:a,r.readDoubleBE=n?a:s}():function(){function e(n,i,o,s,a,c){var u=s<0?1:0;if(u&&(s=-s),s===0)n(0,a,c+i),n(1/s>0?0:2147483648,a,c+o);else if(isNaN(s))n(0,a,c+i),n(2146959360,a,c+o);else if(s>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+o);else{var l;if(s<22250738585072014e-324)l=s/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+o);else{var f=Math.floor(Math.log(s)/Math.LN2);f===1024&&(f=1023),l=s*Math.pow(2,-f),n(l*4503599627370496>>>0,a,c+i),n((u<<31|f+1023<<20|l*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,dz,0,4),r.writeDoubleBE=e.bind(null,hz,4,0);function t(n,i,o,s,a){var c=n(s,a+i),u=n(s,a+o),l=(u>>31)*2+1,f=u>>>20&2047,h=4294967296*(u&1048575)+c;return f===2047?h?NaN:l*(1/0):f===0?l*5e-324*h:l*Math.pow(2,f-1075)*(h+4503599627370496)}r.readDoubleLE=t.bind(null,pz,0,4),r.readDoubleBE=t.bind(null,mz,4,0)}(),r}function dz(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function hz(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function pz(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function mz(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var U6=P((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var F6=P(yz=>{"use strict";var AA=yz;AA.length=function(e){for(var t=0,n=0,i=0;i191&&c<224?s[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[a++]=55296+(c>>10),s[a++]=56320+(c&1023)):s[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};AA.write=function(e,t,n){for(var i=n,o,s,a=0;a>6|192,t[n++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-i}});var z6=P((TWe,wz)=>{"use strict";wz.exports=l5e;function l5e(r,e,t){var n=t||8192,i=n>>>1,o=null,s=n;return function(c){if(c<1||c>i)return r(c);s+c>n&&(o=r(n),s=0);var u=e.call(o,s,s+=c);return s&7&&(s=(s|7)+1),u}}});var _z=P((IWe,bz)=>{"use strict";bz.exports=Qn;var jg=Du();function Qn(r,e){this.lo=r>>>0,this.hi=e>>>0}var dh=Qn.zero=new Qn(0,0);dh.toNumber=function(){return 0};dh.zzEncode=dh.zzDecode=function(){return this};dh.length=function(){return 1};var f5e=Qn.zeroHash="\0\0\0\0\0\0\0\0";Qn.fromNumber=function(e){if(e===0)return dh;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Qn(n,i)};Qn.from=function(e){if(typeof e=="number")return Qn.fromNumber(e);if(jg.isString(e))if(jg.Long)e=jg.Long.fromString(e);else return Qn.fromNumber(parseInt(e,10));return e.low||e.high?new Qn(e.low>>>0,e.high>>>0):dh};Qn.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};Qn.prototype.toLong=function(e){return jg.Long?new jg.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var of=String.prototype.charCodeAt;Qn.fromHash=function(e){return e===f5e?dh:new Qn((of.call(e,0)|of.call(e,1)<<8|of.call(e,2)<<16|of.call(e,3)<<24)>>>0,(of.call(e,4)|of.call(e,5)<<8|of.call(e,6)<<16|of.call(e,7)<<24)>>>0)};Qn.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};Qn.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};Qn.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};Qn.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var Du=P(TA=>{"use strict";var Be=TA;Be.asPromise=N6();Be.base64=O6();Be.EventEmitter=B6();Be.float=M6();Be.inquire=U6();Be.utf8=F6();Be.pool=z6();Be.LongBits=_z();Be.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Be.global=Be.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||TA;Be.emptyArray=Object.freeze?Object.freeze([]):[];Be.emptyObject=Object.freeze?Object.freeze({}):{};Be.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Be.isString=function(e){return typeof e=="string"||e instanceof String};Be.isObject=function(e){return e&&typeof e=="object"};Be.isset=Be.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Be.Buffer=function(){try{var r=Be.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Be._Buffer_from=null;Be._Buffer_allocUnsafe=null;Be.newBuffer=function(e){return typeof e=="number"?Be.Buffer?Be._Buffer_allocUnsafe(e):new Be.Array(e):Be.Buffer?Be._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Be.Array=typeof Uint8Array<"u"?Uint8Array:Array;Be.Long=Be.global.dcodeIO&&Be.global.dcodeIO.Long||Be.global.Long||Be.inquire("long");Be.key2Re=/^true|false|0|1$/;Be.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Be.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Be.longToHash=function(e){return e?Be.LongBits.from(e).toHash():Be.LongBits.zeroHash};Be.longFromHash=function(e,t){var n=Be.LongBits.fromHash(e);return Be.Long?Be.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Ez(r,e,t){for(var n=Object.keys(e),i=0;i-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Be.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";Tz.exports=Ht;var As=Du(),IA,V6=As.LongBits,xz=As.base64,Sz=As.utf8;function Wg(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function CA(){}function d5e(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Ht(){this.len=0,this.head=new Wg(CA,0,0),this.tail=this.head,this.states=null}var Az=function(){return As.Buffer?function(){return(Ht.create=function(){return new IA})()}:function(){return new Ht}};Ht.create=Az();Ht.alloc=function(e){return new As.Array(e)};As.Array!==Array&&(Ht.alloc=As.pool(Ht.alloc,As.Array.prototype.subarray));Ht.prototype._push=function(e,t,n){return this.tail=this.tail.next=new Wg(e,t,n),this.len+=t,this};function PA(r,e,t){e[t]=r&255}function h5e(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function kA(r,e){this.len=r,this.next=void 0,this.val=e}kA.prototype=Object.create(Wg.prototype);kA.prototype.fn=h5e;Ht.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new kA((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ht.prototype.int32=function(e){return e<0?this._push(NA,10,V6.fromNumber(e)):this.uint32(e)};Ht.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function NA(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Ht.prototype.uint64=function(e){var t=V6.from(e);return this._push(NA,t.length(),t)};Ht.prototype.int64=Ht.prototype.uint64;Ht.prototype.sint64=function(e){var t=V6.from(e).zzEncode();return this._push(NA,t.length(),t)};Ht.prototype.bool=function(e){return this._push(PA,1,e?1:0)};function RA(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Ht.prototype.fixed32=function(e){return this._push(RA,4,e>>>0)};Ht.prototype.sfixed32=Ht.prototype.fixed32;Ht.prototype.fixed64=function(e){var t=V6.from(e);return this._push(RA,4,t.lo)._push(RA,4,t.hi)};Ht.prototype.sfixed64=Ht.prototype.fixed64;Ht.prototype.float=function(e){return this._push(As.float.writeFloatLE,4,e)};Ht.prototype.double=function(e){return this._push(As.float.writeDoubleLE,8,e)};var p5e=As.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(PA,1,0);if(As.isString(e)){var n=Ht.alloc(t=xz.length(e));xz.decode(e,n,0),e=n}return this.uint32(t)._push(p5e,t,e)};Ht.prototype.string=function(e){var t=Sz.length(e);return t?this.uint32(t)._push(Sz.write,t,e):this._push(PA,1,0)};Ht.prototype.fork=function(){return this.states=new d5e(this),this.head=this.tail=new Wg(CA,0,0),this.len=0,this};Ht.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 Wg(CA,0,0),this.len=0),this};Ht.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Ht.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Ht._configure=function(r){IA=r,Ht.create=Az(),IA._configure()}});var DA=P((PWe,Rz)=>{"use strict";Rz.exports=pc;var Iz=K6();(pc.prototype=Object.create(Iz.prototype)).constructor=pc;var sf=Du();function pc(){Iz.call(this)}pc._configure=function(){pc.alloc=sf._Buffer_allocUnsafe,pc.writeBytesBuffer=sf.Buffer&&sf.Buffer.prototype instanceof Uint8Array&&sf.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(pc.writeBytesBuffer,t,e),this};function m5e(r,e,t){r.length<40?sf.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}pc.prototype.string=function(e){var t=sf.Buffer.byteLength(e);return this.uint32(t),t&&this._push(m5e,t,e),this};pc._configure()});var q6=P((kWe,Dz)=>{"use strict";Dz.exports=pn;var mc=Du(),LA,kz=mc.LongBits,g5e=mc.utf8;function Sa(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function pn(r){this.buf=r,this.pos=0,this.len=r.length}var Cz=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new pn(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new pn(e);throw Error("illegal buffer")},Nz=function(){return mc.Buffer?function(t){return(pn.create=function(i){return mc.Buffer.isBuffer(i)?new LA(i):Cz(i)})(t)}:Cz};pn.create=Nz();pn.prototype._slice=mc.Array.prototype.subarray||mc.Array.prototype.slice;pn.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Sa(this,10);return e}}();pn.prototype.int32=function(){return this.uint32()|0};pn.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function OA(){var r=new kz(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Sa(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw Sa(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}pn.prototype.bool=function(){return this.uint32()!==0};function $6(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}pn.prototype.fixed32=function(){if(this.pos+4>this.len)throw Sa(this,4);return $6(this.buf,this.pos+=4)};pn.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Sa(this,4);return $6(this.buf,this.pos+=4)|0};function Pz(){if(this.pos+8>this.len)throw Sa(this,8);return new kz($6(this.buf,this.pos+=4),$6(this.buf,this.pos+=4))}pn.prototype.float=function(){if(this.pos+4>this.len)throw Sa(this,4);var e=mc.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};pn.prototype.double=function(){if(this.pos+8>this.len)throw Sa(this,4);var e=mc.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};pn.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Sa(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};pn.prototype.string=function(){var e=this.bytes();return g5e.read(e,0,e.length)};pn.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Sa(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Sa(this);while(this.buf[this.pos++]&128);return this};pn.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};pn._configure=function(r){LA=r,pn.create=Nz(),LA._configure();var e=mc.Long?"toLong":"toNumber";mc.merge(pn.prototype,{int64:function(){return OA.call(this)[e](!1)},uint64:function(){return OA.call(this)[e](!0)},sint64:function(){return OA.call(this).zzDecode()[e](!1)},fixed64:function(){return Pz.call(this)[e](!0)},sfixed64:function(){return Pz.call(this)[e](!1)}})}});var BA=P((NWe,Bz)=>{"use strict";Bz.exports=hh;var Lz=q6();(hh.prototype=Object.create(Lz.prototype)).constructor=hh;var Oz=Du();function hh(r){Lz.call(this,r)}hh._configure=function(){Oz.Buffer&&(hh.prototype._slice=Oz.Buffer.prototype.slice)};hh.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))};hh._configure()});var Uz=P((DWe,Mz)=>{"use strict";Mz.exports=Yg;var MA=Du();(Yg.prototype=Object.create(MA.EventEmitter.prototype)).constructor=Yg;function Yg(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");MA.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}Yg.prototype.rpcCall=function r(e,t,n,i,o){if(!i)throw TypeError("request must be specified");var s=this;if(!o)return MA.asPromise(r,s,e,t,n,i);if(!s.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return s.rpcImpl(e,t[s.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return s.emit("error",c,e),o(c);if(u===null){s.end(!0);return}if(!(u instanceof n))try{u=n[s.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return s.emit("error",l,e),o(l)}return s.emit("data",u,e),o(null,u)})}catch(a){s.emit("error",a,e),setTimeout(function(){o(a)},0);return}};Yg.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var zz=P(Fz=>{"use strict";var y5e=Fz;y5e.Service=Uz()});var Kz=P((LWe,Vz)=>{"use strict";Vz.exports={}});var Hz=P(qz=>{"use strict";var fo=qz;fo.build="minimal";fo.Writer=K6();fo.BufferWriter=DA();fo.Reader=q6();fo.BufferReader=BA();fo.util=Du();fo.rpc=zz();fo.roots=Kz();fo.configure=$z;function $z(){fo.util._configure(),fo.Writer._configure(fo.BufferWriter),fo.Reader._configure(fo.BufferReader)}$z()});var gc=P((MWe,Gz)=>{"use strict";Gz.exports=Hz()});var xq=P((uJe,vq)=>{"use strict";vq.exports=function(){return Date.now()}});var vI=P((lJe,Sq)=>{"use strict";var R8=xq(),EI=class{constructor(e,t,n){let i=this;this._started=R8(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(R8()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,t)}reschedule(e){e||(e=this._scheduled);let t=R8();t+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=t,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=R8(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function w_e(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var e=0;e{"use strict";var{AbortController:b_e}=globalThis,Aq=vI(),vy=class extends b_e{constructor(e){super(),this._ms=e,this._timer=Aq(()=>this.abort(),e),Object.setPrototypeOf(this,vy.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=Aq(()=>this.abort(),this._ms)}};Tq.exports={TimeoutController:vy}});var iR=P((gtt,nH)=>{"use strict";var yEe=typeof navigator<"u"&&navigator.product==="ReactNative";function wEe(){return yEe?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}var Iy=self.URL,rH=wEe(),nR=class{constructor(e="",t=rH){this.super=new Iy(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return Iy.createObjectURL(e)}static revokeObjectURL(e){Iy.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}};function bEe(r){if(typeof r=="string")return new Iy(r).toString();if(!(r instanceof Iy)){let e=r.username&&r.password?`${r.username}:${r.password}@`:"",t=r.auth?r.auth+"@":"",n=r.port?":"+r.port:"",i=r.protocol?r.protocol+"//":"",o=r.host||"",s=r.hostname||"",a=r.search||(r.query?"?"+r.query:""),c=r.hash||"",u=r.pathname||"",l=r.path||u+a;return`${i}${e||t}${o||s+n}${l}${c}`}}nH.exports={URLWithLegacySupport:nR,URLSearchParams:self.URLSearchParams,defaultBase:rH,format:bEe}});var sH=P((ytt,oH)=>{"use strict";var{URLWithLegacySupport:iH,format:_Ee}=iR();oH.exports=(r,e={},t={},n)=>{let i=e.protocol?e.protocol.replace(":",""):"http";i=(t[i]||n||i)+":";let o;try{o=new iH(r)}catch{o={}}let s=Object.assign({},e,{protocol:i||o.protocol,host:e.host||o.host});return new iH(r,_Ee(s)).toString()}});var F8=P((wtt,aH)=>{"use strict";var{URLWithLegacySupport:EEe,format:vEe,URLSearchParams:xEe,defaultBase:SEe}=iR(),AEe=sH();aH.exports={URL:EEe,URLSearchParams:xEe,format:vEe,relative:AEe,defaultBase:SEe}});var Da=P((ort,gR)=>{function AH(r){let e=new globalThis.AbortController;function t(){e.abort();for(let n of r)!n||!n.removeEventListener||n.removeEventListener("abort",t)}for(let n of r)if(!(!n||!n.addEventListener)){if(n.aborted){t();break}n.addEventListener("abort",t)}return e.signal}gR.exports=AH;gR.exports.anySignal=AH});var Cy=P((Art,LH)=>{LH.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var UH=P((Irt,bR)=>{"use strict";var QEe=Object.prototype.hasOwnProperty,Zi="~";function Py(){}Object.create&&(Py.prototype=Object.create(null),new Py().__proto__||(Zi=!1));function XEe(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function MH(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new XEe(t,n||r,i),s=Zi?Zi+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function Q8(r,e){--r._eventsCount===0?r._events=new Py:delete r._events[e]}function ki(){this._events=new Py,this._eventsCount=0}ki.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)QEe.call(t,n)&&e.push(Zi?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ki.prototype.listeners=function(e){var t=Zi?Zi+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i{"use strict";var TR=class extends Error{constructor(e="Request timed out"){super(e),this.name="TimeoutError"}};ob.TimeoutError=TR;var IR=class extends Error{constructor(e="The operation was aborted."){super(e),this.name="AbortError"}};ob.AbortError=IR;var RR=class extends Error{constructor(e){super(e.statusText),this.name="HTTPError",this.response=e}};ob.HTTPError=RR});var My=P((D1,WH)=>{"use strict";var ZEe=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof globalThis<"u")return globalThis;throw new Error("unable to locate global object")},Ch=ZEe();WH.exports=D1=Ch.fetch;Ch.fetch&&(D1.default=Ch.fetch.bind(Ch));D1.Headers=Ch.Headers;D1.Request=Ch.Request;D1.Response=Ch.Response});var YH=P((Urt,PR)=>{"use strict";globalThis.fetch&&globalThis.Headers&&globalThis.Request&&globalThis.Response?PR.exports={default:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response}:PR.exports={default:My().default,Headers:My().Headers,Request:My().Request,Response:My().Response}});var XH=P((Frt,QH)=>{"use strict";QH.exports=YH()});var eG=P((zrt,JH)=>{"use strict";var{TimeoutError:JEe,AbortError:e7e}=CR(),{Response:ZH,Request:t7e,Headers:NR,default:r7e}=XH(),n7e=(r,e={})=>{let t=new XMLHttpRequest;t.open(e.method||"GET",r.toString(),!0);let{timeout:n,headers:i}=e;if(n&&n>0&&n<1/0&&(t.timeout=n),e.overrideMimeType!=null&&t.overrideMimeType(e.overrideMimeType),i)for(let[o,s]of new NR(i))t.setRequestHeader(o,s);return e.signal&&(e.signal.onabort=()=>t.abort()),e.onUploadProgress&&(t.upload.onprogress=e.onUploadProgress),t.responseType="arraybuffer",new Promise((o,s)=>{let a=c=>{switch(c.type){case"error":{o(ZH.error());break}case"load":{o(new kR(t.responseURL,t.response,{status:t.status,statusText:t.statusText,headers:s7e(t.getAllResponseHeaders())}));break}case"timeout":{s(new JEe);break}case"abort":{s(new e7e);break}default:break}};t.onerror=a,t.onload=a,t.ontimeout=a,t.onabort=a,t.send(e.body)})},i7e=r7e,o7e=(r,e={})=>e.onUploadProgress!=null?n7e(r,e):i7e(r,e),s7e=r=>{let e=new NR;for(let t of r.trim().split(/[\r\n]+/)){let n=t.indexOf(": ");n>0&&e.set(t.slice(0,n),t.slice(n+1))}return e},kR=class extends ZH{constructor(e,t,n){super(t,n),Object.defineProperty(this,"url",{value:e})}};JH.exports={fetch:o7e,Request:t7e,Headers:NR}});var rG=P((Vrt,tG)=>{"use strict";async function*a7e(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&t.cancel(),t.releaseLock()}}tG.exports=a7e});var iG=P((Krt,nG)=>{"use strict";var c7e=async r=>{let e=[];for await(let t of r)e.push(t);return e};nG.exports=c7e});var O1=P(($rt,lG)=>{"use strict";var{fetch:u7e,Request:l7e,Headers:f7e}=eG(),{TimeoutError:DR,HTTPError:cG}=CR(),oG=_A().bind({ignoreUndefined:!0}),{URL:sG,URLSearchParams:aG}=F8(),d7e=Da(),h7e=rG(),{isBrowser:p7e,isWebWorker:m7e}=C6(),g7e=iG(),y7e=(r,e,t)=>{if(e===void 0)return r;let n=Date.now(),i=()=>Date.now()-n>=e;return new Promise((o,s)=>{let a=setTimeout(()=>{i()&&(s(new DR),t.abort())},e),c=u=>f=>{if(clearTimeout(a),i()){s(new DR);return}u(f)};r.then(c(o),c(s))})},w7e={throwHttpErrors:!0,credentials:"same-origin"},Ni=class{constructor(e={}){this.opts=oG(w7e,e)}async fetch(e,t={}){let n=oG(this.opts,t),i=new f7e(n.headers);if(typeof e!="string"&&!(e instanceof sG||e instanceof l7e))throw new TypeError("`resource` must be a string, URL, or Request");let o=new sG(e.toString(),n.base),{searchParams:s,transformSearchParams:a,json:c}=n;s&&(typeof a=="function"?o.search=a(new aG(n.searchParams)):o.search=new aG(n.searchParams)),c&&(n.body=JSON.stringify(n.json),i.set("content-type","application/json"));let u=new AbortController,l=d7e([u.signal,n.signal]);globalThis.ReadableStream!=null&&n.body instanceof globalThis.ReadableStream&&(p7e||m7e)&&(n.body=new Blob(await g7e(h7e(n.body))));let f=await y7e(u7e(o.toString(),{...n,signal:l,timeout:void 0,headers:i,duplex:"half"}),n.timeout,u);if(!f.ok&&n.throwHttpErrors)throw n.handleError&&await n.handleError(f),new cG(f);return f.iterator=async function*(){yield*uG(f.body)},f.ndjson=async function*(){for await(let h of b7e(f.iterator()))t.transform?yield t.transform(h):yield h},f}post(e,t={}){return this.fetch(e,{...t,method:"POST"})}get(e,t={}){return this.fetch(e,{...t,method:"GET"})}put(e,t={}){return this.fetch(e,{...t,method:"PUT"})}delete(e,t={}){return this.fetch(e,{...t,method:"DELETE"})}options(e,t={}){return this.fetch(e,{...t,method:"OPTIONS"})}},b7e=async function*(r){let e=new TextDecoder,t="";for await(let n of r){t+=e.decode(n,{stream:!0});let i=t.split(/\r?\n/);for(let o=0;o0&&(yield JSON.parse(s))}t=i[i.length-1]}t+=e.decode(),t=t.trim(),t.length!==0&&(yield JSON.parse(t))},uG=r=>{if(_7e(r))return r;if(v7e(r)){let e=r[Symbol.asyncIterator]();return{[Symbol.asyncIterator](){return{next:e.next.bind(e),return(t){return r.destroy(),typeof e.return=="function"?e.return():Promise.resolve({done:!0,value:t})}}}}}if(E7e(r)){let e=r.getReader();return async function*(){try{for(;;){let{done:t,value:n}=await e.read();if(t)return;n&&(yield n)}}finally{e.releaseLock()}}()}throw new TypeError("Body can't be converted to AsyncIterable")},_7e=r=>typeof r=="object"&&r!==null&&typeof r[Symbol.asyncIterator]=="function",E7e=r=>r&&typeof r.getReader=="function",v7e=r=>Object.prototype.hasOwnProperty.call(r,"readable")&&Object.prototype.hasOwnProperty.call(r,"writable");Ni.HTTPError=cG;Ni.TimeoutError=DR;Ni.streamToAsyncIterator=uG;Ni.post=(r,e)=>new Ni(e).post(r,e);Ni.get=(r,e)=>new Ni(e).get(r,e);Ni.put=(r,e)=>new Ni(e).put(r,e);Ni.delete=(r,e)=>new Ni(e).delete(r,e);Ni.options=(r,e)=>new Ni(e).options(r,e);lG.exports=Ni});var AG=P((Ynt,FR)=>{var Wnt=function(){typeof FR<"u"&&(FR.exports=g);var r=86400,e=3200,t=146097*e/400,n=r*t,i=1e3*n,o=864e13,s=4294967296,a=1e6,c="000000000",u=Math.trunc||function(S){var A=S-S%1;return A==0&&(S<0||S===0&&1/S!=1/0)?-0:A},l=g.prototype,f=(g.fromDate=function(S){return new g(+S)},g.fromInt64BE=y(0,1,2,3,0,4),g.fromInt64LE=y(3,2,1,0,4,0),g.fromString=function(k){var A,I=new g,k=(k+="").replace(/^\s*[+\-]?\d+/,function(O){var O=+O,G=1970+(O-1970)%400;return I.year=O-G,G}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(N,O,G){return O<0&&(G*=-1),A=6e4*(60*+O+ +G),""}).replace(/\.\d+$/,function(N){return I.nano=+(N+c).substr(1,9),""}).split(/\D+/);if(1>24&255,R[K+A]=U>>16&255,R[K+I]=U>>8&255,R[K+k]=255&U}}function y(S,A,I,k,N,O){return function(R,K){b(R,K|=0);var U=G(R,K+N);return x(G(R,K+O),U)};function G(R,K){return 16777216*R[K+S]+(R[K+A]<<16|R[K+I]<<8|R[K+k])}}function b(S,A){if(S=S&&S.length,S==null)throw new TypeError("Invalid Buffer");if(S{TG.exports={options:{usePureJavaScript:!1}}});var CG=P((Xnt,RG)=>{var zR={};RG.exports=zR;var IG={};zR.encode=function(r,e,t){if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');if(t!==void 0&&typeof t!="number")throw new TypeError('"maxline" must be a number.');var n="";if(!(r instanceof Uint8Array))n=O7e(r,e);else{var i=0,o=e.length,s=e.charAt(0),a=[0];for(i=0;i0;)a.push(u%o),u=u/o|0}for(i=0;r[i]===0&&i=0;--i)n+=e[a[i]]}if(t){var l=new RegExp(".{1,"+t+"}","g");n=n.match(l).join(`\r +`)}return n};zR.decode=function(r,e){if(typeof r!="string")throw new TypeError('"input" must be a string.');if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');var t=IG[e];if(!t){t=IG[e]=[];for(var n=0;n>=8;for(;u>0;)s.push(u&255),u>>=8}for(var l=0;r[l]===o&&l0;)o.push(a%n),a=a/n|0}var c="";for(t=0;r.at(t)===0&&t=0;--t)c+=e[o[t]];return c}});var gr=P((Znt,DG)=>{var PG=at(),kG=CG(),F=DG.exports=PG.util=PG.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){F.nextTick=process.nextTick,typeof setImmediate=="function"?F.setImmediate=setImmediate:F.setImmediate=F.nextTick;return}if(typeof setImmediate=="function"){F.setImmediate=function(){return setImmediate.apply(void 0,arguments)},F.nextTick=function(a){return setImmediate(a)};return}if(F.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage=="function"){let a=function(c){if(c.source===window&&c.data===r){c.stopPropagation();var u=e.slice();e.length=0,u.forEach(function(l){l()})}};var s=a,r="forge.setImmediate",e=[];F.setImmediate=function(c){e.push(c),e.length===1&&window.postMessage(r,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var t=Date.now(),n=!0,i=document.createElement("div"),e=[];new MutationObserver(function(){var c=e.slice();e.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var o=F.setImmediate;F.setImmediate=function(c){Date.now()-t>15?(t=Date.now(),o(c)):(e.push(c),e.length===1&&i.setAttribute("a",n=!n))}}F.nextTick=F.setImmediate})();F.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;F.globalScope=function(){return F.isNodejs?globalThis:typeof self>"u"?window:self}();F.isArray=Array.isArray||function(r){return Object.prototype.toString.call(r)==="[object Array]"};F.isArrayBuffer=function(r){return typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer};F.isArrayBufferView=function(r){return r&&F.isArrayBuffer(r.buffer)&&r.byteLength!==void 0};function zy(r){if(!(r===8||r===16||r===24||r===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+r)}F.ByteBuffer=VR;function VR(r){if(this.data="",this.read=0,typeof r=="string")this.data=r;else if(F.isArrayBuffer(r)||F.isArrayBufferView(r))if(typeof Buffer<"u"&&r instanceof Buffer)this.data=r.toString("binary");else{var e=new Uint8Array(r);try{this.data=String.fromCharCode.apply(null,e)}catch{for(var t=0;tL7e&&(this.data.substr(0,1),this._constructedStringLength=0)};F.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};F.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};F.ByteStringBuffer.prototype.putByte=function(r){return this.putBytes(String.fromCharCode(r))};F.ByteStringBuffer.prototype.fillWithByte=function(r,e){r=String.fromCharCode(r);for(var t=this.data;e>0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return this.data=t,this._optimizeConstructedString(e),this};F.ByteStringBuffer.prototype.putBytes=function(r){return this.data+=r,this._optimizeConstructedString(r.length),this};F.ByteStringBuffer.prototype.putString=function(r){return this.putBytes(F.encodeUtf8(r))};F.ByteStringBuffer.prototype.putInt16=function(r){return this.putBytes(String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};F.ByteStringBuffer.prototype.putInt24=function(r){return this.putBytes(String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};F.ByteStringBuffer.prototype.putInt32=function(r){return this.putBytes(String.fromCharCode(r>>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};F.ByteStringBuffer.prototype.putInt16Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255))};F.ByteStringBuffer.prototype.putInt24Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255))};F.ByteStringBuffer.prototype.putInt32Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>24&255))};F.ByteStringBuffer.prototype.putInt=function(r,e){zy(e);var t="";do e-=8,t+=String.fromCharCode(r>>e&255);while(e>0);return this.putBytes(t)};F.ByteStringBuffer.prototype.putSignedInt=function(r,e){return r<0&&(r+=2<0);return e};F.ByteStringBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<=t&&(e-=t<<1),e};F.ByteStringBuffer.prototype.getBytes=function(r){var e;return r?(r=Math.min(this.length(),r),e=this.data.slice(this.read,this.read+r),this.read+=r):r===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};F.ByteStringBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};F.ByteStringBuffer.prototype.at=function(r){return this.data.charCodeAt(this.read+r)};F.ByteStringBuffer.prototype.setAt=function(r,e){return this.data=this.data.substr(0,this.read+r)+String.fromCharCode(e)+this.data.substr(this.read+r+1),this};F.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};F.ByteStringBuffer.prototype.copy=function(){var r=F.createBuffer(this.data);return r.read=this.read,r};F.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};F.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};F.ByteStringBuffer.prototype.truncate=function(r){var e=Math.max(0,this.length()-r);return this.data=this.data.substr(this.read,e),this.read=0,this};F.ByteStringBuffer.prototype.toHex=function(){for(var r="",e=this.read;e=r)return this;e=Math.max(e||this.growSize,r);var t=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+e);return n.set(t),this.data=new DataView(n.buffer),this};F.DataBuffer.prototype.putByte=function(r){return this.accommodate(1),this.data.setUint8(this.write++,r),this};F.DataBuffer.prototype.fillWithByte=function(r,e){this.accommodate(e);for(var t=0;t>8&65535),this.data.setInt8(this.write,r>>16&255),this.write+=3,this};F.DataBuffer.prototype.putInt32=function(r){return this.accommodate(4),this.data.setInt32(this.write,r),this.write+=4,this};F.DataBuffer.prototype.putInt16Le=function(r){return this.accommodate(2),this.data.setInt16(this.write,r,!0),this.write+=2,this};F.DataBuffer.prototype.putInt24Le=function(r){return this.accommodate(3),this.data.setInt8(this.write,r>>16&255),this.data.setInt16(this.write,r>>8&65535,!0),this.write+=3,this};F.DataBuffer.prototype.putInt32Le=function(r){return this.accommodate(4),this.data.setInt32(this.write,r,!0),this.write+=4,this};F.DataBuffer.prototype.putInt=function(r,e){zy(e),this.accommodate(e/8);do e-=8,this.data.setInt8(this.write++,r>>e&255);while(e>0);return this};F.DataBuffer.prototype.putSignedInt=function(r,e){return zy(e),this.accommodate(e/8),r<0&&(r+=2<0);return e};F.DataBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<=t&&(e-=t<<1),e};F.DataBuffer.prototype.getBytes=function(r){var e;return r?(r=Math.min(this.length(),r),e=this.data.slice(this.read,this.read+r),this.read+=r):r===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};F.DataBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};F.DataBuffer.prototype.at=function(r){return this.data.getUint8(this.read+r)};F.DataBuffer.prototype.setAt=function(r,e){return this.data.setUint8(r,e),this};F.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};F.DataBuffer.prototype.copy=function(){return new F.DataBuffer(this)};F.DataBuffer.prototype.compact=function(){if(this.read>0){var r=new Uint8Array(this.data.buffer,this.read),e=new Uint8Array(r.byteLength);e.set(r),this.data=new DataView(e),this.write-=this.read,this.read=0}return this};F.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};F.DataBuffer.prototype.truncate=function(r){return this.write=Math.max(0,this.length()-r),this.read=Math.min(this.read,this.write),this};F.DataBuffer.prototype.toHex=function(){for(var r="",e=this.read;e0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return t};F.xorBytes=function(r,e,t){for(var n="",i="",o="",s=0,a=0;t>0;--t,++s)i=r.charCodeAt(s)^e.charCodeAt(s),a>=10&&(n+=o,o="",a=0),o+=String.fromCharCode(i),++a;return n+=o,n};F.hexToBytes=function(r){var e="",t=0;for(r.length&!0&&(t=1,e+=String.fromCharCode(parseInt(r[0],16)));t>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255)};var Bf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Mf=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],NG="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";F.encode64=function(r,e){for(var t="",n="",i,o,s,a=0;a>2),t+=Bf.charAt((i&3)<<4|o>>4),isNaN(o)?t+="==":(t+=Bf.charAt((o&15)<<2|s>>6),t+=isNaN(s)?"=":Bf.charAt(s&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r `,t=t.substr(e));return n+=t,n};F.decode64=function(r){r=r.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var e="",t,n,i,o,s=0;s>4),i!==64&&(e+=String.fromCharCode((n&15)<<4|i>>2),o!==64&&(e+=String.fromCharCode((i&3)<<6|o)));return e};F.encodeUtf8=function(r){return unescape(encodeURIComponent(r))};F.decodeUtf8=function(r){return decodeURIComponent(escape(r))};F.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:kG.encode,decode:kG.decode}};F.binary.raw.encode=function(r){return String.fromCharCode.apply(null,r)};F.binary.raw.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,o=0;o>2),t+=Bf.charAt((i&3)<<4|o>>4),isNaN(o)?t+="==":(t+=Bf.charAt((o&15)<<2|s>>6),t+=isNaN(s)?"=":Bf.charAt(s&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r -`,t=t.substr(e));return n+=t,n};F.binary.base64.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(Math.ceil(r.length/4)*3)),r=r.replace(/[^A-Za-z0-9\+\/\=]/g,""),t=t||0;for(var i,o,s,a,c=0,u=t;c>4,s!==64&&(n[u++]=(o&15)<<4|s>>2,a!==64&&(n[u++]=(s&3)<<6|a));return e?u-t:n.subarray(0,u)};F.binary.base58.encode=function(r,e){return F.binary.baseN.encode(r,NG,e)};F.binary.base58.decode=function(r,e){return F.binary.baseN.decode(r,NG,e)};F.text={utf8:{},utf16:{}};F.text.utf8.encode=function(r,e,t){r=F.encodeUtf8(r);var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,o=0;o"u"&&(t=["web","flash"]);var i,o=!1,s=null;for(var a in t){i=t[a];try{if(i==="flash"||i==="both"){if(e[0]===null)throw new Error("Flash local storage not available.");n=r.apply(this,e),o=i==="flash"}(i==="web"||i==="both")&&(e[0]=localStorage,n=r.apply(this,e),o=!0)}catch(c){s=c}if(o)break}if(!o)throw s;return n};F.setItem=function(r,e,t,n,i){fb(M7e,arguments,i)};F.getItem=function(r,e,t,n){return fb(U7e,arguments,n)};F.removeItem=function(r,e,t,n){fb(F7e,arguments,n)};F.clearItems=function(r,e,t){fb(z7e,arguments,t)};F.isEmpty=function(r){for(var e in r)if(r.hasOwnProperty(e))return!1;return!0};F.format=function(r){for(var e=/%./g,t,n,i=0,o=[],s=0;t=e.exec(r);){n=r.substring(s,e.lastIndex-2),n.length>0&&o.push(n),s=e.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(r.substring(s)),o.join("")};F.formatNumber=function(r,e,t,n){var i=r,o=isNaN(e=Math.abs(e))?2:e,s=t===void 0?",":t,a=n===void 0?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-u).toFixed(o).slice(2):"")};F.formatSize=function(r){return r>=1073741824?r=F.formatNumber(r/1073741824,2,".","")+" GiB":r>=1048576?r=F.formatNumber(r/1048576,2,".","")+" MiB":r>=1024?r=F.formatNumber(r/1024,0)+" KiB":r=F.formatNumber(r,0)+" bytes",r};F.bytesFromIP=function(r){return r.indexOf(".")!==-1?F.bytesFromIPv4(r):r.indexOf(":")!==-1?F.bytesFromIPv6(r):null};F.bytesFromIPv4=function(r){if(r=r.split("."),r.length!==4)return null;for(var e=F.createBuffer(),t=0;tt[n].end-t[n].start&&(n=t.length-1))}e.push(o)}if(t.length>0){var c=t[n];c.end-c.start>0&&(e.splice(c.start,c.end-c.start+1,""),c.start===0&&e.unshift(""),c.end===7&&e.push(""))}return e.join(":")};F.estimateCores=function(r,e){if(typeof r=="function"&&(e=r,r={}),r=r||{},"cores"in F&&!r.update)return e(null,F.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return F.cores=navigator.hardwareConcurrency,e(null,F.cores);if(typeof Worker>"u")return F.cores=1,e(null,F.cores);if(typeof Blob>"u")return F.cores=2,e(null,F.cores);var t=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){for(var a=Date.now(),c=a+4;Date.now()d.st&&l.stl.st&&d.st{var Vy=at();Vy.pki=Vy.pki||{};var qR=OG.exports=Vy.pki.oids=Vy.oids=Vy.oids||{};function se(r,e){qR[r]=e,qR[e]=r}function ur(r,e){qR[r]=e}se("1.2.840.113549.1.1.1","rsaEncryption");se("1.2.840.113549.1.1.4","md5WithRSAEncryption");se("1.2.840.113549.1.1.5","sha1WithRSAEncryption");se("1.2.840.113549.1.1.7","RSAES-OAEP");se("1.2.840.113549.1.1.8","mgf1");se("1.2.840.113549.1.1.9","pSpecified");se("1.2.840.113549.1.1.10","RSASSA-PSS");se("1.2.840.113549.1.1.11","sha256WithRSAEncryption");se("1.2.840.113549.1.1.12","sha384WithRSAEncryption");se("1.2.840.113549.1.1.13","sha512WithRSAEncryption");se("1.3.101.112","EdDSA25519");se("1.2.840.10040.4.3","dsa-with-sha1");se("1.3.14.3.2.7","desCBC");se("1.3.14.3.2.26","sha1");se("1.3.14.3.2.29","sha1WithRSASignature");se("2.16.840.1.101.3.4.2.1","sha256");se("2.16.840.1.101.3.4.2.2","sha384");se("2.16.840.1.101.3.4.2.3","sha512");se("2.16.840.1.101.3.4.2.4","sha224");se("2.16.840.1.101.3.4.2.5","sha512-224");se("2.16.840.1.101.3.4.2.6","sha512-256");se("1.2.840.113549.2.2","md2");se("1.2.840.113549.2.5","md5");se("1.2.840.113549.1.7.1","data");se("1.2.840.113549.1.7.2","signedData");se("1.2.840.113549.1.7.3","envelopedData");se("1.2.840.113549.1.7.4","signedAndEnvelopedData");se("1.2.840.113549.1.7.5","digestedData");se("1.2.840.113549.1.7.6","encryptedData");se("1.2.840.113549.1.9.1","emailAddress");se("1.2.840.113549.1.9.2","unstructuredName");se("1.2.840.113549.1.9.3","contentType");se("1.2.840.113549.1.9.4","messageDigest");se("1.2.840.113549.1.9.5","signingTime");se("1.2.840.113549.1.9.6","counterSignature");se("1.2.840.113549.1.9.7","challengePassword");se("1.2.840.113549.1.9.8","unstructuredAddress");se("1.2.840.113549.1.9.14","extensionRequest");se("1.2.840.113549.1.9.20","friendlyName");se("1.2.840.113549.1.9.21","localKeyId");se("1.2.840.113549.1.9.22.1","x509Certificate");se("1.2.840.113549.1.12.10.1.1","keyBag");se("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");se("1.2.840.113549.1.12.10.1.3","certBag");se("1.2.840.113549.1.12.10.1.4","crlBag");se("1.2.840.113549.1.12.10.1.5","secretBag");se("1.2.840.113549.1.12.10.1.6","safeContentsBag");se("1.2.840.113549.1.5.13","pkcs5PBES2");se("1.2.840.113549.1.5.12","pkcs5PBKDF2");se("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");se("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");se("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");se("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");se("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");se("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");se("1.2.840.113549.2.7","hmacWithSHA1");se("1.2.840.113549.2.8","hmacWithSHA224");se("1.2.840.113549.2.9","hmacWithSHA256");se("1.2.840.113549.2.10","hmacWithSHA384");se("1.2.840.113549.2.11","hmacWithSHA512");se("1.2.840.113549.3.7","des-EDE3-CBC");se("2.16.840.1.101.3.4.1.2","aes128-CBC");se("2.16.840.1.101.3.4.1.22","aes192-CBC");se("2.16.840.1.101.3.4.1.42","aes256-CBC");se("2.5.4.3","commonName");se("2.5.4.4","surname");se("2.5.4.5","serialNumber");se("2.5.4.6","countryName");se("2.5.4.7","localityName");se("2.5.4.8","stateOrProvinceName");se("2.5.4.9","streetAddress");se("2.5.4.10","organizationName");se("2.5.4.11","organizationalUnitName");se("2.5.4.12","title");se("2.5.4.13","description");se("2.5.4.15","businessCategory");se("2.5.4.17","postalCode");se("2.5.4.42","givenName");se("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");se("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");se("2.16.840.1.113730.1.1","nsCertType");se("2.16.840.1.113730.1.13","nsComment");ur("2.5.29.1","authorityKeyIdentifier");ur("2.5.29.2","keyAttributes");ur("2.5.29.3","certificatePolicies");ur("2.5.29.4","keyUsageRestriction");ur("2.5.29.5","policyMapping");ur("2.5.29.6","subtreesConstraint");ur("2.5.29.7","subjectAltName");ur("2.5.29.8","issuerAltName");ur("2.5.29.9","subjectDirectoryAttributes");ur("2.5.29.10","basicConstraints");ur("2.5.29.11","nameConstraints");ur("2.5.29.12","policyConstraints");ur("2.5.29.13","basicConstraints");se("2.5.29.14","subjectKeyIdentifier");se("2.5.29.15","keyUsage");ur("2.5.29.16","privateKeyUsagePeriod");se("2.5.29.17","subjectAltName");se("2.5.29.18","issuerAltName");se("2.5.29.19","basicConstraints");ur("2.5.29.20","cRLNumber");ur("2.5.29.21","cRLReason");ur("2.5.29.22","expirationDate");ur("2.5.29.23","instructionCode");ur("2.5.29.24","invalidityDate");ur("2.5.29.25","cRLDistributionPoints");ur("2.5.29.26","issuingDistributionPoint");ur("2.5.29.27","deltaCRLIndicator");ur("2.5.29.28","issuingDistributionPoint");ur("2.5.29.29","certificateIssuer");ur("2.5.29.30","nameConstraints");se("2.5.29.31","cRLDistributionPoints");se("2.5.29.32","certificatePolicies");ur("2.5.29.33","policyMappings");ur("2.5.29.34","policyConstraints");se("2.5.29.35","authorityKeyIdentifier");ur("2.5.29.36","policyConstraints");se("2.5.29.37","extKeyUsage");ur("2.5.29.46","freshestCRL");ur("2.5.29.54","inhibitAnyPolicy");se("1.3.6.1.4.1.11129.2.4.2","timestampList");se("1.3.6.1.5.5.7.1.1","authorityInfoAccess");se("1.3.6.1.5.5.7.3.1","serverAuth");se("1.3.6.1.5.5.7.3.2","clientAuth");se("1.3.6.1.5.5.7.3.3","codeSigning");se("1.3.6.1.5.5.7.3.4","emailProtection");se("1.3.6.1.5.5.7.3.8","timeStamping")});var Ic=P((Jnt,BG)=>{var Or=at();gr();z1();var we=BG.exports=Or.asn1=Or.asn1||{};we.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};we.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};we.create=function(r,e,t,n,i){if(Or.util.isArray(n)){for(var o=[],s=0;se){var n=new Error("Too few bytes to parse DER.");throw n.available=r.length(),n.remaining=e,n.requested=t,n}}var V7e=function(r,e){var t=r.getByte();if(e--,t!==128){var n,i=t&128;if(!i)n=t;else{var o=t&127;Ky(r,e,o),n=r.getInt(o<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};we.fromDer=function(r,e){e===void 0&&(e={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof e=="boolean"&&(e={strict:e,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in e||(e.strict=!0),"parseAllBytes"in e||(e.parseAllBytes=!0),"decodeBitStrings"in e||(e.decodeBitStrings=!0),typeof r=="string"&&(r=Or.util.createBuffer(r));var t=r.length(),n=db(r,r.length(),0,e);if(e.parseAllBytes&&r.length()!==0){var i=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=t,i.remaining=r.length(),i}return n};function db(r,e,t,n){var i;Ky(r,e,2);var o=r.getByte();e--;var s=o&192,a=o&31;i=r.length();var c=V7e(r,e);if(e-=i-r.length(),c!==void 0&&c>e){if(n.strict){var u=new Error("Too few bytes to read ASN.1 value.");throw u.available=r.length(),u.remaining=e,u.requested=c,u}c=e}var l,f,h=(o&32)===32;if(h)if(l=[],c===void 0)for(;;){if(Ky(r,e,2),r.bytes(2)===String.fromCharCode(0,0)){r.getBytes(2),e-=2;break}i=r.length(),l.push(db(r,e,t+1,n)),e-=i-r.length()}else for(;c>0;)i=r.length(),l.push(db(r,c,t+1,n)),e-=i-r.length(),c-=i-r.length();if(l===void 0&&s===we.Class.UNIVERSAL&&a===we.Type.BITSTRING&&(f=r.bytes(c)),l===void 0&&n.decodeBitStrings&&s===we.Class.UNIVERSAL&&a===we.Type.BITSTRING&&c>1){var d=r.read,p=e,g=0;if(a===we.Type.BITSTRING&&(Ky(r,e,1),g=r.getByte(),e--),g===0)try{i=r.length();var w={strict:!0,decodeBitStrings:!0},_=db(r,e,t+1,w),x=i-r.length();e-=x,a==we.Type.BITSTRING&&x++;var m=_.tagClass;x===c&&(m===we.Class.UNIVERSAL||m===we.Class.CONTEXT_SPECIFIC)&&(l=[_])}catch{}l===void 0&&(r.read=d,e=p)}if(l===void 0){if(c===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");c=e}if(a===we.Type.BMPSTRING)for(l="";c>0;c-=2)Ky(r,e,2),l+=String.fromCharCode(r.getInt16()),e-=2;else l=r.getBytes(c),e-=c}var y=f===void 0?null:{bitStringContents:f};return we.create(s,a,h,l,y)}we.toDer=function(r){var e=Or.util.createBuffer(),t=r.tagClass|r.type,n=Or.util.createBuffer(),i=!1;if("bitStringContents"in r&&(i=!0,r.original&&(i=we.equals(r,r.original))),i)n.putBytes(r.bitStringContents);else if(r.composed){r.constructed?t|=32:n.putByte(0);for(var o=0;o1&&(r.value.charCodeAt(0)===0&&!(r.value.charCodeAt(1)&128)||r.value.charCodeAt(0)===255&&(r.value.charCodeAt(1)&128)===128)?n.putBytes(r.value.substr(1)):n.putBytes(r.value);if(e.putByte(t),n.length()<=127)e.putByte(n.length()&127);else{var s=n.length(),a="";do a+=String.fromCharCode(s&255),s=s>>>8;while(s>0);e.putByte(a.length|128);for(var o=a.length-1;o>=0;--o)e.putByte(a.charCodeAt(o))}return e.putBuffer(n),e};we.oidToDer=function(r){var e=r.split("."),t=Or.util.createBuffer();t.putByte(40*parseInt(e[0],10)+parseInt(e[1],10));for(var n,i,o,s,a=2;a>>7,n||(s|=128),i.push(s),n=!1;while(o>0);for(var c=i.length-1;c>=0;--c)t.putByte(i[c])}return t};we.derToOid=function(r){var e;typeof r=="string"&&(r=Or.util.createBuffer(r));var t=r.getByte();e=Math.floor(t/40)+"."+t%40;for(var n=0;r.length()>0;)t=r.getByte(),n=n<<7,t&128?n+=t&127:(e+="."+(n+t),n=0);return e};we.utcTimeToDate=function(r){var e=new Date,t=parseInt(r.substr(0,2),10);t=t>=50?1900+t:2e3+t;var n=parseInt(r.substr(2,2),10)-1,i=parseInt(r.substr(4,2),10),o=parseInt(r.substr(6,2),10),s=parseInt(r.substr(8,2),10),a=0;if(r.length>11){var c=r.charAt(10),u=10;c!=="+"&&c!=="-"&&(a=parseInt(r.substr(10,2),10),u+=2)}if(e.setUTCFullYear(t,n,i),e.setUTCHours(o,s,a,0),u&&(c=r.charAt(u),c==="+"||c==="-")){var l=parseInt(r.substr(u+1,2),10),f=parseInt(r.substr(u+4,2),10),h=l*60+f;h*=6e4,c==="+"?e.setTime(+e-h):e.setTime(+e+h)}return e};we.generalizedTimeToDate=function(r){var e=new Date,t=parseInt(r.substr(0,4),10),n=parseInt(r.substr(4,2),10)-1,i=parseInt(r.substr(6,2),10),o=parseInt(r.substr(8,2),10),s=parseInt(r.substr(10,2),10),a=parseInt(r.substr(12,2),10),c=0,u=0,l=!1;r.charAt(r.length-1)==="Z"&&(l=!0);var f=r.length-5,h=r.charAt(f);if(h==="+"||h==="-"){var d=parseInt(r.substr(f+1,2),10),p=parseInt(r.substr(f+4,2),10);u=d*60+p,u*=6e4,h==="+"&&(u*=-1),l=!0}return r.charAt(14)==="."&&(c=parseFloat(r.substr(14),10)*1e3),l?(e.setUTCFullYear(t,n,i),e.setUTCHours(o,s,a,c),e.setTime(+e+u)):(e.setFullYear(t,n,i),e.setHours(o,s,a,c)),e};we.dateToUtcTime=function(r){if(typeof r=="string")return r;var e="",t=[];t.push((""+r.getUTCFullYear()).substr(2)),t.push(""+(r.getUTCMonth()+1)),t.push(""+r.getUTCDate()),t.push(""+r.getUTCHours()),t.push(""+r.getUTCMinutes()),t.push(""+r.getUTCSeconds());for(var n=0;n=-128&&r<128)return e.putSignedInt(r,8);if(r>=-32768&&r<32768)return e.putSignedInt(r,16);if(r>=-8388608&&r<8388608)return e.putSignedInt(r,24);if(r>=-2147483648&&r<2147483648)return e.putSignedInt(r,32);var t=new Error("Integer too large; max is 32-bits.");throw t.integer=r,t};we.derToInteger=function(r){typeof r=="string"&&(r=Or.util.createBuffer(r));var e=r.length()*8;if(e>32)throw new Error("Integer too large; max is 32-bits.");return r.getSignedInt(e)};we.validate=function(r,e,t,n){var i=!1;if((r.tagClass===e.tagClass||typeof e.tagClass>"u")&&(r.type===e.type||typeof e.type>"u"))if(r.constructed===e.constructed||typeof e.constructed>"u"){if(i=!0,e.value&&Or.util.isArray(e.value))for(var o=0,s=0;i&&s0&&(n+=` +`,t=t.substr(e));return n+=t,n};F.binary.base64.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(Math.ceil(r.length/4)*3)),r=r.replace(/[^A-Za-z0-9\+\/\=]/g,""),t=t||0;for(var i,o,s,a,c=0,u=t;c>4,s!==64&&(n[u++]=(o&15)<<4|s>>2,a!==64&&(n[u++]=(s&3)<<6|a));return e?u-t:n.subarray(0,u)};F.binary.base58.encode=function(r,e){return F.binary.baseN.encode(r,NG,e)};F.binary.base58.decode=function(r,e){return F.binary.baseN.decode(r,NG,e)};F.text={utf8:{},utf16:{}};F.text.utf8.encode=function(r,e,t){r=F.encodeUtf8(r);var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,o=0;o"u"&&(t=["web","flash"]);var i,o=!1,s=null;for(var a in t){i=t[a];try{if(i==="flash"||i==="both"){if(e[0]===null)throw new Error("Flash local storage not available.");n=r.apply(this,e),o=i==="flash"}(i==="web"||i==="both")&&(e[0]=localStorage,n=r.apply(this,e),o=!0)}catch(c){s=c}if(o)break}if(!o)throw s;return n};F.setItem=function(r,e,t,n,i){fb(M7e,arguments,i)};F.getItem=function(r,e,t,n){return fb(U7e,arguments,n)};F.removeItem=function(r,e,t,n){fb(F7e,arguments,n)};F.clearItems=function(r,e,t){fb(z7e,arguments,t)};F.isEmpty=function(r){for(var e in r)if(r.hasOwnProperty(e))return!1;return!0};F.format=function(r){for(var e=/%./g,t,n,i=0,o=[],s=0;t=e.exec(r);){n=r.substring(s,e.lastIndex-2),n.length>0&&o.push(n),s=e.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(r.substring(s)),o.join("")};F.formatNumber=function(r,e,t,n){var i=r,o=isNaN(e=Math.abs(e))?2:e,s=t===void 0?",":t,a=n===void 0?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-u).toFixed(o).slice(2):"")};F.formatSize=function(r){return r>=1073741824?r=F.formatNumber(r/1073741824,2,".","")+" GiB":r>=1048576?r=F.formatNumber(r/1048576,2,".","")+" MiB":r>=1024?r=F.formatNumber(r/1024,0)+" KiB":r=F.formatNumber(r,0)+" bytes",r};F.bytesFromIP=function(r){return r.indexOf(".")!==-1?F.bytesFromIPv4(r):r.indexOf(":")!==-1?F.bytesFromIPv6(r):null};F.bytesFromIPv4=function(r){if(r=r.split("."),r.length!==4)return null;for(var e=F.createBuffer(),t=0;tt[n].end-t[n].start&&(n=t.length-1))}e.push(o)}if(t.length>0){var c=t[n];c.end-c.start>0&&(e.splice(c.start,c.end-c.start+1,""),c.start===0&&e.unshift(""),c.end===7&&e.push(""))}return e.join(":")};F.estimateCores=function(r,e){if(typeof r=="function"&&(e=r,r={}),r=r||{},"cores"in F&&!r.update)return e(null,F.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return F.cores=navigator.hardwareConcurrency,e(null,F.cores);if(typeof Worker>"u")return F.cores=1,e(null,F.cores);if(typeof Blob>"u")return F.cores=2,e(null,F.cores);var t=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){for(var a=Date.now(),c=a+4;Date.now()d.st&&l.stl.st&&d.st{var Vy=at();Vy.pki=Vy.pki||{};var qR=OG.exports=Vy.pki.oids=Vy.oids=Vy.oids||{};function se(r,e){qR[r]=e,qR[e]=r}function ur(r,e){qR[r]=e}se("1.2.840.113549.1.1.1","rsaEncryption");se("1.2.840.113549.1.1.4","md5WithRSAEncryption");se("1.2.840.113549.1.1.5","sha1WithRSAEncryption");se("1.2.840.113549.1.1.7","RSAES-OAEP");se("1.2.840.113549.1.1.8","mgf1");se("1.2.840.113549.1.1.9","pSpecified");se("1.2.840.113549.1.1.10","RSASSA-PSS");se("1.2.840.113549.1.1.11","sha256WithRSAEncryption");se("1.2.840.113549.1.1.12","sha384WithRSAEncryption");se("1.2.840.113549.1.1.13","sha512WithRSAEncryption");se("1.3.101.112","EdDSA25519");se("1.2.840.10040.4.3","dsa-with-sha1");se("1.3.14.3.2.7","desCBC");se("1.3.14.3.2.26","sha1");se("1.3.14.3.2.29","sha1WithRSASignature");se("2.16.840.1.101.3.4.2.1","sha256");se("2.16.840.1.101.3.4.2.2","sha384");se("2.16.840.1.101.3.4.2.3","sha512");se("2.16.840.1.101.3.4.2.4","sha224");se("2.16.840.1.101.3.4.2.5","sha512-224");se("2.16.840.1.101.3.4.2.6","sha512-256");se("1.2.840.113549.2.2","md2");se("1.2.840.113549.2.5","md5");se("1.2.840.113549.1.7.1","data");se("1.2.840.113549.1.7.2","signedData");se("1.2.840.113549.1.7.3","envelopedData");se("1.2.840.113549.1.7.4","signedAndEnvelopedData");se("1.2.840.113549.1.7.5","digestedData");se("1.2.840.113549.1.7.6","encryptedData");se("1.2.840.113549.1.9.1","emailAddress");se("1.2.840.113549.1.9.2","unstructuredName");se("1.2.840.113549.1.9.3","contentType");se("1.2.840.113549.1.9.4","messageDigest");se("1.2.840.113549.1.9.5","signingTime");se("1.2.840.113549.1.9.6","counterSignature");se("1.2.840.113549.1.9.7","challengePassword");se("1.2.840.113549.1.9.8","unstructuredAddress");se("1.2.840.113549.1.9.14","extensionRequest");se("1.2.840.113549.1.9.20","friendlyName");se("1.2.840.113549.1.9.21","localKeyId");se("1.2.840.113549.1.9.22.1","x509Certificate");se("1.2.840.113549.1.12.10.1.1","keyBag");se("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");se("1.2.840.113549.1.12.10.1.3","certBag");se("1.2.840.113549.1.12.10.1.4","crlBag");se("1.2.840.113549.1.12.10.1.5","secretBag");se("1.2.840.113549.1.12.10.1.6","safeContentsBag");se("1.2.840.113549.1.5.13","pkcs5PBES2");se("1.2.840.113549.1.5.12","pkcs5PBKDF2");se("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");se("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");se("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");se("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");se("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");se("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");se("1.2.840.113549.2.7","hmacWithSHA1");se("1.2.840.113549.2.8","hmacWithSHA224");se("1.2.840.113549.2.9","hmacWithSHA256");se("1.2.840.113549.2.10","hmacWithSHA384");se("1.2.840.113549.2.11","hmacWithSHA512");se("1.2.840.113549.3.7","des-EDE3-CBC");se("2.16.840.1.101.3.4.1.2","aes128-CBC");se("2.16.840.1.101.3.4.1.22","aes192-CBC");se("2.16.840.1.101.3.4.1.42","aes256-CBC");se("2.5.4.3","commonName");se("2.5.4.4","surname");se("2.5.4.5","serialNumber");se("2.5.4.6","countryName");se("2.5.4.7","localityName");se("2.5.4.8","stateOrProvinceName");se("2.5.4.9","streetAddress");se("2.5.4.10","organizationName");se("2.5.4.11","organizationalUnitName");se("2.5.4.12","title");se("2.5.4.13","description");se("2.5.4.15","businessCategory");se("2.5.4.17","postalCode");se("2.5.4.42","givenName");se("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");se("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");se("2.16.840.1.113730.1.1","nsCertType");se("2.16.840.1.113730.1.13","nsComment");ur("2.5.29.1","authorityKeyIdentifier");ur("2.5.29.2","keyAttributes");ur("2.5.29.3","certificatePolicies");ur("2.5.29.4","keyUsageRestriction");ur("2.5.29.5","policyMapping");ur("2.5.29.6","subtreesConstraint");ur("2.5.29.7","subjectAltName");ur("2.5.29.8","issuerAltName");ur("2.5.29.9","subjectDirectoryAttributes");ur("2.5.29.10","basicConstraints");ur("2.5.29.11","nameConstraints");ur("2.5.29.12","policyConstraints");ur("2.5.29.13","basicConstraints");se("2.5.29.14","subjectKeyIdentifier");se("2.5.29.15","keyUsage");ur("2.5.29.16","privateKeyUsagePeriod");se("2.5.29.17","subjectAltName");se("2.5.29.18","issuerAltName");se("2.5.29.19","basicConstraints");ur("2.5.29.20","cRLNumber");ur("2.5.29.21","cRLReason");ur("2.5.29.22","expirationDate");ur("2.5.29.23","instructionCode");ur("2.5.29.24","invalidityDate");ur("2.5.29.25","cRLDistributionPoints");ur("2.5.29.26","issuingDistributionPoint");ur("2.5.29.27","deltaCRLIndicator");ur("2.5.29.28","issuingDistributionPoint");ur("2.5.29.29","certificateIssuer");ur("2.5.29.30","nameConstraints");se("2.5.29.31","cRLDistributionPoints");se("2.5.29.32","certificatePolicies");ur("2.5.29.33","policyMappings");ur("2.5.29.34","policyConstraints");se("2.5.29.35","authorityKeyIdentifier");ur("2.5.29.36","policyConstraints");se("2.5.29.37","extKeyUsage");ur("2.5.29.46","freshestCRL");ur("2.5.29.54","inhibitAnyPolicy");se("1.3.6.1.4.1.11129.2.4.2","timestampList");se("1.3.6.1.5.5.7.1.1","authorityInfoAccess");se("1.3.6.1.5.5.7.3.1","serverAuth");se("1.3.6.1.5.5.7.3.2","clientAuth");se("1.3.6.1.5.5.7.3.3","codeSigning");se("1.3.6.1.5.5.7.3.4","emailProtection");se("1.3.6.1.5.5.7.3.8","timeStamping")});var Ic=P((eit,BG)=>{var Or=at();gr();z1();var we=BG.exports=Or.asn1=Or.asn1||{};we.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};we.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};we.create=function(r,e,t,n,i){if(Or.util.isArray(n)){for(var o=[],s=0;se){var n=new Error("Too few bytes to parse DER.");throw n.available=r.length(),n.remaining=e,n.requested=t,n}}var V7e=function(r,e){var t=r.getByte();if(e--,t!==128){var n,i=t&128;if(!i)n=t;else{var o=t&127;Ky(r,e,o),n=r.getInt(o<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};we.fromDer=function(r,e){e===void 0&&(e={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof e=="boolean"&&(e={strict:e,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in e||(e.strict=!0),"parseAllBytes"in e||(e.parseAllBytes=!0),"decodeBitStrings"in e||(e.decodeBitStrings=!0),typeof r=="string"&&(r=Or.util.createBuffer(r));var t=r.length(),n=db(r,r.length(),0,e);if(e.parseAllBytes&&r.length()!==0){var i=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=t,i.remaining=r.length(),i}return n};function db(r,e,t,n){var i;Ky(r,e,2);var o=r.getByte();e--;var s=o&192,a=o&31;i=r.length();var c=V7e(r,e);if(e-=i-r.length(),c!==void 0&&c>e){if(n.strict){var u=new Error("Too few bytes to read ASN.1 value.");throw u.available=r.length(),u.remaining=e,u.requested=c,u}c=e}var l,f,h=(o&32)===32;if(h)if(l=[],c===void 0)for(;;){if(Ky(r,e,2),r.bytes(2)===String.fromCharCode(0,0)){r.getBytes(2),e-=2;break}i=r.length(),l.push(db(r,e,t+1,n)),e-=i-r.length()}else for(;c>0;)i=r.length(),l.push(db(r,c,t+1,n)),e-=i-r.length(),c-=i-r.length();if(l===void 0&&s===we.Class.UNIVERSAL&&a===we.Type.BITSTRING&&(f=r.bytes(c)),l===void 0&&n.decodeBitStrings&&s===we.Class.UNIVERSAL&&a===we.Type.BITSTRING&&c>1){var d=r.read,p=e,g=0;if(a===we.Type.BITSTRING&&(Ky(r,e,1),g=r.getByte(),e--),g===0)try{i=r.length();var w={strict:!0,decodeBitStrings:!0},_=db(r,e,t+1,w),x=i-r.length();e-=x,a==we.Type.BITSTRING&&x++;var m=_.tagClass;x===c&&(m===we.Class.UNIVERSAL||m===we.Class.CONTEXT_SPECIFIC)&&(l=[_])}catch{}l===void 0&&(r.read=d,e=p)}if(l===void 0){if(c===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");c=e}if(a===we.Type.BMPSTRING)for(l="";c>0;c-=2)Ky(r,e,2),l+=String.fromCharCode(r.getInt16()),e-=2;else l=r.getBytes(c),e-=c}var y=f===void 0?null:{bitStringContents:f};return we.create(s,a,h,l,y)}we.toDer=function(r){var e=Or.util.createBuffer(),t=r.tagClass|r.type,n=Or.util.createBuffer(),i=!1;if("bitStringContents"in r&&(i=!0,r.original&&(i=we.equals(r,r.original))),i)n.putBytes(r.bitStringContents);else if(r.composed){r.constructed?t|=32:n.putByte(0);for(var o=0;o1&&(r.value.charCodeAt(0)===0&&!(r.value.charCodeAt(1)&128)||r.value.charCodeAt(0)===255&&(r.value.charCodeAt(1)&128)===128)?n.putBytes(r.value.substr(1)):n.putBytes(r.value);if(e.putByte(t),n.length()<=127)e.putByte(n.length()&127);else{var s=n.length(),a="";do a+=String.fromCharCode(s&255),s=s>>>8;while(s>0);e.putByte(a.length|128);for(var o=a.length-1;o>=0;--o)e.putByte(a.charCodeAt(o))}return e.putBuffer(n),e};we.oidToDer=function(r){var e=r.split("."),t=Or.util.createBuffer();t.putByte(40*parseInt(e[0],10)+parseInt(e[1],10));for(var n,i,o,s,a=2;a>>7,n||(s|=128),i.push(s),n=!1;while(o>0);for(var c=i.length-1;c>=0;--c)t.putByte(i[c])}return t};we.derToOid=function(r){var e;typeof r=="string"&&(r=Or.util.createBuffer(r));var t=r.getByte();e=Math.floor(t/40)+"."+t%40;for(var n=0;r.length()>0;)t=r.getByte(),n=n<<7,t&128?n+=t&127:(e+="."+(n+t),n=0);return e};we.utcTimeToDate=function(r){var e=new Date,t=parseInt(r.substr(0,2),10);t=t>=50?1900+t:2e3+t;var n=parseInt(r.substr(2,2),10)-1,i=parseInt(r.substr(4,2),10),o=parseInt(r.substr(6,2),10),s=parseInt(r.substr(8,2),10),a=0;if(r.length>11){var c=r.charAt(10),u=10;c!=="+"&&c!=="-"&&(a=parseInt(r.substr(10,2),10),u+=2)}if(e.setUTCFullYear(t,n,i),e.setUTCHours(o,s,a,0),u&&(c=r.charAt(u),c==="+"||c==="-")){var l=parseInt(r.substr(u+1,2),10),f=parseInt(r.substr(u+4,2),10),h=l*60+f;h*=6e4,c==="+"?e.setTime(+e-h):e.setTime(+e+h)}return e};we.generalizedTimeToDate=function(r){var e=new Date,t=parseInt(r.substr(0,4),10),n=parseInt(r.substr(4,2),10)-1,i=parseInt(r.substr(6,2),10),o=parseInt(r.substr(8,2),10),s=parseInt(r.substr(10,2),10),a=parseInt(r.substr(12,2),10),c=0,u=0,l=!1;r.charAt(r.length-1)==="Z"&&(l=!0);var f=r.length-5,h=r.charAt(f);if(h==="+"||h==="-"){var d=parseInt(r.substr(f+1,2),10),p=parseInt(r.substr(f+4,2),10);u=d*60+p,u*=6e4,h==="+"&&(u*=-1),l=!0}return r.charAt(14)==="."&&(c=parseFloat(r.substr(14),10)*1e3),l?(e.setUTCFullYear(t,n,i),e.setUTCHours(o,s,a,c),e.setTime(+e+u)):(e.setFullYear(t,n,i),e.setHours(o,s,a,c)),e};we.dateToUtcTime=function(r){if(typeof r=="string")return r;var e="",t=[];t.push((""+r.getUTCFullYear()).substr(2)),t.push(""+(r.getUTCMonth()+1)),t.push(""+r.getUTCDate()),t.push(""+r.getUTCHours()),t.push(""+r.getUTCMinutes()),t.push(""+r.getUTCSeconds());for(var n=0;n=-128&&r<128)return e.putSignedInt(r,8);if(r>=-32768&&r<32768)return e.putSignedInt(r,16);if(r>=-8388608&&r<8388608)return e.putSignedInt(r,24);if(r>=-2147483648&&r<2147483648)return e.putSignedInt(r,32);var t=new Error("Integer too large; max is 32-bits.");throw t.integer=r,t};we.derToInteger=function(r){typeof r=="string"&&(r=Or.util.createBuffer(r));var e=r.length()*8;if(e>32)throw new Error("Integer too large; max is 32-bits.");return r.getSignedInt(e)};we.validate=function(r,e,t,n){var i=!1;if((r.tagClass===e.tagClass||typeof e.tagClass>"u")&&(r.type===e.type||typeof e.type>"u"))if(r.constructed===e.constructed||typeof e.constructed>"u"){if(i=!0,e.value&&Or.util.isArray(e.value))for(var o=0,s=0;i&&s0&&(n+=` `);for(var i="",o=0;o1?n+="0x"+Or.util.bytesToHex(r.value.slice(1)):n+="(none)",r.value.length>0){var u=r.value.charCodeAt(0);u==1?n+=" (1 unused bit shown)":u>1&&(n+=" ("+u+" unused bits shown)")}}else if(r.type===we.Type.OCTETSTRING)LG.test(r.value)||(n+="("+r.value+") "),n+="0x"+Or.util.bytesToHex(r.value);else if(r.type===we.Type.UTF8)try{n+=Or.util.decodeUtf8(r.value)}catch(l){if(l.message==="URI malformed")n+="0x"+Or.util.bytesToHex(r.value)+" (malformed UTF8)";else throw l}else r.type===we.Type.PRINTABLESTRING||r.type===we.Type.IA5String?n+=r.value:LG.test(r.value)?n+="0x"+Or.util.bytesToHex(r.value):r.value.length===0?n+="[null]":n+=r.value}return n}});var GR=P((eit,MG)=>{var ri=at();gr();MG.exports=ri.cipher=ri.cipher||{};ri.cipher.algorithms=ri.cipher.algorithms||{};ri.cipher.createCipher=function(r,e){var t=r;if(typeof t=="string"&&(t=ri.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new ri.cipher.BlockCipher({algorithm:t,key:e,decrypt:!1})};ri.cipher.createDecipher=function(r,e){var t=r;if(typeof t=="string"&&(t=ri.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new ri.cipher.BlockCipher({algorithm:t,key:e,decrypt:!0})};ri.cipher.registerAlgorithm=function(r,e){r=r.toUpperCase(),ri.cipher.algorithms[r]=e};ri.cipher.getAlgorithm=function(r){return r=r.toUpperCase(),r in ri.cipher.algorithms?ri.cipher.algorithms[r]:null};var HR=ri.cipher.BlockCipher=function(r){this.algorithm=r.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=r.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=r.decrypt,this.algorithm.initialize(r)};HR.prototype.start=function(r){r=r||{};var e={};for(var t in r)e[t]=r[t];e.decrypt=this._decrypt,this._finish=!1,this._input=ri.util.createBuffer(),this.output=r.output||ri.util.createBuffer(),this.mode.start(e)};HR.prototype.update=function(r){for(r&&this._input.putBuffer(r);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};HR.prototype.finish=function(r){r&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(t){return r(this.blockSize,t,!1)},this.mode.unpad=function(t){return r(this.blockSize,t,!0)});var e={};return e.decrypt=this._decrypt,e.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,e)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,e))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,e))}});var WR=P((tit,UG)=>{var ni=at();gr();ni.cipher=ni.cipher||{};var Tt=UG.exports=ni.cipher.modes=ni.cipher.modes||{};Tt.ecb=function(r){r=r||{},this.name="ECB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Tt.ecb.prototype.start=function(r){};Tt.ecb.prototype.encrypt=function(r,e,t){if(r.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};Tt.cbc=function(r){r=r||{},this.name="CBC",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Tt.cbc.prototype.start=function(r){if(r.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in r)this._iv=hb(r.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};Tt.cbc.prototype.encrypt=function(r,e,t){if(r.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};Tt.cfb=function(r){r=r||{},this.name="CFB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0};Tt.cfb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=hb(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Tt.cfb.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Tt.cfb.prototype.decrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Tt.ofb=function(r){r=r||{},this.name="OFB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0};Tt.ofb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=hb(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Tt.ofb.prototype.encrypt=function(r,e,t){var n=r.length();if(r.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Tt.ofb.prototype.decrypt=Tt.ofb.prototype.encrypt;Tt.ctr=function(r){r=r||{},this.name="CTR",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0};Tt.ctr.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=hb(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Tt.ctr.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0&&(r.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}pb(this._inBlock)};Tt.ctr.prototype.decrypt=Tt.ctr.prototype.encrypt;Tt.gcm=function(r){r=r||{},this.name="GCM",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0,this._R=3774873600};Tt.gcm.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");var e=ni.util.createBuffer(r.iv);this._cipherLength=0;var t;if("additionalData"in r?t=ni.util.createBuffer(r.additionalData):t=ni.util.createBuffer(),"tagLength"in r?this._tagLength=r.tagLength:this._tagLength=128,this._tag=null,r.decrypt&&(this._tag=ni.util.createBuffer(r.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=e.length();if(n===12)this._j0=[e.getInt32(),e.getInt32(),e.getInt32(),1];else{for(this._j0=[0,0,0,0];e.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[e.getInt32(),e.getInt32(),e.getInt32(),e.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(jR(n*8)))}this._inBlock=this._j0.slice(0),pb(this._inBlock),this._partialBytes=0,t=ni.util.createBuffer(t),this._aDataLength=jR(t.length()*8);var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])};Tt.gcm.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return r.read-=this.blockSize,e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),pb(this._inBlock)};Tt.gcm.prototype.decrypt=function(r,e,t){var n=r.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),pb(this._inBlock),this._hashBlock[0]=r.getInt32(),this._hashBlock[1]=r.getInt32(),this._hashBlock[2]=r.getInt32(),this._hashBlock[3]=r.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)e[n]=r[n]>>>1|(r[n-1]&1)<<31;e[0]=r[0]>>>1,t&&(e[0]^=this._R)};Tt.gcm.prototype.tableMultiply=function(r){for(var e=[0,0,0,0],t=0;t<32;++t){var n=t/8|0,i=r[n]>>>(7-t%8)*4&15,o=this._m[t][i];e[0]^=o[0],e[1]^=o[1],e[2]^=o[2],e[3]^=o[3]}return e};Tt.gcm.prototype.ghash=function(r,e,t){return e[0]^=t[0],e[1]^=t[1],e[2]^=t[2],e[3]^=t[3],this.tableMultiply(e)};Tt.gcm.prototype.generateHashTable=function(r,e){for(var t=8/e,n=4*t,i=16*t,o=new Array(i),s=0;s>>1,i=new Array(t);i[n]=r.slice(0);for(var o=n>>>1;o>0;)this.pow(i[2*o],i[o]=[]),o>>=1;for(o=2;o4){var t=r;r=ni.util.createBuffer();for(var n=0;n{var Ar=at();GR();WR();gr();KG.exports=Ar.aes=Ar.aes||{};Ar.aes.startEncrypting=function(r,e,t,n){var i=mb({key:r,output:t,decrypt:!1,mode:n});return i.start(e),i};Ar.aes.createEncryptionCipher=function(r,e){return mb({key:r,output:null,decrypt:!1,mode:e})};Ar.aes.startDecrypting=function(r,e,t,n){var i=mb({key:r,output:t,decrypt:!0,mode:n});return i.start(e),i};Ar.aes.createDecryptionCipher=function(r,e){return mb({key:r,output:null,decrypt:!0,mode:e})};Ar.aes.Algorithm=function(r,e){XR||zG();var t=this;t.name=r,t.mode=new e({blockSize:16,cipher:{encrypt:function(n,i){return QR(t._w,n,i,!1)},decrypt:function(n,i){return QR(t._w,n,i,!0)}}}),t._init=!1};Ar.aes.Algorithm.prototype.initialize=function(r){if(!this._init){var e=r.key,t;if(typeof e=="string"&&(e.length===16||e.length===24||e.length===32))e=Ar.util.createBuffer(e);else if(Ar.util.isArray(e)&&(e.length===16||e.length===24||e.length===32)){t=e,e=Ar.util.createBuffer();for(var n=0;n>>2;for(var n=0;n>8^a&255^99,eo[t]=a,YR[a]=t,c=r[a],i=r[t],o=r[i],s=r[o],u=c<<24^a<<16^a<<8^(a^c),l=(i^o^s)<<24^(t^s)<<16^(t^o^s)<<8^(t^i^s);for(var f=0;f<4;++f)kh[f][t]=u,La[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;t===0?t=n=1:(t=i^r[r[r[i^s]]],n^=r[r[n]])}}function VG(r,e){for(var t=r.slice(0),n,i=1,o=t.length,s=o+6+1,a=V1*s,c=o;c>>16&255]<<24^eo[n>>>8&255]<<16^eo[n&255]<<8^eo[n>>>24]^FG[i]<<24,i++):o>6&&c%o===4&&(n=eo[n>>>24]<<24^eo[n>>>16&255]<<16^eo[n>>>8&255]<<8^eo[n&255]),t[c]=t[c-o]^n;if(e){var u,l=La[0],f=La[1],h=La[2],d=La[3],p=t.slice(0);a=t.length;for(var c=0,g=a-V1;c>>24]]^f[eo[u>>>16&255]]^h[eo[u>>>8&255]]^d[eo[u&255]];t=p}return t}function QR(r,e,t,n){var i=r.length/4-1,o,s,a,c,u;n?(o=La[0],s=La[1],a=La[2],c=La[3],u=YR):(o=kh[0],s=kh[1],a=kh[2],c=kh[3],u=eo);var l,f,h,d,p,g,w;l=e[0]^r[0],f=e[n?3:1]^r[1],h=e[2]^r[2],d=e[n?1:3]^r[3];for(var _=3,x=1;x>>24]^s[f>>>16&255]^a[h>>>8&255]^c[d&255]^r[++_],g=o[f>>>24]^s[h>>>16&255]^a[d>>>8&255]^c[l&255]^r[++_],w=o[h>>>24]^s[d>>>16&255]^a[l>>>8&255]^c[f&255]^r[++_],d=o[d>>>24]^s[l>>>16&255]^a[f>>>8&255]^c[h&255]^r[++_],l=p,f=g,h=w;t[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[h>>>8&255]<<8^u[d&255]^r[++_],t[n?3:1]=u[f>>>24]<<24^u[h>>>16&255]<<16^u[d>>>8&255]<<8^u[l&255]^r[++_],t[2]=u[h>>>24]<<24^u[d>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^r[++_],t[n?1:3]=u[d>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[h&255]^r[++_]}function mb(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="AES-"+e,n;r.decrypt?n=Ar.cipher.createDecipher(t,r.key):n=Ar.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(o,s){var a=null;s instanceof Ar.util.ByteBuffer&&(a=s,s={}),s=s||{},s.output=a,s.iv=o,i.call(n,s)},n}});var yb=P((nit,qG)=>{var zr=at();GR();WR();gr();qG.exports=zr.des=zr.des||{};zr.des.startEncrypting=function(r,e,t,n){var i=gb({key:r,output:t,decrypt:!1,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};zr.des.createEncryptionCipher=function(r,e){return gb({key:r,output:null,decrypt:!1,mode:e})};zr.des.startDecrypting=function(r,e,t,n){var i=gb({key:r,output:t,decrypt:!0,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};zr.des.createDecryptionCipher=function(r,e){return gb({key:r,output:null,decrypt:!0,mode:e})};zr.des.Algorithm=function(r,e){var t=this;t.name=r,t.mode=new e({blockSize:8,cipher:{encrypt:function(n,i){return $G(t._keys,n,i,!1)},decrypt:function(n,i){return $G(t._keys,n,i,!0)}}}),t._init=!1};zr.des.Algorithm.prototype.initialize=function(r){if(!this._init){var e=zr.util.createBuffer(r.key);if(this.name.indexOf("3DES")===0&&e.length()!==24)throw new Error("Invalid Triple-DES key size: "+e.length()*8);this._keys=Q7e(e),this._init=!0}};Rc("DES-ECB",zr.cipher.modes.ecb);Rc("DES-CBC",zr.cipher.modes.cbc);Rc("DES-CFB",zr.cipher.modes.cfb);Rc("DES-OFB",zr.cipher.modes.ofb);Rc("DES-CTR",zr.cipher.modes.ctr);Rc("3DES-ECB",zr.cipher.modes.ecb);Rc("3DES-CBC",zr.cipher.modes.cbc);Rc("3DES-CFB",zr.cipher.modes.cfb);Rc("3DES-OFB",zr.cipher.modes.ofb);Rc("3DES-CTR",zr.cipher.modes.ctr);function Rc(r,e){var t=function(){return new zr.des.Algorithm(r,e)};zr.cipher.registerAlgorithm(r,t)}var K7e=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],$7e=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],q7e=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],H7e=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],G7e=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],j7e=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],W7e=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],Y7e=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function Q7e(r){for(var e=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],t=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=r.length()>8?3:1,w=[],_=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],x=0,m,y=0;y>>4^E)&252645135,E^=m,b^=m<<4,m=(E>>>-16^b)&65535,b^=m,E^=m<<-16,m=(b>>>2^E)&858993459,E^=m,b^=m<<2,m=(E>>>-16^b)&65535,b^=m,E^=m<<-16,m=(b>>>1^E)&1431655765,E^=m,b^=m<<1,m=(E>>>8^b)&16711935,b^=m,E^=m<<8,m=(b>>>1^E)&1431655765,E^=m,b^=m<<1,m=b<<8|E>>>20&240,b=E<<24|E<<8&16711680|E>>>8&65280|E>>>24&240,E=m;for(var v=0;v<_.length;++v){_[v]?(b=b<<2|b>>>26,E=E<<2|E>>>26):(b=b<<1|b>>>27,E=E<<1|E>>>27),b&=-15,E&=-15;var S=e[b>>>28]|t[b>>>24&15]|n[b>>>20&15]|i[b>>>16&15]|o[b>>>12&15]|s[b>>>8&15]|a[b>>>4&15],A=c[E>>>28]|u[E>>>24&15]|l[E>>>20&15]|f[E>>>16&15]|h[E>>>12&15]|d[E>>>8&15]|p[E>>>4&15];m=(A>>>16^S)&65535,w[x++]=S^m,w[x++]=A^m<<16}}return w}function $G(r,e,t,n){var i=r.length===32?3:9,o;i===3?o=n?[30,-2,-2]:[0,32,2]:o=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,a=e[0],c=e[1];s=(a>>>4^c)&252645135,c^=s,a^=s<<4,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u>>4|c<<28)^r[h+1];s=a,a=c,c=s^($7e[d>>>24&63]|H7e[d>>>16&63]|j7e[d>>>8&63]|Y7e[d&63]|K7e[p>>>24&63]|q7e[p>>>16&63]|G7e[p>>>8&63]|W7e[p&63])}s=a,a=c,c=s}a=a>>>1|a<<31,c=c>>>1|c<<31,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(a>>>4^c)&252645135,c^=s,a^=s<<4,t[0]=a,t[1]=c}function gb(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="DES-"+e,n;r.decrypt?n=zr.cipher.createDecipher(t,r.key):n=zr.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(o,s){var a=null;s instanceof zr.util.ByteBuffer&&(a=s,s={}),s=s||{},s.output=a,s.iv=o,i.call(n,s)},n}});var Uf=P((iit,HG)=>{var wb=at();HG.exports=wb.md=wb.md||{};wb.md.algorithms=wb.md.algorithms||{}});var jG=P((oit,GG)=>{var Zu=at();Uf();gr();var X7e=GG.exports=Zu.hmac=Zu.hmac||{};X7e.create=function(){var r=null,e=null,t=null,n=null,i={};return i.start=function(o,s){if(o!==null)if(typeof o=="string")if(o=o.toLowerCase(),o in Zu.md.algorithms)e=Zu.md.algorithms[o].create();else throw new Error('Unknown hash algorithm "'+o+'"');else e=o;if(s===null)s=r;else{if(typeof s=="string")s=Zu.util.createBuffer(s);else if(Zu.util.isArray(s)){var a=s;s=Zu.util.createBuffer();for(var c=0;ce.blockLength&&(e.start(),e.update(s.bytes()),s=e.digest()),t=Zu.util.createBuffer(),n=Zu.util.createBuffer(),u=s.length();for(var c=0;c{});var bb=P((cit,WG)=>{var to=at();jG();Uf();gr();var Z7e=to.pkcs5=to.pkcs5||{},el;to.util.isNodejs&&!to.options.usePureJavaScript&&(el=Ju());WG.exports=to.pbkdf2=Z7e.pbkdf2=function(r,e,t,n,i,o){if(typeof i=="function"&&(o=i,i=null),to.util.isNodejs&&!to.options.usePureJavaScript&&el.pbkdf2&&(i===null||typeof i!="object")&&(el.pbkdf2Sync.length>4||!i||i==="sha1"))return typeof i!="string"&&(i="sha1"),r=Buffer.from(r,"binary"),e=Buffer.from(e,"binary"),o?el.pbkdf2Sync.length===4?el.pbkdf2(r,e,t,n,function(m,y){if(m)return o(m);o(null,y.toString("binary"))}):el.pbkdf2(r,e,t,n,i,function(m,y){if(m)return o(m);o(null,y.toString("binary"))}):el.pbkdf2Sync.length===4?el.pbkdf2Sync(r,e,t,n).toString("binary"):el.pbkdf2Sync(r,e,t,n,i).toString("binary");if((typeof i>"u"||i===null)&&(i="sha1"),typeof i=="string"){if(!(i in to.md.algorithms))throw new Error("Unknown hash algorithm: "+i);i=to.md[i].create()}var s=i.digestLength;if(n>4294967295*s){var a=new Error("Derived key is too long.");if(o)return o(a);throw a}var c=Math.ceil(n/s),u=n-(c-1)*s,l=to.hmac.create();l.start(i,r);var f="",h,d,p;if(!o){for(var g=1;g<=c;++g){l.start(null,null),l.update(e),l.update(to.util.int32ToBytes(g)),h=p=l.digest().getBytes();for(var w=2;w<=t;++w)l.start(null,null),l.update(p),d=l.digest().getBytes(),h=to.util.xorBytes(h,d,s),p=d;f+=gc)return o(null,f);l.start(null,null),l.update(e),l.update(to.util.int32ToBytes(g)),h=p=l.digest().getBytes(),w=2,x()}function x(){if(w<=t)return l.start(null,null),l.update(p),d=l.digest().getBytes(),h=to.util.xorBytes(h,d,s),p=d,++w,to.util.setImmediate(x);f+=g{var Eb=at();gr();var YG=QG.exports=Eb.pem=Eb.pem||{};YG.encode=function(r,e){e=e||{};var t="-----BEGIN "+r.type+`-----\r +`,r.composed){for(var s=0,a="",o=0;o1?n+="0x"+Or.util.bytesToHex(r.value.slice(1)):n+="(none)",r.value.length>0){var u=r.value.charCodeAt(0);u==1?n+=" (1 unused bit shown)":u>1&&(n+=" ("+u+" unused bits shown)")}}else if(r.type===we.Type.OCTETSTRING)LG.test(r.value)||(n+="("+r.value+") "),n+="0x"+Or.util.bytesToHex(r.value);else if(r.type===we.Type.UTF8)try{n+=Or.util.decodeUtf8(r.value)}catch(l){if(l.message==="URI malformed")n+="0x"+Or.util.bytesToHex(r.value)+" (malformed UTF8)";else throw l}else r.type===we.Type.PRINTABLESTRING||r.type===we.Type.IA5String?n+=r.value:LG.test(r.value)?n+="0x"+Or.util.bytesToHex(r.value):r.value.length===0?n+="[null]":n+=r.value}return n}});var GR=P((tit,MG)=>{var ri=at();gr();MG.exports=ri.cipher=ri.cipher||{};ri.cipher.algorithms=ri.cipher.algorithms||{};ri.cipher.createCipher=function(r,e){var t=r;if(typeof t=="string"&&(t=ri.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new ri.cipher.BlockCipher({algorithm:t,key:e,decrypt:!1})};ri.cipher.createDecipher=function(r,e){var t=r;if(typeof t=="string"&&(t=ri.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new ri.cipher.BlockCipher({algorithm:t,key:e,decrypt:!0})};ri.cipher.registerAlgorithm=function(r,e){r=r.toUpperCase(),ri.cipher.algorithms[r]=e};ri.cipher.getAlgorithm=function(r){return r=r.toUpperCase(),r in ri.cipher.algorithms?ri.cipher.algorithms[r]:null};var HR=ri.cipher.BlockCipher=function(r){this.algorithm=r.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=r.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=r.decrypt,this.algorithm.initialize(r)};HR.prototype.start=function(r){r=r||{};var e={};for(var t in r)e[t]=r[t];e.decrypt=this._decrypt,this._finish=!1,this._input=ri.util.createBuffer(),this.output=r.output||ri.util.createBuffer(),this.mode.start(e)};HR.prototype.update=function(r){for(r&&this._input.putBuffer(r);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};HR.prototype.finish=function(r){r&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(t){return r(this.blockSize,t,!1)},this.mode.unpad=function(t){return r(this.blockSize,t,!0)});var e={};return e.decrypt=this._decrypt,e.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,e)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,e))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,e))}});var WR=P((rit,UG)=>{var ni=at();gr();ni.cipher=ni.cipher||{};var Tt=UG.exports=ni.cipher.modes=ni.cipher.modes||{};Tt.ecb=function(r){r=r||{},this.name="ECB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Tt.ecb.prototype.start=function(r){};Tt.ecb.prototype.encrypt=function(r,e,t){if(r.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};Tt.cbc=function(r){r=r||{},this.name="CBC",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Tt.cbc.prototype.start=function(r){if(r.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in r)this._iv=hb(r.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};Tt.cbc.prototype.encrypt=function(r,e,t){if(r.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};Tt.cfb=function(r){r=r||{},this.name="CFB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0};Tt.cfb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=hb(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Tt.cfb.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Tt.cfb.prototype.decrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Tt.ofb=function(r){r=r||{},this.name="OFB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0};Tt.ofb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=hb(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Tt.ofb.prototype.encrypt=function(r,e,t){var n=r.length();if(r.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Tt.ofb.prototype.decrypt=Tt.ofb.prototype.encrypt;Tt.ctr=function(r){r=r||{},this.name="CTR",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0};Tt.ctr.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=hb(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Tt.ctr.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0&&(r.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}pb(this._inBlock)};Tt.ctr.prototype.decrypt=Tt.ctr.prototype.encrypt;Tt.gcm=function(r){r=r||{},this.name="GCM",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=ni.util.createBuffer(),this._partialBytes=0,this._R=3774873600};Tt.gcm.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");var e=ni.util.createBuffer(r.iv);this._cipherLength=0;var t;if("additionalData"in r?t=ni.util.createBuffer(r.additionalData):t=ni.util.createBuffer(),"tagLength"in r?this._tagLength=r.tagLength:this._tagLength=128,this._tag=null,r.decrypt&&(this._tag=ni.util.createBuffer(r.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=e.length();if(n===12)this._j0=[e.getInt32(),e.getInt32(),e.getInt32(),1];else{for(this._j0=[0,0,0,0];e.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[e.getInt32(),e.getInt32(),e.getInt32(),e.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(jR(n*8)))}this._inBlock=this._j0.slice(0),pb(this._inBlock),this._partialBytes=0,t=ni.util.createBuffer(t),this._aDataLength=jR(t.length()*8);var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])};Tt.gcm.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!t)return r.read-=this.blockSize,e.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),pb(this._inBlock)};Tt.gcm.prototype.decrypt=function(r,e,t){var n=r.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),pb(this._inBlock),this._hashBlock[0]=r.getInt32(),this._hashBlock[1]=r.getInt32(),this._hashBlock[2]=r.getInt32(),this._hashBlock[3]=r.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)e[n]=r[n]>>>1|(r[n-1]&1)<<31;e[0]=r[0]>>>1,t&&(e[0]^=this._R)};Tt.gcm.prototype.tableMultiply=function(r){for(var e=[0,0,0,0],t=0;t<32;++t){var n=t/8|0,i=r[n]>>>(7-t%8)*4&15,o=this._m[t][i];e[0]^=o[0],e[1]^=o[1],e[2]^=o[2],e[3]^=o[3]}return e};Tt.gcm.prototype.ghash=function(r,e,t){return e[0]^=t[0],e[1]^=t[1],e[2]^=t[2],e[3]^=t[3],this.tableMultiply(e)};Tt.gcm.prototype.generateHashTable=function(r,e){for(var t=8/e,n=4*t,i=16*t,o=new Array(i),s=0;s>>1,i=new Array(t);i[n]=r.slice(0);for(var o=n>>>1;o>0;)this.pow(i[2*o],i[o]=[]),o>>=1;for(o=2;o4){var t=r;r=ni.util.createBuffer();for(var n=0;n{var Ar=at();GR();WR();gr();KG.exports=Ar.aes=Ar.aes||{};Ar.aes.startEncrypting=function(r,e,t,n){var i=mb({key:r,output:t,decrypt:!1,mode:n});return i.start(e),i};Ar.aes.createEncryptionCipher=function(r,e){return mb({key:r,output:null,decrypt:!1,mode:e})};Ar.aes.startDecrypting=function(r,e,t,n){var i=mb({key:r,output:t,decrypt:!0,mode:n});return i.start(e),i};Ar.aes.createDecryptionCipher=function(r,e){return mb({key:r,output:null,decrypt:!0,mode:e})};Ar.aes.Algorithm=function(r,e){XR||zG();var t=this;t.name=r,t.mode=new e({blockSize:16,cipher:{encrypt:function(n,i){return QR(t._w,n,i,!1)},decrypt:function(n,i){return QR(t._w,n,i,!0)}}}),t._init=!1};Ar.aes.Algorithm.prototype.initialize=function(r){if(!this._init){var e=r.key,t;if(typeof e=="string"&&(e.length===16||e.length===24||e.length===32))e=Ar.util.createBuffer(e);else if(Ar.util.isArray(e)&&(e.length===16||e.length===24||e.length===32)){t=e,e=Ar.util.createBuffer();for(var n=0;n>>2;for(var n=0;n>8^a&255^99,eo[t]=a,YR[a]=t,c=r[a],i=r[t],o=r[i],s=r[o],u=c<<24^a<<16^a<<8^(a^c),l=(i^o^s)<<24^(t^s)<<16^(t^o^s)<<8^(t^i^s);for(var f=0;f<4;++f)kh[f][t]=u,La[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;t===0?t=n=1:(t=i^r[r[r[i^s]]],n^=r[r[n]])}}function VG(r,e){for(var t=r.slice(0),n,i=1,o=t.length,s=o+6+1,a=V1*s,c=o;c>>16&255]<<24^eo[n>>>8&255]<<16^eo[n&255]<<8^eo[n>>>24]^FG[i]<<24,i++):o>6&&c%o===4&&(n=eo[n>>>24]<<24^eo[n>>>16&255]<<16^eo[n>>>8&255]<<8^eo[n&255]),t[c]=t[c-o]^n;if(e){var u,l=La[0],f=La[1],h=La[2],d=La[3],p=t.slice(0);a=t.length;for(var c=0,g=a-V1;c>>24]]^f[eo[u>>>16&255]]^h[eo[u>>>8&255]]^d[eo[u&255]];t=p}return t}function QR(r,e,t,n){var i=r.length/4-1,o,s,a,c,u;n?(o=La[0],s=La[1],a=La[2],c=La[3],u=YR):(o=kh[0],s=kh[1],a=kh[2],c=kh[3],u=eo);var l,f,h,d,p,g,w;l=e[0]^r[0],f=e[n?3:1]^r[1],h=e[2]^r[2],d=e[n?1:3]^r[3];for(var _=3,x=1;x>>24]^s[f>>>16&255]^a[h>>>8&255]^c[d&255]^r[++_],g=o[f>>>24]^s[h>>>16&255]^a[d>>>8&255]^c[l&255]^r[++_],w=o[h>>>24]^s[d>>>16&255]^a[l>>>8&255]^c[f&255]^r[++_],d=o[d>>>24]^s[l>>>16&255]^a[f>>>8&255]^c[h&255]^r[++_],l=p,f=g,h=w;t[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[h>>>8&255]<<8^u[d&255]^r[++_],t[n?3:1]=u[f>>>24]<<24^u[h>>>16&255]<<16^u[d>>>8&255]<<8^u[l&255]^r[++_],t[2]=u[h>>>24]<<24^u[d>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^r[++_],t[n?1:3]=u[d>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[h&255]^r[++_]}function mb(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="AES-"+e,n;r.decrypt?n=Ar.cipher.createDecipher(t,r.key):n=Ar.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(o,s){var a=null;s instanceof Ar.util.ByteBuffer&&(a=s,s={}),s=s||{},s.output=a,s.iv=o,i.call(n,s)},n}});var yb=P((iit,qG)=>{var zr=at();GR();WR();gr();qG.exports=zr.des=zr.des||{};zr.des.startEncrypting=function(r,e,t,n){var i=gb({key:r,output:t,decrypt:!1,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};zr.des.createEncryptionCipher=function(r,e){return gb({key:r,output:null,decrypt:!1,mode:e})};zr.des.startDecrypting=function(r,e,t,n){var i=gb({key:r,output:t,decrypt:!0,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};zr.des.createDecryptionCipher=function(r,e){return gb({key:r,output:null,decrypt:!0,mode:e})};zr.des.Algorithm=function(r,e){var t=this;t.name=r,t.mode=new e({blockSize:8,cipher:{encrypt:function(n,i){return $G(t._keys,n,i,!1)},decrypt:function(n,i){return $G(t._keys,n,i,!0)}}}),t._init=!1};zr.des.Algorithm.prototype.initialize=function(r){if(!this._init){var e=zr.util.createBuffer(r.key);if(this.name.indexOf("3DES")===0&&e.length()!==24)throw new Error("Invalid Triple-DES key size: "+e.length()*8);this._keys=Q7e(e),this._init=!0}};Rc("DES-ECB",zr.cipher.modes.ecb);Rc("DES-CBC",zr.cipher.modes.cbc);Rc("DES-CFB",zr.cipher.modes.cfb);Rc("DES-OFB",zr.cipher.modes.ofb);Rc("DES-CTR",zr.cipher.modes.ctr);Rc("3DES-ECB",zr.cipher.modes.ecb);Rc("3DES-CBC",zr.cipher.modes.cbc);Rc("3DES-CFB",zr.cipher.modes.cfb);Rc("3DES-OFB",zr.cipher.modes.ofb);Rc("3DES-CTR",zr.cipher.modes.ctr);function Rc(r,e){var t=function(){return new zr.des.Algorithm(r,e)};zr.cipher.registerAlgorithm(r,t)}var K7e=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],$7e=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],q7e=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],H7e=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],G7e=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],j7e=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],W7e=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],Y7e=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function Q7e(r){for(var e=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],t=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=r.length()>8?3:1,w=[],_=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],x=0,m,y=0;y>>4^E)&252645135,E^=m,b^=m<<4,m=(E>>>-16^b)&65535,b^=m,E^=m<<-16,m=(b>>>2^E)&858993459,E^=m,b^=m<<2,m=(E>>>-16^b)&65535,b^=m,E^=m<<-16,m=(b>>>1^E)&1431655765,E^=m,b^=m<<1,m=(E>>>8^b)&16711935,b^=m,E^=m<<8,m=(b>>>1^E)&1431655765,E^=m,b^=m<<1,m=b<<8|E>>>20&240,b=E<<24|E<<8&16711680|E>>>8&65280|E>>>24&240,E=m;for(var v=0;v<_.length;++v){_[v]?(b=b<<2|b>>>26,E=E<<2|E>>>26):(b=b<<1|b>>>27,E=E<<1|E>>>27),b&=-15,E&=-15;var S=e[b>>>28]|t[b>>>24&15]|n[b>>>20&15]|i[b>>>16&15]|o[b>>>12&15]|s[b>>>8&15]|a[b>>>4&15],A=c[E>>>28]|u[E>>>24&15]|l[E>>>20&15]|f[E>>>16&15]|h[E>>>12&15]|d[E>>>8&15]|p[E>>>4&15];m=(A>>>16^S)&65535,w[x++]=S^m,w[x++]=A^m<<16}}return w}function $G(r,e,t,n){var i=r.length===32?3:9,o;i===3?o=n?[30,-2,-2]:[0,32,2]:o=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,a=e[0],c=e[1];s=(a>>>4^c)&252645135,c^=s,a^=s<<4,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u>>4|c<<28)^r[h+1];s=a,a=c,c=s^($7e[d>>>24&63]|H7e[d>>>16&63]|j7e[d>>>8&63]|Y7e[d&63]|K7e[p>>>24&63]|q7e[p>>>16&63]|G7e[p>>>8&63]|W7e[p&63])}s=a,a=c,c=s}a=a>>>1|a<<31,c=c>>>1|c<<31,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(a>>>4^c)&252645135,c^=s,a^=s<<4,t[0]=a,t[1]=c}function gb(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="DES-"+e,n;r.decrypt?n=zr.cipher.createDecipher(t,r.key):n=zr.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(o,s){var a=null;s instanceof zr.util.ByteBuffer&&(a=s,s={}),s=s||{},s.output=a,s.iv=o,i.call(n,s)},n}});var Uf=P((oit,HG)=>{var wb=at();HG.exports=wb.md=wb.md||{};wb.md.algorithms=wb.md.algorithms||{}});var jG=P((sit,GG)=>{var Zu=at();Uf();gr();var X7e=GG.exports=Zu.hmac=Zu.hmac||{};X7e.create=function(){var r=null,e=null,t=null,n=null,i={};return i.start=function(o,s){if(o!==null)if(typeof o=="string")if(o=o.toLowerCase(),o in Zu.md.algorithms)e=Zu.md.algorithms[o].create();else throw new Error('Unknown hash algorithm "'+o+'"');else e=o;if(s===null)s=r;else{if(typeof s=="string")s=Zu.util.createBuffer(s);else if(Zu.util.isArray(s)){var a=s;s=Zu.util.createBuffer();for(var c=0;ce.blockLength&&(e.start(),e.update(s.bytes()),s=e.digest()),t=Zu.util.createBuffer(),n=Zu.util.createBuffer(),u=s.length();for(var c=0;c{});var bb=P((uit,WG)=>{var to=at();jG();Uf();gr();var Z7e=to.pkcs5=to.pkcs5||{},el;to.util.isNodejs&&!to.options.usePureJavaScript&&(el=Ju());WG.exports=to.pbkdf2=Z7e.pbkdf2=function(r,e,t,n,i,o){if(typeof i=="function"&&(o=i,i=null),to.util.isNodejs&&!to.options.usePureJavaScript&&el.pbkdf2&&(i===null||typeof i!="object")&&(el.pbkdf2Sync.length>4||!i||i==="sha1"))return typeof i!="string"&&(i="sha1"),r=Buffer.from(r,"binary"),e=Buffer.from(e,"binary"),o?el.pbkdf2Sync.length===4?el.pbkdf2(r,e,t,n,function(m,y){if(m)return o(m);o(null,y.toString("binary"))}):el.pbkdf2(r,e,t,n,i,function(m,y){if(m)return o(m);o(null,y.toString("binary"))}):el.pbkdf2Sync.length===4?el.pbkdf2Sync(r,e,t,n).toString("binary"):el.pbkdf2Sync(r,e,t,n,i).toString("binary");if((typeof i>"u"||i===null)&&(i="sha1"),typeof i=="string"){if(!(i in to.md.algorithms))throw new Error("Unknown hash algorithm: "+i);i=to.md[i].create()}var s=i.digestLength;if(n>4294967295*s){var a=new Error("Derived key is too long.");if(o)return o(a);throw a}var c=Math.ceil(n/s),u=n-(c-1)*s,l=to.hmac.create();l.start(i,r);var f="",h,d,p;if(!o){for(var g=1;g<=c;++g){l.start(null,null),l.update(e),l.update(to.util.int32ToBytes(g)),h=p=l.digest().getBytes();for(var w=2;w<=t;++w)l.start(null,null),l.update(p),d=l.digest().getBytes(),h=to.util.xorBytes(h,d,s),p=d;f+=gc)return o(null,f);l.start(null,null),l.update(e),l.update(to.util.int32ToBytes(g)),h=p=l.digest().getBytes(),w=2,x()}function x(){if(w<=t)return l.start(null,null),l.update(p),d=l.digest().getBytes(),h=to.util.xorBytes(h,d,s),p=d,++w,to.util.setImmediate(x);f+=g{var Eb=at();gr();var YG=QG.exports=Eb.pem=Eb.pem||{};YG.encode=function(r,e){e=e||{};var t="-----BEGIN "+r.type+`-----\r `,n;if(r.procType&&(n={name:"Proc-Type",values:[String(r.procType.version),r.procType.type]},t+=_b(n)),r.contentDomain&&(n={name:"Content-Domain",values:[r.contentDomain]},t+=_b(n)),r.dekInfo&&(n={name:"DEK-Info",values:[r.dekInfo.algorithm]},r.dekInfo.parameters&&n.values.push(r.dekInfo.parameters),t+=_b(n)),r.headers)for(var i=0;i65&&s!==-1){var a=e[s];a===","?(++s,e=e.substr(0,s)+`\r `+e.substr(s)):e=e.substr(0,s)+`\r -`+a+e.substr(s+1),o=i-s-1,s=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(s=i);return e}function J7e(r){return r.replace(/^\s+/,"")}});var rj=P((lit,tj)=>{var Cc=at();Uf();gr();var ZG=tj.exports=Cc.sha256=Cc.sha256||{};Cc.md.sha256=Cc.md.algorithms.sha256=ZG;ZG.create=function(){JG||eve();var r=null,e=Cc.util.createBuffer(),t=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,o=0;o>>0,s>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=s[1],s[1]=s[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return e.putBytes(i),XG(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Cc.util.createBuffer();i.putBytes(e.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,s=o&n.blockLength-1;i.putBytes(ZR.substr(0,n.blockLength-s));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4,h5:r.h5,h6:r.h6,h7:r.h7};XG(f,t,i);var h=Cc.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var ZR=null,JG=!1,ej=null;function eve(){ZR=String.fromCharCode(128),ZR+=Cc.util.fillString(String.fromCharCode(0),64),ej=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],JG=!0}function XG(r,e,t){for(var n,i,o,s,a,c,u,l,f,h,d,p,g,w,_,x=t.length();x>=64;){for(u=0;u<16;++u)e[u]=t.getInt32();for(;u<64;++u)n=e[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=e[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,e[u]=n+e[u-7]+i+e[u-16]|0;for(l=r.h0,f=r.h1,h=r.h2,d=r.h3,p=r.h4,g=r.h5,w=r.h6,_=r.h7,u=0;u<64;++u)s=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),a=w^p&(g^w),o=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|h&(l^f),n=_+s+a+ej[u]+e[u],i=o+c,_=w,w=g,g=p,p=d+n>>>0,d=h,h=f,f=l,l=n+i>>>0;r.h0=r.h0+l|0,r.h1=r.h1+f|0,r.h2=r.h2+h|0,r.h3=r.h3+d|0,r.h4=r.h4+p|0,r.h5=r.h5+g|0,r.h6=r.h6+w|0,r.h7=r.h7+_|0,x-=64}}});var ij=P((fit,nj)=>{var Pc=at();gr();var xb=null;Pc.util.isNodejs&&!Pc.options.usePureJavaScript&&!process.versions["node-webkit"]&&(xb=Ju());var tve=nj.exports=Pc.prng=Pc.prng||{};tve.create=function(r){for(var e={plugin:r,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},t=r.md,n=new Array(32),i=0;i<32;++i)n[i]=t.create();e.pools=n,e.pool=0,e.generate=function(u,l){if(!l)return e.generateSync(u);var f=e.plugin.cipher,h=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed,g=Pc.util.createBuffer();e.key=null,w();function w(_){if(_)return l(_);if(g.length()>=u)return l(null,g.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return Pc.util.nextTick(function(){o(w)});var x=f(e.key,e.seed);e.generated+=x.length,g.putBytes(x),e.key=d(f(e.key,h(e.seed))),e.seed=p(f(e.key,e.seed)),Pc.util.setImmediate(w)}},e.generateSync=function(u){var l=e.plugin.cipher,f=e.plugin.increment,h=e.plugin.formatKey,d=e.plugin.formatSeed;e.key=null;for(var p=Pc.util.createBuffer();p.length()1048575&&(e.key=null),e.key===null&&s();var g=l(e.key,e.seed);e.generated+=g.length,p.putBytes(g),e.key=h(l(e.key,f(e.seed))),e.seed=d(l(e.key,e.seed))}return p.getBytes(u)};function o(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(f,h){if(f)return u(f);e.collect(h),a(),u()})}function s(){if(e.pools[0].messageLength>=32)return a();var u=32-e.pools[0].messageLength<<5;e.collect(e.seedFileSync(u)),a()}function a(){e.reseeds=e.reseeds===4294967295?0:e.reseeds+1;var u=e.plugin.md.create();u.update(e.keyBytes);for(var l=1,f=0;f<32;++f)e.reseeds%l===0&&(u.update(e.pools[f].digest().getBytes()),e.pools[f].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var h=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(h),e.generated=0}function c(u){var l=null,f=Pc.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(l=function(b){return h.getRandomValues(b)});var d=Pc.util.createBuffer();if(l)for(;d.length()>16),x+=(_&32767)<<16,x+=_>>15,x=(x&2147483647)+(x>>31),y=x&4294967295;for(var w=0;w<3;++w)m=y>>>(w<<3),m^=Math.floor(Math.random()*256),d.putByte(m&255)}return d.getBytes(u)}return xb?(e.seedFile=function(u,l){xb.randomBytes(u,function(f,h){if(f)return l(f);l(null,h.toString())})},e.seedFileSync=function(u){return xb.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,f=0;f>h&255);e.collect(f)},e.registerWorker=function(u){if(u===self)e.seedFile=function(f,h){function d(p){var g=p.data;g.forge&&g.forge.prng&&(self.removeEventListener("message",d),h(g.forge.prng.err,g.forge.prng.bytes))}self.addEventListener("message",d),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var h=f.data;h.forge&&h.forge.prng&&e.seedFile(h.forge.prng.needed,function(d,p){u.postMessage({forge:{prng:{err:d,bytes:p}}})})};u.addEventListener("message",l)}},e}});var Dh=P((dit,JR)=>{var ii=at();Nh();rj();ij();gr();(function(){if(ii.random&&ii.random.getBytes){JR.exports=ii.random;return}(function(r){var e={},t=new Array(4),n=ii.util.createBuffer();e.formatKey=function(f){var h=ii.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),ii.aes._expandKey(f,!1)},e.formatSeed=function(f){var h=ii.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},e.cipher=function(f,h){return ii.aes._updateBlock(f,h,t,!1),n.putInt32(t[0]),n.putInt32(t[1]),n.putInt32(t[2]),n.putInt32(t[3]),n.getBytes()},e.increment=function(f){return++f[3],f},e.md=ii.md.sha256;function i(){var f=ii.prng.create(e);return f.getBytes=function(h,d){return f.generate(h,d)},f.getBytesSync=function(h){return f.generate(h)},f}var o=i(),s=null,a=ii.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(s=function(f){return c.getRandomValues(f)}),ii.options.usePureJavaScript||!ii.util.isNodejs&&!s){if(typeof window>"u"||window.document,o.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}o.collect(u),u=null}r&&(r().mousemove(function(f){o.collectInt(f.clientX,16),o.collectInt(f.clientY,16)}),r().keypress(function(f){o.collectInt(f.charCode,8)}))}if(!ii.random)ii.random=o;else for(var l in o)ii.random[l]=o[l];ii.random.createInstance=i,JR.exports=ii.random})(typeof jQuery<"u"?jQuery:null)})()});var cj=P((hit,aj)=>{var ho=at();gr();var eC=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],oj=[1,2,3,5],rve=function(r,e){return r<>16-e},nve=function(r,e){return(r&65535)>>e|r<<16-e&65535};aj.exports=ho.rc2=ho.rc2||{};ho.rc2.expandKey=function(r,e){typeof r=="string"&&(r=ho.util.createBuffer(r)),e=e||128;var t=r,n=r.length(),i=e,o=Math.ceil(i/8),s=255>>(i&7),a;for(a=n;a<128;a++)t.putByte(eC[t.at(a-1)+t.at(a-n)&255]);for(t.setAt(128-o,eC[t.at(128-o)&s]),a=127-o;a>=0;a--)t.setAt(a,eC[t.at(a+1)^t.at(a+o)]);return t};var sj=function(r,e,t){var n=!1,i=null,o=null,s=null,a,c,u,l,f=[];for(r=ho.rc2.expandKey(r,e),u=0;u<64;u++)f.push(r.getInt16Le());t?(a=function(p){for(u=0;u<4;u++)p[u]+=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),p[u]=rve(p[u],oj[u]),l++},c=function(p){for(u=0;u<4;u++)p[u]+=f[p[(u+3)%4]&63]}):(a=function(p){for(u=3;u>=0;u--)p[u]=nve(p[u],oj[u]),p[u]-=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),l--},c=function(p){for(u=3;u>=0;u--)p[u]-=f[p[(u+3)%4]&63]});var h=function(p){var g=[];for(u=0;u<4;u++){var w=i.getInt16Le();s!==null&&(t?w^=s.getInt16Le():s.putInt16Le(w)),g.push(w&65535)}l=t?0:63;for(var _=0;_=8;)h([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(p){var g=!0;if(t)if(p)g=p(8,i,!t);else{var w=i.length()===8?8:8-i.length();i.fillWithByte(w,w)}if(g&&(n=!0,d.update()),!t&&(g=i.length()===0,g))if(p)g=p(8,o,!t);else{var _=o.length(),x=o.at(_-1);x>_?g=!1:o.truncate(x)}return g}},d};ho.rc2.startEncrypting=function(r,e,t){var n=ho.rc2.createEncryptionCipher(r,128);return n.start(e,t),n};ho.rc2.createEncryptionCipher=function(r,e){return sj(r,e,!0)};ho.rc2.startDecrypting=function(r,e,t){var n=ho.rc2.createDecryptionCipher(r,128);return n.start(e,t),n};ho.rc2.createDecryptionCipher=function(r,e){return sj(r,e,!1)}});var qy=P((pit,gj)=>{var tC=at();gj.exports=tC.jsbn=tC.jsbn||{};var tl,ive=0xdeadbeefcafe,uj=(ive&16777215)==15715070;function ne(r,e,t){this.data=[],r!=null&&(typeof r=="number"?this.fromNumber(r,e,t):e==null&&typeof r!="string"?this.fromString(r,256):this.fromString(r,e))}tC.jsbn.BigInteger=ne;function Gt(){return new ne(null)}function ove(r,e,t,n,i,o){for(;--o>=0;){var s=e*this.data[r++]+t.data[n]+i;i=Math.floor(s/67108864),t.data[n++]=s&67108863}return i}function sve(r,e,t,n,i,o){for(var s=e&32767,a=e>>15;--o>=0;){var c=this.data[r]&32767,u=this.data[r++]>>15,l=a*c+u*s;c=s*c+((l&32767)<<15)+t.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),t.data[n++]=c&1073741823}return i}function lj(r,e,t,n,i,o){for(var s=e&16383,a=e>>14;--o>=0;){var c=this.data[r]&16383,u=this.data[r++]>>14,l=a*c+u*s;c=s*c+((l&16383)<<14)+t.data[n]+i,i=(c>>28)+(l>>14)+a*u,t.data[n++]=c&268435455}return i}typeof navigator>"u"?(ne.prototype.am=lj,tl=28):uj&&navigator.appName=="Microsoft Internet Explorer"?(ne.prototype.am=sve,tl=30):uj&&navigator.appName!="Netscape"?(ne.prototype.am=ove,tl=26):(ne.prototype.am=lj,tl=28);ne.prototype.DB=tl;ne.prototype.DM=(1<=0;--e)r.data[e]=this.data[e];r.t=this.t,r.s=this.s}function uve(r){this.t=1,this.s=r<0?-1:0,r>0?this.data[0]=r:r<-1?this.data[0]=r+this.DV:this.t=0}function Ff(r){var e=Gt();return e.fromInt(r),e}function lve(r,e){var t;if(e==16)t=4;else if(e==8)t=3;else if(e==256)t=8;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else{this.fromRadix(r,e);return}this.t=0,this.s=0;for(var n=r.length,i=!1,o=0;--n>=0;){var s=t==8?r[n]&255:dj(r,n);if(s<0){r.charAt(n)=="-"&&(i=!0);continue}i=!1,o==0?this.data[this.t++]=s:o+t>this.DB?(this.data[this.t-1]|=(s&(1<>this.DB-o):this.data[this.t-1]|=s<=this.DB&&(o-=this.DB)}t==8&&r[0]&128&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==r;)--this.t}function dve(r){if(this.s<0)return"-"+this.negate().toString(r);var e;if(r==16)e=4;else if(r==8)e=3;else if(r==2)e=1;else if(r==32)e=5;else if(r==4)e=2;else return this.toRadix(r);var t=(1<0)for(a>a)>0&&(i=!0,o=fj(n));s>=0;)a>(a+=this.DB-e)):(n=this.data[s]>>(a-=e)&t,a<=0&&(a+=this.DB,--s)),n>0&&(i=!0),i&&(o+=fj(n));return i?o:"0"}function hve(){var r=Gt();return ne.ZERO.subTo(this,r),r}function pve(){return this.s<0?this.negate():this}function mve(r){var e=this.s-r.s;if(e!=0)return e;var t=this.t;if(e=t-r.t,e!=0)return this.s<0?-e:e;for(;--t>=0;)if((e=this.data[t]-r.data[t])!=0)return e;return 0}function Ab(r){var e=1,t;return(t=r>>>16)!=0&&(r=t,e+=16),(t=r>>8)!=0&&(r=t,e+=8),(t=r>>4)!=0&&(r=t,e+=4),(t=r>>2)!=0&&(r=t,e+=2),(t=r>>1)!=0&&(r=t,e+=1),e}function gve(){return this.t<=0?0:this.DB*(this.t-1)+Ab(this.data[this.t-1]^this.s&this.DM)}function yve(r,e){var t;for(t=this.t-1;t>=0;--t)e.data[t+r]=this.data[t];for(t=r-1;t>=0;--t)e.data[t]=0;e.t=this.t+r,e.s=this.s}function wve(r,e){for(var t=r;t=0;--a)e.data[a+o+1]=this.data[a]>>n|s,s=(this.data[a]&i)<=0;--a)e.data[a]=0;e.data[o]=s,e.t=this.t+o+1,e.s=this.s,e.clamp()}function _ve(r,e){e.s=this.s;var t=Math.floor(r/this.DB);if(t>=this.t){e.t=0;return}var n=r%this.DB,i=this.DB-n,o=(1<>n;for(var s=t+1;s>n;n>0&&(e.data[this.t-t-1]|=(this.s&o)<>=this.DB;if(r.t>=this.DB;n+=this.s}else{for(n+=this.s;t>=this.DB;n-=r.s}e.s=n<0?-1:0,n<-1?e.data[t++]=this.DV+n:n>0&&(e.data[t++]=n),e.t=t,e.clamp()}function vve(r,e){var t=this.abs(),n=r.abs(),i=t.t;for(e.t=i+n.t;--i>=0;)e.data[i]=0;for(i=0;i=0;)r.data[t]=0;for(t=0;t=e.DV&&(r.data[t+e.t]-=e.DV,r.data[t+e.t+1]=1)}r.t>0&&(r.data[r.t-1]+=e.am(t,e.data[t],r,2*t,0,1)),r.s=0,r.clamp()}function Sve(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,t)):(n.copyTo(o),i.copyTo(t));var u=o.t,l=o.data[u-1];if(l!=0){var f=l*(1<1?o.data[u-2]>>this.F2:0),h=this.FV/f,d=(1<=0&&(t.data[t.t++]=1,t.subTo(_,t)),ne.ONE.dlShiftTo(u,_),_.subTo(o,o);o.t=0;){var x=t.data[--g]==l?this.DM:Math.floor(t.data[g]*h+(t.data[g-1]+p)*d);if((t.data[g]+=o.am(0,x,t,w,0,u))0&&t.rShiftTo(c,t),s<0&&ne.ZERO.subTo(t,t)}}}function Ave(r){var e=Gt();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(ne.ZERO)>0&&r.subTo(e,e),e}function Oh(r){this.m=r}function Tve(r){return r.s<0||r.compareTo(this.m)>=0?r.mod(this.m):r}function Ive(r){return r}function Rve(r){r.divRemTo(this.m,null,r)}function Cve(r,e,t){r.multiplyTo(e,t),this.reduce(t)}function Pve(r,e){r.squareTo(e),this.reduce(e)}Oh.prototype.convert=Tve;Oh.prototype.revert=Ive;Oh.prototype.reduce=Rve;Oh.prototype.mulTo=Cve;Oh.prototype.sqrTo=Pve;function kve(){if(this.t<1)return 0;var r=this.data[0];if(!(r&1))return 0;var e=r&3;return e=e*(2-(r&15)*e)&15,e=e*(2-(r&255)*e)&255,e=e*(2-((r&65535)*e&65535))&65535,e=e*(2-r*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Lh(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(e,e),e}function Dve(r){var e=Gt();return r.copyTo(e),this.reduce(e),e}function Ove(r){for(;r.t<=this.mt2;)r.data[r.t++]=0;for(var e=0;e>15)*this.mpl&this.um)<<15)&r.DM;for(t=e+this.m.t,r.data[t]+=this.m.am(0,n,r,e,0,this.m.t);r.data[t]>=r.DV;)r.data[t]-=r.DV,r.data[++t]++}r.clamp(),r.drShiftTo(this.m.t,r),r.compareTo(this.m)>=0&&r.subTo(this.m,r)}function Lve(r,e){r.squareTo(e),this.reduce(e)}function Bve(r,e,t){r.multiplyTo(e,t),this.reduce(t)}Lh.prototype.convert=Nve;Lh.prototype.revert=Dve;Lh.prototype.reduce=Ove;Lh.prototype.mulTo=Bve;Lh.prototype.sqrTo=Lve;function Mve(){return(this.t>0?this.data[0]&1:this.s)==0}function Uve(r,e){if(r>4294967295||r<1)return ne.ONE;var t=Gt(),n=Gt(),i=e.convert(this),o=Ab(r)-1;for(i.copyTo(t);--o>=0;)if(e.sqrTo(t,n),(r&1<0)e.mulTo(n,i,t);else{var s=t;t=n,n=s}return e.revert(t)}function Fve(r,e){var t;return r<256||e.isEven()?t=new Oh(e):t=new Lh(e),this.exp(r,t)}ne.prototype.copyTo=cve;ne.prototype.fromInt=uve;ne.prototype.fromString=lve;ne.prototype.clamp=fve;ne.prototype.dlShiftTo=yve;ne.prototype.drShiftTo=wve;ne.prototype.lShiftTo=bve;ne.prototype.rShiftTo=_ve;ne.prototype.subTo=Eve;ne.prototype.multiplyTo=vve;ne.prototype.squareTo=xve;ne.prototype.divRemTo=Sve;ne.prototype.invDigit=kve;ne.prototype.isEven=Mve;ne.prototype.exp=Uve;ne.prototype.toString=dve;ne.prototype.negate=hve;ne.prototype.abs=pve;ne.prototype.compareTo=mve;ne.prototype.bitLength=gve;ne.prototype.mod=Ave;ne.prototype.modPowInt=Fve;ne.ZERO=Ff(0);ne.ONE=Ff(1);function zve(){var r=Gt();return this.copyTo(r),r}function Vve(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function $ve(){return this.t==0?this.s:this.data[0]<<16>>16}function qve(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function Hve(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function Gve(r){if(r==null&&(r=10),this.signum()==0||r<2||r>36)return"0";var e=this.chunkSize(r),t=Math.pow(r,e),n=Ff(t),i=Gt(),o=Gt(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(t+o.intValue()).toString(r).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(r)+s}function jve(r,e){this.fromInt(0),e==null&&(e=10);for(var t=this.chunkSize(e),n=Math.pow(e,t),i=!1,o=0,s=0,a=0;a=t&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0)}o>0&&(this.dMultiply(Math.pow(e,o)),this.dAddOffset(s,0)),i&&ne.ZERO.subTo(this,this)}function Wve(r,e,t){if(typeof e=="number")if(r<2)this.fromInt(1);else for(this.fromNumber(r,t),this.testBit(r-1)||this.bitwiseTo(ne.ONE.shiftLeft(r-1),nC,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>r&&this.subTo(ne.ONE.shiftLeft(r-1),this);else{var n=new Array,i=r&7;n.length=(r>>3)+1,e.nextBytes(n),i>0?n[0]&=(1<0)for(t>t)!=(this.s&this.DM)>>t&&(e[i++]=n|this.s<=0;)t<8?(n=(this.data[r]&(1<>(t+=this.DB-8)):(n=this.data[r]>>(t-=8)&255,t<=0&&(t+=this.DB,--r)),n&128&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function Qve(r){return this.compareTo(r)==0}function Xve(r){return this.compareTo(r)<0?this:r}function Zve(r){return this.compareTo(r)>0?this:r}function Jve(r,e,t){var n,i,o=Math.min(r.t,this.t);for(n=0;n>=16,e+=16),r&255||(r>>=8,e+=8),r&15||(r>>=4,e+=4),r&3||(r>>=2,e+=2),r&1||++e,e}function u9e(){for(var r=0;r=this.t?this.s!=0:(this.data[e]&1<>=this.DB;if(r.t>=this.DB;n+=this.s}else{for(n+=this.s;t>=this.DB;n+=r.s}e.s=n<0?-1:0,n>0?e.data[t++]=n:n<-1&&(e.data[t++]=this.DV+n),e.t=t,e.clamp()}function w9e(r){var e=Gt();return this.addTo(r,e),e}function b9e(r){var e=Gt();return this.subTo(r,e),e}function _9e(r){var e=Gt();return this.multiplyTo(r,e),e}function E9e(r){var e=Gt();return this.divRemTo(r,e,null),e}function v9e(r){var e=Gt();return this.divRemTo(r,null,e),e}function x9e(r){var e=Gt(),t=Gt();return this.divRemTo(r,e,t),new Array(e,t)}function S9e(r){this.data[this.t]=this.am(0,r-1,this,0,0,this.t),++this.t,this.clamp()}function A9e(r,e){if(r!=0){for(;this.t<=e;)this.data[this.t++]=0;for(this.data[e]+=r;this.data[e]>=this.DV;)this.data[e]-=this.DV,++e>=this.t&&(this.data[this.t++]=0),++this.data[e]}}function $y(){}function mj(r){return r}function T9e(r,e,t){r.multiplyTo(e,t)}function I9e(r,e){r.squareTo(e)}$y.prototype.convert=mj;$y.prototype.revert=mj;$y.prototype.mulTo=T9e;$y.prototype.sqrTo=I9e;function R9e(r){return this.exp(r,new $y)}function C9e(r,e,t){var n=Math.min(this.t+r.t,e);for(t.s=0,t.t=n;n>0;)t.data[--n]=0;var i;for(i=t.t-this.t;n=0;)t.data[n]=0;for(n=Math.max(e-this.t,0);n2*this.m.t)return r.mod(this.m);if(r.compareTo(this.m)<0)return r;var e=Gt();return r.copyTo(e),this.reduce(e),e}function N9e(r){return r}function D9e(r){for(r.drShiftTo(this.m.t-1,this.r2),r.t>this.m.t+1&&(r.t=this.m.t+1,r.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);r.compareTo(this.r2)<0;)r.dAddOffset(1,this.m.t+1);for(r.subTo(this.r2,r);r.compareTo(this.m)>=0;)r.subTo(this.m,r)}function O9e(r,e){r.squareTo(e),this.reduce(e)}function L9e(r,e,t){r.multiplyTo(e,t),this.reduce(t)}q1.prototype.convert=k9e;q1.prototype.revert=N9e;q1.prototype.reduce=D9e;q1.prototype.mulTo=L9e;q1.prototype.sqrTo=O9e;function B9e(r,e){var t=r.bitLength(),n,i=Ff(1),o;if(t<=0)return i;t<18?n=1:t<48?n=3:t<144?n=4:t<768?n=5:n=6,t<8?o=new Oh(e):e.isEven()?o=new q1(e):o=new Lh(e);var s=new Array,a=3,c=n-1,u=(1<1){var l=Gt();for(o.sqrTo(s[1],l);a<=u;)s[a]=Gt(),o.mulTo(l,s[a-2],s[a]),a+=2}var f=r.t-1,h,d=!0,p=Gt(),g;for(t=Ab(r.data[f])-1;f>=0;){for(t>=c?h=r.data[f]>>t-c&u:(h=(r.data[f]&(1<0&&(h|=r.data[f-1]>>this.DB+t-c)),a=n;!(h&1);)h>>=1,--a;if((t-=a)<0&&(t+=this.DB,--f),d)s[h].copyTo(i),d=!1;else{for(;a>1;)o.sqrTo(i,p),o.sqrTo(p,i),a-=2;a>0?o.sqrTo(i,p):(g=i,i=p,p=g),o.mulTo(p,s[h],i)}for(;f>=0&&!(r.data[f]&1<0&&(e.rShiftTo(o,e),t.rShiftTo(o,t));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),e.compareTo(t)>=0?(e.subTo(t,e),e.rShiftTo(1,e)):(t.subTo(e,t),t.rShiftTo(1,t));return o>0&&t.lShiftTo(o,t),t}function U9e(r){if(r<=0)return 0;var e=this.DV%r,t=this.s<0?r-1:0;if(this.t>0)if(e==0)t=this.data[0]%r;else for(var n=this.t-1;n>=0;--n)t=(e*t+this.data[n])%r;return t}function F9e(r){var e=r.isEven();if(this.isEven()&&e||r.signum()==0)return ne.ZERO;for(var t=r.clone(),n=this.clone(),i=Ff(1),o=Ff(0),s=Ff(0),a=Ff(1);t.signum()!=0;){for(;t.isEven();)t.rShiftTo(1,t),e?((!i.isEven()||!o.isEven())&&(i.addTo(this,i),o.subTo(r,o)),i.rShiftTo(1,i)):o.isEven()||o.subTo(r,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),e?((!s.isEven()||!a.isEven())&&(s.addTo(this,s),a.subTo(r,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(r,a),a.rShiftTo(1,a);t.compareTo(n)>=0?(t.subTo(n,t),e&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(t,n),e&&s.subTo(i,s),a.subTo(o,a))}if(n.compareTo(ne.ONE)!=0)return ne.ZERO;if(a.compareTo(r)>=0)return a.subtract(r);if(a.signum()<0)a.addTo(r,a);else return a;return a.signum()<0?a.add(r):a}var Ba=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],z9e=(1<<26)/Ba[Ba.length-1];function V9e(r){var e,t=this.abs();if(t.t==1&&t.data[0]<=Ba[Ba.length-1]){for(e=0;e=0);var a=o.modPow(n,this);if(a.compareTo(ne.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++{var kc=at();Uf();gr();var wj=_j.exports=kc.sha1=kc.sha1||{};kc.md.sha1=kc.md.algorithms.sha1=wj;wj.create=function(){bj||q9e();var r=null,e=kc.util.createBuffer(),t=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,o=0;o>>0,s>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=s[1],s[1]=s[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return e.putBytes(i),yj(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=kc.util.createBuffer();i.putBytes(e.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,s=o&n.blockLength-1;i.putBytes(iC.substr(0,n.blockLength-s));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4};yj(f,t,i);var h=kc.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var iC=null,bj=!1;function q9e(){iC=String.fromCharCode(128),iC+=kc.util.fillString(String.fromCharCode(0),64),bj=!0}function yj(r,e,t){for(var n,i,o,s,a,c,u,l,f=t.length();f>=64;){for(i=r.h0,o=r.h1,s=r.h2,a=r.h3,c=r.h4,l=0;l<16;++l)n=t.getInt32(),e[l]=n,u=a^o&(s^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<20;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=a^o&(s^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<32;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<40;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<60;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=o&s|a&(o^s),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<80;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;r.h0=r.h0+i|0,r.h1=r.h1+o|0,r.h2=r.h2+s|0,r.h3=r.h3+a|0,r.h4=r.h4+c|0,f-=64}}});var Sj=P((git,xj)=>{var Nc=at();gr();Dh();Ej();var vj=xj.exports=Nc.pkcs1=Nc.pkcs1||{};vj.encode_rsa_oaep=function(r,e,t){var n,i,o,s;typeof t=="string"?(n=t,i=arguments[3]||void 0,o=arguments[4]||void 0):t&&(n=t.label||void 0,i=t.seed||void 0,o=t.md||void 0,t.mgf1&&t.mgf1.md&&(s=t.mgf1.md)),o?o.start():o=Nc.md.sha1.create(),s||(s=o);var a=Math.ceil(r.n.bitLength()/8),c=a-2*o.digestLength-2;if(e.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=e.length,u.maxLength=c,u}n||(n=""),o.update(n,"raw");for(var l=o.digest(),f="",h=c-e.length,d=0;d>24&255,o>>16&255,o>>8&255,o&255);t.start(),t.update(r+s),n+=t.digest().getBytes()}return n.substring(0,e)}});var Aj=P((yit,oC)=>{var zf=at();gr();qy();Dh();(function(){if(zf.prime){oC.exports=zf.prime;return}var r=oC.exports=zf.prime=zf.prime||{},e=zf.jsbn.BigInteger,t=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(f,h){return f|h};r.generateProbablePrime=function(f,h,d){typeof h=="function"&&(d=h,h={}),h=h||{};var p=h.algorithm||"PRIMEINC";typeof p=="string"&&(p={name:p}),p.options=p.options||{};var g=h.prng||zf.random,w={nextBytes:function(_){for(var x=g.getBytesSync(_.length),m=0;m<_.length;++m)_[m]=x.charCodeAt(m)}};if(p.name==="PRIMEINC")return o(f,w,p.options,d);throw new Error("Invalid prime generation algorithm: "+p.name)};function o(f,h,d,p){return"workers"in d?c(f,h,d,p):s(f,h,d,p)}function s(f,h,d,p){var g=u(f,h),w=0,_=l(g.bitLength());"millerRabinTests"in d&&(_=d.millerRabinTests);var x=10;"maxBlockTime"in d&&(x=d.maxBlockTime),a(g,f,h,w,_,x,p)}function a(f,h,d,p,g,w,_){var x=+new Date;do{if(f.bitLength()>h&&(f=u(h,d)),f.isProbablePrime(g))return _(null,f);f.dAddOffset(t[p++%8],0)}while(w<0||+new Date-x"u")return s(f,h,d,p);var g=u(f,h),w=d.workers,_=d.workLoad||100,x=_*30/8,m=d.workerScript||"forge/prime.worker.js";if(w===-1)return zf.util.estimateCores(function(b,E){b&&(E=2),w=E-1,y()});y();function y(){w=Math.max(1,w);for(var b=[],E=0;Ef&&(g=u(f,h));var O=g.toString(16);I.target.postMessage({hex:O,workLoad:_}),g.dAddOffset(x,0)}}}}function u(f,h){var d=new e(f,h),p=f-1;return d.testBit(p)||d.bitwiseTo(e.ONE.shiftLeft(p),i,d),d.dAddOffset(31-d.mod(n).byteValue(),0),d}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var Bh=P((wit,Nj)=>{var Ve=at();Ic();qy();z1();Sj();Aj();Dh();gr();typeof Ft>"u"&&(Ft=Ve.jsbn.BigInteger);var Ft,sC=Ve.util.isNodejs?Ju():null,H=Ve.asn1,Os=Ve.util;Ve.pki=Ve.pki||{};Nj.exports=Ve.pki.rsa=Ve.rsa=Ve.rsa||{};var ct=Ve.pki,H9e=[6,4,2,4,2,4,6,2],G9e={name:"PrivateKeyInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},j9e={name:"RSAPrivateKey",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},W9e={name:"RSAPublicKey",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Y9e=Ve.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:H.Class.UNIVERSAL,type:H.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Q9e={name:"DigestInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:H.Class.UNIVERSAL,type:H.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:H.Class.UNIVERSAL,type:H.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:H.Class.UNIVERSAL,type:H.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},X9e=function(r){var e;if(r.algorithm in ct.oids)e=ct.oids[r.algorithm];else{var t=new Error("Unknown message digest algorithm.");throw t.algorithm=r.algorithm,t}var n=H.oidToDer(e).getBytes(),i=H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[]),o=H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[]);o.value.push(H.create(H.Class.UNIVERSAL,H.Type.OID,!1,n)),o.value.push(H.create(H.Class.UNIVERSAL,H.Type.NULL,!1,""));var s=H.create(H.Class.UNIVERSAL,H.Type.OCTETSTRING,!1,r.digest().getBytes());return i.value.push(o),i.value.push(s),H.toDer(i).getBytes()},Pj=function(r,e,t){if(t)return r.modPow(e.e,e.n);if(!e.p||!e.q)return r.modPow(e.d,e.n);e.dP||(e.dP=e.d.mod(e.p.subtract(Ft.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(Ft.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new Ft(Ve.util.bytesToHex(Ve.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(Ft.ONE));r=r.multiply(n.modPow(e.e,e.n)).mod(e.n);for(var i=r.mod(e.p).modPow(e.dP,e.p),o=r.mod(e.q).modPow(e.dQ,e.q);i.compareTo(o)<0;)i=i.add(e.p);var s=i.subtract(o).multiply(e.qInv).mod(e.p).multiply(e.q).add(o);return s=s.multiply(n.modInverse(e.n)).mod(e.n),s};ct.rsa.encrypt=function(r,e,t){var n=t,i,o=Math.ceil(e.n.bitLength()/8);t!==!1&&t!==!0?(n=t===2,i=kj(r,e,t)):(i=Ve.util.createBuffer(),i.putBytes(r));for(var s=new Ft(i.toHex(),16),a=Pj(s,e,n),c=a.toString(16),u=Ve.util.createBuffer(),l=o-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(Ve.util.hexToBytes(c)),u.getBytes()};ct.rsa.decrypt=function(r,e,t,n){var i=Math.ceil(e.n.bitLength()/8);if(r.length!==i){var o=new Error("Encrypted message length is invalid.");throw o.length=r.length,o.expected=i,o}var s=new Ft(Ve.util.createBuffer(r).toHex(),16);if(s.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=Pj(s,e,t),c=a.toString(16),u=Ve.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(Ve.util.hexToBytes(c)),n!==!1?Ib(u.getBytes(),e,t):u.getBytes()};ct.rsa.createKeyPairGenerationState=function(r,e,t){typeof r=="string"&&(r=parseInt(r,10)),r=r||2048,t=t||{};var n=t.prng||Ve.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u>1,pBits:r-(r>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw new Error("Invalid key generation algorithm: "+o);return s};ct.rsa.stepKeyPairGenerationState=function(r,e){"algorithm"in r||(r.algorithm="PRIMEINC");var t=new Ft(null);t.fromInt(30);for(var n=0,i=function(f,h){return f|h},o=+new Date,s,a=0;r.keys===null&&(e<=0||ac?r.pqState=0:r.num.isProbablePrime(J9e(r.num.bitLength()))?++r.pqState:r.num.dAddOffset(H9e[n++%8],0):r.pqState===2?r.pqState=r.num.subtract(Ft.ONE).gcd(r.e).compareTo(Ft.ONE)===0?3:0:r.pqState===3&&(r.pqState=0,r.p===null?r.p=r.num:r.q=r.num,r.p!==null&&r.q!==null&&++r.state,r.num=null)}else if(r.state===1)r.p.compareTo(r.q)<0&&(r.num=r.p,r.p=r.q,r.q=r.num),++r.state;else if(r.state===2)r.p1=r.p.subtract(Ft.ONE),r.q1=r.q.subtract(Ft.ONE),r.phi=r.p1.multiply(r.q1),++r.state;else if(r.state===3)r.phi.gcd(r.e).compareTo(Ft.ONE)===0?++r.state:(r.p=null,r.q=null,r.state=0);else if(r.state===4)r.n=r.p.multiply(r.q),r.n.bitLength()===r.bits?++r.state:(r.q=null,r.state=0);else if(r.state===5){var l=r.e.modInverse(r.phi);r.keys={privateKey:ct.rsa.setPrivateKey(r.n,r.e,l,r.p,r.q,l.mod(r.p1),l.mod(r.q1),r.q.modInverse(r.p)),publicKey:ct.rsa.setPublicKey(r.n,r.e)}}s=+new Date,a+=s-o,o=s}return r.keys!==null};ct.rsa.generateKeyPair=function(r,e,t,n){if(arguments.length===1?typeof r=="object"?(t=r,r=void 0):typeof r=="function"&&(n=r,r=void 0):arguments.length===2?typeof r=="number"?typeof e=="function"?(n=e,e=void 0):typeof e!="number"&&(t=e,e=void 0):(t=r,n=e,r=void 0,e=void 0):arguments.length===3&&(typeof e=="number"?typeof t=="function"&&(n=t,t=void 0):(n=t,t=e,e=void 0)),t=t||{},r===void 0&&(r=t.bits||2048),e===void 0&&(e=t.e||65537),!Ve.options.usePureJavaScript&&!t.prng&&r>=256&&r<=16384&&(e===65537||e===3)){if(n){if(Tj("generateKeyPair"))return sC.generateKeyPair("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:ct.privateKeyFromPem(u),publicKey:ct.publicKeyFromPem(c)})});if(Ij("generateKey")&&Ij("exportKey"))return Os.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:Cj(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return Os.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=ct.privateKeyFromAsn1(H.fromDer(Ve.util.createBuffer(a)));n(null,{privateKey:c,publicKey:ct.setRsaPublicKey(c.n,c.e)})}});if(Rj("generateKey")&&Rj("exportKey")){var i=Os.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:Cj(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=Os.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,h=ct.privateKeyFromAsn1(H.fromDer(Ve.util.createBuffer(f)));n(null,{privateKey:h,publicKey:ct.setRsaPublicKey(h.n,h.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(Tj("generateKeyPairSync")){var o=sC.generateKeyPairSync("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:ct.privateKeyFromPem(o.privateKey),publicKey:ct.publicKeyFromPem(o.publicKey)}}}var s=ct.rsa.createKeyPairGenerationState(r,e,t);if(!n)return ct.rsa.stepKeyPairGenerationState(s,0),s.keys;Z9e(s,t,n)};ct.setRsaPublicKey=ct.rsa.setPublicKey=function(r,e){var t={n:r,e};return t.encrypt=function(n,i,o){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return kj(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return Ve.pkcs1.encode_rsa_oaep(c,a,o)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var s=i.encode(n,t,!0);return ct.rsa.encrypt(s,t,!0)},t.verify=function(n,i,o,s){typeof o=="string"?o=o.toUpperCase():o===void 0&&(o="RSASSA-PKCS1-V1_5"),s===void 0&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),o==="RSASSA-PKCS1-V1_5"?o={verify:function(c,u){u=Ib(u,t,!0);var l=H.fromDer(u,{parseAllBytes:s._parseAllDigestBytes}),f={},h=[];if(!H.validate(l,Q9e,f,h)){var d=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw d.errors=h,d}var p=H.derToOid(f.algorithmIdentifier);if(!(p===Ve.oids.md2||p===Ve.oids.md5||p===Ve.oids.sha1||p===Ve.oids.sha224||p===Ve.oids.sha256||p===Ve.oids.sha384||p===Ve.oids.sha512||p===Ve.oids["sha512-224"]||p===Ve.oids["sha512-256"])){var d=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw d.oid=p,d}if((p===Ve.oids.md2||p===Ve.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(o==="NONE"||o==="NULL"||o===null)&&(o={verify:function(c,u){return u=Ib(u,t,!0),c===u}});var a=ct.rsa.decrypt(i,t,!0,!1);return o.verify(n,a,t.n.bitLength())},t};ct.setRsaPrivateKey=ct.rsa.setPrivateKey=function(r,e,t,n,i,o,s,a){var c={n:r,e,d:t,p:n,q:i,dP:o,dQ:s,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var h=ct.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:Ib};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(d,p){return Ve.pkcs1.decode_rsa_oaep(p,d,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(d){return d}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(h,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:X9e},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var h=l.encode(u,c.n.bitLength());return ct.rsa.encrypt(h,c,f)},c};ct.wrapRsaPrivateKey=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,H.integerToDer(0).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.OID,!1,H.oidToDer(ct.oids.rsaEncryption).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.NULL,!1,"")]),H.create(H.Class.UNIVERSAL,H.Type.OCTETSTRING,!1,H.toDer(r).getBytes())])};ct.privateKeyFromAsn1=function(r){var e={},t=[];if(H.validate(r,G9e,e,t)&&(r=H.fromDer(Ve.util.createBuffer(e.privateKey))),e={},t=[],!H.validate(r,j9e,e,t)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=t,n}var i,o,s,a,c,u,l,f;return i=Ve.util.createBuffer(e.privateKeyModulus).toHex(),o=Ve.util.createBuffer(e.privateKeyPublicExponent).toHex(),s=Ve.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=Ve.util.createBuffer(e.privateKeyPrime1).toHex(),c=Ve.util.createBuffer(e.privateKeyPrime2).toHex(),u=Ve.util.createBuffer(e.privateKeyExponent1).toHex(),l=Ve.util.createBuffer(e.privateKeyExponent2).toHex(),f=Ve.util.createBuffer(e.privateKeyCoefficient).toHex(),ct.setRsaPrivateKey(new Ft(i,16),new Ft(o,16),new Ft(s,16),new Ft(a,16),new Ft(c,16),new Ft(u,16),new Ft(l,16),new Ft(f,16))};ct.privateKeyToAsn1=ct.privateKeyToRSAPrivateKey=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,H.integerToDer(0).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.n)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.e)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.d)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.p)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.q)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.dP)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.dQ)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.qInv))])};ct.publicKeyFromAsn1=function(r){var e={},t=[];if(H.validate(r,Y9e,e,t)){var n=H.derToOid(e.publicKeyOid);if(n!==ct.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}r=e.rsaPublicKey}if(t=[],!H.validate(r,W9e,e,t)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=t,i}var o=Ve.util.createBuffer(e.publicKeyModulus).toHex(),s=Ve.util.createBuffer(e.publicKeyExponent).toHex();return ct.setRsaPublicKey(new Ft(o,16),new Ft(s,16))};ct.publicKeyToAsn1=ct.publicKeyToSubjectPublicKeyInfo=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.OID,!1,H.oidToDer(ct.oids.rsaEncryption).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.NULL,!1,"")]),H.create(H.Class.UNIVERSAL,H.Type.BITSTRING,!1,[ct.publicKeyToRSAPublicKey(r)])])};ct.publicKeyToRSAPublicKey=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.n)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.e))])};function kj(r,e,t){var n=Ve.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(r.length>i-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=r.length,o.max=i-11,o}n.putByte(0),n.putByte(t);var s=i-3-r.length,a;if(t===0||t===1){a=t===0?0:255;for(var c=0;c0;){for(var u=0,l=Ve.random.getBytes(s),c=0;c"u")throw new Error("Encryption block is invalid.");var c=0;if(a===0){c=i-3-n;for(var u=0;u1;){if(o.getByte()!==255){--o.read;break}++c}else if(a===2)for(c=0;o.length()>1;){if(o.getByte()===0){--o.read;break}++c}var l=o.getByte();if(l!==0||c!==i-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function Z9e(r,e,t){typeof e=="function"&&(t=e,e={}),e=e||{};var n={algorithm:{name:e.algorithm||"PRIMEINC",options:{workers:e.workers||2,workLoad:e.workLoad||100,workerScript:e.workerScript}}};"prng"in e&&(n.prng=e.prng),i();function i(){o(r.pBits,function(a,c){if(a)return t(a);if(r.p=c,r.q!==null)return s(a,r.q);o(r.qBits,s)})}function o(a,c){Ve.prime.generateProbablePrime(a,n,c)}function s(a,c){if(a)return t(a);if(r.q=c,r.p.compareTo(r.q)<0){var u=r.p;r.p=r.q,r.q=u}if(r.p.subtract(Ft.ONE).gcd(r.e).compareTo(Ft.ONE)!==0){r.p=null,i();return}if(r.q.subtract(Ft.ONE).gcd(r.e).compareTo(Ft.ONE)!==0){r.q=null,o(r.qBits,s);return}if(r.p1=r.p.subtract(Ft.ONE),r.q1=r.q.subtract(Ft.ONE),r.phi=r.p1.multiply(r.q1),r.phi.gcd(r.e).compareTo(Ft.ONE)!==0){r.p=r.q=null,i();return}if(r.n=r.p.multiply(r.q),r.n.bitLength()!==r.bits){r.q=null,o(r.qBits,s);return}var l=r.e.modInverse(r.phi);r.keys={privateKey:ct.rsa.setPrivateKey(r.n,r.e,l,r.p,r.q,l.mod(r.p1),l.mod(r.q1),r.q.modInverse(r.p)),publicKey:ct.rsa.setPublicKey(r.n,r.e)},t(null,r.keys)}}function Dc(r){var e=r.toString(16);e[0]>="8"&&(e="00"+e);var t=Ve.util.hexToBytes(e);return t.length>1&&(t.charCodeAt(0)===0&&!(t.charCodeAt(1)&128)||t.charCodeAt(0)===255&&(t.charCodeAt(1)&128)===128)?t.substr(1):t}function J9e(r){return r<=100?27:r<=150?18:r<=200?15:r<=250?12:r<=300?9:r<=350?8:r<=400?7:r<=500?6:r<=600?5:r<=800?4:r<=1250?3:2}function Tj(r){return Ve.util.isNodejs&&typeof sC[r]=="function"}function Ij(r){return typeof Os.globalScope<"u"&&typeof Os.globalScope.crypto=="object"&&typeof Os.globalScope.crypto.subtle=="object"&&typeof Os.globalScope.crypto.subtle[r]=="function"}function Rj(r){return typeof Os.globalScope<"u"&&typeof Os.globalScope.msCrypto=="object"&&typeof Os.globalScope.msCrypto.subtle=="object"&&typeof Os.globalScope.msCrypto.subtle[r]=="function"}function Cj(r){for(var e=Ve.util.hexToBytes(r.toString(16)),t=new Uint8Array(e.length),n=0;n{var Ae=at();Nh();Ic();yb();Uf();z1();bb();vb();Dh();cj();Bh();gr();typeof Dj>"u"&&(Dj=Ae.jsbn.BigInteger);var Dj,W=Ae.asn1,gt=Ae.pki=Ae.pki||{};Mj.exports=gt.pbe=Ae.pbe=Ae.pbe||{};var Mh=gt.oids,exe={name:"EncryptedPrivateKeyInfo",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},txe={name:"PBES2Algorithms",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:W.Class.UNIVERSAL,type:W.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:W.Class.UNIVERSAL,type:W.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},rxe={name:"pkcs-12PbeParams",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:W.Class.UNIVERSAL,type:W.Type.INTEGER,constructed:!1,capture:"iterations"}]};gt.encryptPrivateKeyInfo=function(r,e,t){t=t||{},t.saltSize=t.saltSize||8,t.count=t.count||2048,t.algorithm=t.algorithm||"aes128",t.prfAlgorithm=t.prfAlgorithm||"sha1";var n=Ae.random.getBytesSync(t.saltSize),i=t.count,o=W.integerToDer(i),s,a,c;if(t.algorithm.indexOf("aes")===0||t.algorithm==="des"){var u,l,f;switch(t.algorithm){case"aes128":s=16,u=16,l=Mh["aes128-CBC"],f=Ae.aes.createEncryptionCipher;break;case"aes192":s=24,u=16,l=Mh["aes192-CBC"],f=Ae.aes.createEncryptionCipher;break;case"aes256":s=32,u=16,l=Mh["aes256-CBC"],f=Ae.aes.createEncryptionCipher;break;case"des":s=8,u=8,l=Mh.desCBC,f=Ae.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=t.algorithm,h}var d="hmacWith"+t.prfAlgorithm.toUpperCase(),p=Bj(d),g=Ae.pkcs5.pbkdf2(e,n,i,s,p),w=Ae.random.getBytesSync(u),_=f(g);_.start(w),_.update(W.toDer(r)),_.finish(),c=_.output.getBytes();var x=nxe(n,o,s,d);a=W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(Mh.pkcs5PBES2).getBytes()),W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(Mh.pkcs5PBKDF2).getBytes()),x]),W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(l).getBytes()),W.create(W.Class.UNIVERSAL,W.Type.OCTETSTRING,!1,w)])])])}else if(t.algorithm==="3des"){s=24;var m=new Ae.util.ByteBuffer(n),g=gt.pbe.generatePkcs12Key(e,m,1,i,s),w=gt.pbe.generatePkcs12Key(e,m,2,i,s),_=Ae.des.createEncryptionCipher(g);_.start(w),_.update(W.toDer(r)),_.finish(),c=_.output.getBytes(),a=W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(Mh["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OCTETSTRING,!1,n),W.create(W.Class.UNIVERSAL,W.Type.INTEGER,!1,o.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=t.algorithm,h}var y=W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[a,W.create(W.Class.UNIVERSAL,W.Type.OCTETSTRING,!1,c)]);return y};gt.decryptPrivateKeyInfo=function(r,e){var t=null,n={},i=[];if(!W.validate(r,exe,n,i)){var o=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=W.derToOid(n.encryptionOid),a=gt.pbe.getCipher(s,n.encryptionParams,e),c=Ae.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(t=W.fromDer(a.output)),t};gt.encryptedPrivateKeyToPem=function(r,e){var t={type:"ENCRYPTED PRIVATE KEY",body:W.toDer(r).getBytes()};return Ae.pem.encode(t,{maxline:e})};gt.encryptedPrivateKeyFromPem=function(r){var e=Ae.pem.decode(r)[0];if(e.type!=="ENCRYPTED PRIVATE KEY"){var t=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw t.headerType=e.type,t}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return W.fromDer(e.body)};gt.encryptRsaPrivateKey=function(r,e,t){if(t=t||{},!t.legacy){var n=gt.wrapRsaPrivateKey(gt.privateKeyToAsn1(r));return n=gt.encryptPrivateKeyInfo(n,e,t),gt.encryptedPrivateKeyToPem(n)}var i,o,s,a;switch(t.algorithm){case"aes128":i="AES-128-CBC",s=16,o=Ae.random.getBytesSync(16),a=Ae.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",s=24,o=Ae.random.getBytesSync(16),a=Ae.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",s=32,o=Ae.random.getBytesSync(16),a=Ae.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",s=24,o=Ae.random.getBytesSync(8),a=Ae.des.createEncryptionCipher;break;case"des":i="DES-CBC",s=8,o=Ae.random.getBytesSync(8),a=Ae.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+t.algorithm+'".');throw c.algorithm=t.algorithm,c}var u=Ae.pbe.opensslDeriveBytes(e,o.substr(0,8),s),l=a(u);l.start(o),l.update(W.toDer(gt.privateKeyToAsn1(r))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:Ae.util.bytesToHex(o).toUpperCase()},body:l.output.getBytes()};return Ae.pem.encode(f)};gt.decryptRsaPrivateKey=function(r,e){var t=null,n=Ae.pem.decode(r)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var o,s;switch(n.dekInfo.algorithm){case"DES-CBC":o=8,s=Ae.des.createDecryptionCipher;break;case"DES-EDE3-CBC":o=24,s=Ae.des.createDecryptionCipher;break;case"AES-128-CBC":o=16,s=Ae.aes.createDecryptionCipher;break;case"AES-192-CBC":o=24,s=Ae.aes.createDecryptionCipher;break;case"AES-256-CBC":o=32,s=Ae.aes.createDecryptionCipher;break;case"RC2-40-CBC":o=5,s=function(f){return Ae.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":o=8,s=function(f){return Ae.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":o=16,s=function(f){return Ae.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=Ae.util.hexToBytes(n.dekInfo.parameters),c=Ae.pbe.opensslDeriveBytes(e,a.substr(0,8),o),u=s(c);if(u.start(a),u.update(Ae.util.createBuffer(n.body)),u.finish())t=u.output.getBytes();else return t}else t=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?t=gt.decryptPrivateKeyInfo(W.fromDer(t),e):t=W.fromDer(t),t!==null&&(t=gt.privateKeyFromAsn1(t)),t};gt.pbe.generatePkcs12Key=function(r,e,t,n,i,o){var s,a;if(typeof o>"u"||o===null){if(!("sha1"in Ae.md))throw new Error('"sha1" hash algorithm unavailable.');o=Ae.md.sha1.create()}var c=o.digestLength,u=o.blockLength,l=new Ae.util.ByteBuffer,f=new Ae.util.ByteBuffer;if(r!=null){for(a=0;a=0;a--)N=N>>8,N+=S.at(a)+k.at(a),k.setAt(a,N&255);I.putBuffer(k)}m=I,l.putBuffer(E)}return l.truncate(l.length()-i),l};gt.pbe.getCipher=function(r,e,t){switch(r){case gt.oids.pkcs5PBES2:return gt.pbe.getCipherForPBES2(r,e,t);case gt.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case gt.oids["pbewithSHAAnd40BitRC2-CBC"]:return gt.pbe.getCipherForPKCS12PBE(r,e,t);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=r,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};gt.pbe.getCipherForPBES2=function(r,e,t){var n={},i=[];if(!W.validate(e,txe,n,i)){var o=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}if(r=W.derToOid(n.kdfOid),r!==gt.oids.pkcs5PBKDF2){var o=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw o.oid=r,o.supportedOids=["pkcs5PBKDF2"],o}if(r=W.derToOid(n.encOid),r!==gt.oids["aes128-CBC"]&&r!==gt.oids["aes192-CBC"]&&r!==gt.oids["aes256-CBC"]&&r!==gt.oids["des-EDE3-CBC"]&&r!==gt.oids.desCBC){var o=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw o.oid=r,o.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],o}var s=n.kdfSalt,a=Ae.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(gt.oids[r]){case"aes128-CBC":c=16,u=Ae.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=Ae.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=Ae.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=Ae.des.createDecryptionCipher;break;case"desCBC":c=8,u=Ae.des.createDecryptionCipher;break}var l=Lj(n.prfOid),f=Ae.pkcs5.pbkdf2(t,s,a,c,l),h=n.encIv,d=u(f);return d.start(h),d};gt.pbe.getCipherForPKCS12PBE=function(r,e,t){var n={},i=[];if(!W.validate(e,rxe,n,i)){var o=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=Ae.util.createBuffer(n.salt),a=Ae.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(r){case gt.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=Ae.des.startDecrypting;break;case gt.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(g,w){var _=Ae.rc2.createDecryptionCipher(g,40);return _.start(w,null),_};break;default:var o=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw o.oid=r,o}var f=Lj(n.prfOid),h=gt.pbe.generatePkcs12Key(t,s,1,a,c,f);f.start();var d=gt.pbe.generatePkcs12Key(t,s,2,a,u,f);return l(h,d)};gt.pbe.opensslDeriveBytes=function(r,e,t,n){if(typeof n>"u"||n===null){if(!("md5"in Ae.md))throw new Error('"md5" hash algorithm unavailable.');n=Ae.md.md5.create()}e===null&&(e="");for(var i=[Oj(n,r+e)],o=16,s=1;o{var Mr=at();Uf();gr();var Zy=EW.exports=Mr.sha512=Mr.sha512||{};Mr.md.sha512=Mr.md.algorithms.sha512=Zy;var bW=Mr.sha384=Mr.sha512.sha384=Mr.sha512.sha384||{};bW.create=function(){return Zy.create("SHA-384")};Mr.md.sha384=Mr.md.algorithms.sha384=bW;Mr.sha512.sha256=Mr.sha512.sha256||{create:function(){return Zy.create("SHA-512/256")}};Mr.md["sha512/256"]=Mr.md.algorithms["sha512/256"]=Mr.sha512.sha256;Mr.sha512.sha224=Mr.sha512.sha224||{create:function(){return Zy.create("SHA-512/224")}};Mr.md["sha512/224"]=Mr.md.algorithms["sha512/224"]=Mr.sha512.sha224;Zy.create=function(r){if(_W||Mxe(),typeof r>"u"&&(r="SHA-512"),!(r in Kh))throw new Error("Invalid SHA-512 algorithm: "+r);for(var e=Kh[r],t=null,n=Mr.util.createBuffer(),i=new Array(80),o=0;o<80;++o)i[o]=new Array(2);var s=64;switch(r){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var a={algorithm:r.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),wW(t,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=Mr.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(PC.substr(0,a.blockLength-l));for(var f,h,d=a.fullMessageLength[0]*8,p=0;p>>0,d+=h,c.putInt32(d>>>0),d=f>>>0;c.putInt32(d);for(var g=new Array(t.length),p=0;p=128;){for(R=0;R<16;++R)e[R][0]=t.getInt32()>>>0,e[R][1]=t.getInt32()>>>0;for(;R<80;++R)te=e[R-2],K=te[0],U=te[1],n=((K>>>19|U<<13)^(U>>>29|K<<3)^K>>>6)>>>0,i=((K<<13|U>>>19)^(U<<3|K>>>29)^(K<<26|U>>>6))>>>0,ae=e[R-15],K=ae[0],U=ae[1],o=((K>>>1|U<<31)^(K>>>8|U<<24)^K>>>7)>>>0,s=((K<<31|U>>>1)^(K<<24|U>>>8)^(K<<25|U>>>7))>>>0,Ce=e[R-7],$e=e[R-16],U=i+Ce[1]+s+$e[1],e[R][0]=n+Ce[0]+o+$e[0]+(U/4294967296>>>0)>>>0,e[R][1]=U>>>0;for(g=r[0][0],w=r[0][1],_=r[1][0],x=r[1][1],m=r[2][0],y=r[2][1],b=r[3][0],E=r[3][1],v=r[4][0],S=r[4][1],A=r[5][0],I=r[5][1],k=r[6][0],N=r[6][1],O=r[7][0],G=r[7][1],R=0;R<80;++R)u=((v>>>14|S<<18)^(v>>>18|S<<14)^(S>>>9|v<<23))>>>0,l=((v<<18|S>>>14)^(v<<14|S>>>18)^(S<<23|v>>>9))>>>0,f=(k^v&(A^k))>>>0,h=(N^S&(I^N))>>>0,a=((g>>>28|w<<4)^(w>>>2|g<<30)^(w>>>7|g<<25))>>>0,c=((g<<4|w>>>28)^(w<<30|g>>>2)^(w<<25|g>>>7))>>>0,d=(g&_|m&(g^_))>>>0,p=(w&x|y&(w^x))>>>0,U=G+l+h+kC[R][1]+e[R][1],n=O+u+f+kC[R][0]+e[R][0]+(U/4294967296>>>0)>>>0,i=U>>>0,U=c+p,o=a+d+(U/4294967296>>>0)>>>0,s=U>>>0,O=k,G=N,k=A,N=I,A=v,I=S,U=E+i,v=b+n+(U/4294967296>>>0)>>>0,S=U>>>0,b=m,E=y,m=_,y=x,_=g,x=w,U=i+s,g=n+o+(U/4294967296>>>0)>>>0,w=U>>>0;U=r[0][1]+w,r[0][0]=r[0][0]+g+(U/4294967296>>>0)>>>0,r[0][1]=U>>>0,U=r[1][1]+x,r[1][0]=r[1][0]+_+(U/4294967296>>>0)>>>0,r[1][1]=U>>>0,U=r[2][1]+y,r[2][0]=r[2][0]+m+(U/4294967296>>>0)>>>0,r[2][1]=U>>>0,U=r[3][1]+E,r[3][0]=r[3][0]+b+(U/4294967296>>>0)>>>0,r[3][1]=U>>>0,U=r[4][1]+S,r[4][0]=r[4][0]+v+(U/4294967296>>>0)>>>0,r[4][1]=U>>>0,U=r[5][1]+I,r[5][0]=r[5][0]+A+(U/4294967296>>>0)>>>0,r[5][1]=U>>>0,U=r[6][1]+N,r[6][0]=r[6][0]+k+(U/4294967296>>>0)>>>0,r[6][1]=U>>>0,U=r[7][1]+G,r[7][0]=r[7][0]+O+(U/4294967296>>>0)>>>0,r[7][1]=U>>>0,He-=128}}});var iY=P((Pst,nY)=>{"use strict";nY.exports=si;var l3=Gh();function si(r,e){this.lo=r>>>0,this.hi=e>>>0}var Hh=si.zero=new si(0,0);Hh.toNumber=function(){return 0};Hh.zzEncode=Hh.zzDecode=function(){return this};Hh.length=function(){return 1};var hSe=si.zeroHash="\0\0\0\0\0\0\0\0";si.fromNumber=function(e){if(e===0)return Hh;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new si(n,i)};si.from=function(e){if(typeof e=="number")return si.fromNumber(e);if(l3.isString(e))if(l3.Long)e=l3.Long.fromString(e);else return si.fromNumber(parseInt(e,10));return e.low||e.high?new si(e.low>>>0,e.high>>>0):Hh};si.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};si.prototype.toLong=function(e){return l3.Long?new l3.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Qf=String.prototype.charCodeAt;si.fromHash=function(e){return e===hSe?Hh:new si((Qf.call(e,0)|Qf.call(e,1)<<8|Qf.call(e,2)<<16|Qf.call(e,3)<<24)>>>0,(Qf.call(e,4)|Qf.call(e,5)<<8|Qf.call(e,6)<<16|Qf.call(e,7)<<24)>>>0)};si.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};si.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};si.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};si.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var Gh=P(WC=>{"use strict";var Be=WC;Be.asPromise=N6();Be.base64=O6();Be.EventEmitter=B6();Be.float=M6();Be.inquire=U6();Be.utf8=F6();Be.pool=z6();Be.LongBits=iY();Be.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Be.global=Be.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||WC;Be.emptyArray=Object.freeze?Object.freeze([]):[];Be.emptyObject=Object.freeze?Object.freeze({}):{};Be.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Be.isString=function(e){return typeof e=="string"||e instanceof String};Be.isObject=function(e){return e&&typeof e=="object"};Be.isset=Be.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Be.Buffer=function(){try{var r=Be.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Be._Buffer_from=null;Be._Buffer_allocUnsafe=null;Be.newBuffer=function(e){return typeof e=="number"?Be.Buffer?Be._Buffer_allocUnsafe(e):new Be.Array(e):Be.Buffer?Be._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Be.Array=typeof Uint8Array<"u"?Uint8Array:Array;Be.Long=Be.global.dcodeIO&&Be.global.dcodeIO.Long||Be.global.Long||Be.inquire("long");Be.key2Re=/^true|false|0|1$/;Be.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Be.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Be.longToHash=function(e){return e?Be.LongBits.from(e).toHash():Be.LongBits.zeroHash};Be.longFromHash=function(e,t){var n=Be.LongBits.fromHash(e);return Be.Long?Be.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function oY(r,e,t){for(var n=Object.keys(e),i=0;i-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Be.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";fY.exports=wn;var Ka=Gh(),QC,uY=Ka.LongBits,pSe=Ka.utf8;function $a(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function wn(r){this.buf=r,this.pos=0,this.len=r.length}var aY=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new wn(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new wn(e);throw Error("illegal buffer")},lY=function(){return Ka.Buffer?function(t){return(wn.create=function(i){return Ka.Buffer.isBuffer(i)?new QC(i):aY(i)})(t)}:aY};wn.create=lY();wn.prototype._slice=Ka.Array.prototype.subarray||Ka.Array.prototype.slice;wn.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,$a(this,10);return e}}();wn.prototype.int32=function(){return this.uint32()|0};wn.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function YC(){var r=new uY(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw $a(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw $a(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}wn.prototype.bool=function(){return this.uint32()!==0};function Jb(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}wn.prototype.fixed32=function(){if(this.pos+4>this.len)throw $a(this,4);return Jb(this.buf,this.pos+=4)};wn.prototype.sfixed32=function(){if(this.pos+4>this.len)throw $a(this,4);return Jb(this.buf,this.pos+=4)|0};function cY(){if(this.pos+8>this.len)throw $a(this,8);return new uY(Jb(this.buf,this.pos+=4),Jb(this.buf,this.pos+=4))}wn.prototype.float=function(){if(this.pos+4>this.len)throw $a(this,4);var e=Ka.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};wn.prototype.double=function(){if(this.pos+8>this.len)throw $a(this,4);var e=Ka.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};wn.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw $a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var i=Ka.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)};wn.prototype.string=function(){var e=this.bytes();return pSe.read(e,0,e.length)};wn.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw $a(this,e);this.pos+=e}else do if(this.pos>=this.len)throw $a(this);while(this.buf[this.pos++]&128);return this};wn.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};wn._configure=function(r){QC=r,wn.create=lY(),QC._configure();var e=Ka.Long?"toLong":"toNumber";Ka.merge(wn.prototype,{int64:function(){return YC.call(this)[e](!1)},uint64:function(){return YC.call(this)[e](!0)},sint64:function(){return YC.call(this).zzDecode()[e](!1)},fixed64:function(){return cY.call(this)[e](!0)},sfixed64:function(){return cY.call(this)[e](!1)}})}});var mY=P((Dst,pY)=>{"use strict";pY.exports=jh;var hY=XC();(jh.prototype=Object.create(hY.prototype)).constructor=jh;var dY=Gh();function jh(r){hY.call(this,r)}jh._configure=function(){dY.Buffer&&(jh.prototype._slice=dY.Buffer.prototype.slice)};jh.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))};jh._configure()});var iP=P((Ost,bY)=>{"use strict";bY.exports=Wt;var Ms=Gh(),ZC,e_=Ms.LongBits,gY=Ms.base64,yY=Ms.utf8;function f3(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function eP(){}function mSe(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Wt(){this.len=0,this.head=new f3(eP,0,0),this.tail=this.head,this.states=null}var wY=function(){return Ms.Buffer?function(){return(Wt.create=function(){return new ZC})()}:function(){return new Wt}};Wt.create=wY();Wt.alloc=function(e){return new Ms.Array(e)};Ms.Array!==Array&&(Wt.alloc=Ms.pool(Wt.alloc,Ms.Array.prototype.subarray));Wt.prototype._push=function(e,t,n){return this.tail=this.tail.next=new f3(e,t,n),this.len+=t,this};function tP(r,e,t){e[t]=r&255}function gSe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function rP(r,e){this.len=r,this.next=void 0,this.val=e}rP.prototype=Object.create(f3.prototype);rP.prototype.fn=gSe;Wt.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new rP((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Wt.prototype.int32=function(e){return e<0?this._push(nP,10,e_.fromNumber(e)):this.uint32(e)};Wt.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function nP(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Wt.prototype.uint64=function(e){var t=e_.from(e);return this._push(nP,t.length(),t)};Wt.prototype.int64=Wt.prototype.uint64;Wt.prototype.sint64=function(e){var t=e_.from(e).zzEncode();return this._push(nP,t.length(),t)};Wt.prototype.bool=function(e){return this._push(tP,1,e?1:0)};function JC(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Wt.prototype.fixed32=function(e){return this._push(JC,4,e>>>0)};Wt.prototype.sfixed32=Wt.prototype.fixed32;Wt.prototype.fixed64=function(e){var t=e_.from(e);return this._push(JC,4,t.lo)._push(JC,4,t.hi)};Wt.prototype.sfixed64=Wt.prototype.fixed64;Wt.prototype.float=function(e){return this._push(Ms.float.writeFloatLE,4,e)};Wt.prototype.double=function(e){return this._push(Ms.float.writeDoubleLE,8,e)};var ySe=Ms.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(tP,1,0);if(Ms.isString(e)){var n=Wt.alloc(t=gY.length(e));gY.decode(e,n,0),e=n}return this.uint32(t)._push(ySe,t,e)};Wt.prototype.string=function(e){var t=yY.length(e);return t?this.uint32(t)._push(yY.write,t,e):this._push(tP,1,0)};Wt.prototype.fork=function(){return this.states=new mSe(this),this.head=this.tail=new f3(eP,0,0),this.len=0,this};Wt.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 f3(eP,0,0),this.len=0),this};Wt.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Wt.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Wt._configure=function(r){ZC=r,Wt.create=wY(),ZC._configure()}});var vY=P((Lst,EY)=>{"use strict";EY.exports=Fc;var _Y=iP();(Fc.prototype=Object.create(_Y.prototype)).constructor=Fc;var Xf=Gh();function Fc(){_Y.call(this)}Fc._configure=function(){Fc.alloc=Xf._Buffer_allocUnsafe,Fc.writeBytesBuffer=Xf.Buffer&&Xf.Buffer.prototype instanceof Uint8Array&&Xf.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(Fc.writeBytesBuffer,t,e),this};function wSe(r,e,t){r.length<40?Xf.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}Fc.prototype.string=function(e){var t=Xf.Buffer.byteLength(e);return this.uint32(t),t&&this._push(wSe,t,e),this};Fc._configure()});var QQ=P((sut,YQ)=>{var gm=1e3,ym=gm*60,wm=ym*60,Xh=wm*24,aAe=Xh*7,cAe=Xh*365.25;YQ.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return uAe(r);if(t==="number"&&isFinite(r))return e.long?fAe(r):lAe(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function uAe(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*cAe;case"weeks":case"week":case"w":return t*aAe;case"days":case"day":case"d":return t*Xh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*wm;case"minutes":case"minute":case"mins":case"min":case"m":return t*ym;case"seconds":case"second":case"secs":case"sec":case"s":return t*gm;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function lAe(r){var e=Math.abs(r);return e>=Xh?Math.round(r/Xh)+"d":e>=wm?Math.round(r/wm)+"h":e>=ym?Math.round(r/ym)+"m":e>=gm?Math.round(r/gm)+"s":r+"ms"}function fAe(r){var e=Math.abs(r);return e>=Xh?b_(r,e,Xh,"day"):e>=wm?b_(r,e,wm,"hour"):e>=ym?b_(r,e,ym,"minute"):e>=gm?b_(r,e,gm,"second"):r+" ms"}function b_(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ZQ=P((aut,XQ)=>{function dAe(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=QQ(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let h=0;h{if(E==="%%")return"%";y++;let S=t.formatters[v];if(typeof S=="function"){let A=w[y];E=S.call(_,A),w.splice(y,1),y--}return E}),t.formatArgs.call(_,w),(_.log||t.log).apply(_,w)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:w=>{h=w}}),typeof t.init=="function"&&t.init(g),g}function n(l,f){let h=t(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=t.skips.length;f{Yo.formatArgs=pAe;Yo.save=mAe;Yo.load=gAe;Yo.useColors=hAe;Yo.storage=yAe();Yo.destroy=(()=>{let r=!1;return()=>{r||(r=!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`."))}})();Yo.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"];function hAe(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function pAe(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+__.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Yo.log=console.debug||console.log||(()=>{});function mAe(r){try{r?Yo.storage.setItem("debug",r):Yo.storage.removeItem("debug")}catch{}}function gAe(){let r;try{r=Yo.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function yAe(){try{return localStorage}catch{}}__.exports=ZQ()(Yo);var{formatters:wAe}=__.exports;wAe.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var v_=P((RP,CP)=>{(function(r,e){typeof RP=="object"&&typeof CP<"u"?CP.exports=function(t,n,i,o,s){for(n=n.split?n.split("."):n,o=0;o{"use strict";var RAe=/^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.){0,126}(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9]))\.?$/i;uX.exports=function(e,t){if(t==null&&(t=!1),e.length<2||e.length>255)return!1;var n=e[e.length-1];if(t){if(n!==".")return!1}else if(n===".")return!1;return RAe.test(e)}});var MX=P((Odt,BX)=>{BX.exports=qP;var LX=128,jAe=127,WAe=~jAe,YAe=Math.pow(2,31);function qP(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw qP.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=YAe;)e[t++]=r&255|LX,r/=128;for(;r&WAe;)e[t++]=r&255|LX,r>>>=7;return e[t]=r|0,qP.bytes=t-n+1,e}});var zX=P((Ldt,FX)=>{FX.exports=HP;var QAe=128,UX=127;function HP(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw HP.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&UX)<=QAe);return HP.bytes=o-n,t}});var KX=P((Bdt,VX)=>{var XAe=Math.pow(2,7),ZAe=Math.pow(2,14),JAe=Math.pow(2,21),eTe=Math.pow(2,28),tTe=Math.pow(2,35),rTe=Math.pow(2,42),nTe=Math.pow(2,49),iTe=Math.pow(2,56),oTe=Math.pow(2,63);VX.exports=function(r){return r{$X.exports={encode:MX(),decode:zX(),encodingLength:KX()}});var pZ=P((z3,Y_)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(d){if(!Array.isArray(d)&&!ArrayBuffer.isView(d))return!1;for(var p=0;p255)return!1;return!0}function i(d,p){return(d&65535)*p+(((d>>>16)*p&65535)<<16)}function o(d,p){return d<>>32-p}function s(d){return d^=d>>>16,d=i(d,2246822507),d^=d>>>13,d=i(d,3266489909),d^=d>>>16,d}function a(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var g=[0,0,0,0];return g[3]+=d[3]+p[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=d[2]+p[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=d[1]+p[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=d[0]+p[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function c(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var g=[0,0,0,0];return g[3]+=d[3]*p[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=d[2]*p[3],g[1]+=g[2]>>>16,g[2]&=65535,g[2]+=d[3]*p[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=d[1]*p[3],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=d[2]*p[2],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=d[3]*p[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=d[0]*p[3]+d[1]*p[2]+d[2]*p[1]+d[3]*p[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function u(d,p){return p%=64,p===32?[d[1],d[0]]:p<32?[d[0]<>>32-p,d[1]<>>32-p]:(p-=32,[d[1]<>>32-p,d[0]<>>32-p])}function l(d,p){return p%=64,p===0?d:p<32?[d[0]<>>32-p,d[1]<>>1]),d=c(d,[4283543511,3981806797]),d=f(d,[0,d[0]>>>1]),d=c(d,[3301882366,444984403]),d=f(d,[0,d[0]>>>1]),d}t.x86.hash32=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var g=d.length%4,w=d.length-g,_=p,x=0,m=3432918353,y=461845907,b=0;b>>0},t.x86.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var g=d.length%16,w=d.length-g,_=p,x=p,m=p,y=p,b=0,E=0,v=0,S=0,A=597399067,I=2869860233,k=951274213,N=2716044179,O=0;O>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)},t.x64.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var g=d.length%16,w=d.length-g,_=[0,p],x=[0,p],m=[0,0],y=[0,0],b=[2277735313,289559509],E=[1291169091,658871167],v=0;v>>0).toString(16)).slice(-8)+("00000000"+(_[1]>>>0).toString(16)).slice(-8)+("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)},typeof z3<"u"?(typeof Y_<"u"&&Y_.exports&&(z3=Y_.exports=t),z3.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(z3)});var nk=P((Spt,mZ)=>{mZ.exports=pZ()});var RZ=P((l0t,IZ)=>{var ok=class{constructor(e,t=12,n=8*1024,i=32*1024,o=64,s){this.bits=t,this.min=n,this.max=i,this.asModule=e,this.rabin=new e.Rabin(t,n,i,o,s),this.polynomial=s}fingerprint(e){let{__retain:t,__release:n,__allocArray:i,__getInt32Array:o,Int32Array_ID:s,Uint8Array_ID:a}=this.asModule,c=new Int32Array(Math.ceil(e.length/this.min)),u=t(i(s,c)),l=t(i(a,e)),f=this.rabin.fingerprint(l,u),h=o(f);n(l),n(u);let d=h.indexOf(0);return d>=0?h.subarray(0,d):h}};IZ.exports=ok});var OZ=P(q3=>{"use strict";var UTe=typeof BigUint64Array<"u",K3=Symbol(),$3=1024;function CZ(r,e){let t=new Uint32Array(r),n=new Uint16Array(r);var i=t[e+-4>>>2]>>>1,o=e>>>1;if(i<=$3)return String.fromCharCode.apply(String,n.subarray(o,o+i));let s=[];do{let a=n[o+$3-1],c=a>=55296&&a<56320?$3-1:$3;s.push(String.fromCharCode.apply(String,n.subarray(o,o+=c))),i-=c}while(i>$3);return s.join("")+String.fromCharCode.apply(String,n.subarray(o,o+i))}function sk(r){let e={};function t(i,o){return i?CZ(i.buffer,o):""}let n=r.env=r.env||{};return n.abort=n.abort||function(o,s,a,c){let u=e.memory||n.memory;throw Error("abort: "+t(u,o)+" at "+t(u,s)+":"+a+":"+c)},n.trace=n.trace||function(o,s){let a=e.memory||n.memory;console.log("trace: "+t(a,o)+(s?" ":"")+Array.prototype.slice.call(arguments,2,2+s).join(", "))},r.Math=r.Math||Math,r.Date=r.Date||Date,e}function ak(r,e){let t=e.exports,n=t.memory,i=t.table,o=t.__alloc,s=t.__retain,a=t.__rtti_base||-1;function c(E){let v=new Uint32Array(n.buffer),S=v[a>>>2];if((E>>>=0)>=S)throw Error("invalid id: "+E);return v[(a+4>>>2)+E*2]}function u(E){let v=new Uint32Array(n.buffer),S=v[a>>>2];if((E>>>=0)>=S)throw Error("invalid id: "+E);return v[(a+4>>>2)+E*2+1]}function l(E){return 31-Math.clz32(E>>>5&31)}function f(E){return 31-Math.clz32(E>>>14&31)}function h(E){let v=E.length,S=o(v<<1,1),A=new Uint16Array(n.buffer);for(var I=0,k=S>>>1;I>>2]!==1)throw Error("not a string: "+E);return CZ(v,E)}r.__getString=d;function p(E,v,S){let A=n.buffer;if(S)switch(E){case 2:return new Float32Array(A);case 3:return new Float64Array(A)}else switch(E){case 0:return new(v?Int8Array:Uint8Array)(A);case 1:return new(v?Int16Array:Uint16Array)(A);case 2:return new(v?Int32Array:Uint32Array)(A);case 3:return new(v?BigInt64Array:BigUint64Array)(A)}throw Error("unsupported align: "+E)}function g(E,v){let S=c(E);if(!(S&3))throw Error("not an array: "+E+" @ "+S);let A=l(S),I=v.length,k=o(I<>>2]=s(k),O[N+4>>>2]=k,O[N+8>>>2]=I<>>2]=I);let G=p(A,S&1024,S&2048);if(S&8192)for(let R=0;R>>A)+R]=s(v[R]);else G.set(v,k>>>A);return N}r.__allocArray=g;function w(E){let v=new Uint32Array(n.buffer),S=v[E+-8>>>2],A=c(S);if(!(A&1))throw Error("not an array: "+S);let I=l(A);var k=v[E+4>>>2];let N=A&2?v[E+12>>>2]:v[k+-4>>>2]>>>I;return p(I,A&1024,A&2048).subarray(k>>>=I,k+N)}r.__getArrayView=w;function _(E){let v=w(E),S=v.length,A=new Array(S);for(let I=0;I>>2];return v.slice(E,E+S)}r.__getArrayBuffer=x;function m(E,v,S){return new E(y(E,v,S))}function y(E,v,S){let A=n.buffer,I=new Uint32Array(A),k=I[S+4>>>2];return new E(A,k,I[k+-4>>>2]>>>v)}r.__getInt8Array=m.bind(null,Int8Array,0),r.__getInt8ArrayView=y.bind(null,Int8Array,0),r.__getUint8Array=m.bind(null,Uint8Array,0),r.__getUint8ArrayView=y.bind(null,Uint8Array,0),r.__getUint8ClampedArray=m.bind(null,Uint8ClampedArray,0),r.__getUint8ClampedArrayView=y.bind(null,Uint8ClampedArray,0),r.__getInt16Array=m.bind(null,Int16Array,1),r.__getInt16ArrayView=y.bind(null,Int16Array,1),r.__getUint16Array=m.bind(null,Uint16Array,1),r.__getUint16ArrayView=y.bind(null,Uint16Array,1),r.__getInt32Array=m.bind(null,Int32Array,2),r.__getInt32ArrayView=y.bind(null,Int32Array,2),r.__getUint32Array=m.bind(null,Uint32Array,2),r.__getUint32ArrayView=y.bind(null,Uint32Array,2),UTe&&(r.__getInt64Array=m.bind(null,BigInt64Array,3),r.__getInt64ArrayView=y.bind(null,BigInt64Array,3),r.__getUint64Array=m.bind(null,BigUint64Array,3),r.__getUint64ArrayView=y.bind(null,BigUint64Array,3)),r.__getFloat32Array=m.bind(null,Float32Array,2),r.__getFloat32ArrayView=y.bind(null,Float32Array,2),r.__getFloat64Array=m.bind(null,Float64Array,3),r.__getFloat64ArrayView=y.bind(null,Float64Array,3);function b(E,v){let S=new Uint32Array(n.buffer);var A=S[E+-8>>>2];if(A<=S[a>>>2])do if(A==v)return!0;while(A=u(A));return!1}return r.__instanceof=b,r.memory=r.memory||n,r.table=r.table||i,DZ(t,r)}function PZ(r){return typeof Response<"u"&&r instanceof Response}async function kZ(r,e){return PZ(r=await r)?NZ(r,e):ak(sk(e||(e={})),await WebAssembly.instantiate(r instanceof WebAssembly.Module?r:await WebAssembly.compile(r),e))}q3.instantiate=kZ;function FTe(r,e){return ak(sk(e||(e={})),new WebAssembly.Instance(r instanceof WebAssembly.Module?r:new WebAssembly.Module(r),e))}q3.instantiateSync=FTe;async function NZ(r,e){return WebAssembly.instantiateStreaming?ak(sk(e||(e={})),(await WebAssembly.instantiateStreaming(r,e)).instance):kZ(PZ(r=await r)?r.arrayBuffer():r,e)}q3.instantiateStreaming=NZ;function DZ(r,e){var t=e?Object.create(e):{},n=r.__argumentsLength?function(i){r.__argumentsLength.value=i}:r.__setArgumentsLength||r.__setargc||function(){};for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let o=r[i],s=i.split("."),a=t;for(;s.length>1;){let l=s.shift();Object.prototype.hasOwnProperty.call(a,l)||(a[l]={}),a=a[l]}let c=s[0],u=c.indexOf("#");if(u>=0){let l=c.substring(0,u),f=a[l];if(typeof f>"u"||!f.prototype){let h=function(...d){return h.wrap(h.prototype.constructor(0,...d))};h.prototype={valueOf:function(){return this[K3]}},h.wrap=function(d){return Object.create(h.prototype,{[K3]:{value:d,writable:!1}})},f&&Object.getOwnPropertyNames(f).forEach(d=>Object.defineProperty(h,d,Object.getOwnPropertyDescriptor(f,d))),a[l]=h}if(c=c.substring(u+1),a=a[l].prototype,/^(get|set):/.test(c)){if(!Object.prototype.hasOwnProperty.call(a,c=c.substring(4))){let h=r[i.replace("set:","get:")],d=r[i.replace("get:","set:")];Object.defineProperty(a,c,{get:function(){return h(this[K3])},set:function(p){d(this[K3],p)},enumerable:!0})}}else c==="constructor"?(a[c]=(...h)=>(n(h.length),o(...h))).original=o:(a[c]=function(...h){return n(h.length),o(this[K3],...h)}).original=o}else/^(get|set):/.test(c)?Object.prototype.hasOwnProperty.call(a,c=c.substring(4))||Object.defineProperty(a,c,{get:r[i.replace("set:","get:")],set:r[i.replace("get:","set:")],enumerable:!0}):typeof o=="function"&&o!==n?(a[c]=(...l)=>(n(l.length),o(...l))).original=o:a[c]=o}return t}q3.demangle=DZ});var BZ=P((d0t,LZ)=>{var{instantiate:zTe}=OZ();ck.supported=typeof WebAssembly<"u";function ck(r={}){if(!ck.supported)return null;var e=new Uint8Array([0,97,115,109,1,0,0,0,1,78,14,96,2,127,126,0,96,1,127,1,126,96,2,127,127,0,96,1,127,1,127,96,1,127,0,96,2,127,127,1,127,96,3,127,127,127,1,127,96,0,0,96,3,127,127,127,0,96,0,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,1,127,96,1,126,1,127,96,2,126,126,1,126,2,13,1,3,101,110,118,5,97,98,111,114,116,0,10,3,54,53,2,2,8,9,3,5,2,8,6,5,3,4,2,6,9,12,13,2,5,11,3,2,3,2,3,2,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,6,7,7,4,4,5,3,1,0,1,6,47,9,127,1,65,0,11,127,1,65,0,11,127,0,65,3,11,127,0,65,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,240,2,11,127,0,65,6,11,7,240,5,41,6,109,101,109,111,114,121,2,0,7,95,95,97,108,108,111,99,0,10,8,95,95,114,101,116,97,105,110,0,11,9,95,95,114,101,108,101,97,115,101,0,12,9,95,95,99,111,108,108,101,99,116,0,51,11,95,95,114,116,116,105,95,98,97,115,101,3,7,13,73,110,116,51,50,65,114,114,97,121,95,73,68,3,2,13,85,105,110,116,56,65,114,114,97,121,95,73,68,3,3,6,100,101,103,114,101,101,0,16,3,109,111,100,0,17,5,82,97,98,105,110,3,8,16,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,0,21,16,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,0,22,21,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,23,21,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,24,14,82,97,98,105,110,35,103,101,116,58,119,112,111,115,0,25,14,82,97,98,105,110,35,115,101,116,58,119,112,111,115,0,26,15,82,97,98,105,110,35,103,101,116,58,99,111,117,110,116,0,27,15,82,97,98,105,110,35,115,101,116,58,99,111,117,110,116,0,28,13,82,97,98,105,110,35,103,101,116,58,112,111,115,0,29,13,82,97,98,105,110,35,115,101,116,58,112,111,115,0,30,15,82,97,98,105,110,35,103,101,116,58,115,116,97,114,116,0,31,15,82,97,98,105,110,35,115,101,116,58,115,116,97,114,116,0,32,16,82,97,98,105,110,35,103,101,116,58,100,105,103,101,115,116,0,33,16,82,97,98,105,110,35,115,101,116,58,100,105,103,101,115,116,0,34,21,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,35,21,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,36,22,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,37,22,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,38,31,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,39,31,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,40,20,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,0,41,20,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,0,42,17,82,97,98,105,110,35,103,101,116,58,109,105,110,115,105,122,101,0,43,17,82,97,98,105,110,35,115,101,116,58,109,105,110,115,105,122,101,0,44,17,82,97,98,105,110,35,103,101,116,58,109,97,120,115,105,122,101,0,45,17,82,97,98,105,110,35,115,101,116,58,109,97,120,115,105,122,101,0,46,14,82,97,98,105,110,35,103,101,116,58,109,97,115,107,0,47,14,82,97,98,105,110,35,115,101,116,58,109,97,115,107,0,48,17,82,97,98,105,110,35,99,111,110,115,116,114,117,99,116,111,114,0,20,17,82,97,98,105,110,35,102,105,110,103,101,114,112,114,105,110,116,0,49,8,1,50,10,165,31,53,199,1,1,4,127,32,1,40,2,0,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,3,65,4,107,118,65,16,115,33,4,32,3,65,7,107,11,33,3,32,1,40,2,20,33,2,32,1,40,2,16,34,5,4,64,32,5,32,2,54,2,20,11,32,2,4,64,32,2,32,5,54,2,16,11,32,1,32,0,32,4,32,3,65,4,116,106,65,2,116,106,40,2,96,70,4,64,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,2,54,2,96,32,2,69,4,64,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,65,127,115,113,34,1,54,2,4,32,1,69,4,64,32,0,32,0,40,2,0,65,1,32,3,116,65,127,115,113,54,2,0,11,11,11,11,226,2,1,6,127,32,1,40,2,0,33,3,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,5,65,1,113,4,64,32,3,65,124,113,65,16,106,32,5,65,124,113,106,34,2,65,240,255,255,255,3,73,4,64,32,0,32,4,16,1,32,1,32,2,32,3,65,3,113,114,34,3,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,5,11,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,2,40,2,0,34,6,65,124,113,65,16,106,32,3,65,124,113,106,34,7,65,240,255,255,255,3,73,4,64,32,0,32,2,16,1,32,2,32,7,32,6,65,3,113,114,34,3,54,2,0,32,2,33,1,11,11,32,4,32,5,65,2,114,54,2,0,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,2,65,4,107,118,65,16,115,33,4,32,2,65,7,107,11,34,3,65,4,116,32,4,106,65,2,116,106,40,2,96,33,2,32,1,65,0,54,2,16,32,1,32,2,54,2,20,32,2,4,64,32,2,32,1,54,2,16,11,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,3,116,114,54,2,0,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,114,54,2,4,11,119,1,1,127,32,2,2,127,32,0,40,2,160,12,34,2,4,64,32,2,32,1,65,16,107,70,4,64,32,2,40,2,0,33,3,32,1,65,16,107,33,1,11,11,32,1,11,107,34,2,65,48,73,4,64,15,11,32,1,32,3,65,2,113,32,2,65,32,107,65,1,114,114,54,2,0,32,1,65,0,54,2,16,32,1,65,0,54,2,20,32,1,32,2,106,65,16,107,34,2,65,2,54,2,0,32,0,32,2,54,2,160,12,32,0,32,1,16,2,11,155,1,1,3,127,35,0,34,0,69,4,64,65,1,63,0,34,0,74,4,127,65,1,32,0,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,176,3,34,0,65,0,54,2,0,65,208,15,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,176,3,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,176,3,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,176,3,65,224,15,63,0,65,16,116,16,3,65,176,3,36,0,11,32,0,11,45,0,32,0,65,240,255,255,255,3,79,4,64,65,32,65,224,0,65,201,3,65,29,16,0,0,11,32,0,65,15,106,65,112,113,34,0,65,16,32,0,65,16,75,27,11,169,1,1,1,127,32,0,32,1,65,128,2,73,4,127,32,1,65,4,118,33,1,65,0,5,32,1,65,248,255,255,255,1,73,4,64,32,1,65,1,65,27,32,1,103,107,116,106,65,1,107,33,1,11,32,1,65,31,32,1,103,107,34,2,65,4,107,118,65,16,115,33,1,32,2,65,7,107,11,34,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,111,1,1,127,63,0,34,2,32,1,65,248,255,255,255,1,73,4,127,32,1,65,1,65,27,32,1,103,107,116,65,1,107,106,5,32,1,11,65,16,32,0,40,2,160,12,32,2,65,16,116,65,16,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,32,0,32,2,65,16,116,63,0,65,16,116,16,3,11,113,1,2,127,32,1,40,2,0,34,3,65,124,113,32,2,107,34,4,65,32,79,4,64,32,1,32,2,32,3,65,2,113,114,54,2,0,32,2,32,1,65,16,106,106,34,1,32,4,65,16,107,65,1,114,54,2,0,32,0,32,1,16,2,5,32,1,32,3,65,126,113,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,32,1,65,16,106,32,1,40,2,0,65,124,113,106,40,2,0,65,125,113,54,2,0,11,11,91,1,2,127,32,0,32,1,16,5,34,4,16,6,34,3,69,4,64,65,1,36,1,65,0,36,1,32,0,32,4,16,6,34,3,69,4,64,32,0,32,4,16,7,32,0,32,4,16,6,33,3,11,11,32,3,65,0,54,2,4,32,3,32,2,54,2,8,32,3,32,1,54,2,12,32,0,32,3,16,1,32,0,32,3,32,4,16,8,32,3,11,13,0,16,4,32,0,32,1,16,9,65,16,106,11,33,1,1,127,32,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,18,0,32,0,65,172,3,75,4,64,32,0,65,16,107,16,52,11,11,140,3,1,1,127,2,64,32,1,69,13,0,32,0,65,0,58,0,0,32,0,32,1,106,65,1,107,65,0,58,0,0,32,1,65,2,77,13,0,32,0,65,1,106,65,0,58,0,0,32,0,65,2,106,65,0,58,0,0,32,0,32,1,106,34,2,65,2,107,65,0,58,0,0,32,2,65,3,107,65,0,58,0,0,32,1,65,6,77,13,0,32,0,65,3,106,65,0,58,0,0,32,0,32,1,106,65,4,107,65,0,58,0,0,32,1,65,8,77,13,0,32,1,65,0,32,0,107,65,3,113,34,1,107,33,2,32,0,32,1,106,34,0,65,0,54,2,0,32,0,32,2,65,124,113,34,1,106,65,4,107,65,0,54,2,0,32,1,65,8,77,13,0,32,0,65,4,106,65,0,54,2,0,32,0,65,8,106,65,0,54,2,0,32,0,32,1,106,34,2,65,12,107,65,0,54,2,0,32,2,65,8,107,65,0,54,2,0,32,1,65,24,77,13,0,32,0,65,12,106,65,0,54,2,0,32,0,65,16,106,65,0,54,2,0,32,0,65,20,106,65,0,54,2,0,32,0,65,24,106,65,0,54,2,0,32,0,32,1,106,34,2,65,28,107,65,0,54,2,0,32,2,65,24,107,65,0,54,2,0,32,2,65,20,107,65,0,54,2,0,32,2,65,16,107,65,0,54,2,0,32,0,32,0,65,4,113,65,24,106,34,2,106,33,0,32,1,32,2,107,33,1,3,64,32,1,65,32,79,4,64,32,0,66,0,55,3,0,32,0,65,8,106,66,0,55,3,0,32,0,65,16,106,66,0,55,3,0,32,0,65,24,106,66,0,55,3,0,32,1,65,32,107,33,1,32,0,65,32,106,33,0,12,1,11,11,11,11,178,1,1,3,127,32,1,65,240,255,255,255,3,32,2,118,75,4,64,65,144,1,65,192,1,65,23,65,56,16,0,0,11,32,1,32,2,116,34,3,65,0,16,10,34,2,32,3,16,13,32,0,69,4,64,65,12,65,2,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,2,34,1,32,0,40,2,0,34,4,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,32,4,16,12,11,32,0,32,1,54,2,0,32,0,32,2,54,2,4,32,0,32,3,54,2,8,32,0,11,46,1,2,127,65,12,65,5,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,65,128,2,65,3,16,14,11,9,0,65,63,32,0,121,167,107,11,49,1,2,127,65,63,32,1,121,167,107,33,2,3,64,65,63,32,0,121,167,107,32,2,107,34,3,65,0,78,4,64,32,0,32,1,32,3,172,134,133,33,0,12,1,11,11,32,0,11,40,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,163,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,65,0,58,0,0,11,38,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,152,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,45,0,0,11,254,5,2,1,127,4,126,32,0,69,4,64,65,232,0,65,6,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,24,32,0,66,0,55,3,32,32,0,66,0,55,3,40,32,0,66,0,55,3,48,32,0,66,0,55,3,56,32,0,66,0,55,3,64,32,0,66,0,55,3,72,32,0,66,0,55,3,80,32,0,66,0,55,3,88,32,0,66,0,55,3,96,32,0,32,2,173,55,3,80,32,0,32,3,173,55,3,88,65,12,65,4,16,10,34,2,65,172,3,75,4,64,32,2,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,32,4,65,0,16,14,33,2,32,0,40,2,0,16,12,32,0,32,2,54,2,0,32,0,32,4,54,2,4,32,0,66,1,32,1,173,134,66,1,125,55,3,96,32,0,66,243,130,183,218,216,230,232,30,55,3,72,35,4,69,4,64,65,0,33,2,3,64,32,2,65,128,2,72,4,64,32,2,65,255,1,113,173,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,65,0,33,4,3,64,32,4,32,0,40,2,4,65,1,107,72,4,64,32,6,66,8,134,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,32,4,65,1,106,33,4,12,1,11,11,35,6,40,2,4,32,2,65,3,116,106,32,6,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,63,32,0,41,3,72,121,167,107,172,33,7,65,0,33,2,3,64,32,2,65,128,2,72,4,64,35,5,33,1,32,2,172,32,7,134,34,8,33,6,65,63,32,0,41,3,72,34,9,121,167,107,33,3,3,64,65,63,32,6,121,167,107,32,3,107,34,4,65,0,78,4,64,32,6,32,9,32,4,172,134,133,33,6,12,1,11,11,32,1,40,2,4,32,2,65,3,116,106,32,6,32,8,132,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,1,36,4,11,32,0,66,0,55,3,24,32,0,66,0,55,3,32,65,0,33,2,3,64,32,2,32,0,40,2,4,72,4,64,32,0,40,2,0,32,2,16,18,32,2,65,1,106,33,2,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,6,66,45,136,167,65,3,116,106,41,3,0,32,6,66,8,134,66,1,132,133,55,3,40,32,0,11,38,1,1,127,32,0,40,2,0,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,55,1,2,127,32,1,32,0,40,2,0,34,2,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,16,12,11,32,0,32,1,54,2,0,11,7,0,32,0,40,2,4,11,9,0,32,0,32,1,54,2,4,11,7,0,32,0,40,2,8,11,9,0,32,0,32,1,54,2,8,11,7,0,32,0,41,3,16,11,9,0,32,0,32,1,55,3,16,11,7,0,32,0,41,3,24,11,9,0,32,0,32,1,55,3,24,11,7,0,32,0,41,3,32,11,9,0,32,0,32,1,55,3,32,11,7,0,32,0,41,3,40,11,9,0,32,0,32,1,55,3,40,11,7,0,32,0,41,3,48,11,9,0,32,0,32,1,55,3,48,11,7,0,32,0,41,3,56,11,9,0,32,0,32,1,55,3,56,11,7,0,32,0,41,3,64,11,9,0,32,0,32,1,55,3,64,11,7,0,32,0,41,3,72,11,9,0,32,0,32,1,55,3,72,11,7,0,32,0,41,3,80,11,9,0,32,0,32,1,55,3,80,11,7,0,32,0,41,3,88,11,9,0,32,0,32,1,55,3,88,11,7,0,32,0,41,3,96,11,9,0,32,0,32,1,55,3,96,11,172,4,2,5,127,1,126,32,2,65,172,3,75,4,64,32,2,65,16,107,34,4,32,4,40,2,4,65,1,106,54,2,4,11,32,2,33,4,65,0,33,2,32,1,40,2,8,33,5,32,1,40,2,4,33,6,3,64,2,127,65,0,33,3,3,64,32,3,32,5,72,4,64,32,3,32,6,106,45,0,0,33,1,32,0,40,2,0,32,0,40,2,8,16,19,33,7,32,0,40,2,8,32,0,40,2,0,40,2,4,106,32,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,7,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,1,173,32,8,66,8,134,132,133,55,3,40,32,0,32,0,41,3,16,66,1,124,55,3,16,32,0,32,0,41,3,24,66,1,124,55,3,24,32,0,41,3,16,32,0,41,3,80,90,4,127,32,0,41,3,40,32,0,41,3,96,131,80,5,65,0,11,4,127,65,1,5,32,0,41,3,16,32,0,41,3,88,90,11,4,64,32,0,32,0,41,3,32,55,3,48,32,0,32,0,41,3,16,55,3,56,32,0,32,0,41,3,40,55,3,64,65,0,33,1,3,64,32,1,32,0,40,2,4,72,4,64,32,0,40,2,0,32,1,16,18,32,1,65,1,106,33,1,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,8,66,8,134,66,1,132,133,55,3,40,32,3,65,1,106,12,3,11,32,3,65,1,106,33,3,12,1,11,11,65,127,11,34,1,65,0,78,4,64,32,5,32,1,107,33,5,32,1,32,6,106,33,6,32,2,34,1,65,1,106,33,2,32,4,40,2,4,32,1,65,2,116,106,32,0,41,3,56,62,2,0,12,1,11,11,32,4,11,10,0,16,15,36,5,16,15,36,6,11,3,0,1,11,73,1,2,127,32,0,40,2,4,34,1,65,255,255,255,255,0,113,34,2,65,1,70,4,64,32,0,65,16,106,16,53,32,0,32,0,40,2,0,65,1,114,54,2,0,35,0,32,0,16,2,5,32,0,32,2,65,1,107,32,1,65,128,128,128,128,127,113,114,54,2,4,11,11,58,0,2,64,2,64,2,64,32,0,65,8,107,40,2,0,14,7,0,0,1,1,1,1,1,2,11,15,11,32,0,40,2,0,34,0,4,64,32,0,65,172,3,79,4,64,32,0,65,16,107,16,52,11,11,15,11,0,11,11,137,3,7,0,65,16,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,208,0,11,45,30,0,0,0,1,0,0,0,1,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,128,1,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,176,1,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,240,1,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,176,2,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,126,0,108,0,105,0,98,0,47,0,116,0,121,0,112,0,101,0,100,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,240,2,11,53,7,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,145,4,0,0,2,0,0,0,49,0,0,0,2,0,0,0,17,1,0,0,2,0,0,0,16,0,34,16,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,16,46,47,114,97,98,105,110,46,119,97,115,109,46,109,97,112]);return zTe(new Response(new Blob([e],{type:"application/wasm"})),r)}LZ.exports=ck});var FZ=P((h0t,UZ)=>{var MZ=RZ(),VTe=BZ(),KTe=async(r,e,t,n,i)=>{let o=await VTe();return new MZ(o,r,e,t,n,i)};UZ.exports={Rabin:MZ,create:KTe}});var pk=P((D0t,GZ)=>{"use strict";GZ.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let i=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):i=!0,this._setInternalPos(n,e,t,i),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t=this._bitArrays.length)return-1;let i=this._bitArrays[n],o=e-n*7;if(!((i&1<0))return-1;let a=this._bitArrays.slice(0,n).reduce(XTe,0),c=~(4294967295<=t)o.push(s);else if(o[0][0]<=t)o.unshift(s);else{let a=Math.round(o.length/2);this._data=o.slice(0,a).concat(s).concat(o.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(ZTe),this._changedData=!1}bitField(){let e=[],t=8,n=0,i=0,o,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(o=s.shift(),n=7);let c=Math.min(n,t),u=~(255<>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(i),i=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(JTe)}};function XTe(r,e){return r+HZ(e)}function HZ(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function ZTe(r,e){return r[0]-e[0]}function JTe(r){return r[1]}});var xJ=P((dmt,bk)=>{"use strict";var zIe=Object.prototype.hasOwnProperty,oo="~";function Q3(){}Object.create&&(Q3.prototype=Object.create(null),new Q3().__proto__||(oo=!1));function VIe(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function vJ(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new VIe(t,n||r,i),s=oo?oo+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function cE(r,e){--r._eventsCount===0?r._events=new Q3:delete r._events[e]}function Ui(){this._events=new Q3,this._eventsCount=0}Ui.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)zIe.call(t,n)&&e.push(oo?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ui.prototype.listeners=function(e){var t=oo?oo+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i{"use strict";GJ.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:8,RTLD_LOCAL:4,E2BIG:7,EACCES:13,EADDRINUSE:48,EADDRNOTAVAIL:49,EAFNOSUPPORT:47,EAGAIN:35,EALREADY:37,EBADF:9,EBADMSG:94,EBUSY:16,ECANCELED:89,ECHILD:10,ECONNABORTED:53,ECONNREFUSED:61,ECONNRESET:54,EDEADLK:11,EDESTADDRREQ:39,EDOM:33,EDQUOT:69,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:65,EIDRM:90,EILSEQ:92,EINPROGRESS:36,EINTR:4,EINVAL:22,EIO:5,EISCONN:56,EISDIR:21,ELOOP:62,EMFILE:24,EMLINK:31,EMSGSIZE:40,EMULTIHOP:95,ENAMETOOLONG:63,ENETDOWN:50,ENETRESET:52,ENETUNREACH:51,ENFILE:23,ENOBUFS:55,ENODATA:96,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:77,ENOLINK:97,ENOMEM:12,ENOMSG:91,ENOPROTOOPT:42,ENOSPC:28,ENOSR:98,ENOSTR:99,ENOSYS:78,ENOTCONN:57,ENOTDIR:20,ENOTEMPTY:66,ENOTSOCK:38,ENOTSUP:45,ENOTTY:25,ENXIO:6,EOPNOTSUPP:102,EOVERFLOW:84,EPERM:1,EPIPE:32,EPROTO:100,EPROTONOSUPPORT:43,EPROTOTYPE:41,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:70,ETIME:101,ETIMEDOUT:60,ETXTBSY:26,EWOULDBLOCK:35,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:10,SIGFPE:8,SIGKILL:9,SIGUSR1:30,SIGSEGV:11,SIGUSR2:31,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:20,SIGCONT:19,SIGSTOP:17,SIGTSTP:18,SIGTTIN:21,SIGTTOU:22,SIGURG:16,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:23,SIGINFO:29,SIGSYS:12,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:512,O_EXCL:2048,UV_FS_O_FILEMAP:0,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_DIRECTORY:1048576,O_NOFOLLOW:256,O_SYNC:128,O_DSYNC:4194304,O_SYMLINK:2097152,O_NONBLOCK:4,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306480,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_EPHEMERAL_RSA:0,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER:0,SSL_OP_MICROSOFT_SESS_ID_BUG:0,SSL_OP_MSIE_SSLV2_RSA_PADDING:0,SSL_OP_NETSCAPE_CA_DN_BUG:0,SSL_OP_NETSCAPE_CHALLENGE_BUG:0,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG:0,SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG:0,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PKCS1_CHECK_1:0,SSL_OP_PKCS1_CHECK_2:0,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_SINGLE_DH_USE:0,SSL_OP_SINGLE_ECDH_USE:0,SSL_OP_SSLEAY_080_CLIENT_DH_BUG:0,SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG:0,SSL_OP_TLS_BLOCK_PADDING_BUG:0,SSL_OP_TLS_D5_BUG:0,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6,defaultCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA"}});var vne=P((LN,Ene)=>{"use strict";Object.defineProperty(LN,"__esModule",{value:!0});m7.BASE=2166136261;function m7(r,e=m7.BASE){let t=r.length;for(let n=0;n>>0}LN.default=m7;Ene.exports=m7});var gie=P((e_t,I7)=>{"use strict";I7.exports=BDe;I7.exports.format=pie;I7.exports.parse=mie;var DDe=/\B(?=(\d{3})+(?!\d))/g,ODe=/(?:\.0*|(\.[^0]+)0+)$/,Sd={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},LDe=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function BDe(r,e){return typeof r=="string"?mie(r):typeof r=="number"?pie(r,e):null}function pie(r,e){if(!Number.isFinite(r))return null;var t=Math.abs(r),n=e&&e.thousandsSeparator||"",i=e&&e.unitSeparator||"",o=e&&e.decimalPlaces!==void 0?e.decimalPlaces:2,s=!!(e&&e.fixedDecimals),a=e&&e.unit||"";(!a||!Sd[a.toLowerCase()])&&(t>=Sd.pb?a="PB":t>=Sd.tb?a="TB":t>=Sd.gb?a="GB":t>=Sd.mb?a="MB":t>=Sd.kb?a="KB":a="B");var c=r/Sd[a.toLowerCase()],u=c.toFixed(o);return s||(u=u.replace(ODe,"$1")),n&&(u=u.split(".").map(function(l,f){return f===0?l.replace(DDe,n):l}).join(".")),u+i+a}function mie(r){if(typeof r=="number"&&!isNaN(r))return r;if(typeof r!="string")return null;var e=LDe.exec(r),t,n="b";return e?(t=parseFloat(e[1]),n=e[4].toLowerCase()):(t=parseInt(r,10),n="b"),isNaN(t)?null:Math.floor(Sd[n]*t)}});var Qie=P(Yie=>{"use strict";Yie.supports=function(...e){let t=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(t,{snapshots:t.snapshots||!1,permanence:t.permanence||!1,seek:t.seek||!1,clear:t.clear||!1,getMany:t.getMany||!1,keyIterator:t.keyIterator||!1,valueIterator:t.valueIterator||!1,iteratorNextv:t.iteratorNextv||!1,iteratorAll:t.iteratorAll||!1,status:t.status||!1,createIfMissing:t.createIfMissing||!1,errorIfExists:t.errorIfExists||!1,deferredOpen:t.deferredOpen||!1,promises:t.promises||!1,streams:t.streams||!1,encodings:Object.assign({},t.encodings),events:Object.assign({},t.events),additionalMethods:Object.assign({},t.additionalMethods)})}});var Za=P((WEt,Xie)=>{"use strict";Xie.exports=class extends Error{constructor(e,t){super(e||""),typeof t=="object"&&t!==null&&(t.code&&(this.code=String(t.code)),t.expected&&(this.expected=!0),t.transient&&(this.transient=!0),t.cause&&(this.cause=t.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var eoe=P(L7=>{"use strict";L7.byteLength=aOe;L7.toByteArray=uOe;L7.fromByteArray=dOe;var iu=[],Zs=[],sOe=typeof Uint8Array<"u"?Uint8Array:Array,ND="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Dp=0,Zie=ND.length;Dp0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function aOe(r){var e=Jie(r),t=e[0],n=e[1];return(t+n)*3/4-n}function cOe(r,e,t){return(e+t)*3/4-t}function uOe(r){var e,t=Jie(r),n=t[0],i=t[1],o=new sOe(cOe(r,n,i)),s=0,a=i>0?n-4:n,c;for(c=0;c>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Zs[r.charCodeAt(c)]<<2|Zs[r.charCodeAt(c+1)]>>4,o[s++]=e&255),i===1&&(e=Zs[r.charCodeAt(c)]<<10|Zs[r.charCodeAt(c+1)]<<4|Zs[r.charCodeAt(c+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function lOe(r){return iu[r>>18&63]+iu[r>>12&63]+iu[r>>6&63]+iu[r&63]}function fOe(r,e,t){for(var n,i=[],o=e;oa?a:s+o));return n===1?(e=r[t-1],i.push(iu[e>>2]+iu[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(iu[e>>10]+iu[e>>4&63]+iu[e<<2&63]+"=")),i.join("")}});var toe=P(DD=>{DD.read=function(r,e,t,n,i){var o,s,a=i*8-n-1,c=(1<>1,l=-7,f=t?i-1:0,h=t?-1:1,d=r[e+f];for(f+=h,o=d&(1<<-l)-1,d>>=-l,l+=a;l>0;o=o*256+r[e+f],f+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=s*256+r[e+f],f+=h,l-=8);if(o===0)o=1-u;else{if(o===c)return s?NaN:(d?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(d?-1:1)*s*Math.pow(2,o-n)};DD.write=function(r,e,t,n,i,o){var s,a,c,u=o*8-i-1,l=(1<>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+f>=1?e+=h/c:e+=h*Math.pow(2,1-f),e*c>=2&&(s++,c/=2),s+f>=l?(a=0,s=l):s+f>=1?(a=(e*c-1)*Math.pow(2,i),s=s+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;r[t+d]=a&255,d+=p,a/=256,i-=8);for(s=s<0;r[t+d]=s&255,d+=p,s/=256,u-=8);r[t+d-p]|=g*128}});var n5=P(w2=>{"use strict";var OD=eoe(),g2=toe(),roe=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;w2.Buffer=Y;w2.SlowBuffer=wOe;w2.INSPECT_MAX_BYTES=50;var B7=2147483647;w2.kMaxLength=B7;Y.TYPED_ARRAY_SUPPORT=hOe();!Y.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function hOe(){try{let r=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(r,e),r.foo()===42}catch{return!1}}Object.defineProperty(Y.prototype,"parent",{enumerable:!0,get:function(){if(Y.isBuffer(this))return this.buffer}});Object.defineProperty(Y.prototype,"offset",{enumerable:!0,get:function(){if(Y.isBuffer(this))return this.byteOffset}});function wl(r){if(r>B7)throw new RangeError('The value "'+r+'" is invalid for option "size"');let e=new Uint8Array(r);return Object.setPrototypeOf(e,Y.prototype),e}function Y(r,e,t){if(typeof r=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return UD(r)}return soe(r,e,t)}Y.poolSize=8192;function soe(r,e,t){if(typeof r=="string")return mOe(r,e);if(ArrayBuffer.isView(r))return gOe(r);if(r==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);if(ou(r,ArrayBuffer)||r&&ou(r.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ou(r,SharedArrayBuffer)||r&&ou(r.buffer,SharedArrayBuffer)))return BD(r,e,t);if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=r.valueOf&&r.valueOf();if(n!=null&&n!==r)return Y.from(n,e,t);let i=yOe(r);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]=="function")return Y.from(r[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r)}Y.from=function(r,e,t){return soe(r,e,t)};Object.setPrototypeOf(Y.prototype,Uint8Array.prototype);Object.setPrototypeOf(Y,Uint8Array);function aoe(r){if(typeof r!="number")throw new TypeError('"size" argument must be of type number');if(r<0)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function pOe(r,e,t){return aoe(r),r<=0?wl(r):e!==void 0?typeof t=="string"?wl(r).fill(e,t):wl(r).fill(e):wl(r)}Y.alloc=function(r,e,t){return pOe(r,e,t)};function UD(r){return aoe(r),wl(r<0?0:FD(r)|0)}Y.allocUnsafe=function(r){return UD(r)};Y.allocUnsafeSlow=function(r){return UD(r)};function mOe(r,e){if((typeof e!="string"||e==="")&&(e="utf8"),!Y.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=coe(r,e)|0,n=wl(t),i=n.write(r,e);return i!==t&&(n=n.slice(0,i)),n}function LD(r){let e=r.length<0?0:FD(r.length)|0,t=wl(e);for(let n=0;n=B7)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+B7.toString(16)+" bytes");return r|0}function wOe(r){return+r!=r&&(r=0),Y.alloc(+r)}Y.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==Y.prototype};Y.compare=function(e,t){if(ou(e,Uint8Array)&&(e=Y.from(e,e.offset,e.byteLength)),ou(t,Uint8Array)&&(t=Y.from(t,t.offset,t.byteLength)),!Y.isBuffer(e)||!Y.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let o=0,s=Math.min(n,i);oi.length?(Y.isBuffer(s)||(s=Y.from(s)),s.copy(i,o)):Uint8Array.prototype.set.call(i,s,o);else if(Y.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function coe(r,e){if(Y.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||ou(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);let t=r.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&t===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return MD(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return yoe(r).length;default:if(i)return n?-1:MD(r).length;e=(""+e).toLowerCase(),i=!0}}Y.byteLength=coe;function bOe(r,e,t){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(r||(r="utf8");;)switch(r){case"hex":return COe(this,e,t);case"utf8":case"utf-8":return loe(this,e,t);case"ascii":return IOe(this,e,t);case"latin1":case"binary":return ROe(this,e,t);case"base64":return AOe(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return POe(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}Y.prototype._isBuffer=!0;function Op(r,e,t){let n=r[e];r[e]=r[t],r[t]=n}Y.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tt&&(e+=" ... "),""};roe&&(Y.prototype[roe]=Y.prototype.inspect);Y.prototype.compare=function(e,t,n,i,o){if(ou(e,Uint8Array)&&(e=Y.from(e,e.offset,e.byteLength)),!Y.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),t<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&t>=n)return 0;if(i>=o)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,o>>>=0,this===e)return 0;let s=o-i,a=n-t,c=Math.min(s,a),u=this.slice(i,o),l=e.slice(t,n);for(let f=0;f2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,VD(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t),t>=r.length){if(i)return-1;t=r.length-1}else if(t<0)if(i)t=0;else return-1;if(typeof e=="string"&&(e=Y.from(e,n)),Y.isBuffer(e))return e.length===0?-1:noe(r,e,t,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):noe(r,[e],t,n,i);throw new TypeError("val must be string, number or Buffer")}function noe(r,e,t,n,i){let o=1,s=r.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(r.length<2||e.length<2)return-1;o=2,s/=2,a/=2,t/=2}function c(l,f){return o===1?l[f]:l.readUInt16BE(f*o)}let u;if(i){let l=-1;for(u=t;us&&(t=s-a),u=t;u>=0;u--){let l=!0;for(let f=0;fi&&(n=i)):n=i;let o=e.length;n>o/2&&(n=o/2);let s;for(s=0;s>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let o=this.length-t;if((n===void 0||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let s=!1;for(;;)switch(i){case"hex":return _Oe(this,e,t,n);case"utf8":case"utf-8":return EOe(this,e,t,n);case"ascii":case"latin1":case"binary":return vOe(this,e,t,n);case"base64":return xOe(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return SOe(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};Y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function AOe(r,e,t){return e===0&&t===r.length?OD.fromByteArray(r):OD.fromByteArray(r.slice(e,t))}function loe(r,e,t){t=Math.min(r.length,t);let n=[],i=e;for(;i239?4:o>223?3:o>191?2:1;if(i+a<=t){let c,u,l,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=r[i+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=r[i+1],u=r[i+2],(c&192)===128&&(u&192)===128&&(f=(o&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=r[i+1],u=r[i+2],l=r[i+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,a=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),i+=a}return TOe(n)}var ioe=4096;function TOe(r){let e=r.length;if(e<=ioe)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn)&&(t=n);let i="";for(let o=e;on&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),tt)throw new RangeError("Trying to access beyond buffer length")}Y.prototype.readUintLE=Y.prototype.readUIntLE=function(e,t,n){e=e>>>0,t=t>>>0,n||li(e,t,this.length);let i=this[e],o=1,s=0;for(;++s>>0,t=t>>>0,n||li(e,t,this.length);let i=this[e+--t],o=1;for(;t>0&&(o*=256);)i+=this[e+--t]*o;return i};Y.prototype.readUint8=Y.prototype.readUInt8=function(e,t){return e=e>>>0,t||li(e,1,this.length),this[e]};Y.prototype.readUint16LE=Y.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||li(e,2,this.length),this[e]|this[e+1]<<8};Y.prototype.readUint16BE=Y.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||li(e,2,this.length),this[e]<<8|this[e+1]};Y.prototype.readUint32LE=Y.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||li(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};Y.prototype.readUint32BE=Y.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||li(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};Y.prototype.readBigUInt64LE=Rd(function(e){e=e>>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,o=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(o)<>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],o=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<>>0,t=t>>>0,n||li(e,t,this.length);let i=this[e],o=1,s=0;for(;++s=o&&(i-=Math.pow(2,8*t)),i};Y.prototype.readIntBE=function(e,t,n){e=e>>>0,t=t>>>0,n||li(e,t,this.length);let i=t,o=1,s=this[e+--i];for(;i>0&&(o*=256);)s+=this[e+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*t)),s};Y.prototype.readInt8=function(e,t){return e=e>>>0,t||li(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};Y.prototype.readInt16LE=function(e,t){e=e>>>0,t||li(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};Y.prototype.readInt16BE=function(e,t){e=e>>>0,t||li(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};Y.prototype.readInt32LE=function(e,t){return e=e>>>0,t||li(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};Y.prototype.readInt32BE=function(e,t){return e=e>>>0,t||li(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};Y.prototype.readBigInt64LE=Rd(function(e){e=e>>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,t||li(e,4,this.length),g2.read(this,e,!0,23,4)};Y.prototype.readFloatBE=function(e,t){return e=e>>>0,t||li(e,4,this.length),g2.read(this,e,!1,23,4)};Y.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||li(e,8,this.length),g2.read(this,e,!0,52,8)};Y.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||li(e,8,this.length),g2.read(this,e,!1,52,8)};function vo(r,e,t,n,i,o){if(!Y.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||er.length)throw new RangeError("Index out of range")}Y.prototype.writeUintLE=Y.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t=t>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;vo(this,e,t,n,a,0)}let o=1,s=0;for(this[t]=e&255;++s>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;vo(this,e,t,n,a,0)}let o=n-1,s=1;for(this[t+o]=e&255;--o>=0&&(s*=256);)this[t+o]=e/s&255;return t+n};Y.prototype.writeUint8=Y.prototype.writeUInt8=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,1,255,0),this[t]=e&255,t+1};Y.prototype.writeUint16LE=Y.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};Y.prototype.writeUint16BE=Y.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};Y.prototype.writeUint32LE=Y.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};Y.prototype.writeUint32BE=Y.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function foe(r,e,t,n,i){goe(e,n,i,r,t,7);let o=Number(e&BigInt(4294967295));r[t++]=o,o=o>>8,r[t++]=o,o=o>>8,r[t++]=o,o=o>>8,r[t++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,r[t++]=s,t}function doe(r,e,t,n,i){goe(e,n,i,r,t,7);let o=Number(e&BigInt(4294967295));r[t+7]=o,o=o>>8,r[t+6]=o,o=o>>8,r[t+5]=o,o=o>>8,r[t+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return r[t+3]=s,s=s>>8,r[t+2]=s,s=s>>8,r[t+1]=s,s=s>>8,r[t]=s,t+8}Y.prototype.writeBigUInt64LE=Rd(function(e,t=0){return foe(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});Y.prototype.writeBigUInt64BE=Rd(function(e,t=0){return doe(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});Y.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,8*n-1);vo(this,e,t,n,c-1,-c)}let o=0,s=1,a=0;for(this[t]=e&255;++o>0)-a&255;return t+n};Y.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,8*n-1);vo(this,e,t,n,c-1,-c)}let o=n-1,s=1,a=0;for(this[t+o]=e&255;--o>=0&&(s*=256);)e<0&&a===0&&this[t+o+1]!==0&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+n};Y.prototype.writeInt8=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};Y.prototype.writeInt16LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};Y.prototype.writeInt16BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};Y.prototype.writeInt32LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};Y.prototype.writeInt32BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};Y.prototype.writeBigInt64LE=Rd(function(e,t=0){return foe(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});Y.prototype.writeBigInt64BE=Rd(function(e,t=0){return doe(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function hoe(r,e,t,n,i,o){if(t+n>r.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function poe(r,e,t,n,i){return e=+e,t=t>>>0,i||hoe(r,e,t,4,34028234663852886e22,-34028234663852886e22),g2.write(r,e,t,n,23,4),t+4}Y.prototype.writeFloatLE=function(e,t,n){return poe(this,e,t,!0,n)};Y.prototype.writeFloatBE=function(e,t,n){return poe(this,e,t,!1,n)};function moe(r,e,t,n,i){return e=+e,t=t>>>0,i||hoe(r,e,t,8,17976931348623157e292,-17976931348623157e292),g2.write(r,e,t,n,52,8),t+8}Y.prototype.writeDoubleLE=function(e,t,n){return moe(this,e,t,!0,n)};Y.prototype.writeDoubleBE=function(e,t,n){return moe(this,e,t,!1,n)};Y.prototype.copy=function(e,t,n,i){if(!Y.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let o;if(typeof e=="number")for(o=t;o2**32?i=ooe(String(t)):typeof t=="bigint"&&(i=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(i=ooe(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function ooe(r){let e="",t=r.length,n=r[0]==="-"?1:0;for(;t>=n+4;t-=3)e=`_${r.slice(t-3,t)}${e}`;return`${r.slice(0,t)}${e}`}function kOe(r,e,t){y2(e,"offset"),(r[e]===void 0||r[e+t]===void 0)&&r5(e,r.length-(t+1))}function goe(r,e,t,n,i,o){if(r>t||r3?e===0||e===BigInt(0)?a=`>= 0${s} and < 2${s} ** ${(o+1)*8}${s}`:a=`>= -(2${s} ** ${(o+1)*8-1}${s}) and < 2 ** ${(o+1)*8-1}${s}`:a=`>= ${e}${s} and <= ${t}${s}`,new m2.ERR_OUT_OF_RANGE("value",a,r)}kOe(n,i,o)}function y2(r,e){if(typeof r!="number")throw new m2.ERR_INVALID_ARG_TYPE(e,"number",r)}function r5(r,e,t){throw Math.floor(r)!==r?(y2(r,t),new m2.ERR_OUT_OF_RANGE(t||"offset","an integer",r)):e<0?new m2.ERR_BUFFER_OUT_OF_BOUNDS:new m2.ERR_OUT_OF_RANGE(t||"offset",`>= ${t?1:0} and <= ${e}`,r)}var NOe=/[^+/0-9A-Za-z-_]/g;function DOe(r){if(r=r.split("=")[0],r=r.trim().replace(NOe,""),r.length<2)return"";for(;r.length%4!==0;)r=r+"=";return r}function MD(r,e){e=e||1/0;let t,n=r.length,i=null,o=[];for(let s=0;s55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function OOe(r){let e=[];for(let t=0;t>8,i=t%256,o.push(i),o.push(n);return o}function yoe(r){return OD.toByteArray(DOe(r))}function M7(r,e,t,n){let i;for(i=0;i=e.length||i>=r.length);++i)e[i+t]=r[i];return i}function ou(r,e){return r instanceof e||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===e.name}function VD(r){return r!==r}var BOe=function(){let r="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let n=t*16;for(let i=0;i<16;++i)e[n+i]=r[t]+r[i]}return e}();function Rd(r){return typeof BigInt>"u"?MOe:r}function MOe(){throw new Error("BigInt not supported")}});var $D=P((JEt,woe)=>{"use strict";var KD=null;woe.exports=function(){return KD===null&&(KD={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),KD}});var GD=P(boe=>{"use strict";var qD=Za(),UOe=new Set(["buffer","view","utf8"]),HD=class{constructor(e){if(this.encode=e.encode||this.encode,this.decode=e.decode||this.decode,this.name=e.name||this.name,this.format=e.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!UOe.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");e.createViewTranscoder&&(this.createViewTranscoder=e.createViewTranscoder),e.createBufferTranscoder&&(this.createBufferTranscoder=e.createBufferTranscoder),e.createUTF8Transcoder&&(this.createUTF8Transcoder=e.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new qD(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new qD(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new qD(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};boe.Encoding=HD});var QD=P(U7=>{"use strict";var{Buffer:WD}=n5()||{},{Encoding:YD}=GD(),FOe=$D(),i5=class extends YD{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new o5({encode:this.encode,decode:e=>this.decode(WD.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},o5=class extends YD{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new i5({encode:e=>{let t=this.encode(e);return WD.from(t.buffer,t.byteOffset,t.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},jD=class extends YD{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new i5({encode:e=>WD.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:t}=FOe();return new o5({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(t.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};U7.BufferFormat=i5;U7.ViewFormat=o5;U7.UTF8Format=jD});var xoe=P(Lp=>{"use strict";var{Buffer:zi}=n5()||{Buffer:{isBuffer:()=>!1}},{textEncoder:Eoe,textDecoder:_oe}=$D()(),{BufferFormat:s5,ViewFormat:XD,UTF8Format:voe}=QD(),F7=r=>r;Lp.utf8=new voe({encode:function(r){return zi.isBuffer(r)?r.toString("utf8"):ArrayBuffer.isView(r)?_oe.decode(r):String(r)},decode:F7,name:"utf8",createViewTranscoder(){return new XD({encode:function(r){return ArrayBuffer.isView(r)?r:Eoe.encode(r)},decode:function(r){return _oe.decode(r)},name:`${this.name}+view`})},createBufferTranscoder(){return new s5({encode:function(r){return zi.isBuffer(r)?r:ArrayBuffer.isView(r)?zi.from(r.buffer,r.byteOffset,r.byteLength):zi.from(String(r),"utf8")},decode:function(r){return r.toString("utf8")},name:`${this.name}+buffer`})}});Lp.json=new voe({encode:JSON.stringify,decode:JSON.parse,name:"json"});Lp.buffer=new s5({encode:function(r){return zi.isBuffer(r)?r:ArrayBuffer.isView(r)?zi.from(r.buffer,r.byteOffset,r.byteLength):zi.from(String(r),"utf8")},decode:F7,name:"buffer",createViewTranscoder(){return new XD({encode:function(r){return ArrayBuffer.isView(r)?r:zi.from(String(r),"utf8")},decode:function(r){return zi.from(r.buffer,r.byteOffset,r.byteLength)},name:`${this.name}+view`})}});Lp.view=new XD({encode:function(r){return ArrayBuffer.isView(r)?r:Eoe.encode(r)},decode:F7,name:"view",createBufferTranscoder(){return new s5({encode:function(r){return zi.isBuffer(r)?r:ArrayBuffer.isView(r)?zi.from(r.buffer,r.byteOffset,r.byteLength):zi.from(String(r),"utf8")},decode:F7,name:`${this.name}+buffer`})}});Lp.hex=new s5({encode:function(r){return zi.isBuffer(r)?r:zi.from(String(r),"hex")},decode:function(r){return r.toString("hex")},name:"hex"});Lp.base64=new s5({encode:function(r){return zi.isBuffer(r)?r:zi.from(String(r),"base64")},decode:function(r){return r.toString("base64")},name:"base64"})});var Toe=P(Aoe=>{"use strict";var Soe=Za(),V7=xoe(),{Encoding:zOe}=GD(),{BufferFormat:VOe,ViewFormat:KOe,UTF8Format:$Oe}=QD(),a5=Symbol("formats"),z7=Symbol("encodings"),qOe=new Set(["buffer","view","utf8"]),ZD=class{constructor(e){if(Array.isArray(e)){if(!e.every(t=>qOe.has(t)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[z7]=new Map,this[a5]=new Set(e);for(let t in V7)try{this.encoding(t)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[z7].values()))}encoding(e){let t=this[z7].get(e);if(t===void 0){if(typeof e=="string"&&e!==""){if(t=WOe[e],!t)throw new Soe(`Encoding '${e}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof e!="object"||e===null)throw new TypeError("First argument 'encoding' must be a string or object");t=HOe(e)}let{name:n,format:i}=t;if(!this[a5].has(i))if(this[a5].has("view"))t=t.createViewTranscoder();else if(this[a5].has("buffer"))t=t.createBufferTranscoder();else if(this[a5].has("utf8"))t=t.createUTF8Transcoder();else throw new Soe(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,t.name,t.commonName])this[z7].set(o,t)}return t}};Aoe.Transcoder=ZD;function HOe(r){if(r instanceof zOe)return r;let e="type"in r&&typeof r.type=="string"?r.type:void 0,t=r.name||e||`anonymous-${YOe++}`;switch(GOe(r)){case"view":return new KOe({...r,name:t});case"utf8":return new $Oe({...r,name:t});case"buffer":return new VOe({...r,name:t});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function GOe(r){return"format"in r&&r.format!==void 0?r.format:"buffer"in r&&typeof r.buffer=="boolean"?r.buffer?"buffer":"utf8":"code"in r&&Number.isInteger(r.code)?"view":"buffer"}var jOe={binary:V7.buffer,"utf-8":V7.utf8},WOe={...V7,...jOe},YOe=0});var xi=P((i7t,JD)=>{"use strict";var b2=typeof Reflect=="object"?Reflect:null,Ioe=b2&&typeof b2.apply=="function"?b2.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},K7;b2&&typeof b2.ownKeys=="function"?K7=b2.ownKeys:Object.getOwnPropertySymbols?K7=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:K7=function(e){return Object.getOwnPropertyNames(e)};function QOe(r){console&&console.warn&&console.warn(r)}var Coe=Number.isNaN||function(e){return e!==e};function wr(){wr.init.call(this)}JD.exports=wr;JD.exports.once=eLe;wr.EventEmitter=wr;wr.prototype._events=void 0;wr.prototype._eventsCount=0;wr.prototype._maxListeners=void 0;var Roe=10;function $7(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(wr,"defaultMaxListeners",{enumerable:!0,get:function(){return Roe},set:function(r){if(typeof r!="number"||r<0||Coe(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");Roe=r}});wr.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};wr.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Coe(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Poe(r){return r._maxListeners===void 0?wr.defaultMaxListeners:r._maxListeners}wr.prototype.getMaxListeners=function(){return Poe(this)};wr.prototype.emit=function(e){for(var t=[],n=1;n0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(c===void 0)return!1;if(typeof c=="function")Ioe(c,this,t);else for(var u=c.length,l=Loe(c,u),n=0;n0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=s.length,QOe(a)}return r}wr.prototype.addListener=function(e,t){return koe(this,e,t,!1)};wr.prototype.on=wr.prototype.addListener;wr.prototype.prependListener=function(e,t){return koe(this,e,t,!0)};function XOe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Noe(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=XOe.bind(n);return i.listener=t,n.wrapFn=i,i}wr.prototype.once=function(e,t){return $7(t),this.on(e,Noe(this,e,t)),this};wr.prototype.prependOnceListener=function(e,t){return $7(t),this.prependListener(e,Noe(this,e,t)),this};wr.prototype.removeListener=function(e,t){var n,i,o,s,a;if($7(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():ZOe(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};wr.prototype.off=wr.prototype.removeListener;wr.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i=0;i--)this.removeListener(e,t[i]);return this};function Doe(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?JOe(i):Loe(i,i.length)}wr.prototype.listeners=function(e){return Doe(this,e,!0)};wr.prototype.rawListeners=function(e){return Doe(this,e,!1)};wr.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):Ooe.call(r,e)};wr.prototype.listenerCount=Ooe;function Ooe(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}wr.prototype.eventNames=function(){return this._eventsCount>0?K7(this._events):[]};function Loe(r,e){for(var t=new Array(e),n=0;n{Moe.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)});var c5=P(eO=>{"use strict";var Foe=Uoe();eO.fromCallback=function(r,e){if(r===void 0){var t=new Promise(function(n,i){r=function(o,s){o?i(o):n(s)}});r[e!==void 0?e:"promise"]=t}else if(typeof r!="function")throw new TypeError("Callback must be a function");return r};eO.fromPromise=function(r,e){if(e===void 0)return r;r.then(function(t){Foe(()=>e(null,t))}).catch(function(t){Foe(()=>e(t))})}});var q7=P(tO=>{"use strict";tO.getCallback=function(r,e){return typeof r=="function"?r:e};tO.getOptions=function(r,e){return typeof r=="object"&&r!==null?r:e!==void 0?e:{}}});var Od=P(W7=>{"use strict";var{fromCallback:rO}=c5(),us=Za(),{getOptions:nO,getCallback:zoe}=q7(),Bp=Symbol("promise"),_2=Symbol("callback"),su=Symbol("working"),Mp=Symbol("handleOne"),bl=Symbol("handleMany"),iO=Symbol("autoClose"),Nd=Symbol("finishWork"),au=Symbol("returnMany"),Cd=Symbol("closing"),u5=Symbol("handleClose"),H7=Symbol("closed"),l5=Symbol("closeCallbacks"),kd=Symbol("keyEncoding"),Up=Symbol("valueEncoding"),oO=Symbol("abortOnClose"),G7=Symbol("legacy"),sO=Symbol("keys"),aO=Symbol("values"),Pd=Symbol("limit"),Js=Symbol("count"),j7=Object.freeze({}),rLe=()=>{},Voe=!1,f5=class{constructor(e,t,n){if(typeof e!="object"||e===null){let i=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof t!="object"||t===null)throw new TypeError("The second argument must be an options object");this[H7]=!1,this[l5]=[],this[su]=!1,this[Cd]=!1,this[iO]=!1,this[_2]=null,this[Mp]=this[Mp].bind(this),this[bl]=this[bl].bind(this),this[u5]=this[u5].bind(this),this[kd]=t[kd],this[Up]=t[Up],this[G7]=n,this[Pd]=Number.isInteger(t.limit)&&t.limit>=0?t.limit:1/0,this[Js]=0,this[oO]=!!t.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[Js]}get limit(){return this[Pd]}next(e){let t;if(e===void 0)t=new Promise((n,i)=>{e=(o,s,a)=>{o?i(o):this[G7]?s===void 0&&a===void 0?n():n([s,a]):n(s)}});else if(typeof e!="function")throw new TypeError("Callback must be a function");return this[Cd]?this.nextTick(e,new us("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[su]?this.nextTick(e,new us("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[su]=!0,this[_2]=e,this[Js]>=this[Pd]?this.nextTick(this[Mp],null):this._next(this[Mp])),t}_next(e){this.nextTick(e)}nextv(e,t,n){return n=zoe(t,n),n=rO(n,Bp),t=nO(t,j7),Number.isInteger(e)?(this[Cd]?this.nextTick(n,new us("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[su]?this.nextTick(n,new us("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[Pd]<1/0&&(e=Math.min(e,this[Pd]-this[Js])),this[su]=!0,this[_2]=n,e<=0?this.nextTick(this[bl],null,[]):this._nextv(e,t,this[bl])),n[Bp]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Bp])}_nextv(e,t,n){let i=[],o=(s,a,c)=>{if(s)return n(s);if(this[G7]?a===void 0&&c===void 0:a===void 0)return n(null,i);i.push(this[G7]?[a,c]:a),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,t){return t=zoe(e,t),t=rO(t,Bp),e=nO(e,j7),this[Cd]?this.nextTick(t,new us("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[su]?this.nextTick(t,new us("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[su]=!0,this[_2]=t,this[iO]=!0,this[Js]>=this[Pd]?this.nextTick(this[bl],null,[]):this._all(e,this[bl])),t[Bp]}_all(e,t){let n=this[Js],i=[],o=()=>{let a=this[Pd]<1/0?Math.min(1e3,this[Pd]-n):1e3;a<=0?this.nextTick(t,null,i):this._nextv(a,j7,s)},s=(a,c)=>{a?t(a):c.length===0?t(null,i):(i.push.apply(i,c),n+=c.length,o())};o()}[Nd](){let e=this[_2];return this[oO]&&e===null?rLe:(this[su]=!1,this[_2]=null,this[Cd]&&this._close(this[u5]),e)}[au](e,t,n){this[iO]?this.close(e.bind(null,t,n)):e(t,n)}seek(e,t){if(t=nO(t,j7),!this[Cd]){if(this[su])throw new us("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(t.keyEncoding||this[kd]),i=n.format;t.keyEncoding!==i&&(t={...t,keyEncoding:i});let o=this.db.prefixKey(n.encode(e),i);this._seek(o,t)}}}_seek(e,t){throw new us("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=rO(e,Bp),this[H7]?this.nextTick(e):this[Cd]?this[l5].push(e):(this[Cd]=!0,this[l5].push(e),this[su]?this[oO]&&this[Nd]()(new us("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[u5])),e[Bp]}_close(e){this.nextTick(e)}[u5](){this[H7]=!0,this.db.detachResource(this);let e=this[l5];this[l5]=[];for(let t of e)t()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[H7]||await this.close()}}},E2=class extends f5{constructor(e,t){super(e,t,!0),this[sO]=t.keys!==!1,this[aO]=t.values!==!1}[Mp](e,t,n){let i=this[Nd]();if(e)return i(e);try{t=this[sO]&&t!==void 0?this[kd].decode(t):void 0,n=this[aO]&&n!==void 0?this[Up].decode(n):void 0}catch(o){return i(new Dd("entry",o))}t===void 0&&n===void 0||this[Js]++,i(null,t,n)}[bl](e,t){let n=this[Nd]();if(e)return this[au](n,e);try{for(let i of t){let o=i[0],s=i[1];i[0]=this[sO]&&o!==void 0?this[kd].decode(o):void 0,i[1]=this[aO]&&s!==void 0?this[Up].decode(s):void 0}}catch(i){return this[au](n,new Dd("entries",i))}this[Js]+=t.length,this[au](n,null,t)}end(e){return!Voe&&typeof console<"u"&&(Voe=!0,console.warn(new us("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(e)}},cO=class extends f5{constructor(e,t){super(e,t,!1)}[Mp](e,t){let n=this[Nd]();if(e)return n(e);try{t=t!==void 0?this[kd].decode(t):void 0}catch(i){return n(new Dd("key",i))}t!==void 0&&this[Js]++,n(null,t)}[bl](e,t){let n=this[Nd]();if(e)return this[au](n,e);try{for(let i=0;i{"use strict";var{AbstractKeyIterator:nLe,AbstractValueIterator:iLe}=Od(),Fp=Symbol("iterator"),d5=Symbol("callback"),v2=Symbol("handleOne"),zp=Symbol("handleMany"),h5=class extends nLe{constructor(e,t){super(e,t),this[Fp]=e.iterator({...t,keys:!0,values:!1}),this[v2]=this[v2].bind(this),this[zp]=this[zp].bind(this)}},Y7=class extends iLe{constructor(e,t){super(e,t),this[Fp]=e.iterator({...t,keys:!1,values:!0}),this[v2]=this[v2].bind(this),this[zp]=this[zp].bind(this)}};for(let r of[h5,Y7]){let e=r===h5,t=e?n=>n[0]:n=>n[1];r.prototype._next=function(n){this[d5]=n,this[Fp].next(this[v2])},r.prototype[v2]=function(n,i,o){let s=this[d5];n?s(n):s(null,e?i:o)},r.prototype._nextv=function(n,i,o){this[d5]=o,this[Fp].nextv(n,i,this[zp])},r.prototype._all=function(n,i){this[d5]=i,this[Fp].all(n,this[zp])},r.prototype[zp]=function(n,i){let o=this[d5];n?o(n):o(null,i.map(t))},r.prototype._seek=function(n,i){this[Fp].seek(n,i)},r.prototype._close=function(n){this[Fp].close(n)}}lO.DefaultKeyIterator=h5;lO.DefaultValueIterator=Y7});var $oe=P(tv=>{"use strict";var{AbstractIterator:oLe,AbstractKeyIterator:sLe,AbstractValueIterator:aLe}=Od(),fO=Za(),xo=Symbol("nut"),J7=Symbol("undefer"),ev=Symbol("factory"),Q7=class extends oLe{constructor(e,t){super(e,t),this[xo]=null,this[ev]=()=>e.iterator(t),this.db.defer(()=>this[J7]())}},X7=class extends sLe{constructor(e,t){super(e,t),this[xo]=null,this[ev]=()=>e.keys(t),this.db.defer(()=>this[J7]())}},Z7=class extends aLe{constructor(e,t){super(e,t),this[xo]=null,this[ev]=()=>e.values(t),this.db.defer(()=>this[J7]())}};for(let r of[Q7,X7,Z7])r.prototype[J7]=function(){this.db.status==="open"&&(this[xo]=this[ev]())},r.prototype._next=function(e){this[xo]!==null?this[xo].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new fO("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},r.prototype._nextv=function(e,t,n){this[xo]!==null?this[xo].nextv(e,t,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,t,n)):this.nextTick(n,new fO("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},r.prototype._all=function(e,t){this[xo]!==null?this[xo].all(t):this.db.status==="opening"?this.db.defer(()=>this._all(e,t)):this.nextTick(t,new fO("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},r.prototype._seek=function(e,t){this[xo]!==null?this[xo]._seek(e,t):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,t))},r.prototype._close=function(e){this[xo]!==null?this[xo].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};tv.DeferredIterator=Q7;tv.DeferredKeyIterator=X7;tv.DeferredValueIterator=Z7});var hO=P(Hoe=>{"use strict";var{fromCallback:qoe}=c5(),rv=Za(),{getCallback:cLe,getOptions:uLe}=q7(),nv=Symbol("promise"),ea=Symbol("status"),x2=Symbol("operations"),p5=Symbol("finishClose"),S2=Symbol("closeCallbacks"),dO=class{constructor(e){if(typeof e!="object"||e===null){let t=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${t}`)}this[x2]=[],this[S2]=[],this[ea]="open",this[p5]=this[p5].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[x2].length}put(e,t,n){if(this[ea]!=="open")throw new rv("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(e)||this.db._checkValue(t);if(i)throw i;let o=n&&n.sublevel!=null?n.sublevel:this.db,s=n,a=o.keyEncoding(n&&n.keyEncoding),c=o.valueEncoding(n&&n.valueEncoding),u=a.format;n={...n,keyEncoding:u,valueEncoding:c.format},o!==this.db&&(n.sublevel=null);let l=o.prefixKey(a.encode(e),u),f=c.encode(t);return this._put(l,f,n),this[x2].push({...s,type:"put",key:e,value:t}),this}_put(e,t,n){}del(e,t){if(this[ea]!=="open")throw new rv("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let n=this.db._checkKey(e);if(n)throw n;let i=t&&t.sublevel!=null?t.sublevel:this.db,o=t,s=i.keyEncoding(t&&t.keyEncoding),a=s.format;return t={...t,keyEncoding:a},i!==this.db&&(t.sublevel=null),this._del(i.prefixKey(s.encode(e),a),t),this[x2].push({...o,type:"del",key:e}),this}_del(e,t){}clear(){if(this[ea]!=="open")throw new rv("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[x2]=[],this}_clear(){}write(e,t){return t=cLe(e,t),t=qoe(t,nv),e=uLe(e),this[ea]!=="open"?this.nextTick(t,new rv("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(t):(this[ea]="writing",this._write(e,n=>{this[ea]="closing",this[S2].push(()=>t(n)),n||this.db.emit("batch",this[x2]),this._close(this[p5])})),t[nv]}_write(e,t){}close(e){return e=qoe(e,nv),this[ea]==="closing"?this[S2].push(e):this[ea]==="closed"?this.nextTick(e):(this[S2].push(e),this[ea]!=="writing"&&(this[ea]="closing",this._close(this[p5]))),e[nv]}_close(e){this.nextTick(e)}[p5](){this[ea]="closed",this.db.detachResource(this);let e=this[S2];this[S2]=[];for(let t of e)t()}};Hoe.AbstractChainedBatch=dO});var joe=P(Goe=>{"use strict";var{AbstractChainedBatch:lLe}=hO(),fLe=Za(),A2=Symbol("encoded"),pO=class extends lLe{constructor(e){super(e),this[A2]=[]}_put(e,t,n){this[A2].push({...n,type:"put",key:e,value:t})}_del(e,t){this[A2].push({...t,type:"del",key:e})}_clear(){this[A2]=[]}_write(e,t){this.db.status==="opening"?this.db.defer(()=>this._write(e,t)):this.db.status==="open"?this[A2].length===0?this.nextTick(t):this.db._batch(this[A2],e,t):this.nextTick(t,new fLe("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};Goe.DefaultChainedBatch=pO});var Qoe=P((h7t,Yoe)=>{"use strict";var Woe=Za(),dLe=Object.prototype.hasOwnProperty,hLe=new Set(["lt","lte","gt","gte"]);Yoe.exports=function(r,e){let t={};for(let n in r)if(dLe.call(r,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new Woe(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new Woe("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});hLe.has(n)?t[n]=e.encode(r[n]):t[n]=r[n]}return t.reverse=!!t.reverse,t.limit=Number.isInteger(t.limit)&&t.limit>=0?t.limit:-1,t}});var mO=P((p7t,Zoe)=>{var Xoe;Zoe.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):r=>(Xoe||(Xoe=Promise.resolve())).then(r).catch(e=>setTimeout(()=>{throw e},0))});var tse=P((m7t,ese)=>{"use strict";var Joe=mO();ese.exports=function(r,...e){e.length===0?Joe(r):Joe(()=>r(...e))}});var rse=P(iv=>{"use strict";var{AbstractIterator:pLe,AbstractKeyIterator:mLe,AbstractValueIterator:gLe}=Od(),T2=Symbol("unfix"),Ja=Symbol("iterator"),Vp=Symbol("handleOne"),Ld=Symbol("handleMany"),_l=Symbol("callback"),m5=class extends pLe{constructor(e,t,n,i){super(e,t),this[Ja]=n,this[T2]=i,this[Vp]=this[Vp].bind(this),this[Ld]=this[Ld].bind(this),this[_l]=null}[Vp](e,t,n){let i=this[_l];if(e)return i(e);t!==void 0&&(t=this[T2](t)),i(e,t,n)}[Ld](e,t){let n=this[_l];if(e)return n(e);for(let i of t){let o=i[0];o!==void 0&&(i[0]=this[T2](o))}n(e,t)}},g5=class extends mLe{constructor(e,t,n,i){super(e,t),this[Ja]=n,this[T2]=i,this[Vp]=this[Vp].bind(this),this[Ld]=this[Ld].bind(this),this[_l]=null}[Vp](e,t){let n=this[_l];if(e)return n(e);t!==void 0&&(t=this[T2](t)),n(e,t)}[Ld](e,t){let n=this[_l];if(e)return n(e);for(let i=0;i{"use strict";var gO=Za(),{Buffer:bO}=n5()||{},{AbstractSublevelIterator:yLe,AbstractSublevelKeyIterator:wLe,AbstractSublevelValueIterator:bLe}=rse(),El=Symbol("prefix"),nse=Symbol("upperBound"),w5=Symbol("prefixRange"),ls=Symbol("parent"),yO=Symbol("unfix"),ise=new TextEncoder,_Le={separator:"!"};ose.exports=function({AbstractLevel:r}){class e extends r{static defaults(n){if(typeof n=="string")throw new gO("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new gO("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?_Le:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:a,...c}=e.defaults(o);i=vLe(i,s);let u=s.charCodeAt(0)+1,l=n[ls]||n;if(!ise.encode(i).every(d=>d>u&&d<127))throw new gO(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(ELe(l,a),c);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[ls]=l,this[El]=new ov(f),this[nse]=new ov(h),this[yO]=new _O,this.nextTick=l.nextTick}prefixKey(n,i){if(i==="utf8")return this[El].utf8+n;if(n.byteLength===0)return this[El][i];if(i==="view"){let o=this[El].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[El].buffer;return bO.concat([o,n],o.byteLength+n.byteLength)}}[w5](n,i){n.gte!==void 0?n.gte=this.prefixKey(n.gte,i):n.gt!==void 0?n.gt=this.prefixKey(n.gt,i):n.gte=this[El][i],n.lte!==void 0?n.lte=this.prefixKey(n.lte,i):n.lt!==void 0?n.lt=this.prefixKey(n.lt,i):n.lte=this[nse][i]}get prefix(){return this[El].utf8}get db(){return this[ls]}_open(n,i){this[ls].open({passive:!0},i)}_put(n,i,o,s){this[ls].put(n,i,o,s)}_get(n,i,o){this[ls].get(n,i,o)}_getMany(n,i,o){this[ls].getMany(n,i,o)}_del(n,i,o){this[ls].del(n,i,o)}_batch(n,i,o){this[ls].batch(n,i,o)}_clear(n,i){this[w5](n,n.keyEncoding),this[ls].clear(n,i)}_iterator(n){this[w5](n,n.keyEncoding);let i=this[ls].iterator(n),o=this[yO].get(this[El].utf8.length,n.keyEncoding);return new yLe(this,n,i,o)}_keys(n){this[w5](n,n.keyEncoding);let i=this[ls].keys(n),o=this[yO].get(this[El].utf8.length,n.keyEncoding);return new wLe(this,n,i,o)}_values(n){this[w5](n,n.keyEncoding);let i=this[ls].values(n);return new bLe(this,n,i)}}return{AbstractSublevel:e}};var ELe=function(r,e){return{...r.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:wO(r,"utf8"),buffer:wO(r,"buffer"),view:wO(r,"view")}}},wO=function(r,e){return r.supports.encodings[e]?r.keyEncoding(e).name===e:!1},ov=class{constructor(e){this.utf8=e,this.view=ise.encode(e),this.buffer=bO?bO.from(this.view.buffer,0,this.view.byteLength):{}}},_O=class{constructor(){this.cache=new Map}get(e,t){let n=this.cache.get(t);return n===void 0&&(t==="view"?n=function(i,o){return o.subarray(i)}.bind(null,e):n=function(i,o){return o.slice(i)}.bind(null,e),this.cache.set(t,n)),n}},vLe=function(r,e){let t=0,n=r.length;for(;tt&&r[n-1]===e;)n--;return r.slice(t,n)}});var AO=P(SO=>{"use strict";var{supports:xLe}=Qie(),{Transcoder:SLe}=Toe(),{EventEmitter:ALe}=xi(),{fromCallback:Bd}=c5(),ec=Za(),{AbstractIterator:Kp}=Od(),{DefaultKeyIterator:TLe,DefaultValueIterator:ILe}=Koe(),{DeferredIterator:RLe,DeferredKeyIterator:CLe,DeferredValueIterator:PLe}=$oe(),{DefaultChainedBatch:ase}=joe(),{getCallback:$p,getOptions:Md}=q7(),sv=Qoe(),wt=Symbol("promise"),vl=Symbol("landed"),qp=Symbol("resources"),EO=Symbol("closeResources"),b5=Symbol("operations"),_5=Symbol("undefer"),av=Symbol("deferOpen"),cse=Symbol("options"),It=Symbol("status"),Hp=Symbol("defaultOptions"),I2=Symbol("transcoder"),cv=Symbol("keyEncoding"),vO=Symbol("valueEncoding"),kLe=()=>{},E5=class extends ALe{constructor(e,t){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");t=Md(t);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=t;this[qp]=new Set,this[b5]=[],this[av]=!0,this[cse]=s,this[It]="opening",this.supports=xLe(e,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:e.snapshots!==!1,permanence:e.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:e.encodings||{},events:Object.assign({},e.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[I2]=new SLe(NLe(this)),this[cv]=this[I2].encoding(n||"utf8"),this[vO]=this[I2].encoding(i||"utf8");for(let a of this[I2].encodings())this.supports.encodings[a.commonName]||(this.supports.encodings[a.commonName]=!0);this[Hp]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[cv].commonName,valueEncoding:this[vO].commonName}),key:Object.freeze({keyEncoding:this[cv].commonName})},this.nextTick(()=>{this[av]&&this.open({passive:!1},kLe)})}get status(){return this[It]}keyEncoding(e){return this[I2].encoding(e??this[cv])}valueEncoding(e){return this[I2].encoding(e??this[vO])}open(e,t){t=$p(e,t),t=Bd(t,wt),e={...this[cse],...Md(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[It]==="closing"||this[It]==="opening"?this.once(vl,i?()=>n(i):n):this[It]!=="open"?t(new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):t()};return e.passive?this[It]==="opening"?this.once(vl,n):this.nextTick(n):this[It]==="closed"||this[av]?(this[av]=!1,this[It]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[It]="closed",this[EO](()=>{this.emit(vl),n(i)}),this[_5]();return}this[It]="open",this[_5](),this.emit(vl),this[It]==="open"&&this.emit("open"),this[It]==="open"&&this.emit("ready"),n()})):this[It]==="open"?this.nextTick(n):this.once(vl,()=>this.open(e,t)),t[wt]}_open(e,t){this.nextTick(t)}close(e){e=Bd(e,wt);let t=n=>{this[It]==="opening"||this[It]==="closing"?this.once(vl,n?t(n):t):this[It]!=="closed"?e(new ec("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[It]==="open"){this[It]="closing",this.emit("closing");let n=i=>{this[It]="open",this[_5](),this.emit(vl),t(i)};this[EO](()=>{this._close(i=>{if(i)return n(i);this[It]="closed",this[_5](),this.emit(vl),this[It]==="closed"&&this.emit("closed"),t()})})}else this[It]==="closed"?this.nextTick(t):this.once(vl,()=>this.close(e));return e[wt]}[EO](e){if(this[qp].size===0)return this.nextTick(e);let t=this[qp].size,n=!0,i=()=>{--t===0&&(n?this.nextTick(e):e())};for(let o of this[qp])o.close(i);n=!1,this[qp].clear()}_close(e){this.nextTick(e)}get(e,t,n){if(n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].entry),this[It]==="opening")return this.defer(()=>this.get(e,t,n)),n[wt];if(R2(this,n))return n[wt];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[wt];let o=this.keyEncoding(t.keyEncoding),s=this.valueEncoding(t.valueEncoding),a=o.format,c=s.format;return(t.keyEncoding!==a||t.valueEncoding!==c)&&(t=Object.assign({},t,{keyEncoding:a,valueEncoding:c})),this._get(this.prefixKey(o.encode(e),a),t,(u,l)=>{if(u)return(u.code==="LEVEL_NOT_FOUND"||u.notFound||/NotFound/i.test(u))&&(u.code||(u.code="LEVEL_NOT_FOUND"),u.notFound||(u.notFound=!0),u.status||(u.status=404)),n(u);try{l=s.decode(l)}catch(f){return n(new ec("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,l)}),n[wt]}_get(e,t,n){this.nextTick(n,new Error("NotFound"))}getMany(e,t,n){if(n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].entry),this[It]==="opening")return this.defer(()=>this.getMany(e,t,n)),n[wt];if(R2(this,n))return n[wt];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[wt];if(e.length===0)return this.nextTick(n,null,[]),n[wt];let i=this.keyEncoding(t.keyEncoding),o=this.valueEncoding(t.valueEncoding),s=i.format,a=o.format;(t.keyEncoding!==s||t.valueEncoding!==a)&&(t=Object.assign({},t,{keyEncoding:s,valueEncoding:a}));let c=new Array(e.length);for(let u=0;u{if(u)return n(u);try{for(let f=0;fthis.put(e,t,n,i)),i[wt];if(R2(this,i))return i[wt];let o=this._checkKey(e)||this._checkValue(t);if(o)return this.nextTick(i,o),i[wt];let s=this.keyEncoding(n.keyEncoding),a=this.valueEncoding(n.valueEncoding),c=s.format,u=a.format;(n.keyEncoding!==c||n.valueEncoding!==u)&&(n=Object.assign({},n,{keyEncoding:c,valueEncoding:u}));let l=this.prefixKey(s.encode(e),c),f=a.encode(t);return this._put(l,f,n,h=>{if(h)return i(h);this.emit("put",e,t),i()}),i[wt]}_put(e,t,n,i){this.nextTick(i)}del(e,t,n){if(n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].key),this[It]==="opening")return this.defer(()=>this.del(e,t,n)),n[wt];if(R2(this,n))return n[wt];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[wt];let o=this.keyEncoding(t.keyEncoding),s=o.format;return t.keyEncoding!==s&&(t=Object.assign({},t,{keyEncoding:s})),this._del(this.prefixKey(o.encode(e),s),t,a=>{if(a)return n(a);this.emit("del",e),n()}),n[wt]}_del(e,t,n){this.nextTick(n)}batch(e,t,n){if(!arguments.length){if(this[It]==="opening")return new ase(this);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].empty),this[It]==="opening")return this.defer(()=>this.batch(e,t,n)),n[wt];if(R2(this,n))return n[wt];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[wt];if(e.length===0)return this.nextTick(n),n[wt];let i=new Array(e.length),{keyEncoding:o,valueEncoding:s,...a}=t;for(let c=0;c{if(c)return n(c);this.emit("batch",e),n()}),n[wt]}_batch(e,t,n){this.nextTick(n)}sublevel(e,t){return this._sublevel(e,xO.defaults(t))}_sublevel(e,t){return new xO(this,e,t)}prefixKey(e,t){return e}clear(e,t){if(t=$p(e,t),t=Bd(t,wt),e=Md(e,this[Hp].empty),this[It]==="opening")return this.defer(()=>this.clear(e,t)),t[wt];if(R2(this,t))return t[wt];let n=e,i=this.keyEncoding(e.keyEncoding);return e=sv(e,i),e.keyEncoding=i.format,e.limit===0?this.nextTick(t):this._clear(e,o=>{if(o)return t(o);this.emit("clear",n),t()}),t[wt]}_clear(e,t){this.nextTick(t)}iterator(e){let t=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sv(e,t),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Kp.keyEncoding]=t,e[Kp.valueEncoding]=n,e.keyEncoding=t.format,e.valueEncoding=n.format,this[It]==="opening")return new RLe(this,e);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new Kp(this,e)}keys(e){let t=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sv(e,t),e[Kp.keyEncoding]=t,e[Kp.valueEncoding]=n,e.keyEncoding=t.format,e.valueEncoding=n.format,this[It]==="opening")return new CLe(this,e);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new TLe(this,e)}values(e){let t=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sv(e,t),e[Kp.keyEncoding]=t,e[Kp.valueEncoding]=n,e.keyEncoding=t.format,e.valueEncoding=n.format,this[It]==="opening")return new PLe(this,e);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new ILe(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[b5].push(e)}[_5](){if(this[b5].length===0)return;let e=this[b5];this[b5]=[];for(let t of e)t()}attachResource(e){if(typeof e!="object"||e===null||typeof e.close!="function")throw new TypeError("The first argument must be a resource object");this[qp].add(e)}detachResource(e){this[qp].delete(e)}_chainedBatch(){return new ase(this)}_checkKey(e){if(e==null)return new ec("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new ec("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};E5.prototype.nextTick=tse();var{AbstractSublevel:xO}=sse()({AbstractLevel:E5});SO.AbstractLevel=E5;SO.AbstractSublevel=xO;var R2=function(r,e){return r[It]!=="open"?(r.nextTick(e,new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},NLe=function(r){return Object.keys(r.supports.encodings).filter(e=>!!r.supports.encodings[e])}});var TO=P(Gp=>{"use strict";Gp.AbstractLevel=AO().AbstractLevel;Gp.AbstractSublevel=AO().AbstractSublevel;Gp.AbstractIterator=Od().AbstractIterator;Gp.AbstractKeyIterator=Od().AbstractKeyIterator;Gp.AbstractValueIterator=Od().AbstractValueIterator;Gp.AbstractChainedBatch=hO().AbstractChainedBatch});var lse=P((_7t,use)=>{use.exports=OLe;var DLe=mO();function OLe(r,e,t){if(typeof e!="number")throw new Error("second argument must be a Number");let n,i,o,s,a,c=!0,u;Array.isArray(r)?(n=[],o=i=r.length):(s=Object.keys(r),n={},o=i=s.length);function l(h){function d(){t&&t(h,n),t=null}c?DLe(d):d()}function f(h,d,p){if(n[h]=p,d&&(a=!0),--o===0||d)l(d);else if(!a&&u{"use strict";fse.exports=function(e){let t=e.gte!==void 0?e.gte:e.gt!==void 0?e.gt:void 0,n=e.lte!==void 0?e.lte:e.lt!==void 0?e.lt:void 0,i=e.gte===void 0,o=e.lte===void 0;return t!==void 0&&n!==void 0?IDBKeyRange.bound(t,n,i,o):t!==void 0?IDBKeyRange.lowerBound(t,i):n!==void 0?IDBKeyRange.upperBound(n,o):null}});var RO=P((v7t,dse)=>{"use strict";var LLe=new TextEncoder;dse.exports=function(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):LLe.encode(r)}});var yse=P(gse=>{"use strict";var{AbstractIterator:BLe}=TO(),hse=IO(),uv=RO(),cu=Symbol("cache"),xl=Symbol("finished"),fs=Symbol("options"),Sl=Symbol("currentOptions"),jp=Symbol("position"),CO=Symbol("location"),C2=Symbol("first"),pse={},PO=class extends BLe{constructor(e,t,n){super(e,n),this[cu]=[],this[xl]=this.limit===0,this[fs]=n,this[Sl]={...n},this[jp]=void 0,this[CO]=t,this[C2]=!0}_nextv(e,t,n){if(this[C2]=!1,this[xl])return this.nextTick(n,null,[]);if(this[cu].length>0)return e=Math.min(e,this[cu].length),this.nextTick(n,null,this[cu].splice(0,e));this[jp]!==void 0&&(this[fs].reverse?(this[Sl].lt=this[jp],this[Sl].lte=void 0):(this[Sl].gt=this[jp],this[Sl].gte=void 0));let i;try{i=hse(this[Sl])}catch{return this[xl]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[CO]],"readonly"),s=o.objectStore(this[CO]),a=[];if(this[fs].reverse){let c=!this[fs].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[c](i,"prev").onsuccess=u=>{let l=u.target.result;if(l){let{key:f,value:h}=l;this[jp]=f,a.push([this[fs].keys&&f!==void 0?uv(f):void 0,this[fs].values&&h!==void 0?uv(h):void 0]),a.length{if(c===void 0||u===void 0)return;let f=Math.max(c.length,u.length);f===0||e===1/0?this[xl]=!0:this[jp]=c[f-1],a.length=f;for(let h=0;h{c=f.target.result,l()}:(c=[],this.nextTick(l)),this[fs].values?s.getAll(i,e<1/0?e:void 0).onsuccess=f=>{u=f.target.result,l()}:(u=[],this.nextTick(l))}o.onabort=()=>{n(o.error||new Error("aborted by user")),n=null},o.oncomplete=()=>{n(null,a),n=null}}_next(e){if(this[cu].length>0){let[t,n]=this[cu].shift();this.nextTick(e,null,t,n)}else if(this[xl])this.nextTick(e);else{let t=Math.min(100,this.limit-this.count);this[C2]&&(this[C2]=!1,t=1),this._nextv(t,pse,(n,i)=>{if(n)return e(n);this[cu]=i,this._next(e)})}}_all(e,t){this[C2]=!1;let n=this[cu].splice(0,this[cu].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(t,null,n);this._nextv(i,pse,(o,s)=>{if(o)return t(o);n.length>0&&(s=n.concat(s)),t(null,s)})}_seek(e,t){this[C2]=!0,this[cu]=[],this[xl]=!1,this[jp]=void 0,this[Sl]={...this[fs]};let n;try{n=hse(this[fs])}catch{this[xl]=!0;return}n!==null&&!n.includes(e)?this[xl]=!0:this[fs].reverse?this[Sl].lte=e:this[Sl].gte=e}};gse.Iterator=PO;function mse(r){typeof r.commit=="function"&&r.commit()}});var bse=P((S7t,wse)=>{"use strict";wse.exports=function(e,t,n,i,o){if(i.limit===0)return e.nextTick(o);let s=e.db.transaction([t],"readwrite"),a=s.objectStore(t),c=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let u=a.openKeyCursor?"openKeyCursor":"openCursor",l=i.reverse?"prev":"next";a[u](n,l).onsuccess=function(f){let h=f.target.result;h&&(a.delete(h.key).onsuccess=function(){(i.limit<=0||++c{"use strict";var{AbstractLevel:MLe}=TO(),_se=Za(),ULe=lse(),{fromCallback:FLe}=c5(),{Iterator:zLe}=yse(),Ese=RO(),VLe=bse(),KLe=IO(),xse="level-js-",v5=Symbol("idb"),kO=Symbol("namePrefix"),Al=Symbol("location"),NO=Symbol("version"),Wp=Symbol("store"),x5=Symbol("onComplete"),vse=Symbol("promise"),lv=class extends MLe{constructor(e,t,n){if(typeof t=="function"||typeof n=="function")throw new _se("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=t||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof e!="string")throw new Error("constructor requires a location string argument");this[Al]=e,this[kO]=i??xse,this[NO]=parseInt(o||1,10),this[v5]=null}get location(){return this[Al]}get namePrefix(){return this[kO]}get version(){return this[NO]}get db(){return this[v5]}get type(){return"browser-level"}_open(e,t){let n=indexedDB.open(this[kO]+this[Al],this[NO]);n.onerror=function(){t(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[v5]=n.result,t()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[Al])||o.createObjectStore(this[Al])}}[Wp](e){return this[v5].transaction([this[Al]],e).objectStore(this[Al])}[x5](e,t){let n=e.transaction;n.onabort=function(){t(n.error||new Error("aborted by user"))},n.oncomplete=function(){t(null,e.result)}}_get(e,t,n){let i=this[Wp]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[x5](o,function(s,a){if(s)return n(s);if(a===void 0)return n(new _se("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,Ese(a))})}_getMany(e,t,n){let i=this[Wp]("readonly"),o=e.map(s=>a=>{let c;try{c=i.get(s)}catch(u){return a(u)}c.onsuccess=()=>{let u=c.result;a(null,u===void 0?u:Ese(u))},c.onerror=u=>{u.stopPropagation(),a(c.error)}});ULe(o,16,n)}_del(e,t,n){let i=this[Wp]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[x5](o,n)}_put(e,t,n,i){let o=this[Wp]("readwrite"),s;try{s=o.put(t,e)}catch(a){return this.nextTick(i,a)}this[x5](s,i)}_iterator(e){return new zLe(this,this[Al],e)}_batch(e,t,n){let i=this[Wp]("readwrite"),o=i.transaction,s=0,a;o.onabort=function(){n(a||o.error||new Error("aborted by user"))},o.oncomplete=function(){n()};function c(){let u=e[s++],l=u.key,f;try{f=u.type==="del"?i.delete(l):i.put(u.value,l)}catch(h){a=h,o.abort();return}s=0)return VLe(this,this[Al],n,e,t);try{let o=this[Wp]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(t,o)}this[x5](i,t)}_close(e){this[v5].close(),this.nextTick(e)}};lv.destroy=function(r,e,t){typeof e=="function"&&(t=e,e=xse),t=FLe(t,vse);let n=indexedDB.deleteDatabase(e+r);return n.onsuccess=function(){t()},n.onerror=function(i){t(i)},t[vse]};Sse.BrowserLevel=lv});var Ise=P(Tse=>{Tse.Level=Ase().BrowserLevel});var Mse=P((Kvt,Bse)=>{"use strict";Bse.exports=fi;var T5=Kd();function fi(r,e){this.lo=r>>>0,this.hi=e>>>0}var Qp=fi.zero=new fi(0,0);Qp.toNumber=function(){return 0};Qp.zzEncode=Qp.zzDecode=function(){return this};Qp.length=function(){return 1};var iBe=fi.zeroHash="\0\0\0\0\0\0\0\0";fi.fromNumber=function(e){if(e===0)return Qp;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new fi(n,i)};fi.from=function(e){if(typeof e=="number")return fi.fromNumber(e);if(T5.isString(e))if(T5.Long)e=T5.Long.fromString(e);else return fi.fromNumber(parseInt(e,10));return e.low||e.high?new fi(e.low>>>0,e.high>>>0):Qp};fi.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};fi.prototype.toLong=function(e){return T5.Long?new T5.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Vd=String.prototype.charCodeAt;fi.fromHash=function(e){return e===iBe?Qp:new fi((Vd.call(e,0)|Vd.call(e,1)<<8|Vd.call(e,2)<<16|Vd.call(e,3)<<24)>>>0,(Vd.call(e,4)|Vd.call(e,5)<<8|Vd.call(e,6)<<16|Vd.call(e,7)<<24)>>>0)};fi.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};fi.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};fi.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};fi.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var Kd=P(UO=>{"use strict";var Ue=UO;Ue.asPromise=N6();Ue.base64=O6();Ue.EventEmitter=B6();Ue.float=M6();Ue.inquire=U6();Ue.utf8=F6();Ue.pool=z6();Ue.LongBits=Mse();Ue.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Ue.global=Ue.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||UO;Ue.emptyArray=Object.freeze?Object.freeze([]):[];Ue.emptyObject=Object.freeze?Object.freeze({}):{};Ue.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Ue.isString=function(e){return typeof e=="string"||e instanceof String};Ue.isObject=function(e){return e&&typeof e=="object"};Ue.isset=Ue.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Ue.Buffer=function(){try{var r=Ue.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Ue._Buffer_from=null;Ue._Buffer_allocUnsafe=null;Ue.newBuffer=function(e){return typeof e=="number"?Ue.Buffer?Ue._Buffer_allocUnsafe(e):new Ue.Array(e):Ue.Buffer?Ue._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Ue.Array=typeof Uint8Array<"u"?Uint8Array:Array;Ue.Long=Ue.global.dcodeIO&&Ue.global.dcodeIO.Long||Ue.global.Long||Ue.inquire("long");Ue.key2Re=/^true|false|0|1$/;Ue.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Ue.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Ue.longToHash=function(e){return e?Ue.LongBits.from(e).toHash():Ue.LongBits.zeroHash};Ue.longFromHash=function(e,t){var n=Ue.LongBits.fromHash(e);return Ue.Long?Ue.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Use(r,e,t){for(var n=Object.keys(e),i=0;i-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Ue.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";$se.exports=Xt;var ta=Kd(),FO,mv=ta.LongBits,zse=ta.base64,Vse=ta.utf8;function I5(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function VO(){}function oBe(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Xt(){this.len=0,this.head=new I5(VO,0,0),this.tail=this.head,this.states=null}var Kse=function(){return ta.Buffer?function(){return(Xt.create=function(){return new FO})()}:function(){return new Xt}};Xt.create=Kse();Xt.alloc=function(e){return new ta.Array(e)};ta.Array!==Array&&(Xt.alloc=ta.pool(Xt.alloc,ta.Array.prototype.subarray));Xt.prototype._push=function(e,t,n){return this.tail=this.tail.next=new I5(e,t,n),this.len+=t,this};function KO(r,e,t){e[t]=r&255}function sBe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function $O(r,e){this.len=r,this.next=void 0,this.val=e}$O.prototype=Object.create(I5.prototype);$O.prototype.fn=sBe;Xt.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new $O((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Xt.prototype.int32=function(e){return e<0?this._push(qO,10,mv.fromNumber(e)):this.uint32(e)};Xt.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function qO(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Xt.prototype.uint64=function(e){var t=mv.from(e);return this._push(qO,t.length(),t)};Xt.prototype.int64=Xt.prototype.uint64;Xt.prototype.sint64=function(e){var t=mv.from(e).zzEncode();return this._push(qO,t.length(),t)};Xt.prototype.bool=function(e){return this._push(KO,1,e?1:0)};function zO(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Xt.prototype.fixed32=function(e){return this._push(zO,4,e>>>0)};Xt.prototype.sfixed32=Xt.prototype.fixed32;Xt.prototype.fixed64=function(e){var t=mv.from(e);return this._push(zO,4,t.lo)._push(zO,4,t.hi)};Xt.prototype.sfixed64=Xt.prototype.fixed64;Xt.prototype.float=function(e){return this._push(ta.float.writeFloatLE,4,e)};Xt.prototype.double=function(e){return this._push(ta.float.writeDoubleLE,8,e)};var aBe=ta.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(KO,1,0);if(ta.isString(e)){var n=Xt.alloc(t=zse.length(e));zse.decode(e,n,0),e=n}return this.uint32(t)._push(aBe,t,e)};Xt.prototype.string=function(e){var t=Vse.length(e);return t?this.uint32(t)._push(Vse.write,t,e):this._push(KO,1,0)};Xt.prototype.fork=function(){return this.states=new oBe(this),this.head=this.tail=new I5(VO,0,0),this.len=0,this};Xt.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 I5(VO,0,0),this.len=0),this};Xt.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Xt.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Xt._configure=function(r){FO=r,Xt.create=Kse(),FO._configure()}});var Gse=P((Hvt,Hse)=>{"use strict";Hse.exports=fu;var qse=HO();(fu.prototype=Object.create(qse.prototype)).constructor=fu;var $d=Kd();function fu(){qse.call(this)}fu._configure=function(){fu.alloc=$d._Buffer_allocUnsafe,fu.writeBytesBuffer=$d.Buffer&&$d.Buffer.prototype instanceof Uint8Array&&$d.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(fu.writeBytesBuffer,t,e),this};function cBe(r,e,t){r.length<40?$d.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}fu.prototype.string=function(e){var t=$d.Buffer.byteLength(e);return this.uint32(t),t&&this._push(cBe,t,e),this};fu._configure()});var WO=P((Gvt,Xse)=>{"use strict";Xse.exports=En;var du=Kd(),jO,Yse=du.LongBits,uBe=du.utf8;function tc(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function En(r){this.buf=r,this.pos=0,this.len=r.length}var jse=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new En(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new En(e);throw Error("illegal buffer")},Qse=function(){return du.Buffer?function(t){return(En.create=function(i){return du.Buffer.isBuffer(i)?new jO(i):jse(i)})(t)}:jse};En.create=Qse();En.prototype._slice=du.Array.prototype.subarray||du.Array.prototype.slice;En.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,tc(this,10);return e}}();En.prototype.int32=function(){return this.uint32()|0};En.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function GO(){var r=new Yse(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw tc(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw tc(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}En.prototype.bool=function(){return this.uint32()!==0};function gv(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}En.prototype.fixed32=function(){if(this.pos+4>this.len)throw tc(this,4);return gv(this.buf,this.pos+=4)};En.prototype.sfixed32=function(){if(this.pos+4>this.len)throw tc(this,4);return gv(this.buf,this.pos+=4)|0};function Wse(){if(this.pos+8>this.len)throw tc(this,8);return new Yse(gv(this.buf,this.pos+=4),gv(this.buf,this.pos+=4))}En.prototype.float=function(){if(this.pos+4>this.len)throw tc(this,4);var e=du.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};En.prototype.double=function(){if(this.pos+8>this.len)throw tc(this,4);var e=du.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};En.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw tc(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};En.prototype.string=function(){var e=this.bytes();return uBe.read(e,0,e.length)};En.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw tc(this,e);this.pos+=e}else do if(this.pos>=this.len)throw tc(this);while(this.buf[this.pos++]&128);return this};En.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};En._configure=function(r){jO=r,En.create=Qse(),jO._configure();var e=du.Long?"toLong":"toNumber";du.merge(En.prototype,{int64:function(){return GO.call(this)[e](!1)},uint64:function(){return GO.call(this)[e](!0)},sint64:function(){return GO.call(this).zzDecode()[e](!1)},fixed64:function(){return Wse.call(this)[e](!0)},sfixed64:function(){return Wse.call(this)[e](!1)}})}});var tae=P((jvt,eae)=>{"use strict";eae.exports=Xp;var Jse=WO();(Xp.prototype=Object.create(Jse.prototype)).constructor=Xp;var Zse=Kd();function Xp(r){Jse.call(this,r)}Xp._configure=function(){Zse.Buffer&&(Xp.prototype._slice=Zse.Buffer.prototype.slice)};Xp.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))};Xp._configure()});var nae=P((Wvt,rae)=>{"use strict";rae.exports=R5;var YO=Kd();(R5.prototype=Object.create(YO.EventEmitter.prototype)).constructor=R5;function R5(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");YO.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}R5.prototype.rpcCall=function r(e,t,n,i,o){if(!i)throw TypeError("request must be specified");var s=this;if(!o)return YO.asPromise(r,s,e,t,n,i);if(!s.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return s.rpcImpl(e,t[s.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return s.emit("error",c,e),o(c);if(u===null){s.end(!0);return}if(!(u instanceof n))try{u=n[s.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return s.emit("error",l,e),o(l)}return s.emit("data",u,e),o(null,u)})}catch(a){s.emit("error",a,e),setTimeout(function(){o(a)},0);return}};R5.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var oae=P(iae=>{"use strict";var lBe=iae;lBe.Service=nae()});var aae=P((Qvt,sae)=>{"use strict";sae.exports={}});var lae=P(uae=>{"use strict";var So=uae;So.build="minimal";So.Writer=HO();So.BufferWriter=Gse();So.Reader=WO();So.BufferReader=tae();So.util=Kd();So.rpc=oae();So.roots=aae();So.configure=cae;function cae(){So.util._configure(),So.Writer._configure(So.BufferWriter),So.Reader._configure(So.BufferReader)}cae()});var QO=P((Zvt,fae)=>{"use strict";fae.exports=lae()});var hae=P((dae,C5)=>{(function(r,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof k0=="function"&&typeof C5=="object"&&C5&&C5.exports&&(C5.exports=e(QO()))})(dae,function(r){"use strict";var e=r.Reader,t=r.Writer,n=r.util,i=r.roots.default||(r.roots.default={});return i.RPC=function(){function o(a){if(this.subscriptions=[],this.messages=[],a)for(var c=Object.keys(a),u=0;u>>3){case 1:f.subscriptions&&f.subscriptions.length||(f.subscriptions=[]),f.subscriptions.push(i.RPC.SubOpts.decode(c,c.uint32()));break;case 2:f.messages&&f.messages.length||(f.messages=[]),f.messages.push(i.RPC.Message.decode(c,c.uint32()));break;case 3:f.control=i.RPC.ControlMessage.decode(c,c.uint32());break;default:c.skipType(h&7);break}}return f},o.fromObject=function(c){if(c instanceof i.RPC)return c;var u=new i.RPC;if(c.subscriptions){if(!Array.isArray(c.subscriptions))throw TypeError(".RPC.subscriptions: array expected");u.subscriptions=[];for(var l=0;l>>3){case 1:d.subscribe=l.bool();break;case 2:d.topic=l.string();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.SubOpts)return l;var f=new i.RPC.SubOpts;return l.subscribe!=null&&(f.subscribe=!!l.subscribe),l.topic!=null&&(f.topic=String(l.topic)),f},a.toObject=function(l,f){f||(f={});var h={};return l.subscribe!=null&&l.hasOwnProperty("subscribe")&&(h.subscribe=l.subscribe,f.oneofs&&(h._subscribe="subscribe")),l.topic!=null&&l.hasOwnProperty("topic")&&(h.topic=l.topic,f.oneofs&&(h._topic="topic")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.Message=function(){function a(u){if(u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.from=l.bytes();break;case 2:d.data=l.bytes();break;case 3:d.seqno=l.bytes();break;case 4:d.topic=l.string();break;case 5:d.signature=l.bytes();break;case 6:d.key=l.bytes();break;default:l.skipType(p&7);break}}if(!d.hasOwnProperty("topic"))throw n.ProtocolError("missing required 'topic'",{instance:d});return d},a.fromObject=function(l){if(l instanceof i.RPC.Message)return l;var f=new i.RPC.Message;return l.from!=null&&(typeof l.from=="string"?n.base64.decode(l.from,f.from=n.newBuffer(n.base64.length(l.from)),0):l.from.length&&(f.from=l.from)),l.data!=null&&(typeof l.data=="string"?n.base64.decode(l.data,f.data=n.newBuffer(n.base64.length(l.data)),0):l.data.length&&(f.data=l.data)),l.seqno!=null&&(typeof l.seqno=="string"?n.base64.decode(l.seqno,f.seqno=n.newBuffer(n.base64.length(l.seqno)),0):l.seqno.length&&(f.seqno=l.seqno)),l.topic!=null&&(f.topic=String(l.topic)),l.signature!=null&&(typeof l.signature=="string"?n.base64.decode(l.signature,f.signature=n.newBuffer(n.base64.length(l.signature)),0):l.signature.length&&(f.signature=l.signature)),l.key!=null&&(typeof l.key=="string"?n.base64.decode(l.key,f.key=n.newBuffer(n.base64.length(l.key)),0):l.key.length&&(f.key=l.key)),f},a.toObject=function(l,f){f||(f={});var h={};return f.defaults&&(h.topic=""),l.from!=null&&l.hasOwnProperty("from")&&(h.from=f.bytes===String?n.base64.encode(l.from,0,l.from.length):f.bytes===Array?Array.prototype.slice.call(l.from):l.from,f.oneofs&&(h._from="from")),l.data!=null&&l.hasOwnProperty("data")&&(h.data=f.bytes===String?n.base64.encode(l.data,0,l.data.length):f.bytes===Array?Array.prototype.slice.call(l.data):l.data,f.oneofs&&(h._data="data")),l.seqno!=null&&l.hasOwnProperty("seqno")&&(h.seqno=f.bytes===String?n.base64.encode(l.seqno,0,l.seqno.length):f.bytes===Array?Array.prototype.slice.call(l.seqno):l.seqno,f.oneofs&&(h._seqno="seqno")),l.topic!=null&&l.hasOwnProperty("topic")&&(h.topic=l.topic),l.signature!=null&&l.hasOwnProperty("signature")&&(h.signature=f.bytes===String?n.base64.encode(l.signature,0,l.signature.length):f.bytes===Array?Array.prototype.slice.call(l.signature):l.signature,f.oneofs&&(h._signature="signature")),l.key!=null&&l.hasOwnProperty("key")&&(h.key=f.bytes===String?n.base64.encode(l.key,0,l.key.length):f.bytes===Array?Array.prototype.slice.call(l.key):l.key,f.oneofs&&(h._key="key")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.ControlMessage=function(){function a(c){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],c)for(var u=Object.keys(c),l=0;l>>3){case 1:h.ihave&&h.ihave.length||(h.ihave=[]),h.ihave.push(i.RPC.ControlIHave.decode(u,u.uint32()));break;case 2:h.iwant&&h.iwant.length||(h.iwant=[]),h.iwant.push(i.RPC.ControlIWant.decode(u,u.uint32()));break;case 3:h.graft&&h.graft.length||(h.graft=[]),h.graft.push(i.RPC.ControlGraft.decode(u,u.uint32()));break;case 4:h.prune&&h.prune.length||(h.prune=[]),h.prune.push(i.RPC.ControlPrune.decode(u,u.uint32()));break;default:u.skipType(d&7);break}}return h},a.fromObject=function(u){if(u instanceof i.RPC.ControlMessage)return u;var l=new i.RPC.ControlMessage;if(u.ihave){if(!Array.isArray(u.ihave))throw TypeError(".RPC.ControlMessage.ihave: array expected");l.ihave=[];for(var f=0;f>>3){case 1:d.topicID=l.string();break;case 2:d.messageIDs&&d.messageIDs.length||(d.messageIDs=[]),d.messageIDs.push(l.bytes());break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlIHave)return l;var f=new i.RPC.ControlIHave;if(l.topicID!=null&&(f.topicID=String(l.topicID)),l.messageIDs){if(!Array.isArray(l.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");f.messageIDs=[];for(var h=0;h>>3){case 1:h.messageIDs&&h.messageIDs.length||(h.messageIDs=[]),h.messageIDs.push(u.bytes());break;default:u.skipType(d&7);break}}return h},a.fromObject=function(u){if(u instanceof i.RPC.ControlIWant)return u;var l=new i.RPC.ControlIWant;if(u.messageIDs){if(!Array.isArray(u.messageIDs))throw TypeError(".RPC.ControlIWant.messageIDs: array expected");l.messageIDs=[];for(var f=0;f>>3){case 1:d.topicID=l.string();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlGraft)return l;var f=new i.RPC.ControlGraft;return l.topicID!=null&&(f.topicID=String(l.topicID)),f},a.toObject=function(l,f){f||(f={});var h={};return l.topicID!=null&&l.hasOwnProperty("topicID")&&(h.topicID=l.topicID,f.oneofs&&(h._topicID="topicID")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.ControlPrune=function(){function a(u){if(this.peers=[],u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.topicID=l.string();break;case 2:d.peers&&d.peers.length||(d.peers=[]),d.peers.push(i.RPC.PeerInfo.decode(l,l.uint32()));break;case 3:d.backoff=l.uint64();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlPrune)return l;var f=new i.RPC.ControlPrune;if(l.topicID!=null&&(f.topicID=String(l.topicID)),l.peers){if(!Array.isArray(l.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");f.peers=[];for(var h=0;h>>0,l.backoff.high>>>0).toNumber(!0))),f},a.toObject=function(l,f){f||(f={});var h={};if((f.arrays||f.defaults)&&(h.peers=[]),l.topicID!=null&&l.hasOwnProperty("topicID")&&(h.topicID=l.topicID,f.oneofs&&(h._topicID="topicID")),l.peers&&l.peers.length){h.peers=[];for(var d=0;d>>0,l.backoff.high>>>0).toNumber(!0):l.backoff,f.oneofs&&(h._backoff="backoff")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.PeerInfo=function(){function a(u){if(u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.peerID=l.bytes();break;case 2:d.signedPeerRecord=l.bytes();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.PeerInfo)return l;var f=new i.RPC.PeerInfo;return l.peerID!=null&&(typeof l.peerID=="string"?n.base64.decode(l.peerID,f.peerID=n.newBuffer(n.base64.length(l.peerID)),0):l.peerID.length&&(f.peerID=l.peerID)),l.signedPeerRecord!=null&&(typeof l.signedPeerRecord=="string"?n.base64.decode(l.signedPeerRecord,f.signedPeerRecord=n.newBuffer(n.base64.length(l.signedPeerRecord)),0):l.signedPeerRecord.length&&(f.signedPeerRecord=l.signedPeerRecord)),f},a.toObject=function(l,f){f||(f={});var h={};return l.peerID!=null&&l.hasOwnProperty("peerID")&&(h.peerID=f.bytes===String?n.base64.encode(l.peerID,0,l.peerID.length):f.bytes===Array?Array.prototype.slice.call(l.peerID):l.peerID,f.oneofs&&(h._peerID="peerID")),l.signedPeerRecord!=null&&l.hasOwnProperty("signedPeerRecord")&&(h.signedPeerRecord=f.bytes===String?n.base64.encode(l.signedPeerRecord,0,l.signedPeerRecord.length):f.bytes===Array?Array.prototype.slice.call(l.signedPeerRecord):l.signedPeerRecord,f.oneofs&&(h._signedPeerRecord="signedPeerRecord")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o}(),i})});var Sae=P((S9t,xae)=>{"use strict";function un(r,t){var t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(r)&&this._fromArray(r)}un.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};un.prototype.get=function(e){return this.peekAt(e)};un.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};un.prototype.peekFront=function(){return this.peek()};un.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(un.prototype,"length",{get:function(){return this.size()}});un.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};un.prototype.push=function(e){if(e===void 0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}};un.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o=this._list[t],s;if(e0;s--)this._list[t]=this._list[t=t-1+i&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(s=n-1-e;s>0;s--)this._list[t]=this._list[t=t+1+i&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+i&this._capacityMask}return o}}};un.prototype.remove=function(e,t){var n=e,i,o=t;if(n===(n|0)&&this._head!==this._tail){var s=this.size(),a=this._list.length;if(!(n>=s||n<-s||t<1)){if(n<0&&(n+=s),t===1||!t)return i=new Array(1),i[0]=this.removeOne(n),i;if(n===0&&n+t>=s)return i=this.toArray(),this.clear(),i;n+t>s&&(t=s-n);var c;for(i=new Array(t),c=0;c0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return i}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return i}if(n0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;o>0;)this._list[n=n-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=s-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;o>0;)this._list[n=n+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),i}}};un.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var i=this.size();if(n<0&&(n+=i),!(n>i))if(arguments.length>2){var o,s,a,c=arguments.length,u=this._list.length,l=2;if(!i||n0&&(this._head=this._head+n+u&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+u&this._capacityMask);c>l;)this.unshift(arguments[--c]);for(o=n;o>0;o--)this.unshift(s[o-1])}else{s=new Array(i-(n+t));var f=s.length;for(o=0;othis._tail){for(o=this._head;o>>=1,this._capacityMask>>>=1};xae.exports=un});var fue=P((rPt,lue)=>{lue.exports=r=>{if(r[Symbol.asyncIterator])return r;if(r.getReader)return async function*(){let e=r.getReader();try{for(;;){let{done:t,value:n}=await e.read();if(t)return;yield n}}finally{e.releaseLock()}}();throw new Error("unknown stream")}});var dL=P((ZBt,Jle)=>{"use strict";var oUe=O1(),sUe=(r,e)=>({path:decodeURIComponent(new URL(r).pathname.split("/").pop()||""),content:aUe(r,e)});async function*aUe(r,e){yield*(await new oUe().get(r,e)).iterator()}Jle.exports=sUe});var r9=P((PFt,Nfe)=>{"use strict";function FUe(r){let e=new Uint8Array(r),t=0;if(r>0)if(r>65536)for(;tr?(crypto.getRandomValues(e.subarray(t,t+(r-t))),t+=r-t):(crypto.getRandomValues(e.subarray(t,t+65536)),t+=65536);else crypto.getRandomValues(e);return e}Nfe.exports=FUe});var RL=P((DFt,IL)=>{"use strict";var VUe=(r,e)=>Math.floor(Math.random()*(e-r+1)+r),Lfe=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Bfe=({clearTimeout:r,setTimeout:e,willResolve:t})=>(n,{value:i,signal:o}={})=>{if(o&&o.aborted)return Promise.reject(Lfe());let s,a,c,u=r||clearTimeout,l=()=>{u(s),c(Lfe())},f=()=>{o&&o.removeEventListener("abort",l)},h=new Promise((d,p)=>{a=()=>{f(),t?d(i):p(i)},c=p,s=(e||setTimeout)(a,n)});return o&&o.addEventListener("abort",l,{once:!0}),h.clear=()=>{u(s),s=null,a()},h},Mfe=r=>{let e=Bfe({...r,willResolve:!0});return e.reject=Bfe({...r,willResolve:!1}),e.range=(t,n,i)=>e(VUe(t,n),i),e},TL=Mfe();TL.createWithTimers=Mfe;IL.exports=TL;IL.exports.default=TL});var FL=P((mVt,tde)=>{"use strict";var Q2=new Map,eFe=()=>`${Date.now()}:${Math.floor(Math.random()*1e6)}`;async function tFe(r,e,t){for(;Q2.get(t);){try{await r()}catch(n){setTimeout(()=>{throw n},1);break}if(!Q2.get(t))break;await new Promise(n=>{let i=setTimeout(n,e);Q2.set(t,i)})}}function rFe(r,e,t){t=t||e;let n=eFe(),i=setTimeout(()=>{tFe(r,e,n)},t);return Q2.set(n,i),n}function nFe(r){let e=Q2.get(r);e&&(clearTimeout(e),Q2.delete(r))}tde.exports={setDelayedInterval:rFe,clearDelayedInterval:nFe}});var o4=P((iKt,ade)=>{ade.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ude=P((sKt,cde)=>{cde.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let n=Date.now();return t>=n?t-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var fde=P((aKt,lde)=>{var aFe=ude();lde.exports=aFe});var ys=P((uKt,dde)=>{dde.exports=class{constructor(e,t,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var Z2=P((fKt,pde)=>{var VL=o4(),cFe=fde(),hde=ys();pde.exports=class extends VL{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new cFe}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,n,i,o,s={}){let a=this._getRateLimiterRes(n,i,o);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,s)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(u=>{t(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof VL))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,n={}){let i=t*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,t,n,i={}){let o=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),t,o,i)}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(s);if(a>0)return o(new hde(0,a));this._upsert(s,t,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,o,s,t,c)}).catch(c=>{this._handleError(c,"consume",i,o,e,t,n)})})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,t,a))}).catch(a=>{this._handleError(a,"penalty",o,s,e,t,n)})})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,-t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,-t,a))}).catch(a=>{this._handleError(a,"reward",o,s,e,t,n)})})}get(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._get(n,t).then(s=>{i(s===null||typeof s>"u"?null:this._getRateLimiterRes(n,0,s))}).catch(s=>{this._handleError(s,"get",i,o,e,t)})})}delete(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._delete(n,t).then(s=>{this._inMemoryBlockedKeys.delete(n),i(s)}).catch(s=>{this._handleError(s,"delete",i,o,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,n,i={}){return new Promise((o,s)=>{this._upsert(e,t,n,!0,i).then(()=>{o(new hde(0,n>0?n:-1,t))}).catch(a=>{this._handleError(a,"block",o,s,this.parseKey(e),n/1e3,i)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,n,i=!1,o={}){throw new Error("You have to implement the method '_upsert'!")}}});var yde=P((dKt,gde)=>{var uFe=Z2(),lFe=ys(),mde="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",KL=class extends uFe{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:mde})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,n){let[i,o]=n;Array.isArray(i)&&([,i]=i,[,o]=o);let s=new lFe;return s.consumedPoints=parseInt(i),s.isFirstInDuration=s.consumedPoints===t,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=o,s}_upsert(e,t,n,i=!1){return new Promise((o,s)=>{if(!this._isRedisReady())return s(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,t,"EX",a):c.set(e,t),c.pttl(e).exec((u,l)=>u?s(u):o(l));else if(a>0){let u=function(l,f){return l?s(l):o(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,a,u):this.client.eval(mde,1,e,t,a,u)}else c.incrby(e,t).pttl(e).exec((u,l)=>u?s(u):o(l))})}_get(e){return new Promise((t,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,o)=>{if(i)n(i);else{let[s]=o;if(s===null)return t(null);t(o)}})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):t(o>0)})})}};gde.exports=KL});var _de=P((hKt,bde)=>{var fFe=Z2(),dFe=ys();function wde(r){try{let e=r.client?r.client:r,{version:t}=e.topology.s.options.metadata.driver,n=t.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var s4=class extends fFe{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=wde(this.client)}):(this._initCollection(),this._driverVersion=wde(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?s4.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,n){let i=new dFe,o;return typeof n.value>"u"?o=n:o=n.value,i.isFirstInDuration=o.points===t,i.consumedPoints=o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire!==null?Math.max(new Date(o.expire).getTime()-Date.now(),0):-1,i}_upsert(e,t,n,i=!1,o={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let s=o.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,s),c={$set:{key:e,points:t,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,s)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,s),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,s));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},s),p={$set:Object.assign({key:e,points:t,expire:n>0?new Date(Date.now()+n):null},s)};this._collection.findOneAndUpdate(d,p,u).then(g=>{l(g)}).catch(g=>{g&&g.code===11e3?this._upsert(e,t,n,i).then(w=>l(w)).catch(w=>f(w)):f(g)})}else f(h)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(o=>o.deletedCount>0)}};bde.exports=s4});var vde=P((pKt,Ede)=>{var hFe=Z2(),pFe=ys(),$L=class extends hFe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(n),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((n,i)=>{if(n)return t(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),t(i);n.query(this._getCreateTableStmt(),o=>{if(o)return this._releaseConnection(n),t(o);this._releaseConnection(n),e()})})}).catch(n=>{t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,n){let i=new pFe,[o]=n;return i.isFirstInDuration=t===o.points,i.consumedPoints=i.isFirstInDuration?t:o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire?Math.max(o.expire-Date.now(),0):-1,i}_upsertTransaction(e,t,n,i,o){return new Promise((s,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;o?(f=`INSERT INTO ??.?? VALUES (?, ?, ?) +`+a+e.substr(s+1),o=i-s-1,s=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(s=i);return e}function J7e(r){return r.replace(/^\s+/,"")}});var rj=P((fit,tj)=>{var Cc=at();Uf();gr();var ZG=tj.exports=Cc.sha256=Cc.sha256||{};Cc.md.sha256=Cc.md.algorithms.sha256=ZG;ZG.create=function(){JG||eve();var r=null,e=Cc.util.createBuffer(),t=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,o=0;o>>0,s>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=s[1],s[1]=s[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return e.putBytes(i),XG(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Cc.util.createBuffer();i.putBytes(e.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,s=o&n.blockLength-1;i.putBytes(ZR.substr(0,n.blockLength-s));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4,h5:r.h5,h6:r.h6,h7:r.h7};XG(f,t,i);var h=Cc.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var ZR=null,JG=!1,ej=null;function eve(){ZR=String.fromCharCode(128),ZR+=Cc.util.fillString(String.fromCharCode(0),64),ej=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],JG=!0}function XG(r,e,t){for(var n,i,o,s,a,c,u,l,f,h,d,p,g,w,_,x=t.length();x>=64;){for(u=0;u<16;++u)e[u]=t.getInt32();for(;u<64;++u)n=e[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=e[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,e[u]=n+e[u-7]+i+e[u-16]|0;for(l=r.h0,f=r.h1,h=r.h2,d=r.h3,p=r.h4,g=r.h5,w=r.h6,_=r.h7,u=0;u<64;++u)s=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),a=w^p&(g^w),o=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|h&(l^f),n=_+s+a+ej[u]+e[u],i=o+c,_=w,w=g,g=p,p=d+n>>>0,d=h,h=f,f=l,l=n+i>>>0;r.h0=r.h0+l|0,r.h1=r.h1+f|0,r.h2=r.h2+h|0,r.h3=r.h3+d|0,r.h4=r.h4+p|0,r.h5=r.h5+g|0,r.h6=r.h6+w|0,r.h7=r.h7+_|0,x-=64}}});var ij=P((dit,nj)=>{var Pc=at();gr();var xb=null;Pc.util.isNodejs&&!Pc.options.usePureJavaScript&&!process.versions["node-webkit"]&&(xb=Ju());var tve=nj.exports=Pc.prng=Pc.prng||{};tve.create=function(r){for(var e={plugin:r,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},t=r.md,n=new Array(32),i=0;i<32;++i)n[i]=t.create();e.pools=n,e.pool=0,e.generate=function(u,l){if(!l)return e.generateSync(u);var f=e.plugin.cipher,h=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed,g=Pc.util.createBuffer();e.key=null,w();function w(_){if(_)return l(_);if(g.length()>=u)return l(null,g.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return Pc.util.nextTick(function(){o(w)});var x=f(e.key,e.seed);e.generated+=x.length,g.putBytes(x),e.key=d(f(e.key,h(e.seed))),e.seed=p(f(e.key,e.seed)),Pc.util.setImmediate(w)}},e.generateSync=function(u){var l=e.plugin.cipher,f=e.plugin.increment,h=e.plugin.formatKey,d=e.plugin.formatSeed;e.key=null;for(var p=Pc.util.createBuffer();p.length()1048575&&(e.key=null),e.key===null&&s();var g=l(e.key,e.seed);e.generated+=g.length,p.putBytes(g),e.key=h(l(e.key,f(e.seed))),e.seed=d(l(e.key,e.seed))}return p.getBytes(u)};function o(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(f,h){if(f)return u(f);e.collect(h),a(),u()})}function s(){if(e.pools[0].messageLength>=32)return a();var u=32-e.pools[0].messageLength<<5;e.collect(e.seedFileSync(u)),a()}function a(){e.reseeds=e.reseeds===4294967295?0:e.reseeds+1;var u=e.plugin.md.create();u.update(e.keyBytes);for(var l=1,f=0;f<32;++f)e.reseeds%l===0&&(u.update(e.pools[f].digest().getBytes()),e.pools[f].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var h=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(h),e.generated=0}function c(u){var l=null,f=Pc.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(l=function(b){return h.getRandomValues(b)});var d=Pc.util.createBuffer();if(l)for(;d.length()>16),x+=(_&32767)<<16,x+=_>>15,x=(x&2147483647)+(x>>31),y=x&4294967295;for(var w=0;w<3;++w)m=y>>>(w<<3),m^=Math.floor(Math.random()*256),d.putByte(m&255)}return d.getBytes(u)}return xb?(e.seedFile=function(u,l){xb.randomBytes(u,function(f,h){if(f)return l(f);l(null,h.toString())})},e.seedFileSync=function(u){return xb.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,f=0;f>h&255);e.collect(f)},e.registerWorker=function(u){if(u===self)e.seedFile=function(f,h){function d(p){var g=p.data;g.forge&&g.forge.prng&&(self.removeEventListener("message",d),h(g.forge.prng.err,g.forge.prng.bytes))}self.addEventListener("message",d),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var h=f.data;h.forge&&h.forge.prng&&e.seedFile(h.forge.prng.needed,function(d,p){u.postMessage({forge:{prng:{err:d,bytes:p}}})})};u.addEventListener("message",l)}},e}});var Dh=P((hit,JR)=>{var ii=at();Nh();rj();ij();gr();(function(){if(ii.random&&ii.random.getBytes){JR.exports=ii.random;return}(function(r){var e={},t=new Array(4),n=ii.util.createBuffer();e.formatKey=function(f){var h=ii.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),ii.aes._expandKey(f,!1)},e.formatSeed=function(f){var h=ii.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},e.cipher=function(f,h){return ii.aes._updateBlock(f,h,t,!1),n.putInt32(t[0]),n.putInt32(t[1]),n.putInt32(t[2]),n.putInt32(t[3]),n.getBytes()},e.increment=function(f){return++f[3],f},e.md=ii.md.sha256;function i(){var f=ii.prng.create(e);return f.getBytes=function(h,d){return f.generate(h,d)},f.getBytesSync=function(h){return f.generate(h)},f}var o=i(),s=null,a=ii.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(s=function(f){return c.getRandomValues(f)}),ii.options.usePureJavaScript||!ii.util.isNodejs&&!s){if(typeof window>"u"||window.document,o.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}o.collect(u),u=null}r&&(r().mousemove(function(f){o.collectInt(f.clientX,16),o.collectInt(f.clientY,16)}),r().keypress(function(f){o.collectInt(f.charCode,8)}))}if(!ii.random)ii.random=o;else for(var l in o)ii.random[l]=o[l];ii.random.createInstance=i,JR.exports=ii.random})(typeof jQuery<"u"?jQuery:null)})()});var cj=P((pit,aj)=>{var ho=at();gr();var eC=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],oj=[1,2,3,5],rve=function(r,e){return r<>16-e},nve=function(r,e){return(r&65535)>>e|r<<16-e&65535};aj.exports=ho.rc2=ho.rc2||{};ho.rc2.expandKey=function(r,e){typeof r=="string"&&(r=ho.util.createBuffer(r)),e=e||128;var t=r,n=r.length(),i=e,o=Math.ceil(i/8),s=255>>(i&7),a;for(a=n;a<128;a++)t.putByte(eC[t.at(a-1)+t.at(a-n)&255]);for(t.setAt(128-o,eC[t.at(128-o)&s]),a=127-o;a>=0;a--)t.setAt(a,eC[t.at(a+1)^t.at(a+o)]);return t};var sj=function(r,e,t){var n=!1,i=null,o=null,s=null,a,c,u,l,f=[];for(r=ho.rc2.expandKey(r,e),u=0;u<64;u++)f.push(r.getInt16Le());t?(a=function(p){for(u=0;u<4;u++)p[u]+=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),p[u]=rve(p[u],oj[u]),l++},c=function(p){for(u=0;u<4;u++)p[u]+=f[p[(u+3)%4]&63]}):(a=function(p){for(u=3;u>=0;u--)p[u]=nve(p[u],oj[u]),p[u]-=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),l--},c=function(p){for(u=3;u>=0;u--)p[u]-=f[p[(u+3)%4]&63]});var h=function(p){var g=[];for(u=0;u<4;u++){var w=i.getInt16Le();s!==null&&(t?w^=s.getInt16Le():s.putInt16Le(w)),g.push(w&65535)}l=t?0:63;for(var _=0;_=8;)h([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(p){var g=!0;if(t)if(p)g=p(8,i,!t);else{var w=i.length()===8?8:8-i.length();i.fillWithByte(w,w)}if(g&&(n=!0,d.update()),!t&&(g=i.length()===0,g))if(p)g=p(8,o,!t);else{var _=o.length(),x=o.at(_-1);x>_?g=!1:o.truncate(x)}return g}},d};ho.rc2.startEncrypting=function(r,e,t){var n=ho.rc2.createEncryptionCipher(r,128);return n.start(e,t),n};ho.rc2.createEncryptionCipher=function(r,e){return sj(r,e,!0)};ho.rc2.startDecrypting=function(r,e,t){var n=ho.rc2.createDecryptionCipher(r,128);return n.start(e,t),n};ho.rc2.createDecryptionCipher=function(r,e){return sj(r,e,!1)}});var qy=P((mit,gj)=>{var tC=at();gj.exports=tC.jsbn=tC.jsbn||{};var tl,ive=0xdeadbeefcafe,uj=(ive&16777215)==15715070;function ne(r,e,t){this.data=[],r!=null&&(typeof r=="number"?this.fromNumber(r,e,t):e==null&&typeof r!="string"?this.fromString(r,256):this.fromString(r,e))}tC.jsbn.BigInteger=ne;function Gt(){return new ne(null)}function ove(r,e,t,n,i,o){for(;--o>=0;){var s=e*this.data[r++]+t.data[n]+i;i=Math.floor(s/67108864),t.data[n++]=s&67108863}return i}function sve(r,e,t,n,i,o){for(var s=e&32767,a=e>>15;--o>=0;){var c=this.data[r]&32767,u=this.data[r++]>>15,l=a*c+u*s;c=s*c+((l&32767)<<15)+t.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),t.data[n++]=c&1073741823}return i}function lj(r,e,t,n,i,o){for(var s=e&16383,a=e>>14;--o>=0;){var c=this.data[r]&16383,u=this.data[r++]>>14,l=a*c+u*s;c=s*c+((l&16383)<<14)+t.data[n]+i,i=(c>>28)+(l>>14)+a*u,t.data[n++]=c&268435455}return i}typeof navigator>"u"?(ne.prototype.am=lj,tl=28):uj&&navigator.appName=="Microsoft Internet Explorer"?(ne.prototype.am=sve,tl=30):uj&&navigator.appName!="Netscape"?(ne.prototype.am=ove,tl=26):(ne.prototype.am=lj,tl=28);ne.prototype.DB=tl;ne.prototype.DM=(1<=0;--e)r.data[e]=this.data[e];r.t=this.t,r.s=this.s}function uve(r){this.t=1,this.s=r<0?-1:0,r>0?this.data[0]=r:r<-1?this.data[0]=r+this.DV:this.t=0}function Ff(r){var e=Gt();return e.fromInt(r),e}function lve(r,e){var t;if(e==16)t=4;else if(e==8)t=3;else if(e==256)t=8;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else{this.fromRadix(r,e);return}this.t=0,this.s=0;for(var n=r.length,i=!1,o=0;--n>=0;){var s=t==8?r[n]&255:dj(r,n);if(s<0){r.charAt(n)=="-"&&(i=!0);continue}i=!1,o==0?this.data[this.t++]=s:o+t>this.DB?(this.data[this.t-1]|=(s&(1<>this.DB-o):this.data[this.t-1]|=s<=this.DB&&(o-=this.DB)}t==8&&r[0]&128&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==r;)--this.t}function dve(r){if(this.s<0)return"-"+this.negate().toString(r);var e;if(r==16)e=4;else if(r==8)e=3;else if(r==2)e=1;else if(r==32)e=5;else if(r==4)e=2;else return this.toRadix(r);var t=(1<0)for(a>a)>0&&(i=!0,o=fj(n));s>=0;)a>(a+=this.DB-e)):(n=this.data[s]>>(a-=e)&t,a<=0&&(a+=this.DB,--s)),n>0&&(i=!0),i&&(o+=fj(n));return i?o:"0"}function hve(){var r=Gt();return ne.ZERO.subTo(this,r),r}function pve(){return this.s<0?this.negate():this}function mve(r){var e=this.s-r.s;if(e!=0)return e;var t=this.t;if(e=t-r.t,e!=0)return this.s<0?-e:e;for(;--t>=0;)if((e=this.data[t]-r.data[t])!=0)return e;return 0}function Ab(r){var e=1,t;return(t=r>>>16)!=0&&(r=t,e+=16),(t=r>>8)!=0&&(r=t,e+=8),(t=r>>4)!=0&&(r=t,e+=4),(t=r>>2)!=0&&(r=t,e+=2),(t=r>>1)!=0&&(r=t,e+=1),e}function gve(){return this.t<=0?0:this.DB*(this.t-1)+Ab(this.data[this.t-1]^this.s&this.DM)}function yve(r,e){var t;for(t=this.t-1;t>=0;--t)e.data[t+r]=this.data[t];for(t=r-1;t>=0;--t)e.data[t]=0;e.t=this.t+r,e.s=this.s}function wve(r,e){for(var t=r;t=0;--a)e.data[a+o+1]=this.data[a]>>n|s,s=(this.data[a]&i)<=0;--a)e.data[a]=0;e.data[o]=s,e.t=this.t+o+1,e.s=this.s,e.clamp()}function _ve(r,e){e.s=this.s;var t=Math.floor(r/this.DB);if(t>=this.t){e.t=0;return}var n=r%this.DB,i=this.DB-n,o=(1<>n;for(var s=t+1;s>n;n>0&&(e.data[this.t-t-1]|=(this.s&o)<>=this.DB;if(r.t>=this.DB;n+=this.s}else{for(n+=this.s;t>=this.DB;n-=r.s}e.s=n<0?-1:0,n<-1?e.data[t++]=this.DV+n:n>0&&(e.data[t++]=n),e.t=t,e.clamp()}function vve(r,e){var t=this.abs(),n=r.abs(),i=t.t;for(e.t=i+n.t;--i>=0;)e.data[i]=0;for(i=0;i=0;)r.data[t]=0;for(t=0;t=e.DV&&(r.data[t+e.t]-=e.DV,r.data[t+e.t+1]=1)}r.t>0&&(r.data[r.t-1]+=e.am(t,e.data[t],r,2*t,0,1)),r.s=0,r.clamp()}function Sve(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,t)):(n.copyTo(o),i.copyTo(t));var u=o.t,l=o.data[u-1];if(l!=0){var f=l*(1<1?o.data[u-2]>>this.F2:0),h=this.FV/f,d=(1<=0&&(t.data[t.t++]=1,t.subTo(_,t)),ne.ONE.dlShiftTo(u,_),_.subTo(o,o);o.t=0;){var x=t.data[--g]==l?this.DM:Math.floor(t.data[g]*h+(t.data[g-1]+p)*d);if((t.data[g]+=o.am(0,x,t,w,0,u))0&&t.rShiftTo(c,t),s<0&&ne.ZERO.subTo(t,t)}}}function Ave(r){var e=Gt();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(ne.ZERO)>0&&r.subTo(e,e),e}function Oh(r){this.m=r}function Tve(r){return r.s<0||r.compareTo(this.m)>=0?r.mod(this.m):r}function Ive(r){return r}function Rve(r){r.divRemTo(this.m,null,r)}function Cve(r,e,t){r.multiplyTo(e,t),this.reduce(t)}function Pve(r,e){r.squareTo(e),this.reduce(e)}Oh.prototype.convert=Tve;Oh.prototype.revert=Ive;Oh.prototype.reduce=Rve;Oh.prototype.mulTo=Cve;Oh.prototype.sqrTo=Pve;function kve(){if(this.t<1)return 0;var r=this.data[0];if(!(r&1))return 0;var e=r&3;return e=e*(2-(r&15)*e)&15,e=e*(2-(r&255)*e)&255,e=e*(2-((r&65535)*e&65535))&65535,e=e*(2-r*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Lh(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(e,e),e}function Dve(r){var e=Gt();return r.copyTo(e),this.reduce(e),e}function Ove(r){for(;r.t<=this.mt2;)r.data[r.t++]=0;for(var e=0;e>15)*this.mpl&this.um)<<15)&r.DM;for(t=e+this.m.t,r.data[t]+=this.m.am(0,n,r,e,0,this.m.t);r.data[t]>=r.DV;)r.data[t]-=r.DV,r.data[++t]++}r.clamp(),r.drShiftTo(this.m.t,r),r.compareTo(this.m)>=0&&r.subTo(this.m,r)}function Lve(r,e){r.squareTo(e),this.reduce(e)}function Bve(r,e,t){r.multiplyTo(e,t),this.reduce(t)}Lh.prototype.convert=Nve;Lh.prototype.revert=Dve;Lh.prototype.reduce=Ove;Lh.prototype.mulTo=Bve;Lh.prototype.sqrTo=Lve;function Mve(){return(this.t>0?this.data[0]&1:this.s)==0}function Uve(r,e){if(r>4294967295||r<1)return ne.ONE;var t=Gt(),n=Gt(),i=e.convert(this),o=Ab(r)-1;for(i.copyTo(t);--o>=0;)if(e.sqrTo(t,n),(r&1<0)e.mulTo(n,i,t);else{var s=t;t=n,n=s}return e.revert(t)}function Fve(r,e){var t;return r<256||e.isEven()?t=new Oh(e):t=new Lh(e),this.exp(r,t)}ne.prototype.copyTo=cve;ne.prototype.fromInt=uve;ne.prototype.fromString=lve;ne.prototype.clamp=fve;ne.prototype.dlShiftTo=yve;ne.prototype.drShiftTo=wve;ne.prototype.lShiftTo=bve;ne.prototype.rShiftTo=_ve;ne.prototype.subTo=Eve;ne.prototype.multiplyTo=vve;ne.prototype.squareTo=xve;ne.prototype.divRemTo=Sve;ne.prototype.invDigit=kve;ne.prototype.isEven=Mve;ne.prototype.exp=Uve;ne.prototype.toString=dve;ne.prototype.negate=hve;ne.prototype.abs=pve;ne.prototype.compareTo=mve;ne.prototype.bitLength=gve;ne.prototype.mod=Ave;ne.prototype.modPowInt=Fve;ne.ZERO=Ff(0);ne.ONE=Ff(1);function zve(){var r=Gt();return this.copyTo(r),r}function Vve(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function $ve(){return this.t==0?this.s:this.data[0]<<16>>16}function qve(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function Hve(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function Gve(r){if(r==null&&(r=10),this.signum()==0||r<2||r>36)return"0";var e=this.chunkSize(r),t=Math.pow(r,e),n=Ff(t),i=Gt(),o=Gt(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(t+o.intValue()).toString(r).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(r)+s}function jve(r,e){this.fromInt(0),e==null&&(e=10);for(var t=this.chunkSize(e),n=Math.pow(e,t),i=!1,o=0,s=0,a=0;a=t&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0)}o>0&&(this.dMultiply(Math.pow(e,o)),this.dAddOffset(s,0)),i&&ne.ZERO.subTo(this,this)}function Wve(r,e,t){if(typeof e=="number")if(r<2)this.fromInt(1);else for(this.fromNumber(r,t),this.testBit(r-1)||this.bitwiseTo(ne.ONE.shiftLeft(r-1),nC,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>r&&this.subTo(ne.ONE.shiftLeft(r-1),this);else{var n=new Array,i=r&7;n.length=(r>>3)+1,e.nextBytes(n),i>0?n[0]&=(1<0)for(t>t)!=(this.s&this.DM)>>t&&(e[i++]=n|this.s<=0;)t<8?(n=(this.data[r]&(1<>(t+=this.DB-8)):(n=this.data[r]>>(t-=8)&255,t<=0&&(t+=this.DB,--r)),n&128&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function Qve(r){return this.compareTo(r)==0}function Xve(r){return this.compareTo(r)<0?this:r}function Zve(r){return this.compareTo(r)>0?this:r}function Jve(r,e,t){var n,i,o=Math.min(r.t,this.t);for(n=0;n>=16,e+=16),r&255||(r>>=8,e+=8),r&15||(r>>=4,e+=4),r&3||(r>>=2,e+=2),r&1||++e,e}function u9e(){for(var r=0;r=this.t?this.s!=0:(this.data[e]&1<>=this.DB;if(r.t>=this.DB;n+=this.s}else{for(n+=this.s;t>=this.DB;n+=r.s}e.s=n<0?-1:0,n>0?e.data[t++]=n:n<-1&&(e.data[t++]=this.DV+n),e.t=t,e.clamp()}function w9e(r){var e=Gt();return this.addTo(r,e),e}function b9e(r){var e=Gt();return this.subTo(r,e),e}function _9e(r){var e=Gt();return this.multiplyTo(r,e),e}function E9e(r){var e=Gt();return this.divRemTo(r,e,null),e}function v9e(r){var e=Gt();return this.divRemTo(r,null,e),e}function x9e(r){var e=Gt(),t=Gt();return this.divRemTo(r,e,t),new Array(e,t)}function S9e(r){this.data[this.t]=this.am(0,r-1,this,0,0,this.t),++this.t,this.clamp()}function A9e(r,e){if(r!=0){for(;this.t<=e;)this.data[this.t++]=0;for(this.data[e]+=r;this.data[e]>=this.DV;)this.data[e]-=this.DV,++e>=this.t&&(this.data[this.t++]=0),++this.data[e]}}function $y(){}function mj(r){return r}function T9e(r,e,t){r.multiplyTo(e,t)}function I9e(r,e){r.squareTo(e)}$y.prototype.convert=mj;$y.prototype.revert=mj;$y.prototype.mulTo=T9e;$y.prototype.sqrTo=I9e;function R9e(r){return this.exp(r,new $y)}function C9e(r,e,t){var n=Math.min(this.t+r.t,e);for(t.s=0,t.t=n;n>0;)t.data[--n]=0;var i;for(i=t.t-this.t;n=0;)t.data[n]=0;for(n=Math.max(e-this.t,0);n2*this.m.t)return r.mod(this.m);if(r.compareTo(this.m)<0)return r;var e=Gt();return r.copyTo(e),this.reduce(e),e}function N9e(r){return r}function D9e(r){for(r.drShiftTo(this.m.t-1,this.r2),r.t>this.m.t+1&&(r.t=this.m.t+1,r.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);r.compareTo(this.r2)<0;)r.dAddOffset(1,this.m.t+1);for(r.subTo(this.r2,r);r.compareTo(this.m)>=0;)r.subTo(this.m,r)}function O9e(r,e){r.squareTo(e),this.reduce(e)}function L9e(r,e,t){r.multiplyTo(e,t),this.reduce(t)}q1.prototype.convert=k9e;q1.prototype.revert=N9e;q1.prototype.reduce=D9e;q1.prototype.mulTo=L9e;q1.prototype.sqrTo=O9e;function B9e(r,e){var t=r.bitLength(),n,i=Ff(1),o;if(t<=0)return i;t<18?n=1:t<48?n=3:t<144?n=4:t<768?n=5:n=6,t<8?o=new Oh(e):e.isEven()?o=new q1(e):o=new Lh(e);var s=new Array,a=3,c=n-1,u=(1<1){var l=Gt();for(o.sqrTo(s[1],l);a<=u;)s[a]=Gt(),o.mulTo(l,s[a-2],s[a]),a+=2}var f=r.t-1,h,d=!0,p=Gt(),g;for(t=Ab(r.data[f])-1;f>=0;){for(t>=c?h=r.data[f]>>t-c&u:(h=(r.data[f]&(1<0&&(h|=r.data[f-1]>>this.DB+t-c)),a=n;!(h&1);)h>>=1,--a;if((t-=a)<0&&(t+=this.DB,--f),d)s[h].copyTo(i),d=!1;else{for(;a>1;)o.sqrTo(i,p),o.sqrTo(p,i),a-=2;a>0?o.sqrTo(i,p):(g=i,i=p,p=g),o.mulTo(p,s[h],i)}for(;f>=0&&!(r.data[f]&1<0&&(e.rShiftTo(o,e),t.rShiftTo(o,t));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),e.compareTo(t)>=0?(e.subTo(t,e),e.rShiftTo(1,e)):(t.subTo(e,t),t.rShiftTo(1,t));return o>0&&t.lShiftTo(o,t),t}function U9e(r){if(r<=0)return 0;var e=this.DV%r,t=this.s<0?r-1:0;if(this.t>0)if(e==0)t=this.data[0]%r;else for(var n=this.t-1;n>=0;--n)t=(e*t+this.data[n])%r;return t}function F9e(r){var e=r.isEven();if(this.isEven()&&e||r.signum()==0)return ne.ZERO;for(var t=r.clone(),n=this.clone(),i=Ff(1),o=Ff(0),s=Ff(0),a=Ff(1);t.signum()!=0;){for(;t.isEven();)t.rShiftTo(1,t),e?((!i.isEven()||!o.isEven())&&(i.addTo(this,i),o.subTo(r,o)),i.rShiftTo(1,i)):o.isEven()||o.subTo(r,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),e?((!s.isEven()||!a.isEven())&&(s.addTo(this,s),a.subTo(r,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(r,a),a.rShiftTo(1,a);t.compareTo(n)>=0?(t.subTo(n,t),e&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(t,n),e&&s.subTo(i,s),a.subTo(o,a))}if(n.compareTo(ne.ONE)!=0)return ne.ZERO;if(a.compareTo(r)>=0)return a.subtract(r);if(a.signum()<0)a.addTo(r,a);else return a;return a.signum()<0?a.add(r):a}var Ba=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],z9e=(1<<26)/Ba[Ba.length-1];function V9e(r){var e,t=this.abs();if(t.t==1&&t.data[0]<=Ba[Ba.length-1]){for(e=0;e=0);var a=o.modPow(n,this);if(a.compareTo(ne.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++{var kc=at();Uf();gr();var wj=_j.exports=kc.sha1=kc.sha1||{};kc.md.sha1=kc.md.algorithms.sha1=wj;wj.create=function(){bj||q9e();var r=null,e=kc.util.createBuffer(),t=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,o=0;o>>0,s>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=s[1],s[1]=s[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return e.putBytes(i),yj(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=kc.util.createBuffer();i.putBytes(e.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,s=o&n.blockLength-1;i.putBytes(iC.substr(0,n.blockLength-s));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4};yj(f,t,i);var h=kc.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var iC=null,bj=!1;function q9e(){iC=String.fromCharCode(128),iC+=kc.util.fillString(String.fromCharCode(0),64),bj=!0}function yj(r,e,t){for(var n,i,o,s,a,c,u,l,f=t.length();f>=64;){for(i=r.h0,o=r.h1,s=r.h2,a=r.h3,c=r.h4,l=0;l<16;++l)n=t.getInt32(),e[l]=n,u=a^o&(s^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<20;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=a^o&(s^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<32;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<40;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<60;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=o&s|a&(o^s),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<80;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;r.h0=r.h0+i|0,r.h1=r.h1+o|0,r.h2=r.h2+s|0,r.h3=r.h3+a|0,r.h4=r.h4+c|0,f-=64}}});var Sj=P((yit,xj)=>{var Nc=at();gr();Dh();Ej();var vj=xj.exports=Nc.pkcs1=Nc.pkcs1||{};vj.encode_rsa_oaep=function(r,e,t){var n,i,o,s;typeof t=="string"?(n=t,i=arguments[3]||void 0,o=arguments[4]||void 0):t&&(n=t.label||void 0,i=t.seed||void 0,o=t.md||void 0,t.mgf1&&t.mgf1.md&&(s=t.mgf1.md)),o?o.start():o=Nc.md.sha1.create(),s||(s=o);var a=Math.ceil(r.n.bitLength()/8),c=a-2*o.digestLength-2;if(e.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=e.length,u.maxLength=c,u}n||(n=""),o.update(n,"raw");for(var l=o.digest(),f="",h=c-e.length,d=0;d>24&255,o>>16&255,o>>8&255,o&255);t.start(),t.update(r+s),n+=t.digest().getBytes()}return n.substring(0,e)}});var Aj=P((wit,oC)=>{var zf=at();gr();qy();Dh();(function(){if(zf.prime){oC.exports=zf.prime;return}var r=oC.exports=zf.prime=zf.prime||{},e=zf.jsbn.BigInteger,t=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(f,h){return f|h};r.generateProbablePrime=function(f,h,d){typeof h=="function"&&(d=h,h={}),h=h||{};var p=h.algorithm||"PRIMEINC";typeof p=="string"&&(p={name:p}),p.options=p.options||{};var g=h.prng||zf.random,w={nextBytes:function(_){for(var x=g.getBytesSync(_.length),m=0;m<_.length;++m)_[m]=x.charCodeAt(m)}};if(p.name==="PRIMEINC")return o(f,w,p.options,d);throw new Error("Invalid prime generation algorithm: "+p.name)};function o(f,h,d,p){return"workers"in d?c(f,h,d,p):s(f,h,d,p)}function s(f,h,d,p){var g=u(f,h),w=0,_=l(g.bitLength());"millerRabinTests"in d&&(_=d.millerRabinTests);var x=10;"maxBlockTime"in d&&(x=d.maxBlockTime),a(g,f,h,w,_,x,p)}function a(f,h,d,p,g,w,_){var x=+new Date;do{if(f.bitLength()>h&&(f=u(h,d)),f.isProbablePrime(g))return _(null,f);f.dAddOffset(t[p++%8],0)}while(w<0||+new Date-x"u")return s(f,h,d,p);var g=u(f,h),w=d.workers,_=d.workLoad||100,x=_*30/8,m=d.workerScript||"forge/prime.worker.js";if(w===-1)return zf.util.estimateCores(function(b,E){b&&(E=2),w=E-1,y()});y();function y(){w=Math.max(1,w);for(var b=[],E=0;Ef&&(g=u(f,h));var O=g.toString(16);I.target.postMessage({hex:O,workLoad:_}),g.dAddOffset(x,0)}}}}function u(f,h){var d=new e(f,h),p=f-1;return d.testBit(p)||d.bitwiseTo(e.ONE.shiftLeft(p),i,d),d.dAddOffset(31-d.mod(n).byteValue(),0),d}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var Bh=P((bit,Nj)=>{var Ve=at();Ic();qy();z1();Sj();Aj();Dh();gr();typeof Ft>"u"&&(Ft=Ve.jsbn.BigInteger);var Ft,sC=Ve.util.isNodejs?Ju():null,H=Ve.asn1,Os=Ve.util;Ve.pki=Ve.pki||{};Nj.exports=Ve.pki.rsa=Ve.rsa=Ve.rsa||{};var ct=Ve.pki,H9e=[6,4,2,4,2,4,6,2],G9e={name:"PrivateKeyInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},j9e={name:"RSAPrivateKey",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},W9e={name:"RSAPublicKey",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:H.Class.UNIVERSAL,type:H.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Y9e=Ve.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:H.Class.UNIVERSAL,type:H.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Q9e={name:"DigestInfo",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:H.Class.UNIVERSAL,type:H.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:H.Class.UNIVERSAL,type:H.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:H.Class.UNIVERSAL,type:H.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:H.Class.UNIVERSAL,type:H.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},X9e=function(r){var e;if(r.algorithm in ct.oids)e=ct.oids[r.algorithm];else{var t=new Error("Unknown message digest algorithm.");throw t.algorithm=r.algorithm,t}var n=H.oidToDer(e).getBytes(),i=H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[]),o=H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[]);o.value.push(H.create(H.Class.UNIVERSAL,H.Type.OID,!1,n)),o.value.push(H.create(H.Class.UNIVERSAL,H.Type.NULL,!1,""));var s=H.create(H.Class.UNIVERSAL,H.Type.OCTETSTRING,!1,r.digest().getBytes());return i.value.push(o),i.value.push(s),H.toDer(i).getBytes()},Pj=function(r,e,t){if(t)return r.modPow(e.e,e.n);if(!e.p||!e.q)return r.modPow(e.d,e.n);e.dP||(e.dP=e.d.mod(e.p.subtract(Ft.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(Ft.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new Ft(Ve.util.bytesToHex(Ve.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(Ft.ONE));r=r.multiply(n.modPow(e.e,e.n)).mod(e.n);for(var i=r.mod(e.p).modPow(e.dP,e.p),o=r.mod(e.q).modPow(e.dQ,e.q);i.compareTo(o)<0;)i=i.add(e.p);var s=i.subtract(o).multiply(e.qInv).mod(e.p).multiply(e.q).add(o);return s=s.multiply(n.modInverse(e.n)).mod(e.n),s};ct.rsa.encrypt=function(r,e,t){var n=t,i,o=Math.ceil(e.n.bitLength()/8);t!==!1&&t!==!0?(n=t===2,i=kj(r,e,t)):(i=Ve.util.createBuffer(),i.putBytes(r));for(var s=new Ft(i.toHex(),16),a=Pj(s,e,n),c=a.toString(16),u=Ve.util.createBuffer(),l=o-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(Ve.util.hexToBytes(c)),u.getBytes()};ct.rsa.decrypt=function(r,e,t,n){var i=Math.ceil(e.n.bitLength()/8);if(r.length!==i){var o=new Error("Encrypted message length is invalid.");throw o.length=r.length,o.expected=i,o}var s=new Ft(Ve.util.createBuffer(r).toHex(),16);if(s.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=Pj(s,e,t),c=a.toString(16),u=Ve.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(Ve.util.hexToBytes(c)),n!==!1?Ib(u.getBytes(),e,t):u.getBytes()};ct.rsa.createKeyPairGenerationState=function(r,e,t){typeof r=="string"&&(r=parseInt(r,10)),r=r||2048,t=t||{};var n=t.prng||Ve.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u>1,pBits:r-(r>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw new Error("Invalid key generation algorithm: "+o);return s};ct.rsa.stepKeyPairGenerationState=function(r,e){"algorithm"in r||(r.algorithm="PRIMEINC");var t=new Ft(null);t.fromInt(30);for(var n=0,i=function(f,h){return f|h},o=+new Date,s,a=0;r.keys===null&&(e<=0||ac?r.pqState=0:r.num.isProbablePrime(J9e(r.num.bitLength()))?++r.pqState:r.num.dAddOffset(H9e[n++%8],0):r.pqState===2?r.pqState=r.num.subtract(Ft.ONE).gcd(r.e).compareTo(Ft.ONE)===0?3:0:r.pqState===3&&(r.pqState=0,r.p===null?r.p=r.num:r.q=r.num,r.p!==null&&r.q!==null&&++r.state,r.num=null)}else if(r.state===1)r.p.compareTo(r.q)<0&&(r.num=r.p,r.p=r.q,r.q=r.num),++r.state;else if(r.state===2)r.p1=r.p.subtract(Ft.ONE),r.q1=r.q.subtract(Ft.ONE),r.phi=r.p1.multiply(r.q1),++r.state;else if(r.state===3)r.phi.gcd(r.e).compareTo(Ft.ONE)===0?++r.state:(r.p=null,r.q=null,r.state=0);else if(r.state===4)r.n=r.p.multiply(r.q),r.n.bitLength()===r.bits?++r.state:(r.q=null,r.state=0);else if(r.state===5){var l=r.e.modInverse(r.phi);r.keys={privateKey:ct.rsa.setPrivateKey(r.n,r.e,l,r.p,r.q,l.mod(r.p1),l.mod(r.q1),r.q.modInverse(r.p)),publicKey:ct.rsa.setPublicKey(r.n,r.e)}}s=+new Date,a+=s-o,o=s}return r.keys!==null};ct.rsa.generateKeyPair=function(r,e,t,n){if(arguments.length===1?typeof r=="object"?(t=r,r=void 0):typeof r=="function"&&(n=r,r=void 0):arguments.length===2?typeof r=="number"?typeof e=="function"?(n=e,e=void 0):typeof e!="number"&&(t=e,e=void 0):(t=r,n=e,r=void 0,e=void 0):arguments.length===3&&(typeof e=="number"?typeof t=="function"&&(n=t,t=void 0):(n=t,t=e,e=void 0)),t=t||{},r===void 0&&(r=t.bits||2048),e===void 0&&(e=t.e||65537),!Ve.options.usePureJavaScript&&!t.prng&&r>=256&&r<=16384&&(e===65537||e===3)){if(n){if(Tj("generateKeyPair"))return sC.generateKeyPair("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:ct.privateKeyFromPem(u),publicKey:ct.publicKeyFromPem(c)})});if(Ij("generateKey")&&Ij("exportKey"))return Os.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:Cj(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return Os.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=ct.privateKeyFromAsn1(H.fromDer(Ve.util.createBuffer(a)));n(null,{privateKey:c,publicKey:ct.setRsaPublicKey(c.n,c.e)})}});if(Rj("generateKey")&&Rj("exportKey")){var i=Os.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:Cj(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=Os.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,h=ct.privateKeyFromAsn1(H.fromDer(Ve.util.createBuffer(f)));n(null,{privateKey:h,publicKey:ct.setRsaPublicKey(h.n,h.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(Tj("generateKeyPairSync")){var o=sC.generateKeyPairSync("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:ct.privateKeyFromPem(o.privateKey),publicKey:ct.publicKeyFromPem(o.publicKey)}}}var s=ct.rsa.createKeyPairGenerationState(r,e,t);if(!n)return ct.rsa.stepKeyPairGenerationState(s,0),s.keys;Z9e(s,t,n)};ct.setRsaPublicKey=ct.rsa.setPublicKey=function(r,e){var t={n:r,e};return t.encrypt=function(n,i,o){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return kj(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return Ve.pkcs1.encode_rsa_oaep(c,a,o)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var s=i.encode(n,t,!0);return ct.rsa.encrypt(s,t,!0)},t.verify=function(n,i,o,s){typeof o=="string"?o=o.toUpperCase():o===void 0&&(o="RSASSA-PKCS1-V1_5"),s===void 0&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),o==="RSASSA-PKCS1-V1_5"?o={verify:function(c,u){u=Ib(u,t,!0);var l=H.fromDer(u,{parseAllBytes:s._parseAllDigestBytes}),f={},h=[];if(!H.validate(l,Q9e,f,h)){var d=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw d.errors=h,d}var p=H.derToOid(f.algorithmIdentifier);if(!(p===Ve.oids.md2||p===Ve.oids.md5||p===Ve.oids.sha1||p===Ve.oids.sha224||p===Ve.oids.sha256||p===Ve.oids.sha384||p===Ve.oids.sha512||p===Ve.oids["sha512-224"]||p===Ve.oids["sha512-256"])){var d=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw d.oid=p,d}if((p===Ve.oids.md2||p===Ve.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(o==="NONE"||o==="NULL"||o===null)&&(o={verify:function(c,u){return u=Ib(u,t,!0),c===u}});var a=ct.rsa.decrypt(i,t,!0,!1);return o.verify(n,a,t.n.bitLength())},t};ct.setRsaPrivateKey=ct.rsa.setPrivateKey=function(r,e,t,n,i,o,s,a){var c={n:r,e,d:t,p:n,q:i,dP:o,dQ:s,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var h=ct.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:Ib};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(d,p){return Ve.pkcs1.decode_rsa_oaep(p,d,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(d){return d}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(h,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:X9e},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var h=l.encode(u,c.n.bitLength());return ct.rsa.encrypt(h,c,f)},c};ct.wrapRsaPrivateKey=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,H.integerToDer(0).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.OID,!1,H.oidToDer(ct.oids.rsaEncryption).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.NULL,!1,"")]),H.create(H.Class.UNIVERSAL,H.Type.OCTETSTRING,!1,H.toDer(r).getBytes())])};ct.privateKeyFromAsn1=function(r){var e={},t=[];if(H.validate(r,G9e,e,t)&&(r=H.fromDer(Ve.util.createBuffer(e.privateKey))),e={},t=[],!H.validate(r,j9e,e,t)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=t,n}var i,o,s,a,c,u,l,f;return i=Ve.util.createBuffer(e.privateKeyModulus).toHex(),o=Ve.util.createBuffer(e.privateKeyPublicExponent).toHex(),s=Ve.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=Ve.util.createBuffer(e.privateKeyPrime1).toHex(),c=Ve.util.createBuffer(e.privateKeyPrime2).toHex(),u=Ve.util.createBuffer(e.privateKeyExponent1).toHex(),l=Ve.util.createBuffer(e.privateKeyExponent2).toHex(),f=Ve.util.createBuffer(e.privateKeyCoefficient).toHex(),ct.setRsaPrivateKey(new Ft(i,16),new Ft(o,16),new Ft(s,16),new Ft(a,16),new Ft(c,16),new Ft(u,16),new Ft(l,16),new Ft(f,16))};ct.privateKeyToAsn1=ct.privateKeyToRSAPrivateKey=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,H.integerToDer(0).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.n)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.e)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.d)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.p)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.q)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.dP)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.dQ)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.qInv))])};ct.publicKeyFromAsn1=function(r){var e={},t=[];if(H.validate(r,Y9e,e,t)){var n=H.derToOid(e.publicKeyOid);if(n!==ct.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}r=e.rsaPublicKey}if(t=[],!H.validate(r,W9e,e,t)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=t,i}var o=Ve.util.createBuffer(e.publicKeyModulus).toHex(),s=Ve.util.createBuffer(e.publicKeyExponent).toHex();return ct.setRsaPublicKey(new Ft(o,16),new Ft(s,16))};ct.publicKeyToAsn1=ct.publicKeyToSubjectPublicKeyInfo=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.OID,!1,H.oidToDer(ct.oids.rsaEncryption).getBytes()),H.create(H.Class.UNIVERSAL,H.Type.NULL,!1,"")]),H.create(H.Class.UNIVERSAL,H.Type.BITSTRING,!1,[ct.publicKeyToRSAPublicKey(r)])])};ct.publicKeyToRSAPublicKey=function(r){return H.create(H.Class.UNIVERSAL,H.Type.SEQUENCE,!0,[H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.n)),H.create(H.Class.UNIVERSAL,H.Type.INTEGER,!1,Dc(r.e))])};function kj(r,e,t){var n=Ve.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(r.length>i-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=r.length,o.max=i-11,o}n.putByte(0),n.putByte(t);var s=i-3-r.length,a;if(t===0||t===1){a=t===0?0:255;for(var c=0;c0;){for(var u=0,l=Ve.random.getBytes(s),c=0;c"u")throw new Error("Encryption block is invalid.");var c=0;if(a===0){c=i-3-n;for(var u=0;u1;){if(o.getByte()!==255){--o.read;break}++c}else if(a===2)for(c=0;o.length()>1;){if(o.getByte()===0){--o.read;break}++c}var l=o.getByte();if(l!==0||c!==i-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function Z9e(r,e,t){typeof e=="function"&&(t=e,e={}),e=e||{};var n={algorithm:{name:e.algorithm||"PRIMEINC",options:{workers:e.workers||2,workLoad:e.workLoad||100,workerScript:e.workerScript}}};"prng"in e&&(n.prng=e.prng),i();function i(){o(r.pBits,function(a,c){if(a)return t(a);if(r.p=c,r.q!==null)return s(a,r.q);o(r.qBits,s)})}function o(a,c){Ve.prime.generateProbablePrime(a,n,c)}function s(a,c){if(a)return t(a);if(r.q=c,r.p.compareTo(r.q)<0){var u=r.p;r.p=r.q,r.q=u}if(r.p.subtract(Ft.ONE).gcd(r.e).compareTo(Ft.ONE)!==0){r.p=null,i();return}if(r.q.subtract(Ft.ONE).gcd(r.e).compareTo(Ft.ONE)!==0){r.q=null,o(r.qBits,s);return}if(r.p1=r.p.subtract(Ft.ONE),r.q1=r.q.subtract(Ft.ONE),r.phi=r.p1.multiply(r.q1),r.phi.gcd(r.e).compareTo(Ft.ONE)!==0){r.p=r.q=null,i();return}if(r.n=r.p.multiply(r.q),r.n.bitLength()!==r.bits){r.q=null,o(r.qBits,s);return}var l=r.e.modInverse(r.phi);r.keys={privateKey:ct.rsa.setPrivateKey(r.n,r.e,l,r.p,r.q,l.mod(r.p1),l.mod(r.q1),r.q.modInverse(r.p)),publicKey:ct.rsa.setPublicKey(r.n,r.e)},t(null,r.keys)}}function Dc(r){var e=r.toString(16);e[0]>="8"&&(e="00"+e);var t=Ve.util.hexToBytes(e);return t.length>1&&(t.charCodeAt(0)===0&&!(t.charCodeAt(1)&128)||t.charCodeAt(0)===255&&(t.charCodeAt(1)&128)===128)?t.substr(1):t}function J9e(r){return r<=100?27:r<=150?18:r<=200?15:r<=250?12:r<=300?9:r<=350?8:r<=400?7:r<=500?6:r<=600?5:r<=800?4:r<=1250?3:2}function Tj(r){return Ve.util.isNodejs&&typeof sC[r]=="function"}function Ij(r){return typeof Os.globalScope<"u"&&typeof Os.globalScope.crypto=="object"&&typeof Os.globalScope.crypto.subtle=="object"&&typeof Os.globalScope.crypto.subtle[r]=="function"}function Rj(r){return typeof Os.globalScope<"u"&&typeof Os.globalScope.msCrypto=="object"&&typeof Os.globalScope.msCrypto.subtle=="object"&&typeof Os.globalScope.msCrypto.subtle[r]=="function"}function Cj(r){for(var e=Ve.util.hexToBytes(r.toString(16)),t=new Uint8Array(e.length),n=0;n{var Ae=at();Nh();Ic();yb();Uf();z1();bb();vb();Dh();cj();Bh();gr();typeof Dj>"u"&&(Dj=Ae.jsbn.BigInteger);var Dj,W=Ae.asn1,gt=Ae.pki=Ae.pki||{};Mj.exports=gt.pbe=Ae.pbe=Ae.pbe||{};var Mh=gt.oids,exe={name:"EncryptedPrivateKeyInfo",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},txe={name:"PBES2Algorithms",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:W.Class.UNIVERSAL,type:W.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:W.Class.UNIVERSAL,type:W.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:W.Class.UNIVERSAL,type:W.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},rxe={name:"pkcs-12PbeParams",tagClass:W.Class.UNIVERSAL,type:W.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:W.Class.UNIVERSAL,type:W.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:W.Class.UNIVERSAL,type:W.Type.INTEGER,constructed:!1,capture:"iterations"}]};gt.encryptPrivateKeyInfo=function(r,e,t){t=t||{},t.saltSize=t.saltSize||8,t.count=t.count||2048,t.algorithm=t.algorithm||"aes128",t.prfAlgorithm=t.prfAlgorithm||"sha1";var n=Ae.random.getBytesSync(t.saltSize),i=t.count,o=W.integerToDer(i),s,a,c;if(t.algorithm.indexOf("aes")===0||t.algorithm==="des"){var u,l,f;switch(t.algorithm){case"aes128":s=16,u=16,l=Mh["aes128-CBC"],f=Ae.aes.createEncryptionCipher;break;case"aes192":s=24,u=16,l=Mh["aes192-CBC"],f=Ae.aes.createEncryptionCipher;break;case"aes256":s=32,u=16,l=Mh["aes256-CBC"],f=Ae.aes.createEncryptionCipher;break;case"des":s=8,u=8,l=Mh.desCBC,f=Ae.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=t.algorithm,h}var d="hmacWith"+t.prfAlgorithm.toUpperCase(),p=Bj(d),g=Ae.pkcs5.pbkdf2(e,n,i,s,p),w=Ae.random.getBytesSync(u),_=f(g);_.start(w),_.update(W.toDer(r)),_.finish(),c=_.output.getBytes();var x=nxe(n,o,s,d);a=W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(Mh.pkcs5PBES2).getBytes()),W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(Mh.pkcs5PBKDF2).getBytes()),x]),W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(l).getBytes()),W.create(W.Class.UNIVERSAL,W.Type.OCTETSTRING,!1,w)])])])}else if(t.algorithm==="3des"){s=24;var m=new Ae.util.ByteBuffer(n),g=gt.pbe.generatePkcs12Key(e,m,1,i,s),w=gt.pbe.generatePkcs12Key(e,m,2,i,s),_=Ae.des.createEncryptionCipher(g);_.start(w),_.update(W.toDer(r)),_.finish(),c=_.output.getBytes(),a=W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OID,!1,W.oidToDer(Mh["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[W.create(W.Class.UNIVERSAL,W.Type.OCTETSTRING,!1,n),W.create(W.Class.UNIVERSAL,W.Type.INTEGER,!1,o.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=t.algorithm,h}var y=W.create(W.Class.UNIVERSAL,W.Type.SEQUENCE,!0,[a,W.create(W.Class.UNIVERSAL,W.Type.OCTETSTRING,!1,c)]);return y};gt.decryptPrivateKeyInfo=function(r,e){var t=null,n={},i=[];if(!W.validate(r,exe,n,i)){var o=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=W.derToOid(n.encryptionOid),a=gt.pbe.getCipher(s,n.encryptionParams,e),c=Ae.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(t=W.fromDer(a.output)),t};gt.encryptedPrivateKeyToPem=function(r,e){var t={type:"ENCRYPTED PRIVATE KEY",body:W.toDer(r).getBytes()};return Ae.pem.encode(t,{maxline:e})};gt.encryptedPrivateKeyFromPem=function(r){var e=Ae.pem.decode(r)[0];if(e.type!=="ENCRYPTED PRIVATE KEY"){var t=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw t.headerType=e.type,t}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return W.fromDer(e.body)};gt.encryptRsaPrivateKey=function(r,e,t){if(t=t||{},!t.legacy){var n=gt.wrapRsaPrivateKey(gt.privateKeyToAsn1(r));return n=gt.encryptPrivateKeyInfo(n,e,t),gt.encryptedPrivateKeyToPem(n)}var i,o,s,a;switch(t.algorithm){case"aes128":i="AES-128-CBC",s=16,o=Ae.random.getBytesSync(16),a=Ae.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",s=24,o=Ae.random.getBytesSync(16),a=Ae.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",s=32,o=Ae.random.getBytesSync(16),a=Ae.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",s=24,o=Ae.random.getBytesSync(8),a=Ae.des.createEncryptionCipher;break;case"des":i="DES-CBC",s=8,o=Ae.random.getBytesSync(8),a=Ae.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+t.algorithm+'".');throw c.algorithm=t.algorithm,c}var u=Ae.pbe.opensslDeriveBytes(e,o.substr(0,8),s),l=a(u);l.start(o),l.update(W.toDer(gt.privateKeyToAsn1(r))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:Ae.util.bytesToHex(o).toUpperCase()},body:l.output.getBytes()};return Ae.pem.encode(f)};gt.decryptRsaPrivateKey=function(r,e){var t=null,n=Ae.pem.decode(r)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var o,s;switch(n.dekInfo.algorithm){case"DES-CBC":o=8,s=Ae.des.createDecryptionCipher;break;case"DES-EDE3-CBC":o=24,s=Ae.des.createDecryptionCipher;break;case"AES-128-CBC":o=16,s=Ae.aes.createDecryptionCipher;break;case"AES-192-CBC":o=24,s=Ae.aes.createDecryptionCipher;break;case"AES-256-CBC":o=32,s=Ae.aes.createDecryptionCipher;break;case"RC2-40-CBC":o=5,s=function(f){return Ae.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":o=8,s=function(f){return Ae.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":o=16,s=function(f){return Ae.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=Ae.util.hexToBytes(n.dekInfo.parameters),c=Ae.pbe.opensslDeriveBytes(e,a.substr(0,8),o),u=s(c);if(u.start(a),u.update(Ae.util.createBuffer(n.body)),u.finish())t=u.output.getBytes();else return t}else t=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?t=gt.decryptPrivateKeyInfo(W.fromDer(t),e):t=W.fromDer(t),t!==null&&(t=gt.privateKeyFromAsn1(t)),t};gt.pbe.generatePkcs12Key=function(r,e,t,n,i,o){var s,a;if(typeof o>"u"||o===null){if(!("sha1"in Ae.md))throw new Error('"sha1" hash algorithm unavailable.');o=Ae.md.sha1.create()}var c=o.digestLength,u=o.blockLength,l=new Ae.util.ByteBuffer,f=new Ae.util.ByteBuffer;if(r!=null){for(a=0;a=0;a--)N=N>>8,N+=S.at(a)+k.at(a),k.setAt(a,N&255);I.putBuffer(k)}m=I,l.putBuffer(E)}return l.truncate(l.length()-i),l};gt.pbe.getCipher=function(r,e,t){switch(r){case gt.oids.pkcs5PBES2:return gt.pbe.getCipherForPBES2(r,e,t);case gt.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case gt.oids["pbewithSHAAnd40BitRC2-CBC"]:return gt.pbe.getCipherForPKCS12PBE(r,e,t);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=r,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};gt.pbe.getCipherForPBES2=function(r,e,t){var n={},i=[];if(!W.validate(e,txe,n,i)){var o=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}if(r=W.derToOid(n.kdfOid),r!==gt.oids.pkcs5PBKDF2){var o=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw o.oid=r,o.supportedOids=["pkcs5PBKDF2"],o}if(r=W.derToOid(n.encOid),r!==gt.oids["aes128-CBC"]&&r!==gt.oids["aes192-CBC"]&&r!==gt.oids["aes256-CBC"]&&r!==gt.oids["des-EDE3-CBC"]&&r!==gt.oids.desCBC){var o=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw o.oid=r,o.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],o}var s=n.kdfSalt,a=Ae.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(gt.oids[r]){case"aes128-CBC":c=16,u=Ae.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=Ae.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=Ae.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=Ae.des.createDecryptionCipher;break;case"desCBC":c=8,u=Ae.des.createDecryptionCipher;break}var l=Lj(n.prfOid),f=Ae.pkcs5.pbkdf2(t,s,a,c,l),h=n.encIv,d=u(f);return d.start(h),d};gt.pbe.getCipherForPKCS12PBE=function(r,e,t){var n={},i=[];if(!W.validate(e,rxe,n,i)){var o=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=Ae.util.createBuffer(n.salt),a=Ae.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(r){case gt.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=Ae.des.startDecrypting;break;case gt.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(g,w){var _=Ae.rc2.createDecryptionCipher(g,40);return _.start(w,null),_};break;default:var o=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw o.oid=r,o}var f=Lj(n.prfOid),h=gt.pbe.generatePkcs12Key(t,s,1,a,c,f);f.start();var d=gt.pbe.generatePkcs12Key(t,s,2,a,u,f);return l(h,d)};gt.pbe.opensslDeriveBytes=function(r,e,t,n){if(typeof n>"u"||n===null){if(!("md5"in Ae.md))throw new Error('"md5" hash algorithm unavailable.');n=Ae.md.md5.create()}e===null&&(e="");for(var i=[Oj(n,r+e)],o=16,s=1;o{var Mr=at();Uf();gr();var Zy=EW.exports=Mr.sha512=Mr.sha512||{};Mr.md.sha512=Mr.md.algorithms.sha512=Zy;var bW=Mr.sha384=Mr.sha512.sha384=Mr.sha512.sha384||{};bW.create=function(){return Zy.create("SHA-384")};Mr.md.sha384=Mr.md.algorithms.sha384=bW;Mr.sha512.sha256=Mr.sha512.sha256||{create:function(){return Zy.create("SHA-512/256")}};Mr.md["sha512/256"]=Mr.md.algorithms["sha512/256"]=Mr.sha512.sha256;Mr.sha512.sha224=Mr.sha512.sha224||{create:function(){return Zy.create("SHA-512/224")}};Mr.md["sha512/224"]=Mr.md.algorithms["sha512/224"]=Mr.sha512.sha224;Zy.create=function(r){if(_W||Mxe(),typeof r>"u"&&(r="SHA-512"),!(r in Kh))throw new Error("Invalid SHA-512 algorithm: "+r);for(var e=Kh[r],t=null,n=Mr.util.createBuffer(),i=new Array(80),o=0;o<80;++o)i[o]=new Array(2);var s=64;switch(r){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var a={algorithm:r.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),wW(t,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=Mr.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(PC.substr(0,a.blockLength-l));for(var f,h,d=a.fullMessageLength[0]*8,p=0;p>>0,d+=h,c.putInt32(d>>>0),d=f>>>0;c.putInt32(d);for(var g=new Array(t.length),p=0;p=128;){for(R=0;R<16;++R)e[R][0]=t.getInt32()>>>0,e[R][1]=t.getInt32()>>>0;for(;R<80;++R)te=e[R-2],K=te[0],U=te[1],n=((K>>>19|U<<13)^(U>>>29|K<<3)^K>>>6)>>>0,i=((K<<13|U>>>19)^(U<<3|K>>>29)^(K<<26|U>>>6))>>>0,ae=e[R-15],K=ae[0],U=ae[1],o=((K>>>1|U<<31)^(K>>>8|U<<24)^K>>>7)>>>0,s=((K<<31|U>>>1)^(K<<24|U>>>8)^(K<<25|U>>>7))>>>0,Ce=e[R-7],$e=e[R-16],U=i+Ce[1]+s+$e[1],e[R][0]=n+Ce[0]+o+$e[0]+(U/4294967296>>>0)>>>0,e[R][1]=U>>>0;for(g=r[0][0],w=r[0][1],_=r[1][0],x=r[1][1],m=r[2][0],y=r[2][1],b=r[3][0],E=r[3][1],v=r[4][0],S=r[4][1],A=r[5][0],I=r[5][1],k=r[6][0],N=r[6][1],O=r[7][0],G=r[7][1],R=0;R<80;++R)u=((v>>>14|S<<18)^(v>>>18|S<<14)^(S>>>9|v<<23))>>>0,l=((v<<18|S>>>14)^(v<<14|S>>>18)^(S<<23|v>>>9))>>>0,f=(k^v&(A^k))>>>0,h=(N^S&(I^N))>>>0,a=((g>>>28|w<<4)^(w>>>2|g<<30)^(w>>>7|g<<25))>>>0,c=((g<<4|w>>>28)^(w<<30|g>>>2)^(w<<25|g>>>7))>>>0,d=(g&_|m&(g^_))>>>0,p=(w&x|y&(w^x))>>>0,U=G+l+h+kC[R][1]+e[R][1],n=O+u+f+kC[R][0]+e[R][0]+(U/4294967296>>>0)>>>0,i=U>>>0,U=c+p,o=a+d+(U/4294967296>>>0)>>>0,s=U>>>0,O=k,G=N,k=A,N=I,A=v,I=S,U=E+i,v=b+n+(U/4294967296>>>0)>>>0,S=U>>>0,b=m,E=y,m=_,y=x,_=g,x=w,U=i+s,g=n+o+(U/4294967296>>>0)>>>0,w=U>>>0;U=r[0][1]+w,r[0][0]=r[0][0]+g+(U/4294967296>>>0)>>>0,r[0][1]=U>>>0,U=r[1][1]+x,r[1][0]=r[1][0]+_+(U/4294967296>>>0)>>>0,r[1][1]=U>>>0,U=r[2][1]+y,r[2][0]=r[2][0]+m+(U/4294967296>>>0)>>>0,r[2][1]=U>>>0,U=r[3][1]+E,r[3][0]=r[3][0]+b+(U/4294967296>>>0)>>>0,r[3][1]=U>>>0,U=r[4][1]+S,r[4][0]=r[4][0]+v+(U/4294967296>>>0)>>>0,r[4][1]=U>>>0,U=r[5][1]+I,r[5][0]=r[5][0]+A+(U/4294967296>>>0)>>>0,r[5][1]=U>>>0,U=r[6][1]+N,r[6][0]=r[6][0]+k+(U/4294967296>>>0)>>>0,r[6][1]=U>>>0,U=r[7][1]+G,r[7][0]=r[7][0]+O+(U/4294967296>>>0)>>>0,r[7][1]=U>>>0,He-=128}}});var iY=P((kst,nY)=>{"use strict";nY.exports=si;var l3=Gh();function si(r,e){this.lo=r>>>0,this.hi=e>>>0}var Hh=si.zero=new si(0,0);Hh.toNumber=function(){return 0};Hh.zzEncode=Hh.zzDecode=function(){return this};Hh.length=function(){return 1};var hSe=si.zeroHash="\0\0\0\0\0\0\0\0";si.fromNumber=function(e){if(e===0)return Hh;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new si(n,i)};si.from=function(e){if(typeof e=="number")return si.fromNumber(e);if(l3.isString(e))if(l3.Long)e=l3.Long.fromString(e);else return si.fromNumber(parseInt(e,10));return e.low||e.high?new si(e.low>>>0,e.high>>>0):Hh};si.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};si.prototype.toLong=function(e){return l3.Long?new l3.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Qf=String.prototype.charCodeAt;si.fromHash=function(e){return e===hSe?Hh:new si((Qf.call(e,0)|Qf.call(e,1)<<8|Qf.call(e,2)<<16|Qf.call(e,3)<<24)>>>0,(Qf.call(e,4)|Qf.call(e,5)<<8|Qf.call(e,6)<<16|Qf.call(e,7)<<24)>>>0)};si.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};si.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};si.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};si.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var Gh=P(WC=>{"use strict";var Me=WC;Me.asPromise=N6();Me.base64=O6();Me.EventEmitter=B6();Me.float=M6();Me.inquire=U6();Me.utf8=F6();Me.pool=z6();Me.LongBits=iY();Me.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Me.global=Me.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||WC;Me.emptyArray=Object.freeze?Object.freeze([]):[];Me.emptyObject=Object.freeze?Object.freeze({}):{};Me.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Me.isString=function(e){return typeof e=="string"||e instanceof String};Me.isObject=function(e){return e&&typeof e=="object"};Me.isset=Me.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Me.Buffer=function(){try{var r=Me.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Me._Buffer_from=null;Me._Buffer_allocUnsafe=null;Me.newBuffer=function(e){return typeof e=="number"?Me.Buffer?Me._Buffer_allocUnsafe(e):new Me.Array(e):Me.Buffer?Me._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Me.Array=typeof Uint8Array<"u"?Uint8Array:Array;Me.Long=Me.global.dcodeIO&&Me.global.dcodeIO.Long||Me.global.Long||Me.inquire("long");Me.key2Re=/^true|false|0|1$/;Me.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Me.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Me.longToHash=function(e){return e?Me.LongBits.from(e).toHash():Me.LongBits.zeroHash};Me.longFromHash=function(e,t){var n=Me.LongBits.fromHash(e);return Me.Long?Me.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function oY(r,e,t){for(var n=Object.keys(e),i=0;i-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Me.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";fY.exports=wn;var Ka=Gh(),QC,uY=Ka.LongBits,pSe=Ka.utf8;function $a(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function wn(r){this.buf=r,this.pos=0,this.len=r.length}var aY=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new wn(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new wn(e);throw Error("illegal buffer")},lY=function(){return Ka.Buffer?function(t){return(wn.create=function(i){return Ka.Buffer.isBuffer(i)?new QC(i):aY(i)})(t)}:aY};wn.create=lY();wn.prototype._slice=Ka.Array.prototype.subarray||Ka.Array.prototype.slice;wn.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,$a(this,10);return e}}();wn.prototype.int32=function(){return this.uint32()|0};wn.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function YC(){var r=new uY(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw $a(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw $a(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}wn.prototype.bool=function(){return this.uint32()!==0};function Jb(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}wn.prototype.fixed32=function(){if(this.pos+4>this.len)throw $a(this,4);return Jb(this.buf,this.pos+=4)};wn.prototype.sfixed32=function(){if(this.pos+4>this.len)throw $a(this,4);return Jb(this.buf,this.pos+=4)|0};function cY(){if(this.pos+8>this.len)throw $a(this,8);return new uY(Jb(this.buf,this.pos+=4),Jb(this.buf,this.pos+=4))}wn.prototype.float=function(){if(this.pos+4>this.len)throw $a(this,4);var e=Ka.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};wn.prototype.double=function(){if(this.pos+8>this.len)throw $a(this,4);var e=Ka.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};wn.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw $a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var i=Ka.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)};wn.prototype.string=function(){var e=this.bytes();return pSe.read(e,0,e.length)};wn.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw $a(this,e);this.pos+=e}else do if(this.pos>=this.len)throw $a(this);while(this.buf[this.pos++]&128);return this};wn.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};wn._configure=function(r){QC=r,wn.create=lY(),QC._configure();var e=Ka.Long?"toLong":"toNumber";Ka.merge(wn.prototype,{int64:function(){return YC.call(this)[e](!1)},uint64:function(){return YC.call(this)[e](!0)},sint64:function(){return YC.call(this).zzDecode()[e](!1)},fixed64:function(){return cY.call(this)[e](!0)},sfixed64:function(){return cY.call(this)[e](!1)}})}});var mY=P((Ost,pY)=>{"use strict";pY.exports=jh;var hY=XC();(jh.prototype=Object.create(hY.prototype)).constructor=jh;var dY=Gh();function jh(r){hY.call(this,r)}jh._configure=function(){dY.Buffer&&(jh.prototype._slice=dY.Buffer.prototype.slice)};jh.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))};jh._configure()});var iP=P((Lst,bY)=>{"use strict";bY.exports=Wt;var Ms=Gh(),ZC,e_=Ms.LongBits,gY=Ms.base64,yY=Ms.utf8;function f3(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function eP(){}function mSe(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Wt(){this.len=0,this.head=new f3(eP,0,0),this.tail=this.head,this.states=null}var wY=function(){return Ms.Buffer?function(){return(Wt.create=function(){return new ZC})()}:function(){return new Wt}};Wt.create=wY();Wt.alloc=function(e){return new Ms.Array(e)};Ms.Array!==Array&&(Wt.alloc=Ms.pool(Wt.alloc,Ms.Array.prototype.subarray));Wt.prototype._push=function(e,t,n){return this.tail=this.tail.next=new f3(e,t,n),this.len+=t,this};function tP(r,e,t){e[t]=r&255}function gSe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function rP(r,e){this.len=r,this.next=void 0,this.val=e}rP.prototype=Object.create(f3.prototype);rP.prototype.fn=gSe;Wt.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new rP((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Wt.prototype.int32=function(e){return e<0?this._push(nP,10,e_.fromNumber(e)):this.uint32(e)};Wt.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function nP(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Wt.prototype.uint64=function(e){var t=e_.from(e);return this._push(nP,t.length(),t)};Wt.prototype.int64=Wt.prototype.uint64;Wt.prototype.sint64=function(e){var t=e_.from(e).zzEncode();return this._push(nP,t.length(),t)};Wt.prototype.bool=function(e){return this._push(tP,1,e?1:0)};function JC(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Wt.prototype.fixed32=function(e){return this._push(JC,4,e>>>0)};Wt.prototype.sfixed32=Wt.prototype.fixed32;Wt.prototype.fixed64=function(e){var t=e_.from(e);return this._push(JC,4,t.lo)._push(JC,4,t.hi)};Wt.prototype.sfixed64=Wt.prototype.fixed64;Wt.prototype.float=function(e){return this._push(Ms.float.writeFloatLE,4,e)};Wt.prototype.double=function(e){return this._push(Ms.float.writeDoubleLE,8,e)};var ySe=Ms.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(tP,1,0);if(Ms.isString(e)){var n=Wt.alloc(t=gY.length(e));gY.decode(e,n,0),e=n}return this.uint32(t)._push(ySe,t,e)};Wt.prototype.string=function(e){var t=yY.length(e);return t?this.uint32(t)._push(yY.write,t,e):this._push(tP,1,0)};Wt.prototype.fork=function(){return this.states=new mSe(this),this.head=this.tail=new f3(eP,0,0),this.len=0,this};Wt.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 f3(eP,0,0),this.len=0),this};Wt.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Wt.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Wt._configure=function(r){ZC=r,Wt.create=wY(),ZC._configure()}});var vY=P((Bst,EY)=>{"use strict";EY.exports=Fc;var _Y=iP();(Fc.prototype=Object.create(_Y.prototype)).constructor=Fc;var Xf=Gh();function Fc(){_Y.call(this)}Fc._configure=function(){Fc.alloc=Xf._Buffer_allocUnsafe,Fc.writeBytesBuffer=Xf.Buffer&&Xf.Buffer.prototype instanceof Uint8Array&&Xf.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(Fc.writeBytesBuffer,t,e),this};function wSe(r,e,t){r.length<40?Xf.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}Fc.prototype.string=function(e){var t=Xf.Buffer.byteLength(e);return this.uint32(t),t&&this._push(wSe,t,e),this};Fc._configure()});var QQ=P((aut,YQ)=>{var gm=1e3,ym=gm*60,wm=ym*60,Xh=wm*24,aAe=Xh*7,cAe=Xh*365.25;YQ.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return uAe(r);if(t==="number"&&isFinite(r))return e.long?fAe(r):lAe(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function uAe(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*cAe;case"weeks":case"week":case"w":return t*aAe;case"days":case"day":case"d":return t*Xh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*wm;case"minutes":case"minute":case"mins":case"min":case"m":return t*ym;case"seconds":case"second":case"secs":case"sec":case"s":return t*gm;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function lAe(r){var e=Math.abs(r);return e>=Xh?Math.round(r/Xh)+"d":e>=wm?Math.round(r/wm)+"h":e>=ym?Math.round(r/ym)+"m":e>=gm?Math.round(r/gm)+"s":r+"ms"}function fAe(r){var e=Math.abs(r);return e>=Xh?b_(r,e,Xh,"day"):e>=wm?b_(r,e,wm,"hour"):e>=ym?b_(r,e,ym,"minute"):e>=gm?b_(r,e,gm,"second"):r+" ms"}function b_(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ZQ=P((cut,XQ)=>{function dAe(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=QQ(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let h=0;h{if(E==="%%")return"%";y++;let S=t.formatters[v];if(typeof S=="function"){let A=w[y];E=S.call(_,A),w.splice(y,1),y--}return E}),t.formatArgs.call(_,w),(_.log||t.log).apply(_,w)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:w=>{h=w}}),typeof t.init=="function"&&t.init(g),g}function n(l,f){let h=t(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=t.skips.length;f{Yo.formatArgs=pAe;Yo.save=mAe;Yo.load=gAe;Yo.useColors=hAe;Yo.storage=yAe();Yo.destroy=(()=>{let r=!1;return()=>{r||(r=!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`."))}})();Yo.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"];function hAe(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function pAe(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+__.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Yo.log=console.debug||console.log||(()=>{});function mAe(r){try{r?Yo.storage.setItem("debug",r):Yo.storage.removeItem("debug")}catch{}}function gAe(){let r;try{r=Yo.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function yAe(){try{return localStorage}catch{}}__.exports=ZQ()(Yo);var{formatters:wAe}=__.exports;wAe.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var v_=P((RP,CP)=>{(function(r,e){typeof RP=="object"&&typeof CP<"u"?CP.exports=function(t,n,i,o,s){for(n=n.split?n.split("."):n,o=0;o{"use strict";var RAe=/^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.){0,126}(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9]))\.?$/i;uX.exports=function(e,t){if(t==null&&(t=!1),e.length<2||e.length>255)return!1;var n=e[e.length-1];if(t){if(n!==".")return!1}else if(n===".")return!1;return RAe.test(e)}});var MX=P((Ldt,BX)=>{BX.exports=qP;var LX=128,jAe=127,WAe=~jAe,YAe=Math.pow(2,31);function qP(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw qP.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=YAe;)e[t++]=r&255|LX,r/=128;for(;r&WAe;)e[t++]=r&255|LX,r>>>=7;return e[t]=r|0,qP.bytes=t-n+1,e}});var zX=P((Bdt,FX)=>{FX.exports=HP;var QAe=128,UX=127;function HP(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw HP.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&UX)<=QAe);return HP.bytes=o-n,t}});var KX=P((Mdt,VX)=>{var XAe=Math.pow(2,7),ZAe=Math.pow(2,14),JAe=Math.pow(2,21),eTe=Math.pow(2,28),tTe=Math.pow(2,35),rTe=Math.pow(2,42),nTe=Math.pow(2,49),iTe=Math.pow(2,56),oTe=Math.pow(2,63);VX.exports=function(r){return r{$X.exports={encode:MX(),decode:zX(),encodingLength:KX()}});var pZ=P((z3,Y_)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(d){if(!Array.isArray(d)&&!ArrayBuffer.isView(d))return!1;for(var p=0;p255)return!1;return!0}function i(d,p){return(d&65535)*p+(((d>>>16)*p&65535)<<16)}function o(d,p){return d<>>32-p}function s(d){return d^=d>>>16,d=i(d,2246822507),d^=d>>>13,d=i(d,3266489909),d^=d>>>16,d}function a(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var g=[0,0,0,0];return g[3]+=d[3]+p[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=d[2]+p[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=d[1]+p[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=d[0]+p[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function c(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var g=[0,0,0,0];return g[3]+=d[3]*p[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=d[2]*p[3],g[1]+=g[2]>>>16,g[2]&=65535,g[2]+=d[3]*p[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=d[1]*p[3],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=d[2]*p[2],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=d[3]*p[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=d[0]*p[3]+d[1]*p[2]+d[2]*p[1]+d[3]*p[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function u(d,p){return p%=64,p===32?[d[1],d[0]]:p<32?[d[0]<>>32-p,d[1]<>>32-p]:(p-=32,[d[1]<>>32-p,d[0]<>>32-p])}function l(d,p){return p%=64,p===0?d:p<32?[d[0]<>>32-p,d[1]<>>1]),d=c(d,[4283543511,3981806797]),d=f(d,[0,d[0]>>>1]),d=c(d,[3301882366,444984403]),d=f(d,[0,d[0]>>>1]),d}t.x86.hash32=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var g=d.length%4,w=d.length-g,_=p,x=0,m=3432918353,y=461845907,b=0;b>>0},t.x86.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var g=d.length%16,w=d.length-g,_=p,x=p,m=p,y=p,b=0,E=0,v=0,S=0,A=597399067,I=2869860233,k=951274213,N=2716044179,O=0;O>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)},t.x64.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var g=d.length%16,w=d.length-g,_=[0,p],x=[0,p],m=[0,0],y=[0,0],b=[2277735313,289559509],E=[1291169091,658871167],v=0;v>>0).toString(16)).slice(-8)+("00000000"+(_[1]>>>0).toString(16)).slice(-8)+("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)},typeof z3<"u"?(typeof Y_<"u"&&Y_.exports&&(z3=Y_.exports=t),z3.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(z3)});var nk=P((Apt,mZ)=>{mZ.exports=pZ()});var RZ=P((f0t,IZ)=>{var ok=class{constructor(e,t=12,n=8*1024,i=32*1024,o=64,s){this.bits=t,this.min=n,this.max=i,this.asModule=e,this.rabin=new e.Rabin(t,n,i,o,s),this.polynomial=s}fingerprint(e){let{__retain:t,__release:n,__allocArray:i,__getInt32Array:o,Int32Array_ID:s,Uint8Array_ID:a}=this.asModule,c=new Int32Array(Math.ceil(e.length/this.min)),u=t(i(s,c)),l=t(i(a,e)),f=this.rabin.fingerprint(l,u),h=o(f);n(l),n(u);let d=h.indexOf(0);return d>=0?h.subarray(0,d):h}};IZ.exports=ok});var OZ=P(q3=>{"use strict";var UTe=typeof BigUint64Array<"u",K3=Symbol(),$3=1024;function CZ(r,e){let t=new Uint32Array(r),n=new Uint16Array(r);var i=t[e+-4>>>2]>>>1,o=e>>>1;if(i<=$3)return String.fromCharCode.apply(String,n.subarray(o,o+i));let s=[];do{let a=n[o+$3-1],c=a>=55296&&a<56320?$3-1:$3;s.push(String.fromCharCode.apply(String,n.subarray(o,o+=c))),i-=c}while(i>$3);return s.join("")+String.fromCharCode.apply(String,n.subarray(o,o+i))}function sk(r){let e={};function t(i,o){return i?CZ(i.buffer,o):""}let n=r.env=r.env||{};return n.abort=n.abort||function(o,s,a,c){let u=e.memory||n.memory;throw Error("abort: "+t(u,o)+" at "+t(u,s)+":"+a+":"+c)},n.trace=n.trace||function(o,s){let a=e.memory||n.memory;console.log("trace: "+t(a,o)+(s?" ":"")+Array.prototype.slice.call(arguments,2,2+s).join(", "))},r.Math=r.Math||Math,r.Date=r.Date||Date,e}function ak(r,e){let t=e.exports,n=t.memory,i=t.table,o=t.__alloc,s=t.__retain,a=t.__rtti_base||-1;function c(E){let v=new Uint32Array(n.buffer),S=v[a>>>2];if((E>>>=0)>=S)throw Error("invalid id: "+E);return v[(a+4>>>2)+E*2]}function u(E){let v=new Uint32Array(n.buffer),S=v[a>>>2];if((E>>>=0)>=S)throw Error("invalid id: "+E);return v[(a+4>>>2)+E*2+1]}function l(E){return 31-Math.clz32(E>>>5&31)}function f(E){return 31-Math.clz32(E>>>14&31)}function h(E){let v=E.length,S=o(v<<1,1),A=new Uint16Array(n.buffer);for(var I=0,k=S>>>1;I>>2]!==1)throw Error("not a string: "+E);return CZ(v,E)}r.__getString=d;function p(E,v,S){let A=n.buffer;if(S)switch(E){case 2:return new Float32Array(A);case 3:return new Float64Array(A)}else switch(E){case 0:return new(v?Int8Array:Uint8Array)(A);case 1:return new(v?Int16Array:Uint16Array)(A);case 2:return new(v?Int32Array:Uint32Array)(A);case 3:return new(v?BigInt64Array:BigUint64Array)(A)}throw Error("unsupported align: "+E)}function g(E,v){let S=c(E);if(!(S&3))throw Error("not an array: "+E+" @ "+S);let A=l(S),I=v.length,k=o(I<>>2]=s(k),O[N+4>>>2]=k,O[N+8>>>2]=I<>>2]=I);let G=p(A,S&1024,S&2048);if(S&8192)for(let R=0;R>>A)+R]=s(v[R]);else G.set(v,k>>>A);return N}r.__allocArray=g;function w(E){let v=new Uint32Array(n.buffer),S=v[E+-8>>>2],A=c(S);if(!(A&1))throw Error("not an array: "+S);let I=l(A);var k=v[E+4>>>2];let N=A&2?v[E+12>>>2]:v[k+-4>>>2]>>>I;return p(I,A&1024,A&2048).subarray(k>>>=I,k+N)}r.__getArrayView=w;function _(E){let v=w(E),S=v.length,A=new Array(S);for(let I=0;I>>2];return v.slice(E,E+S)}r.__getArrayBuffer=x;function m(E,v,S){return new E(y(E,v,S))}function y(E,v,S){let A=n.buffer,I=new Uint32Array(A),k=I[S+4>>>2];return new E(A,k,I[k+-4>>>2]>>>v)}r.__getInt8Array=m.bind(null,Int8Array,0),r.__getInt8ArrayView=y.bind(null,Int8Array,0),r.__getUint8Array=m.bind(null,Uint8Array,0),r.__getUint8ArrayView=y.bind(null,Uint8Array,0),r.__getUint8ClampedArray=m.bind(null,Uint8ClampedArray,0),r.__getUint8ClampedArrayView=y.bind(null,Uint8ClampedArray,0),r.__getInt16Array=m.bind(null,Int16Array,1),r.__getInt16ArrayView=y.bind(null,Int16Array,1),r.__getUint16Array=m.bind(null,Uint16Array,1),r.__getUint16ArrayView=y.bind(null,Uint16Array,1),r.__getInt32Array=m.bind(null,Int32Array,2),r.__getInt32ArrayView=y.bind(null,Int32Array,2),r.__getUint32Array=m.bind(null,Uint32Array,2),r.__getUint32ArrayView=y.bind(null,Uint32Array,2),UTe&&(r.__getInt64Array=m.bind(null,BigInt64Array,3),r.__getInt64ArrayView=y.bind(null,BigInt64Array,3),r.__getUint64Array=m.bind(null,BigUint64Array,3),r.__getUint64ArrayView=y.bind(null,BigUint64Array,3)),r.__getFloat32Array=m.bind(null,Float32Array,2),r.__getFloat32ArrayView=y.bind(null,Float32Array,2),r.__getFloat64Array=m.bind(null,Float64Array,3),r.__getFloat64ArrayView=y.bind(null,Float64Array,3);function b(E,v){let S=new Uint32Array(n.buffer);var A=S[E+-8>>>2];if(A<=S[a>>>2])do if(A==v)return!0;while(A=u(A));return!1}return r.__instanceof=b,r.memory=r.memory||n,r.table=r.table||i,DZ(t,r)}function PZ(r){return typeof Response<"u"&&r instanceof Response}async function kZ(r,e){return PZ(r=await r)?NZ(r,e):ak(sk(e||(e={})),await WebAssembly.instantiate(r instanceof WebAssembly.Module?r:await WebAssembly.compile(r),e))}q3.instantiate=kZ;function FTe(r,e){return ak(sk(e||(e={})),new WebAssembly.Instance(r instanceof WebAssembly.Module?r:new WebAssembly.Module(r),e))}q3.instantiateSync=FTe;async function NZ(r,e){return WebAssembly.instantiateStreaming?ak(sk(e||(e={})),(await WebAssembly.instantiateStreaming(r,e)).instance):kZ(PZ(r=await r)?r.arrayBuffer():r,e)}q3.instantiateStreaming=NZ;function DZ(r,e){var t=e?Object.create(e):{},n=r.__argumentsLength?function(i){r.__argumentsLength.value=i}:r.__setArgumentsLength||r.__setargc||function(){};for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let o=r[i],s=i.split("."),a=t;for(;s.length>1;){let l=s.shift();Object.prototype.hasOwnProperty.call(a,l)||(a[l]={}),a=a[l]}let c=s[0],u=c.indexOf("#");if(u>=0){let l=c.substring(0,u),f=a[l];if(typeof f>"u"||!f.prototype){let h=function(...d){return h.wrap(h.prototype.constructor(0,...d))};h.prototype={valueOf:function(){return this[K3]}},h.wrap=function(d){return Object.create(h.prototype,{[K3]:{value:d,writable:!1}})},f&&Object.getOwnPropertyNames(f).forEach(d=>Object.defineProperty(h,d,Object.getOwnPropertyDescriptor(f,d))),a[l]=h}if(c=c.substring(u+1),a=a[l].prototype,/^(get|set):/.test(c)){if(!Object.prototype.hasOwnProperty.call(a,c=c.substring(4))){let h=r[i.replace("set:","get:")],d=r[i.replace("get:","set:")];Object.defineProperty(a,c,{get:function(){return h(this[K3])},set:function(p){d(this[K3],p)},enumerable:!0})}}else c==="constructor"?(a[c]=(...h)=>(n(h.length),o(...h))).original=o:(a[c]=function(...h){return n(h.length),o(this[K3],...h)}).original=o}else/^(get|set):/.test(c)?Object.prototype.hasOwnProperty.call(a,c=c.substring(4))||Object.defineProperty(a,c,{get:r[i.replace("set:","get:")],set:r[i.replace("get:","set:")],enumerable:!0}):typeof o=="function"&&o!==n?(a[c]=(...l)=>(n(l.length),o(...l))).original=o:a[c]=o}return t}q3.demangle=DZ});var BZ=P((h0t,LZ)=>{var{instantiate:zTe}=OZ();ck.supported=typeof WebAssembly<"u";function ck(r={}){if(!ck.supported)return null;var e=new Uint8Array([0,97,115,109,1,0,0,0,1,78,14,96,2,127,126,0,96,1,127,1,126,96,2,127,127,0,96,1,127,1,127,96,1,127,0,96,2,127,127,1,127,96,3,127,127,127,1,127,96,0,0,96,3,127,127,127,0,96,0,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,1,127,96,1,126,1,127,96,2,126,126,1,126,2,13,1,3,101,110,118,5,97,98,111,114,116,0,10,3,54,53,2,2,8,9,3,5,2,8,6,5,3,4,2,6,9,12,13,2,5,11,3,2,3,2,3,2,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,6,7,7,4,4,5,3,1,0,1,6,47,9,127,1,65,0,11,127,1,65,0,11,127,0,65,3,11,127,0,65,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,240,2,11,127,0,65,6,11,7,240,5,41,6,109,101,109,111,114,121,2,0,7,95,95,97,108,108,111,99,0,10,8,95,95,114,101,116,97,105,110,0,11,9,95,95,114,101,108,101,97,115,101,0,12,9,95,95,99,111,108,108,101,99,116,0,51,11,95,95,114,116,116,105,95,98,97,115,101,3,7,13,73,110,116,51,50,65,114,114,97,121,95,73,68,3,2,13,85,105,110,116,56,65,114,114,97,121,95,73,68,3,3,6,100,101,103,114,101,101,0,16,3,109,111,100,0,17,5,82,97,98,105,110,3,8,16,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,0,21,16,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,0,22,21,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,23,21,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,24,14,82,97,98,105,110,35,103,101,116,58,119,112,111,115,0,25,14,82,97,98,105,110,35,115,101,116,58,119,112,111,115,0,26,15,82,97,98,105,110,35,103,101,116,58,99,111,117,110,116,0,27,15,82,97,98,105,110,35,115,101,116,58,99,111,117,110,116,0,28,13,82,97,98,105,110,35,103,101,116,58,112,111,115,0,29,13,82,97,98,105,110,35,115,101,116,58,112,111,115,0,30,15,82,97,98,105,110,35,103,101,116,58,115,116,97,114,116,0,31,15,82,97,98,105,110,35,115,101,116,58,115,116,97,114,116,0,32,16,82,97,98,105,110,35,103,101,116,58,100,105,103,101,115,116,0,33,16,82,97,98,105,110,35,115,101,116,58,100,105,103,101,115,116,0,34,21,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,35,21,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,36,22,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,37,22,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,38,31,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,39,31,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,40,20,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,0,41,20,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,0,42,17,82,97,98,105,110,35,103,101,116,58,109,105,110,115,105,122,101,0,43,17,82,97,98,105,110,35,115,101,116,58,109,105,110,115,105,122,101,0,44,17,82,97,98,105,110,35,103,101,116,58,109,97,120,115,105,122,101,0,45,17,82,97,98,105,110,35,115,101,116,58,109,97,120,115,105,122,101,0,46,14,82,97,98,105,110,35,103,101,116,58,109,97,115,107,0,47,14,82,97,98,105,110,35,115,101,116,58,109,97,115,107,0,48,17,82,97,98,105,110,35,99,111,110,115,116,114,117,99,116,111,114,0,20,17,82,97,98,105,110,35,102,105,110,103,101,114,112,114,105,110,116,0,49,8,1,50,10,165,31,53,199,1,1,4,127,32,1,40,2,0,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,3,65,4,107,118,65,16,115,33,4,32,3,65,7,107,11,33,3,32,1,40,2,20,33,2,32,1,40,2,16,34,5,4,64,32,5,32,2,54,2,20,11,32,2,4,64,32,2,32,5,54,2,16,11,32,1,32,0,32,4,32,3,65,4,116,106,65,2,116,106,40,2,96,70,4,64,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,2,54,2,96,32,2,69,4,64,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,65,127,115,113,34,1,54,2,4,32,1,69,4,64,32,0,32,0,40,2,0,65,1,32,3,116,65,127,115,113,54,2,0,11,11,11,11,226,2,1,6,127,32,1,40,2,0,33,3,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,5,65,1,113,4,64,32,3,65,124,113,65,16,106,32,5,65,124,113,106,34,2,65,240,255,255,255,3,73,4,64,32,0,32,4,16,1,32,1,32,2,32,3,65,3,113,114,34,3,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,5,11,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,2,40,2,0,34,6,65,124,113,65,16,106,32,3,65,124,113,106,34,7,65,240,255,255,255,3,73,4,64,32,0,32,2,16,1,32,2,32,7,32,6,65,3,113,114,34,3,54,2,0,32,2,33,1,11,11,32,4,32,5,65,2,114,54,2,0,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,2,65,4,107,118,65,16,115,33,4,32,2,65,7,107,11,34,3,65,4,116,32,4,106,65,2,116,106,40,2,96,33,2,32,1,65,0,54,2,16,32,1,32,2,54,2,20,32,2,4,64,32,2,32,1,54,2,16,11,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,3,116,114,54,2,0,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,114,54,2,4,11,119,1,1,127,32,2,2,127,32,0,40,2,160,12,34,2,4,64,32,2,32,1,65,16,107,70,4,64,32,2,40,2,0,33,3,32,1,65,16,107,33,1,11,11,32,1,11,107,34,2,65,48,73,4,64,15,11,32,1,32,3,65,2,113,32,2,65,32,107,65,1,114,114,54,2,0,32,1,65,0,54,2,16,32,1,65,0,54,2,20,32,1,32,2,106,65,16,107,34,2,65,2,54,2,0,32,0,32,2,54,2,160,12,32,0,32,1,16,2,11,155,1,1,3,127,35,0,34,0,69,4,64,65,1,63,0,34,0,74,4,127,65,1,32,0,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,176,3,34,0,65,0,54,2,0,65,208,15,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,176,3,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,176,3,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,176,3,65,224,15,63,0,65,16,116,16,3,65,176,3,36,0,11,32,0,11,45,0,32,0,65,240,255,255,255,3,79,4,64,65,32,65,224,0,65,201,3,65,29,16,0,0,11,32,0,65,15,106,65,112,113,34,0,65,16,32,0,65,16,75,27,11,169,1,1,1,127,32,0,32,1,65,128,2,73,4,127,32,1,65,4,118,33,1,65,0,5,32,1,65,248,255,255,255,1,73,4,64,32,1,65,1,65,27,32,1,103,107,116,106,65,1,107,33,1,11,32,1,65,31,32,1,103,107,34,2,65,4,107,118,65,16,115,33,1,32,2,65,7,107,11,34,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,111,1,1,127,63,0,34,2,32,1,65,248,255,255,255,1,73,4,127,32,1,65,1,65,27,32,1,103,107,116,65,1,107,106,5,32,1,11,65,16,32,0,40,2,160,12,32,2,65,16,116,65,16,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,32,0,32,2,65,16,116,63,0,65,16,116,16,3,11,113,1,2,127,32,1,40,2,0,34,3,65,124,113,32,2,107,34,4,65,32,79,4,64,32,1,32,2,32,3,65,2,113,114,54,2,0,32,2,32,1,65,16,106,106,34,1,32,4,65,16,107,65,1,114,54,2,0,32,0,32,1,16,2,5,32,1,32,3,65,126,113,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,32,1,65,16,106,32,1,40,2,0,65,124,113,106,40,2,0,65,125,113,54,2,0,11,11,91,1,2,127,32,0,32,1,16,5,34,4,16,6,34,3,69,4,64,65,1,36,1,65,0,36,1,32,0,32,4,16,6,34,3,69,4,64,32,0,32,4,16,7,32,0,32,4,16,6,33,3,11,11,32,3,65,0,54,2,4,32,3,32,2,54,2,8,32,3,32,1,54,2,12,32,0,32,3,16,1,32,0,32,3,32,4,16,8,32,3,11,13,0,16,4,32,0,32,1,16,9,65,16,106,11,33,1,1,127,32,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,18,0,32,0,65,172,3,75,4,64,32,0,65,16,107,16,52,11,11,140,3,1,1,127,2,64,32,1,69,13,0,32,0,65,0,58,0,0,32,0,32,1,106,65,1,107,65,0,58,0,0,32,1,65,2,77,13,0,32,0,65,1,106,65,0,58,0,0,32,0,65,2,106,65,0,58,0,0,32,0,32,1,106,34,2,65,2,107,65,0,58,0,0,32,2,65,3,107,65,0,58,0,0,32,1,65,6,77,13,0,32,0,65,3,106,65,0,58,0,0,32,0,32,1,106,65,4,107,65,0,58,0,0,32,1,65,8,77,13,0,32,1,65,0,32,0,107,65,3,113,34,1,107,33,2,32,0,32,1,106,34,0,65,0,54,2,0,32,0,32,2,65,124,113,34,1,106,65,4,107,65,0,54,2,0,32,1,65,8,77,13,0,32,0,65,4,106,65,0,54,2,0,32,0,65,8,106,65,0,54,2,0,32,0,32,1,106,34,2,65,12,107,65,0,54,2,0,32,2,65,8,107,65,0,54,2,0,32,1,65,24,77,13,0,32,0,65,12,106,65,0,54,2,0,32,0,65,16,106,65,0,54,2,0,32,0,65,20,106,65,0,54,2,0,32,0,65,24,106,65,0,54,2,0,32,0,32,1,106,34,2,65,28,107,65,0,54,2,0,32,2,65,24,107,65,0,54,2,0,32,2,65,20,107,65,0,54,2,0,32,2,65,16,107,65,0,54,2,0,32,0,32,0,65,4,113,65,24,106,34,2,106,33,0,32,1,32,2,107,33,1,3,64,32,1,65,32,79,4,64,32,0,66,0,55,3,0,32,0,65,8,106,66,0,55,3,0,32,0,65,16,106,66,0,55,3,0,32,0,65,24,106,66,0,55,3,0,32,1,65,32,107,33,1,32,0,65,32,106,33,0,12,1,11,11,11,11,178,1,1,3,127,32,1,65,240,255,255,255,3,32,2,118,75,4,64,65,144,1,65,192,1,65,23,65,56,16,0,0,11,32,1,32,2,116,34,3,65,0,16,10,34,2,32,3,16,13,32,0,69,4,64,65,12,65,2,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,2,34,1,32,0,40,2,0,34,4,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,32,4,16,12,11,32,0,32,1,54,2,0,32,0,32,2,54,2,4,32,0,32,3,54,2,8,32,0,11,46,1,2,127,65,12,65,5,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,65,128,2,65,3,16,14,11,9,0,65,63,32,0,121,167,107,11,49,1,2,127,65,63,32,1,121,167,107,33,2,3,64,65,63,32,0,121,167,107,32,2,107,34,3,65,0,78,4,64,32,0,32,1,32,3,172,134,133,33,0,12,1,11,11,32,0,11,40,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,163,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,65,0,58,0,0,11,38,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,152,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,45,0,0,11,254,5,2,1,127,4,126,32,0,69,4,64,65,232,0,65,6,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,24,32,0,66,0,55,3,32,32,0,66,0,55,3,40,32,0,66,0,55,3,48,32,0,66,0,55,3,56,32,0,66,0,55,3,64,32,0,66,0,55,3,72,32,0,66,0,55,3,80,32,0,66,0,55,3,88,32,0,66,0,55,3,96,32,0,32,2,173,55,3,80,32,0,32,3,173,55,3,88,65,12,65,4,16,10,34,2,65,172,3,75,4,64,32,2,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,32,4,65,0,16,14,33,2,32,0,40,2,0,16,12,32,0,32,2,54,2,0,32,0,32,4,54,2,4,32,0,66,1,32,1,173,134,66,1,125,55,3,96,32,0,66,243,130,183,218,216,230,232,30,55,3,72,35,4,69,4,64,65,0,33,2,3,64,32,2,65,128,2,72,4,64,32,2,65,255,1,113,173,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,65,0,33,4,3,64,32,4,32,0,40,2,4,65,1,107,72,4,64,32,6,66,8,134,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,32,4,65,1,106,33,4,12,1,11,11,35,6,40,2,4,32,2,65,3,116,106,32,6,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,63,32,0,41,3,72,121,167,107,172,33,7,65,0,33,2,3,64,32,2,65,128,2,72,4,64,35,5,33,1,32,2,172,32,7,134,34,8,33,6,65,63,32,0,41,3,72,34,9,121,167,107,33,3,3,64,65,63,32,6,121,167,107,32,3,107,34,4,65,0,78,4,64,32,6,32,9,32,4,172,134,133,33,6,12,1,11,11,32,1,40,2,4,32,2,65,3,116,106,32,6,32,8,132,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,1,36,4,11,32,0,66,0,55,3,24,32,0,66,0,55,3,32,65,0,33,2,3,64,32,2,32,0,40,2,4,72,4,64,32,0,40,2,0,32,2,16,18,32,2,65,1,106,33,2,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,6,66,45,136,167,65,3,116,106,41,3,0,32,6,66,8,134,66,1,132,133,55,3,40,32,0,11,38,1,1,127,32,0,40,2,0,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,55,1,2,127,32,1,32,0,40,2,0,34,2,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,16,12,11,32,0,32,1,54,2,0,11,7,0,32,0,40,2,4,11,9,0,32,0,32,1,54,2,4,11,7,0,32,0,40,2,8,11,9,0,32,0,32,1,54,2,8,11,7,0,32,0,41,3,16,11,9,0,32,0,32,1,55,3,16,11,7,0,32,0,41,3,24,11,9,0,32,0,32,1,55,3,24,11,7,0,32,0,41,3,32,11,9,0,32,0,32,1,55,3,32,11,7,0,32,0,41,3,40,11,9,0,32,0,32,1,55,3,40,11,7,0,32,0,41,3,48,11,9,0,32,0,32,1,55,3,48,11,7,0,32,0,41,3,56,11,9,0,32,0,32,1,55,3,56,11,7,0,32,0,41,3,64,11,9,0,32,0,32,1,55,3,64,11,7,0,32,0,41,3,72,11,9,0,32,0,32,1,55,3,72,11,7,0,32,0,41,3,80,11,9,0,32,0,32,1,55,3,80,11,7,0,32,0,41,3,88,11,9,0,32,0,32,1,55,3,88,11,7,0,32,0,41,3,96,11,9,0,32,0,32,1,55,3,96,11,172,4,2,5,127,1,126,32,2,65,172,3,75,4,64,32,2,65,16,107,34,4,32,4,40,2,4,65,1,106,54,2,4,11,32,2,33,4,65,0,33,2,32,1,40,2,8,33,5,32,1,40,2,4,33,6,3,64,2,127,65,0,33,3,3,64,32,3,32,5,72,4,64,32,3,32,6,106,45,0,0,33,1,32,0,40,2,0,32,0,40,2,8,16,19,33,7,32,0,40,2,8,32,0,40,2,0,40,2,4,106,32,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,7,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,1,173,32,8,66,8,134,132,133,55,3,40,32,0,32,0,41,3,16,66,1,124,55,3,16,32,0,32,0,41,3,24,66,1,124,55,3,24,32,0,41,3,16,32,0,41,3,80,90,4,127,32,0,41,3,40,32,0,41,3,96,131,80,5,65,0,11,4,127,65,1,5,32,0,41,3,16,32,0,41,3,88,90,11,4,64,32,0,32,0,41,3,32,55,3,48,32,0,32,0,41,3,16,55,3,56,32,0,32,0,41,3,40,55,3,64,65,0,33,1,3,64,32,1,32,0,40,2,4,72,4,64,32,0,40,2,0,32,1,16,18,32,1,65,1,106,33,1,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,8,66,8,134,66,1,132,133,55,3,40,32,3,65,1,106,12,3,11,32,3,65,1,106,33,3,12,1,11,11,65,127,11,34,1,65,0,78,4,64,32,5,32,1,107,33,5,32,1,32,6,106,33,6,32,2,34,1,65,1,106,33,2,32,4,40,2,4,32,1,65,2,116,106,32,0,41,3,56,62,2,0,12,1,11,11,32,4,11,10,0,16,15,36,5,16,15,36,6,11,3,0,1,11,73,1,2,127,32,0,40,2,4,34,1,65,255,255,255,255,0,113,34,2,65,1,70,4,64,32,0,65,16,106,16,53,32,0,32,0,40,2,0,65,1,114,54,2,0,35,0,32,0,16,2,5,32,0,32,2,65,1,107,32,1,65,128,128,128,128,127,113,114,54,2,4,11,11,58,0,2,64,2,64,2,64,32,0,65,8,107,40,2,0,14,7,0,0,1,1,1,1,1,2,11,15,11,32,0,40,2,0,34,0,4,64,32,0,65,172,3,79,4,64,32,0,65,16,107,16,52,11,11,15,11,0,11,11,137,3,7,0,65,16,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,208,0,11,45,30,0,0,0,1,0,0,0,1,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,128,1,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,176,1,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,240,1,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,176,2,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,126,0,108,0,105,0,98,0,47,0,116,0,121,0,112,0,101,0,100,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,240,2,11,53,7,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,145,4,0,0,2,0,0,0,49,0,0,0,2,0,0,0,17,1,0,0,2,0,0,0,16,0,34,16,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,16,46,47,114,97,98,105,110,46,119,97,115,109,46,109,97,112]);return zTe(new Response(new Blob([e],{type:"application/wasm"})),r)}LZ.exports=ck});var FZ=P((p0t,UZ)=>{var MZ=RZ(),VTe=BZ(),KTe=async(r,e,t,n,i)=>{let o=await VTe();return new MZ(o,r,e,t,n,i)};UZ.exports={Rabin:MZ,create:KTe}});var pk=P((O0t,GZ)=>{"use strict";GZ.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let i=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):i=!0,this._setInternalPos(n,e,t,i),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t=this._bitArrays.length)return-1;let i=this._bitArrays[n],o=e-n*7;if(!((i&1<0))return-1;let a=this._bitArrays.slice(0,n).reduce(XTe,0),c=~(4294967295<=t)o.push(s);else if(o[0][0]<=t)o.unshift(s);else{let a=Math.round(o.length/2);this._data=o.slice(0,a).concat(s).concat(o.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(ZTe),this._changedData=!1}bitField(){let e=[],t=8,n=0,i=0,o,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(o=s.shift(),n=7);let c=Math.min(n,t),u=~(255<>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(i),i=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(JTe)}};function XTe(r,e){return r+HZ(e)}function HZ(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function ZTe(r,e){return r[0]-e[0]}function JTe(r){return r[1]}});var xJ=P((hmt,bk)=>{"use strict";var zIe=Object.prototype.hasOwnProperty,oo="~";function Q3(){}Object.create&&(Q3.prototype=Object.create(null),new Q3().__proto__||(oo=!1));function VIe(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function vJ(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new VIe(t,n||r,i),s=oo?oo+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function cE(r,e){--r._eventsCount===0?r._events=new Q3:delete r._events[e]}function Ui(){this._events=new Q3,this._eventsCount=0}Ui.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)zIe.call(t,n)&&e.push(oo?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ui.prototype.listeners=function(e){var t=oo?oo+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i{"use strict";GJ.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:8,RTLD_LOCAL:4,E2BIG:7,EACCES:13,EADDRINUSE:48,EADDRNOTAVAIL:49,EAFNOSUPPORT:47,EAGAIN:35,EALREADY:37,EBADF:9,EBADMSG:94,EBUSY:16,ECANCELED:89,ECHILD:10,ECONNABORTED:53,ECONNREFUSED:61,ECONNRESET:54,EDEADLK:11,EDESTADDRREQ:39,EDOM:33,EDQUOT:69,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:65,EIDRM:90,EILSEQ:92,EINPROGRESS:36,EINTR:4,EINVAL:22,EIO:5,EISCONN:56,EISDIR:21,ELOOP:62,EMFILE:24,EMLINK:31,EMSGSIZE:40,EMULTIHOP:95,ENAMETOOLONG:63,ENETDOWN:50,ENETRESET:52,ENETUNREACH:51,ENFILE:23,ENOBUFS:55,ENODATA:96,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:77,ENOLINK:97,ENOMEM:12,ENOMSG:91,ENOPROTOOPT:42,ENOSPC:28,ENOSR:98,ENOSTR:99,ENOSYS:78,ENOTCONN:57,ENOTDIR:20,ENOTEMPTY:66,ENOTSOCK:38,ENOTSUP:45,ENOTTY:25,ENXIO:6,EOPNOTSUPP:102,EOVERFLOW:84,EPERM:1,EPIPE:32,EPROTO:100,EPROTONOSUPPORT:43,EPROTOTYPE:41,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:70,ETIME:101,ETIMEDOUT:60,ETXTBSY:26,EWOULDBLOCK:35,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:10,SIGFPE:8,SIGKILL:9,SIGUSR1:30,SIGSEGV:11,SIGUSR2:31,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:20,SIGCONT:19,SIGSTOP:17,SIGTSTP:18,SIGTTIN:21,SIGTTOU:22,SIGURG:16,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:23,SIGINFO:29,SIGSYS:12,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:512,O_EXCL:2048,UV_FS_O_FILEMAP:0,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_DIRECTORY:1048576,O_NOFOLLOW:256,O_SYNC:128,O_DSYNC:4194304,O_SYMLINK:2097152,O_NONBLOCK:4,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306480,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_EPHEMERAL_RSA:0,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER:0,SSL_OP_MICROSOFT_SESS_ID_BUG:0,SSL_OP_MSIE_SSLV2_RSA_PADDING:0,SSL_OP_NETSCAPE_CA_DN_BUG:0,SSL_OP_NETSCAPE_CHALLENGE_BUG:0,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG:0,SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG:0,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PKCS1_CHECK_1:0,SSL_OP_PKCS1_CHECK_2:0,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_SINGLE_DH_USE:0,SSL_OP_SINGLE_ECDH_USE:0,SSL_OP_SSLEAY_080_CLIENT_DH_BUG:0,SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG:0,SSL_OP_TLS_BLOCK_PADDING_BUG:0,SSL_OP_TLS_D5_BUG:0,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6,defaultCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA"}});var vne=P((LN,Ene)=>{"use strict";Object.defineProperty(LN,"__esModule",{value:!0});m7.BASE=2166136261;function m7(r,e=m7.BASE){let t=r.length;for(let n=0;n>>0}LN.default=m7;Ene.exports=m7});var gie=P((t_t,I7)=>{"use strict";I7.exports=BDe;I7.exports.format=pie;I7.exports.parse=mie;var DDe=/\B(?=(\d{3})+(?!\d))/g,ODe=/(?:\.0*|(\.[^0]+)0+)$/,Sd={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},LDe=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function BDe(r,e){return typeof r=="string"?mie(r):typeof r=="number"?pie(r,e):null}function pie(r,e){if(!Number.isFinite(r))return null;var t=Math.abs(r),n=e&&e.thousandsSeparator||"",i=e&&e.unitSeparator||"",o=e&&e.decimalPlaces!==void 0?e.decimalPlaces:2,s=!!(e&&e.fixedDecimals),a=e&&e.unit||"";(!a||!Sd[a.toLowerCase()])&&(t>=Sd.pb?a="PB":t>=Sd.tb?a="TB":t>=Sd.gb?a="GB":t>=Sd.mb?a="MB":t>=Sd.kb?a="KB":a="B");var c=r/Sd[a.toLowerCase()],u=c.toFixed(o);return s||(u=u.replace(ODe,"$1")),n&&(u=u.split(".").map(function(l,f){return f===0?l.replace(DDe,n):l}).join(".")),u+i+a}function mie(r){if(typeof r=="number"&&!isNaN(r))return r;if(typeof r!="string")return null;var e=LDe.exec(r),t,n="b";return e?(t=parseFloat(e[1]),n=e[4].toLowerCase()):(t=parseInt(r,10),n="b"),isNaN(t)?null:Math.floor(Sd[n]*t)}});var Qie=P(Yie=>{"use strict";Yie.supports=function(...e){let t=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(t,{snapshots:t.snapshots||!1,permanence:t.permanence||!1,seek:t.seek||!1,clear:t.clear||!1,getMany:t.getMany||!1,keyIterator:t.keyIterator||!1,valueIterator:t.valueIterator||!1,iteratorNextv:t.iteratorNextv||!1,iteratorAll:t.iteratorAll||!1,status:t.status||!1,createIfMissing:t.createIfMissing||!1,errorIfExists:t.errorIfExists||!1,deferredOpen:t.deferredOpen||!1,promises:t.promises||!1,streams:t.streams||!1,encodings:Object.assign({},t.encodings),events:Object.assign({},t.events),additionalMethods:Object.assign({},t.additionalMethods)})}});var Za=P((YEt,Xie)=>{"use strict";Xie.exports=class extends Error{constructor(e,t){super(e||""),typeof t=="object"&&t!==null&&(t.code&&(this.code=String(t.code)),t.expected&&(this.expected=!0),t.transient&&(this.transient=!0),t.cause&&(this.cause=t.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var eoe=P(L7=>{"use strict";L7.byteLength=aOe;L7.toByteArray=uOe;L7.fromByteArray=dOe;var iu=[],Zs=[],sOe=typeof Uint8Array<"u"?Uint8Array:Array,ND="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Dp=0,Zie=ND.length;Dp0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function aOe(r){var e=Jie(r),t=e[0],n=e[1];return(t+n)*3/4-n}function cOe(r,e,t){return(e+t)*3/4-t}function uOe(r){var e,t=Jie(r),n=t[0],i=t[1],o=new sOe(cOe(r,n,i)),s=0,a=i>0?n-4:n,c;for(c=0;c>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Zs[r.charCodeAt(c)]<<2|Zs[r.charCodeAt(c+1)]>>4,o[s++]=e&255),i===1&&(e=Zs[r.charCodeAt(c)]<<10|Zs[r.charCodeAt(c+1)]<<4|Zs[r.charCodeAt(c+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function lOe(r){return iu[r>>18&63]+iu[r>>12&63]+iu[r>>6&63]+iu[r&63]}function fOe(r,e,t){for(var n,i=[],o=e;oa?a:s+o));return n===1?(e=r[t-1],i.push(iu[e>>2]+iu[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(iu[e>>10]+iu[e>>4&63]+iu[e<<2&63]+"=")),i.join("")}});var toe=P(DD=>{DD.read=function(r,e,t,n,i){var o,s,a=i*8-n-1,c=(1<>1,l=-7,f=t?i-1:0,h=t?-1:1,d=r[e+f];for(f+=h,o=d&(1<<-l)-1,d>>=-l,l+=a;l>0;o=o*256+r[e+f],f+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=s*256+r[e+f],f+=h,l-=8);if(o===0)o=1-u;else{if(o===c)return s?NaN:(d?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(d?-1:1)*s*Math.pow(2,o-n)};DD.write=function(r,e,t,n,i,o){var s,a,c,u=o*8-i-1,l=(1<>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+f>=1?e+=h/c:e+=h*Math.pow(2,1-f),e*c>=2&&(s++,c/=2),s+f>=l?(a=0,s=l):s+f>=1?(a=(e*c-1)*Math.pow(2,i),s=s+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;r[t+d]=a&255,d+=p,a/=256,i-=8);for(s=s<0;r[t+d]=s&255,d+=p,s/=256,u-=8);r[t+d-p]|=g*128}});var n5=P(w2=>{"use strict";var OD=eoe(),g2=toe(),roe=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;w2.Buffer=Y;w2.SlowBuffer=wOe;w2.INSPECT_MAX_BYTES=50;var B7=2147483647;w2.kMaxLength=B7;Y.TYPED_ARRAY_SUPPORT=hOe();!Y.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function hOe(){try{let r=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(r,e),r.foo()===42}catch{return!1}}Object.defineProperty(Y.prototype,"parent",{enumerable:!0,get:function(){if(Y.isBuffer(this))return this.buffer}});Object.defineProperty(Y.prototype,"offset",{enumerable:!0,get:function(){if(Y.isBuffer(this))return this.byteOffset}});function wl(r){if(r>B7)throw new RangeError('The value "'+r+'" is invalid for option "size"');let e=new Uint8Array(r);return Object.setPrototypeOf(e,Y.prototype),e}function Y(r,e,t){if(typeof r=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return UD(r)}return soe(r,e,t)}Y.poolSize=8192;function soe(r,e,t){if(typeof r=="string")return mOe(r,e);if(ArrayBuffer.isView(r))return gOe(r);if(r==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);if(ou(r,ArrayBuffer)||r&&ou(r.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ou(r,SharedArrayBuffer)||r&&ou(r.buffer,SharedArrayBuffer)))return BD(r,e,t);if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=r.valueOf&&r.valueOf();if(n!=null&&n!==r)return Y.from(n,e,t);let i=yOe(r);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]=="function")return Y.from(r[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r)}Y.from=function(r,e,t){return soe(r,e,t)};Object.setPrototypeOf(Y.prototype,Uint8Array.prototype);Object.setPrototypeOf(Y,Uint8Array);function aoe(r){if(typeof r!="number")throw new TypeError('"size" argument must be of type number');if(r<0)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function pOe(r,e,t){return aoe(r),r<=0?wl(r):e!==void 0?typeof t=="string"?wl(r).fill(e,t):wl(r).fill(e):wl(r)}Y.alloc=function(r,e,t){return pOe(r,e,t)};function UD(r){return aoe(r),wl(r<0?0:FD(r)|0)}Y.allocUnsafe=function(r){return UD(r)};Y.allocUnsafeSlow=function(r){return UD(r)};function mOe(r,e){if((typeof e!="string"||e==="")&&(e="utf8"),!Y.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=coe(r,e)|0,n=wl(t),i=n.write(r,e);return i!==t&&(n=n.slice(0,i)),n}function LD(r){let e=r.length<0?0:FD(r.length)|0,t=wl(e);for(let n=0;n=B7)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+B7.toString(16)+" bytes");return r|0}function wOe(r){return+r!=r&&(r=0),Y.alloc(+r)}Y.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==Y.prototype};Y.compare=function(e,t){if(ou(e,Uint8Array)&&(e=Y.from(e,e.offset,e.byteLength)),ou(t,Uint8Array)&&(t=Y.from(t,t.offset,t.byteLength)),!Y.isBuffer(e)||!Y.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let o=0,s=Math.min(n,i);oi.length?(Y.isBuffer(s)||(s=Y.from(s)),s.copy(i,o)):Uint8Array.prototype.set.call(i,s,o);else if(Y.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function coe(r,e){if(Y.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||ou(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);let t=r.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&t===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return MD(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return yoe(r).length;default:if(i)return n?-1:MD(r).length;e=(""+e).toLowerCase(),i=!0}}Y.byteLength=coe;function bOe(r,e,t){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(r||(r="utf8");;)switch(r){case"hex":return COe(this,e,t);case"utf8":case"utf-8":return loe(this,e,t);case"ascii":return IOe(this,e,t);case"latin1":case"binary":return ROe(this,e,t);case"base64":return AOe(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return POe(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}Y.prototype._isBuffer=!0;function Op(r,e,t){let n=r[e];r[e]=r[t],r[t]=n}Y.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tt&&(e+=" ... "),""};roe&&(Y.prototype[roe]=Y.prototype.inspect);Y.prototype.compare=function(e,t,n,i,o){if(ou(e,Uint8Array)&&(e=Y.from(e,e.offset,e.byteLength)),!Y.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),t<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&t>=n)return 0;if(i>=o)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,o>>>=0,this===e)return 0;let s=o-i,a=n-t,c=Math.min(s,a),u=this.slice(i,o),l=e.slice(t,n);for(let f=0;f2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,VD(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t),t>=r.length){if(i)return-1;t=r.length-1}else if(t<0)if(i)t=0;else return-1;if(typeof e=="string"&&(e=Y.from(e,n)),Y.isBuffer(e))return e.length===0?-1:noe(r,e,t,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):noe(r,[e],t,n,i);throw new TypeError("val must be string, number or Buffer")}function noe(r,e,t,n,i){let o=1,s=r.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(r.length<2||e.length<2)return-1;o=2,s/=2,a/=2,t/=2}function c(l,f){return o===1?l[f]:l.readUInt16BE(f*o)}let u;if(i){let l=-1;for(u=t;us&&(t=s-a),u=t;u>=0;u--){let l=!0;for(let f=0;fi&&(n=i)):n=i;let o=e.length;n>o/2&&(n=o/2);let s;for(s=0;s>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let o=this.length-t;if((n===void 0||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let s=!1;for(;;)switch(i){case"hex":return _Oe(this,e,t,n);case"utf8":case"utf-8":return EOe(this,e,t,n);case"ascii":case"latin1":case"binary":return vOe(this,e,t,n);case"base64":return xOe(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return SOe(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};Y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function AOe(r,e,t){return e===0&&t===r.length?OD.fromByteArray(r):OD.fromByteArray(r.slice(e,t))}function loe(r,e,t){t=Math.min(r.length,t);let n=[],i=e;for(;i239?4:o>223?3:o>191?2:1;if(i+a<=t){let c,u,l,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=r[i+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=r[i+1],u=r[i+2],(c&192)===128&&(u&192)===128&&(f=(o&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=r[i+1],u=r[i+2],l=r[i+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,a=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),i+=a}return TOe(n)}var ioe=4096;function TOe(r){let e=r.length;if(e<=ioe)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn)&&(t=n);let i="";for(let o=e;on&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),tt)throw new RangeError("Trying to access beyond buffer length")}Y.prototype.readUintLE=Y.prototype.readUIntLE=function(e,t,n){e=e>>>0,t=t>>>0,n||li(e,t,this.length);let i=this[e],o=1,s=0;for(;++s>>0,t=t>>>0,n||li(e,t,this.length);let i=this[e+--t],o=1;for(;t>0&&(o*=256);)i+=this[e+--t]*o;return i};Y.prototype.readUint8=Y.prototype.readUInt8=function(e,t){return e=e>>>0,t||li(e,1,this.length),this[e]};Y.prototype.readUint16LE=Y.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||li(e,2,this.length),this[e]|this[e+1]<<8};Y.prototype.readUint16BE=Y.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||li(e,2,this.length),this[e]<<8|this[e+1]};Y.prototype.readUint32LE=Y.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||li(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};Y.prototype.readUint32BE=Y.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||li(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};Y.prototype.readBigUInt64LE=Rd(function(e){e=e>>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,o=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(o)<>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],o=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<>>0,t=t>>>0,n||li(e,t,this.length);let i=this[e],o=1,s=0;for(;++s=o&&(i-=Math.pow(2,8*t)),i};Y.prototype.readIntBE=function(e,t,n){e=e>>>0,t=t>>>0,n||li(e,t,this.length);let i=t,o=1,s=this[e+--i];for(;i>0&&(o*=256);)s+=this[e+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*t)),s};Y.prototype.readInt8=function(e,t){return e=e>>>0,t||li(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};Y.prototype.readInt16LE=function(e,t){e=e>>>0,t||li(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};Y.prototype.readInt16BE=function(e,t){e=e>>>0,t||li(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};Y.prototype.readInt32LE=function(e,t){return e=e>>>0,t||li(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};Y.prototype.readInt32BE=function(e,t){return e=e>>>0,t||li(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};Y.prototype.readBigInt64LE=Rd(function(e){e=e>>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<>>0,y2(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&r5(e,this.length-8);let i=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,t||li(e,4,this.length),g2.read(this,e,!0,23,4)};Y.prototype.readFloatBE=function(e,t){return e=e>>>0,t||li(e,4,this.length),g2.read(this,e,!1,23,4)};Y.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||li(e,8,this.length),g2.read(this,e,!0,52,8)};Y.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||li(e,8,this.length),g2.read(this,e,!1,52,8)};function vo(r,e,t,n,i,o){if(!Y.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||er.length)throw new RangeError("Index out of range")}Y.prototype.writeUintLE=Y.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t=t>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;vo(this,e,t,n,a,0)}let o=1,s=0;for(this[t]=e&255;++s>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;vo(this,e,t,n,a,0)}let o=n-1,s=1;for(this[t+o]=e&255;--o>=0&&(s*=256);)this[t+o]=e/s&255;return t+n};Y.prototype.writeUint8=Y.prototype.writeUInt8=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,1,255,0),this[t]=e&255,t+1};Y.prototype.writeUint16LE=Y.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};Y.prototype.writeUint16BE=Y.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};Y.prototype.writeUint32LE=Y.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};Y.prototype.writeUint32BE=Y.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function foe(r,e,t,n,i){goe(e,n,i,r,t,7);let o=Number(e&BigInt(4294967295));r[t++]=o,o=o>>8,r[t++]=o,o=o>>8,r[t++]=o,o=o>>8,r[t++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,r[t++]=s,t}function doe(r,e,t,n,i){goe(e,n,i,r,t,7);let o=Number(e&BigInt(4294967295));r[t+7]=o,o=o>>8,r[t+6]=o,o=o>>8,r[t+5]=o,o=o>>8,r[t+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return r[t+3]=s,s=s>>8,r[t+2]=s,s=s>>8,r[t+1]=s,s=s>>8,r[t]=s,t+8}Y.prototype.writeBigUInt64LE=Rd(function(e,t=0){return foe(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});Y.prototype.writeBigUInt64BE=Rd(function(e,t=0){return doe(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});Y.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,8*n-1);vo(this,e,t,n,c-1,-c)}let o=0,s=1,a=0;for(this[t]=e&255;++o>0)-a&255;return t+n};Y.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,8*n-1);vo(this,e,t,n,c-1,-c)}let o=n-1,s=1,a=0;for(this[t+o]=e&255;--o>=0&&(s*=256);)e<0&&a===0&&this[t+o+1]!==0&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+n};Y.prototype.writeInt8=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};Y.prototype.writeInt16LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};Y.prototype.writeInt16BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};Y.prototype.writeInt32LE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};Y.prototype.writeInt32BE=function(e,t,n){return e=+e,t=t>>>0,n||vo(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};Y.prototype.writeBigInt64LE=Rd(function(e,t=0){return foe(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});Y.prototype.writeBigInt64BE=Rd(function(e,t=0){return doe(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function hoe(r,e,t,n,i,o){if(t+n>r.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function poe(r,e,t,n,i){return e=+e,t=t>>>0,i||hoe(r,e,t,4,34028234663852886e22,-34028234663852886e22),g2.write(r,e,t,n,23,4),t+4}Y.prototype.writeFloatLE=function(e,t,n){return poe(this,e,t,!0,n)};Y.prototype.writeFloatBE=function(e,t,n){return poe(this,e,t,!1,n)};function moe(r,e,t,n,i){return e=+e,t=t>>>0,i||hoe(r,e,t,8,17976931348623157e292,-17976931348623157e292),g2.write(r,e,t,n,52,8),t+8}Y.prototype.writeDoubleLE=function(e,t,n){return moe(this,e,t,!0,n)};Y.prototype.writeDoubleBE=function(e,t,n){return moe(this,e,t,!1,n)};Y.prototype.copy=function(e,t,n,i){if(!Y.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let o;if(typeof e=="number")for(o=t;o2**32?i=ooe(String(t)):typeof t=="bigint"&&(i=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(i=ooe(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function ooe(r){let e="",t=r.length,n=r[0]==="-"?1:0;for(;t>=n+4;t-=3)e=`_${r.slice(t-3,t)}${e}`;return`${r.slice(0,t)}${e}`}function kOe(r,e,t){y2(e,"offset"),(r[e]===void 0||r[e+t]===void 0)&&r5(e,r.length-(t+1))}function goe(r,e,t,n,i,o){if(r>t||r3?e===0||e===BigInt(0)?a=`>= 0${s} and < 2${s} ** ${(o+1)*8}${s}`:a=`>= -(2${s} ** ${(o+1)*8-1}${s}) and < 2 ** ${(o+1)*8-1}${s}`:a=`>= ${e}${s} and <= ${t}${s}`,new m2.ERR_OUT_OF_RANGE("value",a,r)}kOe(n,i,o)}function y2(r,e){if(typeof r!="number")throw new m2.ERR_INVALID_ARG_TYPE(e,"number",r)}function r5(r,e,t){throw Math.floor(r)!==r?(y2(r,t),new m2.ERR_OUT_OF_RANGE(t||"offset","an integer",r)):e<0?new m2.ERR_BUFFER_OUT_OF_BOUNDS:new m2.ERR_OUT_OF_RANGE(t||"offset",`>= ${t?1:0} and <= ${e}`,r)}var NOe=/[^+/0-9A-Za-z-_]/g;function DOe(r){if(r=r.split("=")[0],r=r.trim().replace(NOe,""),r.length<2)return"";for(;r.length%4!==0;)r=r+"=";return r}function MD(r,e){e=e||1/0;let t,n=r.length,i=null,o=[];for(let s=0;s55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function OOe(r){let e=[];for(let t=0;t>8,i=t%256,o.push(i),o.push(n);return o}function yoe(r){return OD.toByteArray(DOe(r))}function M7(r,e,t,n){let i;for(i=0;i=e.length||i>=r.length);++i)e[i+t]=r[i];return i}function ou(r,e){return r instanceof e||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===e.name}function VD(r){return r!==r}var BOe=function(){let r="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let n=t*16;for(let i=0;i<16;++i)e[n+i]=r[t]+r[i]}return e}();function Rd(r){return typeof BigInt>"u"?MOe:r}function MOe(){throw new Error("BigInt not supported")}});var $D=P((e7t,woe)=>{"use strict";var KD=null;woe.exports=function(){return KD===null&&(KD={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),KD}});var GD=P(boe=>{"use strict";var qD=Za(),UOe=new Set(["buffer","view","utf8"]),HD=class{constructor(e){if(this.encode=e.encode||this.encode,this.decode=e.decode||this.decode,this.name=e.name||this.name,this.format=e.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!UOe.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");e.createViewTranscoder&&(this.createViewTranscoder=e.createViewTranscoder),e.createBufferTranscoder&&(this.createBufferTranscoder=e.createBufferTranscoder),e.createUTF8Transcoder&&(this.createUTF8Transcoder=e.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new qD(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new qD(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new qD(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};boe.Encoding=HD});var QD=P(U7=>{"use strict";var{Buffer:WD}=n5()||{},{Encoding:YD}=GD(),FOe=$D(),i5=class extends YD{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new o5({encode:this.encode,decode:e=>this.decode(WD.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},o5=class extends YD{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new i5({encode:e=>{let t=this.encode(e);return WD.from(t.buffer,t.byteOffset,t.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},jD=class extends YD{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new i5({encode:e=>WD.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:t}=FOe();return new o5({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(t.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};U7.BufferFormat=i5;U7.ViewFormat=o5;U7.UTF8Format=jD});var xoe=P(Lp=>{"use strict";var{Buffer:zi}=n5()||{Buffer:{isBuffer:()=>!1}},{textEncoder:Eoe,textDecoder:_oe}=$D()(),{BufferFormat:s5,ViewFormat:XD,UTF8Format:voe}=QD(),F7=r=>r;Lp.utf8=new voe({encode:function(r){return zi.isBuffer(r)?r.toString("utf8"):ArrayBuffer.isView(r)?_oe.decode(r):String(r)},decode:F7,name:"utf8",createViewTranscoder(){return new XD({encode:function(r){return ArrayBuffer.isView(r)?r:Eoe.encode(r)},decode:function(r){return _oe.decode(r)},name:`${this.name}+view`})},createBufferTranscoder(){return new s5({encode:function(r){return zi.isBuffer(r)?r:ArrayBuffer.isView(r)?zi.from(r.buffer,r.byteOffset,r.byteLength):zi.from(String(r),"utf8")},decode:function(r){return r.toString("utf8")},name:`${this.name}+buffer`})}});Lp.json=new voe({encode:JSON.stringify,decode:JSON.parse,name:"json"});Lp.buffer=new s5({encode:function(r){return zi.isBuffer(r)?r:ArrayBuffer.isView(r)?zi.from(r.buffer,r.byteOffset,r.byteLength):zi.from(String(r),"utf8")},decode:F7,name:"buffer",createViewTranscoder(){return new XD({encode:function(r){return ArrayBuffer.isView(r)?r:zi.from(String(r),"utf8")},decode:function(r){return zi.from(r.buffer,r.byteOffset,r.byteLength)},name:`${this.name}+view`})}});Lp.view=new XD({encode:function(r){return ArrayBuffer.isView(r)?r:Eoe.encode(r)},decode:F7,name:"view",createBufferTranscoder(){return new s5({encode:function(r){return zi.isBuffer(r)?r:ArrayBuffer.isView(r)?zi.from(r.buffer,r.byteOffset,r.byteLength):zi.from(String(r),"utf8")},decode:F7,name:`${this.name}+buffer`})}});Lp.hex=new s5({encode:function(r){return zi.isBuffer(r)?r:zi.from(String(r),"hex")},decode:function(r){return r.toString("hex")},name:"hex"});Lp.base64=new s5({encode:function(r){return zi.isBuffer(r)?r:zi.from(String(r),"base64")},decode:function(r){return r.toString("base64")},name:"base64"})});var Toe=P(Aoe=>{"use strict";var Soe=Za(),V7=xoe(),{Encoding:zOe}=GD(),{BufferFormat:VOe,ViewFormat:KOe,UTF8Format:$Oe}=QD(),a5=Symbol("formats"),z7=Symbol("encodings"),qOe=new Set(["buffer","view","utf8"]),ZD=class{constructor(e){if(Array.isArray(e)){if(!e.every(t=>qOe.has(t)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[z7]=new Map,this[a5]=new Set(e);for(let t in V7)try{this.encoding(t)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[z7].values()))}encoding(e){let t=this[z7].get(e);if(t===void 0){if(typeof e=="string"&&e!==""){if(t=WOe[e],!t)throw new Soe(`Encoding '${e}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof e!="object"||e===null)throw new TypeError("First argument 'encoding' must be a string or object");t=HOe(e)}let{name:n,format:i}=t;if(!this[a5].has(i))if(this[a5].has("view"))t=t.createViewTranscoder();else if(this[a5].has("buffer"))t=t.createBufferTranscoder();else if(this[a5].has("utf8"))t=t.createUTF8Transcoder();else throw new Soe(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,t.name,t.commonName])this[z7].set(o,t)}return t}};Aoe.Transcoder=ZD;function HOe(r){if(r instanceof zOe)return r;let e="type"in r&&typeof r.type=="string"?r.type:void 0,t=r.name||e||`anonymous-${YOe++}`;switch(GOe(r)){case"view":return new KOe({...r,name:t});case"utf8":return new $Oe({...r,name:t});case"buffer":return new VOe({...r,name:t});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function GOe(r){return"format"in r&&r.format!==void 0?r.format:"buffer"in r&&typeof r.buffer=="boolean"?r.buffer?"buffer":"utf8":"code"in r&&Number.isInteger(r.code)?"view":"buffer"}var jOe={binary:V7.buffer,"utf-8":V7.utf8},WOe={...V7,...jOe},YOe=0});var xi=P((o7t,JD)=>{"use strict";var b2=typeof Reflect=="object"?Reflect:null,Ioe=b2&&typeof b2.apply=="function"?b2.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},K7;b2&&typeof b2.ownKeys=="function"?K7=b2.ownKeys:Object.getOwnPropertySymbols?K7=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:K7=function(e){return Object.getOwnPropertyNames(e)};function QOe(r){console&&console.warn&&console.warn(r)}var Coe=Number.isNaN||function(e){return e!==e};function wr(){wr.init.call(this)}JD.exports=wr;JD.exports.once=eLe;wr.EventEmitter=wr;wr.prototype._events=void 0;wr.prototype._eventsCount=0;wr.prototype._maxListeners=void 0;var Roe=10;function $7(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(wr,"defaultMaxListeners",{enumerable:!0,get:function(){return Roe},set:function(r){if(typeof r!="number"||r<0||Coe(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");Roe=r}});wr.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};wr.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Coe(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Poe(r){return r._maxListeners===void 0?wr.defaultMaxListeners:r._maxListeners}wr.prototype.getMaxListeners=function(){return Poe(this)};wr.prototype.emit=function(e){for(var t=[],n=1;n0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(c===void 0)return!1;if(typeof c=="function")Ioe(c,this,t);else for(var u=c.length,l=Loe(c,u),n=0;n0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=s.length,QOe(a)}return r}wr.prototype.addListener=function(e,t){return koe(this,e,t,!1)};wr.prototype.on=wr.prototype.addListener;wr.prototype.prependListener=function(e,t){return koe(this,e,t,!0)};function XOe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Noe(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=XOe.bind(n);return i.listener=t,n.wrapFn=i,i}wr.prototype.once=function(e,t){return $7(t),this.on(e,Noe(this,e,t)),this};wr.prototype.prependOnceListener=function(e,t){return $7(t),this.prependListener(e,Noe(this,e,t)),this};wr.prototype.removeListener=function(e,t){var n,i,o,s,a;if($7(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():ZOe(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};wr.prototype.off=wr.prototype.removeListener;wr.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i=0;i--)this.removeListener(e,t[i]);return this};function Doe(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?JOe(i):Loe(i,i.length)}wr.prototype.listeners=function(e){return Doe(this,e,!0)};wr.prototype.rawListeners=function(e){return Doe(this,e,!1)};wr.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):Ooe.call(r,e)};wr.prototype.listenerCount=Ooe;function Ooe(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}wr.prototype.eventNames=function(){return this._eventsCount>0?K7(this._events):[]};function Loe(r,e){for(var t=new Array(e),n=0;n{Moe.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)});var c5=P(eO=>{"use strict";var Foe=Uoe();eO.fromCallback=function(r,e){if(r===void 0){var t=new Promise(function(n,i){r=function(o,s){o?i(o):n(s)}});r[e!==void 0?e:"promise"]=t}else if(typeof r!="function")throw new TypeError("Callback must be a function");return r};eO.fromPromise=function(r,e){if(e===void 0)return r;r.then(function(t){Foe(()=>e(null,t))}).catch(function(t){Foe(()=>e(t))})}});var q7=P(tO=>{"use strict";tO.getCallback=function(r,e){return typeof r=="function"?r:e};tO.getOptions=function(r,e){return typeof r=="object"&&r!==null?r:e!==void 0?e:{}}});var Od=P(W7=>{"use strict";var{fromCallback:rO}=c5(),us=Za(),{getOptions:nO,getCallback:zoe}=q7(),Bp=Symbol("promise"),_2=Symbol("callback"),su=Symbol("working"),Mp=Symbol("handleOne"),bl=Symbol("handleMany"),iO=Symbol("autoClose"),Nd=Symbol("finishWork"),au=Symbol("returnMany"),Cd=Symbol("closing"),u5=Symbol("handleClose"),H7=Symbol("closed"),l5=Symbol("closeCallbacks"),kd=Symbol("keyEncoding"),Up=Symbol("valueEncoding"),oO=Symbol("abortOnClose"),G7=Symbol("legacy"),sO=Symbol("keys"),aO=Symbol("values"),Pd=Symbol("limit"),Js=Symbol("count"),j7=Object.freeze({}),rLe=()=>{},Voe=!1,f5=class{constructor(e,t,n){if(typeof e!="object"||e===null){let i=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof t!="object"||t===null)throw new TypeError("The second argument must be an options object");this[H7]=!1,this[l5]=[],this[su]=!1,this[Cd]=!1,this[iO]=!1,this[_2]=null,this[Mp]=this[Mp].bind(this),this[bl]=this[bl].bind(this),this[u5]=this[u5].bind(this),this[kd]=t[kd],this[Up]=t[Up],this[G7]=n,this[Pd]=Number.isInteger(t.limit)&&t.limit>=0?t.limit:1/0,this[Js]=0,this[oO]=!!t.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[Js]}get limit(){return this[Pd]}next(e){let t;if(e===void 0)t=new Promise((n,i)=>{e=(o,s,a)=>{o?i(o):this[G7]?s===void 0&&a===void 0?n():n([s,a]):n(s)}});else if(typeof e!="function")throw new TypeError("Callback must be a function");return this[Cd]?this.nextTick(e,new us("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[su]?this.nextTick(e,new us("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[su]=!0,this[_2]=e,this[Js]>=this[Pd]?this.nextTick(this[Mp],null):this._next(this[Mp])),t}_next(e){this.nextTick(e)}nextv(e,t,n){return n=zoe(t,n),n=rO(n,Bp),t=nO(t,j7),Number.isInteger(e)?(this[Cd]?this.nextTick(n,new us("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[su]?this.nextTick(n,new us("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[Pd]<1/0&&(e=Math.min(e,this[Pd]-this[Js])),this[su]=!0,this[_2]=n,e<=0?this.nextTick(this[bl],null,[]):this._nextv(e,t,this[bl])),n[Bp]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Bp])}_nextv(e,t,n){let i=[],o=(s,a,c)=>{if(s)return n(s);if(this[G7]?a===void 0&&c===void 0:a===void 0)return n(null,i);i.push(this[G7]?[a,c]:a),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,t){return t=zoe(e,t),t=rO(t,Bp),e=nO(e,j7),this[Cd]?this.nextTick(t,new us("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[su]?this.nextTick(t,new us("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[su]=!0,this[_2]=t,this[iO]=!0,this[Js]>=this[Pd]?this.nextTick(this[bl],null,[]):this._all(e,this[bl])),t[Bp]}_all(e,t){let n=this[Js],i=[],o=()=>{let a=this[Pd]<1/0?Math.min(1e3,this[Pd]-n):1e3;a<=0?this.nextTick(t,null,i):this._nextv(a,j7,s)},s=(a,c)=>{a?t(a):c.length===0?t(null,i):(i.push.apply(i,c),n+=c.length,o())};o()}[Nd](){let e=this[_2];return this[oO]&&e===null?rLe:(this[su]=!1,this[_2]=null,this[Cd]&&this._close(this[u5]),e)}[au](e,t,n){this[iO]?this.close(e.bind(null,t,n)):e(t,n)}seek(e,t){if(t=nO(t,j7),!this[Cd]){if(this[su])throw new us("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(t.keyEncoding||this[kd]),i=n.format;t.keyEncoding!==i&&(t={...t,keyEncoding:i});let o=this.db.prefixKey(n.encode(e),i);this._seek(o,t)}}}_seek(e,t){throw new us("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=rO(e,Bp),this[H7]?this.nextTick(e):this[Cd]?this[l5].push(e):(this[Cd]=!0,this[l5].push(e),this[su]?this[oO]&&this[Nd]()(new us("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[u5])),e[Bp]}_close(e){this.nextTick(e)}[u5](){this[H7]=!0,this.db.detachResource(this);let e=this[l5];this[l5]=[];for(let t of e)t()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[H7]||await this.close()}}},E2=class extends f5{constructor(e,t){super(e,t,!0),this[sO]=t.keys!==!1,this[aO]=t.values!==!1}[Mp](e,t,n){let i=this[Nd]();if(e)return i(e);try{t=this[sO]&&t!==void 0?this[kd].decode(t):void 0,n=this[aO]&&n!==void 0?this[Up].decode(n):void 0}catch(o){return i(new Dd("entry",o))}t===void 0&&n===void 0||this[Js]++,i(null,t,n)}[bl](e,t){let n=this[Nd]();if(e)return this[au](n,e);try{for(let i of t){let o=i[0],s=i[1];i[0]=this[sO]&&o!==void 0?this[kd].decode(o):void 0,i[1]=this[aO]&&s!==void 0?this[Up].decode(s):void 0}}catch(i){return this[au](n,new Dd("entries",i))}this[Js]+=t.length,this[au](n,null,t)}end(e){return!Voe&&typeof console<"u"&&(Voe=!0,console.warn(new us("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(e)}},cO=class extends f5{constructor(e,t){super(e,t,!1)}[Mp](e,t){let n=this[Nd]();if(e)return n(e);try{t=t!==void 0?this[kd].decode(t):void 0}catch(i){return n(new Dd("key",i))}t!==void 0&&this[Js]++,n(null,t)}[bl](e,t){let n=this[Nd]();if(e)return this[au](n,e);try{for(let i=0;i{"use strict";var{AbstractKeyIterator:nLe,AbstractValueIterator:iLe}=Od(),Fp=Symbol("iterator"),d5=Symbol("callback"),v2=Symbol("handleOne"),zp=Symbol("handleMany"),h5=class extends nLe{constructor(e,t){super(e,t),this[Fp]=e.iterator({...t,keys:!0,values:!1}),this[v2]=this[v2].bind(this),this[zp]=this[zp].bind(this)}},Y7=class extends iLe{constructor(e,t){super(e,t),this[Fp]=e.iterator({...t,keys:!1,values:!0}),this[v2]=this[v2].bind(this),this[zp]=this[zp].bind(this)}};for(let r of[h5,Y7]){let e=r===h5,t=e?n=>n[0]:n=>n[1];r.prototype._next=function(n){this[d5]=n,this[Fp].next(this[v2])},r.prototype[v2]=function(n,i,o){let s=this[d5];n?s(n):s(null,e?i:o)},r.prototype._nextv=function(n,i,o){this[d5]=o,this[Fp].nextv(n,i,this[zp])},r.prototype._all=function(n,i){this[d5]=i,this[Fp].all(n,this[zp])},r.prototype[zp]=function(n,i){let o=this[d5];n?o(n):o(null,i.map(t))},r.prototype._seek=function(n,i){this[Fp].seek(n,i)},r.prototype._close=function(n){this[Fp].close(n)}}lO.DefaultKeyIterator=h5;lO.DefaultValueIterator=Y7});var $oe=P(tv=>{"use strict";var{AbstractIterator:oLe,AbstractKeyIterator:sLe,AbstractValueIterator:aLe}=Od(),fO=Za(),xo=Symbol("nut"),J7=Symbol("undefer"),ev=Symbol("factory"),Q7=class extends oLe{constructor(e,t){super(e,t),this[xo]=null,this[ev]=()=>e.iterator(t),this.db.defer(()=>this[J7]())}},X7=class extends sLe{constructor(e,t){super(e,t),this[xo]=null,this[ev]=()=>e.keys(t),this.db.defer(()=>this[J7]())}},Z7=class extends aLe{constructor(e,t){super(e,t),this[xo]=null,this[ev]=()=>e.values(t),this.db.defer(()=>this[J7]())}};for(let r of[Q7,X7,Z7])r.prototype[J7]=function(){this.db.status==="open"&&(this[xo]=this[ev]())},r.prototype._next=function(e){this[xo]!==null?this[xo].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new fO("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},r.prototype._nextv=function(e,t,n){this[xo]!==null?this[xo].nextv(e,t,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,t,n)):this.nextTick(n,new fO("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},r.prototype._all=function(e,t){this[xo]!==null?this[xo].all(t):this.db.status==="opening"?this.db.defer(()=>this._all(e,t)):this.nextTick(t,new fO("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},r.prototype._seek=function(e,t){this[xo]!==null?this[xo]._seek(e,t):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,t))},r.prototype._close=function(e){this[xo]!==null?this[xo].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};tv.DeferredIterator=Q7;tv.DeferredKeyIterator=X7;tv.DeferredValueIterator=Z7});var hO=P(Hoe=>{"use strict";var{fromCallback:qoe}=c5(),rv=Za(),{getCallback:cLe,getOptions:uLe}=q7(),nv=Symbol("promise"),ea=Symbol("status"),x2=Symbol("operations"),p5=Symbol("finishClose"),S2=Symbol("closeCallbacks"),dO=class{constructor(e){if(typeof e!="object"||e===null){let t=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${t}`)}this[x2]=[],this[S2]=[],this[ea]="open",this[p5]=this[p5].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[x2].length}put(e,t,n){if(this[ea]!=="open")throw new rv("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(e)||this.db._checkValue(t);if(i)throw i;let o=n&&n.sublevel!=null?n.sublevel:this.db,s=n,a=o.keyEncoding(n&&n.keyEncoding),c=o.valueEncoding(n&&n.valueEncoding),u=a.format;n={...n,keyEncoding:u,valueEncoding:c.format},o!==this.db&&(n.sublevel=null);let l=o.prefixKey(a.encode(e),u),f=c.encode(t);return this._put(l,f,n),this[x2].push({...s,type:"put",key:e,value:t}),this}_put(e,t,n){}del(e,t){if(this[ea]!=="open")throw new rv("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let n=this.db._checkKey(e);if(n)throw n;let i=t&&t.sublevel!=null?t.sublevel:this.db,o=t,s=i.keyEncoding(t&&t.keyEncoding),a=s.format;return t={...t,keyEncoding:a},i!==this.db&&(t.sublevel=null),this._del(i.prefixKey(s.encode(e),a),t),this[x2].push({...o,type:"del",key:e}),this}_del(e,t){}clear(){if(this[ea]!=="open")throw new rv("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[x2]=[],this}_clear(){}write(e,t){return t=cLe(e,t),t=qoe(t,nv),e=uLe(e),this[ea]!=="open"?this.nextTick(t,new rv("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(t):(this[ea]="writing",this._write(e,n=>{this[ea]="closing",this[S2].push(()=>t(n)),n||this.db.emit("batch",this[x2]),this._close(this[p5])})),t[nv]}_write(e,t){}close(e){return e=qoe(e,nv),this[ea]==="closing"?this[S2].push(e):this[ea]==="closed"?this.nextTick(e):(this[S2].push(e),this[ea]!=="writing"&&(this[ea]="closing",this._close(this[p5]))),e[nv]}_close(e){this.nextTick(e)}[p5](){this[ea]="closed",this.db.detachResource(this);let e=this[S2];this[S2]=[];for(let t of e)t()}};Hoe.AbstractChainedBatch=dO});var joe=P(Goe=>{"use strict";var{AbstractChainedBatch:lLe}=hO(),fLe=Za(),A2=Symbol("encoded"),pO=class extends lLe{constructor(e){super(e),this[A2]=[]}_put(e,t,n){this[A2].push({...n,type:"put",key:e,value:t})}_del(e,t){this[A2].push({...t,type:"del",key:e})}_clear(){this[A2]=[]}_write(e,t){this.db.status==="opening"?this.db.defer(()=>this._write(e,t)):this.db.status==="open"?this[A2].length===0?this.nextTick(t):this.db._batch(this[A2],e,t):this.nextTick(t,new fLe("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};Goe.DefaultChainedBatch=pO});var Qoe=P((p7t,Yoe)=>{"use strict";var Woe=Za(),dLe=Object.prototype.hasOwnProperty,hLe=new Set(["lt","lte","gt","gte"]);Yoe.exports=function(r,e){let t={};for(let n in r)if(dLe.call(r,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new Woe(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new Woe("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});hLe.has(n)?t[n]=e.encode(r[n]):t[n]=r[n]}return t.reverse=!!t.reverse,t.limit=Number.isInteger(t.limit)&&t.limit>=0?t.limit:-1,t}});var mO=P((m7t,Zoe)=>{var Xoe;Zoe.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):r=>(Xoe||(Xoe=Promise.resolve())).then(r).catch(e=>setTimeout(()=>{throw e},0))});var tse=P((g7t,ese)=>{"use strict";var Joe=mO();ese.exports=function(r,...e){e.length===0?Joe(r):Joe(()=>r(...e))}});var rse=P(iv=>{"use strict";var{AbstractIterator:pLe,AbstractKeyIterator:mLe,AbstractValueIterator:gLe}=Od(),T2=Symbol("unfix"),Ja=Symbol("iterator"),Vp=Symbol("handleOne"),Ld=Symbol("handleMany"),_l=Symbol("callback"),m5=class extends pLe{constructor(e,t,n,i){super(e,t),this[Ja]=n,this[T2]=i,this[Vp]=this[Vp].bind(this),this[Ld]=this[Ld].bind(this),this[_l]=null}[Vp](e,t,n){let i=this[_l];if(e)return i(e);t!==void 0&&(t=this[T2](t)),i(e,t,n)}[Ld](e,t){let n=this[_l];if(e)return n(e);for(let i of t){let o=i[0];o!==void 0&&(i[0]=this[T2](o))}n(e,t)}},g5=class extends mLe{constructor(e,t,n,i){super(e,t),this[Ja]=n,this[T2]=i,this[Vp]=this[Vp].bind(this),this[Ld]=this[Ld].bind(this),this[_l]=null}[Vp](e,t){let n=this[_l];if(e)return n(e);t!==void 0&&(t=this[T2](t)),n(e,t)}[Ld](e,t){let n=this[_l];if(e)return n(e);for(let i=0;i{"use strict";var gO=Za(),{Buffer:bO}=n5()||{},{AbstractSublevelIterator:yLe,AbstractSublevelKeyIterator:wLe,AbstractSublevelValueIterator:bLe}=rse(),El=Symbol("prefix"),nse=Symbol("upperBound"),w5=Symbol("prefixRange"),ls=Symbol("parent"),yO=Symbol("unfix"),ise=new TextEncoder,_Le={separator:"!"};ose.exports=function({AbstractLevel:r}){class e extends r{static defaults(n){if(typeof n=="string")throw new gO("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new gO("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?_Le:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:a,...c}=e.defaults(o);i=vLe(i,s);let u=s.charCodeAt(0)+1,l=n[ls]||n;if(!ise.encode(i).every(d=>d>u&&d<127))throw new gO(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(ELe(l,a),c);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[ls]=l,this[El]=new ov(f),this[nse]=new ov(h),this[yO]=new _O,this.nextTick=l.nextTick}prefixKey(n,i){if(i==="utf8")return this[El].utf8+n;if(n.byteLength===0)return this[El][i];if(i==="view"){let o=this[El].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[El].buffer;return bO.concat([o,n],o.byteLength+n.byteLength)}}[w5](n,i){n.gte!==void 0?n.gte=this.prefixKey(n.gte,i):n.gt!==void 0?n.gt=this.prefixKey(n.gt,i):n.gte=this[El][i],n.lte!==void 0?n.lte=this.prefixKey(n.lte,i):n.lt!==void 0?n.lt=this.prefixKey(n.lt,i):n.lte=this[nse][i]}get prefix(){return this[El].utf8}get db(){return this[ls]}_open(n,i){this[ls].open({passive:!0},i)}_put(n,i,o,s){this[ls].put(n,i,o,s)}_get(n,i,o){this[ls].get(n,i,o)}_getMany(n,i,o){this[ls].getMany(n,i,o)}_del(n,i,o){this[ls].del(n,i,o)}_batch(n,i,o){this[ls].batch(n,i,o)}_clear(n,i){this[w5](n,n.keyEncoding),this[ls].clear(n,i)}_iterator(n){this[w5](n,n.keyEncoding);let i=this[ls].iterator(n),o=this[yO].get(this[El].utf8.length,n.keyEncoding);return new yLe(this,n,i,o)}_keys(n){this[w5](n,n.keyEncoding);let i=this[ls].keys(n),o=this[yO].get(this[El].utf8.length,n.keyEncoding);return new wLe(this,n,i,o)}_values(n){this[w5](n,n.keyEncoding);let i=this[ls].values(n);return new bLe(this,n,i)}}return{AbstractSublevel:e}};var ELe=function(r,e){return{...r.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:wO(r,"utf8"),buffer:wO(r,"buffer"),view:wO(r,"view")}}},wO=function(r,e){return r.supports.encodings[e]?r.keyEncoding(e).name===e:!1},ov=class{constructor(e){this.utf8=e,this.view=ise.encode(e),this.buffer=bO?bO.from(this.view.buffer,0,this.view.byteLength):{}}},_O=class{constructor(){this.cache=new Map}get(e,t){let n=this.cache.get(t);return n===void 0&&(t==="view"?n=function(i,o){return o.subarray(i)}.bind(null,e):n=function(i,o){return o.slice(i)}.bind(null,e),this.cache.set(t,n)),n}},vLe=function(r,e){let t=0,n=r.length;for(;tt&&r[n-1]===e;)n--;return r.slice(t,n)}});var AO=P(SO=>{"use strict";var{supports:xLe}=Qie(),{Transcoder:SLe}=Toe(),{EventEmitter:ALe}=xi(),{fromCallback:Bd}=c5(),ec=Za(),{AbstractIterator:Kp}=Od(),{DefaultKeyIterator:TLe,DefaultValueIterator:ILe}=Koe(),{DeferredIterator:RLe,DeferredKeyIterator:CLe,DeferredValueIterator:PLe}=$oe(),{DefaultChainedBatch:ase}=joe(),{getCallback:$p,getOptions:Md}=q7(),sv=Qoe(),wt=Symbol("promise"),vl=Symbol("landed"),qp=Symbol("resources"),EO=Symbol("closeResources"),b5=Symbol("operations"),_5=Symbol("undefer"),av=Symbol("deferOpen"),cse=Symbol("options"),It=Symbol("status"),Hp=Symbol("defaultOptions"),I2=Symbol("transcoder"),cv=Symbol("keyEncoding"),vO=Symbol("valueEncoding"),kLe=()=>{},E5=class extends ALe{constructor(e,t){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");t=Md(t);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=t;this[qp]=new Set,this[b5]=[],this[av]=!0,this[cse]=s,this[It]="opening",this.supports=xLe(e,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:e.snapshots!==!1,permanence:e.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:e.encodings||{},events:Object.assign({},e.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[I2]=new SLe(NLe(this)),this[cv]=this[I2].encoding(n||"utf8"),this[vO]=this[I2].encoding(i||"utf8");for(let a of this[I2].encodings())this.supports.encodings[a.commonName]||(this.supports.encodings[a.commonName]=!0);this[Hp]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[cv].commonName,valueEncoding:this[vO].commonName}),key:Object.freeze({keyEncoding:this[cv].commonName})},this.nextTick(()=>{this[av]&&this.open({passive:!1},kLe)})}get status(){return this[It]}keyEncoding(e){return this[I2].encoding(e??this[cv])}valueEncoding(e){return this[I2].encoding(e??this[vO])}open(e,t){t=$p(e,t),t=Bd(t,wt),e={...this[cse],...Md(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[It]==="closing"||this[It]==="opening"?this.once(vl,i?()=>n(i):n):this[It]!=="open"?t(new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):t()};return e.passive?this[It]==="opening"?this.once(vl,n):this.nextTick(n):this[It]==="closed"||this[av]?(this[av]=!1,this[It]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[It]="closed",this[EO](()=>{this.emit(vl),n(i)}),this[_5]();return}this[It]="open",this[_5](),this.emit(vl),this[It]==="open"&&this.emit("open"),this[It]==="open"&&this.emit("ready"),n()})):this[It]==="open"?this.nextTick(n):this.once(vl,()=>this.open(e,t)),t[wt]}_open(e,t){this.nextTick(t)}close(e){e=Bd(e,wt);let t=n=>{this[It]==="opening"||this[It]==="closing"?this.once(vl,n?t(n):t):this[It]!=="closed"?e(new ec("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[It]==="open"){this[It]="closing",this.emit("closing");let n=i=>{this[It]="open",this[_5](),this.emit(vl),t(i)};this[EO](()=>{this._close(i=>{if(i)return n(i);this[It]="closed",this[_5](),this.emit(vl),this[It]==="closed"&&this.emit("closed"),t()})})}else this[It]==="closed"?this.nextTick(t):this.once(vl,()=>this.close(e));return e[wt]}[EO](e){if(this[qp].size===0)return this.nextTick(e);let t=this[qp].size,n=!0,i=()=>{--t===0&&(n?this.nextTick(e):e())};for(let o of this[qp])o.close(i);n=!1,this[qp].clear()}_close(e){this.nextTick(e)}get(e,t,n){if(n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].entry),this[It]==="opening")return this.defer(()=>this.get(e,t,n)),n[wt];if(R2(this,n))return n[wt];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[wt];let o=this.keyEncoding(t.keyEncoding),s=this.valueEncoding(t.valueEncoding),a=o.format,c=s.format;return(t.keyEncoding!==a||t.valueEncoding!==c)&&(t=Object.assign({},t,{keyEncoding:a,valueEncoding:c})),this._get(this.prefixKey(o.encode(e),a),t,(u,l)=>{if(u)return(u.code==="LEVEL_NOT_FOUND"||u.notFound||/NotFound/i.test(u))&&(u.code||(u.code="LEVEL_NOT_FOUND"),u.notFound||(u.notFound=!0),u.status||(u.status=404)),n(u);try{l=s.decode(l)}catch(f){return n(new ec("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,l)}),n[wt]}_get(e,t,n){this.nextTick(n,new Error("NotFound"))}getMany(e,t,n){if(n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].entry),this[It]==="opening")return this.defer(()=>this.getMany(e,t,n)),n[wt];if(R2(this,n))return n[wt];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[wt];if(e.length===0)return this.nextTick(n,null,[]),n[wt];let i=this.keyEncoding(t.keyEncoding),o=this.valueEncoding(t.valueEncoding),s=i.format,a=o.format;(t.keyEncoding!==s||t.valueEncoding!==a)&&(t=Object.assign({},t,{keyEncoding:s,valueEncoding:a}));let c=new Array(e.length);for(let u=0;u{if(u)return n(u);try{for(let f=0;fthis.put(e,t,n,i)),i[wt];if(R2(this,i))return i[wt];let o=this._checkKey(e)||this._checkValue(t);if(o)return this.nextTick(i,o),i[wt];let s=this.keyEncoding(n.keyEncoding),a=this.valueEncoding(n.valueEncoding),c=s.format,u=a.format;(n.keyEncoding!==c||n.valueEncoding!==u)&&(n=Object.assign({},n,{keyEncoding:c,valueEncoding:u}));let l=this.prefixKey(s.encode(e),c),f=a.encode(t);return this._put(l,f,n,h=>{if(h)return i(h);this.emit("put",e,t),i()}),i[wt]}_put(e,t,n,i){this.nextTick(i)}del(e,t,n){if(n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].key),this[It]==="opening")return this.defer(()=>this.del(e,t,n)),n[wt];if(R2(this,n))return n[wt];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[wt];let o=this.keyEncoding(t.keyEncoding),s=o.format;return t.keyEncoding!==s&&(t=Object.assign({},t,{keyEncoding:s})),this._del(this.prefixKey(o.encode(e),s),t,a=>{if(a)return n(a);this.emit("del",e),n()}),n[wt]}_del(e,t,n){this.nextTick(n)}batch(e,t,n){if(!arguments.length){if(this[It]==="opening")return new ase(this);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=$p(t,n),n=Bd(n,wt),t=Md(t,this[Hp].empty),this[It]==="opening")return this.defer(()=>this.batch(e,t,n)),n[wt];if(R2(this,n))return n[wt];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[wt];if(e.length===0)return this.nextTick(n),n[wt];let i=new Array(e.length),{keyEncoding:o,valueEncoding:s,...a}=t;for(let c=0;c{if(c)return n(c);this.emit("batch",e),n()}),n[wt]}_batch(e,t,n){this.nextTick(n)}sublevel(e,t){return this._sublevel(e,xO.defaults(t))}_sublevel(e,t){return new xO(this,e,t)}prefixKey(e,t){return e}clear(e,t){if(t=$p(e,t),t=Bd(t,wt),e=Md(e,this[Hp].empty),this[It]==="opening")return this.defer(()=>this.clear(e,t)),t[wt];if(R2(this,t))return t[wt];let n=e,i=this.keyEncoding(e.keyEncoding);return e=sv(e,i),e.keyEncoding=i.format,e.limit===0?this.nextTick(t):this._clear(e,o=>{if(o)return t(o);this.emit("clear",n),t()}),t[wt]}_clear(e,t){this.nextTick(t)}iterator(e){let t=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sv(e,t),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Kp.keyEncoding]=t,e[Kp.valueEncoding]=n,e.keyEncoding=t.format,e.valueEncoding=n.format,this[It]==="opening")return new RLe(this,e);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new Kp(this,e)}keys(e){let t=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sv(e,t),e[Kp.keyEncoding]=t,e[Kp.valueEncoding]=n,e.keyEncoding=t.format,e.valueEncoding=n.format,this[It]==="opening")return new CLe(this,e);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new TLe(this,e)}values(e){let t=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sv(e,t),e[Kp.keyEncoding]=t,e[Kp.valueEncoding]=n,e.keyEncoding=t.format,e.valueEncoding=n.format,this[It]==="opening")return new PLe(this,e);if(this[It]!=="open")throw new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new ILe(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[b5].push(e)}[_5](){if(this[b5].length===0)return;let e=this[b5];this[b5]=[];for(let t of e)t()}attachResource(e){if(typeof e!="object"||e===null||typeof e.close!="function")throw new TypeError("The first argument must be a resource object");this[qp].add(e)}detachResource(e){this[qp].delete(e)}_chainedBatch(){return new ase(this)}_checkKey(e){if(e==null)return new ec("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new ec("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};E5.prototype.nextTick=tse();var{AbstractSublevel:xO}=sse()({AbstractLevel:E5});SO.AbstractLevel=E5;SO.AbstractSublevel=xO;var R2=function(r,e){return r[It]!=="open"?(r.nextTick(e,new ec("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},NLe=function(r){return Object.keys(r.supports.encodings).filter(e=>!!r.supports.encodings[e])}});var TO=P(Gp=>{"use strict";Gp.AbstractLevel=AO().AbstractLevel;Gp.AbstractSublevel=AO().AbstractSublevel;Gp.AbstractIterator=Od().AbstractIterator;Gp.AbstractKeyIterator=Od().AbstractKeyIterator;Gp.AbstractValueIterator=Od().AbstractValueIterator;Gp.AbstractChainedBatch=hO().AbstractChainedBatch});var lse=P((E7t,use)=>{use.exports=OLe;var DLe=mO();function OLe(r,e,t){if(typeof e!="number")throw new Error("second argument must be a Number");let n,i,o,s,a,c=!0,u;Array.isArray(r)?(n=[],o=i=r.length):(s=Object.keys(r),n={},o=i=s.length);function l(h){function d(){t&&t(h,n),t=null}c?DLe(d):d()}function f(h,d,p){if(n[h]=p,d&&(a=!0),--o===0||d)l(d);else if(!a&&u{"use strict";fse.exports=function(e){let t=e.gte!==void 0?e.gte:e.gt!==void 0?e.gt:void 0,n=e.lte!==void 0?e.lte:e.lt!==void 0?e.lt:void 0,i=e.gte===void 0,o=e.lte===void 0;return t!==void 0&&n!==void 0?IDBKeyRange.bound(t,n,i,o):t!==void 0?IDBKeyRange.lowerBound(t,i):n!==void 0?IDBKeyRange.upperBound(n,o):null}});var RO=P((x7t,dse)=>{"use strict";var LLe=new TextEncoder;dse.exports=function(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):LLe.encode(r)}});var yse=P(gse=>{"use strict";var{AbstractIterator:BLe}=TO(),hse=IO(),uv=RO(),cu=Symbol("cache"),xl=Symbol("finished"),fs=Symbol("options"),Sl=Symbol("currentOptions"),jp=Symbol("position"),CO=Symbol("location"),C2=Symbol("first"),pse={},PO=class extends BLe{constructor(e,t,n){super(e,n),this[cu]=[],this[xl]=this.limit===0,this[fs]=n,this[Sl]={...n},this[jp]=void 0,this[CO]=t,this[C2]=!0}_nextv(e,t,n){if(this[C2]=!1,this[xl])return this.nextTick(n,null,[]);if(this[cu].length>0)return e=Math.min(e,this[cu].length),this.nextTick(n,null,this[cu].splice(0,e));this[jp]!==void 0&&(this[fs].reverse?(this[Sl].lt=this[jp],this[Sl].lte=void 0):(this[Sl].gt=this[jp],this[Sl].gte=void 0));let i;try{i=hse(this[Sl])}catch{return this[xl]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[CO]],"readonly"),s=o.objectStore(this[CO]),a=[];if(this[fs].reverse){let c=!this[fs].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[c](i,"prev").onsuccess=u=>{let l=u.target.result;if(l){let{key:f,value:h}=l;this[jp]=f,a.push([this[fs].keys&&f!==void 0?uv(f):void 0,this[fs].values&&h!==void 0?uv(h):void 0]),a.length{if(c===void 0||u===void 0)return;let f=Math.max(c.length,u.length);f===0||e===1/0?this[xl]=!0:this[jp]=c[f-1],a.length=f;for(let h=0;h{c=f.target.result,l()}:(c=[],this.nextTick(l)),this[fs].values?s.getAll(i,e<1/0?e:void 0).onsuccess=f=>{u=f.target.result,l()}:(u=[],this.nextTick(l))}o.onabort=()=>{n(o.error||new Error("aborted by user")),n=null},o.oncomplete=()=>{n(null,a),n=null}}_next(e){if(this[cu].length>0){let[t,n]=this[cu].shift();this.nextTick(e,null,t,n)}else if(this[xl])this.nextTick(e);else{let t=Math.min(100,this.limit-this.count);this[C2]&&(this[C2]=!1,t=1),this._nextv(t,pse,(n,i)=>{if(n)return e(n);this[cu]=i,this._next(e)})}}_all(e,t){this[C2]=!1;let n=this[cu].splice(0,this[cu].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(t,null,n);this._nextv(i,pse,(o,s)=>{if(o)return t(o);n.length>0&&(s=n.concat(s)),t(null,s)})}_seek(e,t){this[C2]=!0,this[cu]=[],this[xl]=!1,this[jp]=void 0,this[Sl]={...this[fs]};let n;try{n=hse(this[fs])}catch{this[xl]=!0;return}n!==null&&!n.includes(e)?this[xl]=!0:this[fs].reverse?this[Sl].lte=e:this[Sl].gte=e}};gse.Iterator=PO;function mse(r){typeof r.commit=="function"&&r.commit()}});var bse=P((A7t,wse)=>{"use strict";wse.exports=function(e,t,n,i,o){if(i.limit===0)return e.nextTick(o);let s=e.db.transaction([t],"readwrite"),a=s.objectStore(t),c=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let u=a.openKeyCursor?"openKeyCursor":"openCursor",l=i.reverse?"prev":"next";a[u](n,l).onsuccess=function(f){let h=f.target.result;h&&(a.delete(h.key).onsuccess=function(){(i.limit<=0||++c{"use strict";var{AbstractLevel:MLe}=TO(),_se=Za(),ULe=lse(),{fromCallback:FLe}=c5(),{Iterator:zLe}=yse(),Ese=RO(),VLe=bse(),KLe=IO(),xse="level-js-",v5=Symbol("idb"),kO=Symbol("namePrefix"),Al=Symbol("location"),NO=Symbol("version"),Wp=Symbol("store"),x5=Symbol("onComplete"),vse=Symbol("promise"),lv=class extends MLe{constructor(e,t,n){if(typeof t=="function"||typeof n=="function")throw new _se("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=t||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof e!="string")throw new Error("constructor requires a location string argument");this[Al]=e,this[kO]=i??xse,this[NO]=parseInt(o||1,10),this[v5]=null}get location(){return this[Al]}get namePrefix(){return this[kO]}get version(){return this[NO]}get db(){return this[v5]}get type(){return"browser-level"}_open(e,t){let n=indexedDB.open(this[kO]+this[Al],this[NO]);n.onerror=function(){t(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[v5]=n.result,t()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[Al])||o.createObjectStore(this[Al])}}[Wp](e){return this[v5].transaction([this[Al]],e).objectStore(this[Al])}[x5](e,t){let n=e.transaction;n.onabort=function(){t(n.error||new Error("aborted by user"))},n.oncomplete=function(){t(null,e.result)}}_get(e,t,n){let i=this[Wp]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[x5](o,function(s,a){if(s)return n(s);if(a===void 0)return n(new _se("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,Ese(a))})}_getMany(e,t,n){let i=this[Wp]("readonly"),o=e.map(s=>a=>{let c;try{c=i.get(s)}catch(u){return a(u)}c.onsuccess=()=>{let u=c.result;a(null,u===void 0?u:Ese(u))},c.onerror=u=>{u.stopPropagation(),a(c.error)}});ULe(o,16,n)}_del(e,t,n){let i=this[Wp]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[x5](o,n)}_put(e,t,n,i){let o=this[Wp]("readwrite"),s;try{s=o.put(t,e)}catch(a){return this.nextTick(i,a)}this[x5](s,i)}_iterator(e){return new zLe(this,this[Al],e)}_batch(e,t,n){let i=this[Wp]("readwrite"),o=i.transaction,s=0,a;o.onabort=function(){n(a||o.error||new Error("aborted by user"))},o.oncomplete=function(){n()};function c(){let u=e[s++],l=u.key,f;try{f=u.type==="del"?i.delete(l):i.put(u.value,l)}catch(h){a=h,o.abort();return}s=0)return VLe(this,this[Al],n,e,t);try{let o=this[Wp]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(t,o)}this[x5](i,t)}_close(e){this[v5].close(),this.nextTick(e)}};lv.destroy=function(r,e,t){typeof e=="function"&&(t=e,e=xse),t=FLe(t,vse);let n=indexedDB.deleteDatabase(e+r);return n.onsuccess=function(){t()},n.onerror=function(i){t(i)},t[vse]};Sse.BrowserLevel=lv});var Ise=P(Tse=>{Tse.Level=Ase().BrowserLevel});var Mse=P(($vt,Bse)=>{"use strict";Bse.exports=fi;var T5=Kd();function fi(r,e){this.lo=r>>>0,this.hi=e>>>0}var Qp=fi.zero=new fi(0,0);Qp.toNumber=function(){return 0};Qp.zzEncode=Qp.zzDecode=function(){return this};Qp.length=function(){return 1};var iBe=fi.zeroHash="\0\0\0\0\0\0\0\0";fi.fromNumber=function(e){if(e===0)return Qp;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new fi(n,i)};fi.from=function(e){if(typeof e=="number")return fi.fromNumber(e);if(T5.isString(e))if(T5.Long)e=T5.Long.fromString(e);else return fi.fromNumber(parseInt(e,10));return e.low||e.high?new fi(e.low>>>0,e.high>>>0):Qp};fi.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};fi.prototype.toLong=function(e){return T5.Long?new T5.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Vd=String.prototype.charCodeAt;fi.fromHash=function(e){return e===iBe?Qp:new fi((Vd.call(e,0)|Vd.call(e,1)<<8|Vd.call(e,2)<<16|Vd.call(e,3)<<24)>>>0,(Vd.call(e,4)|Vd.call(e,5)<<8|Vd.call(e,6)<<16|Vd.call(e,7)<<24)>>>0)};fi.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};fi.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};fi.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};fi.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var Kd=P(UO=>{"use strict";var Fe=UO;Fe.asPromise=N6();Fe.base64=O6();Fe.EventEmitter=B6();Fe.float=M6();Fe.inquire=U6();Fe.utf8=F6();Fe.pool=z6();Fe.LongBits=Mse();Fe.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Fe.global=Fe.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||UO;Fe.emptyArray=Object.freeze?Object.freeze([]):[];Fe.emptyObject=Object.freeze?Object.freeze({}):{};Fe.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Fe.isString=function(e){return typeof e=="string"||e instanceof String};Fe.isObject=function(e){return e&&typeof e=="object"};Fe.isset=Fe.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Fe.Buffer=function(){try{var r=Fe.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Fe._Buffer_from=null;Fe._Buffer_allocUnsafe=null;Fe.newBuffer=function(e){return typeof e=="number"?Fe.Buffer?Fe._Buffer_allocUnsafe(e):new Fe.Array(e):Fe.Buffer?Fe._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Fe.Array=typeof Uint8Array<"u"?Uint8Array:Array;Fe.Long=Fe.global.dcodeIO&&Fe.global.dcodeIO.Long||Fe.global.Long||Fe.inquire("long");Fe.key2Re=/^true|false|0|1$/;Fe.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Fe.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Fe.longToHash=function(e){return e?Fe.LongBits.from(e).toHash():Fe.LongBits.zeroHash};Fe.longFromHash=function(e,t){var n=Fe.LongBits.fromHash(e);return Fe.Long?Fe.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Use(r,e,t){for(var n=Object.keys(e),i=0;i-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Fe.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";$se.exports=Xt;var ta=Kd(),FO,mv=ta.LongBits,zse=ta.base64,Vse=ta.utf8;function I5(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function VO(){}function oBe(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Xt(){this.len=0,this.head=new I5(VO,0,0),this.tail=this.head,this.states=null}var Kse=function(){return ta.Buffer?function(){return(Xt.create=function(){return new FO})()}:function(){return new Xt}};Xt.create=Kse();Xt.alloc=function(e){return new ta.Array(e)};ta.Array!==Array&&(Xt.alloc=ta.pool(Xt.alloc,ta.Array.prototype.subarray));Xt.prototype._push=function(e,t,n){return this.tail=this.tail.next=new I5(e,t,n),this.len+=t,this};function KO(r,e,t){e[t]=r&255}function sBe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function $O(r,e){this.len=r,this.next=void 0,this.val=e}$O.prototype=Object.create(I5.prototype);$O.prototype.fn=sBe;Xt.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new $O((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Xt.prototype.int32=function(e){return e<0?this._push(qO,10,mv.fromNumber(e)):this.uint32(e)};Xt.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function qO(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Xt.prototype.uint64=function(e){var t=mv.from(e);return this._push(qO,t.length(),t)};Xt.prototype.int64=Xt.prototype.uint64;Xt.prototype.sint64=function(e){var t=mv.from(e).zzEncode();return this._push(qO,t.length(),t)};Xt.prototype.bool=function(e){return this._push(KO,1,e?1:0)};function zO(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Xt.prototype.fixed32=function(e){return this._push(zO,4,e>>>0)};Xt.prototype.sfixed32=Xt.prototype.fixed32;Xt.prototype.fixed64=function(e){var t=mv.from(e);return this._push(zO,4,t.lo)._push(zO,4,t.hi)};Xt.prototype.sfixed64=Xt.prototype.fixed64;Xt.prototype.float=function(e){return this._push(ta.float.writeFloatLE,4,e)};Xt.prototype.double=function(e){return this._push(ta.float.writeDoubleLE,8,e)};var aBe=ta.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(KO,1,0);if(ta.isString(e)){var n=Xt.alloc(t=zse.length(e));zse.decode(e,n,0),e=n}return this.uint32(t)._push(aBe,t,e)};Xt.prototype.string=function(e){var t=Vse.length(e);return t?this.uint32(t)._push(Vse.write,t,e):this._push(KO,1,0)};Xt.prototype.fork=function(){return this.states=new oBe(this),this.head=this.tail=new I5(VO,0,0),this.len=0,this};Xt.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 I5(VO,0,0),this.len=0),this};Xt.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Xt.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Xt._configure=function(r){FO=r,Xt.create=Kse(),FO._configure()}});var Gse=P((Gvt,Hse)=>{"use strict";Hse.exports=fu;var qse=HO();(fu.prototype=Object.create(qse.prototype)).constructor=fu;var $d=Kd();function fu(){qse.call(this)}fu._configure=function(){fu.alloc=$d._Buffer_allocUnsafe,fu.writeBytesBuffer=$d.Buffer&&$d.Buffer.prototype instanceof Uint8Array&&$d.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(fu.writeBytesBuffer,t,e),this};function cBe(r,e,t){r.length<40?$d.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}fu.prototype.string=function(e){var t=$d.Buffer.byteLength(e);return this.uint32(t),t&&this._push(cBe,t,e),this};fu._configure()});var WO=P((jvt,Xse)=>{"use strict";Xse.exports=En;var du=Kd(),jO,Yse=du.LongBits,uBe=du.utf8;function tc(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function En(r){this.buf=r,this.pos=0,this.len=r.length}var jse=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new En(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new En(e);throw Error("illegal buffer")},Qse=function(){return du.Buffer?function(t){return(En.create=function(i){return du.Buffer.isBuffer(i)?new jO(i):jse(i)})(t)}:jse};En.create=Qse();En.prototype._slice=du.Array.prototype.subarray||du.Array.prototype.slice;En.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,tc(this,10);return e}}();En.prototype.int32=function(){return this.uint32()|0};En.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function GO(){var r=new Yse(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw tc(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw tc(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}En.prototype.bool=function(){return this.uint32()!==0};function gv(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}En.prototype.fixed32=function(){if(this.pos+4>this.len)throw tc(this,4);return gv(this.buf,this.pos+=4)};En.prototype.sfixed32=function(){if(this.pos+4>this.len)throw tc(this,4);return gv(this.buf,this.pos+=4)|0};function Wse(){if(this.pos+8>this.len)throw tc(this,8);return new Yse(gv(this.buf,this.pos+=4),gv(this.buf,this.pos+=4))}En.prototype.float=function(){if(this.pos+4>this.len)throw tc(this,4);var e=du.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};En.prototype.double=function(){if(this.pos+8>this.len)throw tc(this,4);var e=du.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};En.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw tc(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};En.prototype.string=function(){var e=this.bytes();return uBe.read(e,0,e.length)};En.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw tc(this,e);this.pos+=e}else do if(this.pos>=this.len)throw tc(this);while(this.buf[this.pos++]&128);return this};En.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};En._configure=function(r){jO=r,En.create=Qse(),jO._configure();var e=du.Long?"toLong":"toNumber";du.merge(En.prototype,{int64:function(){return GO.call(this)[e](!1)},uint64:function(){return GO.call(this)[e](!0)},sint64:function(){return GO.call(this).zzDecode()[e](!1)},fixed64:function(){return Wse.call(this)[e](!0)},sfixed64:function(){return Wse.call(this)[e](!1)}})}});var tae=P((Wvt,eae)=>{"use strict";eae.exports=Xp;var Jse=WO();(Xp.prototype=Object.create(Jse.prototype)).constructor=Xp;var Zse=Kd();function Xp(r){Jse.call(this,r)}Xp._configure=function(){Zse.Buffer&&(Xp.prototype._slice=Zse.Buffer.prototype.slice)};Xp.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))};Xp._configure()});var nae=P((Yvt,rae)=>{"use strict";rae.exports=R5;var YO=Kd();(R5.prototype=Object.create(YO.EventEmitter.prototype)).constructor=R5;function R5(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");YO.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}R5.prototype.rpcCall=function r(e,t,n,i,o){if(!i)throw TypeError("request must be specified");var s=this;if(!o)return YO.asPromise(r,s,e,t,n,i);if(!s.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return s.rpcImpl(e,t[s.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return s.emit("error",c,e),o(c);if(u===null){s.end(!0);return}if(!(u instanceof n))try{u=n[s.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return s.emit("error",l,e),o(l)}return s.emit("data",u,e),o(null,u)})}catch(a){s.emit("error",a,e),setTimeout(function(){o(a)},0);return}};R5.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var oae=P(iae=>{"use strict";var lBe=iae;lBe.Service=nae()});var aae=P((Xvt,sae)=>{"use strict";sae.exports={}});var lae=P(uae=>{"use strict";var So=uae;So.build="minimal";So.Writer=HO();So.BufferWriter=Gse();So.Reader=WO();So.BufferReader=tae();So.util=Kd();So.rpc=oae();So.roots=aae();So.configure=cae;function cae(){So.util._configure(),So.Writer._configure(So.BufferWriter),So.Reader._configure(So.BufferReader)}cae()});var QO=P((Jvt,fae)=>{"use strict";fae.exports=lae()});var hae=P((dae,C5)=>{(function(r,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof k0=="function"&&typeof C5=="object"&&C5&&C5.exports&&(C5.exports=e(QO()))})(dae,function(r){"use strict";var e=r.Reader,t=r.Writer,n=r.util,i=r.roots.default||(r.roots.default={});return i.RPC=function(){function o(a){if(this.subscriptions=[],this.messages=[],a)for(var c=Object.keys(a),u=0;u>>3){case 1:f.subscriptions&&f.subscriptions.length||(f.subscriptions=[]),f.subscriptions.push(i.RPC.SubOpts.decode(c,c.uint32()));break;case 2:f.messages&&f.messages.length||(f.messages=[]),f.messages.push(i.RPC.Message.decode(c,c.uint32()));break;case 3:f.control=i.RPC.ControlMessage.decode(c,c.uint32());break;default:c.skipType(h&7);break}}return f},o.fromObject=function(c){if(c instanceof i.RPC)return c;var u=new i.RPC;if(c.subscriptions){if(!Array.isArray(c.subscriptions))throw TypeError(".RPC.subscriptions: array expected");u.subscriptions=[];for(var l=0;l>>3){case 1:d.subscribe=l.bool();break;case 2:d.topic=l.string();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.SubOpts)return l;var f=new i.RPC.SubOpts;return l.subscribe!=null&&(f.subscribe=!!l.subscribe),l.topic!=null&&(f.topic=String(l.topic)),f},a.toObject=function(l,f){f||(f={});var h={};return l.subscribe!=null&&l.hasOwnProperty("subscribe")&&(h.subscribe=l.subscribe,f.oneofs&&(h._subscribe="subscribe")),l.topic!=null&&l.hasOwnProperty("topic")&&(h.topic=l.topic,f.oneofs&&(h._topic="topic")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.Message=function(){function a(u){if(u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.from=l.bytes();break;case 2:d.data=l.bytes();break;case 3:d.seqno=l.bytes();break;case 4:d.topic=l.string();break;case 5:d.signature=l.bytes();break;case 6:d.key=l.bytes();break;default:l.skipType(p&7);break}}if(!d.hasOwnProperty("topic"))throw n.ProtocolError("missing required 'topic'",{instance:d});return d},a.fromObject=function(l){if(l instanceof i.RPC.Message)return l;var f=new i.RPC.Message;return l.from!=null&&(typeof l.from=="string"?n.base64.decode(l.from,f.from=n.newBuffer(n.base64.length(l.from)),0):l.from.length&&(f.from=l.from)),l.data!=null&&(typeof l.data=="string"?n.base64.decode(l.data,f.data=n.newBuffer(n.base64.length(l.data)),0):l.data.length&&(f.data=l.data)),l.seqno!=null&&(typeof l.seqno=="string"?n.base64.decode(l.seqno,f.seqno=n.newBuffer(n.base64.length(l.seqno)),0):l.seqno.length&&(f.seqno=l.seqno)),l.topic!=null&&(f.topic=String(l.topic)),l.signature!=null&&(typeof l.signature=="string"?n.base64.decode(l.signature,f.signature=n.newBuffer(n.base64.length(l.signature)),0):l.signature.length&&(f.signature=l.signature)),l.key!=null&&(typeof l.key=="string"?n.base64.decode(l.key,f.key=n.newBuffer(n.base64.length(l.key)),0):l.key.length&&(f.key=l.key)),f},a.toObject=function(l,f){f||(f={});var h={};return f.defaults&&(h.topic=""),l.from!=null&&l.hasOwnProperty("from")&&(h.from=f.bytes===String?n.base64.encode(l.from,0,l.from.length):f.bytes===Array?Array.prototype.slice.call(l.from):l.from,f.oneofs&&(h._from="from")),l.data!=null&&l.hasOwnProperty("data")&&(h.data=f.bytes===String?n.base64.encode(l.data,0,l.data.length):f.bytes===Array?Array.prototype.slice.call(l.data):l.data,f.oneofs&&(h._data="data")),l.seqno!=null&&l.hasOwnProperty("seqno")&&(h.seqno=f.bytes===String?n.base64.encode(l.seqno,0,l.seqno.length):f.bytes===Array?Array.prototype.slice.call(l.seqno):l.seqno,f.oneofs&&(h._seqno="seqno")),l.topic!=null&&l.hasOwnProperty("topic")&&(h.topic=l.topic),l.signature!=null&&l.hasOwnProperty("signature")&&(h.signature=f.bytes===String?n.base64.encode(l.signature,0,l.signature.length):f.bytes===Array?Array.prototype.slice.call(l.signature):l.signature,f.oneofs&&(h._signature="signature")),l.key!=null&&l.hasOwnProperty("key")&&(h.key=f.bytes===String?n.base64.encode(l.key,0,l.key.length):f.bytes===Array?Array.prototype.slice.call(l.key):l.key,f.oneofs&&(h._key="key")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.ControlMessage=function(){function a(c){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],c)for(var u=Object.keys(c),l=0;l>>3){case 1:h.ihave&&h.ihave.length||(h.ihave=[]),h.ihave.push(i.RPC.ControlIHave.decode(u,u.uint32()));break;case 2:h.iwant&&h.iwant.length||(h.iwant=[]),h.iwant.push(i.RPC.ControlIWant.decode(u,u.uint32()));break;case 3:h.graft&&h.graft.length||(h.graft=[]),h.graft.push(i.RPC.ControlGraft.decode(u,u.uint32()));break;case 4:h.prune&&h.prune.length||(h.prune=[]),h.prune.push(i.RPC.ControlPrune.decode(u,u.uint32()));break;default:u.skipType(d&7);break}}return h},a.fromObject=function(u){if(u instanceof i.RPC.ControlMessage)return u;var l=new i.RPC.ControlMessage;if(u.ihave){if(!Array.isArray(u.ihave))throw TypeError(".RPC.ControlMessage.ihave: array expected");l.ihave=[];for(var f=0;f>>3){case 1:d.topicID=l.string();break;case 2:d.messageIDs&&d.messageIDs.length||(d.messageIDs=[]),d.messageIDs.push(l.bytes());break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlIHave)return l;var f=new i.RPC.ControlIHave;if(l.topicID!=null&&(f.topicID=String(l.topicID)),l.messageIDs){if(!Array.isArray(l.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");f.messageIDs=[];for(var h=0;h>>3){case 1:h.messageIDs&&h.messageIDs.length||(h.messageIDs=[]),h.messageIDs.push(u.bytes());break;default:u.skipType(d&7);break}}return h},a.fromObject=function(u){if(u instanceof i.RPC.ControlIWant)return u;var l=new i.RPC.ControlIWant;if(u.messageIDs){if(!Array.isArray(u.messageIDs))throw TypeError(".RPC.ControlIWant.messageIDs: array expected");l.messageIDs=[];for(var f=0;f>>3){case 1:d.topicID=l.string();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlGraft)return l;var f=new i.RPC.ControlGraft;return l.topicID!=null&&(f.topicID=String(l.topicID)),f},a.toObject=function(l,f){f||(f={});var h={};return l.topicID!=null&&l.hasOwnProperty("topicID")&&(h.topicID=l.topicID,f.oneofs&&(h._topicID="topicID")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.ControlPrune=function(){function a(u){if(this.peers=[],u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.topicID=l.string();break;case 2:d.peers&&d.peers.length||(d.peers=[]),d.peers.push(i.RPC.PeerInfo.decode(l,l.uint32()));break;case 3:d.backoff=l.uint64();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlPrune)return l;var f=new i.RPC.ControlPrune;if(l.topicID!=null&&(f.topicID=String(l.topicID)),l.peers){if(!Array.isArray(l.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");f.peers=[];for(var h=0;h>>0,l.backoff.high>>>0).toNumber(!0))),f},a.toObject=function(l,f){f||(f={});var h={};if((f.arrays||f.defaults)&&(h.peers=[]),l.topicID!=null&&l.hasOwnProperty("topicID")&&(h.topicID=l.topicID,f.oneofs&&(h._topicID="topicID")),l.peers&&l.peers.length){h.peers=[];for(var d=0;d>>0,l.backoff.high>>>0).toNumber(!0):l.backoff,f.oneofs&&(h._backoff="backoff")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o.PeerInfo=function(){function a(u){if(u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.peerID=l.bytes();break;case 2:d.signedPeerRecord=l.bytes();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.PeerInfo)return l;var f=new i.RPC.PeerInfo;return l.peerID!=null&&(typeof l.peerID=="string"?n.base64.decode(l.peerID,f.peerID=n.newBuffer(n.base64.length(l.peerID)),0):l.peerID.length&&(f.peerID=l.peerID)),l.signedPeerRecord!=null&&(typeof l.signedPeerRecord=="string"?n.base64.decode(l.signedPeerRecord,f.signedPeerRecord=n.newBuffer(n.base64.length(l.signedPeerRecord)),0):l.signedPeerRecord.length&&(f.signedPeerRecord=l.signedPeerRecord)),f},a.toObject=function(l,f){f||(f={});var h={};return l.peerID!=null&&l.hasOwnProperty("peerID")&&(h.peerID=f.bytes===String?n.base64.encode(l.peerID,0,l.peerID.length):f.bytes===Array?Array.prototype.slice.call(l.peerID):l.peerID,f.oneofs&&(h._peerID="peerID")),l.signedPeerRecord!=null&&l.hasOwnProperty("signedPeerRecord")&&(h.signedPeerRecord=f.bytes===String?n.base64.encode(l.signedPeerRecord,0,l.signedPeerRecord.length):f.bytes===Array?Array.prototype.slice.call(l.signedPeerRecord):l.signedPeerRecord,f.oneofs&&(h._signedPeerRecord="signedPeerRecord")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),o}(),i})});var Sae=P((A9t,xae)=>{"use strict";function un(r,t){var t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(r)&&this._fromArray(r)}un.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};un.prototype.get=function(e){return this.peekAt(e)};un.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};un.prototype.peekFront=function(){return this.peek()};un.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(un.prototype,"length",{get:function(){return this.size()}});un.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};un.prototype.push=function(e){if(e===void 0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}};un.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o=this._list[t],s;if(e0;s--)this._list[t]=this._list[t=t-1+i&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(s=n-1-e;s>0;s--)this._list[t]=this._list[t=t+1+i&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+i&this._capacityMask}return o}}};un.prototype.remove=function(e,t){var n=e,i,o=t;if(n===(n|0)&&this._head!==this._tail){var s=this.size(),a=this._list.length;if(!(n>=s||n<-s||t<1)){if(n<0&&(n+=s),t===1||!t)return i=new Array(1),i[0]=this.removeOne(n),i;if(n===0&&n+t>=s)return i=this.toArray(),this.clear(),i;n+t>s&&(t=s-n);var c;for(i=new Array(t),c=0;c0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return i}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return i}if(n0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;o>0;)this._list[n=n-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=s-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;o>0;)this._list[n=n+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),i}}};un.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var i=this.size();if(n<0&&(n+=i),!(n>i))if(arguments.length>2){var o,s,a,c=arguments.length,u=this._list.length,l=2;if(!i||n0&&(this._head=this._head+n+u&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+u&this._capacityMask);c>l;)this.unshift(arguments[--c]);for(o=n;o>0;o--)this.unshift(s[o-1])}else{s=new Array(i-(n+t));var f=s.length;for(o=0;othis._tail){for(o=this._head;o>>=1,this._capacityMask>>>=1};xae.exports=un});var fue=P((nPt,lue)=>{lue.exports=r=>{if(r[Symbol.asyncIterator])return r;if(r.getReader)return async function*(){let e=r.getReader();try{for(;;){let{done:t,value:n}=await e.read();if(t)return;yield n}}finally{e.releaseLock()}}();throw new Error("unknown stream")}});var dL=P((JBt,Jle)=>{"use strict";var oUe=O1(),sUe=(r,e)=>({path:decodeURIComponent(new URL(r).pathname.split("/").pop()||""),content:aUe(r,e)});async function*aUe(r,e){yield*(await new oUe().get(r,e)).iterator()}Jle.exports=sUe});var r9=P((kFt,Nfe)=>{"use strict";function FUe(r){let e=new Uint8Array(r),t=0;if(r>0)if(r>65536)for(;tr?(crypto.getRandomValues(e.subarray(t,t+(r-t))),t+=r-t):(crypto.getRandomValues(e.subarray(t,t+65536)),t+=65536);else crypto.getRandomValues(e);return e}Nfe.exports=FUe});var RL=P((OFt,IL)=>{"use strict";var VUe=(r,e)=>Math.floor(Math.random()*(e-r+1)+r),Lfe=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Bfe=({clearTimeout:r,setTimeout:e,willResolve:t})=>(n,{value:i,signal:o}={})=>{if(o&&o.aborted)return Promise.reject(Lfe());let s,a,c,u=r||clearTimeout,l=()=>{u(s),c(Lfe())},f=()=>{o&&o.removeEventListener("abort",l)},h=new Promise((d,p)=>{a=()=>{f(),t?d(i):p(i)},c=p,s=(e||setTimeout)(a,n)});return o&&o.addEventListener("abort",l,{once:!0}),h.clear=()=>{u(s),s=null,a()},h},Mfe=r=>{let e=Bfe({...r,willResolve:!0});return e.reject=Bfe({...r,willResolve:!1}),e.range=(t,n,i)=>e(VUe(t,n),i),e},TL=Mfe();TL.createWithTimers=Mfe;IL.exports=TL;IL.exports.default=TL});var FL=P((gVt,tde)=>{"use strict";var Q2=new Map,eFe=()=>`${Date.now()}:${Math.floor(Math.random()*1e6)}`;async function tFe(r,e,t){for(;Q2.get(t);){try{await r()}catch(n){setTimeout(()=>{throw n},1);break}if(!Q2.get(t))break;await new Promise(n=>{let i=setTimeout(n,e);Q2.set(t,i)})}}function rFe(r,e,t){t=t||e;let n=eFe(),i=setTimeout(()=>{tFe(r,e,n)},t);return Q2.set(n,i),n}function nFe(r){let e=Q2.get(r);e&&(clearTimeout(e),Q2.delete(r))}tde.exports={setDelayedInterval:rFe,clearDelayedInterval:nFe}});var o4=P((oKt,ade)=>{ade.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ude=P((aKt,cde)=>{cde.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let n=Date.now();return t>=n?t-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var fde=P((cKt,lde)=>{var aFe=ude();lde.exports=aFe});var ys=P((lKt,dde)=>{dde.exports=class{constructor(e,t,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var Z2=P((dKt,pde)=>{var VL=o4(),cFe=fde(),hde=ys();pde.exports=class extends VL{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new cFe}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,n,i,o,s={}){let a=this._getRateLimiterRes(n,i,o);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,s)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(u=>{t(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof VL))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,n={}){let i=t*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,t,n,i={}){let o=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),t,o,i)}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(s);if(a>0)return o(new hde(0,a));this._upsert(s,t,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,o,s,t,c)}).catch(c=>{this._handleError(c,"consume",i,o,e,t,n)})})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,t,a))}).catch(a=>{this._handleError(a,"penalty",o,s,e,t,n)})})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,-t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,-t,a))}).catch(a=>{this._handleError(a,"reward",o,s,e,t,n)})})}get(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._get(n,t).then(s=>{i(s===null||typeof s>"u"?null:this._getRateLimiterRes(n,0,s))}).catch(s=>{this._handleError(s,"get",i,o,e,t)})})}delete(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._delete(n,t).then(s=>{this._inMemoryBlockedKeys.delete(n),i(s)}).catch(s=>{this._handleError(s,"delete",i,o,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,n,i={}){return new Promise((o,s)=>{this._upsert(e,t,n,!0,i).then(()=>{o(new hde(0,n>0?n:-1,t))}).catch(a=>{this._handleError(a,"block",o,s,this.parseKey(e),n/1e3,i)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,n,i=!1,o={}){throw new Error("You have to implement the method '_upsert'!")}}});var yde=P((hKt,gde)=>{var uFe=Z2(),lFe=ys(),mde="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",KL=class extends uFe{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:mde})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,n){let[i,o]=n;Array.isArray(i)&&([,i]=i,[,o]=o);let s=new lFe;return s.consumedPoints=parseInt(i),s.isFirstInDuration=s.consumedPoints===t,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=o,s}_upsert(e,t,n,i=!1){return new Promise((o,s)=>{if(!this._isRedisReady())return s(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,t,"EX",a):c.set(e,t),c.pttl(e).exec((u,l)=>u?s(u):o(l));else if(a>0){let u=function(l,f){return l?s(l):o(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,a,u):this.client.eval(mde,1,e,t,a,u)}else c.incrby(e,t).pttl(e).exec((u,l)=>u?s(u):o(l))})}_get(e){return new Promise((t,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,o)=>{if(i)n(i);else{let[s]=o;if(s===null)return t(null);t(o)}})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):t(o>0)})})}};gde.exports=KL});var _de=P((pKt,bde)=>{var fFe=Z2(),dFe=ys();function wde(r){try{let e=r.client?r.client:r,{version:t}=e.topology.s.options.metadata.driver,n=t.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var s4=class extends fFe{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=wde(this.client)}):(this._initCollection(),this._driverVersion=wde(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?s4.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,n){let i=new dFe,o;return typeof n.value>"u"?o=n:o=n.value,i.isFirstInDuration=o.points===t,i.consumedPoints=o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire!==null?Math.max(new Date(o.expire).getTime()-Date.now(),0):-1,i}_upsert(e,t,n,i=!1,o={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let s=o.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,s),c={$set:{key:e,points:t,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,s)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,s),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,s));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},s),p={$set:Object.assign({key:e,points:t,expire:n>0?new Date(Date.now()+n):null},s)};this._collection.findOneAndUpdate(d,p,u).then(g=>{l(g)}).catch(g=>{g&&g.code===11e3?this._upsert(e,t,n,i).then(w=>l(w)).catch(w=>f(w)):f(g)})}else f(h)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(o=>o.deletedCount>0)}};bde.exports=s4});var vde=P((mKt,Ede)=>{var hFe=Z2(),pFe=ys(),$L=class extends hFe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(n),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((n,i)=>{if(n)return t(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),t(i);n.query(this._getCreateTableStmt(),o=>{if(o)return this._releaseConnection(n),t(o);this._releaseConnection(n),e()})})}).catch(n=>{t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,n){let i=new pFe,[o]=n;return i.isFirstInDuration=t===o.points,i.consumedPoints=i.isFirstInDuration?t:o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire?Math.max(o.expire-Date.now(),0):-1,i}_upsertTransaction(e,t,n,i,o){return new Promise((s,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;o?(f=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = ?, expire = ?;`,h=[this.dbName,this.tableName,t,n,l,n,l]):(f=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = IF(expire <= ?, ?, points + (?)), - expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,t,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(p,g)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",w=>{if(w)return e.rollback(),a(w);s(g)})})})})})}_upsert(e,t,n,i=!1){return this.tableCreated?new Promise((o,s)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,n,i).then(c=>{o(c),this._releaseConnection(a)}).catch(c=>{s(c),this._releaseConnection(a)})}).catch(a=>{s(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(o,s)=>{o?n(o):s.length===0?t(null):t(s),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(o,s)=>{o?n(o):t(s.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Ede.exports=$L});var Sde=P((mKt,xde)=>{var mFe=Z2(),gFe=ys(),qL=class extends mFe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof t=="function"&&t():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{t()}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,t)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} ( + expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,t,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(p,g)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",w=>{if(w)return e.rollback(),a(w);s(g)})})})})})}_upsert(e,t,n,i=!1){return this.tableCreated?new Promise((o,s)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,n,i).then(c=>{o(c),this._releaseConnection(a)}).catch(c=>{s(c),this._releaseConnection(a)})}).catch(a=>{s(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(o,s)=>{o?n(o):s.length===0?t(null):t(s),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(o,s)=>{o?n(o):t(s.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Ede.exports=$L});var Sde=P((gKt,xde)=>{var mFe=Z2(),gFe=ys(),qL=class extends mFe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof t=="function"&&t():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{t()}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,t)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} ( key varchar(255) PRIMARY KEY, points integer NOT NULL DEFAULT 0, expire bigint @@ -163,14 +163,14 @@ END, expire = ${s} RETURNING points, expire;`,values:[e,t,o,Date.now()]})}_get(e){return this.tableCreated?new Promise((t,n)=>{this._query({name:"rlflx-get",text:` - SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),t(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};xde.exports=qL});var HL=P(()=>{});var Tde=P((bKt,Ade)=>{Ade.exports=class{constructor(e,t,n=null){this.value=e,this.expiresAt=t,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Rde=P((EKt,Ide)=>{var yFe=Tde(),GL=ys();Ide.exports=class{constructor(){this._storage={}}incrby(e,t,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+t,new GL(0,i,this._storage[e].value,!1)):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new yFe(t,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new GL(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new GL(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var WL=P((vKt,Pde)=>{var wFe=o4(),bFe=Rde(),Cde=ys(),jL=class extends wFe{constructor(e={}){super(e),this._memoryStorage=new bFe}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(s,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(s,c.consumedPoints,this.blockDuration)),o(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}block(e,t){let n=t*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,t),Promise.resolve(new Cde(0,n===0?-1:n,i))}set(e,t,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,n),Promise.resolve(new Cde(0,i===0?-1:i,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Pde.exports=jL});var Mde=P((xKt,Bde)=>{var kde=HL(),_Fe=Ju(),EFe=o4(),Dde=WL(),vFe=ys(),ca="rate_limiter_flexible",tg=null,Nde=function(r,e,t,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},r.send({channel:ca,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:i})},Ode=function(r){setTimeout(()=>{this._initiated?process.send(r):typeof this._promises[r.promiseId]<"u"&&Ode.call(this,r)},30)},J2=function(r,e,t,n,i){let o={channel:ca,keyPrefix:this.keyPrefix,func:r,promiseId:e,data:{key:t,arg:n,opts:i}};this._initiated?process.send(o):Ode.call(this,o)},Lde=function(r,e){if(!e||e.channel!==ca||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(n=>{Nde(r,e,"resolve",n)}).catch(n=>{Nde(r,e,"reject",n)})},xFe=function(r){if(!r||r.channel!==ca||r.keyPrefix!==this.keyPrefix)return!1;if(this._promises[r.promiseId]){clearTimeout(this._promises[r.promiseId].timeoutId);let e;switch(r.data===null||r.data===!0||r.data===!1?e=r.data:e=new vFe(r.data.remainingPoints,r.data.msBeforeNext,r.data.consumedPoints,r.data.isFirstInDuration),r.type){case"resolve":this._promises[r.promiseId].resolve(e);break;case"reject":this._promises[r.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${r.type}'`)}delete this._promises[r.promiseId]}},SFe=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},eg=function(r,e){let t=process.hrtime(),n=t[0].toString()+t[1].toString();return typeof this._promises[n]<"u"&&(n+=_Fe.randomBytes(12).toString("base64")),this._promises[n]={resolve:r,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},YL=class{constructor(){if(tg)return tg;this._rateLimiters={},kde.setMaxListeners(0),kde.on("message",(e,t)=>{t&&t.channel===ca&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new Dde(t.opts)),e.send({channel:ca,type:"init",keyPrefix:t.opts.keyPrefix})):Lde.call(this,e,t)}),tg=this}},QL=class{constructor(e){if(tg)return tg;this._rateLimiters={},e.launchBus((t,n)=>{n.on("process:msg",i=>{let o=i.raw;if(o&&o.channel===ca&&o.type==="init")typeof this._rateLimiters[o.opts.keyPrefix]>"u"&&(this._rateLimiters[o.opts.keyPrefix]=new Dde(o.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:ca,channel:ca,type:"init",keyPrefix:o.opts.keyPrefix},(s,a)=>{s&&console.log(s,a)});else{let s={send:a=>{let c=a;c.topic=ca,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};Lde.call(this,s,o)}})}),tg=this}},XL=class extends EFe{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===ca&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:xFe.call(this,t)}),process.send({channel:ca,type:"init",opts:SFe.call(this)}),this._promises={}}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"consume",s,e,t,n)})}penalty(e,t=1,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"penalty",s,e,t,n)})}reward(e,t=1,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"reward",s,e,t,n)})}block(e,t,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"block",s,e,t,n)})}get(e,t={}){return new Promise((n,i)=>{let o=eg.call(this,n,i);J2.call(this,"get",o,e,t)})}delete(e,t={}){return new Promise((n,i)=>{let o=eg.call(this,n,i);J2.call(this,"delete",o,e,t)})}};Bde.exports={RateLimiterClusterMaster:YL,RateLimiterClusterMasterPM2:QL,RateLimiterCluster:XL}});var Fde=P((SKt,Ude)=>{var AFe=Z2(),TFe=ys(),ZL=class extends AFe{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,n){let i=new TFe;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===t,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,t,n,i=!1,o={}){return new Promise((s,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,t,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(f)})}):this.client.incr(e,t,(l,f)=>{l||f===!1?this.client.add(e,t,u,(h,d)=>{if(h||!d)if(typeof o.attemptNumber>"u"||o.attemptNumber<3){let p=Object.assign({},o);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,t,n,i,p).then(g=>s(g)).catch(g=>a(g))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,g={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};s(g)}})})})}_get(e){return new Promise((t,n)=>{let i=Date.now();this.client.get(e,(o,s)=>{s?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:s,msBeforeNext:u>=0?Math.max(u-i,0):-1};t(l)}}):t(null)})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):o===!1?t(o):this.client.del(`${e}_expire`,s=>{s?n(s):t(o)})})})}};Ude.exports=ZL});var Kde=P((TKt,Vde)=>{var zde=ys();Vde.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new zde(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new zde(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),n)}block(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),n)}penalty(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),n)}reward(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),n)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var qde=P((RKt,$de)=>{var IFe=o4();$de.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof IFe))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((n,i)=>{let o=[];this._limiters.forEach(s=>{o.push(s.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(o).then(s=>{let a={},c=!1;s.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u{Hde.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var Qde=P((NKt,Yde)=>{var jde=Gde(),Wde=4294967295,JL="limiter";Yde.exports=class{constructor(e,t={maxQueueSize:Wde}){this._queueLimiters={KEY_DEFAULT:new b9(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=JL){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=JL){return this._queueLimiters[t]||(this._queueLimiters[t]=new b9(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var b9=class{constructor(e,t={maxQueueSize:Wde,key:JL}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((n,i)=>{if(e>t._limiterFlexible.points){i(new jde(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,n,i,e):t._limiterFlexible.consume(t._key,e).then(o=>{n(o.remainingPoints)}).catch(o=>{o instanceof Error?i(o):(t._queueRequest.call(t,n,i,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),o.msBeforeNext)))})})}_queueRequest(e,t,n){let i=this;i._queue.length{t.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(t.reject(n),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var Zde=P((OKt,Xde)=>{var eB=ys();Xde.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return new eB(e.remainingPoints,Math.min(e.msBeforeNext,t.msBeforeNext),e.consumedPoints,e.isFirstInDuration)}consume(e,t=1,n={}){return this._rateLimiter.consume(e,t,n).catch(i=>i instanceof eB?this._burstLimiter.consume(e,t,n).then(o=>Promise.resolve(this._combineRes(i,o))).catch(o=>o instanceof eB?Promise.reject(this._combineRes(i,o)):Promise.reject(o)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,n])=>this._combineRes(t,n))}get points(){return this._rateLimiter.points}}});var ehe=P((LKt,Jde)=>{var RFe=yde(),CFe=_de(),PFe=vde(),kFe=Sde(),{RateLimiterClusterMaster:NFe,RateLimiterClusterMasterPM2:DFe,RateLimiterCluster:OFe}=Mde(),LFe=WL(),BFe=Fde(),MFe=Kde(),UFe=qde(),FFe=Qde(),zFe=Zde(),VFe=ys();Jde.exports={RateLimiterRedis:RFe,RateLimiterMongo:CFe,RateLimiterMySQL:PFe,RateLimiterPostgres:kFe,RateLimiterMemory:LFe,RateLimiterMemcache:BFe,RateLimiterClusterMaster:NFe,RateLimiterClusterMasterPM2:DFe,RateLimiterCluster:OFe,RLWrapperBlackAndWhite:MFe,RateLimiterUnion:UFe,RateLimiterQueue:FFe,BurstyRateLimiter:zFe,RateLimiterRes:VFe}});var dB=P(u4=>{(function(){var r,e,t,n,i,o,s,a;a=function(c){var u,l,f,h;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,h=c&255,[u,l,f,h].join(".")},s=function(c){var u,l,f,h,d,p;for(u=[],f=h=0;h<=3&&c.length!==0;f=++h){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],l=p[1],c=c.substring(l),u.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),i=t("A"),e=function(c){var u,l,f,h,d;for(h=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),d=f;f>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")h=h*u+(10+t(c[f])-o)>>>0;else if("A"<=c[f]&&c[f]<="F")h=h*u+(10+t(c[f])-i)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");f++}if(f===d)throw new Error("empty octet");return[h,f]},r=function(){function c(u,l){var f,h,d,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=s(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(h=d=32;d>=0;h=--d)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(s(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,h;for(h=s(this.first),f=s(this.last),l=0;h<=f;)u(a(h),h,l),l++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),u4.ip2long=s,u4.long2ip=a,u4.Netmask=r}).call(u4)});var _he=P((bhe,N9)=>{(function(r){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",t={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",s="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${s})|(?:::)(?:${s})?)${e}\\.${e}\\.${e}\\.${e}(${o})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let g=0,w=-1,_=(d.match(a.zoneIndex)||[])[0],x,m;for(_&&(_=_.substring(1),d=d.replace(/%.+$/,""));(w=d.indexOf(":",w+1))>=0;)g++;if(d.substr(0,2)==="::"&&g--,d.substr(-2,2)==="::"&&g--,g>p)return null;for(m=p-g,x=":";m--;)x+="0:";return d=d.replace("::",x),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let y=d.split(":"),b=[];for(let E=0;E0;){if(x=g-w,x<0&&(x=0),d[_]>>x!==p[_]>>x)return!1;w-=g,_+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length=0;_-=1)if(x=this.octets[_],x in w){if(m=w[x],g&&m!==0)return null;m!==8&&(g=!0),p+=m}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<4;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<4;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let g=parseInt(p[2]);if(g>=0&&g<=32){let w=[this.parse(p[1]),g];return Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,g,w;if(p=d.match(t.fourOctet))return function(){let _=p.slice(1,6),x=[];for(let m=0;m<_.length;m++)g=_[m],x.push(l(g));return x}();if(p=d.match(t.longValue)){if(w=l(p[1]),w>4294967295||w<0)throw new Error("ipaddr: address outside defined range");return function(){let _=[],x;for(x=0;x<=24;x+=8)_.push(w>>x&255);return _}().reverse()}else return(p=d.match(t.twoOctet))?function(){let _=p.slice(1,4),x=[];if(w=l(_[1]),w>16777215||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(w>>16&255),x.push(w>>8&255),x.push(w&255),x}():(p=d.match(t.threeOctet))?function(){let _=p.slice(1,5),x=[];if(w=l(_[2]),w>65535||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(l(_[1])),x.push(w>>8&255),x.push(w&255),x}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],g=0,w=Math.floor(d/8);for(;g=0;m-=1)if(_=this.parts[m],_ in w){if(x=w[_],g&&x!==0)return null;x!==16&&(g=!0),p+=x}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,g=[],w=this.parts;for(let _=0;_>8),g.push(p&255);return g},d.prototype.toFixedLengthString=function(){let p=function(){let w=[];for(let _=0;_>8,g&255,w>>8,w&255])},d.prototype.toNormalizedString=function(){let p=function(){let w=[];for(let _=0;__&&(w=x.index,_=x[0].length);return _<0?g:`${g.substring(0,w)}::${g.substring(w+_)}`},d.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<16;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<16;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch(m){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${m})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,g,w;if((g=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(g[2]),p>=0&&p<=128))return w=[this.parse(g[1]),p],Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,g,w,_,x,m;if(w=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${w[1]}`);if(a.native.test(d))return c(d,8);if((w=d.match(a.transitional))&&(m=w[6]||"",p=c(w[1].slice(0,-1)+m,6),p.parts)){for(x=[parseInt(w[2]),parseInt(w[3]),parseInt(w[4]),parseInt(w[5])],g=0;g128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,w=Math.floor(d/8);for(;g{"use strict";function sze(r){return r>=55296&&r<=56319}function aze(r){return r>=56320&&r<=57343}The.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;cn)return t.slice(0,c-a.length+1)}return t}});var Che=P((Jqt,Rhe)=>{"use strict";function cze(r){return r>=55296&&r<=56319}function uze(r){return r>=56320&&r<=57343}Rhe.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var khe=P((eHt,Phe)=>{"use strict";var lze=Ihe(),fze=Che();Phe.exports=lze.bind(null,fze)});var Ohe=P((tHt,Dhe)=>{"use strict";var dze=khe(),hze=/[\/\?<>\\:\*\|"]/g,pze=/[\x00-\x1f\x80-\x9f]/g,mze=/^\.+$/,gze=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,yze=/[\. ]+$/;function Nhe(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(hze,e).replace(pze,e).replace(mze,e).replace(gze,e).replace(yze,e);return dze(t,255)}Dhe.exports=function(r,e){var t=e&&e.replacement||"",n=Nhe(r,t);return t===""?n:Nhe(n,"")}});var Uhe=P((rHt,Mhe)=>{var og=at();Ic();gr();var be=og.asn1,sg=Mhe.exports=og.pkcs7asn1=og.pkcs7asn1||{};og.pkcs7=og.pkcs7||{};og.pkcs7.asn1=sg;var Lhe={name:"ContentInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};sg.contentInfoValidator=Lhe;var Bhe={name:"EncryptedContentInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:be.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};sg.envelopedDataValidator={name:"EnvelopedData",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:be.Class.UNIVERSAL,type:be.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(Bhe)};sg.encryptedDataValidator={name:"EncryptedData",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"}].concat(Bhe)};var wze={name:"SignerInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:be.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:be.Class.UNIVERSAL,type:be.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:be.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};sg.signedDataValidator={name:"SignedData",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:be.Class.UNIVERSAL,type:be.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},Lhe,{name:"SignedData.Certificates",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:be.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:be.Class.UNIVERSAL,type:be.Type.SET,capture:"signerInfos",optional:!0,value:[wze]}]};sg.recipientInfoValidator={name:"RecipientInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:be.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:be.Class.UNIVERSAL,type:be.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var zhe=P((nHt,Fhe)=>{var p0=at();gr();p0.mgf=p0.mgf||{};var bze=Fhe.exports=p0.mgf.mgf1=p0.mgf1=p0.mgf1||{};bze.create=function(r){var e={generate:function(t,n){for(var i=new p0.util.ByteBuffer,o=Math.ceil(n/r.digestLength),s=0;s{var M9=at();zhe();Vhe.exports=M9.mgf=M9.mgf||{};M9.mgf.mgf1=M9.mgf1});var qhe=P((oHt,$he)=>{var m0=at();Dh();gr();var _ze=$he.exports=m0.pss=m0.pss||{};_ze.create=function(r){arguments.length===3&&(r={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var e=r.md,t=r.mgf,n=e.digestLength,i=r.salt||null;typeof i=="string"&&(i=m0.util.createBuffer(i));var o;if("saltLength"in r)o=r.saltLength;else if(i!==null)o=i.length();else throw new Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==o)throw new Error("Given salt length does not match length of given salt.");var s=r.prng||m0.random,a={};return a.encode=function(c,u){var l,f=u-1,h=Math.ceil(f/8),d=c.digest().getBytes();if(h>8*h-f&255;return b=String.fromCharCode(b.charCodeAt(0)&~E)+b.substr(1),b+w+String.fromCharCode(188)},a.verify=function(c,u,l){var f,h=l-1,d=Math.ceil(h/8);if(u=u.substr(-d),d>8*d-h&255;if(g.charCodeAt(0)&_)throw new Error("Bits beyond keysize not zero as expected.");var x=t.generate(w,p),m="";for(f=0;f{var Ke=at();Nh();Ic();yb();Uf();Khe();z1();vb();qhe();Bh();gr();var T=Ke.asn1,le=Yhe.exports=Ke.pki=Ke.pki||{},$t=le.oids,fn={};fn.CN=$t.commonName;fn.commonName="CN";fn.C=$t.countryName;fn.countryName="C";fn.L=$t.localityName;fn.localityName="L";fn.ST=$t.stateOrProvinceName;fn.stateOrProvinceName="ST";fn.O=$t.organizationName;fn.organizationName="O";fn.OU=$t.organizationalUnitName;fn.organizationalUnitName="OU";fn.E=$t.emailAddress;fn.emailAddress="E";var Ghe=Ke.pki.rsa.publicKeyValidator,Eze={name:"Certificate",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:T.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:T.Class.UNIVERSAL,type:T.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:T.Class.UNIVERSAL,type:T.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:T.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:T.Class.UNIVERSAL,type:T.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:T.Class.UNIVERSAL,type:T.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:T.Class.UNIVERSAL,type:T.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:T.Class.UNIVERSAL,type:T.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},Ghe,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:T.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:T.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:T.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:T.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},vze={name:"rsapss",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:T.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:T.Class.UNIVERSAL,type:T.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:T.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:T.Class.UNIVERSAL,type:T.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:T.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:T.Class.UNIVERSAL,type:T.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:T.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:T.Class.UNIVERSAL,type:T.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},xze={name:"CertificationRequestInfo",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:T.Class.UNIVERSAL,type:T.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},Ghe,{name:"CertificationRequestInfo.attributes",tagClass:T.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:T.Class.UNIVERSAL,type:T.Type.SET,constructed:!0}]}]}]},Sze={name:"CertificationRequest",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[xze,{name:"CertificationRequest.signatureAlgorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:T.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};le.RDNAttributesAsArray=function(r,e){for(var t=[],n,i,o,s=0;s2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=c[0],s.validity.notAfter=c[1],s.tbsCertificate=t.tbsCertificate,e){s.md=F9({signatureOid:s.signatureOid,type:"certificate"});var u=T.toDer(s.tbsCertificate);s.md.update(u.getBytes())}var l=Ke.md.sha1.create(),f=T.toDer(t.certIssuer);l.update(f.getBytes()),s.issuer.getField=function(p){return th(s.issuer,p)},s.issuer.addField=function(p){fa([p]),s.issuer.attributes.push(p)},s.issuer.attributes=le.RDNAttributesAsArray(t.certIssuer),t.certIssuerUniqueId&&(s.issuer.uniqueId=t.certIssuerUniqueId),s.issuer.hash=l.digest().toHex();var h=Ke.md.sha1.create(),d=T.toDer(t.certSubject);return h.update(d.getBytes()),s.subject.getField=function(p){return th(s.subject,p)},s.subject.addField=function(p){fa([p]),s.subject.attributes.push(p)},s.subject.attributes=le.RDNAttributesAsArray(t.certSubject),t.certSubjectUniqueId&&(s.subject.uniqueId=t.certSubjectUniqueId),s.subject.hash=h.digest().toHex(),t.certExtensions?s.extensions=le.certificateExtensionsFromAsn1(t.certExtensions):s.extensions=[],s.publicKey=le.publicKeyFromAsn1(t.subjectPublicKeyInfo),s};le.certificateExtensionsFromAsn1=function(r){for(var e=[],t=0;t1&&(n=t.value.charCodeAt(1),i=t.value.length>2?t.value.charCodeAt(2):0),e.digitalSignature=(n&128)===128,e.nonRepudiation=(n&64)===64,e.keyEncipherment=(n&32)===32,e.dataEncipherment=(n&16)===16,e.keyAgreement=(n&8)===8,e.keyCertSign=(n&4)===4,e.cRLSign=(n&2)===2,e.encipherOnly=(n&1)===1,e.decipherOnly=(i&128)===128}else if(e.name==="basicConstraints"){var t=T.fromDer(e.value);t.value.length>0&&t.value[0].type===T.Type.BOOLEAN?e.cA=t.value[0].value.charCodeAt(0)!==0:e.cA=!1;var o=null;t.value.length>0&&t.value[0].type===T.Type.INTEGER?o=t.value[0].value:t.value.length>1&&(o=t.value[1].value),o!==null&&(e.pathLenConstraint=T.derToInteger(o))}else if(e.name==="extKeyUsage")for(var t=T.fromDer(e.value),s=0;s1&&(n=t.value.charCodeAt(1)),e.client=(n&128)===128,e.server=(n&64)===64,e.email=(n&32)===32,e.objsign=(n&16)===16,e.reserved=(n&8)===8,e.sslCA=(n&4)===4,e.emailCA=(n&2)===2,e.objCA=(n&1)===1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];for(var c,t=T.fromDer(e.value),u=0;u"u"&&(e.type&&e.type in le.oids?e.name=le.oids[e.type]:e.shortName&&e.shortName in fn&&(e.name=le.oids[fn[e.shortName]])),typeof e.type>"u")if(e.name&&e.name in le.oids)e.type=le.oids[e.name];else{var n=new Error("Attribute type not specified.");throw n.attribute=e,n}if(typeof e.shortName>"u"&&e.name&&e.name in fn&&(e.shortName=fn[e.name]),e.type===$t.extensionRequest&&(e.valueConstructed=!0,e.valueTagClass=T.Type.SEQUENCE,!e.value&&e.extensions)){e.value=[];for(var i=0;i"u"){var n=new Error("Attribute value not specified.");throw n.attribute=e,n}}}function Whe(r,e){if(e=e||{},typeof r.name>"u"&&r.id&&r.id in le.oids&&(r.name=le.oids[r.id]),typeof r.id>"u")if(r.name&&r.name in le.oids)r.id=le.oids[r.name];else{var t=new Error("Extension ID not specified.");throw t.extension=r,t}if(typeof r.value<"u")return r;if(r.name==="keyUsage"){var n=0,i=0,o=0;r.digitalSignature&&(i|=128,n=7),r.nonRepudiation&&(i|=64,n=6),r.keyEncipherment&&(i|=32,n=5),r.dataEncipherment&&(i|=16,n=4),r.keyAgreement&&(i|=8,n=3),r.keyCertSign&&(i|=4,n=2),r.cRLSign&&(i|=2,n=1),r.encipherOnly&&(i|=1,n=0),r.decipherOnly&&(o|=128,n=7);var s=String.fromCharCode(n);o!==0?s+=String.fromCharCode(i)+String.fromCharCode(o):i!==0&&(s+=String.fromCharCode(i)),r.value=T.create(T.Class.UNIVERSAL,T.Type.BITSTRING,!1,s)}else if(r.name==="basicConstraints")r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]),r.cA&&r.value.value.push(T.create(T.Class.UNIVERSAL,T.Type.BOOLEAN,!1,String.fromCharCode(255))),"pathLenConstraint"in r&&r.value.value.push(T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(r.pathLenConstraint).getBytes()));else if(r.name==="extKeyUsage"){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);var a=r.value.value;for(var c in r)r[c]===!0&&(c in $t?a.push(T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer($t[c]).getBytes())):c.indexOf(".")!==-1&&a.push(T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(c).getBytes())))}else if(r.name==="nsCertType"){var n=0,i=0;r.client&&(i|=128,n=7),r.server&&(i|=64,n=6),r.email&&(i|=32,n=5),r.objsign&&(i|=16,n=4),r.reserved&&(i|=8,n=3),r.sslCA&&(i|=4,n=2),r.emailCA&&(i|=2,n=1),r.objCA&&(i|=1,n=0);var s=String.fromCharCode(n);i!==0&&(s+=String.fromCharCode(i)),r.value=T.create(T.Class.UNIVERSAL,T.Type.BITSTRING,!1,s)}else if(r.name==="subjectAltName"||r.name==="issuerAltName"){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);for(var u,l=0;l128)throw new Error('Invalid "nsComment" content.');r.value=T.create(T.Class.UNIVERSAL,T.Type.IA5STRING,!1,r.comment)}else if(r.name==="subjectKeyIdentifier"&&e.cert){var f=e.cert.generateSubjectKeyIdentifier();r.subjectKeyIdentifier=f.toHex(),r.value=T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,f.getBytes())}else if(r.name==="authorityKeyIdentifier"&&e.cert){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);var a=r.value.value;if(r.keyIdentifier){var h=r.keyIdentifier===!0?e.cert.generateSubjectKeyIdentifier().getBytes():r.keyIdentifier;a.push(T.create(T.Class.CONTEXT_SPECIFIC,0,!1,h))}if(r.authorityCertIssuer){var d=[T.create(T.Class.CONTEXT_SPECIFIC,4,!0,[ag(r.authorityCertIssuer===!0?e.cert.issuer:r.authorityCertIssuer)])];a.push(T.create(T.Class.CONTEXT_SPECIFIC,1,!0,d))}if(r.serialNumber){var p=Ke.util.hexToBytes(r.serialNumber===!0?e.cert.serialNumber:r.serialNumber);a.push(T.create(T.Class.CONTEXT_SPECIFIC,2,!1,p))}}else if(r.name==="cRLDistributionPoints"){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);for(var a=r.value.value,g=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]),w=T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[]),u,l=0;l"u"){var t=new Error("Extension value not specified.");throw t.extension=r,t}return r}function mB(r,e){switch(r){case $t["RSASSA-PSS"]:var t=[];return e.hash.algorithmOid!==void 0&&t.push(T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(e.hash.algorithmOid).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")])])),e.mgf.algorithmOid!==void 0&&t.push(T.create(T.Class.CONTEXT_SPECIFIC,1,!0,[T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(e.mgf.algorithmOid).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(e.mgf.hash.algorithmOid).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")])])])),e.saltLength!==void 0&&t.push(T.create(T.Class.CONTEXT_SPECIFIC,2,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(e.saltLength).getBytes())])),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,t);default:return T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")}}function Aze(r){var e=T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[]);if(r.attributes.length===0)return e;for(var t=r.attributes,n=0;n=Tze&&r0&&n.value.push(le.certificateExtensionsToAsn1(r.extensions)),n};le.getCertificationRequestInfo=function(r){var e=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(r.version).getBytes()),ag(r.subject),le.publicKeyToAsn1(r.publicKey),Aze(r)]);return e};le.distinguishedNameToAsn1=function(r){return ag(r)};le.certificateToAsn1=function(r){var e=r.tbsCertificate||le.getTBSCertificate(r);return T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[e,T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(r.signatureOid).getBytes()),mB(r.signatureOid,r.signatureParameters)]),T.create(T.Class.UNIVERSAL,T.Type.BITSTRING,!1,String.fromCharCode(0)+r.signature)])};le.certificateExtensionsToAsn1=function(r){var e=T.create(T.Class.CONTEXT_SPECIFIC,3,!0,[]),t=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);e.value.push(t);for(var n=0;n"u"&&(i=new Date);var o=!0,s=null,a=0;do{var c=e.shift(),u=null,l=!1;if(i&&(ic.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:le.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:i}),s===null){if(u=e[0]||r.getIssuer(c),u===null&&c.isIssuer(c)&&(l=!0,u=c),u){var f=u;Ke.util.isArray(f)||(f=[f]);for(var h=!1;!h&&f.length>0;){u=f.shift();try{h=u.verify(c)}catch{}}h||(s={message:"Certificate signature is invalid.",error:le.certificateError.bad_certificate})}s===null&&(!u||l)&&!r.hasCertificate(c)&&(s={message:"Certificate is not trusted.",error:le.certificateError.unknown_ca})}if(s===null&&u&&!c.isIssuer(u)&&(s={message:"Certificate issuer is invalid.",error:le.certificateError.bad_certificate}),s===null)for(var d={keyUsage:!0,basicConstraints:!0},p=0;s===null&&pw.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:le.certificateError.bad_certificate})}}var m=s===null?!0:s.error,y=t.verify?t.verify(m,a,n):m;if(y===!0)s=null;else throw m===!0&&(s={message:"The application rejected the certificate.",error:le.certificateError.bad_certificate}),(y||y===0)&&(typeof y=="object"&&!Ke.util.isArray(y)?(y.message&&(s.message=y.message),y.error&&(s.error=y.error)):typeof y=="string"&&(s.error=y)),s;o=!1,++a}while(e.length>0);return!0}});var Zhe=P((aHt,Xhe)=>{var ye=at();Nh();Ic();yb();z1();vb();Uhe();Dh();gr();gB();var L=ye.asn1,uo=Xhe.exports=ye.pkcs7=ye.pkcs7||{};uo.messageFromPem=function(r){var e=ye.pem.decode(r)[0];if(e.type!=="PKCS7"){var t=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw t.headerType=e.type,t}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var n=L.fromDer(e.body);return uo.messageFromAsn1(n)};uo.messageToPem=function(r,e){var t={type:"PKCS7",body:L.toDer(r.toAsn1()).getBytes()};return ye.pem.encode(t,{maxline:e})};uo.messageFromAsn1=function(r){var e={},t=[];if(!L.validate(r,uo.asn1.contentInfoValidator,e,t)){var n=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw n.errors=t,n}var i=L.derToOid(e.contentType),o;switch(i){case ye.pki.oids.envelopedData:o=uo.createEnvelopedData();break;case ye.pki.oids.encryptedData:o=uo.createEncryptedData();break;case ye.pki.oids.signedData:o=uo.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return o.fromAsn1(e.content.value[0]),o};uo.createSignedData=function(){var r=null;return r={type:ye.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(n){if(wB(r,n,uo.asn1.signedDataValidator),r.certificates=[],r.crls=[],r.digestAlgorithmIdentifiers=[],r.contentInfo=null,r.signerInfos=[],r.rawCapture.certificates)for(var i=r.rawCapture.certificates.value,o=0;o0&&s.value[0].value.push(L.create(L.Class.CONTEXT_SPECIFIC,0,!0,n)),o.length>0&&s.value[0].value.push(L.create(L.Class.CONTEXT_SPECIFIC,1,!0,o)),s.value[0].value.push(L.create(L.Class.UNIVERSAL,L.Type.SET,!0,r.signerInfos)),L.create(L.Class.UNIVERSAL,L.Type.SEQUENCE,!0,[L.create(L.Class.UNIVERSAL,L.Type.OID,!1,L.oidToDer(r.type).getBytes()),s])},addSigner:function(n){var i=n.issuer,o=n.serialNumber;if(n.certificate){var s=n.certificate;typeof s=="string"&&(s=ye.pki.certificateFromPem(s)),i=s.issuer.attributes,o=s.serialNumber}var a=n.key;if(!a)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof a=="string"&&(a=ye.pki.privateKeyFromPem(a));var c=n.digestAlgorithm||ye.pki.oids.sha1;switch(c){case ye.pki.oids.sha1:case ye.pki.oids.sha256:case ye.pki.oids.sha384:case ye.pki.oids.sha512:case ye.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var u=n.authenticatedAttributes||[];if(u.length>0){for(var l=!1,f=!1,h=0;h0){for(var t=L.create(L.Class.CONTEXT_SPECIFIC,1,!0,[]),n=0;n=t&&i{"use strict";P0e.exports=C0e;var _Ve=vA(),nh=C0e.prototype,EVe=new Date%1e9;function vVe(){return(Math.random()*1e9>>>0)+EVe++}function C0e(r){r=r||{},this.id=r.id||vVe(),this.max=r.max||1/0,this.items=r.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(r.lastModified||new Date);for(var e,t,n=this.items.length;n--;)e=this.items[n],t=new Date(e.expires)-new Date,this._lookup[e.key]=e,t>0?this.expire(e.key,t):t<=0&&this.delete(e.key)}nh.has=function(r){return r in this._lookup};nh.get=function(r){if(!this.has(r))return null;var e=this._lookup[r];return e.refresh&&this.expire(r,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};nh.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};nh.set=function(r,e,t){var n=this._lookup[r],i=this._lookup[r]={key:r,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),t&&("ttl"in t&&this.expire(r,t.ttl),"meta"in t&&(i.meta=t.meta),t.refresh&&(i.refresh=t.ttl)),this};nh.delete=function(r){var e=this._lookup[r];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[r],this.size--,this):!1};nh.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=_Ve(e)),typeof t!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),t),n.expires=Number(new Date)+t,this};nh.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};nh.toJSON=function(){for(var r=new Array(this.items.length),e,t=r.length;t--;)e=this.items[t],r[t]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:r}}});var V0e=P((VXt,z0e)=>{z0e.exports=class{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 this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var q0e=P(($Xt,$0e)=>{var K0e=V0e();$0e.exports=class{constructor(e){this.hwm=e||16,this.head=new K0e(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){let t=this.head;this.head=t.next=new K0e(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next){let t=this.tail.next;return this.tail.next=null,this.tail=t,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}});var G0e=P((qXt,H0e)=>{"use strict";var kVe=()=>{let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r};H0e.exports=kVe});var Q0e=P((GXt,Y0e)=>{var j0e=q0e(),W0e=G0e();Y0e.exports=class{constructor(){this._buffer=new j0e,this._waitingConsumers=new j0e}push(e){let{promise:t,resolve:n}=W0e();return this._buffer.push({chunk:e,resolve:n}),this._consume(),t}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){let e=this._waitingConsumers.shift(),t=this._buffer.shift();e.resolve(t.chunk),t.resolve()}}shift(){let{promise:e,resolve:t}=W0e();return this._waitingConsumers.push({resolve:t}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}});var a1e=P((cM,s1e)=>{var Rx=n5(),vu=Rx.Buffer;function o1e(r,e){for(var t in r)e[t]=r[t]}vu.from&&vu.alloc&&vu.allocUnsafe&&vu.allocUnsafeSlow?s1e.exports=Rx:(o1e(Rx,cM),cM.Buffer=R0);function R0(r,e,t){return vu(r,e,t)}R0.prototype=Object.create(vu.prototype);o1e(vu,R0);R0.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return vu(r,e,t)};R0.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=vu(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};R0.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return vu(r)};R0.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Rx.SlowBuffer(r)}});var c1e=P((HZt,lM)=>{"use strict";var uM=65536,OVe=4294967295;function LVe(){throw new Error(`Secure random number generation is not supported by this browser. -Use Chrome, Firefox or Internet Explorer 11`)}var BVe=a1e().Buffer,Cx=globalThis.crypto||globalThis.msCrypto;Cx&&Cx.getRandomValues?lM.exports=MVe:lM.exports=LVe;function MVe(r,e){if(r>OVe)throw new RangeError("requested too many random bytes");var t=BVe.allocUnsafe(r);if(r>0)if(r>uM)for(var n=0;n{"use strict";var UVe=c1e(),{EventEmitter:FVe}=xi();function u1e(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0,n=r.length;tt.vectorClock?e:t}static distance(e,t){let n=0,i=0,o=Math.min(e.length,t.length),s=Math.max(e.length,t.length);for(;i=0?(this._update(n,i,e),this):n.contacts.length0&&n.length[this.distance(i.id,e),i]).sort((i,o)=>i[0]-o[0]).slice(0,t).map(i=>i[1])}count(){let e=0;for(let t=[this.root];t.length>0;){let n=t.pop();n.contacts===null?t.push(n.right,n.left):e+=n.contacts.length}return e}_determineNode(e,t,n){let i=n>>3,o=n%8;return t.length<=i&&o!==0?e.left:t[i]&1<<7-o?e.right:e.left}get(e){O4("id",e);let t=0,n=this.root;for(;n.contacts===null;)n=this._determineNode(n,e,t++);let i=this._indexOf(n,e);return i>=0?n.contacts[i]:null}_indexOf(e,t){for(let n=0;n=0){let o=n.contacts.splice(i,1)[0];this.emit("removed",o)}return this}_split(e,t){e.left=fM(),e.right=fM();for(let o of e.contacts)this._determineNode(e,o.id,t).contacts.push(o);e.contacts=null;let n=this._determineNode(e,this.localNodeId,t),i=e.left===n?e.right:e.left;i.dontSplit=!0}toArray(){let e=[];for(let t=[this.root];t.length>0;){let n=t.pop();n.contacts===null?t.push(n.right,n.left):e=e.concat(n.contacts)}return e}*toIterable(){for(let e=[this.root];e.length>0;){let t=e.pop();t.contacts===null?e.push(t.right,t.left):yield*t.contacts}}_update(e,t,n){if(!u1e(e.contacts[t].id,n.id))throw new Error("wrong index for _update");let i=e.contacts[t],o=this.arbiter(i,n);o===i&&i!==n||(e.contacts.splice(t,1),e.contacts.push(o),this.emit("updated",i,o))}};l1e.exports=wg});var h1e=P((d1e,Px)=>{(function(r){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",t={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",s="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${s})|(?:::)(?:${s})?)${e}\\.${e}\\.${e}\\.${e}(${o})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let g=0,w=-1,_=(d.match(a.zoneIndex)||[])[0],x,m;for(_&&(_=_.substring(1),d=d.replace(/%.+$/,""));(w=d.indexOf(":",w+1))>=0;)g++;if(d.substr(0,2)==="::"&&g--,d.substr(-2,2)==="::"&&g--,g>p)return null;for(m=p-g,x=":";m--;)x+="0:";return d=d.replace("::",x),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let y=d.split(":"),b=[];for(let E=0;E0;){if(x=g-w,x<0&&(x=0),d[_]>>x!==p[_]>>x)return!1;w-=g,_+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length=0;_-=1)if(x=this.octets[_],x in w){if(m=w[x],g&&m!==0)return null;m!==8&&(g=!0),p+=m}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<4;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidCIDR=function(d){try{return this.parseCIDR(d),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<4;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let g=parseInt(p[2]);if(g>=0&&g<=32){let w=[this.parse(p[1]),g];return Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,g,w;if(p=d.match(t.fourOctet))return function(){let _=p.slice(1,6),x=[];for(let m=0;m<_.length;m++)g=_[m],x.push(l(g));return x}();if(p=d.match(t.longValue)){if(w=l(p[1]),w>4294967295||w<0)throw new Error("ipaddr: address outside defined range");return function(){let _=[],x;for(x=0;x<=24;x+=8)_.push(w>>x&255);return _}().reverse()}else return(p=d.match(t.twoOctet))?function(){let _=p.slice(1,4),x=[];if(w=l(_[1]),w>16777215||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(w>>16&255),x.push(w>>8&255),x.push(w&255),x}():(p=d.match(t.threeOctet))?function(){let _=p.slice(1,5),x=[];if(w=l(_[2]),w>65535||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(l(_[1])),x.push(w>>8&255),x.push(w&255),x}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],g=0,w=Math.floor(d/8);for(;g=0;m-=1)if(_=this.parts[m],_ in w){if(x=w[_],g&&x!==0)return null;x!==16&&(g=!0),p+=x}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,g=[],w=this.parts;for(let _=0;_>8),g.push(p&255);return g},d.prototype.toFixedLengthString=function(){let p=function(){let w=[];for(let _=0;_>8,g&255,w>>8,w&255])},d.prototype.toNormalizedString=function(){let p=function(){let w=[];for(let _=0;__&&(w=x.index,_=x[0].length);return _<0?g:`${g.substring(0,w)}::${g.substring(w+_)}`},d.prototype.toString=function(){return this.toRFC5952String()},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<16;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.isValidCIDR=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{return this.parseCIDR(d),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<16;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch(m){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${m})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,g,w;if((g=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(g[2]),p>=0&&p<=128))return w=[this.parse(g[1]),p],Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,g,w,_,x,m;if(w=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${w[1]}`);if(a.native.test(d))return c(d,8);if((w=d.match(a.transitional))&&(m=w[6]||"",p=w[1],w[1].endsWith("::")||(p=p.slice(0,-1)),p=c(p+m,6),p.parts)){for(x=[parseInt(w[2]),parseInt(w[3]),parseInt(w[4]),parseInt(w[5])],g=0;g128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,w=Math.floor(d/8);for(;g{"use strict";Object.defineProperty(rS,"__esModule",{value:!0});var SM=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&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(let 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(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&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((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},tS=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new SM;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:o=>i.push(o),stop:()=>i.stop(),fail:o=>i.fail(o),on:(o,s)=>{i.eventHandlers[o]=s}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};rS.EventIterator=tS;rS.default=tS});var eme=P($4=>{"use strict";Object.defineProperty($4,"__esModule",{value:!0});var AM=J1e();$4.EventIterator=AM.EventIterator;function _Ke(r,e,t){return new AM.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}$4.subscribe=_Ke;$4.default=AM.EventIterator});var H4=P((Eir,Rme)=>{Rme.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Pme=P((xir,Cme)=>{Cme.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let n=Date.now();return t>=n?t-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var Nme=P((Sir,kme)=>{var NKe=Pme();kme.exports=NKe});var vs=P((Tir,Dme)=>{Dme.exports=class{constructor(e,t,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var Ig=P((Rir,Lme)=>{var DM=H4(),DKe=Nme(),Ome=vs();Lme.exports=class extends DM{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new DKe}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,n,i,o,s={}){let a=this._getRateLimiterRes(n,i,o);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,s)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(u=>{t(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof DM))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,n={}){let i=t*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,t,n,i={}){let o=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),t,o,i)}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(s);if(a>0)return o(new Ome(0,a));this._upsert(s,t,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,o,s,t,c)}).catch(c=>{this._handleError(c,"consume",i,o,e,t,n)})})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,t,a))}).catch(a=>{this._handleError(a,"penalty",o,s,e,t,n)})})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,-t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,-t,a))}).catch(a=>{this._handleError(a,"reward",o,s,e,t,n)})})}get(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._get(n,t).then(s=>{i(s===null||typeof s>"u"?null:this._getRateLimiterRes(n,0,s))}).catch(s=>{this._handleError(s,"get",i,o,e,t)})})}delete(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._delete(n,t).then(s=>{this._inMemoryBlockedKeys.delete(n),i(s)}).catch(s=>{this._handleError(s,"delete",i,o,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,n,i={}){return new Promise((o,s)=>{this._upsert(e,t,n,!0,i).then(()=>{o(new Ome(0,n>0?n:-1,t))}).catch(a=>{this._handleError(a,"block",o,s,this.parseKey(e),n/1e3,i)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,n,i=!1,o={}){throw new Error("You have to implement the method '_upsert'!")}}});var Ume=P((Cir,Mme)=>{var OKe=Ig(),LKe=vs(),Bme="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",OM=class extends OKe{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:Bme})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,n){let[i,o]=n;Array.isArray(i)&&([,i]=i,[,o]=o);let s=new LKe;return s.consumedPoints=parseInt(i),s.isFirstInDuration=s.consumedPoints===t,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=o,s}_upsert(e,t,n,i=!1){return new Promise((o,s)=>{if(!this._isRedisReady())return s(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,t,"EX",a):c.set(e,t),c.pttl(e).exec((u,l)=>u?s(u):o(l));else if(a>0){let u=function(l,f){return l?s(l):o(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,a,u):this.client.eval(Bme,1,e,t,a,u)}else c.incrby(e,t).pttl(e).exec((u,l)=>u?s(u):o(l))})}_get(e){return new Promise((t,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,o)=>{if(i)n(i);else{let[s]=o;if(s===null)return t(null);t(o)}})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):t(o>0)})})}};Mme.exports=OM});var Vme=P((Pir,zme)=>{var BKe=Ig(),MKe=vs();function Fme(r){try{let e=r.client?r.client:r,{version:t}=e.topology.s.options.metadata.driver,n=t.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var G4=class extends BKe{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=Fme(this.client)}):(this._initCollection(),this._driverVersion=Fme(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?G4.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,n){let i=new MKe,o;return typeof n.value>"u"?o=n:o=n.value,i.isFirstInDuration=o.points===t,i.consumedPoints=o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire!==null?Math.max(new Date(o.expire).getTime()-Date.now(),0):-1,i}_upsert(e,t,n,i=!1,o={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let s=o.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,s),c={$set:{key:e,points:t,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,s)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,s),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,s));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},s),p={$set:Object.assign({key:e,points:t,expire:n>0?new Date(Date.now()+n):null},s)};this._collection.findOneAndUpdate(d,p,u).then(g=>{l(g)}).catch(g=>{g&&g.code===11e3?this._upsert(e,t,n,i).then(w=>l(w)).catch(w=>f(w)):f(g)})}else f(h)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(o=>o.deletedCount>0)}};zme.exports=G4});var $me=P((kir,Kme)=>{var UKe=Ig(),FKe=vs(),LM=class extends UKe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(n),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((n,i)=>{if(n)return t(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),t(i);n.query(this._getCreateTableStmt(),o=>{if(o)return this._releaseConnection(n),t(o);this._releaseConnection(n),e()})})}).catch(n=>{t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,n){let i=new FKe,[o]=n;return i.isFirstInDuration=t===o.points,i.consumedPoints=i.isFirstInDuration?t:o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire?Math.max(o.expire-Date.now(),0):-1,i}_upsertTransaction(e,t,n,i,o){return new Promise((s,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;o?(f=`INSERT INTO ??.?? VALUES (?, ?, ?) + SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),t(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};xde.exports=qL});var HL=P(()=>{});var Tde=P((_Kt,Ade)=>{Ade.exports=class{constructor(e,t,n=null){this.value=e,this.expiresAt=t,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Rde=P((vKt,Ide)=>{var yFe=Tde(),GL=ys();Ide.exports=class{constructor(){this._storage={}}incrby(e,t,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+t,new GL(0,i,this._storage[e].value,!1)):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new yFe(t,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new GL(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new GL(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var WL=P((xKt,Pde)=>{var wFe=o4(),bFe=Rde(),Cde=ys(),jL=class extends wFe{constructor(e={}){super(e),this._memoryStorage=new bFe}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(s,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(s,c.consumedPoints,this.blockDuration)),o(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}block(e,t){let n=t*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,t),Promise.resolve(new Cde(0,n===0?-1:n,i))}set(e,t,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,n),Promise.resolve(new Cde(0,i===0?-1:i,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Pde.exports=jL});var Mde=P((SKt,Bde)=>{var kde=HL(),_Fe=Ju(),EFe=o4(),Dde=WL(),vFe=ys(),ca="rate_limiter_flexible",tg=null,Nde=function(r,e,t,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},r.send({channel:ca,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:i})},Ode=function(r){setTimeout(()=>{this._initiated?process.send(r):typeof this._promises[r.promiseId]<"u"&&Ode.call(this,r)},30)},J2=function(r,e,t,n,i){let o={channel:ca,keyPrefix:this.keyPrefix,func:r,promiseId:e,data:{key:t,arg:n,opts:i}};this._initiated?process.send(o):Ode.call(this,o)},Lde=function(r,e){if(!e||e.channel!==ca||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(n=>{Nde(r,e,"resolve",n)}).catch(n=>{Nde(r,e,"reject",n)})},xFe=function(r){if(!r||r.channel!==ca||r.keyPrefix!==this.keyPrefix)return!1;if(this._promises[r.promiseId]){clearTimeout(this._promises[r.promiseId].timeoutId);let e;switch(r.data===null||r.data===!0||r.data===!1?e=r.data:e=new vFe(r.data.remainingPoints,r.data.msBeforeNext,r.data.consumedPoints,r.data.isFirstInDuration),r.type){case"resolve":this._promises[r.promiseId].resolve(e);break;case"reject":this._promises[r.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${r.type}'`)}delete this._promises[r.promiseId]}},SFe=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},eg=function(r,e){let t=process.hrtime(),n=t[0].toString()+t[1].toString();return typeof this._promises[n]<"u"&&(n+=_Fe.randomBytes(12).toString("base64")),this._promises[n]={resolve:r,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},YL=class{constructor(){if(tg)return tg;this._rateLimiters={},kde.setMaxListeners(0),kde.on("message",(e,t)=>{t&&t.channel===ca&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new Dde(t.opts)),e.send({channel:ca,type:"init",keyPrefix:t.opts.keyPrefix})):Lde.call(this,e,t)}),tg=this}},QL=class{constructor(e){if(tg)return tg;this._rateLimiters={},e.launchBus((t,n)=>{n.on("process:msg",i=>{let o=i.raw;if(o&&o.channel===ca&&o.type==="init")typeof this._rateLimiters[o.opts.keyPrefix]>"u"&&(this._rateLimiters[o.opts.keyPrefix]=new Dde(o.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:ca,channel:ca,type:"init",keyPrefix:o.opts.keyPrefix},(s,a)=>{s&&console.log(s,a)});else{let s={send:a=>{let c=a;c.topic=ca,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};Lde.call(this,s,o)}})}),tg=this}},XL=class extends EFe{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===ca&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:xFe.call(this,t)}),process.send({channel:ca,type:"init",opts:SFe.call(this)}),this._promises={}}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"consume",s,e,t,n)})}penalty(e,t=1,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"penalty",s,e,t,n)})}reward(e,t=1,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"reward",s,e,t,n)})}block(e,t,n={}){return new Promise((i,o)=>{let s=eg.call(this,i,o);J2.call(this,"block",s,e,t,n)})}get(e,t={}){return new Promise((n,i)=>{let o=eg.call(this,n,i);J2.call(this,"get",o,e,t)})}delete(e,t={}){return new Promise((n,i)=>{let o=eg.call(this,n,i);J2.call(this,"delete",o,e,t)})}};Bde.exports={RateLimiterClusterMaster:YL,RateLimiterClusterMasterPM2:QL,RateLimiterCluster:XL}});var Fde=P((AKt,Ude)=>{var AFe=Z2(),TFe=ys(),ZL=class extends AFe{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,n){let i=new TFe;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===t,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,t,n,i=!1,o={}){return new Promise((s,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,t,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(f)})}):this.client.incr(e,t,(l,f)=>{l||f===!1?this.client.add(e,t,u,(h,d)=>{if(h||!d)if(typeof o.attemptNumber>"u"||o.attemptNumber<3){let p=Object.assign({},o);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,t,n,i,p).then(g=>s(g)).catch(g=>a(g))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,g={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};s(g)}})})})}_get(e){return new Promise((t,n)=>{let i=Date.now();this.client.get(e,(o,s)=>{s?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:s,msBeforeNext:u>=0?Math.max(u-i,0):-1};t(l)}}):t(null)})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):o===!1?t(o):this.client.del(`${e}_expire`,s=>{s?n(s):t(o)})})})}};Ude.exports=ZL});var Kde=P((IKt,Vde)=>{var zde=ys();Vde.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new zde(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new zde(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),n)}block(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),n)}penalty(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),n)}reward(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),n)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var qde=P((CKt,$de)=>{var IFe=o4();$de.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof IFe))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((n,i)=>{let o=[];this._limiters.forEach(s=>{o.push(s.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(o).then(s=>{let a={},c=!1;s.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u{Hde.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var Qde=P((DKt,Yde)=>{var jde=Gde(),Wde=4294967295,JL="limiter";Yde.exports=class{constructor(e,t={maxQueueSize:Wde}){this._queueLimiters={KEY_DEFAULT:new b9(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=JL){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=JL){return this._queueLimiters[t]||(this._queueLimiters[t]=new b9(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var b9=class{constructor(e,t={maxQueueSize:Wde,key:JL}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((n,i)=>{if(e>t._limiterFlexible.points){i(new jde(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,n,i,e):t._limiterFlexible.consume(t._key,e).then(o=>{n(o.remainingPoints)}).catch(o=>{o instanceof Error?i(o):(t._queueRequest.call(t,n,i,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),o.msBeforeNext)))})})}_queueRequest(e,t,n){let i=this;i._queue.length{t.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(t.reject(n),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var Zde=P((LKt,Xde)=>{var eB=ys();Xde.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return new eB(e.remainingPoints,Math.min(e.msBeforeNext,t.msBeforeNext),e.consumedPoints,e.isFirstInDuration)}consume(e,t=1,n={}){return this._rateLimiter.consume(e,t,n).catch(i=>i instanceof eB?this._burstLimiter.consume(e,t,n).then(o=>Promise.resolve(this._combineRes(i,o))).catch(o=>o instanceof eB?Promise.reject(this._combineRes(i,o)):Promise.reject(o)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,n])=>this._combineRes(t,n))}get points(){return this._rateLimiter.points}}});var ehe=P((BKt,Jde)=>{var RFe=yde(),CFe=_de(),PFe=vde(),kFe=Sde(),{RateLimiterClusterMaster:NFe,RateLimiterClusterMasterPM2:DFe,RateLimiterCluster:OFe}=Mde(),LFe=WL(),BFe=Fde(),MFe=Kde(),UFe=qde(),FFe=Qde(),zFe=Zde(),VFe=ys();Jde.exports={RateLimiterRedis:RFe,RateLimiterMongo:CFe,RateLimiterMySQL:PFe,RateLimiterPostgres:kFe,RateLimiterMemory:LFe,RateLimiterMemcache:BFe,RateLimiterClusterMaster:NFe,RateLimiterClusterMasterPM2:DFe,RateLimiterCluster:OFe,RLWrapperBlackAndWhite:MFe,RateLimiterUnion:UFe,RateLimiterQueue:FFe,BurstyRateLimiter:zFe,RateLimiterRes:VFe}});var dB=P(u4=>{(function(){var r,e,t,n,i,o,s,a;a=function(c){var u,l,f,h;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,h=c&255,[u,l,f,h].join(".")},s=function(c){var u,l,f,h,d,p;for(u=[],f=h=0;h<=3&&c.length!==0;f=++h){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],l=p[1],c=c.substring(l),u.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),i=t("A"),e=function(c){var u,l,f,h,d;for(h=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),d=f;f>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")h=h*u+(10+t(c[f])-o)>>>0;else if("A"<=c[f]&&c[f]<="F")h=h*u+(10+t(c[f])-i)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");f++}if(f===d)throw new Error("empty octet");return[h,f]},r=function(){function c(u,l){var f,h,d,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=s(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(h=d=32;d>=0;h=--d)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(s(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,h;for(h=s(this.first),f=s(this.last),l=0;h<=f;)u(a(h),h,l),l++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),u4.ip2long=s,u4.long2ip=a,u4.Netmask=r}).call(u4)});var _he=P((bhe,N9)=>{(function(r){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",t={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",s="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${s})|(?:::)(?:${s})?)${e}\\.${e}\\.${e}\\.${e}(${o})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let g=0,w=-1,_=(d.match(a.zoneIndex)||[])[0],x,m;for(_&&(_=_.substring(1),d=d.replace(/%.+$/,""));(w=d.indexOf(":",w+1))>=0;)g++;if(d.substr(0,2)==="::"&&g--,d.substr(-2,2)==="::"&&g--,g>p)return null;for(m=p-g,x=":";m--;)x+="0:";return d=d.replace("::",x),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let y=d.split(":"),b=[];for(let E=0;E0;){if(x=g-w,x<0&&(x=0),d[_]>>x!==p[_]>>x)return!1;w-=g,_+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length=0;_-=1)if(x=this.octets[_],x in w){if(m=w[x],g&&m!==0)return null;m!==8&&(g=!0),p+=m}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<4;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<4;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let g=parseInt(p[2]);if(g>=0&&g<=32){let w=[this.parse(p[1]),g];return Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,g,w;if(p=d.match(t.fourOctet))return function(){let _=p.slice(1,6),x=[];for(let m=0;m<_.length;m++)g=_[m],x.push(l(g));return x}();if(p=d.match(t.longValue)){if(w=l(p[1]),w>4294967295||w<0)throw new Error("ipaddr: address outside defined range");return function(){let _=[],x;for(x=0;x<=24;x+=8)_.push(w>>x&255);return _}().reverse()}else return(p=d.match(t.twoOctet))?function(){let _=p.slice(1,4),x=[];if(w=l(_[1]),w>16777215||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(w>>16&255),x.push(w>>8&255),x.push(w&255),x}():(p=d.match(t.threeOctet))?function(){let _=p.slice(1,5),x=[];if(w=l(_[2]),w>65535||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(l(_[1])),x.push(w>>8&255),x.push(w&255),x}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],g=0,w=Math.floor(d/8);for(;g=0;m-=1)if(_=this.parts[m],_ in w){if(x=w[_],g&&x!==0)return null;x!==16&&(g=!0),p+=x}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,g=[],w=this.parts;for(let _=0;_>8),g.push(p&255);return g},d.prototype.toFixedLengthString=function(){let p=function(){let w=[];for(let _=0;_>8,g&255,w>>8,w&255])},d.prototype.toNormalizedString=function(){let p=function(){let w=[];for(let _=0;__&&(w=x.index,_=x[0].length);return _<0?g:`${g.substring(0,w)}::${g.substring(w+_)}`},d.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<16;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<16;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch(m){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${m})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,g,w;if((g=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(g[2]),p>=0&&p<=128))return w=[this.parse(g[1]),p],Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,g,w,_,x,m;if(w=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${w[1]}`);if(a.native.test(d))return c(d,8);if((w=d.match(a.transitional))&&(m=w[6]||"",p=c(w[1].slice(0,-1)+m,6),p.parts)){for(x=[parseInt(w[2]),parseInt(w[3]),parseInt(w[4]),parseInt(w[5])],g=0;g128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,w=Math.floor(d/8);for(;g{"use strict";function sze(r){return r>=55296&&r<=56319}function aze(r){return r>=56320&&r<=57343}The.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;cn)return t.slice(0,c-a.length+1)}return t}});var Che=P((eHt,Rhe)=>{"use strict";function cze(r){return r>=55296&&r<=56319}function uze(r){return r>=56320&&r<=57343}Rhe.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var khe=P((tHt,Phe)=>{"use strict";var lze=Ihe(),fze=Che();Phe.exports=lze.bind(null,fze)});var Ohe=P((rHt,Dhe)=>{"use strict";var dze=khe(),hze=/[\/\?<>\\:\*\|"]/g,pze=/[\x00-\x1f\x80-\x9f]/g,mze=/^\.+$/,gze=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,yze=/[\. ]+$/;function Nhe(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(hze,e).replace(pze,e).replace(mze,e).replace(gze,e).replace(yze,e);return dze(t,255)}Dhe.exports=function(r,e){var t=e&&e.replacement||"",n=Nhe(r,t);return t===""?n:Nhe(n,"")}});var Uhe=P((nHt,Mhe)=>{var og=at();Ic();gr();var be=og.asn1,sg=Mhe.exports=og.pkcs7asn1=og.pkcs7asn1||{};og.pkcs7=og.pkcs7||{};og.pkcs7.asn1=sg;var Lhe={name:"ContentInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};sg.contentInfoValidator=Lhe;var Bhe={name:"EncryptedContentInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:be.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};sg.envelopedDataValidator={name:"EnvelopedData",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:be.Class.UNIVERSAL,type:be.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(Bhe)};sg.encryptedDataValidator={name:"EncryptedData",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"}].concat(Bhe)};var wze={name:"SignerInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:be.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:be.Class.UNIVERSAL,type:be.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:be.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};sg.signedDataValidator={name:"SignedData",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:be.Class.UNIVERSAL,type:be.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},Lhe,{name:"SignedData.Certificates",tagClass:be.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:be.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:be.Class.UNIVERSAL,type:be.Type.SET,capture:"signerInfos",optional:!0,value:[wze]}]};sg.recipientInfoValidator={name:"RecipientInfo",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:be.Class.UNIVERSAL,type:be.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:be.Class.UNIVERSAL,type:be.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:be.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:be.Class.UNIVERSAL,type:be.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var zhe=P((iHt,Fhe)=>{var p0=at();gr();p0.mgf=p0.mgf||{};var bze=Fhe.exports=p0.mgf.mgf1=p0.mgf1=p0.mgf1||{};bze.create=function(r){var e={generate:function(t,n){for(var i=new p0.util.ByteBuffer,o=Math.ceil(n/r.digestLength),s=0;s{var M9=at();zhe();Vhe.exports=M9.mgf=M9.mgf||{};M9.mgf.mgf1=M9.mgf1});var qhe=P((sHt,$he)=>{var m0=at();Dh();gr();var _ze=$he.exports=m0.pss=m0.pss||{};_ze.create=function(r){arguments.length===3&&(r={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var e=r.md,t=r.mgf,n=e.digestLength,i=r.salt||null;typeof i=="string"&&(i=m0.util.createBuffer(i));var o;if("saltLength"in r)o=r.saltLength;else if(i!==null)o=i.length();else throw new Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==o)throw new Error("Given salt length does not match length of given salt.");var s=r.prng||m0.random,a={};return a.encode=function(c,u){var l,f=u-1,h=Math.ceil(f/8),d=c.digest().getBytes();if(h>8*h-f&255;return b=String.fromCharCode(b.charCodeAt(0)&~E)+b.substr(1),b+w+String.fromCharCode(188)},a.verify=function(c,u,l){var f,h=l-1,d=Math.ceil(h/8);if(u=u.substr(-d),d>8*d-h&255;if(g.charCodeAt(0)&_)throw new Error("Bits beyond keysize not zero as expected.");var x=t.generate(w,p),m="";for(f=0;f{var Ke=at();Nh();Ic();yb();Uf();Khe();z1();vb();qhe();Bh();gr();var T=Ke.asn1,le=Yhe.exports=Ke.pki=Ke.pki||{},$t=le.oids,fn={};fn.CN=$t.commonName;fn.commonName="CN";fn.C=$t.countryName;fn.countryName="C";fn.L=$t.localityName;fn.localityName="L";fn.ST=$t.stateOrProvinceName;fn.stateOrProvinceName="ST";fn.O=$t.organizationName;fn.organizationName="O";fn.OU=$t.organizationalUnitName;fn.organizationalUnitName="OU";fn.E=$t.emailAddress;fn.emailAddress="E";var Ghe=Ke.pki.rsa.publicKeyValidator,Eze={name:"Certificate",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:T.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:T.Class.UNIVERSAL,type:T.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:T.Class.UNIVERSAL,type:T.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:T.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:T.Class.UNIVERSAL,type:T.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:T.Class.UNIVERSAL,type:T.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:T.Class.UNIVERSAL,type:T.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:T.Class.UNIVERSAL,type:T.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},Ghe,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:T.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:T.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:T.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:T.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},vze={name:"rsapss",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:T.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:T.Class.UNIVERSAL,type:T.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:T.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:T.Class.UNIVERSAL,type:T.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:T.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:T.Class.UNIVERSAL,type:T.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:T.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:T.Class.UNIVERSAL,type:T.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},xze={name:"CertificationRequestInfo",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:T.Class.UNIVERSAL,type:T.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},Ghe,{name:"CertificationRequestInfo.attributes",tagClass:T.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:T.Class.UNIVERSAL,type:T.Type.SET,constructed:!0}]}]}]},Sze={name:"CertificationRequest",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[xze,{name:"CertificationRequest.signatureAlgorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:T.Class.UNIVERSAL,type:T.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:T.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:T.Class.UNIVERSAL,type:T.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};le.RDNAttributesAsArray=function(r,e){for(var t=[],n,i,o,s=0;s2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=c[0],s.validity.notAfter=c[1],s.tbsCertificate=t.tbsCertificate,e){s.md=F9({signatureOid:s.signatureOid,type:"certificate"});var u=T.toDer(s.tbsCertificate);s.md.update(u.getBytes())}var l=Ke.md.sha1.create(),f=T.toDer(t.certIssuer);l.update(f.getBytes()),s.issuer.getField=function(p){return th(s.issuer,p)},s.issuer.addField=function(p){fa([p]),s.issuer.attributes.push(p)},s.issuer.attributes=le.RDNAttributesAsArray(t.certIssuer),t.certIssuerUniqueId&&(s.issuer.uniqueId=t.certIssuerUniqueId),s.issuer.hash=l.digest().toHex();var h=Ke.md.sha1.create(),d=T.toDer(t.certSubject);return h.update(d.getBytes()),s.subject.getField=function(p){return th(s.subject,p)},s.subject.addField=function(p){fa([p]),s.subject.attributes.push(p)},s.subject.attributes=le.RDNAttributesAsArray(t.certSubject),t.certSubjectUniqueId&&(s.subject.uniqueId=t.certSubjectUniqueId),s.subject.hash=h.digest().toHex(),t.certExtensions?s.extensions=le.certificateExtensionsFromAsn1(t.certExtensions):s.extensions=[],s.publicKey=le.publicKeyFromAsn1(t.subjectPublicKeyInfo),s};le.certificateExtensionsFromAsn1=function(r){for(var e=[],t=0;t1&&(n=t.value.charCodeAt(1),i=t.value.length>2?t.value.charCodeAt(2):0),e.digitalSignature=(n&128)===128,e.nonRepudiation=(n&64)===64,e.keyEncipherment=(n&32)===32,e.dataEncipherment=(n&16)===16,e.keyAgreement=(n&8)===8,e.keyCertSign=(n&4)===4,e.cRLSign=(n&2)===2,e.encipherOnly=(n&1)===1,e.decipherOnly=(i&128)===128}else if(e.name==="basicConstraints"){var t=T.fromDer(e.value);t.value.length>0&&t.value[0].type===T.Type.BOOLEAN?e.cA=t.value[0].value.charCodeAt(0)!==0:e.cA=!1;var o=null;t.value.length>0&&t.value[0].type===T.Type.INTEGER?o=t.value[0].value:t.value.length>1&&(o=t.value[1].value),o!==null&&(e.pathLenConstraint=T.derToInteger(o))}else if(e.name==="extKeyUsage")for(var t=T.fromDer(e.value),s=0;s1&&(n=t.value.charCodeAt(1)),e.client=(n&128)===128,e.server=(n&64)===64,e.email=(n&32)===32,e.objsign=(n&16)===16,e.reserved=(n&8)===8,e.sslCA=(n&4)===4,e.emailCA=(n&2)===2,e.objCA=(n&1)===1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];for(var c,t=T.fromDer(e.value),u=0;u"u"&&(e.type&&e.type in le.oids?e.name=le.oids[e.type]:e.shortName&&e.shortName in fn&&(e.name=le.oids[fn[e.shortName]])),typeof e.type>"u")if(e.name&&e.name in le.oids)e.type=le.oids[e.name];else{var n=new Error("Attribute type not specified.");throw n.attribute=e,n}if(typeof e.shortName>"u"&&e.name&&e.name in fn&&(e.shortName=fn[e.name]),e.type===$t.extensionRequest&&(e.valueConstructed=!0,e.valueTagClass=T.Type.SEQUENCE,!e.value&&e.extensions)){e.value=[];for(var i=0;i"u"){var n=new Error("Attribute value not specified.");throw n.attribute=e,n}}}function Whe(r,e){if(e=e||{},typeof r.name>"u"&&r.id&&r.id in le.oids&&(r.name=le.oids[r.id]),typeof r.id>"u")if(r.name&&r.name in le.oids)r.id=le.oids[r.name];else{var t=new Error("Extension ID not specified.");throw t.extension=r,t}if(typeof r.value<"u")return r;if(r.name==="keyUsage"){var n=0,i=0,o=0;r.digitalSignature&&(i|=128,n=7),r.nonRepudiation&&(i|=64,n=6),r.keyEncipherment&&(i|=32,n=5),r.dataEncipherment&&(i|=16,n=4),r.keyAgreement&&(i|=8,n=3),r.keyCertSign&&(i|=4,n=2),r.cRLSign&&(i|=2,n=1),r.encipherOnly&&(i|=1,n=0),r.decipherOnly&&(o|=128,n=7);var s=String.fromCharCode(n);o!==0?s+=String.fromCharCode(i)+String.fromCharCode(o):i!==0&&(s+=String.fromCharCode(i)),r.value=T.create(T.Class.UNIVERSAL,T.Type.BITSTRING,!1,s)}else if(r.name==="basicConstraints")r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]),r.cA&&r.value.value.push(T.create(T.Class.UNIVERSAL,T.Type.BOOLEAN,!1,String.fromCharCode(255))),"pathLenConstraint"in r&&r.value.value.push(T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(r.pathLenConstraint).getBytes()));else if(r.name==="extKeyUsage"){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);var a=r.value.value;for(var c in r)r[c]===!0&&(c in $t?a.push(T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer($t[c]).getBytes())):c.indexOf(".")!==-1&&a.push(T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(c).getBytes())))}else if(r.name==="nsCertType"){var n=0,i=0;r.client&&(i|=128,n=7),r.server&&(i|=64,n=6),r.email&&(i|=32,n=5),r.objsign&&(i|=16,n=4),r.reserved&&(i|=8,n=3),r.sslCA&&(i|=4,n=2),r.emailCA&&(i|=2,n=1),r.objCA&&(i|=1,n=0);var s=String.fromCharCode(n);i!==0&&(s+=String.fromCharCode(i)),r.value=T.create(T.Class.UNIVERSAL,T.Type.BITSTRING,!1,s)}else if(r.name==="subjectAltName"||r.name==="issuerAltName"){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);for(var u,l=0;l128)throw new Error('Invalid "nsComment" content.');r.value=T.create(T.Class.UNIVERSAL,T.Type.IA5STRING,!1,r.comment)}else if(r.name==="subjectKeyIdentifier"&&e.cert){var f=e.cert.generateSubjectKeyIdentifier();r.subjectKeyIdentifier=f.toHex(),r.value=T.create(T.Class.UNIVERSAL,T.Type.OCTETSTRING,!1,f.getBytes())}else if(r.name==="authorityKeyIdentifier"&&e.cert){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);var a=r.value.value;if(r.keyIdentifier){var h=r.keyIdentifier===!0?e.cert.generateSubjectKeyIdentifier().getBytes():r.keyIdentifier;a.push(T.create(T.Class.CONTEXT_SPECIFIC,0,!1,h))}if(r.authorityCertIssuer){var d=[T.create(T.Class.CONTEXT_SPECIFIC,4,!0,[ag(r.authorityCertIssuer===!0?e.cert.issuer:r.authorityCertIssuer)])];a.push(T.create(T.Class.CONTEXT_SPECIFIC,1,!0,d))}if(r.serialNumber){var p=Ke.util.hexToBytes(r.serialNumber===!0?e.cert.serialNumber:r.serialNumber);a.push(T.create(T.Class.CONTEXT_SPECIFIC,2,!1,p))}}else if(r.name==="cRLDistributionPoints"){r.value=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);for(var a=r.value.value,g=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]),w=T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[]),u,l=0;l"u"){var t=new Error("Extension value not specified.");throw t.extension=r,t}return r}function mB(r,e){switch(r){case $t["RSASSA-PSS"]:var t=[];return e.hash.algorithmOid!==void 0&&t.push(T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(e.hash.algorithmOid).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")])])),e.mgf.algorithmOid!==void 0&&t.push(T.create(T.Class.CONTEXT_SPECIFIC,1,!0,[T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(e.mgf.algorithmOid).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(e.mgf.hash.algorithmOid).getBytes()),T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")])])])),e.saltLength!==void 0&&t.push(T.create(T.Class.CONTEXT_SPECIFIC,2,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(e.saltLength).getBytes())])),T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,t);default:return T.create(T.Class.UNIVERSAL,T.Type.NULL,!1,"")}}function Aze(r){var e=T.create(T.Class.CONTEXT_SPECIFIC,0,!0,[]);if(r.attributes.length===0)return e;for(var t=r.attributes,n=0;n=Tze&&r0&&n.value.push(le.certificateExtensionsToAsn1(r.extensions)),n};le.getCertificationRequestInfo=function(r){var e=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.INTEGER,!1,T.integerToDer(r.version).getBytes()),ag(r.subject),le.publicKeyToAsn1(r.publicKey),Aze(r)]);return e};le.distinguishedNameToAsn1=function(r){return ag(r)};le.certificateToAsn1=function(r){var e=r.tbsCertificate||le.getTBSCertificate(r);return T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[e,T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[T.create(T.Class.UNIVERSAL,T.Type.OID,!1,T.oidToDer(r.signatureOid).getBytes()),mB(r.signatureOid,r.signatureParameters)]),T.create(T.Class.UNIVERSAL,T.Type.BITSTRING,!1,String.fromCharCode(0)+r.signature)])};le.certificateExtensionsToAsn1=function(r){var e=T.create(T.Class.CONTEXT_SPECIFIC,3,!0,[]),t=T.create(T.Class.UNIVERSAL,T.Type.SEQUENCE,!0,[]);e.value.push(t);for(var n=0;n"u"&&(i=new Date);var o=!0,s=null,a=0;do{var c=e.shift(),u=null,l=!1;if(i&&(ic.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:le.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:i}),s===null){if(u=e[0]||r.getIssuer(c),u===null&&c.isIssuer(c)&&(l=!0,u=c),u){var f=u;Ke.util.isArray(f)||(f=[f]);for(var h=!1;!h&&f.length>0;){u=f.shift();try{h=u.verify(c)}catch{}}h||(s={message:"Certificate signature is invalid.",error:le.certificateError.bad_certificate})}s===null&&(!u||l)&&!r.hasCertificate(c)&&(s={message:"Certificate is not trusted.",error:le.certificateError.unknown_ca})}if(s===null&&u&&!c.isIssuer(u)&&(s={message:"Certificate issuer is invalid.",error:le.certificateError.bad_certificate}),s===null)for(var d={keyUsage:!0,basicConstraints:!0},p=0;s===null&&pw.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:le.certificateError.bad_certificate})}}var m=s===null?!0:s.error,y=t.verify?t.verify(m,a,n):m;if(y===!0)s=null;else throw m===!0&&(s={message:"The application rejected the certificate.",error:le.certificateError.bad_certificate}),(y||y===0)&&(typeof y=="object"&&!Ke.util.isArray(y)?(y.message&&(s.message=y.message),y.error&&(s.error=y.error)):typeof y=="string"&&(s.error=y)),s;o=!1,++a}while(e.length>0);return!0}});var Zhe=P((cHt,Xhe)=>{var ye=at();Nh();Ic();yb();z1();vb();Uhe();Dh();gr();gB();var L=ye.asn1,uo=Xhe.exports=ye.pkcs7=ye.pkcs7||{};uo.messageFromPem=function(r){var e=ye.pem.decode(r)[0];if(e.type!=="PKCS7"){var t=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw t.headerType=e.type,t}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var n=L.fromDer(e.body);return uo.messageFromAsn1(n)};uo.messageToPem=function(r,e){var t={type:"PKCS7",body:L.toDer(r.toAsn1()).getBytes()};return ye.pem.encode(t,{maxline:e})};uo.messageFromAsn1=function(r){var e={},t=[];if(!L.validate(r,uo.asn1.contentInfoValidator,e,t)){var n=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw n.errors=t,n}var i=L.derToOid(e.contentType),o;switch(i){case ye.pki.oids.envelopedData:o=uo.createEnvelopedData();break;case ye.pki.oids.encryptedData:o=uo.createEncryptedData();break;case ye.pki.oids.signedData:o=uo.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return o.fromAsn1(e.content.value[0]),o};uo.createSignedData=function(){var r=null;return r={type:ye.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(n){if(wB(r,n,uo.asn1.signedDataValidator),r.certificates=[],r.crls=[],r.digestAlgorithmIdentifiers=[],r.contentInfo=null,r.signerInfos=[],r.rawCapture.certificates)for(var i=r.rawCapture.certificates.value,o=0;o0&&s.value[0].value.push(L.create(L.Class.CONTEXT_SPECIFIC,0,!0,n)),o.length>0&&s.value[0].value.push(L.create(L.Class.CONTEXT_SPECIFIC,1,!0,o)),s.value[0].value.push(L.create(L.Class.UNIVERSAL,L.Type.SET,!0,r.signerInfos)),L.create(L.Class.UNIVERSAL,L.Type.SEQUENCE,!0,[L.create(L.Class.UNIVERSAL,L.Type.OID,!1,L.oidToDer(r.type).getBytes()),s])},addSigner:function(n){var i=n.issuer,o=n.serialNumber;if(n.certificate){var s=n.certificate;typeof s=="string"&&(s=ye.pki.certificateFromPem(s)),i=s.issuer.attributes,o=s.serialNumber}var a=n.key;if(!a)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof a=="string"&&(a=ye.pki.privateKeyFromPem(a));var c=n.digestAlgorithm||ye.pki.oids.sha1;switch(c){case ye.pki.oids.sha1:case ye.pki.oids.sha256:case ye.pki.oids.sha384:case ye.pki.oids.sha512:case ye.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var u=n.authenticatedAttributes||[];if(u.length>0){for(var l=!1,f=!1,h=0;h0){for(var t=L.create(L.Class.CONTEXT_SPECIFIC,1,!0,[]),n=0;n=t&&i{"use strict";P0e.exports=C0e;var _Ve=vA(),nh=C0e.prototype,EVe=new Date%1e9;function vVe(){return(Math.random()*1e9>>>0)+EVe++}function C0e(r){r=r||{},this.id=r.id||vVe(),this.max=r.max||1/0,this.items=r.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(r.lastModified||new Date);for(var e,t,n=this.items.length;n--;)e=this.items[n],t=new Date(e.expires)-new Date,this._lookup[e.key]=e,t>0?this.expire(e.key,t):t<=0&&this.delete(e.key)}nh.has=function(r){return r in this._lookup};nh.get=function(r){if(!this.has(r))return null;var e=this._lookup[r];return e.refresh&&this.expire(r,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};nh.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};nh.set=function(r,e,t){var n=this._lookup[r],i=this._lookup[r]={key:r,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),t&&("ttl"in t&&this.expire(r,t.ttl),"meta"in t&&(i.meta=t.meta),t.refresh&&(i.refresh=t.ttl)),this};nh.delete=function(r){var e=this._lookup[r];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[r],this.size--,this):!1};nh.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=_Ve(e)),typeof t!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),t),n.expires=Number(new Date)+t,this};nh.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};nh.toJSON=function(){for(var r=new Array(this.items.length),e,t=r.length;t--;)e=this.items[t],r[t]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:r}}});var V0e=P((KXt,z0e)=>{z0e.exports=class{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 this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var q0e=P((qXt,$0e)=>{var K0e=V0e();$0e.exports=class{constructor(e){this.hwm=e||16,this.head=new K0e(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){let t=this.head;this.head=t.next=new K0e(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next){let t=this.tail.next;return this.tail.next=null,this.tail=t,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}});var G0e=P((HXt,H0e)=>{"use strict";var kVe=()=>{let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r};H0e.exports=kVe});var Q0e=P((jXt,Y0e)=>{var j0e=q0e(),W0e=G0e();Y0e.exports=class{constructor(){this._buffer=new j0e,this._waitingConsumers=new j0e}push(e){let{promise:t,resolve:n}=W0e();return this._buffer.push({chunk:e,resolve:n}),this._consume(),t}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){let e=this._waitingConsumers.shift(),t=this._buffer.shift();e.resolve(t.chunk),t.resolve()}}shift(){let{promise:e,resolve:t}=W0e();return this._waitingConsumers.push({resolve:t}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}});var a1e=P((cM,s1e)=>{var Rx=n5(),vu=Rx.Buffer;function o1e(r,e){for(var t in r)e[t]=r[t]}vu.from&&vu.alloc&&vu.allocUnsafe&&vu.allocUnsafeSlow?s1e.exports=Rx:(o1e(Rx,cM),cM.Buffer=R0);function R0(r,e,t){return vu(r,e,t)}R0.prototype=Object.create(vu.prototype);o1e(vu,R0);R0.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return vu(r,e,t)};R0.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=vu(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};R0.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return vu(r)};R0.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Rx.SlowBuffer(r)}});var c1e=P((GZt,lM)=>{"use strict";var uM=65536,OVe=4294967295;function LVe(){throw new Error(`Secure random number generation is not supported by this browser. +Use Chrome, Firefox or Internet Explorer 11`)}var BVe=a1e().Buffer,Cx=globalThis.crypto||globalThis.msCrypto;Cx&&Cx.getRandomValues?lM.exports=MVe:lM.exports=LVe;function MVe(r,e){if(r>OVe)throw new RangeError("requested too many random bytes");var t=BVe.allocUnsafe(r);if(r>0)if(r>uM)for(var n=0;n{"use strict";var UVe=c1e(),{EventEmitter:FVe}=xi();function u1e(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0,n=r.length;tt.vectorClock?e:t}static distance(e,t){let n=0,i=0,o=Math.min(e.length,t.length),s=Math.max(e.length,t.length);for(;i=0?(this._update(n,i,e),this):n.contacts.length0&&n.length[this.distance(i.id,e),i]).sort((i,o)=>i[0]-o[0]).slice(0,t).map(i=>i[1])}count(){let e=0;for(let t=[this.root];t.length>0;){let n=t.pop();n.contacts===null?t.push(n.right,n.left):e+=n.contacts.length}return e}_determineNode(e,t,n){let i=n>>3,o=n%8;return t.length<=i&&o!==0?e.left:t[i]&1<<7-o?e.right:e.left}get(e){O4("id",e);let t=0,n=this.root;for(;n.contacts===null;)n=this._determineNode(n,e,t++);let i=this._indexOf(n,e);return i>=0?n.contacts[i]:null}_indexOf(e,t){for(let n=0;n=0){let o=n.contacts.splice(i,1)[0];this.emit("removed",o)}return this}_split(e,t){e.left=fM(),e.right=fM();for(let o of e.contacts)this._determineNode(e,o.id,t).contacts.push(o);e.contacts=null;let n=this._determineNode(e,this.localNodeId,t),i=e.left===n?e.right:e.left;i.dontSplit=!0}toArray(){let e=[];for(let t=[this.root];t.length>0;){let n=t.pop();n.contacts===null?t.push(n.right,n.left):e=e.concat(n.contacts)}return e}*toIterable(){for(let e=[this.root];e.length>0;){let t=e.pop();t.contacts===null?e.push(t.right,t.left):yield*t.contacts}}_update(e,t,n){if(!u1e(e.contacts[t].id,n.id))throw new Error("wrong index for _update");let i=e.contacts[t],o=this.arbiter(i,n);o===i&&i!==n||(e.contacts.splice(t,1),e.contacts.push(o),this.emit("updated",i,o))}};l1e.exports=wg});var h1e=P((d1e,Px)=>{(function(r){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",t={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",s="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${s})|(?:::)(?:${s})?)${e}\\.${e}\\.${e}\\.${e}(${o})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let g=0,w=-1,_=(d.match(a.zoneIndex)||[])[0],x,m;for(_&&(_=_.substring(1),d=d.replace(/%.+$/,""));(w=d.indexOf(":",w+1))>=0;)g++;if(d.substr(0,2)==="::"&&g--,d.substr(-2,2)==="::"&&g--,g>p)return null;for(m=p-g,x=":";m--;)x+="0:";return d=d.replace("::",x),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let y=d.split(":"),b=[];for(let E=0;E0;){if(x=g-w,x<0&&(x=0),d[_]>>x!==p[_]>>x)return!1;w-=g,_+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length=0;_-=1)if(x=this.octets[_],x in w){if(m=w[x],g&&m!==0)return null;m!==8&&(g=!0),p+=m}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<4;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidCIDR=function(d){try{return this.parseCIDR(d),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<4;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let g=parseInt(p[2]);if(g>=0&&g<=32){let w=[this.parse(p[1]),g];return Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,g,w;if(p=d.match(t.fourOctet))return function(){let _=p.slice(1,6),x=[];for(let m=0;m<_.length;m++)g=_[m],x.push(l(g));return x}();if(p=d.match(t.longValue)){if(w=l(p[1]),w>4294967295||w<0)throw new Error("ipaddr: address outside defined range");return function(){let _=[],x;for(x=0;x<=24;x+=8)_.push(w>>x&255);return _}().reverse()}else return(p=d.match(t.twoOctet))?function(){let _=p.slice(1,4),x=[];if(w=l(_[1]),w>16777215||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(w>>16&255),x.push(w>>8&255),x.push(w&255),x}():(p=d.match(t.threeOctet))?function(){let _=p.slice(1,5),x=[];if(w=l(_[2]),w>65535||w<0)throw new Error("ipaddr: address outside defined range");return x.push(l(_[0])),x.push(l(_[1])),x.push(w>>8&255),x.push(w&255),x}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],g=0,w=Math.floor(d/8);for(;g=0;m-=1)if(_=this.parts[m],_ in w){if(x=w[_],g&&x!==0)return null;x!==16&&(g=!0),p+=x}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,g=[],w=this.parts;for(let _=0;_>8),g.push(p&255);return g},d.prototype.toFixedLengthString=function(){let p=function(){let w=[];for(let _=0;_>8,g&255,w>>8,w&255])},d.prototype.toNormalizedString=function(){let p=function(){let w=[];for(let _=0;__&&(w=x.index,_=x[0].length);return _<0?g:`${g.substring(0,w)}::${g.substring(w+_)}`},d.prototype.toString=function(){return this.toRFC5952String()},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),g=p[0].toByteArray(),w=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],x=0;for(;x<16;)_.push(parseInt(g[x],10)|parseInt(w[x],10)^255),x++;return new this(_)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.isValidCIDR=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{return this.parseCIDR(d),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,g,w,_,x;try{for(p=this.parseCIDR(d),w=p[0].toByteArray(),x=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),_=[],g=0;g<16;)_.push(parseInt(w[g],10)&parseInt(x[g],10)),g++;return new this(_)}catch(m){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${m})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,g,w;if((g=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(g[2]),p>=0&&p<=128))return w=[this.parse(g[1]),p],Object.defineProperty(w,"toString",{value:function(){return this.join("/")}}),w;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,g,w,_,x,m;if(w=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${w[1]}`);if(a.native.test(d))return c(d,8);if((w=d.match(a.transitional))&&(m=w[6]||"",p=w[1],w[1].endsWith("::")||(p=p.slice(0,-1)),p=c(p+m,6),p.parts)){for(x=[parseInt(w[2]),parseInt(w[3]),parseInt(w[4]),parseInt(w[5])],g=0;g128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,w=Math.floor(d/8);for(;g{"use strict";Object.defineProperty(rS,"__esModule",{value:!0});var SM=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&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(let 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(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&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((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},tS=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new SM;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:o=>i.push(o),stop:()=>i.stop(),fail:o=>i.fail(o),on:(o,s)=>{i.eventHandlers[o]=s}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};rS.EventIterator=tS;rS.default=tS});var eme=P($4=>{"use strict";Object.defineProperty($4,"__esModule",{value:!0});var AM=J1e();$4.EventIterator=AM.EventIterator;function _Ke(r,e,t){return new AM.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}$4.subscribe=_Ke;$4.default=AM.EventIterator});var H4=P((vir,Rme)=>{Rme.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Pme=P((Sir,Cme)=>{Cme.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let n=Date.now();return t>=n?t-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var Nme=P((Air,kme)=>{var NKe=Pme();kme.exports=NKe});var vs=P((Iir,Dme)=>{Dme.exports=class{constructor(e,t,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var Ig=P((Cir,Lme)=>{var DM=H4(),DKe=Nme(),Ome=vs();Lme.exports=class extends DM{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new DKe}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,n,i,o,s={}){let a=this._getRateLimiterRes(n,i,o);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,s)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(u=>{t(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof DM))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,n={}){let i=t*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,t,n,i={}){let o=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),t,o,i)}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(s);if(a>0)return o(new Ome(0,a));this._upsert(s,t,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,o,s,t,c)}).catch(c=>{this._handleError(c,"consume",i,o,e,t,n)})})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,t,a))}).catch(a=>{this._handleError(a,"penalty",o,s,e,t,n)})})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise((o,s)=>{this._upsert(i,-t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{o(this._getRateLimiterRes(i,-t,a))}).catch(a=>{this._handleError(a,"reward",o,s,e,t,n)})})}get(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._get(n,t).then(s=>{i(s===null||typeof s>"u"?null:this._getRateLimiterRes(n,0,s))}).catch(s=>{this._handleError(s,"get",i,o,e,t)})})}delete(e,t={}){let n=this.getKey(e);return new Promise((i,o)=>{this._delete(n,t).then(s=>{this._inMemoryBlockedKeys.delete(n),i(s)}).catch(s=>{this._handleError(s,"delete",i,o,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,n,i={}){return new Promise((o,s)=>{this._upsert(e,t,n,!0,i).then(()=>{o(new Ome(0,n>0?n:-1,t))}).catch(a=>{this._handleError(a,"block",o,s,this.parseKey(e),n/1e3,i)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,n,i=!1,o={}){throw new Error("You have to implement the method '_upsert'!")}}});var Ume=P((Pir,Mme)=>{var OKe=Ig(),LKe=vs(),Bme="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",OM=class extends OKe{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:Bme})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,n){let[i,o]=n;Array.isArray(i)&&([,i]=i,[,o]=o);let s=new LKe;return s.consumedPoints=parseInt(i),s.isFirstInDuration=s.consumedPoints===t,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=o,s}_upsert(e,t,n,i=!1){return new Promise((o,s)=>{if(!this._isRedisReady())return s(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,t,"EX",a):c.set(e,t),c.pttl(e).exec((u,l)=>u?s(u):o(l));else if(a>0){let u=function(l,f){return l?s(l):o(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,a,u):this.client.eval(Bme,1,e,t,a,u)}else c.incrby(e,t).pttl(e).exec((u,l)=>u?s(u):o(l))})}_get(e){return new Promise((t,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,o)=>{if(i)n(i);else{let[s]=o;if(s===null)return t(null);t(o)}})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):t(o>0)})})}};Mme.exports=OM});var Vme=P((kir,zme)=>{var BKe=Ig(),MKe=vs();function Fme(r){try{let e=r.client?r.client:r,{version:t}=e.topology.s.options.metadata.driver,n=t.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var G4=class extends BKe{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=Fme(this.client)}):(this._initCollection(),this._driverVersion=Fme(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?G4.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,n){let i=new MKe,o;return typeof n.value>"u"?o=n:o=n.value,i.isFirstInDuration=o.points===t,i.consumedPoints=o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire!==null?Math.max(new Date(o.expire).getTime()-Date.now(),0):-1,i}_upsert(e,t,n,i=!1,o={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let s=o.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,s),c={$set:{key:e,points:t,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,s)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,s),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,s));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},s),p={$set:Object.assign({key:e,points:t,expire:n>0?new Date(Date.now()+n):null},s)};this._collection.findOneAndUpdate(d,p,u).then(g=>{l(g)}).catch(g=>{g&&g.code===11e3?this._upsert(e,t,n,i).then(w=>l(w)).catch(w=>f(w)):f(g)})}else f(h)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(o=>o.deletedCount>0)}};zme.exports=G4});var $me=P((Nir,Kme)=>{var UKe=Ig(),FKe=vs(),LM=class extends UKe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(n),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((n,i)=>{if(n)return t(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),t(i);n.query(this._getCreateTableStmt(),o=>{if(o)return this._releaseConnection(n),t(o);this._releaseConnection(n),e()})})}).catch(n=>{t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,n){let i=new FKe,[o]=n;return i.isFirstInDuration=t===o.points,i.consumedPoints=i.isFirstInDuration?t:o.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=o.expire?Math.max(o.expire-Date.now(),0):-1,i}_upsertTransaction(e,t,n,i,o){return new Promise((s,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;o?(f=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = ?, expire = ?;`,h=[this.dbName,this.tableName,t,n,l,n,l]):(f=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = IF(expire <= ?, ?, points + (?)), - expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,t,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(p,g)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",w=>{if(w)return e.rollback(),a(w);s(g)})})})})})}_upsert(e,t,n,i=!1){return this.tableCreated?new Promise((o,s)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,n,i).then(c=>{o(c),this._releaseConnection(a)}).catch(c=>{s(c),this._releaseConnection(a)})}).catch(a=>{s(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(o,s)=>{o?n(o):s.length===0?t(null):t(s),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(o,s)=>{o?n(o):t(s.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Kme.exports=LM});var Hme=P((Nir,qme)=>{var zKe=Ig(),VKe=vs(),BM=class extends zKe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof t=="function"&&t():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{t()}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,t)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} ( + expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,t,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(p,g)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",w=>{if(w)return e.rollback(),a(w);s(g)})})})})})}_upsert(e,t,n,i=!1){return this.tableCreated?new Promise((o,s)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,n,i).then(c=>{o(c),this._releaseConnection(a)}).catch(c=>{s(c),this._releaseConnection(a)})}).catch(a=>{s(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(o,s)=>{o?n(o):s.length===0?t(null):t(s),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(o,s)=>{o?n(o):t(s.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Kme.exports=LM});var Hme=P((Dir,qme)=>{var zKe=Ig(),VKe=vs(),BM=class extends zKe{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof t=="function"&&t():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{t()}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,t)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} ( key varchar(255) PRIMARY KEY, points integer NOT NULL DEFAULT 0, expire bigint @@ -186,15 +186,15 @@ Use Chrome, Firefox or Internet Explorer 11`)}var BVe=a1e().Buffer,Cx=globalThis END, expire = ${s} RETURNING points, expire;`,values:[e,t,o,Date.now()]})}_get(e){return this.tableCreated?new Promise((t,n)=>{this._query({name:"rlflx-get",text:` - SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),t(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};qme.exports=BM});var jme=P((Oir,Gme)=>{Gme.exports=class{constructor(e,t,n=null){this.value=e,this.expiresAt=t,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Yme=P((Bir,Wme)=>{var KKe=jme(),MM=vs();Wme.exports=class{constructor(){this._storage={}}incrby(e,t,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+t,new MM(0,i,this._storage[e].value,!1)):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new KKe(t,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new MM(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new MM(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var FM=P((Mir,Xme)=>{var $Ke=H4(),qKe=Yme(),Qme=vs(),UM=class extends $Ke{constructor(e={}){super(e),this._memoryStorage=new qKe}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(s,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(s,c.consumedPoints,this.blockDuration)),o(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}block(e,t){let n=t*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,t),Promise.resolve(new Qme(0,n===0?-1:n,i))}set(e,t,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,n),Promise.resolve(new Qme(0,i===0?-1:i,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Xme.exports=UM});var i2e=P((Uir,n2e)=>{var Zme=HL(),HKe=Ju(),GKe=H4(),e2e=FM(),jKe=vs(),ya="rate_limiter_flexible",Pg=null,Jme=function(r,e,t,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},r.send({channel:ya,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:i})},t2e=function(r){setTimeout(()=>{this._initiated?process.send(r):typeof this._promises[r.promiseId]<"u"&&t2e.call(this,r)},30)},Rg=function(r,e,t,n,i){let o={channel:ya,keyPrefix:this.keyPrefix,func:r,promiseId:e,data:{key:t,arg:n,opts:i}};this._initiated?process.send(o):t2e.call(this,o)},r2e=function(r,e){if(!e||e.channel!==ya||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(n=>{Jme(r,e,"resolve",n)}).catch(n=>{Jme(r,e,"reject",n)})},WKe=function(r){if(!r||r.channel!==ya||r.keyPrefix!==this.keyPrefix)return!1;if(this._promises[r.promiseId]){clearTimeout(this._promises[r.promiseId].timeoutId);let e;switch(r.data===null||r.data===!0||r.data===!1?e=r.data:e=new jKe(r.data.remainingPoints,r.data.msBeforeNext,r.data.consumedPoints,r.data.isFirstInDuration),r.type){case"resolve":this._promises[r.promiseId].resolve(e);break;case"reject":this._promises[r.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${r.type}'`)}delete this._promises[r.promiseId]}},YKe=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},Cg=function(r,e){let t=process.hrtime(),n=t[0].toString()+t[1].toString();return typeof this._promises[n]<"u"&&(n+=HKe.randomBytes(12).toString("base64")),this._promises[n]={resolve:r,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},zM=class{constructor(){if(Pg)return Pg;this._rateLimiters={},Zme.setMaxListeners(0),Zme.on("message",(e,t)=>{t&&t.channel===ya&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new e2e(t.opts)),e.send({channel:ya,type:"init",keyPrefix:t.opts.keyPrefix})):r2e.call(this,e,t)}),Pg=this}},VM=class{constructor(e){if(Pg)return Pg;this._rateLimiters={},e.launchBus((t,n)=>{n.on("process:msg",i=>{let o=i.raw;if(o&&o.channel===ya&&o.type==="init")typeof this._rateLimiters[o.opts.keyPrefix]>"u"&&(this._rateLimiters[o.opts.keyPrefix]=new e2e(o.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:ya,channel:ya,type:"init",keyPrefix:o.opts.keyPrefix},(s,a)=>{s&&console.log(s,a)});else{let s={send:a=>{let c=a;c.topic=ya,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};r2e.call(this,s,o)}})}),Pg=this}},KM=class extends GKe{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===ya&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:WKe.call(this,t)}),process.send({channel:ya,type:"init",opts:YKe.call(this)}),this._promises={}}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"consume",s,e,t,n)})}penalty(e,t=1,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"penalty",s,e,t,n)})}reward(e,t=1,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"reward",s,e,t,n)})}block(e,t,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"block",s,e,t,n)})}get(e,t={}){return new Promise((n,i)=>{let o=Cg.call(this,n,i);Rg.call(this,"get",o,e,t)})}delete(e,t={}){return new Promise((n,i)=>{let o=Cg.call(this,n,i);Rg.call(this,"delete",o,e,t)})}};n2e.exports={RateLimiterClusterMaster:zM,RateLimiterClusterMasterPM2:VM,RateLimiterCluster:KM}});var s2e=P((Fir,o2e)=>{var QKe=Ig(),XKe=vs(),$M=class extends QKe{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,n){let i=new XKe;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===t,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,t,n,i=!1,o={}){return new Promise((s,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,t,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(f)})}):this.client.incr(e,t,(l,f)=>{l||f===!1?this.client.add(e,t,u,(h,d)=>{if(h||!d)if(typeof o.attemptNumber>"u"||o.attemptNumber<3){let p=Object.assign({},o);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,t,n,i,p).then(g=>s(g)).catch(g=>a(g))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,g={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};s(g)}})})})}_get(e){return new Promise((t,n)=>{let i=Date.now();this.client.get(e,(o,s)=>{s?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:s,msBeforeNext:u>=0?Math.max(u-i,0):-1};t(l)}}):t(null)})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):o===!1?t(o):this.client.del(`${e}_expire`,s=>{s?n(s):t(o)})})})}};o2e.exports=$M});var u2e=P((Vir,c2e)=>{var a2e=vs();c2e.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new a2e(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new a2e(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),n)}block(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),n)}penalty(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),n)}reward(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),n)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var f2e=P(($ir,l2e)=>{var ZKe=H4();l2e.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof ZKe))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((n,i)=>{let o=[];this._limiters.forEach(s=>{o.push(s.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(o).then(s=>{let a={},c=!1;s.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u{d2e.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var y2e=P((jir,g2e)=>{var p2e=h2e(),m2e=4294967295,qM="limiter";g2e.exports=class{constructor(e,t={maxQueueSize:m2e}){this._queueLimiters={KEY_DEFAULT:new iS(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=qM){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=qM){return this._queueLimiters[t]||(this._queueLimiters[t]=new iS(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var iS=class{constructor(e,t={maxQueueSize:m2e,key:qM}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((n,i)=>{if(e>t._limiterFlexible.points){i(new p2e(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,n,i,e):t._limiterFlexible.consume(t._key,e).then(o=>{n(o.remainingPoints)}).catch(o=>{o instanceof Error?i(o):(t._queueRequest.call(t,n,i,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),o.msBeforeNext)))})})}_queueRequest(e,t,n){let i=this;i._queue.length{t.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(t.reject(n),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var b2e=P((Yir,w2e)=>{var HM=vs();w2e.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new HM(e.remainingPoints,Math.min(e.msBeforeNext,t?t.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,t=1,n={}){return this._rateLimiter.consume(e,t,n).catch(i=>i instanceof HM?this._burstLimiter.consume(e,t,n).then(o=>Promise.resolve(this._combineRes(i,o))).catch(o=>o instanceof HM?Promise.reject(this._combineRes(i,o)):Promise.reject(o)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,n])=>this._combineRes(t,n))}get points(){return this._rateLimiter.points}}});var E2e=P((Qir,_2e)=>{var JKe=Ume(),e$e=Vme(),t$e=$me(),r$e=Hme(),{RateLimiterClusterMaster:n$e,RateLimiterClusterMasterPM2:i$e,RateLimiterCluster:o$e}=i2e(),s$e=FM(),a$e=s2e(),c$e=u2e(),u$e=f2e(),l$e=y2e(),f$e=b2e(),d$e=vs();_2e.exports={RateLimiterRedis:JKe,RateLimiterMongo:e$e,RateLimiterMySQL:t$e,RateLimiterPostgres:r$e,RateLimiterMemory:s$e,RateLimiterMemcache:a$e,RateLimiterClusterMaster:n$e,RateLimiterClusterMasterPM2:i$e,RateLimiterCluster:o$e,RLWrapperBlackAndWhite:c$e,RateLimiterUnion:u$e,RateLimiterQueue:l$e,BurstyRateLimiter:f$e,RateLimiterRes:d$e}});var P2e=P(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});function _$e(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}XM.isSerializableHash=_$e});var hS=P(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});function E$e(r,e,t){return~(r-1)&e|r-1&t}kg.select=E$e;function v$e(r,e){return(r|0)-(e|0)-1>>>31&1}kg.lessOrEqual=v$e;function k2e(r,e){if(r.length!==e.length)return 0;for(var t=0,n=0;n>>8}kg.compare=k2e;function x$e(r,e){return r.length===0||e.length===0?!1:k2e(r,e)!==0}kg.equal=x$e});var Su=P(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});function S$e(r){for(var e=0;e{"use strict";Object.defineProperty(W4,"__esModule",{value:!0});var Au=P2e(),A$e=hS(),T$e=Su(),N2e=function(){function r(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(n).clean():n.set(t);for(var i=0;i{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});var O2e=D2e(),L2e=Su(),R$e=function(){function r(e,t,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var o=O2e.hmac(this._hash,n,t);this._hmac=new O2e.HMAC(e,o),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return r.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},r.prototype.expand=function(e){for(var t=new Uint8Array(e),n=0;n{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.BrowserRandomSource=void 0;var M2e=65536,eU=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let t=new Uint8Array(e);for(let n=0;n{"use strict";Object.defineProperty(mS,"__esModule",{value:!0});mS.NodeRandomSource=void 0;var C$e=Su(),tU=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof k0<"u"){let e=Ju();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});gS.SystemRandomSource=void 0;var P$e=U2e(),k$e=F2e(),rU=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new P$e.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new k$e.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};gS.SystemRandomSource=rU});var V2e=P(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});function N$e(r,e){var t=r>>>16&65535,n=r&65535,i=e>>>16&65535,o=e&65535;return n*o+(t*o+n*i<<16>>>0)|0}xs.mul=Math.imul||N$e;function D$e(r,e){return r+e|0}xs.add=D$e;function O$e(r,e){return r-e|0}xs.sub=O$e;function L$e(r,e){return r<>>32-e}xs.rotl=L$e;function B$e(r,e){return r<<32-e|r>>>e}xs.rotr=B$e;function M$e(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r}xs.isInteger=Number.isInteger||M$e;xs.MAX_SAFE_INTEGER=9007199254740991;xs.isSafeInteger=function(r){return xs.isInteger(r)&&r>=-xs.MAX_SAFE_INTEGER&&r<=xs.MAX_SAFE_INTEGER}});var Y4=P(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});var K2e=V2e();function U$e(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])<<16>>16}At.readInt16BE=U$e;function F$e(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])>>>0}At.readUint16BE=F$e;function z$e(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])<<16>>16}At.readInt16LE=z$e;function V$e(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])>>>0}At.readUint16LE=V$e;function $2e(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>8,e[t+1]=r>>>0,e}At.writeUint16BE=$2e;At.writeInt16BE=$2e;function q2e(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e}At.writeUint16LE=q2e;At.writeInt16LE=q2e;function nU(r,e){return e===void 0&&(e=0),r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}At.readInt32BE=nU;function iU(r,e){return e===void 0&&(e=0),(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}At.readUint32BE=iU;function oU(r,e){return e===void 0&&(e=0),r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e]}At.readInt32LE=oU;function sU(r,e){return e===void 0&&(e=0),(r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e])>>>0}At.readUint32LE=sU;function yS(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>24,e[t+1]=r>>>16,e[t+2]=r>>>8,e[t+3]=r>>>0,e}At.writeUint32BE=yS;At.writeInt32BE=yS;function wS(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e[t+2]=r>>>16,e[t+3]=r>>>24,e}At.writeUint32LE=wS;At.writeInt32LE=wS;function K$e(r,e){e===void 0&&(e=0);var t=nU(r,e),n=nU(r,e+4);return t*4294967296+n-(n>>31)*4294967296}At.readInt64BE=K$e;function $$e(r,e){e===void 0&&(e=0);var t=iU(r,e),n=iU(r,e+4);return t*4294967296+n}At.readUint64BE=$$e;function q$e(r,e){e===void 0&&(e=0);var t=oU(r,e),n=oU(r,e+4);return n*4294967296+t-(t>>31)*4294967296}At.readInt64LE=q$e;function H$e(r,e){e===void 0&&(e=0);var t=sU(r,e),n=sU(r,e+4);return n*4294967296+t}At.readUint64LE=H$e;function H2e(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),yS(r/4294967296>>>0,e,t),yS(r>>>0,e,t+4),e}At.writeUint64BE=H2e;At.writeInt64BE=H2e;function G2e(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),wS(r>>>0,e,t),wS(r/4294967296>>>0,e,t+4),e}At.writeUint64LE=G2e;At.writeInt64LE=G2e;function G$e(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,o=r/8+t-1;o>=t;o--)n+=e[o]*i,i*=256;return n}At.readUintBE=G$e;function j$e(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,o=t;o=n;o--)t[o]=e/i&255,i*=256;return t}At.writeUintBE=W$e;function Y$e(r,e,t,n){if(t===void 0&&(t=new Uint8Array(r/8)),n===void 0&&(n=0),r%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!K2e.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,o=n;o{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.randomStringForEntropy=ji.randomString=ji.randomUint32=ji.randomBytes=ji.defaultRandomSource=void 0;var iqe=z2e(),oqe=Y4(),j2e=Su();ji.defaultRandomSource=new iqe.SystemRandomSource;function aU(r,e=ji.defaultRandomSource){return e.randomBytes(r)}ji.randomBytes=aU;function sqe(r=ji.defaultRandomSource){let e=aU(4,r),t=(0,oqe.readUint32LE)(e);return(0,j2e.wipe)(e),t}ji.randomUint32=sqe;var W2e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Y2e(r,e=W2e,t=ji.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,o=256-256%i;for(;r>0;){let s=aU(Math.ceil(r*256/o),t);for(let a=0;a0;a++){let c=s[a];c{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.sharedKey=dn.generateKeyPair=dn.generateKeyPairFromSeed=dn.scalarMultBase=dn.scalarMult=dn.SHARED_KEY_LENGTH=dn.SECRET_KEY_LENGTH=dn.PUBLIC_KEY_LENGTH=void 0;var cqe=Q2e(),uqe=Su();dn.PUBLIC_KEY_LENGTH=32;dn.SECRET_KEY_LENGTH=32;dn.SHARED_KEY_LENGTH=32;function Tu(r){let e=new Float64Array(16);if(r)for(let t=0;t>16&1),t[s-1]&=65535;t[15]=n[15]-32767-(t[14]>>16&1);let o=t[15]>>16&1;t[14]&=65535,Q4(n,t,1-o)}for(let i=0;i<16;i++)r[2*i]=n[i]&255,r[2*i+1]=n[i]>>8}function dqe(r,e){for(let t=0;t<16;t++)r[t]=e[2*t]+(e[2*t+1]<<8);r[15]&=32767}function bS(r,e,t){for(let n=0;n<16;n++)r[n]=e[n]+t[n]}function _S(r,e,t){for(let n=0;n<16;n++)r[n]=e[n]-t[n]}function Ql(r,e,t){let n,i,o=0,s=0,a=0,c=0,u=0,l=0,f=0,h=0,d=0,p=0,g=0,w=0,_=0,x=0,m=0,y=0,b=0,E=0,v=0,S=0,A=0,I=0,k=0,N=0,O=0,G=0,R=0,K=0,U=0,te=0,Ce=0,ae=t[0],$e=t[1],He=t[2],ot=t[3],Ge=t[4],Qe=t[5],Ze=t[6],Je=t[7],An=t[8],Tn=t[9],zn=t[10],In=t[11],Vn=t[12],Si=t[13],Ai=t[14],Ti=t[15];n=e[0],o+=n*ae,s+=n*$e,a+=n*He,c+=n*ot,u+=n*Ge,l+=n*Qe,f+=n*Ze,h+=n*Je,d+=n*An,p+=n*Tn,g+=n*zn,w+=n*In,_+=n*Vn,x+=n*Si,m+=n*Ai,y+=n*Ti,n=e[1],s+=n*ae,a+=n*$e,c+=n*He,u+=n*ot,l+=n*Ge,f+=n*Qe,h+=n*Ze,d+=n*Je,p+=n*An,g+=n*Tn,w+=n*zn,_+=n*In,x+=n*Vn,m+=n*Si,y+=n*Ai,b+=n*Ti,n=e[2],a+=n*ae,c+=n*$e,u+=n*He,l+=n*ot,f+=n*Ge,h+=n*Qe,d+=n*Ze,p+=n*Je,g+=n*An,w+=n*Tn,_+=n*zn,x+=n*In,m+=n*Vn,y+=n*Si,b+=n*Ai,E+=n*Ti,n=e[3],c+=n*ae,u+=n*$e,l+=n*He,f+=n*ot,h+=n*Ge,d+=n*Qe,p+=n*Ze,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65536),f=n-i*65536,n=h+i+65535,i=Math.floor(n/65536),h=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=p+i+65535,i=Math.floor(n/65536),p=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=_+i+65535,i=Math.floor(n/65536),_=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,o+=i-1+37*(i-1),i=1,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=l+i+65535,i=Math.floor(n/65536),l=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=h+i+65535,i=Math.floor(n/65536),h=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=p+i+65535,i=Math.floor(n/65536),p=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=_+i+65535,i=Math.floor(n/65536),_=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,o+=i-1+37*(i-1),r[0]=o,r[1]=s,r[2]=a,r[3]=c,r[4]=u,r[5]=l,r[6]=f,r[7]=h,r[8]=d,r[9]=p,r[10]=g,r[11]=w,r[12]=_,r[13]=x,r[14]=m,r[15]=y}function X4(r,e){Ql(r,e,e)}function hqe(r,e){let t=Tu();for(let n=0;n<16;n++)t[n]=e[n];for(let n=253;n>=0;n--)X4(t,t),n!==2&&n!==4&&Ql(t,t,e);for(let n=0;n<16;n++)r[n]=t[n]}function uU(r,e){let t=new Uint8Array(32),n=new Float64Array(80),i=Tu(),o=Tu(),s=Tu(),a=Tu(),c=Tu(),u=Tu();for(let d=0;d<31;d++)t[d]=r[d];t[31]=r[31]&127|64,t[0]&=248,dqe(n,e);for(let d=0;d<16;d++)o[d]=n[d];i[0]=a[0]=1;for(let d=254;d>=0;--d){let p=t[d>>>3]>>>(d&7)&1;Q4(i,o,p),Q4(s,a,p),bS(c,i,s),_S(i,i,s),bS(s,o,a),_S(o,o,a),X4(a,c),X4(u,i),Ql(i,s,i),Ql(s,o,c),bS(c,i,s),_S(i,i,s),X4(o,i),_S(s,a,u),Ql(i,s,lqe),bS(i,i,a),Ql(s,s,i),Ql(i,a,u),Ql(a,o,n),X4(o,c),Q4(i,o,p),Q4(s,a,p)}for(let d=0;d<16;d++)n[d+16]=i[d],n[d+32]=s[d],n[d+48]=o[d],n[d+64]=a[d];let l=n.subarray(32),f=n.subarray(16);hqe(l,l),Ql(f,f,l);let h=new Uint8Array(32);return fqe(h,f),h}dn.scalarMult=uU;function Z2e(r){return uU(r,X2e)}dn.scalarMultBase=Z2e;function J2e(r){if(r.length!==dn.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${dn.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(r);return{publicKey:Z2e(e),secretKey:e}}dn.generateKeyPairFromSeed=J2e;function pqe(r){let e=(0,cqe.randomBytes)(32,r),t=J2e(e);return(0,uqe.wipe)(e),t}dn.generateKeyPair=pqe;function mqe(r,e,t=!1){if(r.length!==dn.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==dn.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=uU(r,e);if(t){let i=0;for(let o=0;o{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var vS=Y4(),ES=Su();sh.DIGEST_LENGTH=32;sh.BLOCK_SIZE=64;var tge=function(){function r(){this.digestLength=sh.DIGEST_LENGTH,this.blockSize=sh.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return r.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},r.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},r.prototype.clean=function(){ES.wipe(this._buffer),ES.wipe(this._temp),this.reset()},r.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],t--;this._bufferLength===this.blockSize&&(lU(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(n=lU(this._temp,this._state,e,n,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[n++],t--;return this},r.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,n=this._bufferLength,i=t/536870912|0,o=t<<3,s=t%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},r.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},r.prototype.cleanSavedState=function(e){ES.wipe(e.state),e.buffer&&ES.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},r}();sh.SHA256=tge;var gqe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function lU(r,e,t,n,i){for(;i>=64;){for(var o=e[0],s=e[1],a=e[2],c=e[3],u=e[4],l=e[5],f=e[6],h=e[7],d=0;d<16;d++){var p=n+d*4;r[d]=vS.readUint32BE(t,p)}for(var d=16;d<64;d++){var g=r[d-2],w=(g>>>17|g<<32-17)^(g>>>19|g<<32-19)^g>>>10;g=r[d-15];var _=(g>>>7|g<<32-7)^(g>>>18|g<<32-18)^g>>>3;r[d]=(w+r[d-7]|0)+(_+r[d-16]|0)}for(var d=0;d<64;d++){var w=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&l^~u&f)|0)+(h+(gqe[d]+r[d]|0)|0)|0,_=((o>>>2|o<<32-2)^(o>>>13|o<<32-13)^(o>>>22|o<<32-22))+(o&s^o&a^s&a)|0;h=f,f=l,l=u,u=c+w|0,c=a,a=s,s=o,o=w+_|0}e[0]+=o,e[1]+=s,e[2]+=a,e[3]+=c,e[4]+=u,e[5]+=l,e[6]+=f,e[7]+=h,n+=64,i-=64}return n}function yqe(r){var e=new tge;e.update(r);var t=e.digest();return e.clean(),t}sh.hash=yqe});var ige=P(xS=>{"use strict";Object.defineProperty(xS,"__esModule",{value:!0});var Wi=Y4(),fU=Su(),wqe=20;function bqe(r,e,t){for(var n=1634760805,i=857760878,o=2036477234,s=1797285236,a=t[3]<<24|t[2]<<16|t[1]<<8|t[0],c=t[7]<<24|t[6]<<16|t[5]<<8|t[4],u=t[11]<<24|t[10]<<16|t[9]<<8|t[8],l=t[15]<<24|t[14]<<16|t[13]<<8|t[12],f=t[19]<<24|t[18]<<16|t[17]<<8|t[16],h=t[23]<<24|t[22]<<16|t[21]<<8|t[20],d=t[27]<<24|t[26]<<16|t[25]<<8|t[24],p=t[31]<<24|t[30]<<16|t[29]<<8|t[28],g=e[3]<<24|e[2]<<16|e[1]<<8|e[0],w=e[7]<<24|e[6]<<16|e[5]<<8|e[4],_=e[11]<<24|e[10]<<16|e[9]<<8|e[8],x=e[15]<<24|e[14]<<16|e[13]<<8|e[12],m=n,y=i,b=o,E=s,v=a,S=c,A=u,I=l,k=f,N=h,O=d,G=p,R=g,K=w,U=_,te=x,Ce=0;Ce>>32-16|R<<16,k=k+R|0,v^=k,v=v>>>32-12|v<<12,y=y+S|0,K^=y,K=K>>>32-16|K<<16,N=N+K|0,S^=N,S=S>>>32-12|S<<12,b=b+A|0,U^=b,U=U>>>32-16|U<<16,O=O+U|0,A^=O,A=A>>>32-12|A<<12,E=E+I|0,te^=E,te=te>>>32-16|te<<16,G=G+te|0,I^=G,I=I>>>32-12|I<<12,b=b+A|0,U^=b,U=U>>>32-8|U<<8,O=O+U|0,A^=O,A=A>>>32-7|A<<7,E=E+I|0,te^=E,te=te>>>32-8|te<<8,G=G+te|0,I^=G,I=I>>>32-7|I<<7,y=y+S|0,K^=y,K=K>>>32-8|K<<8,N=N+K|0,S^=N,S=S>>>32-7|S<<7,m=m+v|0,R^=m,R=R>>>32-8|R<<8,k=k+R|0,v^=k,v=v>>>32-7|v<<7,m=m+S|0,te^=m,te=te>>>32-16|te<<16,O=O+te|0,S^=O,S=S>>>32-12|S<<12,y=y+A|0,R^=y,R=R>>>32-16|R<<16,G=G+R|0,A^=G,A=A>>>32-12|A<<12,b=b+I|0,K^=b,K=K>>>32-16|K<<16,k=k+K|0,I^=k,I=I>>>32-12|I<<12,E=E+v|0,U^=E,U=U>>>32-16|U<<16,N=N+U|0,v^=N,v=v>>>32-12|v<<12,b=b+I|0,K^=b,K=K>>>32-8|K<<8,k=k+K|0,I^=k,I=I>>>32-7|I<<7,E=E+v|0,U^=E,U=U>>>32-8|U<<8,N=N+U|0,v^=N,v=v>>>32-7|v<<7,y=y+A|0,R^=y,R=R>>>32-8|R<<8,G=G+R|0,A^=G,A=A>>>32-7|A<<7,m=m+S|0,te^=m,te=te>>>32-8|te<<8,O=O+te|0,S^=O,S=S>>>32-7|S<<7;Wi.writeUint32LE(m+n|0,r,0),Wi.writeUint32LE(y+i|0,r,4),Wi.writeUint32LE(b+o|0,r,8),Wi.writeUint32LE(E+s|0,r,12),Wi.writeUint32LE(v+a|0,r,16),Wi.writeUint32LE(S+c|0,r,20),Wi.writeUint32LE(A+u|0,r,24),Wi.writeUint32LE(I+l|0,r,28),Wi.writeUint32LE(k+f|0,r,32),Wi.writeUint32LE(N+h|0,r,36),Wi.writeUint32LE(O+d|0,r,40),Wi.writeUint32LE(G+p|0,r,44),Wi.writeUint32LE(R+g|0,r,48),Wi.writeUint32LE(K+w|0,r,52),Wi.writeUint32LE(U+_|0,r,56),Wi.writeUint32LE(te+x|0,r,60)}function nge(r,e,t,n,i){if(i===void 0&&(i=0),r.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var sge=P(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var vqe=hS(),SS=Su();Xl.DIGEST_LENGTH=16;var oge=function(){function r(e){this.digestLength=Xl.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var t=e[0]|e[1]<<8;this._r[0]=t&8191;var n=e[2]|e[3]<<8;this._r[1]=(t>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var o=e[6]|e[7]<<8;this._r[3]=(i>>>7|o<<9)&8191;var s=e[8]|e[9]<<8;this._r[4]=(o>>>4|s<<12)&255,this._r[5]=s>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=(s>>>14|a<<2)&8191;var c=e[12]|e[13]<<8;this._r[7]=(a>>>11|c<<5)&8065;var u=e[14]|e[15]<<8;this._r[8]=(c>>>8|u<<8)&8191,this._r[9]=u>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return r.prototype._blocks=function(e,t,n){for(var i=this._fin?0:2048,o=this._h[0],s=this._h[1],a=this._h[2],c=this._h[3],u=this._h[4],l=this._h[5],f=this._h[6],h=this._h[7],d=this._h[8],p=this._h[9],g=this._r[0],w=this._r[1],_=this._r[2],x=this._r[3],m=this._r[4],y=this._r[5],b=this._r[6],E=this._r[7],v=this._r[8],S=this._r[9];n>=16;){var A=e[t+0]|e[t+1]<<8;o+=A&8191;var I=e[t+2]|e[t+3]<<8;s+=(A>>>13|I<<3)&8191;var k=e[t+4]|e[t+5]<<8;a+=(I>>>10|k<<6)&8191;var N=e[t+6]|e[t+7]<<8;c+=(k>>>7|N<<9)&8191;var O=e[t+8]|e[t+9]<<8;u+=(N>>>4|O<<12)&8191,l+=O>>>1&8191;var G=e[t+10]|e[t+11]<<8;f+=(O>>>14|G<<2)&8191;var R=e[t+12]|e[t+13]<<8;h+=(G>>>11|R<<5)&8191;var K=e[t+14]|e[t+15]<<8;d+=(R>>>8|K<<8)&8191,p+=K>>>5|i;var U=0,te=U;te+=o*g,te+=s*(5*S),te+=a*(5*v),te+=c*(5*E),te+=u*(5*b),U=te>>>13,te&=8191,te+=l*(5*y),te+=f*(5*m),te+=h*(5*x),te+=d*(5*_),te+=p*(5*w),U+=te>>>13,te&=8191;var Ce=U;Ce+=o*w,Ce+=s*g,Ce+=a*(5*S),Ce+=c*(5*v),Ce+=u*(5*E),U=Ce>>>13,Ce&=8191,Ce+=l*(5*b),Ce+=f*(5*y),Ce+=h*(5*m),Ce+=d*(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u*y,U=Je>>>13,Je&=8191,Je+=l*m,Je+=f*x,Je+=h*_,Je+=d*w,Je+=p*g,U+=Je>>>13,Je&=8191,U=(U<<2)+U|0,U=U+te|0,te=U&8191,U=U>>>13,Ce+=U,o=te,s=Ce,a=ae,c=$e,u=He,l=ot,f=Ge,h=Qe,d=Ze,p=Je,t+=16,n-=16}this._h[0]=o,this._h[1]=s,this._h[2]=a,this._h[3]=c,this._h[4]=u,this._h[5]=l,this._h[6]=f,this._h[7]=h,this._h[8]=d,this._h[9]=p},r.prototype.finish=function(e,t){t===void 0&&(t=0);var n=new Uint16Array(10),i,o,s,a;if(this._leftover){for(a=this._leftover,this._buffer[a++]=1;a<16;a++)this._buffer[a]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,a=2;a<10;a++)this._h[a]+=i,i=this._h[a]>>>13,this._h[a]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,a=1;a<10;a++)n[a]=this._h[a]+i,i=n[a]>>>13,n[a]&=8191;for(n[9]-=8192,o=(i^1)-1,a=0;a<10;a++)n[a]&=o;for(o=~o,a=0;a<10;a++)this._h[a]=this._h[a]&o|n[a];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,s=this._h[0]+this._pad[0],this._h[0]=s&65535,a=1;a<8;a++)s=(this._h[a]+this._pad[a]|0)+(s>>>16)|0,this._h[a]=s&65535;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},r.prototype.update=function(e){var t=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var o=0;o=16&&(i=n-n%16,this._blocks(e,t,i),t+=i,n-=i),n){for(var o=0;o{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var AS=ige(),Aqe=sge(),Z4=Su(),age=Y4(),Tqe=hS();Zl.KEY_LENGTH=32;Zl.NONCE_LENGTH=12;Zl.TAG_LENGTH=16;var cge=new Uint8Array(16),Iqe=function(){function r(e){if(this.nonceLength=Zl.NONCE_LENGTH,this.tagLength=Zl.TAG_LENGTH,e.length!==Zl.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return r.prototype.seal=function(e,t,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var s=new Uint8Array(32);AS.stream(this._key,o,s,4);var a=t.length+this.tagLength,c;if(i){if(i.length!==a)throw new Error("ChaCha20Poly1305: incorrect destination length");c=i}else c=new Uint8Array(a);return AS.streamXOR(this._key,o,t,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),s,c.subarray(0,c.length-this.tagLength),n),Z4.wipe(o),c},r.prototype.open=function(e,t,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&o.update(cge.subarray(i.length%16))),o.update(n),n.length%16>0&&o.update(cge.subarray(n.length%16));var s=new Uint8Array(8);i&&age.writeUint64LE(i.length,s),o.update(s),age.writeUint64LE(n.length,s),o.update(s);for(var a=o.digest(),c=0;c{Bge.exports=Lge;var Oge=128,zqe=127,Vqe=~zqe,Kqe=Math.pow(2,31);function Lge(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Kqe;)e[t++]=r&255|Oge,r/=128;for(;r&Vqe;)e[t++]=r&255|Oge,r>>>=7;return e[t]=r|0,Lge.bytes=t-n+1,e}});var zge=P((Bar,Fge)=>{Fge.exports=vU;var $qe=128,Uge=127;function vU(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw vU.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Uge)<=$qe);return vU.bytes=o-n,t}});var Kge=P((Mar,Vge)=>{var qqe=Math.pow(2,7),Hqe=Math.pow(2,14),Gqe=Math.pow(2,21),jqe=Math.pow(2,28),Wqe=Math.pow(2,35),Yqe=Math.pow(2,42),Qqe=Math.pow(2,49),Xqe=Math.pow(2,56),Zqe=Math.pow(2,63);Vge.exports=function(r){return r{$ge.exports={encode:Mge(),decode:zge(),encodingLength:Kge()}});var jge=P((Far,Gge)=>{"use strict";var Hge=qge();Gge.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Hge.decode(r);e.push(t),r=r.slice(Hge.decode.bytes)}return e}});var fye=P((uye,lye)=>{"use strict";var fHe=Math.exp;uye=lye.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let t,n=0,i=0,o=0,s,a={};function c(u,l){return 1-fHe(-(u-l)/e)}return a.push=function(l,f){if(s){let h=c(l,s),d=f-t,p=h*d;t=h*f+(1-h)*t,n=(1-h)*(n+d*p),i=Math.sqrt(n),o=t+h*d}else t=f;s=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return o},a}});var qye=P((mdr,YS)=>{(function(){var r=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize","MozTabSize"],e=typeof window<"u",t=e&&window.mozInnerScreenX!=null;function n(i,o,s){if(!e)throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser");var a=s&&s.debug||!1;if(a){var c=document.querySelector("#input-textarea-caret-position-mirror-div");c&&c.parentNode.removeChild(c)}var u=document.createElement("div");u.id="input-textarea-caret-position-mirror-div",document.body.appendChild(u);var l=u.style,f=window.getComputedStyle?window.getComputedStyle(i):i.currentStyle,h=i.nodeName==="INPUT";l.whiteSpace="pre-wrap",h||(l.wordWrap="break-word"),l.position="absolute",a||(l.visibility="hidden"),r.forEach(function(g){h&&g==="lineHeight"?l.lineHeight=f.height:l[g]=f[g]}),t?i.scrollHeight>parseInt(f.height)&&(l.overflowY="scroll"):l.overflow="hidden",u.textContent=i.value.substring(0,o),h&&(u.textContent=u.textContent.replace(/\s/g,"\xA0"));var d=document.createElement("span");d.textContent=i.value.substring(o)||".",u.appendChild(d);var p={top:d.offsetTop+parseInt(f.borderTopWidth),left:d.offsetLeft+parseInt(f.borderLeftWidth),height:parseInt(f.lineHeight)};return a?d.style.backgroundColor="#aaa":document.body.removeChild(u),p}typeof YS<"u"&&typeof YS.exports<"u"?YS.exports=n:e&&(window.getCaretCoordinates=n)})()});var N0=r=>Array.isArray(r);var u3e=r=>({el:document.querySelector(r),elements:document.querySelectorAll(r),placeholder(e){return this.el.placeholder=e,this},getValue(){return this.el.value},insertAtCaret(e){return this.el.setRangeText(e,this.el.selectionStart,this.el.selectionEnd,"end"),this},setValue(e){this.el.value=e;let t=new Event("input",{bubbles:!0,cancelable:!0});return this.el.dispatchEvent(t),this},innerHTML(e){return this.el.innerHTML=e,this},html(e){return this.el.innerHTML="",this.append(e),this},append(e){return(N0(e)?e:[e]).forEach(n=>{let i=D0(n)?n:document.createTextNode(n);this.el.appendChild(i)}),this},appendListElement(e){let t=document.createElement("LI");return t.appendChild(document.createTextNode(e)),this.el.appendChild(t),this},removeClass(e){return this.el.classList.remove(e),this},removeClasses(e=[]){return e.map(t=>this.removeClass(t)),this},addClass(e){return this.el.classList.add(e),this},hasClass(e){return(" "+this.el.className+" ").indexOf(" "+e+" ")>-1},show(e=!0){return e?this.removeClass("hidden"):this.hide(),this},hide(){return this.addClass("hidden"),this},toggle(e="hidden"){return this.hasClass(e)?this.removeClass(e):this.addClass(e),this},focus(){return this.el.focus(),this},listenAll(e,t){return Array.prototype.slice.call(this.elements).map(i=>{i.addEventListener(e,o=>t(o.srcElement))}),this},listen(e,t){return this.el.addEventListener(e,n=>t(n,this)),this},click(){this.el&&this.el.click()},checked(e){return this.el.checked=!!e,this},disable(e=!0){return this.el.disabled=e,this}}),D0=r=>{try{return r instanceof HTMLElement}catch{return typeof r=="object"&&r.nodeType===1&&typeof r.style=="object"&&typeof r.ownerDocument=="object"}},X=u3e;var JS={info:"info",success:"success",error:"error",warning:"warning"},eA=X("#notification"),ZS=()=>eA.removeClasses(Object.values(JS));eA.el.onclick=()=>ZS();var l3e=()=>Object.values(JS).reduce((r,e)=>({...r,[e](t){this.showNotification(t,e)}}),{}),f3e=(r=5)=>({autohideDuration:r,timer:void 0,removeAfter(){this.timer=setTimeout(()=>{ZS()},this.autohideDuration*1e3)},showNotification(e,t=JS.info){ZS(),eA.innerHTML(e).addClass(t),clearTimeout(this.timer),this.removeAfter()},...l3e()}),d3e=f3e(),ze=d3e;var h3e=()=>{let r=localStorage.getItem("miropad.user");r?ze.info(`\u{1F917} Happy to see you again from ${r}`):ze.info(`

Welcome \u{1F44B} \u{1F603}

+ SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),t(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};qme.exports=BM});var jme=P((Lir,Gme)=>{Gme.exports=class{constructor(e,t,n=null){this.value=e,this.expiresAt=t,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Yme=P((Mir,Wme)=>{var KKe=jme(),MM=vs();Wme.exports=class{constructor(){this._storage={}}incrby(e,t,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+t,new MM(0,i,this._storage[e].value,!1)):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new KKe(t,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new MM(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new MM(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var FM=P((Uir,Xme)=>{var $Ke=H4(),qKe=Yme(),Qme=vs(),UM=class extends $Ke{constructor(e={}){super(e),this._memoryStorage=new qKe}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(s,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(s,c.consumedPoints,this.blockDuration)),o(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-t,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}block(e,t){let n=t*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,t),Promise.resolve(new Qme(0,n===0?-1:n,i))}set(e,t,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,n),Promise.resolve(new Qme(0,i===0?-1:i,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Xme.exports=UM});var i2e=P((Fir,n2e)=>{var Zme=HL(),HKe=Ju(),GKe=H4(),e2e=FM(),jKe=vs(),ya="rate_limiter_flexible",Pg=null,Jme=function(r,e,t,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},r.send({channel:ya,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:i})},t2e=function(r){setTimeout(()=>{this._initiated?process.send(r):typeof this._promises[r.promiseId]<"u"&&t2e.call(this,r)},30)},Rg=function(r,e,t,n,i){let o={channel:ya,keyPrefix:this.keyPrefix,func:r,promiseId:e,data:{key:t,arg:n,opts:i}};this._initiated?process.send(o):t2e.call(this,o)},r2e=function(r,e){if(!e||e.channel!==ya||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(n=>{Jme(r,e,"resolve",n)}).catch(n=>{Jme(r,e,"reject",n)})},WKe=function(r){if(!r||r.channel!==ya||r.keyPrefix!==this.keyPrefix)return!1;if(this._promises[r.promiseId]){clearTimeout(this._promises[r.promiseId].timeoutId);let e;switch(r.data===null||r.data===!0||r.data===!1?e=r.data:e=new jKe(r.data.remainingPoints,r.data.msBeforeNext,r.data.consumedPoints,r.data.isFirstInDuration),r.type){case"resolve":this._promises[r.promiseId].resolve(e);break;case"reject":this._promises[r.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${r.type}'`)}delete this._promises[r.promiseId]}},YKe=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},Cg=function(r,e){let t=process.hrtime(),n=t[0].toString()+t[1].toString();return typeof this._promises[n]<"u"&&(n+=HKe.randomBytes(12).toString("base64")),this._promises[n]={resolve:r,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},zM=class{constructor(){if(Pg)return Pg;this._rateLimiters={},Zme.setMaxListeners(0),Zme.on("message",(e,t)=>{t&&t.channel===ya&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new e2e(t.opts)),e.send({channel:ya,type:"init",keyPrefix:t.opts.keyPrefix})):r2e.call(this,e,t)}),Pg=this}},VM=class{constructor(e){if(Pg)return Pg;this._rateLimiters={},e.launchBus((t,n)=>{n.on("process:msg",i=>{let o=i.raw;if(o&&o.channel===ya&&o.type==="init")typeof this._rateLimiters[o.opts.keyPrefix]>"u"&&(this._rateLimiters[o.opts.keyPrefix]=new e2e(o.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:ya,channel:ya,type:"init",keyPrefix:o.opts.keyPrefix},(s,a)=>{s&&console.log(s,a)});else{let s={send:a=>{let c=a;c.topic=ya,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};r2e.call(this,s,o)}})}),Pg=this}},KM=class extends GKe{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===ya&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:WKe.call(this,t)}),process.send({channel:ya,type:"init",opts:YKe.call(this)}),this._promises={}}consume(e,t=1,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"consume",s,e,t,n)})}penalty(e,t=1,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"penalty",s,e,t,n)})}reward(e,t=1,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"reward",s,e,t,n)})}block(e,t,n={}){return new Promise((i,o)=>{let s=Cg.call(this,i,o);Rg.call(this,"block",s,e,t,n)})}get(e,t={}){return new Promise((n,i)=>{let o=Cg.call(this,n,i);Rg.call(this,"get",o,e,t)})}delete(e,t={}){return new Promise((n,i)=>{let o=Cg.call(this,n,i);Rg.call(this,"delete",o,e,t)})}};n2e.exports={RateLimiterClusterMaster:zM,RateLimiterClusterMasterPM2:VM,RateLimiterCluster:KM}});var s2e=P((zir,o2e)=>{var QKe=Ig(),XKe=vs(),$M=class extends QKe{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,n){let i=new XKe;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===t,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,t,n,i=!1,o={}){return new Promise((s,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,t,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(f)})}):this.client.incr(e,t,(l,f)=>{l||f===!1?this.client.add(e,t,u,(h,d)=>{if(h||!d)if(typeof o.attemptNumber>"u"||o.attemptNumber<3){let p=Object.assign({},o);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,t,n,i,p).then(g=>s(g)).catch(g=>a(g))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};s(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,g={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};s(g)}})})})}_get(e){return new Promise((t,n)=>{let i=Date.now();this.client.get(e,(o,s)=>{s?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:s,msBeforeNext:u>=0?Math.max(u-i,0):-1};t(l)}}):t(null)})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,o)=>{i?n(i):o===!1?t(o):this.client.del(`${e}_expire`,s=>{s?n(s):t(o)})})})}};o2e.exports=$M});var u2e=P((Kir,c2e)=>{var a2e=vs();c2e.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new a2e(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new a2e(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),n)}block(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),n)}penalty(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),n)}reward(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),n)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var f2e=P((qir,l2e)=>{var ZKe=H4();l2e.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof ZKe))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((n,i)=>{let o=[];this._limiters.forEach(s=>{o.push(s.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(o).then(s=>{let a={},c=!1;s.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u{d2e.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var y2e=P((Wir,g2e)=>{var p2e=h2e(),m2e=4294967295,qM="limiter";g2e.exports=class{constructor(e,t={maxQueueSize:m2e}){this._queueLimiters={KEY_DEFAULT:new iS(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=qM){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=qM){return this._queueLimiters[t]||(this._queueLimiters[t]=new iS(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var iS=class{constructor(e,t={maxQueueSize:m2e,key:qM}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((n,i)=>{if(e>t._limiterFlexible.points){i(new p2e(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,n,i,e):t._limiterFlexible.consume(t._key,e).then(o=>{n(o.remainingPoints)}).catch(o=>{o instanceof Error?i(o):(t._queueRequest.call(t,n,i,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),o.msBeforeNext)))})})}_queueRequest(e,t,n){let i=this;i._queue.length{t.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(t.reject(n),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var b2e=P((Qir,w2e)=>{var HM=vs();w2e.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new HM(e.remainingPoints,Math.min(e.msBeforeNext,t?t.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,t=1,n={}){return this._rateLimiter.consume(e,t,n).catch(i=>i instanceof HM?this._burstLimiter.consume(e,t,n).then(o=>Promise.resolve(this._combineRes(i,o))).catch(o=>o instanceof HM?Promise.reject(this._combineRes(i,o)):Promise.reject(o)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,n])=>this._combineRes(t,n))}get points(){return this._rateLimiter.points}}});var E2e=P((Xir,_2e)=>{var JKe=Ume(),e$e=Vme(),t$e=$me(),r$e=Hme(),{RateLimiterClusterMaster:n$e,RateLimiterClusterMasterPM2:i$e,RateLimiterCluster:o$e}=i2e(),s$e=FM(),a$e=s2e(),c$e=u2e(),u$e=f2e(),l$e=y2e(),f$e=b2e(),d$e=vs();_2e.exports={RateLimiterRedis:JKe,RateLimiterMongo:e$e,RateLimiterMySQL:t$e,RateLimiterPostgres:r$e,RateLimiterMemory:s$e,RateLimiterMemcache:a$e,RateLimiterClusterMaster:n$e,RateLimiterClusterMasterPM2:i$e,RateLimiterCluster:o$e,RLWrapperBlackAndWhite:c$e,RateLimiterUnion:u$e,RateLimiterQueue:l$e,BurstyRateLimiter:f$e,RateLimiterRes:d$e}});var P2e=P(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});function _$e(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}XM.isSerializableHash=_$e});var hS=P(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});function E$e(r,e,t){return~(r-1)&e|r-1&t}kg.select=E$e;function v$e(r,e){return(r|0)-(e|0)-1>>>31&1}kg.lessOrEqual=v$e;function k2e(r,e){if(r.length!==e.length)return 0;for(var t=0,n=0;n>>8}kg.compare=k2e;function x$e(r,e){return r.length===0||e.length===0?!1:k2e(r,e)!==0}kg.equal=x$e});var Su=P(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});function S$e(r){for(var e=0;e{"use strict";Object.defineProperty(W4,"__esModule",{value:!0});var Au=P2e(),A$e=hS(),T$e=Su(),N2e=function(){function r(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(n).clean():n.set(t);for(var i=0;i{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});var O2e=D2e(),L2e=Su(),R$e=function(){function r(e,t,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var o=O2e.hmac(this._hash,n,t);this._hmac=new O2e.HMAC(e,o),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return r.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},r.prototype.expand=function(e){for(var t=new Uint8Array(e),n=0;n{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.BrowserRandomSource=void 0;var M2e=65536,eU=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let t=new Uint8Array(e);for(let n=0;n{"use strict";Object.defineProperty(mS,"__esModule",{value:!0});mS.NodeRandomSource=void 0;var C$e=Su(),tU=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof k0<"u"){let e=Ju();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});gS.SystemRandomSource=void 0;var P$e=U2e(),k$e=F2e(),rU=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new P$e.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new k$e.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};gS.SystemRandomSource=rU});var V2e=P(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});function N$e(r,e){var t=r>>>16&65535,n=r&65535,i=e>>>16&65535,o=e&65535;return n*o+(t*o+n*i<<16>>>0)|0}xs.mul=Math.imul||N$e;function D$e(r,e){return r+e|0}xs.add=D$e;function O$e(r,e){return r-e|0}xs.sub=O$e;function L$e(r,e){return r<>>32-e}xs.rotl=L$e;function B$e(r,e){return r<<32-e|r>>>e}xs.rotr=B$e;function M$e(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r}xs.isInteger=Number.isInteger||M$e;xs.MAX_SAFE_INTEGER=9007199254740991;xs.isSafeInteger=function(r){return xs.isInteger(r)&&r>=-xs.MAX_SAFE_INTEGER&&r<=xs.MAX_SAFE_INTEGER}});var Y4=P(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});var K2e=V2e();function U$e(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])<<16>>16}At.readInt16BE=U$e;function F$e(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])>>>0}At.readUint16BE=F$e;function z$e(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])<<16>>16}At.readInt16LE=z$e;function V$e(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])>>>0}At.readUint16LE=V$e;function $2e(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>8,e[t+1]=r>>>0,e}At.writeUint16BE=$2e;At.writeInt16BE=$2e;function q2e(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e}At.writeUint16LE=q2e;At.writeInt16LE=q2e;function nU(r,e){return e===void 0&&(e=0),r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}At.readInt32BE=nU;function iU(r,e){return e===void 0&&(e=0),(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}At.readUint32BE=iU;function oU(r,e){return e===void 0&&(e=0),r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e]}At.readInt32LE=oU;function sU(r,e){return e===void 0&&(e=0),(r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e])>>>0}At.readUint32LE=sU;function yS(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>24,e[t+1]=r>>>16,e[t+2]=r>>>8,e[t+3]=r>>>0,e}At.writeUint32BE=yS;At.writeInt32BE=yS;function wS(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e[t+2]=r>>>16,e[t+3]=r>>>24,e}At.writeUint32LE=wS;At.writeInt32LE=wS;function K$e(r,e){e===void 0&&(e=0);var t=nU(r,e),n=nU(r,e+4);return t*4294967296+n-(n>>31)*4294967296}At.readInt64BE=K$e;function $$e(r,e){e===void 0&&(e=0);var t=iU(r,e),n=iU(r,e+4);return t*4294967296+n}At.readUint64BE=$$e;function q$e(r,e){e===void 0&&(e=0);var t=oU(r,e),n=oU(r,e+4);return n*4294967296+t-(t>>31)*4294967296}At.readInt64LE=q$e;function H$e(r,e){e===void 0&&(e=0);var t=sU(r,e),n=sU(r,e+4);return n*4294967296+t}At.readUint64LE=H$e;function H2e(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),yS(r/4294967296>>>0,e,t),yS(r>>>0,e,t+4),e}At.writeUint64BE=H2e;At.writeInt64BE=H2e;function G2e(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),wS(r>>>0,e,t),wS(r/4294967296>>>0,e,t+4),e}At.writeUint64LE=G2e;At.writeInt64LE=G2e;function G$e(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,o=r/8+t-1;o>=t;o--)n+=e[o]*i,i*=256;return n}At.readUintBE=G$e;function j$e(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,o=t;o=n;o--)t[o]=e/i&255,i*=256;return t}At.writeUintBE=W$e;function Y$e(r,e,t,n){if(t===void 0&&(t=new Uint8Array(r/8)),n===void 0&&(n=0),r%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!K2e.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,o=n;o{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.randomStringForEntropy=ji.randomString=ji.randomUint32=ji.randomBytes=ji.defaultRandomSource=void 0;var iqe=z2e(),oqe=Y4(),j2e=Su();ji.defaultRandomSource=new iqe.SystemRandomSource;function aU(r,e=ji.defaultRandomSource){return e.randomBytes(r)}ji.randomBytes=aU;function sqe(r=ji.defaultRandomSource){let e=aU(4,r),t=(0,oqe.readUint32LE)(e);return(0,j2e.wipe)(e),t}ji.randomUint32=sqe;var W2e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Y2e(r,e=W2e,t=ji.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,o=256-256%i;for(;r>0;){let s=aU(Math.ceil(r*256/o),t);for(let a=0;a0;a++){let c=s[a];c{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.sharedKey=dn.generateKeyPair=dn.generateKeyPairFromSeed=dn.scalarMultBase=dn.scalarMult=dn.SHARED_KEY_LENGTH=dn.SECRET_KEY_LENGTH=dn.PUBLIC_KEY_LENGTH=void 0;var cqe=Q2e(),uqe=Su();dn.PUBLIC_KEY_LENGTH=32;dn.SECRET_KEY_LENGTH=32;dn.SHARED_KEY_LENGTH=32;function Tu(r){let e=new Float64Array(16);if(r)for(let t=0;t>16&1),t[s-1]&=65535;t[15]=n[15]-32767-(t[14]>>16&1);let o=t[15]>>16&1;t[14]&=65535,Q4(n,t,1-o)}for(let i=0;i<16;i++)r[2*i]=n[i]&255,r[2*i+1]=n[i]>>8}function dqe(r,e){for(let t=0;t<16;t++)r[t]=e[2*t]+(e[2*t+1]<<8);r[15]&=32767}function bS(r,e,t){for(let n=0;n<16;n++)r[n]=e[n]+t[n]}function _S(r,e,t){for(let n=0;n<16;n++)r[n]=e[n]-t[n]}function Ql(r,e,t){let n,i,o=0,s=0,a=0,c=0,u=0,l=0,f=0,h=0,d=0,p=0,g=0,w=0,_=0,x=0,m=0,y=0,b=0,E=0,v=0,S=0,A=0,I=0,k=0,N=0,O=0,G=0,R=0,K=0,U=0,te=0,Ce=0,ae=t[0],$e=t[1],He=t[2],ot=t[3],Ge=t[4],Qe=t[5],Ze=t[6],Je=t[7],An=t[8],Tn=t[9],zn=t[10],In=t[11],Vn=t[12],Si=t[13],Ai=t[14],Ti=t[15];n=e[0],o+=n*ae,s+=n*$e,a+=n*He,c+=n*ot,u+=n*Ge,l+=n*Qe,f+=n*Ze,h+=n*Je,d+=n*An,p+=n*Tn,g+=n*zn,w+=n*In,_+=n*Vn,x+=n*Si,m+=n*Ai,y+=n*Ti,n=e[1],s+=n*ae,a+=n*$e,c+=n*He,u+=n*ot,l+=n*Ge,f+=n*Qe,h+=n*Ze,d+=n*Je,p+=n*An,g+=n*Tn,w+=n*zn,_+=n*In,x+=n*Vn,m+=n*Si,y+=n*Ai,b+=n*Ti,n=e[2],a+=n*ae,c+=n*$e,u+=n*He,l+=n*ot,f+=n*Ge,h+=n*Qe,d+=n*Ze,p+=n*Je,g+=n*An,w+=n*Tn,_+=n*zn,x+=n*In,m+=n*Vn,y+=n*Si,b+=n*Ai,E+=n*Ti,n=e[3],c+=n*ae,u+=n*$e,l+=n*He,f+=n*ot,h+=n*Ge,d+=n*Qe,p+=n*Ze,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65536),f=n-i*65536,n=h+i+65535,i=Math.floor(n/65536),h=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=p+i+65535,i=Math.floor(n/65536),p=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=_+i+65535,i=Math.floor(n/65536),_=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,o+=i-1+37*(i-1),i=1,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=l+i+65535,i=Math.floor(n/65536),l=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=h+i+65535,i=Math.floor(n/65536),h=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=p+i+65535,i=Math.floor(n/65536),p=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=_+i+65535,i=Math.floor(n/65536),_=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,o+=i-1+37*(i-1),r[0]=o,r[1]=s,r[2]=a,r[3]=c,r[4]=u,r[5]=l,r[6]=f,r[7]=h,r[8]=d,r[9]=p,r[10]=g,r[11]=w,r[12]=_,r[13]=x,r[14]=m,r[15]=y}function X4(r,e){Ql(r,e,e)}function hqe(r,e){let t=Tu();for(let n=0;n<16;n++)t[n]=e[n];for(let n=253;n>=0;n--)X4(t,t),n!==2&&n!==4&&Ql(t,t,e);for(let n=0;n<16;n++)r[n]=t[n]}function uU(r,e){let t=new Uint8Array(32),n=new Float64Array(80),i=Tu(),o=Tu(),s=Tu(),a=Tu(),c=Tu(),u=Tu();for(let d=0;d<31;d++)t[d]=r[d];t[31]=r[31]&127|64,t[0]&=248,dqe(n,e);for(let d=0;d<16;d++)o[d]=n[d];i[0]=a[0]=1;for(let d=254;d>=0;--d){let p=t[d>>>3]>>>(d&7)&1;Q4(i,o,p),Q4(s,a,p),bS(c,i,s),_S(i,i,s),bS(s,o,a),_S(o,o,a),X4(a,c),X4(u,i),Ql(i,s,i),Ql(s,o,c),bS(c,i,s),_S(i,i,s),X4(o,i),_S(s,a,u),Ql(i,s,lqe),bS(i,i,a),Ql(s,s,i),Ql(i,a,u),Ql(a,o,n),X4(o,c),Q4(i,o,p),Q4(s,a,p)}for(let d=0;d<16;d++)n[d+16]=i[d],n[d+32]=s[d],n[d+48]=o[d],n[d+64]=a[d];let l=n.subarray(32),f=n.subarray(16);hqe(l,l),Ql(f,f,l);let h=new Uint8Array(32);return fqe(h,f),h}dn.scalarMult=uU;function Z2e(r){return uU(r,X2e)}dn.scalarMultBase=Z2e;function J2e(r){if(r.length!==dn.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${dn.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(r);return{publicKey:Z2e(e),secretKey:e}}dn.generateKeyPairFromSeed=J2e;function pqe(r){let e=(0,cqe.randomBytes)(32,r),t=J2e(e);return(0,uqe.wipe)(e),t}dn.generateKeyPair=pqe;function mqe(r,e,t=!1){if(r.length!==dn.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==dn.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=uU(r,e);if(t){let i=0;for(let o=0;o{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var vS=Y4(),ES=Su();sh.DIGEST_LENGTH=32;sh.BLOCK_SIZE=64;var tge=function(){function r(){this.digestLength=sh.DIGEST_LENGTH,this.blockSize=sh.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return r.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},r.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},r.prototype.clean=function(){ES.wipe(this._buffer),ES.wipe(this._temp),this.reset()},r.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],t--;this._bufferLength===this.blockSize&&(lU(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(n=lU(this._temp,this._state,e,n,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[n++],t--;return this},r.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,n=this._bufferLength,i=t/536870912|0,o=t<<3,s=t%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},r.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},r.prototype.cleanSavedState=function(e){ES.wipe(e.state),e.buffer&&ES.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},r}();sh.SHA256=tge;var gqe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function lU(r,e,t,n,i){for(;i>=64;){for(var o=e[0],s=e[1],a=e[2],c=e[3],u=e[4],l=e[5],f=e[6],h=e[7],d=0;d<16;d++){var p=n+d*4;r[d]=vS.readUint32BE(t,p)}for(var d=16;d<64;d++){var g=r[d-2],w=(g>>>17|g<<32-17)^(g>>>19|g<<32-19)^g>>>10;g=r[d-15];var _=(g>>>7|g<<32-7)^(g>>>18|g<<32-18)^g>>>3;r[d]=(w+r[d-7]|0)+(_+r[d-16]|0)}for(var d=0;d<64;d++){var w=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&l^~u&f)|0)+(h+(gqe[d]+r[d]|0)|0)|0,_=((o>>>2|o<<32-2)^(o>>>13|o<<32-13)^(o>>>22|o<<32-22))+(o&s^o&a^s&a)|0;h=f,f=l,l=u,u=c+w|0,c=a,a=s,s=o,o=w+_|0}e[0]+=o,e[1]+=s,e[2]+=a,e[3]+=c,e[4]+=u,e[5]+=l,e[6]+=f,e[7]+=h,n+=64,i-=64}return n}function yqe(r){var e=new tge;e.update(r);var t=e.digest();return e.clean(),t}sh.hash=yqe});var ige=P(xS=>{"use strict";Object.defineProperty(xS,"__esModule",{value:!0});var Wi=Y4(),fU=Su(),wqe=20;function bqe(r,e,t){for(var n=1634760805,i=857760878,o=2036477234,s=1797285236,a=t[3]<<24|t[2]<<16|t[1]<<8|t[0],c=t[7]<<24|t[6]<<16|t[5]<<8|t[4],u=t[11]<<24|t[10]<<16|t[9]<<8|t[8],l=t[15]<<24|t[14]<<16|t[13]<<8|t[12],f=t[19]<<24|t[18]<<16|t[17]<<8|t[16],h=t[23]<<24|t[22]<<16|t[21]<<8|t[20],d=t[27]<<24|t[26]<<16|t[25]<<8|t[24],p=t[31]<<24|t[30]<<16|t[29]<<8|t[28],g=e[3]<<24|e[2]<<16|e[1]<<8|e[0],w=e[7]<<24|e[6]<<16|e[5]<<8|e[4],_=e[11]<<24|e[10]<<16|e[9]<<8|e[8],x=e[15]<<24|e[14]<<16|e[13]<<8|e[12],m=n,y=i,b=o,E=s,v=a,S=c,A=u,I=l,k=f,N=h,O=d,G=p,R=g,K=w,U=_,te=x,Ce=0;Ce>>32-16|R<<16,k=k+R|0,v^=k,v=v>>>32-12|v<<12,y=y+S|0,K^=y,K=K>>>32-16|K<<16,N=N+K|0,S^=N,S=S>>>32-12|S<<12,b=b+A|0,U^=b,U=U>>>32-16|U<<16,O=O+U|0,A^=O,A=A>>>32-12|A<<12,E=E+I|0,te^=E,te=te>>>32-16|te<<16,G=G+te|0,I^=G,I=I>>>32-12|I<<12,b=b+A|0,U^=b,U=U>>>32-8|U<<8,O=O+U|0,A^=O,A=A>>>32-7|A<<7,E=E+I|0,te^=E,te=te>>>32-8|te<<8,G=G+te|0,I^=G,I=I>>>32-7|I<<7,y=y+S|0,K^=y,K=K>>>32-8|K<<8,N=N+K|0,S^=N,S=S>>>32-7|S<<7,m=m+v|0,R^=m,R=R>>>32-8|R<<8,k=k+R|0,v^=k,v=v>>>32-7|v<<7,m=m+S|0,te^=m,te=te>>>32-16|te<<16,O=O+te|0,S^=O,S=S>>>32-12|S<<12,y=y+A|0,R^=y,R=R>>>32-16|R<<16,G=G+R|0,A^=G,A=A>>>32-12|A<<12,b=b+I|0,K^=b,K=K>>>32-16|K<<16,k=k+K|0,I^=k,I=I>>>32-12|I<<12,E=E+v|0,U^=E,U=U>>>32-16|U<<16,N=N+U|0,v^=N,v=v>>>32-12|v<<12,b=b+I|0,K^=b,K=K>>>32-8|K<<8,k=k+K|0,I^=k,I=I>>>32-7|I<<7,E=E+v|0,U^=E,U=U>>>32-8|U<<8,N=N+U|0,v^=N,v=v>>>32-7|v<<7,y=y+A|0,R^=y,R=R>>>32-8|R<<8,G=G+R|0,A^=G,A=A>>>32-7|A<<7,m=m+S|0,te^=m,te=te>>>32-8|te<<8,O=O+te|0,S^=O,S=S>>>32-7|S<<7;Wi.writeUint32LE(m+n|0,r,0),Wi.writeUint32LE(y+i|0,r,4),Wi.writeUint32LE(b+o|0,r,8),Wi.writeUint32LE(E+s|0,r,12),Wi.writeUint32LE(v+a|0,r,16),Wi.writeUint32LE(S+c|0,r,20),Wi.writeUint32LE(A+u|0,r,24),Wi.writeUint32LE(I+l|0,r,28),Wi.writeUint32LE(k+f|0,r,32),Wi.writeUint32LE(N+h|0,r,36),Wi.writeUint32LE(O+d|0,r,40),Wi.writeUint32LE(G+p|0,r,44),Wi.writeUint32LE(R+g|0,r,48),Wi.writeUint32LE(K+w|0,r,52),Wi.writeUint32LE(U+_|0,r,56),Wi.writeUint32LE(te+x|0,r,60)}function nge(r,e,t,n,i){if(i===void 0&&(i=0),r.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var sge=P(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var vqe=hS(),SS=Su();Xl.DIGEST_LENGTH=16;var oge=function(){function r(e){this.digestLength=Xl.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var t=e[0]|e[1]<<8;this._r[0]=t&8191;var n=e[2]|e[3]<<8;this._r[1]=(t>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var o=e[6]|e[7]<<8;this._r[3]=(i>>>7|o<<9)&8191;var s=e[8]|e[9]<<8;this._r[4]=(o>>>4|s<<12)&255,this._r[5]=s>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=(s>>>14|a<<2)&8191;var c=e[12]|e[13]<<8;this._r[7]=(a>>>11|c<<5)&8065;var u=e[14]|e[15]<<8;this._r[8]=(c>>>8|u<<8)&8191,this._r[9]=u>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return r.prototype._blocks=function(e,t,n){for(var i=this._fin?0:2048,o=this._h[0],s=this._h[1],a=this._h[2],c=this._h[3],u=this._h[4],l=this._h[5],f=this._h[6],h=this._h[7],d=this._h[8],p=this._h[9],g=this._r[0],w=this._r[1],_=this._r[2],x=this._r[3],m=this._r[4],y=this._r[5],b=this._r[6],E=this._r[7],v=this._r[8],S=this._r[9];n>=16;){var A=e[t+0]|e[t+1]<<8;o+=A&8191;var I=e[t+2]|e[t+3]<<8;s+=(A>>>13|I<<3)&8191;var k=e[t+4]|e[t+5]<<8;a+=(I>>>10|k<<6)&8191;var N=e[t+6]|e[t+7]<<8;c+=(k>>>7|N<<9)&8191;var O=e[t+8]|e[t+9]<<8;u+=(N>>>4|O<<12)&8191,l+=O>>>1&8191;var G=e[t+10]|e[t+11]<<8;f+=(O>>>14|G<<2)&8191;var R=e[t+12]|e[t+13]<<8;h+=(G>>>11|R<<5)&8191;var K=e[t+14]|e[t+15]<<8;d+=(R>>>8|K<<8)&8191,p+=K>>>5|i;var U=0,te=U;te+=o*g,te+=s*(5*S),te+=a*(5*v),te+=c*(5*E),te+=u*(5*b),U=te>>>13,te&=8191,te+=l*(5*y),te+=f*(5*m),te+=h*(5*x),te+=d*(5*_),te+=p*(5*w),U+=te>>>13,te&=8191;var Ce=U;Ce+=o*w,Ce+=s*g,Ce+=a*(5*S),Ce+=c*(5*v),Ce+=u*(5*E),U=Ce>>>13,Ce&=8191,Ce+=l*(5*b),Ce+=f*(5*y),Ce+=h*(5*m),Ce+=d*(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u*y,U=Je>>>13,Je&=8191,Je+=l*m,Je+=f*x,Je+=h*_,Je+=d*w,Je+=p*g,U+=Je>>>13,Je&=8191,U=(U<<2)+U|0,U=U+te|0,te=U&8191,U=U>>>13,Ce+=U,o=te,s=Ce,a=ae,c=$e,u=He,l=ot,f=Ge,h=Qe,d=Ze,p=Je,t+=16,n-=16}this._h[0]=o,this._h[1]=s,this._h[2]=a,this._h[3]=c,this._h[4]=u,this._h[5]=l,this._h[6]=f,this._h[7]=h,this._h[8]=d,this._h[9]=p},r.prototype.finish=function(e,t){t===void 0&&(t=0);var n=new Uint16Array(10),i,o,s,a;if(this._leftover){for(a=this._leftover,this._buffer[a++]=1;a<16;a++)this._buffer[a]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,a=2;a<10;a++)this._h[a]+=i,i=this._h[a]>>>13,this._h[a]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,a=1;a<10;a++)n[a]=this._h[a]+i,i=n[a]>>>13,n[a]&=8191;for(n[9]-=8192,o=(i^1)-1,a=0;a<10;a++)n[a]&=o;for(o=~o,a=0;a<10;a++)this._h[a]=this._h[a]&o|n[a];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,s=this._h[0]+this._pad[0],this._h[0]=s&65535,a=1;a<8;a++)s=(this._h[a]+this._pad[a]|0)+(s>>>16)|0,this._h[a]=s&65535;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},r.prototype.update=function(e){var t=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var o=0;o=16&&(i=n-n%16,this._blocks(e,t,i),t+=i,n-=i),n){for(var o=0;o{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var AS=ige(),Aqe=sge(),Z4=Su(),age=Y4(),Tqe=hS();Zl.KEY_LENGTH=32;Zl.NONCE_LENGTH=12;Zl.TAG_LENGTH=16;var cge=new Uint8Array(16),Iqe=function(){function r(e){if(this.nonceLength=Zl.NONCE_LENGTH,this.tagLength=Zl.TAG_LENGTH,e.length!==Zl.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return r.prototype.seal=function(e,t,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var s=new Uint8Array(32);AS.stream(this._key,o,s,4);var a=t.length+this.tagLength,c;if(i){if(i.length!==a)throw new Error("ChaCha20Poly1305: incorrect destination length");c=i}else c=new Uint8Array(a);return AS.streamXOR(this._key,o,t,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),s,c.subarray(0,c.length-this.tagLength),n),Z4.wipe(o),c},r.prototype.open=function(e,t,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&o.update(cge.subarray(i.length%16))),o.update(n),n.length%16>0&&o.update(cge.subarray(n.length%16));var s=new Uint8Array(8);i&&age.writeUint64LE(i.length,s),o.update(s),age.writeUint64LE(n.length,s),o.update(s);for(var a=o.digest(),c=0;c{Bge.exports=Lge;var Oge=128,zqe=127,Vqe=~zqe,Kqe=Math.pow(2,31);function Lge(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Kqe;)e[t++]=r&255|Oge,r/=128;for(;r&Vqe;)e[t++]=r&255|Oge,r>>>=7;return e[t]=r|0,Lge.bytes=t-n+1,e}});var zge=P((Mar,Fge)=>{Fge.exports=vU;var $qe=128,Uge=127;function vU(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw vU.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Uge)<=$qe);return vU.bytes=o-n,t}});var Kge=P((Uar,Vge)=>{var qqe=Math.pow(2,7),Hqe=Math.pow(2,14),Gqe=Math.pow(2,21),jqe=Math.pow(2,28),Wqe=Math.pow(2,35),Yqe=Math.pow(2,42),Qqe=Math.pow(2,49),Xqe=Math.pow(2,56),Zqe=Math.pow(2,63);Vge.exports=function(r){return r{$ge.exports={encode:Mge(),decode:zge(),encodingLength:Kge()}});var jge=P((zar,Gge)=>{"use strict";var Hge=qge();Gge.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Hge.decode(r);e.push(t),r=r.slice(Hge.decode.bytes)}return e}});var fye=P((uye,lye)=>{"use strict";var fHe=Math.exp;uye=lye.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let t,n=0,i=0,o=0,s,a={};function c(u,l){return 1-fHe(-(u-l)/e)}return a.push=function(l,f){if(s){let h=c(l,s),d=f-t,p=h*d;t=h*f+(1-h)*t,n=(1-h)*(n+d*p),i=Math.sqrt(n),o=t+h*d}else t=f;s=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return o},a}});var qye=P((gdr,YS)=>{(function(){var r=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize","MozTabSize"],e=typeof window<"u",t=e&&window.mozInnerScreenX!=null;function n(i,o,s){if(!e)throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser");var a=s&&s.debug||!1;if(a){var c=document.querySelector("#input-textarea-caret-position-mirror-div");c&&c.parentNode.removeChild(c)}var u=document.createElement("div");u.id="input-textarea-caret-position-mirror-div",document.body.appendChild(u);var l=u.style,f=window.getComputedStyle?window.getComputedStyle(i):i.currentStyle,h=i.nodeName==="INPUT";l.whiteSpace="pre-wrap",h||(l.wordWrap="break-word"),l.position="absolute",a||(l.visibility="hidden"),r.forEach(function(g){h&&g==="lineHeight"?l.lineHeight=f.height:l[g]=f[g]}),t?i.scrollHeight>parseInt(f.height)&&(l.overflowY="scroll"):l.overflow="hidden",u.textContent=i.value.substring(0,o),h&&(u.textContent=u.textContent.replace(/\s/g,"\xA0"));var d=document.createElement("span");d.textContent=i.value.substring(o)||".",u.appendChild(d);var p={top:d.offsetTop+parseInt(f.borderTopWidth),left:d.offsetLeft+parseInt(f.borderLeftWidth),height:parseInt(f.lineHeight)};return a?d.style.backgroundColor="#aaa":document.body.removeChild(u),p}typeof YS<"u"&&typeof YS.exports<"u"?YS.exports=n:e&&(window.getCaretCoordinates=n)})()});var N0=r=>Array.isArray(r);var u3e=r=>({el:document.querySelector(r),elements:document.querySelectorAll(r),placeholder(e){return this.el.placeholder=e,this},getValue(){return this.el.value},insertAtCaret(e){return this.el.setRangeText(e,this.el.selectionStart,this.el.selectionEnd,"end"),this},setValue(e){this.el.value=e;let t=new Event("input",{bubbles:!0,cancelable:!0});return this.el.dispatchEvent(t),this},innerHTML(e){return this.el.innerHTML=e,this},html(e){return this.el.innerHTML="",this.append(e),this},append(e){return(N0(e)?e:[e]).forEach(n=>{let i=D0(n)?n:document.createTextNode(n);this.el.appendChild(i)}),this},appendListElement(e){let t=document.createElement("LI");return t.appendChild(document.createTextNode(e)),this.el.appendChild(t),this},removeClass(e){return this.el.classList.remove(e),this},removeClasses(e=[]){return e.map(t=>this.removeClass(t)),this},addClass(e){return this.el.classList.add(e),this},hasClass(e){return(" "+this.el.className+" ").indexOf(" "+e+" ")>-1},show(e=!0){return e?this.removeClass("hidden"):this.hide(),this},hide(){return this.addClass("hidden"),this},toggle(e="hidden"){return this.hasClass(e)?this.removeClass(e):this.addClass(e),this},focus(){return this.el.focus(),this},listenAll(e,t){return Array.prototype.slice.call(this.elements).map(i=>{i.addEventListener(e,o=>t(o.srcElement))}),this},listen(e,t){return this.el.addEventListener(e,n=>t(n,this)),this},click(){this.el&&this.el.click()},checked(e){return this.el.checked=!!e,this},disable(e=!0){return this.el.disabled=e,this}}),D0=r=>{try{return r instanceof HTMLElement}catch{return typeof r=="object"&&r.nodeType===1&&typeof r.style=="object"&&typeof r.ownerDocument=="object"}},X=u3e;var JS={info:"info",success:"success",error:"error",warning:"warning"},eA=X("#notification"),ZS=()=>eA.removeClasses(Object.values(JS));eA.el.onclick=()=>ZS();var l3e=()=>Object.values(JS).reduce((r,e)=>({...r,[e](t){this.showNotification(t,e)}}),{}),f3e=(r=5)=>({autohideDuration:r,timer:void 0,removeAfter(){this.timer=setTimeout(()=>{ZS()},this.autohideDuration*1e3)},showNotification(e,t=JS.info){ZS(),eA.innerHTML(e).addClass(t),clearTimeout(this.timer),this.removeAfter()},...l3e()}),d3e=f3e(),ze=d3e;var h3e=()=>{let r=localStorage.getItem("miropad.user");r?ze.info(`\u{1F917} Happy to see you again from ${r}`):ze.info(`

Welcome \u{1F44B} \u{1F603}

Use Ctrl+S: to save your note

& Ctrl+P: to format a JSON doc

- `,100),localStorage.setItem("miropad.user",new Date().toLocaleDateString())},MU=h3e;var p3e=(()=>({set:function(r,e){return localStorage.setItem(r,e),this},update:function(r,e){let t=JSON.parse(this.get(r));return localStorage.setItem(r,JSON.stringify({...t,...e})),this},remove:function(r){return localStorage.removeItem(r),this},get:function(r){return N0(r)?r.reduce((e,t)=>({...e,[t]:this.get(t)}),{}):localStorage.getItem(r)},getDictionary:function(){let r=localStorage.getItem("__dictionary__");return r?JSON.parse(r):[]},removeFromDictionary:function(r){let t=this.getDictionary().filter(n=>n!==r);localStorage.setItem("__dictionary__",JSON.stringify(t))},saveToDictionary:async function(r){if(r.length)try{let e=r.toLowerCase().replace(/[^a-zA-Zά-ώΑ-Ω]/g," "),t=await this.getDictionary(),n=[...e.split(" ").filter(o=>o.length>3),...t],i=[...new Set(n)];localStorage.setItem("__dictionary__",JSON.stringify(i))}catch(e){ze.error(`\u{1F631} Something went wrong while trying to save to local storage ${e}`)}else ze.warning("\u{1F615} Nothing to save!");return this}}))(),Fe=p3e;var dc={github:{client_id:"70c1955dfe4914c52c10",request_state:"miro-pad"},auth_service:"https://vercel-api-phi.vercel.app/api/auth",mail_service:{api:"https://vercel-api-phi.vercel.app/api/mail",signature:`Theo Mironidis
+ `,100),localStorage.setItem("miropad.user",new Date().toLocaleDateString())},MU=h3e;var p3e=(()=>({set:function(r,e){return localStorage.setItem(r,e),this},update:function(r,e){let t=JSON.parse(this.get(r));return localStorage.setItem(r,JSON.stringify({...t,...e})),this},remove:function(r){return localStorage.removeItem(r),this},get:function(r){return N0(r)?r.reduce((e,t)=>({...e,[t]:this.get(t)}),{}):localStorage.getItem(r)},parse:function(r){let e=this.get(r);return JSON.parse(e)},getDictionary:function(){let r=localStorage.getItem("__dictionary__");return r?JSON.parse(r):[]},removeFromDictionary:function(r){let t=this.getDictionary().filter(n=>n!==r);localStorage.setItem("__dictionary__",JSON.stringify(t))},saveToDictionary:async function(r){if(r.length)try{let e=r.toLowerCase().replace(/[^a-zA-Zά-ώΑ-Ω]/g," "),t=await this.getDictionary(),n=[...e.split(" ").filter(o=>o.length>3),...t],i=[...new Set(n)];localStorage.setItem("__dictionary__",JSON.stringify(i))}catch(e){ze.error(`\u{1F631} Something went wrong while trying to save to local storage ${e}`)}else ze.warning("\u{1F615} Nothing to save!");return this}}))(),Le=p3e;var dc={github:{client_id:"70c1955dfe4914c52c10",request_state:"miro-pad"},auth_service:"https://vercel-api-phi.vercel.app/api/auth",mail_service:{api:"https://vercel-api-phi.vercel.app/api/mail",signature:`Theo Mironidis
Software Engineer
- https://teomrd.github.io`},file_service:{api:"https://vercel-api-phi.vercel.app/api/upload"}};var p6=(r,e=Fe.get("authToken"))=>fetch(`https://api.github.com/gists/${r}`,{headers:{Authorization:`token ${e}`}}).then(t=>{if(!t.ok)throw Error(t.statusText);return t.json()}),UU=(r=Fe.get("authToken"))=>fetch("https://api.github.com/gists",{headers:{Authorization:`token ${r}`}}).then(e=>{if(!e.ok)throw Error(e.statusText);return e.json()}),FU=async(r,e=Fe.get("gistId"),t=Fe.get("authToken"))=>fetch(`https://api.github.com/gists/${e}`,{method:"PATCH",headers:{Authorization:`token ${t}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:{[r]:null},description:"MiroPad Gist",public:!1})}).then(n=>{if(!n.ok)throw new Error(n.statusText);return n.json()}).then(n=>(ze.info(`${r} deleted on Gist!`),n)),tA=async(r=Ru(),e=Fe.get("gistId"),t=Fe.get("authToken"))=>{if(e&&t){let n=r.reduce((i,{id:o,text:s,deleted:a})=>({...i,[o]:a?null:{content:s}}),{});return fetch(`https://api.github.com/gists/${e}`,{method:"PATCH",headers:{Authorization:`token ${t}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:n,description:"MiroPad Gist",public:!1})}).then(i=>{if(!i.ok)throw new Error(i.statusText);return i.json()}).then(i=>(r.map(({id:o,deleted:s})=>{s&&localStorage.removeItem(o)}),i))}},zU=(r=Fe.get("authToken"))=>{let t=Ru().reduce((n,i)=>({...n,[i.id]:{content:i.text}}),{});return fetch("https://api.github.com/gists",{method:"POST",headers:{Authorization:`token ${r}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:t,description:"MiroPad Gist",public:!1})}).then(n=>{if(!n.ok)throw Error(n.statusText);return n.json()}).then(n=>n)},VU=(r,e)=>fetch(`${dc.auth_service}?state=${e}&code=${r}`,{headers:{Accept:"application/json","Content-Type":"application/json"}}).then(t=>{if(!t.ok)throw Error(t.statusText);return t.json()}).then(t=>t),KU=({note:r,token:e=Fe.get("authToken")}={})=>fetch("https://api.github.com/gists",{method:"POST",headers:{Authorization:`token ${e}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:{[r.id]:{content:r.text}},description:"MiroPad Gist",public:!0})}).then(t=>{if(!t.ok)throw Error(t.statusText);return t.json()}).then(t=>t);var m3e=HU,$U=128,g3e=127,y3e=~g3e,w3e=Math.pow(2,31);function HU(r,e,t){e=e||[],t=t||0;for(var n=t;r>=w3e;)e[t++]=r&255|$U,r/=128;for(;r&y3e;)e[t++]=r&255|$U,r>>>=7;return e[t]=r|0,HU.bytes=t-n+1,e}var b3e=rA,_3e=128,qU=127;function rA(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw rA.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&qU)<=_3e);return rA.bytes=o-n,t}var E3e=Math.pow(2,7),v3e=Math.pow(2,14),x3e=Math.pow(2,21),S3e=Math.pow(2,28),A3e=Math.pow(2,35),T3e=Math.pow(2,42),I3e=Math.pow(2,49),R3e=Math.pow(2,56),C3e=Math.pow(2,63),P3e=function(r){return r[Mg.decode(r,e),Mg.decode.bytes],O0=(r,e,t=0)=>(Mg.encode(r,e,t),e),L0=r=>Mg.encodingLength(r);var dGe=new Uint8Array(0);var GU=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var jU=r=>new TextEncoder().encode(r),WU=r=>new TextDecoder().decode(r);var hc=(r,e)=>{let t=e.byteLength,n=L0(r),i=n+L0(t),o=new Uint8Array(i+t);return O0(r,o,0),O0(t,o,n),o.set(e,i),new B0(r,t,e,o)},Ea=r=>{let e=_a(r),[t,n]=Ug(e),[i,o]=Ug(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new B0(t,i,s,e)},YU=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&GU(r.bytes,t.bytes)}},B0=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var cA={};xe(cA,{base58btc:()=>pr,base58flickr:()=>U3e});function D3e(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var O3e=D3e,L3e=O3e,QU=L3e;var iA=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},oA=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return XU(this,e)}},sA=class{constructor(e){this.decoders=e}or(e){return XU(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},XU=(r,e)=>new sA({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),aA=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new iA(e,t,n),this.decoder=new oA(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},M0=({name:r,prefix:e,encode:t,decode:n})=>new aA(r,e,t,n),tf=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=QU(t,e);return M0({prefix:r,name:e,encode:n,decode:o=>_a(i(o))})},B3e=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},M3e=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<M0({prefix:e,name:r,encode(i){return M3e(i,n,t)},decode(i){return B3e(i,n,t,r)}});var pr=tf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),U3e=tf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lA={};xe(lA,{base32:()=>va,base32hex:()=>V3e,base32hexpad:()=>$3e,base32hexpadupper:()=>q3e,base32hexupper:()=>K3e,base32pad:()=>F3e,base32padupper:()=>z3e,base32upper:()=>uA,base32z:()=>H3e});var va=Zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),uA=Zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F3e=Zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),z3e=Zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V3e=Zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K3e=Zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$3e=Zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),q3e=Zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),H3e=Zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ZU=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return j3e(t,fA(r),e||pr.encoder);default:return W3e(t,fA(r),e||va.encoder)}};var JU=new WeakMap,fA=r=>{let e=JU.get(r);if(e==null){let t=new Map;return JU.set(r,t),t}return e},z=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:t}=this;if(e!==Fg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Y3e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return z.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:{let{code:e,digest:t}=this.multihash,n=hc(e,t);return z.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return z.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&YU(e.multihash,n.multihash)}toString(e){return ZU(this,e)}toJSON(){return{"/":ZU(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof z)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new z(n,i,o,s||eF(n,i,o.bytes))}else if(t[Q3e]===!0){let{version:n,multihash:i,code:o}=t,s=Ea(i);return z.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fg)throw new Error(`Version 0 CID must use dag-pb (code: ${Fg}) block encoding`);return new z(e,t,n,n.bytes)}case 1:{let i=eF(e,t,n.bytes);return new z(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return z.create(0,Fg,e)}static createV1(e,t){return z.create(1,e,t)}static decode(e){let[t,n]=z.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=z.inspectBytes(e),n=t.size-t.multihashSize,i=_a(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new B0(t.multihashCode,t.digestSize,o,i);return[t.version===0?z.createV0(s):z.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Ug(e.subarray(t));return t+=h,f},i=n(),o=Fg;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=G3e(e,t),o=z.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return fA(o).set(n,e),o}},G3e=(r,e)=>{switch(r[0]){case"Q":{let t=e||pr;return[pr.prefix,t.decode(`${pr.prefix}${r}`)]}case pr.prefix:{let t=e||pr;return[pr.prefix,t.decode(r)]}case va.prefix:{let t=e||va;return[va.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},j3e=(r,e,t)=>{let{prefix:n}=t;if(n!==pr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},W3e=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},Fg=112,Y3e=18,eF=(r,e,t)=>{let n=L0(r),i=n+L0(e),o=new Uint8Array(i+t.byteLength);return O0(r,o,0),O0(e,o,n),o.set(t,i),o},Q3e=Symbol.for("@ipld/js-cid/CID");var Vg={};xe(Vg,{code:()=>zg,decode:()=>ewe,encode:()=>dA,name:()=>J3e});var X3e=new TextEncoder,Z3e=new TextDecoder,J3e="json",zg=512,dA=r=>X3e.encode(JSON.stringify(r)),ewe=r=>JSON.parse(Z3e.decode(r));var mA={};xe(mA,{sha256:()=>dt,sha512:()=>twe});var pA=({name:r,code:e,encode:t})=>new hA(r,e,t),hA=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?hc(this.code,t):t.then(n=>hc(this.code,n))}else throw Error("Unknown type, must be binary type")}};var rF=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),dt=pA({name:"sha2-256",code:18,encode:rF("SHA-256")}),twe=pA({name:"sha2-512",code:19,encode:rF("SHA-512")});var rwe=async r=>{let e=dA(r),t=await dt.digest(e);return z.create(1,zg,t).toString()},g6=rwe;var nwe=r=>{try{JSON.parse(r)}catch{return!1}return!0},y6=nwe;var nF=()=>document.title.split("|")[0],gA=r=>{let e=nF();document.title=e.trim()+" | "+r.trim(),X(".title h3").html(r.trim())},w6=()=>{let r=nF();document.title=r,X("title").innerHTML("\u270D\uFE0F MiroPad v2.15.15"),X(".title h3").innerHTML('\u270D\uFE0F MiroPad v2.15.15')};var ht={baseUrl:`${window.location.origin}${window.location.pathname}`,get:function(){return window.location.href},getPageId:function(r=window.location.href){return new URL(r).hash.substr(1).split("?")[0]||null},getSearchParams:function(r=window.location.href){let n=new URL(r).href.split("?")[1]||"";return new URLSearchParams(n)},getParamsObject:function(r=window.location.href){let e=this.getSearchParams(r),t={};for(let n of e.keys())t={...t,[n]:this.getSearchParam(n,r)};return t},getSearchParam(r,e=window.location.href){return this.getSearchParams(e).get(r)},deleteParam:function(r){let e=this.getSearchParams();typeof r=="object"&&r.length>0?r.forEach(i=>{e.delete(i)}):e.delete(r);let{pathname:t}=window.location,n=this.getPageId();return window.location.assign(`${n?`#${n}`:t}${e.toString()?`?${e.toString()}`:""}`)},set:function(r=this.getPageId(),e=this.getParamsObject()){let t={...this.getParamsObject(),...e},n=new URLSearchParams(t);return window.location.assign(`#${r}?${n.toString()}`)}};var Pu=(r=!0)=>{r?(X("#save").removeClass("unsaved"),X("#logo").removeClass("unsaved")):(X("#save").addClass("unsaved"),X("#logo").addClass("unsaved"))};var iF=r=>{let e=encodeURIComponent(r);if(e.length===0)throw new Error("You need to start with a valid title for your note!");return e},b6=r=>{let e=sF(r),t=hn(e),{dateCreated:n}=t||{};return n},iwe=r=>{let e=hn(r);localStorage.setItem(r,JSON.stringify({title:e.title,deleted:!0,revisions:e.revisions}))},hn=(r=ht.getPageId(),e)=>{let t;try{if(t=JSON.parse(Fe.get(r)),!t.revisions)throw new Error("This is not a note!")}catch{return null}let n=t?Object.values(t.revisions).reduce((o,s)=>s.dateCreated>o.dateCreated?s:o,{dateCreated:0}):{},i=e?t.revisions[e]:n;return r?{...t,id:r,...i||{},numberOfRevisions:t&&t.revisions?Object.keys(t.revisions).length:void 0,title:t.title}:null},oF=r=>{let{id:e,title:t}=hn();Fe.update(e,{disableSync:r}),ze.info(`"${t}" cloud sync ${r?"disabled \u{1F636}":"enabled \u26A1\uFE0F"}`)},_6=async(r=ht.getPageId())=>{if(r){let e=ht.getSearchParam("v"),t=hn(void 0,e);t&&(X("#revisions").html(`${t.numberOfRevisions} revision${t.numberOfRevisions>1?"s":""}`),gA(t.title),X(".terminal").setValue(t.text)),t||ze.error("404 Note not found \u{1F937}\u200D\u2642\uFE0F")}},E6=()=>{location.hash="",w6(),X("#revisions").html(""),X(".terminal").setValue("").focus(),Pu()},U0=(r="")=>r.split(` -`)[0].trim().replace("#","").trim(),sF=r=>{let e=U0(r);return iF(e)},aF=async r=>{if(r.length){let e=sF(r),t=U0(r),n=hn(e);if(n===null)return Kg(r);let{text:i}=n,o=await g6(r),s=await g6(i);if(o===s)return;let a=Fe.get(e),c=JSON.parse(a);Fe.set(e,JSON.stringify({...c,title:t,revisions:{...c&&c.revisions||{},[o]:{dateCreated:Date.now(),text:r}}}))}},Kg=async(r=X(".terminal").getValue(),e)=>{if(await Fe.saveToDictionary(r),r.length){let t=await g6(r);try{let n=r.split(` -`)[0].trim().replace("#","").trim();gA(n);let i=iF(n),o=Fe.get(i),s=JSON.parse(o);Fe.set(i,JSON.stringify({...s,title:n,lines:r.split(` -`),revisions:{...s&&s.revisions||{},[t]:{dateCreated:Date.now(),text:r,...e?{cid:e}:{}}}})),ht.set(i,{v:t,...e?{cid:e}:{}}),e||ht.deleteParam("cid"),Fe.set("lastLocalUpdate",new Date),ze.success("\u{1F44C} Note saved!"),Pu()}catch(n){ze.error(`\u{1F631} Something went wrong while trying to save to local storage ${n}`)}}else ze.warning("\u{1F615} Nothing to save!")},Ru=({includeDeleted:r}={})=>Object.entries(localStorage).filter(([,e])=>typeof e=="string").filter(([e,t])=>!e.startsWith("__")&&y6(t)).map(([e,t])=>[e,JSON.parse(t)]).filter(([,e])=>!!e.title).reduce((e,[t])=>[...e,hn(t)],[]).filter(({deleted:e})=>r?!0:!e),cF=r=>r?Ru().map(({id:t})=>hn(t)).filter(({text:t})=>t.toLowerCase().includes(r.toLowerCase()))[0]:void 0,v6=()=>{if(confirm("Are you sure you want do that?")){let e=hn();E6(),e&&e.id&&(FU(e.id),iwe(e.id))}Ct.hide()};var uF=()=>!!Fe.get("authToken");var rf=({title:r,secondary:e,onclick:t,onSecondaryClick:n,icon:i},o=!1)=>{let s=document.createElement("LI");if(s.className=o?"selected":"",i){let u=i.cloneNode(!0);s.appendChild(u)}let a=D0(r)?r:document.createTextNode(r);a.onclick=t,s.appendChild(a);let c=document.createElement("span");if(e){c.className="secondary";let u=D0(e)?e:document.createTextNode(e);u.onclick=n,c.appendChild(u)}return s.appendChild(c),s};var lF=(r,e)=>r.map((t,n)=>rf(t,n===e));var fF=(r,e)=>{let t=r.toLowerCase().split(e),n=0;return t.reduce((i,o,s)=>[...i,...s===0?[o]:[e,o]],[]).filter(i=>i!=="").map(i=>{n=n+i.length;let o=n-i.length,s=o+i.length;return r.slice(o,s)})};var dF=r=>{let e=document.createElement("mark");return e.appendChild(document.createTextNode(r)),e},ku=({content:r="",highlight:e=""})=>{let t=document.createElement("div"),n=r.split(" "),i=e.toLowerCase().split(" ");return e.trim()===""?(t.appendChild(document.createTextNode(r)),t):(n.map(o=>{let s=i.map(a=>o.toLocaleLowerCase().includes(a)?a:void 0).filter(a=>a!==void 0);return{word:o,matches:s}}).forEach(({word:o,matches:s})=>{if(s.length>0){let a=s[0];if(o===a)t.appendChild(dF(` ${o}`));else{let u=fF(o,a).map(l=>l.toLowerCase()===a?dF(l):document.createTextNode(l));t.appendChild(document.createTextNode(" ")),u.forEach(l=>{t.appendChild(l)})}}else t.appendChild(document.createTextNode(` ${o} `))}),t)};var hF=async()=>(ze.info("You need to be authenticated!"),Ct.hide(),window.location.replace(`https://github.com/login/oauth/authorize?client_id=${dc.github.client_id}&scope=gist&state=${dc.github.request_state}`)),pF=async r=>{ze.info("Downloading my Gists!");let e=await UU(r);Ct.setState({mode:Ct.getModes().gists}),ze.info("Select Gist to sync with");let t=e.sort((i,o)=>new Date(o.updated_at).getTime()-new Date(i.updated_at).getTime()).map(({description:i,updated_at:o,id:s})=>({title:ku({content:`${i}(${s})`}),secondary:o,onclick:async()=>{await Fe.set("gistId",s),ze.success(`${i}(${s}) selected for synchronization!`),$g(),Ct.hide()}})),n=lF([{title:"Create a new Gist",onclick:async()=>{ze.info("Syncing your MiroPads to a new Gist");try{let{id:i}=await zU();Fe.set("gistId",i),ze.success("MiroPads synced to a new Gist \u{1F389}")}catch(i){ze.error(i.message)}Ct.hide()}},...t]);X("#commands").html(""),X("#commands").append(n)},$g=async(r=Fe.get("gistId"))=>{if(Fe.get("authToken")&&r){X("#logo").addClass("loading");let{files:t}=await p6(r);Object.values(t).forEach(({content:n})=>{aF(n)}),Fe.set("lastSync",new Date),ze.success("\u2B07 MiroPad synced \u2705"),X("#logo").removeClass("loading")}},mF=async()=>{let r=ht.getSearchParam("code"),e=ht.getSearchParam("state");if(r&&e){X("#logo").addClass("loading"),ze.info("\u{1F510} Authenticating...");try{let{token:t}=await VU(r,e);Fe.set("authToken",t),ze.info("\u26F3 You have been authenticated!"),ht.deleteParam(["code","state"])}catch(t){ze.error(t.message)}X("#logo").removeClass("loading")}};var owe=async(r="no-titled")=>{let e={suggestedName:`${r}`,types:[{description:"MiroPad text notes",accept:{"text/plain":[".miropad"]}}]};return await window.showSaveFilePicker(e)},swe=async(r,e)=>{let t=await r.createWritable();await t.write(e),await t.close()},gF=async(r,e)=>{try{let t=await owe(e);await swe(t,r)}catch{let n="An error occurred trying to save the file.";ze.error(n);return}},yF=(()=>{let r=document.createElement("a");return document.body.appendChild(r),r.style="display: none",(e,t=`MiroPad-${new Date().toISOString()}.json`)=>{let n=JSON.stringify(e),i=new Blob([n],{type:"octet/stream"}),o=window.URL.createObjectURL(i);r.href=o,r.download=t,r.click(),window.URL.revokeObjectURL(o)}})();var _F=C(bF()),EF=new _F.default.Converter({tasklists:!0,underline:!0,emoji:!0,simplifiedAutoLink:!0,tables:!0,openLinksInNewWindow:!0});EF.setFlavor("github");var S6=r=>EF.makeHtml(r);var yA=r=>{if(r.status.toString().slice(0,1)==="2")return r;throw new Error(r)},awe=(r="")=>` + https://teomrd.github.io`},file_service:{api:"https://vercel-api-phi.vercel.app/api/upload"}};var p6=(r,e=Le.get("authToken"))=>fetch(`https://api.github.com/gists/${r}`,{headers:{Authorization:`token ${e}`}}).then(t=>{if(!t.ok)throw Error(t.statusText);return t.json()}),UU=(r=Le.get("authToken"))=>fetch("https://api.github.com/gists",{headers:{Authorization:`token ${r}`}}).then(e=>{if(!e.ok)throw Error(e.statusText);return e.json()}),FU=async(r,e=Le.get("gistId"),t=Le.get("authToken"))=>fetch(`https://api.github.com/gists/${e}`,{method:"PATCH",headers:{Authorization:`token ${t}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:{[r]:null},description:"MiroPad Gist",public:!1})}).then(n=>{if(!n.ok)throw new Error(n.statusText);return n.json()}).then(n=>(ze.info(`${r} deleted on Gist!`),n)),tA=async(r=Ru(),e=Le.get("gistId"),t=Le.get("authToken"))=>{if(e&&t){let n=r.reduce((i,{id:o,text:s,deleted:a})=>({...i,[o]:a?null:{content:s}}),{});return fetch(`https://api.github.com/gists/${e}`,{method:"PATCH",headers:{Authorization:`token ${t}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:n,description:"MiroPad Gist",public:!1})}).then(i=>{if(!i.ok)throw new Error(i.statusText);return i.json()}).then(i=>(r.map(({id:o,deleted:s})=>{s&&localStorage.removeItem(o)}),i))}},zU=(r=Le.get("authToken"))=>{let t=Ru().reduce((n,i)=>({...n,[i.id]:{content:i.text}}),{});return fetch("https://api.github.com/gists",{method:"POST",headers:{Authorization:`token ${r}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:t,description:"MiroPad Gist",public:!1})}).then(n=>{if(!n.ok)throw Error(n.statusText);return n.json()}).then(n=>n)},VU=(r,e)=>fetch(`${dc.auth_service}?state=${e}&code=${r}`,{headers:{Accept:"application/json","Content-Type":"application/json"}}).then(t=>{if(!t.ok)throw Error(t.statusText);return t.json()}).then(t=>t),KU=({note:r,token:e=Le.get("authToken")}={})=>fetch("https://api.github.com/gists",{method:"POST",headers:{Authorization:`token ${e}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({files:{[r.id]:{content:r.text}},description:"MiroPad Gist",public:!0})}).then(t=>{if(!t.ok)throw Error(t.statusText);return t.json()}).then(t=>t);var m3e=HU,$U=128,g3e=127,y3e=~g3e,w3e=Math.pow(2,31);function HU(r,e,t){e=e||[],t=t||0;for(var n=t;r>=w3e;)e[t++]=r&255|$U,r/=128;for(;r&y3e;)e[t++]=r&255|$U,r>>>=7;return e[t]=r|0,HU.bytes=t-n+1,e}var b3e=rA,_3e=128,qU=127;function rA(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw rA.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&qU)<=_3e);return rA.bytes=o-n,t}var E3e=Math.pow(2,7),v3e=Math.pow(2,14),x3e=Math.pow(2,21),S3e=Math.pow(2,28),A3e=Math.pow(2,35),T3e=Math.pow(2,42),I3e=Math.pow(2,49),R3e=Math.pow(2,56),C3e=Math.pow(2,63),P3e=function(r){return r[Mg.decode(r,e),Mg.decode.bytes],O0=(r,e,t=0)=>(Mg.encode(r,e,t),e),L0=r=>Mg.encodingLength(r);var dGe=new Uint8Array(0);var GU=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var jU=r=>new TextEncoder().encode(r),WU=r=>new TextDecoder().decode(r);var hc=(r,e)=>{let t=e.byteLength,n=L0(r),i=n+L0(t),o=new Uint8Array(i+t);return O0(r,o,0),O0(t,o,n),o.set(e,i),new B0(r,t,e,o)},Ea=r=>{let e=_a(r),[t,n]=Ug(e),[i,o]=Ug(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new B0(t,i,s,e)},YU=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&GU(r.bytes,t.bytes)}},B0=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var cA={};xe(cA,{base58btc:()=>pr,base58flickr:()=>U3e});function D3e(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var O3e=D3e,L3e=O3e,QU=L3e;var iA=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},oA=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return XU(this,e)}},sA=class{constructor(e){this.decoders=e}or(e){return XU(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},XU=(r,e)=>new sA({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),aA=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new iA(e,t,n),this.decoder=new oA(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},M0=({name:r,prefix:e,encode:t,decode:n})=>new aA(r,e,t,n),tf=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=QU(t,e);return M0({prefix:r,name:e,encode:n,decode:o=>_a(i(o))})},B3e=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},M3e=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<M0({prefix:e,name:r,encode(i){return M3e(i,n,t)},decode(i){return B3e(i,n,t,r)}});var pr=tf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),U3e=tf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lA={};xe(lA,{base32:()=>va,base32hex:()=>V3e,base32hexpad:()=>$3e,base32hexpadupper:()=>q3e,base32hexupper:()=>K3e,base32pad:()=>F3e,base32padupper:()=>z3e,base32upper:()=>uA,base32z:()=>H3e});var va=Zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),uA=Zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F3e=Zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),z3e=Zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V3e=Zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K3e=Zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$3e=Zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),q3e=Zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),H3e=Zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ZU=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return j3e(t,fA(r),e||pr.encoder);default:return W3e(t,fA(r),e||va.encoder)}};var JU=new WeakMap,fA=r=>{let e=JU.get(r);if(e==null){let t=new Map;return JU.set(r,t),t}return e},z=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:t}=this;if(e!==Fg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Y3e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return z.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:{let{code:e,digest:t}=this.multihash,n=hc(e,t);return z.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return z.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&YU(e.multihash,n.multihash)}toString(e){return ZU(this,e)}toJSON(){return{"/":ZU(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof z)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new z(n,i,o,s||eF(n,i,o.bytes))}else if(t[Q3e]===!0){let{version:n,multihash:i,code:o}=t,s=Ea(i);return z.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fg)throw new Error(`Version 0 CID must use dag-pb (code: ${Fg}) block encoding`);return new z(e,t,n,n.bytes)}case 1:{let i=eF(e,t,n.bytes);return new z(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return z.create(0,Fg,e)}static createV1(e,t){return z.create(1,e,t)}static decode(e){let[t,n]=z.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=z.inspectBytes(e),n=t.size-t.multihashSize,i=_a(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new B0(t.multihashCode,t.digestSize,o,i);return[t.version===0?z.createV0(s):z.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Ug(e.subarray(t));return t+=h,f},i=n(),o=Fg;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=G3e(e,t),o=z.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return fA(o).set(n,e),o}},G3e=(r,e)=>{switch(r[0]){case"Q":{let t=e||pr;return[pr.prefix,t.decode(`${pr.prefix}${r}`)]}case pr.prefix:{let t=e||pr;return[pr.prefix,t.decode(r)]}case va.prefix:{let t=e||va;return[va.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},j3e=(r,e,t)=>{let{prefix:n}=t;if(n!==pr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},W3e=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},Fg=112,Y3e=18,eF=(r,e,t)=>{let n=L0(r),i=n+L0(e),o=new Uint8Array(i+t.byteLength);return O0(r,o,0),O0(e,o,n),o.set(t,i),o},Q3e=Symbol.for("@ipld/js-cid/CID");var Vg={};xe(Vg,{code:()=>zg,decode:()=>ewe,encode:()=>dA,name:()=>J3e});var X3e=new TextEncoder,Z3e=new TextDecoder,J3e="json",zg=512,dA=r=>X3e.encode(JSON.stringify(r)),ewe=r=>JSON.parse(Z3e.decode(r));var mA={};xe(mA,{sha256:()=>dt,sha512:()=>twe});var pA=({name:r,code:e,encode:t})=>new hA(r,e,t),hA=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?hc(this.code,t):t.then(n=>hc(this.code,n))}else throw Error("Unknown type, must be binary type")}};var rF=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),dt=pA({name:"sha2-256",code:18,encode:rF("SHA-256")}),twe=pA({name:"sha2-512",code:19,encode:rF("SHA-512")});var rwe=async r=>{let e=dA(r),t=await dt.digest(e);return z.create(1,zg,t).toString()},g6=rwe;var nwe=r=>{try{JSON.parse(r)}catch{return!1}return!0},y6=nwe;var nF=()=>document.title.split("|")[0],gA=r=>{let e=nF();document.title=e.trim()+" | "+r.trim(),X(".title h3").html(r.trim())},w6=()=>{let r=nF();document.title=r,X("title").innerHTML("\u270D\uFE0F MiroPad v2.15.16"),X(".title h3").innerHTML('\u270D\uFE0F MiroPad v2.15.16')};var ht={baseUrl:`${window.location.origin}${window.location.pathname}`,get:function(){return window.location.href},getPageId:function(r=window.location.href){return new URL(r).hash.substr(1).split("?")[0]||null},getSearchParams:function(r=window.location.href){let n=new URL(r).href.split("?")[1]||"";return new URLSearchParams(n)},getParamsObject:function(r=window.location.href){let e=this.getSearchParams(r),t={};for(let n of e.keys())t={...t,[n]:this.getSearchParam(n,r)};return t},getSearchParam(r,e=window.location.href){return this.getSearchParams(e).get(r)},deleteParam:function(r){let e=this.getSearchParams();typeof r=="object"&&r.length>0?r.forEach(i=>{e.delete(i)}):e.delete(r);let{pathname:t}=window.location,n=this.getPageId();return window.location.assign(`${n?`#${n}`:t}${e.toString()?`?${e.toString()}`:""}`)},set:function(r=this.getPageId(),e=this.getParamsObject()){let t={...this.getParamsObject(),...e},n=new URLSearchParams(t);return window.location.assign(`#${r}?${n.toString()}`)}};var Pu=(r=!0)=>{r?(X("#save").removeClass("unsaved"),X("#logo").removeClass("unsaved")):(X("#save").addClass("unsaved"),X("#logo").addClass("unsaved"))};var iF=r=>{let e=encodeURIComponent(r);if(e.length===0)throw new Error("You need to start with a valid title for your note!");return e},b6=r=>{let e=sF(r),t=hn(e),{dateCreated:n}=t||{};return n},iwe=r=>{let e=hn(r);localStorage.setItem(r,JSON.stringify({title:e.title,deleted:!0,revisions:e.revisions}))},hn=(r=ht.getPageId(),e)=>{let t;try{if(t=JSON.parse(Le.get(r)),!t.revisions)throw new Error("This is not a note!")}catch{return null}let n=t?Object.values(t.revisions).reduce((o,s)=>s.dateCreated>o.dateCreated?s:o,{dateCreated:0}):{},i=e?t.revisions[e]:n;return r?{...t,id:r,...i||{},numberOfRevisions:t&&t.revisions?Object.keys(t.revisions).length:void 0,title:t.title}:null},oF=r=>{let{id:e,title:t}=hn();Le.update(e,{disableSync:r}),ze.info(`"${t}" cloud sync ${r?"disabled \u{1F636}":"enabled \u26A1\uFE0F"}`)},_6=async(r=ht.getPageId())=>{if(r){let e=ht.getSearchParam("v"),t=hn(void 0,e);t&&(X("#revisions").html(`${t.numberOfRevisions} revision${t.numberOfRevisions>1?"s":""}`),gA(t.title),X(".terminal").setValue(t.text)),t||ze.error("404 Note not found \u{1F937}\u200D\u2642\uFE0F")}},E6=()=>{location.hash="",w6(),X("#revisions").html(""),X(".terminal").setValue("").focus(),Pu()},U0=(r="")=>r.split(` +`)[0].trim().replace("#","").trim(),sF=r=>{let e=U0(r);return iF(e)},aF=async r=>{if(r.length){let e=sF(r),t=U0(r),n=hn(e);if(n===null)return Kg(r);let{text:i}=n,o=await g6(r),s=await g6(i);if(o===s)return;let a=Le.get(e),c=JSON.parse(a);Le.set(e,JSON.stringify({...c,title:t,revisions:{...c&&c.revisions||{},[o]:{dateCreated:Date.now(),text:r}}}))}},Kg=async(r=X(".terminal").getValue(),e)=>{if(await Le.saveToDictionary(r),r.length){let t=await g6(r);try{let n=r.split(` +`)[0].trim().replace("#","").trim();gA(n);let i=iF(n),o=Le.get(i),s=JSON.parse(o);Le.set(i,JSON.stringify({...s,title:n,lines:r.split(` +`),revisions:{...s&&s.revisions||{},[t]:{dateCreated:Date.now(),text:r,...e?{cid:e}:{}}}})),ht.set(i,{v:t,...e?{cid:e}:{}}),e||ht.deleteParam("cid"),Le.set("lastLocalUpdate",new Date),ze.success("\u{1F44C} Note saved!"),Pu()}catch(n){ze.error(`\u{1F631} Something went wrong while trying to save to local storage ${n}`)}}else ze.warning("\u{1F615} Nothing to save!")},Ru=({includeDeleted:r}={})=>Object.entries(localStorage).filter(([,e])=>typeof e=="string").filter(([e,t])=>!e.startsWith("__")&&y6(t)).map(([e,t])=>[e,JSON.parse(t)]).filter(([,e])=>!!e.title).reduce((e,[t])=>[...e,hn(t)],[]).filter(({deleted:e})=>r?!0:!e),cF=r=>r?Ru().map(({id:t})=>hn(t)).filter(({text:t})=>t.toLowerCase().includes(r.toLowerCase()))[0]:void 0,v6=()=>{if(confirm("Are you sure you want do that?")){let e=hn();E6(),e&&e.id&&(FU(e.id),iwe(e.id))}Ct.hide()};var uF=()=>!!Le.get("authToken");var rf=({title:r,secondary:e,onclick:t,onSecondaryClick:n,icon:i},o=!1)=>{let s=document.createElement("LI");if(s.className=o?"selected":"",i){let u=i.cloneNode(!0);s.appendChild(u)}let a=D0(r)?r:document.createTextNode(r);a.onclick=t,s.appendChild(a);let c=document.createElement("span");if(e){c.className="secondary";let u=D0(e)?e:document.createTextNode(e);u.onclick=n,c.appendChild(u)}return s.appendChild(c),s};var lF=(r,e)=>r.map((t,n)=>rf(t,n===e));var fF=(r,e)=>{let t=r.toLowerCase().split(e),n=0;return t.reduce((i,o,s)=>[...i,...s===0?[o]:[e,o]],[]).filter(i=>i!=="").map(i=>{n=n+i.length;let o=n-i.length,s=o+i.length;return r.slice(o,s)})};var dF=r=>{let e=document.createElement("mark");return e.appendChild(document.createTextNode(r)),e},ku=({content:r="",highlight:e=""})=>{let t=document.createElement("div"),n=r.split(" "),i=e.toLowerCase().split(" ");return e.trim()===""?(t.appendChild(document.createTextNode(r)),t):(n.map(o=>{let s=i.map(a=>o.toLocaleLowerCase().includes(a)?a:void 0).filter(a=>a!==void 0);return{word:o,matches:s}}).forEach(({word:o,matches:s})=>{if(s.length>0){let a=s[0];if(o===a)t.appendChild(dF(` ${o}`));else{let u=fF(o,a).map(l=>l.toLowerCase()===a?dF(l):document.createTextNode(l));t.appendChild(document.createTextNode(" ")),u.forEach(l=>{t.appendChild(l)})}}else t.appendChild(document.createTextNode(` ${o} `))}),t)};var hF=async()=>(ze.info("You need to be authenticated!"),Ct.hide(),window.location.replace(`https://github.com/login/oauth/authorize?client_id=${dc.github.client_id}&scope=gist&state=${dc.github.request_state}`)),pF=async r=>{ze.info("Downloading my Gists!");let e=await UU(r);Ct.setState({mode:Ct.getModes().gists}),ze.info("Select Gist to sync with");let t=e.sort((i,o)=>new Date(o.updated_at).getTime()-new Date(i.updated_at).getTime()).map(({description:i,updated_at:o,id:s})=>({title:ku({content:`${i}(${s})`}),secondary:o,onclick:async()=>{await Le.set("gistId",s),ze.success(`${i}(${s}) selected for synchronization!`),$g(),Ct.hide()}})),n=lF([{title:"Create a new Gist",onclick:async()=>{ze.info("Syncing your MiroPads to a new Gist");try{let{id:i}=await zU();Le.set("gistId",i),ze.success("MiroPads synced to a new Gist \u{1F389}")}catch(i){ze.error(i.message)}Ct.hide()}},...t]);X("#commands").html(""),X("#commands").append(n)},$g=async(r=Le.get("gistId"))=>{if(Le.get("authToken")&&r){X("#logo").addClass("loading");let{files:t}=await p6(r);Object.values(t).forEach(({content:n})=>{aF(n)}),Le.set("lastSync",new Date),ze.success("\u2B07 MiroPad synced \u2705"),X("#logo").removeClass("loading")}},mF=async()=>{let r=ht.getSearchParam("code"),e=ht.getSearchParam("state");if(r&&e){X("#logo").addClass("loading"),ze.info("\u{1F510} Authenticating...");try{let{token:t}=await VU(r,e);Le.set("authToken",t),ze.info("\u26F3 You have been authenticated!"),ht.deleteParam(["code","state"])}catch(t){ze.error(t.message)}X("#logo").removeClass("loading")}};var owe=async(r="no-titled")=>{let e={suggestedName:`${r}`,types:[{description:"MiroPad text notes",accept:{"text/plain":[".miropad"]}}]};return await window.showSaveFilePicker(e)},swe=async(r,e)=>{let t=await r.createWritable();await t.write(e),await t.close()},gF=async(r,e)=>{try{let t=await owe(e);await swe(t,r)}catch{let n="An error occurred trying to save the file.";ze.error(n);return}},yF=(()=>{let r=document.createElement("a");return document.body.appendChild(r),r.style="display: none",(e,t=`MiroPad-${new Date().toISOString()}.json`)=>{let n=JSON.stringify(e),i=new Blob([n],{type:"octet/stream"}),o=window.URL.createObjectURL(i);r.href=o,r.download=t,r.click(),window.URL.revokeObjectURL(o)}})();var _F=C(bF()),EF=new _F.default.Converter({tasklists:!0,underline:!0,emoji:!0,simplifiedAutoLink:!0,tables:!0,openLinksInNewWindow:!0});EF.setFlavor("github");var S6=r=>EF.makeHtml(r);var yA=r=>{if(r.status.toString().slice(0,1)==="2")return r;throw new Error(r)},awe=(r="")=>` @@ -228,10 +228,10 @@ Use Chrome, Firefox or Internet Explorer 11`)}var BVe=a1e().Buffer,Cx=globalThis - `,cwe=async(r,e,t="MiroPad note")=>{if(!r){ze.error("\u{1F47B} No message to send, type something and try again! \u{1F913}");return}try{await fetch(`${dc.mail_service.api}`,{method:"POST",headers:{"x-secret-token":Fe.get("MIROPAD_SECRET_TOKEN"),accept:"application/json","content-type":"application/json"},body:JSON.stringify({to:e,subject:t,html:awe(r)})}).then(yA).then(n=>n.json()),ze.success("Email sent \u{1F680}")}catch{ze.error("Error not went through \u{1F4A5}! Check your credentials and try again!")}},uwe=()=>{let r=Fe.get("mail");if(r){let n=window.prompt(`Mail ${r} again? (y)es/(no)`,"yeap");if(n===null)return n;if(n.slice(0,1).toLowerCase()==="y")return r}let e=window.prompt("Where do you wanna send the mail to?"),t=window.prompt("Do you wanna save that to your preferences for later on? (y)es/(no)","yeap");return t&&t.slice(0,1).toLowerCase()==="y"&&Fe.set("mail",e),e},vF=r=>{let e=uwe();if(e===null){ze.info("Sending mail cancelled \u{1F636}");return}ze.info("Sending mail... \u{1F680}");let t=U0(r),n=S6(r);cwe(n,e,t)};var Nu=async(r,e="\u{1F4CB} Copied to clipboard")=>{try{await navigator.clipboard.writeText(r),ze.success(e)}catch(t){ze.error(t.message)}};var A6=(r,e,t)=>{let n=N0(r)?r:[r],i=document.createElement("button");return i.setAttribute("type","button"),t&&i.setAttribute("id",t),n.forEach(o=>{typeof o=="string"?i.appendChild(document.createTextNode(o)):i.appendChild(o)}),i.onclick=o=>e(o),i};var lwe=(()=>({view:X(".preview"),init:function(){return this.update(),X(".terminal").listen("input",()=>this.update()),!!ht.getSearchParam("md")?this.view.show():this.view.hide(),this},update:async function(){let md=X(".terminal").getValue();this.view.innerHTML(S6(md));let{elements}=X("pre");Array.prototype.slice.call(elements).forEach(r=>{let e=A6("\u{1F4CB} Copy",async t=>{t.stopPropagation();let n=t.srcElement.previousSibling.innerHTML;await Nu(n,"\u{1F4CB} Code copied to clipboard")});r.appendChild(e)}),X("code").listenAll("click",async({innerHTML})=>{let result=eval(innerHTML);X(".console").show().innerHTML(result)}),X(".console").listen("click",async r=>{r.srcElement.classList.add("hidden");let e=r.srcElement.innerHTML;await Nu(e,"\u{1F4CB} Code copied to clipboard")})},show:function(r=!0){this.view.show(),ht.set(void 0,{md:r})},hide:function(){this.view.hide(),ht.deleteParam("md")},toggle:function(r="true"){return ht.getSearchParam("md")===r?this.hide():this.show(r),this}}))(),nf=lwe;var fwe=r=>{let e=document.querySelector(r);if(y6(e.value)){let t=JSON.stringify(JSON.parse(e.value),null,2);e.value=t,ze.success("\u{1F44D} JSON value prettified")}else ze.error("\u{1F627} Value is not in valid JSON format")},xF=fwe;var SF=(r=1e3)=>new Promise(e=>{setTimeout(e,r)});var Sr=(r,e,t)=>{let n=document.createElement("IMG");return t&&n.classList.add(t),e&&n.setAttribute("alt",e),n.setAttribute("src",r),n};var AF="./list-LK7OCHR7.svg";var qg="./trash-RDL437QG.svg";var TF="./checkmark-circle-JQ7ADSUI.svg";var IF="./cloud-sync-F3RLGHML.svg";var RF="./lighter-UBEI67LL.svg";var CF="./enter-down-6TVO6OFR.svg";var PF="./download-FVXMIYZ4.svg";var kF="./envelope-Z2VRVSLR.svg";var NF="./bug-36UGMUXT.svg";var DF="./picture-3TDOSVS3.svg";var OF="./printer-B7RMPYZC.svg";var LF="./page-break-BLVP5QBQ.svg";var BF="./frame-expand-CX6CNP53.svg";var MF="./arrow-right-circle-2Q6EHM2H.svg";var UF="./magic-wand-JQJ6EKRO.svg";var FF="./rocket-AIY2RJJS.svg";var zF="./earth-DJLABK7O.svg";var VF="./spell-check-V6QYTGNT.svg";var KF="./pencil-X3ZMY3QU.svg";var wA="./exit-up-GH6BPN2X.svg";var $F="./leaf-CGBE7XAJ.svg";var qF=async()=>{try{let r=hn(),e=ht.get();await navigator.share({title:r?r.title:"\u270D\uFE0F MiroPad",text:r?r.text:"Temporary note keeping app for the browser",url:e})}catch(r){ze.info(`${r.message}`)}};var ZF=C(_A(),1),et=ZF.default;var Pye=C(C6(),1);var Co=C(xA(),1);var SA={};xe(SA,{base64:()=>fh,base64pad:()=>o5e,base64url:()=>Gg,base64urlpad:()=>s5e});var fh=Zr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),o5e=Zr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gg=Zr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),s5e=Zr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});Co.default.formatters.b=r=>r==null?"undefined":pr.baseEncode(r);Co.default.formatters.t=r=>r==null?"undefined":va.baseEncode(r);Co.default.formatters.m=r=>r==null?"undefined":fh.baseEncode(r);Co.default.formatters.p=r=>r==null?"undefined":r.toString();Co.default.formatters.c=r=>r==null?"undefined":r.toString();Co.default.formatters.k=r=>r==null?"undefined":r.toString();Co.default.formatters.a=r=>r==null?"undefined":r.toString();function a5e(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function j(r){let e=a5e(`${r}:trace`);return Co.default.enabled(`${r}:trace`)&&Co.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Co.default)(`${r}:trace`)),Object.assign((0,Co.default)(r),{error:(0,Co.default)(`${r}:error`),trace:e})}var jS=C(ee(),1);var H6=C(ee(),1);var Ou=C(gc(),1),H0=Ou.default.Reader,UA=Ou.default.Writer,je=Ou.default.util,pi=Ou.default.roots["ipfs-unixfs"]||(Ou.default.roots["ipfs-unixfs"]={}),jz=pi.Data=(()=>{function r(e){if(this.blocksizes=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.Type=t.int32();break;case 2:o.Data=t.bytes();break;case 3:o.filesize=t.uint64();break;case 4:if(o.blocksizes&&o.blocksizes.length||(o.blocksizes=[]),(s&7)===2)for(var a=t.uint32()+t.pos;t.pos>>0,t.filesize.high>>>0).toNumber(!0))),t.blocksizes){if(!Array.isArray(t.blocksizes))throw TypeError(".Data.blocksizes: array expected");n.blocksizes=[];for(var i=0;i>>0,t.blocksizes[i].high>>>0).toNumber(!0))}if(t.hashType!=null&&(je.Long?(n.hashType=je.Long.fromValue(t.hashType)).unsigned=!0:typeof t.hashType=="string"?n.hashType=parseInt(t.hashType,10):typeof t.hashType=="number"?n.hashType=t.hashType:typeof t.hashType=="object"&&(n.hashType=new je.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0))),t.fanout!=null&&(je.Long?(n.fanout=je.Long.fromValue(t.fanout)).unsigned=!0:typeof t.fanout=="string"?n.fanout=parseInt(t.fanout,10):typeof t.fanout=="number"?n.fanout=t.fanout:typeof t.fanout=="object"&&(n.fanout=new je.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0))),t.mode!=null&&(n.mode=t.mode>>>0),t.mtime!=null){if(typeof t.mtime!="object")throw TypeError(".Data.mtime: object expected");n.mtime=pi.UnixTime.fromObject(t.mtime)}return n},r.toObject=function(t,n){n||(n={});var i={};if((n.arrays||n.defaults)&&(i.blocksizes=[]),n.defaults){if(i.Type=n.enums===String?"Raw":0,n.bytes===String?i.Data="":(i.Data=[],n.bytes!==Array&&(i.Data=je.newBuffer(i.Data))),je.Long){var o=new je.Long(0,0,!0);i.filesize=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.filesize=n.longs===String?"0":0;if(je.Long){var o=new je.Long(0,0,!0);i.hashType=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.hashType=n.longs===String?"0":0;if(je.Long){var o=new je.Long(0,0,!0);i.fanout=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.fanout=n.longs===String?"0":0;i.mode=0,i.mtime=null}if(t.Type!=null&&t.hasOwnProperty("Type")&&(i.Type=n.enums===String?pi.Data.DataType[t.Type]:t.Type),t.Data!=null&&t.hasOwnProperty("Data")&&(i.Data=n.bytes===String?je.base64.encode(t.Data,0,t.Data.length):n.bytes===Array?Array.prototype.slice.call(t.Data):t.Data),t.filesize!=null&&t.hasOwnProperty("filesize")&&(typeof t.filesize=="number"?i.filesize=n.longs===String?String(t.filesize):t.filesize:i.filesize=n.longs===String?je.Long.prototype.toString.call(t.filesize):n.longs===Number?new je.LongBits(t.filesize.low>>>0,t.filesize.high>>>0).toNumber(!0):t.filesize),t.blocksizes&&t.blocksizes.length){i.blocksizes=[];for(var s=0;s>>0,t.blocksizes[s].high>>>0).toNumber(!0):t.blocksizes[s]}return t.hashType!=null&&t.hasOwnProperty("hashType")&&(typeof t.hashType=="number"?i.hashType=n.longs===String?String(t.hashType):t.hashType:i.hashType=n.longs===String?je.Long.prototype.toString.call(t.hashType):n.longs===Number?new je.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0):t.hashType),t.fanout!=null&&t.hasOwnProperty("fanout")&&(typeof t.fanout=="number"?i.fanout=n.longs===String?String(t.fanout):t.fanout:i.fanout=n.longs===String?je.Long.prototype.toString.call(t.fanout):n.longs===Number?new je.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0):t.fanout),t.mode!=null&&t.hasOwnProperty("mode")&&(i.mode=t.mode),t.mtime!=null&&t.hasOwnProperty("mtime")&&(i.mtime=pi.UnixTime.toObject(t.mtime,n)),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Ou.default.util.toJSONOptions)},r.DataType=function(){let e={},t=Object.create(e);return t[e[0]="Raw"]=0,t[e[1]="Directory"]=1,t[e[2]="File"]=2,t[e[3]="Metadata"]=3,t[e[4]="Symlink"]=4,t[e[5]="HAMTShard"]=5,t}(),r})(),MWe=pi.UnixTime=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}if(!o.hasOwnProperty("Seconds"))throw je.ProtocolError("missing required 'Seconds'",{instance:o});return o},r.fromObject=function(t){if(t instanceof pi.UnixTime)return t;var n=new pi.UnixTime;return t.Seconds!=null&&(je.Long?(n.Seconds=je.Long.fromValue(t.Seconds)).unsigned=!1:typeof t.Seconds=="string"?n.Seconds=parseInt(t.Seconds,10):typeof t.Seconds=="number"?n.Seconds=t.Seconds:typeof t.Seconds=="object"&&(n.Seconds=new je.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber())),t.FractionalNanoseconds!=null&&(n.FractionalNanoseconds=t.FractionalNanoseconds>>>0),n},r.toObject=function(t,n){n||(n={});var i={};if(n.defaults){if(je.Long){var o=new je.Long(0,0,!1);i.Seconds=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.Seconds=n.longs===String?"0":0;i.FractionalNanoseconds=0}return t.Seconds!=null&&t.hasOwnProperty("Seconds")&&(typeof t.Seconds=="number"?i.Seconds=n.longs===String?String(t.Seconds):t.Seconds:i.Seconds=n.longs===String?je.Long.prototype.toString.call(t.Seconds):n.longs===Number?new je.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber():t.Seconds),t.FractionalNanoseconds!=null&&t.hasOwnProperty("FractionalNanoseconds")&&(i.FractionalNanoseconds=t.FractionalNanoseconds),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Ou.default.util.toJSONOptions)},r})(),UWe=pi.Metadata=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof pi.Metadata)return t;var n=new pi.Metadata;return t.MimeType!=null&&(n.MimeType=String(t.MimeType)),n},r.toObject=function(t,n){n||(n={});var i={};return n.defaults&&(i.MimeType=""),t.MimeType!=null&&t.hasOwnProperty("MimeType")&&(i.MimeType=t.MimeType),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Ou.default.util.toJSONOptions)},r})();var Lu=jz,Wz=["raw","directory","file","metadata","symlink","hamt-sharded-directory"],b5e=["directory","hamt-sharded-directory"],Yz=parseInt("0644",8),Qz=parseInt("0755",8);function Bu(r){if(r!=null)return typeof r=="number"?r&4095:(r=r.toString(),r.substring(0,1)==="0"?parseInt(r,8)&4095:parseInt(r,10)&4095)}function af(r){if(r==null)return;let e;if(r.secs!=null&&(e={secs:r.secs,nsecs:r.nsecs}),r.Seconds!=null&&(e={secs:r.Seconds,nsecs:r.FractionalNanoseconds}),Array.isArray(r)&&(e={secs:r[0],nsecs:r[1]}),r instanceof Date){let t=r.getTime(),n=Math.floor(t/1e3);e={secs:n,nsecs:(t-n*1e3)*1e3}}if(Object.prototype.hasOwnProperty.call(e,"secs")){if(e!=null&&e.nsecs!=null&&(e.nsecs<0||e.nsecs>999999999))throw(0,H6.default)(new Error("mtime-nsecs must be within the range [0,999999999]"),"ERR_INVALID_MTIME_NSECS");return e}}var st=class{static unmarshal(e){let t=Lu.decode(e),n=Lu.toObject(t,{defaults:!1,arrays:!0,longs:Number,objects:!1}),i=new st({type:Wz[n.Type],data:n.Data,blockSizes:n.blocksizes,mode:n.mode,mtime:n.mtime?{secs:n.mtime.Seconds,nsecs:n.mtime.FractionalNanoseconds}:void 0});return i._originalMode=n.mode||0,i}constructor(e={type:"file"}){let{type:t,data:n,blockSizes:i,hashType:o,fanout:s,mtime:a,mode:c}=e;if(t&&!Wz.includes(t))throw(0,H6.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t||"file",this.data=n,this.hashType=o,this.fanout=s,this.blockSizes=i||[],this._originalMode=0,this.mode=Bu(c),a&&(this.mtime=af(a),this.mtime&&!this.mtime.nsecs&&(this.mtime.nsecs=0))}set mode(e){this._mode=this.isDirectory()?Qz:Yz;let t=Bu(e);t!==void 0&&(this._mode=t)}get mode(){return this._mode}isDirectory(){return!!(this.type&&b5e.includes(this.type))}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0;let e=0;return this.blockSizes.forEach(t=>{e+=t}),this.data&&(e+=this.data.length),e}marshal(){let e;switch(this.type){case"raw":e=Lu.DataType.Raw;break;case"directory":e=Lu.DataType.Directory;break;case"file":e=Lu.DataType.File;break;case"metadata":e=Lu.DataType.Metadata;break;case"symlink":e=Lu.DataType.Symlink;break;case"hamt-sharded-directory":e=Lu.DataType.HAMTShard;break;default:throw(0,H6.default)(new Error("Type: "+e+" is not valid"),"ERR_INVALID_TYPE")}let t=this.data;(!this.data||!this.data.length)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(Bu(this.mode)||0),n===Yz&&!this.isDirectory()&&(n=void 0),n===Qz&&this.isDirectory()&&(n=void 0));let i;if(this.mtime!=null){let s=af(this.mtime);s&&(i={Seconds:s.secs,FractionalNanoseconds:s.nsecs},i.FractionalNanoseconds===0&&delete i.FractionalNanoseconds)}let o={Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i};return Lu.encode(o).finish()}};var sr={};xe(sr,{code:()=>kr,createLink:()=>gV,createNode:()=>mV,decode:()=>en,encode:()=>pt,name:()=>w4e,prepare:()=>Xn,validate:()=>JA});var GA={};xe(GA,{base32:()=>wc,base32hex:()=>k5e,base32hexpad:()=>D5e,base32hexpadupper:()=>O5e,base32hexupper:()=>N5e,base32pad:()=>C5e,base32padupper:()=>P5e,base32upper:()=>R5e,base32z:()=>L5e});var G0={};xe(G0,{coerce:()=>yc,empty:()=>Xz,equals:()=>FA,fromHex:()=>E5e,fromString:()=>zA,isBinary:()=>v5e,toHex:()=>_5e,toString:()=>VA});var Xz=new Uint8Array(0);function _5e(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function E5e(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):Xz}function FA(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var S5e=x5e,A5e=S5e,Zz=A5e;var KA=class{constructor(e,t,n){B(this,"name");B(this,"prefix");B(this,"baseEncode");this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},$A=class{constructor(e,t,n){B(this,"name");B(this,"prefix");B(this,"baseDecode");B(this,"prefixCodePoint");this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Jz(this,e)}},qA=class{constructor(e){B(this,"decoders");this.decoders=e}or(e){return Jz(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Jz(r,e){return new qA({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var HA=class{constructor(e,t,n,i){B(this,"name");B(this,"prefix");B(this,"baseEncode");B(this,"baseDecode");B(this,"encoder");B(this,"decoder");this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new KA(e,t,n),this.decoder=new $A(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function j0({name:r,prefix:e,encode:t,decode:n}){return new HA(r,e,t,n)}function cf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Zz(t,r);return j0({prefix:e,name:r,encode:n,decode:o=>yc(i(o))})}function T5e(r,e,t,n){let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function I5e(r,e,t){let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<Qg,base36upper:()=>B5e});var Qg=cf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),B5e=cf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var WA={};xe(WA,{base58btc:()=>Yi,base58flickr:()=>M5e});var Yi=cf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),M5e=cf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var U5e=rV,eV=128,F5e=127,z5e=~F5e,V5e=Math.pow(2,31);function rV(r,e,t){e=e||[],t=t||0;for(var n=t;r>=V5e;)e[t++]=r&255|eV,r/=128;for(;r&z5e;)e[t++]=r&255|eV,r>>>=7;return e[t]=r|0,rV.bytes=t-n+1,e}var K5e=YA,$5e=128,tV=127;function YA(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw YA.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&tV)<=$5e);return YA.bytes=o-n,t}var q5e=Math.pow(2,7),H5e=Math.pow(2,14),G5e=Math.pow(2,21),j5e=Math.pow(2,28),W5e=Math.pow(2,35),Y5e=Math.pow(2,42),Q5e=Math.pow(2,49),X5e=Math.pow(2,56),Z5e=Math.pow(2,63),J5e=function(r){return r{let[f,h]=Zg(e.subarray(t));return t+=h,f},i=n(),o=Jg;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=r4e(e,t),o=Xe.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return QA(o).set(n,e),o}};function r4e(r,e){switch(r[0]){case"Q":{let t=e??Yi;return[Yi.prefix,t.decode(`${Yi.prefix}${r}`)]}case Yi.prefix:{let t=e??Yi;return[Yi.prefix,t.decode(r)]}case wc.prefix:{let t=e??wc;return[wc.prefix,t.decode(r)]}case Qg.prefix:{let t=e??Qg;return[Qg.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function n4e(r,e,t){let{prefix:n}=t;if(n!==Yi.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function i4e(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var Jg=112,o4e=18;function sV(r,e,t){let n=Y0(r),i=n+Y0(e),o=new Uint8Array(i+t.byteLength);return W0(r,o,0),W0(e,o,n),o.set(t,i),o}var s4e=Symbol.for("@ipld/js-cid/CID");var c4e=new TextDecoder;function XA(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function aV(r,e){let t;return[t,e]=XA(r,e),[t&7,t>>3,e]}function u4e(r){let e={},t=r.length,n=0;for(;nt)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function cV(r){let e=r.length,t=0,n,i=!1,o;for(;te)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var lV=new TextEncoder,uV=2**32,l4e=2**31;function f4e(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=ey(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=lV.encode(r.Name);t-=n.length,e.set(n,t),t=ey(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ey(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function fV(r){let e=h4e(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ey(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=f4e(r.Links[i],t.subarray(0,n));n-=o,n=ey(t,n,o)-1,t[n]=18}return t}function d4e(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+X0(t)}if(typeof r.Name=="string"){let t=lV.encode(r.Name).length;e+=1+t+X0(t)}return typeof r.Tsize=="number"&&(e+=1+X0(r.Tsize)),e}function h4e(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+X0(t)}if(r.Links)for(let t of r.Links){let n=d4e(t);e+=1+n+X0(n)}return e}function ey(r,e,t){e-=X0(t);let n=e;for(;t>=l4e;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function X0(r){return r%2===0&&r++,Math.floor((p4e(r)+6)/7)}function p4e(r){let e=0;return r>=uV&&(r=Math.floor(r/uV),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+m4e[r]}var m4e=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var g4e=["Data","Links"],y4e=["Hash","Name","Tsize"],ZA=new TextEncoder;function hV(r,e){if(r===e)return 0;let t=r.Name?ZA.encode(r.Name):[],n=e.Name?ZA.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s!e.includes(t))}function pV(r){if(typeof r.asCID=="object"){let t=Xe.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=Xe.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=Xe.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=Xe.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Xn(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=ZA.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(pV),e.Links.sort(hV);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function JA(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!dV(r,g4e))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e0&&hV(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function mV(r,e=[]){return Xn({Data:r,Links:e})}function gV(r,e,t){return pV({Hash:t,Name:r,Tsize:e})}function yV(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var w4e="dag-pb",kr=112;function pt(r){JA(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),fV(e)}function en(r){let e=yV(r),t=cV(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=Xe.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}var o1={};xe(o1,{code:()=>lT,decode:()=>dT,decodeOptions:()=>Z4e,encode:()=>fT,encodeOptions:()=>Q4e,name:()=>J4e,toByteView:()=>vK});var b4e=["string","number","bigint","symbol"],_4e=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function wV(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(b4e.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(E4e(r))return"Buffer";let t=v4e(r);return t||"Object"}function E4e(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function v4e(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(_4e.includes(e))return e}var V=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};V.uint=new V(0,"uint",!0);V.negint=new V(1,"negint",!0);V.bytes=new V(2,"bytes",!0);V.string=new V(3,"string",!0);V.array=new V(4,"array",!1);V.map=new V(5,"map",!1);V.tag=new V(6,"tag",!1);V.float=new V(7,"float",!0);V.false=new V(7,"false",!0);V.true=new V(7,"true",!0);V.null=new V(7,"null",!0);V.undefined=new V(7,"undefined",!0);V.break=new V(7,"break",!0);var oe=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Z0=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",x4e=new TextDecoder,S4e=new TextEncoder;function W6(r){return Z0&&globalThis.Buffer.isBuffer(r)}function ty(r){return r instanceof Uint8Array?W6(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var vV=Z0?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):_V(r,e,t):(r,e,t)=>t-e>64?x4e.decode(r.subarray(e,t)):_V(r,e,t),Y6=Z0?r=>r.length>64?globalThis.Buffer.from(r):bV(r):r=>r.length>64?S4e.encode(r):bV(r),bc=r=>Uint8Array.from(r),J0=Z0?(r,e,t)=>W6(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),xV=Z0?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),ty(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},SV=Z0?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function AV(r,e){if(W6(r)&&W6(e))return r.compare(e);for(let t=0;t>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function _V(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return eT(n)}var EV=4096;function eT(r){let e=r.length;if(e<=EV)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=J0(n,0,this.cursor)}else t=xV(this.chunks,this.cursor);return e&&this.reset(),t}};var Pe="CBOR decode error:",Mu="CBOR encode error:",ny=[];ny[23]=1;ny[24]=2;ny[25]=3;ny[26]=5;ny[27]=9;function Uu(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${Pe} encountered BigInt larger than allowable range`)}}Ts.encodedSize=function(e){return mi.encodedSize(e.value)};mi.encodedSize=function(e){return et.value?1:0};function PV(r,e,t,n){return new oe(V.negint,-1-Po(r,e+1,n),2)}function kV(r,e,t,n){return new oe(V.negint,-1-ko(r,e+1,n),3)}function NV(r,e,t,n){return new oe(V.negint,-1-No(r,e+1,n),5)}var tT=BigInt(-1),DV=BigInt(1);function OV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new oe(V.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${Pe} integers outside of the safe integer range are not supported`);return new oe(V.negint,tT-BigInt(i),9)}function Q6(r,e){let t=e.value,n=typeof t=="bigint"?t*tT-DV:t*-1-1;mi(r,e.type.majorEncoded,n)}Q6.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*tT-DV:t*-1-1;return nt.value?-1:0};function iy(r,e,t,n){Uu(r,e,t+n);let i=J0(r,e+t,e+t+n);return new oe(V.bytes,i,t+n)}function LV(r,e,t,n){return iy(r,e,1,t)}function BV(r,e,t,n){return iy(r,e,2,Po(r,e+1,n))}function MV(r,e,t,n){return iy(r,e,3,ko(r,e+1,n))}function UV(r,e,t,n){return iy(r,e,5,No(r,e+1,n))}function FV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer bytes lengths not supported`);return iy(r,e,9,i)}function X6(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===V.string?Y6(r.value):r.value),r.encodedBytes}function e1(r,e){let t=X6(e);mi(r,e.type.majorEncoded,t.length),r.push(t)}e1.encodedSize=function(e){let t=X6(e);return mi.encodedSize(t.length)+t.length};e1.compareTokens=function(e,t){return I4e(X6(e),X6(t))};function I4e(r,e){return r.lengthe.length?1:AV(r,e)}function oy(r,e,t,n,i){let o=t+n;Uu(r,e,o);let s=new oe(V.string,vV(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=J0(r,e+t,e+o)),s}function zV(r,e,t,n){return oy(r,e,1,t,n)}function VV(r,e,t,n){return oy(r,e,2,Po(r,e+1,n),n)}function KV(r,e,t,n){return oy(r,e,3,ko(r,e+1,n),n)}function $V(r,e,t,n){return oy(r,e,5,No(r,e+1,n),n)}function qV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer string lengths not supported`);return oy(r,e,9,i,n)}var HV=e1;function t1(r,e,t,n){return new oe(V.array,n,t)}function GV(r,e,t,n){return t1(r,e,1,t)}function jV(r,e,t,n){return t1(r,e,2,Po(r,e+1,n))}function WV(r,e,t,n){return t1(r,e,3,ko(r,e+1,n))}function YV(r,e,t,n){return t1(r,e,5,No(r,e+1,n))}function QV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer array lengths not supported`);return t1(r,e,9,i)}function XV(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Pe} indefinite length items not allowed`);return t1(r,e,1,1/0)}function Z6(r,e){mi(r,V.array.majorEncoded,e.value)}Z6.compareTokens=Ts.compareTokens;Z6.encodedSize=function(e){return mi.encodedSize(e.value)};function r1(r,e,t,n){return new oe(V.map,n,t)}function ZV(r,e,t,n){return r1(r,e,1,t)}function JV(r,e,t,n){return r1(r,e,2,Po(r,e+1,n))}function eK(r,e,t,n){return r1(r,e,3,ko(r,e+1,n))}function tK(r,e,t,n){return r1(r,e,5,No(r,e+1,n))}function rK(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer map lengths not supported`);return r1(r,e,9,i)}function nK(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Pe} indefinite length items not allowed`);return r1(r,e,1,1/0)}function J6(r,e){mi(r,V.map.majorEncoded,e.value)}J6.compareTokens=Ts.compareTokens;J6.encodedSize=function(e){return mi.encodedSize(e.value)};function iK(r,e,t,n){return new oe(V.tag,t,1)}function oK(r,e,t,n){return new oe(V.tag,Po(r,e+1,n),2)}function sK(r,e,t,n){return new oe(V.tag,ko(r,e+1,n),3)}function aK(r,e,t,n){return new oe(V.tag,No(r,e+1,n),5)}function cK(r,e,t,n){return new oe(V.tag,Do(r,e+1,n),9)}function e8(r,e){mi(r,V.tag.majorEncoded,e.value)}e8.compareTokens=Ts.compareTokens;e8.encodedSize=function(e){return mi.encodedSize(e.value)};var D4e=20,O4e=21,L4e=22,B4e=23;function uK(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Pe} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new oe(V.null,null,1):new oe(V.undefined,void 0,1)}function lK(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Pe} indefinite length items not allowed`);return new oe(V.break,void 0,1)}function rT(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Pe} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Pe} Infinity values are not supported`)}return new oe(V.float,r,e)}function fK(r,e,t,n){return rT(nT(r,e+1),3,n)}function dK(r,e,t,n){return rT(iT(r,e+1),5,n)}function hK(r,e,t,n){return rT(yK(r,e+1),9,n)}function t8(r,e,t){let n=e.value;if(n===!1)r.push([V.float.majorEncoded|D4e]);else if(n===!0)r.push([V.float.majorEncoded|O4e]);else if(n===null)r.push([V.float.majorEncoded|L4e]);else if(n===void 0)r.push([V.float.majorEncoded|B4e]);else{let i,o=!1;(!t||t.float64!==!0)&&(mK(n),i=nT(Aa,1),n===i||Number.isNaN(n)?(Aa[0]=249,r.push(Aa.slice(0,3)),o=!0):(gK(n),i=iT(Aa,1),n===i&&(Aa[0]=250,r.push(Aa.slice(0,5)),o=!0))),o||(M4e(n),i=yK(Aa,1),Aa[0]=251,r.push(Aa.slice(0,9)))}}t8.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){mK(n);let i=nT(Aa,1);if(n===i||Number.isNaN(n))return 3;if(gK(n),i=iT(Aa,1),n===i)return 5}return 9};var pK=new ArrayBuffer(9),Is=new DataView(pK,1),Aa=new Uint8Array(pK,0);function mK(r){if(r===1/0)Is.setUint16(0,31744,!1);else if(r===-1/0)Is.setUint16(0,64512,!1);else if(Number.isNaN(r))Is.setUint16(0,32256,!1);else{Is.setFloat32(0,r);let e=Is.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Is.setUint16(0,31744,!1);else if(t===0)Is.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Is.setUint16(0,0):i<-14?Is.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Is.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function nT(r,e){if(r.length-e<2)throw new Error(`${Pe} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function gK(r){Is.setFloat32(0,r,!1)}function iT(r,e){if(r.length-e<4)throw new Error(`${Pe} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function M4e(r){Is.setFloat64(0,r,!1)}function yK(r,e){if(r.length-e<8)throw new Error(`${Pe} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}t8.compareTokens=Ts.compareTokens;function Jt(r,e,t){throw new Error(`${Pe} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function r8(r){return()=>{throw new Error(`${Pe} ${r}`)}}var de=[];for(let r=0;r<=23;r++)de[r]=Jt;de[24]=TV;de[25]=IV;de[26]=RV;de[27]=CV;de[28]=Jt;de[29]=Jt;de[30]=Jt;de[31]=Jt;for(let r=32;r<=55;r++)de[r]=Jt;de[56]=PV;de[57]=kV;de[58]=NV;de[59]=OV;de[60]=Jt;de[61]=Jt;de[62]=Jt;de[63]=Jt;for(let r=64;r<=87;r++)de[r]=LV;de[88]=BV;de[89]=MV;de[90]=UV;de[91]=FV;de[92]=Jt;de[93]=Jt;de[94]=Jt;de[95]=r8("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)de[r]=zV;de[120]=VV;de[121]=KV;de[122]=$V;de[123]=qV;de[124]=Jt;de[125]=Jt;de[126]=Jt;de[127]=r8("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)de[r]=GV;de[152]=jV;de[153]=WV;de[154]=YV;de[155]=QV;de[156]=Jt;de[157]=Jt;de[158]=Jt;de[159]=XV;for(let r=160;r<=183;r++)de[r]=ZV;de[184]=JV;de[185]=eK;de[186]=tK;de[187]=rK;de[188]=Jt;de[189]=Jt;de[190]=Jt;de[191]=nK;for(let r=192;r<=215;r++)de[r]=iK;de[216]=oK;de[217]=sK;de[218]=aK;de[219]=cK;de[220]=Jt;de[221]=Jt;de[222]=Jt;de[223]=Jt;for(let r=224;r<=243;r++)de[r]=r8("simple values are not supported");de[244]=Jt;de[245]=Jt;de[246]=Jt;de[247]=uK;de[248]=r8("simple values are not supported");de[249]=fK;de[250]=dK;de[251]=hK;de[252]=Jt;de[253]=Jt;de[254]=Jt;de[255]=lK;var Ta=[];for(let r=0;r<24;r++)Ta[r]=new oe(V.uint,r,1);for(let r=-1;r>=-24;r--)Ta[31-r]=new oe(V.negint,r,1);Ta[64]=new oe(V.bytes,new Uint8Array(0),1);Ta[96]=new oe(V.string,"",1);Ta[128]=new oe(V.array,0,1);Ta[160]=new oe(V.map,0,1);Ta[244]=new oe(V.false,!1,1);Ta[245]=new oe(V.true,!0,1);Ta[246]=new oe(V.null,null,1);function wK(r){switch(r.type){case V.false:return bc([244]);case V.true:return bc([245]);case V.null:return bc([246]);case V.bytes:return r.value.length?void 0:bc([64]);case V.string:return r.value===""?bc([96]):void 0;case V.array:return r.value===0?bc([128]):void 0;case V.map:return r.value===0?bc([160]):void 0;case V.uint:return r.value<24?bc([Number(r.value)]):void 0;case V.negint:if(r.value>=-24)return bc([31-Number(r.value)])}}var F4e={float64:!1,mapSorter:K4e,quickEncodeToken:wK};function z4e(){let r=[];return r[V.uint.major]=Ts,r[V.negint.major]=Q6,r[V.bytes.major]=e1,r[V.string.major]=HV,r[V.array.major]=Z6,r[V.map.major]=J6,r[V.tag.major]=e8,r[V.float.major]=t8,r}var bK=z4e(),oT=new ry,n1=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Mu} object contains circular references`);return new n1(t,e)}},ff={null:new oe(V.null,null),undefined:new oe(V.undefined,void 0),true:new oe(V.true,!0),false:new oe(V.false,!1),emptyArray:new oe(V.array,0),emptyMap:new oe(V.map,0)},df={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new oe(V.float,r):r>=0?new oe(V.uint,r):new oe(V.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new oe(V.uint,r):new oe(V.negint,r)},Uint8Array(r,e,t,n){return new oe(V.bytes,r)},string(r,e,t,n){return new oe(V.string,r)},boolean(r,e,t,n){return r?ff.true:ff.false},null(r,e,t,n){return ff.null},undefined(r,e,t,n){return ff.undefined},ArrayBuffer(r,e,t,n){return new oe(V.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new oe(V.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ff.emptyArray,new oe(V.break)]:ff.emptyArray;n=n1.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=n8(s,t,n);return t.addBreakTokens?[new oe(V.array,r.length),i,new oe(V.break)]:[new oe(V.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[ff.emptyMap,new oe(V.break)]:ff.emptyMap;n=n1.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[n8(u,t,n),n8(i?r.get(u):r[u],t,n)];return V4e(a,t),t.addBreakTokens?[new oe(V.map,s),a,new oe(V.break)]:[new oe(V.map,s),a]}};df.Map=df.Object;df.Buffer=df.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))df[`${r}Array`]=df.DataView;function n8(r,e={},t){let n=wV(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||df[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=df[n];if(!o)throw new Error(`${Mu} unsupported type: ${n}`);return o(r,n,e,t)}function V4e(r,e){e.mapSorter&&r.sort(e.mapSorter)}function K4e(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=bK[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function _K(r,e,t,n){if(Array.isArray(e))for(let i of e)_K(r,i,t,n);else t[e.type.major](r,e,n)}function sT(r,e,t){let n=n8(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new ry(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return ty(a.chunks[0])}}return oT.reset(),_K(oT,n,e,t),oT.toBytes(!0)}function aT(r,e){return e=Object.assign({},F4e,e),sT(r,bK,e)}var $4e={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},i8=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Ta[e];if(t===void 0){let n=de[e];if(!n)throw new Error(`${Pe} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},sy=Symbol.for("DONE"),o8=Symbol.for("BREAK");function q4e(r,e,t){let n=[];for(let i=0;i0)throw new Error(`${Pe} too many terminals, data makes no sense`);return t}var EK=42;function vK(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function j4e(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Xe.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new oe(V.tag,EK),new oe(V.bytes,t)]}function W4e(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Y4e(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var uT={float64:!0,typeEncoders:{Object:j4e,undefined:W4e,number:Y4e}},Q4e={...uT,typeEncoders:{...uT.typeEncoders}};function X4e(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Xe.decode(r.subarray(1))}var s8={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};s8.tags[EK]=X4e;var Z4e={...s8,tags:s8.tags.slice()},J4e="dag-cbor",lT=113,fT=r=>aT(r,uT),dT=r=>ay(vK(r),s8);var a1={};xe(a1,{code:()=>_T,decode:()=>AK,encode:()=>SK,format:()=>h6e,name:()=>d6e,parse:()=>m6e,stringify:()=>h6e});var hT=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===V.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===V.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[V.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o32?ty(n):n)}[V.array.major](e,t){this.prefix(e),this.inRecursive.push({type:V.array,elements:0}),e.push([91])}[V.map.major](e,t){this.prefix(e),this.inRecursive.push({type:V.map,elements:0}),e.push([123])}[V.tag.major](e,t){}[V.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===V.array)e.push([93]);else if(s.type===V.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Mu} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;sn)return 1;throw new Error(`${Mu} unexpected duplicate map keys, this is not supported`)}var t6e={addBreakTokens:!0,mapSorter:e6e};function pT(r,e){return e=Object.assign({},t6e,e),sT(r,new hT,e)}var s1=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new oe(V.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${Pe} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Pe} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new oe(V.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new oe(s>=0?V.uint:V.negint,s,this._pos-e):new oe(s>=0?V.uint:V.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Pe} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new oe(V.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Pe} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Pe} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Pe} unexpected unicode sequence at position ${this._pos}`);let c,u,l,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],u=this.data[this._pos+2],(c&192)===128&&(u&192)===128&&(f=(o&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${Pe} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Pe} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new oe(V.string,eT(t),this._pos-e);default:if(o<32)throw new Error(`${Pe} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${Pe} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new oe(V.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new oe(V.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new oe(V.null,null,4);case 102:return this.expect([102,97,108,115,101]),new oe(V.false,!1,5);case 116:return this.expect([116,114,117,101]),new oe(V.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${Pe} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1);if(this.ch()!==44)throw new Error(`${Pe} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1);if(this.ch()!==44)throw new Error(`${Pe} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Pe} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${Pe} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function mT(r,e){return e=Object.assign({tokenizer:new s1(r,e)},e),ay(r,e)}function gh({name:r,code:e,encode:t}){return new gT(r,e,t)}var gT=class{constructor(e,t,n){B(this,"name");B(this,"code");B(this,"encode");this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?ph(this.code,t):t.then(n=>ph(this.code,n))}else throw Error("Unknown type, must be binary type")}};var yT={};xe(yT,{base64:()=>a8,base64pad:()=>n6e,base64url:()=>i6e,base64urlpad:()=>o6e});var a8=Jr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),n6e=Jr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),i6e=Jr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),o6e=Jr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function s6e(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function a6e(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Xe.asCID(r);if(!e)return null;let t=e.toString();return[new oe(V.map,1/0,1),new oe(V.string,"/",1),new oe(V.string,t,t.length),new oe(V.break,void 0,1)]}function c8(r){let e=a8.encode(r).slice(1);return[new oe(V.map,1/0,1),new oe(V.string,"/",1),new oe(V.map,1/0,1),new oe(V.string,"bytes",5),new oe(V.string,e,e.length),new oe(V.break,void 0,1),new oe(V.break,void 0,1)]}function Ia(r){return c8(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function c6e(r){return c8(new Uint8Array(r))}function u6e(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function l6e(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var f6e={typeEncoders:{Object:a6e,Buffer:c8,Uint8Array:c8,Int8Array:Ia,Uint16Array:Ia,Int16Array:Ia,Uint32Array:Ia,Int32Array:Ia,Float32Array:Ia,Float64Array:Ia,Uint8ClampedArray:Ia,BigInt64Array:Ia,BigUint64Array:Ia,DataView:Ia,ArrayBuffer:c6e,undefined:u6e,number:l6e}},wT=class extends s1{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===V.map){let t=this._next();if(t.type===V.string&&t.value==="/"){let n=this._next();if(n.type===V.string){if(this._next().type!==V.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new oe(V.tag,42,0)}if(n.type===V.map){let i=this._next();if(i.type===V.string&&i.value==="bytes"){let o=this._next();if(o.type===V.string){for(let a=0;a<2;a++)if(this._next().type!==V.break)throw new Error("Invalid encoded Bytes form");let s=a8.decode(`m${o.value}`);return new oe(V.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},bT={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};bT.tags[42]=Xe.parse;var d6e="dag-json",_T=297,SK=r=>pT(r,f6e),AK=r=>{let e=s6e(r),t=Object.assign(bT,{tokenizer:new wT(e,bT)});return mT(e,t)},h6e=r=>p6e.decode(SK(r));var p6e=new TextDecoder,m6e=r=>AK(g6e.encode(r)),g6e=new TextEncoder;var yy={};xe(yy,{code:()=>H8e,decode:()=>Y8e,encode:()=>W8e,name:()=>q8e,toGeneral:()=>Z$});var RT={};xe(RT,{base64:()=>wh,base64pad:()=>A6e,base64url:()=>u8,base64urlpad:()=>T6e});function y6e(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var w6e=y6e,b6e=w6e,TK=b6e;var yh={};xe(yh,{coerce:()=>_c,empty:()=>IK,equals:()=>ET,fromHex:()=>E6e,fromString:()=>vT,isBinary:()=>v6e,toHex:()=>_6e,toString:()=>xT});var IK=new Uint8Array(0),_6e=r=>r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),""),E6e=r=>{let e=r.match(/../g);return e?new Uint8Array(e.map(t=>parseInt(t,16))):IK},ET=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},v6e=r=>r instanceof ArrayBuffer||ArrayBuffer.isView(r),vT=r=>new TextEncoder().encode(r),xT=r=>new TextDecoder().decode(r);var ST=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},AT=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return RK(this,e)}},TT=class{constructor(e){this.decoders=e}or(e){return RK(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},RK=(r,e)=>new TT({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),IT=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new ST(e,t,n),this.decoder=new AT(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},c1=({name:r,prefix:e,encode:t,decode:n})=>new IT(r,e,t,n),hf=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=TK(t,e);return c1({prefix:r,name:e,encode:n,decode:o=>_c(i(o))})},x6e=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},S6e=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<c1({prefix:e,name:r,encode(i){return S6e(i,n,t)},decode(i){return x6e(i,n,t,r)}});var wh=tn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),A6e=tn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),u8=tn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),T6e=tn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Ra(r){return u8.encode(r).slice(1)}function Rs(r){return u8.decode(`u${r}`)}var I6e=kK,CK=128,R6e=127,C6e=~R6e,P6e=Math.pow(2,31);function kK(r,e,t){e=e||[],t=t||0;for(var n=t;r>=P6e;)e[t++]=r&255|CK,r/=128;for(;r&C6e;)e[t++]=r&255|CK,r>>>=7;return e[t]=r|0,kK.bytes=t-n+1,e}var k6e=CT,N6e=128,PK=127;function CT(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw CT.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&PK)<=N6e);return CT.bytes=o-n,t}var D6e=Math.pow(2,7),O6e=Math.pow(2,14),L6e=Math.pow(2,21),B6e=Math.pow(2,28),M6e=Math.pow(2,35),U6e=Math.pow(2,42),F6e=Math.pow(2,49),z6e=Math.pow(2,56),V6e=Math.pow(2,63),K6e=function(r){return r[cy.decode(r,e),cy.decode.bytes],u1=(r,e,t=0)=>(cy.encode(r,e,t),e),l1=r=>cy.encodingLength(r);var Ec=(r,e)=>{let t=e.byteLength,n=l1(r),i=n+l1(t),o=new Uint8Array(i+t);return u1(r,o,0),u1(t,o,n),o.set(e,i),new f1(r,t,e,o)},Jn=r=>{let e=_c(r),[t,n]=uy(e),[i,o]=uy(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new f1(t,i,s,e)},NK=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ET(r.bytes,t.bytes)}},f1=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var PT={};xe(PT,{base58btc:()=>tt,base58flickr:()=>H6e});var tt=hf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),H6e=hf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var NT={};xe(NT,{base32:()=>Ot,base32hex:()=>W6e,base32hexpad:()=>Q6e,base32hexpadupper:()=>X6e,base32hexupper:()=>Y6e,base32pad:()=>kT,base32padupper:()=>j6e,base32upper:()=>G6e,base32z:()=>Z6e});var Ot=tn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),G6e=tn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kT=tn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),j6e=tn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),W6e=tn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Y6e=tn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Q6e=tn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),X6e=tn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z6e=tn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var DK=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return e8e(t,DT(r),e||tt.encoder);default:return t8e(t,DT(r),e||Ot.encoder)}};var OK=new WeakMap,DT=r=>{let e=OK.get(r);if(e==null){let t=new Map;return OK.set(r,t),t}return e},ce=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:t}=this;if(e!==ly)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==r8e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ce.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:{let{code:e,digest:t}=this.multihash,n=Ec(e,t);return ce.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return ce.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&NK(e.multihash,n.multihash)}toString(e){return DK(this,e)}toJSON(){return{"/":DK(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof ce)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new ce(n,i,o,s||LK(n,i,o.bytes))}else if(t[n8e]===!0){let{version:n,multihash:i,code:o}=t,s=Jn(i);return ce.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ly)throw new Error(`Version 0 CID must use dag-pb (code: ${ly}) block encoding`);return new ce(e,t,n,n.bytes)}case 1:{let i=LK(e,t,n.bytes);return new ce(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ce.create(0,ly,e)}static createV1(e,t){return ce.create(1,e,t)}static decode(e){let[t,n]=ce.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ce.inspectBytes(e),n=t.size-t.multihashSize,i=_c(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new f1(t.multihashCode,t.digestSize,o,i);return[t.version===0?ce.createV0(s):ce.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=uy(e.subarray(t));return t+=h,f},i=n(),o=ly;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=J6e(e,t),o=ce.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return DT(o).set(n,e),o}},J6e=(r,e)=>{switch(r[0]){case"Q":{let t=e||tt;return[tt.prefix,t.decode(`${tt.prefix}${r}`)]}case tt.prefix:{let t=e||tt;return[tt.prefix,t.decode(r)]}case Ot.prefix:{let t=e||Ot;return[Ot.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},e8e=(r,e,t)=>{let{prefix:n}=t;if(n!==tt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},t8e=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},ly=112,r8e=18,LK=(r,e,t)=>{let n=l1(r),i=n+l1(e),o=new Uint8Array(i+t.byteLength);return u1(r,o,0),u1(e,o,n),o.set(t,i),o},n8e=Symbol.for("@ipld/js-cid/CID");function BK(r){let[e,t,n]=r;return{payload:t,signatures:[{protected:e,signature:n}],link:ce.decode(Rs(t))}}function i8e(r){let e={signature:Rs(r.signature)};return r.header&&(e.header=r.header),r.protected&&(e.protected=Rs(r.protected)),e}function MK(r){let e=Rs(r.payload);try{ce.decode(e)}catch{throw new Error("Not a valid DagJWS")}return{payload:e,signatures:r.signatures.map(i8e)}}function o8e(r){let e={signature:Ra(r.signature)};return r.header&&(e.header=r.header),r.protected&&(e.protected=Ra(r.protected)),e}function UK(r){let e={payload:Ra(r.payload),signatures:r.signatures.map(o8e)};return e.link=ce.decode(new Uint8Array(r.payload)),e}function FK(r){let[e,t,n,i,o]=r,s={ciphertext:i,iv:n,protected:e,tag:o};return t&&(s.recipients=[{encrypted_key:t}]),s}function a8e(r){let e={};return r.encrypted_key&&(e.encrypted_key=Rs(r.encrypted_key)),r.header&&(e.header=r.header),e}function zK(r){let e={ciphertext:Rs(r.ciphertext),protected:Rs(r.protected),iv:Rs(r.iv),tag:Rs(r.tag)};return r.aad&&(e.aad=Rs(r.aad)),r.recipients&&(e.recipients=r.recipients.map(a8e)),r.unprotected&&(e.unprotected=r.unprotected),e}function c8e(r){let e={};return r.encrypted_key&&(e.encrypted_key=Ra(r.encrypted_key)),r.header&&(e.header=r.header),e}function VK(r){let e={ciphertext:Ra(r.ciphertext),protected:Ra(r.protected),iv:Ra(r.iv),tag:Ra(r.tag)};return r.aad&&(e.aad=Ra(r.aad)),r.recipients&&(e.recipients=r.recipients.map(c8e)),r.unprotected&&(e.unprotected=r.unprotected),e}var l8e=["string","number","bigint","symbol"],f8e=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function KK(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(l8e.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(d8e(r))return"Buffer";let t=h8e(r);return t||"Object"}function d8e(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function h8e(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(f8e.includes(e))return e}var Q=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};Q.uint=new Q(0,"uint",!0);Q.negint=new Q(1,"negint",!0);Q.bytes=new Q(2,"bytes",!0);Q.string=new Q(3,"string",!0);Q.array=new Q(4,"array",!1);Q.map=new Q(5,"map",!1);Q.tag=new Q(6,"tag",!1);Q.float=new Q(7,"float",!0);Q.false=new Q(7,"false",!0);Q.true=new Q(7,"true",!0);Q.null=new Q(7,"null",!0);Q.undefined=new Q(7,"undefined",!0);Q.break=new Q(7,"break",!0);var Se=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var d1=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",p8e=new TextDecoder,m8e=new TextEncoder;function f8(r){return d1&&globalThis.Buffer.isBuffer(r)}function OT(r){return r instanceof Uint8Array?f8(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var GK=d1?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):qK(r,e,t):(r,e,t)=>t-e>64?p8e.decode(r.subarray(e,t)):qK(r,e,t),jK=d1?r=>r.length>64?globalThis.Buffer.from(r):$K(r):r=>r.length>64?m8e.encode(r):$K(r),vc=r=>Uint8Array.from(r),h1=d1?(r,e,t)=>f8(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),WK=d1?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),OT(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},YK=d1?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function QK(r,e){if(f8(r)&&f8(e))return r.compare(e);for(let t=0;t55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function qK(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return g8e(n)}var HK=4096;function g8e(r){let e=r.length;if(e<=HK)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=h1(n,0,this.cursor)}else t=WK(this.chunks,this.cursor);return e&&this.reset(),t}};var nt="CBOR decode error:",LT="CBOR encode error:",dy=[];dy[23]=1;dy[24]=2;dy[25]=3;dy[26]=5;dy[27]=9;function Fu(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${nt} encountered BigInt larger than allowable range`)}}Cs.encodedSize=function(e){return gi.encodedSize(e.value)};gi.encodedSize=function(e){return et.value?1:0};function t$(r,e,t,n){return new Se(Q.negint,-1-Lo(r,e+1,n),2)}function r$(r,e,t,n){return new Se(Q.negint,-1-Bo(r,e+1,n),3)}function n$(r,e,t,n){return new Se(Q.negint,-1-Mo(r,e+1,n),5)}var BT=BigInt(-1),i$=BigInt(1);function o$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new Se(Q.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${nt} integers outside of the safe integer range are not supported`);return new Se(Q.negint,BT-BigInt(i),9)}function d8(r,e){let t=e.value,n=typeof t=="bigint"?t*BT-i$:t*-1-1;gi(r,e.type.majorEncoded,n)}d8.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*BT-i$:t*-1-1;return nt.value?-1:0};function hy(r,e,t,n){Fu(r,e,t+n);let i=h1(r,e+t,e+t+n);return new Se(Q.bytes,i,t+n)}function s$(r,e,t,n){return hy(r,e,1,t)}function a$(r,e,t,n){return hy(r,e,2,Lo(r,e+1,n))}function c$(r,e,t,n){return hy(r,e,3,Bo(r,e+1,n))}function u$(r,e,t,n){return hy(r,e,5,Mo(r,e+1,n))}function l$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer bytes lengths not supported`);return hy(r,e,9,i)}function h8(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===Q.string?jK(r.value):r.value),r.encodedBytes}function p1(r,e){let t=h8(e);gi(r,e.type.majorEncoded,t.length),r.push(t)}p1.encodedSize=function(e){let t=h8(e);return gi.encodedSize(t.length)+t.length};p1.compareTokens=function(e,t){return b8e(h8(e),h8(t))};function b8e(r,e){return r.lengthe.length?1:QK(r,e)}function py(r,e,t,n,i){let o=t+n;Fu(r,e,o);let s=new Se(Q.string,GK(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=h1(r,e+t,e+o)),s}function f$(r,e,t,n){return py(r,e,1,t,n)}function d$(r,e,t,n){return py(r,e,2,Lo(r,e+1,n),n)}function h$(r,e,t,n){return py(r,e,3,Bo(r,e+1,n),n)}function p$(r,e,t,n){return py(r,e,5,Mo(r,e+1,n),n)}function m$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer string lengths not supported`);return py(r,e,9,i,n)}var g$=p1;function m1(r,e,t,n){return new Se(Q.array,n,t)}function y$(r,e,t,n){return m1(r,e,1,t)}function w$(r,e,t,n){return m1(r,e,2,Lo(r,e+1,n))}function b$(r,e,t,n){return m1(r,e,3,Bo(r,e+1,n))}function _$(r,e,t,n){return m1(r,e,5,Mo(r,e+1,n))}function E$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer array lengths not supported`);return m1(r,e,9,i)}function v$(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${nt} indefinite length items not allowed`);return m1(r,e,1,1/0)}function p8(r,e){gi(r,Q.array.majorEncoded,e.value)}p8.compareTokens=Cs.compareTokens;p8.encodedSize=function(e){return gi.encodedSize(e.value)};function g1(r,e,t,n){return new Se(Q.map,n,t)}function x$(r,e,t,n){return g1(r,e,1,t)}function S$(r,e,t,n){return g1(r,e,2,Lo(r,e+1,n))}function A$(r,e,t,n){return g1(r,e,3,Bo(r,e+1,n))}function T$(r,e,t,n){return g1(r,e,5,Mo(r,e+1,n))}function I$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer map lengths not supported`);return g1(r,e,9,i)}function R$(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${nt} indefinite length items not allowed`);return g1(r,e,1,1/0)}function m8(r,e){gi(r,Q.map.majorEncoded,e.value)}m8.compareTokens=Cs.compareTokens;m8.encodedSize=function(e){return gi.encodedSize(e.value)};function C$(r,e,t,n){return new Se(Q.tag,t,1)}function P$(r,e,t,n){return new Se(Q.tag,Lo(r,e+1,n),2)}function k$(r,e,t,n){return new Se(Q.tag,Bo(r,e+1,n),3)}function N$(r,e,t,n){return new Se(Q.tag,Mo(r,e+1,n),5)}function D$(r,e,t,n){return new Se(Q.tag,Uo(r,e+1,n),9)}function g8(r,e){gi(r,Q.tag.majorEncoded,e.value)}g8.compareTokens=Cs.compareTokens;g8.encodedSize=function(e){return gi.encodedSize(e.value)};var A8e=20,T8e=21,I8e=22,R8e=23;function O$(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${nt} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Se(Q.null,null,1):new Se(Q.undefined,void 0,1)}function L$(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${nt} indefinite length items not allowed`);return new Se(Q.break,void 0,1)}function MT(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${nt} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${nt} Infinity values are not supported`)}return new Se(Q.float,r,e)}function B$(r,e,t,n){return MT(UT(r,e+1),3,n)}function M$(r,e,t,n){return MT(FT(r,e+1),5,n)}function U$(r,e,t,n){return MT(K$(r,e+1),9,n)}function y8(r,e,t){let n=e.value;if(n===!1)r.push([Q.float.majorEncoded|A8e]);else if(n===!0)r.push([Q.float.majorEncoded|T8e]);else if(n===null)r.push([Q.float.majorEncoded|I8e]);else if(n===void 0)r.push([Q.float.majorEncoded|R8e]);else{let i,o=!1;(!t||t.float64!==!0)&&(z$(n),i=UT(Ca,1),n===i||Number.isNaN(n)?(Ca[0]=249,r.push(Ca.slice(0,3)),o=!0):(V$(n),i=FT(Ca,1),n===i&&(Ca[0]=250,r.push(Ca.slice(0,5)),o=!0))),o||(C8e(n),i=K$(Ca,1),Ca[0]=251,r.push(Ca.slice(0,9)))}}y8.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){z$(n);let i=UT(Ca,1);if(n===i||Number.isNaN(n))return 3;if(V$(n),i=FT(Ca,1),n===i)return 5}return 9};var F$=new ArrayBuffer(9),Ps=new DataView(F$,1),Ca=new Uint8Array(F$,0);function z$(r){if(r===1/0)Ps.setUint16(0,31744,!1);else if(r===-1/0)Ps.setUint16(0,64512,!1);else if(Number.isNaN(r))Ps.setUint16(0,32256,!1);else{Ps.setFloat32(0,r);let e=Ps.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ps.setUint16(0,31744,!1);else if(t===0)Ps.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Ps.setUint16(0,0):i<-14?Ps.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ps.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function UT(r,e){if(r.length-e<2)throw new Error(`${nt} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function V$(r){Ps.setFloat32(0,r,!1)}function FT(r,e){if(r.length-e<4)throw new Error(`${nt} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function C8e(r){Ps.setFloat64(0,r,!1)}function K$(r,e){if(r.length-e<8)throw new Error(`${nt} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}y8.compareTokens=Cs.compareTokens;function er(r,e,t){throw new Error(`${nt} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function w8(r){return()=>{throw new Error(`${nt} ${r}`)}}var he=[];for(let r=0;r<=23;r++)he[r]=er;he[24]=XK;he[25]=ZK;he[26]=JK;he[27]=e$;he[28]=er;he[29]=er;he[30]=er;he[31]=er;for(let r=32;r<=55;r++)he[r]=er;he[56]=t$;he[57]=r$;he[58]=n$;he[59]=o$;he[60]=er;he[61]=er;he[62]=er;he[63]=er;for(let r=64;r<=87;r++)he[r]=s$;he[88]=a$;he[89]=c$;he[90]=u$;he[91]=l$;he[92]=er;he[93]=er;he[94]=er;he[95]=w8("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)he[r]=f$;he[120]=d$;he[121]=h$;he[122]=p$;he[123]=m$;he[124]=er;he[125]=er;he[126]=er;he[127]=w8("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)he[r]=y$;he[152]=w$;he[153]=b$;he[154]=_$;he[155]=E$;he[156]=er;he[157]=er;he[158]=er;he[159]=v$;for(let r=160;r<=183;r++)he[r]=x$;he[184]=S$;he[185]=A$;he[186]=T$;he[187]=I$;he[188]=er;he[189]=er;he[190]=er;he[191]=R$;for(let r=192;r<=215;r++)he[r]=C$;he[216]=P$;he[217]=k$;he[218]=N$;he[219]=D$;he[220]=er;he[221]=er;he[222]=er;he[223]=er;for(let r=224;r<=243;r++)he[r]=w8("simple values are not supported");he[244]=er;he[245]=er;he[246]=er;he[247]=O$;he[248]=w8("simple values are not supported");he[249]=B$;he[250]=M$;he[251]=U$;he[252]=er;he[253]=er;he[254]=er;he[255]=L$;var Pa=[];for(let r=0;r<24;r++)Pa[r]=new Se(Q.uint,r,1);for(let r=-1;r>=-24;r--)Pa[31-r]=new Se(Q.negint,r,1);Pa[64]=new Se(Q.bytes,new Uint8Array(0),1);Pa[96]=new Se(Q.string,"",1);Pa[128]=new Se(Q.array,0,1);Pa[160]=new Se(Q.map,0,1);Pa[244]=new Se(Q.false,!1,1);Pa[245]=new Se(Q.true,!0,1);Pa[246]=new Se(Q.null,null,1);function $$(r){switch(r.type){case Q.false:return vc([244]);case Q.true:return vc([245]);case Q.null:return vc([246]);case Q.bytes:return r.value.length?void 0:vc([64]);case Q.string:return r.value===""?vc([96]):void 0;case Q.array:return r.value===0?vc([128]):void 0;case Q.map:return r.value===0?vc([160]):void 0;case Q.uint:return r.value<24?vc([Number(r.value)]):void 0;case Q.negint:if(r.value>=-24)return vc([31-Number(r.value)])}}var k8e={float64:!1,mapSorter:O8e,quickEncodeToken:$$};function N8e(){let r=[];return r[Q.uint.major]=Cs,r[Q.negint.major]=d8,r[Q.bytes.major]=p1,r[Q.string.major]=g$,r[Q.array.major]=p8,r[Q.map.major]=m8,r[Q.tag.major]=g8,r[Q.float.major]=y8,r}var q$=N8e(),zT=new fy,y1=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${LT} object contains circular references`);return new y1(t,e)}},pf={null:new Se(Q.null,null),undefined:new Se(Q.undefined,void 0),true:new Se(Q.true,!0),false:new Se(Q.false,!1),emptyArray:new Se(Q.array,0),emptyMap:new Se(Q.map,0)},mf={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Se(Q.float,r):r>=0?new Se(Q.uint,r):new Se(Q.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Se(Q.uint,r):new Se(Q.negint,r)},Uint8Array(r,e,t,n){return new Se(Q.bytes,r)},string(r,e,t,n){return new Se(Q.string,r)},boolean(r,e,t,n){return r?pf.true:pf.false},null(r,e,t,n){return pf.null},undefined(r,e,t,n){return pf.undefined},ArrayBuffer(r,e,t,n){return new Se(Q.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Se(Q.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[pf.emptyArray,new Se(Q.break)]:pf.emptyArray;n=y1.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=b8(s,t,n);return t.addBreakTokens?[new Se(Q.array,r.length),i,new Se(Q.break)]:[new Se(Q.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[pf.emptyMap,new Se(Q.break)]:pf.emptyMap;n=y1.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[b8(u,t,n),b8(i?r.get(u):r[u],t,n)];return D8e(a,t),t.addBreakTokens?[new Se(Q.map,s),a,new Se(Q.break)]:[new Se(Q.map,s),a]}};mf.Map=mf.Object;mf.Buffer=mf.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))mf[`${r}Array`]=mf.DataView;function b8(r,e={},t){let n=KK(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||mf[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=mf[n];if(!o)throw new Error(`${LT} unsupported type: ${n}`);return o(r,n,e,t)}function D8e(r,e){e.mapSorter&&r.sort(e.mapSorter)}function O8e(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=q$[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function H$(r,e,t,n){if(Array.isArray(e))for(let i of e)H$(r,i,t,n);else t[e.type.major](r,e,n)}function L8e(r,e,t){let n=b8(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new fy(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return OT(a.chunks[0])}}return zT.reset(),H$(zT,n,e,t),zT.toBytes(!0)}function zu(r,e){return e=Object.assign({},k8e,e),L8e(r,q$,e)}var B8e={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},VT=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=Pa[e];if(t===void 0){let n=he[e];if(!n)throw new Error(`${nt} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},my=Symbol.for("DONE"),_8=Symbol.for("BREAK");function M8e(r,e,t){let n=[];for(let i=0;izu(r,K8e),E8=r=>ks(r,j$);var q8e="dag-jose",H8e=133;function Q$(r){return"payload"in r&&typeof r.payload=="string"&&"signatures"in r&&Array.isArray(r.signatures)}function G8e(r){return"payload"in r&&r.payload instanceof Uint8Array&&"signatures"in r&&Array.isArray(r.signatures)}function j8e(r){return"ciphertext"in r&&r.ciphertext instanceof Uint8Array&&"iv"in r&&r.iv instanceof Uint8Array&&"protected"in r&&r.protected instanceof Uint8Array&&"tag"in r&&r.tag instanceof Uint8Array}function X$(r){return"ciphertext"in r&&typeof r.ciphertext=="string"&&"iv"in r&&typeof r.iv=="string"&&"protected"in r&&typeof r.protected=="string"&&"tag"in r&&typeof r.tag=="string"}function Z$(r){if(typeof r=="string"){let e=r.split(".");if(e.length===3)return BK(e);if(e.length===5)return FK(e);throw new Error("Not a valid JOSE string")}if(Q$(r)||X$(r))return r;throw new Error("Not a valid unencoded JOSE object")}function W8e(r){typeof r=="string"&&(r=Z$(r));let e;if(Q$(r))e=MK(r);else if(X$(r))e=zK(r);else throw new Error("Not a valid JOSE object");return new Uint8Array(Y$(e))}function Y8e(r){let e;try{e=E8(r)}catch{throw new Error("Not a valid DAG-JOSE object")}if(G8e(e))return UK(e);if(j8e(e))return VK(e);throw new Error("Not a valid DAG-JOSE object")}var qT={};xe(qT,{identity:()=>Ii});var J$=0,Q8e="identity",eq=_a,X8e=r=>hc(J$,eq(r)),Ii={code:J$,name:Q8e,encode:eq,digest:X8e};var HT={};xe(HT,{identity:()=>Z8e});var Z8e=M0({prefix:"\0",name:"identity",encode:r=>WU(r),decode:r=>jU(r)});var GT={};xe(GT,{base2:()=>J8e});var J8e=Zr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jT={};xe(jT,{base8:()=>ebe});var ebe=Zr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var WT={};xe(WT,{base10:()=>tbe});var tbe=tf({prefix:"9",name:"base10",alphabet:"0123456789"});var YT={};xe(YT,{base16:()=>rbe,base16upper:()=>nbe});var rbe=Zr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nbe=Zr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var QT={};xe(QT,{base36:()=>w1,base36upper:()=>ibe});var w1=tf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ibe=tf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var XT={};xe(XT,{base256emoji:()=>ube});var tq=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),obe=tq.reduce((r,e,t)=>(r[t]=e,r),[]),sbe=tq.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function abe(r){return r.reduce((e,t)=>(e+=obe[t],e),"")}function cbe(r){let e=[];for(let t of r){let n=sbe[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var ube=M0({prefix:"\u{1F680}",name:"base256emoji",encode:abe,decode:cbe});var yf={};xe(yf,{code:()=>gf,decode:()=>dbe,encode:()=>fbe,name:()=>lbe});var lbe="raw",gf=85,fbe=r=>_a(r),dbe=r=>_a(r);var Vu={...HT,...GT,...jT,...WT,...YT,...lA,...QT,...cA,...SA,...XT},v8={...mA,...qT},x8={raw:yf,json:Vg};var Ku=class extends Error{constructor(e="not initialized"){super(e),this.name="NotInitializedError",this.code=Ku.code}};Ku.code="ERR_NOT_INITIALIZED";var ZT=class extends Error{constructor(e="cannot initialize an initializing node"){super(e),this.name="AlreadyInitializingError",this.code=ka.code}};ZT.code="ERR_ALREADY_INITIALIZING";var ka=class extends Error{constructor(e="cannot re-initialize an initialized node"){super(e),this.name="AlreadyInitializedError",this.code=ka.code}};ka.code="ERR_ALREADY_INITIALIZED";var $u=class extends Error{constructor(e="not started"){super(e),this.name="NotStartedError",this.code=$u.code}};$u.code="ERR_NOT_STARTED";var _h=class extends Error{constructor(e="cannot start, already startin"){super(e),this.name="AlreadyStartingError",this.code=_h.code}};_h.code="ERR_ALREADY_STARTING";var Eh=class extends Error{constructor(e="cannot start, already started"){super(e),this.name="AlreadyStartedError",this.code=Eh.code}};Eh.code="ERR_ALREADY_STARTED";var Na=class extends Error{constructor(e="not enabled"){super(e),this.name="NotEnabledError",this.code=Na.code}};Na.code="ERR_NOT_ENABLED";function wf(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var nI={};xe(nI,{base10:()=>wbe});function hbe(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var pbe=hbe,mbe=pbe,rq=mbe;var _Ze=new Uint8Array(0);var nq=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var iq=r=>new TextEncoder().encode(r),oq=r=>new TextDecoder().decode(r);var JT=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},eI=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return aq(this,e)}},tI=class{constructor(e){this.decoders=e}or(e){return aq(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},aq=(r,e)=>new tI({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),rI=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new JT(e,t,n),this.decoder=new eI(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},b1=({name:r,prefix:e,encode:t,decode:n})=>new rI(r,e,t,n),bf=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=rq(t,e);return b1({prefix:r,name:e,encode:n,decode:o=>qu(i(o))})},gbe=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},ybe=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<b1({prefix:e,name:r,encode(i){return ybe(i,n,t)},decode(i){return gbe(i,n,t,r)}});var wbe=bf({prefix:"9",name:"base10",alphabet:"0123456789"});var iI={};xe(iI,{base16:()=>bbe,base16upper:()=>_be});var bbe=rn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_be=rn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var oI={};xe(oI,{base2:()=>Ebe});var Ebe=rn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sI={};xe(sI,{base256emoji:()=>Tbe});var cq=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),vbe=cq.reduce((r,e,t)=>(r[t]=e,r),[]),xbe=cq.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Sbe(r){return r.reduce((e,t)=>(e+=vbe[t],e),"")}function Abe(r){let e=[];for(let t of r){let n=xbe[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Tbe=b1({prefix:"\u{1F680}",name:"base256emoji",encode:Sbe,decode:Abe});var aI={};xe(aI,{base32:()=>_f,base32hex:()=>Pbe,base32hexpad:()=>Nbe,base32hexpadupper:()=>Dbe,base32hexupper:()=>kbe,base32pad:()=>Rbe,base32padupper:()=>Cbe,base32upper:()=>Ibe,base32z:()=>Obe});var _f=rn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ibe=rn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Rbe=rn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Cbe=rn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pbe=rn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kbe=rn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nbe=rn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Dbe=rn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Obe=rn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var cI={};xe(cI,{base36:()=>Lbe,base36upper:()=>Bbe});var Lbe=bf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Bbe=bf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var uI={};xe(uI,{base58btc:()=>Qi,base58flickr:()=>Mbe});var Qi=bf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mbe=bf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fI={};xe(fI,{base64:()=>lI,base64pad:()=>Ube,base64url:()=>Fbe,base64urlpad:()=>zbe});var lI=rn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ube=rn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fbe=rn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zbe=rn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dI={};xe(dI,{base8:()=>Vbe});var Vbe=rn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hI={};xe(hI,{identity:()=>Kbe});var Kbe=b1({prefix:"\0",name:"identity",encode:r=>oq(r),decode:r=>iq(r)});var LZe=new TextEncoder,BZe=new TextDecoder;var mI={};xe(mI,{identity:()=>A8});var Hbe=fq,uq=128,Gbe=127,jbe=~Gbe,Wbe=Math.pow(2,31);function fq(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Wbe;)e[t++]=r&255|uq,r/=128;for(;r&jbe;)e[t++]=r&255|uq,r>>>=7;return e[t]=r|0,fq.bytes=t-n+1,e}var Ybe=pI,Qbe=128,lq=127;function pI(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw pI.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&lq)<=Qbe);return pI.bytes=o-n,t}var Xbe=Math.pow(2,7),Zbe=Math.pow(2,14),Jbe=Math.pow(2,21),e_e=Math.pow(2,28),t_e=Math.pow(2,35),r_e=Math.pow(2,42),n_e=Math.pow(2,49),i_e=Math.pow(2,56),o_e=Math.pow(2,63),s_e=function(r){return r[wy.decode(r,e),wy.decode.bytes],_1=(r,e,t=0)=>(wy.encode(r,e,t),e),E1=r=>wy.encodingLength(r);var Ef=(r,e)=>{let t=e.byteLength,n=E1(r),i=n+E1(t),o=new Uint8Array(i+t);return _1(r,o,0),_1(t,o,n),o.set(e,i),new v1(r,t,e,o)},_y=r=>{let e=qu(r),[t,n]=by(e),[i,o]=by(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new v1(t,i,s,e)},dq=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&nq(r.bytes,t.bytes)}},v1=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var hq=0,u_e="identity",pq=qu,l_e=r=>Ef(hq,pq(r)),A8={code:hq,name:u_e,encode:pq,digest:l_e};var wI={};xe(wI,{sha256:()=>T8,sha512:()=>f_e});var yI=({name:r,code:e,encode:t})=>new gI(r,e,t),gI=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Ef(this.code,t):t.then(n=>Ef(this.code,n))}else throw Error("Unknown type, must be binary type")}};var gq=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),T8=yI({name:"sha2-256",code:18,encode:gq("SHA-256")}),f_e=yI({name:"sha2-512",code:19,encode:gq("SHA-512")});var yq=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return h_e(t,bI(r),e||Qi.encoder);default:return p_e(t,bI(r),e||_f.encoder)}};var wq=new WeakMap,bI=r=>{let e=wq.get(r);if(e==null){let t=new Map;return wq.set(r,t),t}return e},Nr=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:t}=this;if(e!==Ey)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==m_e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Nr.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:{let{code:e,digest:t}=this.multihash,n=Ef(e,t);return Nr.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return Nr.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&dq(e.multihash,n.multihash)}toString(e){return yq(this,e)}toJSON(){return{"/":yq(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof Nr)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new Nr(n,i,o,s||bq(n,i,o.bytes))}else if(t[g_e]===!0){let{version:n,multihash:i,code:o}=t,s=_y(i);return Nr.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ey)throw new Error(`Version 0 CID must use dag-pb (code: ${Ey}) block encoding`);return new Nr(e,t,n,n.bytes)}case 1:{let i=bq(e,t,n.bytes);return new Nr(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return Nr.create(0,Ey,e)}static createV1(e,t){return Nr.create(1,e,t)}static decode(e){let[t,n]=Nr.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=Nr.inspectBytes(e),n=t.size-t.multihashSize,i=qu(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new v1(t.multihashCode,t.digestSize,o,i);return[t.version===0?Nr.createV0(s):Nr.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=by(e.subarray(t));return t+=h,f},i=n(),o=Ey;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=d_e(e,t),o=Nr.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bI(o).set(n,e),o}},d_e=(r,e)=>{switch(r[0]){case"Q":{let t=e||Qi;return[Qi.prefix,t.decode(`${Qi.prefix}${r}`)]}case Qi.prefix:{let t=e||Qi;return[Qi.prefix,t.decode(r)]}case _f.prefix:{let t=e||_f;return[_f.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},h_e=(r,e,t)=>{let{prefix:n}=t;if(n!==Qi.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},p_e=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},Ey=112,m_e=18,bq=(r,e,t)=>{let n=E1(r),i=n+E1(e),o=new Uint8Array(i+t.byteLength);return _1(r,o,0),_1(e,o,n),o.set(t,i),o},g_e=Symbol.for("@ipld/js-cid/CID");var S1={...hI,...oI,...dI,...nI,...iI,...aI,...cI,...uI,...fI,...sI},ZZe={...wI,...mI};function vf(r=0){var e;return((e=globalThis.Buffer)==null?void 0:e.allocUnsafe)!=null?wf(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Eq(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var _q=Eq("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_I=Eq("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=vf(r.length);for(let t=0;t__e});var __e=cf({prefix:"9",name:"base10",alphabet:"0123456789"});var SI={};xe(SI,{base16:()=>E_e,base16upper:()=>v_e});var E_e=Jr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),v_e=Jr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var AI={};xe(AI,{base2:()=>x_e});var x_e=Jr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var TI={};xe(TI,{base256emoji:()=>R_e});var Iq=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),S_e=Iq.reduce((r,e,t)=>(r[t]=e,r),[]),A_e=Iq.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function T_e(r){return r.reduce((e,t)=>(e+=S_e[t],e),"")}function I_e(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=A_e[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var R_e=j0({prefix:"\u{1F680}",name:"base256emoji",encode:T_e,decode:I_e});var II={};xe(II,{base8:()=>C_e});var C_e=Jr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var RI={};xe(RI,{identity:()=>P_e});var P_e=j0({prefix:"\0",name:"identity",encode:r=>VA(r),decode:r=>zA(r)});var bJe=new TextEncoder,_Je=new TextDecoder;var CI={};xe(CI,{identity:()=>L_e});var Rq=0,D_e="identity",Cq=yc;function O_e(r){return ph(Rq,Cq(r))}var L_e={code:Rq,name:D_e,encode:Cq,digest:O_e};var PI={};xe(PI,{sha256:()=>B_e,sha512:()=>M_e});function Pq(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var B_e=gh({name:"sha2-256",code:18,encode:Pq("SHA-256")}),M_e=gh({name:"sha2-512",code:19,encode:Pq("SHA-512")});var xy={...RI,...AI,...II,...xI,...SI,...GA,...jA,...WA,...yT,...TI},AJe={...PI,...CI};function Hu(r=0){return new Uint8Array(r)}function Ri(r=0){return new Uint8Array(r)}function Nq(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var kq=Nq("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),kI=Nq("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=Ri(r.length);for(let t=0;tNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function BI(r,e,t=0){switch(ti(r)){case 8:e[t++]=r&255|ar,r/=128;case 7:e[t++]=r&255|ar,r/=128;case 6:e[t++]=r&255|ar,r/=128;case 5:e[t++]=r&255|ar,r/=128;case 4:e[t++]=r&255|ar,r>>>=7;case 3:e[t++]=r&255|ar,r>>>=7;case 2:e[t++]=r&255|ar,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function K_e(r,e,t=0){switch(ti(r)){case 8:e.set(t++,r&255|ar),r/=128;case 7:e.set(t++,r&255|ar),r/=128;case 6:e.set(t++,r&255|ar),r/=128;case 5:e.set(t++,r&255|ar),r/=128;case 4:e.set(t++,r&255|ar),r>>>=7;case 3:e.set(t++,r&255|ar),r>>>=7;case 2:e.set(t++,r&255|ar),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function MI(r,e){let t=r[e],n=0;if(n+=t&Ci,ti+o.length,0));let t=Ri(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var N8=class{constructor(){B(this,"index",0);B(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let 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(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=e,o+=l,o>u||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;nthis.readIPv4Addr());if(s!==void 0)return t[i]=s[0],t[i+1]=s[1],t[i+2]=s[2],t[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];t[i]=o>>8,t[i+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Dq=45,q_e=15,A1=new N8;function UI(r){if(!(r.length>q_e))return A1.new(r).parseWith(()=>A1.readIPv4Addr())}function FI(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dq))return A1.new(r).parseWith(()=>A1.readIPv6Addr())}function D8(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dq))return A1.new(r).parseWith(()=>A1.readIPAddr())}var YJe=parseInt("0xFFFF",16),QJe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function cr(r,e="utf8"){let t=P8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function O8(r){return!!UI(r)}function L8(r){return!!FI(r)}function xc(r){return!!D8(r)}var Bq=O8,Y_e=L8,zI=function(r){let e=0;if(r=r.toString().trim(),Bq(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Y_e(r)){let t=r.split(":",8),n;for(n=0;n0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},Mq=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let o=0;o{let e=Z_e(...r);VI[e.code]=e,T1[e.name]=e});function Z_e(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function Lt(r){if(typeof r=="number"){if(VI[r]!=null)return VI[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(T1[r]!=null)return T1[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Met=Lt("ip4"),Uet=Lt("ip6"),Fet=Lt("ipcidr");function Sy(r,e){switch(Lt(r).code){case 4:case 41:return eEe(e);case 42:return qI(e);case 6:case 273:case 33:case 132:return zq(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qI(e);case 421:return iEe(e);case 444:return Fq(e);case 445:return Fq(e);case 466:return nEe(e);case 481:return globalThis.encodeURIComponent(qI(e));default:return $n(e,"base16")}}function HI(r,e){switch(Lt(r).code){case 4:return Uq(e);case 41:return Uq(e);case 42:return $I(e);case 6:case 273:case 33:case 132:return GI(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return $I(e);case 421:return tEe(e);case 444:return oEe(e);case 445:return sEe(e);case 466:return rEe(e);case 481:return $I(globalThis.decodeURIComponent(e));default:return cr(e,"base16")}}var KI=Object.values(xy).map(r=>r.decoder),J_e=function(){let r=KI[0].or(KI[1]);return KI.slice(2).forEach(e=>r=r.or(e)),r}();function Uq(r){if(!xc(r))throw new Error("invalid ip address");return zI(r)}function eEe(r){let e=Mq(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!xc(e))throw new Error("invalid ip address");return e}function GI(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function zq(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function $I(r){let e=cr(r),t=Uint8Array.from(xf(e.length));return yi([t,e],t.length+e.length)}function qI(r){let e=Gu(r);if(r=r.slice(ti(e)),r.length!==e)throw new Error("inconsistent lengths");return $n(r)}function tEe(r){let e;r[0]==="Q"||r[0]==="1"?e=uf(Yi.decode(`z${r}`)).bytes:e=Xe.parse(r).multihash.bytes;let t=Uint8Array.from(xf(e.length));return yi([t,e],t.length+e.length)}function rEe(r){let e=J_e.decode(r),t=Uint8Array.from(xf(e.length));return yi([t,e],t.length+e.length)}function nEe(r){let e=Gu(r),t=r.slice(ti(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+$n(t,"base64url")}function iEe(r){let e=Gu(r),t=r.slice(ti(e));if(t.length!==e)throw new Error("inconsistent lengths");return $n(t,"base58btc")}function oEe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=wc.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=GI(n);return yi([t,i],t.length+i.length)}function sEe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=wc.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=GI(n);return yi([t,i],t.length+i.length)}function Fq(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=$n(e,"base32"),i=zq(t);return`${n}:${i}`}function Vq(r){r=jI(r);let e=[],t=[],n=null,i=r.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o=i.length)throw $q("invalid address: "+r);if(a.path===!0){n=jI(i.slice(o).join("/")),e.push([a.code,HI(a.code,n)]),t.push([a.code,n]);break}let c=HI(a.code,i[o]);e.push([a.code,c]),t.push([a.code,Sy(a.code,c)])}return{string:Kq(t),bytes:YI(e),tuples:e,stringTuples:t,path:n}}function WI(r){let e=[],t=[],n=null,i=0;for(;ir.length)throw $q("Invalid address Uint8Array: "+$n(r,"base16"));e.push([o,u]);let l=Sy(o,u);if(t.push([o,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:Kq(t),tuples:e,stringTuples:t,path:n}}function Kq(r){let e=[];return r.map(t=>{let n=Lt(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),jI(e.join("/"))}function YI(r){return yi(r.map(e=>{let t=Lt(e[0]),n=Uint8Array.from(xf(t.code));return e.length>1&&e[1]!=null&&(n=yi([n,e[1]])),n}))}function aEe(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Gu(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ti(t)}}function jI(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function $q(r){return new Error("Error parsing address: "+r)}var cEe=Symbol.for("nodejs.util.inspect.custom"),XI=Symbol.for("@multiformats/js-multiaddr/multiaddr"),uEe=[Lt("dns").code,Lt("dns4").code,Lt("dns6").code,Lt("dnsaddr").code],QI=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},R1,Sf,Ay,Ty,lEe,I1=class{constructor(e){B(this,"bytes");bt(this,R1,void 0);bt(this,Sf,void 0);bt(this,Ay,void 0);bt(this,Ty,void 0);B(this,lEe,!0);e==null&&(e="");let t;if(e instanceof Uint8Array)t=WI(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Vq(e)}else if(Hq(e))t=WI(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,Dt(this,R1,t.string),Dt(this,Sf,t.tuples),Dt(this,Ay,t.stringTuples),Dt(this,Ty,t.path)}toString(){return ge(this,R1)}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="",s=Lt("tcp"),a=Lt("udp"),c=Lt("ip4"),u=Lt("ip6"),l=Lt("dns6"),f=Lt("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(o=`%${p??""}`),uEe.includes(d)&&(t=s.name,i=443,n=`${p??""}${o}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=Lt(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=Lt(d).name,n=`${p??""}${o}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return ge(this,Sf).map(([e])=>Object.assign({},Lt(e)))}protoCodes(){return ge(this,Sf).map(([e])=>e)}protoNames(){return ge(this,Sf).map(([e])=>Lt(e).name)}tuples(){return ge(this,Sf)}stringTuples(){return ge(this,Ay)}encapsulate(e){return e=new I1(e),new I1(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new I1(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new I1(YI(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,i])=>{n===T1.p2p.code&&e.push([n,i]),n===T1["p2p-circuit"].code&&(e=[])});let t=e.pop();if((t==null?void 0:t[1])!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?$n(Yi.decode(`z${n}`),"base58btc"):$n(Xe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return ge(this,Ty)}equals(e){return C8(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=qq.get(t.name);if(n==null)throw new QI(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>Xi(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")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){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[(lEe=XI,cEe)](){return`Multiaddr(${ge(this,R1)})`}},B8=I1;R1=new WeakMap,Sf=new WeakMap,Ay=new WeakMap,Ty=new WeakMap;var qq=new Map;function Hq(r){return!!(r!=null&&r[XI])}function Xi(r){return new B8(r)}var fEe=_e("dns4"),dEe=_e("dns6"),hEe=_e("dnsaddr"),Tf=mn(_e("dns"),hEe,fEe,dEe),M8=mn(_e("ip4"),_e("ip6")),C1=mn(qe(M8,_e("tcp")),qe(Tf,_e("tcp"))),U8=qe(M8,_e("udp")),pEe=qe(U8,_e("utp")),mEe=qe(U8,_e("quic")),gEe=qe(U8,_e("quic-v1")),ZI=mn(qe(C1,_e("ws")),qe(Tf,_e("ws"))),P1=mn(qe(ZI,_e("p2p")),ZI),JI=mn(qe(C1,_e("wss")),qe(Tf,_e("wss")),qe(C1,_e("tls"),_e("ws")),qe(Tf,_e("tls"),_e("ws"))),xh=mn(qe(JI,_e("p2p")),JI),eR=mn(qe(C1,_e("http")),qe(M8,_e("http")),qe(Tf,_e("http"))),tR=mn(qe(C1,_e("https")),qe(M8,_e("https")),qe(Tf,_e("https"))),Gq=qe(U8,_e("webrtc-direct"),_e("certhash")),Yq=mn(qe(Gq,_e("p2p")),Gq),jq=qe(gEe,_e("webtransport"),_e("certhash"),_e("certhash")),Qq=mn(qe(jq,_e("p2p")),jq),Xq=mn(qe(P1,_e("p2p-webrtc-star"),_e("p2p")),qe(xh,_e("p2p-webrtc-star"),_e("p2p")),qe(P1,_e("p2p-webrtc-star")),qe(xh,_e("p2p-webrtc-star"))),dtt=mn(qe(P1,_e("p2p-websocket-star"),_e("p2p")),qe(xh,_e("p2p-websocket-star"),_e("p2p")),qe(P1,_e("p2p-websocket-star")),qe(xh,_e("p2p-websocket-star"))),Zq=mn(qe(eR,_e("p2p-webrtc-direct"),_e("p2p")),qe(tR,_e("p2p-webrtc-direct"),_e("p2p")),qe(eR,_e("p2p-webrtc-direct")),qe(tR,_e("p2p-webrtc-direct"))),Sh=mn(ZI,JI,eR,tR,Xq,Zq,C1,pEe,mEe,Tf,Yq,Qq),htt=mn(qe(Sh,_e("p2p-stardust"),_e("p2p")),qe(Sh,_e("p2p-stardust"))),Af=mn(qe(Sh,_e("p2p")),Xq,Zq,Yq,Qq,_e("p2p")),Wq=mn(qe(Af,_e("p2p-circuit"),Af),qe(Af,_e("p2p-circuit")),qe(_e("p2p-circuit"),Af),qe(Sh,_e("p2p-circuit")),qe(_e("p2p-circuit"),Sh),_e("p2p-circuit")),Jq=()=>mn(qe(Wq,Jq),Wq),vh=Jq(),rR=mn(qe(vh,Af,vh),qe(Af,vh),qe(vh,Af),vh,Af);var ptt=mn(qe(vh,_e("webrtc"),_e("p2p")),qe(vh,_e("webrtc")),qe(Sh,_e("webrtc"),_e("p2p")),qe(Sh,_e("webrtc")),_e("webrtc"));function eH(r){function e(t){let n;try{n=Xi(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function qe(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:eH(e),partialMatch:e}}function mn(...r){function e(n){let i=null;return r.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:eH(e),partialMatch:e}}function _e(r){let e=r;function t(i){let o;try{o=Xi(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}var cH=C(F8(),1);var z8=/^\/(ip[fn]s)\/([^/?#]+)/,uH=1,lH=2,fH=/^https?:\/\/([^/]+)\.(ip[fn]s)\.[^/?]+/;var TEe=/^(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\.)+([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])$/;function V8(r){try{return pH(r)?!!Xe.parse(r):r instanceof Uint8Array?!!Xe.decode(r):!!Xe.asCID(r)}catch{return!1}}function dH(r,e,t=uH,n=lH){let i=mH(r);if(i===!1)return!1;let o=i.match(e);if(o==null||o[t]!=="ipfs")return!1;let s=o[n];return s!=null&&e===fH&&(s=s.toLowerCase()),V8(s)}function hH(r,e,t=uH,n=lH){let i=mH(r);if(i===!1)return!1;let o=i.match(e);if(o==null||o[t]!=="ipns")return!1;let s=o[n];if(s!=null&&e===fH){if(s=s.toLowerCase(),V8(s))return!0;try{!s.includes(".")&&s.includes("-")&&(s=s.replace(/--/g,"@").replace(/-/g,".").replace(/@/g,"-"));let{hostname:a}=new cH.URL(`http://${s}`);return TEe.test(a)}catch{return!1}}return!0}function pH(r){return typeof r=="string"}function mH(r){return r instanceof Uint8Array?$n(r,"base58btc"):pH(r)?r:!1}var K8=r=>dH(r,z8)||hH(r,z8);var gH=r=>dH(r,z8),$8=r=>hH(r,z8);var k1=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var oR={};xe(oR,{identity:()=>IEe});var IEe=c1({prefix:"\0",name:"identity",encode:r=>xT(r),decode:r=>vT(r)});var sR={};xe(sR,{base2:()=>REe});var REe=tn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var aR={};xe(aR,{base8:()=>CEe});var CEe=tn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cR={};xe(cR,{base10:()=>PEe});var PEe=hf({prefix:"9",name:"base10",alphabet:"0123456789"});var uR={};xe(uR,{base16:()=>kEe,base16upper:()=>NEe});var kEe=tn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),NEe=tn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lR={};xe(lR,{base36:()=>DEe,base36upper:()=>OEe});var DEe=hf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),OEe=hf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fR={};xe(fR,{base256emoji:()=>FEe});var yH=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),LEe=yH.reduce((r,e,t)=>(r[t]=e,r),[]),BEe=yH.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function MEe(r){return r.reduce((e,t)=>(e+=LEe[t],e),"")}function UEe(r){let e=[];for(let t of r){let n=BEe[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var FEe=c1({prefix:"\u{1F680}",name:"base256emoji",encode:MEe,decode:UEe});var hR={};xe(hR,{sha256:()=>mr,sha512:()=>zEe});var Ah=({name:r,code:e,encode:t})=>new dR(r,e,t),dR=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Ec(this.code,t):t.then(n=>Ec(this.code,n))}else throw Error("Unknown type, must be binary type")}};var bH=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),mr=Ah({name:"sha2-256",code:18,encode:bH("SHA-256")}),zEe=Ah({name:"sha2-512",code:19,encode:bH("SHA-512")});var pR={};xe(pR,{identity:()=>Ns});var _H=0,VEe="identity",EH=_c,KEe=r=>Ec(_H,EH(r)),Ns={code:_H,name:VEe,encode:EH,digest:KEe};var Sc=85;var Ltt=new TextEncoder,Btt=new TextDecoder;var If={...oR,...sR,...aR,...cR,...uR,...NT,...lR,...PT,...RT,...fR},Vtt={...hR,...pR};function Rf(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function ju(r=0){var e;return((e=globalThis.Buffer)==null?void 0:e.alloc)!=null?Rf(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Ac(r=0){var e;return((e=globalThis.Buffer)==null?void 0:e.allocUnsafe)!=null?Rf(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function xH(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vH=xH("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),mR=xH("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=Ac(r.length);for(let t=0;t1&&this._buf[this._buf.byteLength-1]===G8;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;is)return!1}return t.lengtht.namespaces()))])}};function HEe(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function GEe(r){let e=r.split(":");return e[e.length-1]}function jEe(r){return[].concat(...r)}var j8=C(ee(),1);var IH=C(Kn(),1),RH=C(Da(),1);var WEe=/(-?(?:\d+\.?\d*|\d*\.?\d+)(?:e[-+]?\d+)?)\s*([\p{L}]*)/uig;Et.nanosecond=Et.ns=1/1e6;Et.\u00B5s=Et.\u03BCs=Et.us=Et.microsecond=1/1e3;Et.millisecond=Et.ms=Et[""]=1;Et.second=Et.sec=Et.s=Et.ms*1e3;Et.minute=Et.min=Et.m=Et.s*60;Et.hour=Et.hr=Et.h=Et.m*60;Et.day=Et.d=Et.h*24;Et.week=Et.wk=Et.w=Et.d*7;Et.month=Et.b=Et.d*(365.25/12);Et.year=Et.yr=Et.y=Et.d*365.25;function Et(r="",e="ms"){var t=null;r=(r+"").replace(/(\d)[,_](\d)/g,"$1$2");var n=r[0]==="-";return r.replace(WEe,function(i,o,s){s=TH(s),s&&(t=(t||0)+Math.abs(parseFloat(o,10))*s)}),t&&t/(TH(e)||1)*(n?-1:1)}function TH(r){return Et[r]||Et[r.toLowerCase().replace(/s$/,"")]}var Cf=Et;var Yu=class extends Error{constructor(e="request timed out"){super(e),this.name="TimeoutError",this.code=Yu.code}};Yu.code="ERR_TIMEOUT";function $(r,e){return(...t)=>{let n=t[e??t.length-1];if(!n||!n.timeout)return r(...t);let i=typeof n.timeout=="string"?Cf(n.timeout):n.timeout,o=new IH.TimeoutController(i);n.signal=(0,RH.anySignal)([n.signal,o.signal]);let s=r(...t),a=new Promise((l,f)=>{o.signal.addEventListener("abort",()=>{f(new Yu)})}),c=Date.now(),u=()=>{if(o.signal.aborted)throw new Yu;if(Date.now()-c>i)throw o.abort(),new Yu};return s[Symbol.asyncIterator]?async function*(){let l=s[Symbol.asyncIterator]();try{for(;;){let{value:f,done:h}=await Promise.race([l.next(),a]);if(h)break;u(),yield f}}catch(f){throw u(),f}finally{o.clear(),l.return&&l.return()}}():(async()=>{try{let l=await Promise.race([s,a]);return u(),l}catch(l){throw u(),l}finally{o.clear()}})()}}var yR=C(ee(),1),CH="/ipfs/";function Qu(r){if(r instanceof Uint8Array)try{r=z.decode(r)}catch(i){throw(0,yR.default)(i,"ERR_INVALID_CID")}let e=z.asCID(r);if(e)return{cid:e,path:void 0};r=r.toString(),r.startsWith(CH)&&(r=r.substring(CH.length));let t=r.split("/"),n;try{e=z.parse(t.shift()||"")}catch(i){throw(0,yR.default)(i,"ERR_INVALID_CID")}return t.length&&(n=`/${t.join("/")}`),{cid:e,path:n}}var YEe="ERR_BAD_PATH",W8="This command must be run in online mode. Try running 'ipfs daemon' first.",Ry=new pe("/local/filesroot"),PH=262144;var kH=r=>{if(z.asCID(r))return`/ipfs/${r}`;let t=r.toString();try{return`/ipfs/${z.parse(t)}`}catch{}if(K8(t))return t;throw(0,j8.default)(new Error(`invalid path: ${r}`),YEe)},N1=r=>r instanceof Uint8Array?z.decode(r).toString():(r=r.toString(),r.indexOf("/ipfs/")===0&&(r=r.substring(6)),r.charAt(r.length-1)==="/"&&(r=r.substring(0,r.length-1)),r),Pf=async function(r,e,t,n={}){let{cid:i,path:o}=Qu(t);o&&(n.path=o);let s=i,a=n.path||"";if(a.startsWith("/")&&(a=a.substring(1)),n.path)try{for await(let{value:c,remainderPath:u}of kf(i,n.path,e,r,{signal:n.signal})){if(!z.asCID(c))break;a=u,s=c}}catch(c){throw c.message.startsWith("Object has no property")&&(c.message=`no link named "${a.split("/")[0]}" under ${s}`,c.code="ERR_NO_LINK"),c}return{cid:s,remainderPath:a||""}},wR=r=>{if(r.type!=="file"&&r.type!=="directory"&&r.type!=="raw")throw new Error(`Unknown node type '${r.type}'`);let e={cid:r.cid,path:r.path,name:r.name,size:r.size,type:"file"};return r.type==="directory"&&(e.type="dir"),r.type==="file"&&(e.size=r.unixfs.fileSize()),(r.type==="file"||r.type==="directory")&&(e.mode=r.unixfs.mode,r.unixfs.mtime!==void 0&&(e.mtime=r.unixfs.mtime)),e},NH=$(async(r,e)=>await r),kf=async function*(r,e,t,n,i){let o=async u=>{let l=await t.getCodec(u.code),f=await n.blocks.get(u,i);return l.decode(f)},s=e.split("/").filter(Boolean),a=await o(r),c=r;for(;s.length;){let u=s.shift();if(!u)throw(0,j8.default)(new Error(`Could not resolve path "${e}"`),"ERR_INVALID_PATH");if(r.code===kr&&Array.isArray(a.Links)){let l=a.Links.find(f=>f.Name===u);if(l){yield{value:l.Hash,remainderPath:s.join("/")},a=await o(l.Hash),c=l.Hash;continue}}if(Object.prototype.hasOwnProperty.call(a,u))a=a[u],yield{value:a,remainderPath:s.join("/")};else throw(0,j8.default)(new Error(`no link named "${u}" under ${c}`),"ERR_NO_LINK");z.asCID(a)&&(c=a,a=await o(a))}yield{value:a,remainderPath:""}};var Pi=class{static create({start:e,stop:t}){return new Pi(e,t)}static async start(e,t){let{state:n,activate:i}=e;switch(n.status){case"stopped":try{let o=i(t);e.state={status:"starting",ready:o};let s=await o;return e.state={status:"started",value:s},s}catch(o){throw e.state={status:"stopped"},o}case"starting":throw new _h;case"started":throw new Eh;case"stopping":return await n.ready,await Pi.start(e,t);default:return Pi.panic(e)}}static async stop(e){let{state:t,deactivate:n}=e;switch(t.status){case"stopped":break;case"starting":{try{await t.ready}catch{}return await Pi.stop(e)}case"stopping":return await t.ready;case"started":{n&&await n(t.value),e.state={status:"stopped"};break}default:Pi.panic(t)}}static try({state:e}){switch(e.status){case"started":return e.value;default:return null}}static async use({state:e},t){switch(e.status){case"started":return e.value;case"starting":return await NH(e.ready,t);default:throw new $u}}static panic({state:e}){let t=JSON.stringify({status:e.status});throw RangeError(`Service in invalid state ${t}, should never happen if you see this please report a bug`)}constructor(e,t){this.activate=e,this.deactivate=t,this.state={status:"stopped"}}async use(e){return await Pi.use(this,e)}try(){return Pi.try(this)}};function DH({network:r,preload:e,peerId:t,keychain:n,repo:i,ipns:o,mfsPreload:s,print:a,hashers:c,options:u}){return async()=>{let{libp2p:f}=await Pi.start(r,{peerId:t,repo:i,print:a,hashers:c,options:u});await Promise.all([o.startOnline({keychain:n,libp2p:f,peerId:t,repo:i}),e.start(),s.start()])}}function OH({network:r,preload:e,ipns:t,repo:n,mfsPreload:i}){return async()=>{await Promise.all([e.stop(),t.stop(),i.stop()]),await Pi.stop(r),await n.close()}}var BH=C(Cy(),1),Y8=class{constructor(e){this.lru=(0,BH.default)(e)}get(e){let t=this.lru.get(e);if(t){if(t.expire&&t.expireglobalThis.DOMException===void 0?new _R(r):new DOMException(r),zH=r=>{let e=r.reason===void 0?FH("This operation was aborted."):r.reason;return e instanceof Error?e:FH(e)};function Ih(r,e,t,n){let i,o=new Promise((s,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(zH(c)),c.addEventListener("abort",()=>{a(zH(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{s(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Nf(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{s(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return o.clear=()=>{clearTimeout(i),i=void 0},o}function ER(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Rh=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Xu,vR=class{constructor(){Xu.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Rh(this,Xu,"f")[this.size-1].priority>=t.priority){Rh(this,Xu,"f").push(n);return}let i=ER(Rh(this,Xu,"f"),n,(o,s)=>s.priority-o.priority);Rh(this,Xu,"f").splice(i,0,n)}dequeue(){let e=Rh(this,Xu,"f").shift();return e==null?void 0:e.run}filter(e){return Rh(this,Xu,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Rh(this,Xu,"f").length}};Xu=new WeakMap;var VH=vR;var Wr=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},ke=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},gn,Dy,Oy,Of,rb,Ly,X8,Oa,Ny,Fo,Z8,zo,By,Df,J8,KH,$H,GH,qH,HH,eb,xR,SR,nb,jH,tb,ib=class extends Error{},AR=class extends ky.default{constructor(e){var t,n,i,o;if(super(),gn.add(this),Dy.set(this,void 0),Oy.set(this,void 0),Of.set(this,0),rb.set(this,void 0),Ly.set(this,void 0),X8.set(this,0),Oa.set(this,void 0),Ny.set(this,void 0),Fo.set(this,void 0),Z8.set(this,void 0),zo.set(this,0),By.set(this,void 0),Df.set(this,void 0),J8.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:VH,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);Wr(this,Dy,e.carryoverConcurrencyCount,"f"),Wr(this,Oy,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Wr(this,rb,e.intervalCap,"f"),Wr(this,Ly,e.interval,"f"),Wr(this,Fo,new e.queueClass,"f"),Wr(this,Z8,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Wr(this,J8,e.throwOnTimeout===!0,"f"),Wr(this,Df,e.autoStart===!1,"f")}get concurrency(){return ke(this,By,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);Wr(this,By,e,"f"),ke(this,gn,"m",nb).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:ke(this,J8,"f"),...t},new Promise((n,i)=>{ke(this,Fo,"f").enqueue(async()=>{var o,s,a;Wr(this,zo,(s=ke(this,zo,"f"),s++,s),"f"),Wr(this,Of,(a=ke(this,Of,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new ib("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Ih(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,ke(this,gn,"m",jH).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nf&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{ke(this,gn,"m",GH).call(this)}},t),this.emit("add"),ke(this,gn,"m",eb).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return ke(this,Df,"f")?(Wr(this,Df,!1,"f"),ke(this,gn,"m",nb).call(this),this):this}pause(){Wr(this,Df,!0,"f")}clear(){Wr(this,Fo,new(ke(this,Z8,"f")),"f")}async onEmpty(){ke(this,Fo,"f").size!==0&&await ke(this,gn,"m",tb).call(this,"empty")}async onSizeLessThan(e){ke(this,Fo,"f").sizeke(this,Fo,"f").size{ke(this,gn,"m",qH).call(this)},t),"f"),!0}return!1},eb=function(){if(ke(this,Fo,"f").size===0)return ke(this,Oa,"f")&&clearInterval(ke(this,Oa,"f")),Wr(this,Oa,void 0,"f"),this.emit("empty"),ke(this,zo,"f")===0&&this.emit("idle"),!1;if(!ke(this,Df,"f")){let e=!ke(this,gn,"a",HH);if(ke(this,gn,"a",KH)&&ke(this,gn,"a",$H)){let t=ke(this,Fo,"f").dequeue();return t?(this.emit("active"),t(),e&&ke(this,gn,"m",xR).call(this),!0):!1}}return!1},xR=function(){ke(this,Oy,"f")||ke(this,Oa,"f")!==void 0||(Wr(this,Oa,setInterval(()=>{ke(this,gn,"m",SR).call(this)},ke(this,Ly,"f")),"f"),Wr(this,X8,Date.now()+ke(this,Ly,"f"),"f"))},SR=function(){ke(this,Of,"f")===0&&ke(this,zo,"f")===0&&ke(this,Oa,"f")&&(clearInterval(ke(this,Oa,"f")),Wr(this,Oa,void 0,"f")),Wr(this,Of,ke(this,Dy,"f")?ke(this,zo,"f"):0,"f"),ke(this,gn,"m",nb).call(this)},nb=function(){for(;ke(this,gn,"m",eb).call(this););},jH=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new ib("The task was aborted."))},{once:!0})})},tb=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var qn=AR;var dG=C(O1(),1),OR=new Y8(1e3),x7e=60*1e3,S7e=qn.default?qn.default:qn,A7e=new S7e({concurrency:4}),fG=r=>{if(r.Path)return r.Path;throw new Error(r.Message)};async function hG(r,e){return(async(n,i={})=>{let o=new URLSearchParams(i);o.set("arg",n);let s=o.toString();if(!i.nocache&&OR.has(s)){let c=OR.get(s);return fG(c)}let a=await A7e.add(async()=>{let c=await dG.default.get("https://ipfs.io/api/v0/dns",{searchParams:o}),u=new URL(c.url).search.slice(1),l=await c.json();return OR.set(u,l,x7e),l});return fG(a)})(r,e)}function T7e(r){return r.endsWith(".eth")&&(r=r.replace(/.eth$/,".eth.link")),r}function pG(){return $(async(e,t={recursive:!0})=>{if(typeof e!="string")throw new Error("Invalid arguments, domain must be a string");return e=T7e(e),hG(e,t)})}function mG({network:r}){return()=>{let e=r.try();return e!=null&&!!e.libp2p.isStarted()}}var LR=Symbol.for("@libp2p/peer-id");function Lf(r){return r!=null&&!!r[LR]}var sb=class extends Error{constructor(t="The operation was aborted"){super(t);B(this,"code");B(this,"type");this.code=sb.code,this.type=sb.type}},Ph=sb;B(Ph,"code","ABORT_ERR"),B(Ph,"type","aborted");var J=class extends Error{constructor(t,n,i){super(t);B(this,"code");B(this,"props");this.code=n,this.name=(i==null?void 0:i.name)??"CodeError",this.props=i??{}}};function mt(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;tr.decoder).reduce((r,e)=>r.or(e),Vu.identity.decoder),yG=114,BR=36,MR=37,C7e,Uy=class{constructor(e){B(this,"type");B(this,"multihash");B(this,"privateKey");B(this,"publicKey");B(this,"string");B(this,C7e,!0);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()})`}toString(){return this.string==null&&(this.string=pr.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return z.createV1(yG,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){var t;if(e instanceof Uint8Array)return mt(this.multihash.bytes,e);if(typeof e=="string")return Oe(e).equals(this);if(((t=e==null?void 0:e.multihash)==null?void 0:t.bytes)!=null)return mt(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[(C7e=LR,I7e)](){return`PeerId(${this.toString()})`}},L1=class extends Uy{constructor(t){super({...t,type:"RSA"});B(this,"type","RSA");B(this,"publicKey");this.publicKey=t.publicKey}},B1=class extends Uy{constructor(t){super({...t,type:"Ed25519"});B(this,"type","Ed25519");B(this,"publicKey");this.publicKey=t.multihash.digest}},M1=class extends Uy{constructor(t){super({...t,type:"secp256k1"});B(this,"type","secp256k1");B(this,"publicKey");this.publicKey=t.multihash.digest}};function Oe(r,e){if(e=e??gG,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Ea(pr.decode(`z${r}`));return r.startsWith("12D")?new B1({multihash:t}):r.startsWith("16U")?new M1({multihash:t}):new L1({multihash:t})}return Di(gG.decode(r))}function Di(r){try{let e=Ea(r);if(e.code===Ii.code){if(e.digest.length===BR)return new B1({multihash:e});if(e.digest.length===MR)return new M1({multihash:e})}if(e.code===dt.code)return new L1({multihash:e})}catch{return R7e(z.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function R7e(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==yG)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===dt.code)return new L1({multihash:r.multihash});if(e.code===Ii.code){if(e.digest.length===BR)return new B1({multihash:r.multihash});if(e.digest.length===MR)return new M1({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Hn(r,e){return r.length===BR?new B1({multihash:hc(Ii.code,r),privateKey:e}):r.length===MR?new M1({multihash:hc(Ii.code,r),privateKey:e}):new L1({multihash:await dt.digest(r),publicKey:r,privateKey:e})}function wG({repo:r,codecs:e,bases:t,name:n}){async function i(o,s={}){if(!K8(o))throw new Error("invalid argument "+o);if($8(o))for await(let w of n.resolve(o,s))o=w;let[,a,c,...u]=o.split("/"),l=s.cidBase?await t.getBase(s.cidBase):void 0,f=P7e(c);if(u.length===0){let w=l?l.encoder.encode(f):c;return`/${a}/${w}`}let h=z.decode(f);o=u.join("/");let d=kf(h,o,e,r,s),p=h,g=o;for await(let w of d)z.asCID(w.value)&&(p=w.value,g=w.remainderPath);return`/ipfs/${p.toString(l&&l.encoder)}${g?"/"+g:""}`}return $(i)}function P7e(r){try{return Oe(r).toBytes()}catch{return z.parse(r).bytes}}async function Dr(r){let e;for await(let t of r)e=t;return e}function bG({addAll:r}){return(e,t={})=>{let n,i=z.asCID(e);return i?n=r([{cid:i,...t}],t):n=r([{path:e.toString(),...t}],t),Dr(n)}}var U1=C(ee(),1);function k7e(r){return Symbol.iterator in r}function N7e(r){return Symbol.asyncIterator in r}function _G(r){return z.asCID(r)!=null}async function*Tc(r){if(r==null)throw(0,U1.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT");let e=z.asCID(r);if(e){yield Ji({cid:e});return}if(r instanceof String||typeof r=="string"){yield Ji({path:r});return}if(r.cid!=null||r.path!=null)return yield Ji(r);if(k7e(r)){let t=r[Symbol.iterator](),n=t.next();if(n.done)return t;if(_G(n.value)){yield Ji({cid:n.value});for(let i of t)yield Ji({cid:i});return}if(n.value instanceof String||typeof n.value=="string"){yield Ji({path:n.value});for(let i of t)yield Ji({path:i});return}if(n.value.cid!=null||n.value.path!=null){yield Ji(n.value);for(let i of t)yield Ji(i);return}throw(0,U1.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}if(N7e(r)){let t=r[Symbol.asyncIterator](),n=await t.next();if(n.done)return t;if(_G(n.value)){yield Ji({cid:n.value});for await(let i of t)yield Ji({cid:i});return}if(n.value instanceof String||typeof n.value=="string"){yield Ji({path:n.value});for await(let i of t)yield Ji({path:i});return}if(n.value.cid!=null||n.value.path!=null){yield Ji(n.value);for await(let i of t)yield Ji(i);return}throw(0,U1.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}throw(0,U1.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}function Ji(r){let e=r.cid||`${r.path}`;if(!e)throw(0,U1.default)(new Error("Unexpected input: Please path either a CID or an IPFS path"),"ERR_UNEXPECTED_INPUT");let t={path:e,recursive:r.recursive!==!1};return r.metadata!=null&&(t.metadata=r.metadata),t}var Pt={direct:"direct",recursive:"recursive",indirect:"indirect",all:"all"};function EG({repo:r,codecs:e}){async function*t(n,i={}){let o=async function*(){for await(let{path:c,recursive:u,metadata:l}of Tc(n)){let{cid:f}=await Pf(r,e,c),{reason:h}=await r.pins.isPinnedWithType(f,[Pt.recursive,Pt.direct]);if(h==="recursive"&&!u)throw new Error(`${f} already pinned recursively`);u?await r.pins.pinRecursively(f,{metadata:l}):await r.pins.pinDirectly(f,{metadata:l}),yield f}};if(!!!i.lock){yield*o();return}let a=await r.gcLock.readLock();try{yield*o()}finally{a()}}return $(t)}var UR=C(ee(),1);function Fy(r,e,t){let n={type:r,cid:e};return t&&(n.metadata=t),n}function vG({repo:r,codecs:e}){async function*t(n={}){let i=Pt.all;if(n.type&&(i=n.type,!Object.keys(Pt).includes(i)))throw(0,UR.default)(new Error("Invalid pin type"),"ERR_INVALID_PIN_TYPE");if(n.paths){let o=!1;for await(let{path:s}of Tc(n.paths)){let{cid:a}=await Pf(r,e,s),{reason:c,pinned:u,parent:l,metadata:f}=await r.pins.isPinnedWithType(a,i);if(!u)throw(0,UR.default)(new Error(`path '${s}' is not pinned`),"ERR_NOT_PINNED");switch(c){case Pt.direct:case Pt.recursive:o=!0,yield Fy(c,a,f);break;default:o=!0,yield Fy(`${Pt.indirect} through ${l}`,a,f)}}if(!o)throw new Error("No match found");return}if(i===Pt.recursive||i===Pt.all)for await(let{cid:o,metadata:s}of r.pins.recursiveKeys())yield Fy(Pt.recursive,o,s);if(i===Pt.indirect||i===Pt.all)for await(let o of r.pins.indirectKeys(n))yield Fy(Pt.indirect,o);if(i===Pt.direct||i===Pt.all)for await(let{cid:o,metadata:s}of r.pins.directKeys())yield Fy(Pt.direct,o,s)}return $(t)}function xG({rmAll:r}){async function e(t,n={}){let i=await Dr(r([{path:t,...n}],n));if(!i)throw new Error("CID expected");return i}return e}function SG({repo:r,codecs:e}){async function*t(n,i={}){let o=await r.gcLock.readLock();try{for await(let{path:s,recursive:a}of Tc(n)){let{cid:c}=await Pf(r,e,s),{pinned:u,reason:l}=await r.pins.isPinnedWithType(c,Pt.all);if(!u)throw new Error(`${c} is not pinned`);switch(l){case Pt.recursive:if(!a)throw new Error(`${c} is pinned recursively`);await r.pins.unpin(c),yield c;break;case Pt.direct:await r.pins.unpin(c),yield c;break;default:throw new Error(`${c} is pinned indirectly under ${l}`)}}}finally{o()}}return $(t)}var ab=class{constructor({codecs:e,repo:t}){let n=EG({codecs:e,repo:t});this.addAll=n,this.add=bG({addAll:n});let i=SG({codecs:e,repo:t});this.rmAll=i,this.rm=xG({rmAll:i}),this.ls=vG({codecs:e,repo:t}),this.remote={add:(o,s={})=>Promise.reject(new Error("Not implemented")),ls:async function*(o,s={}){return Promise.reject(new Error("Not implemented"))},rm:(o,s={})=>Promise.reject(new Error("Not implemented")),rmAll:(o,s={})=>Promise.reject(new Error("Not implemented")),service:{add:(o,s)=>Promise.reject(new Error("Not implemented")),rm:(o,s={})=>Promise.reject(new Error("Not implemented")),ls:(o={})=>Promise.reject(new Error("Not implemented"))}}}};var WQ=C(ee(),1);var Vo={};xe(Vo,{abortedError:()=>D7e,dbDeleteFailedError:()=>ub,dbOpenFailedError:()=>cb,dbWriteFailedError:()=>lb,notFoundError:()=>Gn});var F1=C(ee(),1);function cb(r){return r=r||new Error("Cannot open database"),(0,F1.default)(r,"ERR_DB_OPEN_FAILED")}function ub(r){return r=r||new Error("Delete failed"),(0,F1.default)(r,"ERR_DB_DELETE_FAILED")}function lb(r){return r=r||new Error("Write failed"),(0,F1.default)(r,"ERR_DB_WRITE_FAILED")}function Gn(r){return r=r||new Error("Not Found"),(0,F1.default)(r,"ERR_NOT_FOUND")}function D7e(r){return r=r||new Error("Aborted"),(0,F1.default)(r,"ERR_ABORTED")}var Vs=C(ee(),1);function re(r,e="utf8"){let t=I8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var MQ=C(AG(),1);var Zb={};xe(Zb,{generateEphemeralKeyPair:()=>fW,generateKeyPair:()=>Xb,generateKeyPairFromSeed:()=>dSe,importKey:()=>c3,keyStretcher:()=>yW,keysPBM:()=>Q1,marshalPrivateKey:()=>HC,marshalPublicKey:()=>a3,supportedKeys:()=>Uc,unmarshalPrivateKey:()=>Li,unmarshalPublicKey:()=>Bs});var xst=C(Ic(),1),Sst=C(Rb(),1);var Qb=C(at(),1);var RC={};xe(RC,{Ed25519PrivateKey:()=>Vh,Ed25519PublicKey:()=>Xy,generateKeyPair:()=>kxe,generateKeyPairFromSeed:()=>IC,unmarshalEd25519PrivateKey:()=>Cxe,unmarshalEd25519PublicKey:()=>Pxe});var ixe=C(Ju(),1);var oi=BigInt(0),zt=BigInt(1),$f=BigInt(2),oxe=BigInt(8),Uj=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),Lr=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:Uj,n:Uj,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var $j=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Hy=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),_it=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),sxe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),axe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),cxe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),uxe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Bt=class{constructor(e,t,n,i){this.x=e,this.y=t,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof Vr))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(Vr.ZERO)?Bt.ZERO:new Bt(e.x,e.y,zt,ie(e.x*e.y))}static toAffineBatch(e){let t=dxe(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){zj(e);let{x:t,y:n,z:i}=this,{x:o,y:s,z:a}=e,c=ie(t*a),u=ie(o*i),l=ie(n*a),f=ie(s*i);return c===u&&l===f}negate(){return new Bt(ie(-this.x),this.y,this.z,ie(-this.t))}double(){let{x:e,y:t,z:n}=this,{a:i}=Lr,o=ie(e*e),s=ie(t*t),a=ie($f*ie(n*n)),c=ie(i*o),u=e+t,l=ie(ie(u*u)-o-s),f=c+s,h=f-a,d=c-s,p=ie(l*h),g=ie(f*d),w=ie(l*d),_=ie(h*f);return new Bt(p,g,_,w)}add(e){zj(e);let{x:t,y:n,z:i,t:o}=this,{x:s,y:a,z:c,t:u}=e,l=ie((n-t)*(a+s)),f=ie((n+t)*(a-s)),h=ie(f-l);if(h===oi)return this.double();let d=ie(i*$f*u),p=ie(o*$f*c),g=p+d,w=f+l,_=p-d,x=ie(g*h),m=ie(w*_),y=ie(g*_),b=ie(h*w);return new Bt(x,m,b,y)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let t=1+256/e,n=[],i=this,o=i;for(let s=0;s>=f,p>c&&(p-=l,e+=zt);let g=d,w=d+Math.abs(p)-1,_=h%2!==0,x=p<0;p===0?s=s.add(Fj(_,i[g])):o=o.add(Fj(x,i[w]))}return Bt.normalizeZ([o,s])[0]}multiply(e,t){return this.wNAF(Pb(e,Lr.l),t)}multiplyUnsafe(e){let t=Pb(e,Lr.l,!1),n=Bt.BASE,i=Bt.ZERO;if(t===oi)return i;if(this.equals(i)||t===zt)return this;if(this.equals(n))return this.wNAF(t);let o=i,s=this;for(;t>oi;)t&zt&&(o=o.add(s)),s=s.double(),t>>=zt;return o}isSmallOrder(){return this.multiplyUnsafe(Lr.h).equals(Bt.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(Lr.l/$f).double();return Lr.l%$f&&(e=e.add(this)),e.equals(Bt.ZERO)}toAffine(e){let{x:t,y:n,z:i}=this,o=this.equals(Bt.ZERO);e==null&&(e=o?oxe:kb(i));let s=ie(t*e),a=ie(n*e),c=ie(i*e);if(o)return Vr.ZERO;if(c!==zt)throw new Error("invZ was invalid");return new Vr(s,a)}fromRistrettoBytes(){cC()}toRistrettoBytes(){cC()}fromRistrettoHash(){cC()}};Bt.BASE=new Bt(Lr.Gx,Lr.Gy,zt,ie(Lr.Gx*Lr.Gy));Bt.ZERO=new Bt(oi,zt,zt,oi);function Fj(r,e){let t=e.negate();return r?t:e}function zj(r){if(!(r instanceof Bt))throw new TypeError("ExtendedPoint expected")}function aC(r){if(!(r instanceof po))throw new TypeError("RistrettoPoint expected")}function cC(){throw new Error("Legacy method: switch to RistrettoPoint")}var po=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:t}=Lr,n=ie(Hy*e*e),i=ie((n+zt)*cxe),o=BigInt(-1),s=ie((o-t*n)*ie(n+t)),{isValid:a,value:c}=hC(i,s),u=ie(c*e);Kf(u)||(u=ie(-u)),a||(c=u),a||(o=n);let l=ie(o*(n-zt)*uxe-s),f=c*c,h=ie((c+c)*s),d=ie(l*sxe),p=ie(zt-f),g=ie(zt+f);return new Bt(ie(h*g),ie(p*d),ie(d*g),ie(h*p))}static hashToCurve(e){e=qf(e,64);let t=uC(e.slice(0,32)),n=this.calcElligatorRistrettoMap(t),i=uC(e.slice(32,64)),o=this.calcElligatorRistrettoMap(i);return new po(n.add(o))}static fromHex(e){e=qf(e,32);let{a:t,d:n}=Lr,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",o=uC(e);if(!pxe(Gy(o),e)||Kf(o))throw new Error(i);let s=ie(o*o),a=ie(zt+t*s),c=ie(zt-t*s),u=ie(a*a),l=ie(c*c),f=ie(t*n*u-l),{isValid:h,value:d}=Kj(ie(f*l)),p=ie(d*c),g=ie(d*p*f),w=ie((o+o)*p);Kf(w)&&(w=ie(-w));let _=ie(a*g),x=ie(w*_);if(!h||Kf(x)||_===oi)throw new Error(i);return new po(new Bt(w,_,zt,x))}toRawBytes(){let{x:e,y:t,z:n,t:i}=this.ep,o=ie(ie(n+t)*ie(n-t)),s=ie(e*t),a=ie(s*s),{value:c}=Kj(ie(o*a)),u=ie(c*o),l=ie(c*s),f=ie(u*l*i),h;if(Kf(i*f)){let p=ie(t*Hy),g=ie(e*Hy);e=p,t=g,h=ie(u*axe)}else h=l;Kf(e*f)&&(t=ie(-t));let d=ie((n-t)*h);return Kf(d)&&(d=ie(-d)),Gy(d)}toHex(){return jy(this.toRawBytes())}toString(){return this.toHex()}equals(e){aC(e);let t=this.ep,n=e.ep,i=ie(t.x*n.y)===ie(t.y*n.x),o=ie(t.y*n.y)===ie(t.x*n.x);return i||o}add(e){return aC(e),new po(this.ep.add(e.ep))}subtract(e){return aC(e),new po(this.ep.subtract(e.ep))}multiply(e){return new po(this.ep.multiply(e))}multiplyUnsafe(e){return new po(this.ep.multiplyUnsafe(e))}};po.BASE=new po(Bt.BASE);po.ZERO=new po(Bt.ZERO);var fC=new WeakMap,Vr=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,fC.delete(this)}static fromHex(e,t=!0){let{d:n,P:i}=Lr;e=qf(e,32);let o=e.slice();o[31]=e[31]&-129;let s=Wy(o);if(t&&s>=i)throw new Error("Expected 0 < hex < P");if(!t&&s>=$j)throw new Error("Expected 0 < hex < 2**256");let a=ie(s*s),c=ie(a-zt),u=ie(n*a+zt),{isValid:l,value:f}=hC(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let h=(f&zt)===zt;return(e[31]&128)!==0!==h&&(f=ie(-f)),new Vr(f,s)}static async fromPrivateKey(e){return(await Nb(e)).point}toRawBytes(){let e=Gy(this.y);return e[31]|=this.x&zt?128:0,e}toHex(){return jy(this.toRawBytes())}toX25519(){let{y:e}=this,t=ie((zt+e)*kb(zt-e));return Gy(t)}isTorsionFree(){return Bt.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Vr(ie(-this.x),this.y)}add(e){return Bt.fromAffine(this).add(Bt.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Bt.fromAffine(this).multiply(e,this).toAffine()}};Vr.BASE=new Vr(Lr.Gx,Lr.Gy);Vr.ZERO=new Vr(oi,zt);var Uh=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){let t=qf(e,64),n=Vr.fromHex(t.slice(0,32),!1),i=Wy(t.slice(32,64));return new Uh(n,i)}assertValidity(){let{r:e,s:t}=this;if(!(e instanceof Vr))throw new Error("Expected Point instance");return Pb(t,Lr.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Gy(this.s),32),e}toHex(){return jy(this.toRawBytes())}};function Vj(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function jy(r){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t=oi?t:e+t}function kb(r,e=Lr.P){if(r===oi||e<=oi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=ie(r,e),n=e,i=oi,o=zt,s=zt,a=oi;for(;t!==oi;){let u=n/t,l=n%t,f=i-s*u,h=o-a*u;n=t,t=l,i=s,o=a,s=f,a=h}if(n!==zt)throw new Error("invert: does not exist");return ie(i,e)}function dxe(r,e=Lr.P){let t=new Array(r.length),n=r.reduce((o,s,a)=>s===oi?o:(t[a]=o,ie(o*s,e)),zt),i=kb(n,e);return r.reduceRight((o,s,a)=>s===oi?o:(t[a]=ie(o*t[a],e),ie(o*s,e)),i),t}function Oc(r,e){let{P:t}=Lr,n=r;for(;e-- >oi;)n*=n,n%=t;return n}function hxe(r){let{P:e}=Lr,t=BigInt(5),n=BigInt(10),i=BigInt(20),o=BigInt(40),s=BigInt(80),c=r*r%e*r%e,u=Oc(c,$f)*c%e,l=Oc(u,zt)*r%e,f=Oc(l,t)*l%e,h=Oc(f,n)*f%e,d=Oc(h,i)*h%e,p=Oc(d,o)*d%e,g=Oc(p,s)*p%e,w=Oc(g,s)*p%e,_=Oc(w,n)*f%e;return{pow_p_5_8:Oc(_,$f)*r%e,b2:c}}function hC(r,e){let t=ie(e*e*e),n=ie(t*t*e),i=hxe(r*n).pow_p_5_8,o=ie(r*t*i),s=ie(e*o*o),a=o,c=ie(o*Hy),u=s===r,l=s===ie(-r),f=s===ie(-r*Hy);return u&&(o=a),(l||f)&&(o=c),Kf(o)&&(o=ie(-o)),{isValid:u||l,value:o}}function Kj(r){return hC(zt,r)}function Cb(r){return ie(Wy(r),Lr.l)}function pxe(r,e){if(r.length!==e.length)return!1;for(let t=0;t{if(r=qf(r),r.length<40||r.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return ie(Wy(r),Lr.l-zt)+zt},randomBytes:(r=32)=>{if(Vf.web)return Vf.web.getRandomValues(new Uint8Array(r));if(Vf.node){let{randomBytes:e}=Vf.node;return new Uint8Array(e(r).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Lc.randomBytes(32),sha512:async(...r)=>{let e=Vj(...r);if(Vf.web){let t=await Vf.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(t)}else{if(Vf.node)return Uint8Array.from(Vf.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(r=8,e=Vr.BASE){let t=e.equals(Vr.BASE)?e:new Vr(e.x,e.y);return t._setWindowSize(r),t.multiply($f),t},sha512Sync:void 0};Object.defineProperties(Lc,{sha512Sync:{configurable:!1,get(){return lC},set(r){lC||(lC=r)}}});var G1=32,rl=64,Lb=32;async function Gj(){let r=Lc.randomPrivateKey(),e=await H1(r);return{privateKey:Qj(r,e),publicKey:e}}async function jj(r){if(r.length!==Lb)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await H1(e);return{privateKey:Qj(e,t),publicKey:t}}async function Wj(r,e){let t=r.subarray(0,Lb);return Db(e,t)}async function Yj(r,e,t){return Ob(e,t,r)}function Qj(r,e){let t=new Uint8Array(rl);for(let n=0;ni+o.length,0));let t=vf(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return wf(t)}var yn={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var pC={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Bb(r){let e=(r==null?void 0:r.algorithm)??"AES-GCM",t=(r==null?void 0:r.keyLength)??16,n=(r==null?void 0:r.nonceLength)??12,i=(r==null?void 0:r.digest)??"SHA-256",o=(r==null?void 0:r.saltLength)??16,s=(r==null?void 0:r.iterations)??32767,a=yn.get();t*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(o)),p=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:p};typeof h=="string"&&(h=Ie(h));let w;if(h.length===0){w=await a.subtle.importKey("jwk",pC,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},m=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(x,m,{name:e,length:t},!0,["encrypt"])}catch{w=await a.subtle.importKey("jwk",pC,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},m=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(x,m,{name:e,length:t},!0,["encrypt"])}let _=await a.subtle.encrypt(g,w,f);return rt([d,g.iv,new Uint8Array(_)])}async function u(f,h){let d=f.subarray(0,o),p=f.subarray(o,o+n),g=f.subarray(o+n),w={name:e,iv:p};typeof h=="string"&&(h=Ie(h));let _;if(h.length===0)try{let m={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},y=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);_=await a.subtle.deriveKey(m,y,{name:e,length:t},!0,["decrypt"])}catch{_=await a.subtle.importKey("jwk",pC,{name:"AES-GCM"},!0,["decrypt"])}else{let m={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},y=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);_=await a.subtle.deriveKey(m,y,{name:e,length:t},!0,["decrypt"])}let x=await a.subtle.decrypt(w,_,g);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function j1(r,e){let n=await Bb().encrypt(r,e);return fh.encode(n)}var Q1={};xe(Q1,{KeyType:()=>Br,PrivateKey:()=>Fa,PublicKey:()=>Ua});var mC=new Float32Array([-0]),Hf=new Uint8Array(mC.buffer);function Zj(r,e,t){mC[0]=r,e[t]=Hf[0],e[t+1]=Hf[1],e[t+2]=Hf[2],e[t+3]=Hf[3]}function Jj(r,e){return Hf[0]=r[e],Hf[1]=r[e+1],Hf[2]=r[e+2],Hf[3]=r[e+3],mC[0]}var gC=new Float64Array([-0]),Oi=new Uint8Array(gC.buffer);function eW(r,e,t){gC[0]=r,e[t]=Oi[0],e[t+1]=Oi[1],e[t+2]=Oi[2],e[t+3]=Oi[3],e[t+4]=Oi[4],e[t+5]=Oi[5],e[t+6]=Oi[6],e[t+7]=Oi[7]}function tW(r,e){return Oi[0]=r[e],Oi[1]=r[e+1],Oi[2]=r[e+2],Oi[3]=r[e+3],Oi[4]=r[e+4],Oi[5]=r[e+5],Oi[6]=r[e+6],Oi[7]=r[e+7],gC[0]}var Exe=BigInt(Number.MAX_SAFE_INTEGER),vxe=BigInt(Number.MIN_SAFE_INTEGER),Rn=class{constructor(e,t){B(this,"lo");B(this,"hi");this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Fh;if(evxe)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>rW&&(i=0n,++n>rW&&(n=0n))),new Rn(Number(i),Number(n))}static fromNumber(e){if(e===0)return Fh;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Rn(n,i)}static from(e){return typeof e=="number"?Rn.fromNumber(e):typeof e=="bigint"?Rn.fromBigInt(e):typeof e=="string"?Rn.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Rn(e.low>>>0,e.high>>>0):Fh}},Fh=new Rn(0,0);Fh.toBigInt=function(){return 0n};Fh.zzEncode=Fh.zzDecode=function(){return this};Fh.length=function(){return 1};var rW=4294967296n;function nW(r){let e=0,t=0;for(let n=0;n191&&a<224?o[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function yC(r,e,t){let n=t,i,o;for(let s=0;s>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function Ma(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Mb(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var wC=class{constructor(e){B(this,"buf");B(this,"pos");B(this,"len");B(this,"_slice",Uint8Array.prototype.subarray);this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ma(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ma(this,4);return Mb(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ma(this,4);return Mb(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ma(this,4);let e=Jj(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ma(this,4);let e=tW(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Ma(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return iW(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ma(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ma(this);while(this.buf[this.pos++]&128);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(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Rn(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ma(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ma(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ma(this,8);let e=Mb(this.buf,this.pos+=4),t=Mb(this.buf,this.pos+=4);return new Rn(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=MI(this.buf,this.pos);return this.pos+=ti(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 bC(r){return new wC(r instanceof Uint8Array?r:r.subarray())}function Cn(r,e,t){let n=bC(r);return e.decode(n,void 0,t)}function _C(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return Ri(s);i+s>e&&(n=Ri(e),i=0);let a=n.subarray(i,i+=s);return i&7&&(i=(i|7)+1),a}}var zh=class{constructor(e,t,n){B(this,"fn");B(this,"len");B(this,"next");B(this,"val");this.fn=e,this.len=t,this.next=void 0,this.val=n}};function EC(){}var xC=class{constructor(e){B(this,"head");B(this,"tail");B(this,"len");B(this,"next");this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},xxe=_C();function Sxe(r){return globalThis.Buffer!=null?Ri(r):xxe(r)}var Qy=class{constructor(){B(this,"len");B(this,"head");B(this,"tail");B(this,"states");this.len=0,this.head=new zh(EC,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new zh(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new SC((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ub,10,Rn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Rn.fromBigInt(e);return this._push(Ub,t.length(),t)}uint64Number(e){return this._push(BI,ti(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){let t=Rn.fromBigInt(e).zzEncode();return this._push(Ub,t.length(),t)}sint64Number(e){let t=Rn.fromNumber(e).zzEncode();return this._push(Ub,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vC,1,e?1:0)}fixed32(e){return this._push(Yy,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Rn.fromBigInt(e);return this._push(Yy,4,t.lo)._push(Yy,4,t.hi)}fixed64Number(e){let t=Rn.fromNumber(e);return this._push(Yy,4,t.lo)._push(Yy,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(Zj,4,e)}double(e){return this._push(eW,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(vC,1,0):this.uint32(t)._push(Txe,t,e)}string(e){let t=nW(e);return t!==0?this.uint32(t)._push(yC,t,e):this._push(vC,1,0)}fork(){return this.states=new xC(this),this.head=this.tail=new zh(EC,0,0),this.len=0,this}reset(){return this.states!=null?(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 zh(EC,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Sxe(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function vC(r,e,t){e[t]=r&255}function Axe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var SC=class extends zh{constructor(t,n){super(Axe,t,n);B(this,"next");this.next=void 0}};function Ub(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Yy(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Txe(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Qy.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ixe,e,r),this},Qy.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Rxe,e,r),this});function Ixe(r,e,t){e.set(r,t)}function Rxe(r,e,t){r.length<40?yC(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(cr(r),t)}function AC(){return new Qy}function Pn(r,e){let t=AC();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var W1;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(W1||(W1={}));function Fb(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Y1(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return Fb("enum",W1.VARINT,t,n)}function kn(r,e){return Fb("message",W1.LENGTH_DELIMITED,r,e)}var Br;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Br||(Br={}));var TC;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(TC||(TC={}));(function(r){r.codec=()=>Y1(TC)})(Br||(Br={}));var Ua;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Br.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Br.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(Ua||(Ua={}));var Fa;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Br.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Br.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(Fa||(Fa={}));var Xy=class{constructor(e){B(this,"_key");this._key=X1(e,G1)}async verify(e,t){return Yj(this._key,t,e)}marshal(){return this._key}get bytes(){return Ua.encode({Type:Br.Ed25519,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}},Vh=class{constructor(e,t){B(this,"_key");B(this,"_publicKey");this._key=X1(e,rl),this._publicKey=X1(t,G1)}async sign(e){return Wj(this._key,e)}get public(){return new Xy(this._publicKey)}marshal(){return this._key}get bytes(){return Fa.encode({Type:Br.Ed25519,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}async id(){let e=Ii.digest(this.public.bytes);return pr.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return j1(this.bytes,e);throw new J(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Cxe(r){if(r.length>rl){r=X1(r,rl+G1);let n=r.subarray(0,rl),i=r.subarray(rl,r.length);return new Vh(n,i)}r=X1(r,rl);let e=r.subarray(0,rl),t=r.subarray(G1);return new Vh(e,t)}function Pxe(r){return r=X1(r,G1),new Xy(r)}async function kxe(){let{privateKey:r,publicKey:e}=await Gj();return new Vh(r,e)}async function IC(r){let{privateKey:e,publicKey:t}=await jj(r);return new Vh(e,t)}function X1(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new J(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var bot=C(gr(),1),_ot=C(qy(),1),sW=C(at(),1);function za(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=rt([new Uint8Array(e-t.length),t])}return re(t,"base64url")}function Ko(r){let e=zb(r);return new sW.default.jsbn.BigInteger(re(e,"base16"),16)}function zb(r,e){let t=Ie(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=rt([new Uint8Array(e-t.length),t])}return t}var aW={"P-256":256,"P-384":384,"P-521":521},Nxe=Object.keys(aW),CC=Nxe.join(" / ");async function cW(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new J(`Unknown curve: ${r}. Must be ${CC}`,"ERR_INVALID_CURVE");let e=await yn.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(o,s)=>{let a;s!=null?a=await yn.get().subtle.importKey("jwk",Oxe(r,s),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await yn.get().subtle.importKey("jwk",lW(r,o),{name:"ECDH",namedCurve:r},!1,[]),u=await yn.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,aW[r]);return new Uint8Array(u,0,u.byteLength)},n=await yn.get().subtle.exportKey("jwk",e.publicKey);return{key:Dxe(n),genSharedKey:t}}var uW={"P-256":32,"P-384":48,"P-521":66};function Dxe(r){if(r.crv==null||r.x==null||r.y==null)throw new J("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new J(`Unknown curve: ${r.crv}. Must be ${CC}`,"ERR_INVALID_CURVE");let e=uW[r.crv];return rt([Uint8Array.from([4]),zb(r.x,e),zb(r.y,e)],1+e*2)}function lW(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new J(`Unknown curve: ${r}. Must be ${CC}`,"ERR_INVALID_CURVE");let t=uW[r];if(!mt(e.subarray(0,1),Uint8Array.from([4])))throw new J("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:re(e.subarray(1,t+1),"base64url"),y:re(e.subarray(1+t),"base64url"),ext:!0}}var Oxe=(r,e)=>({...lW(r,e.public),d:re(e.private,"base64url")});var fW=cW;async function dW(r,e){let t=fh.decode(r);return Bb().decrypt(t,e)}var hW={SHA1:20,SHA256:32,SHA512:64};var Lxe={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},Bxe=async(r,e)=>{let t=await yn.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function pW(r,e){let t=Lxe[r],n=await yn.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(i){return Bxe(n,i)},length:hW[r]}}var gW={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function yW(r,e,t){let n=gW[r];if(n==null){let x=Object.keys(gW).join(" / ");throw new J(`unknown cipher type '${r}'. Must be ${x}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new J("missing hash type","ERR_MISSING_HASH_TYPE");let i=n.keySize,o=n.ivSize,s=20,a=Ie("key expansion"),c=2*(o+i+s),u=await pW(e,t),l=await u.digest(a),f=[],h=0;for(;hc&&(m=c-h),f.push(x),h+=m,l=await u.digest(l)}let d=c/2,p=rt(f),g=p.subarray(0,d),w=p.subarray(d,c),_=x=>({iv:x.subarray(0,o),cipherKey:x.subarray(o,o+i),macKey:x.subarray(o+i)});return{k1:_(g),k2:_(w)}}var zC={};xe(zC,{RsaPrivateKey:()=>om,RsaPublicKey:()=>i3,fromJwk:()=>sSe,generateKeyPair:()=>aSe,unmarshalRsaPrivateKey:()=>iSe,unmarshalRsaPublicKey:()=>oSe});var n3=C(at(),1);var fst=C(NC(),1);var Uxe=C(Ju(),1);var Vt=BigInt(0),Ur=BigInt(1),jf=BigInt(2),e3=BigInt(3),vW=BigInt(8),nn=Object.freeze({a:Vt,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Ur,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),xW=(r,e)=>(r+e/jf)/e,Vb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(r){let{n:e}=nn,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ur*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,s=BigInt("0x100000000000000000000000000000000"),a=xW(o*r,e),c=xW(-n*r,e),u=Te(r-a*t-c*i,e),l=Te(-a*n-c*o,e),f=u>s,h=l>s;if(f&&(u=e-u),h&&(l=e-l),u>s||l>s)throw new Error("splitScalarEndo: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:h,k2:l}}},Va=32,em=32,Fxe=32,SW=Va+1,AW=2*Va+1;function TW(r){let{a:e,b:t}=nn,n=Te(r*r),i=Te(n*r);return Te(i+e*r+t)}var Kb=nn.a===Vt,Hb=class extends Error{constructor(e){super(e)}};function IW(r){if(!(r instanceof jt))throw new TypeError("JacobianPoint expected")}var jt=class{constructor(e,t,n){this.x=e,this.y=t,this.z=n}static fromAffine(e){if(!(e instanceof Kt))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Kt.ZERO)?jt.ZERO:new jt(e.x,e.y,Ur)}static toAffineBatch(e){let t=qxe(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return jt.toAffineBatch(e).map(jt.fromAffine)}equals(e){IW(e);let{x:t,y:n,z:i}=this,{x:o,y:s,z:a}=e,c=Te(i*i),u=Te(a*a),l=Te(t*u),f=Te(o*c),h=Te(Te(n*a)*u),d=Te(Te(s*i)*c);return l===f&&h===d}negate(){return new jt(this.x,Te(-this.y),this.z)}double(){let{x:e,y:t,z:n}=this,i=Te(e*e),o=Te(t*t),s=Te(o*o),a=e+o,c=Te(jf*(Te(a*a)-i-s)),u=Te(e3*i),l=Te(u*u),f=Te(l-jf*c),h=Te(u*(c-f)-vW*s),d=Te(jf*t*n);return new jt(f,h,d)}add(e){IW(e);let{x:t,y:n,z:i}=this,{x:o,y:s,z:a}=e;if(o===Vt||s===Vt)return this;if(t===Vt||n===Vt)return e;let c=Te(i*i),u=Te(a*a),l=Te(t*u),f=Te(o*c),h=Te(Te(n*a)*u),d=Te(Te(s*i)*c),p=Te(f-l),g=Te(d-h);if(p===Vt)return g===Vt?this.double():jt.ZERO;let w=Te(p*p),_=Te(p*w),x=Te(l*w),m=Te(g*g-_-jf*x),y=Te(g*(x-m)-h*_),b=Te(i*a*p);return new jt(m,y,b)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=jt.ZERO;if(typeof e=="bigint"&&e===Vt)return t;let n=PW(e);if(n===Ur)return this;if(!Kb){let f=t,h=this;for(;n>Vt;)n&Ur&&(f=f.add(h)),h=h.double(),n>>=Ur;return f}let{k1neg:i,k1:o,k2neg:s,k2:a}=Vb.splitScalar(n),c=t,u=t,l=this;for(;o>Vt||a>Vt;)o&Ur&&(c=c.add(l)),a&Ur&&(u=u.add(l)),l=l.double(),o>>=Ur,a>>=Ur;return i&&(c=c.negate()),s&&(u=u.negate()),u=new jt(Te(u.x*Vb.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let t=Kb?128/e+1:256/e+1,n=[],i=this,o=i;for(let s=0;s>=f,p>c&&(p-=l,e+=Ur);let g=d,w=d+Math.abs(p)-1,_=h%2!==0,x=p<0;p===0?s=s.add($b(_,i[g])):o=o.add($b(x,i[w]))}return{p:o,f:s}}multiply(e,t){let n=PW(e),i,o;if(Kb){let{k1neg:s,k1:a,k2neg:c,k2:u}=Vb.splitScalar(n),{p:l,f}=this.wNAF(a,t),{p:h,f:d}=this.wNAF(u,t);l=$b(s,l),h=$b(c,h),h=new jt(Te(h.x*Vb.beta),h.y,h.z),i=l.add(h),o=f.add(d)}else{let{p:s,f:a}=this.wNAF(n,t);i=s,o=a}return jt.normalizeZ([i,o])[0]}toAffine(e){let{x:t,y:n,z:i}=this,o=this.equals(jt.ZERO);e==null&&(e=o?vW:nm(i));let s=e,a=Te(s*s),c=Te(a*s),u=Te(t*a),l=Te(n*c),f=Te(i*s);if(o)return Kt.ZERO;if(f!==Ur)throw new Error("invZ was invalid");return new Kt(u,l)}};jt.BASE=new jt(nn.Gx,nn.Gy,Ur);jt.ZERO=new jt(Vt,Ur,Vt);function $b(r,e){let t=e.negate();return r?t:e}var OC=new WeakMap,Kt=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,OC.delete(this)}hasEvenY(){return this.y%jf===Vt}static fromCompressedHex(e){let t=e.length===32,n=Wf(t?e:e.subarray(1));if(!DC(n))throw new Error("Point is not on curve");let i=TW(n),o=$xe(i),s=(o&Ur)===Ur;t?s&&(o=Te(-o)):(e[0]&1)===1!==s&&(o=Te(-o));let a=new Kt(n,o);return a.assertValidity(),a}static fromUncompressedHex(e){let t=Wf(e.subarray(1,Va+1)),n=Wf(e.subarray(Va+1,Va*2+1)),i=new Kt(t,n);return i.assertValidity(),i}static fromHex(e){let t=rm(e),n=t.length,i=t[0];if(n===Va)return this.fromCompressedHex(t);if(n===SW&&(i===2||i===3))return this.fromCompressedHex(t);if(n===AW&&i===4)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${SW} compressed bytes or ${AW} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return Kt.BASE.multiply(jb(e))}static fromSignature(e,t,n){let{r:i,s:o}=kW(t);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let s=MC(rm(e)),{n:a}=nn,c=n===2||n===3?i+a:i,u=nm(c,a),l=Te(-s*u,a),f=Te(o*u,a),h=n&1?"03":"02",d=Kt.fromHex(h+Z1(c)),p=Kt.BASE.multiplyAndAddUnsafe(d,l,f);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return $h(this.toHex(e))}toHex(e=!1){let t=Z1(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Z1(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:n}=this;if(!DC(t)||!DC(n))throw new Error(e);let i=Te(n*n),o=TW(t);if(Te(i-o)!==Vt)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Kt(this.x,Te(-this.y))}double(){return jt.fromAffine(this).double().toAffine()}add(e){return jt.fromAffine(this).add(jt.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return jt.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,n){let i=jt.fromAffine(this),o=t===Vt||t===Ur||this!==Kt.BASE?i.multiplyUnsafe(t):i.multiply(t),s=jt.fromAffine(e).multiplyUnsafe(n),a=o.add(s);return a.equals(jt.ZERO)?void 0:a.toAffine()}};Kt.BASE=new Kt(nn.Gx,nn.Gy);Kt.ZERO=new Kt(Vt,Vt);function RW(r){return Number.parseInt(r[0],16)>=8?"00"+r:r}function CW(r){if(r.length<2||r[0]!==2)throw new Error(`Invalid signature integer tag: ${tm(r)}`);let e=r[1],t=r.subarray(2,e+2);if(!e||t.length!==e)throw new Error("Invalid signature integer: wrong length");if(t[0]===0&&t[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Wf(t),left:r.subarray(e+2)}}function zxe(r){if(r.length<2||r[0]!=48)throw new Error(`Invalid signature tag: ${tm(r)}`);if(r[1]!==r.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:t}=CW(r.subarray(2)),{data:n,left:i}=CW(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${tm(i)}`);return{r:e,s:n}}var Bc=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!t)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=t?tm(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Bc(Gb(i.slice(0,64)),Gb(i.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if(typeof e!="string"&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=zxe(t?e:$h(e));return new Bc(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!r3(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!r3(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=nn.n>>Ur;return this.s>e}normalizeS(){return this.hasHighS()?new Bc(this.r,Te(-this.s,nn.n)):this}toDERRawBytes(){return $h(this.toDERHex())}toDERHex(){let e=RW(Jy(this.s)),t=RW(Jy(this.r)),n=e.length/2,i=t.length/2,o=Jy(n),s=Jy(i);return`30${Jy(i+n+4)}02${s}${t}02${o}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return $h(this.toCompactHex())}toCompactHex(){return Z1(this.r)+Z1(this.s)}};function Gf(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function tm(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;t0)return BigInt(r);if(typeof r=="bigint"&&r3(r))return r;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Te(r,e=nn.P){let t=r%e;return t>=Vt?t:e+t}function Ls(r,e){let{P:t}=nn,n=r;for(;e-- >Vt;)n*=n,n%=t;return n}function $xe(r){let{P:e}=nn,t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),s=BigInt(44),a=BigInt(88),c=r*r*r%e,u=c*c*r%e,l=Ls(u,e3)*u%e,f=Ls(l,e3)*u%e,h=Ls(f,jf)*c%e,d=Ls(h,n)*h%e,p=Ls(d,i)*d%e,g=Ls(p,s)*p%e,w=Ls(g,a)*g%e,_=Ls(w,s)*p%e,x=Ls(_,e3)*u%e,m=Ls(x,o)*d%e,y=Ls(m,t)*c%e,b=Ls(y,jf);if(b*b%e!==r)throw new Error("Cannot find square root");return b}function nm(r,e=nn.P){if(r===Vt||e<=Vt)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Te(r,e),n=e,i=Vt,o=Ur,s=Ur,a=Vt;for(;t!==Vt;){let u=n/t,l=n%t,f=i-s*u,h=o-a*u;n=t,t=l,i=s,o=a,s=f,a=h}if(n!==Ur)throw new Error("invert: does not exist");return Te(i,e)}function qxe(r,e=nn.P){let t=new Array(r.length),n=r.reduce((o,s,a)=>s===Vt?o:(t[a]=o,Te(o*s,e)),Ur),i=nm(n,e);return r.reduceRight((o,s,a)=>s===Vt?o:(t[a]=Te(o*t[a],e),Te(o*s,e)),i),t}function Hxe(r){let e=r.length*8-em*8,t=Wf(r);return e>0?t>>BigInt(e):t}function MC(r,e=!1){let t=Hxe(r);if(e)return t;let{n}=nn;return t>=n?t-n:t}var J1,t3,BC=class{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||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 ro.hmacSha256(this.k,...e)}hmacSync(...e){return t3(this.k,...e)}checkSync(){if(typeof t3!="function")throw new Hb("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),e.length!==0&&(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),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e0)e=BigInt(r);else if(typeof r=="string"){if(r.length!==2*em)throw new Error("Expected 32 bytes of private key");e=Gb(r)}else if(r instanceof Uint8Array){if(r.length!==em)throw new Error("Expected 32 bytes of private key");e=Wf(r)}else throw new TypeError("Expected valid private key");if(!r3(e))throw new Error("Expected private key: 0 < key < n");return e}function jxe(r){return r instanceof Kt?(r.assertValidity(),r):Kt.fromHex(r)}function kW(r){if(r instanceof Bc)return r.assertValidity(),r;try{return Bc.fromDER(r)}catch{return Bc.fromCompact(r)}}function im(r,e=!1){return Kt.fromPrivateKey(r).toRawBytes(e)}function NW(r){let e=r.length>Va?r.slice(0,Va):r;return Wf(e)}function Wxe(r){let e=NW(r),t=Te(e,nn.n);return DW(t{r=rm(r);let e=em+8;if(r.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let t=Te(Wf(r),nn.n-Ur)+Ur;return LC(t)},randomBytes:(r=32)=>{if($o.web)return $o.web.getRandomValues(new Uint8Array(r));if($o.node){let{randomBytes:e}=$o.node;return Uint8Array.from(e(r))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>ro.hashToPrivateKey(ro.randomBytes(em+8)),precompute(r=8,e=Kt.BASE){let t=e===Kt.BASE?e:new Kt(e.x,e.y);return t._setWindowSize(r),t.multiply(e3),t},sha256:async(...r)=>{if($o.web){let e=await $o.web.subtle.digest("SHA-256",Gf(...r));return new Uint8Array(e)}else if($o.node){let{createHash:e}=$o.node,t=e("sha256");return r.forEach(n=>t.update(n)),Uint8Array.from(t.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(r,...e)=>{if($o.web){let t=await $o.web.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Gf(...e),i=await $o.web.subtle.sign("HMAC",t,n);return new Uint8Array(i)}else if($o.node){let{createHmac:t}=$o.node,n=t("sha256",r);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(r,...e)=>{let t=qb[r];if(t===void 0){let n=await ro.sha256(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Gf(n,n),qb[r]=t}return ro.sha256(t,...e)},taggedHashSync:(r,...e)=>{if(typeof J1!="function")throw new Hb("sha256Sync is undefined, you need to set it");let t=qb[r];if(t===void 0){let n=J1(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Gf(n,n),qb[r]=t}return J1(t,...e)},_JacobianPoint:jt};Object.defineProperties(ro,{sha256Sync:{configurable:!1,get(){return J1},set(r){J1||(J1=r)}},hmacSha256Sync:{configurable:!1,get(){return t3},set(r){t3||(t3=r)}}});function Mc(r){if(isNaN(r)||r<=0)throw new J("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ro.randomBytes(r)}var jot=C(Bh(),1),UC=C(at(),1);function LW(r,e){return e.map(t=>Ko(r[t]))}function BW(r){return UC.default.pki.setRsaPrivateKey(...LW(r,["n","e","d","p","q","dp","dq","qi"]))}function MW(r){return UC.default.pki.setRsaPublicKey(...LW(r,["n","e"]))}var qh={};xe(qh,{jwkToPkcs1:()=>Jxe,jwkToPkix:()=>tSe,pkcs1ToJwk:()=>Zxe,pkixToJwk:()=>eSe});var Qot=C(Ic(),1),Xot=C(Bh(),1);var nl=C(at(),1);function Zxe(r){let e=nl.default.asn1.fromDer(re(r,"ascii")),t=nl.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:za(t.n),e:za(t.e),d:za(t.d),p:za(t.p),q:za(t.q),dp:za(t.dP),dq:za(t.dQ),qi:za(t.qInv),alg:"RS256"}}function Jxe(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new J("JWK was missing components","ERR_INVALID_PARAMETERS");let e=nl.default.pki.privateKeyToAsn1({n:Ko(r.n),e:Ko(r.e),d:Ko(r.d),p:Ko(r.p),q:Ko(r.q),dP:Ko(r.dp),dQ:Ko(r.dq),qInv:Ko(r.qi)});return Ie(nl.default.asn1.toDer(e).getBytes(),"ascii")}function eSe(r){let e=nl.default.asn1.fromDer(re(r,"ascii")),t=nl.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:za(t.n),e:za(t.e)}}function tSe(r){if(r.n==null||r.e==null)throw new J("JWK was missing components","ERR_INVALID_PARAMETERS");let e=nl.default.pki.publicKeyToAsn1({n:Ko(r.n),e:Ko(r.e)});return Ie(nl.default.asn1.toDer(e).getBytes(),"ascii")}async function UW(r){let e=await yn.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await VW(e);return{privateKey:t[0],publicKey:t[1]}}async function FC(r){let t=[await yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await rSe(r)],n=await VW({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function FW(r,e){let t=await yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await yn.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function zW(r,e,t){let n=await yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return yn.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function VW(r){if(r.privateKey==null||r.publicKey==null)throw new J("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([yn.get().subtle.exportKey("jwk",r.privateKey),yn.get().subtle.exportKey("jwk",r.publicKey)])}async function rSe(r){return yn.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function KW(r,e,t,n){let i=e?MW(r):BW(r),o=re(Uint8Array.from(t),"ascii"),s=n(o,i);return Ie(s,"ascii")}function $W(r,e){return KW(r,!0,e,(t,n)=>n.encrypt(t))}function qW(r,e){return KW(r,!1,e,(t,n)=>n.decrypt(t))}var i3=class{constructor(e){B(this,"_key");this._key=e}async verify(e,t){return zW(this._key,t,e)}marshal(){return qh.jwkToPkix(this._key)}get bytes(){return Ua.encode({Type:Br.RSA,Data:this.marshal()}).subarray()}encrypt(e){return $W(this._key,e)}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}},om=class{constructor(e,t){B(this,"_key");B(this,"_publicKey");this._key=e,this._publicKey=t}genSecret(){return Mc(16)}async sign(e){return FW(this._key,e)}get public(){if(this._publicKey==null)throw new J("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new i3(this._publicKey)}decrypt(e){return qW(this._key,e)}marshal(){return qh.jwkToPkcs1(this._key)}get bytes(){return Fa.encode({Type:Br.RSA,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}async id(){let e=await this.public.hash();return re(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new n3.default.util.ByteBuffer(this.marshal()),i=n3.default.asn1.fromDer(n),o=n3.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return n3.default.pki.encryptRsaPrivateKey(o,e,s)}else{if(t==="libp2p-key")return j1(this.bytes,e);throw new J(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function iSe(r){let e=qh.pkcs1ToJwk(r),t=await FC(e);return new om(t.privateKey,t.publicKey)}function oSe(r){let e=qh.pkixToJwk(r);return new i3(e)}async function sSe(r){let e=await FC(r);return new om(e.privateKey,e.publicKey)}async function aSe(r){let e=await UW(r);return new om(e.privateKey,e.publicKey)}var KC={};xe(KC,{Secp256k1PrivateKey:()=>s3,Secp256k1PublicKey:()=>o3,generateKeyPair:()=>fSe,unmarshalSecp256k1PrivateKey:()=>uSe,unmarshalSecp256k1PublicKey:()=>lSe});function HW(){return ro.randomPrivateKey()}async function GW(r,e){let{digest:t}=await dt.digest(e);try{return await Wb(t,r)}catch(n){throw new J(String(n),"ERR_INVALID_INPUT")}}async function jW(r,e,t){try{let{digest:n}=await dt.digest(t);return Yb(e,n,r)}catch(n){throw new J(String(n),"ERR_INVALID_INPUT")}}function WW(r){return Kt.fromHex(r).toRawBytes(!0)}function YW(r){try{im(r,!0)}catch(e){throw new J(String(e),"ERR_INVALID_PRIVATE_KEY")}}function VC(r){try{Kt.fromHex(r)}catch(e){throw new J(String(e),"ERR_INVALID_PUBLIC_KEY")}}function QW(r){try{return im(r,!0)}catch(e){throw new J(String(e),"ERR_INVALID_PRIVATE_KEY")}}var o3=class{constructor(e){B(this,"_key");VC(e),this._key=e}async verify(e,t){return jW(this._key,t,e)}marshal(){return WW(this._key)}get bytes(){return Ua.encode({Type:Br.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}},s3=class{constructor(e,t){B(this,"_key");B(this,"_publicKey");this._key=e,this._publicKey=t??QW(e),YW(this._key),VC(this._publicKey)}async sign(e){return GW(this._key,e)}get public(){return new o3(this._publicKey)}marshal(){return this._key}get bytes(){return Fa.encode({Type:Br.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}async id(){let e=await this.public.hash();return re(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return j1(this.bytes,e);throw new J(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function uSe(r){return new s3(r)}function lSe(r){return new o3(r)}async function fSe(){let r=HW();return new s3(r)}var Uc={rsa:zC,ed25519:RC,secp256k1:KC};function $C(r){let e=Object.keys(Uc).join(" / ");return new J(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function qC(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Uc[r];throw $C(r)}async function Xb(r,e){return qC(r).generateKeyPair(e??2048)}async function dSe(r,e,t){if(r.toLowerCase()!=="ed25519")throw new J("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return IC(e)}function Bs(r){let e=Ua.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Br.RSA:return Uc.rsa.unmarshalRsaPublicKey(t);case Br.Ed25519:return Uc.ed25519.unmarshalEd25519PublicKey(t);case Br.Secp256k1:return Uc.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw $C(e.Type??"RSA")}}function a3(r,e){return e=(e??"rsa").toLowerCase(),qC(e),r.bytes}async function Li(r){let e=Fa.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Br.RSA:return Uc.rsa.unmarshalRsaPrivateKey(t);case Br.Ed25519:return Uc.ed25519.unmarshalEd25519PrivateKey(t);case Br.Secp256k1:return Uc.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw $C(e.Type??"RSA")}}function HC(r,e){return e=(e??"rsa").toLowerCase(),qC(e),r.bytes}async function c3(r,e){try{let i=await dW(r,e);return await Li(i)}catch{}let t=Qb.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new J("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Qb.default.asn1.toDer(Qb.default.pki.privateKeyToAsn1(t));return n=Ie(n.getBytes(),"ascii"),Uc.rsa.unmarshalRsaPrivateKey(n)}var AP=C(ee(),1);var hm=C(ee(),1);var XW="ERR_IPNS_EXPIRED_RECORD",u3="ERR_UNRECOGNIZED_VALIDITY",ZW="ERR_SIGNATURE_CREATION",Yf="ERR_SIGNATURE_VERIFICATION",JW="ERR_UNRECOGNIZED_FORMAT";var GC="ERR_UNDEFINED_PARAMETER",eY="ERR_INVALID_RECORD_DATA",tY="ERR_INVALID_EMBEDDED_KEY",rY="ERR_MISSING_PRIVATE_KEY";var oP=C(XC(),1),xY=C(mY(),1),sP=C(iP(),1),SY=C(vY(),1),AY=C(Gh(),1);function bSe(){AY.default._configure(),oP.default._configure(xY.default),sP.default._configure(SY.default)}bSe();var TY=["uint64","int64","sint64","fixed64","sfixed64"];function _Se(r){for(let e of TY){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function aP(r){return _Se(new oP.default(r))}function ESe(r){for(let e of TY){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function cP(){return ESe(sP.default.create())}function uP(r,e){let t=aP(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function lP(r,e){let t=cP();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var sm;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(sm||(sm={}));function t_(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function fP(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return t_("enum",sm.VARINT,t,n)}function dP(r,e){return t_("message",sm.LENGTH_DELIMITED,r,e)}var mo;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>fP(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=dP((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.value!=null&&(o.uint32(10),o.bytes(i.value)),i.signature!=null&&(o.uint32(18),o.bytes(i.signature)),i.validityType!=null&&(o.uint32(24),r.ValidityType.codec().encode(i.validityType,o)),i.validity!=null&&(o.uint32(34),o.bytes(i.validity)),i.sequence!=null&&(o.uint32(40),o.uint64(i.sequence)),i.ttl!=null&&(o.uint32(48),o.uint64(i.ttl)),i.pubKey!=null&&(o.uint32(58),o.bytes(i.pubKey)),i.signatureV2!=null&&(o.uint32(66),o.bytes(i.signatureV2)),i.data!=null&&(o.uint32(74),o.bytes(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={},a=o==null?i.len:i.pos+o;for(;i.pos>>3){case 1:s.value=i.bytes();break;case 2:s.signature=i.bytes();break;case 3:s.validityType=r.ValidityType.codec().decode(i);break;case 4:s.validity=i.bytes();break;case 5:s.sequence=i.uint64();break;case 6:s.ttl=i.uint64();break;case 7:s.pubKey=i.bytes();break;case 8:s.signatureV2=i.bytes();break;case 9:s.data=i.bytes();break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>lP(i,r.codec()),r.decode=i=>uP(i,r.codec())})(mo||(mo={}));var vSe=["string","number","bigint","symbol"],xSe=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function IY(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(vSe.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(SSe(r))return"Buffer";let t=ASe(r);return t||"Object"}function SSe(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function ASe(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(xSe.includes(e))return e}var Z=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};Z.uint=new Z(0,"uint",!0);Z.negint=new Z(1,"negint",!0);Z.bytes=new Z(2,"bytes",!0);Z.string=new Z(3,"string",!0);Z.array=new Z(4,"array",!1);Z.map=new Z(5,"map",!1);Z.tag=new Z(6,"tag",!1);Z.float=new Z(7,"float",!0);Z.false=new Z(7,"false",!0);Z.true=new Z(7,"true",!0);Z.null=new Z(7,"null",!0);Z.undefined=new Z(7,"undefined",!0);Z.break=new Z(7,"break",!0);var Re=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var am=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",TSe=new TextDecoder,ISe=new TextEncoder;function r_(r){return am&&globalThis.Buffer.isBuffer(r)}function hP(r){return r instanceof Uint8Array?r_(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var kY=am?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):CY(r,e,t):(r,e,t)=>t-e>64?TSe.decode(r.subarray(e,t)):CY(r,e,t),NY=am?r=>r.length>64?globalThis.Buffer.from(r):RY(r):r=>r.length>64?ISe.encode(r):RY(r),zc=r=>Uint8Array.from(r),cm=am?(r,e,t)=>r_(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),DY=am?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),hP(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},OY=am?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function LY(r,e){if(r_(r)&&r_(e))return r.compare(e);for(let t=0;t55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function CY(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return RSe(n)}var PY=4096;function RSe(r){let e=r.length;if(e<=PY)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=cm(n,0,this.cursor)}else t=DY(this.chunks,this.cursor);return e&&this.reset(),t}};var it="CBOR decode error:",pP="CBOR encode error:",h3=[];h3[23]=1;h3[24]=2;h3[25]=3;h3[26]=5;h3[27]=9;function il(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${it} encountered BigInt larger than allowable range`)}}Us.encodedSize=function(e){return wi.encodedSize(e.value)};wi.encodedSize=function(e){return et.value?1:0};function zY(r,e,t,n){return new Re(Z.negint,-1-qo(r,e+1,n),2)}function VY(r,e,t,n){return new Re(Z.negint,-1-Ho(r,e+1,n),3)}function KY(r,e,t,n){return new Re(Z.negint,-1-Go(r,e+1,n),5)}var mP=BigInt(-1),$Y=BigInt(1);function qY(r,e,t,n){let i=jo(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new Re(Z.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${it} integers outside of the safe integer range are not supported`);return new Re(Z.negint,mP-BigInt(i),9)}function n_(r,e){let t=e.value,n=typeof t=="bigint"?t*mP-$Y:t*-1-1;wi(r,e.type.majorEncoded,n)}n_.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*mP-$Y:t*-1-1;return nt.value?-1:0};function p3(r,e,t,n){il(r,e,t+n);let i=cm(r,e+t,e+t+n);return new Re(Z.bytes,i,t+n)}function HY(r,e,t,n){return p3(r,e,1,t)}function GY(r,e,t,n){return p3(r,e,2,qo(r,e+1,n))}function jY(r,e,t,n){return p3(r,e,3,Ho(r,e+1,n))}function WY(r,e,t,n){return p3(r,e,5,Go(r,e+1,n))}function YY(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer bytes lengths not supported`);return p3(r,e,9,i)}function i_(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===Z.string?NY(r.value):r.value),r.encodedBytes}function um(r,e){let t=i_(e);wi(r,e.type.majorEncoded,t.length),r.push(t)}um.encodedSize=function(e){let t=i_(e);return wi.encodedSize(t.length)+t.length};um.compareTokens=function(e,t){return kSe(i_(e),i_(t))};function kSe(r,e){return r.lengthe.length?1:LY(r,e)}function m3(r,e,t,n,i){let o=t+n;il(r,e,o);let s=new Re(Z.string,kY(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=cm(r,e+t,e+o)),s}function QY(r,e,t,n){return m3(r,e,1,t,n)}function XY(r,e,t,n){return m3(r,e,2,qo(r,e+1,n),n)}function ZY(r,e,t,n){return m3(r,e,3,Ho(r,e+1,n),n)}function JY(r,e,t,n){return m3(r,e,5,Go(r,e+1,n),n)}function eQ(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer string lengths not supported`);return m3(r,e,9,i,n)}var tQ=um;function lm(r,e,t,n){return new Re(Z.array,n,t)}function rQ(r,e,t,n){return lm(r,e,1,t)}function nQ(r,e,t,n){return lm(r,e,2,qo(r,e+1,n))}function iQ(r,e,t,n){return lm(r,e,3,Ho(r,e+1,n))}function oQ(r,e,t,n){return lm(r,e,5,Go(r,e+1,n))}function sQ(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer array lengths not supported`);return lm(r,e,9,i)}function aQ(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${it} indefinite length items not allowed`);return lm(r,e,1,1/0)}function o_(r,e){wi(r,Z.array.majorEncoded,e.value)}o_.compareTokens=Us.compareTokens;o_.encodedSize=function(e){return wi.encodedSize(e.value)};function fm(r,e,t,n){return new Re(Z.map,n,t)}function cQ(r,e,t,n){return fm(r,e,1,t)}function uQ(r,e,t,n){return fm(r,e,2,qo(r,e+1,n))}function lQ(r,e,t,n){return fm(r,e,3,Ho(r,e+1,n))}function fQ(r,e,t,n){return fm(r,e,5,Go(r,e+1,n))}function dQ(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer map lengths not supported`);return fm(r,e,9,i)}function hQ(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${it} indefinite length items not allowed`);return fm(r,e,1,1/0)}function s_(r,e){wi(r,Z.map.majorEncoded,e.value)}s_.compareTokens=Us.compareTokens;s_.encodedSize=function(e){return wi.encodedSize(e.value)};function pQ(r,e,t,n){return new Re(Z.tag,t,1)}function mQ(r,e,t,n){return new Re(Z.tag,qo(r,e+1,n),2)}function gQ(r,e,t,n){return new Re(Z.tag,Ho(r,e+1,n),3)}function yQ(r,e,t,n){return new Re(Z.tag,Go(r,e+1,n),5)}function wQ(r,e,t,n){return new Re(Z.tag,jo(r,e+1,n),9)}function a_(r,e){wi(r,Z.tag.majorEncoded,e.value)}a_.compareTokens=Us.compareTokens;a_.encodedSize=function(e){return wi.encodedSize(e.value)};var MSe=20,USe=21,FSe=22,zSe=23;function bQ(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${it} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Re(Z.null,null,1):new Re(Z.undefined,void 0,1)}function _Q(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${it} indefinite length items not allowed`);return new Re(Z.break,void 0,1)}function gP(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${it} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${it} Infinity values are not supported`)}return new Re(Z.float,r,e)}function EQ(r,e,t,n){return gP(yP(r,e+1),3,n)}function vQ(r,e,t,n){return gP(wP(r,e+1),5,n)}function xQ(r,e,t,n){return gP(IQ(r,e+1),9,n)}function c_(r,e,t){let n=e.value;if(n===!1)r.push([Z.float.majorEncoded|MSe]);else if(n===!0)r.push([Z.float.majorEncoded|USe]);else if(n===null)r.push([Z.float.majorEncoded|FSe]);else if(n===void 0)r.push([Z.float.majorEncoded|zSe]);else{let i,o=!1;(!t||t.float64!==!0)&&(AQ(n),i=yP(qa,1),n===i||Number.isNaN(n)?(qa[0]=249,r.push(qa.slice(0,3)),o=!0):(TQ(n),i=wP(qa,1),n===i&&(qa[0]=250,r.push(qa.slice(0,5)),o=!0))),o||(VSe(n),i=IQ(qa,1),qa[0]=251,r.push(qa.slice(0,9)))}}c_.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){AQ(n);let i=yP(qa,1);if(n===i||Number.isNaN(n))return 3;if(TQ(n),i=wP(qa,1),n===i)return 5}return 9};var SQ=new ArrayBuffer(9),Fs=new DataView(SQ,1),qa=new Uint8Array(SQ,0);function AQ(r){if(r===1/0)Fs.setUint16(0,31744,!1);else if(r===-1/0)Fs.setUint16(0,64512,!1);else if(Number.isNaN(r))Fs.setUint16(0,32256,!1);else{Fs.setFloat32(0,r);let e=Fs.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Fs.setUint16(0,31744,!1);else if(t===0)Fs.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Fs.setUint16(0,0):i<-14?Fs.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Fs.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function yP(r,e){if(r.length-e<2)throw new Error(`${it} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function TQ(r){Fs.setFloat32(0,r,!1)}function wP(r,e){if(r.length-e<4)throw new Error(`${it} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function VSe(r){Fs.setFloat64(0,r,!1)}function IQ(r,e){if(r.length-e<8)throw new Error(`${it} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}c_.compareTokens=Us.compareTokens;function tr(r,e,t){throw new Error(`${it} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function u_(r){return()=>{throw new Error(`${it} ${r}`)}}var me=[];for(let r=0;r<=23;r++)me[r]=tr;me[24]=BY;me[25]=MY;me[26]=UY;me[27]=FY;me[28]=tr;me[29]=tr;me[30]=tr;me[31]=tr;for(let r=32;r<=55;r++)me[r]=tr;me[56]=zY;me[57]=VY;me[58]=KY;me[59]=qY;me[60]=tr;me[61]=tr;me[62]=tr;me[63]=tr;for(let r=64;r<=87;r++)me[r]=HY;me[88]=GY;me[89]=jY;me[90]=WY;me[91]=YY;me[92]=tr;me[93]=tr;me[94]=tr;me[95]=u_("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)me[r]=QY;me[120]=XY;me[121]=ZY;me[122]=JY;me[123]=eQ;me[124]=tr;me[125]=tr;me[126]=tr;me[127]=u_("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)me[r]=rQ;me[152]=nQ;me[153]=iQ;me[154]=oQ;me[155]=sQ;me[156]=tr;me[157]=tr;me[158]=tr;me[159]=aQ;for(let r=160;r<=183;r++)me[r]=cQ;me[184]=uQ;me[185]=lQ;me[186]=fQ;me[187]=dQ;me[188]=tr;me[189]=tr;me[190]=tr;me[191]=hQ;for(let r=192;r<=215;r++)me[r]=pQ;me[216]=mQ;me[217]=gQ;me[218]=yQ;me[219]=wQ;me[220]=tr;me[221]=tr;me[222]=tr;me[223]=tr;for(let r=224;r<=243;r++)me[r]=u_("simple values are not supported");me[244]=tr;me[245]=tr;me[246]=tr;me[247]=bQ;me[248]=u_("simple values are not supported");me[249]=EQ;me[250]=vQ;me[251]=xQ;me[252]=tr;me[253]=tr;me[254]=tr;me[255]=_Q;var Ha=[];for(let r=0;r<24;r++)Ha[r]=new Re(Z.uint,r,1);for(let r=-1;r>=-24;r--)Ha[31-r]=new Re(Z.negint,r,1);Ha[64]=new Re(Z.bytes,new Uint8Array(0),1);Ha[96]=new Re(Z.string,"",1);Ha[128]=new Re(Z.array,0,1);Ha[160]=new Re(Z.map,0,1);Ha[244]=new Re(Z.false,!1,1);Ha[245]=new Re(Z.true,!0,1);Ha[246]=new Re(Z.null,null,1);function RQ(r){switch(r.type){case Z.false:return zc([244]);case Z.true:return zc([245]);case Z.null:return zc([246]);case Z.bytes:return r.value.length?void 0:zc([64]);case Z.string:return r.value===""?zc([96]):void 0;case Z.array:return r.value===0?zc([128]):void 0;case Z.map:return r.value===0?zc([160]):void 0;case Z.uint:return r.value<24?zc([Number(r.value)]):void 0;case Z.negint:if(r.value>=-24)return zc([31-Number(r.value)])}}var $Se={float64:!1,mapSorter:GSe,quickEncodeToken:RQ};function qSe(){let r=[];return r[Z.uint.major]=Us,r[Z.negint.major]=n_,r[Z.bytes.major]=um,r[Z.string.major]=tQ,r[Z.array.major]=o_,r[Z.map.major]=s_,r[Z.tag.major]=a_,r[Z.float.major]=c_,r}var CQ=qSe(),bP=new d3,dm=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${pP} object contains circular references`);return new dm(t,e)}},Zf={null:new Re(Z.null,null),undefined:new Re(Z.undefined,void 0),true:new Re(Z.true,!0),false:new Re(Z.false,!1),emptyArray:new Re(Z.array,0),emptyMap:new Re(Z.map,0)},Jf={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Re(Z.float,r):r>=0?new Re(Z.uint,r):new Re(Z.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Re(Z.uint,r):new Re(Z.negint,r)},Uint8Array(r,e,t,n){return new Re(Z.bytes,r)},string(r,e,t,n){return new Re(Z.string,r)},boolean(r,e,t,n){return r?Zf.true:Zf.false},null(r,e,t,n){return Zf.null},undefined(r,e,t,n){return Zf.undefined},ArrayBuffer(r,e,t,n){return new Re(Z.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Re(Z.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Zf.emptyArray,new Re(Z.break)]:Zf.emptyArray;n=dm.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=l_(s,t,n);return t.addBreakTokens?[new Re(Z.array,r.length),i,new Re(Z.break)]:[new Re(Z.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[Zf.emptyMap,new Re(Z.break)]:Zf.emptyMap;n=dm.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[l_(u,t,n),l_(i?r.get(u):r[u],t,n)];return HSe(a,t),t.addBreakTokens?[new Re(Z.map,s),a,new Re(Z.break)]:[new Re(Z.map,s),a]}};Jf.Map=Jf.Object;Jf.Buffer=Jf.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Jf[`${r}Array`]=Jf.DataView;function l_(r,e={},t){let n=IY(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Jf[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=Jf[n];if(!o)throw new Error(`${pP} unsupported type: ${n}`);return o(r,n,e,t)}function HSe(r,e){e.mapSorter&&r.sort(e.mapSorter)}function GSe(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=CQ[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function PQ(r,e,t,n){if(Array.isArray(e))for(let i of e)PQ(r,i,t,n);else t[e.type.major](r,e,n)}function jSe(r,e,t){let n=l_(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new d3(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return hP(a.chunks[0])}}return bP.reset(),PQ(bP,n,e,t),bP.toBytes(!0)}function _P(r,e){return e=Object.assign({},$Se,e),jSe(r,CQ,e)}var WSe={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},EP=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=Ha[e];if(t===void 0){let n=me[e];if(!n)throw new Error(`${it} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},g3=Symbol.for("DONE"),f_=Symbol.for("BREAK");function YSe(r,e,t){let n=[];for(let i=0;i{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw kQ.error(n),(0,hm.default)(n,GC)}let t;if(e.pubKey!=null){try{t=Bs(e.pubKey)}catch(i){throw kQ.error(i),i}if(!(await Hn(e.pubKey)).equals(r))throw(0,hm.default)(new Error("Embedded public key did not match PeerID"),tY)}else r.publicKey!=null&&(t=Bs(r.publicKey));if(t!=null)return t;throw(0,hm.default)(new Error("no public key is available"),GC)},OQ=(r,e,t)=>{let n=Ie(e);return rt([r,t,n])},d_=r=>{let e=Ie("ipns-signature:");return rt([e,r])},xP=r=>mo.encode(r),ol=r=>{let e=mo.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??mo.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}},ed=r=>rt([NQ,r.toBytes()]),SP=r=>Di(r.slice(NQ.length)),LQ=(r,e,t,n,i)=>{let o;if(t===mo.ValidityType.EOL)o=0;else throw(0,hm.default)(new Error("Unknown validity type"),u3);return _P({Value:r,Validity:e,ValidityType:o,Sequence:n,TTL:i})},BQ=r=>{let e=vP(r);if(e.ValidityType===0)e.ValidityType=mo.ValidityType.EOL;else throw(0,hm.default)(new Error("Unknown validity type"),u3);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var UQ=j("ipns"),ZSe=Ii.code,b3="/ipns/",h_=b3.length,FQ=async(r,e,t,n)=>{let i=new MQ.default(Date.now()+Number(n)),o=mo.ValidityType.EOL,[s,a]=n.toString().split("."),c=BigInt(s)*BigInt(1e5)+BigInt(a??"0");return await JSe(r,e,t,o,i,c)};var JSe=async(r,e,t,n,i,o)=>{t=BigInt(t);let s=Ie(i.toString());if(r.privateKey==null)throw(0,AP.default)(new Error("Missing private key"),rY);let a=await Li(r.privateKey),c=await tAe(a,e,n,s),u=LQ(e,s,n,t,o),l=d_(u),f=await a.sign(l),h={value:e,signature:c,validityType:n,validity:s,sequence:t,ttl:o,signatureV2:f,data:u};if(r.publicKey!=null){let d=Ea(r.toBytes());(d.code!==ZSe||!mt(r.publicKey,d.digest))&&(h.pubKey=r.publicKey)}return UQ("ipns entry for %b created",e),h},eAe=r=>uA.encode(r).slice(1),_3=r=>new pe(`/ipns/${eAe(r)}`),tAe=async(r,e,t,n)=>{try{let i=OQ(e,t,n);return await r.sign(i)}catch(i){throw UQ.error("record signature creation failed",i),(0,AP.default)(new Error("record signature creation failed"),ZW)}};var zs=j("ipfs:ipns:publisher"),zQ=Gn().code,VQ=60*60*1e3,Yh=class{constructor(e,t){this._routing=e,this._datastore=t}async publishWithEOL(e,t,n,i){let o=await this._updateOrCreateRecord(e,t,n,i);return this._putRecordToRouting(o,e,i)}publish(e,t,n){return this.publishWithEOL(e,t,VQ,n)}async _putRecordToRouting(e,t,n){if(!Lf(t)){let o="peerId received is not valid";throw zs.error(o),(0,Vs.default)(new Error(o),"ERR_INVALID_PEER_ID")}if(t.publicKey==null)throw(0,Vs.default)(new Error("Public key was missing"),"ERR_MISSING_PUBLIC_KEY");let i=ed(t);return await this._publishEntry(i,e,n),e}async _publishEntry(e,t,n){try{let i=await this._routing.put(e,t,n);return zs(`ipns record for ${re(e,"base32")} was stored in the routing`),i}catch(i){let o=`ipns record for ${re(e,"base32")} could not be stored in the routing - ${i.stack}`;throw zs.error(o),zs.error(i),(0,Vs.default)(new Error(o),"ERR_PUTTING_TO_ROUTING")}}async _getPublished(e,t={}){if(!Lf(e)){let i="peerId received is not valid";throw zs.error(i),(0,Vs.default)(new Error(i),"ERR_INVALID_PEER_ID")}let n=t.checkRouting!==!1;try{let i=await this._datastore.get(_3(e.toBytes()));return this._unmarshalData(i)}catch(i){if(i.code!==zQ){let o=`unexpected error getting the ipns record ${e.toString()} from datastore`;throw zs.error(o),(0,Vs.default)(new Error(o),"ERR_UNEXPECTED_DATASTORE_RESPONSE")}if(!n)throw(0,Vs.default)(i,"ERR_NOT_FOUND_AND_CHECK_ROUTING_NOT_ENABLED");try{let o=ed(e),s=await this._routing.get(o);return this._unmarshalData(s)}catch(o){throw zs.error(o),o}}}_unmarshalData(e){try{return ol(e)}catch(t){throw(0,Vs.default)(t,"ERR_INVALID_RECORD_DATA")}}async _updateOrCreateRecord(e,t,n,i){if(!Lf(e)){let u="peerId received is not valid";throw zs.error(u),(0,Vs.default)(new Error(u),"ERR_INVALID_PEER_ID")}let o={checkRouting:!0},s;try{s=await this._getPublished(e,o)}catch(u){if(u.code!==zQ){let l=`unexpected error when determining the last published IPNS record for ${e.toString()} ${u.stack}`;throw zs.error(l),(0,Vs.default)(new Error(l),"ERR_DETERMINING_PUBLISHED_RECORD")}}let a=0n;s&&s.sequence!==void 0&&(a=mt(s.value,t)?s.sequence:s.sequence+BigInt(1));let c;try{c=await FQ(e,t,a,n)}catch(u){let l=`ipns record for ${t} could not be created`;throw zs.error(u),(0,Vs.default)(new Error(l),"ERR_CREATING_IPNS_RECORD")}try{let u=xP(c);return await this._datastore.put(_3(e.toBytes()),u,i),zs(`ipns record for ${re(t,"base32")} was stored in the datastore`),u}catch{let l=`ipns record for ${t} could not be stored in the datastore`;throw zs.error(l),(0,Vs.default)(new Error(l),"ERR_STORING_IN_DATASTORE")}}};Yh.defaultRecordLifetime=VQ;var Qh=C(ee(),1);var KQ=C(Kn(),1),p_=j("ipfs:ipns:republisher"),$Q=60*1e3,qQ=60*$Q,rAe=4*qQ,nAe=24*qQ,m_=class{constructor(e,t,n,i,o={pass:""}){this._publisher=e,this._datastore=t,this._peerId=n,this._keychain=i,this._options=o,this._republishHandle=null}async start(){if(this._republishHandle)throw(0,Qh.default)(new Error("republisher is already running"),"ERR_REPUBLISH_ALREADY_RUNNING");let e={_task:null,_inflightTask:null,_timeoutId:null,runPeriodically:i=>{e._timeoutId=setTimeout(async()=>{e._timeoutId=null;try{e._inflightTask=e._task(),await e._inflightTask,e._task&&e.runPeriodically(i)}catch(o){p_.error(o)}},i())},cancel:async()=>{e._timeoutId!=null&&clearTimeout(e._timeoutId),e._task=null,await e._inflightTask}},{pass:t}=this._options,n=!0;e._task=async()=>{let i=new KQ.TimeoutController(3e4);try{await this._republishEntries(this._peerId,t,{signal:i.signal})}finally{i.clear()}},e.runPeriodically(()=>n?(n=!1,this._options.initialBroadcastInterval||$Q):this._options.broadcastInterval||rAe),this._republishHandle=e}async stop(){let e=this._republishHandle;if(!e)throw(0,Qh.default)(new Error("republisher is not running"),"ERR_REPUBLISH_NOT_RUNNING");this._republishHandle=null,await e.cancel()}async _republishEntries(e,t,n){try{await this._republishEntry(e,n)}catch{let o="cannot republish entry for the node's private key";p_.error(o);return}if(t)try{let i=await this._keychain.listKeys();for(let o of i){if(o.name==="self")continue;let s=await this._keychain.exportKey(o.name,t),a=await c3(s,t),c=await Hn(a.public.bytes,a.bytes);await this._republishEntry(c,n)}}catch(i){p_.error(i)}}async _republishEntry(e,t){try{let n=await this._getPreviousValue(e);await this._publisher.publishWithEOL(e,n,nAe,t)}catch(n){if(n.code==="ERR_NO_ENTRY_FOUND")return;throw n}}async _getPreviousValue(e){if(!Lf(e))throw(0,Qh.default)(new Error("invalid peer ID"),"ERR_INVALID_PEER_ID");try{let t=await this._datastore.get(_3(e.toBytes()));if(!(t instanceof Uint8Array))throw(0,Qh.default)(new Error("found ipns record that we couldn't process"),"ERR_INVALID_IPNS_RECORD");try{return ol(t).value}catch(n){throw p_.error(n),(0,Qh.default)(new Error("found ipns record that we couldn't convert to a value"),"ERR_INVALID_IPNS_RECORD")}}catch(t){throw t&&t.notFound?(0,Qh.default)(new Error(`no previous entry for record with id: ${e.toString()}`),"ERR_NO_ENTRY_FOUND"):t}}};var mm=C(ee(),1);var Ks=C(ee(),1);var E3=j("ipns:validator"),iAe=async(r,e)=>{let{value:t,validityType:n,validity:i}=e,o,s;if(e.signatureV2!=null&&e.data!=null)s=e.signatureV2,o=d_(e.data),oAe(e);else throw(0,Ks.default)(new Error("missing data or signatureV2"),Yf);let a;try{a=await r.verify(o,s)}catch{a=!1}if(!a)throw E3.error("record signature verification failed"),(0,Ks.default)(new Error("record signature verification failed"),Yf);if(i!=null&&n===mo.ValidityType.EOL){let c;try{c=w3(re(i))}catch{throw E3.error("unrecognized validity format (not an rfc3339 format)"),(0,Ks.default)(new Error("unrecognized validity format (not an rfc3339 format)"),JW)}if(c.getTime(){if(r.data==null)throw(0,Ks.default)(new Error("Record data is missing"),eY);let e=BQ(r.data);if(!mt(e.Value,r.value))throw(0,Ks.default)(new Error('Field "value" did not match between protobuf and CBOR'),Yf);if(!mt(e.Validity,r.validity))throw(0,Ks.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Yf);if(e.ValidityType!==r.validityType)throw(0,Ks.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Yf);if(e.Sequence!==r.sequence)throw(0,Ks.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Yf);if(e.TTL!==r.ttl)throw(0,Ks.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Yf)},pm=async(r,e)=>{let t=SP(r),n=ol(e),i=await DQ(t,n);await iAe(i,n)};var IP=j("ipfs:ipns:resolver"),sAe=Gn().code,HQ=32,g_=class{constructor(e){this._routing=e}async resolve(e,t={}){if(typeof e!="string")throw(0,mm.default)(new Error("invalid name"),"ERR_INVALID_NAME");let n=t.recursive&&t.recursive.toString()==="true",i=e.split("/");if(i.length!==3||i[0]!=="")throw(0,mm.default)(new Error("invalid name"),"ERR_INVALID_NAME");let o=i[2],s=1/0;n&&(s=HQ);let a=await this.resolver(o,s,t);return IP(`${e} was locally resolved correctly`),a}async resolver(e,t,n){if(t===0){let s=`could not resolve name (recursion limit of ${HQ} exceeded)`;throw IP.error(s),(0,mm.default)(new Error(s),"ERR_RESOLVE_RECURSION_LIMIT")}let i=await this._resolveName(e,n),o=i.split("/");return o[1]==="ipfs"||!t?i:this.resolver(o[2],t-1,n)}async _resolveName(e,t){let n=Oe(e),i=ed(n),o;try{o=await this._routing.get(i,t)}catch(s){throw IP.error("could not get record from routing",s),s.code===sAe?(0,mm.default)(new Error(`record requested for ${e} was not found in the network`),"ERR_NO_RECORD_FOUND"):(0,mm.default)(new Error(`unexpected error getting the ipns record ${n.toString()}`),"ERR_UNEXPECTED_ERROR_GETTING_RECORD")}return this._validateRecord(n,o)}async _validateRecord(e,t){await pm(rt([Ie("/ipns/"),e.toBytes()]),t);let n=ol(t);return re(n.value)}};var GQ=C(Cy(),1),y_=class{constructor(e){this.lru=(0,GQ.default)(e)}get(e){let t=this.lru.get(e);if(t){if(t.expire&&t.expireasync function*(){yield*(await Wo(r)).sort(e)}();async function on(r){for await(let e of r);}async function*Yt(r,e){for await(let t of r)await e(t)&&(yield t)}async function*Ga(r,e){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}var go=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,t,n){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(let{key:n,value:i}of e)await this.put(n,i,t),yield{key:n,value:i}}async*getMany(e,t={}){for await(let n of e)yield this.get(n,t)}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await on(this.putMany(e,n)),e=[],await on(this.deleteMany(t,n)),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 n=this._all(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.key.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>w_(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=e.offset)}return e.limit!=null&&(n=Ga(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>w_(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=e.offset)}return e.limit!=null&&(n=Ga(n,e.limit)),n}};var Vc=C($s(),1);Vc.default.formatters.b=r=>r==null?"undefined":tt.baseEncode(r);Vc.default.formatters.t=r=>r==null?"undefined":Ot.baseEncode(r);Vc.default.formatters.m=r=>r==null?"undefined":wh.baseEncode(r);Vc.default.formatters.p=r=>r==null?"undefined":r.toString();Vc.default.formatters.c=r=>r==null?"undefined":r.toString();Vc.default.formatters.k=r=>r==null?"undefined":r.toString();function ue(r){return Object.assign((0,Vc.default)(r),{error:(0,Vc.default)(`${r}:error`),trace:(0,Vc.default)(`${r}:trace`)})}var E_=class{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 this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},bm=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new E_(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return(e==null?void 0:e.byteLength)!=null?e.byteLength:1}push(e){if((e==null?void 0:e.value)!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new E_(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return(e==null?void 0:e.value)!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function jn(r={}){return bAe(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function bAe(r,e){e=e??{};let t=e.onEnd,n=new bm,i,o,s,a=async()=>n.isEmpty()?s?{done:!0}:await new Promise((g,w)=>{o=_=>{o=null,n.push(_);try{g(r(n))}catch(x){w(x)}return i}}):r(n),c=g=>o!=null?o(g):(n.push(g),i),u=g=>(n=new bm,o!=null?o({error:g}):(n.push({error:g}),i)),l=g=>{if(s)return i;if((e==null?void 0:e.objectMode)!==!0&&(g==null?void 0:g.byteLength)==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:g})},f=g=>s?i:(s=!0,g!=null?u(g):c({done:!0})),h=()=>(n=new bm,f(),{done:!0}),d=g=>(f(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:d,push:l,end:f,get readableLength(){return n.size}},t==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(g){return p.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return p.end(g),t!=null&&(t(g),t=void 0),i},get readableLength(){return p.readableLength}},i}var _Ae=ue("datastore:core:tiered"),S3=class extends go{constructor(e){super(),this.stores=e.slice()}async open(){try{await Promise.all(this.stores.map(e=>e.open()))}catch(e){throw cb(e)}}async put(e,t,n){try{await Promise.all(this.stores.map(i=>i.put(e,t,n)))}catch(i){throw lb(i)}}async get(e,t){for(let n of this.stores)try{let i=await n.get(e,t);if(i)return i}catch(i){_Ae.error(i)}throw Gn()}async has(e,t){for(let n of this.stores)if(await n.has(e,t))return!0;return!1}async delete(e,t){try{await Promise.all(this.stores.map(n=>n.delete(e,t)))}catch(n){throw ub(n)}}async*putMany(e,t={}){let n,i=this.stores.map(o=>{let s=jn({objectMode:!0});return on(o.putMany(s,t)).catch(a=>{n=a}),s});try{for await(let o of e){if(n)throw n;i.forEach(s=>s.push(o)),yield o}}finally{i.forEach(o=>o.end())}}async*deleteMany(e,t={}){let n,i=this.stores.map(o=>{let s=jn({objectMode:!0});return on(o.deleteMany(s,t)).catch(a=>{n=a}),s});try{for await(let o of e){if(n)throw n;i.forEach(s=>s.push(o)),yield o}}finally{i.forEach(o=>o.end())}}async close(){await Promise.all(this.stores.map(e=>e.close()))}batch(){let e=this.stores.map(t=>t.batch());return{put:(t,n)=>{e.forEach(i=>i.put(t,n))},delete:t=>{e.forEach(n=>n.delete(t))},commit:async t=>{for(let n of e)await n.commit(t)}}}query(e,t){return this.stores[this.stores.length-1].query(e,t)}queryKeys(e,t){return this.stores[this.stores.length-1].queryKeys(e,t)}};var R3=C(v_(),1);var x_=(r,e)=>{let t=e.map((n,i)=>({entry:mo.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let o=n.entry.sequence??0n,s=i.entry.sequence??0n;if(o>s)return-1;if(ol.getTime()?-1:u.getTime()({key:new pe(e),value:t}))}async*_allKeys(){yield*Object.entries(this.data).map(([e])=>new pe(e))}};async function*Bi(r,e){for await(let t of r)yield e(t)}async function*Qo(...r){let e=jn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var xAe=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},tX=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),PP=r=>r!=null&&typeof r.sink=="function"&&tX(r.source),SAe=r=>e=>{let t=r.sink(e);if(t.then!=null){let n=jn({objectMode:!0});return t.then(()=>{n.end()},o=>{n.end(o)}),Qo(n,async function*(){yield*r.source,n.end()}())}return r.source};function Ne(r,...e){if(PP(r)){let n=r;r=()=>n.source}else if(tX(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&PP(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n-1)return this._getLocal(e,t);try{await this._pubsub.subscribe(n)}catch{let s=`cannot subscribe topic ${n}`;throw bi.error(s),new We(s,"ERR_SUBSCRIBING_TOPIC")}return bi(`subscribed values for key ${n}`),this._getLocal(e)}unsubscribe(e){let t=T3(e);return this._pubsub.unsubscribe(t)}async _getLocal(e,t){let n=new pe("/"+kP(e),!1),i;try{i=await this._datastore.get(n,t)}catch(o){if(o.code!=="ERR_NOT_FOUND"){let a=`unexpected error getting the ipns record for ${n.toString()}`;throw bi.error(a),new We(a,"ERR_UNEXPECTED_ERROR_GETTING_RECORD")}let s=`local record requested was not found for ${n.toString()}`;throw bi.error(s),new We(s,"ERR_NOT_FOUND")}if(!(i instanceof Uint8Array)){let o="found record that we couldn't convert to a value";throw bi.error(o),new We(o,"ERR_INVALID_RECORD_RECEIVED")}return i}async _onMessage(e){let t=e.detail;if(t.type!=="signed"){bi.error("unsigned message received, this module can only work with signed messages");return}let{data:n,from:i,topic:o}=t,s;try{s=nX(o)}catch(a){bi.error(a);return}if(bi(`message received for topic ${o}`),this._peerId.equals(i)){bi("message discarded as it is from the same peer");return}if(this._handleSubscriptionKeyFn){let a;try{a=await this._handleSubscriptionKeyFn(s)}catch{bi.error("message discarded by the subscriptionKeyFn");return}s=a}try{await this._storeIfSubscriptionIsBetter(s,n)}catch(a){bi.error(a)}}async _storeIfSubscriptionIsBetter(e,t,n){let i=!1;try{i=await this._isBetter(e,t)}catch(o){if(o.code!=="ERR_NOT_VALID_RECORD")throw o}i&&await this._storeRecord(e,t,n)}async _validateRecord(e,t){return this._validator(e,t)}async _selectRecord(e,t){return await this._selector(e,t)===0}async _isBetter(e,t){try{await this._validateRecord(e,t)}catch{let s="record received through pubsub is not valid";throw bi.error(s),new We(s,"ERR_NOT_VALID_RECORD")}let n=new pe(e),i;try{i=await this._getLocal(n.uint8Array())}catch{return!0}return rr(i,t)?!1:this._selectRecord(e,[i,t])}async _storeRecord(e,t,n){let i=new pe("/"+kP(e),!1);await this._datastore.put(i,t,n),bi(`record for ${T3(e)} was stored in the datastore`)}};var NP=C(ee(),1);var T_=j("ipfs:ipns:pubsub"),Zh=class{constructor(e,t,n){this._subscriptions={},this._handleSubscriptionKey=this._handleSubscriptionKey.bind(this),this._pubsubDs=new A_(e,t,n,pm,x_,this._handleSubscriptionKey)}async put(e,t,n){try{await this._pubsubDs.put(e,t,n)}catch(i){throw T_.error(i),i}}async get(e,t){let n,i;try{n=await this._pubsubDs.get(e,t)}catch(s){i=s}let o=e.slice(0,h_);if(re(o)===b3){let s=pr.encode(e).substring(1),a=pr.encode(e.slice(h_)).substring(1);this._subscriptions[s]=a,T_(`subscribed to pubsub topic ${s}, id ${a}`)}if(i)throw i;return n}_handleSubscriptionKey(e){e instanceof Uint8Array&&(e=re(e,"base58btc"));let t=this._subscriptions[e];if(!t)throw(0,NP.default)(new Error(`key ${e} does not correspond to a subscription`),"ERR_INVALID_KEY");try{return ed(Oe(t))}catch(n){throw T_.error(n),n}}getSubscriptions(){return Object.values(this._subscriptions).filter(Boolean).map(t=>`${b3}${t}`)}async cancel(e){if(typeof e!="string")throw(0,NP.default)(new Error("invalid subscription name"),"ERR_INVALID_SUBSCRIPTION_NAME");e.startsWith(b3)&&(e=e.substring(h_));let t=Object.keys(this._subscriptions).find(i=>this._subscriptions[i]===e);if(!t)return{canceled:!1};let n=Ie(t);return this._pubsubDs.unsubscribe(n),delete this._subscriptions[t],T_(`unsubscribed pubsub ${t}: ${e}`),{canceled:!0}}};var I3;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.key!=null&&t.key.byteLength>0&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&t.value.byteLength>0&&(n.uint32(18),n.bytes(t.value)),t.timeReceived!=null&&t.timeReceived!==""&&(n.uint32(42),n.string(t.timeReceived)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={key:new Uint8Array(0),value:new Uint8Array(0),timeReceived:""},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.bytes();break;case 2:i.value=t.bytes();break;case 5:i.timeReceived=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(I3||(I3={}));function iX(r){let e=r.getUTCFullYear(),t=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),i=String(r.getUTCHours()).padStart(2,"0"),o=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${i}:${o}:${s}.${c}Z`}function oX(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,o=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),u=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,o,s,a,c,u))}var Yr=class{constructor(e,t,n){B(this,"key");B(this,"value");B(this,"timeReceived");if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return I3.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:iX(this.timeReceived)}}static deserialize(e){let t=I3.decode(e);return new Yr(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=oX(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new Yr(e.key,e.value,t)}};var _m=C(ee(),1);var DP=j("ipfs:ipns:offline-datastore"),Em=class{constructor(e){this._datastore=e,this.stores=[]}async put(e,t,n){if(!(e instanceof Uint8Array))throw(0,_m.default)(new Error("Offline datastore key must be a Uint8Array"),"ERR_INVALID_KEY");if(!(t instanceof Uint8Array))throw(0,_m.default)(new Error("Offline datastore value must be a Uint8Array"),"ERR_INVALID_VALUE");let i;try{i=this._routingKey(e)}catch(s){throw DP.error(s),(0,_m.default)(new Error("Not possible to generate the routing key"),"ERR_GENERATING_ROUTING_KEY")}let o=new Yr(e,t,new Date);await this._datastore.put(i,o.serialize(),n)}async get(e,t){if(!(e instanceof Uint8Array))throw(0,_m.default)(new Error("Offline datastore key must be a Uint8Array"),"ERR_INVALID_KEY");let n;try{n=this._routingKey(e)}catch(s){throw DP.error(s),(0,_m.default)(new Error("Not possible to generate the routing key"),"ERR_GENERATING_ROUTING_KEY")}let i=await this._datastore.get(n,t),o;try{o=Yr.deserialize(i)}catch(s){throw DP.error(s),s}return o.value}_routingKey(e){return new pe("/dht/record/"+re(e,"base32"),!1)}};async function sl(r){for await(let e of r);}var TAe=j("ipfs:ipns:dht-datastore"),I_=class{constructor(e){this._dht=e}async put(e,t,n){try{await sl(this._dht.put(e,t,n))}catch(i){throw TAe.error(i),i}}async get(e,t){for await(let n of this._dht.get(e,t))if(n.name==="VALUE")return n.value;throw Gn()}};function sX({libp2p:r,repo:e,peerId:t,options:n}){let i=[],o;if((0,R3.default)(n,"EXPERIMENTAL.ipnsPubsub",!1)&&(o=new Zh(r.pubsub,e.datastore,t),i.push(o)),(0,R3.default)(n,"offline",!1)!==!0&&["dht","dhtclient","dhtserver"].includes((0,R3.default)(n,"config.Routing.Type","none"))&&i.push(new I_(r.dht)),(0,R3.default)(n,"offline",!1)||i.length===0){let s=new Em(e.datastore);i.push(s)}return new S3(i)}var IAe=j("ipfs:components:ipns"),R_=class{constructor(e={pass:""}){this.options=e,this.offline=null,this.online=null}getIPNS(){let e=this.online||this.offline;if(e)return e;throw new Ku}get routing(){return this.getIPNS().routing}startOffline({repo:e,peerId:t,keychain:n}){if(this.offline!=null)throw new ka;IAe("initializing IPNS keyspace (offline)");let i=new Em(e.datastore),o=new x3(i,e.datastore,t,n,this.options);this.offline=o}async startOnline({libp2p:e,repo:t,peerId:n,keychain:i}){if(this.online!=null)throw new ka;let o=sX({libp2p:e,repo:t,peerId:n,options:this.options}),s=new x3(o,t.datastore,n,i,this.options);await s.republisher.start(),this.online=s}async stop(){let e=this.online;e&&(await e.republisher.stop(),this.online=null)}publish(e,t,n,i){return this.getIPNS().publish(e,t,n,i)}resolve(e,t){return this.getIPNS().resolve(e,t)}initializeKeyspace(e,t,n){return this.getIPNS().initializeKeyspace(e,t,n)}};var LP=C(ee(),1);async function aX({ipns:r,repo:e,codecs:t},n,i){if($8(n))return r.resolve(n);let{cid:o,path:s}=Qu(n);await sl(kf(o,s||"",t,e,i))}var OP=j("ipfs:name:publish");function cX({ipns:r,repo:e,codecs:t,peerId:n,isOnline:i,keychain:o}){let s=async c=>{let u;if(c==="self"&&n.privateKey!=null)u=await Li(n.privateKey);else try{let l=await o.exportKey(c,"temp");u=await c3(l,"temp")}catch(l){throw OP.error(l),(0,LP.default)(l,"ERR_CANNOT_GET_KEY")}return Hn(u.public.bytes,u.bytes)};async function a(c,u={}){let l=u.resolve!==!1,f=u.lifetime||"24h",h=u.key||"self";if(!i())throw(0,LP.default)(new Error(W8),"OFFLINE_ERROR");try{c=kH(c)}catch(_){throw OP.error(_),_}let d=0;try{d=Cf(f)||0,d=parseFloat(d.toFixed(6))}catch(_){throw OP.error(_),_}let p=await Promise.all([s(h),l?aX({ipns:r,repo:e,codecs:t},c):Promise.resolve()]),g=Ie(c),w=await r.publish(p[0],g,d,u);return{name:w.name,value:re(w.value)}}return $(a)}var C_=C(ee(),1);var dX=C(lX(),1);var CAe=et.bind({ignoreUndefined:!0}),PAe=j("ipfs:name:resolve"),fX=(r,e)=>e.length>0?r+"/"+e.join("/"):r;function hX({dns:r,ipns:e,isOnline:t,options:{offline:n}}){async function*i(o,s={}){if(s=CAe({nocache:!1,recursive:!0},s),n&&s&&s.nocache)throw(0,C_.default)(new Error("cannot specify both offline and nocache"),"ERR_NOCACHE_AND_OFFLINE");if(!t()&&!n)throw(0,C_.default)(new Error(W8),"OFFLINE_ERROR");let a=o.toString();a.startsWith("/ipns/")||(a=`/ipns/${a}`);let[c,u,...l]=a.slice(1).split("/");try{if(u.substring(0,1)==="1"){let h=Oe(u),d=Ea(h.toBytes());u=z.createV1(114,d).toString(w1)}else{let h=z.parse(u);h.version===1&&(u=h.toString(w1))}}catch(h){if((0,dX.default)(u)){yield fX(await r(u,s),l);return}throw PAe.error(h),(0,C_.default)(new Error("Invalid IPNS name"),"ERR_IPNS_INVALID_NAME")}let f=await e.resolve(`/${c}/${u}`,s);yield fX(f instanceof Uint8Array?re(f):f,l)}return $(i)}var BP=C(ee(),1);function vm(r,e){if(!r||!(e&&e.ipnsPubsub))throw(0,BP.default)(new Error("IPNS pubsub subsystem is not enabled"),"ERR_IPNS_PUBSUB_NOT_ENABLED");if(r.routing instanceof Zh)return r.routing;let t=(r.routing.stores||[]).find(n=>n instanceof Zh);if(!t)throw(0,BP.default)(new Error("IPNS pubsub datastore not found"),"ERR_PUBSUB_DATASTORE_NOT_FOUND");return t}function pX({ipns:r,options:e}){let t=e.EXPERIMENTAL;async function n(i,o={}){return vm(r,t).cancel(i,o)}return $(n)}function mX({ipns:r,options:e}){let t=e.EXPERIMENTAL;async function n(i={}){try{return{enabled:!!vm(r,t)}}catch{return{enabled:!1}}}return $(n)}function gX({ipns:r,options:e}){let t=e.EXPERIMENTAL;async function n(i={}){return vm(r,t).getSubscriptions(i)}return $(n)}var P_=class{constructor({ipns:e,options:t}){this.cancel=pX({ipns:e,options:t}),this.state=mX({ipns:e,options:t}),this.subs=gX({ipns:e,options:t})}};var k_=class{constructor({dns:e,ipns:t,repo:n,codecs:i,peerId:o,isOnline:s,keychain:a,options:c}){this.publish=cX({ipns:t,repo:n,codecs:i,peerId:o,isOnline:s,keychain:a}),this.resolve=hX({dns:e,ipns:t,isOnline:s,options:c}),this.pubsub=new P_({ipns:t,options:c})}};var yX=C(Kn(),1),wX=C(Da(),1),kAe=Gn().code,MP={default:"",edges:" -> "};function bX({repo:r,codecs:e,resolve:t,preload:n}){async function*i(o,s={}){if(s.maxDepth===0)return;if(s.edges&&s.format&&s.format!==MP.default)throw new Error("Cannot set edges to true and also specify format");if(s.format=s.edges?MP.edges:s.format,typeof s.maxDepth!="number"&&(s.maxDepth=s.recursive?1/0:1),s.timeout){let l=[new yX.TimeoutController(s.timeout).signal];s.signal&&l.push(s.signal),s.signal=(0,wX.anySignal)(l)}let c=(Array.isArray(o)?o:[o]).map(u=>NAe(n,u,s));for(let u of c)try{yield*DAe(t,r,e,u,s)}catch(l){yield{ref:"",err:l.message}}}return i}function NAe(r,e,t){let{cid:n,path:i}=Qu(e);return t.preload!==!1&&r(n),`/ipfs/${n}${i||""}`}async function*DAe(r,e,t,n,i){let o=await r(n,i),{cid:s}=Qu(o),a=i.maxDepth!=null?i.maxDepth:1/0,c=i.unique||!1;for await(let u of LAe(e,t,s,a,c,i))u.parent&&(u.isDuplicate||(yield{ref:OAe(u.parent.cid,u.node.cid,u.node.name,i.format)}))}function OAe(r,e,t="",n=MP.default){let i=n.replace(//g,r.toString());return i=i.replace(//g,e.toString()),i=i.replace(//g,t),i}async function*LAe(r,e,t,n,i,o){let s=new Set;async function*a(c,u){let l=u+1;if(!(l>n))try{for await(let f of BAe(r,e,c.cid,o))yield{parent:c,node:f,isDuplicate:i&&s.has(f.cid.toString())},i&&s.add(f.cid.toString()),yield*a(f,l)}catch(f){throw f.code===kAe&&(f.message=`Could not find object with CID: ${c.cid}`),f}}yield*a({cid:t},0)}async function*BAe(r,e,t,n){let i=await r.blocks.get(t,n),s=(await e.getCodec(t.code)).decode(i),a=t.code===kr,c=[];for(let[u,l]of UP(s,c)){if(a){let f=u.match(/^Links\/(\d+)\/Hash$/);if(f){let h=Number(f[1]);if(ho[1].cid)}return $(e)}function vX({network:r}){async function e(t,n={}){let{bitswap:i}=await r.use(n),o=i.wantlistForPeer(t);return Array.from(o).map(s=>s[1].cid)}return $(e)}function xX({network:r}){async function e(t,n={}){let{bitswap:i}=await r.use(n);return Array.isArray(t)||(t=[t]),i.unwant(t)}return $(e)}function N_({network:r}){async function e(t={}){let n=(await r.use(t)).bitswap,i=n.stat().snapshot;return{provideBufLen:parseInt(i.providesBufferLength.toString()),blocksReceived:BigInt(i.blocksReceived.toString()),wantlist:Array.from(n.getWantlist()).map(o=>o[1].cid),peers:n.peers(),dupBlksReceived:BigInt(i.dupBlksReceived.toString()),dupDataReceived:BigInt(i.dupDataReceived.toString()),dataReceived:BigInt(i.dataReceived.toString()),blocksSent:BigInt(i.blocksSent.toString()),dataSent:BigInt(i.dataSent.toString())}}return $(e)}var D_=class{constructor({network:e}){this.wantlist=EX({network:e}),this.wantlistForPeer=vX({network:e}),this.unwant=xX({network:e}),this.stat=N_({network:e})}};var MAe=Me("dns4"),UAe=Me("dns6"),FAe=Me("dnsaddr"),Jh=_i(Me("dns"),FAe,MAe,UAe),O_=_i(Me("ip4"),Me("ip6")),xm=_i(ut(O_,Me("tcp")),ut(Jh,Me("tcp"))),VP=ut(O_,Me("udp")),zAe=ut(VP,Me("utp")),VAe=ut(VP,Me("quic")),P3=_i(ut(xm,Me("ws")),ut(Jh,Me("ws"))),k3=_i(ut(xm,Me("wss")),ut(Jh,Me("wss")),ut(xm,Me("tls"),Me("ws")),ut(Jh,Me("tls"),Me("ws"))),FP=_i(ut(xm,Me("http")),ut(O_,Me("http")),ut(Jh,Me("http"))),zP=_i(ut(xm,Me("https")),ut(O_,Me("https")),ut(Jh,Me("https"))),SX=ut(VP,Me("webrtc"),Me("certhash")),TX=_i(ut(SX,Me("p2p")),SX),IX=_i(ut(P3,Me("p2p-webrtc-star"),Me("p2p")),ut(k3,Me("p2p-webrtc-star"),Me("p2p")),ut(P3,Me("p2p-webrtc-star")),ut(k3,Me("p2p-webrtc-star"))),vdt=_i(ut(P3,Me("p2p-websocket-star"),Me("p2p")),ut(k3,Me("p2p-websocket-star"),Me("p2p")),ut(P3,Me("p2p-websocket-star")),ut(k3,Me("p2p-websocket-star"))),RX=_i(ut(FP,Me("p2p-webrtc-direct"),Me("p2p")),ut(zP,Me("p2p-webrtc-direct"),Me("p2p")),ut(FP,Me("p2p-webrtc-direct")),ut(zP,Me("p2p-webrtc-direct"))),N3=_i(P3,k3,FP,zP,IX,RX,xm,zAe,VAe,Jh,TX),xdt=_i(ut(N3,Me("p2p-stardust"),Me("p2p")),ut(N3,Me("p2p-stardust"))),td=_i(ut(N3,Me("p2p")),IX,RX,TX,Me("p2p")),AX=_i(ut(td,Me("p2p-circuit"),td),ut(td,Me("p2p-circuit")),ut(Me("p2p-circuit"),td),ut(N3,Me("p2p-circuit")),ut(Me("p2p-circuit"),N3),Me("p2p-circuit")),CX=()=>_i(ut(AX,CX),AX),C3=CX(),KAe=_i(ut(C3,td,C3),ut(td,C3),ut(C3,td),C3,td),PX=KAe;function kX(r){function e(t){let n;try{n=Xi(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function ut(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:kX(e),partialMatch:e}}function _i(...r){function e(n){let i=null;return r.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:kX(e),partialMatch:e}}function Me(r){let e=r;function t(i){let o;try{o=Xi(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}function L_(r){try{return PX.matches(r)}catch{return!1}}function NX({repo:r}){async function e(t,n={}){if(!L_(t))throw new Error(`${t} is not a valid Multiaddr`);let i=await r.config.getAll(n),o=i.Bootstrap||[];return o.push(t.toString()),i.Bootstrap=Array.from(new Set(o)).sort((s,a)=>s.localeCompare(a)),await r.config.replace(i),{Peers:[t]}}return $(e)}var DX=O8,$Ae=L8,KP=function(r){let e=0;if(r=r.toString().trim(),DX(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if($Ae(r)){let t=r.split(":",8),n;for(n=0;n0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},OX=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let o=0;o{let e=GAe(...r);$P[e.code]=e,D3[e.name]=e});function GAe(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function Fr(r){if(typeof r=="number"){if($P[r]!=null)return $P[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(D3[r]!=null)return D3[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Kc=C(Xo(),1);function WX(r,e){switch(Fr(r).code){case 4:case 41:return aTe(e);case 42:return GX(e);case 6:case 273:case 33:case 132:return QX(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return GX(e);case 421:return fTe(e);case 444:return jX(e);case 445:return jX(e);case 466:return lTe(e);default:return re(e,"base16")}}function YX(r,e){switch(Fr(r).code){case 4:return qX(e);case 41:return qX(e);case 42:return HX(e);case 6:case 273:case 33:case 132:return jP(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return HX(e);case 421:return cTe(e);case 444:return dTe(e);case 445:return hTe(e);case 466:return uTe(e);default:return Ie(e,"base16")}}var GP=Object.values(Vu).map(r=>r.decoder),sTe=function(){let r=GP[0].or(GP[1]);return GP.slice(2).forEach(e=>r=r.or(e)),r}();function qX(r){if(!xc(r))throw new Error("invalid ip address");return KP(r)}function aTe(r){let e=OX(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!xc(e))throw new Error("invalid ip address");return e}function jP(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function QX(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function HX(r){let e=Ie(r),t=Uint8Array.from(Kc.default.encode(e.length));return rt([t,e],t.length+e.length)}function GX(r){let e=Kc.default.decode(r);if(r=r.slice(Kc.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return re(r)}function cTe(r){let e;r[0]==="Q"||r[0]==="1"?e=Ea(pr.decode(`z${r}`)).bytes:e=z.parse(r).multihash.bytes;let t=Uint8Array.from(Kc.default.encode(e.length));return rt([t,e],t.length+e.length)}function uTe(r){let e=sTe.decode(r),t=Uint8Array.from(Kc.default.encode(e.length));return rt([t,e],t.length+e.length)}function lTe(r){let e=Kc.default.decode(r),t=r.slice(Kc.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+re(t,"base64url")}function fTe(r){let e=Kc.default.decode(r),t=r.slice(Kc.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return re(t,"base58btc")}function dTe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=va.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=jP(n);return rt([t,i],t.length+i.length)}function hTe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=va.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=jP(n);return rt([t,i],t.length+i.length)}function jX(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=re(e,"base32"),i=QX(t);return`${n}:${i}`}var Sm=C(Xo(),1);function pTe(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n=t.length)throw ZX("invalid address: "+r);if(o.path===!0){e.push([i,ZP(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function mTe(r){let e=[];return r.map(t=>{let n=U_(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),ZP(e.join("/"))}function gTe(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=U_(e);return e.length>1?[t.code,YX(t.code,e[1])]:[t.code]})}function WP(r){return r.map(e=>{let t=U_(e);return e[1]!=null?[t.code,WX(t.code,e[1])]:[t.code]})}function YP(r){return M_(rt(r.map(e=>{let t=U_(e),n=Uint8Array.from(Sm.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=rt([n,e[1]])),n})))}function QP(r,e){return r.size>0?r.size/8:r.size===0?0:Sm.default.decode(e)+(Sm.default.decode.bytes??0)}function B_(r){let e=[],t=0;for(;tr.length)throw ZX("Invalid address Uint8Array: "+re(r,"base16"));e.push([n,a])}return e}function XP(r){let e=B_(r),t=WP(e);return mTe(t)}function yTe(r){r=ZP(r);let e=pTe(r),t=gTe(e);return YP(t)}function XX(r){return yTe(r)}function M_(r){let e=wTe(r);if(e!=null)throw e;return Uint8Array.from(r)}function wTe(r){try{B_(r)}catch(e){return e}}function ZP(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function ZX(r){return new Error("Error parsing address: "+r)}function U_(r){return Fr(r[0])}var ek=C(Xo(),1);var eZ=C(ee(),1);var Am=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},JP=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},O3,L3,B3,JX,_Te=Symbol.for("nodejs.util.inspect.custom"),ETe=[Fr("dns").code,Fr("dns4").code,Fr("dns6").code,Fr("dnsaddr").code],vTe=new Map,tZ=Symbol.for("@multiformats/js-multiaddr/multiaddr");function F_(r){return!!(r!=null&&r[tZ])}var al=class{constructor(e){if(O3.set(this,void 0),L3.set(this,void 0),B3.set(this,void 0),this[JX]=!0,e==null&&(e=""),e instanceof Uint8Array)this.bytes=M_(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=XX(e)}else if(F_(e))this.bytes=M_(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return Am(this,O3,"f")==null&&JP(this,O3,XP(this.bytes),"f"),Am(this,O3,"f")}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="",s=Fr("tcp"),a=Fr("udp"),c=Fr("ip4"),u=Fr("ip6"),l=Fr("dns6"),f=Fr("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(o=`%${p??""}`),ETe.includes(d)&&(t=s.name,i=443,n=`${p??""}${o}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=Fr(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=Fr(d).name,n=`${p??""}${o}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},Fr(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;ne.name)}tuples(){return Am(this,L3,"f")==null&&JP(this,L3,B_(this.bytes),"f"),Am(this,L3,"f")}stringTuples(){return Am(this,B3,"f")==null&&JP(this,B3,WP(this.tuples()),"f"),Am(this,B3,"f")}encapsulate(e){return e=new al(e),new al(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new al(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new al(YP(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===D3.ipfs.code).pop();if((t==null?void 0:t[1])!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?re(pr.decode(`z${n}`),"base58btc"):re(z.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){let e=null;try{e=this.stringTuples().filter(t=>Fr(t[0]).path===!0)[0][1],e==null&&(e=null)}catch{e=null}return e}equals(e){return mt(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=vTe.get(t.name);if(n==null)throw(0,eZ.default)(new Error(`no available resolver for ${t.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new al(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")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){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[(O3=new WeakMap,L3=new WeakMap,B3=new WeakMap,JX=tZ,_Te)](){return`Multiaddr(${XP(this.bytes)})`}};function yt(r){return new al(r)}function rZ({repo:r}){async function e(t={}){let n=await r.config.getAll(t),i=n.Bootstrap||[];return n.Bootstrap=[],await r.config.replace(n),{Peers:i.map(o=>yt(o))}}return $(e)}function nZ({repo:r}){async function e(t={}){return{Peers:(await r.config.get("Bootstrap",t)||[]).map(i=>yt(i))}}return $(e)}var cl=()=>({Addresses:{Swarm:[],Announce:[],NoAnnounce:[],API:"",Gateway:"",RPC:"",Delegates:["/dns4/node0.delegate.ipfs.io/tcp/443/https","/dns4/node1.delegate.ipfs.io/tcp/443/https","/dns4/node2.delegate.ipfs.io/tcp/443/https","/dns4/node3.delegate.ipfs.io/tcp/443/https"]},Discovery:{MDNS:{Enabled:!1,Interval:10},webRTCStar:{Enabled:!0}},Bootstrap:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dns4/node0.preload.ipfs.io/tcp/443/wss/p2p/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic","/dns4/node1.preload.ipfs.io/tcp/443/wss/p2p/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6","/dns4/node2.preload.ipfs.io/tcp/443/wss/p2p/QmV7gnbW5VTcJ3oyM2Xk1rdFBJ3kTkvxc87UFGsun29STS","/dns4/node3.preload.ipfs.io/tcp/443/wss/p2p/QmY7JB6MQXhxHvq7dBDh4HpbH29v4yE9JRadAVpndvzySN"],Pubsub:{Enabled:!0},Swarm:{ConnMgr:{LowWater:5,HighWater:20},DisableNatPortMap:!0},Routing:{Type:"dhtclient"}});function iZ({repo:r}){async function e(t={}){let n=await r.config.getAll(t);return n.Bootstrap=cl().Bootstrap,await r.config.replace(n),{Peers:cl().Bootstrap.map(i=>yt(i))}}return $(e)}function oZ({repo:r}){async function e(t,n={}){if(!L_(t))throw new Error(`${t} is not a valid Multiaddr`);let i=await r.config.getAll(n);return i.Bootstrap=(i.Bootstrap||[]).filter(o=>o.toString()!==t.toString()),await r.config.replace(i),{Peers:[t]}}return $(e)}var z_=class{constructor({repo:e}){this.add=NX({repo:e}),this.list=nZ({repo:e}),this.rm=oZ({repo:e}),this.clear=rZ({repo:e}),this.reset=iZ({repo:e})}};function sZ({preload:r,repo:e}){async function t(n,i={}){return i.preload!==!1&&r(n),e.blocks.get(n,i)}return $(t)}function aZ({codecs:r,hashers:e,repo:t,preload:n}){async function i(o,s={}){let a=s.pin?await t.gcLock.readLock():null;try{let c=s.version!=null?s.version:0,u=s.format||(c===0?"dag-pb":"raw"),f=await(await e.getHasher(s.mhtype||"sha2-256")).digest(o),h=await r.getCodec(u),d=z.create(c,h.code,f);return await t.blocks.put(d,o,{signal:s.signal}),s.preload!==!1&&n(d),s.pin===!0&&await t.pins.pinRecursively(d,{signal:s.signal}),d}finally{a&&a()}}return $(i)}var cZ=C(ee(),1);function Qt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var V_=globalThis.CustomEvent??Event;async function*ep(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,o=[],s=Qt(),a=Qt(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(s=Qt(),await s.promise),l)break;let g={done:!1};o.push(g),p().then(w=>{g.done=!0,g.ok=!0,g.value=w,i.dispatchEvent(new V_("task-complete"))},w=>{g.done=!0,g.err=w,i.dispatchEvent(new V_("task-complete"))})}c=!0,i.dispatchEvent(new V_("task-complete"))}catch(p){u=p,i.dispatchEvent(new V_("task-complete"))}});function f(){var p;return n?(p=o[0])==null?void 0:p.done:!!o.find(g=>g.done)}function*h(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}function*d(){for(;f();)for(let p=0;pMi(o,s=>async()=>{s=K_(s);let a={cid:s};try{if(!await r.blocks.has(s))throw(0,cZ.default)(new Error("block not found"),"ERR_BLOCK_NOT_FOUND");await r.blocks.delete(s)}catch(c){n.force||(c.message=`cannot remove ${s}: ${c.message}`,a.error=c)}return a}),o=>ep(o,{concurrency:xTe}),o=>M3(o,()=>!n.quiet))}finally{i()}}return $(e)}function lZ({repo:r,preload:e}){async function t(n,i={}){n=K_(n),i.preload!==!1&&e(n);let o=await r.blocks.get(n);return{cid:n,size:o.length}}return $(t)}var $_=class{constructor({codecs:e,hashers:t,preload:n,repo:i}){this.get=sZ({preload:n,repo:i}),this.put=aZ({codecs:e,hashers:t,preload:n,repo:i}),this.rm=uZ({repo:i}),this.stat=lZ({preload:n,repo:i})}};var fZ=C(ee(),1);async function*yo(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}function tk(r){return typeof r.stream=="function"?yo(r.stream()):yo(new Response(r).body)}function ja(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}async function tp(r){let e=[];for await(let t of r)e.push(t);return e}function qs(r){return ArrayBuffer.isView(r)||r instanceof ArrayBuffer}function ul(r){return r.constructor&&(r.constructor.name==="Blob"||r.constructor.name==="File")&&typeof r.stream=="function"}function U3(r){return typeof r=="object"&&(r.path||r.content)}var ll=r=>r&&typeof r.getReader=="function";async function*q_(r){yield r}async function H_(r){if(qs(r))return q_(rk(r));if(typeof r=="string"||r instanceof String)return q_(rk(r.toString()));if(ul(r))return tk(r);if(ll(r)&&(r=yo(r)),Symbol.iterator in r||Symbol.asyncIterator in r){let e=ja(r),{value:t,done:n}=await e.peek();if(n)return q_(new Uint8Array(0));if(e.push(t),Number.isInteger(t))return q_(Uint8Array.from(await tp(e)));if(qs(t)||typeof t=="string"||t instanceof String)return Mi(e,rk)}throw(0,fZ.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT")}function rk(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):Ie(r.toString())}var j_=C(ee(),1);async function*dZ(r,e){if(r==null)throw(0,j_.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT");if(typeof r=="string"||r instanceof String){yield G_(r.toString(),e);return}if(qs(r)||ul(r)){yield G_(r,e);return}if(ll(r)&&(r=yo(r)),Symbol.iterator in r||Symbol.asyncIterator in r){let t=ja(r),{value:n,done:i}=await t.peek();if(i){yield{content:[]};return}if(t.push(n),Number.isInteger(n)||qs(n)||typeof n=="string"||n instanceof String){yield G_(t,e);return}throw(0,j_.default)(new Error("Unexpected input: multiple items passed - if you are using ipfs.add, please use ipfs.addAll instead"),"ERR_UNEXPECTED_INPUT")}if(U3(r)){yield G_(r,e);return}throw(0,j_.default)(new Error('Unexpected input: cannot convert "'+typeof r+'" into ImportCandidate'),"ERR_UNEXPECTED_INPUT")}async function G_(r,e){let{path:t,mode:n,mtime:i,content:o}=r,s={path:t||"",mode:Bu(n),mtime:af(i)};return o?s.content=await e(o):t||(s.content=await e(r)),s}function W_(r){return dZ(r,H_)}function hZ({addAll:r}){async function e(t,n={}){let i=await Dr(r(W_(t),n));if(i==null)throw Error("Failed to add a file, if you see this please report a bug");return i}return e}async function*rp(r,e=1){let t=[];e<1&&(e=1);for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}async function*F3(r,e=1){for await(let t of rp(r,e)){let n=t.map(async i=>await i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;i>8;return new Uint8Array(e)}var Ipt=gh({name:"murmur3-32",code:35,encode:r=>STe(Q_.default.x86.hash32(r))}),V3=gh({name:"murmur3-128",code:34,encode:r=>G0.fromHex(Q_.default.x64.hash128(r))}),Rpt=gh({name:"murmur3-x64-64",code:34,encode:r=>G0.fromHex(Q_.default.x64.hash128(r)).subarray(0,8)});async function ATe(r){return(await V3.encode(r)).slice(0,8).reverse()}var TTe={chunker:"fixed",strategy:"balanced",rawLeaves:!1,onlyHash:!1,reduceSingleLeafToSelf:!0,hasher:dt,leafType:"file",cidVersion:0,progress:()=>()=>{},shardSplitThreshold:1e3,fileImportConcurrency:50,blockWriteConcurrency:10,minChunkSize:262144,maxChunkSize:262144,avgChunkSize:262144,window:16,polynomial:0x3df305dfb2a804,maxChildrenPerNode:174,layerRepeat:4,wrapWithDirectory:!1,recursive:!1,hidden:!1,timeout:void 0,hamtHashFn:ATe,hamtHashCode:34,hamtBucketBits:8},gZ=(r={})=>et.bind({ignoreUndefined:!0})(TTe,r);var ITe=async(r,e,t)=>{t.codec||(t.codec=sr),t.hasher||(t.hasher=dt),t.cidVersion===void 0&&(t.cidVersion=1),t.codec===sr&&t.hasher!==dt&&(t.cidVersion=1);let n=await t.hasher.digest(r),i=z.create(t.cidVersion,t.codec.code,n);return t.onlyHash||await e.put(i,r,{signal:t.signal}),i},Wa=ITe;var RTe=async(r,e,t)=>{let n=new st({type:"directory",mtime:r.mtime,mode:r.mode}),i=pt(Xn({Data:n.marshal()})),o=await Wa(i,e,t),s=r.path;return{cid:o,path:s,unixfs:n,size:i.length}},yZ=RTe;var xZ=C(ee(),1);async function CTe(r,e){return e(await tp(r))}var wZ=CTe;function PTe(r,e,t){return bZ(r,e,t)}async function bZ(r,e,t){let n=[];for await(let i of rp(r,t.maxChildrenPerNode))n.push(await e(i));return n.length>1?bZ(n,e,t):n[0]}var _Z=PTe;async function kTe(r,e,t){let n=new ik(t.layerRepeat),i=0,o=1,s=n;for await(let a of rp(r,t.maxChildrenPerNode))s.isFull()&&(s!==n&&n.addChild(await s.reduce(e)),i&&i%t.layerRepeat===0&&o++,s=new X_(o,t.layerRepeat,i),i++),s.append(a);return s&&s!==n&&n.addChild(await s.reduce(e)),n.reduce(e)}var EZ=kTe,X_=class{constructor(e,t,n=0){this.maxDepth=e,this.layerRepeat=t,this.currentDepth=1,this.iteration=n,this.root=this.node=this.parent={children:[],depth:this.currentDepth,maxDepth:e,maxChildren:(this.maxDepth-this.currentDepth)*this.layerRepeat}}isFull(){if(!this.root.data)return!1;if(this.currentDepthi.data).map(i=>this._reduce(i,t)))),t((e.data||[]).concat(n))}_findParent(e,t){let n=e.parent;if(!(!n||n.depth===0))return n.children.length===n.maxChildren||!n.maxChildren?this._findParent(n,t):n}},ik=class extends X_{constructor(e){super(0,e),this.root.depth=0,this.currentDepth=1}addChild(e){this.root.children.push(e)}reduce(e){return e((this.root.data||[]).concat(this.root.children))}};async function*NTe(r,e,t){for await(let n of r.content)yield async()=>{t.progress(n.length,r.path);let i,o={codec:sr,cidVersion:t.cidVersion,hasher:t.hasher,onlyHash:t.onlyHash};return t.rawLeaves?(o.codec=yf,o.cidVersion=1):(i=new st({type:t.leafType,data:n}),n=pt({Data:i.marshal(),Links:[]})),{cid:await Wa(n,e,o),unixfs:i,size:n.length}}}var vZ=NTe;var DTe={flat:wZ,balanced:_Z,trickle:EZ};async function*OTe(r,e,t){let n=-1,i,o;typeof t.bufferImporter=="function"?o=t.bufferImporter:o=vZ;for await(let s of F3(o(r,e,t),t.blockWriteConcurrency)){if(n++,n===0){i=s;continue}else n===1&&i&&(yield i,i=null);yield s}i&&(i.single=!0,yield i)}var LTe=(r,e,t)=>{async function n(i){if(i.length===1&&i[0].single&&t.reduceSingleLeafToSelf){let l=i[0];if(r.mtime!==void 0||r.mode!==void 0){let f=await e.get(l.cid);l.unixfs=new st({type:"file",mtime:r.mtime,mode:r.mode,data:f}),f=pt(Xn({Data:l.unixfs.marshal()})),l.cid=await Wa(f,e,{...t,codec:sr,hasher:t.hasher,cidVersion:t.cidVersion}),l.size=f.length}return{cid:l.cid,path:r.path,unixfs:l.unixfs,size:l.size}}let o=new st({type:"file",mtime:r.mtime,mode:r.mode}),s=i.filter(l=>l.cid.code===gf&&l.size||l.unixfs&&!l.unixfs.data&&l.unixfs.fileSize()?!0:!!(l.unixfs&&l.unixfs.data&&l.unixfs.data.length)).map(l=>l.cid.code===gf?(o.addBlockSize(l.size),{Name:"",Tsize:l.size,Hash:l.cid}):(!l.unixfs||!l.unixfs.data?o.addBlockSize(l.unixfs&&l.unixfs.fileSize()||0):o.addBlockSize(l.unixfs.data.length),{Name:"",Tsize:l.size,Hash:l.cid})),a={Data:o.marshal(),Links:s},c=pt(Xn(a));return{cid:await Wa(c,e,t),path:r.path,unixfs:o,size:c.length+a.Links.reduce((l,f)=>l+f.Tsize,0)}}return n};function BTe(r,e,t){let n=DTe[t.strategy];if(!n)throw(0,xZ.default)(new Error(`Unknown importer build strategy name: ${t.strategy}`),"ERR_BAD_STRATEGY");return n(OTe(r,e,t),LTe(r,e,t),t)}var SZ=BTe;var fk=C(ee(),1);var TZ=Symbol.for("@achingbrain/uint8arraylist");function AZ(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e0&&this.appendAll(e)}*[(MTe=TZ,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if($c(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if($c(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=AZ(this.bufs,e);return t.buf[t.index]}set(e,t){let n=AZ(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return yi(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:yi(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new vt;return o.length=i,o.bufs=[...n],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(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],i=0;for(let o=0;o=c)continue;let u=e>=a&&ea&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!$c(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=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),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ri(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=Hu(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=Hu(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=Hu(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ri(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=Hu(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=Hu(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=Hu(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=Hu(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=Hu(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof vt)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;ti+o.byteLength,0)),n.length=t,n}};var zZ=C(FZ(),1),uk=C(ee(),1);async function*$Te(r,e){let t,n,i;if(e.minChunkSize&&e.maxChunkSize&&e.avgChunkSize)i=e.avgChunkSize,t=e.minChunkSize,n=e.maxChunkSize;else if(e.avgChunkSize)i=e.avgChunkSize,t=i/3,n=i+i/2;else throw(0,uk.default)(new Error("please specify an average chunk size"),"ERR_INVALID_AVG_CHUNK_SIZE");if(t<16)throw(0,uk.default)(new Error("rabin min must be greater than 16"),"ERR_INVALID_MIN_CHUNK_SIZE");n=o;)if(yield t.slice(0,o),i=!0,o===t.length)t=new vt,n=0;else{let a=new vt;a.append(t.sublist(o)),t=a,n-=o}(!i||n)&&(yield t.subarray(0,n))}var KZ=HTe;var lk=C(ee(),1);async function*GTe(r){for await(let e of r){if(e.length===void 0)throw(0,lk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT");if(typeof e=="string"||e instanceof String)yield Ie(e.toString());else if(Array.isArray(e))yield Uint8Array.from(e);else if(e instanceof Uint8Array)yield e;else throw(0,lk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}}var $Z=GTe;function jTe(r){return Symbol.iterator in r}function WTe(r){return Symbol.asyncIterator in r}function YTe(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(jTe(r))return async function*(){yield*r}();if(WTe(r))return r}catch{throw(0,fk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}throw(0,fk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}async function*QTe(r,e,t){for await(let n of r)if(n.path&&(n.path.substring(0,2)==="./"&&(t.wrapWithDirectory=!0),n.path=n.path.split("/").filter(i=>i&&i!==".").join("/")),n.content){let i;typeof t.chunker=="function"?i=t.chunker:t.chunker==="rabin"?i=VZ:i=KZ;let o;typeof t.chunkValidator=="function"?o=t.chunkValidator:o=$Z;let s={path:n.path,mtime:n.mtime,mode:n.mode,content:i(o(YTe(n.content),t),t)};yield()=>SZ(s,e,t)}else if(n.path){let i={path:n.path,mtime:n.mtime,mode:n.mode};yield()=>yZ(i,e,t)}else throw new Error("Import candidate must have content or path or both")}var qZ=QTe;var dk=class{constructor(e,t){this.options=t||{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime,this.cid=void 0,this.size=void 0}async put(e,t){}get(e){return Promise.resolve(this)}async*eachChildSeries(){}async*flush(e){}},rd=dk;var hk=class extends rd{constructor(e,t){super(e,t),this._children={}}async put(e,t){this.cid=void 0,this.size=void 0,this._children[e]=t}get(e){return Promise.resolve(this._children[e])}childCount(){return Object.keys(this._children).length}directChildrenCount(){return this.childCount()}onlyChild(){return this._children[Object.keys(this._children)[0]]}async*eachChildSeries(){let e=Object.keys(this._children);for(let t=0;tu+(l.Tsize==null?0:l.Tsize),0);this.cid=a,this.size=c,yield{cid:a,unixfs:i,path:this.path,size:c}}},H3=hk;var jZ=C(pk(),1);var bn=class{constructor(e,t,n=0){B(this,"_options");B(this,"_popCount");B(this,"_parent");B(this,"_posAtParent");B(this,"_children");B(this,"key");this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new jZ.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof bn?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof bn?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,o,s)=>(o!=null&&(o instanceof bn?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return WZ(this,e,t)}toJSON(){return this.serialize(tIe,rIe)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof bn)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?cr(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof bn?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new bn(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(eIe);if(e!=null&&!(e instanceof bn)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function eIe(r){return!!r}function tIe(r,e){return r.key}function rIe(r){return r}async function WZ(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof bn)await WZ(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return t(n)}var nIe=[255,254,252,248,240,224,192,128],iIe=[1,3,7,15,31,63,127,255],Z_=class{constructor(e){B(this,"_value");B(this,"_currentBytePos");B(this,"_currentBitPos");this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=oIe(i,o-s,s);n=(n<7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function oIe(r,e,t){let n=sIe(e,t);return(r&n)>>>e}function sIe(r,e){return nIe[r]&iIe[Math.min(e+r-1,7)]}function YZ(r){function e(t){return t instanceof J_?t:new J_(t,r)}return e}var J_=class{constructor(e,t){B(this,"_value");B(this,"_hashFn");B(this,"_depth");B(this,"_availableBits");B(this,"_currentBufferIndex");B(this,"_buffers");if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?yi([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Z_(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Tm(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:YZ(r.hashFn)};return new bn(e)}var mk=class extends rd{constructor(e,t){super(e,t),this._bucket=Tm({hashFn:t.hamtHashFn,bits:t.hamtBucketBits})}async put(e,t){await this._bucket.put(e,t)}get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}async*flush(e){for await(let t of XZ(this._bucket,e,this,this.options))yield{...t,path:this.path}}},QZ=mk;async function*XZ(r,e,t,n){let i=r._children,o=[],s=0;for(let d=0;d=t&&(i=await aIe(e,n));let o=i.parent;if(o){if(i!==e){if(r&&(r.parent=i),!i.parentKey)throw new Error("No parent key found");await o.put(i.parentKey,i)}return ZZ(i,o,t,n)}return i}async function aIe(r,e){let t=new QZ({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:i}of r.eachChildSeries())await t.put(n,i);return t}var JZ=ZZ;var cIe=(r="")=>(r.trim().match(/([^\\/]|\\\/)+/g)||[]).filter(Boolean),eJ=cIe;async function uIe(r,e,t){let n=eJ(r.path||""),i=n.length-1,o=e,s="";for(let a=0;agk({content:o},e));return}if(qs(n)){yield gk({content:t},e);return}if(U3(n)||n[Symbol.iterator]||n[Symbol.asyncIterator]||ll(n)||ul(n)){yield*Mi(t,o=>gk(o,e));return}}throw U3(r)?(0,G3.default)(new Error("Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead"),"ERR_UNEXPECTED_INPUT"):(0,G3.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}async function gk(r,e){let{path:t,mode:n,mtime:i,content:o}=r,s={path:t||"",mode:Bu(n),mtime:af(i)};return o?s.content=await e(o):t||(s.content=await e(r)),s}function nJ(r){return eE(r,H_)}var iJ=r=>{if(r)if(r.startsWith("size-")){let e=r.split("-")[1],t=parseInt(e);if(isNaN(t))throw new Error("Chunker parameter size must be an integer");return{chunker:"fixed",maxChunkSize:t}}else{if(r.startsWith("rabin"))return{chunker:"rabin",...fIe(r)};throw new Error(`Unrecognized chunker option: ${r}`)}else return{chunker:"fixed"}},fIe=r=>{let e={},t=r.split("-");switch(t.length){case 1:e.avgChunkSize=262144;break;case 2:e.avgChunkSize=tE(t[1],"avg");break;case 4:e.minChunkSize=tE(t[1],"min"),e.avgChunkSize=tE(t[2],"avg"),e.maxChunkSize=tE(t[3],"max");break;default:throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"')}return e},tE=(r,e)=>{let t=parseInt(r);if(isNaN(t))throw new Error(`Chunker parameter ${e} must be an integer`);return t};var dIe=et.bind({ignoreUndefined:!0});function oJ({repo:r,preload:e,hashers:t,options:n}){let i=n&&n.sharding;async function*o(s,a={}){let c=dIe({shardSplitThreshold:i?1e3:1/0,strategy:"balanced"},a,{...iJ(a.chunker)});c.hashAlg&&c.hashAlg!=="sha2-256"&&c.cidVersion!==1&&(c.cidVersion=1),c.trickle&&(c.strategy="trickle"),c.strategy==="trickle"&&(c.leafType="raw",c.reduceSingleLeafToSelf=!1),c.cidVersion>0&&c.rawLeaves===void 0&&(c.rawLeaves=!0),c.hashAlg!==void 0&&c.rawLeaves===void 0&&(c.rawLeaves=!0),delete c.trickle;let u={};if(c.progress){let d=c.progress;c.progress=(p,g)=>{u[g]||(u[g]=0),u[g]+=p,d(u[g],g)}}let l;c.hashAlg!=null&&(l=await t.getHasher(c.hashAlg));let f=Ne(nJ(s),d=>Im(d,r.blocks,{...c,hasher:l,pin:!1}),hIe(c),pIe(e,c),mIe(r,c)),h=await r.gcLock.readLock();try{for await(let d of f){let p=d.path??d.cid.toString();delete u[p],yield{...d,path:p}}}finally{h()}}return $(o)}function hIe(r){async function*e(t){for await(let n of t){let i=n.cid;r.cidVersion===1&&(i=i.toV1());let o=n.path?n.path:i.toString();r.wrapWithDirectory&&!n.path&&(o=""),yield{path:o,cid:i,size:n.size,mode:n.unixfs&&n.unixfs.mode,mtime:n.unixfs&&n.unixfs.mtime}}}return e}function pIe(r,e){async function*t(n){for await(let i of n)(!i.path||e.wrapWithDirectory?i.path==="":!i.path.includes("/"))&&!e.onlyHash&&e.preload!==!1&&r(i.cid),yield i}return t}function mIe(r,e){async function*t(n){for await(let i of n){let o=!(i.path&&i.path.includes("/"));(e.pin==null?!0:e.pin)&&o&&!e.onlyHash&&await r.pins.pinRecursively(i.cid),yield i}}return t}var bE=C(ee(),1);var KJ=C(ee(),1);var gIe=new TextDecoder;function yk(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function sJ(r,e){let t;return[t,e]=yk(r,e),[t&7,t>>3,e]}function yIe(r){let e={},t=r.length,n=0;for(;nt)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function aJ(r){let e=r.length,t=0,n,i=!1,o;for(;te)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var uJ=new TextEncoder,cJ=2**32,wIe=2**31;function bIe(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=j3(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=uJ.encode(r.Name);t-=n.length,e.set(n,t),t=j3(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=j3(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function lJ(r){let e=EIe(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=j3(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=bIe(r.Links[i],t.subarray(0,n));n-=o,n=j3(t,n,o)-1,t[n]=18}return t}function _Ie(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Rm(t)}if(typeof r.Name=="string"){let t=uJ.encode(r.Name).length;e+=1+t+Rm(t)}return typeof r.Tsize=="number"&&(e+=1+Rm(r.Tsize)),e}function EIe(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Rm(t)}if(r.Links)for(let t of r.Links){let n=_Ie(t);e+=1+n+Rm(n)}return e}function j3(r,e,t){e-=Rm(t);let n=e;for(;t>=wIe;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Rm(r){return r%2===0&&r++,Math.floor((vIe(r)+6)/7)}function vIe(r){let e=0;return r>=cJ&&(r=Math.floor(r/cJ),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+xIe[r]}var xIe=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var SIe=["Data","Links"],AIe=["Hash","Name","Tsize"],fJ=new TextEncoder;function TIe(r,e){if(r===e)return 0;let t=r.Name?fJ.encode(r.Name):[],n=e.Name?fJ.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s!e.includes(t))}function hJ(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!dJ(r,SIe))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e0&&TIe(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var Zo=112;function W3(r){hJ(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),lJ(e)}function Jo(r){let e=aJ(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=ce.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var wE=C(ee(),1);var pJ=C(pk(),1);var no=class{constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new pJ.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);await n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof no?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof no?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,o,s)=>(o!=null&&(o instanceof no?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return await mJ(this,e,t)}toJSON(){return this.serialize(RIe,CIe)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof no)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?fe(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof no?await i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new no(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),await n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(IIe);if(e!=null&&!(e instanceof no)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function IIe(r){return!!r}function RIe(r,e){return r.key}function CIe(r){return r}async function mJ(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof no)await mJ(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return await t(n)}var PIe=[255,254,252,248,240,224,192,128],kIe=[1,3,7,15,31,63,127,255],nE=class{constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=NIe(i,o-s,s);n=(n<7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function NIe(r,e,t){let n=DIe(e,t);return(r&n)>>>e}function DIe(r,e){return PIe[r]&kIe[Math.min(e+r-1,7)]}function yr(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Ac(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return Rf(t)}function gJ(r){function e(t){return t instanceof iE?t:new iE(t,r)}return e}var iE=class{constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?yr([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new nE(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function yJ(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:gJ(r.hashFn)};return new no(e)}var oE=C(nk(),1);function OIe(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var emt=Ah({name:"murmur3-32",code:35,encode:r=>OIe(oE.default.x86.hash32(r))}),wJ=Ah({name:"murmur3-128",code:34,encode:r=>yh.fromHex(oE.default.x64.hash128(r))}),tmt=Ah({name:"murmur3-x64-64",code:34,encode:r=>yh.fromHex(oE.default.x64.hash128(r)).subarray(0,8)});var LIe=async function(r){return(await wJ.encode(r)).slice(0,8).reverse()},BIe=(r,e,t)=>Promise.all(r.map(n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let i=parseInt(n.Name,16);return e._putObjectAt(i,new no({hash:t._options.hash,bits:t._options.bits},e,i))}return t.put(n.Name.substring(2),!0)})),bJ=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),MIe=r=>{let e=r.bucket,t=[];for(;e._parent;)t.push(e),e=e._parent;return t.push(e),t.reverse()},_J=async(r,e,t,n,i)=>{if(!n){let l=yJ({hashFn:LIe});n={rootBucket:l,hamtDepth:1,lastBucket:l}}await BIe(r.Links,n.lastBucket,n.rootBucket);let o=await n.rootBucket._findNewBucketAndPos(e),s=bJ(o.pos),a=MIe(o);a.length>n.hamtDepth&&(n.lastBucket=a[n.hamtDepth],s=bJ(n.lastBucket._posAtParent));let c=r.Links.find(l=>{if(l.Name==null)return!1;let f=l.Name.substring(0,2),h=l.Name.substring(2);return!(f!==s||h&&h!==e)});if(!c)return null;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await t.get(c.Hash,i);return r=Jo(u),_J(r,e,t,n,i)},EJ=_J;function UIe(r,e,t,n){let i=r.length,o=e+i;return t>=o||n=e&&n=e&&t{if(e||(e=0),e<0)throw(0,sE.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(e>r)throw(0,sE.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(!t&&t!==0&&(t=r-e),t<0)throw(0,sE.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");return e+t>r&&(t=r-e),{offset:e,length:t}},Cm=FIe;var yE=C(ee(),1);function io(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var aE=globalThis.CustomEvent??Event;async function*wk(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,o=[],s=io(),a=io(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(s=io(),await s.promise),l)break;let g={done:!1};o.push(g),p().then(w=>{g.done=!0,g.ok=!0,g.value=w,i.dispatchEvent(new aE("task-complete"))},w=>{g.done=!0,g.err=w,i.dispatchEvent(new aE("task-complete"))})}c=!0,i.dispatchEvent(new aE("task-complete"))}catch(p){u=p,i.dispatchEvent(new aE("task-complete"))}});function f(){var p;return n?(p=o[0])==null?void 0:p.done:!!o.find(g=>g.done)}function*h(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}function*d(){for(;f();)for(let p=0;p0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var ip=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},fl,X3=class{constructor(){fl.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&ip(this,fl,"f")[this.size-1].priority>=t.priority){ip(this,fl,"f").push(n);return}let i=_k(ip(this,fl,"f"),n,(o,s)=>s.priority-o.priority);ip(this,fl,"f").splice(i,0,n)}dequeue(){let e=ip(this,fl,"f").shift();return e==null?void 0:e.run}filter(e){return ip(this,fl,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return ip(this,fl,"f").length}};fl=new WeakMap;var Qr=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},De=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},_n,J3,ew,id,pE,tw,uE,Ya,Z3,es,lE,ts,rw,nd,fE,SJ,AJ,RJ,TJ,IJ,dE,Ek,vk,mE,CJ,hE,gE=class extends Error{},Hs=class extends PJ.default{constructor(e){var t,n,i,o;if(super(),_n.add(this),J3.set(this,void 0),ew.set(this,void 0),id.set(this,0),pE.set(this,void 0),tw.set(this,void 0),uE.set(this,0),Ya.set(this,void 0),Z3.set(this,void 0),es.set(this,void 0),lE.set(this,void 0),ts.set(this,0),rw.set(this,void 0),nd.set(this,void 0),fE.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:X3,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);Qr(this,J3,e.carryoverConcurrencyCount,"f"),Qr(this,ew,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Qr(this,pE,e.intervalCap,"f"),Qr(this,tw,e.interval,"f"),Qr(this,es,new e.queueClass,"f"),Qr(this,lE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Qr(this,fE,e.throwOnTimeout===!0,"f"),Qr(this,nd,e.autoStart===!1,"f")}get concurrency(){return De(this,rw,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);Qr(this,rw,e,"f"),De(this,_n,"m",mE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:De(this,fE,"f"),...t},new Promise((n,i)=>{De(this,es,"f").enqueue(async()=>{var o,s,a;Qr(this,ts,(s=De(this,ts,"f"),s++,s),"f"),Qr(this,id,(a=De(this,id,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new gE("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Ih(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,De(this,_n,"m",CJ).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nf&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{De(this,_n,"m",RJ).call(this)}},t),this.emit("add"),De(this,_n,"m",dE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return De(this,nd,"f")?(Qr(this,nd,!1,"f"),De(this,_n,"m",mE).call(this),this):this}pause(){Qr(this,nd,!0,"f")}clear(){Qr(this,es,new(De(this,lE,"f")),"f")}async onEmpty(){De(this,es,"f").size!==0&&await De(this,_n,"m",hE).call(this,"empty")}async onSizeLessThan(e){De(this,es,"f").sizeDe(this,es,"f").size{De(this,_n,"m",TJ).call(this)},t),"f"),!0}return!1},dE=function(){if(De(this,es,"f").size===0)return De(this,Ya,"f")&&clearInterval(De(this,Ya,"f")),Qr(this,Ya,void 0,"f"),this.emit("empty"),De(this,ts,"f")===0&&this.emit("idle"),!1;if(!De(this,nd,"f")){let e=!De(this,_n,"a",IJ);if(De(this,_n,"a",SJ)&&De(this,_n,"a",AJ)){let t=De(this,es,"f").dequeue();return t?(this.emit("active"),t(),e&&De(this,_n,"m",Ek).call(this),!0):!1}}return!1},Ek=function(){De(this,ew,"f")||De(this,Ya,"f")!==void 0||(Qr(this,Ya,setInterval(()=>{De(this,_n,"m",vk).call(this)},De(this,tw,"f")),"f"),Qr(this,uE,Date.now()+De(this,tw,"f"),"f"))},vk=function(){De(this,id,"f")===0&&De(this,ts,"f")===0&&De(this,Ya,"f")&&(clearInterval(De(this,Ya,"f")),Qr(this,Ya,void 0,"f")),Qr(this,id,De(this,J3,"f")?De(this,ts,"f"):0,"f"),De(this,_n,"m",mE).call(this)},mE=function(){for(;De(this,_n,"m",dE).call(this););},CJ=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new gE("The task was aborted."))},{once:!0})})},hE=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};async function kJ(r,e,t,n,i,o,s,a){if(e instanceof Uint8Array){t.push(np(e,n,i,o));return}if(e.Data==null)throw(0,yE.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let c;try{c=st.unmarshal(e.Data)}catch(l){throw(0,yE.default)(l,"ERR_NOT_UNIXFS")}if(c.data!=null){let l=c.data,f=np(l,n,i,o);t.push(f),n+=f.byteLength}let u=[];for(let l=0;l=h&&i=h&&o<=d||id)&&u.push({link:f,blockStart:n}),n=d,n>o)break}await Ne(u,l=>Bi(l,f=>async()=>{let h=await r.get(f.link.Hash,{signal:a.signal});return{...f,block:h}}),l=>wk(l,{ordered:!0}),async l=>{for await(let{link:f,block:h,blockStart:d}of l){let p;switch(f.Hash.code){case Zo:p=Jo(h);break;case Sc:p=h;break;default:t.end((0,yE.default)(new Error(`Unsupported codec: ${f.Hash.code}`),"ERR_NOT_UNIXFS"));return}s.add(async()=>{await kJ(r,p,t,d,i,o,s,a)})}})}var KIe=(r,e,t,n,i,o,s)=>{async function*a(c={}){let u=t.fileSize();if(u===void 0)throw new Error("File was a directory");let{offset:l,length:f}=Cm(u,c.offset,c.length);if(f===0)return;let h=new Hs({concurrency:1}),d=jn();h.add(async()=>{await kJ(s,e,d,0,l,l+f,h,c)}),h.on("error",g=>{d.end(g)});let p=0;for await(let g of d)g!=null&&(p+=g.byteLength,p===f&&d.end(),yield g)}return a},xk=KIe;var $Ie=(r,e,t,n,i,o,s)=>{async function*a(c={}){let u=c.offset||0,l=c.length||e.Links.length,f=e.Links.slice(u,l);for(let h of f){let d=await i(h.Hash,h.Name||"",`${n}/${h.Name||""}`,[],o+1,s,c);d.entry&&(yield d.entry)}}return a},NJ=$Ie;var qIe=(r,e,t,n,i,o,s)=>{function a(c={}){return DJ(e,n,i,o,s,c)}return a};async function*DJ(r,e,t,n,i,o){let s=r.Links;for(let a of s){let c=a.Name!=null?a.Name.substring(2):null;if(c)yield(await t(a.Hash,c,`${e}/${c}`,[],n+1,i,o)).entry;else{let u=await i.get(a.Hash);r=Jo(u);for await(let l of DJ(r,e,t,n,i,o))yield l}}}var OJ=qIe;var HIe=(r,e)=>{let t=r.Links.find(n=>n.Name===e);return t&&t.Hash},GIe={raw:xk,file:xk,directory:NJ,"hamt-sharded-directory":OJ,metadata:(r,e,t,n,i,o,s)=>()=>[],symlink:(r,e,t,n,i,o,s)=>()=>[]},jIe=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),u=Jo(c),l,f;if(e||(e=r.toString()),u.Data==null)throw(0,wE.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=st.unmarshal(u.Data)}catch(h){throw(0,wE.default)(h,"ERR_NOT_UNIXFS")}if(t||(t=e),n.length){let h;if(l&&l.type==="hamt-sharded-directory"?h=await EJ(u,n[0],s):h=HIe(u,n[0]),!h)throw(0,wE.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let d=n.shift(),p=`${t}/${d}`;f={cid:h,toResolve:n,name:d||"",path:p}}return{entry:{type:l.isDirectory()?"directory":"file",name:e,path:t,cid:r,content:GIe[l.type](r,u,l,t,i,o,s),unixfs:l,depth:o,node:u,size:l.fileSize()},next:f}},LJ=jIe;var BJ=C(ee(),1);var WIe=r=>{async function*e(t={}){let{offset:n,length:i}=Cm(r.length,t.offset,t.length);yield np(r,0,n,n+i)}return e},YIe=async(r,e,t,n,i,o,s,a)=>{if(n.length)throw(0,BJ.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:WIe(c),depth:o,size:c.length,node:c}}},MJ=YIe;var UJ=C(ee(),1);var QIe=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r),u=E8(c),l=u,f=t;for(;n.length;){let h=n[0];if(h in l){n.shift(),f=`${f}/${h}`;let d=ce.asCID(l[h]);if(d)return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:o,size:c.length,content:async function*(){yield u}},next:{cid:d,name:h,path:f,toResolve:n}};l=l[h]}else throw(0,UJ.default)(new Error(`No property named ${h} found in cbor node ${r}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:o,size:c.length,content:async function*(){yield u}}}},FJ=QIe;var zJ=C(ee(),1);var XIe=r=>{async function*e(t={}){let{offset:n,length:i}=Cm(r.length,t.offset,t.length);yield np(r,0,n,n+i)}return e},ZIe=async(r,e,t,n,i,o,s,a)=>{if(n.length)throw(0,zJ.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await Jn(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:XIe(c.digest),depth:o,size:c.digest.length,node:c.digest}}},VJ=ZIe;var JIe={[Zo]:LJ,[Sc]:MJ,[W$]:FJ,[Ns.code]:VJ};function $J(r,e,t,n,i,o,s){let a=JIe[r.code];if(!a)throw(0,KJ.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,$J,i,o,s)}var qJ=$J;async function Sk(r){let e;for await(let t of r)e=t;return e}var eRe=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)||[]).filter(Boolean),tRe=r=>{if(r instanceof Uint8Array)return{cid:ce.decode(r),toResolve:[]};let e=ce.asCID(r);if(e)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=eRe(r);return{cid:ce.parse(t[0]),toResolve:t.slice(1)}}throw(0,bE.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*Ak(r,e,t={}){let{cid:n,toResolve:i}=tRe(r),o=n.toString(),s=o,a=i.length;for(;;){let c=await qJ(n,o,s,i,a,e,t);if(!c.entry&&!c.next)throw(0,bE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry&&(yield c.entry),!c.next)return;i=c.next.toResolve,n=c.next.cid,o=c.next.name,s=c.next.path}}async function Ei(r,e,t={}){let n=await Sk(Ak(r,e,t));if(!n)throw(0,bE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*_E(r,e,t={}){let n=await Ei(r,e,t);if(!n)return;if(yield n,n.type==="directory")for await(let o of i(n,t))yield o;async function*i(o,s){for await(let a of o.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*i(a,s))}}function HJ({repo:r,preload:e}){async function*t(n,i={}){if(n=N1(n),i.preload!==!1){let s=n.split("/");e(z.parse(s[0]))}let o=await Ei(n,r.blocks,i);if(o.type==="directory")throw new Error("this dag node is a directory");if(!o.content)throw new Error("this dag node has no content");yield*o.content(i)}return $(t)}var Um=C(ee(),1);var p2t="0".charCodeAt(0),m2t=cr("ustar\0","binary"),g2t=cr("ustar ","binary"),y2t=cr(" \0","binary");var QJ=C(jJ(),1);function nRe(r){return r[Symbol.asyncIterator]!=null}function iRe(r){if(nRe(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=yi([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return yi(e,t)}var WJ=iRe;var oRe="0000000000000000000",sRe="7777777777777777777",aRe="0".charCodeAt(0),cRe=cr("ustar\0","binary"),uRe=cr("00","binary"),lRe=parseInt("7777",8),fRe=257,dRe=263,hRe=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},pRe=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},od=function(r,e){let t=r.toString(8);return t.length>e?cr(sRe.slice(0,e)+" "):cr(oRe.slice(0,e-t.length)+t+" ")},Tk=function(r){let e=cr(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function YJ(r){let e="";r.name!=null&&(e+=Tk(" path="+r.name+` + `,cwe=async(r,e,t="MiroPad note")=>{if(!r){ze.error("\u{1F47B} No message to send, type something and try again! \u{1F913}");return}try{await fetch(`${dc.mail_service.api}`,{method:"POST",headers:{"x-secret-token":Le.get("MIROPAD_SECRET_TOKEN"),accept:"application/json","content-type":"application/json"},body:JSON.stringify({to:e,subject:t,html:awe(r)})}).then(yA).then(n=>n.json()),ze.success("Email sent \u{1F680}")}catch{ze.error("Error not went through \u{1F4A5}! Check your credentials and try again!")}},uwe=()=>{let r=Le.get("mail");if(r){let n=window.prompt(`Mail ${r} again? (y)es/(no)`,"yeap");if(n===null)return n;if(n.slice(0,1).toLowerCase()==="y")return r}let e=window.prompt("Where do you wanna send the mail to?"),t=window.prompt("Do you wanna save that to your preferences for later on? (y)es/(no)","yeap");return t&&t.slice(0,1).toLowerCase()==="y"&&Le.set("mail",e),e},vF=r=>{let e=uwe();if(e===null){ze.info("Sending mail cancelled \u{1F636}");return}ze.info("Sending mail... \u{1F680}");let t=U0(r),n=S6(r);cwe(n,e,t)};var Nu=async(r,e="\u{1F4CB} Copied to clipboard")=>{try{await navigator.clipboard.writeText(r),ze.success(e)}catch(t){ze.error(t.message)}};var A6=(r,e,t)=>{let n=N0(r)?r:[r],i=document.createElement("button");return i.setAttribute("type","button"),t&&i.setAttribute("id",t),n.forEach(o=>{typeof o=="string"?i.appendChild(document.createTextNode(o)):i.appendChild(o)}),i.onclick=o=>e(o),i};var lwe=(()=>({view:X(".preview"),init:function(){return this.update(),X(".terminal").listen("input",()=>this.update()),!!ht.getSearchParam("md")?this.view.show():this.view.hide(),this},autoLink:function(){let r=Le.parse("__auto-links__"),e=Object.keys(r).join("|"),t=new RegExp(`\\b(${e})\\d+\\b(?=\\s)`,"g"),n=this.view.el.innerHTML.replace(t,i=>{let o=Object.keys(r).find(a=>i.startsWith(a));return`${i}`});this.view.innerHTML(n)},update:async function(){let md=X(".terminal").getValue();this.view.innerHTML(S6(md)),this.autoLink();let{elements}=X("pre");Array.prototype.slice.call(elements).forEach(r=>{let e=A6("\u{1F4CB} Copy",async t=>{t.stopPropagation();let n=t.srcElement.previousSibling.innerHTML;await Nu(n,"\u{1F4CB} Code copied to clipboard")});r.appendChild(e)}),X("code").listenAll("click",async({innerHTML})=>{let result=eval(innerHTML);X(".console").show().innerHTML(result)}),X(".console").listen("click",async r=>{r.srcElement.classList.add("hidden");let e=r.srcElement.innerHTML;await Nu(e,"\u{1F4CB} Code copied to clipboard")})},show:function(r=!0){this.view.show(),ht.set(void 0,{md:r})},hide:function(){this.view.hide(),ht.deleteParam("md")},toggle:function(r="true"){return ht.getSearchParam("md")===r?this.hide():this.show(r),this}}))(),nf=lwe;var fwe=r=>{let e=document.querySelector(r);if(y6(e.value)){let t=JSON.stringify(JSON.parse(e.value),null,2);e.value=t,ze.success("\u{1F44D} JSON value prettified")}else ze.error("\u{1F627} Value is not in valid JSON format")},xF=fwe;var SF=(r=1e3)=>new Promise(e=>{setTimeout(e,r)});var Sr=(r,e,t)=>{let n=document.createElement("IMG");return t&&n.classList.add(t),e&&n.setAttribute("alt",e),n.setAttribute("src",r),n};var AF="./list-LK7OCHR7.svg";var qg="./trash-RDL437QG.svg";var TF="./checkmark-circle-JQ7ADSUI.svg";var IF="./cloud-sync-F3RLGHML.svg";var RF="./lighter-UBEI67LL.svg";var CF="./enter-down-6TVO6OFR.svg";var PF="./download-FVXMIYZ4.svg";var kF="./envelope-Z2VRVSLR.svg";var NF="./bug-36UGMUXT.svg";var DF="./picture-3TDOSVS3.svg";var OF="./printer-B7RMPYZC.svg";var LF="./page-break-BLVP5QBQ.svg";var BF="./frame-expand-CX6CNP53.svg";var MF="./arrow-right-circle-2Q6EHM2H.svg";var UF="./magic-wand-JQJ6EKRO.svg";var FF="./rocket-AIY2RJJS.svg";var zF="./earth-DJLABK7O.svg";var VF="./spell-check-V6QYTGNT.svg";var KF="./pencil-X3ZMY3QU.svg";var wA="./exit-up-GH6BPN2X.svg";var $F="./leaf-CGBE7XAJ.svg";var qF=async()=>{try{let r=hn(),e=ht.get();await navigator.share({title:r?r.title:"\u270D\uFE0F MiroPad",text:r?r.text:"Temporary note keeping app for the browser",url:e})}catch(r){ze.info(`${r.message}`)}};var ZF=C(_A(),1),et=ZF.default;var Pye=C(C6(),1);var Co=C(xA(),1);var SA={};xe(SA,{base64:()=>fh,base64pad:()=>o5e,base64url:()=>Gg,base64urlpad:()=>s5e});var fh=Zr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),o5e=Zr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gg=Zr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),s5e=Zr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});Co.default.formatters.b=r=>r==null?"undefined":pr.baseEncode(r);Co.default.formatters.t=r=>r==null?"undefined":va.baseEncode(r);Co.default.formatters.m=r=>r==null?"undefined":fh.baseEncode(r);Co.default.formatters.p=r=>r==null?"undefined":r.toString();Co.default.formatters.c=r=>r==null?"undefined":r.toString();Co.default.formatters.k=r=>r==null?"undefined":r.toString();Co.default.formatters.a=r=>r==null?"undefined":r.toString();function a5e(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function j(r){let e=a5e(`${r}:trace`);return Co.default.enabled(`${r}:trace`)&&Co.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Co.default)(`${r}:trace`)),Object.assign((0,Co.default)(r),{error:(0,Co.default)(`${r}:error`),trace:e})}var jS=C(ee(),1);var H6=C(ee(),1);var Ou=C(gc(),1),H0=Ou.default.Reader,UA=Ou.default.Writer,je=Ou.default.util,pi=Ou.default.roots["ipfs-unixfs"]||(Ou.default.roots["ipfs-unixfs"]={}),jz=pi.Data=(()=>{function r(e){if(this.blocksizes=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.Type=t.int32();break;case 2:o.Data=t.bytes();break;case 3:o.filesize=t.uint64();break;case 4:if(o.blocksizes&&o.blocksizes.length||(o.blocksizes=[]),(s&7)===2)for(var a=t.uint32()+t.pos;t.pos>>0,t.filesize.high>>>0).toNumber(!0))),t.blocksizes){if(!Array.isArray(t.blocksizes))throw TypeError(".Data.blocksizes: array expected");n.blocksizes=[];for(var i=0;i>>0,t.blocksizes[i].high>>>0).toNumber(!0))}if(t.hashType!=null&&(je.Long?(n.hashType=je.Long.fromValue(t.hashType)).unsigned=!0:typeof t.hashType=="string"?n.hashType=parseInt(t.hashType,10):typeof t.hashType=="number"?n.hashType=t.hashType:typeof t.hashType=="object"&&(n.hashType=new je.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0))),t.fanout!=null&&(je.Long?(n.fanout=je.Long.fromValue(t.fanout)).unsigned=!0:typeof t.fanout=="string"?n.fanout=parseInt(t.fanout,10):typeof t.fanout=="number"?n.fanout=t.fanout:typeof t.fanout=="object"&&(n.fanout=new je.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0))),t.mode!=null&&(n.mode=t.mode>>>0),t.mtime!=null){if(typeof t.mtime!="object")throw TypeError(".Data.mtime: object expected");n.mtime=pi.UnixTime.fromObject(t.mtime)}return n},r.toObject=function(t,n){n||(n={});var i={};if((n.arrays||n.defaults)&&(i.blocksizes=[]),n.defaults){if(i.Type=n.enums===String?"Raw":0,n.bytes===String?i.Data="":(i.Data=[],n.bytes!==Array&&(i.Data=je.newBuffer(i.Data))),je.Long){var o=new je.Long(0,0,!0);i.filesize=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.filesize=n.longs===String?"0":0;if(je.Long){var o=new je.Long(0,0,!0);i.hashType=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.hashType=n.longs===String?"0":0;if(je.Long){var o=new je.Long(0,0,!0);i.fanout=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.fanout=n.longs===String?"0":0;i.mode=0,i.mtime=null}if(t.Type!=null&&t.hasOwnProperty("Type")&&(i.Type=n.enums===String?pi.Data.DataType[t.Type]:t.Type),t.Data!=null&&t.hasOwnProperty("Data")&&(i.Data=n.bytes===String?je.base64.encode(t.Data,0,t.Data.length):n.bytes===Array?Array.prototype.slice.call(t.Data):t.Data),t.filesize!=null&&t.hasOwnProperty("filesize")&&(typeof t.filesize=="number"?i.filesize=n.longs===String?String(t.filesize):t.filesize:i.filesize=n.longs===String?je.Long.prototype.toString.call(t.filesize):n.longs===Number?new je.LongBits(t.filesize.low>>>0,t.filesize.high>>>0).toNumber(!0):t.filesize),t.blocksizes&&t.blocksizes.length){i.blocksizes=[];for(var s=0;s>>0,t.blocksizes[s].high>>>0).toNumber(!0):t.blocksizes[s]}return t.hashType!=null&&t.hasOwnProperty("hashType")&&(typeof t.hashType=="number"?i.hashType=n.longs===String?String(t.hashType):t.hashType:i.hashType=n.longs===String?je.Long.prototype.toString.call(t.hashType):n.longs===Number?new je.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0):t.hashType),t.fanout!=null&&t.hasOwnProperty("fanout")&&(typeof t.fanout=="number"?i.fanout=n.longs===String?String(t.fanout):t.fanout:i.fanout=n.longs===String?je.Long.prototype.toString.call(t.fanout):n.longs===Number?new je.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0):t.fanout),t.mode!=null&&t.hasOwnProperty("mode")&&(i.mode=t.mode),t.mtime!=null&&t.hasOwnProperty("mtime")&&(i.mtime=pi.UnixTime.toObject(t.mtime,n)),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Ou.default.util.toJSONOptions)},r.DataType=function(){let e={},t=Object.create(e);return t[e[0]="Raw"]=0,t[e[1]="Directory"]=1,t[e[2]="File"]=2,t[e[3]="Metadata"]=3,t[e[4]="Symlink"]=4,t[e[5]="HAMTShard"]=5,t}(),r})(),UWe=pi.UnixTime=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}if(!o.hasOwnProperty("Seconds"))throw je.ProtocolError("missing required 'Seconds'",{instance:o});return o},r.fromObject=function(t){if(t instanceof pi.UnixTime)return t;var n=new pi.UnixTime;return t.Seconds!=null&&(je.Long?(n.Seconds=je.Long.fromValue(t.Seconds)).unsigned=!1:typeof t.Seconds=="string"?n.Seconds=parseInt(t.Seconds,10):typeof t.Seconds=="number"?n.Seconds=t.Seconds:typeof t.Seconds=="object"&&(n.Seconds=new je.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber())),t.FractionalNanoseconds!=null&&(n.FractionalNanoseconds=t.FractionalNanoseconds>>>0),n},r.toObject=function(t,n){n||(n={});var i={};if(n.defaults){if(je.Long){var o=new je.Long(0,0,!1);i.Seconds=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else i.Seconds=n.longs===String?"0":0;i.FractionalNanoseconds=0}return t.Seconds!=null&&t.hasOwnProperty("Seconds")&&(typeof t.Seconds=="number"?i.Seconds=n.longs===String?String(t.Seconds):t.Seconds:i.Seconds=n.longs===String?je.Long.prototype.toString.call(t.Seconds):n.longs===Number?new je.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber():t.Seconds),t.FractionalNanoseconds!=null&&t.hasOwnProperty("FractionalNanoseconds")&&(i.FractionalNanoseconds=t.FractionalNanoseconds),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Ou.default.util.toJSONOptions)},r})(),FWe=pi.Metadata=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof pi.Metadata)return t;var n=new pi.Metadata;return t.MimeType!=null&&(n.MimeType=String(t.MimeType)),n},r.toObject=function(t,n){n||(n={});var i={};return n.defaults&&(i.MimeType=""),t.MimeType!=null&&t.hasOwnProperty("MimeType")&&(i.MimeType=t.MimeType),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Ou.default.util.toJSONOptions)},r})();var Lu=jz,Wz=["raw","directory","file","metadata","symlink","hamt-sharded-directory"],b5e=["directory","hamt-sharded-directory"],Yz=parseInt("0644",8),Qz=parseInt("0755",8);function Bu(r){if(r!=null)return typeof r=="number"?r&4095:(r=r.toString(),r.substring(0,1)==="0"?parseInt(r,8)&4095:parseInt(r,10)&4095)}function af(r){if(r==null)return;let e;if(r.secs!=null&&(e={secs:r.secs,nsecs:r.nsecs}),r.Seconds!=null&&(e={secs:r.Seconds,nsecs:r.FractionalNanoseconds}),Array.isArray(r)&&(e={secs:r[0],nsecs:r[1]}),r instanceof Date){let t=r.getTime(),n=Math.floor(t/1e3);e={secs:n,nsecs:(t-n*1e3)*1e3}}if(Object.prototype.hasOwnProperty.call(e,"secs")){if(e!=null&&e.nsecs!=null&&(e.nsecs<0||e.nsecs>999999999))throw(0,H6.default)(new Error("mtime-nsecs must be within the range [0,999999999]"),"ERR_INVALID_MTIME_NSECS");return e}}var st=class{static unmarshal(e){let t=Lu.decode(e),n=Lu.toObject(t,{defaults:!1,arrays:!0,longs:Number,objects:!1}),i=new st({type:Wz[n.Type],data:n.Data,blockSizes:n.blocksizes,mode:n.mode,mtime:n.mtime?{secs:n.mtime.Seconds,nsecs:n.mtime.FractionalNanoseconds}:void 0});return i._originalMode=n.mode||0,i}constructor(e={type:"file"}){let{type:t,data:n,blockSizes:i,hashType:o,fanout:s,mtime:a,mode:c}=e;if(t&&!Wz.includes(t))throw(0,H6.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t||"file",this.data=n,this.hashType=o,this.fanout=s,this.blockSizes=i||[],this._originalMode=0,this.mode=Bu(c),a&&(this.mtime=af(a),this.mtime&&!this.mtime.nsecs&&(this.mtime.nsecs=0))}set mode(e){this._mode=this.isDirectory()?Qz:Yz;let t=Bu(e);t!==void 0&&(this._mode=t)}get mode(){return this._mode}isDirectory(){return!!(this.type&&b5e.includes(this.type))}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0;let e=0;return this.blockSizes.forEach(t=>{e+=t}),this.data&&(e+=this.data.length),e}marshal(){let e;switch(this.type){case"raw":e=Lu.DataType.Raw;break;case"directory":e=Lu.DataType.Directory;break;case"file":e=Lu.DataType.File;break;case"metadata":e=Lu.DataType.Metadata;break;case"symlink":e=Lu.DataType.Symlink;break;case"hamt-sharded-directory":e=Lu.DataType.HAMTShard;break;default:throw(0,H6.default)(new Error("Type: "+e+" is not valid"),"ERR_INVALID_TYPE")}let t=this.data;(!this.data||!this.data.length)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(Bu(this.mode)||0),n===Yz&&!this.isDirectory()&&(n=void 0),n===Qz&&this.isDirectory()&&(n=void 0));let i;if(this.mtime!=null){let s=af(this.mtime);s&&(i={Seconds:s.secs,FractionalNanoseconds:s.nsecs},i.FractionalNanoseconds===0&&delete i.FractionalNanoseconds)}let o={Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i};return Lu.encode(o).finish()}};var sr={};xe(sr,{code:()=>kr,createLink:()=>gV,createNode:()=>mV,decode:()=>en,encode:()=>pt,name:()=>w4e,prepare:()=>Xn,validate:()=>JA});var GA={};xe(GA,{base32:()=>wc,base32hex:()=>k5e,base32hexpad:()=>D5e,base32hexpadupper:()=>O5e,base32hexupper:()=>N5e,base32pad:()=>C5e,base32padupper:()=>P5e,base32upper:()=>R5e,base32z:()=>L5e});var G0={};xe(G0,{coerce:()=>yc,empty:()=>Xz,equals:()=>FA,fromHex:()=>E5e,fromString:()=>zA,isBinary:()=>v5e,toHex:()=>_5e,toString:()=>VA});var Xz=new Uint8Array(0);function _5e(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function E5e(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):Xz}function FA(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var S5e=x5e,A5e=S5e,Zz=A5e;var KA=class{constructor(e,t,n){B(this,"name");B(this,"prefix");B(this,"baseEncode");this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},$A=class{constructor(e,t,n){B(this,"name");B(this,"prefix");B(this,"baseDecode");B(this,"prefixCodePoint");this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Jz(this,e)}},qA=class{constructor(e){B(this,"decoders");this.decoders=e}or(e){return Jz(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Jz(r,e){return new qA({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var HA=class{constructor(e,t,n,i){B(this,"name");B(this,"prefix");B(this,"baseEncode");B(this,"baseDecode");B(this,"encoder");B(this,"decoder");this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new KA(e,t,n),this.decoder=new $A(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function j0({name:r,prefix:e,encode:t,decode:n}){return new HA(r,e,t,n)}function cf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Zz(t,r);return j0({prefix:e,name:r,encode:n,decode:o=>yc(i(o))})}function T5e(r,e,t,n){let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function I5e(r,e,t){let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<Qg,base36upper:()=>B5e});var Qg=cf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),B5e=cf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var WA={};xe(WA,{base58btc:()=>Yi,base58flickr:()=>M5e});var Yi=cf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),M5e=cf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var U5e=rV,eV=128,F5e=127,z5e=~F5e,V5e=Math.pow(2,31);function rV(r,e,t){e=e||[],t=t||0;for(var n=t;r>=V5e;)e[t++]=r&255|eV,r/=128;for(;r&z5e;)e[t++]=r&255|eV,r>>>=7;return e[t]=r|0,rV.bytes=t-n+1,e}var K5e=YA,$5e=128,tV=127;function YA(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw YA.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&tV)<=$5e);return YA.bytes=o-n,t}var q5e=Math.pow(2,7),H5e=Math.pow(2,14),G5e=Math.pow(2,21),j5e=Math.pow(2,28),W5e=Math.pow(2,35),Y5e=Math.pow(2,42),Q5e=Math.pow(2,49),X5e=Math.pow(2,56),Z5e=Math.pow(2,63),J5e=function(r){return r{let[f,h]=Zg(e.subarray(t));return t+=h,f},i=n(),o=Jg;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=r4e(e,t),o=Xe.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return QA(o).set(n,e),o}};function r4e(r,e){switch(r[0]){case"Q":{let t=e??Yi;return[Yi.prefix,t.decode(`${Yi.prefix}${r}`)]}case Yi.prefix:{let t=e??Yi;return[Yi.prefix,t.decode(r)]}case wc.prefix:{let t=e??wc;return[wc.prefix,t.decode(r)]}case Qg.prefix:{let t=e??Qg;return[Qg.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function n4e(r,e,t){let{prefix:n}=t;if(n!==Yi.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function i4e(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var Jg=112,o4e=18;function sV(r,e,t){let n=Y0(r),i=n+Y0(e),o=new Uint8Array(i+t.byteLength);return W0(r,o,0),W0(e,o,n),o.set(t,i),o}var s4e=Symbol.for("@ipld/js-cid/CID");var c4e=new TextDecoder;function XA(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function aV(r,e){let t;return[t,e]=XA(r,e),[t&7,t>>3,e]}function u4e(r){let e={},t=r.length,n=0;for(;nt)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function cV(r){let e=r.length,t=0,n,i=!1,o;for(;te)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var lV=new TextEncoder,uV=2**32,l4e=2**31;function f4e(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=ey(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=lV.encode(r.Name);t-=n.length,e.set(n,t),t=ey(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ey(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function fV(r){let e=h4e(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ey(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=f4e(r.Links[i],t.subarray(0,n));n-=o,n=ey(t,n,o)-1,t[n]=18}return t}function d4e(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+X0(t)}if(typeof r.Name=="string"){let t=lV.encode(r.Name).length;e+=1+t+X0(t)}return typeof r.Tsize=="number"&&(e+=1+X0(r.Tsize)),e}function h4e(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+X0(t)}if(r.Links)for(let t of r.Links){let n=d4e(t);e+=1+n+X0(n)}return e}function ey(r,e,t){e-=X0(t);let n=e;for(;t>=l4e;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function X0(r){return r%2===0&&r++,Math.floor((p4e(r)+6)/7)}function p4e(r){let e=0;return r>=uV&&(r=Math.floor(r/uV),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+m4e[r]}var m4e=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var g4e=["Data","Links"],y4e=["Hash","Name","Tsize"],ZA=new TextEncoder;function hV(r,e){if(r===e)return 0;let t=r.Name?ZA.encode(r.Name):[],n=e.Name?ZA.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s!e.includes(t))}function pV(r){if(typeof r.asCID=="object"){let t=Xe.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=Xe.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=Xe.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=Xe.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Xn(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=ZA.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(pV),e.Links.sort(hV);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function JA(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!dV(r,g4e))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e0&&hV(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function mV(r,e=[]){return Xn({Data:r,Links:e})}function gV(r,e,t){return pV({Hash:t,Name:r,Tsize:e})}function yV(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var w4e="dag-pb",kr=112;function pt(r){JA(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),fV(e)}function en(r){let e=yV(r),t=cV(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=Xe.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}var o1={};xe(o1,{code:()=>lT,decode:()=>dT,decodeOptions:()=>Z4e,encode:()=>fT,encodeOptions:()=>Q4e,name:()=>J4e,toByteView:()=>vK});var b4e=["string","number","bigint","symbol"],_4e=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function wV(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(b4e.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(E4e(r))return"Buffer";let t=v4e(r);return t||"Object"}function E4e(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function v4e(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(_4e.includes(e))return e}var V=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};V.uint=new V(0,"uint",!0);V.negint=new V(1,"negint",!0);V.bytes=new V(2,"bytes",!0);V.string=new V(3,"string",!0);V.array=new V(4,"array",!1);V.map=new V(5,"map",!1);V.tag=new V(6,"tag",!1);V.float=new V(7,"float",!0);V.false=new V(7,"false",!0);V.true=new V(7,"true",!0);V.null=new V(7,"null",!0);V.undefined=new V(7,"undefined",!0);V.break=new V(7,"break",!0);var oe=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Z0=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",x4e=new TextDecoder,S4e=new TextEncoder;function W6(r){return Z0&&globalThis.Buffer.isBuffer(r)}function ty(r){return r instanceof Uint8Array?W6(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var vV=Z0?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):_V(r,e,t):(r,e,t)=>t-e>64?x4e.decode(r.subarray(e,t)):_V(r,e,t),Y6=Z0?r=>r.length>64?globalThis.Buffer.from(r):bV(r):r=>r.length>64?S4e.encode(r):bV(r),bc=r=>Uint8Array.from(r),J0=Z0?(r,e,t)=>W6(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),xV=Z0?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),ty(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},SV=Z0?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function AV(r,e){if(W6(r)&&W6(e))return r.compare(e);for(let t=0;t>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function _V(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return eT(n)}var EV=4096;function eT(r){let e=r.length;if(e<=EV)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=J0(n,0,this.cursor)}else t=xV(this.chunks,this.cursor);return e&&this.reset(),t}};var Pe="CBOR decode error:",Mu="CBOR encode error:",ny=[];ny[23]=1;ny[24]=2;ny[25]=3;ny[26]=5;ny[27]=9;function Uu(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${Pe} encountered BigInt larger than allowable range`)}}Ts.encodedSize=function(e){return mi.encodedSize(e.value)};mi.encodedSize=function(e){return et.value?1:0};function PV(r,e,t,n){return new oe(V.negint,-1-Po(r,e+1,n),2)}function kV(r,e,t,n){return new oe(V.negint,-1-ko(r,e+1,n),3)}function NV(r,e,t,n){return new oe(V.negint,-1-No(r,e+1,n),5)}var tT=BigInt(-1),DV=BigInt(1);function OV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new oe(V.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${Pe} integers outside of the safe integer range are not supported`);return new oe(V.negint,tT-BigInt(i),9)}function Q6(r,e){let t=e.value,n=typeof t=="bigint"?t*tT-DV:t*-1-1;mi(r,e.type.majorEncoded,n)}Q6.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*tT-DV:t*-1-1;return nt.value?-1:0};function iy(r,e,t,n){Uu(r,e,t+n);let i=J0(r,e+t,e+t+n);return new oe(V.bytes,i,t+n)}function LV(r,e,t,n){return iy(r,e,1,t)}function BV(r,e,t,n){return iy(r,e,2,Po(r,e+1,n))}function MV(r,e,t,n){return iy(r,e,3,ko(r,e+1,n))}function UV(r,e,t,n){return iy(r,e,5,No(r,e+1,n))}function FV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer bytes lengths not supported`);return iy(r,e,9,i)}function X6(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===V.string?Y6(r.value):r.value),r.encodedBytes}function e1(r,e){let t=X6(e);mi(r,e.type.majorEncoded,t.length),r.push(t)}e1.encodedSize=function(e){let t=X6(e);return mi.encodedSize(t.length)+t.length};e1.compareTokens=function(e,t){return I4e(X6(e),X6(t))};function I4e(r,e){return r.lengthe.length?1:AV(r,e)}function oy(r,e,t,n,i){let o=t+n;Uu(r,e,o);let s=new oe(V.string,vV(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=J0(r,e+t,e+o)),s}function zV(r,e,t,n){return oy(r,e,1,t,n)}function VV(r,e,t,n){return oy(r,e,2,Po(r,e+1,n),n)}function KV(r,e,t,n){return oy(r,e,3,ko(r,e+1,n),n)}function $V(r,e,t,n){return oy(r,e,5,No(r,e+1,n),n)}function qV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer string lengths not supported`);return oy(r,e,9,i,n)}var HV=e1;function t1(r,e,t,n){return new oe(V.array,n,t)}function GV(r,e,t,n){return t1(r,e,1,t)}function jV(r,e,t,n){return t1(r,e,2,Po(r,e+1,n))}function WV(r,e,t,n){return t1(r,e,3,ko(r,e+1,n))}function YV(r,e,t,n){return t1(r,e,5,No(r,e+1,n))}function QV(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer array lengths not supported`);return t1(r,e,9,i)}function XV(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Pe} indefinite length items not allowed`);return t1(r,e,1,1/0)}function Z6(r,e){mi(r,V.array.majorEncoded,e.value)}Z6.compareTokens=Ts.compareTokens;Z6.encodedSize=function(e){return mi.encodedSize(e.value)};function r1(r,e,t,n){return new oe(V.map,n,t)}function ZV(r,e,t,n){return r1(r,e,1,t)}function JV(r,e,t,n){return r1(r,e,2,Po(r,e+1,n))}function eK(r,e,t,n){return r1(r,e,3,ko(r,e+1,n))}function tK(r,e,t,n){return r1(r,e,5,No(r,e+1,n))}function rK(r,e,t,n){let i=Do(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Pe} 64-bit integer map lengths not supported`);return r1(r,e,9,i)}function nK(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Pe} indefinite length items not allowed`);return r1(r,e,1,1/0)}function J6(r,e){mi(r,V.map.majorEncoded,e.value)}J6.compareTokens=Ts.compareTokens;J6.encodedSize=function(e){return mi.encodedSize(e.value)};function iK(r,e,t,n){return new oe(V.tag,t,1)}function oK(r,e,t,n){return new oe(V.tag,Po(r,e+1,n),2)}function sK(r,e,t,n){return new oe(V.tag,ko(r,e+1,n),3)}function aK(r,e,t,n){return new oe(V.tag,No(r,e+1,n),5)}function cK(r,e,t,n){return new oe(V.tag,Do(r,e+1,n),9)}function e8(r,e){mi(r,V.tag.majorEncoded,e.value)}e8.compareTokens=Ts.compareTokens;e8.encodedSize=function(e){return mi.encodedSize(e.value)};var D4e=20,O4e=21,L4e=22,B4e=23;function uK(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Pe} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new oe(V.null,null,1):new oe(V.undefined,void 0,1)}function lK(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Pe} indefinite length items not allowed`);return new oe(V.break,void 0,1)}function rT(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Pe} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Pe} Infinity values are not supported`)}return new oe(V.float,r,e)}function fK(r,e,t,n){return rT(nT(r,e+1),3,n)}function dK(r,e,t,n){return rT(iT(r,e+1),5,n)}function hK(r,e,t,n){return rT(yK(r,e+1),9,n)}function t8(r,e,t){let n=e.value;if(n===!1)r.push([V.float.majorEncoded|D4e]);else if(n===!0)r.push([V.float.majorEncoded|O4e]);else if(n===null)r.push([V.float.majorEncoded|L4e]);else if(n===void 0)r.push([V.float.majorEncoded|B4e]);else{let i,o=!1;(!t||t.float64!==!0)&&(mK(n),i=nT(Aa,1),n===i||Number.isNaN(n)?(Aa[0]=249,r.push(Aa.slice(0,3)),o=!0):(gK(n),i=iT(Aa,1),n===i&&(Aa[0]=250,r.push(Aa.slice(0,5)),o=!0))),o||(M4e(n),i=yK(Aa,1),Aa[0]=251,r.push(Aa.slice(0,9)))}}t8.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){mK(n);let i=nT(Aa,1);if(n===i||Number.isNaN(n))return 3;if(gK(n),i=iT(Aa,1),n===i)return 5}return 9};var pK=new ArrayBuffer(9),Is=new DataView(pK,1),Aa=new Uint8Array(pK,0);function mK(r){if(r===1/0)Is.setUint16(0,31744,!1);else if(r===-1/0)Is.setUint16(0,64512,!1);else if(Number.isNaN(r))Is.setUint16(0,32256,!1);else{Is.setFloat32(0,r);let e=Is.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Is.setUint16(0,31744,!1);else if(t===0)Is.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Is.setUint16(0,0):i<-14?Is.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Is.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function nT(r,e){if(r.length-e<2)throw new Error(`${Pe} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function gK(r){Is.setFloat32(0,r,!1)}function iT(r,e){if(r.length-e<4)throw new Error(`${Pe} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function M4e(r){Is.setFloat64(0,r,!1)}function yK(r,e){if(r.length-e<8)throw new Error(`${Pe} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}t8.compareTokens=Ts.compareTokens;function Jt(r,e,t){throw new Error(`${Pe} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function r8(r){return()=>{throw new Error(`${Pe} ${r}`)}}var de=[];for(let r=0;r<=23;r++)de[r]=Jt;de[24]=TV;de[25]=IV;de[26]=RV;de[27]=CV;de[28]=Jt;de[29]=Jt;de[30]=Jt;de[31]=Jt;for(let r=32;r<=55;r++)de[r]=Jt;de[56]=PV;de[57]=kV;de[58]=NV;de[59]=OV;de[60]=Jt;de[61]=Jt;de[62]=Jt;de[63]=Jt;for(let r=64;r<=87;r++)de[r]=LV;de[88]=BV;de[89]=MV;de[90]=UV;de[91]=FV;de[92]=Jt;de[93]=Jt;de[94]=Jt;de[95]=r8("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)de[r]=zV;de[120]=VV;de[121]=KV;de[122]=$V;de[123]=qV;de[124]=Jt;de[125]=Jt;de[126]=Jt;de[127]=r8("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)de[r]=GV;de[152]=jV;de[153]=WV;de[154]=YV;de[155]=QV;de[156]=Jt;de[157]=Jt;de[158]=Jt;de[159]=XV;for(let r=160;r<=183;r++)de[r]=ZV;de[184]=JV;de[185]=eK;de[186]=tK;de[187]=rK;de[188]=Jt;de[189]=Jt;de[190]=Jt;de[191]=nK;for(let r=192;r<=215;r++)de[r]=iK;de[216]=oK;de[217]=sK;de[218]=aK;de[219]=cK;de[220]=Jt;de[221]=Jt;de[222]=Jt;de[223]=Jt;for(let r=224;r<=243;r++)de[r]=r8("simple values are not supported");de[244]=Jt;de[245]=Jt;de[246]=Jt;de[247]=uK;de[248]=r8("simple values are not supported");de[249]=fK;de[250]=dK;de[251]=hK;de[252]=Jt;de[253]=Jt;de[254]=Jt;de[255]=lK;var Ta=[];for(let r=0;r<24;r++)Ta[r]=new oe(V.uint,r,1);for(let r=-1;r>=-24;r--)Ta[31-r]=new oe(V.negint,r,1);Ta[64]=new oe(V.bytes,new Uint8Array(0),1);Ta[96]=new oe(V.string,"",1);Ta[128]=new oe(V.array,0,1);Ta[160]=new oe(V.map,0,1);Ta[244]=new oe(V.false,!1,1);Ta[245]=new oe(V.true,!0,1);Ta[246]=new oe(V.null,null,1);function wK(r){switch(r.type){case V.false:return bc([244]);case V.true:return bc([245]);case V.null:return bc([246]);case V.bytes:return r.value.length?void 0:bc([64]);case V.string:return r.value===""?bc([96]):void 0;case V.array:return r.value===0?bc([128]):void 0;case V.map:return r.value===0?bc([160]):void 0;case V.uint:return r.value<24?bc([Number(r.value)]):void 0;case V.negint:if(r.value>=-24)return bc([31-Number(r.value)])}}var F4e={float64:!1,mapSorter:K4e,quickEncodeToken:wK};function z4e(){let r=[];return r[V.uint.major]=Ts,r[V.negint.major]=Q6,r[V.bytes.major]=e1,r[V.string.major]=HV,r[V.array.major]=Z6,r[V.map.major]=J6,r[V.tag.major]=e8,r[V.float.major]=t8,r}var bK=z4e(),oT=new ry,n1=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Mu} object contains circular references`);return new n1(t,e)}},ff={null:new oe(V.null,null),undefined:new oe(V.undefined,void 0),true:new oe(V.true,!0),false:new oe(V.false,!1),emptyArray:new oe(V.array,0),emptyMap:new oe(V.map,0)},df={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new oe(V.float,r):r>=0?new oe(V.uint,r):new oe(V.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new oe(V.uint,r):new oe(V.negint,r)},Uint8Array(r,e,t,n){return new oe(V.bytes,r)},string(r,e,t,n){return new oe(V.string,r)},boolean(r,e,t,n){return r?ff.true:ff.false},null(r,e,t,n){return ff.null},undefined(r,e,t,n){return ff.undefined},ArrayBuffer(r,e,t,n){return new oe(V.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new oe(V.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ff.emptyArray,new oe(V.break)]:ff.emptyArray;n=n1.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=n8(s,t,n);return t.addBreakTokens?[new oe(V.array,r.length),i,new oe(V.break)]:[new oe(V.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[ff.emptyMap,new oe(V.break)]:ff.emptyMap;n=n1.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[n8(u,t,n),n8(i?r.get(u):r[u],t,n)];return V4e(a,t),t.addBreakTokens?[new oe(V.map,s),a,new oe(V.break)]:[new oe(V.map,s),a]}};df.Map=df.Object;df.Buffer=df.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))df[`${r}Array`]=df.DataView;function n8(r,e={},t){let n=wV(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||df[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=df[n];if(!o)throw new Error(`${Mu} unsupported type: ${n}`);return o(r,n,e,t)}function V4e(r,e){e.mapSorter&&r.sort(e.mapSorter)}function K4e(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=bK[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function _K(r,e,t,n){if(Array.isArray(e))for(let i of e)_K(r,i,t,n);else t[e.type.major](r,e,n)}function sT(r,e,t){let n=n8(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new ry(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return ty(a.chunks[0])}}return oT.reset(),_K(oT,n,e,t),oT.toBytes(!0)}function aT(r,e){return e=Object.assign({},F4e,e),sT(r,bK,e)}var $4e={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},i8=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Ta[e];if(t===void 0){let n=de[e];if(!n)throw new Error(`${Pe} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},sy=Symbol.for("DONE"),o8=Symbol.for("BREAK");function q4e(r,e,t){let n=[];for(let i=0;i0)throw new Error(`${Pe} too many terminals, data makes no sense`);return t}var EK=42;function vK(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function j4e(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Xe.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new oe(V.tag,EK),new oe(V.bytes,t)]}function W4e(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Y4e(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var uT={float64:!0,typeEncoders:{Object:j4e,undefined:W4e,number:Y4e}},Q4e={...uT,typeEncoders:{...uT.typeEncoders}};function X4e(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Xe.decode(r.subarray(1))}var s8={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};s8.tags[EK]=X4e;var Z4e={...s8,tags:s8.tags.slice()},J4e="dag-cbor",lT=113,fT=r=>aT(r,uT),dT=r=>ay(vK(r),s8);var a1={};xe(a1,{code:()=>_T,decode:()=>AK,encode:()=>SK,format:()=>h6e,name:()=>d6e,parse:()=>m6e,stringify:()=>h6e});var hT=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===V.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===V.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[V.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o32?ty(n):n)}[V.array.major](e,t){this.prefix(e),this.inRecursive.push({type:V.array,elements:0}),e.push([91])}[V.map.major](e,t){this.prefix(e),this.inRecursive.push({type:V.map,elements:0}),e.push([123])}[V.tag.major](e,t){}[V.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===V.array)e.push([93]);else if(s.type===V.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Mu} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;sn)return 1;throw new Error(`${Mu} unexpected duplicate map keys, this is not supported`)}var t6e={addBreakTokens:!0,mapSorter:e6e};function pT(r,e){return e=Object.assign({},t6e,e),sT(r,new hT,e)}var s1=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new oe(V.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${Pe} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Pe} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new oe(V.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new oe(s>=0?V.uint:V.negint,s,this._pos-e):new oe(s>=0?V.uint:V.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Pe} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new oe(V.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Pe} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Pe} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Pe} unexpected unicode sequence at position ${this._pos}`);let c,u,l,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],u=this.data[this._pos+2],(c&192)===128&&(u&192)===128&&(f=(o&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${Pe} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Pe} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new oe(V.string,eT(t),this._pos-e);default:if(o<32)throw new Error(`${Pe} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${Pe} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new oe(V.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new oe(V.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new oe(V.null,null,4);case 102:return this.expect([102,97,108,115,101]),new oe(V.false,!1,5);case 116:return this.expect([116,114,117,101]),new oe(V.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${Pe} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1);if(this.ch()!==44)throw new Error(`${Pe} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1);if(this.ch()!==44)throw new Error(`${Pe} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new oe(V.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Pe} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${Pe} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function mT(r,e){return e=Object.assign({tokenizer:new s1(r,e)},e),ay(r,e)}function gh({name:r,code:e,encode:t}){return new gT(r,e,t)}var gT=class{constructor(e,t,n){B(this,"name");B(this,"code");B(this,"encode");this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?ph(this.code,t):t.then(n=>ph(this.code,n))}else throw Error("Unknown type, must be binary type")}};var yT={};xe(yT,{base64:()=>a8,base64pad:()=>n6e,base64url:()=>i6e,base64urlpad:()=>o6e});var a8=Jr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),n6e=Jr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),i6e=Jr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),o6e=Jr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function s6e(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function a6e(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Xe.asCID(r);if(!e)return null;let t=e.toString();return[new oe(V.map,1/0,1),new oe(V.string,"/",1),new oe(V.string,t,t.length),new oe(V.break,void 0,1)]}function c8(r){let e=a8.encode(r).slice(1);return[new oe(V.map,1/0,1),new oe(V.string,"/",1),new oe(V.map,1/0,1),new oe(V.string,"bytes",5),new oe(V.string,e,e.length),new oe(V.break,void 0,1),new oe(V.break,void 0,1)]}function Ia(r){return c8(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function c6e(r){return c8(new Uint8Array(r))}function u6e(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function l6e(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var f6e={typeEncoders:{Object:a6e,Buffer:c8,Uint8Array:c8,Int8Array:Ia,Uint16Array:Ia,Int16Array:Ia,Uint32Array:Ia,Int32Array:Ia,Float32Array:Ia,Float64Array:Ia,Uint8ClampedArray:Ia,BigInt64Array:Ia,BigUint64Array:Ia,DataView:Ia,ArrayBuffer:c6e,undefined:u6e,number:l6e}},wT=class extends s1{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===V.map){let t=this._next();if(t.type===V.string&&t.value==="/"){let n=this._next();if(n.type===V.string){if(this._next().type!==V.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new oe(V.tag,42,0)}if(n.type===V.map){let i=this._next();if(i.type===V.string&&i.value==="bytes"){let o=this._next();if(o.type===V.string){for(let a=0;a<2;a++)if(this._next().type!==V.break)throw new Error("Invalid encoded Bytes form");let s=a8.decode(`m${o.value}`);return new oe(V.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},bT={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};bT.tags[42]=Xe.parse;var d6e="dag-json",_T=297,SK=r=>pT(r,f6e),AK=r=>{let e=s6e(r),t=Object.assign(bT,{tokenizer:new wT(e,bT)});return mT(e,t)},h6e=r=>p6e.decode(SK(r));var p6e=new TextDecoder,m6e=r=>AK(g6e.encode(r)),g6e=new TextEncoder;var yy={};xe(yy,{code:()=>H8e,decode:()=>Y8e,encode:()=>W8e,name:()=>q8e,toGeneral:()=>Z$});var RT={};xe(RT,{base64:()=>wh,base64pad:()=>A6e,base64url:()=>u8,base64urlpad:()=>T6e});function y6e(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var w6e=y6e,b6e=w6e,TK=b6e;var yh={};xe(yh,{coerce:()=>_c,empty:()=>IK,equals:()=>ET,fromHex:()=>E6e,fromString:()=>vT,isBinary:()=>v6e,toHex:()=>_6e,toString:()=>xT});var IK=new Uint8Array(0),_6e=r=>r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),""),E6e=r=>{let e=r.match(/../g);return e?new Uint8Array(e.map(t=>parseInt(t,16))):IK},ET=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},v6e=r=>r instanceof ArrayBuffer||ArrayBuffer.isView(r),vT=r=>new TextEncoder().encode(r),xT=r=>new TextDecoder().decode(r);var ST=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},AT=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return RK(this,e)}},TT=class{constructor(e){this.decoders=e}or(e){return RK(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},RK=(r,e)=>new TT({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),IT=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new ST(e,t,n),this.decoder=new AT(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},c1=({name:r,prefix:e,encode:t,decode:n})=>new IT(r,e,t,n),hf=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=TK(t,e);return c1({prefix:r,name:e,encode:n,decode:o=>_c(i(o))})},x6e=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},S6e=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<c1({prefix:e,name:r,encode(i){return S6e(i,n,t)},decode(i){return x6e(i,n,t,r)}});var wh=tn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),A6e=tn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),u8=tn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),T6e=tn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Ra(r){return u8.encode(r).slice(1)}function Rs(r){return u8.decode(`u${r}`)}var I6e=kK,CK=128,R6e=127,C6e=~R6e,P6e=Math.pow(2,31);function kK(r,e,t){e=e||[],t=t||0;for(var n=t;r>=P6e;)e[t++]=r&255|CK,r/=128;for(;r&C6e;)e[t++]=r&255|CK,r>>>=7;return e[t]=r|0,kK.bytes=t-n+1,e}var k6e=CT,N6e=128,PK=127;function CT(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw CT.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&PK)<=N6e);return CT.bytes=o-n,t}var D6e=Math.pow(2,7),O6e=Math.pow(2,14),L6e=Math.pow(2,21),B6e=Math.pow(2,28),M6e=Math.pow(2,35),U6e=Math.pow(2,42),F6e=Math.pow(2,49),z6e=Math.pow(2,56),V6e=Math.pow(2,63),K6e=function(r){return r[cy.decode(r,e),cy.decode.bytes],u1=(r,e,t=0)=>(cy.encode(r,e,t),e),l1=r=>cy.encodingLength(r);var Ec=(r,e)=>{let t=e.byteLength,n=l1(r),i=n+l1(t),o=new Uint8Array(i+t);return u1(r,o,0),u1(t,o,n),o.set(e,i),new f1(r,t,e,o)},Jn=r=>{let e=_c(r),[t,n]=uy(e),[i,o]=uy(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new f1(t,i,s,e)},NK=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ET(r.bytes,t.bytes)}},f1=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var PT={};xe(PT,{base58btc:()=>tt,base58flickr:()=>H6e});var tt=hf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),H6e=hf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var NT={};xe(NT,{base32:()=>Ot,base32hex:()=>W6e,base32hexpad:()=>Q6e,base32hexpadupper:()=>X6e,base32hexupper:()=>Y6e,base32pad:()=>kT,base32padupper:()=>j6e,base32upper:()=>G6e,base32z:()=>Z6e});var Ot=tn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),G6e=tn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kT=tn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),j6e=tn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),W6e=tn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Y6e=tn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Q6e=tn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),X6e=tn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z6e=tn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var DK=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return e8e(t,DT(r),e||tt.encoder);default:return t8e(t,DT(r),e||Ot.encoder)}};var OK=new WeakMap,DT=r=>{let e=OK.get(r);if(e==null){let t=new Map;return OK.set(r,t),t}return e},ce=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:t}=this;if(e!==ly)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==r8e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ce.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:{let{code:e,digest:t}=this.multihash,n=Ec(e,t);return ce.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return ce.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&NK(e.multihash,n.multihash)}toString(e){return DK(this,e)}toJSON(){return{"/":DK(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof ce)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new ce(n,i,o,s||LK(n,i,o.bytes))}else if(t[n8e]===!0){let{version:n,multihash:i,code:o}=t,s=Jn(i);return ce.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ly)throw new Error(`Version 0 CID must use dag-pb (code: ${ly}) block encoding`);return new ce(e,t,n,n.bytes)}case 1:{let i=LK(e,t,n.bytes);return new ce(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ce.create(0,ly,e)}static createV1(e,t){return ce.create(1,e,t)}static decode(e){let[t,n]=ce.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ce.inspectBytes(e),n=t.size-t.multihashSize,i=_c(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new f1(t.multihashCode,t.digestSize,o,i);return[t.version===0?ce.createV0(s):ce.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=uy(e.subarray(t));return t+=h,f},i=n(),o=ly;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=J6e(e,t),o=ce.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return DT(o).set(n,e),o}},J6e=(r,e)=>{switch(r[0]){case"Q":{let t=e||tt;return[tt.prefix,t.decode(`${tt.prefix}${r}`)]}case tt.prefix:{let t=e||tt;return[tt.prefix,t.decode(r)]}case Ot.prefix:{let t=e||Ot;return[Ot.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},e8e=(r,e,t)=>{let{prefix:n}=t;if(n!==tt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},t8e=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},ly=112,r8e=18,LK=(r,e,t)=>{let n=l1(r),i=n+l1(e),o=new Uint8Array(i+t.byteLength);return u1(r,o,0),u1(e,o,n),o.set(t,i),o},n8e=Symbol.for("@ipld/js-cid/CID");function BK(r){let[e,t,n]=r;return{payload:t,signatures:[{protected:e,signature:n}],link:ce.decode(Rs(t))}}function i8e(r){let e={signature:Rs(r.signature)};return r.header&&(e.header=r.header),r.protected&&(e.protected=Rs(r.protected)),e}function MK(r){let e=Rs(r.payload);try{ce.decode(e)}catch{throw new Error("Not a valid DagJWS")}return{payload:e,signatures:r.signatures.map(i8e)}}function o8e(r){let e={signature:Ra(r.signature)};return r.header&&(e.header=r.header),r.protected&&(e.protected=Ra(r.protected)),e}function UK(r){let e={payload:Ra(r.payload),signatures:r.signatures.map(o8e)};return e.link=ce.decode(new Uint8Array(r.payload)),e}function FK(r){let[e,t,n,i,o]=r,s={ciphertext:i,iv:n,protected:e,tag:o};return t&&(s.recipients=[{encrypted_key:t}]),s}function a8e(r){let e={};return r.encrypted_key&&(e.encrypted_key=Rs(r.encrypted_key)),r.header&&(e.header=r.header),e}function zK(r){let e={ciphertext:Rs(r.ciphertext),protected:Rs(r.protected),iv:Rs(r.iv),tag:Rs(r.tag)};return r.aad&&(e.aad=Rs(r.aad)),r.recipients&&(e.recipients=r.recipients.map(a8e)),r.unprotected&&(e.unprotected=r.unprotected),e}function c8e(r){let e={};return r.encrypted_key&&(e.encrypted_key=Ra(r.encrypted_key)),r.header&&(e.header=r.header),e}function VK(r){let e={ciphertext:Ra(r.ciphertext),protected:Ra(r.protected),iv:Ra(r.iv),tag:Ra(r.tag)};return r.aad&&(e.aad=Ra(r.aad)),r.recipients&&(e.recipients=r.recipients.map(c8e)),r.unprotected&&(e.unprotected=r.unprotected),e}var l8e=["string","number","bigint","symbol"],f8e=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function KK(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(l8e.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(d8e(r))return"Buffer";let t=h8e(r);return t||"Object"}function d8e(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function h8e(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(f8e.includes(e))return e}var Q=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};Q.uint=new Q(0,"uint",!0);Q.negint=new Q(1,"negint",!0);Q.bytes=new Q(2,"bytes",!0);Q.string=new Q(3,"string",!0);Q.array=new Q(4,"array",!1);Q.map=new Q(5,"map",!1);Q.tag=new Q(6,"tag",!1);Q.float=new Q(7,"float",!0);Q.false=new Q(7,"false",!0);Q.true=new Q(7,"true",!0);Q.null=new Q(7,"null",!0);Q.undefined=new Q(7,"undefined",!0);Q.break=new Q(7,"break",!0);var Se=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var d1=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",p8e=new TextDecoder,m8e=new TextEncoder;function f8(r){return d1&&globalThis.Buffer.isBuffer(r)}function OT(r){return r instanceof Uint8Array?f8(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var GK=d1?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):qK(r,e,t):(r,e,t)=>t-e>64?p8e.decode(r.subarray(e,t)):qK(r,e,t),jK=d1?r=>r.length>64?globalThis.Buffer.from(r):$K(r):r=>r.length>64?m8e.encode(r):$K(r),vc=r=>Uint8Array.from(r),h1=d1?(r,e,t)=>f8(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),WK=d1?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),OT(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},YK=d1?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function QK(r,e){if(f8(r)&&f8(e))return r.compare(e);for(let t=0;t55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function qK(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return g8e(n)}var HK=4096;function g8e(r){let e=r.length;if(e<=HK)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=h1(n,0,this.cursor)}else t=WK(this.chunks,this.cursor);return e&&this.reset(),t}};var nt="CBOR decode error:",LT="CBOR encode error:",dy=[];dy[23]=1;dy[24]=2;dy[25]=3;dy[26]=5;dy[27]=9;function Fu(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${nt} encountered BigInt larger than allowable range`)}}Cs.encodedSize=function(e){return gi.encodedSize(e.value)};gi.encodedSize=function(e){return et.value?1:0};function t$(r,e,t,n){return new Se(Q.negint,-1-Lo(r,e+1,n),2)}function r$(r,e,t,n){return new Se(Q.negint,-1-Bo(r,e+1,n),3)}function n$(r,e,t,n){return new Se(Q.negint,-1-Mo(r,e+1,n),5)}var BT=BigInt(-1),i$=BigInt(1);function o$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new Se(Q.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${nt} integers outside of the safe integer range are not supported`);return new Se(Q.negint,BT-BigInt(i),9)}function d8(r,e){let t=e.value,n=typeof t=="bigint"?t*BT-i$:t*-1-1;gi(r,e.type.majorEncoded,n)}d8.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*BT-i$:t*-1-1;return nt.value?-1:0};function hy(r,e,t,n){Fu(r,e,t+n);let i=h1(r,e+t,e+t+n);return new Se(Q.bytes,i,t+n)}function s$(r,e,t,n){return hy(r,e,1,t)}function a$(r,e,t,n){return hy(r,e,2,Lo(r,e+1,n))}function c$(r,e,t,n){return hy(r,e,3,Bo(r,e+1,n))}function u$(r,e,t,n){return hy(r,e,5,Mo(r,e+1,n))}function l$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer bytes lengths not supported`);return hy(r,e,9,i)}function h8(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===Q.string?jK(r.value):r.value),r.encodedBytes}function p1(r,e){let t=h8(e);gi(r,e.type.majorEncoded,t.length),r.push(t)}p1.encodedSize=function(e){let t=h8(e);return gi.encodedSize(t.length)+t.length};p1.compareTokens=function(e,t){return b8e(h8(e),h8(t))};function b8e(r,e){return r.lengthe.length?1:QK(r,e)}function py(r,e,t,n,i){let o=t+n;Fu(r,e,o);let s=new Se(Q.string,GK(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=h1(r,e+t,e+o)),s}function f$(r,e,t,n){return py(r,e,1,t,n)}function d$(r,e,t,n){return py(r,e,2,Lo(r,e+1,n),n)}function h$(r,e,t,n){return py(r,e,3,Bo(r,e+1,n),n)}function p$(r,e,t,n){return py(r,e,5,Mo(r,e+1,n),n)}function m$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer string lengths not supported`);return py(r,e,9,i,n)}var g$=p1;function m1(r,e,t,n){return new Se(Q.array,n,t)}function y$(r,e,t,n){return m1(r,e,1,t)}function w$(r,e,t,n){return m1(r,e,2,Lo(r,e+1,n))}function b$(r,e,t,n){return m1(r,e,3,Bo(r,e+1,n))}function _$(r,e,t,n){return m1(r,e,5,Mo(r,e+1,n))}function E$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer array lengths not supported`);return m1(r,e,9,i)}function v$(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${nt} indefinite length items not allowed`);return m1(r,e,1,1/0)}function p8(r,e){gi(r,Q.array.majorEncoded,e.value)}p8.compareTokens=Cs.compareTokens;p8.encodedSize=function(e){return gi.encodedSize(e.value)};function g1(r,e,t,n){return new Se(Q.map,n,t)}function x$(r,e,t,n){return g1(r,e,1,t)}function S$(r,e,t,n){return g1(r,e,2,Lo(r,e+1,n))}function A$(r,e,t,n){return g1(r,e,3,Bo(r,e+1,n))}function T$(r,e,t,n){return g1(r,e,5,Mo(r,e+1,n))}function I$(r,e,t,n){let i=Uo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${nt} 64-bit integer map lengths not supported`);return g1(r,e,9,i)}function R$(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${nt} indefinite length items not allowed`);return g1(r,e,1,1/0)}function m8(r,e){gi(r,Q.map.majorEncoded,e.value)}m8.compareTokens=Cs.compareTokens;m8.encodedSize=function(e){return gi.encodedSize(e.value)};function C$(r,e,t,n){return new Se(Q.tag,t,1)}function P$(r,e,t,n){return new Se(Q.tag,Lo(r,e+1,n),2)}function k$(r,e,t,n){return new Se(Q.tag,Bo(r,e+1,n),3)}function N$(r,e,t,n){return new Se(Q.tag,Mo(r,e+1,n),5)}function D$(r,e,t,n){return new Se(Q.tag,Uo(r,e+1,n),9)}function g8(r,e){gi(r,Q.tag.majorEncoded,e.value)}g8.compareTokens=Cs.compareTokens;g8.encodedSize=function(e){return gi.encodedSize(e.value)};var A8e=20,T8e=21,I8e=22,R8e=23;function O$(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${nt} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Se(Q.null,null,1):new Se(Q.undefined,void 0,1)}function L$(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${nt} indefinite length items not allowed`);return new Se(Q.break,void 0,1)}function MT(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${nt} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${nt} Infinity values are not supported`)}return new Se(Q.float,r,e)}function B$(r,e,t,n){return MT(UT(r,e+1),3,n)}function M$(r,e,t,n){return MT(FT(r,e+1),5,n)}function U$(r,e,t,n){return MT(K$(r,e+1),9,n)}function y8(r,e,t){let n=e.value;if(n===!1)r.push([Q.float.majorEncoded|A8e]);else if(n===!0)r.push([Q.float.majorEncoded|T8e]);else if(n===null)r.push([Q.float.majorEncoded|I8e]);else if(n===void 0)r.push([Q.float.majorEncoded|R8e]);else{let i,o=!1;(!t||t.float64!==!0)&&(z$(n),i=UT(Ca,1),n===i||Number.isNaN(n)?(Ca[0]=249,r.push(Ca.slice(0,3)),o=!0):(V$(n),i=FT(Ca,1),n===i&&(Ca[0]=250,r.push(Ca.slice(0,5)),o=!0))),o||(C8e(n),i=K$(Ca,1),Ca[0]=251,r.push(Ca.slice(0,9)))}}y8.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){z$(n);let i=UT(Ca,1);if(n===i||Number.isNaN(n))return 3;if(V$(n),i=FT(Ca,1),n===i)return 5}return 9};var F$=new ArrayBuffer(9),Ps=new DataView(F$,1),Ca=new Uint8Array(F$,0);function z$(r){if(r===1/0)Ps.setUint16(0,31744,!1);else if(r===-1/0)Ps.setUint16(0,64512,!1);else if(Number.isNaN(r))Ps.setUint16(0,32256,!1);else{Ps.setFloat32(0,r);let e=Ps.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ps.setUint16(0,31744,!1);else if(t===0)Ps.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Ps.setUint16(0,0):i<-14?Ps.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ps.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function UT(r,e){if(r.length-e<2)throw new Error(`${nt} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function V$(r){Ps.setFloat32(0,r,!1)}function FT(r,e){if(r.length-e<4)throw new Error(`${nt} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function C8e(r){Ps.setFloat64(0,r,!1)}function K$(r,e){if(r.length-e<8)throw new Error(`${nt} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}y8.compareTokens=Cs.compareTokens;function er(r,e,t){throw new Error(`${nt} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function w8(r){return()=>{throw new Error(`${nt} ${r}`)}}var he=[];for(let r=0;r<=23;r++)he[r]=er;he[24]=XK;he[25]=ZK;he[26]=JK;he[27]=e$;he[28]=er;he[29]=er;he[30]=er;he[31]=er;for(let r=32;r<=55;r++)he[r]=er;he[56]=t$;he[57]=r$;he[58]=n$;he[59]=o$;he[60]=er;he[61]=er;he[62]=er;he[63]=er;for(let r=64;r<=87;r++)he[r]=s$;he[88]=a$;he[89]=c$;he[90]=u$;he[91]=l$;he[92]=er;he[93]=er;he[94]=er;he[95]=w8("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)he[r]=f$;he[120]=d$;he[121]=h$;he[122]=p$;he[123]=m$;he[124]=er;he[125]=er;he[126]=er;he[127]=w8("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)he[r]=y$;he[152]=w$;he[153]=b$;he[154]=_$;he[155]=E$;he[156]=er;he[157]=er;he[158]=er;he[159]=v$;for(let r=160;r<=183;r++)he[r]=x$;he[184]=S$;he[185]=A$;he[186]=T$;he[187]=I$;he[188]=er;he[189]=er;he[190]=er;he[191]=R$;for(let r=192;r<=215;r++)he[r]=C$;he[216]=P$;he[217]=k$;he[218]=N$;he[219]=D$;he[220]=er;he[221]=er;he[222]=er;he[223]=er;for(let r=224;r<=243;r++)he[r]=w8("simple values are not supported");he[244]=er;he[245]=er;he[246]=er;he[247]=O$;he[248]=w8("simple values are not supported");he[249]=B$;he[250]=M$;he[251]=U$;he[252]=er;he[253]=er;he[254]=er;he[255]=L$;var Pa=[];for(let r=0;r<24;r++)Pa[r]=new Se(Q.uint,r,1);for(let r=-1;r>=-24;r--)Pa[31-r]=new Se(Q.negint,r,1);Pa[64]=new Se(Q.bytes,new Uint8Array(0),1);Pa[96]=new Se(Q.string,"",1);Pa[128]=new Se(Q.array,0,1);Pa[160]=new Se(Q.map,0,1);Pa[244]=new Se(Q.false,!1,1);Pa[245]=new Se(Q.true,!0,1);Pa[246]=new Se(Q.null,null,1);function $$(r){switch(r.type){case Q.false:return vc([244]);case Q.true:return vc([245]);case Q.null:return vc([246]);case Q.bytes:return r.value.length?void 0:vc([64]);case Q.string:return r.value===""?vc([96]):void 0;case Q.array:return r.value===0?vc([128]):void 0;case Q.map:return r.value===0?vc([160]):void 0;case Q.uint:return r.value<24?vc([Number(r.value)]):void 0;case Q.negint:if(r.value>=-24)return vc([31-Number(r.value)])}}var k8e={float64:!1,mapSorter:O8e,quickEncodeToken:$$};function N8e(){let r=[];return r[Q.uint.major]=Cs,r[Q.negint.major]=d8,r[Q.bytes.major]=p1,r[Q.string.major]=g$,r[Q.array.major]=p8,r[Q.map.major]=m8,r[Q.tag.major]=g8,r[Q.float.major]=y8,r}var q$=N8e(),zT=new fy,y1=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${LT} object contains circular references`);return new y1(t,e)}},pf={null:new Se(Q.null,null),undefined:new Se(Q.undefined,void 0),true:new Se(Q.true,!0),false:new Se(Q.false,!1),emptyArray:new Se(Q.array,0),emptyMap:new Se(Q.map,0)},mf={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Se(Q.float,r):r>=0?new Se(Q.uint,r):new Se(Q.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Se(Q.uint,r):new Se(Q.negint,r)},Uint8Array(r,e,t,n){return new Se(Q.bytes,r)},string(r,e,t,n){return new Se(Q.string,r)},boolean(r,e,t,n){return r?pf.true:pf.false},null(r,e,t,n){return pf.null},undefined(r,e,t,n){return pf.undefined},ArrayBuffer(r,e,t,n){return new Se(Q.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Se(Q.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[pf.emptyArray,new Se(Q.break)]:pf.emptyArray;n=y1.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=b8(s,t,n);return t.addBreakTokens?[new Se(Q.array,r.length),i,new Se(Q.break)]:[new Se(Q.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[pf.emptyMap,new Se(Q.break)]:pf.emptyMap;n=y1.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[b8(u,t,n),b8(i?r.get(u):r[u],t,n)];return D8e(a,t),t.addBreakTokens?[new Se(Q.map,s),a,new Se(Q.break)]:[new Se(Q.map,s),a]}};mf.Map=mf.Object;mf.Buffer=mf.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))mf[`${r}Array`]=mf.DataView;function b8(r,e={},t){let n=KK(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||mf[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=mf[n];if(!o)throw new Error(`${LT} unsupported type: ${n}`);return o(r,n,e,t)}function D8e(r,e){e.mapSorter&&r.sort(e.mapSorter)}function O8e(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=q$[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function H$(r,e,t,n){if(Array.isArray(e))for(let i of e)H$(r,i,t,n);else t[e.type.major](r,e,n)}function L8e(r,e,t){let n=b8(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new fy(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return OT(a.chunks[0])}}return zT.reset(),H$(zT,n,e,t),zT.toBytes(!0)}function zu(r,e){return e=Object.assign({},k8e,e),L8e(r,q$,e)}var B8e={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},VT=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=Pa[e];if(t===void 0){let n=he[e];if(!n)throw new Error(`${nt} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},my=Symbol.for("DONE"),_8=Symbol.for("BREAK");function M8e(r,e,t){let n=[];for(let i=0;izu(r,K8e),E8=r=>ks(r,j$);var q8e="dag-jose",H8e=133;function Q$(r){return"payload"in r&&typeof r.payload=="string"&&"signatures"in r&&Array.isArray(r.signatures)}function G8e(r){return"payload"in r&&r.payload instanceof Uint8Array&&"signatures"in r&&Array.isArray(r.signatures)}function j8e(r){return"ciphertext"in r&&r.ciphertext instanceof Uint8Array&&"iv"in r&&r.iv instanceof Uint8Array&&"protected"in r&&r.protected instanceof Uint8Array&&"tag"in r&&r.tag instanceof Uint8Array}function X$(r){return"ciphertext"in r&&typeof r.ciphertext=="string"&&"iv"in r&&typeof r.iv=="string"&&"protected"in r&&typeof r.protected=="string"&&"tag"in r&&typeof r.tag=="string"}function Z$(r){if(typeof r=="string"){let e=r.split(".");if(e.length===3)return BK(e);if(e.length===5)return FK(e);throw new Error("Not a valid JOSE string")}if(Q$(r)||X$(r))return r;throw new Error("Not a valid unencoded JOSE object")}function W8e(r){typeof r=="string"&&(r=Z$(r));let e;if(Q$(r))e=MK(r);else if(X$(r))e=zK(r);else throw new Error("Not a valid JOSE object");return new Uint8Array(Y$(e))}function Y8e(r){let e;try{e=E8(r)}catch{throw new Error("Not a valid DAG-JOSE object")}if(G8e(e))return UK(e);if(j8e(e))return VK(e);throw new Error("Not a valid DAG-JOSE object")}var qT={};xe(qT,{identity:()=>Ii});var J$=0,Q8e="identity",eq=_a,X8e=r=>hc(J$,eq(r)),Ii={code:J$,name:Q8e,encode:eq,digest:X8e};var HT={};xe(HT,{identity:()=>Z8e});var Z8e=M0({prefix:"\0",name:"identity",encode:r=>WU(r),decode:r=>jU(r)});var GT={};xe(GT,{base2:()=>J8e});var J8e=Zr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jT={};xe(jT,{base8:()=>ebe});var ebe=Zr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var WT={};xe(WT,{base10:()=>tbe});var tbe=tf({prefix:"9",name:"base10",alphabet:"0123456789"});var YT={};xe(YT,{base16:()=>rbe,base16upper:()=>nbe});var rbe=Zr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nbe=Zr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var QT={};xe(QT,{base36:()=>w1,base36upper:()=>ibe});var w1=tf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ibe=tf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var XT={};xe(XT,{base256emoji:()=>ube});var tq=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),obe=tq.reduce((r,e,t)=>(r[t]=e,r),[]),sbe=tq.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function abe(r){return r.reduce((e,t)=>(e+=obe[t],e),"")}function cbe(r){let e=[];for(let t of r){let n=sbe[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var ube=M0({prefix:"\u{1F680}",name:"base256emoji",encode:abe,decode:cbe});var yf={};xe(yf,{code:()=>gf,decode:()=>dbe,encode:()=>fbe,name:()=>lbe});var lbe="raw",gf=85,fbe=r=>_a(r),dbe=r=>_a(r);var Vu={...HT,...GT,...jT,...WT,...YT,...lA,...QT,...cA,...SA,...XT},v8={...mA,...qT},x8={raw:yf,json:Vg};var Ku=class extends Error{constructor(e="not initialized"){super(e),this.name="NotInitializedError",this.code=Ku.code}};Ku.code="ERR_NOT_INITIALIZED";var ZT=class extends Error{constructor(e="cannot initialize an initializing node"){super(e),this.name="AlreadyInitializingError",this.code=ka.code}};ZT.code="ERR_ALREADY_INITIALIZING";var ka=class extends Error{constructor(e="cannot re-initialize an initialized node"){super(e),this.name="AlreadyInitializedError",this.code=ka.code}};ka.code="ERR_ALREADY_INITIALIZED";var $u=class extends Error{constructor(e="not started"){super(e),this.name="NotStartedError",this.code=$u.code}};$u.code="ERR_NOT_STARTED";var _h=class extends Error{constructor(e="cannot start, already startin"){super(e),this.name="AlreadyStartingError",this.code=_h.code}};_h.code="ERR_ALREADY_STARTING";var Eh=class extends Error{constructor(e="cannot start, already started"){super(e),this.name="AlreadyStartedError",this.code=Eh.code}};Eh.code="ERR_ALREADY_STARTED";var Na=class extends Error{constructor(e="not enabled"){super(e),this.name="NotEnabledError",this.code=Na.code}};Na.code="ERR_NOT_ENABLED";function wf(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var nI={};xe(nI,{base10:()=>wbe});function hbe(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,y=new Uint8Array(m);_!==x;){for(var b=p[_],E=0,v=m-1;(b!==0||E>>0,y[v]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");w=E,_++}for(var S=m-w;S!==m&&y[S]===0;)S++;for(var A=c.repeat(g);S>>0,m=new Uint8Array(x);p[g];){var y=t[p.charCodeAt(g)];if(y===255)return;for(var b=0,E=x-1;(y!==0||b<_)&&E!==-1;E--,b++)y+=a*m[E]>>>0,m[E]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");_=b,g++}if(p[g]!==" "){for(var v=x-_;v!==x&&m[v]===0;)v++;for(var S=new Uint8Array(w+(x-v)),A=w;v!==x;)S[A++]=m[v++];return S}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var pbe=hbe,mbe=pbe,rq=mbe;var EZe=new Uint8Array(0);var nq=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var iq=r=>new TextEncoder().encode(r),oq=r=>new TextDecoder().decode(r);var JT=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},eI=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return aq(this,e)}},tI=class{constructor(e){this.decoders=e}or(e){return aq(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},aq=(r,e)=>new tI({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),rI=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new JT(e,t,n),this.decoder=new eI(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},b1=({name:r,prefix:e,encode:t,decode:n})=>new rI(r,e,t,n),bf=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=rq(t,e);return b1({prefix:r,name:e,encode:n,decode:o=>qu(i(o))})},gbe=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},ybe=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<b1({prefix:e,name:r,encode(i){return ybe(i,n,t)},decode(i){return gbe(i,n,t,r)}});var wbe=bf({prefix:"9",name:"base10",alphabet:"0123456789"});var iI={};xe(iI,{base16:()=>bbe,base16upper:()=>_be});var bbe=rn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_be=rn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var oI={};xe(oI,{base2:()=>Ebe});var Ebe=rn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sI={};xe(sI,{base256emoji:()=>Tbe});var cq=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),vbe=cq.reduce((r,e,t)=>(r[t]=e,r),[]),xbe=cq.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Sbe(r){return r.reduce((e,t)=>(e+=vbe[t],e),"")}function Abe(r){let e=[];for(let t of r){let n=xbe[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Tbe=b1({prefix:"\u{1F680}",name:"base256emoji",encode:Sbe,decode:Abe});var aI={};xe(aI,{base32:()=>_f,base32hex:()=>Pbe,base32hexpad:()=>Nbe,base32hexpadupper:()=>Dbe,base32hexupper:()=>kbe,base32pad:()=>Rbe,base32padupper:()=>Cbe,base32upper:()=>Ibe,base32z:()=>Obe});var _f=rn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ibe=rn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Rbe=rn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Cbe=rn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pbe=rn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kbe=rn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nbe=rn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Dbe=rn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Obe=rn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var cI={};xe(cI,{base36:()=>Lbe,base36upper:()=>Bbe});var Lbe=bf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Bbe=bf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var uI={};xe(uI,{base58btc:()=>Qi,base58flickr:()=>Mbe});var Qi=bf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mbe=bf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fI={};xe(fI,{base64:()=>lI,base64pad:()=>Ube,base64url:()=>Fbe,base64urlpad:()=>zbe});var lI=rn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ube=rn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fbe=rn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zbe=rn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dI={};xe(dI,{base8:()=>Vbe});var Vbe=rn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hI={};xe(hI,{identity:()=>Kbe});var Kbe=b1({prefix:"\0",name:"identity",encode:r=>oq(r),decode:r=>iq(r)});var BZe=new TextEncoder,MZe=new TextDecoder;var mI={};xe(mI,{identity:()=>A8});var Hbe=fq,uq=128,Gbe=127,jbe=~Gbe,Wbe=Math.pow(2,31);function fq(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Wbe;)e[t++]=r&255|uq,r/=128;for(;r&jbe;)e[t++]=r&255|uq,r>>>=7;return e[t]=r|0,fq.bytes=t-n+1,e}var Ybe=pI,Qbe=128,lq=127;function pI(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw pI.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&lq)<=Qbe);return pI.bytes=o-n,t}var Xbe=Math.pow(2,7),Zbe=Math.pow(2,14),Jbe=Math.pow(2,21),e_e=Math.pow(2,28),t_e=Math.pow(2,35),r_e=Math.pow(2,42),n_e=Math.pow(2,49),i_e=Math.pow(2,56),o_e=Math.pow(2,63),s_e=function(r){return r[wy.decode(r,e),wy.decode.bytes],_1=(r,e,t=0)=>(wy.encode(r,e,t),e),E1=r=>wy.encodingLength(r);var Ef=(r,e)=>{let t=e.byteLength,n=E1(r),i=n+E1(t),o=new Uint8Array(i+t);return _1(r,o,0),_1(t,o,n),o.set(e,i),new v1(r,t,e,o)},_y=r=>{let e=qu(r),[t,n]=by(e),[i,o]=by(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new v1(t,i,s,e)},dq=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&nq(r.bytes,t.bytes)}},v1=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var hq=0,u_e="identity",pq=qu,l_e=r=>Ef(hq,pq(r)),A8={code:hq,name:u_e,encode:pq,digest:l_e};var wI={};xe(wI,{sha256:()=>T8,sha512:()=>f_e});var yI=({name:r,code:e,encode:t})=>new gI(r,e,t),gI=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Ef(this.code,t):t.then(n=>Ef(this.code,n))}else throw Error("Unknown type, must be binary type")}};var gq=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),T8=yI({name:"sha2-256",code:18,encode:gq("SHA-256")}),f_e=yI({name:"sha2-512",code:19,encode:gq("SHA-512")});var yq=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return h_e(t,bI(r),e||Qi.encoder);default:return p_e(t,bI(r),e||_f.encoder)}};var wq=new WeakMap,bI=r=>{let e=wq.get(r);if(e==null){let t=new Map;return wq.set(r,t),t}return e},Nr=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:{let{code:e,multihash:t}=this;if(e!==Ey)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==m_e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Nr.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:{let{code:e,digest:t}=this.multihash,n=Ef(e,t);return Nr.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return Nr.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&dq(e.multihash,n.multihash)}toString(e){return yq(this,e)}toJSON(){return{"/":yq(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof Nr)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new Nr(n,i,o,s||bq(n,i,o.bytes))}else if(t[g_e]===!0){let{version:n,multihash:i,code:o}=t,s=_y(i);return Nr.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ey)throw new Error(`Version 0 CID must use dag-pb (code: ${Ey}) block encoding`);return new Nr(e,t,n,n.bytes)}case 1:{let i=bq(e,t,n.bytes);return new Nr(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return Nr.create(0,Ey,e)}static createV1(e,t){return Nr.create(1,e,t)}static decode(e){let[t,n]=Nr.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=Nr.inspectBytes(e),n=t.size-t.multihashSize,i=qu(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new v1(t.multihashCode,t.digestSize,o,i);return[t.version===0?Nr.createV0(s):Nr.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=by(e.subarray(t));return t+=h,f},i=n(),o=Ey;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=d_e(e,t),o=Nr.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bI(o).set(n,e),o}},d_e=(r,e)=>{switch(r[0]){case"Q":{let t=e||Qi;return[Qi.prefix,t.decode(`${Qi.prefix}${r}`)]}case Qi.prefix:{let t=e||Qi;return[Qi.prefix,t.decode(r)]}case _f.prefix:{let t=e||_f;return[_f.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},h_e=(r,e,t)=>{let{prefix:n}=t;if(n!==Qi.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i},p_e=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i},Ey=112,m_e=18,bq=(r,e,t)=>{let n=E1(r),i=n+E1(e),o=new Uint8Array(i+t.byteLength);return _1(r,o,0),_1(e,o,n),o.set(t,i),o},g_e=Symbol.for("@ipld/js-cid/CID");var S1={...hI,...oI,...dI,...nI,...iI,...aI,...cI,...uI,...fI,...sI},JZe={...wI,...mI};function vf(r=0){var e;return((e=globalThis.Buffer)==null?void 0:e.allocUnsafe)!=null?wf(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Eq(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var _q=Eq("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_I=Eq("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=vf(r.length);for(let t=0;t__e});var __e=cf({prefix:"9",name:"base10",alphabet:"0123456789"});var SI={};xe(SI,{base16:()=>E_e,base16upper:()=>v_e});var E_e=Jr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),v_e=Jr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var AI={};xe(AI,{base2:()=>x_e});var x_e=Jr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var TI={};xe(TI,{base256emoji:()=>R_e});var Iq=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),S_e=Iq.reduce((r,e,t)=>(r[t]=e,r),[]),A_e=Iq.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function T_e(r){return r.reduce((e,t)=>(e+=S_e[t],e),"")}function I_e(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=A_e[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var R_e=j0({prefix:"\u{1F680}",name:"base256emoji",encode:T_e,decode:I_e});var II={};xe(II,{base8:()=>C_e});var C_e=Jr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var RI={};xe(RI,{identity:()=>P_e});var P_e=j0({prefix:"\0",name:"identity",encode:r=>VA(r),decode:r=>zA(r)});var _Je=new TextEncoder,EJe=new TextDecoder;var CI={};xe(CI,{identity:()=>L_e});var Rq=0,D_e="identity",Cq=yc;function O_e(r){return ph(Rq,Cq(r))}var L_e={code:Rq,name:D_e,encode:Cq,digest:O_e};var PI={};xe(PI,{sha256:()=>B_e,sha512:()=>M_e});function Pq(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var B_e=gh({name:"sha2-256",code:18,encode:Pq("SHA-256")}),M_e=gh({name:"sha2-512",code:19,encode:Pq("SHA-512")});var xy={...RI,...AI,...II,...xI,...SI,...GA,...jA,...WA,...yT,...TI},TJe={...PI,...CI};function Hu(r=0){return new Uint8Array(r)}function Ri(r=0){return new Uint8Array(r)}function Nq(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var kq=Nq("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),kI=Nq("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=Ri(r.length);for(let t=0;tNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function BI(r,e,t=0){switch(ti(r)){case 8:e[t++]=r&255|ar,r/=128;case 7:e[t++]=r&255|ar,r/=128;case 6:e[t++]=r&255|ar,r/=128;case 5:e[t++]=r&255|ar,r/=128;case 4:e[t++]=r&255|ar,r>>>=7;case 3:e[t++]=r&255|ar,r>>>=7;case 2:e[t++]=r&255|ar,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function K_e(r,e,t=0){switch(ti(r)){case 8:e.set(t++,r&255|ar),r/=128;case 7:e.set(t++,r&255|ar),r/=128;case 6:e.set(t++,r&255|ar),r/=128;case 5:e.set(t++,r&255|ar),r/=128;case 4:e.set(t++,r&255|ar),r>>>=7;case 3:e.set(t++,r&255|ar),r>>>=7;case 2:e.set(t++,r&255|ar),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function MI(r,e){let t=r[e],n=0;if(n+=t&Ci,ti+o.length,0));let t=Ri(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var N8=class{constructor(){B(this,"index",0);B(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let 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(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=e,o+=l,o>u||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;nthis.readIPv4Addr());if(s!==void 0)return t[i]=s[0],t[i+1]=s[1],t[i+2]=s[2],t[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];t[i]=o>>8,t[i+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Dq=45,q_e=15,A1=new N8;function UI(r){if(!(r.length>q_e))return A1.new(r).parseWith(()=>A1.readIPv4Addr())}function FI(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dq))return A1.new(r).parseWith(()=>A1.readIPv6Addr())}function D8(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dq))return A1.new(r).parseWith(()=>A1.readIPAddr())}var QJe=parseInt("0xFFFF",16),XJe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function cr(r,e="utf8"){let t=P8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function O8(r){return!!UI(r)}function L8(r){return!!FI(r)}function xc(r){return!!D8(r)}var Bq=O8,Y_e=L8,zI=function(r){let e=0;if(r=r.toString().trim(),Bq(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Y_e(r)){let t=r.split(":",8),n;for(n=0;n0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},Mq=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let o=0;o{let e=Z_e(...r);VI[e.code]=e,T1[e.name]=e});function Z_e(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function Lt(r){if(typeof r=="number"){if(VI[r]!=null)return VI[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(T1[r]!=null)return T1[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Uet=Lt("ip4"),Fet=Lt("ip6"),zet=Lt("ipcidr");function Sy(r,e){switch(Lt(r).code){case 4:case 41:return eEe(e);case 42:return qI(e);case 6:case 273:case 33:case 132:return zq(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qI(e);case 421:return iEe(e);case 444:return Fq(e);case 445:return Fq(e);case 466:return nEe(e);case 481:return globalThis.encodeURIComponent(qI(e));default:return $n(e,"base16")}}function HI(r,e){switch(Lt(r).code){case 4:return Uq(e);case 41:return Uq(e);case 42:return $I(e);case 6:case 273:case 33:case 132:return GI(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return $I(e);case 421:return tEe(e);case 444:return oEe(e);case 445:return sEe(e);case 466:return rEe(e);case 481:return $I(globalThis.decodeURIComponent(e));default:return cr(e,"base16")}}var KI=Object.values(xy).map(r=>r.decoder),J_e=function(){let r=KI[0].or(KI[1]);return KI.slice(2).forEach(e=>r=r.or(e)),r}();function Uq(r){if(!xc(r))throw new Error("invalid ip address");return zI(r)}function eEe(r){let e=Mq(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!xc(e))throw new Error("invalid ip address");return e}function GI(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function zq(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function $I(r){let e=cr(r),t=Uint8Array.from(xf(e.length));return yi([t,e],t.length+e.length)}function qI(r){let e=Gu(r);if(r=r.slice(ti(e)),r.length!==e)throw new Error("inconsistent lengths");return $n(r)}function tEe(r){let e;r[0]==="Q"||r[0]==="1"?e=uf(Yi.decode(`z${r}`)).bytes:e=Xe.parse(r).multihash.bytes;let t=Uint8Array.from(xf(e.length));return yi([t,e],t.length+e.length)}function rEe(r){let e=J_e.decode(r),t=Uint8Array.from(xf(e.length));return yi([t,e],t.length+e.length)}function nEe(r){let e=Gu(r),t=r.slice(ti(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+$n(t,"base64url")}function iEe(r){let e=Gu(r),t=r.slice(ti(e));if(t.length!==e)throw new Error("inconsistent lengths");return $n(t,"base58btc")}function oEe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=wc.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=GI(n);return yi([t,i],t.length+i.length)}function sEe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=wc.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=GI(n);return yi([t,i],t.length+i.length)}function Fq(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=$n(e,"base32"),i=zq(t);return`${n}:${i}`}function Vq(r){r=jI(r);let e=[],t=[],n=null,i=r.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o=i.length)throw $q("invalid address: "+r);if(a.path===!0){n=jI(i.slice(o).join("/")),e.push([a.code,HI(a.code,n)]),t.push([a.code,n]);break}let c=HI(a.code,i[o]);e.push([a.code,c]),t.push([a.code,Sy(a.code,c)])}return{string:Kq(t),bytes:YI(e),tuples:e,stringTuples:t,path:n}}function WI(r){let e=[],t=[],n=null,i=0;for(;ir.length)throw $q("Invalid address Uint8Array: "+$n(r,"base16"));e.push([o,u]);let l=Sy(o,u);if(t.push([o,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:Kq(t),tuples:e,stringTuples:t,path:n}}function Kq(r){let e=[];return r.map(t=>{let n=Lt(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),jI(e.join("/"))}function YI(r){return yi(r.map(e=>{let t=Lt(e[0]),n=Uint8Array.from(xf(t.code));return e.length>1&&e[1]!=null&&(n=yi([n,e[1]])),n}))}function aEe(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Gu(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ti(t)}}function jI(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function $q(r){return new Error("Error parsing address: "+r)}var cEe=Symbol.for("nodejs.util.inspect.custom"),XI=Symbol.for("@multiformats/js-multiaddr/multiaddr"),uEe=[Lt("dns").code,Lt("dns4").code,Lt("dns6").code,Lt("dnsaddr").code],QI=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},R1,Sf,Ay,Ty,lEe,I1=class{constructor(e){B(this,"bytes");bt(this,R1,void 0);bt(this,Sf,void 0);bt(this,Ay,void 0);bt(this,Ty,void 0);B(this,lEe,!0);e==null&&(e="");let t;if(e instanceof Uint8Array)t=WI(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Vq(e)}else if(Hq(e))t=WI(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,Dt(this,R1,t.string),Dt(this,Sf,t.tuples),Dt(this,Ay,t.stringTuples),Dt(this,Ty,t.path)}toString(){return ge(this,R1)}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="",s=Lt("tcp"),a=Lt("udp"),c=Lt("ip4"),u=Lt("ip6"),l=Lt("dns6"),f=Lt("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(o=`%${p??""}`),uEe.includes(d)&&(t=s.name,i=443,n=`${p??""}${o}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=Lt(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=Lt(d).name,n=`${p??""}${o}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return ge(this,Sf).map(([e])=>Object.assign({},Lt(e)))}protoCodes(){return ge(this,Sf).map(([e])=>e)}protoNames(){return ge(this,Sf).map(([e])=>Lt(e).name)}tuples(){return ge(this,Sf)}stringTuples(){return ge(this,Ay)}encapsulate(e){return e=new I1(e),new I1(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new I1(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new I1(YI(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,i])=>{n===T1.p2p.code&&e.push([n,i]),n===T1["p2p-circuit"].code&&(e=[])});let t=e.pop();if((t==null?void 0:t[1])!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?$n(Yi.decode(`z${n}`),"base58btc"):$n(Xe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return ge(this,Ty)}equals(e){return C8(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=qq.get(t.name);if(n==null)throw new QI(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>Xi(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")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){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[(lEe=XI,cEe)](){return`Multiaddr(${ge(this,R1)})`}},B8=I1;R1=new WeakMap,Sf=new WeakMap,Ay=new WeakMap,Ty=new WeakMap;var qq=new Map;function Hq(r){return!!(r!=null&&r[XI])}function Xi(r){return new B8(r)}var fEe=_e("dns4"),dEe=_e("dns6"),hEe=_e("dnsaddr"),Tf=mn(_e("dns"),hEe,fEe,dEe),M8=mn(_e("ip4"),_e("ip6")),C1=mn(qe(M8,_e("tcp")),qe(Tf,_e("tcp"))),U8=qe(M8,_e("udp")),pEe=qe(U8,_e("utp")),mEe=qe(U8,_e("quic")),gEe=qe(U8,_e("quic-v1")),ZI=mn(qe(C1,_e("ws")),qe(Tf,_e("ws"))),P1=mn(qe(ZI,_e("p2p")),ZI),JI=mn(qe(C1,_e("wss")),qe(Tf,_e("wss")),qe(C1,_e("tls"),_e("ws")),qe(Tf,_e("tls"),_e("ws"))),xh=mn(qe(JI,_e("p2p")),JI),eR=mn(qe(C1,_e("http")),qe(M8,_e("http")),qe(Tf,_e("http"))),tR=mn(qe(C1,_e("https")),qe(M8,_e("https")),qe(Tf,_e("https"))),Gq=qe(U8,_e("webrtc-direct"),_e("certhash")),Yq=mn(qe(Gq,_e("p2p")),Gq),jq=qe(gEe,_e("webtransport"),_e("certhash"),_e("certhash")),Qq=mn(qe(jq,_e("p2p")),jq),Xq=mn(qe(P1,_e("p2p-webrtc-star"),_e("p2p")),qe(xh,_e("p2p-webrtc-star"),_e("p2p")),qe(P1,_e("p2p-webrtc-star")),qe(xh,_e("p2p-webrtc-star"))),htt=mn(qe(P1,_e("p2p-websocket-star"),_e("p2p")),qe(xh,_e("p2p-websocket-star"),_e("p2p")),qe(P1,_e("p2p-websocket-star")),qe(xh,_e("p2p-websocket-star"))),Zq=mn(qe(eR,_e("p2p-webrtc-direct"),_e("p2p")),qe(tR,_e("p2p-webrtc-direct"),_e("p2p")),qe(eR,_e("p2p-webrtc-direct")),qe(tR,_e("p2p-webrtc-direct"))),Sh=mn(ZI,JI,eR,tR,Xq,Zq,C1,pEe,mEe,Tf,Yq,Qq),ptt=mn(qe(Sh,_e("p2p-stardust"),_e("p2p")),qe(Sh,_e("p2p-stardust"))),Af=mn(qe(Sh,_e("p2p")),Xq,Zq,Yq,Qq,_e("p2p")),Wq=mn(qe(Af,_e("p2p-circuit"),Af),qe(Af,_e("p2p-circuit")),qe(_e("p2p-circuit"),Af),qe(Sh,_e("p2p-circuit")),qe(_e("p2p-circuit"),Sh),_e("p2p-circuit")),Jq=()=>mn(qe(Wq,Jq),Wq),vh=Jq(),rR=mn(qe(vh,Af,vh),qe(Af,vh),qe(vh,Af),vh,Af);var mtt=mn(qe(vh,_e("webrtc"),_e("p2p")),qe(vh,_e("webrtc")),qe(Sh,_e("webrtc"),_e("p2p")),qe(Sh,_e("webrtc")),_e("webrtc"));function eH(r){function e(t){let n;try{n=Xi(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function qe(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:eH(e),partialMatch:e}}function mn(...r){function e(n){let i=null;return r.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:eH(e),partialMatch:e}}function _e(r){let e=r;function t(i){let o;try{o=Xi(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}var cH=C(F8(),1);var z8=/^\/(ip[fn]s)\/([^/?#]+)/,uH=1,lH=2,fH=/^https?:\/\/([^/]+)\.(ip[fn]s)\.[^/?]+/;var TEe=/^(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\.)+([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])$/;function V8(r){try{return pH(r)?!!Xe.parse(r):r instanceof Uint8Array?!!Xe.decode(r):!!Xe.asCID(r)}catch{return!1}}function dH(r,e,t=uH,n=lH){let i=mH(r);if(i===!1)return!1;let o=i.match(e);if(o==null||o[t]!=="ipfs")return!1;let s=o[n];return s!=null&&e===fH&&(s=s.toLowerCase()),V8(s)}function hH(r,e,t=uH,n=lH){let i=mH(r);if(i===!1)return!1;let o=i.match(e);if(o==null||o[t]!=="ipns")return!1;let s=o[n];if(s!=null&&e===fH){if(s=s.toLowerCase(),V8(s))return!0;try{!s.includes(".")&&s.includes("-")&&(s=s.replace(/--/g,"@").replace(/-/g,".").replace(/@/g,"-"));let{hostname:a}=new cH.URL(`http://${s}`);return TEe.test(a)}catch{return!1}}return!0}function pH(r){return typeof r=="string"}function mH(r){return r instanceof Uint8Array?$n(r,"base58btc"):pH(r)?r:!1}var K8=r=>dH(r,z8)||hH(r,z8);var gH=r=>dH(r,z8),$8=r=>hH(r,z8);var k1=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var oR={};xe(oR,{identity:()=>IEe});var IEe=c1({prefix:"\0",name:"identity",encode:r=>xT(r),decode:r=>vT(r)});var sR={};xe(sR,{base2:()=>REe});var REe=tn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var aR={};xe(aR,{base8:()=>CEe});var CEe=tn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cR={};xe(cR,{base10:()=>PEe});var PEe=hf({prefix:"9",name:"base10",alphabet:"0123456789"});var uR={};xe(uR,{base16:()=>kEe,base16upper:()=>NEe});var kEe=tn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),NEe=tn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lR={};xe(lR,{base36:()=>DEe,base36upper:()=>OEe});var DEe=hf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),OEe=hf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fR={};xe(fR,{base256emoji:()=>FEe});var yH=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),LEe=yH.reduce((r,e,t)=>(r[t]=e,r),[]),BEe=yH.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function MEe(r){return r.reduce((e,t)=>(e+=LEe[t],e),"")}function UEe(r){let e=[];for(let t of r){let n=BEe[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var FEe=c1({prefix:"\u{1F680}",name:"base256emoji",encode:MEe,decode:UEe});var hR={};xe(hR,{sha256:()=>mr,sha512:()=>zEe});var Ah=({name:r,code:e,encode:t})=>new dR(r,e,t),dR=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Ec(this.code,t):t.then(n=>Ec(this.code,n))}else throw Error("Unknown type, must be binary type")}};var bH=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),mr=Ah({name:"sha2-256",code:18,encode:bH("SHA-256")}),zEe=Ah({name:"sha2-512",code:19,encode:bH("SHA-512")});var pR={};xe(pR,{identity:()=>Ns});var _H=0,VEe="identity",EH=_c,KEe=r=>Ec(_H,EH(r)),Ns={code:_H,name:VEe,encode:EH,digest:KEe};var Sc=85;var Btt=new TextEncoder,Mtt=new TextDecoder;var If={...oR,...sR,...aR,...cR,...uR,...NT,...lR,...PT,...RT,...fR},Ktt={...hR,...pR};function Rf(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function ju(r=0){var e;return((e=globalThis.Buffer)==null?void 0:e.alloc)!=null?Rf(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Ac(r=0){var e;return((e=globalThis.Buffer)==null?void 0:e.allocUnsafe)!=null?Rf(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function xH(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vH=xH("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),mR=xH("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=Ac(r.length);for(let t=0;t1&&this._buf[this._buf.byteLength-1]===G8;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;is)return!1}return t.lengtht.namespaces()))])}};function HEe(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function GEe(r){let e=r.split(":");return e[e.length-1]}function jEe(r){return[].concat(...r)}var j8=C(ee(),1);var IH=C(Kn(),1),RH=C(Da(),1);var WEe=/(-?(?:\d+\.?\d*|\d*\.?\d+)(?:e[-+]?\d+)?)\s*([\p{L}]*)/uig;Et.nanosecond=Et.ns=1/1e6;Et.\u00B5s=Et.\u03BCs=Et.us=Et.microsecond=1/1e3;Et.millisecond=Et.ms=Et[""]=1;Et.second=Et.sec=Et.s=Et.ms*1e3;Et.minute=Et.min=Et.m=Et.s*60;Et.hour=Et.hr=Et.h=Et.m*60;Et.day=Et.d=Et.h*24;Et.week=Et.wk=Et.w=Et.d*7;Et.month=Et.b=Et.d*(365.25/12);Et.year=Et.yr=Et.y=Et.d*365.25;function Et(r="",e="ms"){var t=null;r=(r+"").replace(/(\d)[,_](\d)/g,"$1$2");var n=r[0]==="-";return r.replace(WEe,function(i,o,s){s=TH(s),s&&(t=(t||0)+Math.abs(parseFloat(o,10))*s)}),t&&t/(TH(e)||1)*(n?-1:1)}function TH(r){return Et[r]||Et[r.toLowerCase().replace(/s$/,"")]}var Cf=Et;var Yu=class extends Error{constructor(e="request timed out"){super(e),this.name="TimeoutError",this.code=Yu.code}};Yu.code="ERR_TIMEOUT";function $(r,e){return(...t)=>{let n=t[e??t.length-1];if(!n||!n.timeout)return r(...t);let i=typeof n.timeout=="string"?Cf(n.timeout):n.timeout,o=new IH.TimeoutController(i);n.signal=(0,RH.anySignal)([n.signal,o.signal]);let s=r(...t),a=new Promise((l,f)=>{o.signal.addEventListener("abort",()=>{f(new Yu)})}),c=Date.now(),u=()=>{if(o.signal.aborted)throw new Yu;if(Date.now()-c>i)throw o.abort(),new Yu};return s[Symbol.asyncIterator]?async function*(){let l=s[Symbol.asyncIterator]();try{for(;;){let{value:f,done:h}=await Promise.race([l.next(),a]);if(h)break;u(),yield f}}catch(f){throw u(),f}finally{o.clear(),l.return&&l.return()}}():(async()=>{try{let l=await Promise.race([s,a]);return u(),l}catch(l){throw u(),l}finally{o.clear()}})()}}var yR=C(ee(),1),CH="/ipfs/";function Qu(r){if(r instanceof Uint8Array)try{r=z.decode(r)}catch(i){throw(0,yR.default)(i,"ERR_INVALID_CID")}let e=z.asCID(r);if(e)return{cid:e,path:void 0};r=r.toString(),r.startsWith(CH)&&(r=r.substring(CH.length));let t=r.split("/"),n;try{e=z.parse(t.shift()||"")}catch(i){throw(0,yR.default)(i,"ERR_INVALID_CID")}return t.length&&(n=`/${t.join("/")}`),{cid:e,path:n}}var YEe="ERR_BAD_PATH",W8="This command must be run in online mode. Try running 'ipfs daemon' first.",Ry=new pe("/local/filesroot"),PH=262144;var kH=r=>{if(z.asCID(r))return`/ipfs/${r}`;let t=r.toString();try{return`/ipfs/${z.parse(t)}`}catch{}if(K8(t))return t;throw(0,j8.default)(new Error(`invalid path: ${r}`),YEe)},N1=r=>r instanceof Uint8Array?z.decode(r).toString():(r=r.toString(),r.indexOf("/ipfs/")===0&&(r=r.substring(6)),r.charAt(r.length-1)==="/"&&(r=r.substring(0,r.length-1)),r),Pf=async function(r,e,t,n={}){let{cid:i,path:o}=Qu(t);o&&(n.path=o);let s=i,a=n.path||"";if(a.startsWith("/")&&(a=a.substring(1)),n.path)try{for await(let{value:c,remainderPath:u}of kf(i,n.path,e,r,{signal:n.signal})){if(!z.asCID(c))break;a=u,s=c}}catch(c){throw c.message.startsWith("Object has no property")&&(c.message=`no link named "${a.split("/")[0]}" under ${s}`,c.code="ERR_NO_LINK"),c}return{cid:s,remainderPath:a||""}},wR=r=>{if(r.type!=="file"&&r.type!=="directory"&&r.type!=="raw")throw new Error(`Unknown node type '${r.type}'`);let e={cid:r.cid,path:r.path,name:r.name,size:r.size,type:"file"};return r.type==="directory"&&(e.type="dir"),r.type==="file"&&(e.size=r.unixfs.fileSize()),(r.type==="file"||r.type==="directory")&&(e.mode=r.unixfs.mode,r.unixfs.mtime!==void 0&&(e.mtime=r.unixfs.mtime)),e},NH=$(async(r,e)=>await r),kf=async function*(r,e,t,n,i){let o=async u=>{let l=await t.getCodec(u.code),f=await n.blocks.get(u,i);return l.decode(f)},s=e.split("/").filter(Boolean),a=await o(r),c=r;for(;s.length;){let u=s.shift();if(!u)throw(0,j8.default)(new Error(`Could not resolve path "${e}"`),"ERR_INVALID_PATH");if(r.code===kr&&Array.isArray(a.Links)){let l=a.Links.find(f=>f.Name===u);if(l){yield{value:l.Hash,remainderPath:s.join("/")},a=await o(l.Hash),c=l.Hash;continue}}if(Object.prototype.hasOwnProperty.call(a,u))a=a[u],yield{value:a,remainderPath:s.join("/")};else throw(0,j8.default)(new Error(`no link named "${u}" under ${c}`),"ERR_NO_LINK");z.asCID(a)&&(c=a,a=await o(a))}yield{value:a,remainderPath:""}};var Pi=class{static create({start:e,stop:t}){return new Pi(e,t)}static async start(e,t){let{state:n,activate:i}=e;switch(n.status){case"stopped":try{let o=i(t);e.state={status:"starting",ready:o};let s=await o;return e.state={status:"started",value:s},s}catch(o){throw e.state={status:"stopped"},o}case"starting":throw new _h;case"started":throw new Eh;case"stopping":return await n.ready,await Pi.start(e,t);default:return Pi.panic(e)}}static async stop(e){let{state:t,deactivate:n}=e;switch(t.status){case"stopped":break;case"starting":{try{await t.ready}catch{}return await Pi.stop(e)}case"stopping":return await t.ready;case"started":{n&&await n(t.value),e.state={status:"stopped"};break}default:Pi.panic(t)}}static try({state:e}){switch(e.status){case"started":return e.value;default:return null}}static async use({state:e},t){switch(e.status){case"started":return e.value;case"starting":return await NH(e.ready,t);default:throw new $u}}static panic({state:e}){let t=JSON.stringify({status:e.status});throw RangeError(`Service in invalid state ${t}, should never happen if you see this please report a bug`)}constructor(e,t){this.activate=e,this.deactivate=t,this.state={status:"stopped"}}async use(e){return await Pi.use(this,e)}try(){return Pi.try(this)}};function DH({network:r,preload:e,peerId:t,keychain:n,repo:i,ipns:o,mfsPreload:s,print:a,hashers:c,options:u}){return async()=>{let{libp2p:f}=await Pi.start(r,{peerId:t,repo:i,print:a,hashers:c,options:u});await Promise.all([o.startOnline({keychain:n,libp2p:f,peerId:t,repo:i}),e.start(),s.start()])}}function OH({network:r,preload:e,ipns:t,repo:n,mfsPreload:i}){return async()=>{await Promise.all([e.stop(),t.stop(),i.stop()]),await Pi.stop(r),await n.close()}}var BH=C(Cy(),1),Y8=class{constructor(e){this.lru=(0,BH.default)(e)}get(e){let t=this.lru.get(e);if(t){if(t.expire&&t.expireglobalThis.DOMException===void 0?new _R(r):new DOMException(r),zH=r=>{let e=r.reason===void 0?FH("This operation was aborted."):r.reason;return e instanceof Error?e:FH(e)};function Ih(r,e,t,n){let i,o=new Promise((s,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(zH(c)),c.addEventListener("abort",()=>{a(zH(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{s(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Nf(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{s(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return o.clear=()=>{clearTimeout(i),i=void 0},o}function ER(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Rh=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Xu,vR=class{constructor(){Xu.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Rh(this,Xu,"f")[this.size-1].priority>=t.priority){Rh(this,Xu,"f").push(n);return}let i=ER(Rh(this,Xu,"f"),n,(o,s)=>s.priority-o.priority);Rh(this,Xu,"f").splice(i,0,n)}dequeue(){let e=Rh(this,Xu,"f").shift();return e==null?void 0:e.run}filter(e){return Rh(this,Xu,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Rh(this,Xu,"f").length}};Xu=new WeakMap;var VH=vR;var Wr=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},ke=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},gn,Dy,Oy,Of,rb,Ly,X8,Oa,Ny,Fo,Z8,zo,By,Df,J8,KH,$H,GH,qH,HH,eb,xR,SR,nb,jH,tb,ib=class extends Error{},AR=class extends ky.default{constructor(e){var t,n,i,o;if(super(),gn.add(this),Dy.set(this,void 0),Oy.set(this,void 0),Of.set(this,0),rb.set(this,void 0),Ly.set(this,void 0),X8.set(this,0),Oa.set(this,void 0),Ny.set(this,void 0),Fo.set(this,void 0),Z8.set(this,void 0),zo.set(this,0),By.set(this,void 0),Df.set(this,void 0),J8.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:VH,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);Wr(this,Dy,e.carryoverConcurrencyCount,"f"),Wr(this,Oy,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Wr(this,rb,e.intervalCap,"f"),Wr(this,Ly,e.interval,"f"),Wr(this,Fo,new e.queueClass,"f"),Wr(this,Z8,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Wr(this,J8,e.throwOnTimeout===!0,"f"),Wr(this,Df,e.autoStart===!1,"f")}get concurrency(){return ke(this,By,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);Wr(this,By,e,"f"),ke(this,gn,"m",nb).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:ke(this,J8,"f"),...t},new Promise((n,i)=>{ke(this,Fo,"f").enqueue(async()=>{var o,s,a;Wr(this,zo,(s=ke(this,zo,"f"),s++,s),"f"),Wr(this,Of,(a=ke(this,Of,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new ib("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Ih(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,ke(this,gn,"m",jH).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nf&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{ke(this,gn,"m",GH).call(this)}},t),this.emit("add"),ke(this,gn,"m",eb).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return ke(this,Df,"f")?(Wr(this,Df,!1,"f"),ke(this,gn,"m",nb).call(this),this):this}pause(){Wr(this,Df,!0,"f")}clear(){Wr(this,Fo,new(ke(this,Z8,"f")),"f")}async onEmpty(){ke(this,Fo,"f").size!==0&&await ke(this,gn,"m",tb).call(this,"empty")}async onSizeLessThan(e){ke(this,Fo,"f").sizeke(this,Fo,"f").size{ke(this,gn,"m",qH).call(this)},t),"f"),!0}return!1},eb=function(){if(ke(this,Fo,"f").size===0)return ke(this,Oa,"f")&&clearInterval(ke(this,Oa,"f")),Wr(this,Oa,void 0,"f"),this.emit("empty"),ke(this,zo,"f")===0&&this.emit("idle"),!1;if(!ke(this,Df,"f")){let e=!ke(this,gn,"a",HH);if(ke(this,gn,"a",KH)&&ke(this,gn,"a",$H)){let t=ke(this,Fo,"f").dequeue();return t?(this.emit("active"),t(),e&&ke(this,gn,"m",xR).call(this),!0):!1}}return!1},xR=function(){ke(this,Oy,"f")||ke(this,Oa,"f")!==void 0||(Wr(this,Oa,setInterval(()=>{ke(this,gn,"m",SR).call(this)},ke(this,Ly,"f")),"f"),Wr(this,X8,Date.now()+ke(this,Ly,"f"),"f"))},SR=function(){ke(this,Of,"f")===0&&ke(this,zo,"f")===0&&ke(this,Oa,"f")&&(clearInterval(ke(this,Oa,"f")),Wr(this,Oa,void 0,"f")),Wr(this,Of,ke(this,Dy,"f")?ke(this,zo,"f"):0,"f"),ke(this,gn,"m",nb).call(this)},nb=function(){for(;ke(this,gn,"m",eb).call(this););},jH=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new ib("The task was aborted."))},{once:!0})})},tb=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var qn=AR;var dG=C(O1(),1),OR=new Y8(1e3),x7e=60*1e3,S7e=qn.default?qn.default:qn,A7e=new S7e({concurrency:4}),fG=r=>{if(r.Path)return r.Path;throw new Error(r.Message)};async function hG(r,e){return(async(n,i={})=>{let o=new URLSearchParams(i);o.set("arg",n);let s=o.toString();if(!i.nocache&&OR.has(s)){let c=OR.get(s);return fG(c)}let a=await A7e.add(async()=>{let c=await dG.default.get("https://ipfs.io/api/v0/dns",{searchParams:o}),u=new URL(c.url).search.slice(1),l=await c.json();return OR.set(u,l,x7e),l});return fG(a)})(r,e)}function T7e(r){return r.endsWith(".eth")&&(r=r.replace(/.eth$/,".eth.link")),r}function pG(){return $(async(e,t={recursive:!0})=>{if(typeof e!="string")throw new Error("Invalid arguments, domain must be a string");return e=T7e(e),hG(e,t)})}function mG({network:r}){return()=>{let e=r.try();return e!=null&&!!e.libp2p.isStarted()}}var LR=Symbol.for("@libp2p/peer-id");function Lf(r){return r!=null&&!!r[LR]}var sb=class extends Error{constructor(t="The operation was aborted"){super(t);B(this,"code");B(this,"type");this.code=sb.code,this.type=sb.type}},Ph=sb;B(Ph,"code","ABORT_ERR"),B(Ph,"type","aborted");var J=class extends Error{constructor(t,n,i){super(t);B(this,"code");B(this,"props");this.code=n,this.name=(i==null?void 0:i.name)??"CodeError",this.props=i??{}}};function mt(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;tr.decoder).reduce((r,e)=>r.or(e),Vu.identity.decoder),yG=114,BR=36,MR=37,C7e,Uy=class{constructor(e){B(this,"type");B(this,"multihash");B(this,"privateKey");B(this,"publicKey");B(this,"string");B(this,C7e,!0);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()})`}toString(){return this.string==null&&(this.string=pr.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return z.createV1(yG,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){var t;if(e instanceof Uint8Array)return mt(this.multihash.bytes,e);if(typeof e=="string")return Oe(e).equals(this);if(((t=e==null?void 0:e.multihash)==null?void 0:t.bytes)!=null)return mt(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[(C7e=LR,I7e)](){return`PeerId(${this.toString()})`}},L1=class extends Uy{constructor(t){super({...t,type:"RSA"});B(this,"type","RSA");B(this,"publicKey");this.publicKey=t.publicKey}},B1=class extends Uy{constructor(t){super({...t,type:"Ed25519"});B(this,"type","Ed25519");B(this,"publicKey");this.publicKey=t.multihash.digest}},M1=class extends Uy{constructor(t){super({...t,type:"secp256k1"});B(this,"type","secp256k1");B(this,"publicKey");this.publicKey=t.multihash.digest}};function Oe(r,e){if(e=e??gG,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Ea(pr.decode(`z${r}`));return r.startsWith("12D")?new B1({multihash:t}):r.startsWith("16U")?new M1({multihash:t}):new L1({multihash:t})}return Di(gG.decode(r))}function Di(r){try{let e=Ea(r);if(e.code===Ii.code){if(e.digest.length===BR)return new B1({multihash:e});if(e.digest.length===MR)return new M1({multihash:e})}if(e.code===dt.code)return new L1({multihash:e})}catch{return R7e(z.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function R7e(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==yG)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===dt.code)return new L1({multihash:r.multihash});if(e.code===Ii.code){if(e.digest.length===BR)return new B1({multihash:r.multihash});if(e.digest.length===MR)return new M1({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Hn(r,e){return r.length===BR?new B1({multihash:hc(Ii.code,r),privateKey:e}):r.length===MR?new M1({multihash:hc(Ii.code,r),privateKey:e}):new L1({multihash:await dt.digest(r),publicKey:r,privateKey:e})}function wG({repo:r,codecs:e,bases:t,name:n}){async function i(o,s={}){if(!K8(o))throw new Error("invalid argument "+o);if($8(o))for await(let w of n.resolve(o,s))o=w;let[,a,c,...u]=o.split("/"),l=s.cidBase?await t.getBase(s.cidBase):void 0,f=P7e(c);if(u.length===0){let w=l?l.encoder.encode(f):c;return`/${a}/${w}`}let h=z.decode(f);o=u.join("/");let d=kf(h,o,e,r,s),p=h,g=o;for await(let w of d)z.asCID(w.value)&&(p=w.value,g=w.remainderPath);return`/ipfs/${p.toString(l&&l.encoder)}${g?"/"+g:""}`}return $(i)}function P7e(r){try{return Oe(r).toBytes()}catch{return z.parse(r).bytes}}async function Dr(r){let e;for await(let t of r)e=t;return e}function bG({addAll:r}){return(e,t={})=>{let n,i=z.asCID(e);return i?n=r([{cid:i,...t}],t):n=r([{path:e.toString(),...t}],t),Dr(n)}}var U1=C(ee(),1);function k7e(r){return Symbol.iterator in r}function N7e(r){return Symbol.asyncIterator in r}function _G(r){return z.asCID(r)!=null}async function*Tc(r){if(r==null)throw(0,U1.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT");let e=z.asCID(r);if(e){yield Ji({cid:e});return}if(r instanceof String||typeof r=="string"){yield Ji({path:r});return}if(r.cid!=null||r.path!=null)return yield Ji(r);if(k7e(r)){let t=r[Symbol.iterator](),n=t.next();if(n.done)return t;if(_G(n.value)){yield Ji({cid:n.value});for(let i of t)yield Ji({cid:i});return}if(n.value instanceof String||typeof n.value=="string"){yield Ji({path:n.value});for(let i of t)yield Ji({path:i});return}if(n.value.cid!=null||n.value.path!=null){yield Ji(n.value);for(let i of t)yield Ji(i);return}throw(0,U1.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}if(N7e(r)){let t=r[Symbol.asyncIterator](),n=await t.next();if(n.done)return t;if(_G(n.value)){yield Ji({cid:n.value});for await(let i of t)yield Ji({cid:i});return}if(n.value instanceof String||typeof n.value=="string"){yield Ji({path:n.value});for await(let i of t)yield Ji({path:i});return}if(n.value.cid!=null||n.value.path!=null){yield Ji(n.value);for await(let i of t)yield Ji(i);return}throw(0,U1.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}throw(0,U1.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}function Ji(r){let e=r.cid||`${r.path}`;if(!e)throw(0,U1.default)(new Error("Unexpected input: Please path either a CID or an IPFS path"),"ERR_UNEXPECTED_INPUT");let t={path:e,recursive:r.recursive!==!1};return r.metadata!=null&&(t.metadata=r.metadata),t}var Pt={direct:"direct",recursive:"recursive",indirect:"indirect",all:"all"};function EG({repo:r,codecs:e}){async function*t(n,i={}){let o=async function*(){for await(let{path:c,recursive:u,metadata:l}of Tc(n)){let{cid:f}=await Pf(r,e,c),{reason:h}=await r.pins.isPinnedWithType(f,[Pt.recursive,Pt.direct]);if(h==="recursive"&&!u)throw new Error(`${f} already pinned recursively`);u?await r.pins.pinRecursively(f,{metadata:l}):await r.pins.pinDirectly(f,{metadata:l}),yield f}};if(!!!i.lock){yield*o();return}let a=await r.gcLock.readLock();try{yield*o()}finally{a()}}return $(t)}var UR=C(ee(),1);function Fy(r,e,t){let n={type:r,cid:e};return t&&(n.metadata=t),n}function vG({repo:r,codecs:e}){async function*t(n={}){let i=Pt.all;if(n.type&&(i=n.type,!Object.keys(Pt).includes(i)))throw(0,UR.default)(new Error("Invalid pin type"),"ERR_INVALID_PIN_TYPE");if(n.paths){let o=!1;for await(let{path:s}of Tc(n.paths)){let{cid:a}=await Pf(r,e,s),{reason:c,pinned:u,parent:l,metadata:f}=await r.pins.isPinnedWithType(a,i);if(!u)throw(0,UR.default)(new Error(`path '${s}' is not pinned`),"ERR_NOT_PINNED");switch(c){case Pt.direct:case Pt.recursive:o=!0,yield Fy(c,a,f);break;default:o=!0,yield Fy(`${Pt.indirect} through ${l}`,a,f)}}if(!o)throw new Error("No match found");return}if(i===Pt.recursive||i===Pt.all)for await(let{cid:o,metadata:s}of r.pins.recursiveKeys())yield Fy(Pt.recursive,o,s);if(i===Pt.indirect||i===Pt.all)for await(let o of r.pins.indirectKeys(n))yield Fy(Pt.indirect,o);if(i===Pt.direct||i===Pt.all)for await(let{cid:o,metadata:s}of r.pins.directKeys())yield Fy(Pt.direct,o,s)}return $(t)}function xG({rmAll:r}){async function e(t,n={}){let i=await Dr(r([{path:t,...n}],n));if(!i)throw new Error("CID expected");return i}return e}function SG({repo:r,codecs:e}){async function*t(n,i={}){let o=await r.gcLock.readLock();try{for await(let{path:s,recursive:a}of Tc(n)){let{cid:c}=await Pf(r,e,s),{pinned:u,reason:l}=await r.pins.isPinnedWithType(c,Pt.all);if(!u)throw new Error(`${c} is not pinned`);switch(l){case Pt.recursive:if(!a)throw new Error(`${c} is pinned recursively`);await r.pins.unpin(c),yield c;break;case Pt.direct:await r.pins.unpin(c),yield c;break;default:throw new Error(`${c} is pinned indirectly under ${l}`)}}}finally{o()}}return $(t)}var ab=class{constructor({codecs:e,repo:t}){let n=EG({codecs:e,repo:t});this.addAll=n,this.add=bG({addAll:n});let i=SG({codecs:e,repo:t});this.rmAll=i,this.rm=xG({rmAll:i}),this.ls=vG({codecs:e,repo:t}),this.remote={add:(o,s={})=>Promise.reject(new Error("Not implemented")),ls:async function*(o,s={}){return Promise.reject(new Error("Not implemented"))},rm:(o,s={})=>Promise.reject(new Error("Not implemented")),rmAll:(o,s={})=>Promise.reject(new Error("Not implemented")),service:{add:(o,s)=>Promise.reject(new Error("Not implemented")),rm:(o,s={})=>Promise.reject(new Error("Not implemented")),ls:(o={})=>Promise.reject(new Error("Not implemented"))}}}};var WQ=C(ee(),1);var Vo={};xe(Vo,{abortedError:()=>D7e,dbDeleteFailedError:()=>ub,dbOpenFailedError:()=>cb,dbWriteFailedError:()=>lb,notFoundError:()=>Gn});var F1=C(ee(),1);function cb(r){return r=r||new Error("Cannot open database"),(0,F1.default)(r,"ERR_DB_OPEN_FAILED")}function ub(r){return r=r||new Error("Delete failed"),(0,F1.default)(r,"ERR_DB_DELETE_FAILED")}function lb(r){return r=r||new Error("Write failed"),(0,F1.default)(r,"ERR_DB_WRITE_FAILED")}function Gn(r){return r=r||new Error("Not Found"),(0,F1.default)(r,"ERR_NOT_FOUND")}function D7e(r){return r=r||new Error("Aborted"),(0,F1.default)(r,"ERR_ABORTED")}var Vs=C(ee(),1);function re(r,e="utf8"){let t=I8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var MQ=C(AG(),1);var Zb={};xe(Zb,{generateEphemeralKeyPair:()=>fW,generateKeyPair:()=>Xb,generateKeyPairFromSeed:()=>dSe,importKey:()=>c3,keyStretcher:()=>yW,keysPBM:()=>Q1,marshalPrivateKey:()=>HC,marshalPublicKey:()=>a3,supportedKeys:()=>Uc,unmarshalPrivateKey:()=>Li,unmarshalPublicKey:()=>Bs});var Sst=C(Ic(),1),Ast=C(Rb(),1);var Qb=C(at(),1);var RC={};xe(RC,{Ed25519PrivateKey:()=>Vh,Ed25519PublicKey:()=>Xy,generateKeyPair:()=>kxe,generateKeyPairFromSeed:()=>IC,unmarshalEd25519PrivateKey:()=>Cxe,unmarshalEd25519PublicKey:()=>Pxe});var ixe=C(Ju(),1);var oi=BigInt(0),zt=BigInt(1),$f=BigInt(2),oxe=BigInt(8),Uj=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),Lr=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:Uj,n:Uj,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var $j=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Hy=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Eit=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),sxe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),axe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),cxe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),uxe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Bt=class{constructor(e,t,n,i){this.x=e,this.y=t,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof Vr))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(Vr.ZERO)?Bt.ZERO:new Bt(e.x,e.y,zt,ie(e.x*e.y))}static toAffineBatch(e){let t=dxe(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){zj(e);let{x:t,y:n,z:i}=this,{x:o,y:s,z:a}=e,c=ie(t*a),u=ie(o*i),l=ie(n*a),f=ie(s*i);return c===u&&l===f}negate(){return new Bt(ie(-this.x),this.y,this.z,ie(-this.t))}double(){let{x:e,y:t,z:n}=this,{a:i}=Lr,o=ie(e*e),s=ie(t*t),a=ie($f*ie(n*n)),c=ie(i*o),u=e+t,l=ie(ie(u*u)-o-s),f=c+s,h=f-a,d=c-s,p=ie(l*h),g=ie(f*d),w=ie(l*d),_=ie(h*f);return new Bt(p,g,_,w)}add(e){zj(e);let{x:t,y:n,z:i,t:o}=this,{x:s,y:a,z:c,t:u}=e,l=ie((n-t)*(a+s)),f=ie((n+t)*(a-s)),h=ie(f-l);if(h===oi)return this.double();let d=ie(i*$f*u),p=ie(o*$f*c),g=p+d,w=f+l,_=p-d,x=ie(g*h),m=ie(w*_),y=ie(g*_),b=ie(h*w);return new Bt(x,m,b,y)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let t=1+256/e,n=[],i=this,o=i;for(let s=0;s>=f,p>c&&(p-=l,e+=zt);let g=d,w=d+Math.abs(p)-1,_=h%2!==0,x=p<0;p===0?s=s.add(Fj(_,i[g])):o=o.add(Fj(x,i[w]))}return Bt.normalizeZ([o,s])[0]}multiply(e,t){return this.wNAF(Pb(e,Lr.l),t)}multiplyUnsafe(e){let t=Pb(e,Lr.l,!1),n=Bt.BASE,i=Bt.ZERO;if(t===oi)return i;if(this.equals(i)||t===zt)return this;if(this.equals(n))return this.wNAF(t);let o=i,s=this;for(;t>oi;)t&zt&&(o=o.add(s)),s=s.double(),t>>=zt;return o}isSmallOrder(){return this.multiplyUnsafe(Lr.h).equals(Bt.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(Lr.l/$f).double();return Lr.l%$f&&(e=e.add(this)),e.equals(Bt.ZERO)}toAffine(e){let{x:t,y:n,z:i}=this,o=this.equals(Bt.ZERO);e==null&&(e=o?oxe:kb(i));let s=ie(t*e),a=ie(n*e),c=ie(i*e);if(o)return Vr.ZERO;if(c!==zt)throw new Error("invZ was invalid");return new Vr(s,a)}fromRistrettoBytes(){cC()}toRistrettoBytes(){cC()}fromRistrettoHash(){cC()}};Bt.BASE=new Bt(Lr.Gx,Lr.Gy,zt,ie(Lr.Gx*Lr.Gy));Bt.ZERO=new Bt(oi,zt,zt,oi);function Fj(r,e){let t=e.negate();return r?t:e}function zj(r){if(!(r instanceof Bt))throw new TypeError("ExtendedPoint expected")}function aC(r){if(!(r instanceof po))throw new TypeError("RistrettoPoint expected")}function cC(){throw new Error("Legacy method: switch to RistrettoPoint")}var po=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:t}=Lr,n=ie(Hy*e*e),i=ie((n+zt)*cxe),o=BigInt(-1),s=ie((o-t*n)*ie(n+t)),{isValid:a,value:c}=hC(i,s),u=ie(c*e);Kf(u)||(u=ie(-u)),a||(c=u),a||(o=n);let l=ie(o*(n-zt)*uxe-s),f=c*c,h=ie((c+c)*s),d=ie(l*sxe),p=ie(zt-f),g=ie(zt+f);return new Bt(ie(h*g),ie(p*d),ie(d*g),ie(h*p))}static hashToCurve(e){e=qf(e,64);let t=uC(e.slice(0,32)),n=this.calcElligatorRistrettoMap(t),i=uC(e.slice(32,64)),o=this.calcElligatorRistrettoMap(i);return new po(n.add(o))}static fromHex(e){e=qf(e,32);let{a:t,d:n}=Lr,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",o=uC(e);if(!pxe(Gy(o),e)||Kf(o))throw new Error(i);let s=ie(o*o),a=ie(zt+t*s),c=ie(zt-t*s),u=ie(a*a),l=ie(c*c),f=ie(t*n*u-l),{isValid:h,value:d}=Kj(ie(f*l)),p=ie(d*c),g=ie(d*p*f),w=ie((o+o)*p);Kf(w)&&(w=ie(-w));let _=ie(a*g),x=ie(w*_);if(!h||Kf(x)||_===oi)throw new Error(i);return new po(new Bt(w,_,zt,x))}toRawBytes(){let{x:e,y:t,z:n,t:i}=this.ep,o=ie(ie(n+t)*ie(n-t)),s=ie(e*t),a=ie(s*s),{value:c}=Kj(ie(o*a)),u=ie(c*o),l=ie(c*s),f=ie(u*l*i),h;if(Kf(i*f)){let p=ie(t*Hy),g=ie(e*Hy);e=p,t=g,h=ie(u*axe)}else h=l;Kf(e*f)&&(t=ie(-t));let d=ie((n-t)*h);return Kf(d)&&(d=ie(-d)),Gy(d)}toHex(){return jy(this.toRawBytes())}toString(){return this.toHex()}equals(e){aC(e);let t=this.ep,n=e.ep,i=ie(t.x*n.y)===ie(t.y*n.x),o=ie(t.y*n.y)===ie(t.x*n.x);return i||o}add(e){return aC(e),new po(this.ep.add(e.ep))}subtract(e){return aC(e),new po(this.ep.subtract(e.ep))}multiply(e){return new po(this.ep.multiply(e))}multiplyUnsafe(e){return new po(this.ep.multiplyUnsafe(e))}};po.BASE=new po(Bt.BASE);po.ZERO=new po(Bt.ZERO);var fC=new WeakMap,Vr=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,fC.delete(this)}static fromHex(e,t=!0){let{d:n,P:i}=Lr;e=qf(e,32);let o=e.slice();o[31]=e[31]&-129;let s=Wy(o);if(t&&s>=i)throw new Error("Expected 0 < hex < P");if(!t&&s>=$j)throw new Error("Expected 0 < hex < 2**256");let a=ie(s*s),c=ie(a-zt),u=ie(n*a+zt),{isValid:l,value:f}=hC(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let h=(f&zt)===zt;return(e[31]&128)!==0!==h&&(f=ie(-f)),new Vr(f,s)}static async fromPrivateKey(e){return(await Nb(e)).point}toRawBytes(){let e=Gy(this.y);return e[31]|=this.x&zt?128:0,e}toHex(){return jy(this.toRawBytes())}toX25519(){let{y:e}=this,t=ie((zt+e)*kb(zt-e));return Gy(t)}isTorsionFree(){return Bt.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Vr(ie(-this.x),this.y)}add(e){return Bt.fromAffine(this).add(Bt.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Bt.fromAffine(this).multiply(e,this).toAffine()}};Vr.BASE=new Vr(Lr.Gx,Lr.Gy);Vr.ZERO=new Vr(oi,zt);var Uh=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){let t=qf(e,64),n=Vr.fromHex(t.slice(0,32),!1),i=Wy(t.slice(32,64));return new Uh(n,i)}assertValidity(){let{r:e,s:t}=this;if(!(e instanceof Vr))throw new Error("Expected Point instance");return Pb(t,Lr.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Gy(this.s),32),e}toHex(){return jy(this.toRawBytes())}};function Vj(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function jy(r){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t=oi?t:e+t}function kb(r,e=Lr.P){if(r===oi||e<=oi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=ie(r,e),n=e,i=oi,o=zt,s=zt,a=oi;for(;t!==oi;){let u=n/t,l=n%t,f=i-s*u,h=o-a*u;n=t,t=l,i=s,o=a,s=f,a=h}if(n!==zt)throw new Error("invert: does not exist");return ie(i,e)}function dxe(r,e=Lr.P){let t=new Array(r.length),n=r.reduce((o,s,a)=>s===oi?o:(t[a]=o,ie(o*s,e)),zt),i=kb(n,e);return r.reduceRight((o,s,a)=>s===oi?o:(t[a]=ie(o*t[a],e),ie(o*s,e)),i),t}function Oc(r,e){let{P:t}=Lr,n=r;for(;e-- >oi;)n*=n,n%=t;return n}function hxe(r){let{P:e}=Lr,t=BigInt(5),n=BigInt(10),i=BigInt(20),o=BigInt(40),s=BigInt(80),c=r*r%e*r%e,u=Oc(c,$f)*c%e,l=Oc(u,zt)*r%e,f=Oc(l,t)*l%e,h=Oc(f,n)*f%e,d=Oc(h,i)*h%e,p=Oc(d,o)*d%e,g=Oc(p,s)*p%e,w=Oc(g,s)*p%e,_=Oc(w,n)*f%e;return{pow_p_5_8:Oc(_,$f)*r%e,b2:c}}function hC(r,e){let t=ie(e*e*e),n=ie(t*t*e),i=hxe(r*n).pow_p_5_8,o=ie(r*t*i),s=ie(e*o*o),a=o,c=ie(o*Hy),u=s===r,l=s===ie(-r),f=s===ie(-r*Hy);return u&&(o=a),(l||f)&&(o=c),Kf(o)&&(o=ie(-o)),{isValid:u||l,value:o}}function Kj(r){return hC(zt,r)}function Cb(r){return ie(Wy(r),Lr.l)}function pxe(r,e){if(r.length!==e.length)return!1;for(let t=0;t{if(r=qf(r),r.length<40||r.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return ie(Wy(r),Lr.l-zt)+zt},randomBytes:(r=32)=>{if(Vf.web)return Vf.web.getRandomValues(new Uint8Array(r));if(Vf.node){let{randomBytes:e}=Vf.node;return new Uint8Array(e(r).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Lc.randomBytes(32),sha512:async(...r)=>{let e=Vj(...r);if(Vf.web){let t=await Vf.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(t)}else{if(Vf.node)return Uint8Array.from(Vf.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(r=8,e=Vr.BASE){let t=e.equals(Vr.BASE)?e:new Vr(e.x,e.y);return t._setWindowSize(r),t.multiply($f),t},sha512Sync:void 0};Object.defineProperties(Lc,{sha512Sync:{configurable:!1,get(){return lC},set(r){lC||(lC=r)}}});var G1=32,rl=64,Lb=32;async function Gj(){let r=Lc.randomPrivateKey(),e=await H1(r);return{privateKey:Qj(r,e),publicKey:e}}async function jj(r){if(r.length!==Lb)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await H1(e);return{privateKey:Qj(e,t),publicKey:t}}async function Wj(r,e){let t=r.subarray(0,Lb);return Db(e,t)}async function Yj(r,e,t){return Ob(e,t,r)}function Qj(r,e){let t=new Uint8Array(rl);for(let n=0;ni+o.length,0));let t=vf(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return wf(t)}var yn={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var pC={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Bb(r){let e=(r==null?void 0:r.algorithm)??"AES-GCM",t=(r==null?void 0:r.keyLength)??16,n=(r==null?void 0:r.nonceLength)??12,i=(r==null?void 0:r.digest)??"SHA-256",o=(r==null?void 0:r.saltLength)??16,s=(r==null?void 0:r.iterations)??32767,a=yn.get();t*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(o)),p=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:p};typeof h=="string"&&(h=Ie(h));let w;if(h.length===0){w=await a.subtle.importKey("jwk",pC,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},m=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(x,m,{name:e,length:t},!0,["encrypt"])}catch{w=await a.subtle.importKey("jwk",pC,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},m=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(x,m,{name:e,length:t},!0,["encrypt"])}let _=await a.subtle.encrypt(g,w,f);return rt([d,g.iv,new Uint8Array(_)])}async function u(f,h){let d=f.subarray(0,o),p=f.subarray(o,o+n),g=f.subarray(o+n),w={name:e,iv:p};typeof h=="string"&&(h=Ie(h));let _;if(h.length===0)try{let m={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},y=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);_=await a.subtle.deriveKey(m,y,{name:e,length:t},!0,["decrypt"])}catch{_=await a.subtle.importKey("jwk",pC,{name:"AES-GCM"},!0,["decrypt"])}else{let m={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},y=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);_=await a.subtle.deriveKey(m,y,{name:e,length:t},!0,["decrypt"])}let x=await a.subtle.decrypt(w,_,g);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function j1(r,e){let n=await Bb().encrypt(r,e);return fh.encode(n)}var Q1={};xe(Q1,{KeyType:()=>Br,PrivateKey:()=>Fa,PublicKey:()=>Ua});var mC=new Float32Array([-0]),Hf=new Uint8Array(mC.buffer);function Zj(r,e,t){mC[0]=r,e[t]=Hf[0],e[t+1]=Hf[1],e[t+2]=Hf[2],e[t+3]=Hf[3]}function Jj(r,e){return Hf[0]=r[e],Hf[1]=r[e+1],Hf[2]=r[e+2],Hf[3]=r[e+3],mC[0]}var gC=new Float64Array([-0]),Oi=new Uint8Array(gC.buffer);function eW(r,e,t){gC[0]=r,e[t]=Oi[0],e[t+1]=Oi[1],e[t+2]=Oi[2],e[t+3]=Oi[3],e[t+4]=Oi[4],e[t+5]=Oi[5],e[t+6]=Oi[6],e[t+7]=Oi[7]}function tW(r,e){return Oi[0]=r[e],Oi[1]=r[e+1],Oi[2]=r[e+2],Oi[3]=r[e+3],Oi[4]=r[e+4],Oi[5]=r[e+5],Oi[6]=r[e+6],Oi[7]=r[e+7],gC[0]}var Exe=BigInt(Number.MAX_SAFE_INTEGER),vxe=BigInt(Number.MIN_SAFE_INTEGER),Rn=class{constructor(e,t){B(this,"lo");B(this,"hi");this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Fh;if(evxe)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>rW&&(i=0n,++n>rW&&(n=0n))),new Rn(Number(i),Number(n))}static fromNumber(e){if(e===0)return Fh;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Rn(n,i)}static from(e){return typeof e=="number"?Rn.fromNumber(e):typeof e=="bigint"?Rn.fromBigInt(e):typeof e=="string"?Rn.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Rn(e.low>>>0,e.high>>>0):Fh}},Fh=new Rn(0,0);Fh.toBigInt=function(){return 0n};Fh.zzEncode=Fh.zzDecode=function(){return this};Fh.length=function(){return 1};var rW=4294967296n;function nW(r){let e=0,t=0;for(let n=0;n191&&a<224?o[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function yC(r,e,t){let n=t,i,o;for(let s=0;s>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function Ma(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Mb(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var wC=class{constructor(e){B(this,"buf");B(this,"pos");B(this,"len");B(this,"_slice",Uint8Array.prototype.subarray);this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ma(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ma(this,4);return Mb(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ma(this,4);return Mb(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ma(this,4);let e=Jj(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ma(this,4);let e=tW(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Ma(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return iW(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ma(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ma(this);while(this.buf[this.pos++]&128);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(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Rn(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ma(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ma(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ma(this,8);let e=Mb(this.buf,this.pos+=4),t=Mb(this.buf,this.pos+=4);return new Rn(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=MI(this.buf,this.pos);return this.pos+=ti(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 bC(r){return new wC(r instanceof Uint8Array?r:r.subarray())}function Cn(r,e,t){let n=bC(r);return e.decode(n,void 0,t)}function _C(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return Ri(s);i+s>e&&(n=Ri(e),i=0);let a=n.subarray(i,i+=s);return i&7&&(i=(i|7)+1),a}}var zh=class{constructor(e,t,n){B(this,"fn");B(this,"len");B(this,"next");B(this,"val");this.fn=e,this.len=t,this.next=void 0,this.val=n}};function EC(){}var xC=class{constructor(e){B(this,"head");B(this,"tail");B(this,"len");B(this,"next");this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},xxe=_C();function Sxe(r){return globalThis.Buffer!=null?Ri(r):xxe(r)}var Qy=class{constructor(){B(this,"len");B(this,"head");B(this,"tail");B(this,"states");this.len=0,this.head=new zh(EC,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new zh(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new SC((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ub,10,Rn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Rn.fromBigInt(e);return this._push(Ub,t.length(),t)}uint64Number(e){return this._push(BI,ti(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){let t=Rn.fromBigInt(e).zzEncode();return this._push(Ub,t.length(),t)}sint64Number(e){let t=Rn.fromNumber(e).zzEncode();return this._push(Ub,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vC,1,e?1:0)}fixed32(e){return this._push(Yy,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Rn.fromBigInt(e);return this._push(Yy,4,t.lo)._push(Yy,4,t.hi)}fixed64Number(e){let t=Rn.fromNumber(e);return this._push(Yy,4,t.lo)._push(Yy,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(Zj,4,e)}double(e){return this._push(eW,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(vC,1,0):this.uint32(t)._push(Txe,t,e)}string(e){let t=nW(e);return t!==0?this.uint32(t)._push(yC,t,e):this._push(vC,1,0)}fork(){return this.states=new xC(this),this.head=this.tail=new zh(EC,0,0),this.len=0,this}reset(){return this.states!=null?(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 zh(EC,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Sxe(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function vC(r,e,t){e[t]=r&255}function Axe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var SC=class extends zh{constructor(t,n){super(Axe,t,n);B(this,"next");this.next=void 0}};function Ub(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Yy(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Txe(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Qy.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ixe,e,r),this},Qy.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Rxe,e,r),this});function Ixe(r,e,t){e.set(r,t)}function Rxe(r,e,t){r.length<40?yC(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(cr(r),t)}function AC(){return new Qy}function Pn(r,e){let t=AC();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var W1;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(W1||(W1={}));function Fb(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Y1(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return Fb("enum",W1.VARINT,t,n)}function kn(r,e){return Fb("message",W1.LENGTH_DELIMITED,r,e)}var Br;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Br||(Br={}));var TC;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(TC||(TC={}));(function(r){r.codec=()=>Y1(TC)})(Br||(Br={}));var Ua;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Br.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Br.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(Ua||(Ua={}));var Fa;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Br.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Br.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(Fa||(Fa={}));var Xy=class{constructor(e){B(this,"_key");this._key=X1(e,G1)}async verify(e,t){return Yj(this._key,t,e)}marshal(){return this._key}get bytes(){return Ua.encode({Type:Br.Ed25519,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}},Vh=class{constructor(e,t){B(this,"_key");B(this,"_publicKey");this._key=X1(e,rl),this._publicKey=X1(t,G1)}async sign(e){return Wj(this._key,e)}get public(){return new Xy(this._publicKey)}marshal(){return this._key}get bytes(){return Fa.encode({Type:Br.Ed25519,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}async id(){let e=Ii.digest(this.public.bytes);return pr.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return j1(this.bytes,e);throw new J(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Cxe(r){if(r.length>rl){r=X1(r,rl+G1);let n=r.subarray(0,rl),i=r.subarray(rl,r.length);return new Vh(n,i)}r=X1(r,rl);let e=r.subarray(0,rl),t=r.subarray(G1);return new Vh(e,t)}function Pxe(r){return r=X1(r,G1),new Xy(r)}async function kxe(){let{privateKey:r,publicKey:e}=await Gj();return new Vh(r,e)}async function IC(r){let{privateKey:e,publicKey:t}=await jj(r);return new Vh(e,t)}function X1(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new J(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var _ot=C(gr(),1),Eot=C(qy(),1),sW=C(at(),1);function za(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=rt([new Uint8Array(e-t.length),t])}return re(t,"base64url")}function Ko(r){let e=zb(r);return new sW.default.jsbn.BigInteger(re(e,"base16"),16)}function zb(r,e){let t=Ie(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=rt([new Uint8Array(e-t.length),t])}return t}var aW={"P-256":256,"P-384":384,"P-521":521},Nxe=Object.keys(aW),CC=Nxe.join(" / ");async function cW(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new J(`Unknown curve: ${r}. Must be ${CC}`,"ERR_INVALID_CURVE");let e=await yn.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(o,s)=>{let a;s!=null?a=await yn.get().subtle.importKey("jwk",Oxe(r,s),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await yn.get().subtle.importKey("jwk",lW(r,o),{name:"ECDH",namedCurve:r},!1,[]),u=await yn.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,aW[r]);return new Uint8Array(u,0,u.byteLength)},n=await yn.get().subtle.exportKey("jwk",e.publicKey);return{key:Dxe(n),genSharedKey:t}}var uW={"P-256":32,"P-384":48,"P-521":66};function Dxe(r){if(r.crv==null||r.x==null||r.y==null)throw new J("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new J(`Unknown curve: ${r.crv}. Must be ${CC}`,"ERR_INVALID_CURVE");let e=uW[r.crv];return rt([Uint8Array.from([4]),zb(r.x,e),zb(r.y,e)],1+e*2)}function lW(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new J(`Unknown curve: ${r}. Must be ${CC}`,"ERR_INVALID_CURVE");let t=uW[r];if(!mt(e.subarray(0,1),Uint8Array.from([4])))throw new J("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:re(e.subarray(1,t+1),"base64url"),y:re(e.subarray(1+t),"base64url"),ext:!0}}var Oxe=(r,e)=>({...lW(r,e.public),d:re(e.private,"base64url")});var fW=cW;async function dW(r,e){let t=fh.decode(r);return Bb().decrypt(t,e)}var hW={SHA1:20,SHA256:32,SHA512:64};var Lxe={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},Bxe=async(r,e)=>{let t=await yn.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function pW(r,e){let t=Lxe[r],n=await yn.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(i){return Bxe(n,i)},length:hW[r]}}var gW={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function yW(r,e,t){let n=gW[r];if(n==null){let x=Object.keys(gW).join(" / ");throw new J(`unknown cipher type '${r}'. Must be ${x}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new J("missing hash type","ERR_MISSING_HASH_TYPE");let i=n.keySize,o=n.ivSize,s=20,a=Ie("key expansion"),c=2*(o+i+s),u=await pW(e,t),l=await u.digest(a),f=[],h=0;for(;hc&&(m=c-h),f.push(x),h+=m,l=await u.digest(l)}let d=c/2,p=rt(f),g=p.subarray(0,d),w=p.subarray(d,c),_=x=>({iv:x.subarray(0,o),cipherKey:x.subarray(o,o+i),macKey:x.subarray(o+i)});return{k1:_(g),k2:_(w)}}var zC={};xe(zC,{RsaPrivateKey:()=>om,RsaPublicKey:()=>i3,fromJwk:()=>sSe,generateKeyPair:()=>aSe,unmarshalRsaPrivateKey:()=>iSe,unmarshalRsaPublicKey:()=>oSe});var n3=C(at(),1);var dst=C(NC(),1);var Uxe=C(Ju(),1);var Vt=BigInt(0),Ur=BigInt(1),jf=BigInt(2),e3=BigInt(3),vW=BigInt(8),nn=Object.freeze({a:Vt,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Ur,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),xW=(r,e)=>(r+e/jf)/e,Vb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(r){let{n:e}=nn,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ur*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,s=BigInt("0x100000000000000000000000000000000"),a=xW(o*r,e),c=xW(-n*r,e),u=Te(r-a*t-c*i,e),l=Te(-a*n-c*o,e),f=u>s,h=l>s;if(f&&(u=e-u),h&&(l=e-l),u>s||l>s)throw new Error("splitScalarEndo: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:h,k2:l}}},Va=32,em=32,Fxe=32,SW=Va+1,AW=2*Va+1;function TW(r){let{a:e,b:t}=nn,n=Te(r*r),i=Te(n*r);return Te(i+e*r+t)}var Kb=nn.a===Vt,Hb=class extends Error{constructor(e){super(e)}};function IW(r){if(!(r instanceof jt))throw new TypeError("JacobianPoint expected")}var jt=class{constructor(e,t,n){this.x=e,this.y=t,this.z=n}static fromAffine(e){if(!(e instanceof Kt))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Kt.ZERO)?jt.ZERO:new jt(e.x,e.y,Ur)}static toAffineBatch(e){let t=qxe(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return jt.toAffineBatch(e).map(jt.fromAffine)}equals(e){IW(e);let{x:t,y:n,z:i}=this,{x:o,y:s,z:a}=e,c=Te(i*i),u=Te(a*a),l=Te(t*u),f=Te(o*c),h=Te(Te(n*a)*u),d=Te(Te(s*i)*c);return l===f&&h===d}negate(){return new jt(this.x,Te(-this.y),this.z)}double(){let{x:e,y:t,z:n}=this,i=Te(e*e),o=Te(t*t),s=Te(o*o),a=e+o,c=Te(jf*(Te(a*a)-i-s)),u=Te(e3*i),l=Te(u*u),f=Te(l-jf*c),h=Te(u*(c-f)-vW*s),d=Te(jf*t*n);return new jt(f,h,d)}add(e){IW(e);let{x:t,y:n,z:i}=this,{x:o,y:s,z:a}=e;if(o===Vt||s===Vt)return this;if(t===Vt||n===Vt)return e;let c=Te(i*i),u=Te(a*a),l=Te(t*u),f=Te(o*c),h=Te(Te(n*a)*u),d=Te(Te(s*i)*c),p=Te(f-l),g=Te(d-h);if(p===Vt)return g===Vt?this.double():jt.ZERO;let w=Te(p*p),_=Te(p*w),x=Te(l*w),m=Te(g*g-_-jf*x),y=Te(g*(x-m)-h*_),b=Te(i*a*p);return new jt(m,y,b)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=jt.ZERO;if(typeof e=="bigint"&&e===Vt)return t;let n=PW(e);if(n===Ur)return this;if(!Kb){let f=t,h=this;for(;n>Vt;)n&Ur&&(f=f.add(h)),h=h.double(),n>>=Ur;return f}let{k1neg:i,k1:o,k2neg:s,k2:a}=Vb.splitScalar(n),c=t,u=t,l=this;for(;o>Vt||a>Vt;)o&Ur&&(c=c.add(l)),a&Ur&&(u=u.add(l)),l=l.double(),o>>=Ur,a>>=Ur;return i&&(c=c.negate()),s&&(u=u.negate()),u=new jt(Te(u.x*Vb.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let t=Kb?128/e+1:256/e+1,n=[],i=this,o=i;for(let s=0;s>=f,p>c&&(p-=l,e+=Ur);let g=d,w=d+Math.abs(p)-1,_=h%2!==0,x=p<0;p===0?s=s.add($b(_,i[g])):o=o.add($b(x,i[w]))}return{p:o,f:s}}multiply(e,t){let n=PW(e),i,o;if(Kb){let{k1neg:s,k1:a,k2neg:c,k2:u}=Vb.splitScalar(n),{p:l,f}=this.wNAF(a,t),{p:h,f:d}=this.wNAF(u,t);l=$b(s,l),h=$b(c,h),h=new jt(Te(h.x*Vb.beta),h.y,h.z),i=l.add(h),o=f.add(d)}else{let{p:s,f:a}=this.wNAF(n,t);i=s,o=a}return jt.normalizeZ([i,o])[0]}toAffine(e){let{x:t,y:n,z:i}=this,o=this.equals(jt.ZERO);e==null&&(e=o?vW:nm(i));let s=e,a=Te(s*s),c=Te(a*s),u=Te(t*a),l=Te(n*c),f=Te(i*s);if(o)return Kt.ZERO;if(f!==Ur)throw new Error("invZ was invalid");return new Kt(u,l)}};jt.BASE=new jt(nn.Gx,nn.Gy,Ur);jt.ZERO=new jt(Vt,Ur,Vt);function $b(r,e){let t=e.negate();return r?t:e}var OC=new WeakMap,Kt=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,OC.delete(this)}hasEvenY(){return this.y%jf===Vt}static fromCompressedHex(e){let t=e.length===32,n=Wf(t?e:e.subarray(1));if(!DC(n))throw new Error("Point is not on curve");let i=TW(n),o=$xe(i),s=(o&Ur)===Ur;t?s&&(o=Te(-o)):(e[0]&1)===1!==s&&(o=Te(-o));let a=new Kt(n,o);return a.assertValidity(),a}static fromUncompressedHex(e){let t=Wf(e.subarray(1,Va+1)),n=Wf(e.subarray(Va+1,Va*2+1)),i=new Kt(t,n);return i.assertValidity(),i}static fromHex(e){let t=rm(e),n=t.length,i=t[0];if(n===Va)return this.fromCompressedHex(t);if(n===SW&&(i===2||i===3))return this.fromCompressedHex(t);if(n===AW&&i===4)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${SW} compressed bytes or ${AW} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return Kt.BASE.multiply(jb(e))}static fromSignature(e,t,n){let{r:i,s:o}=kW(t);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let s=MC(rm(e)),{n:a}=nn,c=n===2||n===3?i+a:i,u=nm(c,a),l=Te(-s*u,a),f=Te(o*u,a),h=n&1?"03":"02",d=Kt.fromHex(h+Z1(c)),p=Kt.BASE.multiplyAndAddUnsafe(d,l,f);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return $h(this.toHex(e))}toHex(e=!1){let t=Z1(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Z1(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:n}=this;if(!DC(t)||!DC(n))throw new Error(e);let i=Te(n*n),o=TW(t);if(Te(i-o)!==Vt)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Kt(this.x,Te(-this.y))}double(){return jt.fromAffine(this).double().toAffine()}add(e){return jt.fromAffine(this).add(jt.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return jt.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,n){let i=jt.fromAffine(this),o=t===Vt||t===Ur||this!==Kt.BASE?i.multiplyUnsafe(t):i.multiply(t),s=jt.fromAffine(e).multiplyUnsafe(n),a=o.add(s);return a.equals(jt.ZERO)?void 0:a.toAffine()}};Kt.BASE=new Kt(nn.Gx,nn.Gy);Kt.ZERO=new Kt(Vt,Vt);function RW(r){return Number.parseInt(r[0],16)>=8?"00"+r:r}function CW(r){if(r.length<2||r[0]!==2)throw new Error(`Invalid signature integer tag: ${tm(r)}`);let e=r[1],t=r.subarray(2,e+2);if(!e||t.length!==e)throw new Error("Invalid signature integer: wrong length");if(t[0]===0&&t[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Wf(t),left:r.subarray(e+2)}}function zxe(r){if(r.length<2||r[0]!=48)throw new Error(`Invalid signature tag: ${tm(r)}`);if(r[1]!==r.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:t}=CW(r.subarray(2)),{data:n,left:i}=CW(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${tm(i)}`);return{r:e,s:n}}var Bc=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!t)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=t?tm(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Bc(Gb(i.slice(0,64)),Gb(i.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if(typeof e!="string"&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=zxe(t?e:$h(e));return new Bc(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!r3(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!r3(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=nn.n>>Ur;return this.s>e}normalizeS(){return this.hasHighS()?new Bc(this.r,Te(-this.s,nn.n)):this}toDERRawBytes(){return $h(this.toDERHex())}toDERHex(){let e=RW(Jy(this.s)),t=RW(Jy(this.r)),n=e.length/2,i=t.length/2,o=Jy(n),s=Jy(i);return`30${Jy(i+n+4)}02${s}${t}02${o}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return $h(this.toCompactHex())}toCompactHex(){return Z1(this.r)+Z1(this.s)}};function Gf(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function tm(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;t0)return BigInt(r);if(typeof r=="bigint"&&r3(r))return r;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Te(r,e=nn.P){let t=r%e;return t>=Vt?t:e+t}function Ls(r,e){let{P:t}=nn,n=r;for(;e-- >Vt;)n*=n,n%=t;return n}function $xe(r){let{P:e}=nn,t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),s=BigInt(44),a=BigInt(88),c=r*r*r%e,u=c*c*r%e,l=Ls(u,e3)*u%e,f=Ls(l,e3)*u%e,h=Ls(f,jf)*c%e,d=Ls(h,n)*h%e,p=Ls(d,i)*d%e,g=Ls(p,s)*p%e,w=Ls(g,a)*g%e,_=Ls(w,s)*p%e,x=Ls(_,e3)*u%e,m=Ls(x,o)*d%e,y=Ls(m,t)*c%e,b=Ls(y,jf);if(b*b%e!==r)throw new Error("Cannot find square root");return b}function nm(r,e=nn.P){if(r===Vt||e<=Vt)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Te(r,e),n=e,i=Vt,o=Ur,s=Ur,a=Vt;for(;t!==Vt;){let u=n/t,l=n%t,f=i-s*u,h=o-a*u;n=t,t=l,i=s,o=a,s=f,a=h}if(n!==Ur)throw new Error("invert: does not exist");return Te(i,e)}function qxe(r,e=nn.P){let t=new Array(r.length),n=r.reduce((o,s,a)=>s===Vt?o:(t[a]=o,Te(o*s,e)),Ur),i=nm(n,e);return r.reduceRight((o,s,a)=>s===Vt?o:(t[a]=Te(o*t[a],e),Te(o*s,e)),i),t}function Hxe(r){let e=r.length*8-em*8,t=Wf(r);return e>0?t>>BigInt(e):t}function MC(r,e=!1){let t=Hxe(r);if(e)return t;let{n}=nn;return t>=n?t-n:t}var J1,t3,BC=class{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||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 ro.hmacSha256(this.k,...e)}hmacSync(...e){return t3(this.k,...e)}checkSync(){if(typeof t3!="function")throw new Hb("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),e.length!==0&&(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),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e0)e=BigInt(r);else if(typeof r=="string"){if(r.length!==2*em)throw new Error("Expected 32 bytes of private key");e=Gb(r)}else if(r instanceof Uint8Array){if(r.length!==em)throw new Error("Expected 32 bytes of private key");e=Wf(r)}else throw new TypeError("Expected valid private key");if(!r3(e))throw new Error("Expected private key: 0 < key < n");return e}function jxe(r){return r instanceof Kt?(r.assertValidity(),r):Kt.fromHex(r)}function kW(r){if(r instanceof Bc)return r.assertValidity(),r;try{return Bc.fromDER(r)}catch{return Bc.fromCompact(r)}}function im(r,e=!1){return Kt.fromPrivateKey(r).toRawBytes(e)}function NW(r){let e=r.length>Va?r.slice(0,Va):r;return Wf(e)}function Wxe(r){let e=NW(r),t=Te(e,nn.n);return DW(t{r=rm(r);let e=em+8;if(r.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let t=Te(Wf(r),nn.n-Ur)+Ur;return LC(t)},randomBytes:(r=32)=>{if($o.web)return $o.web.getRandomValues(new Uint8Array(r));if($o.node){let{randomBytes:e}=$o.node;return Uint8Array.from(e(r))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>ro.hashToPrivateKey(ro.randomBytes(em+8)),precompute(r=8,e=Kt.BASE){let t=e===Kt.BASE?e:new Kt(e.x,e.y);return t._setWindowSize(r),t.multiply(e3),t},sha256:async(...r)=>{if($o.web){let e=await $o.web.subtle.digest("SHA-256",Gf(...r));return new Uint8Array(e)}else if($o.node){let{createHash:e}=$o.node,t=e("sha256");return r.forEach(n=>t.update(n)),Uint8Array.from(t.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(r,...e)=>{if($o.web){let t=await $o.web.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Gf(...e),i=await $o.web.subtle.sign("HMAC",t,n);return new Uint8Array(i)}else if($o.node){let{createHmac:t}=$o.node,n=t("sha256",r);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(r,...e)=>{let t=qb[r];if(t===void 0){let n=await ro.sha256(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Gf(n,n),qb[r]=t}return ro.sha256(t,...e)},taggedHashSync:(r,...e)=>{if(typeof J1!="function")throw new Hb("sha256Sync is undefined, you need to set it");let t=qb[r];if(t===void 0){let n=J1(Uint8Array.from(r,i=>i.charCodeAt(0)));t=Gf(n,n),qb[r]=t}return J1(t,...e)},_JacobianPoint:jt};Object.defineProperties(ro,{sha256Sync:{configurable:!1,get(){return J1},set(r){J1||(J1=r)}},hmacSha256Sync:{configurable:!1,get(){return t3},set(r){t3||(t3=r)}}});function Mc(r){if(isNaN(r)||r<=0)throw new J("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ro.randomBytes(r)}var Wot=C(Bh(),1),UC=C(at(),1);function LW(r,e){return e.map(t=>Ko(r[t]))}function BW(r){return UC.default.pki.setRsaPrivateKey(...LW(r,["n","e","d","p","q","dp","dq","qi"]))}function MW(r){return UC.default.pki.setRsaPublicKey(...LW(r,["n","e"]))}var qh={};xe(qh,{jwkToPkcs1:()=>Jxe,jwkToPkix:()=>tSe,pkcs1ToJwk:()=>Zxe,pkixToJwk:()=>eSe});var Xot=C(Ic(),1),Zot=C(Bh(),1);var nl=C(at(),1);function Zxe(r){let e=nl.default.asn1.fromDer(re(r,"ascii")),t=nl.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:za(t.n),e:za(t.e),d:za(t.d),p:za(t.p),q:za(t.q),dp:za(t.dP),dq:za(t.dQ),qi:za(t.qInv),alg:"RS256"}}function Jxe(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new J("JWK was missing components","ERR_INVALID_PARAMETERS");let e=nl.default.pki.privateKeyToAsn1({n:Ko(r.n),e:Ko(r.e),d:Ko(r.d),p:Ko(r.p),q:Ko(r.q),dP:Ko(r.dp),dQ:Ko(r.dq),qInv:Ko(r.qi)});return Ie(nl.default.asn1.toDer(e).getBytes(),"ascii")}function eSe(r){let e=nl.default.asn1.fromDer(re(r,"ascii")),t=nl.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:za(t.n),e:za(t.e)}}function tSe(r){if(r.n==null||r.e==null)throw new J("JWK was missing components","ERR_INVALID_PARAMETERS");let e=nl.default.pki.publicKeyToAsn1({n:Ko(r.n),e:Ko(r.e)});return Ie(nl.default.asn1.toDer(e).getBytes(),"ascii")}async function UW(r){let e=await yn.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await VW(e);return{privateKey:t[0],publicKey:t[1]}}async function FC(r){let t=[await yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await rSe(r)],n=await VW({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function FW(r,e){let t=await yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await yn.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function zW(r,e,t){let n=await yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return yn.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function VW(r){if(r.privateKey==null||r.publicKey==null)throw new J("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([yn.get().subtle.exportKey("jwk",r.privateKey),yn.get().subtle.exportKey("jwk",r.publicKey)])}async function rSe(r){return yn.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function KW(r,e,t,n){let i=e?MW(r):BW(r),o=re(Uint8Array.from(t),"ascii"),s=n(o,i);return Ie(s,"ascii")}function $W(r,e){return KW(r,!0,e,(t,n)=>n.encrypt(t))}function qW(r,e){return KW(r,!1,e,(t,n)=>n.decrypt(t))}var i3=class{constructor(e){B(this,"_key");this._key=e}async verify(e,t){return zW(this._key,t,e)}marshal(){return qh.jwkToPkix(this._key)}get bytes(){return Ua.encode({Type:Br.RSA,Data:this.marshal()}).subarray()}encrypt(e){return $W(this._key,e)}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}},om=class{constructor(e,t){B(this,"_key");B(this,"_publicKey");this._key=e,this._publicKey=t}genSecret(){return Mc(16)}async sign(e){return FW(this._key,e)}get public(){if(this._publicKey==null)throw new J("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new i3(this._publicKey)}decrypt(e){return qW(this._key,e)}marshal(){return qh.jwkToPkcs1(this._key)}get bytes(){return Fa.encode({Type:Br.RSA,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}async id(){let e=await this.public.hash();return re(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new n3.default.util.ByteBuffer(this.marshal()),i=n3.default.asn1.fromDer(n),o=n3.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return n3.default.pki.encryptRsaPrivateKey(o,e,s)}else{if(t==="libp2p-key")return j1(this.bytes,e);throw new J(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function iSe(r){let e=qh.pkcs1ToJwk(r),t=await FC(e);return new om(t.privateKey,t.publicKey)}function oSe(r){let e=qh.pkixToJwk(r);return new i3(e)}async function sSe(r){let e=await FC(r);return new om(e.privateKey,e.publicKey)}async function aSe(r){let e=await UW(r);return new om(e.privateKey,e.publicKey)}var KC={};xe(KC,{Secp256k1PrivateKey:()=>s3,Secp256k1PublicKey:()=>o3,generateKeyPair:()=>fSe,unmarshalSecp256k1PrivateKey:()=>uSe,unmarshalSecp256k1PublicKey:()=>lSe});function HW(){return ro.randomPrivateKey()}async function GW(r,e){let{digest:t}=await dt.digest(e);try{return await Wb(t,r)}catch(n){throw new J(String(n),"ERR_INVALID_INPUT")}}async function jW(r,e,t){try{let{digest:n}=await dt.digest(t);return Yb(e,n,r)}catch(n){throw new J(String(n),"ERR_INVALID_INPUT")}}function WW(r){return Kt.fromHex(r).toRawBytes(!0)}function YW(r){try{im(r,!0)}catch(e){throw new J(String(e),"ERR_INVALID_PRIVATE_KEY")}}function VC(r){try{Kt.fromHex(r)}catch(e){throw new J(String(e),"ERR_INVALID_PUBLIC_KEY")}}function QW(r){try{return im(r,!0)}catch(e){throw new J(String(e),"ERR_INVALID_PRIVATE_KEY")}}var o3=class{constructor(e){B(this,"_key");VC(e),this._key=e}async verify(e,t){return jW(this._key,t,e)}marshal(){return WW(this._key)}get bytes(){return Ua.encode({Type:Br.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}},s3=class{constructor(e,t){B(this,"_key");B(this,"_publicKey");this._key=e,this._publicKey=t??QW(e),YW(this._key),VC(this._publicKey)}async sign(e){return GW(this._key,e)}get public(){return new o3(this._publicKey)}marshal(){return this._key}get bytes(){return Fa.encode({Type:Br.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return mt(this.bytes,e.bytes)}async hash(){let{bytes:e}=await dt.digest(this.bytes);return e}async id(){let e=await this.public.hash();return re(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return j1(this.bytes,e);throw new J(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function uSe(r){return new s3(r)}function lSe(r){return new o3(r)}async function fSe(){let r=HW();return new s3(r)}var Uc={rsa:zC,ed25519:RC,secp256k1:KC};function $C(r){let e=Object.keys(Uc).join(" / ");return new J(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function qC(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Uc[r];throw $C(r)}async function Xb(r,e){return qC(r).generateKeyPair(e??2048)}async function dSe(r,e,t){if(r.toLowerCase()!=="ed25519")throw new J("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return IC(e)}function Bs(r){let e=Ua.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Br.RSA:return Uc.rsa.unmarshalRsaPublicKey(t);case Br.Ed25519:return Uc.ed25519.unmarshalEd25519PublicKey(t);case Br.Secp256k1:return Uc.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw $C(e.Type??"RSA")}}function a3(r,e){return e=(e??"rsa").toLowerCase(),qC(e),r.bytes}async function Li(r){let e=Fa.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Br.RSA:return Uc.rsa.unmarshalRsaPrivateKey(t);case Br.Ed25519:return Uc.ed25519.unmarshalEd25519PrivateKey(t);case Br.Secp256k1:return Uc.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw $C(e.Type??"RSA")}}function HC(r,e){return e=(e??"rsa").toLowerCase(),qC(e),r.bytes}async function c3(r,e){try{let i=await dW(r,e);return await Li(i)}catch{}let t=Qb.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new J("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Qb.default.asn1.toDer(Qb.default.pki.privateKeyToAsn1(t));return n=Ie(n.getBytes(),"ascii"),Uc.rsa.unmarshalRsaPrivateKey(n)}var AP=C(ee(),1);var hm=C(ee(),1);var XW="ERR_IPNS_EXPIRED_RECORD",u3="ERR_UNRECOGNIZED_VALIDITY",ZW="ERR_SIGNATURE_CREATION",Yf="ERR_SIGNATURE_VERIFICATION",JW="ERR_UNRECOGNIZED_FORMAT";var GC="ERR_UNDEFINED_PARAMETER",eY="ERR_INVALID_RECORD_DATA",tY="ERR_INVALID_EMBEDDED_KEY",rY="ERR_MISSING_PRIVATE_KEY";var oP=C(XC(),1),xY=C(mY(),1),sP=C(iP(),1),SY=C(vY(),1),AY=C(Gh(),1);function bSe(){AY.default._configure(),oP.default._configure(xY.default),sP.default._configure(SY.default)}bSe();var TY=["uint64","int64","sint64","fixed64","sfixed64"];function _Se(r){for(let e of TY){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function aP(r){return _Se(new oP.default(r))}function ESe(r){for(let e of TY){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function cP(){return ESe(sP.default.create())}function uP(r,e){let t=aP(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function lP(r,e){let t=cP();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var sm;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(sm||(sm={}));function t_(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function fP(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return t_("enum",sm.VARINT,t,n)}function dP(r,e){return t_("message",sm.LENGTH_DELIMITED,r,e)}var mo;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>fP(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=dP((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.value!=null&&(o.uint32(10),o.bytes(i.value)),i.signature!=null&&(o.uint32(18),o.bytes(i.signature)),i.validityType!=null&&(o.uint32(24),r.ValidityType.codec().encode(i.validityType,o)),i.validity!=null&&(o.uint32(34),o.bytes(i.validity)),i.sequence!=null&&(o.uint32(40),o.uint64(i.sequence)),i.ttl!=null&&(o.uint32(48),o.uint64(i.ttl)),i.pubKey!=null&&(o.uint32(58),o.bytes(i.pubKey)),i.signatureV2!=null&&(o.uint32(66),o.bytes(i.signatureV2)),i.data!=null&&(o.uint32(74),o.bytes(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={},a=o==null?i.len:i.pos+o;for(;i.pos>>3){case 1:s.value=i.bytes();break;case 2:s.signature=i.bytes();break;case 3:s.validityType=r.ValidityType.codec().decode(i);break;case 4:s.validity=i.bytes();break;case 5:s.sequence=i.uint64();break;case 6:s.ttl=i.uint64();break;case 7:s.pubKey=i.bytes();break;case 8:s.signatureV2=i.bytes();break;case 9:s.data=i.bytes();break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>lP(i,r.codec()),r.decode=i=>uP(i,r.codec())})(mo||(mo={}));var vSe=["string","number","bigint","symbol"],xSe=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function IY(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(vSe.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(SSe(r))return"Buffer";let t=ASe(r);return t||"Object"}function SSe(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function ASe(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(xSe.includes(e))return e}var Z=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};Z.uint=new Z(0,"uint",!0);Z.negint=new Z(1,"negint",!0);Z.bytes=new Z(2,"bytes",!0);Z.string=new Z(3,"string",!0);Z.array=new Z(4,"array",!1);Z.map=new Z(5,"map",!1);Z.tag=new Z(6,"tag",!1);Z.float=new Z(7,"float",!0);Z.false=new Z(7,"false",!0);Z.true=new Z(7,"true",!0);Z.null=new Z(7,"null",!0);Z.undefined=new Z(7,"undefined",!0);Z.break=new Z(7,"break",!0);var Re=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var am=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",TSe=new TextDecoder,ISe=new TextEncoder;function r_(r){return am&&globalThis.Buffer.isBuffer(r)}function hP(r){return r instanceof Uint8Array?r_(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var kY=am?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):CY(r,e,t):(r,e,t)=>t-e>64?TSe.decode(r.subarray(e,t)):CY(r,e,t),NY=am?r=>r.length>64?globalThis.Buffer.from(r):RY(r):r=>r.length>64?ISe.encode(r):RY(r),zc=r=>Uint8Array.from(r),cm=am?(r,e,t)=>r_(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),DY=am?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),hP(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},OY=am?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function LY(r,e){if(r_(r)&&r_(e))return r.compare(e);for(let t=0;t55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return o}function CY(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(o=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(o=l))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return RSe(n)}var PY=4096;function RSe(r){let e=r.length;if(e<=PY)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=cm(n,0,this.cursor)}else t=DY(this.chunks,this.cursor);return e&&this.reset(),t}};var it="CBOR decode error:",pP="CBOR encode error:",h3=[];h3[23]=1;h3[24]=2;h3[25]=3;h3[26]=5;h3[27]=9;function il(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${it} encountered BigInt larger than allowable range`)}}Us.encodedSize=function(e){return wi.encodedSize(e.value)};wi.encodedSize=function(e){return et.value?1:0};function zY(r,e,t,n){return new Re(Z.negint,-1-qo(r,e+1,n),2)}function VY(r,e,t,n){return new Re(Z.negint,-1-Ho(r,e+1,n),3)}function KY(r,e,t,n){return new Re(Z.negint,-1-Go(r,e+1,n),5)}var mP=BigInt(-1),$Y=BigInt(1);function qY(r,e,t,n){let i=jo(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new Re(Z.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${it} integers outside of the safe integer range are not supported`);return new Re(Z.negint,mP-BigInt(i),9)}function n_(r,e){let t=e.value,n=typeof t=="bigint"?t*mP-$Y:t*-1-1;wi(r,e.type.majorEncoded,n)}n_.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*mP-$Y:t*-1-1;return nt.value?-1:0};function p3(r,e,t,n){il(r,e,t+n);let i=cm(r,e+t,e+t+n);return new Re(Z.bytes,i,t+n)}function HY(r,e,t,n){return p3(r,e,1,t)}function GY(r,e,t,n){return p3(r,e,2,qo(r,e+1,n))}function jY(r,e,t,n){return p3(r,e,3,Ho(r,e+1,n))}function WY(r,e,t,n){return p3(r,e,5,Go(r,e+1,n))}function YY(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer bytes lengths not supported`);return p3(r,e,9,i)}function i_(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===Z.string?NY(r.value):r.value),r.encodedBytes}function um(r,e){let t=i_(e);wi(r,e.type.majorEncoded,t.length),r.push(t)}um.encodedSize=function(e){let t=i_(e);return wi.encodedSize(t.length)+t.length};um.compareTokens=function(e,t){return kSe(i_(e),i_(t))};function kSe(r,e){return r.lengthe.length?1:LY(r,e)}function m3(r,e,t,n,i){let o=t+n;il(r,e,o);let s=new Re(Z.string,kY(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=cm(r,e+t,e+o)),s}function QY(r,e,t,n){return m3(r,e,1,t,n)}function XY(r,e,t,n){return m3(r,e,2,qo(r,e+1,n),n)}function ZY(r,e,t,n){return m3(r,e,3,Ho(r,e+1,n),n)}function JY(r,e,t,n){return m3(r,e,5,Go(r,e+1,n),n)}function eQ(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer string lengths not supported`);return m3(r,e,9,i,n)}var tQ=um;function lm(r,e,t,n){return new Re(Z.array,n,t)}function rQ(r,e,t,n){return lm(r,e,1,t)}function nQ(r,e,t,n){return lm(r,e,2,qo(r,e+1,n))}function iQ(r,e,t,n){return lm(r,e,3,Ho(r,e+1,n))}function oQ(r,e,t,n){return lm(r,e,5,Go(r,e+1,n))}function sQ(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer array lengths not supported`);return lm(r,e,9,i)}function aQ(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${it} indefinite length items not allowed`);return lm(r,e,1,1/0)}function o_(r,e){wi(r,Z.array.majorEncoded,e.value)}o_.compareTokens=Us.compareTokens;o_.encodedSize=function(e){return wi.encodedSize(e.value)};function fm(r,e,t,n){return new Re(Z.map,n,t)}function cQ(r,e,t,n){return fm(r,e,1,t)}function uQ(r,e,t,n){return fm(r,e,2,qo(r,e+1,n))}function lQ(r,e,t,n){return fm(r,e,3,Ho(r,e+1,n))}function fQ(r,e,t,n){return fm(r,e,5,Go(r,e+1,n))}function dQ(r,e,t,n){let i=jo(r,e+1,n);if(typeof i=="bigint")throw new Error(`${it} 64-bit integer map lengths not supported`);return fm(r,e,9,i)}function hQ(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${it} indefinite length items not allowed`);return fm(r,e,1,1/0)}function s_(r,e){wi(r,Z.map.majorEncoded,e.value)}s_.compareTokens=Us.compareTokens;s_.encodedSize=function(e){return wi.encodedSize(e.value)};function pQ(r,e,t,n){return new Re(Z.tag,t,1)}function mQ(r,e,t,n){return new Re(Z.tag,qo(r,e+1,n),2)}function gQ(r,e,t,n){return new Re(Z.tag,Ho(r,e+1,n),3)}function yQ(r,e,t,n){return new Re(Z.tag,Go(r,e+1,n),5)}function wQ(r,e,t,n){return new Re(Z.tag,jo(r,e+1,n),9)}function a_(r,e){wi(r,Z.tag.majorEncoded,e.value)}a_.compareTokens=Us.compareTokens;a_.encodedSize=function(e){return wi.encodedSize(e.value)};var MSe=20,USe=21,FSe=22,zSe=23;function bQ(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${it} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Re(Z.null,null,1):new Re(Z.undefined,void 0,1)}function _Q(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${it} indefinite length items not allowed`);return new Re(Z.break,void 0,1)}function gP(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${it} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${it} Infinity values are not supported`)}return new Re(Z.float,r,e)}function EQ(r,e,t,n){return gP(yP(r,e+1),3,n)}function vQ(r,e,t,n){return gP(wP(r,e+1),5,n)}function xQ(r,e,t,n){return gP(IQ(r,e+1),9,n)}function c_(r,e,t){let n=e.value;if(n===!1)r.push([Z.float.majorEncoded|MSe]);else if(n===!0)r.push([Z.float.majorEncoded|USe]);else if(n===null)r.push([Z.float.majorEncoded|FSe]);else if(n===void 0)r.push([Z.float.majorEncoded|zSe]);else{let i,o=!1;(!t||t.float64!==!0)&&(AQ(n),i=yP(qa,1),n===i||Number.isNaN(n)?(qa[0]=249,r.push(qa.slice(0,3)),o=!0):(TQ(n),i=wP(qa,1),n===i&&(qa[0]=250,r.push(qa.slice(0,5)),o=!0))),o||(VSe(n),i=IQ(qa,1),qa[0]=251,r.push(qa.slice(0,9)))}}c_.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){AQ(n);let i=yP(qa,1);if(n===i||Number.isNaN(n))return 3;if(TQ(n),i=wP(qa,1),n===i)return 5}return 9};var SQ=new ArrayBuffer(9),Fs=new DataView(SQ,1),qa=new Uint8Array(SQ,0);function AQ(r){if(r===1/0)Fs.setUint16(0,31744,!1);else if(r===-1/0)Fs.setUint16(0,64512,!1);else if(Number.isNaN(r))Fs.setUint16(0,32256,!1);else{Fs.setFloat32(0,r);let e=Fs.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Fs.setUint16(0,31744,!1);else if(t===0)Fs.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Fs.setUint16(0,0):i<-14?Fs.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Fs.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function yP(r,e){if(r.length-e<2)throw new Error(`${it} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function TQ(r){Fs.setFloat32(0,r,!1)}function wP(r,e){if(r.length-e<4)throw new Error(`${it} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function VSe(r){Fs.setFloat64(0,r,!1)}function IQ(r,e){if(r.length-e<8)throw new Error(`${it} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}c_.compareTokens=Us.compareTokens;function tr(r,e,t){throw new Error(`${it} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function u_(r){return()=>{throw new Error(`${it} ${r}`)}}var me=[];for(let r=0;r<=23;r++)me[r]=tr;me[24]=BY;me[25]=MY;me[26]=UY;me[27]=FY;me[28]=tr;me[29]=tr;me[30]=tr;me[31]=tr;for(let r=32;r<=55;r++)me[r]=tr;me[56]=zY;me[57]=VY;me[58]=KY;me[59]=qY;me[60]=tr;me[61]=tr;me[62]=tr;me[63]=tr;for(let r=64;r<=87;r++)me[r]=HY;me[88]=GY;me[89]=jY;me[90]=WY;me[91]=YY;me[92]=tr;me[93]=tr;me[94]=tr;me[95]=u_("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)me[r]=QY;me[120]=XY;me[121]=ZY;me[122]=JY;me[123]=eQ;me[124]=tr;me[125]=tr;me[126]=tr;me[127]=u_("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)me[r]=rQ;me[152]=nQ;me[153]=iQ;me[154]=oQ;me[155]=sQ;me[156]=tr;me[157]=tr;me[158]=tr;me[159]=aQ;for(let r=160;r<=183;r++)me[r]=cQ;me[184]=uQ;me[185]=lQ;me[186]=fQ;me[187]=dQ;me[188]=tr;me[189]=tr;me[190]=tr;me[191]=hQ;for(let r=192;r<=215;r++)me[r]=pQ;me[216]=mQ;me[217]=gQ;me[218]=yQ;me[219]=wQ;me[220]=tr;me[221]=tr;me[222]=tr;me[223]=tr;for(let r=224;r<=243;r++)me[r]=u_("simple values are not supported");me[244]=tr;me[245]=tr;me[246]=tr;me[247]=bQ;me[248]=u_("simple values are not supported");me[249]=EQ;me[250]=vQ;me[251]=xQ;me[252]=tr;me[253]=tr;me[254]=tr;me[255]=_Q;var Ha=[];for(let r=0;r<24;r++)Ha[r]=new Re(Z.uint,r,1);for(let r=-1;r>=-24;r--)Ha[31-r]=new Re(Z.negint,r,1);Ha[64]=new Re(Z.bytes,new Uint8Array(0),1);Ha[96]=new Re(Z.string,"",1);Ha[128]=new Re(Z.array,0,1);Ha[160]=new Re(Z.map,0,1);Ha[244]=new Re(Z.false,!1,1);Ha[245]=new Re(Z.true,!0,1);Ha[246]=new Re(Z.null,null,1);function RQ(r){switch(r.type){case Z.false:return zc([244]);case Z.true:return zc([245]);case Z.null:return zc([246]);case Z.bytes:return r.value.length?void 0:zc([64]);case Z.string:return r.value===""?zc([96]):void 0;case Z.array:return r.value===0?zc([128]):void 0;case Z.map:return r.value===0?zc([160]):void 0;case Z.uint:return r.value<24?zc([Number(r.value)]):void 0;case Z.negint:if(r.value>=-24)return zc([31-Number(r.value)])}}var $Se={float64:!1,mapSorter:GSe,quickEncodeToken:RQ};function qSe(){let r=[];return r[Z.uint.major]=Us,r[Z.negint.major]=n_,r[Z.bytes.major]=um,r[Z.string.major]=tQ,r[Z.array.major]=o_,r[Z.map.major]=s_,r[Z.tag.major]=a_,r[Z.float.major]=c_,r}var CQ=qSe(),bP=new d3,dm=class{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${pP} object contains circular references`);return new dm(t,e)}},Zf={null:new Re(Z.null,null),undefined:new Re(Z.undefined,void 0),true:new Re(Z.true,!0),false:new Re(Z.false,!1),emptyArray:new Re(Z.array,0),emptyMap:new Re(Z.map,0)},Jf={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Re(Z.float,r):r>=0?new Re(Z.uint,r):new Re(Z.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Re(Z.uint,r):new Re(Z.negint,r)},Uint8Array(r,e,t,n){return new Re(Z.bytes,r)},string(r,e,t,n){return new Re(Z.string,r)},boolean(r,e,t,n){return r?Zf.true:Zf.false},null(r,e,t,n){return Zf.null},undefined(r,e,t,n){return Zf.undefined},ArrayBuffer(r,e,t,n){return new Re(Z.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Re(Z.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Zf.emptyArray,new Re(Z.break)]:Zf.emptyArray;n=dm.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=l_(s,t,n);return t.addBreakTokens?[new Re(Z.array,r.length),i,new Re(Z.break)]:[new Re(Z.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[Zf.emptyMap,new Re(Z.break)]:Zf.emptyMap;n=dm.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[l_(u,t,n),l_(i?r.get(u):r[u],t,n)];return HSe(a,t),t.addBreakTokens?[new Re(Z.map,s),a,new Re(Z.break)]:[new Re(Z.map,s),a]}};Jf.Map=Jf.Object;Jf.Buffer=Jf.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Jf[`${r}Array`]=Jf.DataView;function l_(r,e={},t){let n=IY(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Jf[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=Jf[n];if(!o)throw new Error(`${pP} unsupported type: ${n}`);return o(r,n,e,t)}function HSe(r,e){e.mapSorter&&r.sort(e.mapSorter)}function GSe(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=CQ[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function PQ(r,e,t,n){if(Array.isArray(e))for(let i of e)PQ(r,i,t,n);else t[e.type.major](r,e,n)}function jSe(r,e,t){let n=l_(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new d3(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return hP(a.chunks[0])}}return bP.reset(),PQ(bP,n,e,t),bP.toBytes(!0)}function _P(r,e){return e=Object.assign({},$Se,e),jSe(r,CQ,e)}var WSe={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},EP=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=Ha[e];if(t===void 0){let n=me[e];if(!n)throw new Error(`${it} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},g3=Symbol.for("DONE"),f_=Symbol.for("BREAK");function YSe(r,e,t){let n=[];for(let i=0;i{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw kQ.error(n),(0,hm.default)(n,GC)}let t;if(e.pubKey!=null){try{t=Bs(e.pubKey)}catch(i){throw kQ.error(i),i}if(!(await Hn(e.pubKey)).equals(r))throw(0,hm.default)(new Error("Embedded public key did not match PeerID"),tY)}else r.publicKey!=null&&(t=Bs(r.publicKey));if(t!=null)return t;throw(0,hm.default)(new Error("no public key is available"),GC)},OQ=(r,e,t)=>{let n=Ie(e);return rt([r,t,n])},d_=r=>{let e=Ie("ipns-signature:");return rt([e,r])},xP=r=>mo.encode(r),ol=r=>{let e=mo.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??mo.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}},ed=r=>rt([NQ,r.toBytes()]),SP=r=>Di(r.slice(NQ.length)),LQ=(r,e,t,n,i)=>{let o;if(t===mo.ValidityType.EOL)o=0;else throw(0,hm.default)(new Error("Unknown validity type"),u3);return _P({Value:r,Validity:e,ValidityType:o,Sequence:n,TTL:i})},BQ=r=>{let e=vP(r);if(e.ValidityType===0)e.ValidityType=mo.ValidityType.EOL;else throw(0,hm.default)(new Error("Unknown validity type"),u3);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var UQ=j("ipns"),ZSe=Ii.code,b3="/ipns/",h_=b3.length,FQ=async(r,e,t,n)=>{let i=new MQ.default(Date.now()+Number(n)),o=mo.ValidityType.EOL,[s,a]=n.toString().split("."),c=BigInt(s)*BigInt(1e5)+BigInt(a??"0");return await JSe(r,e,t,o,i,c)};var JSe=async(r,e,t,n,i,o)=>{t=BigInt(t);let s=Ie(i.toString());if(r.privateKey==null)throw(0,AP.default)(new Error("Missing private key"),rY);let a=await Li(r.privateKey),c=await tAe(a,e,n,s),u=LQ(e,s,n,t,o),l=d_(u),f=await a.sign(l),h={value:e,signature:c,validityType:n,validity:s,sequence:t,ttl:o,signatureV2:f,data:u};if(r.publicKey!=null){let d=Ea(r.toBytes());(d.code!==ZSe||!mt(r.publicKey,d.digest))&&(h.pubKey=r.publicKey)}return UQ("ipns entry for %b created",e),h},eAe=r=>uA.encode(r).slice(1),_3=r=>new pe(`/ipns/${eAe(r)}`),tAe=async(r,e,t,n)=>{try{let i=OQ(e,t,n);return await r.sign(i)}catch(i){throw UQ.error("record signature creation failed",i),(0,AP.default)(new Error("record signature creation failed"),ZW)}};var zs=j("ipfs:ipns:publisher"),zQ=Gn().code,VQ=60*60*1e3,Yh=class{constructor(e,t){this._routing=e,this._datastore=t}async publishWithEOL(e,t,n,i){let o=await this._updateOrCreateRecord(e,t,n,i);return this._putRecordToRouting(o,e,i)}publish(e,t,n){return this.publishWithEOL(e,t,VQ,n)}async _putRecordToRouting(e,t,n){if(!Lf(t)){let o="peerId received is not valid";throw zs.error(o),(0,Vs.default)(new Error(o),"ERR_INVALID_PEER_ID")}if(t.publicKey==null)throw(0,Vs.default)(new Error("Public key was missing"),"ERR_MISSING_PUBLIC_KEY");let i=ed(t);return await this._publishEntry(i,e,n),e}async _publishEntry(e,t,n){try{let i=await this._routing.put(e,t,n);return zs(`ipns record for ${re(e,"base32")} was stored in the routing`),i}catch(i){let o=`ipns record for ${re(e,"base32")} could not be stored in the routing - ${i.stack}`;throw zs.error(o),zs.error(i),(0,Vs.default)(new Error(o),"ERR_PUTTING_TO_ROUTING")}}async _getPublished(e,t={}){if(!Lf(e)){let i="peerId received is not valid";throw zs.error(i),(0,Vs.default)(new Error(i),"ERR_INVALID_PEER_ID")}let n=t.checkRouting!==!1;try{let i=await this._datastore.get(_3(e.toBytes()));return this._unmarshalData(i)}catch(i){if(i.code!==zQ){let o=`unexpected error getting the ipns record ${e.toString()} from datastore`;throw zs.error(o),(0,Vs.default)(new Error(o),"ERR_UNEXPECTED_DATASTORE_RESPONSE")}if(!n)throw(0,Vs.default)(i,"ERR_NOT_FOUND_AND_CHECK_ROUTING_NOT_ENABLED");try{let o=ed(e),s=await this._routing.get(o);return this._unmarshalData(s)}catch(o){throw zs.error(o),o}}}_unmarshalData(e){try{return ol(e)}catch(t){throw(0,Vs.default)(t,"ERR_INVALID_RECORD_DATA")}}async _updateOrCreateRecord(e,t,n,i){if(!Lf(e)){let u="peerId received is not valid";throw zs.error(u),(0,Vs.default)(new Error(u),"ERR_INVALID_PEER_ID")}let o={checkRouting:!0},s;try{s=await this._getPublished(e,o)}catch(u){if(u.code!==zQ){let l=`unexpected error when determining the last published IPNS record for ${e.toString()} ${u.stack}`;throw zs.error(l),(0,Vs.default)(new Error(l),"ERR_DETERMINING_PUBLISHED_RECORD")}}let a=0n;s&&s.sequence!==void 0&&(a=mt(s.value,t)?s.sequence:s.sequence+BigInt(1));let c;try{c=await FQ(e,t,a,n)}catch(u){let l=`ipns record for ${t} could not be created`;throw zs.error(u),(0,Vs.default)(new Error(l),"ERR_CREATING_IPNS_RECORD")}try{let u=xP(c);return await this._datastore.put(_3(e.toBytes()),u,i),zs(`ipns record for ${re(t,"base32")} was stored in the datastore`),u}catch{let l=`ipns record for ${t} could not be stored in the datastore`;throw zs.error(l),(0,Vs.default)(new Error(l),"ERR_STORING_IN_DATASTORE")}}};Yh.defaultRecordLifetime=VQ;var Qh=C(ee(),1);var KQ=C(Kn(),1),p_=j("ipfs:ipns:republisher"),$Q=60*1e3,qQ=60*$Q,rAe=4*qQ,nAe=24*qQ,m_=class{constructor(e,t,n,i,o={pass:""}){this._publisher=e,this._datastore=t,this._peerId=n,this._keychain=i,this._options=o,this._republishHandle=null}async start(){if(this._republishHandle)throw(0,Qh.default)(new Error("republisher is already running"),"ERR_REPUBLISH_ALREADY_RUNNING");let e={_task:null,_inflightTask:null,_timeoutId:null,runPeriodically:i=>{e._timeoutId=setTimeout(async()=>{e._timeoutId=null;try{e._inflightTask=e._task(),await e._inflightTask,e._task&&e.runPeriodically(i)}catch(o){p_.error(o)}},i())},cancel:async()=>{e._timeoutId!=null&&clearTimeout(e._timeoutId),e._task=null,await e._inflightTask}},{pass:t}=this._options,n=!0;e._task=async()=>{let i=new KQ.TimeoutController(3e4);try{await this._republishEntries(this._peerId,t,{signal:i.signal})}finally{i.clear()}},e.runPeriodically(()=>n?(n=!1,this._options.initialBroadcastInterval||$Q):this._options.broadcastInterval||rAe),this._republishHandle=e}async stop(){let e=this._republishHandle;if(!e)throw(0,Qh.default)(new Error("republisher is not running"),"ERR_REPUBLISH_NOT_RUNNING");this._republishHandle=null,await e.cancel()}async _republishEntries(e,t,n){try{await this._republishEntry(e,n)}catch{let o="cannot republish entry for the node's private key";p_.error(o);return}if(t)try{let i=await this._keychain.listKeys();for(let o of i){if(o.name==="self")continue;let s=await this._keychain.exportKey(o.name,t),a=await c3(s,t),c=await Hn(a.public.bytes,a.bytes);await this._republishEntry(c,n)}}catch(i){p_.error(i)}}async _republishEntry(e,t){try{let n=await this._getPreviousValue(e);await this._publisher.publishWithEOL(e,n,nAe,t)}catch(n){if(n.code==="ERR_NO_ENTRY_FOUND")return;throw n}}async _getPreviousValue(e){if(!Lf(e))throw(0,Qh.default)(new Error("invalid peer ID"),"ERR_INVALID_PEER_ID");try{let t=await this._datastore.get(_3(e.toBytes()));if(!(t instanceof Uint8Array))throw(0,Qh.default)(new Error("found ipns record that we couldn't process"),"ERR_INVALID_IPNS_RECORD");try{return ol(t).value}catch(n){throw p_.error(n),(0,Qh.default)(new Error("found ipns record that we couldn't convert to a value"),"ERR_INVALID_IPNS_RECORD")}}catch(t){throw t&&t.notFound?(0,Qh.default)(new Error(`no previous entry for record with id: ${e.toString()}`),"ERR_NO_ENTRY_FOUND"):t}}};var mm=C(ee(),1);var Ks=C(ee(),1);var E3=j("ipns:validator"),iAe=async(r,e)=>{let{value:t,validityType:n,validity:i}=e,o,s;if(e.signatureV2!=null&&e.data!=null)s=e.signatureV2,o=d_(e.data),oAe(e);else throw(0,Ks.default)(new Error("missing data or signatureV2"),Yf);let a;try{a=await r.verify(o,s)}catch{a=!1}if(!a)throw E3.error("record signature verification failed"),(0,Ks.default)(new Error("record signature verification failed"),Yf);if(i!=null&&n===mo.ValidityType.EOL){let c;try{c=w3(re(i))}catch{throw E3.error("unrecognized validity format (not an rfc3339 format)"),(0,Ks.default)(new Error("unrecognized validity format (not an rfc3339 format)"),JW)}if(c.getTime(){if(r.data==null)throw(0,Ks.default)(new Error("Record data is missing"),eY);let e=BQ(r.data);if(!mt(e.Value,r.value))throw(0,Ks.default)(new Error('Field "value" did not match between protobuf and CBOR'),Yf);if(!mt(e.Validity,r.validity))throw(0,Ks.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Yf);if(e.ValidityType!==r.validityType)throw(0,Ks.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Yf);if(e.Sequence!==r.sequence)throw(0,Ks.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Yf);if(e.TTL!==r.ttl)throw(0,Ks.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Yf)},pm=async(r,e)=>{let t=SP(r),n=ol(e),i=await DQ(t,n);await iAe(i,n)};var IP=j("ipfs:ipns:resolver"),sAe=Gn().code,HQ=32,g_=class{constructor(e){this._routing=e}async resolve(e,t={}){if(typeof e!="string")throw(0,mm.default)(new Error("invalid name"),"ERR_INVALID_NAME");let n=t.recursive&&t.recursive.toString()==="true",i=e.split("/");if(i.length!==3||i[0]!=="")throw(0,mm.default)(new Error("invalid name"),"ERR_INVALID_NAME");let o=i[2],s=1/0;n&&(s=HQ);let a=await this.resolver(o,s,t);return IP(`${e} was locally resolved correctly`),a}async resolver(e,t,n){if(t===0){let s=`could not resolve name (recursion limit of ${HQ} exceeded)`;throw IP.error(s),(0,mm.default)(new Error(s),"ERR_RESOLVE_RECURSION_LIMIT")}let i=await this._resolveName(e,n),o=i.split("/");return o[1]==="ipfs"||!t?i:this.resolver(o[2],t-1,n)}async _resolveName(e,t){let n=Oe(e),i=ed(n),o;try{o=await this._routing.get(i,t)}catch(s){throw IP.error("could not get record from routing",s),s.code===sAe?(0,mm.default)(new Error(`record requested for ${e} was not found in the network`),"ERR_NO_RECORD_FOUND"):(0,mm.default)(new Error(`unexpected error getting the ipns record ${n.toString()}`),"ERR_UNEXPECTED_ERROR_GETTING_RECORD")}return this._validateRecord(n,o)}async _validateRecord(e,t){await pm(rt([Ie("/ipns/"),e.toBytes()]),t);let n=ol(t);return re(n.value)}};var GQ=C(Cy(),1),y_=class{constructor(e){this.lru=(0,GQ.default)(e)}get(e){let t=this.lru.get(e);if(t){if(t.expire&&t.expireasync function*(){yield*(await Wo(r)).sort(e)}();async function on(r){for await(let e of r);}async function*Yt(r,e){for await(let t of r)await e(t)&&(yield t)}async function*Ga(r,e){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}var go=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,t,n){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(let{key:n,value:i}of e)await this.put(n,i,t),yield{key:n,value:i}}async*getMany(e,t={}){for await(let n of e)yield this.get(n,t)}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await on(this.putMany(e,n)),e=[],await on(this.deleteMany(t,n)),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 n=this._all(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.key.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>w_(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=e.offset)}return e.limit!=null&&(n=Ga(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>w_(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=e.offset)}return e.limit!=null&&(n=Ga(n,e.limit)),n}};var Vc=C($s(),1);Vc.default.formatters.b=r=>r==null?"undefined":tt.baseEncode(r);Vc.default.formatters.t=r=>r==null?"undefined":Ot.baseEncode(r);Vc.default.formatters.m=r=>r==null?"undefined":wh.baseEncode(r);Vc.default.formatters.p=r=>r==null?"undefined":r.toString();Vc.default.formatters.c=r=>r==null?"undefined":r.toString();Vc.default.formatters.k=r=>r==null?"undefined":r.toString();function ue(r){return Object.assign((0,Vc.default)(r),{error:(0,Vc.default)(`${r}:error`),trace:(0,Vc.default)(`${r}:trace`)})}var E_=class{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 this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},bm=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new E_(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return(e==null?void 0:e.byteLength)!=null?e.byteLength:1}push(e){if((e==null?void 0:e.value)!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new E_(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return(e==null?void 0:e.value)!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function jn(r={}){return bAe(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function bAe(r,e){e=e??{};let t=e.onEnd,n=new bm,i,o,s,a=async()=>n.isEmpty()?s?{done:!0}:await new Promise((g,w)=>{o=_=>{o=null,n.push(_);try{g(r(n))}catch(x){w(x)}return i}}):r(n),c=g=>o!=null?o(g):(n.push(g),i),u=g=>(n=new bm,o!=null?o({error:g}):(n.push({error:g}),i)),l=g=>{if(s)return i;if((e==null?void 0:e.objectMode)!==!0&&(g==null?void 0:g.byteLength)==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:g})},f=g=>s?i:(s=!0,g!=null?u(g):c({done:!0})),h=()=>(n=new bm,f(),{done:!0}),d=g=>(f(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:d,push:l,end:f,get readableLength(){return n.size}},t==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(g){return p.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return p.end(g),t!=null&&(t(g),t=void 0),i},get readableLength(){return p.readableLength}},i}var _Ae=ue("datastore:core:tiered"),S3=class extends go{constructor(e){super(),this.stores=e.slice()}async open(){try{await Promise.all(this.stores.map(e=>e.open()))}catch(e){throw cb(e)}}async put(e,t,n){try{await Promise.all(this.stores.map(i=>i.put(e,t,n)))}catch(i){throw lb(i)}}async get(e,t){for(let n of this.stores)try{let i=await n.get(e,t);if(i)return i}catch(i){_Ae.error(i)}throw Gn()}async has(e,t){for(let n of this.stores)if(await n.has(e,t))return!0;return!1}async delete(e,t){try{await Promise.all(this.stores.map(n=>n.delete(e,t)))}catch(n){throw ub(n)}}async*putMany(e,t={}){let n,i=this.stores.map(o=>{let s=jn({objectMode:!0});return on(o.putMany(s,t)).catch(a=>{n=a}),s});try{for await(let o of e){if(n)throw n;i.forEach(s=>s.push(o)),yield o}}finally{i.forEach(o=>o.end())}}async*deleteMany(e,t={}){let n,i=this.stores.map(o=>{let s=jn({objectMode:!0});return on(o.deleteMany(s,t)).catch(a=>{n=a}),s});try{for await(let o of e){if(n)throw n;i.forEach(s=>s.push(o)),yield o}}finally{i.forEach(o=>o.end())}}async close(){await Promise.all(this.stores.map(e=>e.close()))}batch(){let e=this.stores.map(t=>t.batch());return{put:(t,n)=>{e.forEach(i=>i.put(t,n))},delete:t=>{e.forEach(n=>n.delete(t))},commit:async t=>{for(let n of e)await n.commit(t)}}}query(e,t){return this.stores[this.stores.length-1].query(e,t)}queryKeys(e,t){return this.stores[this.stores.length-1].queryKeys(e,t)}};var R3=C(v_(),1);var x_=(r,e)=>{let t=e.map((n,i)=>({entry:mo.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let o=n.entry.sequence??0n,s=i.entry.sequence??0n;if(o>s)return-1;if(ol.getTime()?-1:u.getTime()({key:new pe(e),value:t}))}async*_allKeys(){yield*Object.entries(this.data).map(([e])=>new pe(e))}};async function*Bi(r,e){for await(let t of r)yield e(t)}async function*Qo(...r){let e=jn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var xAe=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},tX=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),PP=r=>r!=null&&typeof r.sink=="function"&&tX(r.source),SAe=r=>e=>{let t=r.sink(e);if(t.then!=null){let n=jn({objectMode:!0});return t.then(()=>{n.end()},o=>{n.end(o)}),Qo(n,async function*(){yield*r.source,n.end()}())}return r.source};function Ne(r,...e){if(PP(r)){let n=r;r=()=>n.source}else if(tX(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&PP(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n-1)return this._getLocal(e,t);try{await this._pubsub.subscribe(n)}catch{let s=`cannot subscribe topic ${n}`;throw bi.error(s),new We(s,"ERR_SUBSCRIBING_TOPIC")}return bi(`subscribed values for key ${n}`),this._getLocal(e)}unsubscribe(e){let t=T3(e);return this._pubsub.unsubscribe(t)}async _getLocal(e,t){let n=new pe("/"+kP(e),!1),i;try{i=await this._datastore.get(n,t)}catch(o){if(o.code!=="ERR_NOT_FOUND"){let a=`unexpected error getting the ipns record for ${n.toString()}`;throw bi.error(a),new We(a,"ERR_UNEXPECTED_ERROR_GETTING_RECORD")}let s=`local record requested was not found for ${n.toString()}`;throw bi.error(s),new We(s,"ERR_NOT_FOUND")}if(!(i instanceof Uint8Array)){let o="found record that we couldn't convert to a value";throw bi.error(o),new We(o,"ERR_INVALID_RECORD_RECEIVED")}return i}async _onMessage(e){let t=e.detail;if(t.type!=="signed"){bi.error("unsigned message received, this module can only work with signed messages");return}let{data:n,from:i,topic:o}=t,s;try{s=nX(o)}catch(a){bi.error(a);return}if(bi(`message received for topic ${o}`),this._peerId.equals(i)){bi("message discarded as it is from the same peer");return}if(this._handleSubscriptionKeyFn){let a;try{a=await this._handleSubscriptionKeyFn(s)}catch{bi.error("message discarded by the subscriptionKeyFn");return}s=a}try{await this._storeIfSubscriptionIsBetter(s,n)}catch(a){bi.error(a)}}async _storeIfSubscriptionIsBetter(e,t,n){let i=!1;try{i=await this._isBetter(e,t)}catch(o){if(o.code!=="ERR_NOT_VALID_RECORD")throw o}i&&await this._storeRecord(e,t,n)}async _validateRecord(e,t){return this._validator(e,t)}async _selectRecord(e,t){return await this._selector(e,t)===0}async _isBetter(e,t){try{await this._validateRecord(e,t)}catch{let s="record received through pubsub is not valid";throw bi.error(s),new We(s,"ERR_NOT_VALID_RECORD")}let n=new pe(e),i;try{i=await this._getLocal(n.uint8Array())}catch{return!0}return rr(i,t)?!1:this._selectRecord(e,[i,t])}async _storeRecord(e,t,n){let i=new pe("/"+kP(e),!1);await this._datastore.put(i,t,n),bi(`record for ${T3(e)} was stored in the datastore`)}};var NP=C(ee(),1);var T_=j("ipfs:ipns:pubsub"),Zh=class{constructor(e,t,n){this._subscriptions={},this._handleSubscriptionKey=this._handleSubscriptionKey.bind(this),this._pubsubDs=new A_(e,t,n,pm,x_,this._handleSubscriptionKey)}async put(e,t,n){try{await this._pubsubDs.put(e,t,n)}catch(i){throw T_.error(i),i}}async get(e,t){let n,i;try{n=await this._pubsubDs.get(e,t)}catch(s){i=s}let o=e.slice(0,h_);if(re(o)===b3){let s=pr.encode(e).substring(1),a=pr.encode(e.slice(h_)).substring(1);this._subscriptions[s]=a,T_(`subscribed to pubsub topic ${s}, id ${a}`)}if(i)throw i;return n}_handleSubscriptionKey(e){e instanceof Uint8Array&&(e=re(e,"base58btc"));let t=this._subscriptions[e];if(!t)throw(0,NP.default)(new Error(`key ${e} does not correspond to a subscription`),"ERR_INVALID_KEY");try{return ed(Oe(t))}catch(n){throw T_.error(n),n}}getSubscriptions(){return Object.values(this._subscriptions).filter(Boolean).map(t=>`${b3}${t}`)}async cancel(e){if(typeof e!="string")throw(0,NP.default)(new Error("invalid subscription name"),"ERR_INVALID_SUBSCRIPTION_NAME");e.startsWith(b3)&&(e=e.substring(h_));let t=Object.keys(this._subscriptions).find(i=>this._subscriptions[i]===e);if(!t)return{canceled:!1};let n=Ie(t);return this._pubsubDs.unsubscribe(n),delete this._subscriptions[t],T_(`unsubscribed pubsub ${t}: ${e}`),{canceled:!0}}};var I3;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.key!=null&&t.key.byteLength>0&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&t.value.byteLength>0&&(n.uint32(18),n.bytes(t.value)),t.timeReceived!=null&&t.timeReceived!==""&&(n.uint32(42),n.string(t.timeReceived)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={key:new Uint8Array(0),value:new Uint8Array(0),timeReceived:""},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.bytes();break;case 2:i.value=t.bytes();break;case 5:i.timeReceived=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(I3||(I3={}));function iX(r){let e=r.getUTCFullYear(),t=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),i=String(r.getUTCHours()).padStart(2,"0"),o=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${i}:${o}:${s}.${c}Z`}function oX(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,o=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),u=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,o,s,a,c,u))}var Yr=class{constructor(e,t,n){B(this,"key");B(this,"value");B(this,"timeReceived");if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return I3.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:iX(this.timeReceived)}}static deserialize(e){let t=I3.decode(e);return new Yr(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=oX(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new Yr(e.key,e.value,t)}};var _m=C(ee(),1);var DP=j("ipfs:ipns:offline-datastore"),Em=class{constructor(e){this._datastore=e,this.stores=[]}async put(e,t,n){if(!(e instanceof Uint8Array))throw(0,_m.default)(new Error("Offline datastore key must be a Uint8Array"),"ERR_INVALID_KEY");if(!(t instanceof Uint8Array))throw(0,_m.default)(new Error("Offline datastore value must be a Uint8Array"),"ERR_INVALID_VALUE");let i;try{i=this._routingKey(e)}catch(s){throw DP.error(s),(0,_m.default)(new Error("Not possible to generate the routing key"),"ERR_GENERATING_ROUTING_KEY")}let o=new Yr(e,t,new Date);await this._datastore.put(i,o.serialize(),n)}async get(e,t){if(!(e instanceof Uint8Array))throw(0,_m.default)(new Error("Offline datastore key must be a Uint8Array"),"ERR_INVALID_KEY");let n;try{n=this._routingKey(e)}catch(s){throw DP.error(s),(0,_m.default)(new Error("Not possible to generate the routing key"),"ERR_GENERATING_ROUTING_KEY")}let i=await this._datastore.get(n,t),o;try{o=Yr.deserialize(i)}catch(s){throw DP.error(s),s}return o.value}_routingKey(e){return new pe("/dht/record/"+re(e,"base32"),!1)}};async function sl(r){for await(let e of r);}var TAe=j("ipfs:ipns:dht-datastore"),I_=class{constructor(e){this._dht=e}async put(e,t,n){try{await sl(this._dht.put(e,t,n))}catch(i){throw TAe.error(i),i}}async get(e,t){for await(let n of this._dht.get(e,t))if(n.name==="VALUE")return n.value;throw Gn()}};function sX({libp2p:r,repo:e,peerId:t,options:n}){let i=[],o;if((0,R3.default)(n,"EXPERIMENTAL.ipnsPubsub",!1)&&(o=new Zh(r.pubsub,e.datastore,t),i.push(o)),(0,R3.default)(n,"offline",!1)!==!0&&["dht","dhtclient","dhtserver"].includes((0,R3.default)(n,"config.Routing.Type","none"))&&i.push(new I_(r.dht)),(0,R3.default)(n,"offline",!1)||i.length===0){let s=new Em(e.datastore);i.push(s)}return new S3(i)}var IAe=j("ipfs:components:ipns"),R_=class{constructor(e={pass:""}){this.options=e,this.offline=null,this.online=null}getIPNS(){let e=this.online||this.offline;if(e)return e;throw new Ku}get routing(){return this.getIPNS().routing}startOffline({repo:e,peerId:t,keychain:n}){if(this.offline!=null)throw new ka;IAe("initializing IPNS keyspace (offline)");let i=new Em(e.datastore),o=new x3(i,e.datastore,t,n,this.options);this.offline=o}async startOnline({libp2p:e,repo:t,peerId:n,keychain:i}){if(this.online!=null)throw new ka;let o=sX({libp2p:e,repo:t,peerId:n,options:this.options}),s=new x3(o,t.datastore,n,i,this.options);await s.republisher.start(),this.online=s}async stop(){let e=this.online;e&&(await e.republisher.stop(),this.online=null)}publish(e,t,n,i){return this.getIPNS().publish(e,t,n,i)}resolve(e,t){return this.getIPNS().resolve(e,t)}initializeKeyspace(e,t,n){return this.getIPNS().initializeKeyspace(e,t,n)}};var LP=C(ee(),1);async function aX({ipns:r,repo:e,codecs:t},n,i){if($8(n))return r.resolve(n);let{cid:o,path:s}=Qu(n);await sl(kf(o,s||"",t,e,i))}var OP=j("ipfs:name:publish");function cX({ipns:r,repo:e,codecs:t,peerId:n,isOnline:i,keychain:o}){let s=async c=>{let u;if(c==="self"&&n.privateKey!=null)u=await Li(n.privateKey);else try{let l=await o.exportKey(c,"temp");u=await c3(l,"temp")}catch(l){throw OP.error(l),(0,LP.default)(l,"ERR_CANNOT_GET_KEY")}return Hn(u.public.bytes,u.bytes)};async function a(c,u={}){let l=u.resolve!==!1,f=u.lifetime||"24h",h=u.key||"self";if(!i())throw(0,LP.default)(new Error(W8),"OFFLINE_ERROR");try{c=kH(c)}catch(_){throw OP.error(_),_}let d=0;try{d=Cf(f)||0,d=parseFloat(d.toFixed(6))}catch(_){throw OP.error(_),_}let p=await Promise.all([s(h),l?aX({ipns:r,repo:e,codecs:t},c):Promise.resolve()]),g=Ie(c),w=await r.publish(p[0],g,d,u);return{name:w.name,value:re(w.value)}}return $(a)}var C_=C(ee(),1);var dX=C(lX(),1);var CAe=et.bind({ignoreUndefined:!0}),PAe=j("ipfs:name:resolve"),fX=(r,e)=>e.length>0?r+"/"+e.join("/"):r;function hX({dns:r,ipns:e,isOnline:t,options:{offline:n}}){async function*i(o,s={}){if(s=CAe({nocache:!1,recursive:!0},s),n&&s&&s.nocache)throw(0,C_.default)(new Error("cannot specify both offline and nocache"),"ERR_NOCACHE_AND_OFFLINE");if(!t()&&!n)throw(0,C_.default)(new Error(W8),"OFFLINE_ERROR");let a=o.toString();a.startsWith("/ipns/")||(a=`/ipns/${a}`);let[c,u,...l]=a.slice(1).split("/");try{if(u.substring(0,1)==="1"){let h=Oe(u),d=Ea(h.toBytes());u=z.createV1(114,d).toString(w1)}else{let h=z.parse(u);h.version===1&&(u=h.toString(w1))}}catch(h){if((0,dX.default)(u)){yield fX(await r(u,s),l);return}throw PAe.error(h),(0,C_.default)(new Error("Invalid IPNS name"),"ERR_IPNS_INVALID_NAME")}let f=await e.resolve(`/${c}/${u}`,s);yield fX(f instanceof Uint8Array?re(f):f,l)}return $(i)}var BP=C(ee(),1);function vm(r,e){if(!r||!(e&&e.ipnsPubsub))throw(0,BP.default)(new Error("IPNS pubsub subsystem is not enabled"),"ERR_IPNS_PUBSUB_NOT_ENABLED");if(r.routing instanceof Zh)return r.routing;let t=(r.routing.stores||[]).find(n=>n instanceof Zh);if(!t)throw(0,BP.default)(new Error("IPNS pubsub datastore not found"),"ERR_PUBSUB_DATASTORE_NOT_FOUND");return t}function pX({ipns:r,options:e}){let t=e.EXPERIMENTAL;async function n(i,o={}){return vm(r,t).cancel(i,o)}return $(n)}function mX({ipns:r,options:e}){let t=e.EXPERIMENTAL;async function n(i={}){try{return{enabled:!!vm(r,t)}}catch{return{enabled:!1}}}return $(n)}function gX({ipns:r,options:e}){let t=e.EXPERIMENTAL;async function n(i={}){return vm(r,t).getSubscriptions(i)}return $(n)}var P_=class{constructor({ipns:e,options:t}){this.cancel=pX({ipns:e,options:t}),this.state=mX({ipns:e,options:t}),this.subs=gX({ipns:e,options:t})}};var k_=class{constructor({dns:e,ipns:t,repo:n,codecs:i,peerId:o,isOnline:s,keychain:a,options:c}){this.publish=cX({ipns:t,repo:n,codecs:i,peerId:o,isOnline:s,keychain:a}),this.resolve=hX({dns:e,ipns:t,isOnline:s,options:c}),this.pubsub=new P_({ipns:t,options:c})}};var yX=C(Kn(),1),wX=C(Da(),1),kAe=Gn().code,MP={default:"",edges:" -> "};function bX({repo:r,codecs:e,resolve:t,preload:n}){async function*i(o,s={}){if(s.maxDepth===0)return;if(s.edges&&s.format&&s.format!==MP.default)throw new Error("Cannot set edges to true and also specify format");if(s.format=s.edges?MP.edges:s.format,typeof s.maxDepth!="number"&&(s.maxDepth=s.recursive?1/0:1),s.timeout){let l=[new yX.TimeoutController(s.timeout).signal];s.signal&&l.push(s.signal),s.signal=(0,wX.anySignal)(l)}let c=(Array.isArray(o)?o:[o]).map(u=>NAe(n,u,s));for(let u of c)try{yield*DAe(t,r,e,u,s)}catch(l){yield{ref:"",err:l.message}}}return i}function NAe(r,e,t){let{cid:n,path:i}=Qu(e);return t.preload!==!1&&r(n),`/ipfs/${n}${i||""}`}async function*DAe(r,e,t,n,i){let o=await r(n,i),{cid:s}=Qu(o),a=i.maxDepth!=null?i.maxDepth:1/0,c=i.unique||!1;for await(let u of LAe(e,t,s,a,c,i))u.parent&&(u.isDuplicate||(yield{ref:OAe(u.parent.cid,u.node.cid,u.node.name,i.format)}))}function OAe(r,e,t="",n=MP.default){let i=n.replace(//g,r.toString());return i=i.replace(//g,e.toString()),i=i.replace(//g,t),i}async function*LAe(r,e,t,n,i,o){let s=new Set;async function*a(c,u){let l=u+1;if(!(l>n))try{for await(let f of BAe(r,e,c.cid,o))yield{parent:c,node:f,isDuplicate:i&&s.has(f.cid.toString())},i&&s.add(f.cid.toString()),yield*a(f,l)}catch(f){throw f.code===kAe&&(f.message=`Could not find object with CID: ${c.cid}`),f}}yield*a({cid:t},0)}async function*BAe(r,e,t,n){let i=await r.blocks.get(t,n),s=(await e.getCodec(t.code)).decode(i),a=t.code===kr,c=[];for(let[u,l]of UP(s,c)){if(a){let f=u.match(/^Links\/(\d+)\/Hash$/);if(f){let h=Number(f[1]);if(ho[1].cid)}return $(e)}function vX({network:r}){async function e(t,n={}){let{bitswap:i}=await r.use(n),o=i.wantlistForPeer(t);return Array.from(o).map(s=>s[1].cid)}return $(e)}function xX({network:r}){async function e(t,n={}){let{bitswap:i}=await r.use(n);return Array.isArray(t)||(t=[t]),i.unwant(t)}return $(e)}function N_({network:r}){async function e(t={}){let n=(await r.use(t)).bitswap,i=n.stat().snapshot;return{provideBufLen:parseInt(i.providesBufferLength.toString()),blocksReceived:BigInt(i.blocksReceived.toString()),wantlist:Array.from(n.getWantlist()).map(o=>o[1].cid),peers:n.peers(),dupBlksReceived:BigInt(i.dupBlksReceived.toString()),dupDataReceived:BigInt(i.dupDataReceived.toString()),dataReceived:BigInt(i.dataReceived.toString()),blocksSent:BigInt(i.blocksSent.toString()),dataSent:BigInt(i.dataSent.toString())}}return $(e)}var D_=class{constructor({network:e}){this.wantlist=EX({network:e}),this.wantlistForPeer=vX({network:e}),this.unwant=xX({network:e}),this.stat=N_({network:e})}};var MAe=Ue("dns4"),UAe=Ue("dns6"),FAe=Ue("dnsaddr"),Jh=_i(Ue("dns"),FAe,MAe,UAe),O_=_i(Ue("ip4"),Ue("ip6")),xm=_i(ut(O_,Ue("tcp")),ut(Jh,Ue("tcp"))),VP=ut(O_,Ue("udp")),zAe=ut(VP,Ue("utp")),VAe=ut(VP,Ue("quic")),P3=_i(ut(xm,Ue("ws")),ut(Jh,Ue("ws"))),k3=_i(ut(xm,Ue("wss")),ut(Jh,Ue("wss")),ut(xm,Ue("tls"),Ue("ws")),ut(Jh,Ue("tls"),Ue("ws"))),FP=_i(ut(xm,Ue("http")),ut(O_,Ue("http")),ut(Jh,Ue("http"))),zP=_i(ut(xm,Ue("https")),ut(O_,Ue("https")),ut(Jh,Ue("https"))),SX=ut(VP,Ue("webrtc"),Ue("certhash")),TX=_i(ut(SX,Ue("p2p")),SX),IX=_i(ut(P3,Ue("p2p-webrtc-star"),Ue("p2p")),ut(k3,Ue("p2p-webrtc-star"),Ue("p2p")),ut(P3,Ue("p2p-webrtc-star")),ut(k3,Ue("p2p-webrtc-star"))),xdt=_i(ut(P3,Ue("p2p-websocket-star"),Ue("p2p")),ut(k3,Ue("p2p-websocket-star"),Ue("p2p")),ut(P3,Ue("p2p-websocket-star")),ut(k3,Ue("p2p-websocket-star"))),RX=_i(ut(FP,Ue("p2p-webrtc-direct"),Ue("p2p")),ut(zP,Ue("p2p-webrtc-direct"),Ue("p2p")),ut(FP,Ue("p2p-webrtc-direct")),ut(zP,Ue("p2p-webrtc-direct"))),N3=_i(P3,k3,FP,zP,IX,RX,xm,zAe,VAe,Jh,TX),Sdt=_i(ut(N3,Ue("p2p-stardust"),Ue("p2p")),ut(N3,Ue("p2p-stardust"))),td=_i(ut(N3,Ue("p2p")),IX,RX,TX,Ue("p2p")),AX=_i(ut(td,Ue("p2p-circuit"),td),ut(td,Ue("p2p-circuit")),ut(Ue("p2p-circuit"),td),ut(N3,Ue("p2p-circuit")),ut(Ue("p2p-circuit"),N3),Ue("p2p-circuit")),CX=()=>_i(ut(AX,CX),AX),C3=CX(),KAe=_i(ut(C3,td,C3),ut(td,C3),ut(C3,td),C3,td),PX=KAe;function kX(r){function e(t){let n;try{n=Xi(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function ut(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:kX(e),partialMatch:e}}function _i(...r){function e(n){let i=null;return r.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:kX(e),partialMatch:e}}function Ue(r){let e=r;function t(i){let o;try{o=Xi(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}function L_(r){try{return PX.matches(r)}catch{return!1}}function NX({repo:r}){async function e(t,n={}){if(!L_(t))throw new Error(`${t} is not a valid Multiaddr`);let i=await r.config.getAll(n),o=i.Bootstrap||[];return o.push(t.toString()),i.Bootstrap=Array.from(new Set(o)).sort((s,a)=>s.localeCompare(a)),await r.config.replace(i),{Peers:[t]}}return $(e)}var DX=O8,$Ae=L8,KP=function(r){let e=0;if(r=r.toString().trim(),DX(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if($Ae(r)){let t=r.split(":",8),n;for(n=0;n0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},OX=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let o=0;o{let e=GAe(...r);$P[e.code]=e,D3[e.name]=e});function GAe(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function Fr(r){if(typeof r=="number"){if($P[r]!=null)return $P[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(D3[r]!=null)return D3[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Kc=C(Xo(),1);function WX(r,e){switch(Fr(r).code){case 4:case 41:return aTe(e);case 42:return GX(e);case 6:case 273:case 33:case 132:return QX(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return GX(e);case 421:return fTe(e);case 444:return jX(e);case 445:return jX(e);case 466:return lTe(e);default:return re(e,"base16")}}function YX(r,e){switch(Fr(r).code){case 4:return qX(e);case 41:return qX(e);case 42:return HX(e);case 6:case 273:case 33:case 132:return jP(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return HX(e);case 421:return cTe(e);case 444:return dTe(e);case 445:return hTe(e);case 466:return uTe(e);default:return Ie(e,"base16")}}var GP=Object.values(Vu).map(r=>r.decoder),sTe=function(){let r=GP[0].or(GP[1]);return GP.slice(2).forEach(e=>r=r.or(e)),r}();function qX(r){if(!xc(r))throw new Error("invalid ip address");return KP(r)}function aTe(r){let e=OX(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!xc(e))throw new Error("invalid ip address");return e}function jP(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function QX(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function HX(r){let e=Ie(r),t=Uint8Array.from(Kc.default.encode(e.length));return rt([t,e],t.length+e.length)}function GX(r){let e=Kc.default.decode(r);if(r=r.slice(Kc.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return re(r)}function cTe(r){let e;r[0]==="Q"||r[0]==="1"?e=Ea(pr.decode(`z${r}`)).bytes:e=z.parse(r).multihash.bytes;let t=Uint8Array.from(Kc.default.encode(e.length));return rt([t,e],t.length+e.length)}function uTe(r){let e=sTe.decode(r),t=Uint8Array.from(Kc.default.encode(e.length));return rt([t,e],t.length+e.length)}function lTe(r){let e=Kc.default.decode(r),t=r.slice(Kc.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+re(t,"base64url")}function fTe(r){let e=Kc.default.decode(r),t=r.slice(Kc.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return re(t,"base58btc")}function dTe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=va.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=jP(n);return rt([t,i],t.length+i.length)}function hTe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=va.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=jP(n);return rt([t,i],t.length+i.length)}function jX(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=re(e,"base32"),i=QX(t);return`${n}:${i}`}var Sm=C(Xo(),1);function pTe(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n=t.length)throw ZX("invalid address: "+r);if(o.path===!0){e.push([i,ZP(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function mTe(r){let e=[];return r.map(t=>{let n=U_(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),ZP(e.join("/"))}function gTe(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=U_(e);return e.length>1?[t.code,YX(t.code,e[1])]:[t.code]})}function WP(r){return r.map(e=>{let t=U_(e);return e[1]!=null?[t.code,WX(t.code,e[1])]:[t.code]})}function YP(r){return M_(rt(r.map(e=>{let t=U_(e),n=Uint8Array.from(Sm.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=rt([n,e[1]])),n})))}function QP(r,e){return r.size>0?r.size/8:r.size===0?0:Sm.default.decode(e)+(Sm.default.decode.bytes??0)}function B_(r){let e=[],t=0;for(;tr.length)throw ZX("Invalid address Uint8Array: "+re(r,"base16"));e.push([n,a])}return e}function XP(r){let e=B_(r),t=WP(e);return mTe(t)}function yTe(r){r=ZP(r);let e=pTe(r),t=gTe(e);return YP(t)}function XX(r){return yTe(r)}function M_(r){let e=wTe(r);if(e!=null)throw e;return Uint8Array.from(r)}function wTe(r){try{B_(r)}catch(e){return e}}function ZP(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function ZX(r){return new Error("Error parsing address: "+r)}function U_(r){return Fr(r[0])}var ek=C(Xo(),1);var eZ=C(ee(),1);var Am=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},JP=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},O3,L3,B3,JX,_Te=Symbol.for("nodejs.util.inspect.custom"),ETe=[Fr("dns").code,Fr("dns4").code,Fr("dns6").code,Fr("dnsaddr").code],vTe=new Map,tZ=Symbol.for("@multiformats/js-multiaddr/multiaddr");function F_(r){return!!(r!=null&&r[tZ])}var al=class{constructor(e){if(O3.set(this,void 0),L3.set(this,void 0),B3.set(this,void 0),this[JX]=!0,e==null&&(e=""),e instanceof Uint8Array)this.bytes=M_(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=XX(e)}else if(F_(e))this.bytes=M_(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return Am(this,O3,"f")==null&&JP(this,O3,XP(this.bytes),"f"),Am(this,O3,"f")}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="",s=Fr("tcp"),a=Fr("udp"),c=Fr("ip4"),u=Fr("ip6"),l=Fr("dns6"),f=Fr("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(o=`%${p??""}`),ETe.includes(d)&&(t=s.name,i=443,n=`${p??""}${o}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=Fr(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=Fr(d).name,n=`${p??""}${o}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},Fr(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;ne.name)}tuples(){return Am(this,L3,"f")==null&&JP(this,L3,B_(this.bytes),"f"),Am(this,L3,"f")}stringTuples(){return Am(this,B3,"f")==null&&JP(this,B3,WP(this.tuples()),"f"),Am(this,B3,"f")}encapsulate(e){return e=new al(e),new al(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new al(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new al(YP(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===D3.ipfs.code).pop();if((t==null?void 0:t[1])!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?re(pr.decode(`z${n}`),"base58btc"):re(z.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){let e=null;try{e=this.stringTuples().filter(t=>Fr(t[0]).path===!0)[0][1],e==null&&(e=null)}catch{e=null}return e}equals(e){return mt(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=vTe.get(t.name);if(n==null)throw(0,eZ.default)(new Error(`no available resolver for ${t.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new al(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")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){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[(O3=new WeakMap,L3=new WeakMap,B3=new WeakMap,JX=tZ,_Te)](){return`Multiaddr(${XP(this.bytes)})`}};function yt(r){return new al(r)}function rZ({repo:r}){async function e(t={}){let n=await r.config.getAll(t),i=n.Bootstrap||[];return n.Bootstrap=[],await r.config.replace(n),{Peers:i.map(o=>yt(o))}}return $(e)}function nZ({repo:r}){async function e(t={}){return{Peers:(await r.config.get("Bootstrap",t)||[]).map(i=>yt(i))}}return $(e)}var cl=()=>({Addresses:{Swarm:[],Announce:[],NoAnnounce:[],API:"",Gateway:"",RPC:"",Delegates:["/dns4/node0.delegate.ipfs.io/tcp/443/https","/dns4/node1.delegate.ipfs.io/tcp/443/https","/dns4/node2.delegate.ipfs.io/tcp/443/https","/dns4/node3.delegate.ipfs.io/tcp/443/https"]},Discovery:{MDNS:{Enabled:!1,Interval:10},webRTCStar:{Enabled:!0}},Bootstrap:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dns4/node0.preload.ipfs.io/tcp/443/wss/p2p/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic","/dns4/node1.preload.ipfs.io/tcp/443/wss/p2p/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6","/dns4/node2.preload.ipfs.io/tcp/443/wss/p2p/QmV7gnbW5VTcJ3oyM2Xk1rdFBJ3kTkvxc87UFGsun29STS","/dns4/node3.preload.ipfs.io/tcp/443/wss/p2p/QmY7JB6MQXhxHvq7dBDh4HpbH29v4yE9JRadAVpndvzySN"],Pubsub:{Enabled:!0},Swarm:{ConnMgr:{LowWater:5,HighWater:20},DisableNatPortMap:!0},Routing:{Type:"dhtclient"}});function iZ({repo:r}){async function e(t={}){let n=await r.config.getAll(t);return n.Bootstrap=cl().Bootstrap,await r.config.replace(n),{Peers:cl().Bootstrap.map(i=>yt(i))}}return $(e)}function oZ({repo:r}){async function e(t,n={}){if(!L_(t))throw new Error(`${t} is not a valid Multiaddr`);let i=await r.config.getAll(n);return i.Bootstrap=(i.Bootstrap||[]).filter(o=>o.toString()!==t.toString()),await r.config.replace(i),{Peers:[t]}}return $(e)}var z_=class{constructor({repo:e}){this.add=NX({repo:e}),this.list=nZ({repo:e}),this.rm=oZ({repo:e}),this.clear=rZ({repo:e}),this.reset=iZ({repo:e})}};function sZ({preload:r,repo:e}){async function t(n,i={}){return i.preload!==!1&&r(n),e.blocks.get(n,i)}return $(t)}function aZ({codecs:r,hashers:e,repo:t,preload:n}){async function i(o,s={}){let a=s.pin?await t.gcLock.readLock():null;try{let c=s.version!=null?s.version:0,u=s.format||(c===0?"dag-pb":"raw"),f=await(await e.getHasher(s.mhtype||"sha2-256")).digest(o),h=await r.getCodec(u),d=z.create(c,h.code,f);return await t.blocks.put(d,o,{signal:s.signal}),s.preload!==!1&&n(d),s.pin===!0&&await t.pins.pinRecursively(d,{signal:s.signal}),d}finally{a&&a()}}return $(i)}var cZ=C(ee(),1);function Qt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var V_=globalThis.CustomEvent??Event;async function*ep(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,o=[],s=Qt(),a=Qt(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(s=Qt(),await s.promise),l)break;let g={done:!1};o.push(g),p().then(w=>{g.done=!0,g.ok=!0,g.value=w,i.dispatchEvent(new V_("task-complete"))},w=>{g.done=!0,g.err=w,i.dispatchEvent(new V_("task-complete"))})}c=!0,i.dispatchEvent(new V_("task-complete"))}catch(p){u=p,i.dispatchEvent(new V_("task-complete"))}});function f(){var p;return n?(p=o[0])==null?void 0:p.done:!!o.find(g=>g.done)}function*h(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}function*d(){for(;f();)for(let p=0;pMi(o,s=>async()=>{s=K_(s);let a={cid:s};try{if(!await r.blocks.has(s))throw(0,cZ.default)(new Error("block not found"),"ERR_BLOCK_NOT_FOUND");await r.blocks.delete(s)}catch(c){n.force||(c.message=`cannot remove ${s}: ${c.message}`,a.error=c)}return a}),o=>ep(o,{concurrency:xTe}),o=>M3(o,()=>!n.quiet))}finally{i()}}return $(e)}function lZ({repo:r,preload:e}){async function t(n,i={}){n=K_(n),i.preload!==!1&&e(n);let o=await r.blocks.get(n);return{cid:n,size:o.length}}return $(t)}var $_=class{constructor({codecs:e,hashers:t,preload:n,repo:i}){this.get=sZ({preload:n,repo:i}),this.put=aZ({codecs:e,hashers:t,preload:n,repo:i}),this.rm=uZ({repo:i}),this.stat=lZ({preload:n,repo:i})}};var fZ=C(ee(),1);async function*yo(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}function tk(r){return typeof r.stream=="function"?yo(r.stream()):yo(new Response(r).body)}function ja(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}async function tp(r){let e=[];for await(let t of r)e.push(t);return e}function qs(r){return ArrayBuffer.isView(r)||r instanceof ArrayBuffer}function ul(r){return r.constructor&&(r.constructor.name==="Blob"||r.constructor.name==="File")&&typeof r.stream=="function"}function U3(r){return typeof r=="object"&&(r.path||r.content)}var ll=r=>r&&typeof r.getReader=="function";async function*q_(r){yield r}async function H_(r){if(qs(r))return q_(rk(r));if(typeof r=="string"||r instanceof String)return q_(rk(r.toString()));if(ul(r))return tk(r);if(ll(r)&&(r=yo(r)),Symbol.iterator in r||Symbol.asyncIterator in r){let e=ja(r),{value:t,done:n}=await e.peek();if(n)return q_(new Uint8Array(0));if(e.push(t),Number.isInteger(t))return q_(Uint8Array.from(await tp(e)));if(qs(t)||typeof t=="string"||t instanceof String)return Mi(e,rk)}throw(0,fZ.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT")}function rk(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):Ie(r.toString())}var j_=C(ee(),1);async function*dZ(r,e){if(r==null)throw(0,j_.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT");if(typeof r=="string"||r instanceof String){yield G_(r.toString(),e);return}if(qs(r)||ul(r)){yield G_(r,e);return}if(ll(r)&&(r=yo(r)),Symbol.iterator in r||Symbol.asyncIterator in r){let t=ja(r),{value:n,done:i}=await t.peek();if(i){yield{content:[]};return}if(t.push(n),Number.isInteger(n)||qs(n)||typeof n=="string"||n instanceof String){yield G_(t,e);return}throw(0,j_.default)(new Error("Unexpected input: multiple items passed - if you are using ipfs.add, please use ipfs.addAll instead"),"ERR_UNEXPECTED_INPUT")}if(U3(r)){yield G_(r,e);return}throw(0,j_.default)(new Error('Unexpected input: cannot convert "'+typeof r+'" into ImportCandidate'),"ERR_UNEXPECTED_INPUT")}async function G_(r,e){let{path:t,mode:n,mtime:i,content:o}=r,s={path:t||"",mode:Bu(n),mtime:af(i)};return o?s.content=await e(o):t||(s.content=await e(r)),s}function W_(r){return dZ(r,H_)}function hZ({addAll:r}){async function e(t,n={}){let i=await Dr(r(W_(t),n));if(i==null)throw Error("Failed to add a file, if you see this please report a bug");return i}return e}async function*rp(r,e=1){let t=[];e<1&&(e=1);for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}async function*F3(r,e=1){for await(let t of rp(r,e)){let n=t.map(async i=>await i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;i>8;return new Uint8Array(e)}var Rpt=gh({name:"murmur3-32",code:35,encode:r=>STe(Q_.default.x86.hash32(r))}),V3=gh({name:"murmur3-128",code:34,encode:r=>G0.fromHex(Q_.default.x64.hash128(r))}),Cpt=gh({name:"murmur3-x64-64",code:34,encode:r=>G0.fromHex(Q_.default.x64.hash128(r)).subarray(0,8)});async function ATe(r){return(await V3.encode(r)).slice(0,8).reverse()}var TTe={chunker:"fixed",strategy:"balanced",rawLeaves:!1,onlyHash:!1,reduceSingleLeafToSelf:!0,hasher:dt,leafType:"file",cidVersion:0,progress:()=>()=>{},shardSplitThreshold:1e3,fileImportConcurrency:50,blockWriteConcurrency:10,minChunkSize:262144,maxChunkSize:262144,avgChunkSize:262144,window:16,polynomial:0x3df305dfb2a804,maxChildrenPerNode:174,layerRepeat:4,wrapWithDirectory:!1,recursive:!1,hidden:!1,timeout:void 0,hamtHashFn:ATe,hamtHashCode:34,hamtBucketBits:8},gZ=(r={})=>et.bind({ignoreUndefined:!0})(TTe,r);var ITe=async(r,e,t)=>{t.codec||(t.codec=sr),t.hasher||(t.hasher=dt),t.cidVersion===void 0&&(t.cidVersion=1),t.codec===sr&&t.hasher!==dt&&(t.cidVersion=1);let n=await t.hasher.digest(r),i=z.create(t.cidVersion,t.codec.code,n);return t.onlyHash||await e.put(i,r,{signal:t.signal}),i},Wa=ITe;var RTe=async(r,e,t)=>{let n=new st({type:"directory",mtime:r.mtime,mode:r.mode}),i=pt(Xn({Data:n.marshal()})),o=await Wa(i,e,t),s=r.path;return{cid:o,path:s,unixfs:n,size:i.length}},yZ=RTe;var xZ=C(ee(),1);async function CTe(r,e){return e(await tp(r))}var wZ=CTe;function PTe(r,e,t){return bZ(r,e,t)}async function bZ(r,e,t){let n=[];for await(let i of rp(r,t.maxChildrenPerNode))n.push(await e(i));return n.length>1?bZ(n,e,t):n[0]}var _Z=PTe;async function kTe(r,e,t){let n=new ik(t.layerRepeat),i=0,o=1,s=n;for await(let a of rp(r,t.maxChildrenPerNode))s.isFull()&&(s!==n&&n.addChild(await s.reduce(e)),i&&i%t.layerRepeat===0&&o++,s=new X_(o,t.layerRepeat,i),i++),s.append(a);return s&&s!==n&&n.addChild(await s.reduce(e)),n.reduce(e)}var EZ=kTe,X_=class{constructor(e,t,n=0){this.maxDepth=e,this.layerRepeat=t,this.currentDepth=1,this.iteration=n,this.root=this.node=this.parent={children:[],depth:this.currentDepth,maxDepth:e,maxChildren:(this.maxDepth-this.currentDepth)*this.layerRepeat}}isFull(){if(!this.root.data)return!1;if(this.currentDepthi.data).map(i=>this._reduce(i,t)))),t((e.data||[]).concat(n))}_findParent(e,t){let n=e.parent;if(!(!n||n.depth===0))return n.children.length===n.maxChildren||!n.maxChildren?this._findParent(n,t):n}},ik=class extends X_{constructor(e){super(0,e),this.root.depth=0,this.currentDepth=1}addChild(e){this.root.children.push(e)}reduce(e){return e((this.root.data||[]).concat(this.root.children))}};async function*NTe(r,e,t){for await(let n of r.content)yield async()=>{t.progress(n.length,r.path);let i,o={codec:sr,cidVersion:t.cidVersion,hasher:t.hasher,onlyHash:t.onlyHash};return t.rawLeaves?(o.codec=yf,o.cidVersion=1):(i=new st({type:t.leafType,data:n}),n=pt({Data:i.marshal(),Links:[]})),{cid:await Wa(n,e,o),unixfs:i,size:n.length}}}var vZ=NTe;var DTe={flat:wZ,balanced:_Z,trickle:EZ};async function*OTe(r,e,t){let n=-1,i,o;typeof t.bufferImporter=="function"?o=t.bufferImporter:o=vZ;for await(let s of F3(o(r,e,t),t.blockWriteConcurrency)){if(n++,n===0){i=s;continue}else n===1&&i&&(yield i,i=null);yield s}i&&(i.single=!0,yield i)}var LTe=(r,e,t)=>{async function n(i){if(i.length===1&&i[0].single&&t.reduceSingleLeafToSelf){let l=i[0];if(r.mtime!==void 0||r.mode!==void 0){let f=await e.get(l.cid);l.unixfs=new st({type:"file",mtime:r.mtime,mode:r.mode,data:f}),f=pt(Xn({Data:l.unixfs.marshal()})),l.cid=await Wa(f,e,{...t,codec:sr,hasher:t.hasher,cidVersion:t.cidVersion}),l.size=f.length}return{cid:l.cid,path:r.path,unixfs:l.unixfs,size:l.size}}let o=new st({type:"file",mtime:r.mtime,mode:r.mode}),s=i.filter(l=>l.cid.code===gf&&l.size||l.unixfs&&!l.unixfs.data&&l.unixfs.fileSize()?!0:!!(l.unixfs&&l.unixfs.data&&l.unixfs.data.length)).map(l=>l.cid.code===gf?(o.addBlockSize(l.size),{Name:"",Tsize:l.size,Hash:l.cid}):(!l.unixfs||!l.unixfs.data?o.addBlockSize(l.unixfs&&l.unixfs.fileSize()||0):o.addBlockSize(l.unixfs.data.length),{Name:"",Tsize:l.size,Hash:l.cid})),a={Data:o.marshal(),Links:s},c=pt(Xn(a));return{cid:await Wa(c,e,t),path:r.path,unixfs:o,size:c.length+a.Links.reduce((l,f)=>l+f.Tsize,0)}}return n};function BTe(r,e,t){let n=DTe[t.strategy];if(!n)throw(0,xZ.default)(new Error(`Unknown importer build strategy name: ${t.strategy}`),"ERR_BAD_STRATEGY");return n(OTe(r,e,t),LTe(r,e,t),t)}var SZ=BTe;var fk=C(ee(),1);var TZ=Symbol.for("@achingbrain/uint8arraylist");function AZ(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e0&&this.appendAll(e)}*[(MTe=TZ,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if($c(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if($c(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=AZ(this.bufs,e);return t.buf[t.index]}set(e,t){let n=AZ(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return yi(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:yi(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new vt;return o.length=i,o.bufs=[...n],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(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],i=0;for(let o=0;o=c)continue;let u=e>=a&&ea&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!$c(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=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),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ri(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=Hu(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=Hu(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=Hu(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ri(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=Hu(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=Hu(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=Hu(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=Hu(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=Hu(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof vt)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;ti+o.byteLength,0)),n.length=t,n}};var zZ=C(FZ(),1),uk=C(ee(),1);async function*$Te(r,e){let t,n,i;if(e.minChunkSize&&e.maxChunkSize&&e.avgChunkSize)i=e.avgChunkSize,t=e.minChunkSize,n=e.maxChunkSize;else if(e.avgChunkSize)i=e.avgChunkSize,t=i/3,n=i+i/2;else throw(0,uk.default)(new Error("please specify an average chunk size"),"ERR_INVALID_AVG_CHUNK_SIZE");if(t<16)throw(0,uk.default)(new Error("rabin min must be greater than 16"),"ERR_INVALID_MIN_CHUNK_SIZE");n=o;)if(yield t.slice(0,o),i=!0,o===t.length)t=new vt,n=0;else{let a=new vt;a.append(t.sublist(o)),t=a,n-=o}(!i||n)&&(yield t.subarray(0,n))}var KZ=HTe;var lk=C(ee(),1);async function*GTe(r){for await(let e of r){if(e.length===void 0)throw(0,lk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT");if(typeof e=="string"||e instanceof String)yield Ie(e.toString());else if(Array.isArray(e))yield Uint8Array.from(e);else if(e instanceof Uint8Array)yield e;else throw(0,lk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}}var $Z=GTe;function jTe(r){return Symbol.iterator in r}function WTe(r){return Symbol.asyncIterator in r}function YTe(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(jTe(r))return async function*(){yield*r}();if(WTe(r))return r}catch{throw(0,fk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}throw(0,fk.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}async function*QTe(r,e,t){for await(let n of r)if(n.path&&(n.path.substring(0,2)==="./"&&(t.wrapWithDirectory=!0),n.path=n.path.split("/").filter(i=>i&&i!==".").join("/")),n.content){let i;typeof t.chunker=="function"?i=t.chunker:t.chunker==="rabin"?i=VZ:i=KZ;let o;typeof t.chunkValidator=="function"?o=t.chunkValidator:o=$Z;let s={path:n.path,mtime:n.mtime,mode:n.mode,content:i(o(YTe(n.content),t),t)};yield()=>SZ(s,e,t)}else if(n.path){let i={path:n.path,mtime:n.mtime,mode:n.mode};yield()=>yZ(i,e,t)}else throw new Error("Import candidate must have content or path or both")}var qZ=QTe;var dk=class{constructor(e,t){this.options=t||{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime,this.cid=void 0,this.size=void 0}async put(e,t){}get(e){return Promise.resolve(this)}async*eachChildSeries(){}async*flush(e){}},rd=dk;var hk=class extends rd{constructor(e,t){super(e,t),this._children={}}async put(e,t){this.cid=void 0,this.size=void 0,this._children[e]=t}get(e){return Promise.resolve(this._children[e])}childCount(){return Object.keys(this._children).length}directChildrenCount(){return this.childCount()}onlyChild(){return this._children[Object.keys(this._children)[0]]}async*eachChildSeries(){let e=Object.keys(this._children);for(let t=0;tu+(l.Tsize==null?0:l.Tsize),0);this.cid=a,this.size=c,yield{cid:a,unixfs:i,path:this.path,size:c}}},H3=hk;var jZ=C(pk(),1);var bn=class{constructor(e,t,n=0){B(this,"_options");B(this,"_popCount");B(this,"_parent");B(this,"_posAtParent");B(this,"_children");B(this,"key");this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new jZ.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof bn?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof bn?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,o,s)=>(o!=null&&(o instanceof bn?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return WZ(this,e,t)}toJSON(){return this.serialize(tIe,rIe)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof bn)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?cr(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof bn?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new bn(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(eIe);if(e!=null&&!(e instanceof bn)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function eIe(r){return!!r}function tIe(r,e){return r.key}function rIe(r){return r}async function WZ(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof bn)await WZ(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return t(n)}var nIe=[255,254,252,248,240,224,192,128],iIe=[1,3,7,15,31,63,127,255],Z_=class{constructor(e){B(this,"_value");B(this,"_currentBytePos");B(this,"_currentBitPos");this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=oIe(i,o-s,s);n=(n<7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function oIe(r,e,t){let n=sIe(e,t);return(r&n)>>>e}function sIe(r,e){return nIe[r]&iIe[Math.min(e+r-1,7)]}function YZ(r){function e(t){return t instanceof J_?t:new J_(t,r)}return e}var J_=class{constructor(e,t){B(this,"_value");B(this,"_hashFn");B(this,"_depth");B(this,"_availableBits");B(this,"_currentBufferIndex");B(this,"_buffers");if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?yi([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Z_(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Tm(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:YZ(r.hashFn)};return new bn(e)}var mk=class extends rd{constructor(e,t){super(e,t),this._bucket=Tm({hashFn:t.hamtHashFn,bits:t.hamtBucketBits})}async put(e,t){await this._bucket.put(e,t)}get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}async*flush(e){for await(let t of XZ(this._bucket,e,this,this.options))yield{...t,path:this.path}}},QZ=mk;async function*XZ(r,e,t,n){let i=r._children,o=[],s=0;for(let d=0;d=t&&(i=await aIe(e,n));let o=i.parent;if(o){if(i!==e){if(r&&(r.parent=i),!i.parentKey)throw new Error("No parent key found");await o.put(i.parentKey,i)}return ZZ(i,o,t,n)}return i}async function aIe(r,e){let t=new QZ({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:i}of r.eachChildSeries())await t.put(n,i);return t}var JZ=ZZ;var cIe=(r="")=>(r.trim().match(/([^\\/]|\\\/)+/g)||[]).filter(Boolean),eJ=cIe;async function uIe(r,e,t){let n=eJ(r.path||""),i=n.length-1,o=e,s="";for(let a=0;agk({content:o},e));return}if(qs(n)){yield gk({content:t},e);return}if(U3(n)||n[Symbol.iterator]||n[Symbol.asyncIterator]||ll(n)||ul(n)){yield*Mi(t,o=>gk(o,e));return}}throw U3(r)?(0,G3.default)(new Error("Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead"),"ERR_UNEXPECTED_INPUT"):(0,G3.default)(new Error("Unexpected input: "+typeof r),"ERR_UNEXPECTED_INPUT")}async function gk(r,e){let{path:t,mode:n,mtime:i,content:o}=r,s={path:t||"",mode:Bu(n),mtime:af(i)};return o?s.content=await e(o):t||(s.content=await e(r)),s}function nJ(r){return eE(r,H_)}var iJ=r=>{if(r)if(r.startsWith("size-")){let e=r.split("-")[1],t=parseInt(e);if(isNaN(t))throw new Error("Chunker parameter size must be an integer");return{chunker:"fixed",maxChunkSize:t}}else{if(r.startsWith("rabin"))return{chunker:"rabin",...fIe(r)};throw new Error(`Unrecognized chunker option: ${r}`)}else return{chunker:"fixed"}},fIe=r=>{let e={},t=r.split("-");switch(t.length){case 1:e.avgChunkSize=262144;break;case 2:e.avgChunkSize=tE(t[1],"avg");break;case 4:e.minChunkSize=tE(t[1],"min"),e.avgChunkSize=tE(t[2],"avg"),e.maxChunkSize=tE(t[3],"max");break;default:throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"')}return e},tE=(r,e)=>{let t=parseInt(r);if(isNaN(t))throw new Error(`Chunker parameter ${e} must be an integer`);return t};var dIe=et.bind({ignoreUndefined:!0});function oJ({repo:r,preload:e,hashers:t,options:n}){let i=n&&n.sharding;async function*o(s,a={}){let c=dIe({shardSplitThreshold:i?1e3:1/0,strategy:"balanced"},a,{...iJ(a.chunker)});c.hashAlg&&c.hashAlg!=="sha2-256"&&c.cidVersion!==1&&(c.cidVersion=1),c.trickle&&(c.strategy="trickle"),c.strategy==="trickle"&&(c.leafType="raw",c.reduceSingleLeafToSelf=!1),c.cidVersion>0&&c.rawLeaves===void 0&&(c.rawLeaves=!0),c.hashAlg!==void 0&&c.rawLeaves===void 0&&(c.rawLeaves=!0),delete c.trickle;let u={};if(c.progress){let d=c.progress;c.progress=(p,g)=>{u[g]||(u[g]=0),u[g]+=p,d(u[g],g)}}let l;c.hashAlg!=null&&(l=await t.getHasher(c.hashAlg));let f=Ne(nJ(s),d=>Im(d,r.blocks,{...c,hasher:l,pin:!1}),hIe(c),pIe(e,c),mIe(r,c)),h=await r.gcLock.readLock();try{for await(let d of f){let p=d.path??d.cid.toString();delete u[p],yield{...d,path:p}}}finally{h()}}return $(o)}function hIe(r){async function*e(t){for await(let n of t){let i=n.cid;r.cidVersion===1&&(i=i.toV1());let o=n.path?n.path:i.toString();r.wrapWithDirectory&&!n.path&&(o=""),yield{path:o,cid:i,size:n.size,mode:n.unixfs&&n.unixfs.mode,mtime:n.unixfs&&n.unixfs.mtime}}}return e}function pIe(r,e){async function*t(n){for await(let i of n)(!i.path||e.wrapWithDirectory?i.path==="":!i.path.includes("/"))&&!e.onlyHash&&e.preload!==!1&&r(i.cid),yield i}return t}function mIe(r,e){async function*t(n){for await(let i of n){let o=!(i.path&&i.path.includes("/"));(e.pin==null?!0:e.pin)&&o&&!e.onlyHash&&await r.pins.pinRecursively(i.cid),yield i}}return t}var bE=C(ee(),1);var KJ=C(ee(),1);var gIe=new TextDecoder;function yk(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function sJ(r,e){let t;return[t,e]=yk(r,e),[t&7,t>>3,e]}function yIe(r){let e={},t=r.length,n=0;for(;nt)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function aJ(r){let e=r.length,t=0,n,i=!1,o;for(;te)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var uJ=new TextEncoder,cJ=2**32,wIe=2**31;function bIe(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=j3(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=uJ.encode(r.Name);t-=n.length,e.set(n,t),t=j3(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=j3(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function lJ(r){let e=EIe(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=j3(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=bIe(r.Links[i],t.subarray(0,n));n-=o,n=j3(t,n,o)-1,t[n]=18}return t}function _Ie(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Rm(t)}if(typeof r.Name=="string"){let t=uJ.encode(r.Name).length;e+=1+t+Rm(t)}return typeof r.Tsize=="number"&&(e+=1+Rm(r.Tsize)),e}function EIe(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Rm(t)}if(r.Links)for(let t of r.Links){let n=_Ie(t);e+=1+n+Rm(n)}return e}function j3(r,e,t){e-=Rm(t);let n=e;for(;t>=wIe;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Rm(r){return r%2===0&&r++,Math.floor((vIe(r)+6)/7)}function vIe(r){let e=0;return r>=cJ&&(r=Math.floor(r/cJ),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+xIe[r]}var xIe=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var SIe=["Data","Links"],AIe=["Hash","Name","Tsize"],fJ=new TextEncoder;function TIe(r,e){if(r===e)return 0;let t=r.Name?fJ.encode(r.Name):[],n=e.Name?fJ.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s!e.includes(t))}function hJ(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!dJ(r,SIe))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e0&&TIe(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var Zo=112;function W3(r){hJ(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),lJ(e)}function Jo(r){let e=aJ(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=ce.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var wE=C(ee(),1);var pJ=C(pk(),1);var no=class{constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new pJ.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);await n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof no?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof no?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,o,s)=>(o!=null&&(o instanceof no?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return await mJ(this,e,t)}toJSON(){return this.serialize(RIe,CIe)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof no)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?fe(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof no?await i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new no(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),await n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(IIe);if(e!=null&&!(e instanceof no)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function IIe(r){return!!r}function RIe(r,e){return r.key}function CIe(r){return r}async function mJ(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof no)await mJ(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return await t(n)}var PIe=[255,254,252,248,240,224,192,128],kIe=[1,3,7,15,31,63,127,255],nE=class{constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=NIe(i,o-s,s);n=(n<7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function NIe(r,e,t){let n=DIe(e,t);return(r&n)>>>e}function DIe(r,e){return PIe[r]&kIe[Math.min(e+r-1,7)]}function yr(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Ac(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return Rf(t)}function gJ(r){function e(t){return t instanceof iE?t:new iE(t,r)}return e}var iE=class{constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?yr([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new nE(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function yJ(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:gJ(r.hashFn)};return new no(e)}var oE=C(nk(),1);function OIe(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var tmt=Ah({name:"murmur3-32",code:35,encode:r=>OIe(oE.default.x86.hash32(r))}),wJ=Ah({name:"murmur3-128",code:34,encode:r=>yh.fromHex(oE.default.x64.hash128(r))}),rmt=Ah({name:"murmur3-x64-64",code:34,encode:r=>yh.fromHex(oE.default.x64.hash128(r)).subarray(0,8)});var LIe=async function(r){return(await wJ.encode(r)).slice(0,8).reverse()},BIe=(r,e,t)=>Promise.all(r.map(n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let i=parseInt(n.Name,16);return e._putObjectAt(i,new no({hash:t._options.hash,bits:t._options.bits},e,i))}return t.put(n.Name.substring(2),!0)})),bJ=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),MIe=r=>{let e=r.bucket,t=[];for(;e._parent;)t.push(e),e=e._parent;return t.push(e),t.reverse()},_J=async(r,e,t,n,i)=>{if(!n){let l=yJ({hashFn:LIe});n={rootBucket:l,hamtDepth:1,lastBucket:l}}await BIe(r.Links,n.lastBucket,n.rootBucket);let o=await n.rootBucket._findNewBucketAndPos(e),s=bJ(o.pos),a=MIe(o);a.length>n.hamtDepth&&(n.lastBucket=a[n.hamtDepth],s=bJ(n.lastBucket._posAtParent));let c=r.Links.find(l=>{if(l.Name==null)return!1;let f=l.Name.substring(0,2),h=l.Name.substring(2);return!(f!==s||h&&h!==e)});if(!c)return null;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await t.get(c.Hash,i);return r=Jo(u),_J(r,e,t,n,i)},EJ=_J;function UIe(r,e,t,n){let i=r.length,o=e+i;return t>=o||n=e&&n=e&&t{if(e||(e=0),e<0)throw(0,sE.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(e>r)throw(0,sE.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(!t&&t!==0&&(t=r-e),t<0)throw(0,sE.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");return e+t>r&&(t=r-e),{offset:e,length:t}},Cm=FIe;var yE=C(ee(),1);function io(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var aE=globalThis.CustomEvent??Event;async function*wk(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,o=[],s=io(),a=io(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(s=io(),await s.promise),l)break;let g={done:!1};o.push(g),p().then(w=>{g.done=!0,g.ok=!0,g.value=w,i.dispatchEvent(new aE("task-complete"))},w=>{g.done=!0,g.err=w,i.dispatchEvent(new aE("task-complete"))})}c=!0,i.dispatchEvent(new aE("task-complete"))}catch(p){u=p,i.dispatchEvent(new aE("task-complete"))}});function f(){var p;return n?(p=o[0])==null?void 0:p.done:!!o.find(g=>g.done)}function*h(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}function*d(){for(;f();)for(let p=0;p0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var ip=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},fl,X3=class{constructor(){fl.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&ip(this,fl,"f")[this.size-1].priority>=t.priority){ip(this,fl,"f").push(n);return}let i=_k(ip(this,fl,"f"),n,(o,s)=>s.priority-o.priority);ip(this,fl,"f").splice(i,0,n)}dequeue(){let e=ip(this,fl,"f").shift();return e==null?void 0:e.run}filter(e){return ip(this,fl,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return ip(this,fl,"f").length}};fl=new WeakMap;var Qr=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},De=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},_n,J3,ew,id,pE,tw,uE,Ya,Z3,es,lE,ts,rw,nd,fE,SJ,AJ,RJ,TJ,IJ,dE,Ek,vk,mE,CJ,hE,gE=class extends Error{},Hs=class extends PJ.default{constructor(e){var t,n,i,o;if(super(),_n.add(this),J3.set(this,void 0),ew.set(this,void 0),id.set(this,0),pE.set(this,void 0),tw.set(this,void 0),uE.set(this,0),Ya.set(this,void 0),Z3.set(this,void 0),es.set(this,void 0),lE.set(this,void 0),ts.set(this,0),rw.set(this,void 0),nd.set(this,void 0),fE.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:X3,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);Qr(this,J3,e.carryoverConcurrencyCount,"f"),Qr(this,ew,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Qr(this,pE,e.intervalCap,"f"),Qr(this,tw,e.interval,"f"),Qr(this,es,new e.queueClass,"f"),Qr(this,lE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Qr(this,fE,e.throwOnTimeout===!0,"f"),Qr(this,nd,e.autoStart===!1,"f")}get concurrency(){return De(this,rw,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);Qr(this,rw,e,"f"),De(this,_n,"m",mE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:De(this,fE,"f"),...t},new Promise((n,i)=>{De(this,es,"f").enqueue(async()=>{var o,s,a;Qr(this,ts,(s=De(this,ts,"f"),s++,s),"f"),Qr(this,id,(a=De(this,id,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new gE("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Ih(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,De(this,_n,"m",CJ).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nf&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{De(this,_n,"m",RJ).call(this)}},t),this.emit("add"),De(this,_n,"m",dE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return De(this,nd,"f")?(Qr(this,nd,!1,"f"),De(this,_n,"m",mE).call(this),this):this}pause(){Qr(this,nd,!0,"f")}clear(){Qr(this,es,new(De(this,lE,"f")),"f")}async onEmpty(){De(this,es,"f").size!==0&&await De(this,_n,"m",hE).call(this,"empty")}async onSizeLessThan(e){De(this,es,"f").sizeDe(this,es,"f").size{De(this,_n,"m",TJ).call(this)},t),"f"),!0}return!1},dE=function(){if(De(this,es,"f").size===0)return De(this,Ya,"f")&&clearInterval(De(this,Ya,"f")),Qr(this,Ya,void 0,"f"),this.emit("empty"),De(this,ts,"f")===0&&this.emit("idle"),!1;if(!De(this,nd,"f")){let e=!De(this,_n,"a",IJ);if(De(this,_n,"a",SJ)&&De(this,_n,"a",AJ)){let t=De(this,es,"f").dequeue();return t?(this.emit("active"),t(),e&&De(this,_n,"m",Ek).call(this),!0):!1}}return!1},Ek=function(){De(this,ew,"f")||De(this,Ya,"f")!==void 0||(Qr(this,Ya,setInterval(()=>{De(this,_n,"m",vk).call(this)},De(this,tw,"f")),"f"),Qr(this,uE,Date.now()+De(this,tw,"f"),"f"))},vk=function(){De(this,id,"f")===0&&De(this,ts,"f")===0&&De(this,Ya,"f")&&(clearInterval(De(this,Ya,"f")),Qr(this,Ya,void 0,"f")),Qr(this,id,De(this,J3,"f")?De(this,ts,"f"):0,"f"),De(this,_n,"m",mE).call(this)},mE=function(){for(;De(this,_n,"m",dE).call(this););},CJ=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new gE("The task was aborted."))},{once:!0})})},hE=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};async function kJ(r,e,t,n,i,o,s,a){if(e instanceof Uint8Array){t.push(np(e,n,i,o));return}if(e.Data==null)throw(0,yE.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let c;try{c=st.unmarshal(e.Data)}catch(l){throw(0,yE.default)(l,"ERR_NOT_UNIXFS")}if(c.data!=null){let l=c.data,f=np(l,n,i,o);t.push(f),n+=f.byteLength}let u=[];for(let l=0;l=h&&i=h&&o<=d||id)&&u.push({link:f,blockStart:n}),n=d,n>o)break}await Ne(u,l=>Bi(l,f=>async()=>{let h=await r.get(f.link.Hash,{signal:a.signal});return{...f,block:h}}),l=>wk(l,{ordered:!0}),async l=>{for await(let{link:f,block:h,blockStart:d}of l){let p;switch(f.Hash.code){case Zo:p=Jo(h);break;case Sc:p=h;break;default:t.end((0,yE.default)(new Error(`Unsupported codec: ${f.Hash.code}`),"ERR_NOT_UNIXFS"));return}s.add(async()=>{await kJ(r,p,t,d,i,o,s,a)})}})}var KIe=(r,e,t,n,i,o,s)=>{async function*a(c={}){let u=t.fileSize();if(u===void 0)throw new Error("File was a directory");let{offset:l,length:f}=Cm(u,c.offset,c.length);if(f===0)return;let h=new Hs({concurrency:1}),d=jn();h.add(async()=>{await kJ(s,e,d,0,l,l+f,h,c)}),h.on("error",g=>{d.end(g)});let p=0;for await(let g of d)g!=null&&(p+=g.byteLength,p===f&&d.end(),yield g)}return a},xk=KIe;var $Ie=(r,e,t,n,i,o,s)=>{async function*a(c={}){let u=c.offset||0,l=c.length||e.Links.length,f=e.Links.slice(u,l);for(let h of f){let d=await i(h.Hash,h.Name||"",`${n}/${h.Name||""}`,[],o+1,s,c);d.entry&&(yield d.entry)}}return a},NJ=$Ie;var qIe=(r,e,t,n,i,o,s)=>{function a(c={}){return DJ(e,n,i,o,s,c)}return a};async function*DJ(r,e,t,n,i,o){let s=r.Links;for(let a of s){let c=a.Name!=null?a.Name.substring(2):null;if(c)yield(await t(a.Hash,c,`${e}/${c}`,[],n+1,i,o)).entry;else{let u=await i.get(a.Hash);r=Jo(u);for await(let l of DJ(r,e,t,n,i,o))yield l}}}var OJ=qIe;var HIe=(r,e)=>{let t=r.Links.find(n=>n.Name===e);return t&&t.Hash},GIe={raw:xk,file:xk,directory:NJ,"hamt-sharded-directory":OJ,metadata:(r,e,t,n,i,o,s)=>()=>[],symlink:(r,e,t,n,i,o,s)=>()=>[]},jIe=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),u=Jo(c),l,f;if(e||(e=r.toString()),u.Data==null)throw(0,wE.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=st.unmarshal(u.Data)}catch(h){throw(0,wE.default)(h,"ERR_NOT_UNIXFS")}if(t||(t=e),n.length){let h;if(l&&l.type==="hamt-sharded-directory"?h=await EJ(u,n[0],s):h=HIe(u,n[0]),!h)throw(0,wE.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let d=n.shift(),p=`${t}/${d}`;f={cid:h,toResolve:n,name:d||"",path:p}}return{entry:{type:l.isDirectory()?"directory":"file",name:e,path:t,cid:r,content:GIe[l.type](r,u,l,t,i,o,s),unixfs:l,depth:o,node:u,size:l.fileSize()},next:f}},LJ=jIe;var BJ=C(ee(),1);var WIe=r=>{async function*e(t={}){let{offset:n,length:i}=Cm(r.length,t.offset,t.length);yield np(r,0,n,n+i)}return e},YIe=async(r,e,t,n,i,o,s,a)=>{if(n.length)throw(0,BJ.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:WIe(c),depth:o,size:c.length,node:c}}},MJ=YIe;var UJ=C(ee(),1);var QIe=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r),u=E8(c),l=u,f=t;for(;n.length;){let h=n[0];if(h in l){n.shift(),f=`${f}/${h}`;let d=ce.asCID(l[h]);if(d)return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:o,size:c.length,content:async function*(){yield u}},next:{cid:d,name:h,path:f,toResolve:n}};l=l[h]}else throw(0,UJ.default)(new Error(`No property named ${h} found in cbor node ${r}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:o,size:c.length,content:async function*(){yield u}}}},FJ=QIe;var zJ=C(ee(),1);var XIe=r=>{async function*e(t={}){let{offset:n,length:i}=Cm(r.length,t.offset,t.length);yield np(r,0,n,n+i)}return e},ZIe=async(r,e,t,n,i,o,s,a)=>{if(n.length)throw(0,zJ.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await Jn(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:XIe(c.digest),depth:o,size:c.digest.length,node:c.digest}}},VJ=ZIe;var JIe={[Zo]:LJ,[Sc]:MJ,[W$]:FJ,[Ns.code]:VJ};function $J(r,e,t,n,i,o,s){let a=JIe[r.code];if(!a)throw(0,KJ.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,$J,i,o,s)}var qJ=$J;async function Sk(r){let e;for await(let t of r)e=t;return e}var eRe=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)||[]).filter(Boolean),tRe=r=>{if(r instanceof Uint8Array)return{cid:ce.decode(r),toResolve:[]};let e=ce.asCID(r);if(e)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=eRe(r);return{cid:ce.parse(t[0]),toResolve:t.slice(1)}}throw(0,bE.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*Ak(r,e,t={}){let{cid:n,toResolve:i}=tRe(r),o=n.toString(),s=o,a=i.length;for(;;){let c=await qJ(n,o,s,i,a,e,t);if(!c.entry&&!c.next)throw(0,bE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry&&(yield c.entry),!c.next)return;i=c.next.toResolve,n=c.next.cid,o=c.next.name,s=c.next.path}}async function Ei(r,e,t={}){let n=await Sk(Ak(r,e,t));if(!n)throw(0,bE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*_E(r,e,t={}){let n=await Ei(r,e,t);if(!n)return;if(yield n,n.type==="directory")for await(let o of i(n,t))yield o;async function*i(o,s){for await(let a of o.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*i(a,s))}}function HJ({repo:r,preload:e}){async function*t(n,i={}){if(n=N1(n),i.preload!==!1){let s=n.split("/");e(z.parse(s[0]))}let o=await Ei(n,r.blocks,i);if(o.type==="directory")throw new Error("this dag node is a directory");if(!o.content)throw new Error("this dag node has no content");yield*o.content(i)}return $(t)}var Um=C(ee(),1);var m2t="0".charCodeAt(0),g2t=cr("ustar\0","binary"),y2t=cr("ustar ","binary"),w2t=cr(" \0","binary");var QJ=C(jJ(),1);function nRe(r){return r[Symbol.asyncIterator]!=null}function iRe(r){if(nRe(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=yi([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return yi(e,t)}var WJ=iRe;var oRe="0000000000000000000",sRe="7777777777777777777",aRe="0".charCodeAt(0),cRe=cr("ustar\0","binary"),uRe=cr("00","binary"),lRe=parseInt("7777",8),fRe=257,dRe=263,hRe=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},pRe=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},od=function(r,e){let t=r.toString(8);return t.length>e?cr(sRe.slice(0,e)+" "):cr(oRe.slice(0,e-t.length)+t+" ")},Tk=function(r){let e=cr(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function YJ(r){let e="";r.name!=null&&(e+=Tk(" path="+r.name+` `)),r.linkname!=null&&(e+=Tk(" linkpath="+r.linkname+` `));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=Tk(" "+n+"="+t[n]+` -`));return cr(e)}function EE(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),cr(t).byteLength!==t.length)return null;for(;cr(t).byteLength>100;){let i=t.indexOf("/");if(i===-1)return null;n+=n!==""?"/"+t.slice(0,i):t.slice(0,i),t=t.slice(i+1)}return cr(t).byteLength>100||cr(n).byteLength>155||r.linkname!=null&&cr(r.linkname).byteLength>100?null:(e.set(cr(t),0),e.set(od(r.mode&lRe,6),100),e.set(od(r.uid,6),108),e.set(od(r.gid,6),116),e.set(od(r.size,11),124),e.set(od(r.mtime.getTime()/1e3|0,11),136),e[156]=aRe+hRe(r.type),r.linkname!=null&&e.set(cr(r.linkname),157),e.set(cRe,fRe),e.set(uRe,dRe),r.uname!=null&&e.set(cr(r.uname),265),r.gname!=null&&e.set(cr(r.gname),297),e.set(od(r.devmajor??0,6),329),e.set(od(r.devminor??0,6),337),n!=null&&e.set(cr(n),345),e.set(od(pRe(e),6),148),e)}var{S_IFMT:gRe,S_IFBLK:yRe,S_IFCHR:wRe,S_IFDIR:bRe,S_IFIFO:_Re,S_IFLNK:ERe}=QJ.default,vRe=parseInt("755",8),xRe=parseInt("644",8),XJ=new Uint8Array(1024);function SRe(r=0){switch(r&gRe){case yRe:return"block-device";case wRe:return"character-device";case bRe:return"directory";case _Re:return"fifo";case ERe:return"symlink";default:return"file"}}function Rk(r){return r&=511,r!==0?XJ.subarray(0,512-r):new Uint8Array(0)}function Ik(r){if(r.pax==null){let e=EE(r);if(e!=null)return e}return ARe(r)}function ARe(r){let e=YJ(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new vt(EE(t)??new Uint8Array(0),e,Rk(e.length),EE({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function vE(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??SRe(e.mode),mode:e.mode??(e.type==="directory"?vRe:xRe),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=cr(t)),t instanceof Uint8Array||$c(t)){n.size=t.length,yield Ik(n),yield $c(t)?t.subarray():t,yield Rk(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=$n(await WJ(t)),yield Ik(n);continue}if(yield Ik(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let i=0;for await(let o of t??[])i+=o.length,yield $c(o)?o.subarray():o;if(i!==n.size)throw new Error(`size mismatch, wrote ${i} of ${n.size} bytes`);yield Rk(n.size)}yield XJ}}function Lm(r){let e=r.length;for(;--e>=0;)r[e]=0}var TRe=0,Bee=1,IRe=2,RRe=3,CRe=258,Zk=29,yw=256,uw=yw+1+Zk,Nm=30,Jk=19,Mee=2*uw+1,op=15,Ck=16,PRe=7,eN=256,Uee=16,Fee=17,zee=18,$k=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),RE=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),kRe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Vee=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),NRe=512,hl=new Array((uw+2)*2);Lm(hl);var sw=new Array(Nm*2);Lm(sw);var lw=new Array(NRe);Lm(lw);var fw=new Array(CRe-RRe+1);Lm(fw);var tN=new Array(Zk);Lm(tN);var CE=new Array(Nm);Lm(CE);function Pk(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}var Kee,$ee,qee;function kk(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}var Hee=r=>r<256?lw[r]:lw[256+(r>>>7)],dw=(r,e)=>{r.pending_buf[r.pending++]=e&255,r.pending_buf[r.pending++]=e>>>8&255},wo=(r,e,t)=>{r.bi_valid>Ck-t?(r.bi_buf|=e<>Ck-r.bi_valid,r.bi_valid+=t-Ck):(r.bi_buf|=e<{wo(r,t[e*2],t[e*2+1])},Gee=(r,e)=>{let t=0;do t|=r&1,r>>>=1,t<<=1;while(--e>0);return t>>>1},DRe=r=>{r.bi_valid===16?(dw(r,r.bi_buf),r.bi_buf=0,r.bi_valid=0):r.bi_valid>=8&&(r.pending_buf[r.pending++]=r.bi_buf&255,r.bi_buf>>=8,r.bi_valid-=8)},ORe=(r,e)=>{let t=e.dyn_tree,n=e.max_code,i=e.stat_desc.static_tree,o=e.stat_desc.has_stree,s=e.stat_desc.extra_bits,a=e.stat_desc.extra_base,c=e.stat_desc.max_length,u,l,f,h,d,p,g=0;for(h=0;h<=op;h++)r.bl_count[h]=0;for(t[r.heap[r.heap_max]*2+1]=0,u=r.heap_max+1;uc&&(h=c,g++),t[l*2+1]=h,!(l>n)&&(r.bl_count[h]++,d=0,l>=a&&(d=s[l-a]),p=t[l*2],r.opt_len+=p*(h+d),o&&(r.static_len+=p*(i[l*2+1]+d)));if(g!==0){do{for(h=c-1;r.bl_count[h]===0;)h--;r.bl_count[h]--,r.bl_count[h+1]+=2,r.bl_count[c]--,g-=2}while(g>0);for(h=c;h!==0;h--)for(l=r.bl_count[h];l!==0;)f=r.heap[--u],!(f>n)&&(t[f*2+1]!==h&&(r.opt_len+=(h-t[f*2+1])*t[f*2],t[f*2+1]=h),l--)}},jee=(r,e,t)=>{let n=new Array(op+1),i=0,o,s;for(o=1;o<=op;o++)i=i+t[o-1]<<1,n[o]=i;for(s=0;s<=e;s++){let a=r[s*2+1];a!==0&&(r[s*2]=Gee(n[a]++,a))}},LRe=()=>{let r,e,t,n,i,o=new Array(op+1);for(t=0,n=0;n>=7;n{let e;for(e=0;e{r.bi_valid>8?dw(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},ZJ=(r,e,t,n)=>{let i=e*2,o=t*2;return r[i]{let n=r.heap[t],i=t<<1;for(;i<=r.heap_len&&(i{let n,i,o=0,s,a;if(r.sym_next!==0)do n=r.pending_buf[r.sym_buf+o++]&255,n+=(r.pending_buf[r.sym_buf+o++]&255)<<8,i=r.pending_buf[r.sym_buf+o++],n===0?Hc(r,i,e):(s=fw[i],Hc(r,s+yw+1,e),a=$k[s],a!==0&&(i-=tN[s],wo(r,i,a)),n--,s=Hee(n),Hc(r,s,t),a=RE[s],a!==0&&(n-=CE[s],wo(r,n,a)));while(o{let t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,o=e.stat_desc.elems,s,a,c=-1,u;for(r.heap_len=0,r.heap_max=Mee,s=0;s>1;s>=1;s--)Nk(r,t,s);u=o;do s=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Nk(r,t,1),a=r.heap[1],r.heap[--r.heap_max]=s,r.heap[--r.heap_max]=a,t[u*2]=t[s*2]+t[a*2],r.depth[u]=(r.depth[s]>=r.depth[a]?r.depth[s]:r.depth[a])+1,t[s*2+1]=t[a*2+1]=u,r.heap[1]=u++,Nk(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],ORe(r,e),jee(t,c,r.bl_count)},eee=(r,e,t)=>{let n,i=-1,o,s=e[0*2+1],a=0,c=7,u=4;for(s===0&&(c=138,u=3),e[(t+1)*2+1]=65535,n=0;n<=t;n++)o=s,s=e[(n+1)*2+1],!(++a{let n,i=-1,o,s=e[0*2+1],a=0,c=7,u=4;for(s===0&&(c=138,u=3),n=0;n<=t;n++)if(o=s,s=e[(n+1)*2+1],!(++a{let e;for(eee(r,r.dyn_ltree,r.l_desc.max_code),eee(r,r.dyn_dtree,r.d_desc.max_code),qk(r,r.bl_desc),e=Jk-1;e>=3&&r.bl_tree[Vee[e]*2+1]===0;e--);return r.opt_len+=3*(e+1)+5+5+4,e},MRe=(r,e,t,n)=>{let i;for(wo(r,e-257,5),wo(r,t-1,5),wo(r,n-4,4),i=0;i{let e=4093624447,t;for(t=0;t<=31;t++,e>>>=1)if(e&1&&r.dyn_ltree[t*2]!==0)return 0;if(r.dyn_ltree[9*2]!==0||r.dyn_ltree[10*2]!==0||r.dyn_ltree[13*2]!==0)return 1;for(t=32;t{ree||(LRe(),ree=!0),r.l_desc=new kk(r.dyn_ltree,Kee),r.d_desc=new kk(r.dyn_dtree,$ee),r.bl_desc=new kk(r.bl_tree,qee),r.bi_buf=0,r.bi_valid=0,Wee(r)},Qee=(r,e,t,n)=>{wo(r,(TRe<<1)+(n?1:0),3),Yee(r),dw(r,t),dw(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},zRe=r=>{wo(r,Bee<<1,3),Hc(r,eN,hl),DRe(r)},VRe=(r,e,t,n)=>{let i,o,s=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=URe(r)),qk(r,r.l_desc),qk(r,r.d_desc),s=BRe(r),i=r.opt_len+3+7>>>3,o=r.static_len+3+7>>>3,o<=i&&(i=o)):i=o=t+5,t+4<=i&&e!==-1?Qee(r,e,t,n):r.strategy===4||o===i?(wo(r,(Bee<<1)+(n?1:0),3),JJ(r,hl,sw)):(wo(r,(IRe<<1)+(n?1:0),3),MRe(r,r.l_desc.max_code+1,r.d_desc.max_code+1,s+1),JJ(r,r.dyn_ltree,r.dyn_dtree)),Wee(r),n&&Yee(r)},KRe=(r,e,t)=>(r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[t*2]++:(r.matches++,e--,r.dyn_ltree[(fw[t]+yw+1)*2]++,r.dyn_dtree[Hee(e)*2]++),r.sym_next===r.sym_end),$Re=FRe,qRe=Qee,HRe=VRe,GRe=KRe,jRe=zRe,WRe={_tr_init:$Re,_tr_stored_block:qRe,_tr_flush_block:HRe,_tr_tally:GRe,_tr_align:jRe},YRe=(r,e,t,n)=>{let i=r&65535|0,o=r>>>16&65535|0,s=0;for(;t!==0;){s=t>2e3?2e3:t,t-=s;do i=i+e[n++]|0,o=o+i|0;while(--s);i%=65521,o%=65521}return i|o<<16|0},hw=YRe,QRe=()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r}return e},XRe=new Uint32Array(QRe()),ZRe=(r,e,t,n)=>{let i=XRe,o=n+t;r^=-1;for(let s=n;s>>8^i[(r^e[s])&255];return r^-1},ci=ZRe,cp={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},fp={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:JRe,_tr_stored_block:Hk,_tr_flush_block:eCe,_tr_tally:cd,_tr_align:tCe}=WRe,{Z_NO_FLUSH:ud,Z_PARTIAL_FLUSH:rCe,Z_FULL_FLUSH:nCe,Z_FINISH:Gs,Z_BLOCK:nee,Z_OK:vi,Z_STREAM_END:iee,Z_STREAM_ERROR:Gc,Z_DATA_ERROR:iCe,Z_BUF_ERROR:Dk,Z_DEFAULT_COMPRESSION:oCe,Z_FILTERED:sCe,Z_HUFFMAN_ONLY:xE,Z_RLE:aCe,Z_FIXED:cCe,Z_DEFAULT_STRATEGY:uCe,Z_UNKNOWN:lCe,Z_DEFLATED:NE}=fp,fCe=9,dCe=15,hCe=8,pCe=29,mCe=256,Gk=mCe+1+pCe,gCe=30,yCe=19,wCe=2*Gk+1,bCe=15,Mt=3,ad=258,jc=ad+Mt+1,_Ce=32,Dm=42,rN=57,jk=69,Wk=73,Yk=91,Qk=103,sp=113,iw=666,so=1,Bm=2,up=3,Mm=4,ECe=3,ap=(r,e)=>(r.msg=cp[e],e),oee=r=>r*2-(r>4?9:0),sd=r=>{let e=r.length;for(;--e>=0;)r[e]=0},vCe=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)},xCe=(r,e,t)=>(e<{let e=r.state,t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},ns=(r,e)=>{eCe(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,rs(r.strm)},or=(r,e)=>{r.pending_buf[r.pending++]=e},nw=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=e&255},Xk=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=hw(r.adler,e,i,t):r.state.wrap===2&&(r.adler=ci(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},Xee=(r,e)=>{let t=r.max_chain_length,n=r.strstart,i,o,s=r.prev_length,a=r.nice_match,c=r.strstart>r.w_size-jc?r.strstart-(r.w_size-jc):0,u=r.window,l=r.w_mask,f=r.prev,h=r.strstart+ad,d=u[n+s-1],p=u[n+s];r.prev_length>=r.good_match&&(t>>=2),a>r.lookahead&&(a=r.lookahead);do if(i=e,!(u[i+s]!==p||u[i+s-1]!==d||u[i]!==u[n]||u[++i]!==u[n+1])){n+=2,i++;do;while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&ns){if(r.match_start=e,s=o,o>=a)break;d=u[n+s-1],p=u[n+s]}}while((e=f[e&l])>c&&--t!==0);return s<=r.lookahead?s:r.lookahead},Om=r=>{let e=r.w_size,t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-jc)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),vCe(r),n+=e),r.strm.avail_in===0)break;if(t=Xk(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.lookahead+r.insert>=Mt)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=ld(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=ld(r,r.ins_h,r.window[i+Mt-1]),r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++,r.insert--,!(r.lookahead+r.insert{let t=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,n,i,o,s=0,a=r.strm.avail_in;do{if(n=65535,o=r.bi_valid+42>>3,r.strm.avail_outi+r.strm.avail_in&&(n=i+r.strm.avail_in),n>o&&(n=o),n>8,r.pending_buf[r.pending-2]=~n,r.pending_buf[r.pending-1]=~n>>8,rs(r.strm),i&&(i>n&&(i=n),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+i),r.strm.next_out),r.strm.next_out+=i,r.strm.avail_out-=i,r.strm.total_out+=i,r.block_start+=i,n-=i),n&&(Xk(r.strm,r.strm.output,r.strm.next_out,n),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n)}while(s===0);return a-=r.strm.avail_in,a&&(a>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=a&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-a,r.strm.next_in),r.strstart),r.strstart+=a,r.insert+=a>r.w_size-r.insert?r.w_size-r.insert:a),r.block_start=r.strstart),r.high_watero&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,o+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),o>r.strm.avail_in&&(o=r.strm.avail_in),o&&(Xk(r.strm,r.window,r.strstart,o),r.strstart+=o,r.insert+=o>r.w_size-r.insert?r.w_size-r.insert:o),r.high_water>3,o=r.pending_buf_size-o>65535?65535:r.pending_buf_size-o,t=o>r.w_size?r.w_size:o,i=r.strstart-r.block_start,(i>=t||(i||e===Gs)&&e!==ud&&r.strm.avail_in===0&&i<=o)&&(n=i>o?o:i,s=e===Gs&&r.strm.avail_in===0&&n===i?1:0,Hk(r,r.block_start,n,s),r.block_start+=n,rs(r.strm)),s?up:so)},Ok=(r,e)=>{let t,n;for(;;){if(r.lookahead=Mt&&(r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),t!==0&&r.strstart-t<=r.w_size-jc&&(r.match_length=Xee(r,t)),r.match_length>=Mt)if(n=cd(r,r.strstart-r.match_start,r.match_length-Mt),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=Mt){r.match_length--;do r.strstart++,r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart;while(--r.match_length!==0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.ins_h=r.window[r.strstart],r.ins_h=ld(r,r.ins_h,r.window[r.strstart+1]);else n=cd(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(ns(r,!1),r.strm.avail_out===0))return so}return r.insert=r.strstart{let t,n,i;for(;;){if(r.lookahead=Mt&&(r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=Mt-1,t!==0&&r.prev_length4096)&&(r.match_length=Mt-1)),r.prev_length>=Mt&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-Mt,n=cd(r,r.strstart-1-r.prev_match,r.prev_length-Mt),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart);while(--r.prev_length!==0);if(r.match_available=0,r.match_length=Mt-1,r.strstart++,n&&(ns(r,!1),r.strm.avail_out===0))return so}else if(r.match_available){if(n=cd(r,0,r.window[r.strstart-1]),n&&ns(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return so}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(n=cd(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart{let t,n,i,o,s=r.window;for(;;){if(r.lookahead<=ad){if(Om(r),r.lookahead<=ad&&e===ud)return so;if(r.lookahead===0)break}if(r.match_length=0,r.lookahead>=Mt&&r.strstart>0&&(i=r.strstart-1,n=s[i],n===s[++i]&&n===s[++i]&&n===s[++i])){o=r.strstart+ad;do;while(n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&ir.lookahead&&(r.match_length=r.lookahead)}if(r.match_length>=Mt?(t=cd(r,1,r.match_length-Mt),r.lookahead-=r.match_length,r.strstart+=r.match_length,r.match_length=0):(t=cd(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++),t&&(ns(r,!1),r.strm.avail_out===0))return so}return r.insert=0,e===Gs?(ns(r,!0),r.strm.avail_out===0?up:Mm):r.sym_next&&(ns(r,!1),r.strm.avail_out===0)?so:Bm},ACe=(r,e)=>{let t;for(;;){if(r.lookahead===0&&(Om(r),r.lookahead===0)){if(e===ud)return so;break}if(r.match_length=0,t=cd(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++,t&&(ns(r,!1),r.strm.avail_out===0))return so}return r.insert=0,e===Gs?(ns(r,!0),r.strm.avail_out===0?up:Mm):r.sym_next&&(ns(r,!1),r.strm.avail_out===0)?so:Bm};function qc(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}var ow=[new qc(0,0,0,0,Zee),new qc(4,4,8,4,Ok),new qc(4,5,16,8,Ok),new qc(4,6,32,32,Ok),new qc(4,4,16,16,Pm),new qc(8,16,32,32,Pm),new qc(8,16,128,128,Pm),new qc(8,32,128,256,Pm),new qc(32,128,258,1024,Pm),new qc(32,258,258,4096,Pm)],TCe=r=>{r.window_size=2*r.w_size,sd(r.head),r.max_lazy_match=ow[r.level].max_lazy,r.good_match=ow[r.level].good_length,r.nice_match=ow[r.level].nice_length,r.max_chain_length=ow[r.level].max_chain,r.strstart=0,r.block_start=0,r.lookahead=0,r.insert=0,r.match_length=r.prev_length=Mt-1,r.match_available=0,r.ins_h=0};function ICe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=NE,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(wCe*2),this.dyn_dtree=new Uint16Array((2*gCe+1)*2),this.bl_tree=new Uint16Array((2*yCe+1)*2),sd(this.dyn_ltree),sd(this.dyn_dtree),sd(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(bCe+1),this.heap=new Uint16Array(2*Gk+1),sd(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Gk+1),sd(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var ww=r=>{if(!r)return 1;let e=r.state;return!e||e.strm!==r||e.status!==Dm&&e.status!==rN&&e.status!==jk&&e.status!==Wk&&e.status!==Yk&&e.status!==Qk&&e.status!==sp&&e.status!==iw?1:0},Jee=r=>{if(ww(r))return ap(r,Gc);r.total_in=r.total_out=0,r.data_type=lCe;let e=r.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?rN:e.wrap?Dm:sp,r.adler=e.wrap===2?0:1,e.last_flush=-2,JRe(e),vi},ete=r=>{let e=Jee(r);return e===vi&&TCe(r.state),e},RCe=(r,e)=>ww(r)||r.state.wrap!==2?Gc:(r.state.gzhead=e,vi),tte=(r,e,t,n,i,o)=>{if(!r)return Gc;let s=1;if(e===oCe&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),i<1||i>fCe||t!==NE||n<8||n>15||e<0||e>9||o<0||o>cCe||n===8&&s!==1)return ap(r,Gc);n===8&&(n=9);let a=new ICe;return r.state=a,a.strm=r,a.status=Dm,a.wrap=s,a.gzhead=null,a.w_bits=n,a.w_size=1<tte(r,e,NE,dCe,hCe,uCe),PCe=(r,e)=>{if(ww(r)||e>nee||e<0)return r?ap(r,Gc):Gc;let t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===iw&&e!==Gs)return ap(r,r.avail_out===0?Dk:Gc);let n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(rs(r),r.avail_out===0)return t.last_flush=-1,vi}else if(r.avail_in===0&&oee(e)<=oee(n)&&e!==Gs)return ap(r,Dk);if(t.status===iw&&r.avail_in!==0)return ap(r,Dk);if(t.status===Dm&&t.wrap===0&&(t.status=sp),t.status===Dm){let i=NE+(t.w_bits-8<<4)<<8,o=-1;if(t.strategy>=xE||t.level<2?o=0:t.level<6?o=1:t.level===6?o=2:o=3,i|=o<<6,t.strstart!==0&&(i|=_Ce),i+=31-i%31,nw(t,i),t.strstart!==0&&(nw(t,r.adler>>>16),nw(t,r.adler&65535)),r.adler=1,t.status=sp,rs(r),t.pending!==0)return t.last_flush=-1,vi}if(t.status===rN){if(r.adler=0,or(t,31),or(t,139),or(t,8),t.gzhead)or(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),or(t,t.gzhead.time&255),or(t,t.gzhead.time>>8&255),or(t,t.gzhead.time>>16&255),or(t,t.gzhead.time>>24&255),or(t,t.level===9?2:t.strategy>=xE||t.level<2?4:0),or(t,t.gzhead.os&255),t.gzhead.extra&&t.gzhead.extra.length&&(or(t,t.gzhead.extra.length&255),or(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=ci(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=jk;else if(or(t,0),or(t,0),or(t,0),or(t,0),or(t,0),or(t,t.level===9?2:t.strategy>=xE||t.level<2?4:0),or(t,ECe),t.status=sp,rs(r),t.pending!==0)return t.last_flush=-1,vi}if(t.status===jk){if(t.gzhead.extra){let i=t.pending,o=(t.gzhead.extra.length&65535)-t.gzindex;for(;t.pending+o>t.pending_buf_size;){let a=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+a),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=a,rs(r),t.pending!==0)return t.last_flush=-1,vi;i=0,o-=a}let s=new Uint8Array(t.gzhead.extra);t.pending_buf.set(s.subarray(t.gzindex,t.gzindex+o),t.pending),t.pending+=o,t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=Wk}if(t.status===Wk){if(t.gzhead.name){let i=t.pending,o;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),rs(r),t.pending!==0)return t.last_flush=-1,vi;i=0}t.gzindexi&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=Yk}if(t.status===Yk){if(t.gzhead.comment){let i=t.pending,o;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),rs(r),t.pending!==0)return t.last_flush=-1,vi;i=0}t.gzindexi&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i))}t.status=Qk}if(t.status===Qk){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(rs(r),t.pending!==0))return t.last_flush=-1,vi;or(t,r.adler&255),or(t,r.adler>>8&255),r.adler=0}if(t.status=sp,rs(r),t.pending!==0)return t.last_flush=-1,vi}if(r.avail_in!==0||t.lookahead!==0||e!==ud&&t.status!==iw){let i=t.level===0?Zee(t,e):t.strategy===xE?ACe(t,e):t.strategy===aCe?SCe(t,e):ow[t.level].func(t,e);if((i===up||i===Mm)&&(t.status=iw),i===so||i===up)return r.avail_out===0&&(t.last_flush=-1),vi;if(i===Bm&&(e===rCe?tCe(t):e!==nee&&(Hk(t,0,0,!1),e===nCe&&(sd(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),rs(r),r.avail_out===0))return t.last_flush=-1,vi}return e!==Gs?vi:t.wrap<=0?iee:(t.wrap===2?(or(t,r.adler&255),or(t,r.adler>>8&255),or(t,r.adler>>16&255),or(t,r.adler>>24&255),or(t,r.total_in&255),or(t,r.total_in>>8&255),or(t,r.total_in>>16&255),or(t,r.total_in>>24&255)):(nw(t,r.adler>>>16),nw(t,r.adler&65535)),rs(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?vi:iee)},kCe=r=>{if(ww(r))return Gc;let e=r.state.status;return r.state=null,e===sp?ap(r,iCe):vi},NCe=(r,e)=>{let t=e.length;if(ww(r))return Gc;let n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==Dm||n.lookahead)return Gc;if(i===1&&(r.adler=hw(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(sd(n.head),n.strstart=0,n.block_start=0,n.insert=0);let c=new Uint8Array(n.w_size);c.set(e.subarray(t-n.w_size,t),0),e=c,t=n.w_size}let o=r.avail_in,s=r.next_in,a=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,Om(n);n.lookahead>=Mt;){let c=n.strstart,u=n.lookahead-(Mt-1);do n.ins_h=ld(n,n.ins_h,n.window[c+Mt-1]),n.prev[c&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=c,c++;while(--u);n.strstart=c,n.lookahead=Mt-1,Om(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=Mt-1,n.match_available=0,r.next_in=s,r.input=a,r.avail_in=o,n.wrap=i,vi},DCe=CCe,OCe=tte,LCe=ete,BCe=Jee,MCe=RCe,UCe=PCe,FCe=kCe,zCe=NCe,VCe="pako deflate (from Nodeca project)",aw={deflateInit:DCe,deflateInit2:OCe,deflateReset:LCe,deflateResetKeep:BCe,deflateSetHeader:MCe,deflate:UCe,deflateEnd:FCe,deflateSetDictionary:zCe,deflateInfo:VCe},KCe=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),$Ce=function(r){let e=Array.prototype.slice.call(arguments,1);for(;e.length;){let t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(let n in t)KCe(t,n)&&(r[n]=t[n])}}return r},qCe=r=>{let e=0;for(let n=0,i=r.length;n=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;pw[254]=pw[254]=1;var HCe=r=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);let e,t,n,i,o,s=r.length,a=0;for(i=0;i>>6,e[o++]=128|t&63):t<65536?(e[o++]=224|t>>>12,e[o++]=128|t>>>6&63,e[o++]=128|t&63):(e[o++]=240|t>>>18,e[o++]=128|t>>>12&63,e[o++]=128|t>>>6&63,e[o++]=128|t&63);return e},GCe=(r,e)=>{if(e<65534&&r.subarray&&rte)return String.fromCharCode.apply(null,r.length===e?r:r.subarray(0,e));let t="";for(let n=0;n{let t=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));let n,i,o=new Array(t*2);for(i=0,n=0;n4){o[i++]=65533,n+=a-1;continue}for(s&=a===2?31:a===3?15:7;a>1&&n1){o[i++]=65533;continue}s<65536?o[i++]=s:(s-=65536,o[i++]=55296|s>>10&1023,o[i++]=56320|s&1023)}return GCe(o,i)},WCe=(r,e)=>{e=e||r.length,e>r.length&&(e=r.length);let t=e-1;for(;t>=0&&(r[t]&192)===128;)t--;return t<0||t===0?e:t+pw[r[t]]>e?t:e},mw={string2buf:HCe,buf2string:jCe,utf8border:WCe};function YCe(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var nte=YCe,ite=Object.prototype.toString,{Z_NO_FLUSH:QCe,Z_SYNC_FLUSH:XCe,Z_FULL_FLUSH:ZCe,Z_FINISH:JCe,Z_OK:PE,Z_STREAM_END:ePe,Z_DEFAULT_COMPRESSION:tPe,Z_DEFAULT_STRATEGY:rPe,Z_DEFLATED:nPe}=fp;function bw(r){this.options=DE.assign({level:tPe,method:nPe,chunkSize:16384,windowBits:15,memLevel:8,strategy:rPe},r||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nte,this.strm.avail_out=0;let t=aw.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==PE)throw new Error(cp[t]);if(e.header&&aw.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(typeof e.dictionary=="string"?n=mw.string2buf(e.dictionary):ite.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,t=aw.deflateSetDictionary(this.strm,n),t!==PE)throw new Error(cp[t]);this._dict_set=!0}}bw.prototype.push=function(r,e){let t=this.strm,n=this.options.chunkSize,i,o;if(this.ended)return!1;for(e===~~e?o=e:o=e===!0?JCe:QCe,typeof r=="string"?t.input=mw.string2buf(r):ite.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(o===XCe||o===ZCe)&&t.avail_out<=6){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(i=aw.deflate(t,o),i===ePe)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=aw.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===PE;if(t.avail_out===0){this.onData(t.output);continue}if(o>0&&t.next_out>0){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(t.avail_in===0)break}return!0};bw.prototype.onData=function(r){this.chunks.push(r)};bw.prototype.onEnd=function(r){r===PE&&(this.result=DE.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};function nN(r,e){let t=new bw(e);if(t.push(r,!0),t.err)throw t.msg||cp[t.err];return t.result}function iPe(r,e){return e=e||{},e.raw=!0,nN(r,e)}function oPe(r,e){return e=e||{},e.gzip=!0,nN(r,e)}var sPe=bw,aPe=nN,cPe=iPe,uPe=oPe,lPe=fp,fPe={Deflate:sPe,deflate:aPe,deflateRaw:cPe,gzip:uPe,constants:lPe},SE=16209,dPe=16191,hPe=function(e,t){let n,i,o,s,a,c,u,l,f,h,d,p,g,w,_,x,m,y,b,E,v,S,A,I,k=e.state;n=e.next_in,A=e.input,i=n+(e.avail_in-5),o=e.next_out,I=e.output,s=o-(t-e.avail_out),a=o+(e.avail_out-257),c=k.dmax,u=k.wsize,l=k.whave,f=k.wnext,h=k.window,d=k.hold,p=k.bits,g=k.lencode,w=k.distcode,_=(1<>>24,d>>>=y,p-=y,y=m>>>16&255,y===0)I[o++]=m&65535;else if(y&16){b=m&65535,y&=15,y&&(p>>=y,p-=y),p<15&&(d+=A[n++]<>>24,d>>>=y,p-=y,y=m>>>16&255,y&16){if(E=m&65535,y&=15,pc){e.msg="invalid distance too far back",k.mode=SE;break e}if(d>>>=y,p-=y,y=o-s,E>y){if(y=E-y,y>l&&k.sane){e.msg="invalid distance too far back",k.mode=SE;break e}if(v=0,S=h,f===0){if(v+=u-y,y2;)I[o++]=S[v++],I[o++]=S[v++],I[o++]=S[v++],b-=3;b&&(I[o++]=S[v++],b>1&&(I[o++]=S[v++]))}else{v=o-E;do I[o++]=I[v++],I[o++]=I[v++],I[o++]=I[v++],b-=3;while(b>2);b&&(I[o++]=I[v++],b>1&&(I[o++]=I[v++]))}}else if(y&64){e.msg="invalid distance code",k.mode=SE;break e}else{m=w[(m&65535)+(d&(1<>3,n-=b,p-=b<<3,d&=(1<{let c=a.bits,u=0,l=0,f=0,h=0,d=0,p=0,g=0,w=0,_=0,x=0,m,y,b,E,v,S=null,A,I=new Uint16Array(km+1),k=new Uint16Array(km+1),N=null,O,G,R;for(u=0;u<=km;u++)I[u]=0;for(l=0;l=1&&I[h]===0;h--);if(d>h&&(d=h),h===0)return i[o++]=1<<24|64<<16|0,i[o++]=1<<24|64<<16|0,a.bits=1,0;for(f=1;f0&&(r===cee||h!==1))return-1;for(k[1]=0,u=1;usee||r===uee&&_>aee)return 1;for(;;){O=u-g,s[l]+1=A?(G=N[s[l]-A],R=S[s[l]-A]):(G=32+64,R=0),m=1<>g)+y]=O<<24|G<<16|R|0;while(y!==0);for(m=1<>=1;if(m!==0?(x&=m-1,x+=m):x=0,l++,--I[u]===0){if(u===h)break;u=e[t+s[l]]}if(u>d&&(x&E)!==b){for(g===0&&(g=d),v+=f,p=u-g,w=1<see||r===uee&&_>aee)return 1;b=x&E,i[b]=d<<24|p<<16|v-o|0}}return x!==0&&(i[v+x]=u-g<<24|64<<16|0),a.bits=d,0},cw=wPe,bPe=0,ote=1,ste=2,{Z_FINISH:lee,Z_BLOCK:_Pe,Z_TREES:AE,Z_OK:lp,Z_STREAM_END:EPe,Z_NEED_DICT:vPe,Z_STREAM_ERROR:js,Z_DATA_ERROR:ate,Z_MEM_ERROR:cte,Z_BUF_ERROR:xPe,Z_DEFLATED:fee}=fp,OE=16180,dee=16181,hee=16182,pee=16183,mee=16184,gee=16185,yee=16186,wee=16187,bee=16188,_ee=16189,kE=16190,dl=16191,Bk=16192,Eee=16193,Mk=16194,vee=16195,xee=16196,See=16197,Aee=16198,TE=16199,IE=16200,Tee=16201,Iee=16202,Ree=16203,Cee=16204,Pee=16205,Uk=16206,kee=16207,Nee=16208,Kr=16209,ute=16210,lte=16211,SPe=852,APe=592,TPe=15,IPe=TPe,Dee=r=>(r>>>24&255)+(r>>>8&65280)+((r&65280)<<8)+((r&255)<<24);function RPe(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var dp=r=>{if(!r)return 1;let e=r.state;return!e||e.strm!==r||e.modelte?1:0},fte=r=>{if(dp(r))return js;let e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.adler=e.wrap&1),e.mode=OE,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(SPe),e.distcode=e.distdyn=new Int32Array(APe),e.sane=1,e.back=-1,lp},dte=r=>{if(dp(r))return js;let e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,fte(r)},hte=(r,e)=>{let t;if(dp(r))return js;let n=r.state;return e<0?(t=0,e=-e):(t=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?js:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,dte(r))},pte=(r,e)=>{if(!r)return js;let t=new RPe;r.state=t,t.strm=r,t.window=null,t.mode=OE;let n=hte(r,e);return n!==lp&&(r.state=null),n},CPe=r=>pte(r,IPe),Oee=!0,Fk,zk,PPe=r=>{if(Oee){Fk=new Int32Array(512),zk=new Int32Array(32);let e=0;for(;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(cw(ote,r.lens,0,288,Fk,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;cw(ste,r.lens,0,32,zk,0,r.work,{bits:5}),Oee=!1}r.lencode=Fk,r.lenbits=9,r.distcode=zk,r.distbits=5},mte=(r,e,t,n)=>{let i,o=r.state;return o.window===null&&(o.wsize=1<=o.wsize?(o.window.set(e.subarray(t-o.wsize,t),0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>n&&(i=n),o.window.set(e.subarray(t-n,t-n+i),o.wnext),n-=i,n?(o.window.set(e.subarray(t-n,t),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave{let t,n,i,o,s,a,c,u,l,f,h,d,p,g,w=0,_,x,m,y,b,E,v,S,A=new Uint8Array(4),I,k,N=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(dp(r)||!r.output||!r.input&&r.avail_in!==0)return js;t=r.state,t.mode===dl&&(t.mode=Bk),s=r.next_out,i=r.output,c=r.avail_out,o=r.next_in,n=r.input,a=r.avail_in,u=t.hold,l=t.bits,f=a,h=c,S=lp;e:for(;;)switch(t.mode){case OE:if(t.wrap===0){t.mode=Bk;break}for(;l<16;){if(a===0)break e;a--,u+=n[o++]<>>8&255,t.check=ci(t.check,A,2,0),u=0,l=0,t.mode=dee;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((u&255)<<8)+(u>>8))%31){r.msg="incorrect header check",t.mode=Kr;break}if((u&15)!==fee){r.msg="unknown compression method",t.mode=Kr;break}if(u>>>=4,l-=4,v=(u&15)+8,t.wbits===0&&(t.wbits=v),v>15||v>t.wbits){r.msg="invalid window size",t.mode=Kr;break}t.dmax=1<>8&1),t.flags&512&&t.wrap&4&&(A[0]=u&255,A[1]=u>>>8&255,t.check=ci(t.check,A,2,0)),u=0,l=0,t.mode=hee;case hee:for(;l<32;){if(a===0)break e;a--,u+=n[o++]<>>8&255,A[2]=u>>>16&255,A[3]=u>>>24&255,t.check=ci(t.check,A,4,0)),u=0,l=0,t.mode=pee;case pee:for(;l<16;){if(a===0)break e;a--,u+=n[o++]<>8),t.flags&512&&t.wrap&4&&(A[0]=u&255,A[1]=u>>>8&255,t.check=ci(t.check,A,2,0)),u=0,l=0,t.mode=mee;case mee:if(t.flags&1024){for(;l<16;){if(a===0)break e;a--,u+=n[o++]<>>8&255,t.check=ci(t.check,A,2,0)),u=0,l=0}else t.head&&(t.head.extra=null);t.mode=gee;case gee:if(t.flags&1024&&(d=t.length,d>a&&(d=a),d&&(t.head&&(v=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(o,o+d),v)),t.flags&512&&t.wrap&4&&(t.check=ci(t.check,n,d,o)),a-=d,o+=d,t.length-=d),t.length))break e;t.length=0,t.mode=yee;case yee:if(t.flags&2048){if(a===0)break e;d=0;do v=n[o+d++],t.head&&v&&t.length<65536&&(t.head.name+=String.fromCharCode(v));while(v&&d>9&1,t.head.done=!0),r.adler=t.check=0,t.mode=dl;break;case _ee:for(;l<32;){if(a===0)break e;a--,u+=n[o++]<>>=l&7,l-=l&7,t.mode=Uk;break}for(;l<3;){if(a===0)break e;a--,u+=n[o++]<>>=1,l-=1,u&3){case 0:t.mode=Eee;break;case 1:if(PPe(t),t.mode=TE,e===AE){u>>>=2,l-=2;break e}break;case 2:t.mode=xee;break;case 3:r.msg="invalid block type",t.mode=Kr}u>>>=2,l-=2;break;case Eee:for(u>>>=l&7,l-=l&7;l<32;){if(a===0)break e;a--,u+=n[o++]<>>16^65535)){r.msg="invalid stored block lengths",t.mode=Kr;break}if(t.length=u&65535,u=0,l=0,t.mode=Mk,e===AE)break e;case Mk:t.mode=vee;case vee:if(d=t.length,d){if(d>a&&(d=a),d>c&&(d=c),d===0)break e;i.set(n.subarray(o,o+d),s),a-=d,o+=d,c-=d,s+=d,t.length-=d;break}t.mode=dl;break;case xee:for(;l<14;){if(a===0)break e;a--,u+=n[o++]<>>=5,l-=5,t.ndist=(u&31)+1,u>>>=5,l-=5,t.ncode=(u&15)+4,u>>>=4,l-=4,t.nlen>286||t.ndist>30){r.msg="too many length or distance symbols",t.mode=Kr;break}t.have=0,t.mode=See;case See:for(;t.have>>=3,l-=3}for(;t.have<19;)t.lens[N[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,I={bits:t.lenbits},S=cw(bPe,t.lens,0,19,t.lencode,0,t.work,I),t.lenbits=I.bits,S){r.msg="invalid code lengths set",t.mode=Kr;break}t.have=0,t.mode=Aee;case Aee:for(;t.have>>24,x=w>>>16&255,m=w&65535,!(_<=l);){if(a===0)break e;a--,u+=n[o++]<>>=_,l-=_,t.lens[t.have++]=m;else{if(m===16){for(k=_+2;l>>=_,l-=_,t.have===0){r.msg="invalid bit length repeat",t.mode=Kr;break}v=t.lens[t.have-1],d=3+(u&3),u>>>=2,l-=2}else if(m===17){for(k=_+3;l>>=_,l-=_,v=0,d=3+(u&7),u>>>=3,l-=3}else{for(k=_+7;l>>=_,l-=_,v=0,d=11+(u&127),u>>>=7,l-=7}if(t.have+d>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=Kr;break}for(;d--;)t.lens[t.have++]=v}}if(t.mode===Kr)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=Kr;break}if(t.lenbits=9,I={bits:t.lenbits},S=cw(ote,t.lens,0,t.nlen,t.lencode,0,t.work,I),t.lenbits=I.bits,S){r.msg="invalid literal/lengths set",t.mode=Kr;break}if(t.distbits=6,t.distcode=t.distdyn,I={bits:t.distbits},S=cw(ste,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,I),t.distbits=I.bits,S){r.msg="invalid distances set",t.mode=Kr;break}if(t.mode=TE,e===AE)break e;case TE:t.mode=IE;case IE:if(a>=6&&c>=258){r.next_out=s,r.avail_out=c,r.next_in=o,r.avail_in=a,t.hold=u,t.bits=l,hPe(r,h),s=r.next_out,i=r.output,c=r.avail_out,o=r.next_in,n=r.input,a=r.avail_in,u=t.hold,l=t.bits,t.mode===dl&&(t.back=-1);break}for(t.back=0;w=t.lencode[u&(1<>>24,x=w>>>16&255,m=w&65535,!(_<=l);){if(a===0)break e;a--,u+=n[o++]<>y)],_=w>>>24,x=w>>>16&255,m=w&65535,!(y+_<=l);){if(a===0)break e;a--,u+=n[o++]<>>=y,l-=y,t.back+=y}if(u>>>=_,l-=_,t.back+=_,t.length=m,x===0){t.mode=Pee;break}if(x&32){t.back=-1,t.mode=dl;break}if(x&64){r.msg="invalid literal/length code",t.mode=Kr;break}t.extra=x&15,t.mode=Tee;case Tee:if(t.extra){for(k=t.extra;l>>=t.extra,l-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=Iee;case Iee:for(;w=t.distcode[u&(1<>>24,x=w>>>16&255,m=w&65535,!(_<=l);){if(a===0)break e;a--,u+=n[o++]<>y)],_=w>>>24,x=w>>>16&255,m=w&65535,!(y+_<=l);){if(a===0)break e;a--,u+=n[o++]<>>=y,l-=y,t.back+=y}if(u>>>=_,l-=_,t.back+=_,x&64){r.msg="invalid distance code",t.mode=Kr;break}t.offset=m,t.extra=x&15,t.mode=Ree;case Ree:if(t.extra){for(k=t.extra;l>>=t.extra,l-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){r.msg="invalid distance too far back",t.mode=Kr;break}t.mode=Cee;case Cee:if(c===0)break e;if(d=h-c,t.offset>d){if(d=t.offset-d,d>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=Kr;break}d>t.wnext?(d-=t.wnext,p=t.wsize-d):p=t.wnext-d,d>t.length&&(d=t.length),g=t.window}else g=i,p=s-t.offset,d=t.length;d>c&&(d=c),c-=d,t.length-=d;do i[s++]=g[p++];while(--d);t.length===0&&(t.mode=IE);break;case Pee:if(c===0)break e;i[s++]=t.length,c--,t.mode=IE;break;case Uk:if(t.wrap){for(;l<32;){if(a===0)break e;a--,u|=n[o++]<{if(dp(r))return js;let e=r.state;return e.window&&(e.window=null),r.state=null,lp},DPe=(r,e)=>{if(dp(r))return js;let t=r.state;return t.wrap&2?(t.head=e,e.done=!1,lp):js},OPe=(r,e)=>{let t=e.length,n,i,o;return dp(r)||(n=r.state,n.wrap!==0&&n.mode!==kE)?js:n.mode===kE&&(i=1,i=hw(i,e,t,0),i!==n.check)?ate:(o=mte(r,e,t,t),o?(n.mode=ute,cte):(n.havedict=1,lp))},LPe=dte,BPe=hte,MPe=fte,UPe=CPe,FPe=pte,zPe=kPe,VPe=NPe,KPe=DPe,$Pe=OPe,qPe="pako inflate (from Nodeca project)",pl={inflateReset:LPe,inflateReset2:BPe,inflateResetKeep:MPe,inflateInit:UPe,inflateInit2:FPe,inflate:zPe,inflateEnd:VPe,inflateGetHeader:KPe,inflateSetDictionary:$Pe,inflateInfo:qPe};function HPe(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var GPe=HPe,gte=Object.prototype.toString,{Z_NO_FLUSH:jPe,Z_FINISH:WPe,Z_OK:gw,Z_STREAM_END:Vk,Z_NEED_DICT:Kk,Z_STREAM_ERROR:YPe,Z_DATA_ERROR:Lee,Z_MEM_ERROR:QPe}=fp;function _w(r){this.options=DE.assign({chunkSize:1024*64,windowBits:15,to:""},r||{});let e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(r&&r.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nte,this.strm.avail_out=0;let t=pl.inflateInit2(this.strm,e.windowBits);if(t!==gw)throw new Error(cp[t]);if(this.header=new GPe,pl.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=mw.string2buf(e.dictionary):gte.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=pl.inflateSetDictionary(this.strm,e.dictionary),t!==gw)))throw new Error(cp[t])}_w.prototype.push=function(r,e){let t=this.strm,n=this.options.chunkSize,i=this.options.dictionary,o,s,a;if(this.ended)return!1;for(e===~~e?s=e:s=e===!0?WPe:jPe,gte.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),o=pl.inflate(t,s),o===Kk&&i&&(o=pl.inflateSetDictionary(t,i),o===gw?o=pl.inflate(t,s):o===Lee&&(o=Kk));t.avail_in>0&&o===Vk&&t.state.wrap>0&&r[t.next_in]!==0;)pl.inflateReset(t),o=pl.inflate(t,s);switch(o){case YPe:case Lee:case Kk:case QPe:return this.onEnd(o),this.ended=!0,!1}if(a=t.avail_out,t.next_out&&(t.avail_out===0||o===Vk))if(this.options.to==="string"){let c=mw.utf8border(t.output,t.next_out),u=t.next_out-c,l=mw.buf2string(t.output,c);t.next_out=u,t.avail_out=n-u,u&&t.output.set(t.output.subarray(c,c+u),0),this.onData(l)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(!(o===gw&&a===0)){if(o===Vk)return o=pl.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(t.avail_in===0)break}}return!0};_w.prototype.onData=function(r){this.chunks.push(r)};_w.prototype.onEnd=function(r){r===gw&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=DE.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};function iN(r,e){let t=new _w(e);if(t.push(r),t.err)throw t.msg||cp[t.err];return t.result}function XPe(r,e){return e=e||{},e.raw=!0,iN(r,e)}var ZPe=_w,JPe=iN,eke=XPe,tke=iN,rke=fp,nke={Inflate:ZPe,inflate:JPe,inflateRaw:eke,ungzip:tke,constants:rke},{Deflate:ike,deflate:oke,deflateRaw:ske,gzip:ake}=fPe,{Inflate:cke,inflate:uke,inflateRaw:lke,ungzip:fke}=nke,dke=ike,hke=oke,pke=ske,mke=ake,gke=cke,yke=uke,wke=lke,bke=fke,_ke=fp,oN={Deflate:dke,deflate:hke,deflateRaw:pke,gzip:mke,Inflate:gke,inflate:yke,inflateRaw:wke,ungzip:bke,constants:_ke};async function LE(r){let e=new Uint8Array(0);for await(let t of r)e=rt([e,t],e.length+t.length);return e}var yte=6;function wte({repo:r,preload:e}){async function*t(n,i={}){if(i.compressionLevel!=null&&(i.compressionLevel<-1||i.compressionLevel>9))throw(0,Um.default)(new Error("Compression level must be between -1 and 9"),"ERR_INVALID_PARAMS");if(i.preload!==!1){let a;try{a=N1(n).split("/")}catch(c){throw(0,Um.default)(c,"ERR_INVALID_PATH")}e(z.parse(a[0]))}let o=z.asCID(n)||n,s=await Ei(o,r.blocks,i);if(s.type==="file"||s.type==="raw"){let a=[];!i.compress||i.archive===!0?a.push([{header:{name:s.path,mode:s.type==="file"&&s.unixfs.mode,mtime:s.type==="file"&&s.unixfs.mtime?new Date(s.unixfs.mtime.secs*1e3):void 0,size:s.size,type:"file"},body:s.content()}],vE()):a.push(s.content),i.compress&&a.push(async function*(c){let u=await LE(c);yield oN.gzip(u,{level:i.compressionLevel||yte})}),yield*Ne(...a);return}if(s.type==="directory"){let a=[_E(o,r.blocks,i),async function*(c){for await(let u of c){let l={header:{name:u.path,size:u.size}};if(u.type==="file")l.header.type="file",l.header.mode=u.unixfs.mode!=null?u.unixfs.mode:void 0,l.header.mtime=u.unixfs.mtime?new Date(u.unixfs.mtime.secs*1e3):void 0,l.body=u.content();else if(u.type==="raw")l.header.type="file",l.body=u.content();else if(u.type==="directory")l.header.type="directory",l.header.mode=u.unixfs.mode!=null?u.unixfs.mode:void 0,l.header.mtime=u.unixfs.mtime?new Date(u.unixfs.mtime.secs*1e3):void 0;else throw(0,Um.default)(new Error("Not a UnixFS node"),"ERR_NOT_UNIXFS");yield l}},vE()];if(i.compress){if(!i.archive)throw(0,Um.default)(new Error("file is not regular"),"ERR_INVALID_PATH");i.compress&&a.push(async function*(c){let u=await LE(c);yield oN.gzip(u,{level:i.compressionLevel||yte})})}yield*Ne(...a);return}throw(0,Um.default)(new Error("Not a UnixFS node"),"ERR_NOT_UNIXFS")}return $(t)}var bte=C(ee(),1);function _te({repo:r,preload:e}){async function*t(n,i={}){let o=N1(n),s=o.split("/");i.preload!==!1&&e(z.parse(s[0]));let a=z.asCID(o)||o,c=await Ei(a,r.blocks,i);if(c.type==="file"){yield wR(c);return}if(c.type==="directory"){for await(let u of c.content())yield wR(u);return}throw(0,bte.default)(new Error(`Unknown UnixFS type ${c.type}`),"ERR_UNKNOWN_UNIXFS_TYPE")}return $(t)}var BE=class{constructor({preload:e,repo:t,hashers:n,options:i}){let o=oJ({preload:e,repo:t,options:i,hashers:n});this.addAll=o,this.add=hZ({addAll:o}),this.cat=HJ({repo:t,preload:e}),this.get=wte({repo:t,preload:e}),this.ls=_te({repo:t,preload:e})}};var hp="0.18.1",Ete="",vte="^0.158.1";function xte({repo:r}){async function e(t={}){let n=await r.version.get();return{version:hp,commit:Ete,repo:`${n}`,"ipfs-core":hp,"interface-ipfs-core":vte}}return $(e)}var ME=C(ee(),1);var Eke=j("ipfs:components:id");function Ste({peerId:r,network:e}){async function t(n={}){let i=e.try();if(!i){if(n.peerId)throw new $u;if(r.publicKey==null)throw(0,ME.default)(new Error("Public key missing"),"ERR_MISSING_PUBLIC_KEY");return{id:r,publicKey:re(r.publicKey,"base64pad"),addresses:[],agentVersion:`js-ipfs/${hp}`,protocolVersion:"9000",protocols:[]}}let{libp2p:o}=i,s=n.peerId?n.peerId:r,a=await vke(s,o,n),c=re(a.metadata.get("AgentVersion")||new Uint8Array),u=re(a.metadata.get("ProtocolVersion")||new Uint8Array),l=a.id.toString(),f=a.publicKey?re(a.publicKey,"base64pad"):"";return{id:s,publicKey:f,addresses:(a.addresses||[]).map(h=>{let d=h.toString();return d.endsWith(`/p2p/${l}`)?d:`${d}/p2p/${l}`}).sort().map(h=>yt(h)),agentVersion:c,protocolVersion:u,protocols:(a.protocols||[]).sort()}}return $(t)}async function vke(r,e,t){let n=await e.peerStore.get(r);n||(n=await xke(r,e,t));let i=r.publicKey?r.publicKey:await e.peerStore.keyBook.get(r);if(i==null)try{i=await e.getPublicKey(r,t)}catch(o){Eke.error("Could not load public key for",r.toString(),o)}return{...n,publicKey:i,metadata:n.metadata||new Map,addresses:n.addresses.map(o=>o.multiaddr)}}async function xke(r,e,t){if(e.dht==null)throw(0,ME.default)(new Error("dht not configured"),"ERR_DHT_NOT_CONFIGURED");for await(let i of e.dht.findPeer(r,t))if(i.name==="FINAL_PEER")break;let n=await e.peerStore.get(r);if(!n)throw(0,ME.default)(new Error("Could not find peer"),"ERR_NOT_FOUND");return n}var $r=Ske;function Ske(r,e,t){var n,i;if(Array.isArray(e)&&(n=e.slice(0)),typeof e=="string"&&(n=e.split(".")),typeof e=="symbol"&&(n=[e]),!Array.isArray(n))throw new Error("props arg must be an array, a string or a symbol");if(i=n.pop(),!i)return!1;Ate(i);for(var o;o=n.shift();)if(Ate(o),typeof r[o]>"u"&&(r[o]={}),r=r[o],!r||typeof r!="object")return!1;return r[i]=t,!0}function Ate(r){if(r=="__proto__"||r=="constructor"||r=="prototype")throw new Error("setting of prototype values not supported")}var Fm={server:{description:"Recommended for nodes with public IPv4 address (servers, VPSes, etc.), disables host and content discovery and UPnP in local networks.",transform:r=>($r(r,"Discovery.MDNS.Enabled",!1),$r(r,"Discovery.webRTCStar.Enabled",!1),r.Swarm={...r.Swarm||{},DisableNatPortMap:!0},r)},"local-discovery":{description:"Sets default values to fields affected by `server` profile, enables discovery and UPnP in local networks.",transform:r=>($r(r,"Discovery.MDNS.Enabled",!0),$r(r,"Discovery.webRTCStar.Enabled",!0),$r(r,"Swarm",{...r.Swarm||{},DisableNatPortMap:!1}),r)},test:{description:"Reduces external interference, useful for running ipfs in test environments. Note that with these settings node won't be able to talk to the rest of the network without manual bootstrap.",transform:r=>{let e=cl();return $r(r,"Addresses.API",e.Addresses.API?"/ip4/127.0.0.1/tcp/0":""),$r(r,"Addresses.Gateway",e.Addresses.Gateway?"/ip4/127.0.0.1/tcp/0":""),$r(r,"Addresses.Swarm",e.Addresses.Swarm.length?["/ip4/127.0.0.1/tcp/0"]:[]),$r(r,"Addresses.Delegates",[]),$r(r,"Bootstrap",[]),$r(r,"Discovery.MDNS.Enabled",!1),$r(r,"Discovery.webRTCStar.Enabled",!1),$r(r,"Swarm",{...r.Swarm||{},DisableNatPortMap:!0}),r}},"default-networking":{description:"Restores default network settings. Inverse profile of the `test` profile.",transform:r=>{let e=cl();return $r(r,"Addresses.API",e.Addresses.API),$r(r,"Addresses.Gateway",e.Addresses.Gateway),$r(r,"Addresses.Swarm",e.Addresses.Swarm),$r(r,"Addresses.Delegates",e.Addresses.Delegates),$r(r,"Bootstrap",e.Bootstrap),$r(r,"Discovery.MDNS.Enabled",e.Discovery.MDNS.Enabled),$r(r,"Discovery.webRTCStar.Enabled",e.Discovery.webRTCStar.Enabled),$r(r,"Swarm",{...r.Swarm||{},DisableNatPortMap:!1}),r}},lowpower:{description:"Reduces daemon overhead on the system. May affect node functionality,performance of content discovery and data fetching may be degraded. Recommended for low power systems.",transform:r=>{let e=r.Swarm||{},t=e.ConnMgr||{};return t.LowWater=20,t.HighWater=40,e.ConnMgr=t,r.Swarm=e,r}},"default-power":{description:'Inverse of "lowpower" profile.',transform:r=>{let e=cl();return r.Swarm=e.Swarm,r}}};var Ake=j("ipfs:core:config");function Tte({repo:r}){return{getAll:$(e),get:$(t),set:$(n),replace:$(i),profiles:{apply:$(o),list:$(Tke)}};async function e(s={}){return r.config.getAll(s)}async function t(s,a){return s?r.config.get(s,a):Promise.reject(new Error("key argument is required"))}async function n(s,a,c){return r.config.set(s,a,c)}async function i(s,a){return r.config.replace(s,a)}async function o(s,a={dryRun:!1}){let{dryRun:c}=a,u=Fm[s];if(!u)throw new Error(`No profile with name '${s}' exists`);try{let l=await r.config.getAll(a),f=JSON.parse(JSON.stringify(l));return f=u.transform(f),c||await r.config.replace(f,a),delete l.Identity.PrivKey,delete f.Identity.PrivKey,{original:l,updated:f}}catch(l){throw Ake(l),new Error(`Could not apply profile '${s}' to config: ${l.message}`)}}}async function Tke(r){return Object.keys(Fm).map(e=>({name:e,description:Fm[e].description}))}function UE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Ike(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=z.asCID(n);o?yield[i.join("/"),o]:typeof n=="object"&&(yield*sN(n,i))}else{let t=z.asCID(e);t?yield[r.join("/"),t]:yield*sN(e,r)}}function*sN(r,e){if(r==null||r instanceof Uint8Array)return;let t=z.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*Ike(o,i)}}function*Rke(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!z.asCID(n)&&(yield*aN(n,i))}else yield*aN(e,r)}function*aN(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!z.asCID(n)&&(yield*Rke(i,n))}}function Cke(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=z.asCID(t);if(o)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var cN=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:UE(),bytes:UE(),value:UE(),asBlock:UE()})}links(){return sN(this.value,[])}tree(){return aN(this.value,[])}get(e="/"){return Cke(this.value,e.split("/").filter(Boolean))}};function Ite({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n&&n.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new cN({cid:e,bytes:r,value:i})}var fd=C(Xo(),1),FE={SHA2_256:18,LENGTH:32,DAG_PB:112},Rte=16+8+8+8;function Ew(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=fd.default.decode(r);return e.seek(fd.default.decode.bytes),t}function Cte(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}function Pte(r){fd.default.decode(r);let e=fd.default.decode.bytes,t=fd.default.decode(r.subarray(fd.default.decode.bytes)),n=fd.default.decode.bytes;return e+n+t}var dd={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},vw={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":dd.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(dd.List(r)!==void 0){for(let e=0;e roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:dd.Int,CarV1HeaderOrV2Pragma:r=>{if(dd.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i roots (anon)"](r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c0))return t}},xw={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":dd.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(dd.List(r)!==void 0){for(let e=0;e roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:dd.Int,CarV1HeaderOrV2Pragma:r=>{if(dd.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c0))return t}},kte={toTyped:vw.CarV1HeaderOrV2Pragma,toRepresentation:xw.CarV1HeaderOrV2Pragma};async function zE(r,e){let t=Ew(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),i=dT(n);if(kte.toTyped(i)===void 0)throw new Error("Invalid CAR header format");if(i.version!==1&&i.version!==2||e!==void 0&&i.version!==e)throw new Error(`Invalid CAR version: ${i.version}${e!==void 0?` (expected ${e})`:""}`);if(i.version===1){if(!Array.isArray(i.roots))throw new Error("Invalid CAR header format");return i}if(i.roots!==void 0)throw new Error("Invalid CAR header format");let o=Cte(await r.exactly(Rte,!0));r.seek(o.dataOffset-r.pos);let s=await zE(r,1);return Object.assign(s,o)}async function Pke(r){let e=await r.exactly(2,!1);if(e[0]===FE.SHA2_256&&e[1]===FE.LENGTH){let s=await r.exactly(34,!0),a=uf(s);return Xe.create(0,FE.DAG_PB,a)}let t=Ew(await r.upTo(8),r);if(t!==1)throw new Error(`Unexpected CID version (${t})`);let n=Ew(await r.upTo(8),r),i=await r.exactly(Pte(await r.upTo(8)),!0),o=uf(i);return Xe.create(t,n,o)}async function Nte(r){let e=r.pos,t=Ew(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR section (zero length)");t+=r.pos-e;let n=await Pke(r),i=t-Number(r.pos-e);return{cid:n,length:t,blockLength:i}}async function kke(r){let{cid:e,blockLength:t}=await Nte(r);return{bytes:await r.exactly(t,!0),cid:e}}async function Nke(r){let e=r.pos,{cid:t,length:n,blockLength:i}=await Nte(r),o={cid:t,length:n,blockLength:i,offset:e,blockOffset:r.pos};return r.seek(o.blockLength),o}function Dte(r){let e=(async()=>{let t=await zE(r);if(t.version===2){let n=r.pos-t.dataOffset;r=Oke(r,t.dataSize-n)}return t})();return{header:()=>e,async*blocks(){for(await e;(await r.upTo(8)).length>0;)yield await kke(r)},async*blocksIndex(){for(await e;(await r.upTo(8)).length>0;)yield await Nke(r)}}}function VE(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let i=r.subarray(e,e+t);return n&&(e+=t),i},seek(t){e+=t},get pos(){return e}}}function Dke(r){let e=0,t=0,n=0,i=new Uint8Array(0),o=async s=>{t=i.length-n;let a=[i.subarray(n)];for(;tt&&a.push(u.subarray(-t)):a.push(u),t+=u.length}i=new Uint8Array(a.reduce((u,l)=>u+l.length,0));let c=0;for(let u of a)i.set(u,c),c+=u.length;n=0};return{async upTo(s){return i.length-ne&&(i=i.subarray(0,e-t)),i},async exactly(n,i=!1){let o=await r.exactly(n,i);if(o.length+t>e)throw new Error("Unexpected end of data");return i&&(t+=n),o},seek(n){t+=n,r.seek(n)},get pos(){return r.pos}}}var uN=C(Xo(),1),Lte=1;function lN(r){let e=fT({version:Lte,roots:r}),t=uN.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Bte(r){return{async setRoots(e){let t=lN(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(uN.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return Lte}}}function KE(){}function Mte(){let r=[],e=null,t=KE,n=!1,i=null,o=KE,s=()=>(e||(e=new Promise(u=>{t=()=>{e=null,t=KE,u()}})),e),a={write(u){r.push(u);let l=s();return o(),l},async end(){n=!0;let u=s();o(),await u}},c={async next(){let u=r.shift();return u?(r.length===0&&t(),{done:!1,value:u}):n?(t(),{done:!0,value:void 0}):(i||(i=new Promise(l=>{o=()=>(i=null,o=KE,l(c.next()))})),i)}};return{writer:a,iterator:c}}var pp=class{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=Xe.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=Lke(e);let{encoder:t,iterator:n}=Ute(),i=new pp(e,t),o=new $E(n);return{writer:i,out:o}}static createAppender(){let{encoder:e,iterator:t}=Ute();e.setRoots=()=>Promise.resolve();let n=new pp([],e),i=new $E(t);return{writer:n,out:i}}static async updateRootsInBytes(e,t){let n=VE(e);await zE(n);let i=lN(t);if(Number(n.pos)!==i.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${i.length} bytes)`);return e.set(i,0),e}},$E=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function Ute(){let r=Mte(),{writer:e,iterator:t}=r;return{encoder:Bte(e),iterator:t}}function Lke(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=Xe.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=Xe.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var fN=async({cid:r,load:e,seen:t})=>{t=t||new Set;let n=r.toString(pr);if(t.has(n))return;let i=await e(r);if(t.add(n),i!==null)for(let[,o]of i.links())await fN({cid:o,load:e,seen:t})};var Fte=j("ipfs:components:dag:import"),Bke=[gf,zg];function zte({repo:r,preload:e,codecs:t}){async function*n(i,o={}){o.preload!==!1&&e(i);let s=z.asCID(i);if(!s)throw new Error(`Unexpected error converting CID type: ${i}`);Fte(`Exporting ${s} as car`);let{writer:a,out:c}=await pp.create([s]),u=null;(async()=>{try{let l=Mke(r,a,{signal:o.signal,timeout:o.timeout},t);await fN({cid:s,load:l})}catch(l){u=l}finally{a.close()}})();for await(let l of c){if(u)break;yield l}if(u)throw u}return $(n)}function Mke(r,e,t,n){return async i=>{let o=await n.getCodec(i.code);if(!o)throw new Error(`Can't decode links in block with codec 0x${i.code.toString(16)} to form complete DAG`);let s=await r.blocks.get(i,t);return Fte(`Adding block ${i} to car`),await e.put({cid:i,bytes:s}),Bke.includes(i.code)?null:Ite({bytes:s,cid:i,codec:o})}}async function mp(r){for await(let e of r)return e}var Vte=C(ee(),1);function Kte({codecs:r,repo:e,preload:t}){return $(async function(o,s={}){if(s.preload!==!1&&t(o),s.path){let f=s.localResolve?await mp(kf(o,s.path,r,e,s)):await Dr(kf(o,s.path,r,e,s));if(!f)throw(0,Vte.default)(new Error("Not found"),"ERR_NOT_FOUND");return f}let a=await r.getCodec(o.code),c=await e.blocks.get(o,s);return{value:a.decode(c),remainderPath:""}})}var qE=class{constructor(e,t,n){this._version=e,this._roots=t,this._iterable=n,this._decoded=!1}get version(){return this._version}async getRoots(){return this._roots}},gp=class extends qE{[Symbol.asyncIterator](){if(this._decoded)throw new Error("Cannot decode more than once");if(!this._iterable)throw new Error("Block iterable not found");return this._decoded=!0,this._iterable[Symbol.asyncIterator]()}static async fromBytes(e){let{version:t,roots:n,iterator:i}=await $te(e);return new gp(t,n,i)}static async fromIterable(e){let{version:t,roots:n,iterator:i}=await qte(e);return new gp(t,n,i)}},Sw=class extends qE{[Symbol.asyncIterator](){if(this._decoded)throw new Error("Cannot decode more than once");if(!this._iterable)throw new Error("Block iterable not found");this._decoded=!0;let e=this._iterable[Symbol.asyncIterator]();return{async next(){let t=await e.next();return t.done?t:{done:!1,value:t.value.cid}}}}static async fromBytes(e){let{version:t,roots:n,iterator:i}=await $te(e);return new Sw(t,n,i)}static async fromIterable(e){let{version:t,roots:n,iterator:i}=await qte(e);return new Sw(t,n,i)}};async function $te(r){if(!(r instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return Hte(VE(r))}async function qte(r){if(!r||typeof r[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return Hte(Ote(r))}async function Hte(r){let e=Dte(r),{version:t,roots:n}=await e.header();return{version:t,roots:n,iterator:e.blocks()}}var Gte=j("ipfs:components:dag:import");function jte({repo:r}){async function*e(t,n={}){let i=await r.gcLock.readLock();try{let o={signal:n.signal,timeout:n.timeout},s=ja(t),{value:a,done:c}=await s.peek();if(c)return;a&&s.push(a);let u;a instanceof Uint8Array?u=[s]:u=s;for await(let l of u){let f=await Uke(r,o,l);if(n.pinRoots!==!1)for(let h of f){let d="";try{await r.blocks.has(h)?(Gte(`Pinning root ${h}`),await r.pins.pinRecursively(h)):d="blockstore: block not found"}catch(p){d=p.message}yield{root:{cid:h,pinErrorMsg:d}}}}}finally{i()}}return $(e)}async function Uke(r,e,t){let n=await gp.fromIterable(t),i=await n.getRoots();return await sl(r.blocks.putMany(Mi(n,({cid:o,bytes:s})=>(Gte(`Import block ${o}`),{key:o,value:s})),{signal:e.signal})),i}function Wte({repo:r,codecs:e,hashers:t,preload:n}){async function i(o,s={}){let a=s.pin?await r.gcLock.readLock():null;try{let c=await e.getCodec(s.storeCodec||"dag-cbor");if(!c)throw new Error(`Unknown storeCodec ${s.storeCodec}, please configure additional BlockCodecs for this IPFS instance`);if(s.inputCodec){if(!(o instanceof Uint8Array))throw new Error("Can only inputCodec on raw bytes that can be decoded");let p=await e.getCodec(s.inputCodec);if(!p)throw new Error(`Unknown inputCodec ${s.inputCodec}, please configure additional BlockCodecs for this IPFS instance`);o=p.decode(o)}let u=s.version!=null?s.version:1,l=await t.getHasher(s.hashAlg||"sha2-256");if(!l)throw new Error(`Unknown hash algorithm ${s.hashAlg}, please configure additional MultihashHashers for this IPFS instance`);let f=c.encode(o),h=await l.digest(f),d=z.create(u,c.code,h);return await r.blocks.put(d,f,{signal:s.signal}),s.pin&&await r.pins.pinRecursively(d),s.preload!==!1&&n(d),d}finally{a&&a()}}return $(i)}function Yte({repo:r,codecs:e,preload:t}){async function n(i,o={}){let{cid:s}=Qu(i);return o.preload!==!1&&t(s),Pf(r,e,i,o)}return $(n)}var HE=class{constructor({repo:e,codecs:t,hashers:n,preload:i}){this.export=zte({repo:e,preload:i,codecs:t}),this.get=Kte({codecs:t,repo:e,preload:i}),this.import=jte({repo:e}),this.resolve=Yte({repo:e,codecs:t,preload:i}),this.put=Wte({repo:e,codecs:t,hashers:n,preload:i})}};function Qte(r){let e;try{e=Lt("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Xte(r){return r.some(([e,t])=>e===Lt("tls").code)}function is(r,e,t){let n=Zte[Lt(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${Lt(r).name}`);let i=n(e,t);return r===Lt("ip6").code?`[${i}]`:i}var Zte={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${is(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${is(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Xte(e),n=Qte(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",o=e.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=is(o[0],o[1]??"",e);return s=s.replace("tcp://",""),`${i}${s}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return is(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return is(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=is(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Xte(e),n=Qte(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",o=e.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=is(o[0],o[1]??"",e);return s=s.replace("tcp://",""),`${i}${s}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=is(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function zm(r,e){let n=Xi(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Lt(i[0]),s=Zte[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let a=s(i[1]??"",n);return(e==null?void 0:e.assumeHttp)!==!1&&i[0]===Lt("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}function dN(r){if(!Array.isArray(r))throw new TypeError(`Expected an array, got ${typeof r}`);r=[...r];for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}var Jte=C(O1(),1);var Fke=j("ipfs:preload"),zke=qn.default?qn.default:qn,Vke=new zke({concurrency:4});function ere(r,e={}){return Fke(r),Vke.add(async()=>{let n=(await Jte.default.post(r,{signal:e.signal})).body.getReader();try{for(;;){let{done:i}=await n.read();if(i)return}}finally{n.releaseLock()}})}var tre=C(Cy(),1),Aw=j("ipfs:preload");function rre(r={}){if(r.enabled=!!r.enabled,r.addresses=r.addresses||[],r.cache=r.cache||1e3,!r.enabled||!r.addresses.length)return Aw("preload disabled"),Object.assign(()=>{},{start:()=>{},stop:()=>{}});let e=!0,t=[],n=r.addresses.map(s=>zm(s)),i=(0,tre.default)(r.cache),o=async s=>{try{if(e)throw new Error(`preload ${s} but preloader is not started`);let a=s.toString();if(i.has(a))return;i.set(a,!0);let c=dN(n),u=!1,l=Date.now();for(let f of c){if(e)throw new Error(`preload aborted for ${a}`);let h;try{h=new AbortController,t=t.concat(h),await ere(`${f}/api/v0/refs?r=true&arg=${encodeURIComponent(a)}`,{signal:h.signal}),u=!0}catch(d){d.type!=="aborted"&&Aw.error(d)}finally{t=t.filter(d=>d!==h)}if(u)break}Aw(`${u?"":"un"}successfully preloaded ${a} in ${Date.now()-l}ms`)}catch(a){Aw.error(a)}};return o.start=()=>{e=!1},o.stop=()=>{e=!0,Aw(`aborting ${t.length} pending preload request(s)`),t.forEach(s=>s.abort()),t=[]},o}var GE=j("ipfs:mfs-preload");function nre({preload:r,files:e,options:t={}}){if(t.interval=t.interval||30*1e3,!t.enabled){GE("MFS preload disabled");let s=async()=>{};return{start:s,stop:s}}let n="",i,o=async()=>{try{let s=await e.stat("/"),a=s.cid.toString();n!==a&&(GE(`preloading updated MFS root ${n} -> ${s.cid}`),await r(s.cid),n=a)}catch(s){GE.error("failed to preload MFS root",s)}finally{i=setTimeout(o,t.interval)}};return{async start(){let s=await e.stat("/");n=s.cid.toString(),GE(`monitoring MFS root ${s.cid}`),i=setTimeout(o,t.interval)},stop(){clearTimeout(i)}}}var Tw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},hN=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ire=r=>globalThis.DOMException===void 0?new hN(r):new DOMException(r),ore=r=>{let e=r.reason===void 0?ire("This operation was aborted."):r.reason;return e instanceof Error?e:ire(e)};function yp(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(ore(h)),h.addEventListener("abort",()=>{l(ore(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new Tw;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}function pN(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Wc,Iw=class{constructor(){bt(this,Wc,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&ge(this,Wc)[this.size-1].priority>=t.priority){ge(this,Wc).push(n);return}let i=pN(ge(this,Wc),n,(o,s)=>s.priority-o.priority);ge(this,Wc).splice(i,0,n)}dequeue(){let e=ge(this,Wc).shift();return e==null?void 0:e.run}filter(e){return ge(this,Wc).filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return ge(this,Wc).length}};Wc=new WeakMap;var Vm,Km,hd,Rw,$m,Cw,Ws,qm,bo,Pw,Ys,Hm,ml,kw,QE,sre,XE,are,ZE,cre,JE,ure,e7,lre,Gm,jE,Nw,mN,Dw,gN,jm,WE,t7,fre,Wm,YE,Ym=class extends ky.default{constructor(t){var n,i;super();bt(this,QE);bt(this,XE);bt(this,ZE);bt(this,JE);bt(this,e7);bt(this,Gm);bt(this,Nw);bt(this,Dw);bt(this,jm);bt(this,t7);bt(this,Wm);bt(this,Vm,void 0);bt(this,Km,void 0);bt(this,hd,0);bt(this,Rw,void 0);bt(this,$m,void 0);bt(this,Cw,0);bt(this,Ws,void 0);bt(this,qm,void 0);bt(this,bo,void 0);bt(this,Pw,void 0);bt(this,Ys,0);bt(this,Hm,void 0);bt(this,ml,void 0);bt(this,kw,void 0);B(this,"timeout");if(t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Iw,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${((n=t.intervalCap)==null?void 0:n.toString())??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${((i=t.interval)==null?void 0:i.toString())??""}\` (${typeof t.interval})`);Dt(this,Vm,t.carryoverConcurrencyCount),Dt(this,Km,t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0),Dt(this,Rw,t.intervalCap),Dt(this,$m,t.interval),Dt(this,bo,new t.queueClass),Dt(this,Pw,t.queueClass),this.concurrency=t.concurrency,this.timeout=t.timeout,Dt(this,kw,t.throwOnTimeout===!0),Dt(this,ml,t.autoStart===!1)}get concurrency(){return ge(this,Hm)}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);Dt(this,Hm,t),hi(this,jm,WE).call(this)}async add(t,n={}){return n={timeout:this.timeout,throwOnTimeout:ge(this,kw),...n},new Promise((i,o)=>{ge(this,bo).enqueue(async()=>{var s;uh(this,Ys)._++,uh(this,hd)._++;try{(s=n.signal)==null||s.throwIfAborted();let a=t({signal:n.signal});n.timeout&&(a=yp(Promise.resolve(a),{milliseconds:n.timeout})),n.signal&&(a=Promise.race([a,hi(this,t7,fre).call(this,n.signal)]));let c=await a;i(c),this.emit("completed",c)}catch(a){if(a instanceof Tw&&!n.throwOnTimeout){i();return}o(a),this.emit("error",a)}finally{hi(this,ZE,cre).call(this)}},n),this.emit("add"),hi(this,Gm,jE).call(this)})}async addAll(t,n){return Promise.all(t.map(async i=>this.add(i,n)))}start(){return ge(this,ml)?(Dt(this,ml,!1),hi(this,jm,WE).call(this),this):this}pause(){Dt(this,ml,!0)}clear(){Dt(this,bo,new(ge(this,Pw)))}async onEmpty(){ge(this,bo).size!==0&&await hi(this,Wm,YE).call(this,"empty")}async onSizeLessThan(t){ge(this,bo).sizege(this,bo).size{hi(this,JE,ure).call(this)},n)),!0}return!1},Gm=new WeakSet,jE=function(){if(ge(this,bo).size===0)return ge(this,Ws)&&clearInterval(ge(this,Ws)),Dt(this,Ws,void 0),this.emit("empty"),ge(this,Ys)===0&&this.emit("idle"),!1;if(!ge(this,ml)){let t=!ge(this,e7,lre);if(ge(this,QE,sre)&&ge(this,XE,are)){let n=ge(this,bo).dequeue();return n?(this.emit("active"),n(),t&&hi(this,Nw,mN).call(this),!0):!1}}return!1},Nw=new WeakSet,mN=function(){ge(this,Km)||ge(this,Ws)!==void 0||(Dt(this,Ws,setInterval(()=>{hi(this,Dw,gN).call(this)},ge(this,$m))),Dt(this,Cw,Date.now()+ge(this,$m)))},Dw=new WeakSet,gN=function(){ge(this,hd)===0&&ge(this,Ys)===0&&ge(this,Ws)&&(clearInterval(ge(this,Ws)),Dt(this,Ws,void 0)),Dt(this,hd,ge(this,Vm)?ge(this,Ys):0),hi(this,jm,WE).call(this)},jm=new WeakSet,WE=function(){for(;hi(this,Gm,jE).call(this););},t7=new WeakSet,fre=async function(t){return new Promise((n,i)=>{t.addEventListener("abort",()=>{i(t.reason)},{once:!0})})},Wm=new WeakSet,YE=async function(t,n){return new Promise(i=>{let o=()=>{n&&!n()||(this.off(t,o),i())};this.on(t,o)})};var pd={},Qm=r=>{r.addEventListener("message",e=>{Qm.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Qm.dispatchEvent("message",r,e)})};Qm.addEventListener=(r,e)=>{pd[r]==null&&(pd[r]=[]),pd[r].push(e)};Qm.removeEventListener=(r,e)=>{pd[r]!=null&&(pd[r]=pd[r].filter(t=>t===e))};Qm.dispatchEvent=function(r,e,t){pd[r]!=null&&pd[r].forEach(n=>n(e,t))};var Xm=Qm;var yN="lock:worker:request-read",wN="lock:worker:release-read",bN="lock:master:grant-read",_N="lock:worker:request-write",EN="lock:worker:release-write",vN="lock:master:grant-write";var dre=(r=21)=>Math.random().toString().substring(2);var hre=(r,e,t,n,i)=>(o,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)})}}}))},pre=(r,e,t,n)=>async()=>{let i=dre();return globalThis.postMessage({type:e,identifier:i,name:r}),new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",s)})},Kke={singleProcess:!1},mre=r=>{if(r=Object.assign({},Kke,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Xm.addEventListener("message",hre(t,"requestReadLock",yN,wN,bN)),Xm.addEventListener("message",hre(t,"requestWriteLock",_N,EN,vN)),t}return{isWorker:!0,readLock:t=>pre(t,yN,bN,wN),writeLock:t=>pre(t,_N,vN,EN)}};var wp={},gd;async function xN(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>yp((async()=>{await new Promise(i=>{t(()=>{i()})})})(),{milliseconds:e.timeout})),n}var $ke=(r,e)=>{if(gd.isWorker===!0)return{readLock:gd.readLock(r,e),writeLock:gd.writeLock(r,e)};let t=new Ym({concurrency:1}),n;return{async readLock(){if(n!=null)return xN(n,e);n=new Ym({concurrency:e.concurrency,autoStart:!1});let i=n,o=xN(n,e);return t.add(async()=>{i.start(),await i.onIdle().then(()=>{n===i&&(n=null)})}),o},async writeLock(){return n=null,xN(t,e)}}},qke={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function SN(r){let e=Object.assign({},qke,r);return gd==null&&(gd=mre(e),gd.isWorker!==!0&&(gd.addEventListener("requestReadLock",t=>{wp[t.data.name]!=null&&wp[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),gd.addEventListener("requestWriteLock",async t=>{wp[t.data.name]!=null&&wp[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),wp[e.name]==null&&(wp[e.name]=$ke(e.name,e)),wp[e.name]}var r7;function Ow(r=!1){if(r7)return r7;let e=SN({singleProcess:r});return r7={readLock:t=>async(...n)=>{let i=await e.readLock();try{return await t.apply(null,n)}finally{i()}},writeLock:t=>async(...n)=>{let i=await e.writeLock();try{return await t.apply(null,n)}finally{i()}}},r7}var AN=C(ee(),1);var gre=j("ipfs:mfs:utils:with-mfs-root");async function Zm(r,e){if(e&&e.signal&&e.signal.aborted)throw(0,AN.default)(new Error("Request aborted"),"ERR_ABORTED",{name:"Aborted"});await r.repo.datastore.open();let t;try{let n=await r.repo.datastore.get(Ry);t=z.decode(n)}catch(n){if(n.code!=="ERR_NOT_FOUND")throw n;gre("Creating new MFS root");let i=pt({Data:new st({type:"directory"}).marshal(),Links:[]}),o=await dt.digest(i);if(t=z.createV0(o),await r.repo.blocks.put(t,i),e&&e.signal&&e.signal.aborted)throw(0,AN.default)(new Error("Request aborted"),"ERR_ABORTED",{name:"Aborted"});await r.repo.datastore.put(Ry,t.bytes)}return gre(`Loaded MFS root /ipfs/${t}`),t}function Jm(r=""){return(r.trim().match(/([^\\^/]|\\\/)+/g)||[]).filter(Boolean)}var IN=C(ee(),1);var TN="ipfs",sn=async(r,e,t)=>{let n=await Zm(r,t),i={entryType:"file"},o="";if(z.asCID(e)?o=`/ipfs/${e}`:o=e.toString(),o=o.trim(),o=o.replace(/(\/\/+)/g,"/"),o.endsWith("/")&&o.length>1&&(o=o.substring(0,o.length-1)),!o)throw(0,IN.default)(new Error("paths must not be empty"),"ERR_NO_PATH");if(o.substring(0,1)!=="/")throw(0,IN.default)(new Error("paths must start with a leading slash"),"ERR_INVALID_PATH");o.substring(o.length-1)==="/"&&(o=o.substring(0,o.length-1));let s=Jm(o);if(s[0]===TN){let c;s.length===2?c=`/${s.join("/")}`:c=`/${s.slice(0,s.length-1).join("/")}`,i={type:"ipfs",depth:s.length-2,entryType:"file",mfsPath:`/${s.join("/")}`,mfsDirectory:c,parts:s,path:`/${s.join("/")}`,name:s[s.length-1]}}else{let c=`/${TN}/${n}${s.length?"/"+s.join("/"):""}`,u=`/${TN}/${n}/${s.slice(0,s.length-1).join("/")}`;i={type:"mfs",depth:s.length,entryType:"file",mfsDirectory:u,mfsPath:c,parts:s,path:`/${s.join("/")}`,name:s[s.length-1]}}let a=i.type==="mfs"?i.mfsPath:i.path;try{let c=await Ei(a,r.repo.blocks,t);i.cid=c.cid,i.mfsPath=`/ipfs/${c.path}`,i.entryType=c.type,i.content=c.content,(i.entryType==="file"||i.entryType==="directory")&&(c.type==="file"||c.type==="directory")&&(i.unixfs=c.unixfs)}catch(c){if(c.code!=="ERR_NOT_FOUND")throw c}return i.exists=!!i.cid,i};var wre=C(ee(),1);var Hke=et.bind({ignoreUndefined:!0}),Gke=j("ipfs:mfs:stat"),jke={withLocal:!1};function yd(r){async function e(t,n={}){n=Hke(jke,n),Gke(`Fetching stats for ${t}`);let{type:i,cid:o,mfsPath:s}=await sn(r,t,n),a=i==="ipfs"&&o?o:s,c;try{c=await Ei(a,r.repo.blocks)}catch(u){throw u.code==="ERR_NOT_FOUND"?(0,wre.default)(new Error(`${t} does not exist`),"ERR_NOT_FOUND"):u}if(!yre[c.type])throw new Error(`Cannot stat codec ${c.cid.code}`);return yre[c.type](c)}return $(e)}var yre={raw:r=>({cid:r.cid,size:r.node.length,cumulativeSize:r.node.length,blocks:0,type:"file",local:void 0,sizeLocal:void 0,withLocality:!1}),file:r=>{let e={cid:r.cid,type:"file",size:r.unixfs.fileSize(),cumulativeSize:pt(r.node).length+(r.node.Links||[]).reduce((t,n)=>t+(n.Tsize||0),0),blocks:r.unixfs.blockSizes.length,local:void 0,sizeLocal:void 0,withLocality:!1,mode:r.unixfs.mode};return r.unixfs.mtime&&(e.mtime=r.unixfs.mtime),e},directory:r=>{let e={cid:r.cid,type:"directory",size:0,cumulativeSize:pt(r.node).length+(r.node.Links||[]).reduce((t,n)=>t+(n.Tsize||0),0),blocks:r.node.Links.length,local:void 0,sizeLocal:void 0,withLocality:!1,mode:r.unixfs.mode};return r.unixfs.mtime&&(e.mtime=r.unixfs.mtime),e},object:r=>({cid:r.cid,size:r.node.length,cumulativeSize:r.node.length,type:"file",blocks:0,local:void 0,sizeLocal:void 0,withLocality:!1}),identity:r=>({cid:r.cid,size:r.node.length,cumulativeSize:r.node.length,blocks:0,type:"file",local:void 0,sizeLocal:void 0,withLocality:!1})};var i2=C(ee(),1);var Wke=j("ipfs:mfs:utils:to-trail");async function Yc(r,e){Wke(`Creating trail for path ${e}`);let t=[];for await(let n of Ak(e,r.repo.blocks))t.push({name:n.name,cid:n.cid,size:n.size,type:n.type});return t}var n7=async(r,e,t)=>{t.codec||(t.codec=sr),t.hasher||(t.hasher=dt),t.cidVersion===void 0&&(t.cidVersion=1),t.codec===sr&&t.hasher!==dt&&(t.cidVersion=1);let n=await t.hasher.digest(r),i=z.create(t.cidVersion,t.codec.code,n);return t.onlyHash||await e.put(i,r,{signal:t.signal}),i};var i7=V3.code,o7=8;async function s7(r){return(await V3.encode(r)).subarray(0,8).reverse()}var RN=class{constructor(e,t){this.options=t||{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime,this.cid=void 0,this.size=void 0}async put(e,t){}get(e){return Promise.resolve(this)}async*eachChildSeries(){}async*flush(e){}},e2=class extends RN{constructor(e,t){super(e,t),this._bucket=Tm({hashFn:s7,bits:o7})}async put(e,t){await this._bucket.put(e,t)}get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}async*flush(e){yield*bre(this._bucket,e,this,this.options)}};async function*bre(r,e,t,n){let i=r._children,o=[],s=0;for(let d=0;d{if(!n.parent.Data)throw new Error("Could not update HAMT directory because parent had no data");let i=Uint8Array.from(t._children.bitField().reverse()),o=st.unmarshal(n.parent.Data),s=new st({type:"hamt-sharded-directory",data:i,fanout:t.tableSize(),hashType:i7,mode:o.mode,mtime:o.mtime}),a=await r.hashers.getHasher(n.hashAlg),c={Data:s.marshal(),Links:e.sort((h,d)=>(h.Name||"").localeCompare(d.Name||""))},u=pt(c),l=await a.digest(u),f=z.create(n.cidVersion,kr,l);return n.flush&&await r.repo.blocks.put(f,u),{node:c,cid:f,size:e.reduce((h,d)=>h+(d.Tsize||0),u.length)}},CN=async(r,e,t,n,i)=>{let o=new bn({hash:t._options.hash,bits:t._options.bits},n,i);return n._putObjectAt(i,o),await Bw(r,e,o,t),o},PN=async r=>{let e=Tm({hashFn:s7,bits:o7});return await Promise.all(r.map(async t=>{let n=t.Name||"";if(n.length===2){let i=parseInt(n,16),o=new bn({hash:e._options.hash,bits:e._options.bits},e,i);return e._putObjectAt(i,o),Promise.resolve()}return e.put(n.substring(2),{size:t.Tsize,cid:t.Hash})})),e},Bw=async(r,e,t,n)=>{await Promise.all(e.map(async i=>{let o=i.Name||"";if(o.length===2){Lw("Populating sub bucket",o);let s=parseInt(o,16),a=await r.repo.blocks.get(i.Hash),c=en(a),u=new bn({hash:n._options.hash,bits:n._options.bits},t,s);return t._putObjectAt(s,u),await Bw(r,c.Links,u,n),Promise.resolve()}return n.put(o.substring(2),{size:i.Tsize,cid:i.Hash})}))},bp=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),_re=async(r,e,t)=>{let n=await PN(t.Links),i=await n._findNewBucketAndPos(e),o=[{bucket:i.bucket,prefix:bp(i.pos)}],s=i.bucket;for(;s!==n;)o.push({bucket:s,prefix:bp(s._posAtParent)}),s=s._parent;o.reverse(),o[0].node=t;for(let a=0;a(d.Name||"").substring(0,2)===c.prefix).pop();if(!u){Lw(`Link ${c.prefix}${e} will be added`);continue}if(u.Name===`${c.prefix}${e}`){Lw(`Link ${c.prefix}${e} will be replaced`);continue}Lw(`Found subshard ${c.prefix}`);let l=await r.repo.blocks.get(u.Hash),f=en(l);if(!o[a+1]){Lw(`Loaded new subshard ${c.prefix}`),await CN(r,f.Links,n,c.bucket,parseInt(c.prefix,16));let d=await n._findNewBucketAndPos(e);o.push({bucket:d.bucket,prefix:bp(d.pos),node:f});continue}let h=o[a+1];await Bw(r,f.Links,h.bucket,n),h.node=f}return await n.put(e,!0),o.reverse(),{rootBucket:n,path:o}},Ere=async(r,e,t={})=>{let n=new e2({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let o=0;o=e.shardSplitThreshold?(Xc("Converting directory to sharded directory"),Yke(r,{...e,parent:t,mtime:n.mtime,mode:n.mode})):(Xc(`Adding ${e.name} (${e.cid}) to regular directory`),Qke(r,{...e,parent:t}))}var Yke=async(r,e)=>{let t=await Ere(r,e.parent.Links.map(n=>({name:n.Name||"",size:n.Tsize||0,cid:n.Hash})).concat({name:e.name,size:e.size,cid:e.cid}),e);return Xc(`Converted directory to sharded directory ${t.cid}`),t},Qke=async(r,e)=>{let t=e.parent.Links.filter(u=>u.Name!==e.name);if(t.push({Name:e.name,Tsize:e.size,Hash:e.cid}),!e.parent.Data)throw(0,Qc.default)(new Error("Parent node with no data passed to addToDirectory"),"ERR_INVALID_PARENT");let n=st.unmarshal(e.parent.Data),i;if(n.mtime){let u=Date.now(),l=Math.floor(u/1e3);n.mtime={secs:l,nsecs:(u-l*1e3)*1e3},i=n.marshal()}else i=e.parent.Data;e.parent=Xn({Data:i,Links:t});let o=await r.hashers.getHasher(e.hashAlg),s=pt(e.parent),a=await o.digest(s),c=z.create(e.cidVersion,kr,a);return e.flush&&await r.repo.blocks.put(c,s),{node:e.parent,cid:c,size:s.length}},Xke=async(r,e)=>{let{shard:t,path:n}=await Zke(r,e),i=await Dr(t.flush(r.repo.blocks));if(!i)throw new Error("No result from flushing shard");let o=await r.repo.blocks.get(i.cid),s=en(o),a=e.parent.Links.filter(u=>(u.Name||"").substring(0,2)!==n[0].prefix),c=s.Links.find(u=>(u.Name||"").substring(0,2)===n[0].prefix);if(!c)throw new Error(`No link found with prefix ${n[0].prefix}`);return a.push(c),t2(r,a,n[0].bucket,e)},Zke=async(r,e)=>{let t={name:e.name,cid:e.cid,size:e.size};if(!e.parent.Data)throw(0,Qc.default)(new Error("Parent node with no data passed to addFileToShardedDirectory"),"ERR_INVALID_PARENT");let n=await PN(e.parent.Links),i=st.unmarshal(e.parent.Data),o=new e2({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mode:i.mode},e);o._bucket=n,i.mtime&&(o.mtime={secs:Math.round(Date.now()/1e3)});let s=await n._findNewBucketAndPos(t.name),a=Jke(s);a[0].node=e.parent;let c=0;for(;c(g.Name||"").substring(0,2)===u.prefix);if(!f){Xc(`Link ${u.prefix}${t.name} will be added`),c=a.length;break}if(f.Name===`${u.prefix}${t.name}`){Xc(`Link ${u.prefix}${t.name} will be replaced`),c=a.length;break}if((f.Name||"").length>2){Xc(`Link ${f.Name} ${f.Hash} will be replaced with a subshard`),c=a.length;break}Xc(`Found subshard ${u.prefix}`);let h=await r.repo.blocks.get(f.Hash),d=en(h);if(!a[c]){Xc(`Loaded new subshard ${u.prefix}`),await CN(r,d.Links,n,u.bucket,parseInt(u.prefix,16));let g=await n._findNewBucketAndPos(t.name);a.push({bucket:g.bucket,prefix:bp(g.pos),node:d});break}let p=a[c];await Bw(r,d.Links,p.bucket,n),p.node=d}return await o._bucket.put(t.name,{size:t.size,cid:t.cid}),{shard:o,path:a}},Jke=r=>{let e=[{bucket:r.bucket,prefix:bp(r.pos)}],t=r.bucket._parent,n=r.bucket._posAtParent;for(;t;)e.push({bucket:t,prefix:bp(n)}),n=t._posAtParent,t=t._parent;return e.reverse(),e};var vre=j("ipfs:mfs:utils:update-tree"),eNe={shardSplitThreshold:1e3};async function os(r,e,t){t=Object.assign({},eNe,t),vre("Trail",e),e=e.slice().reverse();let n=0,i;for await(let s of r.repo.blocks.getMany(e.map(a=>a.cid))){let a=en(s),c=e[n].cid,u=e[n].name;if(n++,!i){i={cid:c,name:u,size:s.length};continue}let l=await Qs(r,{parent:a,name:i.name,cid:i.cid,size:i.size,flush:t.flush,shardSplitThreshold:t.shardSplitThreshold,hashAlg:t.hashAlg,cidVersion:t.cidVersion});i={cid:l.cid,name:u,size:l.size}}let{cid:o}=i;return vre(`Final CID ${o}`),o}var xre=C(ee(),1),tNe=j("ipfs:mfs:utils:update-mfs-root");async function ss(r,e,t){if(t&&t.signal&&t.signal.aborted)throw(0,xre.default)(new Error("Request aborted"),"ERR_ABORTED",{name:"Aborted"});return tNe(`New MFS root will be ${e}`),await r.repo.datastore.put(Ry,e.bytes),e}var _p=C(ee(),1);async function Sre(r,e,t){let n=new st({type:e,mode:t.mode,mtime:t.mtime}),i=await r.hashers.getHasher(t.hashAlg),o={Data:n.marshal(),Links:[]},s=pt(o),a=await i.digest(s),c=z.create(t.cidVersion,kr,a);return t.flush&&await r.repo.blocks.put(c,s),{cid:c,node:o}}var rNe=et.bind({ignoreUndefined:!0}),Are=j("ipfs:mfs:mkdir"),nNe={parents:!1,hashAlg:"sha2-256",cidVersion:0,shardSplitThreshold:1e3,flush:!0};function Ep(r){async function e(t,n={}){let i=rNe(nNe,n);if(!t)throw new Error("no path given to Mkdir");if(t=t.trim(),t==="/"){if(i.parents)return;throw(0,_p.default)(new Error("cannot create directory '/': Already exists"),"ERR_INVALID_PATH")}if(t.substring(0,1)!=="/")throw(0,_p.default)(new Error("paths must start with a leading slash"),"ERR_INVALID_PATH");Are(`Creating ${t}`);let o=Jm(t);if(o[0]==="ipfs")throw(0,_p.default)(new Error("path cannot have the prefix 'ipfs'"),"ERR_INVALID_PATH");let s=await Zm(r,i),a,c=[],u=await Sre(r,"directory",i);for(let f=0;f<=o.length;f++){let h=o.slice(0,f),d=`/ipfs/${s}/${h.join("/")}`;try{if(a=await Ei(d,r.repo.blocks),a.type!=="file"&&a.type!=="directory")throw(0,_p.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");if(f===o.length){if(i.parents)return;throw(0,_p.default)(new Error("file already exists"),"ERR_ALREADY_EXISTS")}c.push({name:a.name,cid:a.cid})}catch(p){if(p.code==="ERR_NOT_FOUND"){if(f{Are(`Adding empty dir called ${e} to ${n.cid}`);let s=await Qs(r,{parent:n.node,parentCid:n.cid,size:0,cid:t.cid,name:e,hashAlg:o.hashAlg,cidVersion:o.cidVersion,flush:o.flush,shardSplitThreshold:o.shardSplitThreshold});i[i.length-1].cid=s.cid,i.push({name:e,cid:t.cid})};var wd=C(ee(),1);var oNe=et.bind({ignoreUndefined:!0}),a7=j("ipfs:mfs:cp"),sNe={parents:!1,flush:!0,hashAlg:"sha2-256",cidVersion:0,shardSplitThreshold:1e3};function r2(r){async function e(t,n,i={}){let o=oNe(sNe,i);Array.isArray(t)||(t=[t]);let s=await Promise.all(t.map(h=>sn(r,h,o))),a=await sn(r,n,o);if(!s.length||!a)throw(0,wd.default)(new Error("Please supply at least one source"),"ERR_INVALID_PARAMS");let c=s.find(h=>!h.exists);if(c)throw(0,wd.default)(new Error(`${c.path} does not exist`),"ERR_INVALID_PARAMS");let u=Tre(a);if(a.exists){if(a7("Destination exists"),s.length===1&&!u)throw(0,wd.default)(new Error("directory already has entry by that name"),"ERR_ALREADY_EXISTS")}else if(a7("Destination does not exist"),s.length>1){if(!o.parents)throw(0,wd.default)(new Error("destination did not exist, pass -p to create intermediate directories"),"ERR_INVALID_PARAMS");await Ep(r)(a.path,o),a=await sn(r,a.path,o)}else if(a.parts.length>1){let h=`/${a.parts.slice(0,-1).join("/")}`;try{await yd(r)(h,o)}catch(d){if(d.code!=="ERR_NOT_FOUND")throw d;if(!o.parents)throw(0,wd.default)(new Error("destination did not exist, pass -p to create intermediate directories"),"ERR_INVALID_PARAMS");await Ep(r)(h,o),a=await sn(r,a.path,o)}}let l=Tre(a)?a.mfsPath:a.mfsDirectory,f=await Yc(r,l);if(s.length===1){let h=s.pop();if(!h)throw(0,wd.default)(new Error("could not find source"),"ERR_INVALID_PARAMS");let d=u?h.name:a.name;return a7(`Only one source, copying to destination ${u?"directory":"file"} ${d}`),aNe(r,h,d,f,o)}return a7("Multiple sources, wrapping in a directory"),cNe(r,s,a,f,o)}return $(e)}var Tre=r=>r.unixfs&&r.unixfs.type&&r.unixfs.type.includes("directory"),aNe=async(r,e,t,n,i)=>{let o=n.pop();if(!o)throw(0,wd.default)(new Error("destination had no parent"),"ERR_INVALID_PARAMS");o=await Ire(r,e,t,o,i),n.push(o);let s=await os(r,n,i);await ss(r,s,i)},cNe=async(r,e,t,n,i)=>{for(let s=0;s{let o=await r.repo.blocks.get(e.cid),{node:s,cid:a,size:c}=await Qs(r,{parentCid:n.cid,size:o.length,cid:e.cid,name:t,hashAlg:i.hashAlg,cidVersion:i.cidVersion,flush:i.flush,shardSplitThreshold:i.shardSplitThreshold});return n.node=s,n.cid=a,n.size=c,n};var Mw=C(ee(),1);var bd=C(ee(),1),_d=j("ipfs:mfs:core:utils:remove-link");async function Rre(r,e){let t=e.parent;if(e.parentCid){let i=z.asCID(e.parentCid);if(i===null)throw(0,bd.default)(new Error("Invalid CID passed to removeLink"),"EINVALIDPARENTCID");_d(`Loading parent node ${i}`);let o=await r.repo.blocks.get(i);t=en(o)}if(!t)throw(0,bd.default)(new Error("No parent node or CID passed to removeLink"),"EINVALIDPARENT");if(!e.name)throw(0,bd.default)(new Error("No child name passed to removeLink"),"EINVALIDCHILDNAME");if(!t.Data)throw(0,bd.default)(new Error("Parent node had no data"),"ERR_INVALID_NODE");return st.unmarshal(t.Data).type==="hamt-sharded-directory"?(_d(`Removing ${e.name} from sharded directory`),lNe(r,{...e,parent:t})):(_d(`Removing link ${e.name} regular directory`),uNe(r,{...e,parent:t}))}var uNe=async(r,e)=>{e.parent.Links=e.parent.Links.filter(s=>s.Name!==e.name);let t=await pt(e.parent),i=await(await r.hashers.getHasher(e.hashAlg)).digest(t),o=z.create(e.cidVersion,kr,i);return await r.repo.blocks.put(o,t),_d(`Updated regular directory ${o}`),{node:e.parent,cid:o}},lNe=async(r,e)=>{let{rootBucket:t,path:n}=await _re(r,e.name,e.parent);await t.del(e.name);let{node:i}=await Cre(r,n,e.name,e);return t2(r,i.Links,t,e)},Cre=async(r,e,t,n)=>{let i=e.pop();if(!i)throw(0,bd.default)(new Error("Could not find parent"),"EINVALIDPARENT");let{bucket:o,prefix:s,node:a}=i;if(!a)throw(0,bd.default)(new Error("Could not find parent"),"EINVALIDPARENT");let c=a.Links.find(d=>(d.Name||"").substring(0,2)===s);if(!c)throw(0,bd.default)(new Error(`No link found with prefix ${s} for file ${t}`),"ERR_NOT_FOUND");if(c.Name===`${s}${t}`){_d(`Removing existing link ${c.Name}`);let d=a.Links.filter(p=>p.Name!==c.Name);return await o.del(t),t2(r,d,o,n)}_d(`Descending into sub-shard ${c.Name} for ${s}${t}`);let u=await Cre(r,e,t,n),l=u.cid,f=u.size,h=s;if(u.node.Links.length===1){_d(`Removing subshard for ${s}`);let d=u.node.Links[0];h=`${s}${(d.Name||"").substring(2)}`,l=d.Hash,f=d.Tsize||0}return _d(`Updating shard ${s} with name ${h}`),fNe(r,o,a,s,h,f,l,n)},fNe=(r,e,t,n,i,o,s,a)=>{let c=t.Links.filter(u=>u.Name!==n);return c.push({Name:i,Tsize:o,Hash:s}),t2(r,c,e,a)};var dNe=et.bind({ignoreUndefined:!0}),hNe={recursive:!1,cidVersion:0,hashAlg:"sha2-256",flush:!0,shardSplitThreshold:1e3};function n2(r){async function e(t,n={}){let i=dNe(hNe,n);Array.isArray(t)||(t=[t]);let o=await Promise.all(t.map(s=>sn(r,s,i)));if(!o.length)throw(0,Mw.default)(new Error("Please supply at least one path to remove"),"ERR_INVALID_PARAMS");o.forEach(s=>{if(s.path==="/")throw(0,Mw.default)(new Error("Cannot delete root"),"ERR_INVALID_PARAMS")});for(let s of o)await pNe(r,s.path,i)}return $(e)}var pNe=async(r,e,t)=>{let n=await sn(r,e,t),i=await Yc(r,n.mfsPath),o=i[i.length-1];i.pop();let s=i[i.length-1];if(!s)throw(0,Mw.default)(new Error(`${e} does not exist`),"ERR_NOT_FOUND");if(o.type==="directory"&&!t.recursive)throw(0,Mw.default)(new Error(`${e} is a directory, use -r to remove directories`),"ERR_WAS_DIR");let{cid:a}=await Rre(r,{parentCid:s.cid,name:o.name,hashAlg:t.hashAlg,cidVersion:t.cidVersion,flush:t.flush,shardSplitThreshold:t.shardSplitThreshold});s.cid=a;let c=await os(r,i,t);await ss(r,c,t)};var mNe=et.bind({ignoreUndefined:!0}),gNe=j("ipfs:mfs:touch"),Pre={flush:!0,shardSplitThreshold:1e3,hashAlg:"sha2-256",cidVersion:0,recursive:!1};function yNe(r,e,t){let n=0;return(r.includes("x")||r.includes("X")&&(t||e&1||e&8||e&64))&&(n+=1),r.includes("w")&&(n+=2),r.includes("r")&&(n+=4),n}function wNe(r,e){let t=0;return r.includes("u")&&(t+=e<<6),r.includes("g")&&(t+=e<<3),r.includes("o")&&(t+=e),t}function bNe(r,e,t){return e.includes("t")&&(t+=parseInt("1000",8)),e.includes("s")&&(r.includes("u")&&(t+=parseInt("4000",8)),r.includes("g")&&(t+=parseInt("2000",8))),t}function _Ne(r,e,t){e||(e=0);let n=r.match(/^(u?g?o?a?)(-?\+?=?)?(r?w?x?X?s?t?)$/);if(!n)throw new Error(`Invalid file mode: ${r}`);let[,i,o,s]=n;(i==="a"||!i)&&(i="ugo");let a=yNe(s,e,t);return a=wNe(i,a),a=bNe(i,s,a),o==="="?(i.includes("u")&&(e=e&parseInt("7077",8),e=e|a),i.includes("g")&&(e=e&parseInt("7707",8),e=e|a),i.includes("o")&&(e=e&parseInt("7770",8),e=e|a),e):o==="+"?a|e:o==="-"?a^e:e}function kre(r,e){if(r instanceof String||typeof r=="string"){let t=`${r}`;t.match(/^\d+$/g)?r=parseInt(t,8):r=0+t.split(",").reduce((n,i)=>_Ne(i,n,e.isDirectory()),e.mode||0)}return r}function Nre(r){async function e(t,n,i={}){let o=mNe(Pre,i);gNe(`Fetching stats for ${t}`);let{cid:s,mfsDirectory:a,name:c}=await sn(r,t,o);if(s.code!==kr)throw(0,i2.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");if(o.recursive){let S=await Ne(async function*(){for await(let A of _E(s,r.repo.blocks)){if(A.type!=="file"&&A.type!=="directory")throw(0,i2.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");A.unixfs.mode=kre(n,A.unixfs);let I=Xn({Data:A.unixfs.marshal(),Links:A.node.Links});yield{path:A.path,content:I}}},A=>Im(A,r.repo.blocks,{...o,pin:!1,dagBuilder:async function*(I,k,N){for await(let O of I)yield async function(){let G=O.content,R=pt(G),K=await n7(R,k,N);if(!G.Data)throw(0,i2.default)(new Error(`${K} had no data`),"ERR_INVALID_NODE");let U=st.unmarshal(G.Data);return{cid:K,size:R.length,path:O.path,unixfs:U}}}}),A=>Dr(A));if(!S)throw(0,i2.default)(new Error(`Could not chmod ${t}`),"ERR_COULD_NOT_CHMOD");await n2(r)(t,o),await r2(r)(`/ipfs/${S.cid}`,t,o);return}let u=await r.repo.blocks.get(s),l=en(u);if(!l.Data)throw(0,i2.default)(new Error(`${s} had no data`),"ERR_INVALID_NODE");let f=st.unmarshal(l.Data);f.mode=kre(n,f);let h=pt({Data:f.marshal(),Links:l.Links}),d=o.hashAlg||Pre.hashAlg,g=await(await r.hashers.getHasher(d)).digest(h),w=z.create(o.cidVersion,kr,g);o.flush&&await r.repo.blocks.put(w,h);let _=await Yc(r,a),x=_[_.length-1],m=z.decode(x.cid.bytes),y=await r.repo.blocks.get(m),b=en(y),E=await Qs(r,{parent:b,name:c,cid:w,size:h.length,flush:o.flush,hashAlg:d,cidVersion:s.version,shardSplitThreshold:1/0});x.cid=E.cid;let v=await os(r,_,o);await ss(r,v,o)}return $(e)}var ENe=et.bind({ignoreUndefined:!0}),vNe={};function Dre(r){async function e(t,n={}){n=ENe(vNe,n);let{cid:i}=await yd(r)(t,n);return i}return $(e)}var xNe=et.bind({ignoreUndefined:!0}),SNe={parents:!1,flush:!0,cidVersion:0,hashAlg:"sha2-256",shardSplitThreshold:1e3};function Ore(r){async function e(t,n,i={}){let o=xNe(SNe,i);await r2(r)(t,n,o),await n2(r)(t,{...o,recursive:!0})}return $(e)}var kN=C(ee(),1);var ANe=et.bind({ignoreUndefined:!0}),TNe=j("ipfs:mfs:touch"),Lre={flush:!0,shardSplitThreshold:1e3,cidVersion:0,hashAlg:"sha2-256"};function Bre(r){async function e(t,n={}){let i=ANe(Lre,n);i.mtime=i.mtime||new Date,TNe(`Touching ${t} mtime: ${i.mtime}`);let{cid:o,mfsDirectory:s,name:a,exists:c}=await sn(r,t,i),u=n.hashAlg||Lre.hashAlg,l=await r.hashers.getHasher(u),f,h,d=i.cidVersion;if(c){if(o.code!==kr)throw(0,kN.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");d=o.version;let b=await r.repo.blocks.get(o),E=en(b);if(!E.Data)throw(0,kN.default)(new Error(`${t} had no data`),"ERR_INVALID_NODE");let v=st.unmarshal(E.Data);v.mtime=i.mtime,f=pt({Data:v.marshal(),Links:E.Links});let S=await l.digest(f);h=z.create(i.cidVersion,kr,S),i.flush&&await r.repo.blocks.put(h,f)}else{let b=new st({type:"file",mtime:i.mtime});f=pt({Data:b.marshal(),Links:[]});let E=await l.digest(f);h=z.create(i.cidVersion,kr,E),i.flush&&await r.repo.blocks.put(h,f)}let p=await Yc(r,s),g=p[p.length-1],w=g.cid,_=await r.repo.blocks.get(w),x=en(_),m=await Qs(r,{parent:x,name:a,cid:h,size:f.length,flush:i.flush,shardSplitThreshold:i.shardSplitThreshold,hashAlg:i.hashAlg,cidVersion:d});g.cid=m.cid;let y=await os(r,p,i);await ss(r,y,i)}return $(e)}var NN=C(ee(),1);var INe=et.bind({ignoreUndefined:!0}),RNe={offset:0,length:1/0};function Mre(r){function e(t,n={}){return n=INe(RNe,n),{[Symbol.asyncIterator]:async function*(){let o=await sn(r,t,n),s=await Ei(o.mfsPath,r.repo.blocks);if(s.type!=="file"&&s.type!=="raw")throw(0,NN.default)(new Error(`${t} was not a file or raw bytes`),"ERR_NOT_FILE");if(!s.content)throw(0,NN.default)(new Error(`Could not load content stream from ${t}`),"ERR_NO_CONTENT");for await(let a of s.content({offset:n.offset,length:n.length}))yield a}}}return $(e)}var DN=C(ee(),1);var Uw=j("ipfs:mfs:utils:to-async-iterator");function Ure(r){if(!r)throw(0,DN.default)(new Error("paths must start with a leading slash"),"ERR_INVALID_PATH");if((typeof r=="string"||r instanceof String)&&(Uw("Content was a string"),r=Ie(r.toString())),r.length)return Uw("Content was array-like"),{[Symbol.asyncIterator]:function*(){yield r}};if(r[Symbol.asyncIterator])return Uw("Content was an async iterator"),r;if(r[Symbol.iterator])return Uw("Content was an iterator"),r;if(globalThis.Blob&&r instanceof globalThis.Blob)return Uw("Content was an HTML5 Blob"),yo(r.stream());throw(0,DN.default)(new Error(`Don't know how to convert ${r} into an async iterator`),"ERR_INVALID_PARAMS")}var Jc=C(ee(),1);var CNe=et.bind({ignoreUndefined:!0}),Zc=j("ipfs:mfs:write"),PNe={offset:0,length:1/0,create:!1,truncate:!1,rawLeaves:!1,reduceSingleLeafToSelf:!1,cidVersion:0,hashAlg:"sha2-256",parents:!1,progress:(r,e)=>{},strategy:"trickle",flush:!0,leafType:"raw",shardSplitThreshold:1e3};function zre(r){async function e(t,n,i={}){let o=CNe(PNe,i),s,a,c;if(Zc("Reading source, destination and parent"),await Ow().readLock(async()=>{s=await Ure(n),a=await sn(r,t,o),c=await sn(r,a.mfsDirectory,o)})(),Zc("Read source, destination and parent"),!o.parents&&!c.exists)throw(0,Jc.default)(new Error("directory does not exist"),"ERR_NO_EXIST");if(s==null)throw(0,Jc.default)(new Error("could not create source"),"ERR_NO_SOURCE");if(a==null)throw(0,Jc.default)(new Error("could not create destination"),"ERR_NO_DESTINATION");if(!o.create&&!a.exists)throw(0,Jc.default)(new Error("file does not exist"),"ERR_NO_EXIST");if(a.entryType!=="file")throw(0,Jc.default)(new Error("not a file"),"ERR_NOT_A_FILE");return kNe(r,t,s,a,o)}return $(e)}var kNe=async(r,e,t,n,i)=>{let o=await NNe(r,t,n,i);await Ow().writeLock(async()=>{let s=Jm(e),a=s.pop();if(a==null)throw(0,Jc.default)(new Error("source does not exist"),"ERR_NO_EXIST");let c=!1;try{await yd(r)(`/${s.join("/")}`,i),c=!0}catch(w){if(w.code!=="ERR_NOT_FOUND")throw w}c||await Ep(r)(`/${s.join("/")}`,i);let u=await sn(r,e,i),l=await Yc(r,u.mfsDirectory),f=l[l.length-1];if(!f)throw(0,Jc.default)(new Error("directory does not exist"),"ERR_NO_EXIST");if(!f.type||!f.type.includes("directory"))throw(0,Jc.default)(new Error(`cannot write to ${f.name}: Not a directory`),"ERR_NOT_A_DIRECTORY");let h=await r.repo.blocks.get(f.cid),d=en(h),p=await Qs(r,{parent:d,name:a,cid:o.cid,size:o.size,flush:i.flush,shardSplitThreshold:i.shardSplitThreshold,hashAlg:i.hashAlg,cidVersion:i.cidVersion});f.cid=p.cid;let g=await os(r,l,i);await ss(r,g,i)})()},NNe=async(r,e,t,n)=>{t.exists?Zc(`Overwriting file ${t.cid} offset ${n.offset} length ${n.length}`):Zc(`Writing file offset ${n.offset} length ${n.length}`);let i=[];if(n.offset>0)if(t.unixfs){if(Zc(`Writing first ${n.offset} bytes of original file`),i.push(()=>t.content({offset:0,length:n.offset})),t.unixfs.fileSize(){if(t.unixfs&&!n.truncate){let f=t.unixfs.fileSize();if(f>l)return Zc(`Writing last ${f-l} of ${f} bytes from original file starting at offset ${l}`),t.content({offset:l});Zc("Not writing last bytes from original file")}return{[Symbol.asyncIterator]:async function*(){}}}),s;n.mode!==void 0&&n.mode!==null?s=Bu(n.mode):t&&t.unixfs&&(s=t.unixfs.mode);let a;n.mtime!=null?a=af(n.mtime):t&&t.unixfs&&(a=t.unixfs.mtime);let c=await r.hashers.getHasher(n.hashAlg),u=await Dr(Im([{content:o,mode:s,mtime:a}],r.repo.blocks,{progress:n.progress,hasher:c,cidVersion:n.cidVersion,strategy:n.strategy,rawLeaves:n.rawLeaves,reduceSingleLeafToSelf:n.reduceSingleLeafToSelf,leafType:n.leafType}));if(!u)throw(0,Jc.default)(new Error(`cannot write to ${parent.name}`),"ERR_COULD_NOT_WRITE");return Zc(`Wrote ${u.cid}`),{cid:u.cid,size:u.size}},Vre=(r,e)=>async function*(){let n=0;for await(let i of r){if(n+=i.length,n>e){yield i.subarray(0,e-n);return}yield i}},Fre=(r,e=PH)=>{let t=new Uint8Array(e);async function*n(){for(;;)yield t}return Vre(n(),r)},DNe=async function*(r){for(let e=0;e{let e={cid:r.cid,name:r.name,type:r.type==="directory"?"directory":"file",size:r.size};return(r.type==="file"||r.type==="directory")&&(e.mode=r.unixfs.mode,e.mtime=r.unixfs.mtime),e};function $re(r){async function*e(t,n={}){let i=await sn(r,t,n),o=await Ei(i.mfsPath,r.repo.blocks);if(o.type==="directory"){yield*Mi(o.content(n),Kre);return}yield Kre(o)}return $(e)}var LNe={stat:yd},BNe={chmod:Nre,cp:r2,flush:Dre,mkdir:Ep,mv:Ore,rm:n2,touch:Bre},qre={write:zre,read:Mre,ls:$re},Hre=({options:r,mfs:e,operations:t,lock:n})=>{Object.keys(t).forEach(i=>{e[i]=n(t[i](r))})},MNe={repoOwner:!0,repo:null};function UNe(r){let{repoOwner:e}=Object.assign({},MNe||{},r),t=Ow(e),n=s=>t.readLock(s),i=s=>t.writeLock(s),o={};return Hre({options:r,mfs:o,operations:LNe,lock:n}),Hre({options:r,mfs:o,operations:BNe,lock:i}),Object.keys(qre).forEach(s=>{o[s]=qre[s](r)}),o}function Gre({repo:r,preload:e,hashers:t,options:n}){let i=UNe({repo:r,repoOwner:n.repoOwner!==!1,hashers:t}),o=s=>(...c)=>{let u=c.filter(l=>gH(l)||V8(l));if(u.length){let l=c[c.length-1];l&&l.preload!==!1&&u.forEach(f=>e(f))}return s(...c)};return{...i,chmod:i.chmod,cp:o(i.cp),mkdir:i.mkdir,stat:o(i.stat),rm:i.rm,read:o(i.read),touch:i.touch,write:i.write,mv:o(i.mv),flush:i.flush,ls:o(async function*(...s){for await(let a of i.ls(...s))yield{...a,size:a.size||0}})}}function jre({keychain:r}){return $((t,n)=>r.exportKey(t,n))}var Wre="Ed25519",Yre=2048;function Qre({keychain:r}){return $((t,n={type:Wre,size:Yre})=>r.createKey(t,n.type||Wre,n.size||Yre))}function Xre({keychain:r}){return $((t,n,i)=>r.importKey(t,n,i))}function Zre({keychain:r}){return $(t=>r.findKeyByName(t))}function Jre({keychain:r}){return $(()=>r.listKeys())}function ene({keychain:r}){return $(async(t,n)=>{let i=await r.renameKey(t,n);return{was:t,now:i.name,id:i.id,overwrite:!1}})}function tne({keychain:r}){return $(t=>r.removeKey(t))}var c7=class{constructor({keychain:e}){this.gen=Qre({keychain:e}),this.list=Jre({keychain:e}),this.rm=tne({keychain:e}),this.rename=ene({keychain:e}),this.export=jre({keychain:e}),this.import=Xre({keychain:e}),this.info=Zre({keychain:e})}};function _o({repo:r,preload:e}){async function t(n,i={}){i.preload!==!1&&e(n);let o=await r.blocks.get(n,i);return en(o)}return $(t)}function rne({repo:r,preload:e}){let t=_o({repo:r,preload:e});async function n(i,o={}){return(await t(i,o)).Data||new Uint8Array(0)}return $(n)}function ON(r,e=[]){for(let t in r){let n=r[t];if(t==="/"&&Object.keys(r).length===1)try{e.push({Name:"",Tsize:0,Hash:z.parse(n)});continue}catch{}let i=z.asCID(n);if(i){e.push({Name:"",Tsize:0,Hash:i});continue}Array.isArray(n)&&ON(n,e),n&&typeof n=="object"&&ON(n,e)}return e}function nne({repo:r,codecs:e}){async function t(n,i={}){let o=await e.getCodec(n.code),s=await r.blocks.get(n,i),a=o.decode(s);switch(n.code){case gf:return[];case kr:return a.Links;case lT:case _T:return ON(a);default:throw new Error(`Cannot resolve links from codec ${n.code}`)}}return $(t)}function ine({repo:r,preload:e}){async function t(n={}){let i;if(n.template)if(n.template==="unixfs-dir")i=new st({type:"directory"}).marshal();else throw new Error("unknown template");let o=pt({Data:i,Links:[]}),s=await dt.digest(o),a=z.createV0(s);return await r.blocks.put(a,o,{signal:n.signal}),n.preload!==!1&&e(a),a}return $(t)}function eu({repo:r,preload:e}){async function t(n,i={}){let o=await r.gcLock.readLock();try{let s=pt(n),a=await dt.digest(s),c=z.createV1(kr,a);return await r.blocks.put(c,s,{signal:i.signal}),i.preload!==!1&&e(c),i.pin&&await r.pins.pinRecursively(c,{signal:i.signal}),c}finally{o()}}return $(t)}function one({repo:r,preload:e}){let t=_o({repo:r,preload:e});async function n(i,o={}){let s=await t(i,o),c=pt(s).length,u=s.Links.reduce((l,f)=>l+(f.Tsize||0),0);return{Hash:i,NumLinks:s.Links.length,BlockSize:c,LinksSize:c-(s.Data||[]).length,DataSize:(s.Data||[]).length,CumulativeSize:c+u}}return $(n)}function sne({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a);return n({...c,Links:c.Links.concat([s])},a)}return $(i)}function ane({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a),u=rt([c.Data||[],s]);return n({...c,Data:u},a)}return $(i)}function cne({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a),u=(typeof s=="string"?s:s.Name)||"";return c.Links=c.Links.filter(l=>l.Name!==u),n(c,a)}return $(i)}function une({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a);return n({...c,Data:s},a)}return $(i)}var u7=class{constructor({repo:e,preload:t}){this.addLink=sne({repo:e,preload:t}),this.appendData=ane({repo:e,preload:t}),this.rmLink=cne({repo:e,preload:t}),this.setData=une({repo:e,preload:t})}};var l7=class{constructor({repo:e,codecs:t,preload:n}){this.data=rne({repo:e,preload:n}),this.get=_o({repo:e,preload:n}),this.links=nne({repo:e,codecs:t}),this.new=ine({repo:e,preload:n}),this.put=eu({repo:e,preload:n}),this.stat=one({repo:e,preload:n}),this.patch=new u7({repo:e,preload:n})}};var FNe=j("ipfs:repo:gc");function lne({repo:r,hashers:e}){async function*t(n={}){let i=Date.now(),o;try{o=await Zm({repo:r,hashers:e},n),await r.pins.pinRecursively(o),yield*r.gc()}finally{o&&await r.pins.unpin(o)}FNe(`Complete (${Date.now()-i}ms)`)}return $(t)}function f7({repo:r}){async function e(t={}){let n=await r.stat();return{numObjects:BigInt(n.numObjects.toString()),repoSize:BigInt(n.repoSize.toString()),repoPath:n.repoPath,version:`${n.version}`,storageMax:BigInt(n.storageMax.toString())}}return $(e)}function fne({repo:r}){async function e(t={}){try{await r._checkInitialized(t)}catch(n){if([/Key not found in database \[\/version\]/,/ENOENT/,/repo is not initialized yet/].some(o=>o.test(n.message)))return 12;throw n}return r.version.get()}return $(e)}var d7=class{constructor({repo:e,hashers:t}){this.gc=lne({repo:e,hashers:t}),this.stat=f7({repo:e}),this.version=fne({repo:e}),this.setApiAddr=n=>e.apiAddr.set(n)}};var hne=C(ee(),1);function dne(r,e){return{totalIn:BigInt(0),totalOut:BigInt(0),rateIn:0,rateOut:0}}function pne({network:r}){return $(async function*(t={}){let{libp2p:n}=await r.use(t);if(!t.poll){yield dne(n,t);return}let i=t.interval||1e3,o=-1;try{if(o=typeof i=="string"?Cf(i)||-1:i,!o||o<0)throw new Error("invalid duration")}catch(a){throw(0,hne.default)(a,"ERR_INVALID_POLL_INTERVAL")}let s;try{for(;;)yield dne(n,t),await new Promise(a=>{s=setTimeout(a,o)})}finally{clearTimeout(s)}})}var h7=class{constructor({repo:e,network:t}){this.repo=f7({repo:e}),this.bw=pne({network:t}),this.bitswap=N_({network:t})}};var zw=VNe;function VNe(r,e,t){if(!r)return t;var n,i;if(Array.isArray(e)&&(n=e.slice(0)),typeof e=="string"&&(n=e.split(".")),typeof e=="symbol"&&(n=[e]),!Array.isArray(n))throw new Error("props arg must be an array, a string or a symbol");for(;n.length;)if(i=n.shift(),!r||(r=r[i],r===void 0))return t;return r}var Gie=C($s(),1),Np=C(ee(),1);var gne=C($s(),1);async function vp(r){let e=0;for await(let t of r)e++;return e}var KNe=(0,gne.default)("ipfs:repo:migrator:migration-8");function yne(r){return r.child?yne(r.child):r}function $Ne(r){try{let e=Ot.decode(`b${r.toString().toLowerCase().slice(1)}`),t=ce.decode(e).multihash.bytes,n=Ot.encode(t).slice(1).toUpperCase();return new pe(`/${n}`,!1)}catch{return r}}function qNe(r){try{let e=Ot.decode(`b${r.toString().toLowerCase().slice(1)}`),t=Jn(e),n=Ot.encode(ce.createV1(Sc,t).bytes).slice(1);return new pe(`/${n.toUpperCase()}`,!1)}catch{return r}}async function mne(r,e,t){let n=r.blocks;await n.open();let i=yne(n),o=await vp(i.queryKeys({filters:[s=>t(s).toString()!==s.toString()]}));try{let s=0;for await(let a of i.query({})){let c=t(a.key);c.toString()!==a.key.toString()&&(s+=1,KNe(`Migrating Block from ${a.key} to ${c}`,await i.has(a.key)),await i.delete(a.key),await i.put(c,a.value),e(s/o*100,`Migrated Block from ${a.key} to ${c}`))}}finally{await n.close()}}var wne={version:8,description:"Transforms key names into base32 encoding and converts Block store to use bare multihashes encoded as base32",migrate:(r,e=()=>{})=>mne(r,e,$Ne),revert:(r,e=()=>{})=>mne(r,e,qNe)};var xp=C(gc(),1),bne=xp.default.Reader,HNe=xp.default.Writer,w8t=xp.default.util,p7=xp.default.roots.default||(xp.default.roots.default={}),_ne=p7.ipfs=(()=>{let r={};return r.pin=function(){let e={};return e.Set=function(){function t(n){if(n)for(var i=Object.keys(n),o=0;o>>3){case 1:a.version=i.uint32();break;case 2:a.fanout=i.uint32();break;case 3:a.seed=i.fixed32();break;default:i.skipType(c&7);break}}return a},t.fromObject=function(i){if(i instanceof p7.ipfs.pin.Set)return i;var o=new p7.ipfs.pin.Set;return i.version!=null&&(o.version=i.version>>>0),i.fanout!=null&&(o.fanout=i.fanout>>>0),i.seed!=null&&(o.seed=i.seed>>>0),o},t.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(s.version=0,s.fanout=0,s.seed=0),i.version!=null&&i.hasOwnProperty("version")&&(s.version=i.version),i.fanout!=null&&i.hasOwnProperty("fanout")&&(s.fanout=i.fanout),i.seed!=null&&i.hasOwnProperty("seed")&&(s.seed=i.seed),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,xp.default.util.toJSONOptions)},t}(),e}(),r})();var Sne=C(vne(),1),y7=C(Xo(),1);var Vw=new pe("/local/pins"),g7=256,xne=8192,BN=ce.parse("QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n"),Sp={direct:"direct",recursive:"recursive"};function MN(r){return new pe(`/${Ot.encode(r.multihash.bytes).toUpperCase().substring(1)}`)}function UN(r,e){for(let t=0;te[t])return 1}return r.byteLength>e.byteLength?1:r.byteLengthe.length)throw new Error("Impossibly large set header length");let i=e.slice(n,t+n),o=FN.toObject(FN.decode(i),{defaults:!1,arrays:!0,longs:Number,objects:!1});if(o.version!==1)throw new Error(`Unsupported Set version: ${o.version}`);if(o.fanout>r.Links.length)throw new Error("Impossibly large fanout");return{header:o,data:e.slice(t+n)}}function jNe(r,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,r,!0);let i=fe(e.toString()),o=yr([t,i],t.byteLength+i.byteLength);return(0,Sne.default)(Ee(o))}async function*Ane(r,e){let t=GNe(e),n=0;for(let i of e.Links){if(ns.Name===t);if(!n)throw new Error("No link found with name "+t);let i=await r.get(n.Hash),o=Jo(i);yield*Ane(r,o)}function WNe(r,e){return t(e,0);async function t(n,i){let o=FN.encode({version:1,fanout:g7,seed:i}).finish(),s=y7.default.encode(o.length),a=yr([s,o]),c=[];for(let l=0;l({link:{Name:"",Tsize:1,Hash:d.key},data:d.data||new Uint8Array})).sort((d,p)=>UN(d.link.Hash.bytes,p.link.Hash.bytes)),f=c.concat(l.map(d=>d.link));return{Data:yr([a,...l.map(d=>d.data)]),Links:f}}else{let l=n.reduce((h,d)=>{let p=jNe(i,d.key)%g7;return h[p]=p in h?h[p].concat([d]):[d],h},[]),f=0;for(let h of l){let d=await t(h,i+1);await u(d,f),f++}return{Data:a,Links:c}}async function u(l,f){let h=W3(l),d=await mr.digest(h),p=ce.createV0(d);await r.put(p,h);let g=l.Links.reduce((w,_)=>w+(_.Tsize||0),0)+h.length;c[f]={Name:"",Tsize:g,Hash:p}}}}async function zN(r,e,t){let n=await WNe(r,t.map(c=>({key:c}))),i=W3(n),o=await mr.digest(i),s=ce.createV0(o);await r.put(s,i);let a=n.Links.reduce((c,u)=>c+u.Tsize,0)+i.length;return{Name:e,Tsize:a,Hash:s}}async function QNe(r,e,t,n){if(!await e.has(Vw))return;let i=await e.get(Vw),o=ce.decode(i),s=await r.get(o),a=Jo(s),c=0,u=await vp(Kw(r,a,Sp.recursive))+await vp(Kw(r,a,Sp.direct));for await(let l of Kw(r,a,Sp.recursive)){c++;let f={depth:1/0};l.version!==0&&(f.version=l.version),l.code!==Zo&&(f.codec=l.code),await t.put(MN(l),zu(f)),n(c/u*100,`Migrated recursive pin ${l}`)}for await(let l of Kw(r,a,Sp.direct)){c++;let f={depth:0};l.version!==0&&(f.version=l.version),l.code!==Zo&&(f.codec=l.code),await t.put(MN(l),zu(f)),n(c/u*100,`Migrated direct pin ${l}`)}await r.delete(o),await e.delete(Vw)}async function XNe(r,e,t,n){let i=[],o=[],s=0,a=await vp(t.queryKeys({}));for await(let{key:h,value:d}of t.query({})){s++;let p=ks(d),g=ce.create(p.version||0,p.codec||Zo,Jn(Ot.decode("b"+h.toString().toLowerCase().split("/").pop())));p.depth===0?(n(s/a*100,`Reverted direct pin ${g}`),o.push(g)):(n(s/a*100,`Reverted recursive pin ${g}`),i.push(g))}n(100,"Updating pin root");let c={Links:[await zN(r,Sp.direct,o),await zN(r,Sp.recursive,i)]},u=W3(c),l=await mr.digest(u),f=ce.createV0(l);await r.put(f,u),await e.put(Vw,f.bytes)}async function Tne(r,e,t){let n=r.blocks,i=r.datastore,o=r.pins;await n.open(),await i.open(),await o.open();try{await t(n,i,o,e)}finally{await o.close(),await i.close(),await n.close()}}var Ine={version:9,description:"Migrates pins to datastore",migrate:(r,e=()=>{})=>Tne(r,e,QNe),revert:(r,e=()=>{})=>Tne(r,e,XNe)};var Rne=new pe("/config"),$w=new pe("/version");function qw(r){let e=r;for(;e.db||e.child;)if(e=e.db||e.child,e.type==="level-js"||e.constructor.name==="Level")return e}async function ZNe(r,e,t){let n=await e(r);if(n)return n;let i=qw(t);return i?new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{o(!!a.result)}}):!1}async function JNe(r,e,t,n){if(await t(r))return e(r);let i=qw(n);if(!i)throw Gn();return new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{if(a.result)return o(a.result);s(Gn())}})}function w7(r){let e=r.get.bind(r),t=r.has.bind(r);return r.get=n=>JNe(n,e,t,r),r.has=n=>ZNe(n,t,r),r}function VN(r){return{...r,root:w7(r.root),datastore:w7(r.datastore),pins:w7(r.pins),keys:w7(r.keys)}}async function eDe(r,e,t=()=>{}){let n=qw(e);if(!n){t(`${r} did not need an upgrade`);return}t(`Upgrading ${r}`),await Nne(n,(o,s)=>[{type:"del",key:o},{type:"put",key:fe(o),value:s}])}async function tDe(r,e,t=()=>{}){let n=qw(e);if(!n){t(`${r} did not need a downgrade`);return}t(`Downgrading ${r}`),await Nne(n,(o,s)=>[{type:"del",key:o},{type:"put",key:Ee(o),value:s}])}function Pne(r){return r.child?Pne(r.child):r}async function Cne(r,e,t){let n=Object.entries(r).map(([s,a])=>({key:s,backend:Pne(a)})).filter(({key:s,backend:a})=>a.constructor.name==="LevelDatastore").map(({key:s,backend:a})=>({name:s,store:a}));e(0,`Migrating ${n.length} dbs`);let i=0,o=s=>{e(Math.round(i/n.length*100),s)};for(let{name:s,store:a}of n){await a.open();try{await t(s,a,o)}finally{i++,await a.close()}}e(100,`Migrated ${n.length} dbs`)}var kne={version:10,description:"Migrates datastore-level keys to binary",migrate:(r,e=()=>{})=>Cne(r,e,eDe),revert:(r,e=()=>{})=>Cne(r,e,tDe)};function Nne(r,e){function t(n,i){let o=r.store("readwrite"),s=o.transaction,a=0,c;s.onabort=()=>i(c||s.error||new Error("aborted by user")),s.oncomplete=()=>i();function u(){let l=n[a++],f=l.key,h;try{h=l.type==="del"?o.delete(f):o.put(l.value,f)}catch(d){c=d,s.abort();return}a{let o=r.iterator(),s=c=>c;o._deserializeKey=o._deserializeValue=s,a();function a(){let c=(u,l,f)=>{if(u||l===void 0){let h=d=>{if(d){i(d);return}n()};o.end(h);return}t(e(l,f),a)};o.next(c)}})}var Ed=new pe("/local/filesroot");async function rDe(r,e=()=>{}){if(e(100,"Migrating MFS root to repo datastore"),await r.root.open(),await r.datastore.open(),await r.root.has(Ed)){let t=await r.root.get(Ed);await r.datastore.put(Ed,t),await r.root.delete(Ed)}await r.datastore.close(),await r.root.close(),e(100,"Stored MFS root in repo datastore")}async function nDe(r,e=()=>{}){if(e(100,"Migrating MFS root to repo root datastore"),await r.root.open(),await r.datastore.open(),await r.datastore.has(Ed)){let t=await r.datastore.get(Ed);await r.root.put(Ed,t),await r.datastore.delete(Ed)}await r.datastore.close(),await r.root.close(),e(100,"Stored MFS root in repo root datastore")}var Dne={version:11,description:"Store mfs root in the datastore",migrate:rDe,revert:nDe};var oD=C(gc(),1);var Ap=C(gc(),1),One=Ap.default.Reader,iDe=Ap.default.Writer,oDe=Ap.default.util,b7=Ap.default.roots.default||(Ap.default.roots.default={}),KN=b7.Protocols=(()=>{function r(e){if(this.protocols=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.protocols&&o.protocols.length||(o.protocols=[]),o.protocols.push(t.string());break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof b7.Protocols)return t;var n=new b7.Protocols;if(t.protocols){if(!Array.isArray(t.protocols))throw TypeError(".Protocols.protocols: array expected");n.protocols=[];for(var i=0;i{function r(e){if(this.addrs=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.addrs&&o.addrs.length||(o.addrs=[]),o.addrs.push(ui.Addresses.Address.decode(t,t.uint32()));break;case 2:o.certifiedRecord=ui.Addresses.CertifiedRecord.decode(t,t.uint32());break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof ui.Addresses)return t;var n=new ui.Addresses;if(t.addrs){if(!Array.isArray(t.addrs))throw TypeError(".Addresses.addrs: array expected");n.addrs=[];for(var i=0;i>>3){case 1:a.multiaddr=i.bytes();break;case 2:a.isCertified=i.bool();break;default:i.skipType(c&7);break}}return a},e.fromObject=function(i){if(i instanceof ui.Addresses.Address)return i;var o=new ui.Addresses.Address;return i.multiaddr!=null&&(typeof i.multiaddr=="string"?qr.base64.decode(i.multiaddr,o.multiaddr=qr.newBuffer(qr.base64.length(i.multiaddr)),0):i.multiaddr.length&&(o.multiaddr=i.multiaddr)),i.isCertified!=null&&(o.isCertified=!!i.isCertified),o},e.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(o.bytes===String?s.multiaddr="":(s.multiaddr=[],o.bytes!==Array&&(s.multiaddr=qr.newBuffer(s.multiaddr)))),i.multiaddr!=null&&i.hasOwnProperty("multiaddr")&&(s.multiaddr=o.bytes===String?qr.base64.encode(i.multiaddr,0,i.multiaddr.length):o.bytes===Array?Array.prototype.slice.call(i.multiaddr):i.multiaddr),i.isCertified!=null&&i.hasOwnProperty("isCertified")&&(s.isCertified=i.isCertified,o.oneofs&&(s._isCertified="isCertified")),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,gl.default.util.toJSONOptions)},e}(),r.CertifiedRecord=function(){function e(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:s.seq=n.uint64();break;case 2:s.raw=n.bytes();break;default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof ui.Addresses.CertifiedRecord)return n;var i=new ui.Addresses.CertifiedRecord;return n.seq!=null&&(qr.Long?(i.seq=qr.Long.fromValue(n.seq)).unsigned=!0:typeof n.seq=="string"?i.seq=parseInt(n.seq,10):typeof n.seq=="number"?i.seq=n.seq:typeof n.seq=="object"&&(i.seq=new qr.LongBits(n.seq.low>>>0,n.seq.high>>>0).toNumber(!0))),n.raw!=null&&(typeof n.raw=="string"?qr.base64.decode(n.raw,i.raw=qr.newBuffer(qr.base64.length(n.raw)),0):n.raw.length&&(i.raw=n.raw)),i},e.toObject=function(n,i){i||(i={});var o={};if(i.defaults){if(qr.Long){var s=new qr.Long(0,0,!0);o.seq=i.longs===String?s.toString():i.longs===Number?s.toNumber():s}else o.seq=i.longs===String?"0":0;i.bytes===String?o.raw="":(o.raw=[],i.bytes!==Array&&(o.raw=qr.newBuffer(o.raw)))}return n.seq!=null&&n.hasOwnProperty("seq")&&(typeof n.seq=="number"?o.seq=i.longs===String?String(n.seq):n.seq:o.seq=i.longs===String?qr.Long.prototype.toString.call(n.seq):i.longs===Number?new qr.LongBits(n.seq.low>>>0,n.seq.high>>>0).toNumber(!0):n.seq),n.raw!=null&&n.hasOwnProperty("raw")&&(o.raw=i.bytes===String?qr.base64.encode(n.raw,0,n.raw.length):i.bytes===Array?Array.prototype.slice.call(n.raw):n.raw),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,gl.default.util.toJSONOptions)},e}(),r})();var yl=C(gc(),1),s2=yl.default.Reader,HN=yl.default.Writer,dr=yl.default.util,Nn=yl.default.roots.default||(yl.default.roots.default={}),GN=Nn.Peer=(()=>{function r(t){if(this.addresses=[],this.protocols=[],this.metadata=[],t)for(var n=Object.keys(t),i=0;i>>3){case 1:s.addresses&&s.addresses.length||(s.addresses=[]),s.addresses.push(Nn.Address.decode(n,n.uint32()));break;case 2:s.protocols&&s.protocols.length||(s.protocols=[]),s.protocols.push(n.string());break;case 3:s.metadata&&s.metadata.length||(s.metadata=[]),s.metadata.push(Nn.Metadata.decode(n,n.uint32()));break;case 4:s.pubKey=n.bytes();break;case 5:s.peerRecordEnvelope=n.bytes();break;default:n.skipType(a&7);break}}return s},r.fromObject=function(n){if(n instanceof Nn.Peer)return n;var i=new Nn.Peer;if(n.addresses){if(!Array.isArray(n.addresses))throw TypeError(".Peer.addresses: array expected");i.addresses=[];for(var o=0;o{function r(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:s.multiaddr=n.bytes();break;case 2:s.isCertified=n.bool();break;default:n.skipType(a&7);break}}return s},r.fromObject=function(n){if(n instanceof Nn.Address)return n;var i=new Nn.Address;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?dr.base64.decode(n.multiaddr,i.multiaddr=dr.newBuffer(dr.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),n.isCertified!=null&&(i.isCertified=!!n.isCertified),i},r.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.multiaddr="":(o.multiaddr=[],i.bytes!==Array&&(o.multiaddr=dr.newBuffer(o.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(o.multiaddr=i.bytes===String?dr.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),n.isCertified!=null&&n.hasOwnProperty("isCertified")&&(o.isCertified=n.isCertified,i.oneofs&&(o._isCertified="isCertified")),o},r.prototype.toJSON=function(){return this.constructor.toObject(this,yl.default.util.toJSONOptions)},r})(),X8t=Nn.Metadata=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.key=t.string();break;case 2:o.value=t.bytes();break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof Nn.Metadata)return t;var n=new Nn.Metadata;return t.key!=null&&(n.key=String(t.key)),t.value!=null&&(typeof t.value=="string"?dr.base64.decode(t.value,n.value=dr.newBuffer(dr.base64.length(t.value)),0):t.value.length&&(n.value=t.value)),n},r.toObject=function(t,n){n||(n={});var i={};return n.defaults&&(i.key="",n.bytes===String?i.value="":(i.value=[],n.bytes!==Array&&(i.value=dr.newBuffer(i.value)))),t.key!=null&&t.hasOwnProperty("key")&&(i.key=t.key),t.value!=null&&t.hasOwnProperty("value")&&(i.value=n.bytes===String?dr.base64.encode(t.value,0,t.value.length):n.bytes===Array?Array.prototype.slice.call(t.value):t.value),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,yl.default.util.toJSONOptions)},r})();var Tp=C(gc(),1),Lne=Tp.default.Reader,sDe=Tp.default.Writer,Hr=Tp.default.util,_7=Tp.default.roots.default||(Tp.default.roots.default={}),Bne=_7.Envelope=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof _7.Envelope)return t;var n=new _7.Envelope;return t.publicKey!=null&&(typeof t.publicKey=="string"?Hr.base64.decode(t.publicKey,n.publicKey=Hr.newBuffer(Hr.base64.length(t.publicKey)),0):t.publicKey.length&&(n.publicKey=t.publicKey)),t.payloadType!=null&&(typeof t.payloadType=="string"?Hr.base64.decode(t.payloadType,n.payloadType=Hr.newBuffer(Hr.base64.length(t.payloadType)),0):t.payloadType.length&&(n.payloadType=t.payloadType)),t.payload!=null&&(typeof t.payload=="string"?Hr.base64.decode(t.payload,n.payload=Hr.newBuffer(Hr.base64.length(t.payload)),0):t.payload.length&&(n.payload=t.payload)),t.signature!=null&&(typeof t.signature=="string"?Hr.base64.decode(t.signature,n.signature=Hr.newBuffer(Hr.base64.length(t.signature)),0):t.signature.length&&(n.signature=t.signature)),n},r.toObject=function(t,n){n||(n={});var i={};return n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=Hr.newBuffer(i.publicKey))),n.bytes===String?i.payloadType="":(i.payloadType=[],n.bytes!==Array&&(i.payloadType=Hr.newBuffer(i.payloadType))),n.bytes===String?i.payload="":(i.payload=[],n.bytes!==Array&&(i.payload=Hr.newBuffer(i.payload))),n.bytes===String?i.signature="":(i.signature=[],n.bytes!==Array&&(i.signature=Hr.newBuffer(i.signature)))),t.publicKey!=null&&t.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?Hr.base64.encode(t.publicKey,0,t.publicKey.length):n.bytes===Array?Array.prototype.slice.call(t.publicKey):t.publicKey),t.payloadType!=null&&t.hasOwnProperty("payloadType")&&(i.payloadType=n.bytes===String?Hr.base64.encode(t.payloadType,0,t.payloadType.length):n.bytes===Array?Array.prototype.slice.call(t.payloadType):t.payloadType),t.payload!=null&&t.hasOwnProperty("payload")&&(i.payload=n.bytes===String?Hr.base64.encode(t.payload,0,t.payload.length):n.bytes===Array?Array.prototype.slice.call(t.payload):t.payload),t.signature!=null&&t.hasOwnProperty("signature")&&(i.signature=n.bytes===String?Hr.base64.encode(t.signature,0,t.signature.length):n.bytes===Array?Array.prototype.slice.call(t.signature):t.signature),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Tp.default.util.toJSONOptions)},r})();var vd=C(gc(),1),E7=vd.default.Reader,Mne=vd.default.Writer,an=vd.default.util,Qa=vd.default.roots.default||(vd.default.roots.default={}),Une=Qa.PeerRecord=(()=>{function r(e){if(this.addresses=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.peerId=t.bytes();break;case 2:o.seq=t.uint64();break;case 3:o.addresses&&o.addresses.length||(o.addresses=[]),o.addresses.push(Qa.PeerRecord.AddressInfo.decode(t,t.uint32()));break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof Qa.PeerRecord)return t;var n=new Qa.PeerRecord;if(t.peerId!=null&&(typeof t.peerId=="string"?an.base64.decode(t.peerId,n.peerId=an.newBuffer(an.base64.length(t.peerId)),0):t.peerId.length&&(n.peerId=t.peerId)),t.seq!=null&&(an.Long?(n.seq=an.Long.fromValue(t.seq)).unsigned=!0:typeof t.seq=="string"?n.seq=parseInt(t.seq,10):typeof t.seq=="number"?n.seq=t.seq:typeof t.seq=="object"&&(n.seq=new an.LongBits(t.seq.low>>>0,t.seq.high>>>0).toNumber(!0))),t.addresses){if(!Array.isArray(t.addresses))throw TypeError(".PeerRecord.addresses: array expected");n.addresses=[];for(var i=0;i>>0,t.seq.high>>>0).toNumber(!0):t.seq),t.addresses&&t.addresses.length){i.addresses=[];for(var s=0;s>>3){case 1:s.multiaddr=n.bytes();break;default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof Qa.PeerRecord.AddressInfo)return n;var i=new Qa.PeerRecord.AddressInfo;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?an.base64.decode(n.multiaddr,i.multiaddr=an.newBuffer(an.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),i},e.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.multiaddr="":(o.multiaddr=[],i.bytes!==Array&&(o.multiaddr=an.newBuffer(o.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(o.multiaddr=i.bytes===String?an.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,vd.default.util.toJSONOptions)},e}(),r})();var v7=class{constructor(){B(this,"index",0);B(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let 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(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=e,o+=l,o>u||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;nthis.readIPv4Addr());if(s!==void 0)return t[i]=s[0],t[i+1]=s[1],t[i+2]=s[2],t[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];t[i]=o>>8,t[i+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Fne=45,aDe=15,a2=new v7;function zne(r){if(!(r.length>aDe))return a2.new(r).parseWith(()=>a2.readIPv4Addr())}function Vne(r){if(!(r.length>Fne))return a2.new(r).parseWith(()=>a2.readIPv6Addr())}function Kne(r){if(!(r.length>Fne))return a2.new(r).parseWith(()=>a2.readIPAddr())}function $ne(r){return!!zne(r)}function qne(r){return!!Vne(r)}function c2(r){return!!Kne(r)}var Hne=$ne,cDe=qne,jN=function(r){let e=0;if(r=r.toString().trim(),Hne(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(cDe(r)){let t=r.split(":",8),n;for(n=0;n0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},Gne=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let o=0;o{let e=fDe(...r);WN[e.code]=e,Hw[e.name]=e});function fDe(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function hr(r){if(typeof r=="number"){if(WN[r]!=null)return WN[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hw[r]!=null)return Hw[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var tu=C(Xo(),1);function Xne(r,e){switch(hr(r).code){case 4:case 41:return hDe(e);case 42:return Yne(e);case 6:case 273:case 33:case 132:return Jne(e).toString();case 53:case 54:case 55:case 56:case 400:case 777:return Yne(e);case 421:return yDe(e);case 444:return Qne(e);case 445:return Qne(e);case 466:return gDe(e);default:return Ee(e,"base16")}}function Zne(r,e){switch(hr(r).code){case 4:return jne(e);case 41:return jne(e);case 42:return Wne(e);case 6:case 273:case 33:case 132:return QN(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 777:return Wne(e);case 421:return pDe(e);case 444:return wDe(e);case 445:return bDe(e);case 466:return mDe(e);default:return fe(e,"base16")}}var YN=Object.values(If).map(r=>r.decoder),dDe=function(){let r=YN[0].or(YN[1]);return YN.slice(2).forEach(e=>r=r.or(e)),r}();function jne(r){if(!c2(r))throw new Error("invalid ip address");return jN(r)}function hDe(r){let e=Gne(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!c2(e))throw new Error("invalid ip address");return e}function QN(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Jne(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Wne(r){let e=fe(r),t=Uint8Array.from(tu.default.encode(e.length));return yr([t,e],t.length+e.length)}function Yne(r){let e=tu.default.decode(r);if(r=r.slice(tu.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return Ee(r)}function pDe(r){let e;r[0]==="Q"||r[0]==="1"?e=Jn(tt.decode(`z${r}`)).bytes:e=ce.parse(r).multihash.bytes;let t=Uint8Array.from(tu.default.encode(e.length));return yr([t,e],t.length+e.length)}function mDe(r){let e=dDe.decode(r),t=Uint8Array.from(tu.default.encode(e.length));return yr([t,e],t.length+e.length)}function gDe(r){let e=tu.default.decode(r),t=r.slice(tu.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+Ee(t,"base64url")}function yDe(r){let e=tu.default.decode(r),t=r.slice(tu.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return Ee(t,"base58btc")}function wDe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ot.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=QN(n);return yr([t,i],t.length+i.length)}function bDe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ot.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=QN(n);return yr([t,i],t.length+i.length)}function Qne(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=Ee(e,"base32"),i=Jne(t);return`${n}:${i}`}var u2=C(Xo(),1);function _De(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n=t.length)throw tie("invalid address: "+r);if(o.path===!0){e.push([i,tD(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function EDe(r){let e=[];return r.map(t=>{let n=A7(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),tD(e.join("/"))}function vDe(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=A7(e);return e.length>1?[t.code,Zne(t.code,e[1])]:[t.code]})}function XN(r){return r.map(e=>{let t=A7(e);return e[1]!=null?[t.code,Xne(t.code,e[1])]:[t.code]})}function ZN(r){return S7(yr(r.map(e=>{let t=A7(e),n=Uint8Array.from(u2.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=yr([n,e[1]])),n})))}function JN(r,e){return r.size>0?r.size/8:r.size===0?0:u2.default.decode(e)+(u2.default.decode.bytes??0)}function x7(r){let e=[],t=0;for(;tr.length)throw tie("Invalid address Uint8Array: "+Ee(r,"base16"));e.push([n,a])}return e}function eD(r){let e=x7(r),t=XN(e);return EDe(t)}function xDe(r){r=tD(r);let e=_De(r),t=vDe(e);return ZN(t)}function eie(r){return xDe(r)}function S7(r){let e=SDe(r);if(e!=null)throw e;return Uint8Array.from(r)}function SDe(r){try{x7(r)}catch(e){return e}}function tD(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function tie(r){return new Error("Error parsing address: "+r)}function A7(r){return hr(r[0])}var nD=C(Xo(),1);var nie=C(ee(),1);var l2=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},rD=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Gw,jw,Ww,rie,TDe=Symbol.for("nodejs.util.inspect.custom"),IDe=[hr("dns").code,hr("dns4").code,hr("dns6").code,hr("dnsaddr").code],iD=new Map,iie=Symbol.for("@multiformats/js-multiaddr/multiaddr");function oie(r,e){if(r==null)throw new Error("requires node address object");if(e==null)throw new Error("requires transport protocol");let t,n=r.address;switch(r.family){case 4:t="ip4";break;case 6:if(t="ip6",n.includes("%")){let i=n.split("%");if(i.length!==2)throw Error("Multiple ip6 zones in multiaddr");n=i[0],t=`/ip6zone/${i[1]}/ip6`}break;default:throw Error("Invalid addr family, should be 4 or 6.")}return new ru("/"+[t,n,e,r.port].join("/"))}function sie(r){return as(r)?r.protos().some(e=>e.resolvable):!1}function as(r){return!!(r!=null&&r[iie])}var ru=class{constructor(e){if(Gw.set(this,void 0),jw.set(this,void 0),Ww.set(this,void 0),this[rie]=!0,e==null&&(e=""),e instanceof Uint8Array)this.bytes=S7(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=eie(e)}else if(as(e))this.bytes=S7(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return l2(this,Gw,"f")==null&&rD(this,Gw,eD(this.bytes),"f"),l2(this,Gw,"f")}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="",s=hr("tcp"),a=hr("udp"),c=hr("ip4"),u=hr("ip6"),l=hr("dns6"),f=hr("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(o=`%${p??""}`),IDe.includes(d)&&(t=s.name,i=443,n=`${p??""}${o}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=hr(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=hr(d).name,n=`${p??""}${o}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},hr(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;ne.name)}tuples(){return l2(this,jw,"f")==null&&rD(this,jw,x7(this.bytes),"f"),l2(this,jw,"f")}stringTuples(){return l2(this,Ww,"f")==null&&rD(this,Ww,XN(this.tuples()),"f"),l2(this,Ww,"f")}encapsulate(e){return e=new ru(e),new ru(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new ru(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new ru(ZN(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===Hw.ipfs.code).pop();if((t==null?void 0:t[1])!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?Ee(tt.decode(`z${n}`),"base58btc"):Ee(ce.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){let e=null;try{e=this.stringTuples().filter(t=>hr(t[0]).path===!0)[0][1],e==null&&(e=null)}catch{e=null}return e}equals(e){return rr(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=iD.get(t.name);if(n==null)throw(0,nie.default)(new Error(`no available resolver for ${t.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new ru(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")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){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[(Gw=new WeakMap,jw=new WeakMap,Ww=new WeakMap,rie=iie,TDe)](){return`Multiaddr(${eD(this.bytes)})`}};function lt(r){return new ru(r)}oD.default.util.Long=void 0;oD.default.configure();async function RDe(r,e=()=>{}){e(0,"Storing each peerstore key under a single datastore key"),await r.datastore.open();let t={},n=[];for await(let{key:i,value:o}of r.datastore.query({prefix:"/peers"})){n.push(i);let s=i.toString(),[,a,c,u,l]=s.split("/");if(a==="peers"&&["protos","addrs","metadata","keys"].includes(c)&&u)if(t[u]=t[u]||{addresses:[],protocols:[],metadata:[]},c==="protos"){let f=KN.decode(o);t[u].protocols=f.protocols.sort()}else if(c==="addrs"){let f=qN.decode(o);t[u].addresses=f.addrs.sort((h,d)=>lt(h.multiaddr).toString().localeCompare(lt(d.multiaddr).toString())),f.certifiedRecord&&f.certifiedRecord.raw&&(t[u].peerRecordEnvelope=f.certifiedRecord.raw)}else c==="metadata"?t[u].metadata.push({key:l,value:o}):c==="keys"&&(t[u].pubKey=o)}e(33,"Read peer data from store");for(let i of n)await r.datastore.delete(i);e(66,"Removed existing peer data from store");for(let i of Object.keys(t)){let o=t[i];o.metadata=o.metadata.sort((a,c)=>a.key.localeCompare(c.key));let s=GN.encode(o).finish();await r.datastore.put(new pe(`/peers/${i}`),s)}await r.datastore.close(),e(100,"Stored each peerstore key under a single datastore key")}async function CDe(r,e=()=>{}){e(0,"Storing each peerstore key under a multiple datastore keys"),await r.datastore.open();let t={},n=[];for await(let{key:i,value:o}of r.datastore.query({prefix:"/peers"})){n.push(i);let s=i.toString(),[,,a]=s.split("/");t[a]=GN.decode(o)}e(33,"Read peer data from store");for(let i of n)await r.datastore.delete(i);e(66,"Removed existing peer data from store");for(let[i,o]of Object.entries(t)){if(o.protocols&&o.protocols.length>0&&await r.datastore.put(new pe(`/peers/protos/${i}`),KN.encode({protocols:o.protocols}).finish()),o.addresses&&o.addresses.length>0){let s=o.peerRecordEnvelope,a;if(s){let c=Bne.decode(s),u=Une.decode(c.payload);a={raw:s,seq:u.seq}}await r.datastore.put(new pe(`/peers/addrs/${i}`),qN.encode({addrs:o.addresses,certifiedRecord:a}).finish())}if(o.metadata&&o.metadata.length>0)for(let{key:s,value:a}of o.metadata)await r.datastore.put(new pe(`/peers/metadata/${i}/${s}`),a);o.pubKey&&await r.datastore.put(new pe(`/peers/keys/${i}`),o.pubKey)}await r.datastore.close(),e(100,"Stored each peerstore key under multiple datastore keys")}var aie={version:12,description:"Store each peerstore peer under a single datastore key",migrate:RDe,revert:CDe};var Ip={description:"Empty migration.",migrate:()=>{},revert:()=>{},empty:!0},T7=[Object.assign({version:1},Ip),Object.assign({version:2},Ip),Object.assign({version:3},Ip),Object.assign({version:4},Ip),Object.assign({version:5},Ip),Object.assign({version:6},Ip),Object.assign({version:7},Ip),wne,Ine,kne,Dne,aie];var cie=C($s(),1);var sD={};xe(sD,{InvalidValueError:()=>h2,MissingRepoOptionsError:()=>nu,NonReversibleMigrationError:()=>f2,NotInitializedRepoError:()=>xd,RequiredParameterError:()=>d2});var f2=class extends Error{constructor(e){super(e),this.name="NonReversibleMigrationError",this.code=f2.code,this.message=e}};f2.code="ERR_NON_REVERSIBLE_MIGRATION";var xd=class extends Error{constructor(e){super(e),this.name="NotInitializedRepoError",this.code=xd.code,this.message=e}};xd.code="ERR_NOT_INITIALIZED_REPO";var d2=class extends Error{constructor(e){super(e),this.name="RequiredParameterError",this.code=d2.code,this.message=e}};d2.code="ERR_REQUIRED_PARAMETER";var h2=class extends Error{constructor(e){super(e),this.name="InvalidValueError",this.code=h2.code,this.message=e}};h2.code="ERR_INVALID_VALUE";var nu=class extends Error{constructor(e){super(e),this.name="MissingRepoOptionsError",this.code=nu.code,this.message=e}};nu.code="ERR_MISSING_REPO_OPTIONS";var aD=(0,cie.default)("ipfs:repo:migrator:repo:init");async function uie(r){if(!r)throw new nu("Please pass repo options when trying to open a repo");let e=r.root;try{await e.open();let t=await e.has($w),n=await e.has(Rne);return!t||!n?(aD(`Version entry present: ${t}`),aD(`Config entry present: ${n}`),!1):!0}catch(t){return aD("While checking if repo is initialized error was thrown: "+t.message),!1}finally{if(e!==void 0)try{await e.close()}catch{}}}async function cD(r){if(!await uie(r))throw new xd("Repo is not initialized!");let e=r.root;await e.open();try{return parseInt(Ee(await e.get($w)))}finally{await e.close()}}async function Yw(r,e){if(!e)throw new nu("Please pass repo options when trying to open a repo");let t=e.root;await t.open(),await t.put($w,fe(String(r))),await t.close()}var lie=C($s(),1),Xa=(0,lie.default)("ipfs:repo:migrator");function kDe(r){return r=r||T7,!Array.isArray(r)||r.length===0?0:r[r.length-1].version}async function fie(r,e,t,n,i={}){let o=i.ignoreLock??!1,s=i.onProgress,a=i.isDryRun??!1,c=i.migrations??T7;if(!r)throw new Xs.RequiredParameterError("Path argument is required!");if(!t)throw new Xs.RequiredParameterError("repoOptions argument is required!");if(!n)throw new Xs.RequiredParameterError("toVersion argument is required!");if(!Number.isInteger(n)||n<=0)throw new Xs.InvalidValueError("Version has to be positive integer!");e=VN(e);let u=await cD(e);if(u===n){Xa("Nothing to migrate.");return}if(u>n)throw new Xs.InvalidValueError(`Current repo's version (${u}) is higher then toVersion (${n}), you probably wanted to revert it?`);hie(c,u,n);let l;!a&&!o&&(l=await t.repoLock.lock(r));try{for(let f of c){if(n!==void 0&&f.version>n)break;if(!(f.version<=u)){Xa(`Migrating version ${f.version}`);try{if(!a){let h=()=>{};s&&(h=(d,p)=>s(f.version,d.toFixed(2),p)),await f.migrate(e,h)}}catch(h){let d=f.version-1;throw Xa(`An exception was raised during execution of migration. Setting the repo's version to last successfully migrated version: ${d}`),await Yw(d,e),new Error(`During migration to version ${f.version} exception was raised: ${h.stack||h.message||h}`)}Xa(`Migrating to version ${f.version} finished`)}}a||await Yw(n||kDe(c),e),Xa("Repo successfully migrated",n!==void 0?`to version ${n}!`:"to latest version!")}finally{!a&&!o&&l&&await l.close()}}async function die(r,e,t,n,i={}){let o=i.ignoreLock??!1,s=i.onProgress,a=i.isDryRun??!1,c=i.migrations??T7;if(!r)throw new Xs.RequiredParameterError("Path argument is required!");if(!t)throw new Xs.RequiredParameterError("repoOptions argument is required!");if(!n)throw new Xs.RequiredParameterError("When reverting migrations, you have to specify to which version to revert!");if(!Number.isInteger(n)||n<=0)throw new Xs.InvalidValueError("Version has to be positive integer!");e=VN(e);let u=await cD(e);if(u===n){Xa("Nothing to revert.");return}if(uu)){Xa(`Reverting migration version ${h.version}`);try{if(!a){let d=()=>{};s&&(d=(p,g)=>s(h.version,p.toFixed(2),g)),await h.revert(e,d)}}catch(d){let p=h.version;throw Xa(`An exception was raised during execution of migration. Setting the repo's version to last successfully reverted version: ${p}`),await Yw(p,e),d.message=`During reversion to version ${h.version} exception was raised: ${d.message}`,d}Xa(`Reverting to version ${h.version} finished`)}}a||await Yw(n,e),Xa(`All migrations successfully reverted to version ${n}!`)}finally{!a&&!o&&l&&await l.close()}}function hie(r,e,t,n=!1){let i=0;for(let o of r){if(o.version>t)break;if(o.version>e){if(n&&!o.revert)throw new Xs.NonReversibleMigrationError(`It is not possible to revert to version ${e} because migration version ${o.version} is not reversible. Cancelling reversion.`);i++}}if(i!==t-e)throw new Xs.InvalidValueError(`The ipfs-repo-migrations package does not have all migration to migrate from version ${e} to ${t}`)}var Xs=sD;var jie=C(gie(),1);var _ie=C($s(),1);var Rp=class extends Error{constructor(e){super(e),this.name="LockExistsError",this.code=Rp.code}};Rp.code="ERR_LOCK_EXISTS";var cs=class extends Error{constructor(e){super(e),this.name="NotFoundError",this.code=cs.code}};cs.code="ERR_NOT_FOUND";var Cp=class extends Error{constructor(e){super(e),this.name="InvalidRepoVersionError",this.code=Cp.code}};Cp.code="ERR_INVALID_REPO_VERSION";var Pp="ERR_REPO_NOT_INITIALIZED",yie="ERR_REPO_ALREADY_OPEN",wie="ERR_REPO_ALREADY_CLOSED";async function R7(r,e,t){let n=await e(r);if(n)return n;let i=bie(t);return i?new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{o(!!a.result)}}):!1}async function C7(r,e,t,n){if(await t(r))return e(r);let i=bie(n);if(!i)throw new cs;return new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{if(a.result)return o(a.result);s(new cs)}})}function bie(r){let e=r;for(;e.db||e.child;)if(e=e.db||e.child,e.type==="level-js"||e.constructor.name==="Level")return e}var UDe=(0,_ie.default)("ipfs:repo:version"),uD=new pe("version");function Eie(r){return{async exists(){return R7(uD,r.has.bind(r),r)},async get(){let e=await C7(uD,r.get.bind(r),r.has.bind(r),r);return parseInt(Ee(e),10)},set(e){return r.put(uD,fe(String(e)))},async check(e){let t=await this.get();return UDe("comparing version: %s and %s",t,e),t===e||(t===6&&e===7||e===6&&t===7)}}}var P7=C(ee(),1);var FDe=Hs.default?Hs.default:Hs,lD=new pe("config");function vie(r){let e=new FDe({concurrency:1}),t={async getAll(o={}){let s=await C7(lD,r.get.bind(r),r.has.bind(r),r);return JSON.parse(Ee(s))},async get(o,s={}){if(o==null)throw new cs(`Key ${o} does not exist in config`);let a=await this.getAll(s),c=zw(a,o);if(c===void 0)throw new cs(`Key ${o} does not exist in config`);return c},set(o,s,a={}){if(typeof o!="string"&&!(o instanceof String))throw(0,P7.default)(new Error("Invalid key type: "+typeof o),"ERR_INVALID_KEY");if(s===void 0||s instanceof Uint8Array)throw(0,P7.default)(new Error("Invalid value type: "+typeof s),"ERR_INVALID_VALUE");return e.add(()=>n({key:o,value:s},a.signal))},replace(o,s={}){if(!o||o instanceof Uint8Array)throw(0,P7.default)(new Error("Invalid value type: "+typeof o),"ERR_INVALID_VALUE");return e.add(()=>n({key:void 0,value:o},s.signal))},async exists(){return R7(lD,r.has.bind(r),r)}};return t;async function n(o,s){if(s&&s.aborted)return;let a=o.key,c=o.value;if(a){let u=await t.getAll();return typeof u=="object"&&u!==null&&$r(u,a,c),i(u)}return i(c)}function i(o){let s=fe(JSON.stringify(o,null,2));return r.put(lD,s)}}function Qw(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}function fD(r,e={}){if(!Qw(r)&&!Array.isArray(r))throw new TypeError("Expected a plain object or array");let{deep:t,compare:n}=e,i=[],o=[],s=c=>{let u=i.indexOf(c);if(u!==-1)return o[u];let l=[];return i.push(c),o.push(l),l.push(...c.map(f=>Array.isArray(f)?s(f):Qw(f)?a(f):f)),l},a=c=>{let u=i.indexOf(c);if(u!==-1)return o[u];let l={},f=Object.keys(c).sort(n);i.push(c),o.push(l);for(let h of f){let d=c[h],p;t&&Array.isArray(d)?p=s(d):p=t&&Qw(d)?a(d):d,Object.defineProperty(l,h,{...Object.getOwnPropertyDescriptor(c,h),value:p})}return l};return Array.isArray(r)?t?s(r):r.slice():a(r)}var dD=new pe("datastore_spec");function xie(r){return{exists(){return r.has(dD)},async get(){let e=await r.get(dD);return JSON.parse(Ee(e))},async set(e){return r.put(dD,fe(JSON.stringify(fD(e,{deep:!0}))))}}}var hD=new pe("api");function Sie(r){return{async get(){let e=await r.get(hD);return e&&e.toString()},set(e){return r.put(hD,fe(e.toString()))},delete(){return r.delete(hD)}}}var Aie=C(ee(),1);function Tie(r){return{open(){return r.open()},close(){return r.close()},query(e,t){return r.query(e,t)},queryKeys(e,t){return r.queryKeys(e,t)},async get(e,t){let n=Ad(e);return n.isIdentity?Promise.resolve(n.digest):r.get(e,t)},async*getMany(e,t){for await(let n of e)yield this.get(n,t)},async put(e,t,n){let{isIdentity:i}=Ad(e);i||await r.put(e,t,n)},async*putMany(e,t){let n=jn({objectMode:!0});(globalThis.process&&globalThis.process.nextTick?globalThis.process.nextTick:globalThis.setImmediate||globalThis.setTimeout)(async()=>{try{await on(r.putMany(async function*(){for await(let{key:o,value:s}of e)Ad(o).isIdentity||(yield{key:o,value:s}),n.push({key:o,value:s})}())),n.end()}catch(o){n.end(o)}}),yield*n},has(e,t){let{isIdentity:n}=Ad(e);return n?Promise.resolve(!0):r.has(e,t)},delete(e,t){let{isIdentity:n}=Ad(e);return n?Promise.resolve():r.delete(e,t)},deleteMany(e,t){return r.deleteMany(Yt(e,n=>!Ad(n).isIdentity),t)},batch(){let e=r.batch();return{put(t,n){let{isIdentity:i}=Ad(t);i||e.put(t,n)},delete(t){let{isIdentity:n}=Ad(t);n||e.delete(t)},commit:t=>e.commit(t)}}}}function Ad(r){let e=ce.asCID(r);if(e==null)throw(0,Aie.default)(new Error("Not a valid cid"),"ERR_INVALID_CID");return e.multihash.code!==Ns.code?{isIdentity:!1}:{isIdentity:!0,digest:e.multihash.digest}}var Iie=C($s(),1),Rie=(0,Iie.default)("ipfs:repo:lock:memory"),Cie="repo.lock",Xw={};async function zDe(r){let e=r+"/"+Cie;if(Rie("locking %s",e),Xw[e]===!0)throw new Rp(`Lock already being held for file: ${e}`);return Xw[e]=!0,{async close(){Xw[e]&&delete Xw[e]}}}async function VDe(r){let e=r+"/"+Cie;return Rie(`checking lock: ${e}`),!!Xw[e]}var k7={lock:zDe,locked:VDe};var Pie={autoMigrate:!0,onMigrationProgress:()=>{},repoOwner:!0,repoLock:k7};var pD={Spec:{type:"mount",mounts:[{mountpoint:"/blocks",type:"measure",prefix:"flatfs.datastore",child:{type:"flatfs",path:"blocks",sync:!0,shardFunc:"/repo/flatfs/shard/v1/next-to-last/2"}},{mountpoint:"/",type:"measure",prefix:"leveldb.datastore",child:{type:"levelds",path:"datastore",compression:"none"}}]}};var Die=C(ee(),1),Oie=C($s(),1);async function Fi(r){for await(let e of r)return e}function N7({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*KDe(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=ce.asCID(n);o?yield[i.join("/"),o]:typeof n=="object"&&(yield*mD(n,i))}else{let t=ce.asCID(e);t?yield[r.join("/"),t]:yield*mD(e,r)}}function*mD(r,e){if(r==null||r instanceof Uint8Array)return;let t=ce.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*KDe(o,i)}}function*$De(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!ce.asCID(n)&&(yield*gD(n,i))}else yield*gD(e,r)}function*gD(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!ce.asCID(n)&&(yield*$De(i,n))}}function qDe(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=ce.asCID(t);if(o)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var yD=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:N7(),bytes:N7(),value:N7(),asBlock:N7()})}links(){return mD(this.value,[])}tree(){return gD(this.value,[])}get(e="/"){return qDe(this.value,e.split("/").filter(Boolean))}};function D7({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n&&n.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new yD({cid:e,bytes:r,value:i})}var kie=C(ee(),1);function Zw(r){let e=ce.asCID(r);if(e==null)throw(0,kie.default)(new Error("Not a valid cid"),"ERR_INVALID_CID");let t=Ot.encode(e.multihash.bytes);return new pe("/"+t.slice(1).toUpperCase(),!1)}function wD(r){return Jn(Ot.decode(`b${r.toString().toLowerCase().substring(1)}`))}var Nie=C($s(),1);var HDe=(0,Nie.default)("ipfs:repo:utils:walk-dag");async function*p2(r,e,t,n){try{let i=await e.get(r,n),o=await t(r.code),s=D7({bytes:i,cid:r,codec:o});for(let[,a]of s.links())yield a,yield*p2(a,e,t,n)}catch(i){throw HDe("Could not walk DAG for CID",r.toString(),i),i}}var Jw=class extends Map{constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=e.maxSize,this.maxAge=e.maxAge||Number.POSITIVE_INFINITY,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(e){if(typeof this.onEviction=="function")for(let[t,n]of e)this.onEviction(t,n.value)}_deleteIfExpired(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(e,t.value),this.delete(e)):!1}_getOrDeleteIfExpired(e,t){if(this._deleteIfExpired(e,t)===!1)return t.value}_getItemValue(e,t){return t.expiry?this._getOrDeleteIfExpired(e,t):t.value}_peek(e,t){let n=t.get(e);return this._getItemValue(e,n)}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(e,t){this.oldCache.delete(e),this._set(e,t)}*_entriesAscending(){for(let e of this.oldCache){let[t,n]=e;this.cache.has(t)||this._deleteIfExpired(t,n)===!1&&(yield e)}for(let e of this.cache){let[t,n]=e;this._deleteIfExpired(t,n)===!1&&(yield e)}}get(e){if(this.cache.has(e)){let t=this.cache.get(e);return this._getItemValue(e,t)}if(this.oldCache.has(e)){let t=this.oldCache.get(e);if(this._deleteIfExpired(e,t)===!1)return this._moveToRecent(e,t),t.value}}set(e,t,{maxAge:n=this.maxAge}={}){let i=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;this.cache.has(e)?this.cache.set(e,{value:t,expiry:i}):this._set(e,{value:t,expiry:i})}has(e){return this.cache.has(e)?!this._deleteIfExpired(e,this.cache.get(e)):this.oldCache.has(e)?!this._deleteIfExpired(e,this.oldCache.get(e)):!1}peek(e){if(this.cache.has(e))return this._peek(e,this.cache);if(this.oldCache.has(e))return this._peek(e,this.oldCache)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this._entriesAscending()],n=t.length-e;n<0?(this.cache=new Map(t),this.oldCache=new Map,this._size=t.length):(n>0&&this._emitEvictions(t.slice(0,n)),this.oldCache=new Map(t.slice(n)),this.cache=new Map,this._size=0),this.maxSize=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache){let[t,n]=e;this._deleteIfExpired(t,n)===!1&&(yield[t,n.value])}for(let e of this.oldCache){let[t,n]=e;this.cache.has(t)||this._deleteIfExpired(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.cache];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this._deleteIfExpired(i,o)===!1&&(yield[i,o.value])}e=[...this.oldCache];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.cache.has(i)||this._deleteIfExpired(i,o)===!1&&(yield[i,o.value])}}*entriesAscending(){for(let[e,t]of this._entriesAscending())yield[e,t.value]}get size(){if(!this._size)return this.oldCache.size;let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,i]of this.entriesAscending())e.call(t,i,n,this)}get[Symbol.toStringTag](){return JSON.stringify([...this.entriesAscending()])}};var GDe=2048;function jDe(r){let e=`Invalid type '${r}', must be one of {direct, indirect, recursive, all}`;return(0,Die.default)(new Error(e),"ERR_INVALID_PIN_TYPE")}var O7=class{constructor({pinstore:e,blockstore:t,loadCodec:n}){this.pinstore=e,this.blockstore=t,this.loadCodec=n,this.log=(0,Oie.default)("ipfs:repo:pin"),this.directPins=new Set,this.recursivePins=new Set}async pinDirectly(e,t={}){await this.blockstore.get(e,t);let n={depth:0};return e.version!==0&&(n.version=e.version),e.code!==Zo&&(n.codec=e.code),t.metadata&&(n.metadata=t.metadata),this.pinstore.put(Zw(e),zu(n))}unpin(e,t){return this.pinstore.delete(Zw(e),t)}async pinRecursively(e,t={}){await this.fetchCompleteDag(e,t);let n={depth:1/0};e.version!==0&&(n.version=e.version),e.code!==Zo&&(n.codec=e.code),t.metadata&&(n.metadata=t.metadata),await this.pinstore.put(Zw(e),zu(n))}async*directKeys(e){for await(let t of this.pinstore.query({filters:[n=>ks(n.value).depth===0]})){let n=ks(t.value),i=n.version||0,o=n.codec!=null?n.codec:Zo,s=wD(t.key);yield{cid:ce.create(i,o,s),metadata:n.metadata}}}async*recursiveKeys(e){for await(let t of this.pinstore.query({filters:[n=>ks(n.value).depth===1/0]})){let n=ks(t.value),i=n.version||0,o=n.codec!=null?n.codec:Zo,s=wD(t.key);yield{cid:ce.create(i,o,s),metadata:n.metadata}}}async*indirectKeys(e){for await(let{cid:t}of this.recursiveKeys())for await(let n of p2(t,this.blockstore,this.loadCodec,e)){let i=[Pt.recursive];(await this.isPinnedWithType(n,i)).pinned||(yield n)}}async isPinnedWithType(e,t,n){Array.isArray(t)||(t=[t]);let i=t.includes(Pt.all),o=t.includes(Pt.direct),s=t.includes(Pt.recursive),a=t.includes(Pt.indirect);if(s||o||i){let l=await Fi(this.pinstore.query({prefix:Zw(e).toString(),filters:[f=>{if(i)return!0;let h=ks(f.value);return t.includes(h.depth===0?Pt.direct:Pt.recursive)}],limit:1}));if(l){let f=ks(l.value);return{cid:e,pinned:!0,reason:f.depth===0?Pt.direct:Pt.recursive,metadata:f.metadata}}}let c=this;async function*u(l,f){for await(let{cid:h}of f)for await(let d of p2(h,c.blockstore,c.loadCodec))if(d.equals(l)){yield h;return}}if(i||a){let l=await Fi(u(e,this.recursiveKeys()));if(l)return{cid:e,pinned:!0,reason:Pt.indirect,parent:l}}return{cid:e,pinned:!1}}async fetchCompleteDag(e,t={}){let n=new Jw({maxSize:t.cidCacheMaxSize??GDe}),i=async(o,s)=>{if(n.has(o.toString()))return;n.set(o.toString(),!0);let a=await this.blockstore.get(o,s),c=await this.loadCodec(o.code),u=D7({bytes:a,cid:o,codec:c});await Promise.all([...u.links()].map(([,l])=>i(l,s)))};await i(e,t)}static checkPinType(e){if(typeof e!="string"||!Object.keys(Pt).includes(e))throw jDe(e);return!0}};var Bie=C(ee(),1);function Mie(r,e){return{open(){return e.open()},close(){return e.close()},query(t,n){return e.query(t,n)},queryKeys(t,n){return e.queryKeys(t,n)},async get(t,n){return e.get(t,n)},async*getMany(t,n){yield*e.getMany(t,n)},async put(t,n,i){await e.put(t,n,i)},async*putMany(t,n){yield*e.putMany(t,n)},has(t,n){return e.has(t,n)},async delete(t,n){return await Lie(t,r),e.delete(t,n)},deleteMany(t,n){return e.deleteMany(Bi(t,async i=>(await Lie(i,r),i)),n)},batch(){return e.batch()}}}async function Lie(r,e){let{pinned:t,reason:n}=await e.isPinnedWithType(r,Pt.all);if(t)throw(0,Bie.default)(new Error(`pinned: ${n}`),"ERR_BLOCK_PINNED")}var bD=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},_D=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Uie=r=>globalThis.DOMException===void 0?new _D(r):new DOMException(r),Fie=r=>{let e=r.reason===void 0?Uie("This operation was aborted."):r.reason;return e instanceof Error?e:Uie(e)};function ED(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,a=new Promise((c,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:f}=e;f.aborted&&u(Fie(f)),f.addEventListener("abort",()=>{u(Fie(f))})}let l=new bD;s=o.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(f){u(f)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${t} milliseconds`,u(l))},t),(async()=>{try{c(await r)}catch(f){u(f)}finally{o.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},a}var vD="lock:worker:request-read",xD="lock:worker:release-read",SD="lock:master:grant-read",AD="lock:worker:request-write",TD="lock:worker:release-write",ID="lock:master:grant-write";var zie=(r,e,t,n,i)=>(o,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},Vie=(r,e,t,n)=>async()=>{let i=k1();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",s)})},WDe={singleProcess:!1},Kie=r=>{if(r=Object.assign({},WDe,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Xm.addEventListener("message",zie(t,"requestReadLock",vD,xD,SD)),Xm.addEventListener("message",zie(t,"requestWriteLock",AD,TD,ID)),t}return{isWorker:!0,readLock:t=>Vie(t,vD,SD,xD),writeLock:t=>Vie(t,AD,ID,TD)}};var kp={},Td;async function RD(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await ED((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var YDe=(r,e)=>{if(Td.isWorker===!0)return{readLock:Td.readLock(r,e),writeLock:Td.writeLock(r,e)};let t=new Hs({concurrency:1}),n;return{async readLock(){if(n!=null)return await RD(n,e);n=new Hs({concurrency:e.concurrency,autoStart:!1});let i=n,o=RD(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await RD(t,e)}}},QDe={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function e5(r){let e=Object.assign({},QDe,r);return Td==null&&(Td=Kie(e),Td.isWorker!==!0&&(Td.addEventListener("requestReadLock",t=>{kp[t.data.name]!=null&&kp[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),Td.addEventListener("requestWriteLock",async t=>{kp[t.data.name]!=null&&kp[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),kp[e.name]==null&&(kp[e.name]=YDe(e.name,e)),kp[e.name]}var $ie=C($s(),1);async function*CD(r,e=1){let t=[];e<1&&(e=1);for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}async function*PD(r,e=1){for await(let t of CD(r,e)){let n=t.map(async i=>await i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;ia),r.indirectKeys(),Bi(r.directKeys(),({cid:a})=>a),i),s=new Set;for await(let a of Qo(o,i))s.add(Ot.encode(a.multihash.bytes));return s}async function*tOe({blockstore:r},e,t){let n=0,i=0;yield*Ne(PD(Bi(t,async s=>async function(){n++;try{let c=Ot.encode(s.multihash.bytes);if(e.has(c))return null;try{await r.delete(s),i++}catch(u){return{err:new Error(`Could not delete block with CID ${s}: ${u.message}`)}}return{cid:s}}catch(c){let u=`Could delete block with CID ${s}`;return t5(u,c),{err:new Error(u+`: ${c.message}`)}}}),ZDe),s=>Yt(s,Boolean)),t5(`Marked set has ${e.size} unique blocks. Blockstore has ${n} blocks. Deleted ${i} blocks.`)}var Eo=(0,Gie.default)("ipfs:repo"),rOe=Number.MAX_SAFE_INTEGER,nOe="repoAutoMigrate",kD=class{constructor(e,t,n,i){if(typeof e!="string")throw new Error("missing repo path");if(typeof t!="function")throw new Error("missing codec loader");this.options=et(Pie,i),this.closed=!0,this.path=e,this.root=n.root,this.datastore=n.datastore,this.keys=n.keys;let o=n.blocks,s=n.pins;this.pins=new O7({pinstore:s,blockstore:o,loadCodec:t});let a=Mie(this.pins,o);this.blocks=Tie(a),this.version=Eie(this.root),this.config=vie(this.root),this.spec=xie(this.root),this.apiAddr=Sie(this.root),this.gcLock=e5({name:e,singleProcess:this.options.repoOwner!==!1}),this.gc=qie({gcLock:this.gcLock,pins:this.pins,blockstore:this.blocks,root:this.root,loadCodec:t})}async init(e){Eo("initializing at: %s",this.path),await this._openRoot(),await this.config.replace(iOe(e)),await this.spec.set(oOe(e)),await this.version.set(12)}async isInitialized(){if(!this.closed)return!0;try{return await this._openRoot(),await this._checkInitialized(),await this.root.close(),!0}catch{return!1}}async open(){if(!this.closed)throw(0,Np.default)(new Error("repo is already open"),yie);Eo("opening at: %s",this.path);try{if(await this._openRoot(),await this._checkInitialized(),this._lockfile=await this._openLock(),Eo("acquired repo.lock"),!await this.version.check(12))if(await this._isAutoMigrationEnabled())await this._migrate(12,{root:this.root,datastore:this.datastore,pins:this.pins.pinstore,blocks:this.pins.blockstore,keys:this.keys});else throw new Cp("Incompatible repo versions. Automatic migrations disabled. Please migrate the repo manually.");Eo("creating datastore"),await this.datastore.open(),Eo("creating blocks"),await this.blocks.open(),Eo("creating keystore"),await this.keys.open(),Eo("creating pins"),await this.pins.pinstore.open(),this.closed=!1,Eo("all opened")}catch(e){if(this._lockfile)try{await this._closeLock(),this._lockfile=null}catch(t){Eo("error removing lock",t)}throw e}}async _openRoot(){try{await this.root.open()}catch(e){if(e.message!=="Already open")throw e}}async _openLock(){let e=await this.options.repoLock.lock(this.path);if(typeof e.close!="function")throw(0,Np.default)(new Error("Locks must have a close method"),"ERR_NO_CLOSE_FUNCTION");return e}_closeLock(){return this._lockfile&&this._lockfile.close()}async _checkInitialized(){Eo("init check");let e;try{[e]=await Promise.all([this.config.exists(),this.spec.exists(),this.version.exists()])}catch(t){throw t.code==="ERR_NOT_FOUND"?(0,Np.default)(new Error("repo is not initialized yet"),Pp,{path:this.path}):t}if(!e)throw(0,Np.default)(new Error("repo is not initialized yet"),Pp,{path:this.path})}async close(){if(this.closed)throw(0,Np.default)(new Error("repo is already closed"),wie);Eo("closing at: %s",this.path);try{await this.apiAddr.delete()}catch(e){if(e.code!==Pp&&!e.message.startsWith("ENOENT"))throw e}await Promise.all([this.root,this.blocks,this.keys,this.datastore,this.pins.pinstore].map(e=>e&&e.close())),Eo("unlocking"),this.closed=!0,await this._closeLock()}exists(){return this.version.exists()}async stat(){if(this.datastore&&this.keys){let[e,t,n,i,o]=await Promise.all([this._storageMaxStat(),this._blockStat(),this.version.get(),Hie(this.datastore),Hie(this.keys)]),s=t.size+i+o;return{repoPath:this.path,storageMax:e,version:n,numObjects:t.count,repoSize:s}}throw(0,Np.default)(new Error("repo is not initialized yet"),Pp,{path:this.path})}async _isAutoMigrationEnabled(){if(this.options.autoMigrate!==void 0)return this.options.autoMigrate;let e;try{e=await this.config.get(nOe)}catch(t){if(t.code===cs.code)e=!0;else throw t}return e}async _migrate(e,t){return await this.version.get()>e?(Eo(`reverting to version ${e}`),die(this.path,t,this.options,e,{ignoreLock:!0,onProgress:this.options.onMigrationProgress})):(Eo(`migrating to version ${e}`),fie(this.path,t,this.options,e,{ignoreLock:!0,onProgress:this.options.onMigrationProgress}))}async _storageMaxStat(){try{let e=await this.config.get("Datastore.StorageMax");return BigInt((0,jie.default)(e))}catch{return BigInt(rOe)}}async _blockStat(){let e=BigInt(0),t=BigInt(0);if(this.blocks)for await(let{key:n,value:i}of this.blocks.query({}))e+=BigInt(1),t+=BigInt(i.byteLength),t+=BigInt(n.bytes.byteLength);return{count:e,size:t}}};async function Hie(r){let e=BigInt(0);for await(let t of r.query({}))e+=BigInt(t.value.byteLength),e+=BigInt(t.key.uint8Array().byteLength);return e}function Wie(r,e,t,n){return new kD(r,e,t,n)}function iOe(r){return r.Datastore=Object.assign({},pD,zw(r,"datastore")),r}function oOe(r){let e={...pD.Spec,...zw(r,"Datastore.Spec")};return{type:e.type,mounts:e.mounts.map(t=>({mountpoint:t.mountpoint,type:t.child.type,path:t.child.path,shardFunc:t.child.shardFunc}))}}async function*Id(r,e){yield*(await Wo(r)).sort(e)}var Rse=C(Ise(),1),Ud=class extends go{constructor(e,t={}){super(),this.db=typeof e=="string"?new Rse.Level(e,{...t,keyEncoding:"utf8",valueEncoding:"view"}):e,this.opts={createIfMissing:!0,compression:!1,...t}}async open(){try{await this.db.open(this.opts)}catch(e){throw Vo.dbOpenFailedError(e)}}async put(e,t){try{await this.db.put(e.toString(),t)}catch(n){throw Vo.dbWriteFailedError(n)}}async get(e){let t;try{t=await this.db.get(e.toString())}catch(n){throw n.notFound?Vo.notFoundError(n):Vo.dbWriteFailedError(n)}return t}async has(e){try{await this.db.get(e.toString())}catch(t){if(t.notFound)return!1;throw t}return!0}async delete(e){try{await this.db.del(e.toString())}catch(t){throw Vo.dbDeleteFailedError(t)}}close(){return this.db&&this.db.close()}batch(){let e=[];return{put:(t,n)=>{e.push({type:"put",key:t.toString(),value:n})},delete:t=>{e.push({type:"del",key:t.toString()})},commit:()=>this.db.batch(e)}}query(e){let t=this._query({values:!0,prefix:e.prefix});Array.isArray(e.filters)&&(t=e.filters.reduce((o,s)=>Yt(o,s),t)),Array.isArray(e.orders)&&(t=e.orders.reduce((o,s)=>Id(o,s),t));let{offset:n,limit:i}=e;if(n){let o=0;t=Yt(t,()=>o++>=n)}return i&&(t=Ga(t,i)),t}queryKeys(e){let t=Bi(this._query({values:!1,prefix:e.prefix}),({key:o})=>o);Array.isArray(e.filters)&&(t=e.filters.reduce((o,s)=>Yt(o,s),t)),Array.isArray(e.orders)&&(t=e.orders.reduce((o,s)=>Id(o,s),t));let{offset:n,limit:i}=e;if(n){let o=0;t=Yt(t,()=>o++>=n)}return i&&(t=Ga(t,i)),t}_query(e){let t={keys:!0,keyEncoding:"buffer",values:e.values};if(e.prefix!=null){let i=e.prefix.toString();t.gte=i,t.lt=i+"\xFF"}let n=this.db.iterator(t);if(n[Symbol.asyncIterator])return $Le(n);if(n.next!=null&&n.end!=null)return qLe(n);throw new Error("Level returned incompatible iterator")}};async function*$Le(r){for await(let[e,t]of r)yield{key:new pe(e,!1),value:t};await r.close()}function qLe(r){return{[Symbol.asyncIterator](){return{next:()=>new Promise((e,t)=>{r.next((n,i,o)=>{if(n)return t(n);if(i==null)return r.end(s=>{if(s)return t(s);e({done:!0,value:void 0})});e({done:!1,value:{key:new pe(i,!1),value:o}})})}),return:()=>new Promise((e,t)=>{r.end(n=>{if(n)return t(n);e({done:!0,value:void 0})})})}}}}var Pse=C(ee(),1);var Cse=(r,e)=>async function*(){yield*(await Wo(r)).sort(e)}(),uu=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,t,n){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(let{key:n,value:i}of e)await this.put(n,i,t),yield{key:n,value:i}}async*getMany(e,t={}){for await(let n of e)yield this.get(n,t)}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await on(this.putMany(e,n)),e=[],await on(this.deleteMany(t,n)),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 n=this._all(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.key.toString().startsWith(e.prefix||""))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cse(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=(e.offset||0))}return e.limit!=null&&(n=Ga(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.toString().startsWith(e.prefix||""))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cse(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=e.offset)}return e.limit!=null&&(n=Ga(n,e.limit)),n}};function P2(r){let e=ce.asCID(r);if(!e)throw(0,Pse.default)(new Error("Not a valid cid"),"ERR_INVALID_CID");return new pe("/"+Ot.encode(e.multihash.bytes).slice(1).toUpperCase(),!1)}function Fd(r){return ce.createV1(Sc,Jn(Ot.decode("b"+r.toString().slice(1).toLowerCase())))}function DO(r){let e=r.substring(0,1);if(e==="/")return DO(r.substring(1));let t;e.toLowerCase()==="b"?t=o=>Ot.decode(o.toLowerCase()).subarray(2):e.toLowerCase()==="c"?t=o=>kT.decode(o.toLowerCase()).subarray(2):e==="z"?t=o=>tt.decode(o).subarray(2):e==="Q"?t=o=>tt.decode("z"+o):t=o=>Ot.decode("b"+o.toLowerCase()).subarray(2);let n;for(let o=1;ot=>e({key:Fd(t.key),value:t.value})):void 0,orders:r.orders?r.orders.map(e=>(t,n)=>e({key:Fd(t.key),value:t.value},{key:Fd(n.key),value:n.value})):void 0}}function GLe(r){return{...r,prefix:r.prefix?DO(r.prefix):void 0,filters:r.filters?r.filters.map(e=>t=>e(Fd(t))):void 0,orders:r.orders?r.orders.map(e=>(t,n)=>e(Fd(t),Fd(n))):void 0}}var fv=class extends uu{constructor(e){super(),this.child=e}open(){return this.child.open()}close(){return this.child.close()}async*query(e,t){for await(let{key:n,value:i}of this.child.query(HLe(e),t))yield{key:Fd(n),value:i}}async*queryKeys(e,t){for await(let n of this.child.queryKeys(GLe(e),t))yield Fd(n)}async get(e,t){return this.child.get(P2(e),t)}async*getMany(e,t){for await(let n of e)yield this.get(n,t)}async put(e,t,n){await this.child.put(P2(e),t,n)}async*putMany(e,t){let n=jn({objectMode:!0});(globalThis.process&&globalThis.process.nextTick?globalThis.process.nextTick:globalThis.setImmediate||globalThis.setTimeout)(async()=>{try{let o=this.child;await on(this.child.putMany(async function*(){for await(let s of e){let a=P2(s.key);await o.has(a,t)||(yield{key:a,value:s.value}),n.push(s)}}())),n.end()}catch(o){n.end(o)}}),yield*n}has(e,t){return this.child.has(P2(e),t)}delete(e,t){return this.child.delete(P2(e),t)}deleteMany(e,t){let n=jn({objectMode:!0});return on(this.child.deleteMany(async function*(){for await(let i of e)yield P2(i),n.push(i);n.end()}(),t)).catch(i=>{n.end(i)}),n}};function kse(r,e,t){let n=t.path||"ipfs";return Wie(n,i=>e.getCodec(i),{root:new Ud(n,{prefix:"",version:2}),blocks:new fv(new Ud(`${n}/blocks`,{prefix:"",version:2})),datastore:new Ud(`${n}/datastore`,{prefix:"",version:2}),keys:new Ud(`${n}/keys`,{prefix:"",version:2}),pins:new Ud(`${n}/pins`,{prefix:"",version:2})},{autoMigrate:t.autoMigrate,onMigrationProgress:t.onMigrationProgress||r,repoLock:k7})}var lr=C(v_(),1);var Ige=C(ee(),1);function dv(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var Nse=4294967296,Vi=class{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new Vi(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new Vi(t,n)}toBytes(e,t=0){let n=dv(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new Vi;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>Nse&&(i=0,++n>Nse&&(n=0))),new Vi(n,i)}static fromNumber(e){if(e===0)return new Vi;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Vi(i,n)}static fromBytes(e,t=0){let n=dv(e),i=new Vi,o=0;if(e.length-t>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(t)&127)<>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;o=0}else for(;o<4;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;o<5;++o)if(i.hi=(i.hi|(n.get(t)&127)<>>0,n.get(t++)<128)return i}else if(t=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var jLe=Math.pow(2,7),WLe=Math.pow(2,14),YLe=Math.pow(2,21),QLe=Math.pow(2,28),XLe=Math.pow(2,35),ZLe=Math.pow(2,42),JLe=Math.pow(2,49),eBe=Math.pow(2,56),tBe=Math.pow(2,63),Yp={encodingLength(r){return rNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=vf(Yp.encodingLength(r))),Vi.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return Vi.fromBytes(r,e).toNumber(!0)}};var Dse={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var S5;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(S5||(S5={}));var A5=class{constructor(e){B(this,"peerId");B(this,"payloadType");B(this,"payload");B(this,"signature");B(this,"marshaled");let{peerId:t,payloadType:n,payload:i,signature:o}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=S5.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return mt(this.marshal(),e.marshal())}async validate(e){let t=Ose(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Bs(this.peerId.publicKey).verify(t.subarray(),this.signature)}},zd=A5;B(zd,"createFromProtobuf",async e=>{let t=S5.decode(e),n=await Hn(t.publicKey);return new A5({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})}),B(zd,"seal",async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,i=e.codec,o=e.marshal(),s=Ose(n,i,o),c=await(await Li(t.privateKey)).sign(s.subarray());return new A5({peerId:t,payloadType:i,payload:o,signature:c})}),B(zd,"openAndCertify",async(e,t)=>{let n=await A5.createFromProtobuf(e);if(!await n.validate(t))throw new J("envelope signature is not valid for the given domain",Dse.ERR_SIGNATURE_NOT_VALID);return n});var Ose=(r,e,t)=>{let n=Ie(r),i=Yp.encode(n.byteLength),o=Yp.encode(e.length),s=Yp.encode(t.length);return new vt(i,n,o,e,s,t)};var rBe=Uint8Array.from([3,1]);var OO;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=kn((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>Pn(o,n.codec()),n.decode=o=>Cn(o,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=kn((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),t),r.encode=n=>Pn(n,r.codec()),r.decode=n=>Cn(n,r.codec())})(OO||(OO={}));var LO=Symbol.for("@libp2p/topology");var Lse=()=>{},nBe,BO=class{constructor(e){B(this,"min");B(this,"max");B(this,"peers");B(this,"onConnect");B(this,"onDisconnect");B(this,"registrar");B(this,nBe,!0);this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??Lse,this.onDisconnect=e.onDisconnect??Lse}get[Symbol.toStringTag](){return LO.toString()}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};nBe=LO;function hv(r){return new BO(r)}var lu,Ki=class extends EventTarget{constructor(){super(...arguments);bt(this,lu,new Map)}listenerCount(t){let n=ge(this,lu).get(t);return n==null?0:n.length}addEventListener(t,n,i){super.addEventListener(t,n,i);let o=ge(this,lu).get(t);o==null&&(o=[],ge(this,lu).set(t,o)),o.push({callback:n,once:(i!==!0&&i!==!1&&(i==null?void 0:i.once))??!1})}removeEventListener(t,n,i){super.removeEventListener(t.toString(),n??null,i);let o=ge(this,lu).get(t);o!=null&&(o=o.filter(({callback:s})=>s!==n),ge(this,lu).set(t,o))}dispatchEvent(t){let n=super.dispatchEvent(t),i=ge(this,lu).get(t.type);return i==null||(i=i.filter(({once:o})=>!o),ge(this,lu).set(t.type,i)),n}safeDispatchEvent(t,n){return this.dispatchEvent(new cn(t,n))}};lu=new WeakMap;var MO=class extends Event{constructor(t,n){super(t,n);B(this,"detail");this.detail=n==null?void 0:n.detail}},cn=globalThis.CustomEvent??MO;var pv=class{constructor(e,t,n){this.gossip=e,this.msgs=new Map,this.history=[],this.notValidatedCount=0,this.msgIdToStrFn=n;for(let i=0;i{let o=this.msgs.get(i.msgIdStr);if(o&&o.validated&&e.has(i.topic)){let s=t.get(i.topic);s||(s=[],t.set(i.topic,s)),s.push(i.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(!t)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:i}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:i}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t?(this.msgs.delete(e),t):null}};var pae=C(hae(),1),{RPC:P5}=pae.default;var XO="/floodsub/1.0.0",ZO="/meshsub/1.0.0",JO="/meshsub/1.1.0";var mae="ERR_TOPIC_VALIDATOR_REJECT",gae="ERR_TOPIC_VALIDATOR_IGNORE";function hu(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},hBe={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function bae(r={}){return{...dBe,...r,topics:r.topics?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=pBe(n),e),{}):{}}}function pBe(r={}){return{...hBe,...r}}function _ae(r){for(let[e,t]of Object.entries(r.topics))try{mBe(t)}catch(n){throw new J(`invalid score parameters for topic ${e}: ${n.message}`,br)}if(r.topicScoreCap<0)throw new J("invalid topic score cap; must be positive (or 0 for no cap)",br);if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new J("missing application specific score function",br);if(r.IPColocationFactorWeight>0)throw new J("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",br);if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new J("invalid IPColocationFactorThreshold; must be at least 1",br);if(r.behaviourPenaltyWeight>0)throw new J("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",br);if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new J("invalid BehaviourPenaltyDecay; must be between 0 and 1",br);if(r.decayInterval<1e3)throw new J("invalid DecayInterval; must be at least 1s",br);if(r.decayToZero<=0||r.decayToZero>=1)throw new J("invalid DecayToZero; must be between 0 and 1",br)}function mBe(r){if(r.topicWeight<0)throw new J("invalid topic weight; must be >= 0",br);if(r.timeInMeshQuantum===0)throw new J("invalid TimeInMeshQuantum; must be non zero",br);if(r.timeInMeshWeight<0)throw new J("invalid TimeInMeshWeight; must be positive (or 0 to disable)",br);if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new J("invalid TimeInMeshQuantum; must be positive",br);if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new J("invalid TimeInMeshCap; must be positive",br);if(r.firstMessageDeliveriesWeight<0)throw new J("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",br);if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new J("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",br);if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new J("invalid FirstMessageDeliveriesCap; must be positive",br);if(r.meshMessageDeliveriesWeight>0)throw new J("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",br);if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new J("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",br);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new J("invalid MeshMessageDeliveriesCap; must be positive",br);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new J("invalid MeshMessageDeliveriesThreshold; must be positive",br);if(r.meshMessageDeliveriesWindow<0)throw new J("invalid MeshMessageDeliveriesWindow; must be non-negative",br);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new J("invalid MeshMessageDeliveriesActivation; must be at least 1s",br);if(r.meshFailurePenaltyWeight>0)throw new J("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",br);if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new J("invalid MeshFailurePenaltyDecay; must be between 0 and 1",br);if(r.invalidMessageDeliveriesWeight>0)throw new J("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",br);if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new J("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",br)}var gBe={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Eae(r={}){return{...gBe,...r}}function vae(r,e,t,n){let i=0;Object.entries(e.topics).forEach(([s,a])=>{let c=t.topics[s];if(c===void 0)return;let u=0;if(a.inMesh){let d=a.meshTime/c.timeInMeshQuantum;d>c.timeInMeshCap&&(d=c.timeInMeshCap),u+=d*c.timeInMeshWeight}let l=a.firstMessageDeliveries;if(l>c.firstMessageDeliveriesCap&&(l=c.firstMessageDeliveriesCap),u+=l*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries0&&i>t.topicScoreCap&&(i=t.topicScoreCap);let o=t.appSpecificScore(r);if(i+=o*t.appSpecificWeight,e.knownIPs.forEach(s=>{if(t.IPColocationFactorWhitelist.has(s))return;let a=n.get(s),c=a?a.size:0;if(c>t.IPColocationFactorThreshold){let u=c-t.IPColocationFactorThreshold,l=u*u;i+=l*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let s=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=s*s;i+=a*t.behaviourPenaltyWeight}return i}var Aae=C(Sae(),1),co;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(co||(co={}));var yv=class{constructor(){this.records=new Map,this.queue=new Aae.default}ensureRecord(e){let t=this.records.get(e);if(t)return t;t={status:co.unknown,firstSeen:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t&&t.expire!0){let n=new Set;if(e<=0)return n;for(let i of r){if(n.size>=e)break;t(i)&&(n.add(i),r.delete(i))}return n}function Tae(r,e){return bv(r,e,()=>!0)}var wv=class extends Map{constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};var N2=j("libp2p:gossipsub:score"),_v=class{constructor(e,t,n){this.params=e,this.metrics=t,this.peerStats=new Map,this.peerIPs=new wv(()=>new Set),this.scoreCache=new Map,this.deliveryRecords=new yv,_ae(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??vae}get size(){return this.peerStats.size}start(){if(this._backgroundInterval){N2("Peer score already running");return}this._backgroundInterval=setInterval(()=>this.background(),this.params.decayInterval),N2("started")}stop(){if(!this._backgroundInterval){N2("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),N2("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,i)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(i,n.knownIPs),this.peerStats.delete(i),this.scoreCache.delete(i));return}Object.entries(n.topics).forEach(([o,s])=>{let a=this.params.topics[o];a!==void 0&&(s.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,s.firstMessageDeliveriesa.meshMessageDeliveriesActivation&&(s.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenaltyn)return i.score;(c=this.metrics)==null||c.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),s=n+this.scoreCacheValidityMs;return i?((u=this.metrics)==null||u.scoreCachedDelta.observe(Math.abs(o-i.score)),i.score=o,i.cacheUntil=s):this.scoreCache.set(e,{score:o,cacheUntil:s}),o}addPenalty(e,t,n){var o;let i=this.peerStats.get(e);i&&(i.behaviourPenalty+=t,(o=this.metrics)==null||o.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n&&n.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n&&n.knownIPs.delete(t);let i=this.peerIPs.get(t);i&&(i.delete(e),i.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,i])=>{i.firstMessageDeliveries=0;let o=this.params.topics[n].meshMessageDeliveriesThreshold;if(i.inMesh&&i.meshMessageDeliveriesActive&&i.meshMessageDeliveries{s!==e.toString()&&this.markDuplicateMessageDelivery(s,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,i){switch(i){case ao.Error:this.markInvalidMessageDelivery(e,n);return;case ao.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==co.unknown){N2("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeen,co[o.status]);return}if(i===ao.Ignore){o.status=co.ignored,o.peers.clear();return}o.status=co.invalid,this.markInvalidMessageDelivery(e,n),o.peers.forEach(s=>{this.markInvalidMessageDelivery(s,n)}),o.peers.clear()}duplicateMessage(e,t,n){let i=this.deliveryRecords.ensureRecord(t);if(!i.peers.has(e))switch(i.status){case co.unknown:i.peers.add(e);break;case co.valid:i.peers.add(e),this.markDuplicateMessageDelivery(e,n,i.validated);break;case co.invalid:this.markInvalidMessageDelivery(e,n);break;case co.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);i&&(i.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);if(i){let o=this.params.topics[t].firstMessageDeliveriesCap;i.firstMessageDeliveries=Math.min(o,i.firstMessageDeliveries+1),i.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,i.meshMessageDeliveries=Math.min(o,i.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){var o;let i=this.peerStats.get(e);if(i){let s=n!==void 0?Date.now():0,a=this.getPtopicStats(i,t);if(a&&a.inMesh){let c=this.params.topics[t];if(n!==void 0){let l=s-n,f=l>c.meshMessageDeliveriesWindow;if((o=this.metrics)==null||o.onDuplicateMsgDelivery(t,l,f),f)return}let u=c.meshMessageDeliveriesCap;a.meshMessageDeliveries=Math.min(u,a.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let i=this.peerIPs.get(n);i&&(i.delete(e),i.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};var Ev=class{constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.promises=new Map,this.requestMsByMsg=new Map,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),i=t[n],o=this.msgIdToStrFn(i),s=this.promises.get(o);s||(s=new Map,this.promises.set(o,s));let a=Date.now();s.has(e)||(s.set(e,a+this.gossipsubIWantFollowupMs),this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){var i;let e=Date.now(),t=new Map,n=0;return this.promises.forEach((o,s)=>{o.forEach((a,c)=>{a=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Iae;(function(r){r.forward="forward",r.publish="publish"})(Iae||(Iae={}));var Tl;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Tl||(Tl={}));var Jp;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Unsub="unsubscribed",r.Excess="excess"})(Jp||(Jp={}));var L2;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(L2||(L2={}));var B2;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(B2||(B2={}));var O2;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(O2||(O2={}));function Rae(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEvents:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_total",help:"Number of times we include peers in a topic mesh for different reasons",labelNames:["topic","reason"]}),meshPeerChurnEvents:r.gauge({name:"gossipsub_peer_churn_events_total",help:"Number of times we remove peers in a topic mesh for different reasons",labelNames:["topic","reason"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),asyncValidationResult:r.gauge({name:"gossipsub_async_validation_result_total",help:"Message validation result for each topic",labelNames:["topic","acceptance"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeers:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),msgPublishPeersByGroup:r.gauge({name:"gossipsub_msg_publish_peers_by_group",help:"Total count of peers (by group) that we publish a msg to",labelNames:["topic","peerGroup"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),msgReceivedStatus:r.gauge({name:"gossipsub_msg_received_status_total",help:"Tracks distribution of recv msgs by duplicate, invalid, valid",labelNames:["topic","status"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["topic","error"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,1*t.maxMeshMessageDeliveriesWindowSec,2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores",labelNames:["topic","p"]}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,1*t.behaviourPenaltyThreshold,2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,1*t.gossipPromiseExpireSec,2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,i,o){let s=this.toTopic(n);this.meshPeerInclusionEvents.inc({topic:s,reason:i},o)},onRemoveFromMesh(n,i,o){let s=this.toTopic(n);this.meshPeerChurnEvents.inc({topic:s,reason:i},o)},onReportValidationMcacheHit(n){this.asyncValidationMcacheHit.inc({hit:n?"hit":"miss"})},onReportValidation(n,i){let o=this.toTopic(n);this.asyncValidationResult.inc({topic:o,acceptance:i})},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,i,o){let s=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:s},i),this.ihaveRcvNotSeenMsgids.inc({topic:s},o)},onIwantRcv(n,i){for(let[o,s]of n){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},s)}this.iwantRcvDonthaveMsgids.inc(i)},onForwardMsg(n,i){let o=this.toTopic(n);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},i)},onPublishMsg(n,i,o,s){let a=this.toTopic(n);this.msgPublishCount.inc({topic:a},1),this.msgPublishBytes.inc({topic:a},o*s),this.msgPublishPeers.inc({topic:a},o),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"direct"},i.direct),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"floodsub"},i.floodsub),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"mesh"},i.mesh),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"fanout"},i.fanout)},onMsgRecvPreValidation(n){let i=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:i},1)},onMsgRecvError(n){let i=this.toTopic(n);this.msgReceivedError.inc({topic:i},1)},onMsgRecvResult(n,i){let o=this.toTopic(n);this.msgReceivedStatus.inc({topic:o,status:i})},onMsgRecvInvalid(n,i){let o=this.toTopic(n),s=i.reason===ao.Error?i.error:i.reason;this.msgReceivedInvalid.inc({topic:o,error:s},1)},onDuplicateMsgDelivery(n,i,o){if(this.duplicateMsgDeliveryDelay.observe(i/1e3),o){let s=this.toTopic(n);this.duplicateMsgLateDelivery.inc({topic:s},1)}},onPublishDuplicateMsg(n){let i=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:i},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,i){this.rpcRecvBytes.inc(i),this.rpcRecvCount.inc(1),n.subscriptions&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages&&this.rpcRecvMessage.inc(n.messages.length),n.control&&(this.rpcRecvControl.inc(1),n.control.ihave&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,i){var o,s,a,c;if(this.rpcSentBytes.inc(i),this.rpcSentCount.inc(1),n.subscriptions&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages&&this.rpcSentMessage.inc(n.messages.length),n.control){let u=((o=n.control.ihave)==null?void 0:o.length)??0,l=((s=n.control.iwant)==null?void 0:s.length)??0,f=((a=n.control.graft)==null?void 0:a.length)??0,h=((c=n.control.prune)==null?void 0:c.length)??0;u>0&&this.rpcSentIHave.inc(u),l>0&&this.rpcSentIWant.inc(l),f>0&&this.rpcSentGraft.inc(f),h>0&&this.rpcSentPrune.inc(h),(u>0||l>0||f>0||h>0)&&this.rpcSentControl.inc(1)}},registerScores(n,i){let o=0,s=0,a=0,c=0;for(let u of n)u>=i.graylistThreshold&&o++,u>=i.publishThreshold&&s++,u>=i.gossipThreshold&&a++,u>=0&&c++;this.peersByScoreThreshold.set({threshold:O2.graylist},o),this.peersByScoreThreshold.set({threshold:O2.publish},s),this.peersByScoreThreshold.set({threshold:O2.gossip},a),this.peersByScoreThreshold.set({threshold:O2.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[i,o]of n.byTopic)this.scoreWeights.set({topic:i,p:"p1"},o.p1w),this.scoreWeights.set({topic:i,p:"p2"},o.p2w),this.scoreWeights.set({topic:i,p:"p3"},o.p3w),this.scoreWeights.set({topic:i,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:i,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,i){let o=new Map;n.forEach((s,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",u=o.get(c);u||(u=new Set,o.set(c,u)),s.forEach(l=>u==null?void 0:u.add(l))});for(let[s,a]of o){let c=[];a.forEach(u=>{c.push(i.get(u)??0)}),this.scorePerMesh.set({topic:s},c)}}}}var G9t=C(Nh(),1),wBe=C(at(),1);var EBe=C(bb(),1),vBe=C(gr(),1);var Cae=Ie("libp2p-pubsub:");async function Pae(r,e,t,n){switch(r.type){case qd.Signing:{let i={from:r.author.toBytes(),data:n,seqno:Mc(8),topic:e,signature:void 0,key:void 0},o=rt([Cae,P5.Message.encode(i).finish()]);i.signature=await r.privateKey.sign(o),i.key=r.key;let s={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${re(i.seqno,"base16")}`),topic:e,signature:i.signature,key:i.key};return{raw:i,msg:s}}case qd.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}}}}async function kae(r,e){switch(r){case k2:return e.signature!=null?{valid:!1,error:$i.SignaturePresent}:e.seqno!=null?{valid:!1,error:$i.SeqnoPresent}:e.key!=null?{valid:!1,error:$i.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Zp:{if(e.seqno==null)return{valid:!1,error:$i.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:$i.InvalidSeqno};if(e.signature==null)return{valid:!1,error:$i.InvalidSignature};if(e.from==null)return{valid:!1,error:$i.InvalidPeerId};let t;try{t=Di(e.from)}catch{return{valid:!1,error:$i.InvalidPeerId}}let n;if(e.key){if(n=Bs(e.key),t.publicKey!==void 0&&!mt(n.bytes,t.publicKey))return{valid:!1,error:$i.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:$i.InvalidPeerId};n=Bs(t.publicKey)}let i={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=rt([Cae,P5.Message.encode(i).finish()]);return await n.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${re(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:e.key??a3(n)}}:{valid:!1,error:$i.InvalidSignature}}}}var Nae=(r,e)=>{let t=Ie(e.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),n};function Dae(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return Nae(r.from.toBytes(),r.sequenceNumber)}async function Oae(r){return await dt.encode(r.data)}function xBe(r,e,t,n,i){let o=0,s=new Map;if(Object.entries(e.topics).forEach(([h,d])=>{let p=i.get(h)??"unknown",g=t.topics[h];if(g===void 0)return;let w=s.get(p);w||(w={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},s.set(p,w));let _=0,x=0,m=0,y=0,b=0;if(d.inMesh){let A=Math.max(d.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);_+=A*g.timeInMeshWeight}let E=d.firstMessageDeliveries;if(E>g.firstMessageDeliveriesCap&&(E=g.firstMessageDeliveriesCap),x+=E*g.firstMessageDeliveriesWeight,d.meshMessageDeliveriesActive&&d.meshMessageDeliveries0&&o>t.topicScoreCap){o=t.topicScoreCap;let h=t.topicScoreCap/o;for(let d of s.values())d.p1w*=h,d.p2w*=h,d.p3w*=h,d.p3bw*=h,d.p4w*=h}let a=0,c=0,u=0,l=t.appSpecificScore(r);a+=l*t.appSpecificWeight,e.knownIPs.forEach(h=>{if(t.IPColocationFactorWhitelist.has(h))return;let d=n.get(h),p=d?d.size:0;if(p>t.IPColocationFactorThreshold){let g=p-t.IPColocationFactorThreshold,w=g*g;c+=w*t.IPColocationFactorWeight}});let f=e.behaviourPenalty*e.behaviourPenalty;return u+=f*t.behaviourPenaltyWeight,o+=a+c+u,{byTopic:s,p5w:a,p6w:c,p7w:u,score:o}}function Lae(r,e,t,n,i){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let s of r){let a=e.get(s);if(a){let c=xBe(s,a,t,n,i);for(let[u,l]of c.byTopic){let f=o.byTopic.get(u);f||(f={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(u,f)),f.p1w.push(l.p1w),f.p2w.push(l.p2w),f.p3w.push(l.p3w),f.p3bw.push(l.p3bw),f.p4w.push(l.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var vv=class{constructor(e){B(this,"buffer");B(this,"mask");B(this,"top");B(this,"btm");B(this,"next");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 this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},M2=class{constructor(e={}){B(this,"size");B(this,"hwm");B(this,"head");B(this,"tail");this.hwm=e.splitLimit??16,this.head=new vv(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return(e==null?void 0:e.byteLength)!=null?e.byteLength:1}push(e){if((e==null?void 0:e.value)!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new vv(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return(e==null?void 0:e.value)!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var rL=class extends Error{constructor(t,n){super(t??"The operation was aborted");B(this,"type");B(this,"code");this.type="aborted",this.code=n??"ABORT_ERR"}};function Ao(r={}){return Mae(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Bae(r={}){return Mae(t=>{let n,i=[];for(;!t.isEmpty()&&(n=t.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&i.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:i}},r)}function Mae(r,e){e=e??{};let t=e.onEnd,n=new M2,i,o,s,a=Qt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,_)=>{o=x=>{o=null,n.push(x);try{w(r(n))}catch(m){_(m)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Qt()})}},u=w=>o!=null?o(w):(n.push(w),i),l=w=>(n=new M2,o!=null?o({error:w}):(n.push({error:w}),i)),f=w=>{if(s)return i;if((e==null?void 0:e.objectMode)!==!0&&(w==null?void 0:w.byteLength)==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},h=w=>s?i:(s=!0,w!=null?l(w):u({done:!0})),d=()=>(n=new M2,h(),{done:!0}),p=w=>(h(w),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:h,get readableLength(){return n.size},onEmpty:async w=>{let _=w==null?void 0:w.signal;if(_==null||_.throwIfAborted(),n.isEmpty())return;let x,m;_!=null&&(x=new Promise((y,b)=>{m=()=>{b(new rL)},_.addEventListener("abort",m)}));try{await Promise.race([a.promise,x])}finally{m!=null&&_!=null&&(_==null||_.removeEventListener("abort",m))}}},t==null)return i;let g=i;return i={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return g.end(w),t!=null&&(t(w),t=void 0),i},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},i}var k5=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Uae(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function na(r,e,t){let n=t??{},i=Uae(r);async function*o(){let s,a=()=>{s!=null&&s()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new k5(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:d}=n;f(new k5(h,d))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function SBe(r,e,t){return n=>r(na(n,e,t))}function nL(r,e,t){return{sink:SBe(r.sink,e,{...t,onAbort:void 0}),source:na(r.source,e,t)}}var zae=Symbol.for("@achingbrain/uint8arraylist");function Fae(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(xv(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(xv(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Fae(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fae(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return yr(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:yr(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new ln;return o.length=i,o.bufs=n,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(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o=c)continue;let u=e>=a&&ea&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!xv(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=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),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ac(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=ju(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=ju(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=ju(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ac(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=ju(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=ju(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=ju(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=ju(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=ju(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof ln)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;ti+o.byteLength,0)),n.length=t,n}};var ABe=Math.pow(2,7),TBe=Math.pow(2,14),IBe=Math.pow(2,21),RBe=Math.pow(2,28),CBe=Math.pow(2,35),PBe=Math.pow(2,42),kBe=Math.pow(2,49),NBe=Math.pow(2,56),DBe=Math.pow(2,63),nc={encodingLength(r){return rNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Ac(nc.encodingLength(r))),Vi.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return Vi.fromBytes(r,e).toNumber(!0)}};function Vae(r){var e;return((e=globalThis==null?void 0:globalThis.Buffer)==null?void 0:e.allocUnsafe)!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var Sv=r=>{let e=nc.encodingLength(r),t=Vae(e);return nc.encode(r,t),Sv.bytes=e,t};Sv.bytes=0;function vn(r){r=r??{};let e=r.lengthEncoder??Sv;return async function*(n){for await(let i of n){let o=e(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}}}vn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Sv;return new ln(t(r.byteLength),r)};var N5=C(ee(),1),OBe=8,LBe=1024*1024*4,e0;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(e0||(e0={}));var iL=r=>{let e=nc.decode(r);return iL.bytes=nc.encodingLength(e),e};iL.bytes=0;function Xr(r){return async function*(t){let n=new ln,i=e0.LENGTH,o=-1,s=(r==null?void 0:r.lengthDecoder)??iL,a=(r==null?void 0:r.maxLengthLength)??OBe,c=(r==null?void 0:r.maxDataLength)??LBe;for await(let u of t)for(n.append(u);n.byteLength>0;){if(i===e0.LENGTH)try{if(o=s(n),o<0)throw(0,N5.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>c)throw(0,N5.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;n.consume(l),(r==null?void 0:r.onLength)!=null&&r.onLength(o),i=e0.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>a)throw(0,N5.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(i===e0.DATA){if(n.byteLength0)throw(0,N5.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}Xr.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return Xr({...e??{},onLength:o=>{t=o}})(n)};var Av=class{constructor(e,t,n){this.rawStream=e,this.pushable=Ao({objectMode:!1}),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,Ne(na(this.pushable,this.closeController.signal,{returnOnAbort:!0}),vn(),this.rawStream).catch(t)}get protocol(){return this.rawStream.stat.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}close(){this.closeController.abort(),this.pushable.return(),this.rawStream.close()}},Tv=class{constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.source=na(Ne(this.rawStream,Xr(t)),this.closeController.signal,{returnOnAbort:!0})}close(){this.closeController.abort(),this.rawStream.close()}};var Kae=C(QO(),1),$ae={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};function qae(r,e){e={...e};let t=Kae.default.Reader.create(r),n=r.length,i=n===void 0?t.len:t.pos+n,o={};for(;t.pos>>3){case 1:o.subscriptions&&o.subscriptions.length||(o.subscriptions=[]),o.subscriptions.length>>3){case 1:n.subscribe=r.bool();break;case 2:n.topic=r.string();break;default:r.skipType(i&7);break}}return n}function MBe(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.from=r.bytes();break;case 2:n.data=r.bytes();break;case 3:n.seqno=r.bytes();break;case 4:n.topic=r.string();break;case 5:n.signature=r.bytes();break;case 6:n.key=r.bytes();break;default:r.skipType(i&7);break}}if(!n.topic)throw Error("missing required 'topic'");return n}function UBe(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.ihave&&i.ihave.length||(i.ihave=[]),i.ihave.length>>3){case 1:i.topicID=r.string();break;case 2:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIhaveMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(o&7);break;default:r.skipType(o&7);break}}return i}function zBe(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIwantMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(o&7);break;default:r.skipType(o&7);break}}return i}function VBe(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.topicID=r.string();break;default:r.skipType(i&7);break}}return n}function KBe(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.topicID=r.string();break;case 2:i.peers&&i.peers.length||(i.peers=[]),t.maxPeerInfos-- >0?i.peers.push($Be(r,r.uint32())):r.skipType(o&7);break;case 3:i.backoff=r.uint64();break;default:r.skipType(o&7);break}}return i}function $Be(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.peerID=r.bytes();break;case 2:n.signedPeerRecord=r.bytes();break;default:r.skipType(i&7);break}}return n}var Iv;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(Iv||(Iv={}));function Hae(r){for(let e of r.tuples())switch(e[0]){case Iv.ip4:case Iv.ip6:return Sy(e[0],e[1])}return null}var ds;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(ds||(ds={}));var Rv=class extends Ki{constructor(e,t={}){super(),this.multicodecs=[JO,ZO],this.peers=new Set,this.streamsInbound=new Map,this.streamsOutbound=new Map,this.outboundInflightQueue=Ao({objectMode:!0}),this.direct=new Set,this.floodsubPeers=new Set,this.acceptFromWhitelist=new Map,this.topics=new Map,this.subscriptions=new Set,this.mesh=new Map,this.fanout=new Map,this.fanoutLastpub=new Map,this.gossip=new Map,this.control=new Map,this.peerhave=new Map,this.iasked=new Map,this.backoff=new Map,this.outbound=new Map,this.topicValidators=new Map,this.heartbeatTicks=0,this.directPeerInitial=null,this.status={code:ds.stopped},this.heartbeatTimer=null,this.runHeartbeat=()=>{var o;let i=(o=this.metrics)==null?void 0:o.heartbeatDuration.startTimer();this.heartbeat().catch(s=>{this.log("Error running heartbeat",s)}).finally(()=>{var s;if(i!=null&&i(),this.status.code===ds.started){clearTimeout(this.status.heartbeatTimeout);let a=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;ai.id.toString())),this.seenCache=new D2({validityMs:n.seenTTL}),this.publishedMessageIds=new D2({validityMs:n.seenTTL}),t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Zp:this.msgIdFn=Dae;break;case k2:this.msgIdFn=Oae;break}if(t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new D2({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??yae,this.mcache=t.messageCache||new pv(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform&&(this.dataTransform=t.dataTransform),t.metricsRegister){if(!t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");let i=Math.max(...Object.values(n.scoreParams.topics).map(s=>s.meshMessageDeliveriesWindow),1e3),o=Rae(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:i/1e3});o.mcacheSize.addCollect(()=>this.onScrapeMetrics(o));for(let s of this.multicodecs)o.protocolsEnabled.set({protocol:s},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new Ev(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new _v(this.opts.scoreParams,this.metrics,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.allowedTopics=n.allowedTopics?new Set(n.allowedTopics):null}getPeers(){return[...this.peers.keys()].map(e=>Oe(e))}isStarted(){return this.status.code===ds.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await tL(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=Ao({objectMode:!0}),Ne(this.outboundInflightQueue,async o=>{for await(let{peerId:s,connection:a}of o)await this.createOutboundStream(s,a)}).catch(o=>this.log.error("outbound inflight queue error",o)),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.addressBook.add(o.id,o.addrs)}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})));let t=hv({onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this)}),n=await Promise.all(this.multicodecs.map(o=>e.register(o,t))),i=setTimeout(this.runHeartbeat,100);this.status={code:ds.started,registrarTopologyIds:n,heartbeatTimeout:i,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>await this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==ds.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:ds.stopped};let t=this.components.registrar;e.forEach(n=>t.unregister(n)),this.outboundInflightQueue.end();for(let n of this.streamsOutbound.values())n.close();this.streamsOutbound.clear();for(let n of this.streamsInbound.values())n.close();this.streamsInbound.clear(),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache&&this.fastMsgIdCache.clear(),this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.stat.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){var n;(n=this.metrics)==null||n.newConnectionCount.inc({status:t.stat.status}),!(!this.isStarted()||t.stat.status!=="OPEN")&&(this.addPeer(e,t.stat.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){var i;if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let o=new Av(await t.newStream(this.multicodecs),a=>this.log.error("outbound pipe error",a),{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,o);let s=o.protocol;s===XO&&this.floodsubPeers.add(n),(i=this.metrics)==null||i.peersPerProtocol.inc({protocol:s},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(o){this.log.error("createOutboundStream error",o)}}async createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let i=this.streamsInbound.get(n);i!==void 0&&(this.log("replacing existing inbound steam %s",n),i.close()),this.log("create inbound stream %s",n);let o=new Tv(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,o),this.pipePeerReadStream(e,o.source).catch(s=>this.log(s))}addPeer(e,t,n){let i=e.toString();if(!this.peers.has(i)){this.log("new peer %p",e),this.peers.add(i),this.score.addPeer(i);let o=Hae(n);o!==null?this.score.addIP(i,o):this.log("Added peer has no IP in current address %s %s",i,n.toString()),this.outbound.has(i)||this.outbound.set(i,t==="outbound")}}removePeer(e){var o,s;let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),i=this.streamsInbound.get(t);n&&((o=this.metrics)==null||o.peersPerProtocol.inc({protocol:n.protocol},-1)),n==null||n.close(),i==null||i.close(),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let a of this.topics.values())a.delete(t);for(let[a,c]of this.mesh)c.delete(t)===!0&&((s=this.metrics)==null||s.onRemoveFromMesh(a,Jp.Dc,1));for(let a of this.fanout.values())a.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===ds.started}getMeshPeers(e){let t=this.mesh.get(e);return t?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t?Array.from(t):[]).map(n=>Oe(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){var n;try{await Ne(t,async i=>{var o,s,a;for await(let c of i)try{let u=c.subarray(),l=qae(u,this.decodeRpcLimits);if((o=this.metrics)==null||o.onRpcRecv(l,u.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,l)}catch(f){(s=this.metrics)==null||s.onRpcRecvError(),this.log(f)}else this.handleReceivedRpc(e,l).catch(f=>{var h;(h=this.metrics)==null||h.onRpcRecvError(),this.log(f)})}catch(u){(a=this.metrics)==null||a.onRpcDataError(),this.log(u)}})}catch(i){(n=this.metrics)==null||n.onPeerReadStreamError(),this.handlePeerReadStreamError(i,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){var u;if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),(u=this.metrics)==null||u.rpcRecvNotAccepted.inc();return}let n=t.subscriptions?t.subscriptions.length:0,i=t.messages?t.messages.length:0,o=0,s=0,a=0,c=0;if(t.control&&(t.control.ihave&&(o=t.control.ihave.length),t.control.iwant&&(s=t.control.iwant.length),t.control.graft&&(a=t.control.graft.length),t.control.prune&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${i} ihave ${o} iwant ${s} graft ${a} prune ${c}`),t.subscriptions&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(f=>{let h=f.topic,d=f.subscribe===!0;if(h!=null){if(this.allowedTopics&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,d),l.push({topic:h,subscribe:d})}}),this.dispatchEvent(new cn("subscription-change",{detail:{peerId:e,subscriptions:l}}))}if(t.messages)for(let l of t.messages){if(this.allowedTopics&&!this.allowedTopics.has(l.topic))continue;let f=this.handleReceivedMessage(e,l).catch(h=>{var d;(d=this.metrics)==null||d.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await f}t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let i=this.topics.get(t);i==null&&(i=new Set,this.topics.set(t,i)),n?i.add(e.toString()):i.delete(e.toString())}async handleReceivedMessage(e,t){var i,o,s;(i=this.metrics)==null||i.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);switch((o=this.metrics)==null||o.onMsgRecvResult(t.topic,n.code),n.code){case ra.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case ra.invalid:if(n.msgIdStr){let a=n.msgIdStr;this.score.rejectMessage(e.toString(),a,t.topic,n.reason),this.gossipTracer.rejectMessage(a,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);(s=this.metrics)==null||s.onMsgRecvInvalid(t.topic,n);return;case ra.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new cn("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new cn("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString())}}async validateReceivedMessage(e,t){var f,h,d;let n=(f=this.fastMsgIdFn)==null?void 0:f.call(this,t),i=n!==void 0?(h=this.fastMsgIdCache)==null?void 0:h.get(n):void 0;if(i)return{code:ra.duplicate,msgIdStr:i};let o=await kae(this.globalSignaturePolicy,t);if(!o.valid)return{code:ra.invalid,reason:ao.Error,error:o.error};let s=o.message;try{this.dataTransform&&(s.data=this.dataTransform.inboundTransform(t.topic,s.data))}catch(p){return this.log("Invalid message, transform failed",p),{code:ra.invalid,reason:ao.Error,error:$i.TransformFailed}}let a=await this.msgIdFn(s),c=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache&&this.fastMsgIdCache.put(n,c)&&((d=this.metrics)==null||d.fastMsgIdCacheCollision.inc()),this.seenCache.has(c))return{code:ra.duplicate,msgIdStr:c};this.seenCache.put(c);let l=this.topicValidators.get(t.topic);if(l!=null){let p;try{p=await l(e,s)}catch(g){let w=g.code;w===gae&&(p=rc.Ignore),w===mae?p=rc.Reject:p=rc.Ignore}if(p!==rc.Accept)return{code:ra.invalid,reason:eL(p),msgIdStr:c}}return{code:ra.valid,messageId:u,msg:s}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(i=>({topic:i,subscribe:n}))})}async handleControlMessage(e,t){var c,u;if(t===void 0)return;let n=t.ihave?this.handleIHave(e,t.ihave):[],i=t.iwant?this.handleIWant(e,t.iwant):[],o=t.graft?await this.handleGraft(e,t.graft):[];if(t.prune&&await this.handlePrune(e,t.prune),!n.length&&!i.length&&!o.length)return;let s=this.sendRpc(e,{messages:i,control:{iwant:n,prune:o}}),a=(c=n[0])==null?void 0:c.messageIDs;a&&(s?this.gossipTracer.addPromise(e,a):(u=this.metrics)==null||u.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let i=this.score.score(e);return i>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),i>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){var u,l,f;if(!t.length)return[];let n=this.score.score(e);if(n10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,i),(l=this.metrics)==null||l.ihaveRcvIgnored.inc({reason:B2.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),(f=this.metrics)==null||f.ihaveRcvIgnored.inc({reason:B2.MaxIasked}),[];let s=new Map;if(t.forEach(({topicID:h,messageIDs:d})=>{var g;if(!h||!d||!this.mesh.has(h))return;let p=0;d.forEach(w=>{let _=this.msgIdToStrFn(w);this.seenCache.has(_)||(s.set(_,w),p++)}),(g=this.metrics)==null||g.onIhaveRcv(h,d.length,p)}),!s.size)return[];let a=s.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,s.size,e);let c=Array.from(s.values());return hu(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){var a;if(!t.length)return[];let n=this.score.score(e);if(n{c&&c.forEach(u=>{let l=this.msgIdToStrFn(u),f=this.mcache.getWithIWantCount(l,e);if(f==null){s++;return}if(o.set(f.msg.topic,1+(o.get(f.msg.topic)??0)),f.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,u);return}i.set(l,f.msg)})}),(a=this.metrics)==null||a.onIwantRcv(o,s),i.size?(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values())):(this.log("IWANT: Could not provide any wanted messages to %s",e),[])}async handleGraft(e,t){let n=[],i=this.score.score(e),o=Date.now(),s=this.opts.doPX;return t.forEach(({topicID:a})=>{var l,f;if(!a)return;let c=this.mesh.get(a);if(!c){s=!1;return}if(c.has(e))return;if(this.direct.has(e)){this.log("GRAFT: ignoring request from direct peer %s",e),n.push(a),s=!1;return}let u=(l=this.backoff.get(a))==null?void 0:l.get(e);if(typeof u=="number"&&o=this.opts.Dhi&&!this.outbound.get(e)){n.push(a),this.addBackoff(e,a);return}this.log("GRAFT: Add mesh link from %s in %s",e,a),this.score.graft(e,a),c.add(e),(f=this.metrics)==null||f.onAddToMesh(a,Tl.Subscribed,1)}),n.length?await Promise.all(n.map(a=>this.makePrune(e,a,s))):[]}async handlePrune(e,t){var i;let n=this.score.score(e);for(let{topicID:o,backoff:s,peers:a}of t){if(o==null)continue;let c=this.mesh.get(o);if(!c)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,o),this.score.prune(e,o),c.has(e)&&(c.delete(e),(i=this.metrics)==null||i.onRemoveFromMesh(o,Jp.Unsub,1)),typeof s=="number"&&s>0?this.doAddBackoff(e,o,s*1e3):this.addBackoff(e,o),a&&a.length){if(n{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,L2.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((i,o)=>{i{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>await this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(hu(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(!n.peerID)return;let i=Di(n.peerID).toString();if(!this.peers.has(i)){if(!n.signedPeerRecord){t.push(i);return}try{let o=await zd.openAndCertify(n.signedPeerRecord,"libp2p-peer-record"),s=o.peerId;if(!o.peerId.equals(i)){this.log("bogus peer record obtained through px: peer ID %p doesn't match expected peer %p",s,i);return}if(!await this.components.peerStore.addressBook.consumePeerRecord(o)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(i)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length&&await Promise.all(t.map(async n=>await this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=Oe(e),n=await this.components.connectionManager.openConnection(t);for(let i of this.multicodecs)for(let o of this.components.registrar.getTopologies(i))o.onConnect(t,n)}subscribe(e){if(this.status.code!==ds.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==ds.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){var i,o,s;if(this.status.code!==ds.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),(i=this.metrics)==null||i.onJoin(e);let t=new Set,n=this.fanout.get(e);if(n&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(a=>{!this.direct.has(a)&&this.score.score(a)>=0&&t.add(a)}),(o=this.metrics)==null||o.onAddToMesh(e,Tl.Fanout,t.size)),t.size!t.has(u)&&!this.direct.has(u)&&this.score.score(u)>=0).forEach(u=>{t.add(u)}),(s=this.metrics)==null||s.onAddToMesh(e,Tl.Random,t.size-a)}this.mesh.set(e,t),t.forEach(a=>{this.log("JOIN: Add mesh link to %s in %s",a,e),this.sendGraft(a,e)})}leave(e){var n;if(this.status.code!==ds.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),(n=this.metrics)==null||n.onLeave(e);let t=this.mesh.get(e);t&&(Promise.all(Array.from(t).map(async i=>(this.log("LEAVE: Remove mesh link to %s in %s",i,e),await this.sendPrune(i,e)))).catch(i=>{this.log("Error sending prunes to mesh peers",i)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let i=new Set,o=this.topics.get(e);o&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(n!=null&&n.has(a))&&i.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(n!=null&&n.has(a))&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&i.add(a)}));let s=this.mesh.get(e);return s&&s.size>0&&s.forEach(a=>{t!==a&&!(n!=null&&n.has(a))&&i.add(a)}),i}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},i=this.topics.get(e);if(i)if(this.opts.floodPublish)i.forEach(o=>{this.direct.has(o)?(t.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});else{this.direct.forEach(s=>{i.has(s)&&(t.add(s),n.direct++)}),this.floodsubPeers.forEach(s=>{i.has(s)&&this.score.score(s)>=this.opts.scoreThresholds.publishThreshold&&(t.add(s),n.floodsub++)});let o=this.mesh.get(e);if(o&&o.size>0)o.forEach(s=>{t.add(s),n.mesh++});else{let s=this.fanout.get(e);if(s&&s.size>0)s.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,i){var s;n&&this.score.deliverMessage(n,e,t.topic);let o=this.selectPeersToForward(t.topic,n,i);o.forEach(a=>{this.sendRpc(a,{messages:[t]})}),(s=this.metrics)==null||s.onForwardMsg(t.topic,o.size)}async publish(e,t,n){var p,g;let i=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:o,msg:s}=await Pae(this.publishConfig,e,t,i),a=await this.msgIdFn(s),c=this.msgIdToStrFn(a),u=(n==null?void 0:n.ignoreDuplicatePublishError)??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(u)return(p=this.metrics)==null||p.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:l,tosendCount:f}=this.selectPeersToPublish(e),h=this.opts.emitSelf===!0&&this.subscriptions.has(e),d=(n==null?void 0:n.allowPublishToZeroPeers)??this.opts.allowPublishToZeroPeers;if(l.size===0&&!d&&!h)throw Error("PublishError.InsufficientPeers");this.seenCache.put(c),this.mcache.put({msgId:a,msgIdStr:c},o,!0),this.publishedMessageIds.put(c);for(let w of l)this.sendRpc(w,{messages:[o]})||l.delete(w);return(g=this.metrics)==null||g.onPublishMsg(e,f,l.size,o.data!=null?o.data.length:0),h&&(l.add(this.components.peerId.toString()),super.dispatchEvent(new cn("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:s}})),super.dispatchEvent(new cn("message",{detail:s}))),{recipients:Array.from(l.values()).map(w=>Oe(w))}}reportMessageValidationResult(e,t,n){var i,o,s,a;if(n===rc.Accept){let c=this.mcache.validate(e);if((i=this.metrics)==null||i.onReportValidationMcacheHit(c!==null),c!=null){let{message:u,originatingPeers:l}=c;this.score.deliverMessage(t.toString(),e,u.topic),this.forwardMessage(e,c.message,t.toString(),l),(o=this.metrics)==null||o.onReportValidation(u.topic,n)}}else{let c=this.mcache.remove(e);if((s=this.metrics)==null||s.onReportValidationMcacheHit(c!==null),c){let u=eL(n),{message:l,originatingPeers:f}=c;this.score.rejectMessage(t.toString(),e,l.topic,u);for(let h of f)this.score.rejectMessage(h,e,l.topic,u);(a=this.metrics)==null||a.onReportValidation(l.topic,n)}}}sendGraft(e,t){let n=[{topicID:t}];this.sendRpc(e,{control:{graft:n}})}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX)];this.sendRpc(e,{control:{prune:n}})}sendRpc(e,t){var a;let n=this.streamsOutbound.get(e);if(!n)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let i=this.control.get(e);i&&(this.piggybackControl(e,t,i),this.control.delete(e));let o=this.gossip.get(e);o&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let s=P5.encode(t).finish();try{n.push(s)}catch(c){return this.log.error(`Cannot send rpc to ${e}`,c),i&&this.control.set(e,i),o&&this.gossip.set(e,o),!1}return(a=this.metrics)==null||a.onRpcSent(t,s.length),!0}piggybackControl(e,t,n){var i,o;if(n.graft){t.control||(t.control={}),t.control.graft||(t.control.graft=[]);for(let s of n.graft)s.topicID&&((i=this.mesh.get(s.topicID))!=null&&i.has(e))&&t.control.graft.push(s)}if(n.prune){t.control||(t.control={}),t.control.prune||(t.control.prune=[]);for(let s of n.prune)s.topicID&&!((o=this.mesh.get(s.topicID))!=null&&o.has(e))&&t.control.prune.push(s)}}piggybackGossip(e,t,n){t.control||(t.control={}),t.control.ihave=n}async sendGraftPrune(e,t,n){let i=this.opts.doPX;for(let[o,s]of e){let a=s.map(l=>({topicID:l})),c=[],u=t.get(o);u&&(c=await Promise.all(u.map(async l=>await this.makePrune(o,l,i&&!(n.get(o)??!1)))),t.delete(o)),this.sendRpc(o,{control:{graft:a,prune:c}})}for(let[o,s]of t){let a=await Promise.all(s.map(async c=>await this.makePrune(o,c,i&&!(n.get(o)??!1))));this.sendRpc(o,{control:{prune:a}})}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,i]of e)this.doEmitGossip(n,i,t.get(n)??[])}doEmitGossip(e,t,n){if(!n.length||(hu(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),!t.size))return;let i=this.opts.Dlazy,o=.25*t.size,s=t;o>i&&(i=o),i>s.size?i=s.size:s=hu(Array.from(s)).slice(0,i),s.forEach(a=>{let c=n;n.length>5e3&&(c=hu(c.slice()).slice(0,5e3)),this.pushGossip(a,{topicID:e,messageIDs:c})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,{control:{ihave:t}});for(let[e,t]of this.control.entries())this.control.delete(e),this.sendRpc(e,{control:{graft:t.graft,prune:t.prune}})}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)||[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n){if(this.score.prune(e,t),this.streamsOutbound.get(e).protocol===ZO)return{topicID:t,peers:[]};let i=this.opts.pruneBackoff/1e3;if(!n)return{topicID:t,peers:[],backoff:i};let o=this.getRandomGossipPeers(t,this.opts.prunePeers,a=>a!==e&&this.score.score(a)>=0),s=await Promise.all(Array.from(o).map(async a=>{let c=Oe(a);return{peerID:c.toBytes(),signedPeerRecord:await this.components.peerStore.addressBook.getRawEnvelope(c)}}));return{topicID:t,peers:s,backoff:i}}async heartbeat(){var p,g;let{D:e,Dlo:t,Dhi:n,Dscore:i,Dout:o,fanoutTTL:s}=this.opts;this.heartbeatTicks++;let a=new Map,c=w=>{let _=a.get(w);return _===void 0&&(_=this.score.score(w),a.set(w,_)),_},u=new Map,l=new Map,f=new Map;this.clearBackoff(),this.peerhave.clear(),(p=this.metrics)==null||p.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),(g=this.fastMsgIdCache)==null||g.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let h=new Map;this.mesh.forEach((w,_)=>{let x=this.topics.get(_),m=new Set,y=new Set;if(h.set(_,y),x){let v=hu(Array.from(x)),S=this.backoff.get(_);for(let A of v){let I=this.streamsOutbound.get(A);if(I&&this.multicodecs.includes(I.protocol)&&!w.has(A)&&!this.direct.has(A)){let k=c(A);(!S||!S.has(A))&&k>=0&&m.add(A),k>=this.opts.scoreThresholds.gossipThreshold&&y.add(A)}}}let b=(v,S)=>{var I;this.log("HEARTBEAT: Remove mesh link to %s in %s",v,_),this.addBackoff(v,_),w.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&y.add(v),(I=this.metrics)==null||I.onRemoveFromMesh(_,S,1);let A=l.get(v);A?A.push(_):l.set(v,[_])},E=(v,S)=>{var I;this.log("HEARTBEAT: Add mesh link to %s in %s",v,_),this.score.graft(v,_),w.add(v),y.delete(v),(I=this.metrics)==null||I.onAddToMesh(_,S,1);let A=u.get(v);A?A.push(_):u.set(v,[_])};if(w.forEach(v=>{let S=c(v);S<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,S,_),b(v,Jp.BadScore),f.set(v,!0))}),w.size{E(A,Tl.NotEnough)})}if(w.size>n){let v=Array.from(w);v.sort((A,I)=>c(I)-c(A)),v=v.slice(0,i).concat(hu(v.slice(i)));let S=0;if(v.slice(0,e).forEach(A=>{this.outbound.get(A)&&S++}),S{let N=v[k];for(let O=k;O>0;O--)v[O]=v[O-1];v[0]=N};if(S>0){let k=S;for(let N=1;N0;N++)this.outbound.get(v[N])&&(A(N),k--)}let I=e-S;for(let k=e;k0;k++)this.outbound.get(v[k])&&(A(k),I--)}v.slice(e).forEach(A=>{b(A,Jp.Excess)})}if(w.size>=t){let v=0;if(w.forEach(S=>{this.outbound.get(S)&&v++}),vthis.outbound.get(I)===!0).forEach(I=>{E(I,Tl.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&w.size>1){let v=Array.from(w).sort((I,k)=>c(I)-c(k)),S=Math.floor(w.size/2),A=c(v[S]);if(Ac(N)>A);for(let N of k)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",N,_),E(N,Tl.Opportunistic)}}});let d=Date.now();this.fanoutLastpub.forEach((w,_)=>{w+s{let x=this.topics.get(_);w.forEach(E=>{(!x.has(E)||c(E)=this.opts.scoreThresholds.publishThreshold&&y.push(v),A>=this.opts.scoreThresholds.gossipThreshold&&b.add(v)}}}if(w.size{w.add(v),b==null||b.delete(v)})}}),this.emitGossip(h),await this.sendGraftPrune(u,l,f),this.flush(),this.mcache.shift(),this.dispatchEvent(new cn("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let i=this.topics.get(e);if(!i)return new Set;let o=[];return i.forEach(s=>{let a=this.streamsOutbound.get(s);a&&this.multicodecs.includes(a.protocol)&&n(s)&&o.push(s)}),o=hu(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){var s,a;e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},((s=this.fastMsgIdCache)==null?void 0:s.size)??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0;for(let c of this.backoff.values())t+=c.size;e.cacheSize.set({cache:"backoff"},t);for(let[c,u]of this.topics)e.topicPeersCount.set({topicStr:c},u.size);for(let[c,u]of this.mesh)e.meshPeerCounts.set({topicStr:c},u.size);let n=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let u=this.score.score(c);n.push(u),i.set(c,u),e.behaviourPenalty.observe(((a=this.score.peerStats.get(c))==null?void 0:a.behaviourPenalty)??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let o=Lae(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(o)}};Rv.multicodec=JO;function jae(r={}){return e=>new Rv(e,r)}var Wae=()=>({gossipsub:jae({fallbackToFloodsub:!0,emitSelf:!0,maxInboundStreams:64,maxOutboundStreams:128})});var hs=C(xA(),1);hs.default.formatters.b=r=>r==null?"undefined":Qi.baseEncode(r);hs.default.formatters.t=r=>r==null?"undefined":_f.baseEncode(r);hs.default.formatters.m=r=>r==null?"undefined":lI.baseEncode(r);hs.default.formatters.p=r=>r==null?"undefined":r.toString();hs.default.formatters.c=r=>r==null?"undefined":r.toString();hs.default.formatters.k=r=>r==null?"undefined":r.toString();hs.default.formatters.a=r=>r==null?"undefined":r.toString();function yMe(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Cv(r){let e=yMe(`${r}:trace`);return hs.default.enabled(`${r}:trace`)&&hs.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,hs.default)(`${r}:trace`)),Object.assign((0,hs.default)(r),{error:(0,hs.default)(`${r}:error`),trace:e})}var Yae=Symbol.for("@libp2p/peer-id");var wMe=Symbol.for("nodejs.util.inspect.custom"),Qae=Object.values(S1).map(r=>r.decoder).reduce((r,e)=>r.or(e),S1.identity.decoder),Xae=114,Zae=36,Jae=37,EMe,D5=class{constructor(e){B(this,"type");B(this,"multihash");B(this,"privateKey");B(this,"publicKey");B(this,"string");B(this,EMe,!0);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()})`}toString(){return this.string==null&&(this.string=Qi.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Nr.createV1(Xae,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){var t;if(e instanceof Uint8Array)return mt(this.multihash.bytes,e);if(typeof e=="string")return bMe(e).equals(this);if(((t=e==null?void 0:e.multihash)==null?void 0:t.bytes)!=null)return mt(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[(EMe=Yae,wMe)](){return`PeerId(${this.toString()})`}},O5=class extends D5{constructor(t){super({...t,type:"RSA"});B(this,"type","RSA");B(this,"publicKey");this.publicKey=t.publicKey}},L5=class extends D5{constructor(t){super({...t,type:"Ed25519"});B(this,"type","Ed25519");B(this,"publicKey");this.publicKey=t.multihash.digest}},B5=class extends D5{constructor(t){super({...t,type:"secp256k1"});B(this,"type","secp256k1");B(this,"publicKey");this.publicKey=t.multihash.digest}};function bMe(r,e){if(e=e??Qae,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=_y(Qi.decode(`z${r}`));return r.startsWith("12D")?new L5({multihash:t}):r.startsWith("16U")?new B5({multihash:t}):new O5({multihash:t})}return oL(Qae.decode(r))}function oL(r){try{let e=_y(r);if(e.code===A8.code){if(e.digest.length===Zae)return new L5({multihash:e});if(e.digest.length===Jae)return new B5({multihash:e})}if(e.code===T8.code)return new O5({multihash:e})}catch{return _Me(Nr.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function _Me(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Xae)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===T8.code)return new O5({multihash:r.multihash});if(e.code===A8.code){if(e.digest.length===Zae)return new L5({multihash:r.multihash});if(e.digest.length===Jae)return new B5({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function ia(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)(o==null?void 0:o.removeEventListener)!=null&&o.removeEventListener("abort",t)}for(let o of r){if((o==null?void 0:o.aborted)===!0){t();break}(o==null?void 0:o.addEventListener)!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)(o==null?void 0:o.removeEventListener)!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var r0=Cv("libp2p:delegated-peer-routing"),ece=3e4,vMe=4,tce;(function(r){r[r.SENDING_QUERY=0]="SENDING_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADDING_PEER=6]="ADDING_PEER",r[r.DIALING_PEER=7]="DIALING_PEER"})(tce||(tce={}));var rce;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(rce||(rce={}));var sL=class{constructor(e){B(this,"client");B(this,"httpQueue");B(this,"started");B(this,"abortController");if(e==null)throw new Error("missing ipfs http client");this.client=e,this.started=!1,this.abortController=new AbortController,this.httpQueue=new qn({concurrency:vMe});let{protocol:t,host:n,port:i}=e.getEndpointConfig();r0(`enabled DelegatedPeerRouting via ${t}://${n}:${i}`)}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.abortController.abort(),this.abortController=new AbortController,this.started=!1}async findPeer(e,t={}){r0("findPeer starts: %p",e),t.timeout=t.timeout??ece;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise;for await(let s of this.client.dht.findPeer(e,{...t,signal:n}))if(s.name==="FINAL_PEER"&&s.peer.multiaddrs.length>0)return{id:s.peer.id,multiaddrs:s.peer.multiaddrs,protocols:[]};throw new J("Not found","ERR_NOT_FOUND")}catch(s){throw r0.error("findPeer errored: %o",s),s}finally{n.clear(),o.resolve(),r0("findPeer finished: %p",e)}}async*getClosestPeers(e,t={}){let n,i=Nr.asCID(e);i!=null?n=i:n=oL(e),r0("getClosestPeers starts: %s",n),t.timeout=t.timeout??ece;let o=ia([this.abortController.signal,t.signal]),s=Qt(),a=Qt();this.httpQueue.add(async()=>(s.resolve(),a.promise));try{await s.promise;for await(let c of this.client.dht.query(n,{...t,signal:o}))c.name==="PEER_RESPONSE"&&(yield*c.closer.map(u=>({id:u.id,multiaddrs:u.multiaddrs,protocols:[]})))}catch(c){throw r0.error("getClosestPeers errored:",c),c}finally{o.clear(),a.resolve(),r0("getClosestPeers finished: %b",e)}}};function nce(r){return()=>new sL(r)}var sce=C(ee(),1);function xMe(r){return r[Symbol.asyncIterator]!=null}function SMe(r){if(xMe(r))return(async()=>{for await(let e of r);})();for(let e of r);}var aL=SMe;var To=Cv("libp2p:delegated-content-routing"),Pv=3e4,AMe=4,TMe=2,ice;(function(r){r[r.SENDING_QUERY=0]="SENDING_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADDING_PEER=6]="ADDING_PEER",r[r.DIALING_PEER=7]="DIALING_PEER"})(ice||(ice={}));var oce;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(oce||(oce={}));var cL=class{constructor(e){B(this,"client");B(this,"httpQueue");B(this,"httpQueueRefs");B(this,"started");B(this,"abortController");if(e==null)throw new Error("missing ipfs http client");this.client=e,this.started=!1,this.abortController=new AbortController,this.httpQueue=new qn({concurrency:AMe}),this.httpQueueRefs=new qn({concurrency:TMe});let{protocol:t,host:n,port:i}=e.getEndpointConfig();To(`enabled DelegatedContentRouting via ${t}://${n}:${i}`)}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.httpQueueRefs.clear(),this.abortController.abort(),this.abortController=new AbortController,this.started=!1}async*findProviders(e,t={}){To("findProviders starts: %c",e),t.timeout=t.timeout??Pv;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise;for await(let s of this.client.dht.findProvs(e,{...t,signal:n}))s.name==="PROVIDER"&&(yield*s.providers.map(a=>({id:a.id,protocols:[],multiaddrs:a.multiaddrs})))}catch(s){throw To.error("findProviders errored:",s),s}finally{n.clear(),o.resolve(),To("findProviders finished: %c",e)}}async provide(e,t={}){To("provide starts: %c",e),t.timeout=t.timeout??Pv;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise,await this.client.block.stat(e,{...t,signal:n}),await aL(this.client.dht.provide(e,{...t,signal:n}))}catch(s){throw To.error("provide errored:",s),s}finally{n.clear(),o.resolve(),To("provide finished: %c",e)}}async put(e,t,n={}){To("put value start: %b",e),n.timeout=n.timeout??Pv;let i=ia([this.abortController.signal,n.signal]),o=Qt(),s=Qt();this.httpQueue.add(async()=>(o.resolve(),s.promise));try{await o.promise,await aL(this.client.dht.put(e,t,{...n,signal:i}))}catch(a){throw To.error("put errored:",a),a}finally{i.clear(),s.resolve(),To("put finished: %b",e)}}async get(e,t={}){To("get value start: %b",e),t.timeout=t.timeout??Pv;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise;for await(let s of this.client.dht.get(e,{...t,signal:n}))if(s.name==="VALUE")return To("get value finished: %b",e),s.value;throw(0,sce.default)(new Error("Not found"),"ERR_NOT_FOUND")}catch(s){throw To.error("put errored:",s),s}finally{n.clear(),o.resolve(),To("put finished: %b",e)}}};function ace(r){return()=>new cL(r)}var IMe=r=>Promise.reject(new Error(`No base found for "${r}"`)),F2=class{constructor(e){this._basesByName={},this._basesByPrefix={},this._loadBase=e.loadBase||IMe;for(let t of e.bases)this.addBase(t)}addBase(e){if(this._basesByName[e.name]||this._basesByPrefix[e.prefix])throw new Error(`Codec already exists for codec "${e.name}"`);this._basesByName[e.name]=e,this._basesByPrefix[e.prefix]=e}removeBase(e){delete this._basesByName[e.name],delete this._basesByPrefix[e.prefix]}async getBase(e){if(this._basesByName[e])return this._basesByName[e];if(this._basesByPrefix[e])return this._basesByPrefix[e];let t=await this._loadBase(e);return this._basesByName[t.name]==null&&this._basesByPrefix[t.prefix]==null&&this.addBase(t),t}listBases(){return Object.values(this._basesByName)}};var RMe=r=>Promise.reject(new Error(`No codec found for "${r}"`)),z2=class{constructor(e){this._codecsByName={},this._codecsByCode={},this._loadCodec=e.loadCodec||RMe;for(let t of e.codecs)this.addCodec(t)}addCodec(e){if(this._codecsByName[e.name]||this._codecsByCode[e.code])throw new Error(`Resolver already exists for codec "${e.name}"`);this._codecsByName[e.name]=e,this._codecsByCode[e.code]=e}removeCodec(e){delete this._codecsByName[e.name],delete this._codecsByCode[e.code]}async getCodec(e){let t=typeof e=="string"?this._codecsByName:this._codecsByCode;if(t[e])return t[e];let n=await this._loadCodec(e);return t[e]==null&&this.addCodec(n),n}listCodecs(){return Object.values(this._codecsByName)}};var CMe=r=>Promise.reject(new Error(`No hasher found for "${r}"`)),V2=class{constructor(e){this._hashersByName={},this._hashersByCode={},this._loadHasher=e.loadHasher||CMe;for(let t of e.hashers)this.addHasher(t)}addHasher(e){if(this._hashersByName[e.name]||this._hashersByCode[e.code])throw new Error(`Resolver already exists for codec "${e.name}"`);this._hashersByName[e.name]=e,this._hashersByCode[e.code]=e}removeHasher(e){delete this._hashersByName[e.name],delete this._hashersByCode[e.code]}async getHasher(e){let t=typeof e=="string"?this._hashersByName:this._hashersByCode;if(t[e])return t[e];let n=await this._loadHasher(e);return t[e]==null&&this.addHasher(n),n}listHashers(){return Object.values(this._hashersByName)}};var pu=C(C6(),1);var n0=C(O1(),1);function uL(r){try{r=zm(yt(r))}catch{}return r=r.toString(),r}var cce=()=>{};var uce=j("ipfs-http-client:lib:error-handler"),PMe=et.bind({ignoreUndefined:!0}),kMe=pu.isBrowser||pu.isWebWorker?location.protocol:"http",NMe=pu.isBrowser||pu.isWebWorker?location.hostname:"localhost",DMe=pu.isBrowser||pu.isWebWorker?location.port:"5001",OMe=(r={})=>{let e,t={},n;if(typeof r=="string"||F_(r))e=new URL(uL(r));else if(r instanceof URL)e=r;else if(typeof r.url=="string"||F_(r.url))e=new URL(uL(r.url)),t=r;else if(r.url instanceof URL)e=r.url,t=r;else{t=r||{};let i=(t.protocol||kMe).replace(":",""),o=(t.host||NMe).split(":")[0],s=t.port||DMe;e=new URL(`${i}://${o}:${s}`)}if(t.apiPath?e.pathname=t.apiPath:(e.pathname==="/"||e.pathname===void 0)&&(e.pathname="api/v0"),pu.isNode){let i=cce(e);n=t.agent||new i({keepAlive:!0,maxSockets:6})}return{...t,host:e.host,protocol:e.protocol.replace(":",""),port:Number(e.port),apiPath:e.pathname,url:e,agent:n}},LMe=async r=>{let e;try{if((r.headers.get("Content-Type")||"").startsWith("application/json")){let n=await r.json();uce(n),e=n.Message||n.message}else e=await r.text()}catch(n){uce("Failed to parse error response",n),e=n.message}let t=new n0.default.HTTPError(r);throw e&&(e.includes("deadline has elapsed")&&(t=new n0.default.TimeoutError),e&&e.includes("context deadline exceeded")&&(t=new n0.default.TimeoutError)),e&&e.includes("request timed out")&&(t=new n0.default.TimeoutError),e&&(t.message=e),t},BMe=/[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g,lce=r=>r.replace(BMe,function(e){return"-"+e.toLowerCase()}),MMe=r=>typeof r=="string"?Cf(r):r,Hd=class extends n0.default{constructor(e={}){let t=OMe(e);super({timeout:MMe(t.timeout||0)||void 0,headers:t.headers,base:`${t.url}`,handleError:LMe,transformSearchParams:i=>{let o=new URLSearchParams;for(let[s,a]of i)a!=="undefined"&&a!=="null"&&s!=="signal"&&o.append(lce(s),a),s==="timeout"&&!isNaN(a)&&o.append(lce(s),a);return o},agent:t.agent}),delete this.get,delete this.put,delete this.delete,delete this.options;let n=this.fetch;this.fetch=(i,o={})=>(typeof i=="string"&&!i.startsWith("/")&&(i=`${t.url}/${i}`),n.call(this,i,PMe(o,{method:"POST"})))}},UAt=n0.default.HTTPError;var D=r=>e=>r(new Hd(e),e);function kv(r){if(r!=null)return typeof r=="string"?r:r.toString(8).padStart(4,"0")}var fce=C(ee(),1);function Nv(r){if(r==null)return;let e;if(r.secs!=null&&(e={secs:r.secs,nsecs:r.nsecs}),r.Seconds!=null&&(e={secs:r.Seconds,nsecs:r.FractionalNanoseconds}),Array.isArray(r)&&(e={secs:r[0],nsecs:r[1]}),r instanceof Date){let t=r.getTime(),n=Math.floor(t/1e3);e={secs:n,nsecs:(t-n*1e3)*1e3}}if(Object.prototype.hasOwnProperty.call(e,"secs")){if(e!=null&&e.nsecs!=null&&(e.nsecs<0||e.nsecs>999999999))throw(0,fce.default)(new Error("mtime-nsecs must be within the range [0,999999999]"),"ERR_INVALID_MTIME_NSECS");return e}}function M({arg:r,searchParams:e,hashAlg:t,mtime:n,mode:i,...o}={}){e&&(o={...o,...e}),t&&(o.hash=t),n!=null&&(n=Nv(n),o.mtime=n.secs,o.mtimeNsecs=n.nsecs),i!=null&&(o.mode=kv(i)),o.timeout&&!isNaN(o.timeout)&&(o.timeout=`${o.timeout}ms`),r==null?r=[]:Array.isArray(r)||(r=[r]);let s=new URLSearchParams(o);return r.forEach(a=>s.append("arg",a)),s}var dce=D(r=>{async function e(t={}){return((await(await r.post("bitswap/wantlist",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Keys||[]).map(i=>z.parse(i["/"]))}return e});var hce=D(r=>{async function e(t,n={}){return((await(await r.post("bitswap/wantlist",{signal:n.signal,searchParams:M({...n,peer:t.toString()}),headers:n.headers})).json()).Keys||[]).map(o=>z.parse(o["/"]))}return e});var Dv=D(r=>{async function e(t={}){let n=await r.post("bitswap/stat",{searchParams:M(t),signal:t.signal,headers:t.headers});return UMe(await n.json())}return e});function UMe(r){return{provideBufLen:r.ProvideBufLen,wantlist:(r.Wantlist||[]).map(e=>z.parse(e["/"])),peers:(r.Peers||[]).map(e=>Oe(e)),blocksReceived:BigInt(r.BlocksReceived),dataReceived:BigInt(r.DataReceived),blocksSent:BigInt(r.BlocksSent),dataSent:BigInt(r.DataSent),dupBlksReceived:BigInt(r.DupBlksReceived),dupDataReceived:BigInt(r.DupDataReceived)}}var pce=D(r=>{async function e(t,n={}){return(await r.post("bitswap/unwant",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers})).json()}return e});function mce(r){return{wantlist:dce(r),wantlistForPeer:hce(r),unwant:pce(r),stat:Dv(r)}}var Ov=D(r=>{async function e(t,n={}){let i=await r.post("block/get",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers});return new Uint8Array(await i.arrayBuffer())}return e});var yce=C(ee(),1);async function wce(r){if(qs(r))return new Blob([r]);if(typeof r=="string"||r instanceof String)return new Blob([r.toString()]);if(ul(r))return r;if(ll(r)&&(r=yo(r)),Symbol.iterator in r||Symbol.asyncIterator in r){let e=ja(r),{value:t,done:n}=await e.peek();if(n)return gce(e);if(e.push(t),Number.isInteger(t))return new Blob([Uint8Array.from(await tp(e))]);if(qs(t)||typeof t=="string"||t instanceof String)return gce(e)}throw(0,yce.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT")}async function gce(r){let e=[];for await(let t of r)e.push(t);return new Blob(e)}function bce(r){return eE(r,wce,!0)}function _ce(r){if(r!=null)return typeof r=="string"?r:r.toString(8).padStart(4,"0")}async function Dn(r,e,t={}){let n=[],i=new FormData,o=0,s=0;for await(let{content:a,path:c,mode:u,mtime:l}of bce(r)){let f="",h=a?"file":"dir";o>0&&(f=`-${o}`);let d=h+f,p=[];if(u!=null&&p.push(`mode=${_ce(u)}`),l!=null){let{secs:g,nsecs:w}=l;p.push(`mtime=${g}`),w!=null&&p.push(`mtime-nsecs=${w}`)}if(p.length&&(d=`${d}?${p.join("&")}`),a){i.set(d,a,c!=null?encodeURIComponent(c):void 0);let g=s+a.size;n.push({name:c,start:s,end:g}),s=g}else if(c!=null)i.set(d,new File([""],encodeURIComponent(c),{type:"application/x-directory"}));else throw new Error("path or content or both must be set");o++}return{total:s,parts:n,headers:t,body:i}}var Ece=C(Da(),1);function FMe(r){return r.filter(Boolean)}function On(...r){return(0,Ece.anySignal)(FMe(r))}var vce=D(r=>{async function e(t,n={}){let i=new AbortController,o=On(i.signal,n.signal),s;try{s=await(await r.post("block/put",{signal:o,searchParams:M(n),...await Dn([t],i,n.headers)})).json()}catch(a){if(n.format==="dag-pb")return e(t,{...n,format:"protobuf"});if(n.format==="dag-cbor")return e(t,{...n,format:"cbor"});throw a}return z.parse(s.Key)}return e});var xce=D(r=>{async function*e(t,n={}){Array.isArray(t)||(t=[t]);let i=await r.post("block/rm",{signal:n.signal,searchParams:M({arg:t.map(o=>o.toString()),"stream-channels":!0,...n}),headers:n.headers});for await(let o of i.ndjson())yield zMe(o)}return e});function zMe(r){let e={cid:z.parse(r.Hash)};return r.Error&&(e.error=new Error(r.Error)),e}var Sce=D(r=>{async function e(t,n={}){let o=await(await r.post("block/stat",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers})).json();return{cid:z.parse(o.Key),size:o.Size}}return e});function Ace(r){return{get:Ov(r),put:vce(r),rm:xce(r),stat:Sce(r)}}var Tce=D(r=>{async function e(t,n={}){let i=await r.post("bootstrap/add",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Peers:o}=await i.json();return{Peers:o.map(s=>yt(s))}}return e});var Ice=D(r=>{async function e(t={}){let n=await r.post("bootstrap/rm",{signal:t.signal,searchParams:M({...t,all:!0}),headers:t.headers}),{Peers:i}=await n.json();return{Peers:i.map(o=>yt(o))}}return e});var Rce=D(r=>{async function e(t={}){let n=await r.post("bootstrap/list",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Peers:i}=await n.json();return{Peers:i.map(o=>yt(o))}}return e});var Cce=D(r=>{async function e(t={}){let n=await r.post("bootstrap/add",{signal:t.signal,searchParams:M({...t,default:!0}),headers:t.headers}),{Peers:i}=await n.json();return{Peers:i.map(o=>yt(o))}}return e});var Pce=D(r=>{async function e(t,n={}){let i=await r.post("bootstrap/rm",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Peers:o}=await i.json();return{Peers:o.map(s=>yt(s))}}return e});function kce(r){return{add:Tce(r),clear:Ice(r),list:Rce(r),reset:Cce(r),rm:Pce(r)}}var Nce=D(r=>{async function e(t,n={}){let o=await(await r.post("config/profile/apply",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return{original:o.OldCfg,updated:o.NewCfg}}return e});function kt(r){if(r==null)return r;let e=/^[A-Z]+$/,t={};return Object.keys(r).reduce((n,i)=>(e.test(i)?n[i.toLowerCase()]=r[i]:e.test(i[0])?n[i[0].toLowerCase()+i.slice(1)]=r[i]:n[i]=r[i],n),t)}var Dce=D(r=>{async function e(t={}){return(await(await r.post("config/profile/list",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).map(o=>kt(o))}return e});function Oce(r){return{apply:Nce(r),list:Dce(r)}}var Lce=D(r=>async(t,n={})=>{if(!t)throw new Error("key argument is required");return(await(await r.post("config",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json()).Value});var Bce=D(r=>async(t={})=>await(await r.post("config/show",{signal:t.signal,searchParams:M({...t}),headers:t.headers})).json());var Mce=D(r=>async(t,n={})=>{let i=new AbortController,o=On(i.signal,n.signal);await(await r.post("config/replace",{signal:o,searchParams:M(n),...await Dn([Ie(JSON.stringify(t))],i,n.headers)})).text()});var Uce=D(r=>async(t,n,i={})=>{if(typeof t!="string")throw new Error("Invalid key type");let o={...i,...VMe(t,n)};await(await r.post("config",{signal:i.signal,searchParams:M(o),headers:i.headers})).text()}),VMe=(r,e)=>{switch(typeof e){case"boolean":return{arg:[r,e.toString()],bool:!0};case"string":return{arg:[r,e]};default:return{arg:[r,JSON.stringify(e)],json:!0}}};function Fce(r){return{getAll:Bce(r),get:Lce(r),set:Uce(r),replace:Mce(r),profiles:Oce(r)}}var zce=D(r=>{async function*e(t,n={}){yield*(await r.post("dag/export",{signal:n.signal,searchParams:M({arg:t.toString()}),headers:n.headers})).iterator()}return e});var lL=C(ee(),1);async function*fL(r,e,t,n,i){let o=async u=>{let l=await t.getCodec(u.code),f=await n(u,i);return l.decode(f)},s=e.split("/").filter(Boolean),a=await o(r),c=r;for(;s.length;){let u=s.shift();if(!u)throw(0,lL.default)(new Error(`Could not resolve path "${e}"`),"ERR_INVALID_PATH");if(Object.prototype.hasOwnProperty.call(a,u))a=a[u],yield{value:a,remainderPath:s.join("/")};else throw(0,lL.default)(new Error(`no link named "${u}" under ${c}`),"ERR_NO_LINK");let l=z.asCID(a);l&&(c=l,a=await o(a))}yield{value:a,remainderPath:""}}var Vce=C(ee(),1);var Kce=(r,e)=>D((n,i)=>{let o=Ov(i);return async(a,c={})=>{if(c.path){let d=c.localResolve?await mp(fL(a,c.path,r,o,c)):await Dr(fL(a,c.path,r,o,c));if(!d)throw(0,Vce.default)(new Error("Not found"),"ERR_NOT_FOUND");return d}let u=await r.getCodec(a.code),l=await o(a,c);return{value:u.decode(l),remainderPath:""}}})(e);var $ce=D(r=>{async function*e(t,n={}){let i=new AbortController,o=On(i.signal,n.signal),{headers:s,body:a}=await Dn(t,i,n.headers),c=await r.post("dag/import",{signal:o,headers:s,body:a,searchParams:M({"pin-roots":n.pinRoots})});for await(let{Root:u}of c.ndjson())if(u!==void 0){let{Cid:{"/":l},PinErrorMsg:f}=u;yield{root:{cid:z.parse(l),pinErrorMsg:f}}}}return e});var Lv=(r,e)=>D(n=>async(o,s={})=>{let a={storeCodec:"dag-cbor",hashAlg:"sha2-256",...s},c;if(a.inputCodec){if(!(o instanceof Uint8Array))throw new Error("Can only inputCodec on raw bytes that can be decoded");c=o}else c=(await r.getCodec(a.storeCodec)).encode(o),a.inputCodec=a.storeCodec;let u=new AbortController,l=On(u.signal,a.signal),h=await(await n.post("dag/put",{timeout:a.timeout,signal:l,searchParams:M(a),...await Dn([c],u,a.headers)})).json();return z.parse(h.Cid["/"])})(e);var qce=D(r=>async(t,n={})=>{let o=await(await r.post("dag/resolve",{signal:n.signal,searchParams:M({arg:`${t}${n.path?`/${n.path}`.replace(/\/[/]+/g,"/"):""}`,...n}),headers:n.headers})).json();return{cid:z.parse(o.Cid["/"]),remainderPath:o.RemPath}});function Hce(r,e){return{export:zce(e),get:Kce(r,e),import:$ce(e),put:Lv(r,e),resolve:qce(e)}}var oa=r=>{if(r.Type===0)return{name:"SENDING_QUERY",type:r.Type};if(r.Type===1)return{from:Oe(r.ID),name:"PEER_RESPONSE",type:r.Type,messageType:0,messageName:"PUT_VALUE",closer:(r.Responses||[]).map(({ID:e,Addrs:t})=>({id:Oe(e),multiaddrs:t.map(n=>yt(n)),protocols:[]})),providers:(r.Responses||[]).map(({ID:e,Addrs:t})=>({id:Oe(e),multiaddrs:t.map(n=>yt(n)),protocols:[]}))};if(r.Type===2){let e={id:r.ID??Oe(r.ID),multiaddrs:[],protocols:[]};return r.Responses&&r.Responses.length&&(e={id:Oe(r.Responses[0].ID),multiaddrs:r.Responses[0].Addrs.map(t=>yt(t)),protocols:[]}),{name:"FINAL_PEER",type:r.Type,peer:e}}if(r.Type===3)return{name:"QUERY_ERROR",type:r.Type,error:new Error(r.Extra)};if(r.Type===4)return{name:"PROVIDER",type:r.Type,providers:r.Responses.map(({ID:e,Addrs:t})=>({id:Oe(e),multiaddrs:t.map(n=>yt(n)),protocols:[]}))};if(r.Type===5)return{name:"VALUE",type:r.Type,value:Ie(r.Extra,"base64pad")};if(r.Type===6){let e=r.Responses.map(({ID:t})=>Oe(t));if(!e.length)throw new Error("No peer found");return{name:"ADDING_PEER",type:r.Type,peer:e[0]}}if(r.Type===7)return{name:"DIALING_PEER",type:r.Type,peer:Oe(r.ID)};throw new Error("Unknown DHT event type")};var Gce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/findpeer",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});var jce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/findprovs",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});var Wce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/get",{signal:n.signal,searchParams:M({arg:t instanceof Uint8Array?re(t):t.toString(),...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});var Yce=D(r=>{async function*e(t,n={recursive:!1}){let i=Array.isArray(t)?t:[t],o=await r.post("dht/provide",{signal:n.signal,searchParams:M({arg:i.map(s=>s.toString()),...n}),headers:n.headers});for await(let s of o.ndjson())yield oa(s)}return e});var Qce=D(r=>{async function*e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal),a=await r.post("dht/put",{signal:s,searchParams:M({arg:t instanceof Uint8Array?re(t):t.toString(),...i}),...await Dn([n],o,i.headers)});for await(let c of a.ndjson())yield oa(c)}return e});var Xce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/query",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});function Zce(r){return{findPeer:Gce(r),findProvs:jce(r),get:Wce(r),provide:Yce(r),put:Qce(r),query:Xce(r)}}var Jce=D(r=>{async function e(t={}){return(await r.post("diag/cmds",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()}return e});var eue=D(r=>{async function e(t={}){return(await r.post("diag/net",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()}return e});var tue=D(r=>{async function e(t={}){return(await r.post("diag/sys",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()}return e});function rue(r){return{cmds:Jce(r),net:eue(r),sys:tue(r)}}var nue=D(r=>{async function e(t,n,i={}){await(await r.post("files/chmod",{signal:i.signal,searchParams:M({arg:t,mode:n,...i}),headers:i.headers})).text()}return e});var iue=D(r=>{async function e(t,n,i={}){let o=Array.isArray(t)?t:[t];await(await r.post("files/cp",{signal:i.signal,searchParams:M({arg:o.concat(n).map(a=>z.asCID(a)?`/ipfs/${a}`:a),...i}),headers:i.headers})).text()}return e});var oue=D(r=>{async function e(t,n={}){if(!t||typeof t!="string")throw new Error("ipfs.files.flush requires a path");let o=await(await r.post("files/flush",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return z.parse(o.Cid)}return e});function M5(r){let e=kt(r);return Object.prototype.hasOwnProperty.call(e,"mode")&&(e.mode=parseInt(e.mode,8)),Object.prototype.hasOwnProperty.call(e,"mtime")&&(e.mtime={secs:e.mtime,nsecs:e.mtimeNsecs||0},delete e.mtimeNsecs),e}var aue=D(r=>{async function*e(t,n={}){if(!t)throw new Error("ipfs.files.ls requires a path");let i=await r.post("files/ls",{signal:n.signal,searchParams:M({arg:z.asCID(t)?`/ipfs/${t}`:t,long:!0,...n,stream:!0}),headers:n.headers});for await(let o of i.ndjson())if("Entries"in o)for(let s of o.Entries||[])yield sue(M5(s));else yield sue(M5(o))}return e});function sue(r){return r.hash&&(r.cid=z.parse(r.hash)),delete r.hash,r.type=r.type===1?"directory":"file",r}var cue=D(r=>{async function e(t,n={}){await(await r.post("files/mkdir",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).text()}return e});var uue=D(r=>{async function e(t,n,i={}){Array.isArray(t)||(t=[t]),await(await r.post("files/mv",{signal:i.signal,searchParams:M({arg:t.concat(n),...i}),headers:i.headers})).text()}return e});var due=C(fue(),1),hue=D(r=>{async function*e(t,n={}){let i=await r.post("files/read",{signal:n.signal,searchParams:M({arg:t,count:n.length,...n}),headers:n.headers});yield*(0,due.default)(i.body)}return e});var pue=C(O1(),1),mue=D(r=>{async function e(t,n={}){let i=await r.post("files/rm",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),o=await i.text();if(o!==""){let s=new pue.default.HTTPError(i);throw s.message=o,s}}return e});var Bv=D(r=>{async function e(t,n={}){let o=await(await r.post("files/stat",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return o.WithLocality=o.WithLocality||!1,QMe(M5(o))}return e});function QMe(r){return r.cid=z.parse(r.hash),delete r.hash,r}var gue=D(r=>{async function e(t,n={}){await(await r.post("files/touch",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).text()}return e});var yue=D(r=>{async function e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal);await(await r.post("files/write",{signal:s,searchParams:M({arg:t,streamChannels:!0,count:i.length,...i}),...await Dn([{content:n,path:"arg",mode:kv(i.mode),mtime:Nv(i.mtime)}],o,i.headers)})).text()}return e});function wue(r){return{chmod:nue(r),cp:iue(r),flush:oue(r),ls:aue(r),mkdir:cue(r),mv:uue(r),read:hue(r),rm:mue(r),stat:Bv(r),touch:gue(r),write:yue(r)}}var bue=C(ee(),1),_ue=D(r=>async(t,n,i={})=>{throw(0,bue.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")});var Eue=D(r=>{async function e(t,n){let i=n??{type:"Ed25519"},s=await(await r.post("key/gen",{signal:i.signal,searchParams:M({arg:t,...i}),headers:i.headers})).json();return kt(s)}return e});var vue=D(r=>{async function e(t,n,i,o={}){let a=await(await r.post("key/import",{signal:o.signal,searchParams:M({arg:t,pem:n,password:i,...o}),headers:o.headers})).json();return kt(a)}return e});var xue=C(ee(),1),Sue=D(r=>async(t,n={})=>{throw(0,xue.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")});var Aue=D(r=>{async function e(t={}){return((await(await r.post("key/list",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Keys||[]).map(o=>kt(o))}return e});var Tue=D(r=>{async function e(t,n,i={}){let o=await r.post("key/rename",{signal:i.signal,searchParams:M({arg:[t,n],...i}),headers:i.headers});return kt(await o.json())}return e});var Iue=D(r=>{async function e(t,n={}){let o=await(await r.post("key/rm",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return kt(o.Keys[0])}return e});function Rue(r){return{export:_ue(r),gen:Eue(r),import:vue(r),info:Sue(r),list:Aue(r),rename:Tue(r),rm:Iue(r)}}var Cue=D(r=>{async function e(t,n,i={}){let o=await r.post("log/level",{signal:i.signal,searchParams:M({arg:[t,n],...i}),headers:i.headers});return kt(await o.json())}return e});var Pue=D(r=>{async function e(t={}){return(await(await r.post("log/ls",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Strings}return e});var kue=D(r=>{async function*e(t={}){yield*(await r.post("log/tail",{signal:t.signal,searchParams:M(t),headers:t.headers})).ndjson()}return e});function Nue(r){return{level:Cue(r),ls:Pue(r),tail:kue(r)}}var Due=D(r=>{async function e(t,n={}){let i=await r.post("name/publish",{signal:n.signal,searchParams:M({arg:`${t}`,...n}),headers:n.headers});return kt(await i.json())}return e});var Oue=D(r=>{async function*e(t,n={}){let i=await r.post("name/resolve",{signal:n.signal,searchParams:M({arg:t,stream:!0,...n}),headers:n.headers});for await(let o of i.ndjson())yield o.Path}return e});var Lue=D(r=>{async function e(t,n={}){let i=await r.post("name/pubsub/cancel",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers});return kt(await i.json())}return e});var Bue=D(r=>{async function e(t={}){let n=await r.post("name/pubsub/state",{signal:t.signal,searchParams:M(t),headers:t.headers});return kt(await n.json())}return e});var Mue=D(r=>{async function e(t={}){return(await(await r.post("name/pubsub/subs",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Strings||[]}return e});function Uue(r){return{cancel:Lue(r),state:Bue(r),subs:Mue(r)}}function Fue(r){return{publish:Due(r),resolve:Oue(r),pubsub:Uue(r)}}var zue=D(r=>{async function e(t,n={}){let o=await(await r.post("object/data",{signal:n.signal,searchParams:M({arg:`${t instanceof Uint8Array?z.decode(t):t}`,...n}),headers:n.headers})).arrayBuffer();return new Uint8Array(o,0,o.byteLength)}return e});var Vue=D(r=>{async function e(t,n={}){let o=await(await r.post("object/get",{signal:n.signal,searchParams:M({arg:`${t instanceof Uint8Array?z.decode(t):t}`,dataEncoding:"base64",...n}),headers:n.headers})).json();return{Data:Ie(o.Data,"base64pad"),Links:(o.Links||[]).map(s=>({Name:s.Name,Hash:z.parse(s.Hash),Tsize:s.Size}))}}return e});var Kue=D(r=>{async function e(t,n={}){return((await(await r.post("object/links",{signal:n.signal,searchParams:M({arg:`${t instanceof Uint8Array?z.decode(t):t}`,...n}),headers:n.headers})).json()).Links||[]).map(s=>({Name:s.Name,Tsize:s.Size,Hash:z.parse(s.Hash)}))}return e});var $ue=D(r=>{async function e(t={}){let n=await r.post("object/new",{signal:t.signal,searchParams:M({arg:t.template,...t}),headers:t.headers}),{Hash:i}=await n.json();return z.parse(i)}return e});var que=(r,e)=>D(n=>{let i=Lv(r,e);async function o(s,a={}){return i(s,{...a,storeCodec:"dag-pb",hashAlg:"sha2-256",version:1})}return o})(e);var Hue=D(r=>{async function e(t,n={}){let o=await(await r.post("object/stat",{signal:n.signal,searchParams:M({arg:`${t}`,...n}),headers:n.headers})).json();return{...o,Hash:z.parse(o.Hash)}}return e});var Gue=D(r=>{async function e(t,n,i={}){let o=await r.post("object/patch/add-link",{signal:i.signal,searchParams:M({arg:[`${t}`,n.Name||n.name||"",(n.Hash||n.cid||"").toString()||null],...i}),headers:i.headers}),{Hash:s}=await o.json();return z.parse(s)}return e});var jue=D(r=>{async function e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal),a=await r.post("object/patch/append-data",{signal:s,searchParams:M({arg:`${t}`,...i}),...await Dn([n],o,i.headers)}),{Hash:c}=await a.json();return z.parse(c)}return e});var Wue=D(r=>{async function e(t,n,i={}){let o=await r.post("object/patch/rm-link",{signal:i.signal,searchParams:M({arg:[`${t}`,n.Name||n.name||null],...i}),headers:i.headers}),{Hash:s}=await o.json();return z.parse(s)}return e});var Yue=D(r=>{async function e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal),a=await r.post("object/patch/set-data",{signal:s,searchParams:M({arg:[`${t}`],...i}),...await Dn([n],o,i.headers)}),{Hash:c}=await a.json();return z.parse(c)}return e});function Que(r){return{addLink:Gue(r),appendData:jue(r),rmLink:Wue(r),setData:Yue(r)}}function Xue(r,e){return{data:zue(e),get:Vue(e),links:Kue(e),new:$ue(e),put:que(r,e),stat:Hue(e),patch:Que(e)}}var Mv=D(r=>{async function*e(t,n={}){for await(let{path:i,recursive:o,metadata:s}of Tc(t)){let a=await r.post("pin/add",{signal:n.signal,searchParams:M({...n,arg:i,recursive:o,metadata:s?JSON.stringify(s):void 0,stream:!0}),headers:n.headers});for await(let c of a.ndjson()){if(c.Pins){for(let u of c.Pins)yield z.parse(u);continue}yield z.parse(c)}}}return e});function Zue(r){let e=Mv(r);return D(()=>{async function t(n,i={}){return Dr(e([{path:n,...i}],i))}return t})(r)}function Jue(r,e,t){let n={type:r,cid:z.parse(e)};return t&&(n.metadata=t),n}var ele=D(r=>{async function*e(t={}){let n=[];t.paths&&(n=Array.isArray(t.paths)?t.paths:[t.paths]);let i=await r.post("pin/ls",{signal:t.signal,searchParams:M({...t,arg:n.map(o=>`${o}`),stream:!0}),headers:t.headers});for await(let o of i.ndjson()){if(o.Keys){for(let s of Object.keys(o.Keys))yield Jue(o.Keys[s].Type,s,o.Keys[s].Metadata);return}yield Jue(o.Type,o.Cid,o.Metadata)}}return e});var Uv=D(r=>{async function*e(t,n={}){for await(let{path:i,recursive:o}of Tc(t)){let s=new URLSearchParams(n.searchParams);s.append("arg",`${i}`),o!=null&&s.set("recursive",String(o));let a=await r.post("pin/rm",{signal:n.signal,headers:n.headers,searchParams:M({...n,arg:`${i}`,recursive:o})});for await(let c of a.ndjson()){if(c.Pins){yield*c.Pins.map(u=>z.parse(u));continue}yield z.parse(c)}}}return e});var tle=r=>{let e=Uv(r);return D(()=>{async function t(n,i={}){return Dr(e([{path:n,...i}],i))}return t})(r)};var Fv=({Name:r,Status:e,Cid:t})=>({cid:z.parse(t),name:r,status:e}),rle=r=>{if(typeof r=="string"&&r!=="")return r;throw new TypeError("service name must be passed")},nle=r=>{if(z.asCID(r))return r.toString();throw new TypeError(`CID instance expected instead of ${typeof r}`)},K2=({service:r,cid:e,name:t,status:n,all:i})=>{let o=M({service:rle(r),name:t,force:i?!0:void 0});if(e)for(let s of e)o.append("cid",nle(s));if(n)for(let s of n)o.append("status",s);return o},ile=({cid:r,service:e,background:t,name:n,origins:i})=>{let o=M({arg:nle(r),service:rle(e),name:n,background:t?!0:void 0});if(i)for(let s of i)o.append("origin",s.toString());return o};function ole(r){async function e(t,{timeout:n,signal:i,headers:o,...s}){let a=await r.post("pin/remote/add",{timeout:n,signal:i,headers:o,searchParams:ile({cid:t,...s})});return Fv(await a.json())}return e}function sle(r){async function*e({timeout:t,signal:n,headers:i,...o}){let s=await r.post("pin/remote/ls",{timeout:t,signal:n,headers:i,searchParams:K2(o)});for await(let a of s.ndjson())yield Fv(a)}return e}function ale(r){async function e({timeout:t,signal:n,headers:i,...o}){await r.post("pin/remote/rm",{timeout:t,signal:n,headers:i,searchParams:K2({...o,all:!1})})}return e}function cle(r){async function e({timeout:t,signal:n,headers:i,...o}){await r.post("pin/remote/rm",{timeout:t,signal:n,headers:i,searchParams:K2({...o,all:!0})})}return e}function ule(r){let e=String(r);if(e==="undefined")throw Error("endpoint is required");return e[e.length-1]==="/"?e.slice(0,-1):e}function lle(r){return{service:r.Service,endpoint:new URL(r.ApiEndpoint),...r.Stat&&{stat:XMe(r.Stat)}}}function XMe(r){switch(r.Status){case"valid":{let{Pinning:e,Pinned:t,Queued:n,Failed:i}=r.PinCount;return{status:"valid",pinCount:{queued:n,pinning:e,pinned:t,failed:i}}}case"invalid":return{status:"invalid"};default:return{status:r.Status}}}function fle(r){async function e(t,n){let{endpoint:i,key:o,headers:s,timeout:a,signal:c}=n;await r.post("pin/remote/service/add",{timeout:a,signal:c,searchParams:M({arg:[t,ule(i),o]}),headers:s})}return e}function dle(r){async function e(t={}){let{stat:n,headers:i,timeout:o,signal:s}=t,a=await r.post("pin/remote/service/ls",{timeout:o,signal:s,headers:i,searchParams:n===!0?M({stat:n}):void 0}),{RemoteServices:c}=await a.json();return c.map(lle)}return e}function hle(r){async function e(t,n={}){await r.post("pin/remote/service/rm",{signal:n.signal,headers:n.headers,searchParams:M({arg:t})})}return e}function ple(r){let e=new Hd(r);return{add:fle(e),ls:dle(e),rm:hle(e)}}function mle(r){let e=new Hd(r);return{add:ole(e),ls:sle(e),rm:ale(e),rmAll:cle(e),service:ple(r)}}function gle(r){return{addAll:Mv(r),add:Zue(r),ls:ele(r),rmAll:Uv(r),rm:tle(r),remote:mle(r)}}var yle=r=>Array.isArray(r)?r.map(zv):r,zv=r=>re($2(r)),$2=r=>Gg.decode(r),wle=r=>BigInt(`0x${re(Gg.decode(r),"base16")}`),q2=r=>Gg.encode(Ie(r));var ble=D(r=>{async function e(t={}){let{Strings:n}=await(await r.post("pubsub/ls",{signal:t.signal,searchParams:M(t),headers:t.headers})).json();return yle(n)||[]}return e});var _le=D(r=>{async function e(t,n={}){let i=await r.post("pubsub/peers",{signal:n.signal,searchParams:M({arg:q2(t),...n}),headers:n.headers}),{Strings:o}=await i.json();return o||[]}return e});var Ele=D(r=>{async function e(t,n,i={}){let o=M({arg:q2(t),...i}),s=new AbortController,a=On(s.signal,i.signal);await(await r.post("pubsub/pub",{signal:a,searchParams:o,...await Dn([n],s,i.headers)})).text()}return e});var ZMe=j("ipfs-http-client:pubsub:subscribe"),vle=(r,e)=>D(t=>{async function n(i,o,s={}){s.signal=e.subscribe(i,o,s.signal);let a,c,u=new Promise((f,h)=>{a=f,c=h}),l=setTimeout(()=>a(),1e3);return t.post("pubsub/sub",{signal:s.signal,searchParams:M({arg:q2(i),...s}),headers:s.headers}).catch(f=>{e.unsubscribe(i,o),c(f)}).then(f=>{clearTimeout(l),f&&(JMe(f,{onMessage:h=>{if(o){if(typeof o=="function"){o(h);return}typeof o.handleEvent=="function"&&o.handleEvent(h)}},onEnd:()=>e.unsubscribe(i,o),onError:s.onError}),a())}),u}return n})(r);async function JMe(r,{onMessage:e,onEnd:t,onError:n}){n=n||ZMe;try{for await(let i of r.ndjson())try{if(!i.from)continue;i.from!=null&&i.seqno!=null?e({type:"signed",from:Oe(i.from),data:$2(i.data),sequenceNumber:wle(i.seqno),topic:zv(i.topicIDs[0]),key:$2(i.key??"u"),signature:$2(i.signature??"u")}):e({type:"unsigned",data:$2(i.data),topic:zv(i.topicIDs[0])})}catch(o){o.message=`Failed to parse pubsub message: ${o.message}`,n(o,!1,i)}}catch(i){eUe(i)||n(i,!0)}finally{t()}}var eUe=r=>{switch(r.type){case"aborted":return!0;case"abort":return!0;default:return r.name==="AbortError"}};var xle=(r,e)=>{async function t(n,i){e.unsubscribe(n,i)}return t};var Vv=class{constructor(){this._subs=new Map}subscribe(e,t,n){let i=this._subs.get(e)||[];if(i.find(s=>s.handler===t))throw new Error(`Already subscribed to ${e} with this handler`);let o=new AbortController;return this._subs.set(e,[{handler:t,controller:o}].concat(i)),n&&n.addEventListener("abort",()=>this.unsubscribe(e,t)),o.signal}unsubscribe(e,t){let n=this._subs.get(e)||[],i;t?(this._subs.set(e,n.filter(o=>o.handler!==t)),i=n.filter(o=>o.handler===t)):(this._subs.set(e,[]),i=n),(this._subs.get(e)||[]).length||this._subs.delete(e),i.forEach(o=>o.controller.abort())}};function Sle(r){let e=new Vv;return{ls:ble(r),peers:_le(r),publish:Ele(r),subscribe:vle(r,e),unsubscribe:xle(r,e)}}var Ale=D(r=>{async function*e(t={}){yield*(await r.post("refs/local",{signal:t.signal,transform:kt,searchParams:M(t),headers:t.headers})).ndjson()}return e});var Tle=D((r,e)=>Object.assign(async function*(n,i={}){let o=Array.isArray(n)?n:[n];yield*(await r.post("refs",{signal:i.signal,searchParams:M({arg:o.map(a=>`${a instanceof Uint8Array?z.decode(a):a}`),...i}),headers:i.headers,transform:kt})).ndjson()},{local:Ale(e)}));var Ile=D(r=>{async function*e(t={}){yield*(await r.post("repo/gc",{signal:t.signal,searchParams:M(t),headers:t.headers,transform:i=>({err:i.Error?new Error(i.Error):null,cid:(i.Key||{})["/"]?z.parse(i.Key["/"]):null})})).ndjson()}return e});var Kv=D(r=>{async function e(t={}){let i=await(await r.post("repo/stat",{signal:t.signal,searchParams:M(t),headers:t.headers})).json();return{numObjects:BigInt(i.NumObjects),repoSize:BigInt(i.RepoSize),repoPath:i.RepoPath,version:i.Version,storageMax:BigInt(i.StorageMax)}}return e});var Rle=D(r=>{async function e(t={}){return(await(await r.post("repo/version",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Version}return e});function Cle(r){return{gc:Ile(r),stat:Kv(r),version:Rle(r)}}var Ple=D(r=>{async function*e(t={}){yield*(await r.post("stats/bw",{signal:t.signal,searchParams:M(t),headers:t.headers,transform:i=>({totalIn:BigInt(i.TotalIn),totalOut:BigInt(i.TotalOut),rateIn:parseFloat(i.RateIn),rateOut:parseFloat(i.RateOut)})})).ndjson()}return e});function kle(r){return{bitswap:Dv(r),repo:Kv(r),bw:Ple(r)}}var Nle=D(r=>{async function e(t={}){let n=await r.post("swarm/addrs",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Addrs:i}=await n.json();return Object.keys(i).map(o=>({id:Oe(o),addrs:(i[o]||[]).map(s=>yt(s))}))}return e});var Dle=D(r=>{async function e(t,n={}){let i=await r.post("swarm/connect",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Strings:o}=await i.json();return o||[]}return e});var Ole=D(r=>{async function e(t,n={}){let i=await r.post("swarm/disconnect",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Strings:o}=await i.json();return o||[]}return e});var Lle=D(r=>{async function e(t={}){let n=await r.post("swarm/addrs/local",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Strings:i}=await n.json();return(i||[]).map(o=>yt(o))}return e});var Ble=D(r=>{async function e(t={}){let n=await r.post("swarm/peers",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Peers:i}=await n.json();return(i||[]).map(o=>({addr:yt(o.Addr),peer:Oe(o.Peer),muxer:o.Muxer,latency:o.Latency,streams:o.Streams,direction:o.Direction==null?void 0:o.Direction===0?"inbound":"outbound"}))}return e});function Mle(r){return{addrs:Nle(r),connect:Dle(r),disconnect:Ole(r),localAddrs:Lle(r),peers:Ble(r)}}var $v=D(r=>{async function*e(t,n={}){let i=new AbortController,o=On(i.signal,n.signal),{headers:s,body:a,total:c,parts:u}=await Dn(t,i,n.headers),[l,f]=typeof n.progress=="function"?tUe(c,u,n.progress):[void 0,void 0],h=await r.post("add",{searchParams:M({"stream-channels":!0,...n,progress:!!l}),onUploadProgress:f,signal:o,headers:s,body:a});for await(let d of h.ndjson())d=kt(d),d.hash!==void 0?yield nUe(d):l&&l(d.bytes||0,d.name)}return e}),tUe=(r,e,t)=>e?[void 0,rUe(r,e,t)]:[t,void 0],rUe=(r,e,t)=>{let n=0,i=e.length;return({loaded:o,total:s})=>{let a=Math.floor(o/s*r);for(;n{async function t(n,i={}){return await Dr(e(W_(n),i))}return t})(r)}var Fle=D(r=>{async function*e(t,n={}){yield*(await r.post("cat",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers})).iterator()}return e});var zle=D(r=>async(t={})=>(await r.post("commands",{signal:t.signal,searchParams:M(t),headers:t.headers})).json());var Vle=D(r=>async(t,n={})=>(await(await r.post("dns",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json()).Path);var Kle=D(r=>()=>{let e=new URL(r.opts.base||"");return{host:e.hostname,port:e.port,protocol:e.protocol,pathname:e.pathname,"api-path":e.pathname}});var $le=D(r=>{async function*e(t,n={}){let i={arg:`${t instanceof Uint8Array?z.decode(t):t}`,...n};i.compressionLevel&&(i["compression-level"]=i.compressionLevel,delete i.compressionLevel),yield*(await r.post("get",{signal:n.signal,searchParams:M(i),headers:n.headers})).iterator()}return e});var qv=D(r=>{async function e(t={}){let i=await(await r.post("id",{signal:t.signal,searchParams:M({arg:t.peerId?t.peerId.toString():void 0,...t}),headers:t.headers})).json(),o={...kt(i)};return o.id=Oe(o.id),o.addresses&&(o.addresses=o.addresses.map(s=>yt(s))),o}return e});var qle=r=>{let e=qv(r);async function t(n={}){let i=await e(n);return!!(i&&i.addresses&&i.addresses.length)}return t};var Hle=D((r,e)=>{async function*t(n,i={}){let o=`${n instanceof Uint8Array?z.decode(n):n}`;async function s(c){let u=c.Hash;if(u.includes("/")){let f=u.startsWith("/ipfs/")?u:`/ipfs/${u}`;u=(await Bv(e)(f)).cid}else u=z.parse(u);let l={name:c.Name,path:o+(c.Name?`/${c.Name}`:""),size:c.Size,cid:u,type:iUe(c)};return c.Mode&&(l.mode=parseInt(c.Mode,8)),c.Mtime!==void 0&&c.Mtime!==null&&(l.mtime={secs:c.Mtime},c.MtimeNsecs!==void 0&&c.MtimeNsecs!==null&&(l.mtime.nsecs=c.MtimeNsecs)),l}let a=await r.post("ls",{signal:i.signal,searchParams:M({arg:o,...i}),headers:i.headers});for await(let c of a.ndjson()){if(c=c.Objects,!c)throw new Error("expected .Objects in results");if(c=c[0],!c)throw new Error("expected one array in results.Objects");let u=c.Links;if(!Array.isArray(u))throw new Error("expected one array in results.Objects[0].Links");if(!u.length){yield s(c);return}yield*u.map(s)}}return t});function iUe(r){switch(r.Type){case 1:case 5:return"dir";case 2:return"file";default:return"file"}}var Gle=D(r=>{async function e(t={}){let n=await r.post("dns",{signal:t.signal,searchParams:M(t),headers:t.headers});return kt(await n.json())}return e});var jle=D(r=>{async function*e(t,n={}){yield*(await r.post("ping",{signal:n.signal,searchParams:M({arg:`${t}`,...n}),headers:n.headers,transform:kt})).ndjson()}return e});var Wle=D(r=>{async function e(t,n={}){let i=await r.post("resolve",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Path:o}=await i.json();return o}return e});var Yle=C(ee(),1),Qle=D(r=>async(t={})=>{throw(0,Yle.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")});var Xle=D(r=>{async function e(t={}){await(await r.post("shutdown",{signal:t.signal,searchParams:M(t),headers:t.headers})).text()}return e});var Zle=D(r=>{async function e(t={}){let n=await r.post("version",{signal:t.signal,searchParams:M(t),headers:t.headers});return{...kt(await n.json()),"ipfs-http-client":"1.0.0"}}return e});var cUe=C(dL(),1);function efe(r={}){let e={name:Ii.name,code:Ii.code,encode:u=>u,decode:u=>u},t=Object.values(Vu);(r.ipld&&r.ipld.bases?r.ipld.bases:[]).forEach(u=>t.push(u));let n=new F2({bases:t,loadBase:r.ipld&&r.ipld.loadBase}),i=Object.values(x8);[sr,o1,a1,yy,e].concat(r.ipld&&r.ipld.codecs||[]).forEach(u=>i.push(u));let o=new z2({codecs:i,loadCodec:r.ipld&&r.ipld.loadCodec}),s=Object.values(v8);(r.ipld&&r.ipld.hashers?r.ipld.hashers:[]).forEach(u=>s.push(u));let a=new V2({hashers:s,loadHasher:r.ipld&&r.ipld.loadHasher});return{add:Ule(r),addAll:$v(r),bitswap:mce(r),block:Ace(r),bootstrap:kce(r),cat:Fle(r),commands:zle(r),config:Fce(r),dag:Hce(o,r),dht:Zce(r),diag:rue(r),dns:Vle(r),files:wue(r),get:$le(r),getEndpointConfig:Kle(r),id:qv(r),isOnline:qle(r),key:Rue(r),log:Nue(r),ls:Hle(r),mount:Gle(r),name:Fue(r),object:Xue(o,r),pin:gle(r),ping:jle(r),pubsub:Sle(r),refs:Tle(r),repo:Cle(r),resolve:Wle(r),start:Qle(r),stats:kle(r),stop:Xle(r),swarm:Mle(r),version:Zle(r),bases:n,codecs:o,hashers:a}}var t4=C(ee(),1);var Gd=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function tfe(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function sa(r,e,t){let n=t??{},i=tfe(r);async function*o(){let s,a=()=>{s!=null&&s()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new Gd(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:d}=n;f(new Gd(h,d))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function uUe(r,e,t){return n=>r(sa(n,e,t))}function ps(r,e,t){return{sink:uUe(r.sink,e,{...t,onAbort:void 0}),source:sa(r.source,e,t)}}var lUe=Ye("dns4"),fUe=Ye("dns6"),dUe=Ye("dnsaddr"),H2=qi(Ye("dns"),dUe,lUe,fUe),Hv=qi(Ye("ip4"),Ye("ip6")),V5=qi(_t(Hv,Ye("tcp")),_t(H2,Ye("tcp"))),nfe=_t(Hv,Ye("udp")),hUe=_t(nfe,Ye("utp")),pUe=_t(nfe,Ye("quic")),U5=qi(_t(V5,Ye("ws")),_t(H2,Ye("ws"))),F5=qi(_t(V5,Ye("wss")),_t(H2,Ye("wss"))),hL=qi(_t(V5,Ye("http")),_t(Hv,Ye("http")),_t(H2,Ye("http"))),pL=qi(_t(V5,Ye("https")),_t(Hv,Ye("https")),_t(H2,Ye("https"))),Gv=qi(_t(U5,Ye("p2p-webrtc-star"),Ye("p2p")),_t(F5,Ye("p2p-webrtc-star"),Ye("p2p")),_t(U5,Ye("p2p-webrtc-star")),_t(F5,Ye("p2p-webrtc-star"))),jMt=qi(_t(U5,Ye("p2p-websocket-star"),Ye("p2p")),_t(F5,Ye("p2p-websocket-star"),Ye("p2p")),_t(U5,Ye("p2p-websocket-star")),_t(F5,Ye("p2p-websocket-star"))),ife=qi(_t(hL,Ye("p2p-webrtc-direct"),Ye("p2p")),_t(pL,Ye("p2p-webrtc-direct"),Ye("p2p")),_t(hL,Ye("p2p-webrtc-direct")),_t(pL,Ye("p2p-webrtc-direct"))),z5=qi(U5,F5,hL,pL,Gv,ife,V5,hUe,pUe,H2),WMt=qi(_t(z5,Ye("p2p-stardust"),Ye("p2p")),_t(z5,Ye("p2p-stardust"))),jd=qi(_t(z5,Ye("p2p")),Gv,ife,Ye("p2p")),rfe=qi(_t(jd,Ye("p2p-circuit"),jd),_t(jd,Ye("p2p-circuit")),_t(Ye("p2p-circuit"),jd),_t(z5,Ye("p2p-circuit")),_t(Ye("p2p-circuit"),z5),Ye("p2p-circuit")),ofe=()=>qi(_t(rfe,ofe),rfe),i0=ofe(),YMt=qi(_t(i0,jd,i0),_t(jd,i0),_t(i0,jd),i0,jd);function sfe(r){function e(t){let n;try{n=lt(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function _t(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:sfe(e),partialMatch:e}}function qi(...r){function e(n){let i=null;return r.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:sfe(e),partialMatch:e}}function Ye(r){let e=r;function t(i){let o;try{o=lt(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}var jfe=C(ee(),1);var ic=Object.create(null);ic.open="0";ic.close="1";ic.ping="2";ic.pong="3";ic.message="4";ic.upgrade="5";ic.noop="6";var K5=Object.create(null);Object.keys(ic).forEach(r=>{K5[ic[r]]=r});var cfe={type:"error",data:"parser error"};var mUe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",gUe=typeof ArrayBuffer=="function",yUe=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,wUe=({type:r,data:e},t,n)=>mUe&&e instanceof Blob?t?n(e):ufe(e,n):gUe&&(e instanceof ArrayBuffer||yUe(e))?t?n(e):ufe(new Blob([e]),n):n(ic[r]+(e||"")),ufe=(r,e)=>{let t=new FileReader;return t.onload=function(){let n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)},jv=wUe;var lfe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$5=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r{let e=r.length*.75,t=r.length,n,i=0,o,s,a,c;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);let u=new ArrayBuffer(e),l=new Uint8Array(u);for(n=0;n>4,l[i++]=(s&15)<<4|a>>2,l[i++]=(a&3)<<6|c&63;return u};var bUe=typeof ArrayBuffer=="function",_Ue=(r,e)=>{if(typeof r!="string")return{type:"message",data:dfe(r,e)};let t=r.charAt(0);return t==="b"?{type:"message",data:EUe(r.substring(1),e)}:K5[t]?r.length>1?{type:K5[t],data:r.substring(1)}:{type:K5[t]}:cfe},EUe=(r,e)=>{if(bUe){let t=ffe(r);return dfe(t,e)}else return{base64:!0,data:r}},dfe=(r,e)=>{switch(e){case"blob":return r instanceof ArrayBuffer?new Blob([r]):r;case"arraybuffer":default:return r}},Wv=_Ue;var hfe=String.fromCharCode(30),pfe=(r,e)=>{let t=r.length,n=new Array(t),i=0;r.forEach((o,s)=>{jv(o,!1,a=>{n[s]=a,++i===t&&e(n.join(hfe))})})},mfe=(r,e)=>{let t=r.split(hfe),n=[];for(let i=0;itypeof self<"u"?self:typeof window<"u"?window:Function("return this")())();function Yv(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var xUe=Hi.setTimeout,SUe=Hi.clearTimeout;function Il(r,e){e.useNativeTimers?(r.setTimeoutFn=xUe.bind(Hi),r.clearTimeoutFn=SUe.bind(Hi)):(r.setTimeoutFn=Hi.setTimeout.bind(Hi),r.clearTimeoutFn=Hi.clearTimeout.bind(Hi))}var AUe=1.33;function gfe(r){return typeof r=="string"?TUe(r):Math.ceil((r.byteLength||r.size)*AUe)}function TUe(r){let e=0,t=0;for(let n=0,i=r.length;n=57344?t+=3:(n++,t+=4);return t}var gL=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}},o0=class extends Tr{constructor(e){super(),this.writable=!1,Il(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new gL(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Wv(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}};var _fe="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),yL=64,IUe={},yfe=0,Qv=0,wfe;function bfe(r){let e="";do e=_fe[r%yL]+e,r=Math.floor(r/yL);while(r>0);return e}function Xv(){let r=bfe(+new Date);return r!==wfe?(yfe=0,wfe=r):r+"."+bfe(yfe++)}for(;Qv{this.readyState="paused",e()};if(this.polling||!this.writable){let n=0;this.polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};mfe(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,pfe(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.query||{},t=this.opts.secure?"https":"http",n="";this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Xv()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.opts.port&&(t==="https"&&Number(this.opts.port)!==443||t==="http"&&Number(this.opts.port)!==80)&&(n=":"+this.opts.port);let i=Zv(e),o=this.opts.hostname.indexOf(":")!==-1;return t+"://"+(o?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(i.length?"?"+i:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new aa(this.uri(),e)}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}},aa=class extends Tr{constructor(e,t){super(),Il(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=t.async!==!1,this.data=t.data!==void 0?t.data:null,this.create()}create(){let e=Yv(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;let t=this.xhr=new wL(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let n in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(n)&&t.setRequestHeader(n,this.opts.extraHeaders[n])}}catch{}if(this.method==="POST")try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{t.setRequestHeader("Accept","*/*")}catch{}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{t.readyState===4&&(t.status===200||t.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof t.status=="number"?t.status:0)},0))},t.send(this.data)}catch(n){this.setTimeoutFn(()=>{this.onError(n)},0);return}typeof document<"u"&&(this.index=aa.requestsCount++,aa.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=RUe,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete aa.requests[this.index],this.xhr=null}}onLoad(){let e=this.xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};aa.requestsCount=0;aa.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Sfe);else if(typeof addEventListener=="function"){let r="onpagehide"in Hi?"pagehide":"unload";addEventListener(r,Sfe,!1)}}function Sfe(){for(let r in aa.requests)aa.requests.hasOwnProperty(r)&&aa.requests[r].abort()}var q5=(()=>typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0))(),H5=Hi.WebSocket||Hi.MozWebSocket,e9=!0,Afe="arraybuffer";var Tfe=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",t9=class extends o0{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;let e=this.uri(),t=this.opts.protocols,n=Tfe?{}:Yv(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=e9&&!Tfe?t?new H5(e,t):new H5(e):new H5(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType||Afe,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t{let s={};e9||(n.options&&(s.compress=n.options.compress),this.opts.perMessageDeflate&&(typeof o=="string"?Buffer.byteLength(o):o.length){this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{},t=this.opts.secure?"wss":"ws",n="";this.opts.port&&(t==="wss"&&Number(this.opts.port)!==443||t==="ws"&&Number(this.opts.port)!==80)&&(n=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=Xv()),this.supportsBinary||(e.b64=1);let i=Zv(e),o=this.opts.hostname.indexOf(":")!==-1;return t+"://"+(o?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(i.length?"?"+i:"")}check(){return!!H5}};var bL={websocket:t9,polling:Jv};var PUe=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,kUe=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function G2(r){let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=PUe.exec(r||""),o={},s=14;for(;s--;)o[kUe[s]]=i[s]||"";return t!=-1&&n!=-1&&(o.source=e,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=NUe(o,o.path),o.queryKey=DUe(o,o.query),o}function NUe(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function DUe(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,o){i&&(t[i]=o)}),t}var ms=class extends Tr{constructor(e,t={}){super(),this.writeBuffer=[],e&&typeof e=="object"&&(t=e,e=null),e?(e=G2(e),t.hostname=e.host,t.secure=e.protocol==="https"||e.protocol==="wss",t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=G2(t.host).host),Il(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Efe(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=mL,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new bL[e](n)}open(){let e;if(this.opts.rememberUpgrade&&ms.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)e="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else e=this.transports[0];this.readyState="opening";try{e=this.createTransport(e)}catch{this.transports.shift(),this.open();return}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",t=>this.onClose("transport close",t))}probe(e){let t=this.createTransport(e),n=!1;ms.priorWebsocketSuccess=!1;let i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",f=>{if(!n)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ms.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let h=new Error("probe error");h.transport=t.name,this.emitReserved("upgradeError",h)}}))};function o(){n||(n=!0,l(),t.close(),t=null)}let s=f=>{let h=new Error("probe error: "+f);h.transport=t.name,o(),this.emitReserved("upgradeError",h)};function a(){s("transport closed")}function c(){s("socket closed")}function u(f){t&&f.name!==t.name&&o()}let l=()=>{t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",a),this.off("close",c),this.off("upgrading",u)};t.once("open",i),t.once("error",s),t.once("close",a),this.once("close",c),this.once("upgrading",u),t.open()}onOpen(){if(this.readyState="open",ms.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let e=0,t=this.upgrades.length;for(;e{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n0&&t>this.maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){let e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}onError(e){ms.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){let t=[],n=0,i=e.length;for(;nW5,Encoder:()=>vL,PacketType:()=>Nt,protocol:()=>kfe});var OUe=typeof ArrayBuffer=="function",LUe=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Rfe=Object.prototype.toString,BUe=typeof Blob=="function"||typeof Blob<"u"&&Rfe.call(Blob)==="[object BlobConstructor]",MUe=typeof File=="function"||typeof File<"u"&&Rfe.call(File)==="[object FileConstructor]";function j5(r){return OUe&&(r instanceof ArrayBuffer||LUe(r))||BUe&&r instanceof Blob||MUe&&r instanceof File}function G5(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t=0&&r.num0;case Nt.ACK:case Nt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},xL=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=Pfe(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function gs(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var UUe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),j2=class extends Tr{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[gs(e,"open",this.onopen.bind(this)),gs(e,"packet",this.onpacket.bind(this)),gs(e,"error",this.onerror.bind(this)),gs(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(UUe.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:Nt.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let s=this.ids++,a=t.pop();this._registerAckCallback(s,a),n.id=s}let i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var n;let i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}let o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let s=0;s{this.io.clearTimeoutFn(o),t.apply(this,[null,...s])}}emitWithAck(e,...t){let n=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((i,o)=>{t.push((s,a)=>n?s?o(s):i(a):i(s)),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...o)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...o)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Nt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Nt.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Nt.EVENT:case Nt.BINARY_EVENT:this.onevent(e);break;case Nt.ACK:case Nt.BINARY_ACK:this.onack(e);break;case Nt.DISCONNECT:this.ondisconnect();break;case Nt.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...i){n||(n=!0,t.packet({type:Nt.ACK,id:e,data:i}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Nt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n0&&r.jitter<=1?r.jitter:0,this.attempts=0}s0.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};s0.prototype.reset=function(){this.attempts=0};s0.prototype.setMin=function(r){this.ms=r};s0.prototype.setMax=function(r){this.max=r};s0.prototype.setJitter=function(r){this.jitter=r};var W2=class extends Tr{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Il(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new s0({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let i=t.parser||SL;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ms(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let i=gs(t,"open",function(){n.onopen(),e&&e()}),o=gs(t,"error",s=>{n.cleanup(),n._readyState="closed",this.emitReserved("error",s),e?e(s):n.maybeReconnectOnOpen()});if(this._timeout!==!1){let s=this._timeout;s===0&&i();let a=this.setTimeoutFn(()=>{i(),t.close(),t.emit("error",new Error("timeout"))},s);this.opts.autoUnref&&a.unref(),this.subs.push(function(){clearTimeout(a)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(gs(e,"ping",this.onping.bind(this)),gs(e,"data",this.ondata.bind(this)),gs(e,"error",this.onerror.bind(this)),gs(e,"close",this.onclose.bind(this)),gs(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){q5(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new j2(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;ne()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(function(){clearTimeout(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};var Y5={};function Q5(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=Ife(r,e.path||"/socket.io"),n=t.source,i=t.id,o=t.path,s=Y5[i]&&o in Y5[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||s,c;return a?c=new W2(n,e):(Y5[i]||(Y5[i]=new W2(n,e)),c=Y5[i]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(Q5,{Manager:W2,Socket:j2,io:Q5,connect:Q5});var a0=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Rl,Zt=class extends EventTarget{constructor(){super(...arguments),Rl.set(this,new Map)}listenerCount(e){let t=a0(this,Rl,"f").get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=a0(this,Rl,"f").get(e);i==null&&(i=[],a0(this,Rl,"f").set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&(n==null?void 0:n.once))??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=a0(this,Rl,"f").get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),a0(this,Rl,"f").set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=a0(this,Rl,"f").get(e.type);return n==null||(n=n.filter(({once:i})=>!i),a0(this,Rl,"f").set(e.type,n)),t}safeDispatchEvent(e,t){return this.dispatchEvent(new ve(e,t))}};Rl=new WeakMap;var AL=class extends Event{constructor(e,t){super(e,t),this.detail=t==null?void 0:t.detail}},ve=globalThis.CustomEvent??AL;var X5=C(ee(),1),Ufe=C(r9(),1);var Ofe=C(ee(),1);var Dfe=64*1024,zUe=5*1e3,n9=class{constructor(e,t){this.label=e.label,this.open=io(),this.channel=e,this.channel.binaryType="arraybuffer",this.log=t.log,typeof this.channel.bufferedAmountLowThreshold=="number"&&(this.channel.bufferedAmountLowThreshold=Dfe),e.addEventListener("message",i=>{t.onMessage(i)}),e.addEventListener("bufferedamountlow",()=>{this.log("stop backpressure: bufferedAmount %d",this.channel.bufferedAmount),this.open.resolve()}),e.addEventListener("open",()=>{this.open.resolve(),t.onOpen()}),e.addEventListener("close",()=>{t.onClose()}),e.addEventListener("error",i=>{var s,a,c,u,l;if(((s=i.error)==null?void 0:s.message)==="Transport channel closed")return this.close();t.log.error('channel encounter an error in state "%s" message: "%s" detail: "%s',e.readyState,(a=i.error)==null?void 0:a.message,(c=i.error)==null?void 0:c.errorDetail);let o=i.error instanceof Error?i.error:new Error(`datachannel error: ${(u=i.error)==null?void 0:u.message} ${(l=i.error)==null?void 0:l.errorDetail}`);t.onError((0,Ofe.default)(o,"ERR_DATA_CHANNEL"))});let n=!1;this.closingInterval=setInterval(()=>{e.readyState==="closing"?(n&&t.onClose(),n=!0):n=!1},zUe)}async send(e){await this.open.promise,this.channel.send(e),this.channel.bufferedAmount>Dfe&&(this.log("start backpressure: bufferedAmount %d",this.channel.bufferedAmount),this.open=io())}close(){clearInterval(this.closingInterval),this.channel.close()}get bufferedAmount(){return this.channel.bufferedAmount}};var Ffe=C(RL(),1),KUe={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}]};function $Ue(){if(typeof globalThis>"u")throw(0,X5.default)(new Error("No WebRTC support detected"),"ERR_WEBRTC_SUPPORT");let r={RTCPeerConnection:globalThis.RTCPeerConnection??globalThis.mozRTCPeerConnection??globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription??globalThis.mozRTCSessionDescription??globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate??globalThis.mozRTCIceCandidate??globalThis.webkitRTCIceCandidate};if(r.RTCPeerConnection==null)throw(0,X5.default)(new Error("No WebRTC support detected"),"ERR_WEBRTC_SUPPORT");return r}var c0=class extends Zt{constructor(e){super(),this.id=e.id??Ee((0,Ufe.default)(4),"hex").slice(0,7),this.log=ue(`libp2p:webrtc-peer:${e.logPrefix}:${this.id}`),this.wrtc=e.wrtc??$Ue(),this.peerConnection=new this.wrtc.RTCPeerConnection(Object.assign({},KUe,e.peerConnectionConfig)),this.closed=!1,this.connected=io(),this.source=jn(),this.sink=async t=>{if(await this.connected.promise,this.channel==null)throw(0,X5.default)(new Error("Connected but no channel?!"),"ERR_DATA_CHANNEL");for await(let n of t)await this.channel.send(n);await this.close()}}handleDataChannelEvent(e){let t=e.channel;if(t==null){this.close((0,X5.default)(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL")).catch(n=>{this.log("Error closing after event channel was found to be null",n)});return}this.channel=new n9(t,{log:this.log,onMessage:n=>{this.source.push(new Uint8Array(n.data))},onOpen:()=>{this.connected.resolve(),this.dispatchEvent(new ve("ready"))},onClose:()=>{this.close().catch(n=>{this.log("error closing connection after channel close",n)})},onError:n=>{this.close(n).catch(i=>{this.log("error closing connection after channel error",i)})}})}async close(e){var t;if(this.closed=!0,e==null&&this.channel!=null)for(;this.channel.bufferedAmount>0;)await(0,Ffe.default)(100);(t=this.channel)==null||t.close(),this.peerConnection.close(),this.source.end(e),this.dispatchEvent(new ve("close"))}};var zfe=C(ee(),1),Y2=class extends Zt{constructor(e){super(),this.log=e.log,this.peerConnection=e.peerConnection,this.wrtc=e.wrtc,this.status="idle",this.peerConnection.addEventListener("negotiationneeded",()=>{this.log("peer connection negotiation needed"),this.handleRenegotiate({type:"renegotiate"}).catch(t=>{this.log.error("could not renegotiate %o",t)})})}async handleSignal(e){if(this.log('incoming signal "%s"',e.type),e.type==="offer")return await this.handleOffer(e);if(e.type==="answer")return await this.handleAnswer(e);if(e.type==="candidate")return await this.handleCandidate(e);if(e.type==="renegotiate")return await this.handleRenegotiate(e);if(e.type==="goodbye")return await this.handleGoodye(e);this.log(`Unknown signal type ${e.type}`)}async handleOffer(e){}async handleAnswer(e){}async handleRenegotiate(e){}async handleGoodye(e){this.peerConnection.close()}async handleCandidate(e){let t=new this.wrtc.RTCIceCandidate(e.candidate);try{await this.peerConnection.addIceCandidate(t)}catch(n){if(t.address==null||t.address.endsWith(".local"))this.log("ignoring unsupported ICE candidate.");else throw(0,zfe.default)(n,"ERR_ADD_ICE_CANDIDATE")}}};var Vfe=ue("libp2p:webrtc-peer:receiver"),Z5=class extends c0{constructor(e={}){super({...e,logPrefix:"receiver"}),this.handshake=new CL({log:this.log,peerConnection:this.peerConnection,wrtc:this.wrtc,answerOptions:e.answerOptions}),this.handshake.addEventListener("signal",t=>this.dispatchEvent(new ve("signal",{detail:t.detail}))),this.peerConnection.addEventListener("datachannel",t=>{this.handleDataChannelEvent(t)})}handleSignal(e){this.handshake.handleSignal(e).catch(t=>{this.log("error handling signal %o %o",e,t)})}},CL=class extends Y2{constructor(e){super(e),this.options=e,this.status="idle",this.iceCandidates=[]}async handleRenegotiate(){Vfe.trace("renegotiate"),this.dispatchEvent(new ve("signal",{detail:{type:"renegotiate"}}))}async handleOffer(e){await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(e));for(let n of this.iceCandidates)await this.handleCandidate(n);this.iceCandidates=[];let t=await this.peerConnection.createAnswer(this.options.answerOptions);await this.peerConnection.setLocalDescription(t),Vfe.trace("handle offer",this.peerConnection.localDescription),this.dispatchEvent(new ve("signal",{detail:this.peerConnection.localDescription??t}))}async handleCandidate(e){if(this.peerConnection.remoteDescription==null||this.peerConnection.remoteDescription.type==null){this.iceCandidates.push(e);return}await super.handleCandidate(e)}};var $fe=C(r9(),1);var qUe=r=>{let e=r.on||r.addListener||r.addEventListener,t=r.off||r.removeListener||r.removeEventListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function HUe(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");let a=[e].flat(),c=[],{addListener:u,removeListener:l}=qUe(r),f=(...d)=>{let p=t.multiArgs?d:d[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),o(c)))},h=d=>{n(),s(d)};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)l(d,h)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)u(d,h);t.resolveImmediately&&o(c)});if(i.cancel=n,typeof t.timeout=="number"){let o=Ih(i,t.timeout);return o.cancel=n,o}return i}function Kfe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=HUe(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}var qfe=C(RL(),1);var PL=ue("libp2p:webrtc-peer:initator"),GUe=1e3,J5=class extends c0{constructor(e={}){super({...e,logPrefix:"initiator"}),this.handleDataChannelEvent({channel:this.peerConnection.createDataChannel(e.dataChannelLabel??Ee((0,$fe.default)(20),"hex").slice(0,7),e.dataChannelInit)}),this.handshake=new kL({log:this.log,peerConnection:this.peerConnection,wrtc:this.wrtc,offerOptions:e.offerOptions}),this.handshake.addEventListener("signal",t=>{this.dispatchEvent(new ve("signal",{detail:t.detail}))})}handleSignal(e){this.handshake.handleSignal(e).catch(t=>{this.log("error handling signal %o %o",e,t)})}},kL=class extends Y2{constructor(e){super(e),this.options=e,this.status="idle",this.peerConnection.addEventListener("icecandidate",t=>{if(t.candidate==null)return;let n={type:"candidate",candidate:{candidate:t.candidate.candidate,sdpMLineIndex:t.candidate.sdpMLineIndex,sdpMid:t.candidate.sdpMid}};PL.trace("create candidate",n),this.dispatchEvent(new ve("signal",{detail:n})),this.dispatchEvent(new ve("ice-candidate"))})}async handleRenegotiate(){if(this.status==="negotiating"){this.log("already negotiating, queueing");return}this.status="negotiating";let e=await this.peerConnection.createOffer(this.options.offerOptions);await this.peerConnection.setLocalDescription(e),await Kfe(this,"ice-candidate"),await(0,qfe.default)(GUe),PL.trace("renegotiate",this.peerConnection.localDescription),this.dispatchEvent(new ve("signal",{detail:this.peerConnection.localDescription??e}))}async handleAnswer(e){PL.trace("handle answer",e),await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(e)),this.status="idle"}};var NL=ue("libp2p:webrtc-star:socket");function i9(r,e){let{sink:t,source:n}=r,i={remoteAddr:e.remoteAddr,async sink(o){e.signal!=null&&(o=sa(o,e.signal));try{await t(o)}catch(s){s.type!=="aborted"&&NL.error(s)}},source:e.signal!=null?sa(n,e.signal):n,timeline:{open:Date.now()},async close(){if(r.closed)return;let o=Date.now(),s=setTimeout(()=>{if(i.remoteAddr!=null){let{host:a,port:c}=i.remoteAddr.toOptions();NL("timeout closing socket to %s:%s after %dms, destroying it manually",a,c,Date.now()-o)}r.closed||r.close().catch(a=>{NL.error("could not close socket",a)})},2e3);try{await r.close()}finally{clearTimeout(s)}}};return r.addEventListener("close",()=>{i.timeline.close==null&&(i.timeline.close=Date.now())},{once:!0}),i}function o9(r){let e=r.toString().split("/"),t=r.protos()[1].name,n=r.protos()[2].name,i=r.stringTuples()[1][1];if(t!=="tcp"||n!=="ws"&&n!=="wss")throw new Error(`invalid multiaddr: ${r.toString()}`);if(!sie(r))return`http://${e[2]}:${e[4]}`;if(n==="ws")return`http://${e[2]}${i==null||i==="80"?"":`:${i}`}`;if(n==="wss")return`https://${e[2]}${i==null||i==="443"?"":`:${i}`}`;throw new Error("invalid multiaddr: "+r.toString())}function Hfe(r){let e="/libp2p-webrtc-star";if(r.startsWith(e)){r=r.substring(e.length,r.length);let t=lt(r),n=t.stringTuples().filter(i=>i[0]===421)[0];if(n[1]==null)throw new Error("invalid multiaddr: "+r);t=t.decapsulate("p2p"),t=t.encapsulate("/p2p-webrtc-star"),t=t.encapsulate(`/p2p/${n[1]}`),r=t.toString()}return r}var Gi=ue("libp2p:webrtc-star:listener"),WUe={transports:["websocket"],path:"/socket.io-next/"},DL=class extends Zt{constructor(e,t,n,i,o){super(),this.signallingAddr=t,this.socket=Q5(e,WUe),this.connections=[],this.channels=new Map,this.pendingSignals=new Map,this.upgrader=n,this.handler=i,this.channelOptions=o,this.handleWsHandshake=this.handleWsHandshake.bind(this);let s=!1;this.socket.on("connect_error",a=>{s&&a.type==="TransportError"||this.dispatchEvent(new ve("error",{detail:a}))}),this.socket.on("error",a=>{this.dispatchEvent(new ve("error",{detail:a}))}),this.socket.on("ws-handshake",this.handleWsHandshake),this.socket.on("ws-peer",a=>{this.dispatchEvent(new ve("peer",{detail:a}))}),this.socket.on("connect",()=>{this.socket.emit("ss-join",this.signallingAddr.toString()),s&&this.dispatchEvent(new ve("reconnect"))}),this.socket.once("connect",()=>{s=!0,this.dispatchEvent(new ve("listening"))}),this.socket.on("disconnect",()=>{this.dispatchEvent(new ve("disconnect"))})}_createChannel(e,t,n){let i={...this.channelOptions},o=new Z5(i),s=a=>{let c=a.detail;Gi.error("incoming connection errored",c)};return o.addEventListener("error",s),o.addEventListener("close",()=>{o.removeEventListener("error",s)},{once:!0}),o.addEventListener("signal",a=>{let c=a.detail;this.socket.emit("ss-handshake",{intentId:e,srcMultiaddr:t,dstMultiaddr:n,answer:!0,signal:c})}),o.addEventListener("ready",()=>{let a=i9(o,{remoteAddr:this.signallingAddr});Gi("new inbound connection %s",a.remoteAddr);try{this.upgrader.upgradeInbound(a).then(c=>{Gi("inbound connection %s upgraded",a.remoteAddr),this.connections.push(a);let u=()=>{this.connections=this.connections.filter(l=>l!==a),this.channels.delete(e),this.pendingSignals.delete(e)};o.addEventListener("close",u,{once:!0}),this.dispatchEvent(new ve("connection",{detail:c})),this.handler(c)}).catch(c=>{Gi.error("inbound connection failed to upgrade",c),a.close().catch(u=>{Gi.error("inbound connection failed to close after failing to upgrade",u)})})}catch(c){Gi.error("inbound connection failed to upgrade",c),a.close().catch(u=>{Gi.error("inbound connection failed to close after failing to upgrade",u)})}},{once:!0}),o}handleWsHandshake(e){if(Gi('incoming handshake. signal type "%s" is answer %s',e.signal.type,e.answer),e.answer===!0||e.err!=null||e.intentId==null)return;let t=e.intentId,n=this.pendingSignals.get(t);n==null&&(n=[],this.pendingSignals.set(t,n)),n.push(e);let i=this.channels.get(t);if(i==null){if(e.signal.type!=="offer"){Gi("handshake is not an offer and channel does not exist, buffering until we receive an offer");return}Gi("creating new channel to handle offer handshake"),i=this._createChannel(e.intentId,e.srcMultiaddr,e.dstMultiaddr),this.channels.set(t,i)}else Gi("channel already exists, using it to handle handshake");for(;n.length>0;){let o=n.shift();(o==null?void 0:o.signal)!=null&&i.handleSignal(o.signal)}}async close(){this.socket.emit("ss-leave",this.signallingAddr.toString()),this.socket.removeAllListeners(),this.socket.close(),await Promise.all([...this.connections.map(async e=>await e.close()),...Array.from(this.channels.values()).map(async e=>await e.close())]),this.dispatchEvent(new ve("close"))}},OL=class extends Zt{constructor(e,t,n,i,o){super(),this.upgrader=e,this.handler=t,this.peerId=n,this.transport=i,this.options=o}async listen(e){if(this.listeningAddr!=null)throw(0,jfe.default)(new Error("listener already in use"),"ERR_ALREADY_LISTENING");let t=io();this.listeningAddr=e;let n;e.protoCodes().includes(421)?n=e:n=e.encapsulate(`/p2p/${this.peerId.toString()}`);let i=this.signallingUrl=o9(e);Gi("connecting to signalling server on: %s",this.signallingUrl);let o=new DL(this.signallingUrl,n,this.upgrader,this.handler,this.options.channelOptions);return o.addEventListener("error",s=>{let a=s.detail;Gi("error connecting to signalling server %o",a),o.close().catch(c=>{Gi.error("error closing server after error",c)}),t.reject(a)}),o.addEventListener("listening",()=>{Gi("connected to signalling server"),this.dispatchEvent(new ve("listening")),t.resolve()}),o.addEventListener("peer",s=>{this.transport.peerDiscovered(s.detail)}),o.addEventListener("connection",s=>{let a=s.detail;if(a.remoteAddr==null)try{a.remoteAddr=e.decapsulateCode(421).encapsulate(`/p2p/${a.remotePeer.toString()}`)}catch(c){Gi.error("could not determine remote address",c)}this.dispatchEvent(new ve("connection",{detail:a}))}),o.addEventListener("disconnect",()=>{this.transport.sigServers.delete(i)}),o.addEventListener("reconnect",()=>{this.transport.sigServers.set(i,o)}),this.transport.sigServers.set(this.signallingUrl,o),await t.promise}async close(){if(this.signallingUrl!=null){let e=this.transport.sigServers.get(this.signallingUrl);e!=null&&(await e.close(),this.transport.sigServers.delete(this.signallingUrl))}this.dispatchEvent(new ve("close")),this.listeningAddr=void 0}getAddrs(){return this.listeningAddr!=null?[this.listeningAddr]:[]}};function Wfe(r,e,t,n,i){return new OL(r,e,t,n,i)}var Xfe=C(r9(),1);var LL=Symbol.for("@libp2p/peer-id");function u0(r){return r!=null&&!!r[LL]}var YUe=Symbol.for("nodejs.util.inspect.custom"),Yfe=Object.values(If).map(r=>r.decoder).reduce((r,e)=>r.or(e),If.identity.decoder),Qfe=114,BL=36,ML=37,e4=class{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()})`}get[LL](){return!0}toString(){return this.string==null&&(this.string=tt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ce.createV1(Qfe,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){var t;if(e instanceof Uint8Array)return rr(this.multihash.bytes,e);if(typeof e=="string")return xt(e).equals(this);if(((t=e==null?void 0:e.multihash)==null?void 0:t.bytes)!=null)return rr(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[YUe](){return`PeerId(${this.toString()})`}},l0=class extends e4{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},f0=class extends e4{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},d0=class extends e4{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function xn(r){if(r.type==="RSA")return new l0(r);if(r.type==="Ed25519")return new f0(r);if(r.type==="secp256k1")return new d0(r);throw new We("Not a PeerId","ERR_INVALID_PARAMETERS")}function xt(r,e){if(e=e??Yfe,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Jn(tt.decode(`z${r}`));return r.startsWith("12D")?new f0({multihash:t}):r.startsWith("16U")?new d0({multihash:t}):new l0({multihash:t})}return Wd(Yfe.decode(r))}function Wd(r){try{let e=Jn(r);if(e.code===Ns.code){if(e.digest.length===BL)return new f0({multihash:e});if(e.digest.length===ML)return new d0({multihash:e})}if(e.code===mr.code)return new l0({multihash:e})}catch{return QUe(ce.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function QUe(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Qfe)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===mr.code)return new l0({multihash:r.multihash});if(e.code===Ns.code){if(e.digest.length===BL)return new f0({multihash:r.multihash});if(e.digest.length===ML)return new d0({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Yd(r,e){return r.length===BL?new f0({multihash:Ec(Ns.code,r),privateKey:e}):r.length===ML?new d0({multihash:Ec(Ns.code,r),privateKey:e}):new l0({multihash:await mr.digest(r),publicKey:r,privateKey:e})}var s9=Symbol.for("@libp2p/transport");var Qd;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Qd||(Qd={}));var a9=Symbol.for("@libp2p/peer-discovery");var ZUe="RTCPeerConnection"in globalThis,h0=ue("libp2p:webrtc-star"),JUe=()=>{},UL=class extends Zt{constructor(){super(...arguments),this.started=!1}get[a9](){return!0}get[Symbol.toStringTag](){return"@libp2p/webrtc-star-discovery"}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}dispatchEvent(e){return this.isStarted()?super.dispatchEvent(e):!1}},c9=class{constructor(e){(e==null?void 0:e.wrtc)!=null&&(this.wrtc=e.wrtc),this.sigServers=new Map,this._discovery=new UL,this.discovery=()=>this._discovery,this.peerDiscovered=this.peerDiscovered.bind(this)}get[s9](){return!0}get[Symbol.toStringTag](){return"@libp2p/webrtc-star"}async dial(e,t){let n=await this._connect(e,t),i=i9(n,{remoteAddr:e,signal:t.signal});h0("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i);return h0("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){var s;if(((s=t.signal)==null?void 0:s.aborted)===!0)throw new Gd;let n={...t.channelOptions??{}};this.wrtc!=null&&(n.wrtc=this.wrtc);let i=e.toOptions(),o=Ee((0,Xfe.default)(36),"hex");return await new Promise((a,c)=>{var w;let u=this.sigServers.get(o9(e));if((u==null?void 0:u.socket)==null)return c((0,t4.default)(new Error("unknown signal server to use"),"ERR_UNKNOWN_SIGNAL_SERVER"));let l=!1;h0("dialing %s:%s",i.host,i.port);let f=new J5(n),h=_=>{let x=_.detail;if(!l){let m=`connection error ${i.host}:${i.port}: ${x.message}`;h0.error(m),g(x)}},d=()=>{l=!0,h0("connection opened %s:%s",i.host,i.port),g()},p=()=>{h0.error("connection aborted %s:%s",i.host,i.port),f.close().finally(()=>{g(new Gd)})},g=_=>{var x;f.removeEventListener("ready",d),(x=t.signal)==null||x.removeEventListener("abort",p),_==null?a(f):c(_)};f.addEventListener("ready",d,{once:!0}),f.addEventListener("close",()=>{f.removeEventListener("error",h)}),(w=t.signal)==null||w.addEventListener("abort",p),f.addEventListener("signal",_=>{let x=_.detail;u.socket.emit("ss-handshake",{intentId:o,srcMultiaddr:u.signallingAddr.toString(),dstMultiaddr:e.toString(),signal:x})}),u.socket.on("ws-handshake",_=>{_.intentId===o&&_.err!=null&&f.close().finally(()=>{c((0,t4.default)(new Error(_.err),"ERR_SIGNALLING_FAILED"))}),!(_.intentId!==o||_.answer==null||f.closed)&&f.handleSignal(_.signal)})})}createListener(e){if(!ZUe&&this.wrtc==null)throw(0,t4.default)(new Error("no WebRTC support"),"ERR_NO_WEBRTC_SUPPORT");if(e.channelOptions=e.channelOptions??{},this.wrtc!=null&&(e.channelOptions.wrtc=this.wrtc),this.peerId==null)throw(0,t4.default)(new Error("PeerId not set"),"ERR_MISSING_PEER_ID");return Wfe(e.upgrader,e.handler??JUe,this.peerId,this,e)}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>t.protoCodes().includes(290)?!1:Gv.matches(t))}peerDiscovered(e){h0("peer discovered: %s",e),e=Hfe(e);let t=lt(e),n=t.getPeerId();if(n==null)return;let i=xt(n);this._discovery.dispatchEvent(new ve("peer",{detail:{id:i,multiaddrs:[t],protocols:[]}}))}};function Zfe(r={}){let e=new c9(r);return{transport:t=>(e.peerId=t.peerId,e),discovery:e.discovery}}function Jfe(){let r=Zfe();return{transports:[r.transport],peerDiscovery:[r.discovery],connectionManager:{maxParallelDials:150,maxDialsPerPeer:4,dialTimeout:1e4,autoDial:!0},nat:{enabled:!1}}}function Cl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var n4=C(ee(),1);var Rt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.DHT_DISABLED="DHT is not available",r.PUBSUB_DISABLED="PubSub is not available",r.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",r.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Rt||(Rt={}));var q;(function(r){r.DHT_DISABLED="ERR_DHT_DISABLED",r.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",r.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",r.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",r.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",r.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TIMEOUT="ERR_TIMEOUT",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED"})(q||(q={}));var ede=C(ee(),1);async function*r4(r,e){yield*Bi(r,async t=>(await e.addressBook.add(t.id,t.multiaddrs),t))}function u9(r){let e=new Set;return Yt(r,t=>e.has(t.id.toString())?!1:(e.add(t.id.toString()),!0))}async function*l9(r,e=1){let t=0;for await(let n of r)t++,yield n;if(tasync function*(){try{yield await i.findPeer(e,t)}catch(o){rde.error(o)}}())),i=>Yt(i,Boolean),i=>r4(i,this.components.peerStore),async i=>await Fi(i));if(n!=null)return n;throw(0,n4.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}async*getClosestPeers(e,t){if(this.routers.length===0)throw(0,n4.default)(new Error("No peer routers available"),q.ERR_NO_ROUTERS_AVAILABLE);yield*Ne(Qo(...this.routers.map(n=>n.getClosestPeers(e,t))),n=>r4(n,this.components.peerStore),n=>u9(n),n=>l9(n))}};var Xd=C(ee(),1);var h9=class{constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw(0,Xd.default)(new Error("No content this.routers available"),q.ERR_NO_ROUTERS_AVAILABLE);yield*Ne(Qo(...this.routers.map(n=>n.findProviders(e,t))),n=>r4(n,this.components.peerStore),n=>u9(n),n=>l9(n))}async provide(e,t={}){if(this.routers.length===0)throw(0,Xd.default)(new Error("No content routers available"),q.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>await n.provide(e,t)))}async put(e,t,n){if(!this.isStarted())throw(0,Xd.default)(new Error(Rt.NOT_STARTED_YET),q.DHT_NOT_STARTED);let i=this.components.dht;i!=null&&await on(i.put(e,t,n))}async get(e,t){if(!this.isStarted())throw(0,Xd.default)(new Error(Rt.NOT_STARTED_YET),q.DHT_NOT_STARTED);let n=this.components.dht;if(n!=null){for await(let i of n.get(e,t))if(i.name==="VALUE")return i.value}throw(0,Xd.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}async*getMany(e,t,n){if(!this.isStarted())throw(0,Xd.default)(new Error(Rt.NOT_STARTED_YET),q.DHT_NOT_STARTED);if(t==null||t===0)return;let i=0,o=this.components.dht;if(o!=null){for await(let s of o.get(e,n))if(s.name==="VALUE"&&(yield{from:s.from,val:s.value},i++,i===t))break}if(i===0)throw(0,Xd.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}};var iFe=r=>r,p9=class extends Zt{constructor(e,t){super();let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(o=>o.toString()),this.announce=new Set(i.map(o=>o.toString())),this.observed=new Set,this.announceFilter=t.announceFilter??iFe}getListenAddrs(){return Array.from(this.listen).map(e=>lt(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>lt(e))}getObservedAddrs(){return Array.from(this.observed).map(e=>lt(e))}confirmObservedAddr(e){}removeObservedAddr(e){}addObservedAddr(e){let t=lt(e),n=t.getPeerId();n!=null&&xt(n).equals(this.components.peerId)&&(t=t.decapsulate(lt(`/p2p/${this.components.peerId.toString()}`)));let i=t.toString();this.observed.has(i)||(this.observed.add(i),this.dispatchEvent(new ve("change:addresses")))}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(this.getObservedAddrs().map(n=>n.toString()));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>lt(n))).map(n=>{var i;return((i=n.protos().pop())==null?void 0:i.path)===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`)})}};var E9=C(ee(),1);var ode=ue("libp2p:connection-manager:latency-monitor:visibility-change-emitter"),m9=class extends Zt{constructor(){super(),this.hidden="hidden",this.visibilityChange="visibilityChange",globalThis.document!=null&&(this._initializeVisibilityVarNames(),this._addVisibilityChangeListener())}_initializeVisibilityVarNames(){let e="hidden",t="visibilitychange";typeof globalThis.document.hidden<"u"?(e="hidden",t="visibilitychange"):typeof globalThis.document.mozHidden<"u"?(e="mozHidden",t="mozvisibilitychange"):typeof globalThis.document.msHidden<"u"?(e="msHidden",t="msvisibilitychange"):typeof globalThis.document.webkitHidden<"u"&&(e="webkitHidden",t="webkitvisibilitychange"),this.hidden=e,this.visibilityChange=t}_addVisibilityChangeListener(){typeof globalThis.document.addEventListener>"u"||typeof document[this.hidden]>"u"?ode("Checking page visibility requires a browser that supports the Page Visibility API."):globalThis.document.addEventListener(this.visibilityChange,this._handleVisibilityChange.bind(this),!1)}isVisible(){if(!(this.hidden===void 0||document[this.hidden]===void 0))return document[this.hidden]==null}_handleVisibilityChange(){let e=globalThis.document[this.hidden]===!1;ode(e?"Page Visible":"Page Hidden"),this.dispatchEvent(new ve("visibilityChange",{detail:e}))}};var Pl=ue("libp2p:connection-manager:latency-monitor"),g9=class extends Zt{constructor(e={}){var s,a;super();let{latencyCheckIntervalMs:t,dataEmitIntervalMs:n,asyncTestFn:i,latencyRandomPercentage:o}=e;this.latencyCheckIntervalMs=t??500,this.latencyRandomPercentage=o??10,this.latencyCheckMultiply=2*(this.latencyRandomPercentage/100)*this.latencyCheckIntervalMs,this.latencyCheckSubtract=this.latencyCheckMultiply/2,this.dataEmitIntervalMs=n===null||n===0?void 0:n??5*1e3,Pl("latencyCheckIntervalMs: %s dataEmitIntervalMs: %s",this.latencyCheckIntervalMs,this.dataEmitIntervalMs),this.dataEmitIntervalMs!=null?Pl("Expecting ~%s events per summary",this.latencyCheckIntervalMs/this.dataEmitIntervalMs):Pl("Not emitting summaries"),this.asyncTestFn=i,((s=globalThis.process)==null?void 0:s.hrtime)!=null?(Pl("Using process.hrtime for timing"),this.now=globalThis.process.hrtime,this.getDeltaMS=c=>{let u=this.now(c);return u[0]*1e3+u[1]/1e6}):typeof window<"u"&&((a=window.performance)==null?void 0:a.now)!=null?(Pl("Using performance.now for timing"),this.now=window.performance.now.bind(window.performance),this.getDeltaMS=c=>Math.round(this.now()-c)):(Pl("Using Date.now for timing"),this.now=Date.now,this.getDeltaMS=c=>this.now()-c),this.latencyData=this.initLatencyData()}start(){var e;oFe()&&(this.visibilityChangeEmitter=new m9,this.visibilityChangeEmitter.addEventListener("visibilityChange",t=>{let{detail:n}=t;n?this._startTimers():(this._emitSummary(),this._stopTimers())})),((e=this.visibilityChangeEmitter)==null?void 0:e.isVisible())===!0&&this._startTimers()}stop(){this._stopTimers()}_startTimers(){this.checkLatencyID==null&&(this.checkLatency(),this.dataEmitIntervalMs!=null&&(this.emitIntervalID=setInterval(()=>this._emitSummary(),this.dataEmitIntervalMs),typeof this.emitIntervalID.unref=="function"&&this.emitIntervalID.unref()))}_stopTimers(){this.checkLatencyID!=null&&(clearTimeout(this.checkLatencyID),this.checkLatencyID=void 0),this.emitIntervalID!=null&&(clearInterval(this.emitIntervalID),this.emitIntervalID=void 0)}_emitSummary(){let e=this.getSummary();e.events>0&&this.dispatchEvent(new ve("data",{detail:e}))}getSummary(){let e={events:this.latencyData.events,minMs:this.latencyData.minMs,maxMs:this.latencyData.maxMs,avgMs:this.latencyData.events>0?this.latencyData.totalMs/this.latencyData.events:Number.POSITIVE_INFINITY,lengthMs:this.getDeltaMS(this.latencyData.startTime)};return this.latencyData=this.initLatencyData(),Pl.trace("Summary: %O",e),e}checkLatency(){let e=Math.random()*this.latencyCheckMultiply-this.latencyCheckSubtract,t={deltaOffset:Math.ceil(this.latencyCheckIntervalMs+e),startTime:this.now()},n=()=>{if(this.checkLatencyID==null)return;let i=this.getDeltaMS(t.startTime)-t.deltaOffset;this.checkLatency(),this.latencyData.events++,this.latencyData.minMs=Math.min(this.latencyData.minMs,i),this.latencyData.maxMs=Math.max(this.latencyData.maxMs,i),this.latencyData.totalMs+=i,Pl.trace("MS: %s Data: %O",i,this.latencyData)};Pl.trace("localData: %O",t),this.checkLatencyID=setTimeout(()=>{this.asyncTestFn!=null?(t.deltaOffset=0,t.startTime=this.now(),this.asyncTestFn(n)):(t.deltaOffset-=1,n())},t.deltaOffset),typeof this.checkLatencyID.unref=="function"&&this.checkLatencyID.unref()}initLatencyData(){return{startTime:this.now(),minMs:Number.POSITIVE_INFINITY,maxMs:Number.NEGATIVE_INFINITY,events:0,totalMs:0}}};function oFe(){return typeof globalThis.window<"u"}var v9=C(xi(),1);var y9="OPEN",zL="CLOSING",w9="CLOSED";function kl(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var i4=class{constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return kl(this.map.entries(),e=>[xt(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,xt(n),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 kl(this.map.keys(),e=>xt(e))}values(){return this.map.values()}get size(){return this.map.size}};var Nl=class{constructor(e){if(this.set=new Set,e!=null)for(let 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 kl(this.set.entries(),e=>{let t=xt(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=xt(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return kl(this.set.values(),e=>xt(e))}intersection(e){let t=new Nl;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new Nl;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new Nl;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var X2=class{constructor(e){if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return kl(this.list.entries(),e=>xt(e[1]))}concat(e){let t=new X2(this);for(let n of e)t.push(n);return t}entries(){return kl(this.list.entries(),e=>[e[0],xt(e[1])])}every(e){return this.list.every((t,n)=>e(xt(t),n,this))}filter(e){let t=new X2;return this.list.forEach((n,i)=>{let o=xt(n);e(o,i,this)&&t.push(o)}),t}find(e){let t=this.list.find((n,i)=>e(xt(n),i,this));if(t!=null)return xt(t)}findIndex(e){return this.list.findIndex((t,n)=>e(xt(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(xt(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return xt(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return xt(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var tB=C(Kn(),1);var sde="keep-alive";var rhe=C(ehe(),1);var the=C(ee(),1);function _9(r){if(u0(r))return{peerId:r};if(as(r)){let e=r.getPeerId();return{multiaddr:r,peerId:e==null?void 0:xt(e)}}throw(0,the.default)(new Error(`${r} is not a PeerId or a Multiaddr`),q.ERR_INVALID_MULTIADDR)}var Ln=ue("libp2p:connection-manager"),KFe={maxConnections:1/0,minConnections:0,maxEventLoopDelay:1/0,pollInterval:2e3,autoDialInterval:1e4,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},$Fe=6e4,x9=class extends Zt{constructor(e,t){var n;if(super(),this.opts=et.call({ignoreUndefined:!0},KFe,t),this.opts.maxConnections0&&t.maxEventLoopDelay!==1/0&&(this.latencyMonitor=new g9({latencyCheckIntervalMs:t.pollInterval,dataEmitIntervalMs:t.pollInterval}));try{(n=v9.setMaxListeners)==null||n(1/0,this)}catch{}this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.startupReconnectTimeout=t.startupReconnectTimeout??$Fe,this.dialTimeout=t.dialTimeout??3e4,this.allow=(t.allow??[]).map(i=>lt(i)),this.deny=(t.deny??[]).map(i=>lt(i)),this.inboundConnectionRateLimiter=new rhe.RateLimiterMemory({points:this.opts.inboundConnectionThreshold,duration:1}),this.incomingPendingConnections=0}isStarted(){return this.started}async start(){var e,t,n,i,o;(e=this.components.metrics)==null||e.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let s={inbound:0,outbound:0};for(let a of this.connections.values())for(let c of a)c.stat.direction==="inbound"?s.inbound++:s.outbound++;return s}}),(t=this.components.metrics)==null||t.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let s={};for(let a of this.connections.values())for(let c of a)for(let u of c.streams){let l=`${u.stat.direction} ${u.stat.protocol??"unnegotiated"}`;s[l]=(s[l]??0)+1}return s}}),(n=this.components.metrics)==null||n.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let s={};for(let c of this.connections.values())for(let u of c){let l={};for(let f of u.streams){let h=`${f.stat.direction} ${f.stat.protocol??"unnegotiated"}`;l[h]=(l[h]??0)+1}for(let[f,h]of Object.entries(l))s[f]=s[f]??[],s[f].push(h)}let a={};for(let[c,u]of Object.entries(s)){u=u.sort((f,h)=>f-h);let l=Math.floor(u.length*.9);a[c]=u[l]}return a}}),(i=this.latencyMonitor)==null||i.start(),this._onLatencyMeasure=this._onLatencyMeasure.bind(this),(o=this.latencyMonitor)==null||o.addEventListener("data",this._onLatencyMeasure),this.started=!0,Ln("started")}async afterStart(){this.components.upgrader.addEventListener("connection",this.onConnect),this.components.upgrader.addEventListener("connectionEnd",this.onDisconnect),Promise.resolve().then(async()=>{var t,n;let e=[];for(let i of await this.components.peerStore.all())(await this.components.peerStore.getTags(i.id)).filter(a=>a.name===sde).length>0&&e.push(i.id);(t=this.connectOnStartupController)==null||t.clear(),this.connectOnStartupController=new tB.TimeoutController(this.startupReconnectTimeout);try{(n=v9.setMaxListeners)==null||n(1/0,this.connectOnStartupController.signal)}catch{}await Promise.all(e.map(async i=>{var o;await this.openConnection(i,{signal:(o=this.connectOnStartupController)==null?void 0:o.signal}).catch(s=>{Ln.error(s)})}))}).catch(e=>{Ln.error(e)}).finally(()=>{var e;(e=this.connectOnStartupController)==null||e.clear()})}async beforeStop(){var e;(e=this.connectOnStartupController)==null||e.abort(),this.components.upgrader.removeEventListener("connection",this.onConnect),this.components.upgrader.removeEventListener("connectionEnd",this.onDisconnect)}async stop(){var e,t;(e=this.latencyMonitor)==null||e.removeEventListener("data",this._onLatencyMeasure),(t=this.latencyMonitor)==null||t.stop(),this.started=!1,await this._close(),Ln("stopped")}async _close(){let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){Ln.error(i)}})());Ln("closing %d connections",e.length),await Promise.all(e),this.connections.clear()}onConnect(e){this._onConnect(e).catch(t=>{Ln.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,i=n.toString(),o=this.connections.get(i);o!=null?o.push(t):this.connections.set(i,[t]),n.publicKey!=null&&await this.components.peerStore.keyBook.set(n,n.publicKey);let s=this.getConnections().length,a=s-this.opts.maxConnections;await this._checkMaxLimit("maxConnections",s,a),this.dispatchEvent(new ve("peer:connect",{detail:t}))}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer.toString(),i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==t.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.dispatchEvent(new ve("peer:disconnect",{detail:t})))}getConnections(e){if(e!=null)return this.connections.get(e.toString())??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}async openConnection(e,t={}){var s;let{peerId:n,multiaddr:i}=_9(e);if(n==null&&i==null)throw(0,E9.default)(new TypeError("Can only open connections to PeerIds or Multiaddrs"),q.ERR_INVALID_PARAMETERS);if(n!=null){Ln("dial to",n);let a=this.getConnections(n);if(a.length>0)return Ln("had an existing connection to %p",n),a[0]}let o;if((t==null?void 0:t.signal)==null){o=new tB.TimeoutController(this.dialTimeout),t.signal=o.signal;try{(s=v9.setMaxListeners)==null||s(1/0,o.signal)}catch{}}try{let a=await this.components.dialer.dial(e,t),c=this.connections.get(a.remotePeer.toString());c==null&&(c=[],this.connections.set(a.remotePeer.toString(),c));let u=!1;for(let l of c)l.id===a.id&&(u=!0);return u||c.push(a),a}finally{o!=null&&o.clear()}}async closeConnections(e){let t=this.connections.get(e.toString())??[];await Promise.all(t.map(async n=>await n.close()))}getAll(e){if(!u0(e))throw(0,E9.default)(new Error("peerId must be an instance of peer-id"),q.ERR_INVALID_PARAMETERS);let t=e.toString(),n=this.connections.get(t);return n!=null?n.filter(i=>i.stat.status===y9):[]}_onLatencyMeasure(e){let{detail:t}=e;this._checkMaxLimit("maxEventLoopDelay",t.avgMs,1).catch(n=>{Ln.error(n)})}async _checkMaxLimit(e,t,n=1){let i=this.opts[e];if(i==null){Ln.trace("limit %s was not set so it cannot be applied",e);return}Ln.trace("checking limit of %s. current value: %d of %d",e,t,i),t>i&&(Ln("%s: limit exceeded: %p, %d/%d, pruning %d connection(s)",this.components.peerId,e,t,i,n),await this._pruneConnections(n))}async _pruneConnections(e){let t=this.getConnections(),n=new i4;for(let s of t){let a=s.remotePeer;if(n.has(a))continue;let c=await this.components.peerStore.getTags(a);n.set(a,c.reduce((u,l)=>u+l.value,0))}let i=t.sort((s,a)=>{let c=n.get(s.remotePeer)??0,u=n.get(a.remotePeer)??0;if(c>u)return 1;if(cf?-1:0}),o=[];for(let s of i)if(Ln("too many connections open - closing a connection to %p",s.remotePeer),o.push(s),o.length===e)break;await Promise.all(o.map(async s=>{try{await s.close()}catch(a){Ln.error(a)}this.onDisconnect(new ve("connectionEnd",{detail:s}))}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return Ln("connection from %s refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.opts.maxIncomingPendingConnections)return Ln("connection from %s refused - incomingPendingConnections exceeded by peer %s",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return Ln("connection from %s refused - inboundConnectionThreshold exceeded by host %s",i,e.remoteAddr),!1}}return this.getConnections().length{Zd.error("could start autodial",e)}),Zd("started")}async stop(){if(!this.options.enabled){Zd("not enabled");return}this.running=!1,this.autoDialTimeout!=null&&this.autoDialTimeout.clear(),Zd("stopped")}async _autoDial(){this.autoDialTimeout!=null&&this.autoDialTimeout.clear();let e=this.options.minConnections;if(this.components.connectionManager.getConnections().length>=e){this.autoDialTimeout=(0,rB.default)(this._autoDial,this.options.autoDialInterval);return}let t=await this.components.peerStore.all(),n=await Ne(t.sort(()=>Math.random()>.5?1:-1),i=>Yt(i,o=>!o.id.equals(this.components.peerId)),i=>Id(i,(o,s)=>s.protocols.length>o.protocols.length||s.id.publicKey!=null&&o.id.publicKey==null?1:-1),async i=>await Wo(i));for(let i=0;this.running&&iJd(t)}(e=r.Status||(r.Status={}));let n;(function(a){a.HOP="HOP",a.STOP="STOP",a.STATUS="STATUS",a.CAN_HOP="CAN_HOP"})(n=r.Type||(r.Type={}));let i;(function(a){a[a.HOP=1]="HOP",a[a.STOP=2]="STOP",a[a.STATUS=3]="STATUS",a[a.CAN_HOP=4]="CAN_HOP"})(i||(i={})),function(a){a.codec=()=>Jd(i)}(n=r.Type||(r.Type={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=Cr((u,l,f={})=>{if(f.lengthDelimited!==!1&&l.fork(),(f.writeDefaults===!0||u.id!=null&&u.id.byteLength>0)&&(l.uint32(10),l.bytes(u.id)),u.addrs!=null)for(let h of u.addrs)l.uint32(18),l.bytes(h);f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={id:new Uint8Array(0),addrs:[]},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.id=u.bytes();break;case 2:f.addrs.push(u.bytes());break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>Rr(u,a.codec()),a.decode=u=>Ir(u,a.codec())})(o=r.Peer||(r.Peer={}));let s;r.codec=()=>(s==null&&(s=Cr((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.srcPeer!=null&&(c.uint32(18),r.Peer.codec().encode(a.srcPeer,c,{writeDefaults:!1})),a.dstPeer!=null&&(c.uint32(26),r.Peer.codec().encode(a.dstPeer,c,{writeDefaults:!1})),a.code!=null&&(c.uint32(32),r.Status.codec().encode(a.code,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={},l=c==null?a.len:a.pos+c;for(;a.pos>>3){case 1:u.type=r.Type.codec().decode(a);break;case 2:u.srcPeer=r.Peer.codec().decode(a,a.uint32());break;case 3:u.dstPeer=r.Peer.codec().decode(a,a.uint32());break;case 4:u.code=r.Status.codec().decode(a);break;default:a.skipType(f&7);break}}return u})),s),r.encode=a=>Rr(a,r.codec()),r.decode=a=>Ir(a,r.codec())})(ft||(ft={}));var WFe=ue("libp2p:stream:converter");function aB(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:o}=t,s=async function*(){for await(let u of o)yield*u}(),a={async sink(u){e.signal!=null&&(u=sa(u,e.signal));try{await i(u),await c()}catch(l){l.type!=="aborted"&&WFe(l)}},source:e.signal!=null?sa(s,e.signal):s,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){return a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var mu="/libp2p/circuit/relay/0.1.0";function ahe(r){let e=new Map;async function t(o){let s=o.toString().split("/p2p-circuit").find(h=>h!==""),a=lt(s),c=a.getPeerId();if(c==null)throw new Error("Could not determine relay peer from multiaddr");let u=xt(c);await r.peerStore.addressBook.add(u,[a]);let l=await r.connectionManager.openConnection(u),f=l.remoteAddr.encapsulate("/p2p-circuit");e.set(l.remotePeer.toString(),f),i.dispatchEvent(new ve("listening"))}function n(){let o=[];for(let s of e.values())o.push(s);return o}let i=Object.assign(new Zt,{close:async()=>await Promise.resolve(),listen:t,getAddrs:n});return r.connectionManager.addEventListener("peer:disconnect",o=>{let{detail:s}=o;e.delete(s.remotePeer.toString())&&i.dispatchEvent(new ve("close"))}),i}var uB=C(ee(),1);function che(r,e){r.write({type:ft.Type.STATUS,code:e})}function T9(r,e){var t,n;try{((t=r.dstPeer)==null?void 0:t.addrs)!=null&&r.dstPeer.addrs.forEach(i=>lt(i))}catch(i){throw che(e,r.type===ft.Type.HOP?ft.Status.HOP_DST_MULTIADDR_INVALID:ft.Status.STOP_DST_MULTIADDR_INVALID),i}try{((n=r.srcPeer)==null?void 0:n.addrs)!=null&&r.srcPeer.addrs.forEach(i=>lt(i))}catch(i){throw che(e,r.type===ft.Type.HOP?ft.Status.HOP_SRC_MULTIADDR_INVALID:ft.Status.STOP_SRC_MULTIADDR_INVALID),i}}function cB(r){let e=async function*(){let t=yield,n=new ln;for await(let i of r){if(t==null){n.append(i),t=yield n,n=new ln;continue}for(n.append(i);n.length>=t;){let o=n.sublist(0,t);if(n.consume(t),t=yield o,t==null){n.length>0&&(t=yield n,n=new ln);break}}}if(t!=null)throw Object.assign(new Error(`stream ended before ${t} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function ng(r){let e=jn(),t=cB(r.source),n=io(),i,o=r.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:t,writer:e,stream:{sink:async a=>i!=null?await Promise.reject(i):(n.resolve(a),await o),source:t},rest:()=>e.end(),write:e.push,read:async()=>{let a=await t.next();if(a.value!=null)return a.value}}}var a4=ue("libp2p:circuit:stream-handler"),Dl=class{constructor(e){let{stream:t,maxLength:n=4096}=e;this.stream=t,this.shake=ng(this.stream),this.decoder=Xr.fromReader(this.shake.reader,{maxDataLength:n})}async read(){let e=await this.decoder.next();if(e.value!=null){let t=ft.decode(e.value);return a4("read message type",t.type),t}a4("read received no value, closing stream"),this.close()}write(e){a4("write message type %s",e.type),this.shake.write(vn.single(ft.encode(e)))}rest(){return this.shake.rest(),this.shake.stream}end(e){this.write(e),this.close()}close(){a4("closing the stream"),this.rest().sink([]).catch(e=>{a4.error(e)})}};var c4=ue("libp2p:circuit:stop");function uhe(r){let{connection:e,request:t,streamHandler:n}=r;try{T9(t,n)}catch(i){c4.error("invalid stop request via peer %p %o",e.remotePeer,i);return}return c4("stop request is valid"),n.write({type:ft.Type.STATUS,code:ft.Status.SUCCESS}),n.rest()}async function lhe(r){let{connection:e,request:t,signal:n}=r,i=await e.newStream(mu,{signal:n});c4("starting stop request to %p",e.remotePeer);let o=new Dl({stream:i});o.write(t);let s=await o.read();if(s==null){o.close();return}if(s.code===ft.Status.SUCCESS)return c4("stop request to %p was successful",e.remotePeer),o.rest();c4("stop request failed with code %d",s.code),o.close()}var ua=ue("libp2p:circuit:hop");async function fhe(r){let{connection:e,request:t,streamHandler:n,circuit:i,connectionManager:o}=r;if(!i.hopEnabled())return ua("HOP request received but we are not acting as a relay"),n.end({type:ft.Type.STATUS,code:ft.Status.HOP_CANT_SPEAK_RELAY});try{T9(t,n)}catch(f){ua.error("invalid hop request via peer %p %o",e.remotePeer,f);return}if(t.dstPeer==null){ua("HOP request received but we do not receive a dstPeer");return}let s=Wd(t.dstPeer.id),a=o.getConnections(s);if(a.length===0&&!i.hopActive())return ua("HOP request received but we are not connected to the destination peer"),n.end({type:ft.Type.STATUS,code:ft.Status.HOP_NO_CONN_TO_DST});if(a.length===0)return ua("did not have connection to remote peer"),n.end({type:ft.Type.STATUS,code:ft.Status.HOP_NO_CONN_TO_DST});let c={type:ft.Type.STOP,dstPeer:t.dstPeer,srcPeer:t.srcPeer},u;try{ua("performing STOP request");let f=await lhe({connection:a[0],request:c});if(f==null)throw new Error("Could not stop");u=f}catch(f){ua.error(f);return}ua("hop request from %p is valid",e.remotePeer),n.write({type:ft.Type.STATUS,code:ft.Status.SUCCESS});let l=n.rest();return ua("creating related connections"),await Ne(l,u,l)}async function dhe(r){let{connection:e,request:t,signal:n}=r,i=await e.newStream(mu,{signal:n}),o=new Dl({stream:i});o.write(t);let s=await o.read();if(s==null)throw(0,uB.default)(new Error("HOP request had no response"),q.ERR_HOP_REQUEST_FAILED);if(s.code===ft.Status.SUCCESS)return ua("hop request was successful"),o.rest();throw ua("hop request failed with code %d, closing stream",s.code),o.close(),(0,uB.default)(new Error(`HOP request failed with code "${s.code??"unknown"}"`),q.ERR_HOP_REQUEST_FAILED)}async function hhe(r){let{connection:e,signal:t}=r,n=await e.newStream(mu,{signal:t}),i=new Dl({stream:n});i.write({type:ft.Type.CAN_HOP});let o=await i.read();return await i.close(),!(o==null||o.code!==ft.Status.SUCCESS)}function phe(r){let{connection:e,streamHandler:t,circuit:n}=r,i=n.hopEnabled();ua("can hop (%s) request from %p",i,e.remotePeer),t.end({type:ft.Type.STATUS,code:i?ft.Status.SUCCESS:ft.Status.HOP_CANT_SPEAK_RELAY})}var ghe=C(Kn(),1),yhe=C(xi(),1),la=ue("libp2p:circuit"),I9=class{constructor(e,t){this._init=t,this.components=e,this._started=!1}isStarted(){return this._started}async start(){this._started||(this._started=!0,await this.components.registrar.handle(mu,e=>{this._onProtocol(e).catch(t=>{la.error(t)})},{...this._init}).catch(e=>{la.error(e)}))}async stop(){await this.components.registrar.unhandle(mu)}hopEnabled(){return!0}hopActive(){return!0}get[s9](){return!0}get[Symbol.toStringTag](){return"libp2p/circuit-relay-v1"}async _onProtocol(e){var o,s,a;let{connection:t,stream:n}=e,i=new ghe.TimeoutController(this._init.hop.timeout);try{(o=yhe.setMaxListeners)==null||o(1/0,i.signal)}catch{}try{let c=ps(n,i.signal),u=new Dl({stream:{...n,...c}}),l=await u.read();if(l==null){la("request was invalid, could not read from stream"),u.write({type:ft.Type.STATUS,code:ft.Status.MALFORMED_MESSAGE}),u.close();return}let f;switch(l.type){case ft.Type.CAN_HOP:{la("received CAN_HOP request from %p",t.remotePeer),await phe({circuit:this,connection:t,streamHandler:u});break}case ft.Type.HOP:{la("received HOP request from %p",t.remotePeer),await fhe({connection:t,request:l,streamHandler:u,circuit:this,connectionManager:this.components.connectionManager});break}case ft.Type.STOP:{la("received STOP request from %p",t.remotePeer),f=await uhe({connection:t,request:l,streamHandler:u});break}default:{la("Request of type %s not supported",l.type),u.write({type:ft.Type.STATUS,code:ft.Status.MALFORMED_MESSAGE}),u.close();return}}if(f!=null){let h=t.remoteAddr.encapsulate("/p2p-circuit").encapsulate(lt((s=l.dstPeer)==null?void 0:s.addrs[0])),d=lt((a=l.srcPeer)==null?void 0:a.addrs[0]),p=aB({stream:f,remoteAddr:h,localAddr:d}),g=l.type===ft.Type.HOP?"relay":"inbound";la("new %s connection %s",g,p.remoteAddr);let w=await this.components.upgrader.upgradeInbound(p);la("%s connection %s upgraded",g,p.remoteAddr),this.handler!=null&&this.handler(w)}}finally{i.clear()}}async dial(e,t={}){let n=e.toString().split("/p2p-circuit"),i=lt(n[0]),o=lt(n[n.length-1]),s=i.getPeerId(),a=o.getPeerId();if(s==null||a==null){let d="Circuit relay dial failed as addresses did not have peer id";throw la.error(d),(0,mhe.default)(new Error(d),q.ERR_RELAYED_DIAL)}let c=xt(s),u=xt(a),l=!1,h=this.components.connectionManager.getConnections(c)[0];h==null&&(await this.components.peerStore.addressBook.add(c,[i]),h=await this.components.connectionManager.openConnection(c,t),l=!0);try{let d=await dhe({...t,connection:h,request:{type:ft.Type.HOP,srcPeer:{id:this.components.peerId.toBytes(),addrs:this.components.addressManager.getAddresses().map(w=>w.bytes)},dstPeer:{id:u.toBytes(),addrs:[lt(o).bytes]}}}),p=i.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),g=aB({stream:d,remoteAddr:e,localAddr:p});return la("new outbound connection %s",g.remoteAddr),await this.components.upgrader.upgradeOutbound(g)}catch(d){throw la.error("Circuit relay dial failed",d),l&&await h.close(),d}}createListener(e){return this.handler=e.handler,ahe({connectionManager:this.components.connectionManager,peerStore:this.components.peerStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>i0.matches(t))}};var B9=C(FL(),1);async function R9(r){let e=new TextEncoder().encode(r),t=await mr.digest(e);return ce.createV0(t)}var lB="hop_relay",fB="true",C9="/libp2p/relay";var vhe=C(dB(),1);var whe="[a-fA-F\\d:]",eh=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${whe})|(?<=${whe})(?=\\s|$))`:"",oc="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Bn="[a-fA-F\\d]{1,4}",P9=` +`));return cr(e)}function EE(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),cr(t).byteLength!==t.length)return null;for(;cr(t).byteLength>100;){let i=t.indexOf("/");if(i===-1)return null;n+=n!==""?"/"+t.slice(0,i):t.slice(0,i),t=t.slice(i+1)}return cr(t).byteLength>100||cr(n).byteLength>155||r.linkname!=null&&cr(r.linkname).byteLength>100?null:(e.set(cr(t),0),e.set(od(r.mode&lRe,6),100),e.set(od(r.uid,6),108),e.set(od(r.gid,6),116),e.set(od(r.size,11),124),e.set(od(r.mtime.getTime()/1e3|0,11),136),e[156]=aRe+hRe(r.type),r.linkname!=null&&e.set(cr(r.linkname),157),e.set(cRe,fRe),e.set(uRe,dRe),r.uname!=null&&e.set(cr(r.uname),265),r.gname!=null&&e.set(cr(r.gname),297),e.set(od(r.devmajor??0,6),329),e.set(od(r.devminor??0,6),337),n!=null&&e.set(cr(n),345),e.set(od(pRe(e),6),148),e)}var{S_IFMT:gRe,S_IFBLK:yRe,S_IFCHR:wRe,S_IFDIR:bRe,S_IFIFO:_Re,S_IFLNK:ERe}=QJ.default,vRe=parseInt("755",8),xRe=parseInt("644",8),XJ=new Uint8Array(1024);function SRe(r=0){switch(r&gRe){case yRe:return"block-device";case wRe:return"character-device";case bRe:return"directory";case _Re:return"fifo";case ERe:return"symlink";default:return"file"}}function Rk(r){return r&=511,r!==0?XJ.subarray(0,512-r):new Uint8Array(0)}function Ik(r){if(r.pax==null){let e=EE(r);if(e!=null)return e}return ARe(r)}function ARe(r){let e=YJ(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new vt(EE(t)??new Uint8Array(0),e,Rk(e.length),EE({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function vE(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??SRe(e.mode),mode:e.mode??(e.type==="directory"?vRe:xRe),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=cr(t)),t instanceof Uint8Array||$c(t)){n.size=t.length,yield Ik(n),yield $c(t)?t.subarray():t,yield Rk(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=$n(await WJ(t)),yield Ik(n);continue}if(yield Ik(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let i=0;for await(let o of t??[])i+=o.length,yield $c(o)?o.subarray():o;if(i!==n.size)throw new Error(`size mismatch, wrote ${i} of ${n.size} bytes`);yield Rk(n.size)}yield XJ}}function Lm(r){let e=r.length;for(;--e>=0;)r[e]=0}var TRe=0,Bee=1,IRe=2,RRe=3,CRe=258,Zk=29,yw=256,uw=yw+1+Zk,Nm=30,Jk=19,Mee=2*uw+1,op=15,Ck=16,PRe=7,eN=256,Uee=16,Fee=17,zee=18,$k=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),RE=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),kRe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Vee=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),NRe=512,hl=new Array((uw+2)*2);Lm(hl);var sw=new Array(Nm*2);Lm(sw);var lw=new Array(NRe);Lm(lw);var fw=new Array(CRe-RRe+1);Lm(fw);var tN=new Array(Zk);Lm(tN);var CE=new Array(Nm);Lm(CE);function Pk(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}var Kee,$ee,qee;function kk(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}var Hee=r=>r<256?lw[r]:lw[256+(r>>>7)],dw=(r,e)=>{r.pending_buf[r.pending++]=e&255,r.pending_buf[r.pending++]=e>>>8&255},wo=(r,e,t)=>{r.bi_valid>Ck-t?(r.bi_buf|=e<>Ck-r.bi_valid,r.bi_valid+=t-Ck):(r.bi_buf|=e<{wo(r,t[e*2],t[e*2+1])},Gee=(r,e)=>{let t=0;do t|=r&1,r>>>=1,t<<=1;while(--e>0);return t>>>1},DRe=r=>{r.bi_valid===16?(dw(r,r.bi_buf),r.bi_buf=0,r.bi_valid=0):r.bi_valid>=8&&(r.pending_buf[r.pending++]=r.bi_buf&255,r.bi_buf>>=8,r.bi_valid-=8)},ORe=(r,e)=>{let t=e.dyn_tree,n=e.max_code,i=e.stat_desc.static_tree,o=e.stat_desc.has_stree,s=e.stat_desc.extra_bits,a=e.stat_desc.extra_base,c=e.stat_desc.max_length,u,l,f,h,d,p,g=0;for(h=0;h<=op;h++)r.bl_count[h]=0;for(t[r.heap[r.heap_max]*2+1]=0,u=r.heap_max+1;uc&&(h=c,g++),t[l*2+1]=h,!(l>n)&&(r.bl_count[h]++,d=0,l>=a&&(d=s[l-a]),p=t[l*2],r.opt_len+=p*(h+d),o&&(r.static_len+=p*(i[l*2+1]+d)));if(g!==0){do{for(h=c-1;r.bl_count[h]===0;)h--;r.bl_count[h]--,r.bl_count[h+1]+=2,r.bl_count[c]--,g-=2}while(g>0);for(h=c;h!==0;h--)for(l=r.bl_count[h];l!==0;)f=r.heap[--u],!(f>n)&&(t[f*2+1]!==h&&(r.opt_len+=(h-t[f*2+1])*t[f*2],t[f*2+1]=h),l--)}},jee=(r,e,t)=>{let n=new Array(op+1),i=0,o,s;for(o=1;o<=op;o++)i=i+t[o-1]<<1,n[o]=i;for(s=0;s<=e;s++){let a=r[s*2+1];a!==0&&(r[s*2]=Gee(n[a]++,a))}},LRe=()=>{let r,e,t,n,i,o=new Array(op+1);for(t=0,n=0;n>=7;n{let e;for(e=0;e{r.bi_valid>8?dw(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},ZJ=(r,e,t,n)=>{let i=e*2,o=t*2;return r[i]{let n=r.heap[t],i=t<<1;for(;i<=r.heap_len&&(i{let n,i,o=0,s,a;if(r.sym_next!==0)do n=r.pending_buf[r.sym_buf+o++]&255,n+=(r.pending_buf[r.sym_buf+o++]&255)<<8,i=r.pending_buf[r.sym_buf+o++],n===0?Hc(r,i,e):(s=fw[i],Hc(r,s+yw+1,e),a=$k[s],a!==0&&(i-=tN[s],wo(r,i,a)),n--,s=Hee(n),Hc(r,s,t),a=RE[s],a!==0&&(n-=CE[s],wo(r,n,a)));while(o{let t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,o=e.stat_desc.elems,s,a,c=-1,u;for(r.heap_len=0,r.heap_max=Mee,s=0;s>1;s>=1;s--)Nk(r,t,s);u=o;do s=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Nk(r,t,1),a=r.heap[1],r.heap[--r.heap_max]=s,r.heap[--r.heap_max]=a,t[u*2]=t[s*2]+t[a*2],r.depth[u]=(r.depth[s]>=r.depth[a]?r.depth[s]:r.depth[a])+1,t[s*2+1]=t[a*2+1]=u,r.heap[1]=u++,Nk(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],ORe(r,e),jee(t,c,r.bl_count)},eee=(r,e,t)=>{let n,i=-1,o,s=e[0*2+1],a=0,c=7,u=4;for(s===0&&(c=138,u=3),e[(t+1)*2+1]=65535,n=0;n<=t;n++)o=s,s=e[(n+1)*2+1],!(++a{let n,i=-1,o,s=e[0*2+1],a=0,c=7,u=4;for(s===0&&(c=138,u=3),n=0;n<=t;n++)if(o=s,s=e[(n+1)*2+1],!(++a{let e;for(eee(r,r.dyn_ltree,r.l_desc.max_code),eee(r,r.dyn_dtree,r.d_desc.max_code),qk(r,r.bl_desc),e=Jk-1;e>=3&&r.bl_tree[Vee[e]*2+1]===0;e--);return r.opt_len+=3*(e+1)+5+5+4,e},MRe=(r,e,t,n)=>{let i;for(wo(r,e-257,5),wo(r,t-1,5),wo(r,n-4,4),i=0;i{let e=4093624447,t;for(t=0;t<=31;t++,e>>>=1)if(e&1&&r.dyn_ltree[t*2]!==0)return 0;if(r.dyn_ltree[9*2]!==0||r.dyn_ltree[10*2]!==0||r.dyn_ltree[13*2]!==0)return 1;for(t=32;t{ree||(LRe(),ree=!0),r.l_desc=new kk(r.dyn_ltree,Kee),r.d_desc=new kk(r.dyn_dtree,$ee),r.bl_desc=new kk(r.bl_tree,qee),r.bi_buf=0,r.bi_valid=0,Wee(r)},Qee=(r,e,t,n)=>{wo(r,(TRe<<1)+(n?1:0),3),Yee(r),dw(r,t),dw(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},zRe=r=>{wo(r,Bee<<1,3),Hc(r,eN,hl),DRe(r)},VRe=(r,e,t,n)=>{let i,o,s=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=URe(r)),qk(r,r.l_desc),qk(r,r.d_desc),s=BRe(r),i=r.opt_len+3+7>>>3,o=r.static_len+3+7>>>3,o<=i&&(i=o)):i=o=t+5,t+4<=i&&e!==-1?Qee(r,e,t,n):r.strategy===4||o===i?(wo(r,(Bee<<1)+(n?1:0),3),JJ(r,hl,sw)):(wo(r,(IRe<<1)+(n?1:0),3),MRe(r,r.l_desc.max_code+1,r.d_desc.max_code+1,s+1),JJ(r,r.dyn_ltree,r.dyn_dtree)),Wee(r),n&&Yee(r)},KRe=(r,e,t)=>(r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[t*2]++:(r.matches++,e--,r.dyn_ltree[(fw[t]+yw+1)*2]++,r.dyn_dtree[Hee(e)*2]++),r.sym_next===r.sym_end),$Re=FRe,qRe=Qee,HRe=VRe,GRe=KRe,jRe=zRe,WRe={_tr_init:$Re,_tr_stored_block:qRe,_tr_flush_block:HRe,_tr_tally:GRe,_tr_align:jRe},YRe=(r,e,t,n)=>{let i=r&65535|0,o=r>>>16&65535|0,s=0;for(;t!==0;){s=t>2e3?2e3:t,t-=s;do i=i+e[n++]|0,o=o+i|0;while(--s);i%=65521,o%=65521}return i|o<<16|0},hw=YRe,QRe=()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r}return e},XRe=new Uint32Array(QRe()),ZRe=(r,e,t,n)=>{let i=XRe,o=n+t;r^=-1;for(let s=n;s>>8^i[(r^e[s])&255];return r^-1},ci=ZRe,cp={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},fp={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:JRe,_tr_stored_block:Hk,_tr_flush_block:eCe,_tr_tally:cd,_tr_align:tCe}=WRe,{Z_NO_FLUSH:ud,Z_PARTIAL_FLUSH:rCe,Z_FULL_FLUSH:nCe,Z_FINISH:Gs,Z_BLOCK:nee,Z_OK:vi,Z_STREAM_END:iee,Z_STREAM_ERROR:Gc,Z_DATA_ERROR:iCe,Z_BUF_ERROR:Dk,Z_DEFAULT_COMPRESSION:oCe,Z_FILTERED:sCe,Z_HUFFMAN_ONLY:xE,Z_RLE:aCe,Z_FIXED:cCe,Z_DEFAULT_STRATEGY:uCe,Z_UNKNOWN:lCe,Z_DEFLATED:NE}=fp,fCe=9,dCe=15,hCe=8,pCe=29,mCe=256,Gk=mCe+1+pCe,gCe=30,yCe=19,wCe=2*Gk+1,bCe=15,Mt=3,ad=258,jc=ad+Mt+1,_Ce=32,Dm=42,rN=57,jk=69,Wk=73,Yk=91,Qk=103,sp=113,iw=666,so=1,Bm=2,up=3,Mm=4,ECe=3,ap=(r,e)=>(r.msg=cp[e],e),oee=r=>r*2-(r>4?9:0),sd=r=>{let e=r.length;for(;--e>=0;)r[e]=0},vCe=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)},xCe=(r,e,t)=>(e<{let e=r.state,t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},ns=(r,e)=>{eCe(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,rs(r.strm)},or=(r,e)=>{r.pending_buf[r.pending++]=e},nw=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=e&255},Xk=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=hw(r.adler,e,i,t):r.state.wrap===2&&(r.adler=ci(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},Xee=(r,e)=>{let t=r.max_chain_length,n=r.strstart,i,o,s=r.prev_length,a=r.nice_match,c=r.strstart>r.w_size-jc?r.strstart-(r.w_size-jc):0,u=r.window,l=r.w_mask,f=r.prev,h=r.strstart+ad,d=u[n+s-1],p=u[n+s];r.prev_length>=r.good_match&&(t>>=2),a>r.lookahead&&(a=r.lookahead);do if(i=e,!(u[i+s]!==p||u[i+s-1]!==d||u[i]!==u[n]||u[++i]!==u[n+1])){n+=2,i++;do;while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&ns){if(r.match_start=e,s=o,o>=a)break;d=u[n+s-1],p=u[n+s]}}while((e=f[e&l])>c&&--t!==0);return s<=r.lookahead?s:r.lookahead},Om=r=>{let e=r.w_size,t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-jc)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),vCe(r),n+=e),r.strm.avail_in===0)break;if(t=Xk(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.lookahead+r.insert>=Mt)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=ld(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=ld(r,r.ins_h,r.window[i+Mt-1]),r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++,r.insert--,!(r.lookahead+r.insert{let t=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,n,i,o,s=0,a=r.strm.avail_in;do{if(n=65535,o=r.bi_valid+42>>3,r.strm.avail_outi+r.strm.avail_in&&(n=i+r.strm.avail_in),n>o&&(n=o),n>8,r.pending_buf[r.pending-2]=~n,r.pending_buf[r.pending-1]=~n>>8,rs(r.strm),i&&(i>n&&(i=n),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+i),r.strm.next_out),r.strm.next_out+=i,r.strm.avail_out-=i,r.strm.total_out+=i,r.block_start+=i,n-=i),n&&(Xk(r.strm,r.strm.output,r.strm.next_out,n),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n)}while(s===0);return a-=r.strm.avail_in,a&&(a>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=a&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-a,r.strm.next_in),r.strstart),r.strstart+=a,r.insert+=a>r.w_size-r.insert?r.w_size-r.insert:a),r.block_start=r.strstart),r.high_watero&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,o+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),o>r.strm.avail_in&&(o=r.strm.avail_in),o&&(Xk(r.strm,r.window,r.strstart,o),r.strstart+=o,r.insert+=o>r.w_size-r.insert?r.w_size-r.insert:o),r.high_water>3,o=r.pending_buf_size-o>65535?65535:r.pending_buf_size-o,t=o>r.w_size?r.w_size:o,i=r.strstart-r.block_start,(i>=t||(i||e===Gs)&&e!==ud&&r.strm.avail_in===0&&i<=o)&&(n=i>o?o:i,s=e===Gs&&r.strm.avail_in===0&&n===i?1:0,Hk(r,r.block_start,n,s),r.block_start+=n,rs(r.strm)),s?up:so)},Ok=(r,e)=>{let t,n;for(;;){if(r.lookahead=Mt&&(r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),t!==0&&r.strstart-t<=r.w_size-jc&&(r.match_length=Xee(r,t)),r.match_length>=Mt)if(n=cd(r,r.strstart-r.match_start,r.match_length-Mt),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=Mt){r.match_length--;do r.strstart++,r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart;while(--r.match_length!==0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.ins_h=r.window[r.strstart],r.ins_h=ld(r,r.ins_h,r.window[r.strstart+1]);else n=cd(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(ns(r,!1),r.strm.avail_out===0))return so}return r.insert=r.strstart{let t,n,i;for(;;){if(r.lookahead=Mt&&(r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=Mt-1,t!==0&&r.prev_length4096)&&(r.match_length=Mt-1)),r.prev_length>=Mt&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-Mt,n=cd(r,r.strstart-1-r.prev_match,r.prev_length-Mt),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(r.ins_h=ld(r,r.ins_h,r.window[r.strstart+Mt-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart);while(--r.prev_length!==0);if(r.match_available=0,r.match_length=Mt-1,r.strstart++,n&&(ns(r,!1),r.strm.avail_out===0))return so}else if(r.match_available){if(n=cd(r,0,r.window[r.strstart-1]),n&&ns(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return so}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(n=cd(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart{let t,n,i,o,s=r.window;for(;;){if(r.lookahead<=ad){if(Om(r),r.lookahead<=ad&&e===ud)return so;if(r.lookahead===0)break}if(r.match_length=0,r.lookahead>=Mt&&r.strstart>0&&(i=r.strstart-1,n=s[i],n===s[++i]&&n===s[++i]&&n===s[++i])){o=r.strstart+ad;do;while(n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&ir.lookahead&&(r.match_length=r.lookahead)}if(r.match_length>=Mt?(t=cd(r,1,r.match_length-Mt),r.lookahead-=r.match_length,r.strstart+=r.match_length,r.match_length=0):(t=cd(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++),t&&(ns(r,!1),r.strm.avail_out===0))return so}return r.insert=0,e===Gs?(ns(r,!0),r.strm.avail_out===0?up:Mm):r.sym_next&&(ns(r,!1),r.strm.avail_out===0)?so:Bm},ACe=(r,e)=>{let t;for(;;){if(r.lookahead===0&&(Om(r),r.lookahead===0)){if(e===ud)return so;break}if(r.match_length=0,t=cd(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++,t&&(ns(r,!1),r.strm.avail_out===0))return so}return r.insert=0,e===Gs?(ns(r,!0),r.strm.avail_out===0?up:Mm):r.sym_next&&(ns(r,!1),r.strm.avail_out===0)?so:Bm};function qc(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}var ow=[new qc(0,0,0,0,Zee),new qc(4,4,8,4,Ok),new qc(4,5,16,8,Ok),new qc(4,6,32,32,Ok),new qc(4,4,16,16,Pm),new qc(8,16,32,32,Pm),new qc(8,16,128,128,Pm),new qc(8,32,128,256,Pm),new qc(32,128,258,1024,Pm),new qc(32,258,258,4096,Pm)],TCe=r=>{r.window_size=2*r.w_size,sd(r.head),r.max_lazy_match=ow[r.level].max_lazy,r.good_match=ow[r.level].good_length,r.nice_match=ow[r.level].nice_length,r.max_chain_length=ow[r.level].max_chain,r.strstart=0,r.block_start=0,r.lookahead=0,r.insert=0,r.match_length=r.prev_length=Mt-1,r.match_available=0,r.ins_h=0};function ICe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=NE,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(wCe*2),this.dyn_dtree=new Uint16Array((2*gCe+1)*2),this.bl_tree=new Uint16Array((2*yCe+1)*2),sd(this.dyn_ltree),sd(this.dyn_dtree),sd(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(bCe+1),this.heap=new Uint16Array(2*Gk+1),sd(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Gk+1),sd(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var ww=r=>{if(!r)return 1;let e=r.state;return!e||e.strm!==r||e.status!==Dm&&e.status!==rN&&e.status!==jk&&e.status!==Wk&&e.status!==Yk&&e.status!==Qk&&e.status!==sp&&e.status!==iw?1:0},Jee=r=>{if(ww(r))return ap(r,Gc);r.total_in=r.total_out=0,r.data_type=lCe;let e=r.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?rN:e.wrap?Dm:sp,r.adler=e.wrap===2?0:1,e.last_flush=-2,JRe(e),vi},ete=r=>{let e=Jee(r);return e===vi&&TCe(r.state),e},RCe=(r,e)=>ww(r)||r.state.wrap!==2?Gc:(r.state.gzhead=e,vi),tte=(r,e,t,n,i,o)=>{if(!r)return Gc;let s=1;if(e===oCe&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),i<1||i>fCe||t!==NE||n<8||n>15||e<0||e>9||o<0||o>cCe||n===8&&s!==1)return ap(r,Gc);n===8&&(n=9);let a=new ICe;return r.state=a,a.strm=r,a.status=Dm,a.wrap=s,a.gzhead=null,a.w_bits=n,a.w_size=1<tte(r,e,NE,dCe,hCe,uCe),PCe=(r,e)=>{if(ww(r)||e>nee||e<0)return r?ap(r,Gc):Gc;let t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===iw&&e!==Gs)return ap(r,r.avail_out===0?Dk:Gc);let n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(rs(r),r.avail_out===0)return t.last_flush=-1,vi}else if(r.avail_in===0&&oee(e)<=oee(n)&&e!==Gs)return ap(r,Dk);if(t.status===iw&&r.avail_in!==0)return ap(r,Dk);if(t.status===Dm&&t.wrap===0&&(t.status=sp),t.status===Dm){let i=NE+(t.w_bits-8<<4)<<8,o=-1;if(t.strategy>=xE||t.level<2?o=0:t.level<6?o=1:t.level===6?o=2:o=3,i|=o<<6,t.strstart!==0&&(i|=_Ce),i+=31-i%31,nw(t,i),t.strstart!==0&&(nw(t,r.adler>>>16),nw(t,r.adler&65535)),r.adler=1,t.status=sp,rs(r),t.pending!==0)return t.last_flush=-1,vi}if(t.status===rN){if(r.adler=0,or(t,31),or(t,139),or(t,8),t.gzhead)or(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),or(t,t.gzhead.time&255),or(t,t.gzhead.time>>8&255),or(t,t.gzhead.time>>16&255),or(t,t.gzhead.time>>24&255),or(t,t.level===9?2:t.strategy>=xE||t.level<2?4:0),or(t,t.gzhead.os&255),t.gzhead.extra&&t.gzhead.extra.length&&(or(t,t.gzhead.extra.length&255),or(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=ci(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=jk;else if(or(t,0),or(t,0),or(t,0),or(t,0),or(t,0),or(t,t.level===9?2:t.strategy>=xE||t.level<2?4:0),or(t,ECe),t.status=sp,rs(r),t.pending!==0)return t.last_flush=-1,vi}if(t.status===jk){if(t.gzhead.extra){let i=t.pending,o=(t.gzhead.extra.length&65535)-t.gzindex;for(;t.pending+o>t.pending_buf_size;){let a=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+a),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=a,rs(r),t.pending!==0)return t.last_flush=-1,vi;i=0,o-=a}let s=new Uint8Array(t.gzhead.extra);t.pending_buf.set(s.subarray(t.gzindex,t.gzindex+o),t.pending),t.pending+=o,t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=Wk}if(t.status===Wk){if(t.gzhead.name){let i=t.pending,o;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),rs(r),t.pending!==0)return t.last_flush=-1,vi;i=0}t.gzindexi&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=Yk}if(t.status===Yk){if(t.gzhead.comment){let i=t.pending,o;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>i&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i)),rs(r),t.pending!==0)return t.last_flush=-1,vi;i=0}t.gzindexi&&(r.adler=ci(r.adler,t.pending_buf,t.pending-i,i))}t.status=Qk}if(t.status===Qk){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(rs(r),t.pending!==0))return t.last_flush=-1,vi;or(t,r.adler&255),or(t,r.adler>>8&255),r.adler=0}if(t.status=sp,rs(r),t.pending!==0)return t.last_flush=-1,vi}if(r.avail_in!==0||t.lookahead!==0||e!==ud&&t.status!==iw){let i=t.level===0?Zee(t,e):t.strategy===xE?ACe(t,e):t.strategy===aCe?SCe(t,e):ow[t.level].func(t,e);if((i===up||i===Mm)&&(t.status=iw),i===so||i===up)return r.avail_out===0&&(t.last_flush=-1),vi;if(i===Bm&&(e===rCe?tCe(t):e!==nee&&(Hk(t,0,0,!1),e===nCe&&(sd(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),rs(r),r.avail_out===0))return t.last_flush=-1,vi}return e!==Gs?vi:t.wrap<=0?iee:(t.wrap===2?(or(t,r.adler&255),or(t,r.adler>>8&255),or(t,r.adler>>16&255),or(t,r.adler>>24&255),or(t,r.total_in&255),or(t,r.total_in>>8&255),or(t,r.total_in>>16&255),or(t,r.total_in>>24&255)):(nw(t,r.adler>>>16),nw(t,r.adler&65535)),rs(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?vi:iee)},kCe=r=>{if(ww(r))return Gc;let e=r.state.status;return r.state=null,e===sp?ap(r,iCe):vi},NCe=(r,e)=>{let t=e.length;if(ww(r))return Gc;let n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==Dm||n.lookahead)return Gc;if(i===1&&(r.adler=hw(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(sd(n.head),n.strstart=0,n.block_start=0,n.insert=0);let c=new Uint8Array(n.w_size);c.set(e.subarray(t-n.w_size,t),0),e=c,t=n.w_size}let o=r.avail_in,s=r.next_in,a=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,Om(n);n.lookahead>=Mt;){let c=n.strstart,u=n.lookahead-(Mt-1);do n.ins_h=ld(n,n.ins_h,n.window[c+Mt-1]),n.prev[c&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=c,c++;while(--u);n.strstart=c,n.lookahead=Mt-1,Om(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=Mt-1,n.match_available=0,r.next_in=s,r.input=a,r.avail_in=o,n.wrap=i,vi},DCe=CCe,OCe=tte,LCe=ete,BCe=Jee,MCe=RCe,UCe=PCe,FCe=kCe,zCe=NCe,VCe="pako deflate (from Nodeca project)",aw={deflateInit:DCe,deflateInit2:OCe,deflateReset:LCe,deflateResetKeep:BCe,deflateSetHeader:MCe,deflate:UCe,deflateEnd:FCe,deflateSetDictionary:zCe,deflateInfo:VCe},KCe=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),$Ce=function(r){let e=Array.prototype.slice.call(arguments,1);for(;e.length;){let t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(let n in t)KCe(t,n)&&(r[n]=t[n])}}return r},qCe=r=>{let e=0;for(let n=0,i=r.length;n=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;pw[254]=pw[254]=1;var HCe=r=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);let e,t,n,i,o,s=r.length,a=0;for(i=0;i>>6,e[o++]=128|t&63):t<65536?(e[o++]=224|t>>>12,e[o++]=128|t>>>6&63,e[o++]=128|t&63):(e[o++]=240|t>>>18,e[o++]=128|t>>>12&63,e[o++]=128|t>>>6&63,e[o++]=128|t&63);return e},GCe=(r,e)=>{if(e<65534&&r.subarray&&rte)return String.fromCharCode.apply(null,r.length===e?r:r.subarray(0,e));let t="";for(let n=0;n{let t=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));let n,i,o=new Array(t*2);for(i=0,n=0;n4){o[i++]=65533,n+=a-1;continue}for(s&=a===2?31:a===3?15:7;a>1&&n1){o[i++]=65533;continue}s<65536?o[i++]=s:(s-=65536,o[i++]=55296|s>>10&1023,o[i++]=56320|s&1023)}return GCe(o,i)},WCe=(r,e)=>{e=e||r.length,e>r.length&&(e=r.length);let t=e-1;for(;t>=0&&(r[t]&192)===128;)t--;return t<0||t===0?e:t+pw[r[t]]>e?t:e},mw={string2buf:HCe,buf2string:jCe,utf8border:WCe};function YCe(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var nte=YCe,ite=Object.prototype.toString,{Z_NO_FLUSH:QCe,Z_SYNC_FLUSH:XCe,Z_FULL_FLUSH:ZCe,Z_FINISH:JCe,Z_OK:PE,Z_STREAM_END:ePe,Z_DEFAULT_COMPRESSION:tPe,Z_DEFAULT_STRATEGY:rPe,Z_DEFLATED:nPe}=fp;function bw(r){this.options=DE.assign({level:tPe,method:nPe,chunkSize:16384,windowBits:15,memLevel:8,strategy:rPe},r||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nte,this.strm.avail_out=0;let t=aw.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==PE)throw new Error(cp[t]);if(e.header&&aw.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(typeof e.dictionary=="string"?n=mw.string2buf(e.dictionary):ite.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,t=aw.deflateSetDictionary(this.strm,n),t!==PE)throw new Error(cp[t]);this._dict_set=!0}}bw.prototype.push=function(r,e){let t=this.strm,n=this.options.chunkSize,i,o;if(this.ended)return!1;for(e===~~e?o=e:o=e===!0?JCe:QCe,typeof r=="string"?t.input=mw.string2buf(r):ite.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(o===XCe||o===ZCe)&&t.avail_out<=6){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(i=aw.deflate(t,o),i===ePe)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=aw.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===PE;if(t.avail_out===0){this.onData(t.output);continue}if(o>0&&t.next_out>0){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(t.avail_in===0)break}return!0};bw.prototype.onData=function(r){this.chunks.push(r)};bw.prototype.onEnd=function(r){r===PE&&(this.result=DE.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};function nN(r,e){let t=new bw(e);if(t.push(r,!0),t.err)throw t.msg||cp[t.err];return t.result}function iPe(r,e){return e=e||{},e.raw=!0,nN(r,e)}function oPe(r,e){return e=e||{},e.gzip=!0,nN(r,e)}var sPe=bw,aPe=nN,cPe=iPe,uPe=oPe,lPe=fp,fPe={Deflate:sPe,deflate:aPe,deflateRaw:cPe,gzip:uPe,constants:lPe},SE=16209,dPe=16191,hPe=function(e,t){let n,i,o,s,a,c,u,l,f,h,d,p,g,w,_,x,m,y,b,E,v,S,A,I,k=e.state;n=e.next_in,A=e.input,i=n+(e.avail_in-5),o=e.next_out,I=e.output,s=o-(t-e.avail_out),a=o+(e.avail_out-257),c=k.dmax,u=k.wsize,l=k.whave,f=k.wnext,h=k.window,d=k.hold,p=k.bits,g=k.lencode,w=k.distcode,_=(1<>>24,d>>>=y,p-=y,y=m>>>16&255,y===0)I[o++]=m&65535;else if(y&16){b=m&65535,y&=15,y&&(p>>=y,p-=y),p<15&&(d+=A[n++]<>>24,d>>>=y,p-=y,y=m>>>16&255,y&16){if(E=m&65535,y&=15,pc){e.msg="invalid distance too far back",k.mode=SE;break e}if(d>>>=y,p-=y,y=o-s,E>y){if(y=E-y,y>l&&k.sane){e.msg="invalid distance too far back",k.mode=SE;break e}if(v=0,S=h,f===0){if(v+=u-y,y2;)I[o++]=S[v++],I[o++]=S[v++],I[o++]=S[v++],b-=3;b&&(I[o++]=S[v++],b>1&&(I[o++]=S[v++]))}else{v=o-E;do I[o++]=I[v++],I[o++]=I[v++],I[o++]=I[v++],b-=3;while(b>2);b&&(I[o++]=I[v++],b>1&&(I[o++]=I[v++]))}}else if(y&64){e.msg="invalid distance code",k.mode=SE;break e}else{m=w[(m&65535)+(d&(1<>3,n-=b,p-=b<<3,d&=(1<{let c=a.bits,u=0,l=0,f=0,h=0,d=0,p=0,g=0,w=0,_=0,x=0,m,y,b,E,v,S=null,A,I=new Uint16Array(km+1),k=new Uint16Array(km+1),N=null,O,G,R;for(u=0;u<=km;u++)I[u]=0;for(l=0;l=1&&I[h]===0;h--);if(d>h&&(d=h),h===0)return i[o++]=1<<24|64<<16|0,i[o++]=1<<24|64<<16|0,a.bits=1,0;for(f=1;f0&&(r===cee||h!==1))return-1;for(k[1]=0,u=1;usee||r===uee&&_>aee)return 1;for(;;){O=u-g,s[l]+1=A?(G=N[s[l]-A],R=S[s[l]-A]):(G=32+64,R=0),m=1<>g)+y]=O<<24|G<<16|R|0;while(y!==0);for(m=1<>=1;if(m!==0?(x&=m-1,x+=m):x=0,l++,--I[u]===0){if(u===h)break;u=e[t+s[l]]}if(u>d&&(x&E)!==b){for(g===0&&(g=d),v+=f,p=u-g,w=1<see||r===uee&&_>aee)return 1;b=x&E,i[b]=d<<24|p<<16|v-o|0}}return x!==0&&(i[v+x]=u-g<<24|64<<16|0),a.bits=d,0},cw=wPe,bPe=0,ote=1,ste=2,{Z_FINISH:lee,Z_BLOCK:_Pe,Z_TREES:AE,Z_OK:lp,Z_STREAM_END:EPe,Z_NEED_DICT:vPe,Z_STREAM_ERROR:js,Z_DATA_ERROR:ate,Z_MEM_ERROR:cte,Z_BUF_ERROR:xPe,Z_DEFLATED:fee}=fp,OE=16180,dee=16181,hee=16182,pee=16183,mee=16184,gee=16185,yee=16186,wee=16187,bee=16188,_ee=16189,kE=16190,dl=16191,Bk=16192,Eee=16193,Mk=16194,vee=16195,xee=16196,See=16197,Aee=16198,TE=16199,IE=16200,Tee=16201,Iee=16202,Ree=16203,Cee=16204,Pee=16205,Uk=16206,kee=16207,Nee=16208,Kr=16209,ute=16210,lte=16211,SPe=852,APe=592,TPe=15,IPe=TPe,Dee=r=>(r>>>24&255)+(r>>>8&65280)+((r&65280)<<8)+((r&255)<<24);function RPe(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var dp=r=>{if(!r)return 1;let e=r.state;return!e||e.strm!==r||e.modelte?1:0},fte=r=>{if(dp(r))return js;let e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.adler=e.wrap&1),e.mode=OE,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(SPe),e.distcode=e.distdyn=new Int32Array(APe),e.sane=1,e.back=-1,lp},dte=r=>{if(dp(r))return js;let e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,fte(r)},hte=(r,e)=>{let t;if(dp(r))return js;let n=r.state;return e<0?(t=0,e=-e):(t=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?js:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,dte(r))},pte=(r,e)=>{if(!r)return js;let t=new RPe;r.state=t,t.strm=r,t.window=null,t.mode=OE;let n=hte(r,e);return n!==lp&&(r.state=null),n},CPe=r=>pte(r,IPe),Oee=!0,Fk,zk,PPe=r=>{if(Oee){Fk=new Int32Array(512),zk=new Int32Array(32);let e=0;for(;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(cw(ote,r.lens,0,288,Fk,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;cw(ste,r.lens,0,32,zk,0,r.work,{bits:5}),Oee=!1}r.lencode=Fk,r.lenbits=9,r.distcode=zk,r.distbits=5},mte=(r,e,t,n)=>{let i,o=r.state;return o.window===null&&(o.wsize=1<=o.wsize?(o.window.set(e.subarray(t-o.wsize,t),0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>n&&(i=n),o.window.set(e.subarray(t-n,t-n+i),o.wnext),n-=i,n?(o.window.set(e.subarray(t-n,t),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave{let t,n,i,o,s,a,c,u,l,f,h,d,p,g,w=0,_,x,m,y,b,E,v,S,A=new Uint8Array(4),I,k,N=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(dp(r)||!r.output||!r.input&&r.avail_in!==0)return js;t=r.state,t.mode===dl&&(t.mode=Bk),s=r.next_out,i=r.output,c=r.avail_out,o=r.next_in,n=r.input,a=r.avail_in,u=t.hold,l=t.bits,f=a,h=c,S=lp;e:for(;;)switch(t.mode){case OE:if(t.wrap===0){t.mode=Bk;break}for(;l<16;){if(a===0)break e;a--,u+=n[o++]<>>8&255,t.check=ci(t.check,A,2,0),u=0,l=0,t.mode=dee;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((u&255)<<8)+(u>>8))%31){r.msg="incorrect header check",t.mode=Kr;break}if((u&15)!==fee){r.msg="unknown compression method",t.mode=Kr;break}if(u>>>=4,l-=4,v=(u&15)+8,t.wbits===0&&(t.wbits=v),v>15||v>t.wbits){r.msg="invalid window size",t.mode=Kr;break}t.dmax=1<>8&1),t.flags&512&&t.wrap&4&&(A[0]=u&255,A[1]=u>>>8&255,t.check=ci(t.check,A,2,0)),u=0,l=0,t.mode=hee;case hee:for(;l<32;){if(a===0)break e;a--,u+=n[o++]<>>8&255,A[2]=u>>>16&255,A[3]=u>>>24&255,t.check=ci(t.check,A,4,0)),u=0,l=0,t.mode=pee;case pee:for(;l<16;){if(a===0)break e;a--,u+=n[o++]<>8),t.flags&512&&t.wrap&4&&(A[0]=u&255,A[1]=u>>>8&255,t.check=ci(t.check,A,2,0)),u=0,l=0,t.mode=mee;case mee:if(t.flags&1024){for(;l<16;){if(a===0)break e;a--,u+=n[o++]<>>8&255,t.check=ci(t.check,A,2,0)),u=0,l=0}else t.head&&(t.head.extra=null);t.mode=gee;case gee:if(t.flags&1024&&(d=t.length,d>a&&(d=a),d&&(t.head&&(v=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(o,o+d),v)),t.flags&512&&t.wrap&4&&(t.check=ci(t.check,n,d,o)),a-=d,o+=d,t.length-=d),t.length))break e;t.length=0,t.mode=yee;case yee:if(t.flags&2048){if(a===0)break e;d=0;do v=n[o+d++],t.head&&v&&t.length<65536&&(t.head.name+=String.fromCharCode(v));while(v&&d>9&1,t.head.done=!0),r.adler=t.check=0,t.mode=dl;break;case _ee:for(;l<32;){if(a===0)break e;a--,u+=n[o++]<>>=l&7,l-=l&7,t.mode=Uk;break}for(;l<3;){if(a===0)break e;a--,u+=n[o++]<>>=1,l-=1,u&3){case 0:t.mode=Eee;break;case 1:if(PPe(t),t.mode=TE,e===AE){u>>>=2,l-=2;break e}break;case 2:t.mode=xee;break;case 3:r.msg="invalid block type",t.mode=Kr}u>>>=2,l-=2;break;case Eee:for(u>>>=l&7,l-=l&7;l<32;){if(a===0)break e;a--,u+=n[o++]<>>16^65535)){r.msg="invalid stored block lengths",t.mode=Kr;break}if(t.length=u&65535,u=0,l=0,t.mode=Mk,e===AE)break e;case Mk:t.mode=vee;case vee:if(d=t.length,d){if(d>a&&(d=a),d>c&&(d=c),d===0)break e;i.set(n.subarray(o,o+d),s),a-=d,o+=d,c-=d,s+=d,t.length-=d;break}t.mode=dl;break;case xee:for(;l<14;){if(a===0)break e;a--,u+=n[o++]<>>=5,l-=5,t.ndist=(u&31)+1,u>>>=5,l-=5,t.ncode=(u&15)+4,u>>>=4,l-=4,t.nlen>286||t.ndist>30){r.msg="too many length or distance symbols",t.mode=Kr;break}t.have=0,t.mode=See;case See:for(;t.have>>=3,l-=3}for(;t.have<19;)t.lens[N[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,I={bits:t.lenbits},S=cw(bPe,t.lens,0,19,t.lencode,0,t.work,I),t.lenbits=I.bits,S){r.msg="invalid code lengths set",t.mode=Kr;break}t.have=0,t.mode=Aee;case Aee:for(;t.have>>24,x=w>>>16&255,m=w&65535,!(_<=l);){if(a===0)break e;a--,u+=n[o++]<>>=_,l-=_,t.lens[t.have++]=m;else{if(m===16){for(k=_+2;l>>=_,l-=_,t.have===0){r.msg="invalid bit length repeat",t.mode=Kr;break}v=t.lens[t.have-1],d=3+(u&3),u>>>=2,l-=2}else if(m===17){for(k=_+3;l>>=_,l-=_,v=0,d=3+(u&7),u>>>=3,l-=3}else{for(k=_+7;l>>=_,l-=_,v=0,d=11+(u&127),u>>>=7,l-=7}if(t.have+d>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=Kr;break}for(;d--;)t.lens[t.have++]=v}}if(t.mode===Kr)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=Kr;break}if(t.lenbits=9,I={bits:t.lenbits},S=cw(ote,t.lens,0,t.nlen,t.lencode,0,t.work,I),t.lenbits=I.bits,S){r.msg="invalid literal/lengths set",t.mode=Kr;break}if(t.distbits=6,t.distcode=t.distdyn,I={bits:t.distbits},S=cw(ste,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,I),t.distbits=I.bits,S){r.msg="invalid distances set",t.mode=Kr;break}if(t.mode=TE,e===AE)break e;case TE:t.mode=IE;case IE:if(a>=6&&c>=258){r.next_out=s,r.avail_out=c,r.next_in=o,r.avail_in=a,t.hold=u,t.bits=l,hPe(r,h),s=r.next_out,i=r.output,c=r.avail_out,o=r.next_in,n=r.input,a=r.avail_in,u=t.hold,l=t.bits,t.mode===dl&&(t.back=-1);break}for(t.back=0;w=t.lencode[u&(1<>>24,x=w>>>16&255,m=w&65535,!(_<=l);){if(a===0)break e;a--,u+=n[o++]<>y)],_=w>>>24,x=w>>>16&255,m=w&65535,!(y+_<=l);){if(a===0)break e;a--,u+=n[o++]<>>=y,l-=y,t.back+=y}if(u>>>=_,l-=_,t.back+=_,t.length=m,x===0){t.mode=Pee;break}if(x&32){t.back=-1,t.mode=dl;break}if(x&64){r.msg="invalid literal/length code",t.mode=Kr;break}t.extra=x&15,t.mode=Tee;case Tee:if(t.extra){for(k=t.extra;l>>=t.extra,l-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=Iee;case Iee:for(;w=t.distcode[u&(1<>>24,x=w>>>16&255,m=w&65535,!(_<=l);){if(a===0)break e;a--,u+=n[o++]<>y)],_=w>>>24,x=w>>>16&255,m=w&65535,!(y+_<=l);){if(a===0)break e;a--,u+=n[o++]<>>=y,l-=y,t.back+=y}if(u>>>=_,l-=_,t.back+=_,x&64){r.msg="invalid distance code",t.mode=Kr;break}t.offset=m,t.extra=x&15,t.mode=Ree;case Ree:if(t.extra){for(k=t.extra;l>>=t.extra,l-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){r.msg="invalid distance too far back",t.mode=Kr;break}t.mode=Cee;case Cee:if(c===0)break e;if(d=h-c,t.offset>d){if(d=t.offset-d,d>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=Kr;break}d>t.wnext?(d-=t.wnext,p=t.wsize-d):p=t.wnext-d,d>t.length&&(d=t.length),g=t.window}else g=i,p=s-t.offset,d=t.length;d>c&&(d=c),c-=d,t.length-=d;do i[s++]=g[p++];while(--d);t.length===0&&(t.mode=IE);break;case Pee:if(c===0)break e;i[s++]=t.length,c--,t.mode=IE;break;case Uk:if(t.wrap){for(;l<32;){if(a===0)break e;a--,u|=n[o++]<{if(dp(r))return js;let e=r.state;return e.window&&(e.window=null),r.state=null,lp},DPe=(r,e)=>{if(dp(r))return js;let t=r.state;return t.wrap&2?(t.head=e,e.done=!1,lp):js},OPe=(r,e)=>{let t=e.length,n,i,o;return dp(r)||(n=r.state,n.wrap!==0&&n.mode!==kE)?js:n.mode===kE&&(i=1,i=hw(i,e,t,0),i!==n.check)?ate:(o=mte(r,e,t,t),o?(n.mode=ute,cte):(n.havedict=1,lp))},LPe=dte,BPe=hte,MPe=fte,UPe=CPe,FPe=pte,zPe=kPe,VPe=NPe,KPe=DPe,$Pe=OPe,qPe="pako inflate (from Nodeca project)",pl={inflateReset:LPe,inflateReset2:BPe,inflateResetKeep:MPe,inflateInit:UPe,inflateInit2:FPe,inflate:zPe,inflateEnd:VPe,inflateGetHeader:KPe,inflateSetDictionary:$Pe,inflateInfo:qPe};function HPe(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var GPe=HPe,gte=Object.prototype.toString,{Z_NO_FLUSH:jPe,Z_FINISH:WPe,Z_OK:gw,Z_STREAM_END:Vk,Z_NEED_DICT:Kk,Z_STREAM_ERROR:YPe,Z_DATA_ERROR:Lee,Z_MEM_ERROR:QPe}=fp;function _w(r){this.options=DE.assign({chunkSize:1024*64,windowBits:15,to:""},r||{});let e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(r&&r.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nte,this.strm.avail_out=0;let t=pl.inflateInit2(this.strm,e.windowBits);if(t!==gw)throw new Error(cp[t]);if(this.header=new GPe,pl.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=mw.string2buf(e.dictionary):gte.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=pl.inflateSetDictionary(this.strm,e.dictionary),t!==gw)))throw new Error(cp[t])}_w.prototype.push=function(r,e){let t=this.strm,n=this.options.chunkSize,i=this.options.dictionary,o,s,a;if(this.ended)return!1;for(e===~~e?s=e:s=e===!0?WPe:jPe,gte.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),o=pl.inflate(t,s),o===Kk&&i&&(o=pl.inflateSetDictionary(t,i),o===gw?o=pl.inflate(t,s):o===Lee&&(o=Kk));t.avail_in>0&&o===Vk&&t.state.wrap>0&&r[t.next_in]!==0;)pl.inflateReset(t),o=pl.inflate(t,s);switch(o){case YPe:case Lee:case Kk:case QPe:return this.onEnd(o),this.ended=!0,!1}if(a=t.avail_out,t.next_out&&(t.avail_out===0||o===Vk))if(this.options.to==="string"){let c=mw.utf8border(t.output,t.next_out),u=t.next_out-c,l=mw.buf2string(t.output,c);t.next_out=u,t.avail_out=n-u,u&&t.output.set(t.output.subarray(c,c+u),0),this.onData(l)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(!(o===gw&&a===0)){if(o===Vk)return o=pl.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(t.avail_in===0)break}}return!0};_w.prototype.onData=function(r){this.chunks.push(r)};_w.prototype.onEnd=function(r){r===gw&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=DE.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};function iN(r,e){let t=new _w(e);if(t.push(r),t.err)throw t.msg||cp[t.err];return t.result}function XPe(r,e){return e=e||{},e.raw=!0,iN(r,e)}var ZPe=_w,JPe=iN,eke=XPe,tke=iN,rke=fp,nke={Inflate:ZPe,inflate:JPe,inflateRaw:eke,ungzip:tke,constants:rke},{Deflate:ike,deflate:oke,deflateRaw:ske,gzip:ake}=fPe,{Inflate:cke,inflate:uke,inflateRaw:lke,ungzip:fke}=nke,dke=ike,hke=oke,pke=ske,mke=ake,gke=cke,yke=uke,wke=lke,bke=fke,_ke=fp,oN={Deflate:dke,deflate:hke,deflateRaw:pke,gzip:mke,Inflate:gke,inflate:yke,inflateRaw:wke,ungzip:bke,constants:_ke};async function LE(r){let e=new Uint8Array(0);for await(let t of r)e=rt([e,t],e.length+t.length);return e}var yte=6;function wte({repo:r,preload:e}){async function*t(n,i={}){if(i.compressionLevel!=null&&(i.compressionLevel<-1||i.compressionLevel>9))throw(0,Um.default)(new Error("Compression level must be between -1 and 9"),"ERR_INVALID_PARAMS");if(i.preload!==!1){let a;try{a=N1(n).split("/")}catch(c){throw(0,Um.default)(c,"ERR_INVALID_PATH")}e(z.parse(a[0]))}let o=z.asCID(n)||n,s=await Ei(o,r.blocks,i);if(s.type==="file"||s.type==="raw"){let a=[];!i.compress||i.archive===!0?a.push([{header:{name:s.path,mode:s.type==="file"&&s.unixfs.mode,mtime:s.type==="file"&&s.unixfs.mtime?new Date(s.unixfs.mtime.secs*1e3):void 0,size:s.size,type:"file"},body:s.content()}],vE()):a.push(s.content),i.compress&&a.push(async function*(c){let u=await LE(c);yield oN.gzip(u,{level:i.compressionLevel||yte})}),yield*Ne(...a);return}if(s.type==="directory"){let a=[_E(o,r.blocks,i),async function*(c){for await(let u of c){let l={header:{name:u.path,size:u.size}};if(u.type==="file")l.header.type="file",l.header.mode=u.unixfs.mode!=null?u.unixfs.mode:void 0,l.header.mtime=u.unixfs.mtime?new Date(u.unixfs.mtime.secs*1e3):void 0,l.body=u.content();else if(u.type==="raw")l.header.type="file",l.body=u.content();else if(u.type==="directory")l.header.type="directory",l.header.mode=u.unixfs.mode!=null?u.unixfs.mode:void 0,l.header.mtime=u.unixfs.mtime?new Date(u.unixfs.mtime.secs*1e3):void 0;else throw(0,Um.default)(new Error("Not a UnixFS node"),"ERR_NOT_UNIXFS");yield l}},vE()];if(i.compress){if(!i.archive)throw(0,Um.default)(new Error("file is not regular"),"ERR_INVALID_PATH");i.compress&&a.push(async function*(c){let u=await LE(c);yield oN.gzip(u,{level:i.compressionLevel||yte})})}yield*Ne(...a);return}throw(0,Um.default)(new Error("Not a UnixFS node"),"ERR_NOT_UNIXFS")}return $(t)}var bte=C(ee(),1);function _te({repo:r,preload:e}){async function*t(n,i={}){let o=N1(n),s=o.split("/");i.preload!==!1&&e(z.parse(s[0]));let a=z.asCID(o)||o,c=await Ei(a,r.blocks,i);if(c.type==="file"){yield wR(c);return}if(c.type==="directory"){for await(let u of c.content())yield wR(u);return}throw(0,bte.default)(new Error(`Unknown UnixFS type ${c.type}`),"ERR_UNKNOWN_UNIXFS_TYPE")}return $(t)}var BE=class{constructor({preload:e,repo:t,hashers:n,options:i}){let o=oJ({preload:e,repo:t,options:i,hashers:n});this.addAll=o,this.add=hZ({addAll:o}),this.cat=HJ({repo:t,preload:e}),this.get=wte({repo:t,preload:e}),this.ls=_te({repo:t,preload:e})}};var hp="0.18.1",Ete="",vte="^0.158.1";function xte({repo:r}){async function e(t={}){let n=await r.version.get();return{version:hp,commit:Ete,repo:`${n}`,"ipfs-core":hp,"interface-ipfs-core":vte}}return $(e)}var ME=C(ee(),1);var Eke=j("ipfs:components:id");function Ste({peerId:r,network:e}){async function t(n={}){let i=e.try();if(!i){if(n.peerId)throw new $u;if(r.publicKey==null)throw(0,ME.default)(new Error("Public key missing"),"ERR_MISSING_PUBLIC_KEY");return{id:r,publicKey:re(r.publicKey,"base64pad"),addresses:[],agentVersion:`js-ipfs/${hp}`,protocolVersion:"9000",protocols:[]}}let{libp2p:o}=i,s=n.peerId?n.peerId:r,a=await vke(s,o,n),c=re(a.metadata.get("AgentVersion")||new Uint8Array),u=re(a.metadata.get("ProtocolVersion")||new Uint8Array),l=a.id.toString(),f=a.publicKey?re(a.publicKey,"base64pad"):"";return{id:s,publicKey:f,addresses:(a.addresses||[]).map(h=>{let d=h.toString();return d.endsWith(`/p2p/${l}`)?d:`${d}/p2p/${l}`}).sort().map(h=>yt(h)),agentVersion:c,protocolVersion:u,protocols:(a.protocols||[]).sort()}}return $(t)}async function vke(r,e,t){let n=await e.peerStore.get(r);n||(n=await xke(r,e,t));let i=r.publicKey?r.publicKey:await e.peerStore.keyBook.get(r);if(i==null)try{i=await e.getPublicKey(r,t)}catch(o){Eke.error("Could not load public key for",r.toString(),o)}return{...n,publicKey:i,metadata:n.metadata||new Map,addresses:n.addresses.map(o=>o.multiaddr)}}async function xke(r,e,t){if(e.dht==null)throw(0,ME.default)(new Error("dht not configured"),"ERR_DHT_NOT_CONFIGURED");for await(let i of e.dht.findPeer(r,t))if(i.name==="FINAL_PEER")break;let n=await e.peerStore.get(r);if(!n)throw(0,ME.default)(new Error("Could not find peer"),"ERR_NOT_FOUND");return n}var $r=Ske;function Ske(r,e,t){var n,i;if(Array.isArray(e)&&(n=e.slice(0)),typeof e=="string"&&(n=e.split(".")),typeof e=="symbol"&&(n=[e]),!Array.isArray(n))throw new Error("props arg must be an array, a string or a symbol");if(i=n.pop(),!i)return!1;Ate(i);for(var o;o=n.shift();)if(Ate(o),typeof r[o]>"u"&&(r[o]={}),r=r[o],!r||typeof r!="object")return!1;return r[i]=t,!0}function Ate(r){if(r=="__proto__"||r=="constructor"||r=="prototype")throw new Error("setting of prototype values not supported")}var Fm={server:{description:"Recommended for nodes with public IPv4 address (servers, VPSes, etc.), disables host and content discovery and UPnP in local networks.",transform:r=>($r(r,"Discovery.MDNS.Enabled",!1),$r(r,"Discovery.webRTCStar.Enabled",!1),r.Swarm={...r.Swarm||{},DisableNatPortMap:!0},r)},"local-discovery":{description:"Sets default values to fields affected by `server` profile, enables discovery and UPnP in local networks.",transform:r=>($r(r,"Discovery.MDNS.Enabled",!0),$r(r,"Discovery.webRTCStar.Enabled",!0),$r(r,"Swarm",{...r.Swarm||{},DisableNatPortMap:!1}),r)},test:{description:"Reduces external interference, useful for running ipfs in test environments. Note that with these settings node won't be able to talk to the rest of the network without manual bootstrap.",transform:r=>{let e=cl();return $r(r,"Addresses.API",e.Addresses.API?"/ip4/127.0.0.1/tcp/0":""),$r(r,"Addresses.Gateway",e.Addresses.Gateway?"/ip4/127.0.0.1/tcp/0":""),$r(r,"Addresses.Swarm",e.Addresses.Swarm.length?["/ip4/127.0.0.1/tcp/0"]:[]),$r(r,"Addresses.Delegates",[]),$r(r,"Bootstrap",[]),$r(r,"Discovery.MDNS.Enabled",!1),$r(r,"Discovery.webRTCStar.Enabled",!1),$r(r,"Swarm",{...r.Swarm||{},DisableNatPortMap:!0}),r}},"default-networking":{description:"Restores default network settings. Inverse profile of the `test` profile.",transform:r=>{let e=cl();return $r(r,"Addresses.API",e.Addresses.API),$r(r,"Addresses.Gateway",e.Addresses.Gateway),$r(r,"Addresses.Swarm",e.Addresses.Swarm),$r(r,"Addresses.Delegates",e.Addresses.Delegates),$r(r,"Bootstrap",e.Bootstrap),$r(r,"Discovery.MDNS.Enabled",e.Discovery.MDNS.Enabled),$r(r,"Discovery.webRTCStar.Enabled",e.Discovery.webRTCStar.Enabled),$r(r,"Swarm",{...r.Swarm||{},DisableNatPortMap:!1}),r}},lowpower:{description:"Reduces daemon overhead on the system. May affect node functionality,performance of content discovery and data fetching may be degraded. Recommended for low power systems.",transform:r=>{let e=r.Swarm||{},t=e.ConnMgr||{};return t.LowWater=20,t.HighWater=40,e.ConnMgr=t,r.Swarm=e,r}},"default-power":{description:'Inverse of "lowpower" profile.',transform:r=>{let e=cl();return r.Swarm=e.Swarm,r}}};var Ake=j("ipfs:core:config");function Tte({repo:r}){return{getAll:$(e),get:$(t),set:$(n),replace:$(i),profiles:{apply:$(o),list:$(Tke)}};async function e(s={}){return r.config.getAll(s)}async function t(s,a){return s?r.config.get(s,a):Promise.reject(new Error("key argument is required"))}async function n(s,a,c){return r.config.set(s,a,c)}async function i(s,a){return r.config.replace(s,a)}async function o(s,a={dryRun:!1}){let{dryRun:c}=a,u=Fm[s];if(!u)throw new Error(`No profile with name '${s}' exists`);try{let l=await r.config.getAll(a),f=JSON.parse(JSON.stringify(l));return f=u.transform(f),c||await r.config.replace(f,a),delete l.Identity.PrivKey,delete f.Identity.PrivKey,{original:l,updated:f}}catch(l){throw Ake(l),new Error(`Could not apply profile '${s}' to config: ${l.message}`)}}}async function Tke(r){return Object.keys(Fm).map(e=>({name:e,description:Fm[e].description}))}function UE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Ike(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=z.asCID(n);o?yield[i.join("/"),o]:typeof n=="object"&&(yield*sN(n,i))}else{let t=z.asCID(e);t?yield[r.join("/"),t]:yield*sN(e,r)}}function*sN(r,e){if(r==null||r instanceof Uint8Array)return;let t=z.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*Ike(o,i)}}function*Rke(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!z.asCID(n)&&(yield*aN(n,i))}else yield*aN(e,r)}function*aN(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!z.asCID(n)&&(yield*Rke(i,n))}}function Cke(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=z.asCID(t);if(o)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var cN=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:UE(),bytes:UE(),value:UE(),asBlock:UE()})}links(){return sN(this.value,[])}tree(){return aN(this.value,[])}get(e="/"){return Cke(this.value,e.split("/").filter(Boolean))}};function Ite({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n&&n.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new cN({cid:e,bytes:r,value:i})}var fd=C(Xo(),1),FE={SHA2_256:18,LENGTH:32,DAG_PB:112},Rte=16+8+8+8;function Ew(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=fd.default.decode(r);return e.seek(fd.default.decode.bytes),t}function Cte(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}function Pte(r){fd.default.decode(r);let e=fd.default.decode.bytes,t=fd.default.decode(r.subarray(fd.default.decode.bytes)),n=fd.default.decode.bytes;return e+n+t}var dd={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},vw={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":dd.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(dd.List(r)!==void 0){for(let e=0;e roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:dd.Int,CarV1HeaderOrV2Pragma:r=>{if(dd.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i roots (anon)"](r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c0))return t}},xw={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":dd.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(dd.List(r)!==void 0){for(let e=0;e roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:dd.Int,CarV1HeaderOrV2Pragma:r=>{if(dd.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c0))return t}},kte={toTyped:vw.CarV1HeaderOrV2Pragma,toRepresentation:xw.CarV1HeaderOrV2Pragma};async function zE(r,e){let t=Ew(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),i=dT(n);if(kte.toTyped(i)===void 0)throw new Error("Invalid CAR header format");if(i.version!==1&&i.version!==2||e!==void 0&&i.version!==e)throw new Error(`Invalid CAR version: ${i.version}${e!==void 0?` (expected ${e})`:""}`);if(i.version===1){if(!Array.isArray(i.roots))throw new Error("Invalid CAR header format");return i}if(i.roots!==void 0)throw new Error("Invalid CAR header format");let o=Cte(await r.exactly(Rte,!0));r.seek(o.dataOffset-r.pos);let s=await zE(r,1);return Object.assign(s,o)}async function Pke(r){let e=await r.exactly(2,!1);if(e[0]===FE.SHA2_256&&e[1]===FE.LENGTH){let s=await r.exactly(34,!0),a=uf(s);return Xe.create(0,FE.DAG_PB,a)}let t=Ew(await r.upTo(8),r);if(t!==1)throw new Error(`Unexpected CID version (${t})`);let n=Ew(await r.upTo(8),r),i=await r.exactly(Pte(await r.upTo(8)),!0),o=uf(i);return Xe.create(t,n,o)}async function Nte(r){let e=r.pos,t=Ew(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR section (zero length)");t+=r.pos-e;let n=await Pke(r),i=t-Number(r.pos-e);return{cid:n,length:t,blockLength:i}}async function kke(r){let{cid:e,blockLength:t}=await Nte(r);return{bytes:await r.exactly(t,!0),cid:e}}async function Nke(r){let e=r.pos,{cid:t,length:n,blockLength:i}=await Nte(r),o={cid:t,length:n,blockLength:i,offset:e,blockOffset:r.pos};return r.seek(o.blockLength),o}function Dte(r){let e=(async()=>{let t=await zE(r);if(t.version===2){let n=r.pos-t.dataOffset;r=Oke(r,t.dataSize-n)}return t})();return{header:()=>e,async*blocks(){for(await e;(await r.upTo(8)).length>0;)yield await kke(r)},async*blocksIndex(){for(await e;(await r.upTo(8)).length>0;)yield await Nke(r)}}}function VE(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let i=r.subarray(e,e+t);return n&&(e+=t),i},seek(t){e+=t},get pos(){return e}}}function Dke(r){let e=0,t=0,n=0,i=new Uint8Array(0),o=async s=>{t=i.length-n;let a=[i.subarray(n)];for(;tt&&a.push(u.subarray(-t)):a.push(u),t+=u.length}i=new Uint8Array(a.reduce((u,l)=>u+l.length,0));let c=0;for(let u of a)i.set(u,c),c+=u.length;n=0};return{async upTo(s){return i.length-ne&&(i=i.subarray(0,e-t)),i},async exactly(n,i=!1){let o=await r.exactly(n,i);if(o.length+t>e)throw new Error("Unexpected end of data");return i&&(t+=n),o},seek(n){t+=n,r.seek(n)},get pos(){return r.pos}}}var uN=C(Xo(),1),Lte=1;function lN(r){let e=fT({version:Lte,roots:r}),t=uN.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Bte(r){return{async setRoots(e){let t=lN(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(uN.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return Lte}}}function KE(){}function Mte(){let r=[],e=null,t=KE,n=!1,i=null,o=KE,s=()=>(e||(e=new Promise(u=>{t=()=>{e=null,t=KE,u()}})),e),a={write(u){r.push(u);let l=s();return o(),l},async end(){n=!0;let u=s();o(),await u}},c={async next(){let u=r.shift();return u?(r.length===0&&t(),{done:!1,value:u}):n?(t(),{done:!0,value:void 0}):(i||(i=new Promise(l=>{o=()=>(i=null,o=KE,l(c.next()))})),i)}};return{writer:a,iterator:c}}var pp=class{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=Xe.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=Lke(e);let{encoder:t,iterator:n}=Ute(),i=new pp(e,t),o=new $E(n);return{writer:i,out:o}}static createAppender(){let{encoder:e,iterator:t}=Ute();e.setRoots=()=>Promise.resolve();let n=new pp([],e),i=new $E(t);return{writer:n,out:i}}static async updateRootsInBytes(e,t){let n=VE(e);await zE(n);let i=lN(t);if(Number(n.pos)!==i.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${i.length} bytes)`);return e.set(i,0),e}},$E=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function Ute(){let r=Mte(),{writer:e,iterator:t}=r;return{encoder:Bte(e),iterator:t}}function Lke(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=Xe.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=Xe.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var fN=async({cid:r,load:e,seen:t})=>{t=t||new Set;let n=r.toString(pr);if(t.has(n))return;let i=await e(r);if(t.add(n),i!==null)for(let[,o]of i.links())await fN({cid:o,load:e,seen:t})};var Fte=j("ipfs:components:dag:import"),Bke=[gf,zg];function zte({repo:r,preload:e,codecs:t}){async function*n(i,o={}){o.preload!==!1&&e(i);let s=z.asCID(i);if(!s)throw new Error(`Unexpected error converting CID type: ${i}`);Fte(`Exporting ${s} as car`);let{writer:a,out:c}=await pp.create([s]),u=null;(async()=>{try{let l=Mke(r,a,{signal:o.signal,timeout:o.timeout},t);await fN({cid:s,load:l})}catch(l){u=l}finally{a.close()}})();for await(let l of c){if(u)break;yield l}if(u)throw u}return $(n)}function Mke(r,e,t,n){return async i=>{let o=await n.getCodec(i.code);if(!o)throw new Error(`Can't decode links in block with codec 0x${i.code.toString(16)} to form complete DAG`);let s=await r.blocks.get(i,t);return Fte(`Adding block ${i} to car`),await e.put({cid:i,bytes:s}),Bke.includes(i.code)?null:Ite({bytes:s,cid:i,codec:o})}}async function mp(r){for await(let e of r)return e}var Vte=C(ee(),1);function Kte({codecs:r,repo:e,preload:t}){return $(async function(o,s={}){if(s.preload!==!1&&t(o),s.path){let f=s.localResolve?await mp(kf(o,s.path,r,e,s)):await Dr(kf(o,s.path,r,e,s));if(!f)throw(0,Vte.default)(new Error("Not found"),"ERR_NOT_FOUND");return f}let a=await r.getCodec(o.code),c=await e.blocks.get(o,s);return{value:a.decode(c),remainderPath:""}})}var qE=class{constructor(e,t,n){this._version=e,this._roots=t,this._iterable=n,this._decoded=!1}get version(){return this._version}async getRoots(){return this._roots}},gp=class extends qE{[Symbol.asyncIterator](){if(this._decoded)throw new Error("Cannot decode more than once");if(!this._iterable)throw new Error("Block iterable not found");return this._decoded=!0,this._iterable[Symbol.asyncIterator]()}static async fromBytes(e){let{version:t,roots:n,iterator:i}=await $te(e);return new gp(t,n,i)}static async fromIterable(e){let{version:t,roots:n,iterator:i}=await qte(e);return new gp(t,n,i)}},Sw=class extends qE{[Symbol.asyncIterator](){if(this._decoded)throw new Error("Cannot decode more than once");if(!this._iterable)throw new Error("Block iterable not found");this._decoded=!0;let e=this._iterable[Symbol.asyncIterator]();return{async next(){let t=await e.next();return t.done?t:{done:!1,value:t.value.cid}}}}static async fromBytes(e){let{version:t,roots:n,iterator:i}=await $te(e);return new Sw(t,n,i)}static async fromIterable(e){let{version:t,roots:n,iterator:i}=await qte(e);return new Sw(t,n,i)}};async function $te(r){if(!(r instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return Hte(VE(r))}async function qte(r){if(!r||typeof r[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return Hte(Ote(r))}async function Hte(r){let e=Dte(r),{version:t,roots:n}=await e.header();return{version:t,roots:n,iterator:e.blocks()}}var Gte=j("ipfs:components:dag:import");function jte({repo:r}){async function*e(t,n={}){let i=await r.gcLock.readLock();try{let o={signal:n.signal,timeout:n.timeout},s=ja(t),{value:a,done:c}=await s.peek();if(c)return;a&&s.push(a);let u;a instanceof Uint8Array?u=[s]:u=s;for await(let l of u){let f=await Uke(r,o,l);if(n.pinRoots!==!1)for(let h of f){let d="";try{await r.blocks.has(h)?(Gte(`Pinning root ${h}`),await r.pins.pinRecursively(h)):d="blockstore: block not found"}catch(p){d=p.message}yield{root:{cid:h,pinErrorMsg:d}}}}}finally{i()}}return $(e)}async function Uke(r,e,t){let n=await gp.fromIterable(t),i=await n.getRoots();return await sl(r.blocks.putMany(Mi(n,({cid:o,bytes:s})=>(Gte(`Import block ${o}`),{key:o,value:s})),{signal:e.signal})),i}function Wte({repo:r,codecs:e,hashers:t,preload:n}){async function i(o,s={}){let a=s.pin?await r.gcLock.readLock():null;try{let c=await e.getCodec(s.storeCodec||"dag-cbor");if(!c)throw new Error(`Unknown storeCodec ${s.storeCodec}, please configure additional BlockCodecs for this IPFS instance`);if(s.inputCodec){if(!(o instanceof Uint8Array))throw new Error("Can only inputCodec on raw bytes that can be decoded");let p=await e.getCodec(s.inputCodec);if(!p)throw new Error(`Unknown inputCodec ${s.inputCodec}, please configure additional BlockCodecs for this IPFS instance`);o=p.decode(o)}let u=s.version!=null?s.version:1,l=await t.getHasher(s.hashAlg||"sha2-256");if(!l)throw new Error(`Unknown hash algorithm ${s.hashAlg}, please configure additional MultihashHashers for this IPFS instance`);let f=c.encode(o),h=await l.digest(f),d=z.create(u,c.code,h);return await r.blocks.put(d,f,{signal:s.signal}),s.pin&&await r.pins.pinRecursively(d),s.preload!==!1&&n(d),d}finally{a&&a()}}return $(i)}function Yte({repo:r,codecs:e,preload:t}){async function n(i,o={}){let{cid:s}=Qu(i);return o.preload!==!1&&t(s),Pf(r,e,i,o)}return $(n)}var HE=class{constructor({repo:e,codecs:t,hashers:n,preload:i}){this.export=zte({repo:e,preload:i,codecs:t}),this.get=Kte({codecs:t,repo:e,preload:i}),this.import=jte({repo:e}),this.resolve=Yte({repo:e,codecs:t,preload:i}),this.put=Wte({repo:e,codecs:t,hashers:n,preload:i})}};function Qte(r){let e;try{e=Lt("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Xte(r){return r.some(([e,t])=>e===Lt("tls").code)}function is(r,e,t){let n=Zte[Lt(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${Lt(r).name}`);let i=n(e,t);return r===Lt("ip6").code?`[${i}]`:i}var Zte={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${is(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${is(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Xte(e),n=Qte(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",o=e.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=is(o[0],o[1]??"",e);return s=s.replace("tcp://",""),`${i}${s}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return is(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return is(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=is(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Xte(e),n=Qte(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",o=e.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=is(o[0],o[1]??"",e);return s=s.replace("tcp://",""),`${i}${s}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=is(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${is(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function zm(r,e){let n=Xi(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Lt(i[0]),s=Zte[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let a=s(i[1]??"",n);return(e==null?void 0:e.assumeHttp)!==!1&&i[0]===Lt("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}function dN(r){if(!Array.isArray(r))throw new TypeError(`Expected an array, got ${typeof r}`);r=[...r];for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}var Jte=C(O1(),1);var Fke=j("ipfs:preload"),zke=qn.default?qn.default:qn,Vke=new zke({concurrency:4});function ere(r,e={}){return Fke(r),Vke.add(async()=>{let n=(await Jte.default.post(r,{signal:e.signal})).body.getReader();try{for(;;){let{done:i}=await n.read();if(i)return}}finally{n.releaseLock()}})}var tre=C(Cy(),1),Aw=j("ipfs:preload");function rre(r={}){if(r.enabled=!!r.enabled,r.addresses=r.addresses||[],r.cache=r.cache||1e3,!r.enabled||!r.addresses.length)return Aw("preload disabled"),Object.assign(()=>{},{start:()=>{},stop:()=>{}});let e=!0,t=[],n=r.addresses.map(s=>zm(s)),i=(0,tre.default)(r.cache),o=async s=>{try{if(e)throw new Error(`preload ${s} but preloader is not started`);let a=s.toString();if(i.has(a))return;i.set(a,!0);let c=dN(n),u=!1,l=Date.now();for(let f of c){if(e)throw new Error(`preload aborted for ${a}`);let h;try{h=new AbortController,t=t.concat(h),await ere(`${f}/api/v0/refs?r=true&arg=${encodeURIComponent(a)}`,{signal:h.signal}),u=!0}catch(d){d.type!=="aborted"&&Aw.error(d)}finally{t=t.filter(d=>d!==h)}if(u)break}Aw(`${u?"":"un"}successfully preloaded ${a} in ${Date.now()-l}ms`)}catch(a){Aw.error(a)}};return o.start=()=>{e=!1},o.stop=()=>{e=!0,Aw(`aborting ${t.length} pending preload request(s)`),t.forEach(s=>s.abort()),t=[]},o}var GE=j("ipfs:mfs-preload");function nre({preload:r,files:e,options:t={}}){if(t.interval=t.interval||30*1e3,!t.enabled){GE("MFS preload disabled");let s=async()=>{};return{start:s,stop:s}}let n="",i,o=async()=>{try{let s=await e.stat("/"),a=s.cid.toString();n!==a&&(GE(`preloading updated MFS root ${n} -> ${s.cid}`),await r(s.cid),n=a)}catch(s){GE.error("failed to preload MFS root",s)}finally{i=setTimeout(o,t.interval)}};return{async start(){let s=await e.stat("/");n=s.cid.toString(),GE(`monitoring MFS root ${s.cid}`),i=setTimeout(o,t.interval)},stop(){clearTimeout(i)}}}var Tw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},hN=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ire=r=>globalThis.DOMException===void 0?new hN(r):new DOMException(r),ore=r=>{let e=r.reason===void 0?ire("This operation was aborted."):r.reason;return e instanceof Error?e:ire(e)};function yp(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(ore(h)),h.addEventListener("abort",()=>{l(ore(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new Tw;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}function pN(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Wc,Iw=class{constructor(){bt(this,Wc,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&ge(this,Wc)[this.size-1].priority>=t.priority){ge(this,Wc).push(n);return}let i=pN(ge(this,Wc),n,(o,s)=>s.priority-o.priority);ge(this,Wc).splice(i,0,n)}dequeue(){let e=ge(this,Wc).shift();return e==null?void 0:e.run}filter(e){return ge(this,Wc).filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return ge(this,Wc).length}};Wc=new WeakMap;var Vm,Km,hd,Rw,$m,Cw,Ws,qm,bo,Pw,Ys,Hm,ml,kw,QE,sre,XE,are,ZE,cre,JE,ure,e7,lre,Gm,jE,Nw,mN,Dw,gN,jm,WE,t7,fre,Wm,YE,Ym=class extends ky.default{constructor(t){var n,i;super();bt(this,QE);bt(this,XE);bt(this,ZE);bt(this,JE);bt(this,e7);bt(this,Gm);bt(this,Nw);bt(this,Dw);bt(this,jm);bt(this,t7);bt(this,Wm);bt(this,Vm,void 0);bt(this,Km,void 0);bt(this,hd,0);bt(this,Rw,void 0);bt(this,$m,void 0);bt(this,Cw,0);bt(this,Ws,void 0);bt(this,qm,void 0);bt(this,bo,void 0);bt(this,Pw,void 0);bt(this,Ys,0);bt(this,Hm,void 0);bt(this,ml,void 0);bt(this,kw,void 0);B(this,"timeout");if(t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Iw,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${((n=t.intervalCap)==null?void 0:n.toString())??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${((i=t.interval)==null?void 0:i.toString())??""}\` (${typeof t.interval})`);Dt(this,Vm,t.carryoverConcurrencyCount),Dt(this,Km,t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0),Dt(this,Rw,t.intervalCap),Dt(this,$m,t.interval),Dt(this,bo,new t.queueClass),Dt(this,Pw,t.queueClass),this.concurrency=t.concurrency,this.timeout=t.timeout,Dt(this,kw,t.throwOnTimeout===!0),Dt(this,ml,t.autoStart===!1)}get concurrency(){return ge(this,Hm)}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);Dt(this,Hm,t),hi(this,jm,WE).call(this)}async add(t,n={}){return n={timeout:this.timeout,throwOnTimeout:ge(this,kw),...n},new Promise((i,o)=>{ge(this,bo).enqueue(async()=>{var s;uh(this,Ys)._++,uh(this,hd)._++;try{(s=n.signal)==null||s.throwIfAborted();let a=t({signal:n.signal});n.timeout&&(a=yp(Promise.resolve(a),{milliseconds:n.timeout})),n.signal&&(a=Promise.race([a,hi(this,t7,fre).call(this,n.signal)]));let c=await a;i(c),this.emit("completed",c)}catch(a){if(a instanceof Tw&&!n.throwOnTimeout){i();return}o(a),this.emit("error",a)}finally{hi(this,ZE,cre).call(this)}},n),this.emit("add"),hi(this,Gm,jE).call(this)})}async addAll(t,n){return Promise.all(t.map(async i=>this.add(i,n)))}start(){return ge(this,ml)?(Dt(this,ml,!1),hi(this,jm,WE).call(this),this):this}pause(){Dt(this,ml,!0)}clear(){Dt(this,bo,new(ge(this,Pw)))}async onEmpty(){ge(this,bo).size!==0&&await hi(this,Wm,YE).call(this,"empty")}async onSizeLessThan(t){ge(this,bo).sizege(this,bo).size{hi(this,JE,ure).call(this)},n)),!0}return!1},Gm=new WeakSet,jE=function(){if(ge(this,bo).size===0)return ge(this,Ws)&&clearInterval(ge(this,Ws)),Dt(this,Ws,void 0),this.emit("empty"),ge(this,Ys)===0&&this.emit("idle"),!1;if(!ge(this,ml)){let t=!ge(this,e7,lre);if(ge(this,QE,sre)&&ge(this,XE,are)){let n=ge(this,bo).dequeue();return n?(this.emit("active"),n(),t&&hi(this,Nw,mN).call(this),!0):!1}}return!1},Nw=new WeakSet,mN=function(){ge(this,Km)||ge(this,Ws)!==void 0||(Dt(this,Ws,setInterval(()=>{hi(this,Dw,gN).call(this)},ge(this,$m))),Dt(this,Cw,Date.now()+ge(this,$m)))},Dw=new WeakSet,gN=function(){ge(this,hd)===0&&ge(this,Ys)===0&&ge(this,Ws)&&(clearInterval(ge(this,Ws)),Dt(this,Ws,void 0)),Dt(this,hd,ge(this,Vm)?ge(this,Ys):0),hi(this,jm,WE).call(this)},jm=new WeakSet,WE=function(){for(;hi(this,Gm,jE).call(this););},t7=new WeakSet,fre=async function(t){return new Promise((n,i)=>{t.addEventListener("abort",()=>{i(t.reason)},{once:!0})})},Wm=new WeakSet,YE=async function(t,n){return new Promise(i=>{let o=()=>{n&&!n()||(this.off(t,o),i())};this.on(t,o)})};var pd={},Qm=r=>{r.addEventListener("message",e=>{Qm.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Qm.dispatchEvent("message",r,e)})};Qm.addEventListener=(r,e)=>{pd[r]==null&&(pd[r]=[]),pd[r].push(e)};Qm.removeEventListener=(r,e)=>{pd[r]!=null&&(pd[r]=pd[r].filter(t=>t===e))};Qm.dispatchEvent=function(r,e,t){pd[r]!=null&&pd[r].forEach(n=>n(e,t))};var Xm=Qm;var yN="lock:worker:request-read",wN="lock:worker:release-read",bN="lock:master:grant-read",_N="lock:worker:request-write",EN="lock:worker:release-write",vN="lock:master:grant-write";var dre=(r=21)=>Math.random().toString().substring(2);var hre=(r,e,t,n,i)=>(o,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)})}}}))},pre=(r,e,t,n)=>async()=>{let i=dre();return globalThis.postMessage({type:e,identifier:i,name:r}),new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",s)})},Kke={singleProcess:!1},mre=r=>{if(r=Object.assign({},Kke,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Xm.addEventListener("message",hre(t,"requestReadLock",yN,wN,bN)),Xm.addEventListener("message",hre(t,"requestWriteLock",_N,EN,vN)),t}return{isWorker:!0,readLock:t=>pre(t,yN,bN,wN),writeLock:t=>pre(t,_N,vN,EN)}};var wp={},gd;async function xN(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>yp((async()=>{await new Promise(i=>{t(()=>{i()})})})(),{milliseconds:e.timeout})),n}var $ke=(r,e)=>{if(gd.isWorker===!0)return{readLock:gd.readLock(r,e),writeLock:gd.writeLock(r,e)};let t=new Ym({concurrency:1}),n;return{async readLock(){if(n!=null)return xN(n,e);n=new Ym({concurrency:e.concurrency,autoStart:!1});let i=n,o=xN(n,e);return t.add(async()=>{i.start(),await i.onIdle().then(()=>{n===i&&(n=null)})}),o},async writeLock(){return n=null,xN(t,e)}}},qke={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function SN(r){let e=Object.assign({},qke,r);return gd==null&&(gd=mre(e),gd.isWorker!==!0&&(gd.addEventListener("requestReadLock",t=>{wp[t.data.name]!=null&&wp[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),gd.addEventListener("requestWriteLock",async t=>{wp[t.data.name]!=null&&wp[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),wp[e.name]==null&&(wp[e.name]=$ke(e.name,e)),wp[e.name]}var r7;function Ow(r=!1){if(r7)return r7;let e=SN({singleProcess:r});return r7={readLock:t=>async(...n)=>{let i=await e.readLock();try{return await t.apply(null,n)}finally{i()}},writeLock:t=>async(...n)=>{let i=await e.writeLock();try{return await t.apply(null,n)}finally{i()}}},r7}var AN=C(ee(),1);var gre=j("ipfs:mfs:utils:with-mfs-root");async function Zm(r,e){if(e&&e.signal&&e.signal.aborted)throw(0,AN.default)(new Error("Request aborted"),"ERR_ABORTED",{name:"Aborted"});await r.repo.datastore.open();let t;try{let n=await r.repo.datastore.get(Ry);t=z.decode(n)}catch(n){if(n.code!=="ERR_NOT_FOUND")throw n;gre("Creating new MFS root");let i=pt({Data:new st({type:"directory"}).marshal(),Links:[]}),o=await dt.digest(i);if(t=z.createV0(o),await r.repo.blocks.put(t,i),e&&e.signal&&e.signal.aborted)throw(0,AN.default)(new Error("Request aborted"),"ERR_ABORTED",{name:"Aborted"});await r.repo.datastore.put(Ry,t.bytes)}return gre(`Loaded MFS root /ipfs/${t}`),t}function Jm(r=""){return(r.trim().match(/([^\\^/]|\\\/)+/g)||[]).filter(Boolean)}var IN=C(ee(),1);var TN="ipfs",sn=async(r,e,t)=>{let n=await Zm(r,t),i={entryType:"file"},o="";if(z.asCID(e)?o=`/ipfs/${e}`:o=e.toString(),o=o.trim(),o=o.replace(/(\/\/+)/g,"/"),o.endsWith("/")&&o.length>1&&(o=o.substring(0,o.length-1)),!o)throw(0,IN.default)(new Error("paths must not be empty"),"ERR_NO_PATH");if(o.substring(0,1)!=="/")throw(0,IN.default)(new Error("paths must start with a leading slash"),"ERR_INVALID_PATH");o.substring(o.length-1)==="/"&&(o=o.substring(0,o.length-1));let s=Jm(o);if(s[0]===TN){let c;s.length===2?c=`/${s.join("/")}`:c=`/${s.slice(0,s.length-1).join("/")}`,i={type:"ipfs",depth:s.length-2,entryType:"file",mfsPath:`/${s.join("/")}`,mfsDirectory:c,parts:s,path:`/${s.join("/")}`,name:s[s.length-1]}}else{let c=`/${TN}/${n}${s.length?"/"+s.join("/"):""}`,u=`/${TN}/${n}/${s.slice(0,s.length-1).join("/")}`;i={type:"mfs",depth:s.length,entryType:"file",mfsDirectory:u,mfsPath:c,parts:s,path:`/${s.join("/")}`,name:s[s.length-1]}}let a=i.type==="mfs"?i.mfsPath:i.path;try{let c=await Ei(a,r.repo.blocks,t);i.cid=c.cid,i.mfsPath=`/ipfs/${c.path}`,i.entryType=c.type,i.content=c.content,(i.entryType==="file"||i.entryType==="directory")&&(c.type==="file"||c.type==="directory")&&(i.unixfs=c.unixfs)}catch(c){if(c.code!=="ERR_NOT_FOUND")throw c}return i.exists=!!i.cid,i};var wre=C(ee(),1);var Hke=et.bind({ignoreUndefined:!0}),Gke=j("ipfs:mfs:stat"),jke={withLocal:!1};function yd(r){async function e(t,n={}){n=Hke(jke,n),Gke(`Fetching stats for ${t}`);let{type:i,cid:o,mfsPath:s}=await sn(r,t,n),a=i==="ipfs"&&o?o:s,c;try{c=await Ei(a,r.repo.blocks)}catch(u){throw u.code==="ERR_NOT_FOUND"?(0,wre.default)(new Error(`${t} does not exist`),"ERR_NOT_FOUND"):u}if(!yre[c.type])throw new Error(`Cannot stat codec ${c.cid.code}`);return yre[c.type](c)}return $(e)}var yre={raw:r=>({cid:r.cid,size:r.node.length,cumulativeSize:r.node.length,blocks:0,type:"file",local:void 0,sizeLocal:void 0,withLocality:!1}),file:r=>{let e={cid:r.cid,type:"file",size:r.unixfs.fileSize(),cumulativeSize:pt(r.node).length+(r.node.Links||[]).reduce((t,n)=>t+(n.Tsize||0),0),blocks:r.unixfs.blockSizes.length,local:void 0,sizeLocal:void 0,withLocality:!1,mode:r.unixfs.mode};return r.unixfs.mtime&&(e.mtime=r.unixfs.mtime),e},directory:r=>{let e={cid:r.cid,type:"directory",size:0,cumulativeSize:pt(r.node).length+(r.node.Links||[]).reduce((t,n)=>t+(n.Tsize||0),0),blocks:r.node.Links.length,local:void 0,sizeLocal:void 0,withLocality:!1,mode:r.unixfs.mode};return r.unixfs.mtime&&(e.mtime=r.unixfs.mtime),e},object:r=>({cid:r.cid,size:r.node.length,cumulativeSize:r.node.length,type:"file",blocks:0,local:void 0,sizeLocal:void 0,withLocality:!1}),identity:r=>({cid:r.cid,size:r.node.length,cumulativeSize:r.node.length,blocks:0,type:"file",local:void 0,sizeLocal:void 0,withLocality:!1})};var i2=C(ee(),1);var Wke=j("ipfs:mfs:utils:to-trail");async function Yc(r,e){Wke(`Creating trail for path ${e}`);let t=[];for await(let n of Ak(e,r.repo.blocks))t.push({name:n.name,cid:n.cid,size:n.size,type:n.type});return t}var n7=async(r,e,t)=>{t.codec||(t.codec=sr),t.hasher||(t.hasher=dt),t.cidVersion===void 0&&(t.cidVersion=1),t.codec===sr&&t.hasher!==dt&&(t.cidVersion=1);let n=await t.hasher.digest(r),i=z.create(t.cidVersion,t.codec.code,n);return t.onlyHash||await e.put(i,r,{signal:t.signal}),i};var i7=V3.code,o7=8;async function s7(r){return(await V3.encode(r)).subarray(0,8).reverse()}var RN=class{constructor(e,t){this.options=t||{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime,this.cid=void 0,this.size=void 0}async put(e,t){}get(e){return Promise.resolve(this)}async*eachChildSeries(){}async*flush(e){}},e2=class extends RN{constructor(e,t){super(e,t),this._bucket=Tm({hashFn:s7,bits:o7})}async put(e,t){await this._bucket.put(e,t)}get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}async*flush(e){yield*bre(this._bucket,e,this,this.options)}};async function*bre(r,e,t,n){let i=r._children,o=[],s=0;for(let d=0;d{if(!n.parent.Data)throw new Error("Could not update HAMT directory because parent had no data");let i=Uint8Array.from(t._children.bitField().reverse()),o=st.unmarshal(n.parent.Data),s=new st({type:"hamt-sharded-directory",data:i,fanout:t.tableSize(),hashType:i7,mode:o.mode,mtime:o.mtime}),a=await r.hashers.getHasher(n.hashAlg),c={Data:s.marshal(),Links:e.sort((h,d)=>(h.Name||"").localeCompare(d.Name||""))},u=pt(c),l=await a.digest(u),f=z.create(n.cidVersion,kr,l);return n.flush&&await r.repo.blocks.put(f,u),{node:c,cid:f,size:e.reduce((h,d)=>h+(d.Tsize||0),u.length)}},CN=async(r,e,t,n,i)=>{let o=new bn({hash:t._options.hash,bits:t._options.bits},n,i);return n._putObjectAt(i,o),await Bw(r,e,o,t),o},PN=async r=>{let e=Tm({hashFn:s7,bits:o7});return await Promise.all(r.map(async t=>{let n=t.Name||"";if(n.length===2){let i=parseInt(n,16),o=new bn({hash:e._options.hash,bits:e._options.bits},e,i);return e._putObjectAt(i,o),Promise.resolve()}return e.put(n.substring(2),{size:t.Tsize,cid:t.Hash})})),e},Bw=async(r,e,t,n)=>{await Promise.all(e.map(async i=>{let o=i.Name||"";if(o.length===2){Lw("Populating sub bucket",o);let s=parseInt(o,16),a=await r.repo.blocks.get(i.Hash),c=en(a),u=new bn({hash:n._options.hash,bits:n._options.bits},t,s);return t._putObjectAt(s,u),await Bw(r,c.Links,u,n),Promise.resolve()}return n.put(o.substring(2),{size:i.Tsize,cid:i.Hash})}))},bp=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),_re=async(r,e,t)=>{let n=await PN(t.Links),i=await n._findNewBucketAndPos(e),o=[{bucket:i.bucket,prefix:bp(i.pos)}],s=i.bucket;for(;s!==n;)o.push({bucket:s,prefix:bp(s._posAtParent)}),s=s._parent;o.reverse(),o[0].node=t;for(let a=0;a(d.Name||"").substring(0,2)===c.prefix).pop();if(!u){Lw(`Link ${c.prefix}${e} will be added`);continue}if(u.Name===`${c.prefix}${e}`){Lw(`Link ${c.prefix}${e} will be replaced`);continue}Lw(`Found subshard ${c.prefix}`);let l=await r.repo.blocks.get(u.Hash),f=en(l);if(!o[a+1]){Lw(`Loaded new subshard ${c.prefix}`),await CN(r,f.Links,n,c.bucket,parseInt(c.prefix,16));let d=await n._findNewBucketAndPos(e);o.push({bucket:d.bucket,prefix:bp(d.pos),node:f});continue}let h=o[a+1];await Bw(r,f.Links,h.bucket,n),h.node=f}return await n.put(e,!0),o.reverse(),{rootBucket:n,path:o}},Ere=async(r,e,t={})=>{let n=new e2({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let o=0;o=e.shardSplitThreshold?(Xc("Converting directory to sharded directory"),Yke(r,{...e,parent:t,mtime:n.mtime,mode:n.mode})):(Xc(`Adding ${e.name} (${e.cid}) to regular directory`),Qke(r,{...e,parent:t}))}var Yke=async(r,e)=>{let t=await Ere(r,e.parent.Links.map(n=>({name:n.Name||"",size:n.Tsize||0,cid:n.Hash})).concat({name:e.name,size:e.size,cid:e.cid}),e);return Xc(`Converted directory to sharded directory ${t.cid}`),t},Qke=async(r,e)=>{let t=e.parent.Links.filter(u=>u.Name!==e.name);if(t.push({Name:e.name,Tsize:e.size,Hash:e.cid}),!e.parent.Data)throw(0,Qc.default)(new Error("Parent node with no data passed to addToDirectory"),"ERR_INVALID_PARENT");let n=st.unmarshal(e.parent.Data),i;if(n.mtime){let u=Date.now(),l=Math.floor(u/1e3);n.mtime={secs:l,nsecs:(u-l*1e3)*1e3},i=n.marshal()}else i=e.parent.Data;e.parent=Xn({Data:i,Links:t});let o=await r.hashers.getHasher(e.hashAlg),s=pt(e.parent),a=await o.digest(s),c=z.create(e.cidVersion,kr,a);return e.flush&&await r.repo.blocks.put(c,s),{node:e.parent,cid:c,size:s.length}},Xke=async(r,e)=>{let{shard:t,path:n}=await Zke(r,e),i=await Dr(t.flush(r.repo.blocks));if(!i)throw new Error("No result from flushing shard");let o=await r.repo.blocks.get(i.cid),s=en(o),a=e.parent.Links.filter(u=>(u.Name||"").substring(0,2)!==n[0].prefix),c=s.Links.find(u=>(u.Name||"").substring(0,2)===n[0].prefix);if(!c)throw new Error(`No link found with prefix ${n[0].prefix}`);return a.push(c),t2(r,a,n[0].bucket,e)},Zke=async(r,e)=>{let t={name:e.name,cid:e.cid,size:e.size};if(!e.parent.Data)throw(0,Qc.default)(new Error("Parent node with no data passed to addFileToShardedDirectory"),"ERR_INVALID_PARENT");let n=await PN(e.parent.Links),i=st.unmarshal(e.parent.Data),o=new e2({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mode:i.mode},e);o._bucket=n,i.mtime&&(o.mtime={secs:Math.round(Date.now()/1e3)});let s=await n._findNewBucketAndPos(t.name),a=Jke(s);a[0].node=e.parent;let c=0;for(;c(g.Name||"").substring(0,2)===u.prefix);if(!f){Xc(`Link ${u.prefix}${t.name} will be added`),c=a.length;break}if(f.Name===`${u.prefix}${t.name}`){Xc(`Link ${u.prefix}${t.name} will be replaced`),c=a.length;break}if((f.Name||"").length>2){Xc(`Link ${f.Name} ${f.Hash} will be replaced with a subshard`),c=a.length;break}Xc(`Found subshard ${u.prefix}`);let h=await r.repo.blocks.get(f.Hash),d=en(h);if(!a[c]){Xc(`Loaded new subshard ${u.prefix}`),await CN(r,d.Links,n,u.bucket,parseInt(u.prefix,16));let g=await n._findNewBucketAndPos(t.name);a.push({bucket:g.bucket,prefix:bp(g.pos),node:d});break}let p=a[c];await Bw(r,d.Links,p.bucket,n),p.node=d}return await o._bucket.put(t.name,{size:t.size,cid:t.cid}),{shard:o,path:a}},Jke=r=>{let e=[{bucket:r.bucket,prefix:bp(r.pos)}],t=r.bucket._parent,n=r.bucket._posAtParent;for(;t;)e.push({bucket:t,prefix:bp(n)}),n=t._posAtParent,t=t._parent;return e.reverse(),e};var vre=j("ipfs:mfs:utils:update-tree"),eNe={shardSplitThreshold:1e3};async function os(r,e,t){t=Object.assign({},eNe,t),vre("Trail",e),e=e.slice().reverse();let n=0,i;for await(let s of r.repo.blocks.getMany(e.map(a=>a.cid))){let a=en(s),c=e[n].cid,u=e[n].name;if(n++,!i){i={cid:c,name:u,size:s.length};continue}let l=await Qs(r,{parent:a,name:i.name,cid:i.cid,size:i.size,flush:t.flush,shardSplitThreshold:t.shardSplitThreshold,hashAlg:t.hashAlg,cidVersion:t.cidVersion});i={cid:l.cid,name:u,size:l.size}}let{cid:o}=i;return vre(`Final CID ${o}`),o}var xre=C(ee(),1),tNe=j("ipfs:mfs:utils:update-mfs-root");async function ss(r,e,t){if(t&&t.signal&&t.signal.aborted)throw(0,xre.default)(new Error("Request aborted"),"ERR_ABORTED",{name:"Aborted"});return tNe(`New MFS root will be ${e}`),await r.repo.datastore.put(Ry,e.bytes),e}var _p=C(ee(),1);async function Sre(r,e,t){let n=new st({type:e,mode:t.mode,mtime:t.mtime}),i=await r.hashers.getHasher(t.hashAlg),o={Data:n.marshal(),Links:[]},s=pt(o),a=await i.digest(s),c=z.create(t.cidVersion,kr,a);return t.flush&&await r.repo.blocks.put(c,s),{cid:c,node:o}}var rNe=et.bind({ignoreUndefined:!0}),Are=j("ipfs:mfs:mkdir"),nNe={parents:!1,hashAlg:"sha2-256",cidVersion:0,shardSplitThreshold:1e3,flush:!0};function Ep(r){async function e(t,n={}){let i=rNe(nNe,n);if(!t)throw new Error("no path given to Mkdir");if(t=t.trim(),t==="/"){if(i.parents)return;throw(0,_p.default)(new Error("cannot create directory '/': Already exists"),"ERR_INVALID_PATH")}if(t.substring(0,1)!=="/")throw(0,_p.default)(new Error("paths must start with a leading slash"),"ERR_INVALID_PATH");Are(`Creating ${t}`);let o=Jm(t);if(o[0]==="ipfs")throw(0,_p.default)(new Error("path cannot have the prefix 'ipfs'"),"ERR_INVALID_PATH");let s=await Zm(r,i),a,c=[],u=await Sre(r,"directory",i);for(let f=0;f<=o.length;f++){let h=o.slice(0,f),d=`/ipfs/${s}/${h.join("/")}`;try{if(a=await Ei(d,r.repo.blocks),a.type!=="file"&&a.type!=="directory")throw(0,_p.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");if(f===o.length){if(i.parents)return;throw(0,_p.default)(new Error("file already exists"),"ERR_ALREADY_EXISTS")}c.push({name:a.name,cid:a.cid})}catch(p){if(p.code==="ERR_NOT_FOUND"){if(f{Are(`Adding empty dir called ${e} to ${n.cid}`);let s=await Qs(r,{parent:n.node,parentCid:n.cid,size:0,cid:t.cid,name:e,hashAlg:o.hashAlg,cidVersion:o.cidVersion,flush:o.flush,shardSplitThreshold:o.shardSplitThreshold});i[i.length-1].cid=s.cid,i.push({name:e,cid:t.cid})};var wd=C(ee(),1);var oNe=et.bind({ignoreUndefined:!0}),a7=j("ipfs:mfs:cp"),sNe={parents:!1,flush:!0,hashAlg:"sha2-256",cidVersion:0,shardSplitThreshold:1e3};function r2(r){async function e(t,n,i={}){let o=oNe(sNe,i);Array.isArray(t)||(t=[t]);let s=await Promise.all(t.map(h=>sn(r,h,o))),a=await sn(r,n,o);if(!s.length||!a)throw(0,wd.default)(new Error("Please supply at least one source"),"ERR_INVALID_PARAMS");let c=s.find(h=>!h.exists);if(c)throw(0,wd.default)(new Error(`${c.path} does not exist`),"ERR_INVALID_PARAMS");let u=Tre(a);if(a.exists){if(a7("Destination exists"),s.length===1&&!u)throw(0,wd.default)(new Error("directory already has entry by that name"),"ERR_ALREADY_EXISTS")}else if(a7("Destination does not exist"),s.length>1){if(!o.parents)throw(0,wd.default)(new Error("destination did not exist, pass -p to create intermediate directories"),"ERR_INVALID_PARAMS");await Ep(r)(a.path,o),a=await sn(r,a.path,o)}else if(a.parts.length>1){let h=`/${a.parts.slice(0,-1).join("/")}`;try{await yd(r)(h,o)}catch(d){if(d.code!=="ERR_NOT_FOUND")throw d;if(!o.parents)throw(0,wd.default)(new Error("destination did not exist, pass -p to create intermediate directories"),"ERR_INVALID_PARAMS");await Ep(r)(h,o),a=await sn(r,a.path,o)}}let l=Tre(a)?a.mfsPath:a.mfsDirectory,f=await Yc(r,l);if(s.length===1){let h=s.pop();if(!h)throw(0,wd.default)(new Error("could not find source"),"ERR_INVALID_PARAMS");let d=u?h.name:a.name;return a7(`Only one source, copying to destination ${u?"directory":"file"} ${d}`),aNe(r,h,d,f,o)}return a7("Multiple sources, wrapping in a directory"),cNe(r,s,a,f,o)}return $(e)}var Tre=r=>r.unixfs&&r.unixfs.type&&r.unixfs.type.includes("directory"),aNe=async(r,e,t,n,i)=>{let o=n.pop();if(!o)throw(0,wd.default)(new Error("destination had no parent"),"ERR_INVALID_PARAMS");o=await Ire(r,e,t,o,i),n.push(o);let s=await os(r,n,i);await ss(r,s,i)},cNe=async(r,e,t,n,i)=>{for(let s=0;s{let o=await r.repo.blocks.get(e.cid),{node:s,cid:a,size:c}=await Qs(r,{parentCid:n.cid,size:o.length,cid:e.cid,name:t,hashAlg:i.hashAlg,cidVersion:i.cidVersion,flush:i.flush,shardSplitThreshold:i.shardSplitThreshold});return n.node=s,n.cid=a,n.size=c,n};var Mw=C(ee(),1);var bd=C(ee(),1),_d=j("ipfs:mfs:core:utils:remove-link");async function Rre(r,e){let t=e.parent;if(e.parentCid){let i=z.asCID(e.parentCid);if(i===null)throw(0,bd.default)(new Error("Invalid CID passed to removeLink"),"EINVALIDPARENTCID");_d(`Loading parent node ${i}`);let o=await r.repo.blocks.get(i);t=en(o)}if(!t)throw(0,bd.default)(new Error("No parent node or CID passed to removeLink"),"EINVALIDPARENT");if(!e.name)throw(0,bd.default)(new Error("No child name passed to removeLink"),"EINVALIDCHILDNAME");if(!t.Data)throw(0,bd.default)(new Error("Parent node had no data"),"ERR_INVALID_NODE");return st.unmarshal(t.Data).type==="hamt-sharded-directory"?(_d(`Removing ${e.name} from sharded directory`),lNe(r,{...e,parent:t})):(_d(`Removing link ${e.name} regular directory`),uNe(r,{...e,parent:t}))}var uNe=async(r,e)=>{e.parent.Links=e.parent.Links.filter(s=>s.Name!==e.name);let t=await pt(e.parent),i=await(await r.hashers.getHasher(e.hashAlg)).digest(t),o=z.create(e.cidVersion,kr,i);return await r.repo.blocks.put(o,t),_d(`Updated regular directory ${o}`),{node:e.parent,cid:o}},lNe=async(r,e)=>{let{rootBucket:t,path:n}=await _re(r,e.name,e.parent);await t.del(e.name);let{node:i}=await Cre(r,n,e.name,e);return t2(r,i.Links,t,e)},Cre=async(r,e,t,n)=>{let i=e.pop();if(!i)throw(0,bd.default)(new Error("Could not find parent"),"EINVALIDPARENT");let{bucket:o,prefix:s,node:a}=i;if(!a)throw(0,bd.default)(new Error("Could not find parent"),"EINVALIDPARENT");let c=a.Links.find(d=>(d.Name||"").substring(0,2)===s);if(!c)throw(0,bd.default)(new Error(`No link found with prefix ${s} for file ${t}`),"ERR_NOT_FOUND");if(c.Name===`${s}${t}`){_d(`Removing existing link ${c.Name}`);let d=a.Links.filter(p=>p.Name!==c.Name);return await o.del(t),t2(r,d,o,n)}_d(`Descending into sub-shard ${c.Name} for ${s}${t}`);let u=await Cre(r,e,t,n),l=u.cid,f=u.size,h=s;if(u.node.Links.length===1){_d(`Removing subshard for ${s}`);let d=u.node.Links[0];h=`${s}${(d.Name||"").substring(2)}`,l=d.Hash,f=d.Tsize||0}return _d(`Updating shard ${s} with name ${h}`),fNe(r,o,a,s,h,f,l,n)},fNe=(r,e,t,n,i,o,s,a)=>{let c=t.Links.filter(u=>u.Name!==n);return c.push({Name:i,Tsize:o,Hash:s}),t2(r,c,e,a)};var dNe=et.bind({ignoreUndefined:!0}),hNe={recursive:!1,cidVersion:0,hashAlg:"sha2-256",flush:!0,shardSplitThreshold:1e3};function n2(r){async function e(t,n={}){let i=dNe(hNe,n);Array.isArray(t)||(t=[t]);let o=await Promise.all(t.map(s=>sn(r,s,i)));if(!o.length)throw(0,Mw.default)(new Error("Please supply at least one path to remove"),"ERR_INVALID_PARAMS");o.forEach(s=>{if(s.path==="/")throw(0,Mw.default)(new Error("Cannot delete root"),"ERR_INVALID_PARAMS")});for(let s of o)await pNe(r,s.path,i)}return $(e)}var pNe=async(r,e,t)=>{let n=await sn(r,e,t),i=await Yc(r,n.mfsPath),o=i[i.length-1];i.pop();let s=i[i.length-1];if(!s)throw(0,Mw.default)(new Error(`${e} does not exist`),"ERR_NOT_FOUND");if(o.type==="directory"&&!t.recursive)throw(0,Mw.default)(new Error(`${e} is a directory, use -r to remove directories`),"ERR_WAS_DIR");let{cid:a}=await Rre(r,{parentCid:s.cid,name:o.name,hashAlg:t.hashAlg,cidVersion:t.cidVersion,flush:t.flush,shardSplitThreshold:t.shardSplitThreshold});s.cid=a;let c=await os(r,i,t);await ss(r,c,t)};var mNe=et.bind({ignoreUndefined:!0}),gNe=j("ipfs:mfs:touch"),Pre={flush:!0,shardSplitThreshold:1e3,hashAlg:"sha2-256",cidVersion:0,recursive:!1};function yNe(r,e,t){let n=0;return(r.includes("x")||r.includes("X")&&(t||e&1||e&8||e&64))&&(n+=1),r.includes("w")&&(n+=2),r.includes("r")&&(n+=4),n}function wNe(r,e){let t=0;return r.includes("u")&&(t+=e<<6),r.includes("g")&&(t+=e<<3),r.includes("o")&&(t+=e),t}function bNe(r,e,t){return e.includes("t")&&(t+=parseInt("1000",8)),e.includes("s")&&(r.includes("u")&&(t+=parseInt("4000",8)),r.includes("g")&&(t+=parseInt("2000",8))),t}function _Ne(r,e,t){e||(e=0);let n=r.match(/^(u?g?o?a?)(-?\+?=?)?(r?w?x?X?s?t?)$/);if(!n)throw new Error(`Invalid file mode: ${r}`);let[,i,o,s]=n;(i==="a"||!i)&&(i="ugo");let a=yNe(s,e,t);return a=wNe(i,a),a=bNe(i,s,a),o==="="?(i.includes("u")&&(e=e&parseInt("7077",8),e=e|a),i.includes("g")&&(e=e&parseInt("7707",8),e=e|a),i.includes("o")&&(e=e&parseInt("7770",8),e=e|a),e):o==="+"?a|e:o==="-"?a^e:e}function kre(r,e){if(r instanceof String||typeof r=="string"){let t=`${r}`;t.match(/^\d+$/g)?r=parseInt(t,8):r=0+t.split(",").reduce((n,i)=>_Ne(i,n,e.isDirectory()),e.mode||0)}return r}function Nre(r){async function e(t,n,i={}){let o=mNe(Pre,i);gNe(`Fetching stats for ${t}`);let{cid:s,mfsDirectory:a,name:c}=await sn(r,t,o);if(s.code!==kr)throw(0,i2.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");if(o.recursive){let S=await Ne(async function*(){for await(let A of _E(s,r.repo.blocks)){if(A.type!=="file"&&A.type!=="directory")throw(0,i2.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");A.unixfs.mode=kre(n,A.unixfs);let I=Xn({Data:A.unixfs.marshal(),Links:A.node.Links});yield{path:A.path,content:I}}},A=>Im(A,r.repo.blocks,{...o,pin:!1,dagBuilder:async function*(I,k,N){for await(let O of I)yield async function(){let G=O.content,R=pt(G),K=await n7(R,k,N);if(!G.Data)throw(0,i2.default)(new Error(`${K} had no data`),"ERR_INVALID_NODE");let U=st.unmarshal(G.Data);return{cid:K,size:R.length,path:O.path,unixfs:U}}}}),A=>Dr(A));if(!S)throw(0,i2.default)(new Error(`Could not chmod ${t}`),"ERR_COULD_NOT_CHMOD");await n2(r)(t,o),await r2(r)(`/ipfs/${S.cid}`,t,o);return}let u=await r.repo.blocks.get(s),l=en(u);if(!l.Data)throw(0,i2.default)(new Error(`${s} had no data`),"ERR_INVALID_NODE");let f=st.unmarshal(l.Data);f.mode=kre(n,f);let h=pt({Data:f.marshal(),Links:l.Links}),d=o.hashAlg||Pre.hashAlg,g=await(await r.hashers.getHasher(d)).digest(h),w=z.create(o.cidVersion,kr,g);o.flush&&await r.repo.blocks.put(w,h);let _=await Yc(r,a),x=_[_.length-1],m=z.decode(x.cid.bytes),y=await r.repo.blocks.get(m),b=en(y),E=await Qs(r,{parent:b,name:c,cid:w,size:h.length,flush:o.flush,hashAlg:d,cidVersion:s.version,shardSplitThreshold:1/0});x.cid=E.cid;let v=await os(r,_,o);await ss(r,v,o)}return $(e)}var ENe=et.bind({ignoreUndefined:!0}),vNe={};function Dre(r){async function e(t,n={}){n=ENe(vNe,n);let{cid:i}=await yd(r)(t,n);return i}return $(e)}var xNe=et.bind({ignoreUndefined:!0}),SNe={parents:!1,flush:!0,cidVersion:0,hashAlg:"sha2-256",shardSplitThreshold:1e3};function Ore(r){async function e(t,n,i={}){let o=xNe(SNe,i);await r2(r)(t,n,o),await n2(r)(t,{...o,recursive:!0})}return $(e)}var kN=C(ee(),1);var ANe=et.bind({ignoreUndefined:!0}),TNe=j("ipfs:mfs:touch"),Lre={flush:!0,shardSplitThreshold:1e3,cidVersion:0,hashAlg:"sha2-256"};function Bre(r){async function e(t,n={}){let i=ANe(Lre,n);i.mtime=i.mtime||new Date,TNe(`Touching ${t} mtime: ${i.mtime}`);let{cid:o,mfsDirectory:s,name:a,exists:c}=await sn(r,t,i),u=n.hashAlg||Lre.hashAlg,l=await r.hashers.getHasher(u),f,h,d=i.cidVersion;if(c){if(o.code!==kr)throw(0,kN.default)(new Error(`${t} was not a UnixFS node`),"ERR_NOT_UNIXFS");d=o.version;let b=await r.repo.blocks.get(o),E=en(b);if(!E.Data)throw(0,kN.default)(new Error(`${t} had no data`),"ERR_INVALID_NODE");let v=st.unmarshal(E.Data);v.mtime=i.mtime,f=pt({Data:v.marshal(),Links:E.Links});let S=await l.digest(f);h=z.create(i.cidVersion,kr,S),i.flush&&await r.repo.blocks.put(h,f)}else{let b=new st({type:"file",mtime:i.mtime});f=pt({Data:b.marshal(),Links:[]});let E=await l.digest(f);h=z.create(i.cidVersion,kr,E),i.flush&&await r.repo.blocks.put(h,f)}let p=await Yc(r,s),g=p[p.length-1],w=g.cid,_=await r.repo.blocks.get(w),x=en(_),m=await Qs(r,{parent:x,name:a,cid:h,size:f.length,flush:i.flush,shardSplitThreshold:i.shardSplitThreshold,hashAlg:i.hashAlg,cidVersion:d});g.cid=m.cid;let y=await os(r,p,i);await ss(r,y,i)}return $(e)}var NN=C(ee(),1);var INe=et.bind({ignoreUndefined:!0}),RNe={offset:0,length:1/0};function Mre(r){function e(t,n={}){return n=INe(RNe,n),{[Symbol.asyncIterator]:async function*(){let o=await sn(r,t,n),s=await Ei(o.mfsPath,r.repo.blocks);if(s.type!=="file"&&s.type!=="raw")throw(0,NN.default)(new Error(`${t} was not a file or raw bytes`),"ERR_NOT_FILE");if(!s.content)throw(0,NN.default)(new Error(`Could not load content stream from ${t}`),"ERR_NO_CONTENT");for await(let a of s.content({offset:n.offset,length:n.length}))yield a}}}return $(e)}var DN=C(ee(),1);var Uw=j("ipfs:mfs:utils:to-async-iterator");function Ure(r){if(!r)throw(0,DN.default)(new Error("paths must start with a leading slash"),"ERR_INVALID_PATH");if((typeof r=="string"||r instanceof String)&&(Uw("Content was a string"),r=Ie(r.toString())),r.length)return Uw("Content was array-like"),{[Symbol.asyncIterator]:function*(){yield r}};if(r[Symbol.asyncIterator])return Uw("Content was an async iterator"),r;if(r[Symbol.iterator])return Uw("Content was an iterator"),r;if(globalThis.Blob&&r instanceof globalThis.Blob)return Uw("Content was an HTML5 Blob"),yo(r.stream());throw(0,DN.default)(new Error(`Don't know how to convert ${r} into an async iterator`),"ERR_INVALID_PARAMS")}var Jc=C(ee(),1);var CNe=et.bind({ignoreUndefined:!0}),Zc=j("ipfs:mfs:write"),PNe={offset:0,length:1/0,create:!1,truncate:!1,rawLeaves:!1,reduceSingleLeafToSelf:!1,cidVersion:0,hashAlg:"sha2-256",parents:!1,progress:(r,e)=>{},strategy:"trickle",flush:!0,leafType:"raw",shardSplitThreshold:1e3};function zre(r){async function e(t,n,i={}){let o=CNe(PNe,i),s,a,c;if(Zc("Reading source, destination and parent"),await Ow().readLock(async()=>{s=await Ure(n),a=await sn(r,t,o),c=await sn(r,a.mfsDirectory,o)})(),Zc("Read source, destination and parent"),!o.parents&&!c.exists)throw(0,Jc.default)(new Error("directory does not exist"),"ERR_NO_EXIST");if(s==null)throw(0,Jc.default)(new Error("could not create source"),"ERR_NO_SOURCE");if(a==null)throw(0,Jc.default)(new Error("could not create destination"),"ERR_NO_DESTINATION");if(!o.create&&!a.exists)throw(0,Jc.default)(new Error("file does not exist"),"ERR_NO_EXIST");if(a.entryType!=="file")throw(0,Jc.default)(new Error("not a file"),"ERR_NOT_A_FILE");return kNe(r,t,s,a,o)}return $(e)}var kNe=async(r,e,t,n,i)=>{let o=await NNe(r,t,n,i);await Ow().writeLock(async()=>{let s=Jm(e),a=s.pop();if(a==null)throw(0,Jc.default)(new Error("source does not exist"),"ERR_NO_EXIST");let c=!1;try{await yd(r)(`/${s.join("/")}`,i),c=!0}catch(w){if(w.code!=="ERR_NOT_FOUND")throw w}c||await Ep(r)(`/${s.join("/")}`,i);let u=await sn(r,e,i),l=await Yc(r,u.mfsDirectory),f=l[l.length-1];if(!f)throw(0,Jc.default)(new Error("directory does not exist"),"ERR_NO_EXIST");if(!f.type||!f.type.includes("directory"))throw(0,Jc.default)(new Error(`cannot write to ${f.name}: Not a directory`),"ERR_NOT_A_DIRECTORY");let h=await r.repo.blocks.get(f.cid),d=en(h),p=await Qs(r,{parent:d,name:a,cid:o.cid,size:o.size,flush:i.flush,shardSplitThreshold:i.shardSplitThreshold,hashAlg:i.hashAlg,cidVersion:i.cidVersion});f.cid=p.cid;let g=await os(r,l,i);await ss(r,g,i)})()},NNe=async(r,e,t,n)=>{t.exists?Zc(`Overwriting file ${t.cid} offset ${n.offset} length ${n.length}`):Zc(`Writing file offset ${n.offset} length ${n.length}`);let i=[];if(n.offset>0)if(t.unixfs){if(Zc(`Writing first ${n.offset} bytes of original file`),i.push(()=>t.content({offset:0,length:n.offset})),t.unixfs.fileSize(){if(t.unixfs&&!n.truncate){let f=t.unixfs.fileSize();if(f>l)return Zc(`Writing last ${f-l} of ${f} bytes from original file starting at offset ${l}`),t.content({offset:l});Zc("Not writing last bytes from original file")}return{[Symbol.asyncIterator]:async function*(){}}}),s;n.mode!==void 0&&n.mode!==null?s=Bu(n.mode):t&&t.unixfs&&(s=t.unixfs.mode);let a;n.mtime!=null?a=af(n.mtime):t&&t.unixfs&&(a=t.unixfs.mtime);let c=await r.hashers.getHasher(n.hashAlg),u=await Dr(Im([{content:o,mode:s,mtime:a}],r.repo.blocks,{progress:n.progress,hasher:c,cidVersion:n.cidVersion,strategy:n.strategy,rawLeaves:n.rawLeaves,reduceSingleLeafToSelf:n.reduceSingleLeafToSelf,leafType:n.leafType}));if(!u)throw(0,Jc.default)(new Error(`cannot write to ${parent.name}`),"ERR_COULD_NOT_WRITE");return Zc(`Wrote ${u.cid}`),{cid:u.cid,size:u.size}},Vre=(r,e)=>async function*(){let n=0;for await(let i of r){if(n+=i.length,n>e){yield i.subarray(0,e-n);return}yield i}},Fre=(r,e=PH)=>{let t=new Uint8Array(e);async function*n(){for(;;)yield t}return Vre(n(),r)},DNe=async function*(r){for(let e=0;e{let e={cid:r.cid,name:r.name,type:r.type==="directory"?"directory":"file",size:r.size};return(r.type==="file"||r.type==="directory")&&(e.mode=r.unixfs.mode,e.mtime=r.unixfs.mtime),e};function $re(r){async function*e(t,n={}){let i=await sn(r,t,n),o=await Ei(i.mfsPath,r.repo.blocks);if(o.type==="directory"){yield*Mi(o.content(n),Kre);return}yield Kre(o)}return $(e)}var LNe={stat:yd},BNe={chmod:Nre,cp:r2,flush:Dre,mkdir:Ep,mv:Ore,rm:n2,touch:Bre},qre={write:zre,read:Mre,ls:$re},Hre=({options:r,mfs:e,operations:t,lock:n})=>{Object.keys(t).forEach(i=>{e[i]=n(t[i](r))})},MNe={repoOwner:!0,repo:null};function UNe(r){let{repoOwner:e}=Object.assign({},MNe||{},r),t=Ow(e),n=s=>t.readLock(s),i=s=>t.writeLock(s),o={};return Hre({options:r,mfs:o,operations:LNe,lock:n}),Hre({options:r,mfs:o,operations:BNe,lock:i}),Object.keys(qre).forEach(s=>{o[s]=qre[s](r)}),o}function Gre({repo:r,preload:e,hashers:t,options:n}){let i=UNe({repo:r,repoOwner:n.repoOwner!==!1,hashers:t}),o=s=>(...c)=>{let u=c.filter(l=>gH(l)||V8(l));if(u.length){let l=c[c.length-1];l&&l.preload!==!1&&u.forEach(f=>e(f))}return s(...c)};return{...i,chmod:i.chmod,cp:o(i.cp),mkdir:i.mkdir,stat:o(i.stat),rm:i.rm,read:o(i.read),touch:i.touch,write:i.write,mv:o(i.mv),flush:i.flush,ls:o(async function*(...s){for await(let a of i.ls(...s))yield{...a,size:a.size||0}})}}function jre({keychain:r}){return $((t,n)=>r.exportKey(t,n))}var Wre="Ed25519",Yre=2048;function Qre({keychain:r}){return $((t,n={type:Wre,size:Yre})=>r.createKey(t,n.type||Wre,n.size||Yre))}function Xre({keychain:r}){return $((t,n,i)=>r.importKey(t,n,i))}function Zre({keychain:r}){return $(t=>r.findKeyByName(t))}function Jre({keychain:r}){return $(()=>r.listKeys())}function ene({keychain:r}){return $(async(t,n)=>{let i=await r.renameKey(t,n);return{was:t,now:i.name,id:i.id,overwrite:!1}})}function tne({keychain:r}){return $(t=>r.removeKey(t))}var c7=class{constructor({keychain:e}){this.gen=Qre({keychain:e}),this.list=Jre({keychain:e}),this.rm=tne({keychain:e}),this.rename=ene({keychain:e}),this.export=jre({keychain:e}),this.import=Xre({keychain:e}),this.info=Zre({keychain:e})}};function _o({repo:r,preload:e}){async function t(n,i={}){i.preload!==!1&&e(n);let o=await r.blocks.get(n,i);return en(o)}return $(t)}function rne({repo:r,preload:e}){let t=_o({repo:r,preload:e});async function n(i,o={}){return(await t(i,o)).Data||new Uint8Array(0)}return $(n)}function ON(r,e=[]){for(let t in r){let n=r[t];if(t==="/"&&Object.keys(r).length===1)try{e.push({Name:"",Tsize:0,Hash:z.parse(n)});continue}catch{}let i=z.asCID(n);if(i){e.push({Name:"",Tsize:0,Hash:i});continue}Array.isArray(n)&&ON(n,e),n&&typeof n=="object"&&ON(n,e)}return e}function nne({repo:r,codecs:e}){async function t(n,i={}){let o=await e.getCodec(n.code),s=await r.blocks.get(n,i),a=o.decode(s);switch(n.code){case gf:return[];case kr:return a.Links;case lT:case _T:return ON(a);default:throw new Error(`Cannot resolve links from codec ${n.code}`)}}return $(t)}function ine({repo:r,preload:e}){async function t(n={}){let i;if(n.template)if(n.template==="unixfs-dir")i=new st({type:"directory"}).marshal();else throw new Error("unknown template");let o=pt({Data:i,Links:[]}),s=await dt.digest(o),a=z.createV0(s);return await r.blocks.put(a,o,{signal:n.signal}),n.preload!==!1&&e(a),a}return $(t)}function eu({repo:r,preload:e}){async function t(n,i={}){let o=await r.gcLock.readLock();try{let s=pt(n),a=await dt.digest(s),c=z.createV1(kr,a);return await r.blocks.put(c,s,{signal:i.signal}),i.preload!==!1&&e(c),i.pin&&await r.pins.pinRecursively(c,{signal:i.signal}),c}finally{o()}}return $(t)}function one({repo:r,preload:e}){let t=_o({repo:r,preload:e});async function n(i,o={}){let s=await t(i,o),c=pt(s).length,u=s.Links.reduce((l,f)=>l+(f.Tsize||0),0);return{Hash:i,NumLinks:s.Links.length,BlockSize:c,LinksSize:c-(s.Data||[]).length,DataSize:(s.Data||[]).length,CumulativeSize:c+u}}return $(n)}function sne({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a);return n({...c,Links:c.Links.concat([s])},a)}return $(i)}function ane({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a),u=rt([c.Data||[],s]);return n({...c,Data:u},a)}return $(i)}function cne({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a),u=(typeof s=="string"?s:s.Name)||"";return c.Links=c.Links.filter(l=>l.Name!==u),n(c,a)}return $(i)}function une({repo:r,preload:e}){let t=_o({repo:r,preload:e}),n=eu({repo:r,preload:e});async function i(o,s,a={}){let c=await t(o,a);return n({...c,Data:s},a)}return $(i)}var u7=class{constructor({repo:e,preload:t}){this.addLink=sne({repo:e,preload:t}),this.appendData=ane({repo:e,preload:t}),this.rmLink=cne({repo:e,preload:t}),this.setData=une({repo:e,preload:t})}};var l7=class{constructor({repo:e,codecs:t,preload:n}){this.data=rne({repo:e,preload:n}),this.get=_o({repo:e,preload:n}),this.links=nne({repo:e,codecs:t}),this.new=ine({repo:e,preload:n}),this.put=eu({repo:e,preload:n}),this.stat=one({repo:e,preload:n}),this.patch=new u7({repo:e,preload:n})}};var FNe=j("ipfs:repo:gc");function lne({repo:r,hashers:e}){async function*t(n={}){let i=Date.now(),o;try{o=await Zm({repo:r,hashers:e},n),await r.pins.pinRecursively(o),yield*r.gc()}finally{o&&await r.pins.unpin(o)}FNe(`Complete (${Date.now()-i}ms)`)}return $(t)}function f7({repo:r}){async function e(t={}){let n=await r.stat();return{numObjects:BigInt(n.numObjects.toString()),repoSize:BigInt(n.repoSize.toString()),repoPath:n.repoPath,version:`${n.version}`,storageMax:BigInt(n.storageMax.toString())}}return $(e)}function fne({repo:r}){async function e(t={}){try{await r._checkInitialized(t)}catch(n){if([/Key not found in database \[\/version\]/,/ENOENT/,/repo is not initialized yet/].some(o=>o.test(n.message)))return 12;throw n}return r.version.get()}return $(e)}var d7=class{constructor({repo:e,hashers:t}){this.gc=lne({repo:e,hashers:t}),this.stat=f7({repo:e}),this.version=fne({repo:e}),this.setApiAddr=n=>e.apiAddr.set(n)}};var hne=C(ee(),1);function dne(r,e){return{totalIn:BigInt(0),totalOut:BigInt(0),rateIn:0,rateOut:0}}function pne({network:r}){return $(async function*(t={}){let{libp2p:n}=await r.use(t);if(!t.poll){yield dne(n,t);return}let i=t.interval||1e3,o=-1;try{if(o=typeof i=="string"?Cf(i)||-1:i,!o||o<0)throw new Error("invalid duration")}catch(a){throw(0,hne.default)(a,"ERR_INVALID_POLL_INTERVAL")}let s;try{for(;;)yield dne(n,t),await new Promise(a=>{s=setTimeout(a,o)})}finally{clearTimeout(s)}})}var h7=class{constructor({repo:e,network:t}){this.repo=f7({repo:e}),this.bw=pne({network:t}),this.bitswap=N_({network:t})}};var zw=VNe;function VNe(r,e,t){if(!r)return t;var n,i;if(Array.isArray(e)&&(n=e.slice(0)),typeof e=="string"&&(n=e.split(".")),typeof e=="symbol"&&(n=[e]),!Array.isArray(n))throw new Error("props arg must be an array, a string or a symbol");for(;n.length;)if(i=n.shift(),!r||(r=r[i],r===void 0))return t;return r}var Gie=C($s(),1),Np=C(ee(),1);var gne=C($s(),1);async function vp(r){let e=0;for await(let t of r)e++;return e}var KNe=(0,gne.default)("ipfs:repo:migrator:migration-8");function yne(r){return r.child?yne(r.child):r}function $Ne(r){try{let e=Ot.decode(`b${r.toString().toLowerCase().slice(1)}`),t=ce.decode(e).multihash.bytes,n=Ot.encode(t).slice(1).toUpperCase();return new pe(`/${n}`,!1)}catch{return r}}function qNe(r){try{let e=Ot.decode(`b${r.toString().toLowerCase().slice(1)}`),t=Jn(e),n=Ot.encode(ce.createV1(Sc,t).bytes).slice(1);return new pe(`/${n.toUpperCase()}`,!1)}catch{return r}}async function mne(r,e,t){let n=r.blocks;await n.open();let i=yne(n),o=await vp(i.queryKeys({filters:[s=>t(s).toString()!==s.toString()]}));try{let s=0;for await(let a of i.query({})){let c=t(a.key);c.toString()!==a.key.toString()&&(s+=1,KNe(`Migrating Block from ${a.key} to ${c}`,await i.has(a.key)),await i.delete(a.key),await i.put(c,a.value),e(s/o*100,`Migrated Block from ${a.key} to ${c}`))}}finally{await n.close()}}var wne={version:8,description:"Transforms key names into base32 encoding and converts Block store to use bare multihashes encoded as base32",migrate:(r,e=()=>{})=>mne(r,e,$Ne),revert:(r,e=()=>{})=>mne(r,e,qNe)};var xp=C(gc(),1),bne=xp.default.Reader,HNe=xp.default.Writer,b8t=xp.default.util,p7=xp.default.roots.default||(xp.default.roots.default={}),_ne=p7.ipfs=(()=>{let r={};return r.pin=function(){let e={};return e.Set=function(){function t(n){if(n)for(var i=Object.keys(n),o=0;o>>3){case 1:a.version=i.uint32();break;case 2:a.fanout=i.uint32();break;case 3:a.seed=i.fixed32();break;default:i.skipType(c&7);break}}return a},t.fromObject=function(i){if(i instanceof p7.ipfs.pin.Set)return i;var o=new p7.ipfs.pin.Set;return i.version!=null&&(o.version=i.version>>>0),i.fanout!=null&&(o.fanout=i.fanout>>>0),i.seed!=null&&(o.seed=i.seed>>>0),o},t.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(s.version=0,s.fanout=0,s.seed=0),i.version!=null&&i.hasOwnProperty("version")&&(s.version=i.version),i.fanout!=null&&i.hasOwnProperty("fanout")&&(s.fanout=i.fanout),i.seed!=null&&i.hasOwnProperty("seed")&&(s.seed=i.seed),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,xp.default.util.toJSONOptions)},t}(),e}(),r})();var Sne=C(vne(),1),y7=C(Xo(),1);var Vw=new pe("/local/pins"),g7=256,xne=8192,BN=ce.parse("QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n"),Sp={direct:"direct",recursive:"recursive"};function MN(r){return new pe(`/${Ot.encode(r.multihash.bytes).toUpperCase().substring(1)}`)}function UN(r,e){for(let t=0;te[t])return 1}return r.byteLength>e.byteLength?1:r.byteLengthe.length)throw new Error("Impossibly large set header length");let i=e.slice(n,t+n),o=FN.toObject(FN.decode(i),{defaults:!1,arrays:!0,longs:Number,objects:!1});if(o.version!==1)throw new Error(`Unsupported Set version: ${o.version}`);if(o.fanout>r.Links.length)throw new Error("Impossibly large fanout");return{header:o,data:e.slice(t+n)}}function jNe(r,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,r,!0);let i=fe(e.toString()),o=yr([t,i],t.byteLength+i.byteLength);return(0,Sne.default)(Ee(o))}async function*Ane(r,e){let t=GNe(e),n=0;for(let i of e.Links){if(ns.Name===t);if(!n)throw new Error("No link found with name "+t);let i=await r.get(n.Hash),o=Jo(i);yield*Ane(r,o)}function WNe(r,e){return t(e,0);async function t(n,i){let o=FN.encode({version:1,fanout:g7,seed:i}).finish(),s=y7.default.encode(o.length),a=yr([s,o]),c=[];for(let l=0;l({link:{Name:"",Tsize:1,Hash:d.key},data:d.data||new Uint8Array})).sort((d,p)=>UN(d.link.Hash.bytes,p.link.Hash.bytes)),f=c.concat(l.map(d=>d.link));return{Data:yr([a,...l.map(d=>d.data)]),Links:f}}else{let l=n.reduce((h,d)=>{let p=jNe(i,d.key)%g7;return h[p]=p in h?h[p].concat([d]):[d],h},[]),f=0;for(let h of l){let d=await t(h,i+1);await u(d,f),f++}return{Data:a,Links:c}}async function u(l,f){let h=W3(l),d=await mr.digest(h),p=ce.createV0(d);await r.put(p,h);let g=l.Links.reduce((w,_)=>w+(_.Tsize||0),0)+h.length;c[f]={Name:"",Tsize:g,Hash:p}}}}async function zN(r,e,t){let n=await WNe(r,t.map(c=>({key:c}))),i=W3(n),o=await mr.digest(i),s=ce.createV0(o);await r.put(s,i);let a=n.Links.reduce((c,u)=>c+u.Tsize,0)+i.length;return{Name:e,Tsize:a,Hash:s}}async function QNe(r,e,t,n){if(!await e.has(Vw))return;let i=await e.get(Vw),o=ce.decode(i),s=await r.get(o),a=Jo(s),c=0,u=await vp(Kw(r,a,Sp.recursive))+await vp(Kw(r,a,Sp.direct));for await(let l of Kw(r,a,Sp.recursive)){c++;let f={depth:1/0};l.version!==0&&(f.version=l.version),l.code!==Zo&&(f.codec=l.code),await t.put(MN(l),zu(f)),n(c/u*100,`Migrated recursive pin ${l}`)}for await(let l of Kw(r,a,Sp.direct)){c++;let f={depth:0};l.version!==0&&(f.version=l.version),l.code!==Zo&&(f.codec=l.code),await t.put(MN(l),zu(f)),n(c/u*100,`Migrated direct pin ${l}`)}await r.delete(o),await e.delete(Vw)}async function XNe(r,e,t,n){let i=[],o=[],s=0,a=await vp(t.queryKeys({}));for await(let{key:h,value:d}of t.query({})){s++;let p=ks(d),g=ce.create(p.version||0,p.codec||Zo,Jn(Ot.decode("b"+h.toString().toLowerCase().split("/").pop())));p.depth===0?(n(s/a*100,`Reverted direct pin ${g}`),o.push(g)):(n(s/a*100,`Reverted recursive pin ${g}`),i.push(g))}n(100,"Updating pin root");let c={Links:[await zN(r,Sp.direct,o),await zN(r,Sp.recursive,i)]},u=W3(c),l=await mr.digest(u),f=ce.createV0(l);await r.put(f,u),await e.put(Vw,f.bytes)}async function Tne(r,e,t){let n=r.blocks,i=r.datastore,o=r.pins;await n.open(),await i.open(),await o.open();try{await t(n,i,o,e)}finally{await o.close(),await i.close(),await n.close()}}var Ine={version:9,description:"Migrates pins to datastore",migrate:(r,e=()=>{})=>Tne(r,e,QNe),revert:(r,e=()=>{})=>Tne(r,e,XNe)};var Rne=new pe("/config"),$w=new pe("/version");function qw(r){let e=r;for(;e.db||e.child;)if(e=e.db||e.child,e.type==="level-js"||e.constructor.name==="Level")return e}async function ZNe(r,e,t){let n=await e(r);if(n)return n;let i=qw(t);return i?new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{o(!!a.result)}}):!1}async function JNe(r,e,t,n){if(await t(r))return e(r);let i=qw(n);if(!i)throw Gn();return new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{if(a.result)return o(a.result);s(Gn())}})}function w7(r){let e=r.get.bind(r),t=r.has.bind(r);return r.get=n=>JNe(n,e,t,r),r.has=n=>ZNe(n,t,r),r}function VN(r){return{...r,root:w7(r.root),datastore:w7(r.datastore),pins:w7(r.pins),keys:w7(r.keys)}}async function eDe(r,e,t=()=>{}){let n=qw(e);if(!n){t(`${r} did not need an upgrade`);return}t(`Upgrading ${r}`),await Nne(n,(o,s)=>[{type:"del",key:o},{type:"put",key:fe(o),value:s}])}async function tDe(r,e,t=()=>{}){let n=qw(e);if(!n){t(`${r} did not need a downgrade`);return}t(`Downgrading ${r}`),await Nne(n,(o,s)=>[{type:"del",key:o},{type:"put",key:Ee(o),value:s}])}function Pne(r){return r.child?Pne(r.child):r}async function Cne(r,e,t){let n=Object.entries(r).map(([s,a])=>({key:s,backend:Pne(a)})).filter(({key:s,backend:a})=>a.constructor.name==="LevelDatastore").map(({key:s,backend:a})=>({name:s,store:a}));e(0,`Migrating ${n.length} dbs`);let i=0,o=s=>{e(Math.round(i/n.length*100),s)};for(let{name:s,store:a}of n){await a.open();try{await t(s,a,o)}finally{i++,await a.close()}}e(100,`Migrated ${n.length} dbs`)}var kne={version:10,description:"Migrates datastore-level keys to binary",migrate:(r,e=()=>{})=>Cne(r,e,eDe),revert:(r,e=()=>{})=>Cne(r,e,tDe)};function Nne(r,e){function t(n,i){let o=r.store("readwrite"),s=o.transaction,a=0,c;s.onabort=()=>i(c||s.error||new Error("aborted by user")),s.oncomplete=()=>i();function u(){let l=n[a++],f=l.key,h;try{h=l.type==="del"?o.delete(f):o.put(l.value,f)}catch(d){c=d,s.abort();return}a{let o=r.iterator(),s=c=>c;o._deserializeKey=o._deserializeValue=s,a();function a(){let c=(u,l,f)=>{if(u||l===void 0){let h=d=>{if(d){i(d);return}n()};o.end(h);return}t(e(l,f),a)};o.next(c)}})}var Ed=new pe("/local/filesroot");async function rDe(r,e=()=>{}){if(e(100,"Migrating MFS root to repo datastore"),await r.root.open(),await r.datastore.open(),await r.root.has(Ed)){let t=await r.root.get(Ed);await r.datastore.put(Ed,t),await r.root.delete(Ed)}await r.datastore.close(),await r.root.close(),e(100,"Stored MFS root in repo datastore")}async function nDe(r,e=()=>{}){if(e(100,"Migrating MFS root to repo root datastore"),await r.root.open(),await r.datastore.open(),await r.datastore.has(Ed)){let t=await r.datastore.get(Ed);await r.root.put(Ed,t),await r.datastore.delete(Ed)}await r.datastore.close(),await r.root.close(),e(100,"Stored MFS root in repo root datastore")}var Dne={version:11,description:"Store mfs root in the datastore",migrate:rDe,revert:nDe};var oD=C(gc(),1);var Ap=C(gc(),1),One=Ap.default.Reader,iDe=Ap.default.Writer,oDe=Ap.default.util,b7=Ap.default.roots.default||(Ap.default.roots.default={}),KN=b7.Protocols=(()=>{function r(e){if(this.protocols=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.protocols&&o.protocols.length||(o.protocols=[]),o.protocols.push(t.string());break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof b7.Protocols)return t;var n=new b7.Protocols;if(t.protocols){if(!Array.isArray(t.protocols))throw TypeError(".Protocols.protocols: array expected");n.protocols=[];for(var i=0;i{function r(e){if(this.addrs=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.addrs&&o.addrs.length||(o.addrs=[]),o.addrs.push(ui.Addresses.Address.decode(t,t.uint32()));break;case 2:o.certifiedRecord=ui.Addresses.CertifiedRecord.decode(t,t.uint32());break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof ui.Addresses)return t;var n=new ui.Addresses;if(t.addrs){if(!Array.isArray(t.addrs))throw TypeError(".Addresses.addrs: array expected");n.addrs=[];for(var i=0;i>>3){case 1:a.multiaddr=i.bytes();break;case 2:a.isCertified=i.bool();break;default:i.skipType(c&7);break}}return a},e.fromObject=function(i){if(i instanceof ui.Addresses.Address)return i;var o=new ui.Addresses.Address;return i.multiaddr!=null&&(typeof i.multiaddr=="string"?qr.base64.decode(i.multiaddr,o.multiaddr=qr.newBuffer(qr.base64.length(i.multiaddr)),0):i.multiaddr.length&&(o.multiaddr=i.multiaddr)),i.isCertified!=null&&(o.isCertified=!!i.isCertified),o},e.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(o.bytes===String?s.multiaddr="":(s.multiaddr=[],o.bytes!==Array&&(s.multiaddr=qr.newBuffer(s.multiaddr)))),i.multiaddr!=null&&i.hasOwnProperty("multiaddr")&&(s.multiaddr=o.bytes===String?qr.base64.encode(i.multiaddr,0,i.multiaddr.length):o.bytes===Array?Array.prototype.slice.call(i.multiaddr):i.multiaddr),i.isCertified!=null&&i.hasOwnProperty("isCertified")&&(s.isCertified=i.isCertified,o.oneofs&&(s._isCertified="isCertified")),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,gl.default.util.toJSONOptions)},e}(),r.CertifiedRecord=function(){function e(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:s.seq=n.uint64();break;case 2:s.raw=n.bytes();break;default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof ui.Addresses.CertifiedRecord)return n;var i=new ui.Addresses.CertifiedRecord;return n.seq!=null&&(qr.Long?(i.seq=qr.Long.fromValue(n.seq)).unsigned=!0:typeof n.seq=="string"?i.seq=parseInt(n.seq,10):typeof n.seq=="number"?i.seq=n.seq:typeof n.seq=="object"&&(i.seq=new qr.LongBits(n.seq.low>>>0,n.seq.high>>>0).toNumber(!0))),n.raw!=null&&(typeof n.raw=="string"?qr.base64.decode(n.raw,i.raw=qr.newBuffer(qr.base64.length(n.raw)),0):n.raw.length&&(i.raw=n.raw)),i},e.toObject=function(n,i){i||(i={});var o={};if(i.defaults){if(qr.Long){var s=new qr.Long(0,0,!0);o.seq=i.longs===String?s.toString():i.longs===Number?s.toNumber():s}else o.seq=i.longs===String?"0":0;i.bytes===String?o.raw="":(o.raw=[],i.bytes!==Array&&(o.raw=qr.newBuffer(o.raw)))}return n.seq!=null&&n.hasOwnProperty("seq")&&(typeof n.seq=="number"?o.seq=i.longs===String?String(n.seq):n.seq:o.seq=i.longs===String?qr.Long.prototype.toString.call(n.seq):i.longs===Number?new qr.LongBits(n.seq.low>>>0,n.seq.high>>>0).toNumber(!0):n.seq),n.raw!=null&&n.hasOwnProperty("raw")&&(o.raw=i.bytes===String?qr.base64.encode(n.raw,0,n.raw.length):i.bytes===Array?Array.prototype.slice.call(n.raw):n.raw),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,gl.default.util.toJSONOptions)},e}(),r})();var yl=C(gc(),1),s2=yl.default.Reader,HN=yl.default.Writer,dr=yl.default.util,Nn=yl.default.roots.default||(yl.default.roots.default={}),GN=Nn.Peer=(()=>{function r(t){if(this.addresses=[],this.protocols=[],this.metadata=[],t)for(var n=Object.keys(t),i=0;i>>3){case 1:s.addresses&&s.addresses.length||(s.addresses=[]),s.addresses.push(Nn.Address.decode(n,n.uint32()));break;case 2:s.protocols&&s.protocols.length||(s.protocols=[]),s.protocols.push(n.string());break;case 3:s.metadata&&s.metadata.length||(s.metadata=[]),s.metadata.push(Nn.Metadata.decode(n,n.uint32()));break;case 4:s.pubKey=n.bytes();break;case 5:s.peerRecordEnvelope=n.bytes();break;default:n.skipType(a&7);break}}return s},r.fromObject=function(n){if(n instanceof Nn.Peer)return n;var i=new Nn.Peer;if(n.addresses){if(!Array.isArray(n.addresses))throw TypeError(".Peer.addresses: array expected");i.addresses=[];for(var o=0;o{function r(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:s.multiaddr=n.bytes();break;case 2:s.isCertified=n.bool();break;default:n.skipType(a&7);break}}return s},r.fromObject=function(n){if(n instanceof Nn.Address)return n;var i=new Nn.Address;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?dr.base64.decode(n.multiaddr,i.multiaddr=dr.newBuffer(dr.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),n.isCertified!=null&&(i.isCertified=!!n.isCertified),i},r.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.multiaddr="":(o.multiaddr=[],i.bytes!==Array&&(o.multiaddr=dr.newBuffer(o.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(o.multiaddr=i.bytes===String?dr.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),n.isCertified!=null&&n.hasOwnProperty("isCertified")&&(o.isCertified=n.isCertified,i.oneofs&&(o._isCertified="isCertified")),o},r.prototype.toJSON=function(){return this.constructor.toObject(this,yl.default.util.toJSONOptions)},r})(),Z8t=Nn.Metadata=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.key=t.string();break;case 2:o.value=t.bytes();break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof Nn.Metadata)return t;var n=new Nn.Metadata;return t.key!=null&&(n.key=String(t.key)),t.value!=null&&(typeof t.value=="string"?dr.base64.decode(t.value,n.value=dr.newBuffer(dr.base64.length(t.value)),0):t.value.length&&(n.value=t.value)),n},r.toObject=function(t,n){n||(n={});var i={};return n.defaults&&(i.key="",n.bytes===String?i.value="":(i.value=[],n.bytes!==Array&&(i.value=dr.newBuffer(i.value)))),t.key!=null&&t.hasOwnProperty("key")&&(i.key=t.key),t.value!=null&&t.hasOwnProperty("value")&&(i.value=n.bytes===String?dr.base64.encode(t.value,0,t.value.length):n.bytes===Array?Array.prototype.slice.call(t.value):t.value),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,yl.default.util.toJSONOptions)},r})();var Tp=C(gc(),1),Lne=Tp.default.Reader,sDe=Tp.default.Writer,Hr=Tp.default.util,_7=Tp.default.roots.default||(Tp.default.roots.default={}),Bne=_7.Envelope=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof _7.Envelope)return t;var n=new _7.Envelope;return t.publicKey!=null&&(typeof t.publicKey=="string"?Hr.base64.decode(t.publicKey,n.publicKey=Hr.newBuffer(Hr.base64.length(t.publicKey)),0):t.publicKey.length&&(n.publicKey=t.publicKey)),t.payloadType!=null&&(typeof t.payloadType=="string"?Hr.base64.decode(t.payloadType,n.payloadType=Hr.newBuffer(Hr.base64.length(t.payloadType)),0):t.payloadType.length&&(n.payloadType=t.payloadType)),t.payload!=null&&(typeof t.payload=="string"?Hr.base64.decode(t.payload,n.payload=Hr.newBuffer(Hr.base64.length(t.payload)),0):t.payload.length&&(n.payload=t.payload)),t.signature!=null&&(typeof t.signature=="string"?Hr.base64.decode(t.signature,n.signature=Hr.newBuffer(Hr.base64.length(t.signature)),0):t.signature.length&&(n.signature=t.signature)),n},r.toObject=function(t,n){n||(n={});var i={};return n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=Hr.newBuffer(i.publicKey))),n.bytes===String?i.payloadType="":(i.payloadType=[],n.bytes!==Array&&(i.payloadType=Hr.newBuffer(i.payloadType))),n.bytes===String?i.payload="":(i.payload=[],n.bytes!==Array&&(i.payload=Hr.newBuffer(i.payload))),n.bytes===String?i.signature="":(i.signature=[],n.bytes!==Array&&(i.signature=Hr.newBuffer(i.signature)))),t.publicKey!=null&&t.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?Hr.base64.encode(t.publicKey,0,t.publicKey.length):n.bytes===Array?Array.prototype.slice.call(t.publicKey):t.publicKey),t.payloadType!=null&&t.hasOwnProperty("payloadType")&&(i.payloadType=n.bytes===String?Hr.base64.encode(t.payloadType,0,t.payloadType.length):n.bytes===Array?Array.prototype.slice.call(t.payloadType):t.payloadType),t.payload!=null&&t.hasOwnProperty("payload")&&(i.payload=n.bytes===String?Hr.base64.encode(t.payload,0,t.payload.length):n.bytes===Array?Array.prototype.slice.call(t.payload):t.payload),t.signature!=null&&t.hasOwnProperty("signature")&&(i.signature=n.bytes===String?Hr.base64.encode(t.signature,0,t.signature.length):n.bytes===Array?Array.prototype.slice.call(t.signature):t.signature),i},r.prototype.toJSON=function(){return this.constructor.toObject(this,Tp.default.util.toJSONOptions)},r})();var vd=C(gc(),1),E7=vd.default.Reader,Mne=vd.default.Writer,an=vd.default.util,Qa=vd.default.roots.default||(vd.default.roots.default={}),Une=Qa.PeerRecord=(()=>{function r(e){if(this.addresses=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:o.peerId=t.bytes();break;case 2:o.seq=t.uint64();break;case 3:o.addresses&&o.addresses.length||(o.addresses=[]),o.addresses.push(Qa.PeerRecord.AddressInfo.decode(t,t.uint32()));break;default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof Qa.PeerRecord)return t;var n=new Qa.PeerRecord;if(t.peerId!=null&&(typeof t.peerId=="string"?an.base64.decode(t.peerId,n.peerId=an.newBuffer(an.base64.length(t.peerId)),0):t.peerId.length&&(n.peerId=t.peerId)),t.seq!=null&&(an.Long?(n.seq=an.Long.fromValue(t.seq)).unsigned=!0:typeof t.seq=="string"?n.seq=parseInt(t.seq,10):typeof t.seq=="number"?n.seq=t.seq:typeof t.seq=="object"&&(n.seq=new an.LongBits(t.seq.low>>>0,t.seq.high>>>0).toNumber(!0))),t.addresses){if(!Array.isArray(t.addresses))throw TypeError(".PeerRecord.addresses: array expected");n.addresses=[];for(var i=0;i>>0,t.seq.high>>>0).toNumber(!0):t.seq),t.addresses&&t.addresses.length){i.addresses=[];for(var s=0;s>>3){case 1:s.multiaddr=n.bytes();break;default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof Qa.PeerRecord.AddressInfo)return n;var i=new Qa.PeerRecord.AddressInfo;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?an.base64.decode(n.multiaddr,i.multiaddr=an.newBuffer(an.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),i},e.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.multiaddr="":(o.multiaddr=[],i.bytes!==Array&&(o.multiaddr=an.newBuffer(o.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(o.multiaddr=i.bytes===String?an.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,vd.default.util.toJSONOptions)},e}(),r})();var v7=class{constructor(){B(this,"index",0);B(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let 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(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=e,o+=l,o>u||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;nthis.readIPv4Addr());if(s!==void 0)return t[i]=s[0],t[i+1]=s[1],t[i+2]=s[2],t[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];t[i]=o>>8,t[i+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Fne=45,aDe=15,a2=new v7;function zne(r){if(!(r.length>aDe))return a2.new(r).parseWith(()=>a2.readIPv4Addr())}function Vne(r){if(!(r.length>Fne))return a2.new(r).parseWith(()=>a2.readIPv6Addr())}function Kne(r){if(!(r.length>Fne))return a2.new(r).parseWith(()=>a2.readIPAddr())}function $ne(r){return!!zne(r)}function qne(r){return!!Vne(r)}function c2(r){return!!Kne(r)}var Hne=$ne,cDe=qne,jN=function(r){let e=0;if(r=r.toString().trim(),Hne(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(cDe(r)){let t=r.split(":",8),n;for(n=0;n0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},Gne=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let o=0;o{let e=fDe(...r);WN[e.code]=e,Hw[e.name]=e});function fDe(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function hr(r){if(typeof r=="number"){if(WN[r]!=null)return WN[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hw[r]!=null)return Hw[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var tu=C(Xo(),1);function Xne(r,e){switch(hr(r).code){case 4:case 41:return hDe(e);case 42:return Yne(e);case 6:case 273:case 33:case 132:return Jne(e).toString();case 53:case 54:case 55:case 56:case 400:case 777:return Yne(e);case 421:return yDe(e);case 444:return Qne(e);case 445:return Qne(e);case 466:return gDe(e);default:return Ee(e,"base16")}}function Zne(r,e){switch(hr(r).code){case 4:return jne(e);case 41:return jne(e);case 42:return Wne(e);case 6:case 273:case 33:case 132:return QN(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 777:return Wne(e);case 421:return pDe(e);case 444:return wDe(e);case 445:return bDe(e);case 466:return mDe(e);default:return fe(e,"base16")}}var YN=Object.values(If).map(r=>r.decoder),dDe=function(){let r=YN[0].or(YN[1]);return YN.slice(2).forEach(e=>r=r.or(e)),r}();function jne(r){if(!c2(r))throw new Error("invalid ip address");return jN(r)}function hDe(r){let e=Gne(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!c2(e))throw new Error("invalid ip address");return e}function QN(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Jne(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Wne(r){let e=fe(r),t=Uint8Array.from(tu.default.encode(e.length));return yr([t,e],t.length+e.length)}function Yne(r){let e=tu.default.decode(r);if(r=r.slice(tu.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return Ee(r)}function pDe(r){let e;r[0]==="Q"||r[0]==="1"?e=Jn(tt.decode(`z${r}`)).bytes:e=ce.parse(r).multihash.bytes;let t=Uint8Array.from(tu.default.encode(e.length));return yr([t,e],t.length+e.length)}function mDe(r){let e=dDe.decode(r),t=Uint8Array.from(tu.default.encode(e.length));return yr([t,e],t.length+e.length)}function gDe(r){let e=tu.default.decode(r),t=r.slice(tu.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+Ee(t,"base64url")}function yDe(r){let e=tu.default.decode(r),t=r.slice(tu.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return Ee(t,"base58btc")}function wDe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ot.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=QN(n);return yr([t,i],t.length+i.length)}function bDe(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ot.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=QN(n);return yr([t,i],t.length+i.length)}function Qne(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=Ee(e,"base32"),i=Jne(t);return`${n}:${i}`}var u2=C(Xo(),1);function _De(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n=t.length)throw tie("invalid address: "+r);if(o.path===!0){e.push([i,tD(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function EDe(r){let e=[];return r.map(t=>{let n=A7(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),tD(e.join("/"))}function vDe(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=A7(e);return e.length>1?[t.code,Zne(t.code,e[1])]:[t.code]})}function XN(r){return r.map(e=>{let t=A7(e);return e[1]!=null?[t.code,Xne(t.code,e[1])]:[t.code]})}function ZN(r){return S7(yr(r.map(e=>{let t=A7(e),n=Uint8Array.from(u2.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=yr([n,e[1]])),n})))}function JN(r,e){return r.size>0?r.size/8:r.size===0?0:u2.default.decode(e)+(u2.default.decode.bytes??0)}function x7(r){let e=[],t=0;for(;tr.length)throw tie("Invalid address Uint8Array: "+Ee(r,"base16"));e.push([n,a])}return e}function eD(r){let e=x7(r),t=XN(e);return EDe(t)}function xDe(r){r=tD(r);let e=_De(r),t=vDe(e);return ZN(t)}function eie(r){return xDe(r)}function S7(r){let e=SDe(r);if(e!=null)throw e;return Uint8Array.from(r)}function SDe(r){try{x7(r)}catch(e){return e}}function tD(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function tie(r){return new Error("Error parsing address: "+r)}function A7(r){return hr(r[0])}var nD=C(Xo(),1);var nie=C(ee(),1);var l2=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},rD=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Gw,jw,Ww,rie,TDe=Symbol.for("nodejs.util.inspect.custom"),IDe=[hr("dns").code,hr("dns4").code,hr("dns6").code,hr("dnsaddr").code],iD=new Map,iie=Symbol.for("@multiformats/js-multiaddr/multiaddr");function oie(r,e){if(r==null)throw new Error("requires node address object");if(e==null)throw new Error("requires transport protocol");let t,n=r.address;switch(r.family){case 4:t="ip4";break;case 6:if(t="ip6",n.includes("%")){let i=n.split("%");if(i.length!==2)throw Error("Multiple ip6 zones in multiaddr");n=i[0],t=`/ip6zone/${i[1]}/ip6`}break;default:throw Error("Invalid addr family, should be 4 or 6.")}return new ru("/"+[t,n,e,r.port].join("/"))}function sie(r){return as(r)?r.protos().some(e=>e.resolvable):!1}function as(r){return!!(r!=null&&r[iie])}var ru=class{constructor(e){if(Gw.set(this,void 0),jw.set(this,void 0),Ww.set(this,void 0),this[rie]=!0,e==null&&(e=""),e instanceof Uint8Array)this.bytes=S7(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=eie(e)}else if(as(e))this.bytes=S7(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return l2(this,Gw,"f")==null&&rD(this,Gw,eD(this.bytes),"f"),l2(this,Gw,"f")}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="",s=hr("tcp"),a=hr("udp"),c=hr("ip4"),u=hr("ip6"),l=hr("dns6"),f=hr("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(o=`%${p??""}`),IDe.includes(d)&&(t=s.name,i=443,n=`${p??""}${o}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=hr(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=hr(d).name,n=`${p??""}${o}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},hr(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;ne.name)}tuples(){return l2(this,jw,"f")==null&&rD(this,jw,x7(this.bytes),"f"),l2(this,jw,"f")}stringTuples(){return l2(this,Ww,"f")==null&&rD(this,Ww,XN(this.tuples()),"f"),l2(this,Ww,"f")}encapsulate(e){return e=new ru(e),new ru(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new ru(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new ru(ZN(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===Hw.ipfs.code).pop();if((t==null?void 0:t[1])!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?Ee(tt.decode(`z${n}`),"base58btc"):Ee(ce.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){let e=null;try{e=this.stringTuples().filter(t=>hr(t[0]).path===!0)[0][1],e==null&&(e=null)}catch{e=null}return e}equals(e){return rr(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=iD.get(t.name);if(n==null)throw(0,nie.default)(new Error(`no available resolver for ${t.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new ru(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")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){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[(Gw=new WeakMap,jw=new WeakMap,Ww=new WeakMap,rie=iie,TDe)](){return`Multiaddr(${eD(this.bytes)})`}};function lt(r){return new ru(r)}oD.default.util.Long=void 0;oD.default.configure();async function RDe(r,e=()=>{}){e(0,"Storing each peerstore key under a single datastore key"),await r.datastore.open();let t={},n=[];for await(let{key:i,value:o}of r.datastore.query({prefix:"/peers"})){n.push(i);let s=i.toString(),[,a,c,u,l]=s.split("/");if(a==="peers"&&["protos","addrs","metadata","keys"].includes(c)&&u)if(t[u]=t[u]||{addresses:[],protocols:[],metadata:[]},c==="protos"){let f=KN.decode(o);t[u].protocols=f.protocols.sort()}else if(c==="addrs"){let f=qN.decode(o);t[u].addresses=f.addrs.sort((h,d)=>lt(h.multiaddr).toString().localeCompare(lt(d.multiaddr).toString())),f.certifiedRecord&&f.certifiedRecord.raw&&(t[u].peerRecordEnvelope=f.certifiedRecord.raw)}else c==="metadata"?t[u].metadata.push({key:l,value:o}):c==="keys"&&(t[u].pubKey=o)}e(33,"Read peer data from store");for(let i of n)await r.datastore.delete(i);e(66,"Removed existing peer data from store");for(let i of Object.keys(t)){let o=t[i];o.metadata=o.metadata.sort((a,c)=>a.key.localeCompare(c.key));let s=GN.encode(o).finish();await r.datastore.put(new pe(`/peers/${i}`),s)}await r.datastore.close(),e(100,"Stored each peerstore key under a single datastore key")}async function CDe(r,e=()=>{}){e(0,"Storing each peerstore key under a multiple datastore keys"),await r.datastore.open();let t={},n=[];for await(let{key:i,value:o}of r.datastore.query({prefix:"/peers"})){n.push(i);let s=i.toString(),[,,a]=s.split("/");t[a]=GN.decode(o)}e(33,"Read peer data from store");for(let i of n)await r.datastore.delete(i);e(66,"Removed existing peer data from store");for(let[i,o]of Object.entries(t)){if(o.protocols&&o.protocols.length>0&&await r.datastore.put(new pe(`/peers/protos/${i}`),KN.encode({protocols:o.protocols}).finish()),o.addresses&&o.addresses.length>0){let s=o.peerRecordEnvelope,a;if(s){let c=Bne.decode(s),u=Une.decode(c.payload);a={raw:s,seq:u.seq}}await r.datastore.put(new pe(`/peers/addrs/${i}`),qN.encode({addrs:o.addresses,certifiedRecord:a}).finish())}if(o.metadata&&o.metadata.length>0)for(let{key:s,value:a}of o.metadata)await r.datastore.put(new pe(`/peers/metadata/${i}/${s}`),a);o.pubKey&&await r.datastore.put(new pe(`/peers/keys/${i}`),o.pubKey)}await r.datastore.close(),e(100,"Stored each peerstore key under multiple datastore keys")}var aie={version:12,description:"Store each peerstore peer under a single datastore key",migrate:RDe,revert:CDe};var Ip={description:"Empty migration.",migrate:()=>{},revert:()=>{},empty:!0},T7=[Object.assign({version:1},Ip),Object.assign({version:2},Ip),Object.assign({version:3},Ip),Object.assign({version:4},Ip),Object.assign({version:5},Ip),Object.assign({version:6},Ip),Object.assign({version:7},Ip),wne,Ine,kne,Dne,aie];var cie=C($s(),1);var sD={};xe(sD,{InvalidValueError:()=>h2,MissingRepoOptionsError:()=>nu,NonReversibleMigrationError:()=>f2,NotInitializedRepoError:()=>xd,RequiredParameterError:()=>d2});var f2=class extends Error{constructor(e){super(e),this.name="NonReversibleMigrationError",this.code=f2.code,this.message=e}};f2.code="ERR_NON_REVERSIBLE_MIGRATION";var xd=class extends Error{constructor(e){super(e),this.name="NotInitializedRepoError",this.code=xd.code,this.message=e}};xd.code="ERR_NOT_INITIALIZED_REPO";var d2=class extends Error{constructor(e){super(e),this.name="RequiredParameterError",this.code=d2.code,this.message=e}};d2.code="ERR_REQUIRED_PARAMETER";var h2=class extends Error{constructor(e){super(e),this.name="InvalidValueError",this.code=h2.code,this.message=e}};h2.code="ERR_INVALID_VALUE";var nu=class extends Error{constructor(e){super(e),this.name="MissingRepoOptionsError",this.code=nu.code,this.message=e}};nu.code="ERR_MISSING_REPO_OPTIONS";var aD=(0,cie.default)("ipfs:repo:migrator:repo:init");async function uie(r){if(!r)throw new nu("Please pass repo options when trying to open a repo");let e=r.root;try{await e.open();let t=await e.has($w),n=await e.has(Rne);return!t||!n?(aD(`Version entry present: ${t}`),aD(`Config entry present: ${n}`),!1):!0}catch(t){return aD("While checking if repo is initialized error was thrown: "+t.message),!1}finally{if(e!==void 0)try{await e.close()}catch{}}}async function cD(r){if(!await uie(r))throw new xd("Repo is not initialized!");let e=r.root;await e.open();try{return parseInt(Ee(await e.get($w)))}finally{await e.close()}}async function Yw(r,e){if(!e)throw new nu("Please pass repo options when trying to open a repo");let t=e.root;await t.open(),await t.put($w,fe(String(r))),await t.close()}var lie=C($s(),1),Xa=(0,lie.default)("ipfs:repo:migrator");function kDe(r){return r=r||T7,!Array.isArray(r)||r.length===0?0:r[r.length-1].version}async function fie(r,e,t,n,i={}){let o=i.ignoreLock??!1,s=i.onProgress,a=i.isDryRun??!1,c=i.migrations??T7;if(!r)throw new Xs.RequiredParameterError("Path argument is required!");if(!t)throw new Xs.RequiredParameterError("repoOptions argument is required!");if(!n)throw new Xs.RequiredParameterError("toVersion argument is required!");if(!Number.isInteger(n)||n<=0)throw new Xs.InvalidValueError("Version has to be positive integer!");e=VN(e);let u=await cD(e);if(u===n){Xa("Nothing to migrate.");return}if(u>n)throw new Xs.InvalidValueError(`Current repo's version (${u}) is higher then toVersion (${n}), you probably wanted to revert it?`);hie(c,u,n);let l;!a&&!o&&(l=await t.repoLock.lock(r));try{for(let f of c){if(n!==void 0&&f.version>n)break;if(!(f.version<=u)){Xa(`Migrating version ${f.version}`);try{if(!a){let h=()=>{};s&&(h=(d,p)=>s(f.version,d.toFixed(2),p)),await f.migrate(e,h)}}catch(h){let d=f.version-1;throw Xa(`An exception was raised during execution of migration. Setting the repo's version to last successfully migrated version: ${d}`),await Yw(d,e),new Error(`During migration to version ${f.version} exception was raised: ${h.stack||h.message||h}`)}Xa(`Migrating to version ${f.version} finished`)}}a||await Yw(n||kDe(c),e),Xa("Repo successfully migrated",n!==void 0?`to version ${n}!`:"to latest version!")}finally{!a&&!o&&l&&await l.close()}}async function die(r,e,t,n,i={}){let o=i.ignoreLock??!1,s=i.onProgress,a=i.isDryRun??!1,c=i.migrations??T7;if(!r)throw new Xs.RequiredParameterError("Path argument is required!");if(!t)throw new Xs.RequiredParameterError("repoOptions argument is required!");if(!n)throw new Xs.RequiredParameterError("When reverting migrations, you have to specify to which version to revert!");if(!Number.isInteger(n)||n<=0)throw new Xs.InvalidValueError("Version has to be positive integer!");e=VN(e);let u=await cD(e);if(u===n){Xa("Nothing to revert.");return}if(uu)){Xa(`Reverting migration version ${h.version}`);try{if(!a){let d=()=>{};s&&(d=(p,g)=>s(h.version,p.toFixed(2),g)),await h.revert(e,d)}}catch(d){let p=h.version;throw Xa(`An exception was raised during execution of migration. Setting the repo's version to last successfully reverted version: ${p}`),await Yw(p,e),d.message=`During reversion to version ${h.version} exception was raised: ${d.message}`,d}Xa(`Reverting to version ${h.version} finished`)}}a||await Yw(n,e),Xa(`All migrations successfully reverted to version ${n}!`)}finally{!a&&!o&&l&&await l.close()}}function hie(r,e,t,n=!1){let i=0;for(let o of r){if(o.version>t)break;if(o.version>e){if(n&&!o.revert)throw new Xs.NonReversibleMigrationError(`It is not possible to revert to version ${e} because migration version ${o.version} is not reversible. Cancelling reversion.`);i++}}if(i!==t-e)throw new Xs.InvalidValueError(`The ipfs-repo-migrations package does not have all migration to migrate from version ${e} to ${t}`)}var Xs=sD;var jie=C(gie(),1);var _ie=C($s(),1);var Rp=class extends Error{constructor(e){super(e),this.name="LockExistsError",this.code=Rp.code}};Rp.code="ERR_LOCK_EXISTS";var cs=class extends Error{constructor(e){super(e),this.name="NotFoundError",this.code=cs.code}};cs.code="ERR_NOT_FOUND";var Cp=class extends Error{constructor(e){super(e),this.name="InvalidRepoVersionError",this.code=Cp.code}};Cp.code="ERR_INVALID_REPO_VERSION";var Pp="ERR_REPO_NOT_INITIALIZED",yie="ERR_REPO_ALREADY_OPEN",wie="ERR_REPO_ALREADY_CLOSED";async function R7(r,e,t){let n=await e(r);if(n)return n;let i=bie(t);return i?new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{o(!!a.result)}}):!1}async function C7(r,e,t,n){if(await t(r))return e(r);let i=bie(n);if(!i)throw new cs;return new Promise((o,s)=>{let a=i.store("readonly").get(r.toString());a.transaction.onabort=()=>{s(a.transaction.error)},a.transaction.oncomplete=()=>{if(a.result)return o(a.result);s(new cs)}})}function bie(r){let e=r;for(;e.db||e.child;)if(e=e.db||e.child,e.type==="level-js"||e.constructor.name==="Level")return e}var UDe=(0,_ie.default)("ipfs:repo:version"),uD=new pe("version");function Eie(r){return{async exists(){return R7(uD,r.has.bind(r),r)},async get(){let e=await C7(uD,r.get.bind(r),r.has.bind(r),r);return parseInt(Ee(e),10)},set(e){return r.put(uD,fe(String(e)))},async check(e){let t=await this.get();return UDe("comparing version: %s and %s",t,e),t===e||(t===6&&e===7||e===6&&t===7)}}}var P7=C(ee(),1);var FDe=Hs.default?Hs.default:Hs,lD=new pe("config");function vie(r){let e=new FDe({concurrency:1}),t={async getAll(o={}){let s=await C7(lD,r.get.bind(r),r.has.bind(r),r);return JSON.parse(Ee(s))},async get(o,s={}){if(o==null)throw new cs(`Key ${o} does not exist in config`);let a=await this.getAll(s),c=zw(a,o);if(c===void 0)throw new cs(`Key ${o} does not exist in config`);return c},set(o,s,a={}){if(typeof o!="string"&&!(o instanceof String))throw(0,P7.default)(new Error("Invalid key type: "+typeof o),"ERR_INVALID_KEY");if(s===void 0||s instanceof Uint8Array)throw(0,P7.default)(new Error("Invalid value type: "+typeof s),"ERR_INVALID_VALUE");return e.add(()=>n({key:o,value:s},a.signal))},replace(o,s={}){if(!o||o instanceof Uint8Array)throw(0,P7.default)(new Error("Invalid value type: "+typeof o),"ERR_INVALID_VALUE");return e.add(()=>n({key:void 0,value:o},s.signal))},async exists(){return R7(lD,r.has.bind(r),r)}};return t;async function n(o,s){if(s&&s.aborted)return;let a=o.key,c=o.value;if(a){let u=await t.getAll();return typeof u=="object"&&u!==null&&$r(u,a,c),i(u)}return i(c)}function i(o){let s=fe(JSON.stringify(o,null,2));return r.put(lD,s)}}function Qw(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}function fD(r,e={}){if(!Qw(r)&&!Array.isArray(r))throw new TypeError("Expected a plain object or array");let{deep:t,compare:n}=e,i=[],o=[],s=c=>{let u=i.indexOf(c);if(u!==-1)return o[u];let l=[];return i.push(c),o.push(l),l.push(...c.map(f=>Array.isArray(f)?s(f):Qw(f)?a(f):f)),l},a=c=>{let u=i.indexOf(c);if(u!==-1)return o[u];let l={},f=Object.keys(c).sort(n);i.push(c),o.push(l);for(let h of f){let d=c[h],p;t&&Array.isArray(d)?p=s(d):p=t&&Qw(d)?a(d):d,Object.defineProperty(l,h,{...Object.getOwnPropertyDescriptor(c,h),value:p})}return l};return Array.isArray(r)?t?s(r):r.slice():a(r)}var dD=new pe("datastore_spec");function xie(r){return{exists(){return r.has(dD)},async get(){let e=await r.get(dD);return JSON.parse(Ee(e))},async set(e){return r.put(dD,fe(JSON.stringify(fD(e,{deep:!0}))))}}}var hD=new pe("api");function Sie(r){return{async get(){let e=await r.get(hD);return e&&e.toString()},set(e){return r.put(hD,fe(e.toString()))},delete(){return r.delete(hD)}}}var Aie=C(ee(),1);function Tie(r){return{open(){return r.open()},close(){return r.close()},query(e,t){return r.query(e,t)},queryKeys(e,t){return r.queryKeys(e,t)},async get(e,t){let n=Ad(e);return n.isIdentity?Promise.resolve(n.digest):r.get(e,t)},async*getMany(e,t){for await(let n of e)yield this.get(n,t)},async put(e,t,n){let{isIdentity:i}=Ad(e);i||await r.put(e,t,n)},async*putMany(e,t){let n=jn({objectMode:!0});(globalThis.process&&globalThis.process.nextTick?globalThis.process.nextTick:globalThis.setImmediate||globalThis.setTimeout)(async()=>{try{await on(r.putMany(async function*(){for await(let{key:o,value:s}of e)Ad(o).isIdentity||(yield{key:o,value:s}),n.push({key:o,value:s})}())),n.end()}catch(o){n.end(o)}}),yield*n},has(e,t){let{isIdentity:n}=Ad(e);return n?Promise.resolve(!0):r.has(e,t)},delete(e,t){let{isIdentity:n}=Ad(e);return n?Promise.resolve():r.delete(e,t)},deleteMany(e,t){return r.deleteMany(Yt(e,n=>!Ad(n).isIdentity),t)},batch(){let e=r.batch();return{put(t,n){let{isIdentity:i}=Ad(t);i||e.put(t,n)},delete(t){let{isIdentity:n}=Ad(t);n||e.delete(t)},commit:t=>e.commit(t)}}}}function Ad(r){let e=ce.asCID(r);if(e==null)throw(0,Aie.default)(new Error("Not a valid cid"),"ERR_INVALID_CID");return e.multihash.code!==Ns.code?{isIdentity:!1}:{isIdentity:!0,digest:e.multihash.digest}}var Iie=C($s(),1),Rie=(0,Iie.default)("ipfs:repo:lock:memory"),Cie="repo.lock",Xw={};async function zDe(r){let e=r+"/"+Cie;if(Rie("locking %s",e),Xw[e]===!0)throw new Rp(`Lock already being held for file: ${e}`);return Xw[e]=!0,{async close(){Xw[e]&&delete Xw[e]}}}async function VDe(r){let e=r+"/"+Cie;return Rie(`checking lock: ${e}`),!!Xw[e]}var k7={lock:zDe,locked:VDe};var Pie={autoMigrate:!0,onMigrationProgress:()=>{},repoOwner:!0,repoLock:k7};var pD={Spec:{type:"mount",mounts:[{mountpoint:"/blocks",type:"measure",prefix:"flatfs.datastore",child:{type:"flatfs",path:"blocks",sync:!0,shardFunc:"/repo/flatfs/shard/v1/next-to-last/2"}},{mountpoint:"/",type:"measure",prefix:"leveldb.datastore",child:{type:"levelds",path:"datastore",compression:"none"}}]}};var Die=C(ee(),1),Oie=C($s(),1);async function Fi(r){for await(let e of r)return e}function N7({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*KDe(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=ce.asCID(n);o?yield[i.join("/"),o]:typeof n=="object"&&(yield*mD(n,i))}else{let t=ce.asCID(e);t?yield[r.join("/"),t]:yield*mD(e,r)}}function*mD(r,e){if(r==null||r instanceof Uint8Array)return;let t=ce.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*KDe(o,i)}}function*$De(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!ce.asCID(n)&&(yield*gD(n,i))}else yield*gD(e,r)}function*gD(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!ce.asCID(n)&&(yield*$De(i,n))}}function qDe(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=ce.asCID(t);if(o)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var yD=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:N7(),bytes:N7(),value:N7(),asBlock:N7()})}links(){return mD(this.value,[])}tree(){return gD(this.value,[])}get(e="/"){return qDe(this.value,e.split("/").filter(Boolean))}};function D7({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n&&n.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new yD({cid:e,bytes:r,value:i})}var kie=C(ee(),1);function Zw(r){let e=ce.asCID(r);if(e==null)throw(0,kie.default)(new Error("Not a valid cid"),"ERR_INVALID_CID");let t=Ot.encode(e.multihash.bytes);return new pe("/"+t.slice(1).toUpperCase(),!1)}function wD(r){return Jn(Ot.decode(`b${r.toString().toLowerCase().substring(1)}`))}var Nie=C($s(),1);var HDe=(0,Nie.default)("ipfs:repo:utils:walk-dag");async function*p2(r,e,t,n){try{let i=await e.get(r,n),o=await t(r.code),s=D7({bytes:i,cid:r,codec:o});for(let[,a]of s.links())yield a,yield*p2(a,e,t,n)}catch(i){throw HDe("Could not walk DAG for CID",r.toString(),i),i}}var Jw=class extends Map{constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=e.maxSize,this.maxAge=e.maxAge||Number.POSITIVE_INFINITY,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(e){if(typeof this.onEviction=="function")for(let[t,n]of e)this.onEviction(t,n.value)}_deleteIfExpired(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(e,t.value),this.delete(e)):!1}_getOrDeleteIfExpired(e,t){if(this._deleteIfExpired(e,t)===!1)return t.value}_getItemValue(e,t){return t.expiry?this._getOrDeleteIfExpired(e,t):t.value}_peek(e,t){let n=t.get(e);return this._getItemValue(e,n)}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(e,t){this.oldCache.delete(e),this._set(e,t)}*_entriesAscending(){for(let e of this.oldCache){let[t,n]=e;this.cache.has(t)||this._deleteIfExpired(t,n)===!1&&(yield e)}for(let e of this.cache){let[t,n]=e;this._deleteIfExpired(t,n)===!1&&(yield e)}}get(e){if(this.cache.has(e)){let t=this.cache.get(e);return this._getItemValue(e,t)}if(this.oldCache.has(e)){let t=this.oldCache.get(e);if(this._deleteIfExpired(e,t)===!1)return this._moveToRecent(e,t),t.value}}set(e,t,{maxAge:n=this.maxAge}={}){let i=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;this.cache.has(e)?this.cache.set(e,{value:t,expiry:i}):this._set(e,{value:t,expiry:i})}has(e){return this.cache.has(e)?!this._deleteIfExpired(e,this.cache.get(e)):this.oldCache.has(e)?!this._deleteIfExpired(e,this.oldCache.get(e)):!1}peek(e){if(this.cache.has(e))return this._peek(e,this.cache);if(this.oldCache.has(e))return this._peek(e,this.oldCache)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this._entriesAscending()],n=t.length-e;n<0?(this.cache=new Map(t),this.oldCache=new Map,this._size=t.length):(n>0&&this._emitEvictions(t.slice(0,n)),this.oldCache=new Map(t.slice(n)),this.cache=new Map,this._size=0),this.maxSize=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache){let[t,n]=e;this._deleteIfExpired(t,n)===!1&&(yield[t,n.value])}for(let e of this.oldCache){let[t,n]=e;this.cache.has(t)||this._deleteIfExpired(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.cache];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this._deleteIfExpired(i,o)===!1&&(yield[i,o.value])}e=[...this.oldCache];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.cache.has(i)||this._deleteIfExpired(i,o)===!1&&(yield[i,o.value])}}*entriesAscending(){for(let[e,t]of this._entriesAscending())yield[e,t.value]}get size(){if(!this._size)return this.oldCache.size;let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,i]of this.entriesAscending())e.call(t,i,n,this)}get[Symbol.toStringTag](){return JSON.stringify([...this.entriesAscending()])}};var GDe=2048;function jDe(r){let e=`Invalid type '${r}', must be one of {direct, indirect, recursive, all}`;return(0,Die.default)(new Error(e),"ERR_INVALID_PIN_TYPE")}var O7=class{constructor({pinstore:e,blockstore:t,loadCodec:n}){this.pinstore=e,this.blockstore=t,this.loadCodec=n,this.log=(0,Oie.default)("ipfs:repo:pin"),this.directPins=new Set,this.recursivePins=new Set}async pinDirectly(e,t={}){await this.blockstore.get(e,t);let n={depth:0};return e.version!==0&&(n.version=e.version),e.code!==Zo&&(n.codec=e.code),t.metadata&&(n.metadata=t.metadata),this.pinstore.put(Zw(e),zu(n))}unpin(e,t){return this.pinstore.delete(Zw(e),t)}async pinRecursively(e,t={}){await this.fetchCompleteDag(e,t);let n={depth:1/0};e.version!==0&&(n.version=e.version),e.code!==Zo&&(n.codec=e.code),t.metadata&&(n.metadata=t.metadata),await this.pinstore.put(Zw(e),zu(n))}async*directKeys(e){for await(let t of this.pinstore.query({filters:[n=>ks(n.value).depth===0]})){let n=ks(t.value),i=n.version||0,o=n.codec!=null?n.codec:Zo,s=wD(t.key);yield{cid:ce.create(i,o,s),metadata:n.metadata}}}async*recursiveKeys(e){for await(let t of this.pinstore.query({filters:[n=>ks(n.value).depth===1/0]})){let n=ks(t.value),i=n.version||0,o=n.codec!=null?n.codec:Zo,s=wD(t.key);yield{cid:ce.create(i,o,s),metadata:n.metadata}}}async*indirectKeys(e){for await(let{cid:t}of this.recursiveKeys())for await(let n of p2(t,this.blockstore,this.loadCodec,e)){let i=[Pt.recursive];(await this.isPinnedWithType(n,i)).pinned||(yield n)}}async isPinnedWithType(e,t,n){Array.isArray(t)||(t=[t]);let i=t.includes(Pt.all),o=t.includes(Pt.direct),s=t.includes(Pt.recursive),a=t.includes(Pt.indirect);if(s||o||i){let l=await Fi(this.pinstore.query({prefix:Zw(e).toString(),filters:[f=>{if(i)return!0;let h=ks(f.value);return t.includes(h.depth===0?Pt.direct:Pt.recursive)}],limit:1}));if(l){let f=ks(l.value);return{cid:e,pinned:!0,reason:f.depth===0?Pt.direct:Pt.recursive,metadata:f.metadata}}}let c=this;async function*u(l,f){for await(let{cid:h}of f)for await(let d of p2(h,c.blockstore,c.loadCodec))if(d.equals(l)){yield h;return}}if(i||a){let l=await Fi(u(e,this.recursiveKeys()));if(l)return{cid:e,pinned:!0,reason:Pt.indirect,parent:l}}return{cid:e,pinned:!1}}async fetchCompleteDag(e,t={}){let n=new Jw({maxSize:t.cidCacheMaxSize??GDe}),i=async(o,s)=>{if(n.has(o.toString()))return;n.set(o.toString(),!0);let a=await this.blockstore.get(o,s),c=await this.loadCodec(o.code),u=D7({bytes:a,cid:o,codec:c});await Promise.all([...u.links()].map(([,l])=>i(l,s)))};await i(e,t)}static checkPinType(e){if(typeof e!="string"||!Object.keys(Pt).includes(e))throw jDe(e);return!0}};var Bie=C(ee(),1);function Mie(r,e){return{open(){return e.open()},close(){return e.close()},query(t,n){return e.query(t,n)},queryKeys(t,n){return e.queryKeys(t,n)},async get(t,n){return e.get(t,n)},async*getMany(t,n){yield*e.getMany(t,n)},async put(t,n,i){await e.put(t,n,i)},async*putMany(t,n){yield*e.putMany(t,n)},has(t,n){return e.has(t,n)},async delete(t,n){return await Lie(t,r),e.delete(t,n)},deleteMany(t,n){return e.deleteMany(Bi(t,async i=>(await Lie(i,r),i)),n)},batch(){return e.batch()}}}async function Lie(r,e){let{pinned:t,reason:n}=await e.isPinnedWithType(r,Pt.all);if(t)throw(0,Bie.default)(new Error(`pinned: ${n}`),"ERR_BLOCK_PINNED")}var bD=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},_D=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Uie=r=>globalThis.DOMException===void 0?new _D(r):new DOMException(r),Fie=r=>{let e=r.reason===void 0?Uie("This operation was aborted."):r.reason;return e instanceof Error?e:Uie(e)};function ED(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,a=new Promise((c,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:f}=e;f.aborted&&u(Fie(f)),f.addEventListener("abort",()=>{u(Fie(f))})}let l=new bD;s=o.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(f){u(f)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${t} milliseconds`,u(l))},t),(async()=>{try{c(await r)}catch(f){u(f)}finally{o.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},a}var vD="lock:worker:request-read",xD="lock:worker:release-read",SD="lock:master:grant-read",AD="lock:worker:request-write",TD="lock:worker:release-write",ID="lock:master:grant-write";var zie=(r,e,t,n,i)=>(o,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},Vie=(r,e,t,n)=>async()=>{let i=k1();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",s)})},WDe={singleProcess:!1},Kie=r=>{if(r=Object.assign({},WDe,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Xm.addEventListener("message",zie(t,"requestReadLock",vD,xD,SD)),Xm.addEventListener("message",zie(t,"requestWriteLock",AD,TD,ID)),t}return{isWorker:!0,readLock:t=>Vie(t,vD,SD,xD),writeLock:t=>Vie(t,AD,ID,TD)}};var kp={},Td;async function RD(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await ED((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var YDe=(r,e)=>{if(Td.isWorker===!0)return{readLock:Td.readLock(r,e),writeLock:Td.writeLock(r,e)};let t=new Hs({concurrency:1}),n;return{async readLock(){if(n!=null)return await RD(n,e);n=new Hs({concurrency:e.concurrency,autoStart:!1});let i=n,o=RD(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await RD(t,e)}}},QDe={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function e5(r){let e=Object.assign({},QDe,r);return Td==null&&(Td=Kie(e),Td.isWorker!==!0&&(Td.addEventListener("requestReadLock",t=>{kp[t.data.name]!=null&&kp[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),Td.addEventListener("requestWriteLock",async t=>{kp[t.data.name]!=null&&kp[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),kp[e.name]==null&&(kp[e.name]=YDe(e.name,e)),kp[e.name]}var $ie=C($s(),1);async function*CD(r,e=1){let t=[];e<1&&(e=1);for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}async function*PD(r,e=1){for await(let t of CD(r,e)){let n=t.map(async i=>await i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;ia),r.indirectKeys(),Bi(r.directKeys(),({cid:a})=>a),i),s=new Set;for await(let a of Qo(o,i))s.add(Ot.encode(a.multihash.bytes));return s}async function*tOe({blockstore:r},e,t){let n=0,i=0;yield*Ne(PD(Bi(t,async s=>async function(){n++;try{let c=Ot.encode(s.multihash.bytes);if(e.has(c))return null;try{await r.delete(s),i++}catch(u){return{err:new Error(`Could not delete block with CID ${s}: ${u.message}`)}}return{cid:s}}catch(c){let u=`Could delete block with CID ${s}`;return t5(u,c),{err:new Error(u+`: ${c.message}`)}}}),ZDe),s=>Yt(s,Boolean)),t5(`Marked set has ${e.size} unique blocks. Blockstore has ${n} blocks. Deleted ${i} blocks.`)}var Eo=(0,Gie.default)("ipfs:repo"),rOe=Number.MAX_SAFE_INTEGER,nOe="repoAutoMigrate",kD=class{constructor(e,t,n,i){if(typeof e!="string")throw new Error("missing repo path");if(typeof t!="function")throw new Error("missing codec loader");this.options=et(Pie,i),this.closed=!0,this.path=e,this.root=n.root,this.datastore=n.datastore,this.keys=n.keys;let o=n.blocks,s=n.pins;this.pins=new O7({pinstore:s,blockstore:o,loadCodec:t});let a=Mie(this.pins,o);this.blocks=Tie(a),this.version=Eie(this.root),this.config=vie(this.root),this.spec=xie(this.root),this.apiAddr=Sie(this.root),this.gcLock=e5({name:e,singleProcess:this.options.repoOwner!==!1}),this.gc=qie({gcLock:this.gcLock,pins:this.pins,blockstore:this.blocks,root:this.root,loadCodec:t})}async init(e){Eo("initializing at: %s",this.path),await this._openRoot(),await this.config.replace(iOe(e)),await this.spec.set(oOe(e)),await this.version.set(12)}async isInitialized(){if(!this.closed)return!0;try{return await this._openRoot(),await this._checkInitialized(),await this.root.close(),!0}catch{return!1}}async open(){if(!this.closed)throw(0,Np.default)(new Error("repo is already open"),yie);Eo("opening at: %s",this.path);try{if(await this._openRoot(),await this._checkInitialized(),this._lockfile=await this._openLock(),Eo("acquired repo.lock"),!await this.version.check(12))if(await this._isAutoMigrationEnabled())await this._migrate(12,{root:this.root,datastore:this.datastore,pins:this.pins.pinstore,blocks:this.pins.blockstore,keys:this.keys});else throw new Cp("Incompatible repo versions. Automatic migrations disabled. Please migrate the repo manually.");Eo("creating datastore"),await this.datastore.open(),Eo("creating blocks"),await this.blocks.open(),Eo("creating keystore"),await this.keys.open(),Eo("creating pins"),await this.pins.pinstore.open(),this.closed=!1,Eo("all opened")}catch(e){if(this._lockfile)try{await this._closeLock(),this._lockfile=null}catch(t){Eo("error removing lock",t)}throw e}}async _openRoot(){try{await this.root.open()}catch(e){if(e.message!=="Already open")throw e}}async _openLock(){let e=await this.options.repoLock.lock(this.path);if(typeof e.close!="function")throw(0,Np.default)(new Error("Locks must have a close method"),"ERR_NO_CLOSE_FUNCTION");return e}_closeLock(){return this._lockfile&&this._lockfile.close()}async _checkInitialized(){Eo("init check");let e;try{[e]=await Promise.all([this.config.exists(),this.spec.exists(),this.version.exists()])}catch(t){throw t.code==="ERR_NOT_FOUND"?(0,Np.default)(new Error("repo is not initialized yet"),Pp,{path:this.path}):t}if(!e)throw(0,Np.default)(new Error("repo is not initialized yet"),Pp,{path:this.path})}async close(){if(this.closed)throw(0,Np.default)(new Error("repo is already closed"),wie);Eo("closing at: %s",this.path);try{await this.apiAddr.delete()}catch(e){if(e.code!==Pp&&!e.message.startsWith("ENOENT"))throw e}await Promise.all([this.root,this.blocks,this.keys,this.datastore,this.pins.pinstore].map(e=>e&&e.close())),Eo("unlocking"),this.closed=!0,await this._closeLock()}exists(){return this.version.exists()}async stat(){if(this.datastore&&this.keys){let[e,t,n,i,o]=await Promise.all([this._storageMaxStat(),this._blockStat(),this.version.get(),Hie(this.datastore),Hie(this.keys)]),s=t.size+i+o;return{repoPath:this.path,storageMax:e,version:n,numObjects:t.count,repoSize:s}}throw(0,Np.default)(new Error("repo is not initialized yet"),Pp,{path:this.path})}async _isAutoMigrationEnabled(){if(this.options.autoMigrate!==void 0)return this.options.autoMigrate;let e;try{e=await this.config.get(nOe)}catch(t){if(t.code===cs.code)e=!0;else throw t}return e}async _migrate(e,t){return await this.version.get()>e?(Eo(`reverting to version ${e}`),die(this.path,t,this.options,e,{ignoreLock:!0,onProgress:this.options.onMigrationProgress})):(Eo(`migrating to version ${e}`),fie(this.path,t,this.options,e,{ignoreLock:!0,onProgress:this.options.onMigrationProgress}))}async _storageMaxStat(){try{let e=await this.config.get("Datastore.StorageMax");return BigInt((0,jie.default)(e))}catch{return BigInt(rOe)}}async _blockStat(){let e=BigInt(0),t=BigInt(0);if(this.blocks)for await(let{key:n,value:i}of this.blocks.query({}))e+=BigInt(1),t+=BigInt(i.byteLength),t+=BigInt(n.bytes.byteLength);return{count:e,size:t}}};async function Hie(r){let e=BigInt(0);for await(let t of r.query({}))e+=BigInt(t.value.byteLength),e+=BigInt(t.key.uint8Array().byteLength);return e}function Wie(r,e,t,n){return new kD(r,e,t,n)}function iOe(r){return r.Datastore=Object.assign({},pD,zw(r,"datastore")),r}function oOe(r){let e={...pD.Spec,...zw(r,"Datastore.Spec")};return{type:e.type,mounts:e.mounts.map(t=>({mountpoint:t.mountpoint,type:t.child.type,path:t.child.path,shardFunc:t.child.shardFunc}))}}async function*Id(r,e){yield*(await Wo(r)).sort(e)}var Rse=C(Ise(),1),Ud=class extends go{constructor(e,t={}){super(),this.db=typeof e=="string"?new Rse.Level(e,{...t,keyEncoding:"utf8",valueEncoding:"view"}):e,this.opts={createIfMissing:!0,compression:!1,...t}}async open(){try{await this.db.open(this.opts)}catch(e){throw Vo.dbOpenFailedError(e)}}async put(e,t){try{await this.db.put(e.toString(),t)}catch(n){throw Vo.dbWriteFailedError(n)}}async get(e){let t;try{t=await this.db.get(e.toString())}catch(n){throw n.notFound?Vo.notFoundError(n):Vo.dbWriteFailedError(n)}return t}async has(e){try{await this.db.get(e.toString())}catch(t){if(t.notFound)return!1;throw t}return!0}async delete(e){try{await this.db.del(e.toString())}catch(t){throw Vo.dbDeleteFailedError(t)}}close(){return this.db&&this.db.close()}batch(){let e=[];return{put:(t,n)=>{e.push({type:"put",key:t.toString(),value:n})},delete:t=>{e.push({type:"del",key:t.toString()})},commit:()=>this.db.batch(e)}}query(e){let t=this._query({values:!0,prefix:e.prefix});Array.isArray(e.filters)&&(t=e.filters.reduce((o,s)=>Yt(o,s),t)),Array.isArray(e.orders)&&(t=e.orders.reduce((o,s)=>Id(o,s),t));let{offset:n,limit:i}=e;if(n){let o=0;t=Yt(t,()=>o++>=n)}return i&&(t=Ga(t,i)),t}queryKeys(e){let t=Bi(this._query({values:!1,prefix:e.prefix}),({key:o})=>o);Array.isArray(e.filters)&&(t=e.filters.reduce((o,s)=>Yt(o,s),t)),Array.isArray(e.orders)&&(t=e.orders.reduce((o,s)=>Id(o,s),t));let{offset:n,limit:i}=e;if(n){let o=0;t=Yt(t,()=>o++>=n)}return i&&(t=Ga(t,i)),t}_query(e){let t={keys:!0,keyEncoding:"buffer",values:e.values};if(e.prefix!=null){let i=e.prefix.toString();t.gte=i,t.lt=i+"\xFF"}let n=this.db.iterator(t);if(n[Symbol.asyncIterator])return $Le(n);if(n.next!=null&&n.end!=null)return qLe(n);throw new Error("Level returned incompatible iterator")}};async function*$Le(r){for await(let[e,t]of r)yield{key:new pe(e,!1),value:t};await r.close()}function qLe(r){return{[Symbol.asyncIterator](){return{next:()=>new Promise((e,t)=>{r.next((n,i,o)=>{if(n)return t(n);if(i==null)return r.end(s=>{if(s)return t(s);e({done:!0,value:void 0})});e({done:!1,value:{key:new pe(i,!1),value:o}})})}),return:()=>new Promise((e,t)=>{r.end(n=>{if(n)return t(n);e({done:!0,value:void 0})})})}}}}var Pse=C(ee(),1);var Cse=(r,e)=>async function*(){yield*(await Wo(r)).sort(e)}(),uu=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,t,n){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(let{key:n,value:i}of e)await this.put(n,i,t),yield{key:n,value:i}}async*getMany(e,t={}){for await(let n of e)yield this.get(n,t)}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await on(this.putMany(e,n)),e=[],await on(this.deleteMany(t,n)),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 n=this._all(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.key.toString().startsWith(e.prefix||""))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cse(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=(e.offset||0))}return e.limit!=null&&(n=Ga(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null&&(n=Yt(n,i=>i.toString().startsWith(e.prefix||""))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Yt(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cse(i,o),n)),e.offset!=null){let i=0;n=Yt(n,()=>i++>=e.offset)}return e.limit!=null&&(n=Ga(n,e.limit)),n}};function P2(r){let e=ce.asCID(r);if(!e)throw(0,Pse.default)(new Error("Not a valid cid"),"ERR_INVALID_CID");return new pe("/"+Ot.encode(e.multihash.bytes).slice(1).toUpperCase(),!1)}function Fd(r){return ce.createV1(Sc,Jn(Ot.decode("b"+r.toString().slice(1).toLowerCase())))}function DO(r){let e=r.substring(0,1);if(e==="/")return DO(r.substring(1));let t;e.toLowerCase()==="b"?t=o=>Ot.decode(o.toLowerCase()).subarray(2):e.toLowerCase()==="c"?t=o=>kT.decode(o.toLowerCase()).subarray(2):e==="z"?t=o=>tt.decode(o).subarray(2):e==="Q"?t=o=>tt.decode("z"+o):t=o=>Ot.decode("b"+o.toLowerCase()).subarray(2);let n;for(let o=1;ot=>e({key:Fd(t.key),value:t.value})):void 0,orders:r.orders?r.orders.map(e=>(t,n)=>e({key:Fd(t.key),value:t.value},{key:Fd(n.key),value:n.value})):void 0}}function GLe(r){return{...r,prefix:r.prefix?DO(r.prefix):void 0,filters:r.filters?r.filters.map(e=>t=>e(Fd(t))):void 0,orders:r.orders?r.orders.map(e=>(t,n)=>e(Fd(t),Fd(n))):void 0}}var fv=class extends uu{constructor(e){super(),this.child=e}open(){return this.child.open()}close(){return this.child.close()}async*query(e,t){for await(let{key:n,value:i}of this.child.query(HLe(e),t))yield{key:Fd(n),value:i}}async*queryKeys(e,t){for await(let n of this.child.queryKeys(GLe(e),t))yield Fd(n)}async get(e,t){return this.child.get(P2(e),t)}async*getMany(e,t){for await(let n of e)yield this.get(n,t)}async put(e,t,n){await this.child.put(P2(e),t,n)}async*putMany(e,t){let n=jn({objectMode:!0});(globalThis.process&&globalThis.process.nextTick?globalThis.process.nextTick:globalThis.setImmediate||globalThis.setTimeout)(async()=>{try{let o=this.child;await on(this.child.putMany(async function*(){for await(let s of e){let a=P2(s.key);await o.has(a,t)||(yield{key:a,value:s.value}),n.push(s)}}())),n.end()}catch(o){n.end(o)}}),yield*n}has(e,t){return this.child.has(P2(e),t)}delete(e,t){return this.child.delete(P2(e),t)}deleteMany(e,t){let n=jn({objectMode:!0});return on(this.child.deleteMany(async function*(){for await(let i of e)yield P2(i),n.push(i);n.end()}(),t)).catch(i=>{n.end(i)}),n}};function kse(r,e,t){let n=t.path||"ipfs";return Wie(n,i=>e.getCodec(i),{root:new Ud(n,{prefix:"",version:2}),blocks:new fv(new Ud(`${n}/blocks`,{prefix:"",version:2})),datastore:new Ud(`${n}/datastore`,{prefix:"",version:2}),keys:new Ud(`${n}/keys`,{prefix:"",version:2}),pins:new Ud(`${n}/pins`,{prefix:"",version:2})},{autoMigrate:t.autoMigrate,onMigrationProgress:t.onMigrationProgress||r,repoLock:k7})}var lr=C(v_(),1);var Ige=C(ee(),1);function dv(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var Nse=4294967296,Vi=class{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new Vi(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new Vi(t,n)}toBytes(e,t=0){let n=dv(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new Vi;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>Nse&&(i=0,++n>Nse&&(n=0))),new Vi(n,i)}static fromNumber(e){if(e===0)return new Vi;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new Vi(i,n)}static fromBytes(e,t=0){let n=dv(e),i=new Vi,o=0;if(e.length-t>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(t)&127)<>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;o=0}else for(;o<4;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;o<5;++o)if(i.hi=(i.hi|(n.get(t)&127)<>>0,n.get(t++)<128)return i}else if(t=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var jLe=Math.pow(2,7),WLe=Math.pow(2,14),YLe=Math.pow(2,21),QLe=Math.pow(2,28),XLe=Math.pow(2,35),ZLe=Math.pow(2,42),JLe=Math.pow(2,49),eBe=Math.pow(2,56),tBe=Math.pow(2,63),Yp={encodingLength(r){return rNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=vf(Yp.encodingLength(r))),Vi.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return Vi.fromBytes(r,e).toNumber(!0)}};var Dse={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var S5;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(S5||(S5={}));var A5=class{constructor(e){B(this,"peerId");B(this,"payloadType");B(this,"payload");B(this,"signature");B(this,"marshaled");let{peerId:t,payloadType:n,payload:i,signature:o}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=S5.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return mt(this.marshal(),e.marshal())}async validate(e){let t=Ose(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Bs(this.peerId.publicKey).verify(t.subarray(),this.signature)}},zd=A5;B(zd,"createFromProtobuf",async e=>{let t=S5.decode(e),n=await Hn(t.publicKey);return new A5({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})}),B(zd,"seal",async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,i=e.codec,o=e.marshal(),s=Ose(n,i,o),c=await(await Li(t.privateKey)).sign(s.subarray());return new A5({peerId:t,payloadType:i,payload:o,signature:c})}),B(zd,"openAndCertify",async(e,t)=>{let n=await A5.createFromProtobuf(e);if(!await n.validate(t))throw new J("envelope signature is not valid for the given domain",Dse.ERR_SIGNATURE_NOT_VALID);return n});var Ose=(r,e,t)=>{let n=Ie(r),i=Yp.encode(n.byteLength),o=Yp.encode(e.length),s=Yp.encode(t.length);return new vt(i,n,o,e,s,t)};var rBe=Uint8Array.from([3,1]);var OO;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=kn((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>Pn(o,n.codec()),n.decode=o=>Cn(o,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=kn((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),t),r.encode=n=>Pn(n,r.codec()),r.decode=n=>Cn(n,r.codec())})(OO||(OO={}));var LO=Symbol.for("@libp2p/topology");var Lse=()=>{},nBe,BO=class{constructor(e){B(this,"min");B(this,"max");B(this,"peers");B(this,"onConnect");B(this,"onDisconnect");B(this,"registrar");B(this,nBe,!0);this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??Lse,this.onDisconnect=e.onDisconnect??Lse}get[Symbol.toStringTag](){return LO.toString()}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};nBe=LO;function hv(r){return new BO(r)}var lu,Ki=class extends EventTarget{constructor(){super(...arguments);bt(this,lu,new Map)}listenerCount(t){let n=ge(this,lu).get(t);return n==null?0:n.length}addEventListener(t,n,i){super.addEventListener(t,n,i);let o=ge(this,lu).get(t);o==null&&(o=[],ge(this,lu).set(t,o)),o.push({callback:n,once:(i!==!0&&i!==!1&&(i==null?void 0:i.once))??!1})}removeEventListener(t,n,i){super.removeEventListener(t.toString(),n??null,i);let o=ge(this,lu).get(t);o!=null&&(o=o.filter(({callback:s})=>s!==n),ge(this,lu).set(t,o))}dispatchEvent(t){let n=super.dispatchEvent(t),i=ge(this,lu).get(t.type);return i==null||(i=i.filter(({once:o})=>!o),ge(this,lu).set(t.type,i)),n}safeDispatchEvent(t,n){return this.dispatchEvent(new cn(t,n))}};lu=new WeakMap;var MO=class extends Event{constructor(t,n){super(t,n);B(this,"detail");this.detail=n==null?void 0:n.detail}},cn=globalThis.CustomEvent??MO;var pv=class{constructor(e,t,n){this.gossip=e,this.msgs=new Map,this.history=[],this.notValidatedCount=0,this.msgIdToStrFn=n;for(let i=0;i{let o=this.msgs.get(i.msgIdStr);if(o&&o.validated&&e.has(i.topic)){let s=t.get(i.topic);s||(s=[],t.set(i.topic,s)),s.push(i.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(!t)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:i}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:i}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t?(this.msgs.delete(e),t):null}};var pae=C(hae(),1),{RPC:P5}=pae.default;var XO="/floodsub/1.0.0",ZO="/meshsub/1.0.0",JO="/meshsub/1.1.0";var mae="ERR_TOPIC_VALIDATOR_REJECT",gae="ERR_TOPIC_VALIDATOR_IGNORE";function hu(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},hBe={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function bae(r={}){return{...dBe,...r,topics:r.topics?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=pBe(n),e),{}):{}}}function pBe(r={}){return{...hBe,...r}}function _ae(r){for(let[e,t]of Object.entries(r.topics))try{mBe(t)}catch(n){throw new J(`invalid score parameters for topic ${e}: ${n.message}`,br)}if(r.topicScoreCap<0)throw new J("invalid topic score cap; must be positive (or 0 for no cap)",br);if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new J("missing application specific score function",br);if(r.IPColocationFactorWeight>0)throw new J("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",br);if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new J("invalid IPColocationFactorThreshold; must be at least 1",br);if(r.behaviourPenaltyWeight>0)throw new J("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",br);if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new J("invalid BehaviourPenaltyDecay; must be between 0 and 1",br);if(r.decayInterval<1e3)throw new J("invalid DecayInterval; must be at least 1s",br);if(r.decayToZero<=0||r.decayToZero>=1)throw new J("invalid DecayToZero; must be between 0 and 1",br)}function mBe(r){if(r.topicWeight<0)throw new J("invalid topic weight; must be >= 0",br);if(r.timeInMeshQuantum===0)throw new J("invalid TimeInMeshQuantum; must be non zero",br);if(r.timeInMeshWeight<0)throw new J("invalid TimeInMeshWeight; must be positive (or 0 to disable)",br);if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new J("invalid TimeInMeshQuantum; must be positive",br);if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new J("invalid TimeInMeshCap; must be positive",br);if(r.firstMessageDeliveriesWeight<0)throw new J("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",br);if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new J("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",br);if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new J("invalid FirstMessageDeliveriesCap; must be positive",br);if(r.meshMessageDeliveriesWeight>0)throw new J("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",br);if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new J("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",br);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new J("invalid MeshMessageDeliveriesCap; must be positive",br);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new J("invalid MeshMessageDeliveriesThreshold; must be positive",br);if(r.meshMessageDeliveriesWindow<0)throw new J("invalid MeshMessageDeliveriesWindow; must be non-negative",br);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new J("invalid MeshMessageDeliveriesActivation; must be at least 1s",br);if(r.meshFailurePenaltyWeight>0)throw new J("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",br);if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new J("invalid MeshFailurePenaltyDecay; must be between 0 and 1",br);if(r.invalidMessageDeliveriesWeight>0)throw new J("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",br);if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new J("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",br)}var gBe={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Eae(r={}){return{...gBe,...r}}function vae(r,e,t,n){let i=0;Object.entries(e.topics).forEach(([s,a])=>{let c=t.topics[s];if(c===void 0)return;let u=0;if(a.inMesh){let d=a.meshTime/c.timeInMeshQuantum;d>c.timeInMeshCap&&(d=c.timeInMeshCap),u+=d*c.timeInMeshWeight}let l=a.firstMessageDeliveries;if(l>c.firstMessageDeliveriesCap&&(l=c.firstMessageDeliveriesCap),u+=l*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries0&&i>t.topicScoreCap&&(i=t.topicScoreCap);let o=t.appSpecificScore(r);if(i+=o*t.appSpecificWeight,e.knownIPs.forEach(s=>{if(t.IPColocationFactorWhitelist.has(s))return;let a=n.get(s),c=a?a.size:0;if(c>t.IPColocationFactorThreshold){let u=c-t.IPColocationFactorThreshold,l=u*u;i+=l*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let s=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=s*s;i+=a*t.behaviourPenaltyWeight}return i}var Aae=C(Sae(),1),co;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(co||(co={}));var yv=class{constructor(){this.records=new Map,this.queue=new Aae.default}ensureRecord(e){let t=this.records.get(e);if(t)return t;t={status:co.unknown,firstSeen:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t&&t.expire!0){let n=new Set;if(e<=0)return n;for(let i of r){if(n.size>=e)break;t(i)&&(n.add(i),r.delete(i))}return n}function Tae(r,e){return bv(r,e,()=>!0)}var wv=class extends Map{constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};var N2=j("libp2p:gossipsub:score"),_v=class{constructor(e,t,n){this.params=e,this.metrics=t,this.peerStats=new Map,this.peerIPs=new wv(()=>new Set),this.scoreCache=new Map,this.deliveryRecords=new yv,_ae(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??vae}get size(){return this.peerStats.size}start(){if(this._backgroundInterval){N2("Peer score already running");return}this._backgroundInterval=setInterval(()=>this.background(),this.params.decayInterval),N2("started")}stop(){if(!this._backgroundInterval){N2("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),N2("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,i)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(i,n.knownIPs),this.peerStats.delete(i),this.scoreCache.delete(i));return}Object.entries(n.topics).forEach(([o,s])=>{let a=this.params.topics[o];a!==void 0&&(s.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,s.firstMessageDeliveriesa.meshMessageDeliveriesActivation&&(s.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenaltyn)return i.score;(c=this.metrics)==null||c.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),s=n+this.scoreCacheValidityMs;return i?((u=this.metrics)==null||u.scoreCachedDelta.observe(Math.abs(o-i.score)),i.score=o,i.cacheUntil=s):this.scoreCache.set(e,{score:o,cacheUntil:s}),o}addPenalty(e,t,n){var o;let i=this.peerStats.get(e);i&&(i.behaviourPenalty+=t,(o=this.metrics)==null||o.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n&&n.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n&&n.knownIPs.delete(t);let i=this.peerIPs.get(t);i&&(i.delete(e),i.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,i])=>{i.firstMessageDeliveries=0;let o=this.params.topics[n].meshMessageDeliveriesThreshold;if(i.inMesh&&i.meshMessageDeliveriesActive&&i.meshMessageDeliveries{s!==e.toString()&&this.markDuplicateMessageDelivery(s,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,i){switch(i){case ao.Error:this.markInvalidMessageDelivery(e,n);return;case ao.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==co.unknown){N2("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeen,co[o.status]);return}if(i===ao.Ignore){o.status=co.ignored,o.peers.clear();return}o.status=co.invalid,this.markInvalidMessageDelivery(e,n),o.peers.forEach(s=>{this.markInvalidMessageDelivery(s,n)}),o.peers.clear()}duplicateMessage(e,t,n){let i=this.deliveryRecords.ensureRecord(t);if(!i.peers.has(e))switch(i.status){case co.unknown:i.peers.add(e);break;case co.valid:i.peers.add(e),this.markDuplicateMessageDelivery(e,n,i.validated);break;case co.invalid:this.markInvalidMessageDelivery(e,n);break;case co.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);i&&(i.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);if(i){let o=this.params.topics[t].firstMessageDeliveriesCap;i.firstMessageDeliveries=Math.min(o,i.firstMessageDeliveries+1),i.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,i.meshMessageDeliveries=Math.min(o,i.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){var o;let i=this.peerStats.get(e);if(i){let s=n!==void 0?Date.now():0,a=this.getPtopicStats(i,t);if(a&&a.inMesh){let c=this.params.topics[t];if(n!==void 0){let l=s-n,f=l>c.meshMessageDeliveriesWindow;if((o=this.metrics)==null||o.onDuplicateMsgDelivery(t,l,f),f)return}let u=c.meshMessageDeliveriesCap;a.meshMessageDeliveries=Math.min(u,a.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let i=this.peerIPs.get(n);i&&(i.delete(e),i.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};var Ev=class{constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.promises=new Map,this.requestMsByMsg=new Map,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),i=t[n],o=this.msgIdToStrFn(i),s=this.promises.get(o);s||(s=new Map,this.promises.set(o,s));let a=Date.now();s.has(e)||(s.set(e,a+this.gossipsubIWantFollowupMs),this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){var i;let e=Date.now(),t=new Map,n=0;return this.promises.forEach((o,s)=>{o.forEach((a,c)=>{a=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Iae;(function(r){r.forward="forward",r.publish="publish"})(Iae||(Iae={}));var Tl;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Tl||(Tl={}));var Jp;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Unsub="unsubscribed",r.Excess="excess"})(Jp||(Jp={}));var L2;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(L2||(L2={}));var B2;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(B2||(B2={}));var O2;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(O2||(O2={}));function Rae(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEvents:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_total",help:"Number of times we include peers in a topic mesh for different reasons",labelNames:["topic","reason"]}),meshPeerChurnEvents:r.gauge({name:"gossipsub_peer_churn_events_total",help:"Number of times we remove peers in a topic mesh for different reasons",labelNames:["topic","reason"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),asyncValidationResult:r.gauge({name:"gossipsub_async_validation_result_total",help:"Message validation result for each topic",labelNames:["topic","acceptance"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeers:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),msgPublishPeersByGroup:r.gauge({name:"gossipsub_msg_publish_peers_by_group",help:"Total count of peers (by group) that we publish a msg to",labelNames:["topic","peerGroup"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),msgReceivedStatus:r.gauge({name:"gossipsub_msg_received_status_total",help:"Tracks distribution of recv msgs by duplicate, invalid, valid",labelNames:["topic","status"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["topic","error"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,1*t.maxMeshMessageDeliveriesWindowSec,2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores",labelNames:["topic","p"]}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,1*t.behaviourPenaltyThreshold,2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,1*t.gossipPromiseExpireSec,2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,i,o){let s=this.toTopic(n);this.meshPeerInclusionEvents.inc({topic:s,reason:i},o)},onRemoveFromMesh(n,i,o){let s=this.toTopic(n);this.meshPeerChurnEvents.inc({topic:s,reason:i},o)},onReportValidationMcacheHit(n){this.asyncValidationMcacheHit.inc({hit:n?"hit":"miss"})},onReportValidation(n,i){let o=this.toTopic(n);this.asyncValidationResult.inc({topic:o,acceptance:i})},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,i,o){let s=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:s},i),this.ihaveRcvNotSeenMsgids.inc({topic:s},o)},onIwantRcv(n,i){for(let[o,s]of n){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},s)}this.iwantRcvDonthaveMsgids.inc(i)},onForwardMsg(n,i){let o=this.toTopic(n);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},i)},onPublishMsg(n,i,o,s){let a=this.toTopic(n);this.msgPublishCount.inc({topic:a},1),this.msgPublishBytes.inc({topic:a},o*s),this.msgPublishPeers.inc({topic:a},o),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"direct"},i.direct),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"floodsub"},i.floodsub),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"mesh"},i.mesh),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"fanout"},i.fanout)},onMsgRecvPreValidation(n){let i=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:i},1)},onMsgRecvError(n){let i=this.toTopic(n);this.msgReceivedError.inc({topic:i},1)},onMsgRecvResult(n,i){let o=this.toTopic(n);this.msgReceivedStatus.inc({topic:o,status:i})},onMsgRecvInvalid(n,i){let o=this.toTopic(n),s=i.reason===ao.Error?i.error:i.reason;this.msgReceivedInvalid.inc({topic:o,error:s},1)},onDuplicateMsgDelivery(n,i,o){if(this.duplicateMsgDeliveryDelay.observe(i/1e3),o){let s=this.toTopic(n);this.duplicateMsgLateDelivery.inc({topic:s},1)}},onPublishDuplicateMsg(n){let i=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:i},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,i){this.rpcRecvBytes.inc(i),this.rpcRecvCount.inc(1),n.subscriptions&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages&&this.rpcRecvMessage.inc(n.messages.length),n.control&&(this.rpcRecvControl.inc(1),n.control.ihave&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,i){var o,s,a,c;if(this.rpcSentBytes.inc(i),this.rpcSentCount.inc(1),n.subscriptions&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages&&this.rpcSentMessage.inc(n.messages.length),n.control){let u=((o=n.control.ihave)==null?void 0:o.length)??0,l=((s=n.control.iwant)==null?void 0:s.length)??0,f=((a=n.control.graft)==null?void 0:a.length)??0,h=((c=n.control.prune)==null?void 0:c.length)??0;u>0&&this.rpcSentIHave.inc(u),l>0&&this.rpcSentIWant.inc(l),f>0&&this.rpcSentGraft.inc(f),h>0&&this.rpcSentPrune.inc(h),(u>0||l>0||f>0||h>0)&&this.rpcSentControl.inc(1)}},registerScores(n,i){let o=0,s=0,a=0,c=0;for(let u of n)u>=i.graylistThreshold&&o++,u>=i.publishThreshold&&s++,u>=i.gossipThreshold&&a++,u>=0&&c++;this.peersByScoreThreshold.set({threshold:O2.graylist},o),this.peersByScoreThreshold.set({threshold:O2.publish},s),this.peersByScoreThreshold.set({threshold:O2.gossip},a),this.peersByScoreThreshold.set({threshold:O2.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[i,o]of n.byTopic)this.scoreWeights.set({topic:i,p:"p1"},o.p1w),this.scoreWeights.set({topic:i,p:"p2"},o.p2w),this.scoreWeights.set({topic:i,p:"p3"},o.p3w),this.scoreWeights.set({topic:i,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:i,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,i){let o=new Map;n.forEach((s,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",u=o.get(c);u||(u=new Set,o.set(c,u)),s.forEach(l=>u==null?void 0:u.add(l))});for(let[s,a]of o){let c=[];a.forEach(u=>{c.push(i.get(u)??0)}),this.scorePerMesh.set({topic:s},c)}}}}var j9t=C(Nh(),1),wBe=C(at(),1);var EBe=C(bb(),1),vBe=C(gr(),1);var Cae=Ie("libp2p-pubsub:");async function Pae(r,e,t,n){switch(r.type){case qd.Signing:{let i={from:r.author.toBytes(),data:n,seqno:Mc(8),topic:e,signature:void 0,key:void 0},o=rt([Cae,P5.Message.encode(i).finish()]);i.signature=await r.privateKey.sign(o),i.key=r.key;let s={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${re(i.seqno,"base16")}`),topic:e,signature:i.signature,key:i.key};return{raw:i,msg:s}}case qd.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}}}}async function kae(r,e){switch(r){case k2:return e.signature!=null?{valid:!1,error:$i.SignaturePresent}:e.seqno!=null?{valid:!1,error:$i.SeqnoPresent}:e.key!=null?{valid:!1,error:$i.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Zp:{if(e.seqno==null)return{valid:!1,error:$i.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:$i.InvalidSeqno};if(e.signature==null)return{valid:!1,error:$i.InvalidSignature};if(e.from==null)return{valid:!1,error:$i.InvalidPeerId};let t;try{t=Di(e.from)}catch{return{valid:!1,error:$i.InvalidPeerId}}let n;if(e.key){if(n=Bs(e.key),t.publicKey!==void 0&&!mt(n.bytes,t.publicKey))return{valid:!1,error:$i.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:$i.InvalidPeerId};n=Bs(t.publicKey)}let i={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=rt([Cae,P5.Message.encode(i).finish()]);return await n.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${re(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:e.key??a3(n)}}:{valid:!1,error:$i.InvalidSignature}}}}var Nae=(r,e)=>{let t=Ie(e.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),n};function Dae(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return Nae(r.from.toBytes(),r.sequenceNumber)}async function Oae(r){return await dt.encode(r.data)}function xBe(r,e,t,n,i){let o=0,s=new Map;if(Object.entries(e.topics).forEach(([h,d])=>{let p=i.get(h)??"unknown",g=t.topics[h];if(g===void 0)return;let w=s.get(p);w||(w={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},s.set(p,w));let _=0,x=0,m=0,y=0,b=0;if(d.inMesh){let A=Math.max(d.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);_+=A*g.timeInMeshWeight}let E=d.firstMessageDeliveries;if(E>g.firstMessageDeliveriesCap&&(E=g.firstMessageDeliveriesCap),x+=E*g.firstMessageDeliveriesWeight,d.meshMessageDeliveriesActive&&d.meshMessageDeliveries0&&o>t.topicScoreCap){o=t.topicScoreCap;let h=t.topicScoreCap/o;for(let d of s.values())d.p1w*=h,d.p2w*=h,d.p3w*=h,d.p3bw*=h,d.p4w*=h}let a=0,c=0,u=0,l=t.appSpecificScore(r);a+=l*t.appSpecificWeight,e.knownIPs.forEach(h=>{if(t.IPColocationFactorWhitelist.has(h))return;let d=n.get(h),p=d?d.size:0;if(p>t.IPColocationFactorThreshold){let g=p-t.IPColocationFactorThreshold,w=g*g;c+=w*t.IPColocationFactorWeight}});let f=e.behaviourPenalty*e.behaviourPenalty;return u+=f*t.behaviourPenaltyWeight,o+=a+c+u,{byTopic:s,p5w:a,p6w:c,p7w:u,score:o}}function Lae(r,e,t,n,i){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let s of r){let a=e.get(s);if(a){let c=xBe(s,a,t,n,i);for(let[u,l]of c.byTopic){let f=o.byTopic.get(u);f||(f={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(u,f)),f.p1w.push(l.p1w),f.p2w.push(l.p2w),f.p3w.push(l.p3w),f.p3bw.push(l.p3bw),f.p4w.push(l.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var vv=class{constructor(e){B(this,"buffer");B(this,"mask");B(this,"top");B(this,"btm");B(this,"next");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 this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},M2=class{constructor(e={}){B(this,"size");B(this,"hwm");B(this,"head");B(this,"tail");this.hwm=e.splitLimit??16,this.head=new vv(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return(e==null?void 0:e.byteLength)!=null?e.byteLength:1}push(e){if((e==null?void 0:e.value)!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new vv(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return(e==null?void 0:e.value)!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var rL=class extends Error{constructor(t,n){super(t??"The operation was aborted");B(this,"type");B(this,"code");this.type="aborted",this.code=n??"ABORT_ERR"}};function Ao(r={}){return Mae(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Bae(r={}){return Mae(t=>{let n,i=[];for(;!t.isEmpty()&&(n=t.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&i.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:i}},r)}function Mae(r,e){e=e??{};let t=e.onEnd,n=new M2,i,o,s,a=Qt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,_)=>{o=x=>{o=null,n.push(x);try{w(r(n))}catch(m){_(m)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Qt()})}},u=w=>o!=null?o(w):(n.push(w),i),l=w=>(n=new M2,o!=null?o({error:w}):(n.push({error:w}),i)),f=w=>{if(s)return i;if((e==null?void 0:e.objectMode)!==!0&&(w==null?void 0:w.byteLength)==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},h=w=>s?i:(s=!0,w!=null?l(w):u({done:!0})),d=()=>(n=new M2,h(),{done:!0}),p=w=>(h(w),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:h,get readableLength(){return n.size},onEmpty:async w=>{let _=w==null?void 0:w.signal;if(_==null||_.throwIfAborted(),n.isEmpty())return;let x,m;_!=null&&(x=new Promise((y,b)=>{m=()=>{b(new rL)},_.addEventListener("abort",m)}));try{await Promise.race([a.promise,x])}finally{m!=null&&_!=null&&(_==null||_.removeEventListener("abort",m))}}},t==null)return i;let g=i;return i={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return g.end(w),t!=null&&(t(w),t=void 0),i},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},i}var k5=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Uae(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function na(r,e,t){let n=t??{},i=Uae(r);async function*o(){let s,a=()=>{s!=null&&s()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new k5(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:d}=n;f(new k5(h,d))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function SBe(r,e,t){return n=>r(na(n,e,t))}function nL(r,e,t){return{sink:SBe(r.sink,e,{...t,onAbort:void 0}),source:na(r.source,e,t)}}var zae=Symbol.for("@achingbrain/uint8arraylist");function Fae(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(xv(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(xv(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Fae(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fae(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return yr(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:yr(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new ln;return o.length=i,o.bufs=n,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(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o=c)continue;let u=e>=a&&ea&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!xv(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=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),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ac(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=ju(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=ju(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=ju(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ac(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=ju(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=ju(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=ju(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=ju(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=ju(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof ln)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;ti+o.byteLength,0)),n.length=t,n}};var ABe=Math.pow(2,7),TBe=Math.pow(2,14),IBe=Math.pow(2,21),RBe=Math.pow(2,28),CBe=Math.pow(2,35),PBe=Math.pow(2,42),kBe=Math.pow(2,49),NBe=Math.pow(2,56),DBe=Math.pow(2,63),nc={encodingLength(r){return rNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Ac(nc.encodingLength(r))),Vi.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return Vi.fromBytes(r,e).toNumber(!0)}};function Vae(r){var e;return((e=globalThis==null?void 0:globalThis.Buffer)==null?void 0:e.allocUnsafe)!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var Sv=r=>{let e=nc.encodingLength(r),t=Vae(e);return nc.encode(r,t),Sv.bytes=e,t};Sv.bytes=0;function vn(r){r=r??{};let e=r.lengthEncoder??Sv;return async function*(n){for await(let i of n){let o=e(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}}}vn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Sv;return new ln(t(r.byteLength),r)};var N5=C(ee(),1),OBe=8,LBe=1024*1024*4,e0;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(e0||(e0={}));var iL=r=>{let e=nc.decode(r);return iL.bytes=nc.encodingLength(e),e};iL.bytes=0;function Xr(r){return async function*(t){let n=new ln,i=e0.LENGTH,o=-1,s=(r==null?void 0:r.lengthDecoder)??iL,a=(r==null?void 0:r.maxLengthLength)??OBe,c=(r==null?void 0:r.maxDataLength)??LBe;for await(let u of t)for(n.append(u);n.byteLength>0;){if(i===e0.LENGTH)try{if(o=s(n),o<0)throw(0,N5.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>c)throw(0,N5.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;n.consume(l),(r==null?void 0:r.onLength)!=null&&r.onLength(o),i=e0.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>a)throw(0,N5.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(i===e0.DATA){if(n.byteLength0)throw(0,N5.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}Xr.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return Xr({...e??{},onLength:o=>{t=o}})(n)};var Av=class{constructor(e,t,n){this.rawStream=e,this.pushable=Ao({objectMode:!1}),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,Ne(na(this.pushable,this.closeController.signal,{returnOnAbort:!0}),vn(),this.rawStream).catch(t)}get protocol(){return this.rawStream.stat.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}close(){this.closeController.abort(),this.pushable.return(),this.rawStream.close()}},Tv=class{constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.source=na(Ne(this.rawStream,Xr(t)),this.closeController.signal,{returnOnAbort:!0})}close(){this.closeController.abort(),this.rawStream.close()}};var Kae=C(QO(),1),$ae={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};function qae(r,e){e={...e};let t=Kae.default.Reader.create(r),n=r.length,i=n===void 0?t.len:t.pos+n,o={};for(;t.pos>>3){case 1:o.subscriptions&&o.subscriptions.length||(o.subscriptions=[]),o.subscriptions.length>>3){case 1:n.subscribe=r.bool();break;case 2:n.topic=r.string();break;default:r.skipType(i&7);break}}return n}function MBe(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.from=r.bytes();break;case 2:n.data=r.bytes();break;case 3:n.seqno=r.bytes();break;case 4:n.topic=r.string();break;case 5:n.signature=r.bytes();break;case 6:n.key=r.bytes();break;default:r.skipType(i&7);break}}if(!n.topic)throw Error("missing required 'topic'");return n}function UBe(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.ihave&&i.ihave.length||(i.ihave=[]),i.ihave.length>>3){case 1:i.topicID=r.string();break;case 2:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIhaveMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(o&7);break;default:r.skipType(o&7);break}}return i}function zBe(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIwantMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(o&7);break;default:r.skipType(o&7);break}}return i}function VBe(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.topicID=r.string();break;default:r.skipType(i&7);break}}return n}function KBe(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.topicID=r.string();break;case 2:i.peers&&i.peers.length||(i.peers=[]),t.maxPeerInfos-- >0?i.peers.push($Be(r,r.uint32())):r.skipType(o&7);break;case 3:i.backoff=r.uint64();break;default:r.skipType(o&7);break}}return i}function $Be(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.peerID=r.bytes();break;case 2:n.signedPeerRecord=r.bytes();break;default:r.skipType(i&7);break}}return n}var Iv;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(Iv||(Iv={}));function Hae(r){for(let e of r.tuples())switch(e[0]){case Iv.ip4:case Iv.ip6:return Sy(e[0],e[1])}return null}var ds;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(ds||(ds={}));var Rv=class extends Ki{constructor(e,t={}){super(),this.multicodecs=[JO,ZO],this.peers=new Set,this.streamsInbound=new Map,this.streamsOutbound=new Map,this.outboundInflightQueue=Ao({objectMode:!0}),this.direct=new Set,this.floodsubPeers=new Set,this.acceptFromWhitelist=new Map,this.topics=new Map,this.subscriptions=new Set,this.mesh=new Map,this.fanout=new Map,this.fanoutLastpub=new Map,this.gossip=new Map,this.control=new Map,this.peerhave=new Map,this.iasked=new Map,this.backoff=new Map,this.outbound=new Map,this.topicValidators=new Map,this.heartbeatTicks=0,this.directPeerInitial=null,this.status={code:ds.stopped},this.heartbeatTimer=null,this.runHeartbeat=()=>{var o;let i=(o=this.metrics)==null?void 0:o.heartbeatDuration.startTimer();this.heartbeat().catch(s=>{this.log("Error running heartbeat",s)}).finally(()=>{var s;if(i!=null&&i(),this.status.code===ds.started){clearTimeout(this.status.heartbeatTimeout);let a=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;ai.id.toString())),this.seenCache=new D2({validityMs:n.seenTTL}),this.publishedMessageIds=new D2({validityMs:n.seenTTL}),t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Zp:this.msgIdFn=Dae;break;case k2:this.msgIdFn=Oae;break}if(t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new D2({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??yae,this.mcache=t.messageCache||new pv(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform&&(this.dataTransform=t.dataTransform),t.metricsRegister){if(!t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");let i=Math.max(...Object.values(n.scoreParams.topics).map(s=>s.meshMessageDeliveriesWindow),1e3),o=Rae(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:i/1e3});o.mcacheSize.addCollect(()=>this.onScrapeMetrics(o));for(let s of this.multicodecs)o.protocolsEnabled.set({protocol:s},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new Ev(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new _v(this.opts.scoreParams,this.metrics,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.allowedTopics=n.allowedTopics?new Set(n.allowedTopics):null}getPeers(){return[...this.peers.keys()].map(e=>Oe(e))}isStarted(){return this.status.code===ds.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await tL(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=Ao({objectMode:!0}),Ne(this.outboundInflightQueue,async o=>{for await(let{peerId:s,connection:a}of o)await this.createOutboundStream(s,a)}).catch(o=>this.log.error("outbound inflight queue error",o)),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.addressBook.add(o.id,o.addrs)}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})));let t=hv({onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this)}),n=await Promise.all(this.multicodecs.map(o=>e.register(o,t))),i=setTimeout(this.runHeartbeat,100);this.status={code:ds.started,registrarTopologyIds:n,heartbeatTimeout:i,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>await this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==ds.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:ds.stopped};let t=this.components.registrar;e.forEach(n=>t.unregister(n)),this.outboundInflightQueue.end();for(let n of this.streamsOutbound.values())n.close();this.streamsOutbound.clear();for(let n of this.streamsInbound.values())n.close();this.streamsInbound.clear(),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache&&this.fastMsgIdCache.clear(),this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.stat.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){var n;(n=this.metrics)==null||n.newConnectionCount.inc({status:t.stat.status}),!(!this.isStarted()||t.stat.status!=="OPEN")&&(this.addPeer(e,t.stat.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){var i;if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let o=new Av(await t.newStream(this.multicodecs),a=>this.log.error("outbound pipe error",a),{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,o);let s=o.protocol;s===XO&&this.floodsubPeers.add(n),(i=this.metrics)==null||i.peersPerProtocol.inc({protocol:s},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(o){this.log.error("createOutboundStream error",o)}}async createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let i=this.streamsInbound.get(n);i!==void 0&&(this.log("replacing existing inbound steam %s",n),i.close()),this.log("create inbound stream %s",n);let o=new Tv(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,o),this.pipePeerReadStream(e,o.source).catch(s=>this.log(s))}addPeer(e,t,n){let i=e.toString();if(!this.peers.has(i)){this.log("new peer %p",e),this.peers.add(i),this.score.addPeer(i);let o=Hae(n);o!==null?this.score.addIP(i,o):this.log("Added peer has no IP in current address %s %s",i,n.toString()),this.outbound.has(i)||this.outbound.set(i,t==="outbound")}}removePeer(e){var o,s;let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),i=this.streamsInbound.get(t);n&&((o=this.metrics)==null||o.peersPerProtocol.inc({protocol:n.protocol},-1)),n==null||n.close(),i==null||i.close(),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let a of this.topics.values())a.delete(t);for(let[a,c]of this.mesh)c.delete(t)===!0&&((s=this.metrics)==null||s.onRemoveFromMesh(a,Jp.Dc,1));for(let a of this.fanout.values())a.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===ds.started}getMeshPeers(e){let t=this.mesh.get(e);return t?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t?Array.from(t):[]).map(n=>Oe(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){var n;try{await Ne(t,async i=>{var o,s,a;for await(let c of i)try{let u=c.subarray(),l=qae(u,this.decodeRpcLimits);if((o=this.metrics)==null||o.onRpcRecv(l,u.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,l)}catch(f){(s=this.metrics)==null||s.onRpcRecvError(),this.log(f)}else this.handleReceivedRpc(e,l).catch(f=>{var h;(h=this.metrics)==null||h.onRpcRecvError(),this.log(f)})}catch(u){(a=this.metrics)==null||a.onRpcDataError(),this.log(u)}})}catch(i){(n=this.metrics)==null||n.onPeerReadStreamError(),this.handlePeerReadStreamError(i,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){var u;if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),(u=this.metrics)==null||u.rpcRecvNotAccepted.inc();return}let n=t.subscriptions?t.subscriptions.length:0,i=t.messages?t.messages.length:0,o=0,s=0,a=0,c=0;if(t.control&&(t.control.ihave&&(o=t.control.ihave.length),t.control.iwant&&(s=t.control.iwant.length),t.control.graft&&(a=t.control.graft.length),t.control.prune&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${i} ihave ${o} iwant ${s} graft ${a} prune ${c}`),t.subscriptions&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(f=>{let h=f.topic,d=f.subscribe===!0;if(h!=null){if(this.allowedTopics&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,d),l.push({topic:h,subscribe:d})}}),this.dispatchEvent(new cn("subscription-change",{detail:{peerId:e,subscriptions:l}}))}if(t.messages)for(let l of t.messages){if(this.allowedTopics&&!this.allowedTopics.has(l.topic))continue;let f=this.handleReceivedMessage(e,l).catch(h=>{var d;(d=this.metrics)==null||d.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await f}t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let i=this.topics.get(t);i==null&&(i=new Set,this.topics.set(t,i)),n?i.add(e.toString()):i.delete(e.toString())}async handleReceivedMessage(e,t){var i,o,s;(i=this.metrics)==null||i.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);switch((o=this.metrics)==null||o.onMsgRecvResult(t.topic,n.code),n.code){case ra.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case ra.invalid:if(n.msgIdStr){let a=n.msgIdStr;this.score.rejectMessage(e.toString(),a,t.topic,n.reason),this.gossipTracer.rejectMessage(a,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);(s=this.metrics)==null||s.onMsgRecvInvalid(t.topic,n);return;case ra.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new cn("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new cn("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString())}}async validateReceivedMessage(e,t){var f,h,d;let n=(f=this.fastMsgIdFn)==null?void 0:f.call(this,t),i=n!==void 0?(h=this.fastMsgIdCache)==null?void 0:h.get(n):void 0;if(i)return{code:ra.duplicate,msgIdStr:i};let o=await kae(this.globalSignaturePolicy,t);if(!o.valid)return{code:ra.invalid,reason:ao.Error,error:o.error};let s=o.message;try{this.dataTransform&&(s.data=this.dataTransform.inboundTransform(t.topic,s.data))}catch(p){return this.log("Invalid message, transform failed",p),{code:ra.invalid,reason:ao.Error,error:$i.TransformFailed}}let a=await this.msgIdFn(s),c=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache&&this.fastMsgIdCache.put(n,c)&&((d=this.metrics)==null||d.fastMsgIdCacheCollision.inc()),this.seenCache.has(c))return{code:ra.duplicate,msgIdStr:c};this.seenCache.put(c);let l=this.topicValidators.get(t.topic);if(l!=null){let p;try{p=await l(e,s)}catch(g){let w=g.code;w===gae&&(p=rc.Ignore),w===mae?p=rc.Reject:p=rc.Ignore}if(p!==rc.Accept)return{code:ra.invalid,reason:eL(p),msgIdStr:c}}return{code:ra.valid,messageId:u,msg:s}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(i=>({topic:i,subscribe:n}))})}async handleControlMessage(e,t){var c,u;if(t===void 0)return;let n=t.ihave?this.handleIHave(e,t.ihave):[],i=t.iwant?this.handleIWant(e,t.iwant):[],o=t.graft?await this.handleGraft(e,t.graft):[];if(t.prune&&await this.handlePrune(e,t.prune),!n.length&&!i.length&&!o.length)return;let s=this.sendRpc(e,{messages:i,control:{iwant:n,prune:o}}),a=(c=n[0])==null?void 0:c.messageIDs;a&&(s?this.gossipTracer.addPromise(e,a):(u=this.metrics)==null||u.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let i=this.score.score(e);return i>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),i>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){var u,l,f;if(!t.length)return[];let n=this.score.score(e);if(n10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,i),(l=this.metrics)==null||l.ihaveRcvIgnored.inc({reason:B2.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),(f=this.metrics)==null||f.ihaveRcvIgnored.inc({reason:B2.MaxIasked}),[];let s=new Map;if(t.forEach(({topicID:h,messageIDs:d})=>{var g;if(!h||!d||!this.mesh.has(h))return;let p=0;d.forEach(w=>{let _=this.msgIdToStrFn(w);this.seenCache.has(_)||(s.set(_,w),p++)}),(g=this.metrics)==null||g.onIhaveRcv(h,d.length,p)}),!s.size)return[];let a=s.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,s.size,e);let c=Array.from(s.values());return hu(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){var a;if(!t.length)return[];let n=this.score.score(e);if(n{c&&c.forEach(u=>{let l=this.msgIdToStrFn(u),f=this.mcache.getWithIWantCount(l,e);if(f==null){s++;return}if(o.set(f.msg.topic,1+(o.get(f.msg.topic)??0)),f.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,u);return}i.set(l,f.msg)})}),(a=this.metrics)==null||a.onIwantRcv(o,s),i.size?(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values())):(this.log("IWANT: Could not provide any wanted messages to %s",e),[])}async handleGraft(e,t){let n=[],i=this.score.score(e),o=Date.now(),s=this.opts.doPX;return t.forEach(({topicID:a})=>{var l,f;if(!a)return;let c=this.mesh.get(a);if(!c){s=!1;return}if(c.has(e))return;if(this.direct.has(e)){this.log("GRAFT: ignoring request from direct peer %s",e),n.push(a),s=!1;return}let u=(l=this.backoff.get(a))==null?void 0:l.get(e);if(typeof u=="number"&&o=this.opts.Dhi&&!this.outbound.get(e)){n.push(a),this.addBackoff(e,a);return}this.log("GRAFT: Add mesh link from %s in %s",e,a),this.score.graft(e,a),c.add(e),(f=this.metrics)==null||f.onAddToMesh(a,Tl.Subscribed,1)}),n.length?await Promise.all(n.map(a=>this.makePrune(e,a,s))):[]}async handlePrune(e,t){var i;let n=this.score.score(e);for(let{topicID:o,backoff:s,peers:a}of t){if(o==null)continue;let c=this.mesh.get(o);if(!c)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,o),this.score.prune(e,o),c.has(e)&&(c.delete(e),(i=this.metrics)==null||i.onRemoveFromMesh(o,Jp.Unsub,1)),typeof s=="number"&&s>0?this.doAddBackoff(e,o,s*1e3):this.addBackoff(e,o),a&&a.length){if(n{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,L2.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((i,o)=>{i{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>await this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(hu(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(!n.peerID)return;let i=Di(n.peerID).toString();if(!this.peers.has(i)){if(!n.signedPeerRecord){t.push(i);return}try{let o=await zd.openAndCertify(n.signedPeerRecord,"libp2p-peer-record"),s=o.peerId;if(!o.peerId.equals(i)){this.log("bogus peer record obtained through px: peer ID %p doesn't match expected peer %p",s,i);return}if(!await this.components.peerStore.addressBook.consumePeerRecord(o)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(i)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length&&await Promise.all(t.map(async n=>await this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=Oe(e),n=await this.components.connectionManager.openConnection(t);for(let i of this.multicodecs)for(let o of this.components.registrar.getTopologies(i))o.onConnect(t,n)}subscribe(e){if(this.status.code!==ds.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==ds.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){var i,o,s;if(this.status.code!==ds.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),(i=this.metrics)==null||i.onJoin(e);let t=new Set,n=this.fanout.get(e);if(n&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(a=>{!this.direct.has(a)&&this.score.score(a)>=0&&t.add(a)}),(o=this.metrics)==null||o.onAddToMesh(e,Tl.Fanout,t.size)),t.size!t.has(u)&&!this.direct.has(u)&&this.score.score(u)>=0).forEach(u=>{t.add(u)}),(s=this.metrics)==null||s.onAddToMesh(e,Tl.Random,t.size-a)}this.mesh.set(e,t),t.forEach(a=>{this.log("JOIN: Add mesh link to %s in %s",a,e),this.sendGraft(a,e)})}leave(e){var n;if(this.status.code!==ds.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),(n=this.metrics)==null||n.onLeave(e);let t=this.mesh.get(e);t&&(Promise.all(Array.from(t).map(async i=>(this.log("LEAVE: Remove mesh link to %s in %s",i,e),await this.sendPrune(i,e)))).catch(i=>{this.log("Error sending prunes to mesh peers",i)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let i=new Set,o=this.topics.get(e);o&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(n!=null&&n.has(a))&&i.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(n!=null&&n.has(a))&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&i.add(a)}));let s=this.mesh.get(e);return s&&s.size>0&&s.forEach(a=>{t!==a&&!(n!=null&&n.has(a))&&i.add(a)}),i}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},i=this.topics.get(e);if(i)if(this.opts.floodPublish)i.forEach(o=>{this.direct.has(o)?(t.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});else{this.direct.forEach(s=>{i.has(s)&&(t.add(s),n.direct++)}),this.floodsubPeers.forEach(s=>{i.has(s)&&this.score.score(s)>=this.opts.scoreThresholds.publishThreshold&&(t.add(s),n.floodsub++)});let o=this.mesh.get(e);if(o&&o.size>0)o.forEach(s=>{t.add(s),n.mesh++});else{let s=this.fanout.get(e);if(s&&s.size>0)s.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,i){var s;n&&this.score.deliverMessage(n,e,t.topic);let o=this.selectPeersToForward(t.topic,n,i);o.forEach(a=>{this.sendRpc(a,{messages:[t]})}),(s=this.metrics)==null||s.onForwardMsg(t.topic,o.size)}async publish(e,t,n){var p,g;let i=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:o,msg:s}=await Pae(this.publishConfig,e,t,i),a=await this.msgIdFn(s),c=this.msgIdToStrFn(a),u=(n==null?void 0:n.ignoreDuplicatePublishError)??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(u)return(p=this.metrics)==null||p.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:l,tosendCount:f}=this.selectPeersToPublish(e),h=this.opts.emitSelf===!0&&this.subscriptions.has(e),d=(n==null?void 0:n.allowPublishToZeroPeers)??this.opts.allowPublishToZeroPeers;if(l.size===0&&!d&&!h)throw Error("PublishError.InsufficientPeers");this.seenCache.put(c),this.mcache.put({msgId:a,msgIdStr:c},o,!0),this.publishedMessageIds.put(c);for(let w of l)this.sendRpc(w,{messages:[o]})||l.delete(w);return(g=this.metrics)==null||g.onPublishMsg(e,f,l.size,o.data!=null?o.data.length:0),h&&(l.add(this.components.peerId.toString()),super.dispatchEvent(new cn("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:s}})),super.dispatchEvent(new cn("message",{detail:s}))),{recipients:Array.from(l.values()).map(w=>Oe(w))}}reportMessageValidationResult(e,t,n){var i,o,s,a;if(n===rc.Accept){let c=this.mcache.validate(e);if((i=this.metrics)==null||i.onReportValidationMcacheHit(c!==null),c!=null){let{message:u,originatingPeers:l}=c;this.score.deliverMessage(t.toString(),e,u.topic),this.forwardMessage(e,c.message,t.toString(),l),(o=this.metrics)==null||o.onReportValidation(u.topic,n)}}else{let c=this.mcache.remove(e);if((s=this.metrics)==null||s.onReportValidationMcacheHit(c!==null),c){let u=eL(n),{message:l,originatingPeers:f}=c;this.score.rejectMessage(t.toString(),e,l.topic,u);for(let h of f)this.score.rejectMessage(h,e,l.topic,u);(a=this.metrics)==null||a.onReportValidation(l.topic,n)}}}sendGraft(e,t){let n=[{topicID:t}];this.sendRpc(e,{control:{graft:n}})}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX)];this.sendRpc(e,{control:{prune:n}})}sendRpc(e,t){var a;let n=this.streamsOutbound.get(e);if(!n)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let i=this.control.get(e);i&&(this.piggybackControl(e,t,i),this.control.delete(e));let o=this.gossip.get(e);o&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let s=P5.encode(t).finish();try{n.push(s)}catch(c){return this.log.error(`Cannot send rpc to ${e}`,c),i&&this.control.set(e,i),o&&this.gossip.set(e,o),!1}return(a=this.metrics)==null||a.onRpcSent(t,s.length),!0}piggybackControl(e,t,n){var i,o;if(n.graft){t.control||(t.control={}),t.control.graft||(t.control.graft=[]);for(let s of n.graft)s.topicID&&((i=this.mesh.get(s.topicID))!=null&&i.has(e))&&t.control.graft.push(s)}if(n.prune){t.control||(t.control={}),t.control.prune||(t.control.prune=[]);for(let s of n.prune)s.topicID&&!((o=this.mesh.get(s.topicID))!=null&&o.has(e))&&t.control.prune.push(s)}}piggybackGossip(e,t,n){t.control||(t.control={}),t.control.ihave=n}async sendGraftPrune(e,t,n){let i=this.opts.doPX;for(let[o,s]of e){let a=s.map(l=>({topicID:l})),c=[],u=t.get(o);u&&(c=await Promise.all(u.map(async l=>await this.makePrune(o,l,i&&!(n.get(o)??!1)))),t.delete(o)),this.sendRpc(o,{control:{graft:a,prune:c}})}for(let[o,s]of t){let a=await Promise.all(s.map(async c=>await this.makePrune(o,c,i&&!(n.get(o)??!1))));this.sendRpc(o,{control:{prune:a}})}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,i]of e)this.doEmitGossip(n,i,t.get(n)??[])}doEmitGossip(e,t,n){if(!n.length||(hu(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),!t.size))return;let i=this.opts.Dlazy,o=.25*t.size,s=t;o>i&&(i=o),i>s.size?i=s.size:s=hu(Array.from(s)).slice(0,i),s.forEach(a=>{let c=n;n.length>5e3&&(c=hu(c.slice()).slice(0,5e3)),this.pushGossip(a,{topicID:e,messageIDs:c})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,{control:{ihave:t}});for(let[e,t]of this.control.entries())this.control.delete(e),this.sendRpc(e,{control:{graft:t.graft,prune:t.prune}})}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)||[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n){if(this.score.prune(e,t),this.streamsOutbound.get(e).protocol===ZO)return{topicID:t,peers:[]};let i=this.opts.pruneBackoff/1e3;if(!n)return{topicID:t,peers:[],backoff:i};let o=this.getRandomGossipPeers(t,this.opts.prunePeers,a=>a!==e&&this.score.score(a)>=0),s=await Promise.all(Array.from(o).map(async a=>{let c=Oe(a);return{peerID:c.toBytes(),signedPeerRecord:await this.components.peerStore.addressBook.getRawEnvelope(c)}}));return{topicID:t,peers:s,backoff:i}}async heartbeat(){var p,g;let{D:e,Dlo:t,Dhi:n,Dscore:i,Dout:o,fanoutTTL:s}=this.opts;this.heartbeatTicks++;let a=new Map,c=w=>{let _=a.get(w);return _===void 0&&(_=this.score.score(w),a.set(w,_)),_},u=new Map,l=new Map,f=new Map;this.clearBackoff(),this.peerhave.clear(),(p=this.metrics)==null||p.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),(g=this.fastMsgIdCache)==null||g.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let h=new Map;this.mesh.forEach((w,_)=>{let x=this.topics.get(_),m=new Set,y=new Set;if(h.set(_,y),x){let v=hu(Array.from(x)),S=this.backoff.get(_);for(let A of v){let I=this.streamsOutbound.get(A);if(I&&this.multicodecs.includes(I.protocol)&&!w.has(A)&&!this.direct.has(A)){let k=c(A);(!S||!S.has(A))&&k>=0&&m.add(A),k>=this.opts.scoreThresholds.gossipThreshold&&y.add(A)}}}let b=(v,S)=>{var I;this.log("HEARTBEAT: Remove mesh link to %s in %s",v,_),this.addBackoff(v,_),w.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&y.add(v),(I=this.metrics)==null||I.onRemoveFromMesh(_,S,1);let A=l.get(v);A?A.push(_):l.set(v,[_])},E=(v,S)=>{var I;this.log("HEARTBEAT: Add mesh link to %s in %s",v,_),this.score.graft(v,_),w.add(v),y.delete(v),(I=this.metrics)==null||I.onAddToMesh(_,S,1);let A=u.get(v);A?A.push(_):u.set(v,[_])};if(w.forEach(v=>{let S=c(v);S<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,S,_),b(v,Jp.BadScore),f.set(v,!0))}),w.size{E(A,Tl.NotEnough)})}if(w.size>n){let v=Array.from(w);v.sort((A,I)=>c(I)-c(A)),v=v.slice(0,i).concat(hu(v.slice(i)));let S=0;if(v.slice(0,e).forEach(A=>{this.outbound.get(A)&&S++}),S{let N=v[k];for(let O=k;O>0;O--)v[O]=v[O-1];v[0]=N};if(S>0){let k=S;for(let N=1;N0;N++)this.outbound.get(v[N])&&(A(N),k--)}let I=e-S;for(let k=e;k0;k++)this.outbound.get(v[k])&&(A(k),I--)}v.slice(e).forEach(A=>{b(A,Jp.Excess)})}if(w.size>=t){let v=0;if(w.forEach(S=>{this.outbound.get(S)&&v++}),vthis.outbound.get(I)===!0).forEach(I=>{E(I,Tl.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&w.size>1){let v=Array.from(w).sort((I,k)=>c(I)-c(k)),S=Math.floor(w.size/2),A=c(v[S]);if(Ac(N)>A);for(let N of k)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",N,_),E(N,Tl.Opportunistic)}}});let d=Date.now();this.fanoutLastpub.forEach((w,_)=>{w+s{let x=this.topics.get(_);w.forEach(E=>{(!x.has(E)||c(E)=this.opts.scoreThresholds.publishThreshold&&y.push(v),A>=this.opts.scoreThresholds.gossipThreshold&&b.add(v)}}}if(w.size{w.add(v),b==null||b.delete(v)})}}),this.emitGossip(h),await this.sendGraftPrune(u,l,f),this.flush(),this.mcache.shift(),this.dispatchEvent(new cn("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let i=this.topics.get(e);if(!i)return new Set;let o=[];return i.forEach(s=>{let a=this.streamsOutbound.get(s);a&&this.multicodecs.includes(a.protocol)&&n(s)&&o.push(s)}),o=hu(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){var s,a;e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},((s=this.fastMsgIdCache)==null?void 0:s.size)??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0;for(let c of this.backoff.values())t+=c.size;e.cacheSize.set({cache:"backoff"},t);for(let[c,u]of this.topics)e.topicPeersCount.set({topicStr:c},u.size);for(let[c,u]of this.mesh)e.meshPeerCounts.set({topicStr:c},u.size);let n=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let u=this.score.score(c);n.push(u),i.set(c,u),e.behaviourPenalty.observe(((a=this.score.peerStats.get(c))==null?void 0:a.behaviourPenalty)??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let o=Lae(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(o)}};Rv.multicodec=JO;function jae(r={}){return e=>new Rv(e,r)}var Wae=()=>({gossipsub:jae({fallbackToFloodsub:!0,emitSelf:!0,maxInboundStreams:64,maxOutboundStreams:128})});var hs=C(xA(),1);hs.default.formatters.b=r=>r==null?"undefined":Qi.baseEncode(r);hs.default.formatters.t=r=>r==null?"undefined":_f.baseEncode(r);hs.default.formatters.m=r=>r==null?"undefined":lI.baseEncode(r);hs.default.formatters.p=r=>r==null?"undefined":r.toString();hs.default.formatters.c=r=>r==null?"undefined":r.toString();hs.default.formatters.k=r=>r==null?"undefined":r.toString();hs.default.formatters.a=r=>r==null?"undefined":r.toString();function yMe(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Cv(r){let e=yMe(`${r}:trace`);return hs.default.enabled(`${r}:trace`)&&hs.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,hs.default)(`${r}:trace`)),Object.assign((0,hs.default)(r),{error:(0,hs.default)(`${r}:error`),trace:e})}var Yae=Symbol.for("@libp2p/peer-id");var wMe=Symbol.for("nodejs.util.inspect.custom"),Qae=Object.values(S1).map(r=>r.decoder).reduce((r,e)=>r.or(e),S1.identity.decoder),Xae=114,Zae=36,Jae=37,EMe,D5=class{constructor(e){B(this,"type");B(this,"multihash");B(this,"privateKey");B(this,"publicKey");B(this,"string");B(this,EMe,!0);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()})`}toString(){return this.string==null&&(this.string=Qi.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Nr.createV1(Xae,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){var t;if(e instanceof Uint8Array)return mt(this.multihash.bytes,e);if(typeof e=="string")return bMe(e).equals(this);if(((t=e==null?void 0:e.multihash)==null?void 0:t.bytes)!=null)return mt(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[(EMe=Yae,wMe)](){return`PeerId(${this.toString()})`}},O5=class extends D5{constructor(t){super({...t,type:"RSA"});B(this,"type","RSA");B(this,"publicKey");this.publicKey=t.publicKey}},L5=class extends D5{constructor(t){super({...t,type:"Ed25519"});B(this,"type","Ed25519");B(this,"publicKey");this.publicKey=t.multihash.digest}},B5=class extends D5{constructor(t){super({...t,type:"secp256k1"});B(this,"type","secp256k1");B(this,"publicKey");this.publicKey=t.multihash.digest}};function bMe(r,e){if(e=e??Qae,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=_y(Qi.decode(`z${r}`));return r.startsWith("12D")?new L5({multihash:t}):r.startsWith("16U")?new B5({multihash:t}):new O5({multihash:t})}return oL(Qae.decode(r))}function oL(r){try{let e=_y(r);if(e.code===A8.code){if(e.digest.length===Zae)return new L5({multihash:e});if(e.digest.length===Jae)return new B5({multihash:e})}if(e.code===T8.code)return new O5({multihash:e})}catch{return _Me(Nr.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function _Me(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Xae)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===T8.code)return new O5({multihash:r.multihash});if(e.code===A8.code){if(e.digest.length===Zae)return new L5({multihash:r.multihash});if(e.digest.length===Jae)return new B5({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function ia(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)(o==null?void 0:o.removeEventListener)!=null&&o.removeEventListener("abort",t)}for(let o of r){if((o==null?void 0:o.aborted)===!0){t();break}(o==null?void 0:o.addEventListener)!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)(o==null?void 0:o.removeEventListener)!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var r0=Cv("libp2p:delegated-peer-routing"),ece=3e4,vMe=4,tce;(function(r){r[r.SENDING_QUERY=0]="SENDING_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADDING_PEER=6]="ADDING_PEER",r[r.DIALING_PEER=7]="DIALING_PEER"})(tce||(tce={}));var rce;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(rce||(rce={}));var sL=class{constructor(e){B(this,"client");B(this,"httpQueue");B(this,"started");B(this,"abortController");if(e==null)throw new Error("missing ipfs http client");this.client=e,this.started=!1,this.abortController=new AbortController,this.httpQueue=new qn({concurrency:vMe});let{protocol:t,host:n,port:i}=e.getEndpointConfig();r0(`enabled DelegatedPeerRouting via ${t}://${n}:${i}`)}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.abortController.abort(),this.abortController=new AbortController,this.started=!1}async findPeer(e,t={}){r0("findPeer starts: %p",e),t.timeout=t.timeout??ece;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise;for await(let s of this.client.dht.findPeer(e,{...t,signal:n}))if(s.name==="FINAL_PEER"&&s.peer.multiaddrs.length>0)return{id:s.peer.id,multiaddrs:s.peer.multiaddrs,protocols:[]};throw new J("Not found","ERR_NOT_FOUND")}catch(s){throw r0.error("findPeer errored: %o",s),s}finally{n.clear(),o.resolve(),r0("findPeer finished: %p",e)}}async*getClosestPeers(e,t={}){let n,i=Nr.asCID(e);i!=null?n=i:n=oL(e),r0("getClosestPeers starts: %s",n),t.timeout=t.timeout??ece;let o=ia([this.abortController.signal,t.signal]),s=Qt(),a=Qt();this.httpQueue.add(async()=>(s.resolve(),a.promise));try{await s.promise;for await(let c of this.client.dht.query(n,{...t,signal:o}))c.name==="PEER_RESPONSE"&&(yield*c.closer.map(u=>({id:u.id,multiaddrs:u.multiaddrs,protocols:[]})))}catch(c){throw r0.error("getClosestPeers errored:",c),c}finally{o.clear(),a.resolve(),r0("getClosestPeers finished: %b",e)}}};function nce(r){return()=>new sL(r)}var sce=C(ee(),1);function xMe(r){return r[Symbol.asyncIterator]!=null}function SMe(r){if(xMe(r))return(async()=>{for await(let e of r);})();for(let e of r);}var aL=SMe;var To=Cv("libp2p:delegated-content-routing"),Pv=3e4,AMe=4,TMe=2,ice;(function(r){r[r.SENDING_QUERY=0]="SENDING_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADDING_PEER=6]="ADDING_PEER",r[r.DIALING_PEER=7]="DIALING_PEER"})(ice||(ice={}));var oce;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(oce||(oce={}));var cL=class{constructor(e){B(this,"client");B(this,"httpQueue");B(this,"httpQueueRefs");B(this,"started");B(this,"abortController");if(e==null)throw new Error("missing ipfs http client");this.client=e,this.started=!1,this.abortController=new AbortController,this.httpQueue=new qn({concurrency:AMe}),this.httpQueueRefs=new qn({concurrency:TMe});let{protocol:t,host:n,port:i}=e.getEndpointConfig();To(`enabled DelegatedContentRouting via ${t}://${n}:${i}`)}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.httpQueueRefs.clear(),this.abortController.abort(),this.abortController=new AbortController,this.started=!1}async*findProviders(e,t={}){To("findProviders starts: %c",e),t.timeout=t.timeout??Pv;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise;for await(let s of this.client.dht.findProvs(e,{...t,signal:n}))s.name==="PROVIDER"&&(yield*s.providers.map(a=>({id:a.id,protocols:[],multiaddrs:a.multiaddrs})))}catch(s){throw To.error("findProviders errored:",s),s}finally{n.clear(),o.resolve(),To("findProviders finished: %c",e)}}async provide(e,t={}){To("provide starts: %c",e),t.timeout=t.timeout??Pv;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise,await this.client.block.stat(e,{...t,signal:n}),await aL(this.client.dht.provide(e,{...t,signal:n}))}catch(s){throw To.error("provide errored:",s),s}finally{n.clear(),o.resolve(),To("provide finished: %c",e)}}async put(e,t,n={}){To("put value start: %b",e),n.timeout=n.timeout??Pv;let i=ia([this.abortController.signal,n.signal]),o=Qt(),s=Qt();this.httpQueue.add(async()=>(o.resolve(),s.promise));try{await o.promise,await aL(this.client.dht.put(e,t,{...n,signal:i}))}catch(a){throw To.error("put errored:",a),a}finally{i.clear(),s.resolve(),To("put finished: %b",e)}}async get(e,t={}){To("get value start: %b",e),t.timeout=t.timeout??Pv;let n=ia([this.abortController.signal,t.signal]),i=Qt(),o=Qt();this.httpQueue.add(async()=>(i.resolve(),o.promise));try{await i.promise;for await(let s of this.client.dht.get(e,{...t,signal:n}))if(s.name==="VALUE")return To("get value finished: %b",e),s.value;throw(0,sce.default)(new Error("Not found"),"ERR_NOT_FOUND")}catch(s){throw To.error("put errored:",s),s}finally{n.clear(),o.resolve(),To("put finished: %b",e)}}};function ace(r){return()=>new cL(r)}var IMe=r=>Promise.reject(new Error(`No base found for "${r}"`)),F2=class{constructor(e){this._basesByName={},this._basesByPrefix={},this._loadBase=e.loadBase||IMe;for(let t of e.bases)this.addBase(t)}addBase(e){if(this._basesByName[e.name]||this._basesByPrefix[e.prefix])throw new Error(`Codec already exists for codec "${e.name}"`);this._basesByName[e.name]=e,this._basesByPrefix[e.prefix]=e}removeBase(e){delete this._basesByName[e.name],delete this._basesByPrefix[e.prefix]}async getBase(e){if(this._basesByName[e])return this._basesByName[e];if(this._basesByPrefix[e])return this._basesByPrefix[e];let t=await this._loadBase(e);return this._basesByName[t.name]==null&&this._basesByPrefix[t.prefix]==null&&this.addBase(t),t}listBases(){return Object.values(this._basesByName)}};var RMe=r=>Promise.reject(new Error(`No codec found for "${r}"`)),z2=class{constructor(e){this._codecsByName={},this._codecsByCode={},this._loadCodec=e.loadCodec||RMe;for(let t of e.codecs)this.addCodec(t)}addCodec(e){if(this._codecsByName[e.name]||this._codecsByCode[e.code])throw new Error(`Resolver already exists for codec "${e.name}"`);this._codecsByName[e.name]=e,this._codecsByCode[e.code]=e}removeCodec(e){delete this._codecsByName[e.name],delete this._codecsByCode[e.code]}async getCodec(e){let t=typeof e=="string"?this._codecsByName:this._codecsByCode;if(t[e])return t[e];let n=await this._loadCodec(e);return t[e]==null&&this.addCodec(n),n}listCodecs(){return Object.values(this._codecsByName)}};var CMe=r=>Promise.reject(new Error(`No hasher found for "${r}"`)),V2=class{constructor(e){this._hashersByName={},this._hashersByCode={},this._loadHasher=e.loadHasher||CMe;for(let t of e.hashers)this.addHasher(t)}addHasher(e){if(this._hashersByName[e.name]||this._hashersByCode[e.code])throw new Error(`Resolver already exists for codec "${e.name}"`);this._hashersByName[e.name]=e,this._hashersByCode[e.code]=e}removeHasher(e){delete this._hashersByName[e.name],delete this._hashersByCode[e.code]}async getHasher(e){let t=typeof e=="string"?this._hashersByName:this._hashersByCode;if(t[e])return t[e];let n=await this._loadHasher(e);return t[e]==null&&this.addHasher(n),n}listHashers(){return Object.values(this._hashersByName)}};var pu=C(C6(),1);var n0=C(O1(),1);function uL(r){try{r=zm(yt(r))}catch{}return r=r.toString(),r}var cce=()=>{};var uce=j("ipfs-http-client:lib:error-handler"),PMe=et.bind({ignoreUndefined:!0}),kMe=pu.isBrowser||pu.isWebWorker?location.protocol:"http",NMe=pu.isBrowser||pu.isWebWorker?location.hostname:"localhost",DMe=pu.isBrowser||pu.isWebWorker?location.port:"5001",OMe=(r={})=>{let e,t={},n;if(typeof r=="string"||F_(r))e=new URL(uL(r));else if(r instanceof URL)e=r;else if(typeof r.url=="string"||F_(r.url))e=new URL(uL(r.url)),t=r;else if(r.url instanceof URL)e=r.url,t=r;else{t=r||{};let i=(t.protocol||kMe).replace(":",""),o=(t.host||NMe).split(":")[0],s=t.port||DMe;e=new URL(`${i}://${o}:${s}`)}if(t.apiPath?e.pathname=t.apiPath:(e.pathname==="/"||e.pathname===void 0)&&(e.pathname="api/v0"),pu.isNode){let i=cce(e);n=t.agent||new i({keepAlive:!0,maxSockets:6})}return{...t,host:e.host,protocol:e.protocol.replace(":",""),port:Number(e.port),apiPath:e.pathname,url:e,agent:n}},LMe=async r=>{let e;try{if((r.headers.get("Content-Type")||"").startsWith("application/json")){let n=await r.json();uce(n),e=n.Message||n.message}else e=await r.text()}catch(n){uce("Failed to parse error response",n),e=n.message}let t=new n0.default.HTTPError(r);throw e&&(e.includes("deadline has elapsed")&&(t=new n0.default.TimeoutError),e&&e.includes("context deadline exceeded")&&(t=new n0.default.TimeoutError)),e&&e.includes("request timed out")&&(t=new n0.default.TimeoutError),e&&(t.message=e),t},BMe=/[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g,lce=r=>r.replace(BMe,function(e){return"-"+e.toLowerCase()}),MMe=r=>typeof r=="string"?Cf(r):r,Hd=class extends n0.default{constructor(e={}){let t=OMe(e);super({timeout:MMe(t.timeout||0)||void 0,headers:t.headers,base:`${t.url}`,handleError:LMe,transformSearchParams:i=>{let o=new URLSearchParams;for(let[s,a]of i)a!=="undefined"&&a!=="null"&&s!=="signal"&&o.append(lce(s),a),s==="timeout"&&!isNaN(a)&&o.append(lce(s),a);return o},agent:t.agent}),delete this.get,delete this.put,delete this.delete,delete this.options;let n=this.fetch;this.fetch=(i,o={})=>(typeof i=="string"&&!i.startsWith("/")&&(i=`${t.url}/${i}`),n.call(this,i,PMe(o,{method:"POST"})))}},FAt=n0.default.HTTPError;var D=r=>e=>r(new Hd(e),e);function kv(r){if(r!=null)return typeof r=="string"?r:r.toString(8).padStart(4,"0")}var fce=C(ee(),1);function Nv(r){if(r==null)return;let e;if(r.secs!=null&&(e={secs:r.secs,nsecs:r.nsecs}),r.Seconds!=null&&(e={secs:r.Seconds,nsecs:r.FractionalNanoseconds}),Array.isArray(r)&&(e={secs:r[0],nsecs:r[1]}),r instanceof Date){let t=r.getTime(),n=Math.floor(t/1e3);e={secs:n,nsecs:(t-n*1e3)*1e3}}if(Object.prototype.hasOwnProperty.call(e,"secs")){if(e!=null&&e.nsecs!=null&&(e.nsecs<0||e.nsecs>999999999))throw(0,fce.default)(new Error("mtime-nsecs must be within the range [0,999999999]"),"ERR_INVALID_MTIME_NSECS");return e}}function M({arg:r,searchParams:e,hashAlg:t,mtime:n,mode:i,...o}={}){e&&(o={...o,...e}),t&&(o.hash=t),n!=null&&(n=Nv(n),o.mtime=n.secs,o.mtimeNsecs=n.nsecs),i!=null&&(o.mode=kv(i)),o.timeout&&!isNaN(o.timeout)&&(o.timeout=`${o.timeout}ms`),r==null?r=[]:Array.isArray(r)||(r=[r]);let s=new URLSearchParams(o);return r.forEach(a=>s.append("arg",a)),s}var dce=D(r=>{async function e(t={}){return((await(await r.post("bitswap/wantlist",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Keys||[]).map(i=>z.parse(i["/"]))}return e});var hce=D(r=>{async function e(t,n={}){return((await(await r.post("bitswap/wantlist",{signal:n.signal,searchParams:M({...n,peer:t.toString()}),headers:n.headers})).json()).Keys||[]).map(o=>z.parse(o["/"]))}return e});var Dv=D(r=>{async function e(t={}){let n=await r.post("bitswap/stat",{searchParams:M(t),signal:t.signal,headers:t.headers});return UMe(await n.json())}return e});function UMe(r){return{provideBufLen:r.ProvideBufLen,wantlist:(r.Wantlist||[]).map(e=>z.parse(e["/"])),peers:(r.Peers||[]).map(e=>Oe(e)),blocksReceived:BigInt(r.BlocksReceived),dataReceived:BigInt(r.DataReceived),blocksSent:BigInt(r.BlocksSent),dataSent:BigInt(r.DataSent),dupBlksReceived:BigInt(r.DupBlksReceived),dupDataReceived:BigInt(r.DupDataReceived)}}var pce=D(r=>{async function e(t,n={}){return(await r.post("bitswap/unwant",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers})).json()}return e});function mce(r){return{wantlist:dce(r),wantlistForPeer:hce(r),unwant:pce(r),stat:Dv(r)}}var Ov=D(r=>{async function e(t,n={}){let i=await r.post("block/get",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers});return new Uint8Array(await i.arrayBuffer())}return e});var yce=C(ee(),1);async function wce(r){if(qs(r))return new Blob([r]);if(typeof r=="string"||r instanceof String)return new Blob([r.toString()]);if(ul(r))return r;if(ll(r)&&(r=yo(r)),Symbol.iterator in r||Symbol.asyncIterator in r){let e=ja(r),{value:t,done:n}=await e.peek();if(n)return gce(e);if(e.push(t),Number.isInteger(t))return new Blob([Uint8Array.from(await tp(e))]);if(qs(t)||typeof t=="string"||t instanceof String)return gce(e)}throw(0,yce.default)(new Error(`Unexpected input: ${r}`),"ERR_UNEXPECTED_INPUT")}async function gce(r){let e=[];for await(let t of r)e.push(t);return new Blob(e)}function bce(r){return eE(r,wce,!0)}function _ce(r){if(r!=null)return typeof r=="string"?r:r.toString(8).padStart(4,"0")}async function Dn(r,e,t={}){let n=[],i=new FormData,o=0,s=0;for await(let{content:a,path:c,mode:u,mtime:l}of bce(r)){let f="",h=a?"file":"dir";o>0&&(f=`-${o}`);let d=h+f,p=[];if(u!=null&&p.push(`mode=${_ce(u)}`),l!=null){let{secs:g,nsecs:w}=l;p.push(`mtime=${g}`),w!=null&&p.push(`mtime-nsecs=${w}`)}if(p.length&&(d=`${d}?${p.join("&")}`),a){i.set(d,a,c!=null?encodeURIComponent(c):void 0);let g=s+a.size;n.push({name:c,start:s,end:g}),s=g}else if(c!=null)i.set(d,new File([""],encodeURIComponent(c),{type:"application/x-directory"}));else throw new Error("path or content or both must be set");o++}return{total:s,parts:n,headers:t,body:i}}var Ece=C(Da(),1);function FMe(r){return r.filter(Boolean)}function On(...r){return(0,Ece.anySignal)(FMe(r))}var vce=D(r=>{async function e(t,n={}){let i=new AbortController,o=On(i.signal,n.signal),s;try{s=await(await r.post("block/put",{signal:o,searchParams:M(n),...await Dn([t],i,n.headers)})).json()}catch(a){if(n.format==="dag-pb")return e(t,{...n,format:"protobuf"});if(n.format==="dag-cbor")return e(t,{...n,format:"cbor"});throw a}return z.parse(s.Key)}return e});var xce=D(r=>{async function*e(t,n={}){Array.isArray(t)||(t=[t]);let i=await r.post("block/rm",{signal:n.signal,searchParams:M({arg:t.map(o=>o.toString()),"stream-channels":!0,...n}),headers:n.headers});for await(let o of i.ndjson())yield zMe(o)}return e});function zMe(r){let e={cid:z.parse(r.Hash)};return r.Error&&(e.error=new Error(r.Error)),e}var Sce=D(r=>{async function e(t,n={}){let o=await(await r.post("block/stat",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers})).json();return{cid:z.parse(o.Key),size:o.Size}}return e});function Ace(r){return{get:Ov(r),put:vce(r),rm:xce(r),stat:Sce(r)}}var Tce=D(r=>{async function e(t,n={}){let i=await r.post("bootstrap/add",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Peers:o}=await i.json();return{Peers:o.map(s=>yt(s))}}return e});var Ice=D(r=>{async function e(t={}){let n=await r.post("bootstrap/rm",{signal:t.signal,searchParams:M({...t,all:!0}),headers:t.headers}),{Peers:i}=await n.json();return{Peers:i.map(o=>yt(o))}}return e});var Rce=D(r=>{async function e(t={}){let n=await r.post("bootstrap/list",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Peers:i}=await n.json();return{Peers:i.map(o=>yt(o))}}return e});var Cce=D(r=>{async function e(t={}){let n=await r.post("bootstrap/add",{signal:t.signal,searchParams:M({...t,default:!0}),headers:t.headers}),{Peers:i}=await n.json();return{Peers:i.map(o=>yt(o))}}return e});var Pce=D(r=>{async function e(t,n={}){let i=await r.post("bootstrap/rm",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Peers:o}=await i.json();return{Peers:o.map(s=>yt(s))}}return e});function kce(r){return{add:Tce(r),clear:Ice(r),list:Rce(r),reset:Cce(r),rm:Pce(r)}}var Nce=D(r=>{async function e(t,n={}){let o=await(await r.post("config/profile/apply",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return{original:o.OldCfg,updated:o.NewCfg}}return e});function kt(r){if(r==null)return r;let e=/^[A-Z]+$/,t={};return Object.keys(r).reduce((n,i)=>(e.test(i)?n[i.toLowerCase()]=r[i]:e.test(i[0])?n[i[0].toLowerCase()+i.slice(1)]=r[i]:n[i]=r[i],n),t)}var Dce=D(r=>{async function e(t={}){return(await(await r.post("config/profile/list",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).map(o=>kt(o))}return e});function Oce(r){return{apply:Nce(r),list:Dce(r)}}var Lce=D(r=>async(t,n={})=>{if(!t)throw new Error("key argument is required");return(await(await r.post("config",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json()).Value});var Bce=D(r=>async(t={})=>await(await r.post("config/show",{signal:t.signal,searchParams:M({...t}),headers:t.headers})).json());var Mce=D(r=>async(t,n={})=>{let i=new AbortController,o=On(i.signal,n.signal);await(await r.post("config/replace",{signal:o,searchParams:M(n),...await Dn([Ie(JSON.stringify(t))],i,n.headers)})).text()});var Uce=D(r=>async(t,n,i={})=>{if(typeof t!="string")throw new Error("Invalid key type");let o={...i,...VMe(t,n)};await(await r.post("config",{signal:i.signal,searchParams:M(o),headers:i.headers})).text()}),VMe=(r,e)=>{switch(typeof e){case"boolean":return{arg:[r,e.toString()],bool:!0};case"string":return{arg:[r,e]};default:return{arg:[r,JSON.stringify(e)],json:!0}}};function Fce(r){return{getAll:Bce(r),get:Lce(r),set:Uce(r),replace:Mce(r),profiles:Oce(r)}}var zce=D(r=>{async function*e(t,n={}){yield*(await r.post("dag/export",{signal:n.signal,searchParams:M({arg:t.toString()}),headers:n.headers})).iterator()}return e});var lL=C(ee(),1);async function*fL(r,e,t,n,i){let o=async u=>{let l=await t.getCodec(u.code),f=await n(u,i);return l.decode(f)},s=e.split("/").filter(Boolean),a=await o(r),c=r;for(;s.length;){let u=s.shift();if(!u)throw(0,lL.default)(new Error(`Could not resolve path "${e}"`),"ERR_INVALID_PATH");if(Object.prototype.hasOwnProperty.call(a,u))a=a[u],yield{value:a,remainderPath:s.join("/")};else throw(0,lL.default)(new Error(`no link named "${u}" under ${c}`),"ERR_NO_LINK");let l=z.asCID(a);l&&(c=l,a=await o(a))}yield{value:a,remainderPath:""}}var Vce=C(ee(),1);var Kce=(r,e)=>D((n,i)=>{let o=Ov(i);return async(a,c={})=>{if(c.path){let d=c.localResolve?await mp(fL(a,c.path,r,o,c)):await Dr(fL(a,c.path,r,o,c));if(!d)throw(0,Vce.default)(new Error("Not found"),"ERR_NOT_FOUND");return d}let u=await r.getCodec(a.code),l=await o(a,c);return{value:u.decode(l),remainderPath:""}}})(e);var $ce=D(r=>{async function*e(t,n={}){let i=new AbortController,o=On(i.signal,n.signal),{headers:s,body:a}=await Dn(t,i,n.headers),c=await r.post("dag/import",{signal:o,headers:s,body:a,searchParams:M({"pin-roots":n.pinRoots})});for await(let{Root:u}of c.ndjson())if(u!==void 0){let{Cid:{"/":l},PinErrorMsg:f}=u;yield{root:{cid:z.parse(l),pinErrorMsg:f}}}}return e});var Lv=(r,e)=>D(n=>async(o,s={})=>{let a={storeCodec:"dag-cbor",hashAlg:"sha2-256",...s},c;if(a.inputCodec){if(!(o instanceof Uint8Array))throw new Error("Can only inputCodec on raw bytes that can be decoded");c=o}else c=(await r.getCodec(a.storeCodec)).encode(o),a.inputCodec=a.storeCodec;let u=new AbortController,l=On(u.signal,a.signal),h=await(await n.post("dag/put",{timeout:a.timeout,signal:l,searchParams:M(a),...await Dn([c],u,a.headers)})).json();return z.parse(h.Cid["/"])})(e);var qce=D(r=>async(t,n={})=>{let o=await(await r.post("dag/resolve",{signal:n.signal,searchParams:M({arg:`${t}${n.path?`/${n.path}`.replace(/\/[/]+/g,"/"):""}`,...n}),headers:n.headers})).json();return{cid:z.parse(o.Cid["/"]),remainderPath:o.RemPath}});function Hce(r,e){return{export:zce(e),get:Kce(r,e),import:$ce(e),put:Lv(r,e),resolve:qce(e)}}var oa=r=>{if(r.Type===0)return{name:"SENDING_QUERY",type:r.Type};if(r.Type===1)return{from:Oe(r.ID),name:"PEER_RESPONSE",type:r.Type,messageType:0,messageName:"PUT_VALUE",closer:(r.Responses||[]).map(({ID:e,Addrs:t})=>({id:Oe(e),multiaddrs:t.map(n=>yt(n)),protocols:[]})),providers:(r.Responses||[]).map(({ID:e,Addrs:t})=>({id:Oe(e),multiaddrs:t.map(n=>yt(n)),protocols:[]}))};if(r.Type===2){let e={id:r.ID??Oe(r.ID),multiaddrs:[],protocols:[]};return r.Responses&&r.Responses.length&&(e={id:Oe(r.Responses[0].ID),multiaddrs:r.Responses[0].Addrs.map(t=>yt(t)),protocols:[]}),{name:"FINAL_PEER",type:r.Type,peer:e}}if(r.Type===3)return{name:"QUERY_ERROR",type:r.Type,error:new Error(r.Extra)};if(r.Type===4)return{name:"PROVIDER",type:r.Type,providers:r.Responses.map(({ID:e,Addrs:t})=>({id:Oe(e),multiaddrs:t.map(n=>yt(n)),protocols:[]}))};if(r.Type===5)return{name:"VALUE",type:r.Type,value:Ie(r.Extra,"base64pad")};if(r.Type===6){let e=r.Responses.map(({ID:t})=>Oe(t));if(!e.length)throw new Error("No peer found");return{name:"ADDING_PEER",type:r.Type,peer:e[0]}}if(r.Type===7)return{name:"DIALING_PEER",type:r.Type,peer:Oe(r.ID)};throw new Error("Unknown DHT event type")};var Gce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/findpeer",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});var jce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/findprovs",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});var Wce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/get",{signal:n.signal,searchParams:M({arg:t instanceof Uint8Array?re(t):t.toString(),...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});var Yce=D(r=>{async function*e(t,n={recursive:!1}){let i=Array.isArray(t)?t:[t],o=await r.post("dht/provide",{signal:n.signal,searchParams:M({arg:i.map(s=>s.toString()),...n}),headers:n.headers});for await(let s of o.ndjson())yield oa(s)}return e});var Qce=D(r=>{async function*e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal),a=await r.post("dht/put",{signal:s,searchParams:M({arg:t instanceof Uint8Array?re(t):t.toString(),...i}),...await Dn([n],o,i.headers)});for await(let c of a.ndjson())yield oa(c)}return e});var Xce=D(r=>{async function*e(t,n={}){let i=await r.post("dht/query",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers});for await(let o of i.ndjson())yield oa(o)}return e});function Zce(r){return{findPeer:Gce(r),findProvs:jce(r),get:Wce(r),provide:Yce(r),put:Qce(r),query:Xce(r)}}var Jce=D(r=>{async function e(t={}){return(await r.post("diag/cmds",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()}return e});var eue=D(r=>{async function e(t={}){return(await r.post("diag/net",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()}return e});var tue=D(r=>{async function e(t={}){return(await r.post("diag/sys",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()}return e});function rue(r){return{cmds:Jce(r),net:eue(r),sys:tue(r)}}var nue=D(r=>{async function e(t,n,i={}){await(await r.post("files/chmod",{signal:i.signal,searchParams:M({arg:t,mode:n,...i}),headers:i.headers})).text()}return e});var iue=D(r=>{async function e(t,n,i={}){let o=Array.isArray(t)?t:[t];await(await r.post("files/cp",{signal:i.signal,searchParams:M({arg:o.concat(n).map(a=>z.asCID(a)?`/ipfs/${a}`:a),...i}),headers:i.headers})).text()}return e});var oue=D(r=>{async function e(t,n={}){if(!t||typeof t!="string")throw new Error("ipfs.files.flush requires a path");let o=await(await r.post("files/flush",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return z.parse(o.Cid)}return e});function M5(r){let e=kt(r);return Object.prototype.hasOwnProperty.call(e,"mode")&&(e.mode=parseInt(e.mode,8)),Object.prototype.hasOwnProperty.call(e,"mtime")&&(e.mtime={secs:e.mtime,nsecs:e.mtimeNsecs||0},delete e.mtimeNsecs),e}var aue=D(r=>{async function*e(t,n={}){if(!t)throw new Error("ipfs.files.ls requires a path");let i=await r.post("files/ls",{signal:n.signal,searchParams:M({arg:z.asCID(t)?`/ipfs/${t}`:t,long:!0,...n,stream:!0}),headers:n.headers});for await(let o of i.ndjson())if("Entries"in o)for(let s of o.Entries||[])yield sue(M5(s));else yield sue(M5(o))}return e});function sue(r){return r.hash&&(r.cid=z.parse(r.hash)),delete r.hash,r.type=r.type===1?"directory":"file",r}var cue=D(r=>{async function e(t,n={}){await(await r.post("files/mkdir",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).text()}return e});var uue=D(r=>{async function e(t,n,i={}){Array.isArray(t)||(t=[t]),await(await r.post("files/mv",{signal:i.signal,searchParams:M({arg:t.concat(n),...i}),headers:i.headers})).text()}return e});var due=C(fue(),1),hue=D(r=>{async function*e(t,n={}){let i=await r.post("files/read",{signal:n.signal,searchParams:M({arg:t,count:n.length,...n}),headers:n.headers});yield*(0,due.default)(i.body)}return e});var pue=C(O1(),1),mue=D(r=>{async function e(t,n={}){let i=await r.post("files/rm",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),o=await i.text();if(o!==""){let s=new pue.default.HTTPError(i);throw s.message=o,s}}return e});var Bv=D(r=>{async function e(t,n={}){let o=await(await r.post("files/stat",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return o.WithLocality=o.WithLocality||!1,QMe(M5(o))}return e});function QMe(r){return r.cid=z.parse(r.hash),delete r.hash,r}var gue=D(r=>{async function e(t,n={}){await(await r.post("files/touch",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).text()}return e});var yue=D(r=>{async function e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal);await(await r.post("files/write",{signal:s,searchParams:M({arg:t,streamChannels:!0,count:i.length,...i}),...await Dn([{content:n,path:"arg",mode:kv(i.mode),mtime:Nv(i.mtime)}],o,i.headers)})).text()}return e});function wue(r){return{chmod:nue(r),cp:iue(r),flush:oue(r),ls:aue(r),mkdir:cue(r),mv:uue(r),read:hue(r),rm:mue(r),stat:Bv(r),touch:gue(r),write:yue(r)}}var bue=C(ee(),1),_ue=D(r=>async(t,n,i={})=>{throw(0,bue.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")});var Eue=D(r=>{async function e(t,n){let i=n??{type:"Ed25519"},s=await(await r.post("key/gen",{signal:i.signal,searchParams:M({arg:t,...i}),headers:i.headers})).json();return kt(s)}return e});var vue=D(r=>{async function e(t,n,i,o={}){let a=await(await r.post("key/import",{signal:o.signal,searchParams:M({arg:t,pem:n,password:i,...o}),headers:o.headers})).json();return kt(a)}return e});var xue=C(ee(),1),Sue=D(r=>async(t,n={})=>{throw(0,xue.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")});var Aue=D(r=>{async function e(t={}){return((await(await r.post("key/list",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Keys||[]).map(o=>kt(o))}return e});var Tue=D(r=>{async function e(t,n,i={}){let o=await r.post("key/rename",{signal:i.signal,searchParams:M({arg:[t,n],...i}),headers:i.headers});return kt(await o.json())}return e});var Iue=D(r=>{async function e(t,n={}){let o=await(await r.post("key/rm",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json();return kt(o.Keys[0])}return e});function Rue(r){return{export:_ue(r),gen:Eue(r),import:vue(r),info:Sue(r),list:Aue(r),rename:Tue(r),rm:Iue(r)}}var Cue=D(r=>{async function e(t,n,i={}){let o=await r.post("log/level",{signal:i.signal,searchParams:M({arg:[t,n],...i}),headers:i.headers});return kt(await o.json())}return e});var Pue=D(r=>{async function e(t={}){return(await(await r.post("log/ls",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Strings}return e});var kue=D(r=>{async function*e(t={}){yield*(await r.post("log/tail",{signal:t.signal,searchParams:M(t),headers:t.headers})).ndjson()}return e});function Nue(r){return{level:Cue(r),ls:Pue(r),tail:kue(r)}}var Due=D(r=>{async function e(t,n={}){let i=await r.post("name/publish",{signal:n.signal,searchParams:M({arg:`${t}`,...n}),headers:n.headers});return kt(await i.json())}return e});var Oue=D(r=>{async function*e(t,n={}){let i=await r.post("name/resolve",{signal:n.signal,searchParams:M({arg:t,stream:!0,...n}),headers:n.headers});for await(let o of i.ndjson())yield o.Path}return e});var Lue=D(r=>{async function e(t,n={}){let i=await r.post("name/pubsub/cancel",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers});return kt(await i.json())}return e});var Bue=D(r=>{async function e(t={}){let n=await r.post("name/pubsub/state",{signal:t.signal,searchParams:M(t),headers:t.headers});return kt(await n.json())}return e});var Mue=D(r=>{async function e(t={}){return(await(await r.post("name/pubsub/subs",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Strings||[]}return e});function Uue(r){return{cancel:Lue(r),state:Bue(r),subs:Mue(r)}}function Fue(r){return{publish:Due(r),resolve:Oue(r),pubsub:Uue(r)}}var zue=D(r=>{async function e(t,n={}){let o=await(await r.post("object/data",{signal:n.signal,searchParams:M({arg:`${t instanceof Uint8Array?z.decode(t):t}`,...n}),headers:n.headers})).arrayBuffer();return new Uint8Array(o,0,o.byteLength)}return e});var Vue=D(r=>{async function e(t,n={}){let o=await(await r.post("object/get",{signal:n.signal,searchParams:M({arg:`${t instanceof Uint8Array?z.decode(t):t}`,dataEncoding:"base64",...n}),headers:n.headers})).json();return{Data:Ie(o.Data,"base64pad"),Links:(o.Links||[]).map(s=>({Name:s.Name,Hash:z.parse(s.Hash),Tsize:s.Size}))}}return e});var Kue=D(r=>{async function e(t,n={}){return((await(await r.post("object/links",{signal:n.signal,searchParams:M({arg:`${t instanceof Uint8Array?z.decode(t):t}`,...n}),headers:n.headers})).json()).Links||[]).map(s=>({Name:s.Name,Tsize:s.Size,Hash:z.parse(s.Hash)}))}return e});var $ue=D(r=>{async function e(t={}){let n=await r.post("object/new",{signal:t.signal,searchParams:M({arg:t.template,...t}),headers:t.headers}),{Hash:i}=await n.json();return z.parse(i)}return e});var que=(r,e)=>D(n=>{let i=Lv(r,e);async function o(s,a={}){return i(s,{...a,storeCodec:"dag-pb",hashAlg:"sha2-256",version:1})}return o})(e);var Hue=D(r=>{async function e(t,n={}){let o=await(await r.post("object/stat",{signal:n.signal,searchParams:M({arg:`${t}`,...n}),headers:n.headers})).json();return{...o,Hash:z.parse(o.Hash)}}return e});var Gue=D(r=>{async function e(t,n,i={}){let o=await r.post("object/patch/add-link",{signal:i.signal,searchParams:M({arg:[`${t}`,n.Name||n.name||"",(n.Hash||n.cid||"").toString()||null],...i}),headers:i.headers}),{Hash:s}=await o.json();return z.parse(s)}return e});var jue=D(r=>{async function e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal),a=await r.post("object/patch/append-data",{signal:s,searchParams:M({arg:`${t}`,...i}),...await Dn([n],o,i.headers)}),{Hash:c}=await a.json();return z.parse(c)}return e});var Wue=D(r=>{async function e(t,n,i={}){let o=await r.post("object/patch/rm-link",{signal:i.signal,searchParams:M({arg:[`${t}`,n.Name||n.name||null],...i}),headers:i.headers}),{Hash:s}=await o.json();return z.parse(s)}return e});var Yue=D(r=>{async function e(t,n,i={}){let o=new AbortController,s=On(o.signal,i.signal),a=await r.post("object/patch/set-data",{signal:s,searchParams:M({arg:[`${t}`],...i}),...await Dn([n],o,i.headers)}),{Hash:c}=await a.json();return z.parse(c)}return e});function Que(r){return{addLink:Gue(r),appendData:jue(r),rmLink:Wue(r),setData:Yue(r)}}function Xue(r,e){return{data:zue(e),get:Vue(e),links:Kue(e),new:$ue(e),put:que(r,e),stat:Hue(e),patch:Que(e)}}var Mv=D(r=>{async function*e(t,n={}){for await(let{path:i,recursive:o,metadata:s}of Tc(t)){let a=await r.post("pin/add",{signal:n.signal,searchParams:M({...n,arg:i,recursive:o,metadata:s?JSON.stringify(s):void 0,stream:!0}),headers:n.headers});for await(let c of a.ndjson()){if(c.Pins){for(let u of c.Pins)yield z.parse(u);continue}yield z.parse(c)}}}return e});function Zue(r){let e=Mv(r);return D(()=>{async function t(n,i={}){return Dr(e([{path:n,...i}],i))}return t})(r)}function Jue(r,e,t){let n={type:r,cid:z.parse(e)};return t&&(n.metadata=t),n}var ele=D(r=>{async function*e(t={}){let n=[];t.paths&&(n=Array.isArray(t.paths)?t.paths:[t.paths]);let i=await r.post("pin/ls",{signal:t.signal,searchParams:M({...t,arg:n.map(o=>`${o}`),stream:!0}),headers:t.headers});for await(let o of i.ndjson()){if(o.Keys){for(let s of Object.keys(o.Keys))yield Jue(o.Keys[s].Type,s,o.Keys[s].Metadata);return}yield Jue(o.Type,o.Cid,o.Metadata)}}return e});var Uv=D(r=>{async function*e(t,n={}){for await(let{path:i,recursive:o}of Tc(t)){let s=new URLSearchParams(n.searchParams);s.append("arg",`${i}`),o!=null&&s.set("recursive",String(o));let a=await r.post("pin/rm",{signal:n.signal,headers:n.headers,searchParams:M({...n,arg:`${i}`,recursive:o})});for await(let c of a.ndjson()){if(c.Pins){yield*c.Pins.map(u=>z.parse(u));continue}yield z.parse(c)}}}return e});var tle=r=>{let e=Uv(r);return D(()=>{async function t(n,i={}){return Dr(e([{path:n,...i}],i))}return t})(r)};var Fv=({Name:r,Status:e,Cid:t})=>({cid:z.parse(t),name:r,status:e}),rle=r=>{if(typeof r=="string"&&r!=="")return r;throw new TypeError("service name must be passed")},nle=r=>{if(z.asCID(r))return r.toString();throw new TypeError(`CID instance expected instead of ${typeof r}`)},K2=({service:r,cid:e,name:t,status:n,all:i})=>{let o=M({service:rle(r),name:t,force:i?!0:void 0});if(e)for(let s of e)o.append("cid",nle(s));if(n)for(let s of n)o.append("status",s);return o},ile=({cid:r,service:e,background:t,name:n,origins:i})=>{let o=M({arg:nle(r),service:rle(e),name:n,background:t?!0:void 0});if(i)for(let s of i)o.append("origin",s.toString());return o};function ole(r){async function e(t,{timeout:n,signal:i,headers:o,...s}){let a=await r.post("pin/remote/add",{timeout:n,signal:i,headers:o,searchParams:ile({cid:t,...s})});return Fv(await a.json())}return e}function sle(r){async function*e({timeout:t,signal:n,headers:i,...o}){let s=await r.post("pin/remote/ls",{timeout:t,signal:n,headers:i,searchParams:K2(o)});for await(let a of s.ndjson())yield Fv(a)}return e}function ale(r){async function e({timeout:t,signal:n,headers:i,...o}){await r.post("pin/remote/rm",{timeout:t,signal:n,headers:i,searchParams:K2({...o,all:!1})})}return e}function cle(r){async function e({timeout:t,signal:n,headers:i,...o}){await r.post("pin/remote/rm",{timeout:t,signal:n,headers:i,searchParams:K2({...o,all:!0})})}return e}function ule(r){let e=String(r);if(e==="undefined")throw Error("endpoint is required");return e[e.length-1]==="/"?e.slice(0,-1):e}function lle(r){return{service:r.Service,endpoint:new URL(r.ApiEndpoint),...r.Stat&&{stat:XMe(r.Stat)}}}function XMe(r){switch(r.Status){case"valid":{let{Pinning:e,Pinned:t,Queued:n,Failed:i}=r.PinCount;return{status:"valid",pinCount:{queued:n,pinning:e,pinned:t,failed:i}}}case"invalid":return{status:"invalid"};default:return{status:r.Status}}}function fle(r){async function e(t,n){let{endpoint:i,key:o,headers:s,timeout:a,signal:c}=n;await r.post("pin/remote/service/add",{timeout:a,signal:c,searchParams:M({arg:[t,ule(i),o]}),headers:s})}return e}function dle(r){async function e(t={}){let{stat:n,headers:i,timeout:o,signal:s}=t,a=await r.post("pin/remote/service/ls",{timeout:o,signal:s,headers:i,searchParams:n===!0?M({stat:n}):void 0}),{RemoteServices:c}=await a.json();return c.map(lle)}return e}function hle(r){async function e(t,n={}){await r.post("pin/remote/service/rm",{signal:n.signal,headers:n.headers,searchParams:M({arg:t})})}return e}function ple(r){let e=new Hd(r);return{add:fle(e),ls:dle(e),rm:hle(e)}}function mle(r){let e=new Hd(r);return{add:ole(e),ls:sle(e),rm:ale(e),rmAll:cle(e),service:ple(r)}}function gle(r){return{addAll:Mv(r),add:Zue(r),ls:ele(r),rmAll:Uv(r),rm:tle(r),remote:mle(r)}}var yle=r=>Array.isArray(r)?r.map(zv):r,zv=r=>re($2(r)),$2=r=>Gg.decode(r),wle=r=>BigInt(`0x${re(Gg.decode(r),"base16")}`),q2=r=>Gg.encode(Ie(r));var ble=D(r=>{async function e(t={}){let{Strings:n}=await(await r.post("pubsub/ls",{signal:t.signal,searchParams:M(t),headers:t.headers})).json();return yle(n)||[]}return e});var _le=D(r=>{async function e(t,n={}){let i=await r.post("pubsub/peers",{signal:n.signal,searchParams:M({arg:q2(t),...n}),headers:n.headers}),{Strings:o}=await i.json();return o||[]}return e});var Ele=D(r=>{async function e(t,n,i={}){let o=M({arg:q2(t),...i}),s=new AbortController,a=On(s.signal,i.signal);await(await r.post("pubsub/pub",{signal:a,searchParams:o,...await Dn([n],s,i.headers)})).text()}return e});var ZMe=j("ipfs-http-client:pubsub:subscribe"),vle=(r,e)=>D(t=>{async function n(i,o,s={}){s.signal=e.subscribe(i,o,s.signal);let a,c,u=new Promise((f,h)=>{a=f,c=h}),l=setTimeout(()=>a(),1e3);return t.post("pubsub/sub",{signal:s.signal,searchParams:M({arg:q2(i),...s}),headers:s.headers}).catch(f=>{e.unsubscribe(i,o),c(f)}).then(f=>{clearTimeout(l),f&&(JMe(f,{onMessage:h=>{if(o){if(typeof o=="function"){o(h);return}typeof o.handleEvent=="function"&&o.handleEvent(h)}},onEnd:()=>e.unsubscribe(i,o),onError:s.onError}),a())}),u}return n})(r);async function JMe(r,{onMessage:e,onEnd:t,onError:n}){n=n||ZMe;try{for await(let i of r.ndjson())try{if(!i.from)continue;i.from!=null&&i.seqno!=null?e({type:"signed",from:Oe(i.from),data:$2(i.data),sequenceNumber:wle(i.seqno),topic:zv(i.topicIDs[0]),key:$2(i.key??"u"),signature:$2(i.signature??"u")}):e({type:"unsigned",data:$2(i.data),topic:zv(i.topicIDs[0])})}catch(o){o.message=`Failed to parse pubsub message: ${o.message}`,n(o,!1,i)}}catch(i){eUe(i)||n(i,!0)}finally{t()}}var eUe=r=>{switch(r.type){case"aborted":return!0;case"abort":return!0;default:return r.name==="AbortError"}};var xle=(r,e)=>{async function t(n,i){e.unsubscribe(n,i)}return t};var Vv=class{constructor(){this._subs=new Map}subscribe(e,t,n){let i=this._subs.get(e)||[];if(i.find(s=>s.handler===t))throw new Error(`Already subscribed to ${e} with this handler`);let o=new AbortController;return this._subs.set(e,[{handler:t,controller:o}].concat(i)),n&&n.addEventListener("abort",()=>this.unsubscribe(e,t)),o.signal}unsubscribe(e,t){let n=this._subs.get(e)||[],i;t?(this._subs.set(e,n.filter(o=>o.handler!==t)),i=n.filter(o=>o.handler===t)):(this._subs.set(e,[]),i=n),(this._subs.get(e)||[]).length||this._subs.delete(e),i.forEach(o=>o.controller.abort())}};function Sle(r){let e=new Vv;return{ls:ble(r),peers:_le(r),publish:Ele(r),subscribe:vle(r,e),unsubscribe:xle(r,e)}}var Ale=D(r=>{async function*e(t={}){yield*(await r.post("refs/local",{signal:t.signal,transform:kt,searchParams:M(t),headers:t.headers})).ndjson()}return e});var Tle=D((r,e)=>Object.assign(async function*(n,i={}){let o=Array.isArray(n)?n:[n];yield*(await r.post("refs",{signal:i.signal,searchParams:M({arg:o.map(a=>`${a instanceof Uint8Array?z.decode(a):a}`),...i}),headers:i.headers,transform:kt})).ndjson()},{local:Ale(e)}));var Ile=D(r=>{async function*e(t={}){yield*(await r.post("repo/gc",{signal:t.signal,searchParams:M(t),headers:t.headers,transform:i=>({err:i.Error?new Error(i.Error):null,cid:(i.Key||{})["/"]?z.parse(i.Key["/"]):null})})).ndjson()}return e});var Kv=D(r=>{async function e(t={}){let i=await(await r.post("repo/stat",{signal:t.signal,searchParams:M(t),headers:t.headers})).json();return{numObjects:BigInt(i.NumObjects),repoSize:BigInt(i.RepoSize),repoPath:i.RepoPath,version:i.Version,storageMax:BigInt(i.StorageMax)}}return e});var Rle=D(r=>{async function e(t={}){return(await(await r.post("repo/version",{signal:t.signal,searchParams:M(t),headers:t.headers})).json()).Version}return e});function Cle(r){return{gc:Ile(r),stat:Kv(r),version:Rle(r)}}var Ple=D(r=>{async function*e(t={}){yield*(await r.post("stats/bw",{signal:t.signal,searchParams:M(t),headers:t.headers,transform:i=>({totalIn:BigInt(i.TotalIn),totalOut:BigInt(i.TotalOut),rateIn:parseFloat(i.RateIn),rateOut:parseFloat(i.RateOut)})})).ndjson()}return e});function kle(r){return{bitswap:Dv(r),repo:Kv(r),bw:Ple(r)}}var Nle=D(r=>{async function e(t={}){let n=await r.post("swarm/addrs",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Addrs:i}=await n.json();return Object.keys(i).map(o=>({id:Oe(o),addrs:(i[o]||[]).map(s=>yt(s))}))}return e});var Dle=D(r=>{async function e(t,n={}){let i=await r.post("swarm/connect",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Strings:o}=await i.json();return o||[]}return e});var Ole=D(r=>{async function e(t,n={}){let i=await r.post("swarm/disconnect",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Strings:o}=await i.json();return o||[]}return e});var Lle=D(r=>{async function e(t={}){let n=await r.post("swarm/addrs/local",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Strings:i}=await n.json();return(i||[]).map(o=>yt(o))}return e});var Ble=D(r=>{async function e(t={}){let n=await r.post("swarm/peers",{signal:t.signal,searchParams:M(t),headers:t.headers}),{Peers:i}=await n.json();return(i||[]).map(o=>({addr:yt(o.Addr),peer:Oe(o.Peer),muxer:o.Muxer,latency:o.Latency,streams:o.Streams,direction:o.Direction==null?void 0:o.Direction===0?"inbound":"outbound"}))}return e});function Mle(r){return{addrs:Nle(r),connect:Dle(r),disconnect:Ole(r),localAddrs:Lle(r),peers:Ble(r)}}var $v=D(r=>{async function*e(t,n={}){let i=new AbortController,o=On(i.signal,n.signal),{headers:s,body:a,total:c,parts:u}=await Dn(t,i,n.headers),[l,f]=typeof n.progress=="function"?tUe(c,u,n.progress):[void 0,void 0],h=await r.post("add",{searchParams:M({"stream-channels":!0,...n,progress:!!l}),onUploadProgress:f,signal:o,headers:s,body:a});for await(let d of h.ndjson())d=kt(d),d.hash!==void 0?yield nUe(d):l&&l(d.bytes||0,d.name)}return e}),tUe=(r,e,t)=>e?[void 0,rUe(r,e,t)]:[t,void 0],rUe=(r,e,t)=>{let n=0,i=e.length;return({loaded:o,total:s})=>{let a=Math.floor(o/s*r);for(;n{async function t(n,i={}){return await Dr(e(W_(n),i))}return t})(r)}var Fle=D(r=>{async function*e(t,n={}){yield*(await r.post("cat",{signal:n.signal,searchParams:M({arg:t.toString(),...n}),headers:n.headers})).iterator()}return e});var zle=D(r=>async(t={})=>(await r.post("commands",{signal:t.signal,searchParams:M(t),headers:t.headers})).json());var Vle=D(r=>async(t,n={})=>(await(await r.post("dns",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers})).json()).Path);var Kle=D(r=>()=>{let e=new URL(r.opts.base||"");return{host:e.hostname,port:e.port,protocol:e.protocol,pathname:e.pathname,"api-path":e.pathname}});var $le=D(r=>{async function*e(t,n={}){let i={arg:`${t instanceof Uint8Array?z.decode(t):t}`,...n};i.compressionLevel&&(i["compression-level"]=i.compressionLevel,delete i.compressionLevel),yield*(await r.post("get",{signal:n.signal,searchParams:M(i),headers:n.headers})).iterator()}return e});var qv=D(r=>{async function e(t={}){let i=await(await r.post("id",{signal:t.signal,searchParams:M({arg:t.peerId?t.peerId.toString():void 0,...t}),headers:t.headers})).json(),o={...kt(i)};return o.id=Oe(o.id),o.addresses&&(o.addresses=o.addresses.map(s=>yt(s))),o}return e});var qle=r=>{let e=qv(r);async function t(n={}){let i=await e(n);return!!(i&&i.addresses&&i.addresses.length)}return t};var Hle=D((r,e)=>{async function*t(n,i={}){let o=`${n instanceof Uint8Array?z.decode(n):n}`;async function s(c){let u=c.Hash;if(u.includes("/")){let f=u.startsWith("/ipfs/")?u:`/ipfs/${u}`;u=(await Bv(e)(f)).cid}else u=z.parse(u);let l={name:c.Name,path:o+(c.Name?`/${c.Name}`:""),size:c.Size,cid:u,type:iUe(c)};return c.Mode&&(l.mode=parseInt(c.Mode,8)),c.Mtime!==void 0&&c.Mtime!==null&&(l.mtime={secs:c.Mtime},c.MtimeNsecs!==void 0&&c.MtimeNsecs!==null&&(l.mtime.nsecs=c.MtimeNsecs)),l}let a=await r.post("ls",{signal:i.signal,searchParams:M({arg:o,...i}),headers:i.headers});for await(let c of a.ndjson()){if(c=c.Objects,!c)throw new Error("expected .Objects in results");if(c=c[0],!c)throw new Error("expected one array in results.Objects");let u=c.Links;if(!Array.isArray(u))throw new Error("expected one array in results.Objects[0].Links");if(!u.length){yield s(c);return}yield*u.map(s)}}return t});function iUe(r){switch(r.Type){case 1:case 5:return"dir";case 2:return"file";default:return"file"}}var Gle=D(r=>{async function e(t={}){let n=await r.post("dns",{signal:t.signal,searchParams:M(t),headers:t.headers});return kt(await n.json())}return e});var jle=D(r=>{async function*e(t,n={}){yield*(await r.post("ping",{signal:n.signal,searchParams:M({arg:`${t}`,...n}),headers:n.headers,transform:kt})).ndjson()}return e});var Wle=D(r=>{async function e(t,n={}){let i=await r.post("resolve",{signal:n.signal,searchParams:M({arg:t,...n}),headers:n.headers}),{Path:o}=await i.json();return o}return e});var Yle=C(ee(),1),Qle=D(r=>async(t={})=>{throw(0,Yle.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")});var Xle=D(r=>{async function e(t={}){await(await r.post("shutdown",{signal:t.signal,searchParams:M(t),headers:t.headers})).text()}return e});var Zle=D(r=>{async function e(t={}){let n=await r.post("version",{signal:t.signal,searchParams:M(t),headers:t.headers});return{...kt(await n.json()),"ipfs-http-client":"1.0.0"}}return e});var cUe=C(dL(),1);function efe(r={}){let e={name:Ii.name,code:Ii.code,encode:u=>u,decode:u=>u},t=Object.values(Vu);(r.ipld&&r.ipld.bases?r.ipld.bases:[]).forEach(u=>t.push(u));let n=new F2({bases:t,loadBase:r.ipld&&r.ipld.loadBase}),i=Object.values(x8);[sr,o1,a1,yy,e].concat(r.ipld&&r.ipld.codecs||[]).forEach(u=>i.push(u));let o=new z2({codecs:i,loadCodec:r.ipld&&r.ipld.loadCodec}),s=Object.values(v8);(r.ipld&&r.ipld.hashers?r.ipld.hashers:[]).forEach(u=>s.push(u));let a=new V2({hashers:s,loadHasher:r.ipld&&r.ipld.loadHasher});return{add:Ule(r),addAll:$v(r),bitswap:mce(r),block:Ace(r),bootstrap:kce(r),cat:Fle(r),commands:zle(r),config:Fce(r),dag:Hce(o,r),dht:Zce(r),diag:rue(r),dns:Vle(r),files:wue(r),get:$le(r),getEndpointConfig:Kle(r),id:qv(r),isOnline:qle(r),key:Rue(r),log:Nue(r),ls:Hle(r),mount:Gle(r),name:Fue(r),object:Xue(o,r),pin:gle(r),ping:jle(r),pubsub:Sle(r),refs:Tle(r),repo:Cle(r),resolve:Wle(r),start:Qle(r),stats:kle(r),stop:Xle(r),swarm:Mle(r),version:Zle(r),bases:n,codecs:o,hashers:a}}var t4=C(ee(),1);var Gd=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function tfe(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function sa(r,e,t){let n=t??{},i=tfe(r);async function*o(){let s,a=()=>{s!=null&&s()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new Gd(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:d}=n;f(new Gd(h,d))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&await n.onAbort(r),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function uUe(r,e,t){return n=>r(sa(n,e,t))}function ps(r,e,t){return{sink:uUe(r.sink,e,{...t,onAbort:void 0}),source:sa(r.source,e,t)}}var lUe=Ye("dns4"),fUe=Ye("dns6"),dUe=Ye("dnsaddr"),H2=qi(Ye("dns"),dUe,lUe,fUe),Hv=qi(Ye("ip4"),Ye("ip6")),V5=qi(_t(Hv,Ye("tcp")),_t(H2,Ye("tcp"))),nfe=_t(Hv,Ye("udp")),hUe=_t(nfe,Ye("utp")),pUe=_t(nfe,Ye("quic")),U5=qi(_t(V5,Ye("ws")),_t(H2,Ye("ws"))),F5=qi(_t(V5,Ye("wss")),_t(H2,Ye("wss"))),hL=qi(_t(V5,Ye("http")),_t(Hv,Ye("http")),_t(H2,Ye("http"))),pL=qi(_t(V5,Ye("https")),_t(Hv,Ye("https")),_t(H2,Ye("https"))),Gv=qi(_t(U5,Ye("p2p-webrtc-star"),Ye("p2p")),_t(F5,Ye("p2p-webrtc-star"),Ye("p2p")),_t(U5,Ye("p2p-webrtc-star")),_t(F5,Ye("p2p-webrtc-star"))),WMt=qi(_t(U5,Ye("p2p-websocket-star"),Ye("p2p")),_t(F5,Ye("p2p-websocket-star"),Ye("p2p")),_t(U5,Ye("p2p-websocket-star")),_t(F5,Ye("p2p-websocket-star"))),ife=qi(_t(hL,Ye("p2p-webrtc-direct"),Ye("p2p")),_t(pL,Ye("p2p-webrtc-direct"),Ye("p2p")),_t(hL,Ye("p2p-webrtc-direct")),_t(pL,Ye("p2p-webrtc-direct"))),z5=qi(U5,F5,hL,pL,Gv,ife,V5,hUe,pUe,H2),YMt=qi(_t(z5,Ye("p2p-stardust"),Ye("p2p")),_t(z5,Ye("p2p-stardust"))),jd=qi(_t(z5,Ye("p2p")),Gv,ife,Ye("p2p")),rfe=qi(_t(jd,Ye("p2p-circuit"),jd),_t(jd,Ye("p2p-circuit")),_t(Ye("p2p-circuit"),jd),_t(z5,Ye("p2p-circuit")),_t(Ye("p2p-circuit"),z5),Ye("p2p-circuit")),ofe=()=>qi(_t(rfe,ofe),rfe),i0=ofe(),QMt=qi(_t(i0,jd,i0),_t(jd,i0),_t(i0,jd),i0,jd);function sfe(r){function e(t){let n;try{n=lt(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function _t(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:sfe(e),partialMatch:e}}function qi(...r){function e(n){let i=null;return r.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:sfe(e),partialMatch:e}}function Ye(r){let e=r;function t(i){let o;try{o=lt(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}var jfe=C(ee(),1);var ic=Object.create(null);ic.open="0";ic.close="1";ic.ping="2";ic.pong="3";ic.message="4";ic.upgrade="5";ic.noop="6";var K5=Object.create(null);Object.keys(ic).forEach(r=>{K5[ic[r]]=r});var cfe={type:"error",data:"parser error"};var mUe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",gUe=typeof ArrayBuffer=="function",yUe=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,wUe=({type:r,data:e},t,n)=>mUe&&e instanceof Blob?t?n(e):ufe(e,n):gUe&&(e instanceof ArrayBuffer||yUe(e))?t?n(e):ufe(new Blob([e]),n):n(ic[r]+(e||"")),ufe=(r,e)=>{let t=new FileReader;return t.onload=function(){let n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)},jv=wUe;var lfe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$5=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r{let e=r.length*.75,t=r.length,n,i=0,o,s,a,c;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);let u=new ArrayBuffer(e),l=new Uint8Array(u);for(n=0;n>4,l[i++]=(s&15)<<4|a>>2,l[i++]=(a&3)<<6|c&63;return u};var bUe=typeof ArrayBuffer=="function",_Ue=(r,e)=>{if(typeof r!="string")return{type:"message",data:dfe(r,e)};let t=r.charAt(0);return t==="b"?{type:"message",data:EUe(r.substring(1),e)}:K5[t]?r.length>1?{type:K5[t],data:r.substring(1)}:{type:K5[t]}:cfe},EUe=(r,e)=>{if(bUe){let t=ffe(r);return dfe(t,e)}else return{base64:!0,data:r}},dfe=(r,e)=>{switch(e){case"blob":return r instanceof ArrayBuffer?new Blob([r]):r;case"arraybuffer":default:return r}},Wv=_Ue;var hfe=String.fromCharCode(30),pfe=(r,e)=>{let t=r.length,n=new Array(t),i=0;r.forEach((o,s)=>{jv(o,!1,a=>{n[s]=a,++i===t&&e(n.join(hfe))})})},mfe=(r,e)=>{let t=r.split(hfe),n=[];for(let i=0;itypeof self<"u"?self:typeof window<"u"?window:Function("return this")())();function Yv(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var xUe=Hi.setTimeout,SUe=Hi.clearTimeout;function Il(r,e){e.useNativeTimers?(r.setTimeoutFn=xUe.bind(Hi),r.clearTimeoutFn=SUe.bind(Hi)):(r.setTimeoutFn=Hi.setTimeout.bind(Hi),r.clearTimeoutFn=Hi.clearTimeout.bind(Hi))}var AUe=1.33;function gfe(r){return typeof r=="string"?TUe(r):Math.ceil((r.byteLength||r.size)*AUe)}function TUe(r){let e=0,t=0;for(let n=0,i=r.length;n=57344?t+=3:(n++,t+=4);return t}var gL=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}},o0=class extends Tr{constructor(e){super(),this.writable=!1,Il(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new gL(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Wv(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}};var _fe="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),yL=64,IUe={},yfe=0,Qv=0,wfe;function bfe(r){let e="";do e=_fe[r%yL]+e,r=Math.floor(r/yL);while(r>0);return e}function Xv(){let r=bfe(+new Date);return r!==wfe?(yfe=0,wfe=r):r+"."+bfe(yfe++)}for(;Qv{this.readyState="paused",e()};if(this.polling||!this.writable){let n=0;this.polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};mfe(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,pfe(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.query||{},t=this.opts.secure?"https":"http",n="";this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Xv()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.opts.port&&(t==="https"&&Number(this.opts.port)!==443||t==="http"&&Number(this.opts.port)!==80)&&(n=":"+this.opts.port);let i=Zv(e),o=this.opts.hostname.indexOf(":")!==-1;return t+"://"+(o?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(i.length?"?"+i:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new aa(this.uri(),e)}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}},aa=class extends Tr{constructor(e,t){super(),Il(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=t.async!==!1,this.data=t.data!==void 0?t.data:null,this.create()}create(){let e=Yv(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;let t=this.xhr=new wL(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let n in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(n)&&t.setRequestHeader(n,this.opts.extraHeaders[n])}}catch{}if(this.method==="POST")try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{t.setRequestHeader("Accept","*/*")}catch{}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{t.readyState===4&&(t.status===200||t.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof t.status=="number"?t.status:0)},0))},t.send(this.data)}catch(n){this.setTimeoutFn(()=>{this.onError(n)},0);return}typeof document<"u"&&(this.index=aa.requestsCount++,aa.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=RUe,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete aa.requests[this.index],this.xhr=null}}onLoad(){let e=this.xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};aa.requestsCount=0;aa.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Sfe);else if(typeof addEventListener=="function"){let r="onpagehide"in Hi?"pagehide":"unload";addEventListener(r,Sfe,!1)}}function Sfe(){for(let r in aa.requests)aa.requests.hasOwnProperty(r)&&aa.requests[r].abort()}var q5=(()=>typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0))(),H5=Hi.WebSocket||Hi.MozWebSocket,e9=!0,Afe="arraybuffer";var Tfe=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",t9=class extends o0{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;let e=this.uri(),t=this.opts.protocols,n=Tfe?{}:Yv(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=e9&&!Tfe?t?new H5(e,t):new H5(e):new H5(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType||Afe,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t{let s={};e9||(n.options&&(s.compress=n.options.compress),this.opts.perMessageDeflate&&(typeof o=="string"?Buffer.byteLength(o):o.length){this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{},t=this.opts.secure?"wss":"ws",n="";this.opts.port&&(t==="wss"&&Number(this.opts.port)!==443||t==="ws"&&Number(this.opts.port)!==80)&&(n=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=Xv()),this.supportsBinary||(e.b64=1);let i=Zv(e),o=this.opts.hostname.indexOf(":")!==-1;return t+"://"+(o?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(i.length?"?"+i:"")}check(){return!!H5}};var bL={websocket:t9,polling:Jv};var PUe=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,kUe=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function G2(r){let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=PUe.exec(r||""),o={},s=14;for(;s--;)o[kUe[s]]=i[s]||"";return t!=-1&&n!=-1&&(o.source=e,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=NUe(o,o.path),o.queryKey=DUe(o,o.query),o}function NUe(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function DUe(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,o){i&&(t[i]=o)}),t}var ms=class extends Tr{constructor(e,t={}){super(),this.writeBuffer=[],e&&typeof e=="object"&&(t=e,e=null),e?(e=G2(e),t.hostname=e.host,t.secure=e.protocol==="https"||e.protocol==="wss",t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=G2(t.host).host),Il(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Efe(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=mL,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new bL[e](n)}open(){let e;if(this.opts.rememberUpgrade&&ms.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)e="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else e=this.transports[0];this.readyState="opening";try{e=this.createTransport(e)}catch{this.transports.shift(),this.open();return}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",t=>this.onClose("transport close",t))}probe(e){let t=this.createTransport(e),n=!1;ms.priorWebsocketSuccess=!1;let i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",f=>{if(!n)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ms.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let h=new Error("probe error");h.transport=t.name,this.emitReserved("upgradeError",h)}}))};function o(){n||(n=!0,l(),t.close(),t=null)}let s=f=>{let h=new Error("probe error: "+f);h.transport=t.name,o(),this.emitReserved("upgradeError",h)};function a(){s("transport closed")}function c(){s("socket closed")}function u(f){t&&f.name!==t.name&&o()}let l=()=>{t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",a),this.off("close",c),this.off("upgrading",u)};t.once("open",i),t.once("error",s),t.once("close",a),this.once("close",c),this.once("upgrading",u),t.open()}onOpen(){if(this.readyState="open",ms.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let e=0,t=this.upgrades.length;for(;e{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n0&&t>this.maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){let e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}onError(e){ms.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){let t=[],n=0,i=e.length;for(;nW5,Encoder:()=>vL,PacketType:()=>Nt,protocol:()=>kfe});var OUe=typeof ArrayBuffer=="function",LUe=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Rfe=Object.prototype.toString,BUe=typeof Blob=="function"||typeof Blob<"u"&&Rfe.call(Blob)==="[object BlobConstructor]",MUe=typeof File=="function"||typeof File<"u"&&Rfe.call(File)==="[object FileConstructor]";function j5(r){return OUe&&(r instanceof ArrayBuffer||LUe(r))||BUe&&r instanceof Blob||MUe&&r instanceof File}function G5(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t=0&&r.num0;case Nt.ACK:case Nt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},xL=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=Pfe(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function gs(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var UUe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),j2=class extends Tr{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[gs(e,"open",this.onopen.bind(this)),gs(e,"packet",this.onpacket.bind(this)),gs(e,"error",this.onerror.bind(this)),gs(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(UUe.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:Nt.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let s=this.ids++,a=t.pop();this._registerAckCallback(s,a),n.id=s}let i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var n;let i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}let o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let s=0;s{this.io.clearTimeoutFn(o),t.apply(this,[null,...s])}}emitWithAck(e,...t){let n=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((i,o)=>{t.push((s,a)=>n?s?o(s):i(a):i(s)),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...o)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...o)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Nt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Nt.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Nt.EVENT:case Nt.BINARY_EVENT:this.onevent(e);break;case Nt.ACK:case Nt.BINARY_ACK:this.onack(e);break;case Nt.DISCONNECT:this.ondisconnect();break;case Nt.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...i){n||(n=!0,t.packet({type:Nt.ACK,id:e,data:i}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Nt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n0&&r.jitter<=1?r.jitter:0,this.attempts=0}s0.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};s0.prototype.reset=function(){this.attempts=0};s0.prototype.setMin=function(r){this.ms=r};s0.prototype.setMax=function(r){this.max=r};s0.prototype.setJitter=function(r){this.jitter=r};var W2=class extends Tr{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Il(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new s0({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let i=t.parser||SL;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ms(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let i=gs(t,"open",function(){n.onopen(),e&&e()}),o=gs(t,"error",s=>{n.cleanup(),n._readyState="closed",this.emitReserved("error",s),e?e(s):n.maybeReconnectOnOpen()});if(this._timeout!==!1){let s=this._timeout;s===0&&i();let a=this.setTimeoutFn(()=>{i(),t.close(),t.emit("error",new Error("timeout"))},s);this.opts.autoUnref&&a.unref(),this.subs.push(function(){clearTimeout(a)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(gs(e,"ping",this.onping.bind(this)),gs(e,"data",this.ondata.bind(this)),gs(e,"error",this.onerror.bind(this)),gs(e,"close",this.onclose.bind(this)),gs(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){q5(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new j2(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;ne()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(function(){clearTimeout(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};var Y5={};function Q5(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=Ife(r,e.path||"/socket.io"),n=t.source,i=t.id,o=t.path,s=Y5[i]&&o in Y5[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||s,c;return a?c=new W2(n,e):(Y5[i]||(Y5[i]=new W2(n,e)),c=Y5[i]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(Q5,{Manager:W2,Socket:j2,io:Q5,connect:Q5});var a0=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Rl,Zt=class extends EventTarget{constructor(){super(...arguments),Rl.set(this,new Map)}listenerCount(e){let t=a0(this,Rl,"f").get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=a0(this,Rl,"f").get(e);i==null&&(i=[],a0(this,Rl,"f").set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&(n==null?void 0:n.once))??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=a0(this,Rl,"f").get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),a0(this,Rl,"f").set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=a0(this,Rl,"f").get(e.type);return n==null||(n=n.filter(({once:i})=>!i),a0(this,Rl,"f").set(e.type,n)),t}safeDispatchEvent(e,t){return this.dispatchEvent(new ve(e,t))}};Rl=new WeakMap;var AL=class extends Event{constructor(e,t){super(e,t),this.detail=t==null?void 0:t.detail}},ve=globalThis.CustomEvent??AL;var X5=C(ee(),1),Ufe=C(r9(),1);var Ofe=C(ee(),1);var Dfe=64*1024,zUe=5*1e3,n9=class{constructor(e,t){this.label=e.label,this.open=io(),this.channel=e,this.channel.binaryType="arraybuffer",this.log=t.log,typeof this.channel.bufferedAmountLowThreshold=="number"&&(this.channel.bufferedAmountLowThreshold=Dfe),e.addEventListener("message",i=>{t.onMessage(i)}),e.addEventListener("bufferedamountlow",()=>{this.log("stop backpressure: bufferedAmount %d",this.channel.bufferedAmount),this.open.resolve()}),e.addEventListener("open",()=>{this.open.resolve(),t.onOpen()}),e.addEventListener("close",()=>{t.onClose()}),e.addEventListener("error",i=>{var s,a,c,u,l;if(((s=i.error)==null?void 0:s.message)==="Transport channel closed")return this.close();t.log.error('channel encounter an error in state "%s" message: "%s" detail: "%s',e.readyState,(a=i.error)==null?void 0:a.message,(c=i.error)==null?void 0:c.errorDetail);let o=i.error instanceof Error?i.error:new Error(`datachannel error: ${(u=i.error)==null?void 0:u.message} ${(l=i.error)==null?void 0:l.errorDetail}`);t.onError((0,Ofe.default)(o,"ERR_DATA_CHANNEL"))});let n=!1;this.closingInterval=setInterval(()=>{e.readyState==="closing"?(n&&t.onClose(),n=!0):n=!1},zUe)}async send(e){await this.open.promise,this.channel.send(e),this.channel.bufferedAmount>Dfe&&(this.log("start backpressure: bufferedAmount %d",this.channel.bufferedAmount),this.open=io())}close(){clearInterval(this.closingInterval),this.channel.close()}get bufferedAmount(){return this.channel.bufferedAmount}};var Ffe=C(RL(),1),KUe={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}]};function $Ue(){if(typeof globalThis>"u")throw(0,X5.default)(new Error("No WebRTC support detected"),"ERR_WEBRTC_SUPPORT");let r={RTCPeerConnection:globalThis.RTCPeerConnection??globalThis.mozRTCPeerConnection??globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription??globalThis.mozRTCSessionDescription??globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate??globalThis.mozRTCIceCandidate??globalThis.webkitRTCIceCandidate};if(r.RTCPeerConnection==null)throw(0,X5.default)(new Error("No WebRTC support detected"),"ERR_WEBRTC_SUPPORT");return r}var c0=class extends Zt{constructor(e){super(),this.id=e.id??Ee((0,Ufe.default)(4),"hex").slice(0,7),this.log=ue(`libp2p:webrtc-peer:${e.logPrefix}:${this.id}`),this.wrtc=e.wrtc??$Ue(),this.peerConnection=new this.wrtc.RTCPeerConnection(Object.assign({},KUe,e.peerConnectionConfig)),this.closed=!1,this.connected=io(),this.source=jn(),this.sink=async t=>{if(await this.connected.promise,this.channel==null)throw(0,X5.default)(new Error("Connected but no channel?!"),"ERR_DATA_CHANNEL");for await(let n of t)await this.channel.send(n);await this.close()}}handleDataChannelEvent(e){let t=e.channel;if(t==null){this.close((0,X5.default)(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL")).catch(n=>{this.log("Error closing after event channel was found to be null",n)});return}this.channel=new n9(t,{log:this.log,onMessage:n=>{this.source.push(new Uint8Array(n.data))},onOpen:()=>{this.connected.resolve(),this.dispatchEvent(new ve("ready"))},onClose:()=>{this.close().catch(n=>{this.log("error closing connection after channel close",n)})},onError:n=>{this.close(n).catch(i=>{this.log("error closing connection after channel error",i)})}})}async close(e){var t;if(this.closed=!0,e==null&&this.channel!=null)for(;this.channel.bufferedAmount>0;)await(0,Ffe.default)(100);(t=this.channel)==null||t.close(),this.peerConnection.close(),this.source.end(e),this.dispatchEvent(new ve("close"))}};var zfe=C(ee(),1),Y2=class extends Zt{constructor(e){super(),this.log=e.log,this.peerConnection=e.peerConnection,this.wrtc=e.wrtc,this.status="idle",this.peerConnection.addEventListener("negotiationneeded",()=>{this.log("peer connection negotiation needed"),this.handleRenegotiate({type:"renegotiate"}).catch(t=>{this.log.error("could not renegotiate %o",t)})})}async handleSignal(e){if(this.log('incoming signal "%s"',e.type),e.type==="offer")return await this.handleOffer(e);if(e.type==="answer")return await this.handleAnswer(e);if(e.type==="candidate")return await this.handleCandidate(e);if(e.type==="renegotiate")return await this.handleRenegotiate(e);if(e.type==="goodbye")return await this.handleGoodye(e);this.log(`Unknown signal type ${e.type}`)}async handleOffer(e){}async handleAnswer(e){}async handleRenegotiate(e){}async handleGoodye(e){this.peerConnection.close()}async handleCandidate(e){let t=new this.wrtc.RTCIceCandidate(e.candidate);try{await this.peerConnection.addIceCandidate(t)}catch(n){if(t.address==null||t.address.endsWith(".local"))this.log("ignoring unsupported ICE candidate.");else throw(0,zfe.default)(n,"ERR_ADD_ICE_CANDIDATE")}}};var Vfe=ue("libp2p:webrtc-peer:receiver"),Z5=class extends c0{constructor(e={}){super({...e,logPrefix:"receiver"}),this.handshake=new CL({log:this.log,peerConnection:this.peerConnection,wrtc:this.wrtc,answerOptions:e.answerOptions}),this.handshake.addEventListener("signal",t=>this.dispatchEvent(new ve("signal",{detail:t.detail}))),this.peerConnection.addEventListener("datachannel",t=>{this.handleDataChannelEvent(t)})}handleSignal(e){this.handshake.handleSignal(e).catch(t=>{this.log("error handling signal %o %o",e,t)})}},CL=class extends Y2{constructor(e){super(e),this.options=e,this.status="idle",this.iceCandidates=[]}async handleRenegotiate(){Vfe.trace("renegotiate"),this.dispatchEvent(new ve("signal",{detail:{type:"renegotiate"}}))}async handleOffer(e){await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(e));for(let n of this.iceCandidates)await this.handleCandidate(n);this.iceCandidates=[];let t=await this.peerConnection.createAnswer(this.options.answerOptions);await this.peerConnection.setLocalDescription(t),Vfe.trace("handle offer",this.peerConnection.localDescription),this.dispatchEvent(new ve("signal",{detail:this.peerConnection.localDescription??t}))}async handleCandidate(e){if(this.peerConnection.remoteDescription==null||this.peerConnection.remoteDescription.type==null){this.iceCandidates.push(e);return}await super.handleCandidate(e)}};var $fe=C(r9(),1);var qUe=r=>{let e=r.on||r.addListener||r.addEventListener,t=r.off||r.removeListener||r.removeEventListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function HUe(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");let a=[e].flat(),c=[],{addListener:u,removeListener:l}=qUe(r),f=(...d)=>{let p=t.multiArgs?d:d[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),o(c)))},h=d=>{n(),s(d)};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)l(d,h)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)u(d,h);t.resolveImmediately&&o(c)});if(i.cancel=n,typeof t.timeout=="number"){let o=Ih(i,t.timeout);return o.cancel=n,o}return i}function Kfe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=HUe(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}var qfe=C(RL(),1);var PL=ue("libp2p:webrtc-peer:initator"),GUe=1e3,J5=class extends c0{constructor(e={}){super({...e,logPrefix:"initiator"}),this.handleDataChannelEvent({channel:this.peerConnection.createDataChannel(e.dataChannelLabel??Ee((0,$fe.default)(20),"hex").slice(0,7),e.dataChannelInit)}),this.handshake=new kL({log:this.log,peerConnection:this.peerConnection,wrtc:this.wrtc,offerOptions:e.offerOptions}),this.handshake.addEventListener("signal",t=>{this.dispatchEvent(new ve("signal",{detail:t.detail}))})}handleSignal(e){this.handshake.handleSignal(e).catch(t=>{this.log("error handling signal %o %o",e,t)})}},kL=class extends Y2{constructor(e){super(e),this.options=e,this.status="idle",this.peerConnection.addEventListener("icecandidate",t=>{if(t.candidate==null)return;let n={type:"candidate",candidate:{candidate:t.candidate.candidate,sdpMLineIndex:t.candidate.sdpMLineIndex,sdpMid:t.candidate.sdpMid}};PL.trace("create candidate",n),this.dispatchEvent(new ve("signal",{detail:n})),this.dispatchEvent(new ve("ice-candidate"))})}async handleRenegotiate(){if(this.status==="negotiating"){this.log("already negotiating, queueing");return}this.status="negotiating";let e=await this.peerConnection.createOffer(this.options.offerOptions);await this.peerConnection.setLocalDescription(e),await Kfe(this,"ice-candidate"),await(0,qfe.default)(GUe),PL.trace("renegotiate",this.peerConnection.localDescription),this.dispatchEvent(new ve("signal",{detail:this.peerConnection.localDescription??e}))}async handleAnswer(e){PL.trace("handle answer",e),await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(e)),this.status="idle"}};var NL=ue("libp2p:webrtc-star:socket");function i9(r,e){let{sink:t,source:n}=r,i={remoteAddr:e.remoteAddr,async sink(o){e.signal!=null&&(o=sa(o,e.signal));try{await t(o)}catch(s){s.type!=="aborted"&&NL.error(s)}},source:e.signal!=null?sa(n,e.signal):n,timeline:{open:Date.now()},async close(){if(r.closed)return;let o=Date.now(),s=setTimeout(()=>{if(i.remoteAddr!=null){let{host:a,port:c}=i.remoteAddr.toOptions();NL("timeout closing socket to %s:%s after %dms, destroying it manually",a,c,Date.now()-o)}r.closed||r.close().catch(a=>{NL.error("could not close socket",a)})},2e3);try{await r.close()}finally{clearTimeout(s)}}};return r.addEventListener("close",()=>{i.timeline.close==null&&(i.timeline.close=Date.now())},{once:!0}),i}function o9(r){let e=r.toString().split("/"),t=r.protos()[1].name,n=r.protos()[2].name,i=r.stringTuples()[1][1];if(t!=="tcp"||n!=="ws"&&n!=="wss")throw new Error(`invalid multiaddr: ${r.toString()}`);if(!sie(r))return`http://${e[2]}:${e[4]}`;if(n==="ws")return`http://${e[2]}${i==null||i==="80"?"":`:${i}`}`;if(n==="wss")return`https://${e[2]}${i==null||i==="443"?"":`:${i}`}`;throw new Error("invalid multiaddr: "+r.toString())}function Hfe(r){let e="/libp2p-webrtc-star";if(r.startsWith(e)){r=r.substring(e.length,r.length);let t=lt(r),n=t.stringTuples().filter(i=>i[0]===421)[0];if(n[1]==null)throw new Error("invalid multiaddr: "+r);t=t.decapsulate("p2p"),t=t.encapsulate("/p2p-webrtc-star"),t=t.encapsulate(`/p2p/${n[1]}`),r=t.toString()}return r}var Gi=ue("libp2p:webrtc-star:listener"),WUe={transports:["websocket"],path:"/socket.io-next/"},DL=class extends Zt{constructor(e,t,n,i,o){super(),this.signallingAddr=t,this.socket=Q5(e,WUe),this.connections=[],this.channels=new Map,this.pendingSignals=new Map,this.upgrader=n,this.handler=i,this.channelOptions=o,this.handleWsHandshake=this.handleWsHandshake.bind(this);let s=!1;this.socket.on("connect_error",a=>{s&&a.type==="TransportError"||this.dispatchEvent(new ve("error",{detail:a}))}),this.socket.on("error",a=>{this.dispatchEvent(new ve("error",{detail:a}))}),this.socket.on("ws-handshake",this.handleWsHandshake),this.socket.on("ws-peer",a=>{this.dispatchEvent(new ve("peer",{detail:a}))}),this.socket.on("connect",()=>{this.socket.emit("ss-join",this.signallingAddr.toString()),s&&this.dispatchEvent(new ve("reconnect"))}),this.socket.once("connect",()=>{s=!0,this.dispatchEvent(new ve("listening"))}),this.socket.on("disconnect",()=>{this.dispatchEvent(new ve("disconnect"))})}_createChannel(e,t,n){let i={...this.channelOptions},o=new Z5(i),s=a=>{let c=a.detail;Gi.error("incoming connection errored",c)};return o.addEventListener("error",s),o.addEventListener("close",()=>{o.removeEventListener("error",s)},{once:!0}),o.addEventListener("signal",a=>{let c=a.detail;this.socket.emit("ss-handshake",{intentId:e,srcMultiaddr:t,dstMultiaddr:n,answer:!0,signal:c})}),o.addEventListener("ready",()=>{let a=i9(o,{remoteAddr:this.signallingAddr});Gi("new inbound connection %s",a.remoteAddr);try{this.upgrader.upgradeInbound(a).then(c=>{Gi("inbound connection %s upgraded",a.remoteAddr),this.connections.push(a);let u=()=>{this.connections=this.connections.filter(l=>l!==a),this.channels.delete(e),this.pendingSignals.delete(e)};o.addEventListener("close",u,{once:!0}),this.dispatchEvent(new ve("connection",{detail:c})),this.handler(c)}).catch(c=>{Gi.error("inbound connection failed to upgrade",c),a.close().catch(u=>{Gi.error("inbound connection failed to close after failing to upgrade",u)})})}catch(c){Gi.error("inbound connection failed to upgrade",c),a.close().catch(u=>{Gi.error("inbound connection failed to close after failing to upgrade",u)})}},{once:!0}),o}handleWsHandshake(e){if(Gi('incoming handshake. signal type "%s" is answer %s',e.signal.type,e.answer),e.answer===!0||e.err!=null||e.intentId==null)return;let t=e.intentId,n=this.pendingSignals.get(t);n==null&&(n=[],this.pendingSignals.set(t,n)),n.push(e);let i=this.channels.get(t);if(i==null){if(e.signal.type!=="offer"){Gi("handshake is not an offer and channel does not exist, buffering until we receive an offer");return}Gi("creating new channel to handle offer handshake"),i=this._createChannel(e.intentId,e.srcMultiaddr,e.dstMultiaddr),this.channels.set(t,i)}else Gi("channel already exists, using it to handle handshake");for(;n.length>0;){let o=n.shift();(o==null?void 0:o.signal)!=null&&i.handleSignal(o.signal)}}async close(){this.socket.emit("ss-leave",this.signallingAddr.toString()),this.socket.removeAllListeners(),this.socket.close(),await Promise.all([...this.connections.map(async e=>await e.close()),...Array.from(this.channels.values()).map(async e=>await e.close())]),this.dispatchEvent(new ve("close"))}},OL=class extends Zt{constructor(e,t,n,i,o){super(),this.upgrader=e,this.handler=t,this.peerId=n,this.transport=i,this.options=o}async listen(e){if(this.listeningAddr!=null)throw(0,jfe.default)(new Error("listener already in use"),"ERR_ALREADY_LISTENING");let t=io();this.listeningAddr=e;let n;e.protoCodes().includes(421)?n=e:n=e.encapsulate(`/p2p/${this.peerId.toString()}`);let i=this.signallingUrl=o9(e);Gi("connecting to signalling server on: %s",this.signallingUrl);let o=new DL(this.signallingUrl,n,this.upgrader,this.handler,this.options.channelOptions);return o.addEventListener("error",s=>{let a=s.detail;Gi("error connecting to signalling server %o",a),o.close().catch(c=>{Gi.error("error closing server after error",c)}),t.reject(a)}),o.addEventListener("listening",()=>{Gi("connected to signalling server"),this.dispatchEvent(new ve("listening")),t.resolve()}),o.addEventListener("peer",s=>{this.transport.peerDiscovered(s.detail)}),o.addEventListener("connection",s=>{let a=s.detail;if(a.remoteAddr==null)try{a.remoteAddr=e.decapsulateCode(421).encapsulate(`/p2p/${a.remotePeer.toString()}`)}catch(c){Gi.error("could not determine remote address",c)}this.dispatchEvent(new ve("connection",{detail:a}))}),o.addEventListener("disconnect",()=>{this.transport.sigServers.delete(i)}),o.addEventListener("reconnect",()=>{this.transport.sigServers.set(i,o)}),this.transport.sigServers.set(this.signallingUrl,o),await t.promise}async close(){if(this.signallingUrl!=null){let e=this.transport.sigServers.get(this.signallingUrl);e!=null&&(await e.close(),this.transport.sigServers.delete(this.signallingUrl))}this.dispatchEvent(new ve("close")),this.listeningAddr=void 0}getAddrs(){return this.listeningAddr!=null?[this.listeningAddr]:[]}};function Wfe(r,e,t,n,i){return new OL(r,e,t,n,i)}var Xfe=C(r9(),1);var LL=Symbol.for("@libp2p/peer-id");function u0(r){return r!=null&&!!r[LL]}var YUe=Symbol.for("nodejs.util.inspect.custom"),Yfe=Object.values(If).map(r=>r.decoder).reduce((r,e)=>r.or(e),If.identity.decoder),Qfe=114,BL=36,ML=37,e4=class{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()})`}get[LL](){return!0}toString(){return this.string==null&&(this.string=tt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ce.createV1(Qfe,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){var t;if(e instanceof Uint8Array)return rr(this.multihash.bytes,e);if(typeof e=="string")return xt(e).equals(this);if(((t=e==null?void 0:e.multihash)==null?void 0:t.bytes)!=null)return rr(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[YUe](){return`PeerId(${this.toString()})`}},l0=class extends e4{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},f0=class extends e4{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},d0=class extends e4{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function xn(r){if(r.type==="RSA")return new l0(r);if(r.type==="Ed25519")return new f0(r);if(r.type==="secp256k1")return new d0(r);throw new We("Not a PeerId","ERR_INVALID_PARAMETERS")}function xt(r,e){if(e=e??Yfe,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Jn(tt.decode(`z${r}`));return r.startsWith("12D")?new f0({multihash:t}):r.startsWith("16U")?new d0({multihash:t}):new l0({multihash:t})}return Wd(Yfe.decode(r))}function Wd(r){try{let e=Jn(r);if(e.code===Ns.code){if(e.digest.length===BL)return new f0({multihash:e});if(e.digest.length===ML)return new d0({multihash:e})}if(e.code===mr.code)return new l0({multihash:e})}catch{return QUe(ce.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function QUe(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Qfe)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===mr.code)return new l0({multihash:r.multihash});if(e.code===Ns.code){if(e.digest.length===BL)return new f0({multihash:r.multihash});if(e.digest.length===ML)return new d0({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Yd(r,e){return r.length===BL?new f0({multihash:Ec(Ns.code,r),privateKey:e}):r.length===ML?new d0({multihash:Ec(Ns.code,r),privateKey:e}):new l0({multihash:await mr.digest(r),publicKey:r,privateKey:e})}var s9=Symbol.for("@libp2p/transport");var Qd;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Qd||(Qd={}));var a9=Symbol.for("@libp2p/peer-discovery");var ZUe="RTCPeerConnection"in globalThis,h0=ue("libp2p:webrtc-star"),JUe=()=>{},UL=class extends Zt{constructor(){super(...arguments),this.started=!1}get[a9](){return!0}get[Symbol.toStringTag](){return"@libp2p/webrtc-star-discovery"}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}dispatchEvent(e){return this.isStarted()?super.dispatchEvent(e):!1}},c9=class{constructor(e){(e==null?void 0:e.wrtc)!=null&&(this.wrtc=e.wrtc),this.sigServers=new Map,this._discovery=new UL,this.discovery=()=>this._discovery,this.peerDiscovered=this.peerDiscovered.bind(this)}get[s9](){return!0}get[Symbol.toStringTag](){return"@libp2p/webrtc-star"}async dial(e,t){let n=await this._connect(e,t),i=i9(n,{remoteAddr:e,signal:t.signal});h0("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i);return h0("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){var s;if(((s=t.signal)==null?void 0:s.aborted)===!0)throw new Gd;let n={...t.channelOptions??{}};this.wrtc!=null&&(n.wrtc=this.wrtc);let i=e.toOptions(),o=Ee((0,Xfe.default)(36),"hex");return await new Promise((a,c)=>{var w;let u=this.sigServers.get(o9(e));if((u==null?void 0:u.socket)==null)return c((0,t4.default)(new Error("unknown signal server to use"),"ERR_UNKNOWN_SIGNAL_SERVER"));let l=!1;h0("dialing %s:%s",i.host,i.port);let f=new J5(n),h=_=>{let x=_.detail;if(!l){let m=`connection error ${i.host}:${i.port}: ${x.message}`;h0.error(m),g(x)}},d=()=>{l=!0,h0("connection opened %s:%s",i.host,i.port),g()},p=()=>{h0.error("connection aborted %s:%s",i.host,i.port),f.close().finally(()=>{g(new Gd)})},g=_=>{var x;f.removeEventListener("ready",d),(x=t.signal)==null||x.removeEventListener("abort",p),_==null?a(f):c(_)};f.addEventListener("ready",d,{once:!0}),f.addEventListener("close",()=>{f.removeEventListener("error",h)}),(w=t.signal)==null||w.addEventListener("abort",p),f.addEventListener("signal",_=>{let x=_.detail;u.socket.emit("ss-handshake",{intentId:o,srcMultiaddr:u.signallingAddr.toString(),dstMultiaddr:e.toString(),signal:x})}),u.socket.on("ws-handshake",_=>{_.intentId===o&&_.err!=null&&f.close().finally(()=>{c((0,t4.default)(new Error(_.err),"ERR_SIGNALLING_FAILED"))}),!(_.intentId!==o||_.answer==null||f.closed)&&f.handleSignal(_.signal)})})}createListener(e){if(!ZUe&&this.wrtc==null)throw(0,t4.default)(new Error("no WebRTC support"),"ERR_NO_WEBRTC_SUPPORT");if(e.channelOptions=e.channelOptions??{},this.wrtc!=null&&(e.channelOptions.wrtc=this.wrtc),this.peerId==null)throw(0,t4.default)(new Error("PeerId not set"),"ERR_MISSING_PEER_ID");return Wfe(e.upgrader,e.handler??JUe,this.peerId,this,e)}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>t.protoCodes().includes(290)?!1:Gv.matches(t))}peerDiscovered(e){h0("peer discovered: %s",e),e=Hfe(e);let t=lt(e),n=t.getPeerId();if(n==null)return;let i=xt(n);this._discovery.dispatchEvent(new ve("peer",{detail:{id:i,multiaddrs:[t],protocols:[]}}))}};function Zfe(r={}){let e=new c9(r);return{transport:t=>(e.peerId=t.peerId,e),discovery:e.discovery}}function Jfe(){let r=Zfe();return{transports:[r.transport],peerDiscovery:[r.discovery],connectionManager:{maxParallelDials:150,maxDialsPerPeer:4,dialTimeout:1e4,autoDial:!0},nat:{enabled:!1}}}function Cl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var n4=C(ee(),1);var Rt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.DHT_DISABLED="DHT is not available",r.PUBSUB_DISABLED="PubSub is not available",r.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",r.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Rt||(Rt={}));var q;(function(r){r.DHT_DISABLED="ERR_DHT_DISABLED",r.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",r.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",r.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",r.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",r.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TIMEOUT="ERR_TIMEOUT",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED"})(q||(q={}));var ede=C(ee(),1);async function*r4(r,e){yield*Bi(r,async t=>(await e.addressBook.add(t.id,t.multiaddrs),t))}function u9(r){let e=new Set;return Yt(r,t=>e.has(t.id.toString())?!1:(e.add(t.id.toString()),!0))}async function*l9(r,e=1){let t=0;for await(let n of r)t++,yield n;if(tasync function*(){try{yield await i.findPeer(e,t)}catch(o){rde.error(o)}}())),i=>Yt(i,Boolean),i=>r4(i,this.components.peerStore),async i=>await Fi(i));if(n!=null)return n;throw(0,n4.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}async*getClosestPeers(e,t){if(this.routers.length===0)throw(0,n4.default)(new Error("No peer routers available"),q.ERR_NO_ROUTERS_AVAILABLE);yield*Ne(Qo(...this.routers.map(n=>n.getClosestPeers(e,t))),n=>r4(n,this.components.peerStore),n=>u9(n),n=>l9(n))}};var Xd=C(ee(),1);var h9=class{constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw(0,Xd.default)(new Error("No content this.routers available"),q.ERR_NO_ROUTERS_AVAILABLE);yield*Ne(Qo(...this.routers.map(n=>n.findProviders(e,t))),n=>r4(n,this.components.peerStore),n=>u9(n),n=>l9(n))}async provide(e,t={}){if(this.routers.length===0)throw(0,Xd.default)(new Error("No content routers available"),q.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>await n.provide(e,t)))}async put(e,t,n){if(!this.isStarted())throw(0,Xd.default)(new Error(Rt.NOT_STARTED_YET),q.DHT_NOT_STARTED);let i=this.components.dht;i!=null&&await on(i.put(e,t,n))}async get(e,t){if(!this.isStarted())throw(0,Xd.default)(new Error(Rt.NOT_STARTED_YET),q.DHT_NOT_STARTED);let n=this.components.dht;if(n!=null){for await(let i of n.get(e,t))if(i.name==="VALUE")return i.value}throw(0,Xd.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}async*getMany(e,t,n){if(!this.isStarted())throw(0,Xd.default)(new Error(Rt.NOT_STARTED_YET),q.DHT_NOT_STARTED);if(t==null||t===0)return;let i=0,o=this.components.dht;if(o!=null){for await(let s of o.get(e,n))if(s.name==="VALUE"&&(yield{from:s.from,val:s.value},i++,i===t))break}if(i===0)throw(0,Xd.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}};var iFe=r=>r,p9=class extends Zt{constructor(e,t){super();let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(o=>o.toString()),this.announce=new Set(i.map(o=>o.toString())),this.observed=new Set,this.announceFilter=t.announceFilter??iFe}getListenAddrs(){return Array.from(this.listen).map(e=>lt(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>lt(e))}getObservedAddrs(){return Array.from(this.observed).map(e=>lt(e))}confirmObservedAddr(e){}removeObservedAddr(e){}addObservedAddr(e){let t=lt(e),n=t.getPeerId();n!=null&&xt(n).equals(this.components.peerId)&&(t=t.decapsulate(lt(`/p2p/${this.components.peerId.toString()}`)));let i=t.toString();this.observed.has(i)||(this.observed.add(i),this.dispatchEvent(new ve("change:addresses")))}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(this.getObservedAddrs().map(n=>n.toString()));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>lt(n))).map(n=>{var i;return((i=n.protos().pop())==null?void 0:i.path)===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`)})}};var E9=C(ee(),1);var ode=ue("libp2p:connection-manager:latency-monitor:visibility-change-emitter"),m9=class extends Zt{constructor(){super(),this.hidden="hidden",this.visibilityChange="visibilityChange",globalThis.document!=null&&(this._initializeVisibilityVarNames(),this._addVisibilityChangeListener())}_initializeVisibilityVarNames(){let e="hidden",t="visibilitychange";typeof globalThis.document.hidden<"u"?(e="hidden",t="visibilitychange"):typeof globalThis.document.mozHidden<"u"?(e="mozHidden",t="mozvisibilitychange"):typeof globalThis.document.msHidden<"u"?(e="msHidden",t="msvisibilitychange"):typeof globalThis.document.webkitHidden<"u"&&(e="webkitHidden",t="webkitvisibilitychange"),this.hidden=e,this.visibilityChange=t}_addVisibilityChangeListener(){typeof globalThis.document.addEventListener>"u"||typeof document[this.hidden]>"u"?ode("Checking page visibility requires a browser that supports the Page Visibility API."):globalThis.document.addEventListener(this.visibilityChange,this._handleVisibilityChange.bind(this),!1)}isVisible(){if(!(this.hidden===void 0||document[this.hidden]===void 0))return document[this.hidden]==null}_handleVisibilityChange(){let e=globalThis.document[this.hidden]===!1;ode(e?"Page Visible":"Page Hidden"),this.dispatchEvent(new ve("visibilityChange",{detail:e}))}};var Pl=ue("libp2p:connection-manager:latency-monitor"),g9=class extends Zt{constructor(e={}){var s,a;super();let{latencyCheckIntervalMs:t,dataEmitIntervalMs:n,asyncTestFn:i,latencyRandomPercentage:o}=e;this.latencyCheckIntervalMs=t??500,this.latencyRandomPercentage=o??10,this.latencyCheckMultiply=2*(this.latencyRandomPercentage/100)*this.latencyCheckIntervalMs,this.latencyCheckSubtract=this.latencyCheckMultiply/2,this.dataEmitIntervalMs=n===null||n===0?void 0:n??5*1e3,Pl("latencyCheckIntervalMs: %s dataEmitIntervalMs: %s",this.latencyCheckIntervalMs,this.dataEmitIntervalMs),this.dataEmitIntervalMs!=null?Pl("Expecting ~%s events per summary",this.latencyCheckIntervalMs/this.dataEmitIntervalMs):Pl("Not emitting summaries"),this.asyncTestFn=i,((s=globalThis.process)==null?void 0:s.hrtime)!=null?(Pl("Using process.hrtime for timing"),this.now=globalThis.process.hrtime,this.getDeltaMS=c=>{let u=this.now(c);return u[0]*1e3+u[1]/1e6}):typeof window<"u"&&((a=window.performance)==null?void 0:a.now)!=null?(Pl("Using performance.now for timing"),this.now=window.performance.now.bind(window.performance),this.getDeltaMS=c=>Math.round(this.now()-c)):(Pl("Using Date.now for timing"),this.now=Date.now,this.getDeltaMS=c=>this.now()-c),this.latencyData=this.initLatencyData()}start(){var e;oFe()&&(this.visibilityChangeEmitter=new m9,this.visibilityChangeEmitter.addEventListener("visibilityChange",t=>{let{detail:n}=t;n?this._startTimers():(this._emitSummary(),this._stopTimers())})),((e=this.visibilityChangeEmitter)==null?void 0:e.isVisible())===!0&&this._startTimers()}stop(){this._stopTimers()}_startTimers(){this.checkLatencyID==null&&(this.checkLatency(),this.dataEmitIntervalMs!=null&&(this.emitIntervalID=setInterval(()=>this._emitSummary(),this.dataEmitIntervalMs),typeof this.emitIntervalID.unref=="function"&&this.emitIntervalID.unref()))}_stopTimers(){this.checkLatencyID!=null&&(clearTimeout(this.checkLatencyID),this.checkLatencyID=void 0),this.emitIntervalID!=null&&(clearInterval(this.emitIntervalID),this.emitIntervalID=void 0)}_emitSummary(){let e=this.getSummary();e.events>0&&this.dispatchEvent(new ve("data",{detail:e}))}getSummary(){let e={events:this.latencyData.events,minMs:this.latencyData.minMs,maxMs:this.latencyData.maxMs,avgMs:this.latencyData.events>0?this.latencyData.totalMs/this.latencyData.events:Number.POSITIVE_INFINITY,lengthMs:this.getDeltaMS(this.latencyData.startTime)};return this.latencyData=this.initLatencyData(),Pl.trace("Summary: %O",e),e}checkLatency(){let e=Math.random()*this.latencyCheckMultiply-this.latencyCheckSubtract,t={deltaOffset:Math.ceil(this.latencyCheckIntervalMs+e),startTime:this.now()},n=()=>{if(this.checkLatencyID==null)return;let i=this.getDeltaMS(t.startTime)-t.deltaOffset;this.checkLatency(),this.latencyData.events++,this.latencyData.minMs=Math.min(this.latencyData.minMs,i),this.latencyData.maxMs=Math.max(this.latencyData.maxMs,i),this.latencyData.totalMs+=i,Pl.trace("MS: %s Data: %O",i,this.latencyData)};Pl.trace("localData: %O",t),this.checkLatencyID=setTimeout(()=>{this.asyncTestFn!=null?(t.deltaOffset=0,t.startTime=this.now(),this.asyncTestFn(n)):(t.deltaOffset-=1,n())},t.deltaOffset),typeof this.checkLatencyID.unref=="function"&&this.checkLatencyID.unref()}initLatencyData(){return{startTime:this.now(),minMs:Number.POSITIVE_INFINITY,maxMs:Number.NEGATIVE_INFINITY,events:0,totalMs:0}}};function oFe(){return typeof globalThis.window<"u"}var v9=C(xi(),1);var y9="OPEN",zL="CLOSING",w9="CLOSED";function kl(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var i4=class{constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return kl(this.map.entries(),e=>[xt(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,xt(n),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 kl(this.map.keys(),e=>xt(e))}values(){return this.map.values()}get size(){return this.map.size}};var Nl=class{constructor(e){if(this.set=new Set,e!=null)for(let 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 kl(this.set.entries(),e=>{let t=xt(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=xt(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return kl(this.set.values(),e=>xt(e))}intersection(e){let t=new Nl;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new Nl;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new Nl;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var X2=class{constructor(e){if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return kl(this.list.entries(),e=>xt(e[1]))}concat(e){let t=new X2(this);for(let n of e)t.push(n);return t}entries(){return kl(this.list.entries(),e=>[e[0],xt(e[1])])}every(e){return this.list.every((t,n)=>e(xt(t),n,this))}filter(e){let t=new X2;return this.list.forEach((n,i)=>{let o=xt(n);e(o,i,this)&&t.push(o)}),t}find(e){let t=this.list.find((n,i)=>e(xt(n),i,this));if(t!=null)return xt(t)}findIndex(e){return this.list.findIndex((t,n)=>e(xt(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(xt(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return xt(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return xt(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var tB=C(Kn(),1);var sde="keep-alive";var rhe=C(ehe(),1);var the=C(ee(),1);function _9(r){if(u0(r))return{peerId:r};if(as(r)){let e=r.getPeerId();return{multiaddr:r,peerId:e==null?void 0:xt(e)}}throw(0,the.default)(new Error(`${r} is not a PeerId or a Multiaddr`),q.ERR_INVALID_MULTIADDR)}var Ln=ue("libp2p:connection-manager"),KFe={maxConnections:1/0,minConnections:0,maxEventLoopDelay:1/0,pollInterval:2e3,autoDialInterval:1e4,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},$Fe=6e4,x9=class extends Zt{constructor(e,t){var n;if(super(),this.opts=et.call({ignoreUndefined:!0},KFe,t),this.opts.maxConnections0&&t.maxEventLoopDelay!==1/0&&(this.latencyMonitor=new g9({latencyCheckIntervalMs:t.pollInterval,dataEmitIntervalMs:t.pollInterval}));try{(n=v9.setMaxListeners)==null||n(1/0,this)}catch{}this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.startupReconnectTimeout=t.startupReconnectTimeout??$Fe,this.dialTimeout=t.dialTimeout??3e4,this.allow=(t.allow??[]).map(i=>lt(i)),this.deny=(t.deny??[]).map(i=>lt(i)),this.inboundConnectionRateLimiter=new rhe.RateLimiterMemory({points:this.opts.inboundConnectionThreshold,duration:1}),this.incomingPendingConnections=0}isStarted(){return this.started}async start(){var e,t,n,i,o;(e=this.components.metrics)==null||e.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let s={inbound:0,outbound:0};for(let a of this.connections.values())for(let c of a)c.stat.direction==="inbound"?s.inbound++:s.outbound++;return s}}),(t=this.components.metrics)==null||t.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let s={};for(let a of this.connections.values())for(let c of a)for(let u of c.streams){let l=`${u.stat.direction} ${u.stat.protocol??"unnegotiated"}`;s[l]=(s[l]??0)+1}return s}}),(n=this.components.metrics)==null||n.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let s={};for(let c of this.connections.values())for(let u of c){let l={};for(let f of u.streams){let h=`${f.stat.direction} ${f.stat.protocol??"unnegotiated"}`;l[h]=(l[h]??0)+1}for(let[f,h]of Object.entries(l))s[f]=s[f]??[],s[f].push(h)}let a={};for(let[c,u]of Object.entries(s)){u=u.sort((f,h)=>f-h);let l=Math.floor(u.length*.9);a[c]=u[l]}return a}}),(i=this.latencyMonitor)==null||i.start(),this._onLatencyMeasure=this._onLatencyMeasure.bind(this),(o=this.latencyMonitor)==null||o.addEventListener("data",this._onLatencyMeasure),this.started=!0,Ln("started")}async afterStart(){this.components.upgrader.addEventListener("connection",this.onConnect),this.components.upgrader.addEventListener("connectionEnd",this.onDisconnect),Promise.resolve().then(async()=>{var t,n;let e=[];for(let i of await this.components.peerStore.all())(await this.components.peerStore.getTags(i.id)).filter(a=>a.name===sde).length>0&&e.push(i.id);(t=this.connectOnStartupController)==null||t.clear(),this.connectOnStartupController=new tB.TimeoutController(this.startupReconnectTimeout);try{(n=v9.setMaxListeners)==null||n(1/0,this.connectOnStartupController.signal)}catch{}await Promise.all(e.map(async i=>{var o;await this.openConnection(i,{signal:(o=this.connectOnStartupController)==null?void 0:o.signal}).catch(s=>{Ln.error(s)})}))}).catch(e=>{Ln.error(e)}).finally(()=>{var e;(e=this.connectOnStartupController)==null||e.clear()})}async beforeStop(){var e;(e=this.connectOnStartupController)==null||e.abort(),this.components.upgrader.removeEventListener("connection",this.onConnect),this.components.upgrader.removeEventListener("connectionEnd",this.onDisconnect)}async stop(){var e,t;(e=this.latencyMonitor)==null||e.removeEventListener("data",this._onLatencyMeasure),(t=this.latencyMonitor)==null||t.stop(),this.started=!1,await this._close(),Ln("stopped")}async _close(){let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){Ln.error(i)}})());Ln("closing %d connections",e.length),await Promise.all(e),this.connections.clear()}onConnect(e){this._onConnect(e).catch(t=>{Ln.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,i=n.toString(),o=this.connections.get(i);o!=null?o.push(t):this.connections.set(i,[t]),n.publicKey!=null&&await this.components.peerStore.keyBook.set(n,n.publicKey);let s=this.getConnections().length,a=s-this.opts.maxConnections;await this._checkMaxLimit("maxConnections",s,a),this.dispatchEvent(new ve("peer:connect",{detail:t}))}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer.toString(),i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==t.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.dispatchEvent(new ve("peer:disconnect",{detail:t})))}getConnections(e){if(e!=null)return this.connections.get(e.toString())??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}async openConnection(e,t={}){var s;let{peerId:n,multiaddr:i}=_9(e);if(n==null&&i==null)throw(0,E9.default)(new TypeError("Can only open connections to PeerIds or Multiaddrs"),q.ERR_INVALID_PARAMETERS);if(n!=null){Ln("dial to",n);let a=this.getConnections(n);if(a.length>0)return Ln("had an existing connection to %p",n),a[0]}let o;if((t==null?void 0:t.signal)==null){o=new tB.TimeoutController(this.dialTimeout),t.signal=o.signal;try{(s=v9.setMaxListeners)==null||s(1/0,o.signal)}catch{}}try{let a=await this.components.dialer.dial(e,t),c=this.connections.get(a.remotePeer.toString());c==null&&(c=[],this.connections.set(a.remotePeer.toString(),c));let u=!1;for(let l of c)l.id===a.id&&(u=!0);return u||c.push(a),a}finally{o!=null&&o.clear()}}async closeConnections(e){let t=this.connections.get(e.toString())??[];await Promise.all(t.map(async n=>await n.close()))}getAll(e){if(!u0(e))throw(0,E9.default)(new Error("peerId must be an instance of peer-id"),q.ERR_INVALID_PARAMETERS);let t=e.toString(),n=this.connections.get(t);return n!=null?n.filter(i=>i.stat.status===y9):[]}_onLatencyMeasure(e){let{detail:t}=e;this._checkMaxLimit("maxEventLoopDelay",t.avgMs,1).catch(n=>{Ln.error(n)})}async _checkMaxLimit(e,t,n=1){let i=this.opts[e];if(i==null){Ln.trace("limit %s was not set so it cannot be applied",e);return}Ln.trace("checking limit of %s. current value: %d of %d",e,t,i),t>i&&(Ln("%s: limit exceeded: %p, %d/%d, pruning %d connection(s)",this.components.peerId,e,t,i,n),await this._pruneConnections(n))}async _pruneConnections(e){let t=this.getConnections(),n=new i4;for(let s of t){let a=s.remotePeer;if(n.has(a))continue;let c=await this.components.peerStore.getTags(a);n.set(a,c.reduce((u,l)=>u+l.value,0))}let i=t.sort((s,a)=>{let c=n.get(s.remotePeer)??0,u=n.get(a.remotePeer)??0;if(c>u)return 1;if(cf?-1:0}),o=[];for(let s of i)if(Ln("too many connections open - closing a connection to %p",s.remotePeer),o.push(s),o.length===e)break;await Promise.all(o.map(async s=>{try{await s.close()}catch(a){Ln.error(a)}this.onDisconnect(new ve("connectionEnd",{detail:s}))}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return Ln("connection from %s refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.opts.maxIncomingPendingConnections)return Ln("connection from %s refused - incomingPendingConnections exceeded by peer %s",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return Ln("connection from %s refused - inboundConnectionThreshold exceeded by host %s",i,e.remoteAddr),!1}}return this.getConnections().length{Zd.error("could start autodial",e)}),Zd("started")}async stop(){if(!this.options.enabled){Zd("not enabled");return}this.running=!1,this.autoDialTimeout!=null&&this.autoDialTimeout.clear(),Zd("stopped")}async _autoDial(){this.autoDialTimeout!=null&&this.autoDialTimeout.clear();let e=this.options.minConnections;if(this.components.connectionManager.getConnections().length>=e){this.autoDialTimeout=(0,rB.default)(this._autoDial,this.options.autoDialInterval);return}let t=await this.components.peerStore.all(),n=await Ne(t.sort(()=>Math.random()>.5?1:-1),i=>Yt(i,o=>!o.id.equals(this.components.peerId)),i=>Id(i,(o,s)=>s.protocols.length>o.protocols.length||s.id.publicKey!=null&&o.id.publicKey==null?1:-1),async i=>await Wo(i));for(let i=0;this.running&&iJd(t)}(e=r.Status||(r.Status={}));let n;(function(a){a.HOP="HOP",a.STOP="STOP",a.STATUS="STATUS",a.CAN_HOP="CAN_HOP"})(n=r.Type||(r.Type={}));let i;(function(a){a[a.HOP=1]="HOP",a[a.STOP=2]="STOP",a[a.STATUS=3]="STATUS",a[a.CAN_HOP=4]="CAN_HOP"})(i||(i={})),function(a){a.codec=()=>Jd(i)}(n=r.Type||(r.Type={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=Cr((u,l,f={})=>{if(f.lengthDelimited!==!1&&l.fork(),(f.writeDefaults===!0||u.id!=null&&u.id.byteLength>0)&&(l.uint32(10),l.bytes(u.id)),u.addrs!=null)for(let h of u.addrs)l.uint32(18),l.bytes(h);f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={id:new Uint8Array(0),addrs:[]},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.id=u.bytes();break;case 2:f.addrs.push(u.bytes());break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>Rr(u,a.codec()),a.decode=u=>Ir(u,a.codec())})(o=r.Peer||(r.Peer={}));let s;r.codec=()=>(s==null&&(s=Cr((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.srcPeer!=null&&(c.uint32(18),r.Peer.codec().encode(a.srcPeer,c,{writeDefaults:!1})),a.dstPeer!=null&&(c.uint32(26),r.Peer.codec().encode(a.dstPeer,c,{writeDefaults:!1})),a.code!=null&&(c.uint32(32),r.Status.codec().encode(a.code,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={},l=c==null?a.len:a.pos+c;for(;a.pos>>3){case 1:u.type=r.Type.codec().decode(a);break;case 2:u.srcPeer=r.Peer.codec().decode(a,a.uint32());break;case 3:u.dstPeer=r.Peer.codec().decode(a,a.uint32());break;case 4:u.code=r.Status.codec().decode(a);break;default:a.skipType(f&7);break}}return u})),s),r.encode=a=>Rr(a,r.codec()),r.decode=a=>Ir(a,r.codec())})(ft||(ft={}));var WFe=ue("libp2p:stream:converter");function aB(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:o}=t,s=async function*(){for await(let u of o)yield*u}(),a={async sink(u){e.signal!=null&&(u=sa(u,e.signal));try{await i(u),await c()}catch(l){l.type!=="aborted"&&WFe(l)}},source:e.signal!=null?sa(s,e.signal):s,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){return a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var mu="/libp2p/circuit/relay/0.1.0";function ahe(r){let e=new Map;async function t(o){let s=o.toString().split("/p2p-circuit").find(h=>h!==""),a=lt(s),c=a.getPeerId();if(c==null)throw new Error("Could not determine relay peer from multiaddr");let u=xt(c);await r.peerStore.addressBook.add(u,[a]);let l=await r.connectionManager.openConnection(u),f=l.remoteAddr.encapsulate("/p2p-circuit");e.set(l.remotePeer.toString(),f),i.dispatchEvent(new ve("listening"))}function n(){let o=[];for(let s of e.values())o.push(s);return o}let i=Object.assign(new Zt,{close:async()=>await Promise.resolve(),listen:t,getAddrs:n});return r.connectionManager.addEventListener("peer:disconnect",o=>{let{detail:s}=o;e.delete(s.remotePeer.toString())&&i.dispatchEvent(new ve("close"))}),i}var uB=C(ee(),1);function che(r,e){r.write({type:ft.Type.STATUS,code:e})}function T9(r,e){var t,n;try{((t=r.dstPeer)==null?void 0:t.addrs)!=null&&r.dstPeer.addrs.forEach(i=>lt(i))}catch(i){throw che(e,r.type===ft.Type.HOP?ft.Status.HOP_DST_MULTIADDR_INVALID:ft.Status.STOP_DST_MULTIADDR_INVALID),i}try{((n=r.srcPeer)==null?void 0:n.addrs)!=null&&r.srcPeer.addrs.forEach(i=>lt(i))}catch(i){throw che(e,r.type===ft.Type.HOP?ft.Status.HOP_SRC_MULTIADDR_INVALID:ft.Status.STOP_SRC_MULTIADDR_INVALID),i}}function cB(r){let e=async function*(){let t=yield,n=new ln;for await(let i of r){if(t==null){n.append(i),t=yield n,n=new ln;continue}for(n.append(i);n.length>=t;){let o=n.sublist(0,t);if(n.consume(t),t=yield o,t==null){n.length>0&&(t=yield n,n=new ln);break}}}if(t!=null)throw Object.assign(new Error(`stream ended before ${t} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function ng(r){let e=jn(),t=cB(r.source),n=io(),i,o=r.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:t,writer:e,stream:{sink:async a=>i!=null?await Promise.reject(i):(n.resolve(a),await o),source:t},rest:()=>e.end(),write:e.push,read:async()=>{let a=await t.next();if(a.value!=null)return a.value}}}var a4=ue("libp2p:circuit:stream-handler"),Dl=class{constructor(e){let{stream:t,maxLength:n=4096}=e;this.stream=t,this.shake=ng(this.stream),this.decoder=Xr.fromReader(this.shake.reader,{maxDataLength:n})}async read(){let e=await this.decoder.next();if(e.value!=null){let t=ft.decode(e.value);return a4("read message type",t.type),t}a4("read received no value, closing stream"),this.close()}write(e){a4("write message type %s",e.type),this.shake.write(vn.single(ft.encode(e)))}rest(){return this.shake.rest(),this.shake.stream}end(e){this.write(e),this.close()}close(){a4("closing the stream"),this.rest().sink([]).catch(e=>{a4.error(e)})}};var c4=ue("libp2p:circuit:stop");function uhe(r){let{connection:e,request:t,streamHandler:n}=r;try{T9(t,n)}catch(i){c4.error("invalid stop request via peer %p %o",e.remotePeer,i);return}return c4("stop request is valid"),n.write({type:ft.Type.STATUS,code:ft.Status.SUCCESS}),n.rest()}async function lhe(r){let{connection:e,request:t,signal:n}=r,i=await e.newStream(mu,{signal:n});c4("starting stop request to %p",e.remotePeer);let o=new Dl({stream:i});o.write(t);let s=await o.read();if(s==null){o.close();return}if(s.code===ft.Status.SUCCESS)return c4("stop request to %p was successful",e.remotePeer),o.rest();c4("stop request failed with code %d",s.code),o.close()}var ua=ue("libp2p:circuit:hop");async function fhe(r){let{connection:e,request:t,streamHandler:n,circuit:i,connectionManager:o}=r;if(!i.hopEnabled())return ua("HOP request received but we are not acting as a relay"),n.end({type:ft.Type.STATUS,code:ft.Status.HOP_CANT_SPEAK_RELAY});try{T9(t,n)}catch(f){ua.error("invalid hop request via peer %p %o",e.remotePeer,f);return}if(t.dstPeer==null){ua("HOP request received but we do not receive a dstPeer");return}let s=Wd(t.dstPeer.id),a=o.getConnections(s);if(a.length===0&&!i.hopActive())return ua("HOP request received but we are not connected to the destination peer"),n.end({type:ft.Type.STATUS,code:ft.Status.HOP_NO_CONN_TO_DST});if(a.length===0)return ua("did not have connection to remote peer"),n.end({type:ft.Type.STATUS,code:ft.Status.HOP_NO_CONN_TO_DST});let c={type:ft.Type.STOP,dstPeer:t.dstPeer,srcPeer:t.srcPeer},u;try{ua("performing STOP request");let f=await lhe({connection:a[0],request:c});if(f==null)throw new Error("Could not stop");u=f}catch(f){ua.error(f);return}ua("hop request from %p is valid",e.remotePeer),n.write({type:ft.Type.STATUS,code:ft.Status.SUCCESS});let l=n.rest();return ua("creating related connections"),await Ne(l,u,l)}async function dhe(r){let{connection:e,request:t,signal:n}=r,i=await e.newStream(mu,{signal:n}),o=new Dl({stream:i});o.write(t);let s=await o.read();if(s==null)throw(0,uB.default)(new Error("HOP request had no response"),q.ERR_HOP_REQUEST_FAILED);if(s.code===ft.Status.SUCCESS)return ua("hop request was successful"),o.rest();throw ua("hop request failed with code %d, closing stream",s.code),o.close(),(0,uB.default)(new Error(`HOP request failed with code "${s.code??"unknown"}"`),q.ERR_HOP_REQUEST_FAILED)}async function hhe(r){let{connection:e,signal:t}=r,n=await e.newStream(mu,{signal:t}),i=new Dl({stream:n});i.write({type:ft.Type.CAN_HOP});let o=await i.read();return await i.close(),!(o==null||o.code!==ft.Status.SUCCESS)}function phe(r){let{connection:e,streamHandler:t,circuit:n}=r,i=n.hopEnabled();ua("can hop (%s) request from %p",i,e.remotePeer),t.end({type:ft.Type.STATUS,code:i?ft.Status.SUCCESS:ft.Status.HOP_CANT_SPEAK_RELAY})}var ghe=C(Kn(),1),yhe=C(xi(),1),la=ue("libp2p:circuit"),I9=class{constructor(e,t){this._init=t,this.components=e,this._started=!1}isStarted(){return this._started}async start(){this._started||(this._started=!0,await this.components.registrar.handle(mu,e=>{this._onProtocol(e).catch(t=>{la.error(t)})},{...this._init}).catch(e=>{la.error(e)}))}async stop(){await this.components.registrar.unhandle(mu)}hopEnabled(){return!0}hopActive(){return!0}get[s9](){return!0}get[Symbol.toStringTag](){return"libp2p/circuit-relay-v1"}async _onProtocol(e){var o,s,a;let{connection:t,stream:n}=e,i=new ghe.TimeoutController(this._init.hop.timeout);try{(o=yhe.setMaxListeners)==null||o(1/0,i.signal)}catch{}try{let c=ps(n,i.signal),u=new Dl({stream:{...n,...c}}),l=await u.read();if(l==null){la("request was invalid, could not read from stream"),u.write({type:ft.Type.STATUS,code:ft.Status.MALFORMED_MESSAGE}),u.close();return}let f;switch(l.type){case ft.Type.CAN_HOP:{la("received CAN_HOP request from %p",t.remotePeer),await phe({circuit:this,connection:t,streamHandler:u});break}case ft.Type.HOP:{la("received HOP request from %p",t.remotePeer),await fhe({connection:t,request:l,streamHandler:u,circuit:this,connectionManager:this.components.connectionManager});break}case ft.Type.STOP:{la("received STOP request from %p",t.remotePeer),f=await uhe({connection:t,request:l,streamHandler:u});break}default:{la("Request of type %s not supported",l.type),u.write({type:ft.Type.STATUS,code:ft.Status.MALFORMED_MESSAGE}),u.close();return}}if(f!=null){let h=t.remoteAddr.encapsulate("/p2p-circuit").encapsulate(lt((s=l.dstPeer)==null?void 0:s.addrs[0])),d=lt((a=l.srcPeer)==null?void 0:a.addrs[0]),p=aB({stream:f,remoteAddr:h,localAddr:d}),g=l.type===ft.Type.HOP?"relay":"inbound";la("new %s connection %s",g,p.remoteAddr);let w=await this.components.upgrader.upgradeInbound(p);la("%s connection %s upgraded",g,p.remoteAddr),this.handler!=null&&this.handler(w)}}finally{i.clear()}}async dial(e,t={}){let n=e.toString().split("/p2p-circuit"),i=lt(n[0]),o=lt(n[n.length-1]),s=i.getPeerId(),a=o.getPeerId();if(s==null||a==null){let d="Circuit relay dial failed as addresses did not have peer id";throw la.error(d),(0,mhe.default)(new Error(d),q.ERR_RELAYED_DIAL)}let c=xt(s),u=xt(a),l=!1,h=this.components.connectionManager.getConnections(c)[0];h==null&&(await this.components.peerStore.addressBook.add(c,[i]),h=await this.components.connectionManager.openConnection(c,t),l=!0);try{let d=await dhe({...t,connection:h,request:{type:ft.Type.HOP,srcPeer:{id:this.components.peerId.toBytes(),addrs:this.components.addressManager.getAddresses().map(w=>w.bytes)},dstPeer:{id:u.toBytes(),addrs:[lt(o).bytes]}}}),p=i.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),g=aB({stream:d,remoteAddr:e,localAddr:p});return la("new outbound connection %s",g.remoteAddr),await this.components.upgrader.upgradeOutbound(g)}catch(d){throw la.error("Circuit relay dial failed",d),l&&await h.close(),d}}createListener(e){return this.handler=e.handler,ahe({connectionManager:this.components.connectionManager,peerStore:this.components.peerStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>i0.matches(t))}};var B9=C(FL(),1);async function R9(r){let e=new TextEncoder().encode(r),t=await mr.digest(e);return ce.createV0(t)}var lB="hop_relay",fB="true",C9="/libp2p/relay";var vhe=C(dB(),1);var whe="[a-fA-F\\d:]",eh=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${whe})|(?<=${whe})(?=\\s|$))`:"",oc="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Bn="[a-fA-F\\d]{1,4}",P9=` (?: (?:${Bn}:){7}(?:${Bn}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 (?:${Bn}:){6}(?:${oc}|:${Bn}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 @@ -242,14 +242,14 @@ Use Chrome, Firefox or Internet Explorer 11`)}var BVe=a1e().Buffer,Cx=globalThis (?:${Bn}:){1}(?:(?::${Bn}){0,4}:${oc}|(?::${Bn}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 (?::(?:(?::${Bn}){0,5}:${oc}|(?::${Bn}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 -`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),QFe=new RegExp(`(?:^${oc}$)|(?:^${P9}$)`),XFe=new RegExp(`^${oc}$`),ZFe=new RegExp(`^${P9}$`),hB=r=>r&&r.exact?QFe:new RegExp(`(?:${eh(r)}${oc}${eh(r)})|(?:${eh(r)}${P9}${eh(r)})`,"g");hB.v4=r=>r&&r.exact?XFe:new RegExp(`${eh(r)}${oc}${eh(r)}`,"g");hB.v6=r=>r&&r.exact?ZFe:new RegExp(`${eh(r)}${P9}${eh(r)}`,"g");var k9=hB;var xhe=C(_he(),1),{isValid:JFe,parse:eze}=xhe.default,tze=["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"],rze=tze.map(r=>new vhe.Netmask(r));function nze(r){for(let e of rze)if(e.contains(r))return!0;return!1}function Ehe(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}var She=r=>{if(JFe(r)){let e=eze(r);if(e.kind()==="ipv4")return nze(e.toNormalizedString());if(e.kind()==="ipv6")return Ehe(r)}else if(c2(r)&&k9.v6().test(r))return Ehe(r)};var D9=She;function pB(r){let{address:e}=r.nodeAddress();return!!D9(e)}function ig(r,e){let t=pB(r.multiaddr),n=pB(e.multiaddr);return t&&!n?1:!t&&n||r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}var l4=ue("libp2p:auto-relay"),oze=()=>{},O9=class{constructor(e,t){this.components=e,this.addressSorter=t.addressSorter??ig,this.maxListeners=t.maxListeners??1,this.listenRelays=new Set,this.onError=t.onError??oze,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this.components.peerStore.addEventListener("change:protocols",n=>{this._onProtocolChange(n).catch(i=>{l4.error(i)})}),this.components.connectionManager.addEventListener("peer:disconnect",this._onPeerDisconnected)}async _onProtocolChange(e){let{peerId:t,protocols:n}=e.detail,i=t.toString();if(n.find(s=>s===mu)==null){this.listenRelays.has(i)&&await this._removeListenRelay(i);return}if(!this.listenRelays.has(i))try{let s=this.components.connectionManager.getConnections(t);if(s.length===0)return;let a=s[0];if(a.remoteAddr.protoCodes().includes(290)){l4(`relayed connection to ${i} will not be used to hop on`);return}await hhe({connection:a})&&(await this.components.peerStore.metadataBook.setValue(t,lB,fe(fB)),await this._addListenRelay(a,i))}catch(s){this.onError(s)}}_onPeerDisconnected(e){let i=e.detail.remotePeer.toString();this.listenRelays.has(i)&&this._removeListenRelay(i).catch(o=>{l4.error(o)})}async _addListenRelay(e,t){try{if(this.listenRelays.size>=this.maxListeners)return;let n=await Ne(await this.components.peerStore.addressBook.get(e.remotePeer),o=>Id(o,this.addressSorter),async o=>await Wo(o));(await Promise.all(n.map(async o=>{try{let s=o.multiaddr;return s.getPeerId()==null&&(s=s.encapsulate(`/p2p/${e.remotePeer.toString()}`)),s=s.encapsulate("/p2p-circuit"),await this.components.transportManager.listen([s]),!0}catch(s){l4.error("error listening on circuit address",s),this.onError(s)}return!1}))).includes(!0)&&this.listenRelays.add(t)}catch(n){this.onError(n),this.listenRelays.delete(t)}}async _removeListenRelay(e){this.listenRelays.delete(e)&&await this._listenOnAvailableHopRelays([e])}async _listenOnAvailableHopRelays(e=[]){if(this.listenRelays.size>=this.maxListeners)return;let t=[],n=await this.components.peerStore.all();for(let{id:i,metadata:o}of n){let s=i.toString();if(this.listenRelays.has(s)||e.includes(s))continue;let a=o.get(lB);if(a==null||Ee(a)!==fB)continue;let c=this.components.connectionManager.getConnections(i);if(c.length===0){t.push(i);continue}if(await this._addListenRelay(c[0],s),this.listenRelays.size>=this.maxListeners)return}for(let i of t)if(await this._tryToListenOnRelay(i),this.listenRelays.size>=this.maxListeners)return;try{let i=await R9(C9);for await(let o of this.components.contentRouting.findProviders(i)){if(o.multiaddrs.length===0)continue;let s=o.id;if(!s.equals(this.components.peerId)&&(await this.components.peerStore.addressBook.add(s,o.multiaddrs),await this._tryToListenOnRelay(s),this.listenRelays.size>=this.maxListeners))return}}catch(i){this.onError(i)}}async _tryToListenOnRelay(e){try{let t=await this.components.connectionManager.openConnection(e);await this._addListenRelay(t,e.toString())}catch(t){l4.error("Could not use %p as relay",e,t),this.onError(t,`could not connect and listen on known hop relay ${e.toString()}`)}}};var Ahe=ue("libp2p:relay"),L9=class{constructor(e,t){var n;this.components=e,this.autoRelay=((n=t.autoRelay)==null?void 0:n.enabled)!==!1?new O9(e,{addressSorter:t.addressSorter,...t.autoRelay}):void 0,this.started=!1,this.init=t,this._advertiseService=this._advertiseService.bind(this)}isStarted(){return this.started}async start(){this.init.hop.enabled!==!1&&this.init.advertise.enabled!==!1&&(this.timeout=(0,B9.setDelayedInterval)(this._advertiseService,this.init.advertise.ttl,this.init.advertise.bootDelay)),this.started=!0}async stop(){this.timeout!=null&&(0,B9.clearDelayedInterval)(this.timeout),this.started=!1}async _advertiseService(){try{let e=await R9(C9);await this.components.contentRouting.provide(e)}catch(e){e.code===q.ERR_NO_ROUTERS_AVAILABLE?(Ahe.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),await this.stop()):Ahe.error(e)}}};var Lpe=C(Ohe(),1);var lHt=C(Zhe(),1),fHt=C(Rb(),1),Ol=C(at(),1);var cHt=C(gB(),1),epe=C(at(),1),Jhe=epe.default.pki,tpe=(r,e)=>{let t=Jhe.rsa.setPublicKey(e.n,e.e),n=Jhe.createCertificate();n.publicKey=t,n.serialNumber="01",n.validity.notBefore=new Date,n.validity.notAfter=new Date,n.validity.notAfter.setFullYear(n.validity.notBefore.getFullYear()+10);let i=[{name:"organizationName",value:"ipfs"},{shortName:"OU",value:"keystore"},{name:"commonName",value:r.id}];return n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0,codeSigning:!0,emailProtection:!0,timeStamping:!0},{name:"nsCertType",client:!0,server:!0,email:!0,objsign:!0,sslCA:!0,emailCA:!0,objCA:!0}]),n.sign(e),n};async function rpe(r,e){let t=r.map(e),i=(await Promise.all(t)).findIndex(o=>o);return r[i]}var Ll=C(ee(),1);var Lze=ue("libp2p:keychain:cms"),bB=new WeakMap,z9=class{constructor(e,t){if(e==null)throw(0,Ll.default)(new Error("keychain is required"),q.ERR_KEYCHAIN_REQUIRED);this.keychain=e,bB.set(this,{dek:t})}async encrypt(e,t){if(!(t instanceof Uint8Array))throw(0,Ll.default)(new Error("Plain data must be a Uint8Array"),q.ERR_INVALID_PARAMETERS);let n=await this.keychain.findKeyByName(e),i=await this.keychain.getPrivateKey(e),o=bB.get(this);if(o==null)throw(0,Ll.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let s=o.dek,a=Ol.default.pki.decryptRsaPrivateKey(i,s),c=await tpe(n,a),u=Ol.default.pkcs7.createEnvelopedData();u.addRecipient(c),u.content=Ol.default.util.createBuffer(t),u.encrypt();let l=Ol.default.asn1.toDer(u.toAsn1()).getBytes();return fe(l,"ascii")}async decrypt(e){if(!(e instanceof Uint8Array))throw(0,Ll.default)(new Error("CMS data is required"),q.ERR_INVALID_PARAMETERS);let t;try{let l=Ol.default.util.createBuffer(Ee(e,"ascii")),f=Ol.default.asn1.fromDer(l);t=Ol.default.pkcs7.messageFromAsn1(f)}catch(l){throw Lze.error(l),(0,Ll.default)(new Error("Invalid CMS"),q.ERR_INVALID_CMS)}let n=t.recipients.filter(l=>l.issuer.find(f=>f.shortName==="O"&&f.value==="ipfs")).filter(l=>l.issuer.find(f=>f.shortName==="CN")).map(l=>({recipient:l,keyId:l.issuer.find(f=>f.shortName==="CN").value})),i=await rpe(n,async l=>{try{if(await this.keychain.findKeyById(l.keyId)!=null)return!0}catch{return!1}return!1});if(i==null){let l=n.map(f=>f.keyId);throw(0,Ll.default)(new Error(`Decryption needs one of the key(s): ${l.join(", ")}`),q.ERR_MISSING_KEYS,{missingKeys:l})}let o=await this.keychain.findKeyById(i.keyId);if(o==null)throw(0,Ll.default)(new Error("No key available to decrypto"),q.ERR_NO_KEY);let s=await this.keychain.getPrivateKey(o.name),a=bB.get(this);if(a==null)throw(0,Ll.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let c=a.dek,u=Ol.default.pki.decryptRsaPrivateKey(s,c);return t.decrypt(i.recipient,u),fe(t.content.getBytes(),"ascii")}};var nr=C(ee(),1);var Gr;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Gr||(Gr={}));var _B;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(_B||(_B={}));(function(r){r.codec=()=>Jd(_B)})(Gr||(Gr={}));var gu;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Gr.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Gr.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(gu||(gu={}));var yu;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Gr.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Gr.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(yu||(yu={}));var UGt=C(Ic(),1),FGt=C(Rb(),1),q9=C(at(),1);var Io={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var CHt=C(gr(),1),PHt=C(qy(),1),ipe=C(at(),1);function sc(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=yr([new Uint8Array(e-t.length),t])}return Ee(t,"base64url")}function ws(r){let e=ope(r);return new ipe.default.jsbn.BigInteger(Ee(e,"base16"),16)}function ope(r,e){let t=fe(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=yr([new Uint8Array(e-t.length),t])}return t}var Bze={"P-256":256,"P-384":384,"P-521":521},Mze=Object.keys(Bze),VHt=Mze.join(" / ");function K9(r){let e=(r==null?void 0:r.algorithm)??"AES-GCM",t=(r==null?void 0:r.keyLength)??16,n=(r==null?void 0:r.nonceLength)??12,i=(r==null?void 0:r.digest)??"SHA-256",o=(r==null?void 0:r.saltLength)??16,s=(r==null?void 0:r.iterations)??32767,a=Io.get();t*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(o)),p=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:p};typeof h=="string"&&(h=fe(h));let w={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),x=await a.subtle.deriveKey(w,_,{name:e,length:t},!0,["encrypt"]),m=await a.subtle.encrypt(g,x,f);return yr([d,g.iv,new Uint8Array(m)])}async function u(f,h){let d=f.subarray(0,o),p=f.subarray(o,o+n),g=f.subarray(o+n),w={name:e,iv:p};typeof h=="string"&&(h=fe(h));let _={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),m=await a.subtle.deriveKey(_,x,{name:e,length:t},!0,["decrypt"]),y=await a.subtle.decrypt(w,m,g);return new Uint8Array(y)}return{encrypt:c,decrypt:u}}async function ape(r,e){let t=wh.decode(r);return await K9().decrypt(t,e)}var xB={};xe(xB,{RsaPrivateKey:()=>ug,RsaPublicKey:()=>d4,fromJwk:()=>Gze,generateKeyPair:()=>jze,unmarshalRsaPrivateKey:()=>qze,unmarshalRsaPublicKey:()=>Hze});var EGt=C(NC(),1),f4=C(at(),1);function Bl(r){if(isNaN(r)||r<=0)throw new We("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ro.randomBytes(r)}var g0={};xe(g0,{jwkToPkcs1:()=>Fze,jwkToPkix:()=>Vze,pkcs1ToJwk:()=>Uze,pkixToJwk:()=>zze});var eGt=C(Ic(),1),tGt=C(Bh(),1),Ml=C(at(),1);function Uze(r){let e=Ml.default.asn1.fromDer(Ee(r,"ascii")),t=Ml.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:sc(t.n),e:sc(t.e),d:sc(t.d),p:sc(t.p),q:sc(t.q),dp:sc(t.dP),dq:sc(t.dQ),qi:sc(t.qInv),alg:"RS256"}}function Fze(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new We("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ml.default.pki.privateKeyToAsn1({n:ws(r.n),e:ws(r.e),d:ws(r.d),p:ws(r.p),q:ws(r.q),dP:ws(r.dp),dQ:ws(r.dq),qInv:ws(r.qi)});return fe(Ml.default.asn1.toDer(e).getBytes(),"ascii")}function zze(r){let e=Ml.default.asn1.fromDer(Ee(r,"ascii")),t=Ml.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:sc(t.n),e:sc(t.e)}}function Vze(r){if(r.n==null||r.e==null)throw new We("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ml.default.pki.publicKeyToAsn1({n:ws(r.n),e:ws(r.e)});return fe(Ml.default.asn1.toDer(e).getBytes(),"ascii")}var sGt=C(Bh(),1),EB=C(at(),1);function cpe(r,e){return e.map(t=>ws(r[t]))}function upe(r){return EB.default.pki.setRsaPrivateKey(...cpe(r,["n","e","d","p","q","dp","dq","qi"]))}function lpe(r){return EB.default.pki.setRsaPublicKey(...cpe(r,["n","e"]))}async function fpe(r){let e=await Io.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await ppe(e);return{privateKey:t[0],publicKey:t[1]}}async function vB(r){let t=[await Io.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Kze(r)],n=await ppe({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function dpe(r,e){let t=await Io.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Io.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function hpe(r,e,t){let n=await Io.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return await Io.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function ppe(r){if(r.privateKey==null||r.publicKey==null)throw new We("Private and public key are required","ERR_INVALID_PARAMETERS");return await Promise.all([Io.get().subtle.exportKey("jwk",r.privateKey),Io.get().subtle.exportKey("jwk",r.publicKey)])}async function Kze(r){return await Io.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function mpe(r,e,t,n){let i=e?lpe(r):upe(r),o=Ee(Uint8Array.from(t),"ascii"),s=n(o,i);return fe(s,"ascii")}function gpe(r,e){return mpe(r,!0,e,(t,n)=>n.encrypt(t))}function ype(r,e){return mpe(r,!1,e,(t,n)=>n.decrypt(t))}async function cg(r,e){let n=await K9().encrypt(r,e);return wh.encode(n)}var d4=class{constructor(e){this._key=e}async verify(e,t){return await hpe(this._key,t,e)}marshal(){return g0.jwkToPkix(this._key)}get bytes(){return gu.encode({Type:Gr.RSA,Data:this.marshal()}).subarray()}encrypt(e){return gpe(this._key,e)}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}},ug=class{constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Bl(16)}async sign(e){return await dpe(this._key,e)}get public(){if(this._publicKey==null)throw new We("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new d4(this._publicKey)}decrypt(e){return ype(this._key,e)}marshal(){return g0.jwkToPkcs1(this._key)}get bytes(){return yu.encode({Type:Gr.RSA,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}async id(){let e=await this.public.hash();return Ee(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new f4.default.util.ByteBuffer(this.marshal()),i=f4.default.asn1.fromDer(n),o=f4.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return f4.default.pki.encryptRsaPrivateKey(o,e,s)}else{if(t==="libp2p-key")return await cg(this.bytes,e);throw new We(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function qze(r){let e=g0.pkcs1ToJwk(r),t=await vB(e);return new ug(t.privateKey,t.publicKey)}function Hze(r){let e=g0.pkixToJwk(r);return new d4(e)}async function Gze(r){let e=await vB(r);return new ug(e.privateKey,e.publicKey)}async function jze(r){let e=await fpe(r);return new ug(e.privateKey,e.publicKey)}var SB={};xe(SB,{Ed25519PrivateKey:()=>y0,Ed25519PublicKey:()=>h4,generateKeyPair:()=>Xze,generateKeyPairFromSeed:()=>xpe,unmarshalEd25519PrivateKey:()=>Yze,unmarshalEd25519PublicKey:()=>Qze});var lg=32,Ul=64,$9=32;async function wpe(){let r=Lc.randomPrivateKey(),e=await H1(r);return{privateKey:vpe(r,e),publicKey:e}}async function bpe(r){if(r.length!==$9)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await H1(e);return{privateKey:vpe(e,t),publicKey:t}}async function _pe(r,e){let t=r.subarray(0,$9);return await Db(e,t)}async function Epe(r,e,t){return await Ob(e,t,r)}function vpe(r,e){let t=new Uint8Array(Ul);for(let n=0;n<$9;n++)t[n]=r[n],t[$9+n]=e[n];return t}var h4=class{constructor(e){this._key=fg(e,lg)}async verify(e,t){return await Epe(this._key,t,e)}marshal(){return this._key}get bytes(){return gu.encode({Type:Gr.Ed25519,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}},y0=class{constructor(e,t){this._key=fg(e,Ul),this._publicKey=fg(t,lg)}async sign(e){return await _pe(this._key,e)}get public(){return new h4(this._publicKey)}marshal(){return this._key}get bytes(){return yu.encode({Type:Gr.Ed25519,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}async id(){let e=await Ns.digest(this.public.bytes);return tt.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return await cg(this.bytes,e);throw new We(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Yze(r){if(r.length>Ul){r=fg(r,Ul+lg);let n=r.subarray(0,Ul),i=r.subarray(Ul,r.length);return new y0(n,i)}r=fg(r,Ul);let e=r.subarray(0,Ul),t=r.subarray(lg);return new y0(e,t)}function Qze(r){return r=fg(r,lg),new h4(r)}async function Xze(){let{privateKey:r,publicKey:e}=await wpe();return new y0(r,e)}async function xpe(r){let{privateKey:e,publicKey:t}=await bpe(r);return new y0(e,t)}function fg(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new We(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var TB={};xe(TB,{Secp256k1PrivateKey:()=>m4,Secp256k1PublicKey:()=>p4,generateKeyPair:()=>tVe,unmarshalSecp256k1PrivateKey:()=>Jze,unmarshalSecp256k1PublicKey:()=>eVe});function Spe(){return ro.randomPrivateKey()}async function Ape(r,e){let{digest:t}=await mr.digest(e);try{return await Wb(t,r)}catch(n){throw new We(String(n),"ERR_INVALID_INPUT")}}async function Tpe(r,e,t){try{let{digest:n}=await mr.digest(t);return Yb(e,n,r)}catch(n){throw new We(String(n),"ERR_INVALID_INPUT")}}function Ipe(r){return Kt.fromHex(r).toRawBytes(!0)}function Rpe(r){try{im(r,!0)}catch(e){throw new We(String(e),"ERR_INVALID_PRIVATE_KEY")}}function AB(r){try{Kt.fromHex(r)}catch(e){throw new We(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Cpe(r){try{return im(r,!0)}catch(e){throw new We(String(e),"ERR_INVALID_PRIVATE_KEY")}}var p4=class{constructor(e){AB(e),this._key=e}async verify(e,t){return await Tpe(this._key,t,e)}marshal(){return Ipe(this._key)}get bytes(){return gu.encode({Type:Gr.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}},m4=class{constructor(e,t){this._key=e,this._publicKey=t??Cpe(e),Rpe(this._key),AB(this._publicKey)}async sign(e){return await Ape(this._key,e)}get public(){return new p4(this._publicKey)}marshal(){return this._key}get bytes(){return yu.encode({Type:Gr.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}async id(){let e=await this.public.hash();return Ee(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return await cg(this.bytes,e);throw new We(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Jze(r){return new m4(r)}function eVe(r){return new p4(r)}async function tVe(){let r=await Spe();return new m4(r)}var Fl={rsa:xB,ed25519:SB,secp256k1:TB};function IB(r){let e=Object.keys(Fl).join(" / ");return new We(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function RB(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Fl[r];throw IB(r)}async function H9(r,e){return await RB(r).generateKeyPair(e??2048)}function g4(r){let e=gu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Gr.RSA:return Fl.rsa.unmarshalRsaPublicKey(t);case Gr.Ed25519:return Fl.ed25519.unmarshalEd25519PublicKey(t);case Gr.Secp256k1:return Fl.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw IB(e.Type??"RSA")}}function Ppe(r,e){return e=(e??"rsa").toLowerCase(),RB(e),r.bytes}async function dg(r){let e=yu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Gr.RSA:return await Fl.rsa.unmarshalRsaPrivateKey(t);case Gr.Ed25519:return Fl.ed25519.unmarshalEd25519PrivateKey(t);case Gr.Secp256k1:return Fl.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw IB(e.Type??"RSA")}}function kpe(r,e){return e=(e??"rsa").toLowerCase(),RB(e),r.bytes}async function y4(r,e){try{let i=await ape(r,e);return await dg(i)}catch{}let t=q9.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new We("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=q9.default.asn1.toDer(q9.default.pki.privateKeyToAsn1(t));return n=fe(n.getBytes(),"ascii"),await Fl.rsa.unmarshalRsaPrivateKey(n)}var HGt=C(Nh(),1),nVe=C(at(),1);var Dpe=C(bb(),1),Ope=C(gr(),1);var Npe={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function w4(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(Npe).join(" / ");throw new We(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let o=Npe[i],s=(0,Dpe.default)(r,e,t,n,o);return Ope.default.encode64(s,null)}var G9=ue("libp2p:keychain"),sVe="/pkcs8/",Bpe="/info/",rh=new WeakMap,w0={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},CB={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function zl(r){return r==null||typeof r!="string"?!1:r===(0,Lpe.default)(r.trim())&&r.length>0}async function _r(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function wu(r){return new pe(sVe+r)}function Vl(r){return new pe(Bpe+r)}var b0=class{constructor(e,t){var i,o,s,a,c,u,l,f,h,d;if(this.components=e,this.init=et(CB,t),this.init.pass!=null&&((i=this.init.pass)==null?void 0:i.length)<20)throw new Error("pass must be least 20 characters");if(((o=this.init.dek)==null?void 0:o.keyLength)!=null&&this.init.dek.keyLengthn.id===e)}catch(t){throw await _r(),t}}async findKeyByName(e){if(!zl(e))throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);let t=Vl(e);try{let n=await this.components.datastore.get(t);return JSON.parse(Ee(n))}catch(n){throw await _r(),G9.error(n),(0,nr.default)(new Error(`Key '${e}' does not exist.`),q.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!zl(e)||e==="self")throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);let t=wu(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(Vl(e)),await i.commit(),n}async renameKey(e,t){if(!zl(e)||e==="self")throw await _r(),(0,nr.default)(new Error(`Invalid old key name '${e}'`),q.ERR_OLD_KEY_NAME_INVALID);if(!zl(t)||t==="self")throw await _r(),(0,nr.default)(new Error(`Invalid new key name '${t}'`),q.ERR_NEW_KEY_NAME_INVALID);let n=wu(e),i=wu(t),o=Vl(e),s=Vl(t);if(await this.components.datastore.has(i))throw await _r(),(0,nr.default)(new Error(`Key '${t}' already exists`),q.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(o),l=JSON.parse(Ee(u));l.name=t;let f=this.components.datastore.batch();return f.put(i,c),f.put(s,fe(JSON.stringify(l))),f.delete(n),f.delete(o),await f.commit(),l}catch(c){throw await _r(),c}}async exportKey(e,t){if(!zl(e))throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);if(t==null)throw await _r(),(0,nr.default)(new Error("Password is required"),q.ERR_PASSWORD_REQUIRED);let n=wu(e);try{let i=await this.components.datastore.get(n),o=Ee(i),s=rh.get(this);if(s==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let a=s.dek;return await(await y4(o,a)).export(t)}catch(i){throw await _r(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await y4(n,t);return await Yd(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!zl(e)||e==="self")throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);if(t==null)throw await _r(),(0,nr.default)(new Error("PEM encoded key is required"),q.ERR_PEM_REQUIRED);let i=wu(e);if(await this.components.datastore.has(i))throw await _r(),(0,nr.default)(new Error(`Key '${e}' already exists`),q.ERR_KEY_ALREADY_EXISTS);let s;try{s=await y4(t,n)}catch{throw await _r(),(0,nr.default)(new Error("Cannot read the key, most likely the password is wrong"),q.ERR_CANNOT_READ_KEY)}let a;try{a=await s.id();let l=rh.get(this);if(l==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let f=l.dek;t=await s.export(f)}catch(l){throw await _r(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,fe(t)),u.put(Vl(e),fe(JSON.stringify(c))),await u.commit(),c}async importPeer(e,t){try{if(!zl(e))throw(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);if(t==null)throw(0,nr.default)(new Error("PeerId is required"),q.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw(0,nr.default)(new Error("PeerId.privKey is required"),q.ERR_MISSING_PRIVATE_KEY);let n=await dg(t.privateKey),i=wu(e);if(await this.components.datastore.has(i))throw await _r(),(0,nr.default)(new Error(`Key '${e}' already exists`),q.ERR_KEY_ALREADY_EXISTS);let s=rh.get(this);if(s==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let a=s.dek,c=await n.export(a),u={name:e,id:t.toString()},l=this.components.datastore.batch();return l.put(i,fe(c)),l.put(Vl(e),fe(JSON.stringify(u))),await l.commit(),u}catch(n){throw await _r(),n}}async getPrivateKey(e){if(!zl(e))throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);try{let t=wu(e),n=await this.components.datastore.get(t);return Ee(n)}catch(t){throw await _r(),G9.error(t),(0,nr.default)(new Error(`Key '${e}' does not exist.`),q.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){var a,c,u,l;if(typeof e!="string")throw await _r(),(0,nr.default)(new Error(`Invalid old pass type '${typeof e}'`),q.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await _r(),(0,nr.default)(new Error(`Invalid new pass type '${typeof t}'`),q.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await _r(),(0,nr.default)(new Error(`Invalid pass length ${t.length}`),q.ERR_INVALID_PASS_LENGTH);G9("recreating keychain");let n=rh.get(this);if(n==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let o=t!=null&&((a=this.init.dek)==null?void 0:a.salt)!=null?w4(t,this.init.dek.salt,(c=this.init.dek)==null?void 0:c.iterationCount,(u=this.init.dek)==null?void 0:u.keyLength,(l=this.init.dek)==null?void 0:l.hash):"";rh.set(this,{dek:o});let s=await this.listKeys();for(let f of s){let h=await this.components.datastore.get(wu(f.name)),d=Ee(h),p=await y4(d,i),g=o.toString(),w=await p.export(g),_=this.components.datastore.batch(),x={name:f.name,id:f.id};_.put(wu(f.name),fe(w)),_.put(Vl(f.name),fe(JSON.stringify(x))),await _.commit()}G9("keychain reconstructed")}};async function b4(r){try{return{status:"fulfilled",value:await r,isFulfilled:!0,isRejected:!1}}catch(e){return{status:"rejected",reason:e,isFulfilled:!1,isRejected:!0}}}var PB=class{constructor(e){B(this,"value");B(this,"next");this.value=e}},bu,_0,E0,_4=class{constructor(){bt(this,bu,void 0);bt(this,_0,void 0);bt(this,E0,void 0);this.clear()}enqueue(e){let t=new PB(e);ge(this,bu)?(ge(this,_0).next=t,Dt(this,_0,t)):(Dt(this,bu,t),Dt(this,_0,t)),uh(this,E0)._++}dequeue(){let e=ge(this,bu);if(e)return Dt(this,bu,ge(this,bu).next),uh(this,E0)._--,e.value}clear(){Dt(this,bu,void 0),Dt(this,_0,void 0),Dt(this,E0,0)}get size(){return ge(this,E0)}*[Symbol.iterator](){let e=ge(this,bu);for(;e;)yield e.value,e=e.next}};bu=new WeakMap,_0=new WeakMap,E0=new WeakMap;function kB(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=new _4,t=0,n=()=>{t--,e.size>0&&e.dequeue()()},i=async(a,c,u)=>{t++;let l=(async()=>a(...u))();c(l);try{await l}catch{}n()},o=(a,c,u)=>{e.enqueue(i.bind(void 0,a,c,u)),(async()=>(await Promise.resolve(),t0&&e.dequeue()()))()},s=(a,...c)=>new Promise(u=>{o(a,u,c)});return Object.defineProperties(s,{activeCount:{get:()=>t},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),s}async function NB(r,e={}){let{concurrency:t=Number.POSITIVE_INFINITY}=e,n=kB(t);return Promise.all(r.map(i=>i&&typeof i.then=="function"?b4(i):typeof i=="function"?b4(n(()=>i())):b4(Promise.resolve(i))))}var hg=C(ee(),1);var DB=class extends Map{constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function bs(r){let{name:e,metrics:t}=r,n;return t!=null?n=new DB({name:e,metrics:t}):n=new Map,n}var v0=ue("libp2p:transports"),j9=class extends Zt{constructor(e,t={}){super(),this.components=e,this.started=!1,this.transports=new Map,this.listeners=bs({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Qd.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw(0,hg.default)(new Error("Transport must have a valid tag"),q.ERR_INVALID_KEY);if(this.transports.has(t))throw(0,hg.default)(new Error("There is already a transport with this tag"),q.ERR_DUPLICATE_TRANSPORT);v0("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}async start(){let e=this.components.addressManager.getListenAddrs();await this.listen(e),this.started=!0}async stop(){let e=[];for(let[t,n]of this.listeners)for(v0("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),v0("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw(0,hg.default)(new Error(`No transport available for address ${String(e)}`),q.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=q.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(e==null||e.length===0){v0("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){v0("creating listener for %s on %s",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n);f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.dispatchEvent(new ve("listener:listening",{detail:l}))}),l.addEventListener("close",()=>{this.dispatchEvent(new ve("listener:close",{detail:l}))}),s.push(l.listen(u))}if(s.length===0){t.push(n);continue}if((await NB(s)).find(u=>u.isFulfilled)==null&&this.faultTolerance!==Qd.NO_FATAL)throw(0,hg.default)(new Error(`Transport (${n}) could not listen on any available address`),q.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Qd.FATAL_ALL)throw(0,hg.default)(new Error(n),q.ERR_NO_VALID_ADDRESSES);v0(`libp2p in dial mode only: ${n}`)}}async remove(e){v0("removing %s",e);for(let t of this.listeners.get(e)??[])await t.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Wn=C(ee(),1);var Kl="/multistream/1.0.0";var zpe=C(ee(),1);var OB=C(ee(),1);var cVe=ue("libp2p:mss"),Mpe=fe(` -`);function E4(r){let e=new ln(r,Mpe);return vn.single(e)}function x0(r,e,t={}){let n=E4(e);t.writeBytes===!0?r.push(n.subarray()):r.push(n)}function Upe(r,e,t={}){let n=new ln;for(let i of e)n.append(E4(i));t.writeBytes===!0?r.push(n.subarray()):r.push(n)}async function uVe(r,e){let t=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await r.next(t)},i=n;(e==null?void 0:e.signal)!=null&&(i=sa(n,e.signal));let s=await Ne(i,Xr({onLength:a=>{t=a},maxDataLength:1024}),async a=>await Fi(a));if(s==null||s.length===0)throw(0,OB.default)(new Error("no buffer returned"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(s.get(s.byteLength-1)!==Mpe[0])throw cVe.error("Invalid mss message - missing newline - %s",s.subarray()),(0,OB.default)(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return s.sublist(0,-1)}async function pg(r,e){let t=await uVe(r,e);return Ee(t.subarray())}var v4=ue("libp2p:mss:select");async function x4(r,e,t={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:o,stream:s}=ng(r),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");v4('select: write ["%s", "%s"]',Kl,a);let c=fe(Kl),u=fe(a);Upe(i,[c,u],t);let l=await pg(n,t);if(v4('select: read "%s"',l),l===Kl&&(l=await pg(n,t),v4('select: read "%s"',l)),l===a)return o(),{stream:s,protocol:a};for(let f of e){v4('select: write "%s"',f),x0(i,fe(f),t);let h=await pg(n,t);if(v4('select: read "%s" for "%s"',h,f),h===f)return o(),{stream:s,protocol:f}}throw o(),(0,zpe.default)(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}var S4=ue("libp2p:mss:handle");async function A4(r,e,t){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:o,stream:s}=ng(r);for(;;){let a=await pg(i,t);if(S4('read "%s"',a),a===Kl){S4('respond with "%s" for "%s"',Kl,a),x0(n,fe(Kl),t);continue}if(e.includes(a))return x0(n,fe(a),t),S4('respond with "%s" for "%s"',a,a),o(),{stream:s,protocol:a};if(a==="ls"){x0(n,new ln(...e.map(c=>E4(fe(c)))),t),S4('respond with "%s" for %s',e,a);continue}x0(n,fe("na"),t),S4('respond with "na" for "%s"',a)}}var LB=C(ee(),1);var Vpe=Symbol.for("@libp2p/connection");var fVe=ue("libp2p:connection"),BB=class{constructor(e){let{remoteAddr:t,remotePeer:n,newStream:i,close:o,getStreams:s,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.stat={...a,status:y9},this._newStream=i,this._close=o,this._getStreams=s,this.tags=[],this._closing=!1}get[Symbol.toStringTag](){return"Connection"}get[Vpe](){return!0}get streams(){return this._getStreams()}async newStream(e,t){if(this.stat.status===zL)throw(0,LB.default)(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===w9)throw(0,LB.default)(new Error("the connection is closed"),"ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,t);return n.stat.direction="outbound",n}addStream(e){e.stat.direction="inbound"}removeStream(e){}async close(){if(!(this.stat.status===w9||this._closing)){this.stat.status=zL;try{this.streams.forEach(e=>e.close())}catch(e){fVe.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=w9}}};function Kpe(r){return new BB(r)}var Y9=C(ee(),1);var W9=Symbol.for("@libp2p/topology");function $pe(r){return r!=null&&!!r[W9]}var MB=ue("libp2p:registrar"),UB=32,FB=64,Q9=class{constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onProtocolChange=this._onProtocolChange.bind(this),this._onConnect=this._onConnect.bind(this),this.components.connectionManager.addEventListener("peer:disconnect",this._onDisconnect),this.components.connectionManager.addEventListener("peer:connect",this._onConnect),this.components.peerStore.addEventListener("change:protocols",this._onProtocolChange)}getProtocols(){return Array.from(new Set([...this.topologies.keys(),...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw(0,Y9.default)(new Error(`No handler registered for protocol ${e}`),q.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw(0,Y9.default)(new Error(`Handler already registered for protocol ${e}`),q.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=et.bind({ignoreUndefined:!0})({maxInboundStreams:UB,maxOutboundStreams:FB},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.protoBook.add(this.components.peerId,[e])}async unhandle(e){let t=Array.isArray(e)?e:[e];t.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.protoBook.remove(this.components.peerId,t)}async register(e,t){if(!$pe(t))throw MB.error("topology must be an instance of interfaces/topology"),(0,Y9.default)(new Error("topology must be an instance of interfaces/topology"),q.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,t),await t.setRegistrar(this),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.protoBook.get(t.remotePeer).then(n=>{for(let i of n){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect(t.remotePeer)}}).catch(n=>{MB.error(n)})}_onConnect(e){let t=e.detail;this.components.peerStore.protoBook.get(t.remotePeer).then(n=>{for(let i of n){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onConnect(t.remotePeer,t)}}).catch(n=>{MB.error(n)})}_onProtocolChange(e){let{peerId:t,protocols:n,oldProtocols:i}=e.detail,o=i.filter(a=>!n.includes(a)),s=n.filter(a=>!i.includes(a));for(let a of o){let c=this.topologies.get(a);if(c!=null)for(let u of c.values())u.onDisconnect(t)}for(let a of s){let c=this.topologies.get(a);if(c!=null)for(let u of c.values()){let l=this.components.connectionManager.getConnections(t)[0];l!=null&&u.onConnect(t,l)}}}};var zB=C(Kn(),1);var VB=C(xi(),1),Pr=ue("libp2p:upgrader");function dVe(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==q.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return UB}function hVe(r,e){try{let{options:t}=e.getHandler(r);return t.maxOutboundStreams}catch(t){if(t.code!==q.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return FB}function qpe(r,e,t){let n=0;return t.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===r&&n++}),n}var X9=class extends Zt{constructor(e,t){super(),this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout}async upgradeInbound(e,t){var l,f;if(!await this.components.connectionManager.acceptIncomingConnection(e))throw(0,Wn.default)(new Error("connection denied"),q.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=new zB.TimeoutController(this.inboundUpgradeTimeout);try{(l=VB.setMaxListeners)==null||l(1/0,u.signal)}catch{}try{let h=ps(e,u.signal);if(e.source=h.source,e.sink=h.sink,await this.components.connectionGater.denyInboundConnection(e))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptConnection"),q.ERR_CONNECTION_INTERCEPTED);(f=this.components.metrics)==null||f.trackMultiaddrConnection(e),Pr("starting the inbound connection upgrade");let d=e;if((t==null?void 0:t.skipProtection)!==!0){let p=this.components.connectionProtector;p!=null&&(Pr("protecting the inbound connection"),d=await p.protect(e))}try{if(i=d,(t==null?void 0:t.skipEncryption)!==!0){if({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(d),await this.components.connectionGater.denyInboundEncryptedConnection(o,{...d,...i}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED)}else{let p=e.remoteAddr.getPeerId();if(p==null)throw(0,Wn.default)(new Error("inbound connection that skipped encryption must have a peer id"),q.ERR_INVALID_MULTIADDR);let g=xt(p);c="native",o=g}if(s=i,(t==null?void 0:t.muxerFactory)!=null)a=t.muxerFactory;else if(this.muxers.size>0){let p=await this._multiplexInbound({...d,...i},this.muxers);a=p.muxerFactory,s=p.stream}}catch(p){throw Pr.error("Failed to upgrade inbound connection",p),p}if(await this.components.connectionGater.denyInboundUpgradedConnection(o,{...d,...i}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED);return Pr("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,t){var f;let n=e.remoteAddr.getPeerId(),i;if(n!=null&&(i=xt(n),await this.components.connectionGater.denyOutboundConnection(i,e)))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),q.ERR_CONNECTION_INTERCEPTED);let o,s,a,c,u;(f=this.components.metrics)==null||f.trackMultiaddrConnection(e),Pr("Starting the outbound connection upgrade");let l=e;if((t==null?void 0:t.skipProtection)!==!0){let h=this.components.connectionProtector;h!=null&&(l=await h.protect(e))}try{if(o=l,(t==null?void 0:t.skipEncryption)!==!0){if({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i),await this.components.connectionGater.denyOutboundEncryptedConnection(s,{...l,...o}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED)}else{if(i==null)throw(0,Wn.default)(new Error("Encryption was skipped but no peer id was passed"),q.ERR_INVALID_PEER);c="native",s=i}if(a=o,(t==null?void 0:t.muxerFactory)!=null)u=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...l,...o},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw Pr.error("Failed to upgrade outbound connection",h),await e.close(h),h}if(await this.components.connectionGater.denyOutboundUpgradedConnection(s,{...l,...o}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED);return Pr("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{var m;let p=this.components.registrar.getProtocols(),{stream:g,protocol:w}=await A4(d,p);if(Pr("%s: incoming stream opened on %s",n,w),l==null)return;let _=dVe(w,this.components.registrar);if(qpe(w,"inbound",l)===_){d.abort((0,Wn.default)(new Error(`Too many inbound protocol streams for protocol "${w}" - limit ${_}`),q.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS));return}d.source=g.source,d.sink=g.sink,d.stat.protocol=w,this.components.peerStore.protoBook.add(s,[w]).catch(y=>Pr.error(y)),l.addStream(d),(m=this.components.metrics)==null||m.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:w})}).catch(p=>{Pr.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l==null||l.removeStream(d.id)}}),u=async(d,p={})=>{var _,x;if(c==null)throw(0,Wn.default)(new Error("Stream is not multiplexed"),q.ERR_MUXER_UNAVAILABLE);Pr("%s: starting new stream on %s",n,d);let g=await c.newStream(),w;try{if(p.signal==null){Pr("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),w=new zB.TimeoutController(3e4),p.signal=w.signal;try{(_=VB.setMaxListeners)==null||_(1/0,w.signal)}catch{}}let{stream:m,protocol:y}=await x4(g,d,p),b=hVe(y,this.components.registrar);if(qpe(y,"outbound",l)===b){let v=(0,Wn.default)(new Error(`Too many outbound protocol streams for protocol "${y}" - limit ${b}`),q.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw g.abort(v),v}return this.components.peerStore.protoBook.add(s,[y]).catch(v=>Pr.error(v)),g.source=m.source,g.sink=m.sink,g.stat.protocol=y,(x=this.components.metrics)==null||x.trackProtocolStream(g,l),g}catch(m){throw Pr.error("could not create new stream",m),g.stat.timeline.close==null&&g.close(),m.code!=null?m:(0,Wn.default)(m,q.ERR_UNSUPPORTED_PROTOCOL)}finally{w!=null&&w.clear()}},Promise.all([c.sink(o.source),o.sink(c.source)]).catch(d=>{Pr.error(d)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){Pr.error(p)}finally{this.dispatchEvent(new ve("connectionEnd",{detail:l}))}})().catch(p=>{Pr.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let h=()=>{throw(0,Wn.default)(new Error("connection is not multiplexed"),q.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Kpe({remoteAddr:i.remoteAddr,remotePeer:s,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c==null?void 0:c.protocol,encryption:t},newStream:u??h,getStreams:()=>c!=null?c.streams:h(),close:async()=>{await i.close(),c!=null&&c.close()}}),this.dispatchEvent(new ve("connection",{detail:l})),l}_onStream(e){let{connection:t,stream:n,protocol:i}=e,{handler:o}=this.components.registrar.getHandler(i);o({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());Pr("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:i}=await A4(e,t,{writeBytes:!0}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return Pr("encrypting inbound connection..."),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw(0,Wn.default)(n,q.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());Pr("selecting outbound crypto protocol",n);try{let{stream:i,protocol:o}=await x4(e,n,{writeBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return Pr("encrypting outbound connection to %p",t),{...await s.secureOutbound(this.components.peerId,i,t),protocol:o}}catch(i){throw(0,Wn.default)(i,q.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());Pr("outbound selecting muxer %s",n);try{let{stream:i,protocol:o}=await x4(e,n,{writeBytes:!0});Pr("%s selected as muxer protocol",o);let s=t.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Pr.error("error multiplexing outbound stream",i),(0,Wn.default)(i,q.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());Pr("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await A4(e,n,{writeBytes:!0}),s=t.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Pr.error("error multiplexing inbound stream",i),(0,Wn.default)(i,q.ERR_MUXER_UNAVAILABLE)}}};var A0=C(ee(),1);var S0;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(S0||(S0={}));var Gpe=C(ee(),1);var Hpe={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var T4;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.publicKey!=null&&t.publicKey.byteLength>0)&&(n.uint32(10),n.bytes(t.publicKey)),(i.writeDefaults===!0||t.payloadType!=null&&t.payloadType.byteLength>0)&&(n.uint32(18),n.bytes(t.payloadType)),(i.writeDefaults===!0||t.payload!=null&&t.payload.byteLength>0)&&(n.uint32(26),n.bytes(t.payload)),(i.writeDefaults===!0||t.signature!=null&&t.signature.byteLength>0)&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(T4||(T4={}));var pVe,Yn=class{constructor(e){let{peerId:t,payloadType:n,payload:i,signature:o}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=T4.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return rr(this.marshal(),e.marshal())}async validate(e){let t=jpe(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await g4(this.peerId.publicKey).verify(t.subarray(),this.signature)}};pVe=Yn;Yn.createFromProtobuf=async r=>{let e=T4.decode(r),t=await Yd(e.publicKey);return new Yn({peerId:t,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};Yn.seal=async(r,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let t=r.domain,n=r.codec,i=r.marshal(),o=jpe(t,n,i),a=await(await dg(e.privateKey)).sign(o.subarray());return new Yn({peerId:e,payloadType:n,payload:i,signature:a})};Yn.openAndCertify=async(r,e)=>{let t=await Yn.createFromProtobuf(r);if(!await t.validate(e))throw(0,Gpe.default)(new Error("envelope signature is not valid for the given domain"),Hpe.ERR_SIGNATURE_NOT_VALID);return t};var jpe=(r,e,t)=>{let n=fe(r),i=nc.encode(n.byteLength),o=nc.encode(e.length),s=nc.encode(t.length);return new ln(i,n,o,e,s,t)};function Wpe(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var I4;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=Cr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),(a.writeDefaults===!0||o.multiaddr!=null&&o.multiaddr.byteLength>0)&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>Rr(o,n.codec()),n.decode=o=>Ir(o,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Cr((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),(o.writeDefaults===!0||n.peerId!=null&&n.peerId.byteLength>0)&&(i.uint32(10),i.bytes(n.peerId)),(o.writeDefaults===!0||n.seq!==0n)&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(s,i,{writeDefaults:!0});o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),t),r.encode=n=>Rr(n,r.codec()),r.decode=n=>Ir(n,r.codec())})(I4||(I4={}));var Ype="libp2p-peer-record",Qpe=Uint8Array.from([3,1]);var Mn=class{constructor(e){this.domain=Mn.DOMAIN,this.codec=Mn.CODEC;let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=I4.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Mn)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Wpe(this.multiaddrs,e.multiaddrs))}};Mn.createFromProtobuf=r=>{let e=I4.decode(r),t=Wd(e.peerId),n=(e.addresses??[]).map(o=>lt(o.multiaddr)),i=e.seq;return new Mn({peerId:t,multiaddrs:n,seqNumber:i})};Mn.DOMAIN=Ype;Mn.CODEC=Qpe;var Z9="0.0.0",Xpe="libp2p";var KB=`js-libp2p/${Z9}`;var Zpe="0.1.0",Jpe="id",e0e="id/push",t0e="1.0.0",r0e="1.0.0";var R4=C(Kn(),1);var C4=C(xi(),1),vr=ue("libp2p:identify"),n0e=1024*8,mg=class{constructor(e,t){this.components=e,this.started=!1,this.init=t,this.identifyProtocolStr=`/${t.protocolPrefix}/${Jpe}/${t0e}`,this.identifyPushProtocolStr=`/${t.protocolPrefix}/${e0e}/${r0e}`,this.host={protocolVersion:`${t.protocolPrefix}/${Zpe}`,...t.host},this.components.connectionManager.addEventListener("peer:connect",n=>{let i=n.detail;this.identify(i).catch(vr.error)}),this.components.peerStore.addEventListener("change:multiaddrs",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(o=>vr.error(o))}),this.components.peerStore.addEventListener("change:protocols",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(o=>vr.error(o))})}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.metadataBook.setValue(this.components.peerId,"AgentVersion",fe(this.host.agentVersion)),await this.components.peerStore.metadataBook.setValue(this.components.peerId,"ProtocolVersion",fe(this.host.protocolVersion)),await this.components.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{vr.error(t)})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),await this.components.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{vr.error(t)})},{maxInboundStreams:this.init.maxPushIncomingStreams,maxOutboundStreams:this.init.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.identifyProtocolStr),await this.components.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async push(e){let t=await this.components.peerStore.addressBook.getRawEnvelope(this.components.peerId),n=this.components.addressManager.getAddresses().map(s=>s.bytes),i=await this.components.peerStore.protoBook.get(this.components.peerId),o=e.map(async s=>{var u;let a,c=new R4.TimeoutController(this.init.timeout);try{(u=C4.setMaxListeners)==null||u(1/0,c.signal)}catch{}try{a=await s.newStream([this.identifyPushProtocolStr],{signal:c.signal}),await ps(a,c.signal).sink(Ne([S0.encode({listenAddrs:n,signedPeerRecord:t,protocols:i})],vn()))}catch(l){vr.error("could not push identify update to peer",l)}finally{a!=null&&a.close(),c.clear()}});await Promise.all(o)}async pushToPeerStore(){if(!this.isStarted())return;let e=[];for(let t of this.components.connectionManager.getConnections()){let n=t.remotePeer;(await this.components.peerStore.get(n)).protocols.includes(this.identifyPushProtocolStr)&&e.push(t)}await this.push(e)}async _identify(e,t={}){var s;let n,i=t.signal,o;if(i==null){n=new R4.TimeoutController(this.init.timeout),i=n.signal;try{(s=C4.setMaxListeners)==null||s(1/0,n.signal)}catch{}}try{o=await e.newStream([this.identifyProtocolStr],{signal:i});let a=ps(o,i),c=await Ne([],a,Xr({maxDataLength:this.init.maxIdentifyMessageSize??n0e}),async u=>await Fi(u));if(c==null)throw(0,A0.default)(new Error("No data could be retrieved"),q.ERR_CONNECTION_ENDED);try{return S0.decode(c)}catch(u){throw(0,A0.default)(u,q.ERR_INVALID_MESSAGE)}}finally{n!=null&&n.clear(),o!=null&&o.close()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,listenAddrs:o,protocols:s,observedAddr:a,signedPeerRecord:c,agentVersion:u,protocolVersion:l}=n;if(i==null)throw(0,A0.default)(new Error("public key was missing from identify message"),q.ERR_MISSING_PUBLIC_KEY);let f=await Yd(i);if(!e.remotePeer.equals(f))throw(0,A0.default)(new Error("identified peer does not match the expected peer"),q.ERR_INVALID_PEER);if(this.components.peerId.equals(f))throw(0,A0.default)(new Error("identified peer is our own peer id?"),q.ERR_INVALID_PEER);let h=mg.getCleanMultiaddr(a);if(c!=null){vr("received signed peer record from %p",f);try{let d=await Yn.openAndCertify(c,Mn.DOMAIN);if(!d.peerId.equals(f))throw(0,A0.default)(new Error("identified peer does not match the expected peer"),q.ERR_INVALID_PEER);if(await this.components.peerStore.addressBook.consumePeerRecord(d)){await this.components.peerStore.protoBook.set(f,s),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",fe(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",fe(l)),vr("identify completed for peer %p and protocols %o",f,s);return}}catch(d){vr("received invalid envelope, discard it and fallback to listenAddrs is available",d)}}else vr("no signed peer record received from %p",f);vr("falling back to legacy addresses from %p",f);try{await this.components.peerStore.addressBook.set(f,o.map(d=>lt(d)))}catch(d){vr.error("received invalid addrs",d)}await this.components.peerStore.protoBook.set(f,s),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",fe(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",fe(l)),vr("identify completed for peer %p and protocols %o",f,s),vr("received observed address of %s",h==null?void 0:h.toString())}async _handleIdentify(e){var o;let{connection:t,stream:n}=e,i=new R4.TimeoutController(this.init.timeout);try{(o=C4.setMaxListeners)==null||o(1/0,i.signal)}catch{}try{let s=this.components.peerId.publicKey??new Uint8Array(0),a=await this.components.peerStore.get(this.components.peerId),c=this.components.addressManager.getAddresses().map(d=>d.decapsulateCode(hr("p2p").code)),u=a.peerRecordEnvelope;if(c.length>0&&u==null){let d=new Mn({peerId:this.components.peerId,multiaddrs:c}),p=await Yn.seal(d,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(p),u=p.marshal().subarray()}let l=S0.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:c.map(d=>d.bytes),signedPeerRecord:u,observedAddr:t.remoteAddr.bytes,protocols:a.protocols}),f=ps(n,i.signal),h=Ne([l],vn());await f.sink(h)}catch(s){vr.error("could not respond to identify request",s)}finally{n.close(),i.clear()}}async _handlePush(e){var a;let{connection:t,stream:n}=e,i=new R4.TimeoutController(this.init.timeout);try{(a=C4.setMaxListeners)==null||a(1/0,i.signal)}catch{}let o;try{let c=ps(n,i.signal),u=await Ne([],c,Xr({maxDataLength:this.init.maxIdentifyMessageSize??n0e}),async l=>await Fi(l));u!=null&&(o=S0.decode(u))}catch(c){return vr.error("received invalid message",c)}finally{n.close(),i.clear()}if(o==null)return vr.error("received invalid message");let s=t.remotePeer;if(this.components.peerId.equals(s)){vr("received push from ourselves?");return}if(vr("received push from %p",s),o.signedPeerRecord!=null){vr("received signedPeerRecord in push");try{let c=await Yn.openAndCertify(o.signedPeerRecord,Mn.DOMAIN);if(await this.components.peerStore.addressBook.consumePeerRecord(c)){vr("consumed signedPeerRecord sent in push"),await this.components.peerStore.protoBook.set(s,o.protocols);return}else vr("failed to consume signedPeerRecord sent in push")}catch(c){vr("received invalid envelope, discard it and fallback to listenAddrs is available",c)}}else vr("did not receive signedPeerRecord in push");try{await this.components.peerStore.addressBook.set(s,o.listenAddrs.map(c=>lt(c)))}catch(c){vr.error("received invalid addrs",c)}try{await this.components.peerStore.protoBook.set(s,o.protocols)}catch(c){vr.error("received invalid protocols",c)}vr("handled push from %p",s)}static getCleanMultiaddr(e){if(e!=null&&e.length>0)try{return lt(e)}catch{}}};var gg=C(ee(),1);var P4;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identifier!=="")&&(n.uint32(10),n.string(t.identifier)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identifier:""},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.identifier=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(P4||(P4={}));var ac;(function(r){let e;(function(i){i.OK="OK",i.NOT_FOUND="NOT_FOUND",i.ERROR="ERROR"})(e=r.StatusCode||(r.StatusCode={}));let t;(function(i){i[i.OK=0]="OK",i[i.NOT_FOUND=1]="NOT_FOUND",i[i.ERROR=2]="ERROR"})(t||(t={})),function(i){i.codec=()=>Jd(t)}(e=r.StatusCode||(r.StatusCode={}));let n;r.codec=()=>(n==null&&(n=Cr((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),(s.writeDefaults===!0||i.status!=null&&t[i.status]!==0)&&(o.uint32(8),r.StatusCode.codec().encode(i.status,o)),(s.writeDefaults===!0||i.data!=null&&i.data.byteLength>0)&&(o.uint32(18),o.bytes(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={status:e.OK,data:new Uint8Array(0)},a=o==null?i.len:i.pos+o;for(;i.pos>>3){case 1:s.status=r.StatusCode.codec().decode(i);break;case 2:s.data=i.bytes();break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>Rr(i,r.codec()),r.decode=i=>Ir(i,r.codec())})(ac||(ac={}));var i0e="0.0.1",o0e="fetch";var s0e=C(Kn(),1),a0e=C(xi(),1);var da=ue("libp2p:fetch"),J9=class{constructor(e,t){this.started=!1,this.components=e,this.protocol=`/${t.protocolPrefix??"libp2p"}/${o0e}/${i0e}`,this.lookupFunctions=new Map,this.handleMessage=this.handleMessage.bind(this),this.init=t}async start(){await this.components.registrar.handle(this.protocol,e=>{this.handleMessage(e).catch(t=>{da.error(t)}).finally(()=>{e.stream.close()})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async fetch(e,t,n={}){var c;da("dialing %s to %p",this.protocol,e);let i=await this.components.connectionManager.openConnection(e,n),o,s=n.signal,a;if(s==null){da("using default timeout of %d ms",this.init.timeout),o=new s0e.TimeoutController(this.init.timeout),s=o.signal;try{(c=a0e.setMaxListeners)==null||c(1/0,o.signal)}catch{}}try{a=await i.newStream(this.protocol,{signal:s});let u=ps(a,s);return da("fetch %s",t),await Ne([P4.encode({identifier:t})],vn(),u,Xr(),async function(f){let h=await Fi(f);if(h==null)throw(0,gg.default)(new Error("No data received"),q.ERR_INVALID_MESSAGE);let d=ac.decode(h);switch(d.status){case ac.StatusCode.OK:return da("received status for %s ok",t),d.data;case ac.StatusCode.NOT_FOUND:return da("received status for %s not found",t),null;case ac.StatusCode.ERROR:{da("received status for %s error",t);let p=Ee(d.data);throw(0,gg.default)(new Error("Error in fetch protocol response: "+p),q.ERR_INVALID_PARAMETERS)}default:throw da("received status for %s unknown",t),(0,gg.default)(new Error("Unknown response status"),q.ERR_INVALID_MESSAGE)}})??null}finally{o!=null&&o.clear(),a!=null&&a.close()}}async handleMessage(e){let{stream:t}=e,n=this;await Ne(t,Xr(),async function*(i){let o=await Fi(i);if(o==null)throw(0,gg.default)(new Error("No data received"),q.ERR_INVALID_MESSAGE);let s=P4.decode(o),a,c=n._getLookupFunction(s.identifier);if(c!=null){da("look up data with identifier %s",s.identifier);let u=await c(s.identifier);u!=null?(da("sending status for %s ok",s.identifier),a={status:ac.StatusCode.OK,data:u}):(da("sending status for %s not found",s.identifier),a={status:ac.StatusCode.NOT_FOUND,data:new Uint8Array(0)})}else{da("sending status for %s error",s.identifier);let u=fe(`No lookup function registered for key: ${s.identifier}`);a={status:ac.StatusCode.ERROR,data:u}}yield ac.encode(a)},vn(),t)}_getLookupFunction(e){for(let t of this.lookupFunctions.keys())if(e.startsWith(t))return this.lookupFunctions.get(t)}registerLookupFunction(e,t){if(this.lookupFunctions.has(e))throw(0,gg.default)(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),q.ERR_KEY_ALREADY_EXISTS);this.lookupFunctions.set(e,t)}unregisterLookupFunction(e,t){t!=null&&this.lookupFunctions.get(e)!==t||this.lookupFunctions.delete(e)}};var f0e=C(ee(),1);var c0e="1.0.0",u0e="ping";var d0e=C(Kn(),1),h0e=C(xi(),1),l0e=ue("libp2p:ping"),ex=class{constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix}/${u0e}/${c0e}`,this.init=t}async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){let{stream:t}=e;Ne(t,t).catch(n=>{l0e.error(n)})}async ping(e,t={}){var u;l0e("dialing %s to %p",this.protocol,e);let n=Date.now(),i=Bl(32),o=await this.components.connectionManager.openConnection(e,t),s,a=t.signal,c;if(a==null){s=new d0e.TimeoutController(this.init.timeout),a=s.signal;try{(u=h0e.setMaxListeners)==null||u(1/0,s.signal)}catch{}}try{c=await o.newStream([this.protocol],{signal:a});let l=ps(c,a),f=await Ne([i],l,async d=>await Fi(d)),h=Date.now();if(f==null||!rr(i,f.subarray()))throw(0,f0e.default)(new Error("Received wrong ping ack"),q.ERR_WRONG_PING_ACK);return h-n}finally{s!=null&&s.clear(),c!=null&&c.close()}}};async function p0e(){throw new Error("Not supported in browsers")}var m0e=C(EA(),1),$B=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,tx=(0,m0e.default)(),T0=$B&&!tx,g0e=tx&&!$B,y0e=tx&&$B,w0e=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!tx,rx=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,UYt=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",b0e=typeof navigator<"u"&&navigator.product==="ReactNative";var v0e=C(ee(),1);function _0e(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function E0e(r){let{address:e}=r.nodeAddress();return _0e(e)}var qB=ue("libp2p:nat"),HB=7200;function yVe(r=1024,e=65535){return Math.floor(Math.random()*(e-r+1)+r)}var nx=class{constructor(e,t){if(this.components=e,this.started=!1,this.enabled=t.enabled,this.externalAddress=t.externalAddress,this.localAddress=t.localAddress,this.description=t.description??`${Xpe}@${Z9} ${this.components.peerId.toString()}`,this.ttl=t.ttl??HB,this.keepAlive=t.keepAlive??!0,this.gateway=t.gateway,this.ttl{qB.error(e)}))}async _start(){let e=this.components.transportManager.getAddrs();for(let t of e){let{family:n,host:i,port:o,transport:s}=t.toOptions();if(!t.isThinWaistAddress()||s!=="tcp"||E0e(t)||n!==4)continue;let a=await this._getClient(),c=this.externalAddress??await a.externalIp(),u=D9(c);if(u===!0)throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);if(u==null)throw new Error(`${c} is not an IP address`);let l=yVe();qB(`opening uPnP connection from ${c}:${l} to ${i}:${o}`),await a.map({publicPort:l,localPort:o,localAddress:this.localAddress,protocol:s.toUpperCase()==="TCP"?"TCP":"UDP"}),this.components.addressManager.addObservedAddr(oie({family:4,address:c,port:l},s))}}async _getClient(){return this.client!=null?this.client:(this.client=await p0e({description:this.description,ttl:this.ttl,keepAlive:this.keepAlive,gateway:this.gateway}),this.client)}async stop(){if(!(T0||this.client==null))try{await this.client.close(),this.client=void 0}catch(e){qB.error(e)}}};var wVe=ue("libp2p:peer-record-updater"),ix=class{constructor(e){this.components=e,this.started=!1,this.update=this.update.bind(this)}isStarted(){return this.started}async start(){this.started=!0,this.components.transportManager.addEventListener("listener:listening",this.update),this.components.transportManager.addEventListener("listener:close",this.update),this.components.addressManager.addEventListener("change:addresses",this.update)}async stop(){this.started=!1,this.components.transportManager.removeEventListener("listener:listening",this.update),this.components.transportManager.removeEventListener("listener:close",this.update),this.components.addressManager.removeEventListener("change:addresses",this.update)}update(){Promise.resolve().then(async()=>{let e=new Mn({peerId:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(n=>n.decapsulateCode(hr("p2p").code))}),t=await Yn.seal(e,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(t)}).catch(e=>{wVe.error("Could not update self peer record: %o",e)})}};var x0e=C(ee(),1);var ox=class{constructor(e){this.dht=e}async findPeer(e,t={}){for await(let n of this.dht.findPeer(e,t))if(n.name==="FINAL_PEER")return n.peer;throw(0,x0e.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){for await(let n of this.dht.getClosestPeers(e,t))n.name==="FINAL_PEER"&&(yield n.peer)}};var ax=C(ee(),1);var St={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_NOT_FOUND:"ERR_NOT_FOUND"};async function*GB(r,e){for await(let t of r)await e(t),yield t}var Er=ue("libp2p:peer-store:address-book"),sx="change:multiaddrs";async function bVe(){return!0}var cx=class{constructor(e,t,n){this.dispatchEvent=e,this.store=t,this.addressFilter=n??bVe}async consumePeerRecord(e){Er.trace("consumePeerRecord await write lock");let t=await this.store.lock.writeLock();Er.trace("consumePeerRecord got write lock");let n,i,o;try{let s;try{s=Mn.createFromProtobuf(e.payload)}catch{return Er.error("invalid peer record received"),!1}n=s.peerId;let a=s.multiaddrs;if(!n.equals(e.peerId))return Er("signing key does not match PeerId in the PeerRecord"),!1;if(a==null||a.length===0)return!1;if(await this.store.has(n)&&(i=await this.store.load(n),i.peerRecordEnvelope!=null)){let u=await Yn.createFromProtobuf(i.peerRecordEnvelope),l=Mn.createFromProtobuf(u.payload);if(l.seqNumber>=s.seqNumber)return Er("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,s.seqNumber),!1}let c=await jB(n,a,this.addressFilter,!0);o=await this.store.patchOrCreate(n,{addresses:c,peerRecordEnvelope:e.marshal().subarray()}),Er("stored provided peer record for %p",s.peerId)}finally{Er.trace("consumePeerRecord release write lock"),t()}return this.dispatchEvent(new ve(sx,{detail:{peerId:n,multiaddrs:o.addresses.map(({multiaddr:s})=>s),oldMultiaddrs:i==null?[]:i.addresses.map(({multiaddr:s})=>s)}})),!0}async getRawEnvelope(e){Er.trace("getRawEnvelope await read lock");let t=await this.store.lock.readLock();Er.trace("getRawEnvelope got read lock");try{return(await this.store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Er.trace("getRawEnvelope release read lock"),t()}}async getPeerRecord(e){let t=await this.getRawEnvelope(e);if(t!=null)return await Yn.createFromProtobuf(t)}async get(e){e=xn(e),Er.trace("get wait for read lock");let t=await this.store.lock.readLock();Er.trace("get got read lock");try{return(await this.store.load(e)).addresses}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Er.trace("get release read lock"),t()}return[]}async set(e,t){if(e=xn(e),!Array.isArray(t))throw Er.error("multiaddrs must be an array of Multiaddrs"),(0,ax.default)(new Error("multiaddrs must be an array of Multiaddrs"),St.ERR_INVALID_PARAMETERS);Er.trace("set await write lock");let n=await this.store.lock.writeLock();Er.trace("set got write lock");let i=!1,o,s;try{let a=await jB(e,t,this.addressFilter);if(a.length===0)return;try{if(o=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...o.addresses.map(({multiaddr:c})=>c.toString())]).size===o.addresses.length&&a.length===o.addresses.length)return}catch(c){if(c.code!==St.ERR_NOT_FOUND)throw c}s=await this.store.patchOrCreate(e,{addresses:a}),Er("set multiaddrs for %p",e)}finally{Er.trace("set multiaddrs for %p",e),Er("set release write lock"),n()}this.dispatchEvent(new ve(sx,{detail:{peerId:e,multiaddrs:s.addresses.map(a=>a.multiaddr),oldMultiaddrs:o==null?[]:o.addresses.map(({multiaddr:a})=>a)}})),i||this.dispatchEvent(new ve("peer",{detail:{id:e,multiaddrs:s.addresses.map(a=>a.multiaddr),protocols:s.protocols}}))}async add(e,t){if(e=xn(e),!Array.isArray(t))throw Er.error("multiaddrs must be an array of Multiaddrs"),(0,ax.default)(new Error("multiaddrs must be an array of Multiaddrs"),St.ERR_INVALID_PARAMETERS);Er.trace("add await write lock");let n=await this.store.lock.writeLock();Er.trace("add got write lock");let i,o,s;try{let a=await jB(e,t,this.addressFilter);if(a.length===0)return;try{if(o=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...o.addresses.map(({multiaddr:c})=>c.toString())]).size===o.addresses.length)return}catch(c){if(c.code!==St.ERR_NOT_FOUND)throw c}s=await this.store.mergeOrCreate(e,{addresses:a}),Er("added multiaddrs for %p",e)}finally{Er.trace("set release write lock"),n()}this.dispatchEvent(new ve(sx,{detail:{peerId:e,multiaddrs:s.addresses.map(a=>a.multiaddr),oldMultiaddrs:o==null?[]:o.addresses.map(({multiaddr:a})=>a)}})),i===!0&&this.dispatchEvent(new ve("peer",{detail:{id:e,multiaddrs:s.addresses.map(a=>a.multiaddr),protocols:s.protocols}}))}async delete(e){e=xn(e),Er.trace("delete await write lock");let t=await this.store.lock.writeLock();Er.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{addresses:[]})}finally{Er.trace("delete release write lock"),t()}n!=null&&this.dispatchEvent(new ve(sx,{detail:{peerId:e,multiaddrs:[],oldMultiaddrs:n==null?[]:n.addresses.map(({multiaddr:i})=>i)}}))}};async function jB(r,e,t,n=!1){return await Ne(e,i=>GB(i,o=>{if(!as(o))throw Er.error("multiaddr must be an instance of Multiaddr"),(0,ax.default)(new Error("multiaddr must be an instance of Multiaddr"),St.ERR_INVALID_PARAMETERS)}),i=>Yt(i,async o=>await t(r,o)),i=>Bi(i,o=>({multiaddr:o,isCertified:n})),async i=>await Wo(i))}var A0e=C(ee(),1);var _u=ue("libp2p:peer-store:key-book"),S0e="change:pubkey",ux=class{constructor(e,t){this.dispatchEvent=e,this.store=t}async set(e,t){if(e=xn(e),!(t instanceof Uint8Array))throw _u.error("publicKey must be an instance of Uint8Array to store data"),(0,A0e.default)(new Error("publicKey must be an instance of PublicKey"),St.ERR_INVALID_PARAMETERS);_u.trace("set await write lock");let n=await this.store.lock.writeLock();_u.trace("set got write lock");let i=!1,o;try{try{if(o=await this.store.load(e),o.pubKey!=null&&rr(o.pubKey,t))return}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}await this.store.patchOrCreate(e,{pubKey:t}),i=!0}finally{_u.trace("set release write lock"),n()}i&&this.dispatchEvent(new ve(S0e,{detail:{peerId:e,publicKey:t,oldPublicKey:o==null?void 0:o.pubKey}}))}async get(e){e=xn(e),_u.trace("get await write lock");let t=await this.store.lock.readLock();_u.trace("get got write lock");try{return(await this.store.load(e)).pubKey}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{_u("get release write lock"),t()}}async delete(e){e=xn(e),_u.trace("delete await write lock");let t=await this.store.lock.writeLock();_u.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{pubKey:void 0})}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}finally{_u.trace("delete release write lock"),t()}this.dispatchEvent(new ve(S0e,{detail:{peerId:e,publicKey:void 0,oldPublicKey:n==null?void 0:n.pubKey}}))}};var WB=C(ee(),1);var Un=ue("libp2p:peer-store:metadata-book"),lx="change:metadata",fx=class{constructor(e,t){this.dispatchEvent=e,this.store=t}async get(e){e=xn(e),Un.trace("get await read lock");let t=await this.store.lock.readLock();Un.trace("get got read lock");try{return(await this.store.load(e)).metadata}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Un.trace("get release read lock"),t()}return new Map}async getValue(e,t){e=xn(e),Un.trace("getValue await read lock");let n=await this.store.lock.readLock();Un.trace("getValue got read lock");try{return(await this.store.load(e)).metadata.get(t)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}finally{Un.trace("getValue release write lock"),n()}}async set(e,t){if(e=xn(e),!(t instanceof Map))throw Un.error("valid metadata must be provided to store data"),(0,WB.default)(new Error("valid metadata must be provided"),St.ERR_INVALID_PARAMETERS);Un.trace("set await write lock");let n=await this.store.lock.writeLock();Un.trace("set got write lock");let i;try{try{i=await this.store.load(e)}catch(o){if(o.code!==St.ERR_NOT_FOUND)throw o}await this.store.mergeOrCreate(e,{metadata:t})}finally{Un.trace("set release write lock"),n()}this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:t,oldMetadata:i==null?new Map:i.metadata}}))}async setValue(e,t,n){if(e=xn(e),typeof t!="string"||!(n instanceof Uint8Array))throw Un.error("valid key and value must be provided to store data"),(0,WB.default)(new Error("valid key and value must be provided"),St.ERR_INVALID_PARAMETERS);Un.trace("setValue await write lock");let i=await this.store.lock.writeLock();Un.trace("setValue got write lock");let o,s;try{try{o=await this.store.load(e);let a=o.metadata.get(t);if(a!=null&&rr(n,a))return}catch(a){if(a.code!==St.ERR_NOT_FOUND)throw a}s=await this.store.mergeOrCreate(e,{metadata:new Map([[t,n]])})}finally{Un.trace("setValue release write lock"),i()}this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:s.metadata,oldMetadata:o==null?new Map:o.metadata}}))}async delete(e){e=xn(e),Un.trace("delete await write lock");let t=await this.store.lock.writeLock();Un.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}n!=null&&await this.store.patch(e,{metadata:new Map})}finally{Un.trace("delete release write lock"),t()}n!=null&&this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:new Map,oldMetadata:n.metadata}}))}async deleteValue(e,t){e=xn(e),Un.trace("deleteValue await write lock");let n=await this.store.lock.writeLock();Un.trace("deleteValue got write lock");let i,o;try{o=await this.store.load(e),i=o.metadata,i.delete(t),await this.store.patch(e,{metadata:i})}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}finally{Un.trace("deleteValue release write lock"),n()}i!=null&&this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:i,oldMetadata:o==null?new Map:o.metadata}}))}};var hx=C(ee(),1);var Fn=ue("libp2p:peer-store:proto-book"),dx="change:protocols",px=class{constructor(e,t){this.dispatchEvent=e,this.store=t}async get(e){Fn.trace("get wait for read lock");let t=await this.store.lock.readLock();Fn.trace("get got read lock");try{return(await this.store.load(e)).protocols}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Fn.trace("get release read lock"),t()}return[]}async set(e,t){if(e=xn(e),!Array.isArray(t))throw Fn.error("protocols must be provided to store data"),(0,hx.default)(new Error("protocols must be provided"),St.ERR_INVALID_PARAMETERS);Fn.trace("set await write lock");let n=await this.store.lock.writeLock();Fn.trace("set got write lock");let i,o;try{try{if(i=await this.store.load(e),new Set([...t]).size===i.protocols.length)return}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}o=await this.store.patchOrCreate(e,{protocols:t}),Fn("stored provided protocols for %p",e)}finally{Fn.trace("set release write lock"),n()}this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:o.protocols,oldProtocols:i==null?[]:i.protocols}}))}async add(e,t){if(e=xn(e),!Array.isArray(t))throw Fn.error("protocols must be provided to store data"),(0,hx.default)(new Error("protocols must be provided"),St.ERR_INVALID_PARAMETERS);Fn.trace("add await write lock");let n=await this.store.lock.writeLock();Fn.trace("add got write lock");let i,o;try{try{if(i=await this.store.load(e),new Set([...i.protocols,...t]).size===i.protocols.length)return}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}o=await this.store.mergeOrCreate(e,{protocols:t}),Fn("added provided protocols for %p",e)}finally{Fn.trace("add release write lock"),n()}this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:o.protocols,oldProtocols:i==null?[]:i.protocols}}))}async remove(e,t){if(e=xn(e),!Array.isArray(t))throw Fn.error("protocols must be provided to store data"),(0,hx.default)(new Error("protocols must be provided"),St.ERR_INVALID_PARAMETERS);Fn.trace("remove await write lock");let n=await this.store.lock.writeLock();Fn.trace("remove got write lock");let i,o;try{try{i=await this.store.load(e);let s=new Set(i.protocols);for(let a of t)s.delete(a);if(i.protocols.length===s.size)return;t=Array.from(s)}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}o=await this.store.patchOrCreate(e,{protocols:t})}finally{Fn.trace("remove release write lock"),n()}this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:o.protocols,oldProtocols:i==null?[]:i.protocols}}))}async delete(e){e=xn(e),Fn.trace("delete await write lock");let t=await this.store.lock.writeLock();Fn.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{protocols:[]})}finally{Fn.trace("delete release write lock"),t()}n!=null&&this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:[],oldProtocols:n.protocols}}))}};var YB=C(ee(),1);var k4;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.addresses!=null)for(let o of t.addresses)n.uint32(10),mx.codec().encode(o,n,{writeDefaults:!0});if(t.protocols!=null)for(let o of t.protocols)n.uint32(18),n.string(o);if(t.metadata!=null)for(let o of t.metadata)n.uint32(26),gx.codec().encode(o,n,{writeDefaults:!0});t.pubKey!=null&&(n.uint32(34),n.bytes(t.pubKey)),t.peerRecordEnvelope!=null&&(n.uint32(42),n.bytes(t.peerRecordEnvelope)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={addresses:[],protocols:[],metadata:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.addresses.push(mx.codec().decode(t,t.uint32()));break;case 2:i.protocols.push(t.string());break;case 3:i.metadata.push(gx.codec().decode(t,t.uint32()));break;case 4:i.pubKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(k4||(k4={}));var mx;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.multiaddr!=null&&t.multiaddr.byteLength>0)&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={multiaddr:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(mx||(mx={}));var gx;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.key!=="")&&(n.uint32(10),n.string(t.key)),(i.writeDefaults===!0||t.value!=null&&t.value.byteLength>0)&&(n.uint32(18),n.bytes(t.value)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={key:"",value:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.string();break;case 2:i.value=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(gx||(gx={}));var T0e=ue("libp2p:peer-store:store"),I0e="/peers/",yx=class{constructor(e){this.components=e,this.lock=e5({name:"peer-store",singleProcess:!0})}_peerIdToDatastoreKey(e){if(e.type==null)throw T0e.error("peerId must be an instance of peer-id to store data"),(0,YB.default)(new Error("peerId must be an instance of peer-id"),St.ERR_INVALID_PARAMETERS);let t=e.toCID().toString();return new pe(`${I0e}${t}`)}async has(e){return await this.components.datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this.components.datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let t=await this.components.datastore.get(this._peerIdToDatastoreKey(e)),n=k4.decode(t),i=new Map;for(let o of n.metadata)i.set(o.key,o.value);return{...n,id:e,addresses:n.addresses.map(({multiaddr:o,isCertified:s})=>({multiaddr:lt(o),isCertified:s??!1})),metadata:i,pubKey:n.pubKey??void 0,peerRecordEnvelope:n.peerRecordEnvelope??void 0}}async save(e){if(e.pubKey!=null&&e.id.publicKey!=null&&!rr(e.pubKey,e.id.publicKey))throw T0e.error("peer publicKey bytes do not match peer id publicKey bytes"),(0,YB.default)(new Error("publicKey bytes do not match peer id publicKey bytes"),St.ERR_INVALID_PARAMETERS);let t=new Set,n=e.addresses.filter(s=>t.has(s.multiaddr.toString())?!1:(t.add(s.multiaddr.toString()),!0)).sort((s,a)=>s.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({multiaddr:s,isCertified:a})=>({multiaddr:s.bytes,isCertified:a})),i=[];[...e.metadata.keys()].sort().forEach(s=>{let a=e.metadata.get(s);a!=null&&i.push({key:s,value:a})});let o=k4.encode({addresses:n,protocols:e.protocols.sort(),pubKey:e.pubKey,metadata:i,peerRecordEnvelope:e.peerRecordEnvelope});return await this.components.datastore.put(this._peerIdToDatastoreKey(e.id),o.subarray()),await this.load(e.id)}async patch(e,t){let n=await this.load(e);return await this._patch(e,t,n)}async patchOrCreate(e,t){let n;try{n=await this.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,t,n)}async _patch(e,t,n){return await this.save({...n,...t,id:e})}async merge(e,t){let n=await this.load(e);return await this._merge(e,t,n)}async mergeOrCreate(e,t){let n;try{n=await this.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,t,n)}async _merge(e,t,n){var o,s;let i=new Map;return n.addresses.forEach(a=>{i.set(a.multiaddr.toString(),a.isCertified)}),(t.addresses??[]).forEach(a=>{let c=a.multiaddr.toString(),l=!!i.get(c)||a.isCertified;i.set(c,l)}),await this.save({id:e,addresses:Array.from(i.entries()).map(([a,c])=>({multiaddr:lt(a),isCertified:c})),protocols:Array.from(new Set([...n.protocols??[],...t.protocols??[]])),metadata:new Map([...((o=n.metadata)==null?void 0:o.entries())??[],...((s=t.metadata)==null?void 0:s.entries())??[]]),pubKey:t.pubKey??(n!=null?n.pubKey:void 0),peerRecordEnvelope:t.peerRecordEnvelope??(n!=null?n.peerRecordEnvelope:void 0)})}async*all(){for await(let e of this.components.datastore.queryKeys({prefix:I0e})){let t=e.toString().split("/")[2],n=Ot.decode(t);yield this.load(Wd(n))}}};var QB=C(ee(),1);var $l;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.tags!=null)for(let o of t.tags)n.uint32(10),wx.codec().encode(o,n,{writeDefaults:!0});i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={tags:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.tags.push(wx.codec().decode(t,t.uint32()));break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})($l||($l={}));var wx;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.name!=="")&&(n.uint32(10),n.string(t.name)),t.value!=null&&(n.uint32(16),n.uint32(t.value)),t.expiry!=null&&(n.uint32(24),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={name:""},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.name=t.string();break;case 2:i.value=t.uint32();break;case 3:i.expiry=t.uint64();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(wx||(wx={}));var ha=ue("libp2p:peer-store"),bx=class extends Zt{constructor(e,t={}){super(),this.components=e,this.store=new yx(e),this.addressBook=new cx(this.dispatchEvent.bind(this),this.store,t.addressFilter),this.keyBook=new ux(this.dispatchEvent.bind(this),this.store),this.metadataBook=new fx(this.dispatchEvent.bind(this),this.store),this.protoBook=new px(this.dispatchEvent.bind(this),this.store)}async forEach(e){ha.trace("getPeers await read lock");let t=await this.store.lock.readLock();ha.trace("getPeers got read lock");try{for await(let n of this.store.all())n.id.equals(this.components.peerId)||e(n)}finally{ha.trace("getPeers release read lock"),t()}}async all(){let e=[];return await this.forEach(t=>{e.push(t)}),e}async delete(e){ha.trace("delete await write lock");let t=await this.store.lock.writeLock();ha.trace("delete got write lock");try{await this.store.delete(e)}finally{ha.trace("delete release write lock"),t()}}async get(e){ha.trace("get await read lock");let t=await this.store.lock.readLock();ha.trace("get got read lock");try{return await this.store.load(e)}finally{ha.trace("get release read lock"),t()}}async has(e){ha.trace("has await read lock");let t=await this.store.lock.readLock();ha.trace("has got read lock");try{return await this.store.has(e)}finally{ha.trace("has release read lock"),t()}}async tagPeer(e,t,n={}){let i=n.value??0,o=Math.round(i),s=n.ttl??void 0;if(o!==i||o<0||o>100)throw(0,QB.default)(new Error("Tag value must be between 0-100"),"ERR_TAG_VALUE_OUT_OF_BOUNDS");let a=await this.metadataBook.getValue(e,"tags"),c=[];a!=null&&(c=$l.decode(a).tags);for(let u of c)if(u.name===t)throw(0,QB.default)(new Error("Peer already tagged"),"ERR_DUPLICATE_TAG");c.push({name:t,value:o,expiry:s==null?void 0:BigInt(Date.now()+s)}),await this.metadataBook.setValue(e,"tags",$l.encode({tags:c}).subarray())}async unTagPeer(e,t){let n=await this.metadataBook.getValue(e,"tags"),i=[];n!=null&&(i=$l.decode(n).tags),i=i.filter(o=>o.name!==t),await this.metadataBook.setValue(e,"tags",$l.encode({tags:i}).subarray())}async getTags(e){let t=await this.metadataBook.getValue(e,"tags"),n=[];t!=null&&(n=$l.decode(t).tags);let i=BigInt(Date.now()),o=n.filter(s=>s.expiry==null||s.expiry>i);return o.length!==n.length&&await this.metadataBook.setValue(e,"tags",$l.encode({tags:o}).subarray()),o.map(s=>({name:s.name,value:s.value??0}))}};var R0e=C(ee(),1),_x=class{constructor(e){this.dht=e}async provide(e){await on(this.dht.provide(e))}async*findProviders(e,t={}){for await(let n of this.dht.findProviders(e,t))n.name==="PROVIDER"&&(yield*n.providers)}async put(e,t,n){await on(this.dht.put(e,t,n))}async get(e,t){for await(let n of this.dht.get(e,t))if(n.name==="VALUE")return n.value;throw(0,R0e.default)(new Error("Not found"),"ERR_NOT_FOUND")}};var _s=C(ee(),1);var Ex=class{constructor(e={}){this._started=!1,this._peerId=e.peerId,this._addressManager=e.addressManager,this._peerStore=e.peerStore,this._upgrader=e.upgrader,this._metrics=e.metrics,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._connectionGater=e.connectionGater,this._contentRouting=e.contentRouting,this._peerRouting=e.peerRouting,this._datastore=e.datastore,this._connectionProtector=e.connectionProtector,this._dht=e.dht,this._pubsub=e.pubsub,this._dialer=e.dialer}isStarted(){return this._started}async beforeStart(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.beforeStart!=null&&await e.beforeStart()}))}async start(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{await e.start()})),this._started=!0}async afterStart(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async beforeStop(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.beforeStop!=null&&await e.beforeStop()}))}async stop(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{await e.stop()})),this._started=!1}async afterStop(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.afterStop!=null&&await e.afterStop()}))}get peerId(){if(this._peerId==null)throw(0,_s.default)(new Error("peerId not set"),"ERR_SERVICE_MISSING");return this._peerId}set peerId(e){this._peerId=e}get addressManager(){if(this._addressManager==null)throw(0,_s.default)(new Error("addressManager not set"),"ERR_SERVICE_MISSING");return this._addressManager}set addressManager(e){this._addressManager=e}get peerStore(){if(this._peerStore==null)throw(0,_s.default)(new Error("peerStore not set"),"ERR_SERVICE_MISSING");return this._peerStore}set peerStore(e){this._peerStore=e}get upgrader(){if(this._upgrader==null)throw(0,_s.default)(new Error("upgrader not set"),"ERR_SERVICE_MISSING");return this._upgrader}set upgrader(e){this._upgrader=e}get registrar(){if(this._registrar==null)throw(0,_s.default)(new Error("registrar not set"),"ERR_SERVICE_MISSING");return this._registrar}set registrar(e){this._registrar=e}get connectionManager(){if(this._connectionManager==null)throw(0,_s.default)(new Error("connectionManager not set"),"ERR_SERVICE_MISSING");return this._connectionManager}set connectionManager(e){this._connectionManager=e}get transportManager(){if(this._transportManager==null)throw(0,_s.default)(new Error("transportManager not set"),"ERR_SERVICE_MISSING");return this._transportManager}set transportManager(e){this._transportManager=e}get connectionGater(){if(this._connectionGater==null)throw(0,_s.default)(new Error("connectionGater not set"),"ERR_SERVICE_MISSING");return this._connectionGater}set connectionGater(e){this._connectionGater=e}get contentRouting(){if(this._contentRouting==null)throw(0,_s.default)(new Error("contentRouting not set"),"ERR_SERVICE_MISSING");return this._contentRouting}set contentRouting(e){this._contentRouting=e}get peerRouting(){if(this._peerRouting==null)throw(0,_s.default)(new Error("peerRouting not set"),"ERR_SERVICE_MISSING");return this._peerRouting}set peerRouting(e){this._peerRouting=e}get datastore(){if(this._datastore==null)throw(0,_s.default)(new Error("datastore not set"),"ERR_SERVICE_MISSING");return this._datastore}set datastore(e){this._datastore=e}get connectionProtector(){return this._connectionProtector}set connectionProtector(e){this._connectionProtector=e}get dialer(){if(this._dialer==null)throw(0,_s.default)(new Error("dialer not set"),"ERR_SERVICE_MISSING");return this._dialer}set dialer(e){this._dialer=e}get metrics(){return this._metrics}set metrics(e){this._metrics=e}get dht(){return this._dht}set dht(e){this._dht=e}get pubsub(){return this._pubsub}set pubsub(e){this._pubsub=e}};var ZB=C($s(),1),JB=C(k0e(),1);var N0e=globalThis.fetch,D0e=globalThis.Headers,cXt=globalThis.Request,uXt=globalThis.Response;function vx(r,e,t){return`${r}?name=${e}&type=${t}`}async function O0e(r,e){return await(await N0e(r,{headers:new D0e({accept:"application/dns-json"}),signal:e})).json()}function I0(r,e){return`${e}_${r}`}var XB=Object.assign((0,ZB.default)("dns-over-http-resolver"),{error:(0,ZB.default)("dns-over-http-resolver:error")}),eM=class{constructor(e={}){this._cache=new JB.default({max:(e==null?void 0:e.maxCache)??100}),this._TXTcache=new JB.default({max:(e==null?void 0:e.maxCache)??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??O0e,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*t),i=e[t];e[t]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(I0(e,t));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(vx(o,e,t),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(I0(e,t),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),XB.error(`${o} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){let t="AAAA",n=this._cache.get(I0(e,t));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(vx(o,e,t),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(I0(e,t),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),XB.error(`${o} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){let t="TXT",n=this._TXTcache.get(I0(e,t));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(vx(o,e,t),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(I0(e,t),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),XB.error(`${o} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},L0e=eM;var B0e=L0e;var{code:SVe}=hr("dnsaddr");async function M0e(r,e={}){let t=new B0e;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,i]=r.stringTuples().find(([a])=>a===SVe)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await t.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var xx=C(ee(),1);var CVe={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{maxConnections:300,minConnections:50,autoDial:!0,autoDialInterval:1e4,maxParallelDials:100,maxDialsPerPeer:4,dialTimeout:3e4,inboundUpgradeTimeout:3e4,resolvers:{dnsaddr:M0e},addressSorter:ig},connectionGater:{},transportManager:{faultTolerance:Qd.FATAL_ALL},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},nat:{enabled:!0,ttl:7200,keepAlive:!0},relay:{enabled:!0,advertise:{bootDelay:9e5,enabled:!1,ttl:18e5},hop:{enabled:!1,active:!1,timeout:3e4},autoRelay:{enabled:!1,maxListeners:2}},identify:{protocolPrefix:"ipfs",host:{agentVersion:KB},timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1},ping:{protocolPrefix:"ipfs",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4},fetch:{protocolPrefix:"libp2p",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4}};function U0e(r){var t,n;let e=et(CVe,r);if(e.transports==null||e.transports.length<1)throw(0,xx.default)(new Error(Rt.ERR_TRANSPORTS_REQUIRED),q.ERR_TRANSPORTS_REQUIRED);if(e.connectionEncryption==null||e.connectionEncryption.length===0)throw(0,xx.default)(new Error(Rt.CONN_ENCRYPTION_REQUIRED),q.CONN_ENCRYPTION_REQUIRED);if(e.connectionProtector===null&&((n=(t=globalThis.process)==null?void 0:t.env)==null?void 0:n.LIBP2P_FORCE_PNET)!=null)throw(0,xx.default)(new Error(Rt.ERR_PROTECTOR_REQUIRED),q.ERR_PROTECTOR_REQUIRED);return e.identify.host.agentVersion===KB&&(w0e||g0e?e.identify.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(T0||rx||y0e||b0e)&&(e.identify.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`)),e}var iM;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.id!=null&&t.id.byteLength>0)&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(iM||(iM={}));var F0e=async()=>{let r=await H9("Ed25519"),e=await PVe(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function PVe(r){return await Yd(Ppe(r.public),kpe(r))}var D4=C(ee(),1);var pa=C(ee(),1);var Sx=class extends Zt{get[a9](){return!0}get[Symbol.toStringTag](){return"@libp2p/dummy-dht"}get wan(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}get lan(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}get(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}findProviders(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}findPeer(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}getClosestPeers(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}provide(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}put(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}async getMode(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}async setMode(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}async refreshRoutingTable(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}};var ql=C(ee(),1);var Ax=class extends Zt{constructor(){super(...arguments),this.topicValidators=new Map}isStarted(){return!1}start(){}stop(){}get globalSignaturePolicy(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}get multicodecs(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}getPeers(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}getTopics(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}subscribe(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}unsubscribe(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}getSubscribers(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}async publish(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}};var yg=C(ee(),1);var t1e=C(Kn(),1),sM=C(Da(),1),r1e=C(xi(),1);var N4=C(ee(),1),Z0e=C(Da(),1),J0e=C(Q0e(),1),oM=C(xi(),1);var X0e=ue("libp2p:dialer:dial-request"),Tx=class{constructor(e){let{addrs:t,dialAction:n,dialer:i}=e;this.addrs=t,this.dialer=i,this.dialAction=n}async run(e={}){var a;let t=this.dialer.getTokens(this.addrs.length);if(t.length<1)throw(0,N4.default)(new Error("No dial tokens available"),q.ERR_NO_DIAL_TOKENS);let n=new J0e.default;for(let c of t)n.push(c).catch(u=>{X0e.error(u)});let i=this.addrs.map(()=>{var u;let c=new AbortController;try{(u=oM.setMaxListeners)==null||u(1/0,c.signal)}catch{}return c});if(e.signal!=null)try{(a=oM.setMaxListeners)==null||a(1/0,e.signal)}catch{}let o=0,s=!1;try{return await Promise.any(this.addrs.map(async(c,u)=>{let l=await n.shift();if(s)throw this.dialer.releaseToken(t.splice(t.indexOf(l),1)[0]),(0,N4.default)(new Error("dialAction already succeeded"),q.ERR_ALREADY_SUCCEEDED);let f=i[u];if(f==null)throw(0,N4.default)(new Error("dialAction did not come with an AbortController"),q.ERR_INVALID_PARAMETERS);let h;try{let d=f.signal;h=await this.dialAction(c,{...e,signal:e.signal!=null?(0,Z0e.anySignal)([d,e.signal]):d}),i[u]=void 0}finally{o++,this.addrs.length-o>=t.length?n.push(l).catch(d=>{X0e.error(d)}):this.dialer.releaseToken(t.splice(t.indexOf(l),1)[0])}if(h==null)throw(0,N4.default)(new Error("dialAction led to empty object"),q.ERR_TRANSPORT_DIAL_FAILED);return s=!0,h}))}finally{i.forEach(c=>{c!==void 0&&c.abort()}),t.forEach(c=>this.dialer.releaseToken(c))}}};var Eu=ue("libp2p:dialer"),Ix=class{constructor(e,t={}){this.started=!1,this.addressSorter=t.addressSorter??ig,this.maxAddrsToDial=t.maxAddrsToDial??25,this.timeout=t.dialTimeout??3e4,this.maxDialsPerPeer=t.maxDialsPerPeer??4,this.tokens=[...new Array(t.maxParallelDials??100)].map((n,i)=>i),this.components=e,this.pendingDials=bs({name:"libp2p_dialler_pending_dials",metrics:e.metrics}),this.pendingDialTargets=bs({name:"libp2p_dialler_pending_dial_targets",metrics:e.metrics});for(let[n,i]of Object.entries(t.resolvers??{}))iD.set(n,i)}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1;for(let e of this.pendingDials.values())try{e.controller.abort()}catch(t){Eu.error(t)}this.pendingDials.clear();for(let e of this.pendingDialTargets.values())e.abort();this.pendingDialTargets.clear()}async dial(e,t={}){let{peerId:n,multiaddr:i}=_9(e);if(n!=null){if(this.components.peerId.equals(n))throw(0,yg.default)(new Error("Tried to dial self"),q.ERR_DIALED_SELF);if(i!=null&&(Eu("storing multiaddrs %p",n,i),await this.components.peerStore.addressBook.add(n,[i])),await this.components.connectionGater.denyDialPeer(n))throw(0,yg.default)(new Error("The dial request is blocked by gater.allowDialPeer"),q.ERR_PEER_DIAL_INTERCEPTED)}Eu("creating dial target for %p",n);let o=new AbortController,s=e1e();this.pendingDialTargets.set(s,o);let a=o.signal;t.signal!=null&&(a=(0,sM.anySignal)([a,t.signal]));let c;try{c=await this._createDialTarget({peerId:n,multiaddr:i},{...t,signal:a})}finally{this.pendingDialTargets.delete(s)}if(c.addrs.length===0)throw(0,yg.default)(new Error("The dial request has no valid addresses"),q.ERR_NO_VALID_ADDRESSES);let u=this.pendingDials.get(c.id)??this._createPendingDial(c,t);try{let l=await u.promise;return Eu("dial succeeded to %s",c.id),l}catch(l){throw Eu("dial failed to %s",c.id,l),u.controller.signal.aborted&&(l.code=q.ERR_TIMEOUT),Eu.error(l),l}finally{u.destroy()}}async _createDialTarget(e,t){let n=[];if(as(e.multiaddr)&&n.push(e.multiaddr),!as(e.multiaddr)&&u0(e.peerId)&&n.push(...await this._loadAddresses(e.peerId)),n=(await Promise.all(n.map(async o=>await this._resolve(o,t)))).flat().filter(o=>!!this.components.transportManager.transportForMultiaddr(o)),n=[...new Set(n.map(o=>o.toString()))].map(o=>lt(o)),n.length>this.maxAddrsToDial)throw(0,yg.default)(new Error("dial with more addresses than allowed"),q.ERR_TOO_MANY_ADDRESSES);let i=u0(e.peerId)?e.peerId:void 0;if(i!=null){let o=`/p2p/${i.toString()}`;n=n.map(s=>{let a=s.getPeerId();return a==null||!i.equals(a)?s.encapsulate(o):s})}return{id:i==null?e1e():i.toString(),addrs:n}}async _loadAddresses(e){let t=await this.components.peerStore.addressBook.get(e);return(await Promise.all(t.map(async n=>await this.components.connectionGater.denyDialMultiaddr(e,n.multiaddr)?!1:n))).filter(DVe).sort(this.addressSorter).map(n=>n.multiaddr)}_createPendingDial(e,t={}){var u;let n=async(l,f={})=>{var h;if(((h=f.signal)==null?void 0:h.aborted)===!0)throw(0,yg.default)(new Error("already aborted"),q.ERR_ALREADY_ABORTED);return await this.components.transportManager.dial(l,f).catch(d=>{throw Eu.error("dial to %s failed",l,d),d})},i=new Tx({addrs:e.addrs,dialAction:n,dialer:this}),o=new t1e.TimeoutController(this.timeout),s=[o.signal];t.signal!=null&&s.push(t.signal);let a=(0,sM.anySignal)(s);try{(u=r1e.setMaxListeners)==null||u(1/0,a)}catch{}let c={dialRequest:i,controller:o,promise:i.run({...t,signal:a}),destroy:()=>{o.clear(),this.pendingDials.delete(e.id)}};return this.pendingDials.set(e.id,c),c}getTokens(e){let t=Math.min(e,this.maxDialsPerPeer,this.tokens.length),n=this.tokens.splice(0,t);return Eu("%d tokens request, returning %d, %d remaining",e,t,this.tokens.length),n}releaseToken(e){this.tokens.includes(e)||(Eu("token %d released",e),this.tokens.push(e))}async _resolve(e,t){if(!e.protoNames().includes("dnsaddr"))return[e];let i=await this._resolveRecord(e,t);return(await Promise.all(i.map(async a=>await this._resolve(a,t)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[])}async _resolveRecord(e,t){try{return e=lt(e.toString()),await e.resolve(t)}catch(n){return Eu.error(`multiaddr ${e.toString()} could not be resolved`,n),[]}}};function DVe(r){return!!r}function e1e(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Hl=ue("libp2p"),aM=class extends Zt{constructor(e){super(),this.started=!1,this.peerId=e.peerId;let t=this.components=new Ex({peerId:e.peerId,datastore:e.datastore??new A3,connectionGater:{denyDialPeer:async()=>await Promise.resolve(!1),denyDialMultiaddr:async()=>await Promise.resolve(!1),denyInboundConnection:async()=>await Promise.resolve(!1),denyOutboundConnection:async()=>await Promise.resolve(!1),denyInboundEncryptedConnection:async()=>await Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>await Promise.resolve(!1),denyInboundUpgradedConnection:async()=>await Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>await Promise.resolve(!1),filterMultiaddrForPeer:async()=>await Promise.resolve(!0),...e.connectionGater}});t.peerStore=new bx(t,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore}),this.services=[t],e.metrics!=null&&(this.metrics=this.components.metrics=this.configureComponent(e.metrics(this.components))),this.peerStore=this.components.peerStore,this.peerStore.addEventListener("peer",s=>{let{detail:a}=s;this.dispatchEvent(new ve("peer:discovery",{detail:a}))}),e.connectionProtector!=null&&(this.components.connectionProtector=e.connectionProtector(t)),this.components.upgrader=new X9(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(s=>this.configureComponent(s(this.components))),muxers:(e.streamMuxers??[]).map(s=>this.configureComponent(s(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.components.dialer=new Ix(this.components,e.connectionManager),this.connectionManager=this.components.connectionManager=new x9(this.components,e.connectionManager),this.components.connectionManager.addEventListener("peer:disconnect",s=>{this.dispatchEvent(new ve("peer:disconnect",{detail:s.detail}))}),this.components.connectionManager.addEventListener("peer:connect",s=>{this.dispatchEvent(new ve("peer:connect",{detail:s.detail}))}),this.registrar=this.components.registrar=new Q9(this.components),this.components.transportManager=new j9(this.components,e.transportManager),this.components.addressManager=new p9(this.components,e.addresses),this.configureComponent(new ix(this.components)),this.configureComponent(new S9(this.components,{enabled:e.connectionManager.autoDial,minConnections:e.connectionManager.minConnections,autoDialInterval:e.connectionManager.autoDialInterval}));let n=b0.generateOptions();this.keychain=this.configureComponent(new b0(this.components,{...n,...e.keychain})),this.services.push(new nx(this.components,e.nat)),e.transports.forEach(s=>{this.components.transportManager.add(this.configureComponent(s(this.components)))}),this.identifyService=new mg(this.components,{...e.identify}),this.configureComponent(this.identifyService),e.dht!=null?this.dht=this.components.dht=e.dht(this.components):this.dht=new Sx,e.pubsub!=null?this.pubsub=this.components.pubsub=e.pubsub(this.components):this.pubsub=new Ax;let i=(e.peerRouters??[]).map(s=>this.configureComponent(s(this.components)));e.dht!=null&&(i.push(this.configureComponent(new ox(this.dht))),this.dht.addEventListener("peer",s=>{this.onDiscoveryPeer(s)})),this.peerRouting=this.components.peerRouting=this.configureComponent(new f9(this.components,{...e.peerRouting,routers:i}));let o=(e.contentRouters??[]).map(s=>this.configureComponent(s(this.components)));e.dht!=null&&o.push(this.configureComponent(new _x(this.dht))),this.contentRouting=this.components.contentRouting=this.configureComponent(new h9(this.components,{routers:o})),e.relay.enabled&&(this.components.transportManager.add(this.configureComponent(new I9(this.components,e.relay))),this.configureComponent(new L9(this.components,{addressSorter:e.connectionManager.addressSorter,...e.relay}))),this.fetchService=this.configureComponent(new J9(this.components,{...e.fetch})),this.pingService=this.configureComponent(new ex(this.components,{...e.ping}));for(let s of e.peerDiscovery??[])this.configureComponent(s(this.components)).addEventListener("peer",c=>{this.onDiscoveryPeer(c)})}configureComponent(e){return Cl(e)&&this.services.push(e),e}async start(){if(!this.started){this.started=!0,Hl("libp2p is starting");try{await Promise.all(this.services.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(this.services.map(e=>e.start())),await Promise.all(this.services.map(async e=>{e.afterStart!=null&&await e.afterStart()})),Hl("libp2p has started")}catch(e){throw Hl.error("An error occurred starting libp2p",e),await this.stop(),e}}}async stop(){this.started&&(Hl("libp2p is stopping"),this.started=!1,await Promise.all(this.services.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(this.services.map(e=>e.stop())),await Promise.all(this.services.map(async e=>{e.afterStop!=null&&await e.afterStop()})),Hl("libp2p has stopped"))}isStarted(){return this.started}getConnections(e){return this.components.connectionManager.getConnections(e)}getPeers(){let e=new Nl;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return await this.components.connectionManager.openConnection(e,t)}async dialProtocol(e,t,n={}){if(t==null)throw(0,D4.default)(new Error("no protocols were provided to open a stream"),q.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw(0,D4.default)(new Error("no protocols were provided to open a stream"),q.ERR_INVALID_PROTOCOLS_FOR_STREAM);return await(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e){as(e)&&(e=xt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,t={}){if(Hl("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.pubKey!=null)return n.pubKey;if(this.dht==null)throw(0,D4.default)(new Error("Public key was not in the peer store and the DHT is not enabled"),q.ERR_NO_ROUTERS_AVAILABLE);let i=yr([fe("/pk/"),e.multihash.digest]);for await(let o of this.dht.get(i,t))if(o.name==="VALUE"){let s=g4(o.value);return await this.peerStore.keyBook.set(e,o.value),s.bytes}throw(0,D4.default)(new Error(`Node not responding with its public key: ${e.toString()}`),q.ERR_INVALID_RECORD)}async fetch(e,t,n={}){if(as(e)){let i=xt(e.getPeerId()??"");await this.components.peerStore.addressBook.add(i,[e]),e=i}return await this.fetchService.fetch(e,t,n)}async ping(e,t={}){if(as(e)){let n=xt(e.getPeerId()??"");await this.components.peerStore.addressBook.add(n,[e]),e=n}return await this.pingService.ping(e,t)}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return await this.registrar.register(e,t)}unregister(e){this.registrar.unregister(e)}onDiscoveryPeer(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){Hl.error(new Error(q.ERR_DISCOVERED_SELF));return}t.multiaddrs.length>0&&this.components.peerStore.addressBook.add(t.id,t.multiaddrs).catch(n=>Hl.error(n)),t.protocols.length>0&&this.components.peerStore.protoBook.set(t.id,t.protocols).catch(n=>Hl.error(n)),this.dispatchEvent(new ve("peer:discovery",{detail:t}))}};async function n1e(r){if(r.peerId==null){let e=r.datastore;if(e!=null)try{let t=new b0({datastore:e},{...b0.generateOptions(),...r.keychain??{}});r.peerId=await t.exportPeerId("self")}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}}return r.peerId==null&&(r.peerId=await F0e()),new aM(U0e(r))}async function i1e(r){let e=await n1e(r);return r.start!==!1&&await e.start(),e}var I1e=C(f1e(),1);var m1e=C(dB(),1);var g1e=C(h1e(),1),{isValid:zVe,parse:VVe}=g1e.default,KVe=["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"],$Ve=KVe.map(r=>new m1e.Netmask(r));function qVe(r){for(let e of $Ve)if(e.contains(r))return!0;return!1}function p1e(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}var y1e=r=>{if(zVe(r)){let e=VVe(r);if(e.kind()==="ipv4")return qVe(e.toNormalizedString());if(e.kind()==="ipv6")return p1e(r)}else if(xc(r)&&k9.v6().test(r))return p1e(r)};var dM=y1e;var w1e="/lan",b1e="/ipfs",_1e="/kad/1.0.0",E1e="/dht/record",hM="/dht/provider";var HVe=Ie("/pk/");function bg(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>{let[[t,n]]=e.stringTuples();if(t===53||t===54||t===55)return n!=="localhost";if(t!==4&&t!==6||n==null)return!1;let i=dM(n);return i==null?!0:!i})}}function _g(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>{let[[t,n]]=e.stringTuples();if(n==="localhost")return!0;if(t!==4&&t!==6||n==null)return!1;let i=dM(n);return i??!1})}}async function xu(r){return(await dt.digest(r)).digest}async function Es(r){return await xu(r.toBytes())}function Gl(r){return new pe(`${E1e}/${re(r,"base32")}`,!1)}function v1e(r){return rt([HVe,r.toBytes()])}function x1e(r){return re(r.subarray(0,4))==="/pk/"}function S1e(r){return Di(r.subarray(4))}function pM(r,e){let t=new Date;return new Yr(r,e,t).serialize()}function A1e(r,e=100){let t;return()=>{clearTimeout(t),t=setTimeout(()=>{r()},e)}}var R1e=C(Kn(),1);function jl(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var gM=class{constructor(e){B(this,"map");if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return jl(this.map.entries(),e=>[Oe(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,Oe(n),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 jl(this.map.keys(),e=>Oe(e))}values(){return this.map.values()}get size(){return this.map.size}};var ma=class{constructor(e){B(this,"set");if(this.set=new Set,e!=null)for(let 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 jl(this.set.entries(),e=>{let t=Oe(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Oe(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return jl(this.set.values(),e=>Oe(e))}intersection(e){let t=new ma;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new ma;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new ma;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Eg=class{constructor(e){B(this,"list");if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return jl(this.list.entries(),e=>Oe(e[1]))}concat(e){let t=new Eg(this);for(let n of e)t.push(n);return t}entries(){return jl(this.list.entries(),e=>[e[0],Oe(e[1])])}every(e){return this.list.every((t,n)=>e(Oe(t),n,this))}filter(e){let t=new Eg;return this.list.forEach((n,i)=>{let o=Oe(n);e(o,i,this)&&t.push(o)}),t}find(e){let t=this.list.find((n,i)=>e(Oe(n),i,this));if(t!=null)return Oe(t)}findIndex(e){return this.list.findIndex((t,n)=>e(Oe(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(Oe(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return Oe(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return Oe(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var GVe="kad-close",jVe=50,T1e=20,WVe=1e4,YVe=10,kx=class{constructor(e,t){let{kBucketSize:n,pingTimeout:i,lan:o,pingConcurrency:s,protocol:a,tagName:c,tagValue:u}=t;this.components=e,this.log=j(`libp2p:kad-dht:${o?"lan":"wan"}:routing-table`),this.kBucketSize=n??T1e,this.pingTimeout=i??WVe,this.pingConcurrency=s??YVe,this.lan=o,this.running=!1,this.protocol=a,this.tagName=c??GVe,this.tagValue=u??jVe;let l=()=>{var f,h;(f=this.metrics)==null||f.pingQueueSize.update(this.pingQueue.size),(h=this.metrics)==null||h.pingRunning.update(this.pingQueue.pending)};this.pingQueue=new qn({concurrency:this.pingConcurrency}),this.pingQueue.addListener("add",l),this.pingQueue.addListener("next",l),this._onPing=this._onPing.bind(this)}isStarted(){return this.running}async start(){this.running=!0,this.components.metrics!=null&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_routing_table_size`),pingQueueSize:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_ping_queue_size`),pingRunning:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_ping_running`)});let e=new I1e.default({localNodeId:await Es(this.components.peerId),numberOfNodesPerKBucket:this.kBucketSize,numberOfNodesToPing:1});this.kb=e,e.on("ping",this._onPing),this._tagPeers(e)}async stop(){this.running=!1,this.pingQueue.clear(),this.kb=void 0}_tagPeers(e){let t=new ma,n=A1e(()=>{let i=new ma(e.closest(e.localNodeId,T1e).map(a=>a.peer)),o=i.difference(t),s=t.difference(i);Promise.resolve().then(async()=>{for(let a of o)await this.components.peerStore.tagPeer(a,this.tagName,{value:this.tagValue});for(let a of s)await this.components.peerStore.unTagPeer(a,this.tagName)}).catch(a=>{this.log.error("Could not update peer tags",a)}),t=i});e.on("added",()=>{n()}),e.on("removed",()=>{n()})}_onPing(e,t){this.pingQueue.add(async()=>{if(!this.running)return;let n=0;try{await Promise.all(e.map(async i=>{var s;let o;try{o=new R1e.TimeoutController(this.pingTimeout);let a={signal:o.signal};this.log("pinging old contact %p",i.peer),(await(await this.components.connectionManager.openConnection(i.peer,a)).newStream(this.protocol,a)).close(),n++}catch(a){this.running&&this.kb!=null&&(this.log.error("could not ping peer %p",i.peer,a),this.log("evicting old contact after ping failed %p",i),this.kb.remove(i.id))}finally{o!=null&&o.clear(),(s=this.metrics)==null||s.routingTableSize.update(this.size)}})),this.running&&n{this.log.error("could not process k-bucket ping event",n)})}get size(){return this.kb==null?0:this.kb.count()}async find(e){let t=await Es(e),n=this.closestPeer(t);if(n!=null&&e.equals(n))return n}closestPeer(e){let t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e,t=this.kBucketSize){return this.kb==null?[]:this.kb.closest(e,t).map(i=>i.peer)}async add(e){var n;if(this.kb==null)throw new Error("RoutingTable is not started");let t=await Es(e);this.kb.add({id:t,peer:e}),this.log("added %p with kad id %b",e,t),(n=this.metrics)==null||n.routingTableSize.update(this.size)}async remove(e){var n;if(this.kb==null)throw new Error("RoutingTable is not started");let t=await Es(e);this.kb.remove(t),(n=this.metrics)==null||n.routingTableSize.update(this.size)}};function Wl(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=vf(r.length);for(let n=0;ni.toISOString()).join(", ")} ]`),Promise.all(n.map(async(i,o)=>{try{if(await this._refreshCommonPrefixLength(o,i,e),this._numPeersForCpl(t)===0){let s=Math.min(2*(o+1),n.length-1);for(let a=o+1;a{this.log.error(i)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),this.refreshTimeoutId.unref!=null&&this.refreshTimeoutId.unref()}).catch(i=>{this.log.error(i)})}async _refreshCommonPrefixLength(e,t,n){if(!n&&t.getTime()>Date.now()-this.refreshInterval){this.log("not running refresh for cpl %s as time since last refresh not above interval",e);return}let i=await this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);let o=new P1e.TimeoutController(this.refreshQueryTimeout);try{let s=await L4(this.peerRouting.getClosestPeers(i.toBytes(),{signal:o.signal}));this.log(`found ${s} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}finally{o.clear()}}_getTrackedCommonPrefixLengthsForRefresh(e){e>Nx&&(e=Nx);let t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}async _generateRandomPeerId(e){if(this.routingTable.kb==null)throw new Error("Routing table not started");let t=Mc(2),n=(t[1]<<8)+t[0],i=await this._makePeerId(this.routingTable.kb.localNodeId,n,e);return Di(i)}async _makePeerId(e,t,n){if(n>Nx)throw new Error(`Cannot generate peer ID for common prefix length greater than ${Nx}`);let s=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1)^32768>>n,a=65535<<16-(n+1),c=s&a|t&~a,u=C1e[c],l=new ArrayBuffer(34),f=new DataView(l,0,l.byteLength);return f.setUint8(0,dt.code),f.setUint8(1,32),f.setUint32(2,u,!1),new Uint8Array(f.buffer,f.byteOffset,f.byteLength)}_maxCommonPrefix(){let e=0;for(let t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(let n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(this.routingTable.kb!=null)for(let{id:e}of this.routingTable.kb.toIterable()){let t=Wl(this.routingTable.kb.localNodeId,e),n=0;for(let i of t)if(i===0)n++;else break;yield n}}};var k1e;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.key!=null&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&(n.uint32(18),n.bytes(t.value)),t.author!=null&&(n.uint32(26),n.bytes(t.author)),t.signature!=null&&(n.uint32(34),n.bytes(t.signature)),t.timeReceived!=null&&(n.uint32(42),n.string(t.timeReceived)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.bytes();break;case 2:i.value=t.bytes();break;case 3:i.author=t.bytes();break;case 4:i.signature=t.bytes();break;case 5:i.timeReceived=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(k1e||(k1e={}));var ih;(function(r){let e;(function(a){a.PUT_VALUE="PUT_VALUE",a.GET_VALUE="GET_VALUE",a.ADD_PROVIDER="ADD_PROVIDER",a.GET_PROVIDERS="GET_PROVIDERS",a.FIND_NODE="FIND_NODE",a.PING="PING"})(e=r.MessageType||(r.MessageType={}));let t;(function(a){a[a.PUT_VALUE=0]="PUT_VALUE",a[a.GET_VALUE=1]="GET_VALUE",a[a.ADD_PROVIDER=2]="ADD_PROVIDER",a[a.GET_PROVIDERS=3]="GET_PROVIDERS",a[a.FIND_NODE=4]="FIND_NODE",a[a.PING=5]="PING"})(t||(t={})),function(a){a.codec=()=>Y1(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(a){a.NOT_CONNECTED="NOT_CONNECTED",a.CONNECTED="CONNECTED",a.CAN_CONNECT="CAN_CONNECT",a.CANNOT_CONNECT="CANNOT_CONNECT"})(n=r.ConnectionType||(r.ConnectionType={}));let i;(function(a){a[a.NOT_CONNECTED=0]="NOT_CONNECTED",a[a.CONNECTED=1]="CONNECTED",a[a.CAN_CONNECT=2]="CAN_CONNECT",a[a.CANNOT_CONNECT=3]="CANNOT_CONNECT"})(i||(i={})),function(a){a.codec=()=>Y1(i)}(n=r.ConnectionType||(r.ConnectionType={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=kn((u,l,f={})=>{if(f.lengthDelimited!==!1&&l.fork(),u.id!=null&&(l.uint32(10),l.bytes(u.id)),u.addrs!=null)for(let h of u.addrs)l.uint32(18),l.bytes(h);u.connection!=null&&(l.uint32(24),r.ConnectionType.codec().encode(u.connection,l)),f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={addrs:[]},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.id=u.bytes();break;case 2:f.addrs.push(u.bytes());break;case 3:f.connection=r.ConnectionType.codec().decode(u);break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>Pn(u,a.codec()),a.decode=u=>Cn(u,a.codec())})(o=r.Peer||(r.Peer={}));let s;r.codec=()=>(s==null&&(s=kn((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.MessageType.codec().encode(a.type,c)),a.clusterLevelRaw!=null&&(c.uint32(80),c.int32(a.clusterLevelRaw)),a.key!=null&&(c.uint32(18),c.bytes(a.key)),a.record!=null&&(c.uint32(26),c.bytes(a.record)),a.closerPeers!=null)for(let l of a.closerPeers)c.uint32(66),r.Peer.codec().encode(l,c);if(a.providerPeers!=null)for(let l of a.providerPeers)c.uint32(74),r.Peer.codec().encode(l,c);u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={closerPeers:[],providerPeers:[]},l=c==null?a.len:a.pos+c;for(;a.pos>>3){case 1:u.type=r.MessageType.codec().decode(a);break;case 10:u.clusterLevelRaw=a.int32();break;case 2:u.key=a.bytes();break;case 3:u.record=a.bytes();break;case 8:u.closerPeers.push(r.Peer.codec().decode(a,a.uint32()));break;case 9:u.providerPeers.push(r.Peer.codec().decode(a,a.uint32()));break;default:a.skipType(f&7);break}}return u})),s),r.encode=a=>Pn(a,r.codec()),r.decode=a=>Cn(a,r.codec())})(ih||(ih={}));var Sn=ih.MessageType,ZVe=ih.ConnectionType,O1e=Object.keys(Sn),jr=class{constructor(e,t,n){if(!(t instanceof Uint8Array))throw new Error("Key must be a Uint8Array");this.type=e,this.key=t,this.clusterLevelRaw=n,this.closerPeers=[],this.providerPeers=[],this.record=void 0}get clusterLevel(){let e=this.clusterLevelRaw-1;return e<0?0:e}set clusterLevel(e){this.clusterLevelRaw=e}serialize(){return ih.encode({key:this.key,type:this.type,clusterLevelRaw:this.clusterLevelRaw,closerPeers:this.closerPeers.map(N1e),providerPeers:this.providerPeers.map(N1e),record:this.record==null?void 0:this.record.serialize().subarray()})}static deserialize(e){var i;let t=ih.decode(e),n=new jr(t.type??ih.MessageType.PUT_VALUE,t.key??Uint8Array.from([]),t.clusterLevelRaw??0);return n.closerPeers=t.closerPeers.map(D1e),n.providerPeers=t.providerPeers.map(D1e),((i=t.record)==null?void 0:i.length)!=null&&(n.record=Yr.deserialize(t.record)),n}};function N1e(r){return{id:r.id.toBytes(),addrs:(r.multiaddrs??[]).map(t=>t.bytes),connection:ZVe.CONNECTED}}function D1e(r){if(r.id==null)throw new Error("Invalid peer in message");return{id:Di(r.id),multiaddrs:(r.addrs??[]).map(e=>yt(e)),protocols:[]}}function yM(r){return{...r,name:"SENDING_QUERY",type:0,messageName:r.type,messageType:O1e.indexOf(r.type.toString())}}function B4(r){return{...r,name:"PEER_RESPONSE",type:1,messageName:r.messageType,closer:r.closer!=null?r.closer:[],providers:r.providers!=null?r.providers:[]}}function M4(r){return{...r,name:"FINAL_PEER",type:2}}function lo(r){return{...r,name:"QUERY_ERROR",type:3}}function wM(r){return{...r,name:"PROVIDER",type:4}}function U4(r){return{...r,name:"VALUE",type:5}}function bM(r){return{...r,name:"DIALING_PEER",type:7}}var Ox=class extends Ki{constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=j(`libp2p:kad-dht:${i?"lan":"wan"}:network`),this.running=!1,this.protocol=n}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield bM({peer:e}),yield yM({to:e,type:t.type});let i;try{let s=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n),a=await this._writeReadMessage(s,t.serialize(),n);yield B4({from:e,messageType:a.type,closer:a.closerPeers,providers:a.providerPeers,record:a.record})}catch(o){yield lo({from:e,error:o})}finally{i!=null&&i.close()}}async*sendMessage(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield bM({peer:e}),yield yM({to:e,type:t.type});let i;try{let s=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n);await this._writeMessage(s,t.serialize(),n),yield B4({from:e,messageType:t.type})}catch(o){yield lo({from:e,error:o})}finally{i!=null&&i.close()}}async _writeMessage(e,t,n){n.signal!=null&&(e=nL(e,n.signal)),await Ne([t],vn(),e,sl)}async _writeReadMessage(e,t,n){n.signal!=null&&(e=nL(e,n.signal));let i=await Ne([t],vn(),e,Xr(),async s=>{let a=await mp(s);if(a!=null)return a;throw new J("No message received","ERR_NO_MESSAGE_RECEIVED")}),o=jr.deserialize(i);return o.closerPeers.forEach(s=>{this.dispatchEvent(new cn("peer",{detail:s}))}),o.providerPeers.forEach(s=>{this.dispatchEvent(new cn("peer",{detail:s}))}),o}};async function vg(r,e){let t=e.key,i=re(t).split("/");if(i.length<3)return;let o=r[i[1].toString()];if(o==null){let s="Invalid record keytype";throw new J(s,"ERR_INVALID_RECORD_KEY_TYPE")}await o(t,e.value)}var JVe=async(r,e)=>{if(!(r instanceof Uint8Array))throw new J('"key" must be a Uint8Array',"ERR_INVALID_RECORD_KEY_NOT_BUFFER");if(r.byteLength<5)throw new J("invalid public key record","ERR_INVALID_RECORD_KEY_TOO_SHORT");if(re(r.subarray(0,4))!=="/pk/")throw new J("key was not prefixed with /pk/","ERR_INVALID_RECORD_KEY_BAD_PREFIX");let n=r.slice(4),i=await dt.digest(e);if(!mt(n,i.bytes))throw new J("public key does not match passed in key","ERR_INVALID_RECORD_HASH_MISMATCH")},L1e={pk:JVe};function B1e(r,e,t){if(t.length===0){let s="No records given";throw new J(s,"ERR_NO_RECORDS_RECEIVED")}let i=re(e).split("/");if(i.length<3){let s="Record key does not have a selector function";throw new J(s,"ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")}let o=r[i[1].toString()];if(o==null){let s=`Unrecognized key prefix: ${i[1]}`;throw new J(s,"ERR_UNRECOGNIZED_KEY_PREFIX")}return t.length===1?0:o(e,t)}function eKe(r,e){return 0}var M1e={pk:eKe};var Lx=class{constructor(e,t){let{validators:n,selectors:i,peerRouting:o,queryManager:s,routingTable:a,network:c,lan:u}=t;this.components=e,this.log=j(`libp2p:kad-dht:${u?"lan":"wan"}:content-fetching`),this.validators=n,this.selectors=i,this.peerRouting=o,this.queryManager=s,this.routingTable=a,this.network=c}async putLocal(e,t){let n=Gl(e);await this.components.datastore.put(n,t)}async getLocal(e){this.log("getLocal %b",e);let t=Gl(e);this.log("fetching record for key %k",t);let n=await this.components.datastore.get(t);this.log("found %k in local datastore",t);let i=Yr.deserialize(n);return await vg(this.validators,i),i}async*sendCorrectionRecord(e,t,n,i={}){this.log("sendCorrection for %b",e);let o=pM(e,n);for(let{value:s,from:a}of t){if(mt(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{let l=Gl(e);this.log(`Storing corrected record for key ${l.toString()}`),await this.components.datastore.put(l,o.subarray())}catch(l){this.log.error("Failed error correcting self",l)}continue}let c=!1,u=new jr(Sn.PUT_VALUE,e,0);u.record=Yr.deserialize(o);for await(let l of this.network.sendRequest(a,u,i))l.name==="PEER_RESPONSE"&&l.record!=null&&mt(l.record.value,Yr.deserialize(o).value)&&(c=!0),yield l;c||(yield lo({from:a,error:new J("value not put correctly","ERR_PUT_VALUE_INVALID")})),this.log.error("Failed error correcting entry")}}async*put(e,t,n={}){this.log("put key %b value %b",e,t);let i=pM(e,t),o=Gl(e);this.log(`storing record for key ${o.toString()}`),await this.components.datastore.put(o,i.subarray()),yield*Ne(this.peerRouting.getClosestPeers(e,{signal:n.signal}),s=>Mi(s,a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[],u=new jr(Sn.PUT_VALUE,e,0);u.record=Yr.deserialize(i),this.log("send put to %p",a.peer.id);for await(let l of this.network.sendRequest(a.peer.id,u,n))c.push(l),l.name==="PEER_RESPONSE"&&(l.record!=null&&mt(l.record.value,Yr.deserialize(i).value)||c.push(lo({from:a.peer.id,error:new J("value not put correctly","ERR_PUT_VALUE_INVALID")})));return c}),s=>ep(s,{ordered:!1,concurrency:3}),async function*(s){for await(let a of s)yield*a})}async*get(e,t={}){this.log("get %b",e);let n=[];for await(let a of this.getMany(e,t))a.name==="VALUE"&&n.push(a),yield a;if(n.length===0)return;let i=n.map(a=>a.value),o=0;try{o=B1e(this.selectors,e,i)}catch(a){if(a.code!=="ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")throw a}let s=i[o];if(this.log("GetValue %b %b",e,s),s==null)throw new J("best value was not found","ERR_NOT_FOUND");yield*this.sendCorrectionRecord(e,n,s,t),yield n[o]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{let a=await this.getLocal(e);yield U4({value:a.value,from:this.components.peerId})}catch(a){this.log("error getting local value for %b",e,a)}let n=await xu(e),i=this.routingTable.closestPeers(n);this.log("found %d peers in routing table",i.length);let o=this,s=async function*({peer:a,signal:c}){for await(let u of o.peerRouting.getValueOrPeers(a,e,{signal:c}))yield u,u.name==="PEER_RESPONSE"&&u.record!=null&&(yield U4({from:a,value:u.record.value}))};yield*this.queryManager.run(e,i,s,t)}};var Bx=class{constructor(e,t){let{network:n,peerRouting:i,queryManager:o,routingTable:s,providers:a,lan:c}=t;this.components=e,this.log=j(`libp2p:kad-dht:${c?"lan":"wan"}:content-routing`),this.network=n,this.peerRouting=i,this.queryManager=o,this.routingTable=s,this.providers=a}async*provide(e,t,n={}){this.log("provide %s",e),await this.providers.addProvider(e,this.components.peerId);let i=new jr(Sn.ADD_PROVIDER,e.multihash.bytes,0);i.providerPeers=[{id:this.components.peerId,multiaddrs:t,protocols:[]}];let o=0,s=a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[];this.log("putProvider %s to %p",e,a.peer.id);try{this.log("sending provider record for %s to %p",e,a.peer.id);for await(let u of this.network.sendMessage(a.peer.id,i,n))u.name==="PEER_RESPONSE"&&(this.log("sent provider record for %s to %p",e,a.peer.id),o++),c.push(u)}catch(u){this.log.error("error sending provide record to peer %p",a.peer.id,u),c.push(lo({from:a.peer.id,error:u}))}return c};yield*Ne(this.peerRouting.getClosestPeers(e.multihash.bytes,n),a=>Mi(a,c=>s(c)),a=>ep(a,{ordered:!1,concurrency:3}),async function*(a){for await(let c of a)yield*c}),this.log("sent provider records to %d peers",o)}async*findProviders(e,t){let n=this.routingTable.kBucketSize,i=e.multihash.bytes,o=await xu(i),s=this;this.log("findProviders %c",e);let a=await this.providers.getProviders(e);if(a.length>0){let l=[];for(let f of a.slice(0,n))l.push({id:f,multiaddrs:(await this.components.peerStore.addressBook.get(f)??[]).map(h=>h.multiaddr),protocols:[]});yield B4({from:this.components.peerId,messageType:Sn.GET_PROVIDERS,providers:l}),yield wM({from:this.components.peerId,providers:l})}if(a.length>=n)return;let c=async function*({peer:l,signal:f}){let h=new jr(Sn.GET_PROVIDERS,i,0);yield*s.network.sendRequest(l,h,{signal:f})},u=new Set(a.map(l=>l.toString()));for await(let l of this.queryManager.run(i,this.routingTable.closestPeers(o),c,t))if(yield l,l.name==="PEER_RESPONSE"){this.log("Found %d provider entries for %c and %d closer peers",l.providers.length,e,l.closer.length);let f=[];for(let h of l.providers)u.has(h.id.toString())||(u.add(h.id.toString()),f.push(h));if(f.length>0&&(yield wM({from:l.from,providers:f})),u.size===n)return}}};function Mx(r,e){if(globalThis.Buffer!=null)return globalThis.Buffer.compare(r,e);for(let t=0;te[t])return 1}return r.byteLength>e.byteLength?1:r.byteLengthe.peerId)}async add(e){if(this.peerDistances.find(i=>i.peerId.equals(e))!=null)return;let t=await Es(e),n={peerId:e,distance:Wl(this.originDhtKey,t)};this.peerDistances.push(n),this.peerDistances.sort((i,o)=>Mx(i.distance,o.distance)),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async anyCloser(e){if(e.length===0)return!1;if(this.length===0)return!0;let t=await Promise.all(e.map(Es)),n=this.peerDistances[this.peerDistances.length-1].distance;for(let i of t){let o=Wl(this.originDhtKey,i);if(Mx(o,n)<0)return!0}return!1}};var Fx=class{constructor(e,t){let{routingTable:n,network:i,validators:o,queryManager:s,lan:a}=t;this.components=e,this.routingTable=n,this.network=i,this.validators=o,this.queryManager=s,this.log=j(`libp2p:kad-dht:${a?"lan":"wan"}:peer-routing`)}async findPeerLocal(e){let t,n=await this.routingTable.find(e);if(n!=null){this.log("findPeerLocal found %p in routing table",e);try{t=await this.components.peerStore.get(n)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}}if(t==null)try{t=await this.components.peerStore.get(e)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(t!=null)return this.log("findPeerLocal found %p in peer store",e),{id:t.id,multiaddrs:t.addresses.map(i=>i.multiaddr),protocols:[]}}async*_getValueSingle(e,t,n={}){let i=new jr(Sn.GET_VALUE,t,0);yield*this.network.sendRequest(e,i,n)}async*getPublicKeyFromNode(e,t={}){let n=v1e(e);for await(let i of this._getValueSingle(e,n,t))if(yield i,i.name==="PEER_RESPONSE"&&i.record!=null){let o=await Hn(Zb.marshalPublicKey({bytes:i.record.value}));if(!o.equals(e))throw new J("public key does not match id","ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID");if(o.publicKey==null)throw new J("public key missing","ERR_PUBLIC_KEY_MISSING");yield U4({from:e,value:o.publicKey})}throw new J(`Node not responding with its public key: ${e.toString()}`,"ERR_INVALID_RECORD")}async*findPeer(e,t={}){this.log("findPeer %p",e);let n=await this.findPeerLocal(e);if(n!=null){this.log("found local"),yield M4({from:this.components.peerId,peer:n});return}let i=await Es(e),o=this.routingTable.closestPeers(i);if(o.find(l=>l.equals(e))!=null)try{let l=await this.components.peerStore.get(e);this.log("found in peerStore"),yield M4({from:this.components.peerId,peer:{id:l.id,multiaddrs:l.addresses.map(f=>f.multiaddr),protocols:[]}});return}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}let a=this,c=async function*({peer:l,signal:f}){let h=new jr(Sn.FIND_NODE,e.toBytes(),0);for await(let d of a.network.sendRequest(l,h,{signal:f}))if(yield d,d.name==="PEER_RESPONSE"){let p=d.closer.find(g=>g.id.equals(e));p!=null&&(yield M4({from:d.from,peer:p}))}},u=!1;for await(let l of this.queryManager.run(e.toBytes(),o,c,t))l.name==="FINAL_PEER"&&(u=!0),yield l;u||(yield lo({from:this.components.peerId,error:new J("Not found","ERR_NOT_FOUND")}))}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);let n=await xu(e),i=this.routingTable.closestPeers(n),o=this,s=new Ux(n,this.routingTable.kBucketSize);await Promise.all(i.map(async c=>{await s.add(c)}));let a=async function*({peer:c,signal:u}){o.log("closerPeersSingle %s from %p",re(e,"base32"),c);let l=new jr(Sn.FIND_NODE,e,0);yield*o.network.sendRequest(c,l,{signal:u})};for await(let c of this.queryManager.run(e,i,a,t))yield c,c.name==="PEER_RESPONSE"&&await Promise.all(c.closer.map(async u=>{await s.add(u.id)}));this.log("found %d peers close to %b",s.length,e);for(let c of s.peers)yield M4({from:this.components.peerId,peer:{id:c,multiaddrs:(await this.components.peerStore.addressBook.get(c)??[]).map(u=>u.multiaddr),protocols:[]}})}async*getValueOrPeers(e,t,n={}){for await(let i of this._getValueSingle(e,t,n)){if(i.name==="PEER_RESPONSE"&&i.record!=null)try{await this._verifyRecordOnline(i.record)}catch{let s="invalid record received, discarded";this.log(s),yield lo({from:i.from,error:new J(s,"ERR_INVALID_RECORD")});continue}yield i}}async _verifyRecordOnline(e){if(e.timeReceived==null)throw new J("invalid record received","ERR_INVALID_RECORD");await vg(this.validators,new Yr(e.key,e.value,e.timeReceived))}async getCloserPeersOffline(e,t){let n=await xu(e),i=this.routingTable.closestPeers(n),o=[];for(let s of i)if(!s.equals(t))try{let a=await this.components.peerStore.addressBook.get(s),c=await this.components.peerStore.protoBook.get(s);o.push({id:s,multiaddrs:a.map(u=>u.multiaddr),protocols:c})}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}return o.length>0?this.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",o.length,e,t):this.log("getCloserPeersOffline could not find peer closer to %b than %p",e,t),o}};var U1e=C(Cy(),1),_M=C(Xo(),1);var Yl=j("libp2p:kad-dht:providers"),zx=class{constructor(e,t={}){let{cacheSize:n,cleanupInterval:i,provideValidity:o}=t;this.components=e,this.cleanupInterval=i??36e5,this.provideValidity=o??864e5,this.cache=(0,U1e.default)(n??256),this.syncQueue=new qn({concurrency:1}),this.started=!1}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cleaner=setInterval(()=>{this._cleanup().catch(e=>{Yl.error(e)})},this.cleanupInterval))}async stop(){this.started=!1,this.cleaner!=null&&(clearInterval(this.cleaner),this.cleaner=void 0)}async _cleanup(){await this.syncQueue.add(async()=>{let e=Date.now(),t=0,n=0,i=new Map,o=this.components.datastore.batch(),s=this.components.datastore.query({prefix:hM});for await(let a of s)try{let{cid:c,peerId:u}=F1e(a.key),l=z1e(a.value).getTime(),f=Date.now(),h=f-l,d=h>this.provideValidity;if(Yl("comparing: %d - %d = %d > %d %s",f,l,h,this.provideValidity,d?"(expired)":""),d){n++,o.delete(a.key);let p=i.get(c)??new Set;p.add(u),i.set(c,p)}t++}catch(c){Yl.error(c.message)}i.size>0?(Yl("deleting %d / %d entries",n,t),await o.commit()):Yl("nothing to delete");for(let[a,c]of i){let u=F4(a),l=this.cache.get(u);if(l!=null){for(let f of c)l.delete(f);l.size===0?this.cache.remove(u):this.cache.set(u,l)}}Yl("Cleanup successful (%dms)",Date.now()-e)})}async _getProvidersMap(e){let t=F4(e),n=this.cache.get(t);return n==null&&(n=await oKe(this.components.datastore,e),this.cache.set(t,n)),n}async addProvider(e,t){await this.syncQueue.add(async()=>{Yl("%p provides %s",t,e);let n=await this._getProvidersMap(e);Yl("loaded %s provs",n.size);let i=new Date;n.set(t.toString(),i);let o=F4(e);this.cache.set(o,n),await iKe(this.components.datastore,e,t,i)})}async getProviders(e){return await this.syncQueue.add(async()=>(Yl("get providers for %s",e),[...(await this._getProvidersMap(e)).keys()].map(n=>Oe(n))),{throwOnTimeout:!0})}};function F4(r){let e=typeof r=="string"?r:re(r.multihash.bytes,"base32");return`${hM}/${e}`}async function iKe(r,e,t,n){let i=[F4(e),"/",t.toString()].join(""),o=new pe(i),s=Uint8Array.from(_M.default.encode(n.getTime()));await r.put(o,s)}function F1e(r){let e=r.toString().split("/");if(e.length!==5)throw new Error(`incorrectly formatted provider entry key in datastore: ${r.toString()}`);return{cid:e[3],peerId:e[4]}}async function oKe(r,e){let t=new Map,n=r.query({prefix:F4(e)});for await(let i of n){let{peerId:o}=F1e(i.key);t.set(o,z1e(i.value))}return t}function z1e(r){return new Date(_M.default.decode(r))}var q1e=C(Kn(),1),H1e=C(Da(),1);var V1e=C(Kn(),1),K1e=C(Da(),1);var sKe=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");async function*$1e(r){let{key:e,startingPeer:t,ourPeerId:n,signal:i,query:o,alpha:s,pathIndex:a,numPaths:c,cleanUp:u,queryFuncTimeout:l,log:f,peersSeen:h}=r,d=new qn({concurrency:s}),p=await xu(e);function g(w,_){if(w==null)return;h.add(w);let x=BigInt("0x"+re(Wl(_,p),"base16"));d.add(async()=>{let m,y=[i];l!=null&&(m=new V1e.TimeoutController(l),y.push(m.signal));let b=(0,K1e.anySignal)(y);try{for await(let E of o({key:e,peer:w,signal:b,pathIndex:a,numPaths:c})){if(b.aborted)return;if(E.name==="PEER_RESPONSE")for(let v of E.closer){if(h.has(v.id)){f("already seen %p in query",v.id);continue}if(n.equals(v.id)){f("not querying ourselves");continue}let S=await Es(v.id);if(BigInt("0x"+re(Wl(S,p),"base16"))>x){f("skipping %p as they are not closer to %b than %p",v.id,e,w);continue}f("querying closer peer %p",v.id),g(v.id,S)}d.emit("completed",E)}m==null||m.clear()}catch(E){i.aborted?d.emit("error",E):d.emit("completed",lo({from:w,error:E}))}finally{m==null||m.clear()}},{priority:sKe-x}).catch(m=>{f.error(m)})}g(t,await Es(t)),yield*aKe(d,i,u,f)}async function*aKe(r,e,t,n){let i=Qt(),o=!0,s=[],a=()=>{o&&(n("clean up queue, results %d, queue size %d, pending tasks %d",s.length,r.size,r.pending),o=!1,r.clear(),s.splice(0,s.length))};for(r.on("completed",c=>{s.push(c),i.resolve()}),r.on("error",c=>{n("queue error",c),a(),i.reject(c)}),r.on("idle",()=>{n("queue idle"),o=!1,i.resolve()}),e.addEventListener("abort",()=>{n("abort queue");let c=o;a(),c&&i.reject(new J("Query aborted","ERR_QUERY_ABORTED"))}),t.addEventListener("cleanup",()=>{a(),i.resolve()});o;)for(await i.promise,i=Qt();s.length>0;){let c=s.shift();c!=null&&(yield c)}yield*s}async function*ga(...r){let e=Ao({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var z4=C(xi(),1);var Kx=class{constructor(e,t){let{lan:n=!1,disjointPaths:i=20,alpha:o=3}=t;this.components=e,this.disjointPaths=i??20,this.controllers=new Set,this.running=!1,this.alpha=o??3,this.lan=n,this.queries=0}isStarted(){return this.running}async start(){this.running=!0,this.components.metrics!=null&&this.metrics==null&&(this.metrics={runningQueries:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_running_queries`),queryTime:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_query_time_seconds`)})}async stop(){this.running=!1;for(let e of this.controllers)e.abort();this.controllers.clear()}async*run(e,t,n,i={}){var p,g,w;if(!this.running)throw new Error("QueryManager not started");let o=(p=this.metrics)==null?void 0:p.queryTime.timer(),s;if(i.signal==null){s=new q1e.TimeoutController(3e4),i.signal=s.signal;try{z4.setMaxListeners!=null&&(0,z4.setMaxListeners)(1/0,s.signal)}catch{}}let a=new AbortController;this.controllers.add(a);let c=[a.signal];i.signal!=null&&c.push(i.signal);let u=(0,H1e.anySignal)(c);try{z4.setMaxListeners!=null&&(0,z4.setMaxListeners)(1/0,u)}catch{}let l=j(`libp2p:kad-dht:${this.lan?"lan":"wan"}:query:`+re(e,"base58btc")),f=t.slice(0,Math.min(this.disjointPaths,t.length)),h=Date.now(),d=new Ki;try{if(l("query:start"),this.queries++,(g=this.metrics)==null||g.runningQueries.update(this.queries),t.length===0){l.error("Running query with no peers");return}let _=new ma,x=f.map((m,y)=>$1e({key:e,startingPeer:m,ourPeerId:this.components.peerId,signal:u,query:n,pathIndex:y,numPaths:f.length,alpha:this.alpha,cleanUp:d,queryFuncTimeout:i.queryFuncTimeout,log:l,peersSeen:_}));for await(let m of ga(...x))yield m,m.name==="QUERY_ERROR"&&l("error",m.error)}catch(_){if(!(!this.running&&_.code==="ERR_QUERY_ABORTED"))throw _}finally{this.controllers.delete(a),s!=null&&s.clear(),this.queries--,(w=this.metrics)==null||w.runningQueries.update(this.queries),o!=null&&o(),d.dispatchEvent(new cn("cleanup")),l("query:done in %dms",Date.now()-h)}}};var V4=j("libp2p:kad-dht:rpc:handlers:add-provider"),$x=class{constructor(e){let{providers:t}=e;this.providers=t}async handle(e,t){if(V4("start"),t.key==null||t.key.length===0)throw new J("Missing key","ERR_MISSING_KEY");let n;try{n=z.decode(t.key)}catch{throw new J("Invalid CID","ERR_INVALID_CID")}(t.providerPeers==null||t.providerPeers.length===0)&&V4.error("no providers found in message"),await Promise.all(t.providerPeers.map(async i=>{if(!i.id.equals(e)){V4("invalid provider peer %p from %p",i.id,e);return}if(i.multiaddrs.length<1){V4("no valid addresses for provider %p. Ignore",e);return}V4("received provider %p for %s (addrs %s)",e,n,i.multiaddrs.map(o=>o.toString())),await this.providers.addProvider(n,i.id)}))}};var G1e=j("libp2p:kad-dht:rpc:handlers:find-node"),qx=class{constructor(e,t){let{peerRouting:n,lan:i}=t;this.components=e,this.peerRouting=n,this.lan=!!i}async handle(e,t){G1e("incoming request from %p for peers closer to %b",e,t.key);let n=[];mt(this.components.peerId.toBytes(),t.key)?n=[{id:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(o=>o.decapsulateCode(Fr("p2p").code)),protocols:[]}]:n=await this.peerRouting.getCloserPeersOffline(t.key,e),n=n.map(this.lan?_g:bg).filter(({multiaddrs:o})=>o.length);let i=new jr(t.type,new Uint8Array(0),t.clusterLevel);return n.length>0?i.closerPeers=n:G1e("could not find any peers closer to %b than %p",t.key,e),i}};var j1e=j("libp2p:kad-dht:rpc:handlers:get-providers"),Hx=class{constructor(e,t){let{peerRouting:n,providers:i,lan:o}=t;this.components=e,this.peerRouting=n,this.providers=i,this.lan=!!o}async handle(e,t){let n;try{n=z.decode(t.key)}catch{throw new J("Invalid CID","ERR_INVALID_CID")}j1e("%p asking for providers for %s",e,n);let[i,o]=await Promise.all([this.providers.getProviders(n),this.peerRouting.getCloserPeersOffline(t.key,e)]),s=await this._getPeers(i),a=await this._getPeers(o.map(({id:u})=>u)),c=new jr(t.type,t.key,t.clusterLevel);return s.length>0&&(c.providerPeers=s),a.length>0&&(c.closerPeers=a),j1e("got %s providers %s closerPeers",s.length,a.length),c}async _getAddresses(e){return(await this.components.peerStore.addressBook.get(e)).map(n=>n.multiaddr)}async _getPeers(e){let t=[],n=this.lan?_g:bg;for(let i of e){let o=n({id:i,multiaddrs:await this._getAddresses(i),protocols:[]});o.multiaddrs.length>0&&t.push(o)}return t}};var Sg=j("libp2p:kad-dht:rpc:handlers:get-value"),Gx=class{constructor(e,t){let{peerRouting:n}=t;this.components=e,this.peerRouting=n}async handle(e,t){let n=t.key;if(Sg("%p asked for key %b",e,n),n==null||n.length===0)throw new J("Invalid key","ERR_INVALID_KEY");let i=new jr(Sn.GET_VALUE,n,t.clusterLevel);if(x1e(n)){Sg("is public key");let a=S1e(n),c;try{let u=await this.components.peerStore.keyBook.get(a);if(u==null)throw new J("No public key found in key book","ERR_NOT_FOUND");c=u}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(c!=null)return Sg("returning found public key"),i.record=new Yr(n,c,new Date),i}let[o,s]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getCloserPeersOffline(t.key,e)]);return o!=null&&(Sg("had record for %b in local datastore",n),i.record=o),s.length>0&&(Sg("had %s closer peers in routing table",s.length),i.closerPeers=s),i}async _checkLocalDatastore(e){Sg("checkLocalDatastore looking for %b",e);let t=Gl(e),n;try{n=await this.components.datastore.get(t)}catch(o){if(o.code==="ERR_NOT_FOUND")return;throw o}let i=Yr.deserialize(n);if(i==null)throw new J("Invalid record","ERR_INVALID_RECORD");if(i.timeReceived==null||Date.now()-i.timeReceived.getTime()>1296e5){await this.components.datastore.delete(t);return}return i}};var lKe=j("libp2p:kad-dht:rpc:handlers:ping"),jx=class{async handle(e,t){return lKe("ping from %p",e),t}};var Wx=class{constructor(e,t){let{validators:n}=t;this.components=e,this.log=j("libp2p:kad-dht:rpc:handlers:put-value"),this.validators=n}async handle(e,t){let n=t.key;this.log("%p asked us to store value for key %b",e,n);let i=t.record;if(i==null){let o=`Empty record from: ${e.toString()}`;throw this.log.error(o),new J(o,"ERR_EMPTY_RECORD")}try{await vg(this.validators,i),i.timeReceived=new Date;let o=Gl(i.key);await this.components.datastore.put(o,i.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,o)}catch(o){this.log("did not put record for key %b into datastore %o",n,o)}return t}};var Yx=class{constructor(e,t){let{providers:n,peerRouting:i,validators:o,lan:s}=t;this.log=j("libp2p:kad-dht:rpc"),this.routingTable=t.routingTable,this.handlers={[Sn.GET_VALUE]:new Gx(e,{peerRouting:i}),[Sn.PUT_VALUE]:new Wx(e,{validators:o}),[Sn.FIND_NODE]:new qx(e,{peerRouting:i,lan:s}),[Sn.ADD_PROVIDER]:new $x({providers:n}),[Sn.GET_PROVIDERS]:new Hx(e,{peerRouting:i,providers:n,lan:s}),[Sn.PING]:new jx}}async handleMessage(e,t){try{await this.routingTable.add(e)}catch(i){this.log.error("Failed to update the kbucket store",i)}let n=this.handlers[t.type];if(n==null){this.log.error(`no handler found for message type: ${t.type}`);return}return await n.handle(e,t)}onIncomingStream(e){Promise.resolve().then(async()=>{let{stream:t,connection:n}=e,i=n.remotePeer;try{await this.routingTable.add(i)}catch(s){this.log.error(s)}let o=this;await Ne(t,Xr(),async function*(s){for await(let a of s){let c=jr.deserialize(a);o.log("incoming %s from %p",c.type,i);let u=await o.handleMessage(i,c);u!=null&&(yield u.serialize())}},vn(),t)}).catch(t=>{this.log.error(t)})}};var Qx=class extends Ki{constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=j(`libp2p:kad-dht:topology-listener:${i?"lan":"wan"}`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){if(this.running)return;this.running=!0;let e=hv({onConnect:t=>{this.log("observed peer %p with protocol %s",t,this.protocol),this.dispatchEvent(new cn("peer",{detail:t}))}});this.registrarId=await this.components.registrar.register(this.protocol,e)}async stop(){this.running=!1,this.registrarId!=null&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}};var vM=C(xi(),1);async function*EM(r,e){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}var W1e=C(Kn(),1),Y1e=C(Da(),1);var Xx=class{constructor(e,t){let{peerRouting:n,lan:i,count:o,interval:s,queryTimeout:a}=t;this.components=e,this.log=j(`libp2p:kad-dht:${i?"lan":"wan"}:query-self`),this.running=!1,this.peerRouting=n,this.count=o??20,this.interval=s??3e5,this.queryTimeout=a??3e4}isStarted(){return this.running}async start(){this.running||(this.running=!0,this._querySelf())}async stop(){this.running=!1,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.controller!=null&&this.controller.abort()}_querySelf(){Promise.resolve().then(async()=>{let e=new W1e.TimeoutController(this.queryTimeout);try{this.controller=new AbortController;let t=(0,Y1e.anySignal)([this.controller.signal,e.signal]);try{vM.setMaxListeners!=null&&(0,vM.setMaxListeners)(1/0,t)}catch{}let n=await Ne(this.peerRouting.getClosestPeers(this.components.peerId.toBytes(),{signal:t}),i=>EM(i,this.count),async i=>await L4(i));this.log("query ran successfully - found %d peers",n)}catch(t){this.log("query error",t)}finally{this.timeoutId=setTimeout(this._querySelf.bind(this),this.interval),e.clear()}}).catch(e=>{this.log("query error",e)})}};var Crr=Symbol.for("@libp2p/peer-discovery"),Ag=Symbol.for("@libp2p/peer-discovery");var hKe=32,pKe=64,K4=class extends Ki{constructor(e,t){super();let{kBucketSize:n,clientMode:i,validators:o,selectors:s,querySelfInterval:a,lan:c,protocolPrefix:u,pingTimeout:l,pingConcurrency:f,maxInboundStreams:h,maxOutboundStreams:d,providers:p}=t;this.running=!1,this.components=e,this.lan=!!c,this.log=j(`libp2p:kad-dht:${c===!0?"lan":"wan"}`),this.protocol=`${u??b1e}${c===!0?w1e:""}${_1e}`,this.kBucketSize=n??20,this.clientMode=i??!0,this.maxInboundStreams=h??hKe,this.maxOutboundStreams=d??pKe,this.routingTable=new kx(e,{kBucketSize:n,lan:this.lan,pingTimeout:l,pingConcurrency:f,protocol:this.protocol}),this.providers=new zx(e,p??{}),this.validators={...L1e,...o},this.selectors={...M1e,...s},this.network=new Ox(e,{protocol:this.protocol,lan:this.lan}),this.queryManager=new Kx(e,{disjointPaths:Math.ceil(this.kBucketSize/2),lan:c}),this.peerRouting=new Fx(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,lan:this.lan}),this.contentFetching=new Lx(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,network:this.network,lan:this.lan}),this.contentRouting=new Bx(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,lan:this.lan}),this.routingTableRefresh=new Dx({peerRouting:this.peerRouting,routingTable:this.routingTable,lan:this.lan}),this.rpc=new Yx(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,lan:this.lan}),this.topologyListener=new Qx(e,{protocol:this.protocol,lan:this.lan}),this.querySelf=new Xx(e,{peerRouting:this.peerRouting,interval:a,lan:this.lan}),this.network.addEventListener("peer",g=>{let w=g.detail;this.onPeerConnect(w).catch(_=>{this.log.error("could not add %p to routing table",w.id,_)}),this.dispatchEvent(new cn("peer",{detail:w}))}),this.topologyListener.addEventListener("peer",g=>{let w=g.detail;Promise.resolve().then(async()=>{let _=await this.components.peerStore.addressBook.get(w),x={id:w,multiaddrs:_.map(m=>m.multiaddr),protocols:[]};await this.onPeerConnect(x)}).catch(_=>{this.log.error("could not add %p to routing table",w,_)})})}get[Ag](){return!0}get[Symbol.toStringTag](){return"@libp2p/kad-dht"}async onPeerConnect(e){if(this.log("peer %p connected with protocols %s",e.id,e.protocols),this.lan?e=_g(e):e=bg(e),e.multiaddrs.length===0){this.log("ignoring %p as they do not have any %s addresses in %s",e.id,this.lan?"private":"public",e.multiaddrs.map(t=>t.toString()));return}try{await this.routingTable.add(e.id)}catch(t){this.log.error("could not add %p to routing table",e.id,t)}}isStarted(){return this.running}async getMode(){return this.clientMode?"client":"server"}async setMode(e){await this.components.registrar.unhandle(this.protocol),e==="client"?(this.log("enabling client mode"),this.clientMode=!0):(this.log("enabling server mode"),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}))}async start(){this.running=!0,await this.setMode(this.clientMode?"client":"server"),await Promise.all([this.providers.start(),this.queryManager.start(),this.network.start(),this.routingTable.start(),this.topologyListener.start(),this.querySelf.start()]),await this.routingTableRefresh.start()}async stop(){this.running=!1,await Promise.all([this.providers.stop(),this.queryManager.stop(),this.network.stop(),this.routingTable.stop(),this.routingTableRefresh.stop(),this.topologyListener.stop(),this.querySelf.stop()])}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(){this.routingTableRefresh.refreshTable(!0)}};var mKe=j("libp2p:kad-dht"),Zx=class extends Ki{constructor(e,t,n){super(),this.components=e,this.wan=t,this.lan=n,this.wan.addEventListener("peer",i=>{this.dispatchEvent(new cn("peer",{detail:i.detail}))}),this.lan.addEventListener("peer",i=>{this.dispatchEvent(new cn("peer",{detail:i.detail}))})}get[Ag](){return!0}get[Symbol.toStringTag](){return"@libp2p/dual-kad-dht"}isStarted(){return this.wan.isStarted()&&this.lan.isStarted()}async getMode(){return await this.wan.getMode()}async setMode(e){await this.wan.setMode(e)}async start(){await Promise.all([this.lan.start(),this.wan.start()])}async stop(){await Promise.all([this.lan.stop(),this.wan.stop()])}async*put(e,t,n={}){for await(let i of ga(this.lan.put(e,t,n),this.wan.put(e,t,n)))yield i}async*get(e,t={}){let n=!1,i=!1;for await(let o of ga(this.lan.get(e,t),this.wan.get(e,t)))yield o,o.name==="DIALING_PEER"&&(n=!0),o.name==="VALUE"&&(n=!0,o.value!=null&&(i=!0)),o.name==="SENDING_QUERY"&&(n=!0);if(!n)throw new J("No peers found in routing table!","ERR_NO_PEERS_IN_ROUTING_TABLE");i||(yield lo({from:this.components.peerId,error:new J("Not found","ERR_NOT_FOUND")}))}async*provide(e,t={}){let n=0,i=0,o=[],s=[this.lan];await this.wan.getMode()==="server"&&s.push(this.wan);for await(let a of ga(...s.map(c=>c.provide(e,t))))yield a,a.name==="SENDING_QUERY"&&n++,a.name==="QUERY_ERROR"&&o.push(a.error),a.name==="PEER_RESPONSE"&&a.messageName==="ADD_PROVIDER"&&(mKe("sent provider record for %s to %p",e,a.from),i++);if(i===0)throw o.length>0?new J(`Failed to provide to ${o.length} of ${n} peers`,"ERR_PROVIDES_FAILED",{errors:o}):new J("Failed to provide - no peers found","ERR_PROVIDES_FAILED")}async*findProviders(e,t={}){yield*ga(this.lan.findProviders(e,t),this.wan.findProviders(e,t))}async*findPeer(e,t={}){let n=!1;for await(let i of ga(this.lan.findPeer(e,t),this.wan.findPeer(e,t)))yield i,(i.name==="SENDING_QUERY"||i.name==="FINAL_PEER")&&(n=!0);if(!n)throw new J("Peer lookup failed","ERR_LOOKUP_FAILED")}async*getClosestPeers(e,t={}){yield*ga(this.lan.getClosestPeers(e,t),this.wan.getClosestPeers(e,t))}async refreshRoutingTable(){await Promise.all([this.lan.refreshRoutingTable(),this.wan.refreshRoutingTable()])}};var xM=class extends Zx{constructor(e,t){super(e,new K4(e,{protocolPrefix:"/ipfs",...t,lan:!1}),new K4(e,{protocolPrefix:"/ipfs",...t,clientMode:!1,lan:!0}))}};function Q1e(r){return e=>new xM(e,r)}var Jx=j("libp2p:bootstrap"),gKe="bootstrap",yKe=50,wKe=12e4,bKe=1e3,eS=class extends Ki{constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.timeout=t.timeout??bKe,this.list=[];for(let n of t.list){if(!rR.matches(n)){Jx.error("Invalid multiaddr");continue}let i=Xi(n),o=i.getPeerId();if(o==null){Jx.error("Invalid bootstrap multiaddr without peer id");continue}let s={id:Oe(o),multiaddrs:[i],protocols:[]};this.list.push(s)}this._init=t}get[Ag](){return!0}get[Symbol.toStringTag](){return"@libp2p/bootstrap"}isStarted(){return!!this.timer}start(){this.isStarted()||(Jx("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{Jx.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.tagPeer(e.id,this._init.tagName??gKe,{value:this._init.tagValue??yKe,ttl:this._init.tagTTL??wKe}),this.timer==null)return;this.dispatchEvent(new cn("peer",{detail:e}))}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};eS.tag="bootstrap";function X1e(r){return e=>new eS(e,r)}var Z1e=WebSocket;var rme=C(eme(),1);function tme(r){var e;return r instanceof ArrayBuffer||((e=r==null?void 0:r.constructor)==null?void 0:e.name)==="ArrayBuffer"&&typeof(r==null?void 0:r.byteLength)=="number"}var nme=r=>{r.binaryType="arraybuffer";let e=async()=>await new Promise((o,s)=>{if(n)return o();if(i!=null)return s(i);let a=l=>{r.removeEventListener("open",c),r.removeEventListener("error",u),l()},c=()=>a(o),u=l=>{a(()=>s(l.error??new Error(`connect ECONNREFUSED ${r.url}`)))};r.addEventListener("open",c),r.addEventListener("error",u)}),t=async function*(){let o=new rme.EventIterator(({push:s,stop:a,fail:c})=>{let u=f=>{let h=null;typeof f.data=="string"&&(h=fe(f.data)),tme(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&s(h)},l=f=>c(f.error??new Error("Socket error"));return r.addEventListener("message",u),r.addEventListener("error",l),r.addEventListener("close",a),()=>{r.removeEventListener("message",u),r.removeEventListener("error",l),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of o)yield tme(s)?new Uint8Array(s):s}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",o=>{n||(i=o.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var ime=r=>{if(r.readyState>=2)throw new Error("socket closed");if(r.readyState!==1)return new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",o)}function i(){n(),e()}function o(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",o)})};var ome=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await ime(r)}catch(o){if(o.message==="socket closed")break;throw o}r.send(i)}if(e.closeOnEnd!=null&&r.readyState<=1)return await new Promise((i,o)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:s});o(a)}}),setTimeout(()=>r.close())})});var sme=(r,e)=>{e=e??{};let t=nme(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,i=parseInt(s.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:ome(r,e),source:t,connected:async()=>await t.connected(),close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var ame=C(F8(),1),EKe={http:"ws",https:"wss"},vKe="ws",cme=(r,e)=>(0,ame.relative)(r,e,EKe,vKe);function ume(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=cme(r,t.toString()),i=new Z1e(n,e.websocket);return sme(i,e)}function lme(){throw new Error("WebSocket Servers can not be created in the browser!")}var fme=j("libp2p:websockets:socket");function dme(r,e,t){t=t??{};let n={async sink(i){(t==null?void 0:t.signal)!=null&&(i=na(i,t.signal));try{await r.sink(i)}catch(o){o.type!=="aborted"&&fme.error(o)}},source:t.signal!=null?na(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let i=Date.now();try{await yp(r.close(),{milliseconds:2e3})}catch{let{host:s,port:a}=n.remoteAddr.toOptions();fme("timeout closing stream to %s:%s after %dms, destroying it manually",s,a,Date.now()-i),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}function mme(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return P1.matches(t)||xh.matches(t)})}function gme(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return xh.matches(t)})}var wme=Symbol.for("@libp2p/transport");var yme;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(yme||(yme={}));var oh=j("libp2p:websockets"),TM=class{constructor(e){this.init=e}get[Symbol.toStringTag](){return"@libp2p/websockets"}get[wme](){return!0}async dial(e,t){oh("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=dme(n,e);oh("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i);return oh("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){var u,l;if(((u=t==null?void 0:t.signal)==null?void 0:u.aborted)===!0)throw new Ph;let n=e.toOptions();oh("dialing %s:%s",n.host,n.port);let i=Qt(),o=f=>{oh.error("connection error:",f),i.reject(f)},s=ume(zm(e),this.init);if(s.socket.on!=null?s.socket.on("error",o):s.socket.onerror=o,t.signal==null)return await Promise.race([s.connected(),i.promise]),oh("connected %s",e),s;let a,c=new Promise((f,h)=>{var d,p;if(a=()=>{h(new Ph),s.close().catch(g=>{oh.error("error closing raw socket",g)})},((d=t==null?void 0:t.signal)==null?void 0:d.aborted)===!0){a();return}(p=t==null?void 0:t.signal)==null||p.addEventListener("abort",a)});try{await Promise.race([c,i.promise,s.connected()])}finally{a!=null&&((l=t==null?void 0:t.signal)==null||l.removeEventListener("abort",a))}return oh("connected %s",e),s}createListener(e){return lme({...this.init,...e})}filter(e){var t,n;return e=Array.isArray(e)?e:[e],((t=this.init)==null?void 0:t.filter)!=null?(n=this.init)==null?void 0:n.filter(e):T0||rx?gme(e):mme(e)}};function bme(r={}){return()=>new TM(r)}var Tg=C(Xo(),1);function IM(r){return new Uint8Array(r)}var Ut;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(Ut||(Ut={}));var q4=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),RM=Object.freeze({NEW_STREAM:Ut.NEW_STREAM,MESSAGE:Ut.MESSAGE_INITIATOR,CLOSE:Ut.CLOSE_INITIATOR,RESET:Ut.RESET_INITIATOR}),_me=Object.freeze({MESSAGE:Ut.MESSAGE_RECEIVER,CLOSE:Ut.CLOSE_RECEIVER,RESET:Ut.RESET_RECEIVER});var Eme=1024*1024,AKe=(r,e)=>{e.append(r)};async function*TKe(r,e={}){let t=new vt,n=!1,i=Qt(),o=Number(e.size??Eme);(isNaN(o)||o===0||o<0)&&(o=Eme);let s=e.yieldAfter??0,a=e.serialize??AKe;for(Promise.resolve().then(async()=>{try{let c;for await(let u of r){if(a(u,t),t.byteLength>=o){clearTimeout(c),i.resolve();continue}c=setTimeout(()=>{i.resolve()},s)}clearTimeout(c),i.resolve()}catch(c){i.reject(c)}finally{n=!0}});!n;)if(await i.promise,i=Qt(),t.byteLength>0){let c=t;t=new vt,yield c.subarray()}}var vme=TKe;var CM=10*1024,PM=class{constructor(){this._pool=IM(CM),this._poolOffset=0}write(e,t){let n=this._pool,i=this._poolOffset;Tg.default.encode(e.id<<3|e.type,n,i),i+=Tg.default.encode.bytes??0,(e.type===Ut.NEW_STREAM||e.type===Ut.MESSAGE_INITIATOR||e.type===Ut.MESSAGE_RECEIVER)&&e.data!=null?Tg.default.encode(e.data.length,n,i):Tg.default.encode(0,n,i),i+=Tg.default.encode.bytes??0;let o=n.subarray(this._poolOffset,i);CM-i<100?(this._pool=IM(CM),this._poolOffset=0):this._poolOffset=i,t.append(o),(e.type===Ut.NEW_STREAM||e.type===Ut.MESSAGE_INITIATOR||e.type===Ut.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},xme=new PM;async function*Sme(r,e=0){if(e==null||e===0){for await(let t of r){let n=new vt;for(let i of t)xme.write(i,n);yield n.subarray()}return}yield*vme(r,{size:e,serialize:(t,n)=>{for(let i of t)xme.write(i,n)}})}var kM=1<<20,IKe=4<<20,nS=class{constructor(e=kM,t=IKe){this._buffer=new vt,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)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"});let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(u){if(u.code==="ERR_MSG_TOO_BIG")throw u;break}let{id:n,type:i,length:o,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:s,offset:n+o,length:i}}},RKe=128,Ame=127;function Tme(r,e=0){let t=0,n=0,i=e,o,s=r.length;do{if(i>=s||n>49)throw e=0,new RangeError("Could not decode varint");o=r.get(i++),t+=n<28?(o&Ame)<=RKe);return e=i-e,{value:t,offset:e}}var cc=j("libp2p:mplex:stream"),NM="ERR_STREAM_RESET",CKe="ERR_STREAM_ABORT",PKe="ERR_SINK_ENDED",kKe="ERR_DOUBLE_SINK";function Ime(r){let{id:e,name:t,send:n,onEnd:i,type:o="initiator",maxMsgSize:s=kM}=r,a=new AbortController,c=new AbortController,u=new AbortController,l=o==="initiator"?RM:_me,f=o==="initiator"?`i${e}`:`r${e}`,h=`${t??e}`,d=!1,p=!1,g=!1,w,_={open:Date.now()},x=E=>{d||(d=!0,cc.trace("%s stream %s source end - err: %o",o,h,E),E!=null&&w==null&&(w=E),p&&(b.stat.timeline.close=Date.now(),i!=null&&i(w)))},m=E=>{p||(p=!0,cc.trace("%s stream %s sink end - err: %o",o,h,E),E!=null&&w==null&&(w=E),d&&(_.close=Date.now(),i!=null&&i(w)))},y=Ao({onEnd:x}),b={close:()=>{cc.trace("%s stream %s close",o,h),b.closeRead(),b.closeWrite()},closeRead:()=>{cc.trace("%s stream %s closeRead",o,h),!d&&y.end()},closeWrite:()=>{if(cc.trace("%s stream %s closeWrite",o,h),!p){u.abort();try{n({id:e,type:l.CLOSE})}catch(E){cc.trace("%s stream %s error sending close",o,t,E)}m()}},abort:E=>{cc.trace("%s stream %s abort",o,h,E),y.end(E),a.abort(),m(E)},reset:()=>{let E=new J("stream reset",NM);c.abort(),y.end(E),m(E)},sink:async E=>{if(g)throw new J("sink already called on stream",kKe);if(g=!0,p)throw new J("stream closed for writing",PKe);let v=ia([a.signal,c.signal,u.signal]);try{E=na(E,v),o==="initiator"&&n({id:e,type:RM.NEW_STREAM,data:new vt(Ie(h))});for await(let S of E)for(;S.length>0;){if(S.length<=s){n({id:e,type:l.MESSAGE,data:S instanceof Uint8Array?new vt(S):S});break}S=S instanceof Uint8Array?new vt(S):S,n({id:e,type:l.MESSAGE,data:S.sublist(0,s)}),S.consume(s)}}catch(S){if(S.type==="aborted"&&S.message==="The operation was aborted"){if(u.signal.aborted)return;c.signal.aborted&&(S.message="stream reset",S.code=NM),a.signal.aborted&&(S.message="stream aborted",S.code=CKe)}if(S.code===NM)cc.trace("%s stream %s reset",o,t);else{cc.trace("%s stream %s error",o,t,S);try{n({id:e,type:l.RESET})}catch(A){cc.trace("%s stream %s error sending reset",o,t,A)}}y.end(S),m(S);return}finally{v.clear()}try{n({id:e,type:l.CLOSE})}catch(S){cc.trace("%s stream %s error sending close",o,t,S)}m()},source:y,sourcePush:E=>{y.push(E)},sourceReadableLength(){return y.readableLength},stat:{direction:o==="initiator"?"outbound":"inbound",timeline:_},metadata:{},id:f};return b}var x2e=C(E2e(),1);var uc=j("libp2p:mplex"),h$e=1024,p$e=1024,m$e=1024*1024*4,g$e=5;function v2e(r){let e={...r,type:`${q4[r.type]} (${r.type})`};return r.type===Ut.NEW_STREAM&&(e.data=re(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===Ut.MESSAGE_INITIATOR||r.type===Ut.MESSAGE_RECEIVER)&&(e.data=re(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var oS=class{constructor(e){this.protocol="/mplex/6.7.0",e=e??{},this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=e,this.sink=this._createSink();let t=this._createSource();this._source=t,this.source=t,this.closeController=new AbortController,this.rateLimiter=new x2e.RateLimiterMemory({points:e.disconnectThreshold??g$e,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let n=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:n})}close(e){this.closeController.signal.aborted||(e!=null?this.streams.forEach(t=>{t.abort(e)}):this.streams.forEach(t=>{t.close()}),this.closeController.abort())}_newReceiverStream(e){let{id:t,name:n}=e,i=this._streams.receivers;return this._newStream({id:t,name:n,type:"receiver",registry:i})}_newStream(e){let{id:t,name:n,type:i,registry:o}=e;if(uc("new %s stream %s",i,t),i==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??p$e))throw new J("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(o.has(t))throw new Error(`${i} stream ${t} already exists!`);let c=Ime({id:t,name:n,send:u=>{uc.enabled&&uc.trace("%s stream %s send",i,t,v2e(u)),this._source.push(u)},type:i,onEnd:()=>{uc("%s stream with id %s and protocol %s ended",i,t,c.stat.protocol),o.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize});return o.set(t,c),c}_createSink(){return async t=>{let n=ia([this.closeController.signal,this._init.signal]);try{t=na(t,n);let i=new nS(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let o of t)for(let s of i.write(o))await this._handleIncoming(s);this._source.end()}catch(i){uc("error in sink",i),this._source.end(i)}finally{n.clear()}}}_createSource(){let t=Bae({objectMode:!0,onEnd:n=>{this.close(n)}});return Object.assign(Sme(t,this._init.minSendBytes),{push:t.push,end:t.end,return:t.return})}async _handleIncoming(e){let{id:t,type:n}=e;if(uc.enabled&&uc.trace("incoming message",v2e(e)),e.type===Ut.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??h$e)){uc("too many inbound streams open"),this._source.push({id:t,type:Ut.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{uc("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this._source.end(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:re(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let o=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(o==null){uc("missing stream %s for message type %s",t,q4[n]);return}let s=this._init.maxStreamBufferSize??m$e;switch(n){case Ut.MESSAGE_INITIATOR:case Ut.MESSAGE_RECEIVER:if(o.sourceReadableLength()>s){this._source.push({id:e.id,type:n===Ut.MESSAGE_INITIATOR?Ut.RESET_RECEIVER:Ut.RESET_INITIATOR});let a=new J("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");o.abort(a);return}o.sourcePush(e.data);break;case Ut.CLOSE_INITIATOR:case Ut.CLOSE_RECEIVER:o.closeRead();break;case Ut.RESET_INITIATOR:case Ut.RESET_RECEIVER:o.reset();break;default:uc("unknown message type %s",n)}}};var GM=class{constructor(e={}){this.protocol="/mplex/6.7.0",this._init=e}createStreamMuxer(e={}){return new oS({...e,...this._init})}};function S2e(r={}){return()=>new GM(r)}function sS(r){return r[Symbol.asyncIterator]!=null}var aS=r=>{let e=ti(r),t=Ri(e);return xf(r,t),aS.bytes=e,t};aS.bytes=0;function cS(r,e){e=e??{};let t=e.lengthEncoder??aS;function*n(i){let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return sS(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}cS.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??aS;return new vt(t(r.byteLength),r)};var uS=class extends Error{constructor(){super(...arguments);B(this,"name","InvalidMessageLengthError");B(this,"code","ERR_INVALID_MSG_LENGTH")}},lS=class extends Error{constructor(){super(...arguments);B(this,"name","InvalidDataLengthError");B(this,"code","ERR_MSG_DATA_TOO_LONG")}},fS=class extends Error{constructor(){super(...arguments);B(this,"name","InvalidDataLengthLengthError");B(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},j4=class extends Error{constructor(){super(...arguments);B(this,"name","UnexpectedEOFError");B(this,"code","ERR_UNEXPECTED_EOF")}};var y$e=8,w$e=1024*1024*4,C0;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(C0||(C0={}));var WM=r=>{let e=Gu(r);return WM.bytes=ti(e),e};WM.bytes=0;function jM(r,e){let t=new vt,n=C0.LENGTH,i=-1,o=(e==null?void 0:e.lengthDecoder)??WM,s=(e==null?void 0:e.maxLengthLength)??y$e,a=(e==null?void 0:e.maxDataLength)??w$e;function*c(){for(;t.byteLength>0;){if(n===C0.LENGTH)try{if(i=o(t),i<0)throw new uS("Invalid message length");if(i>a)throw new lS("Message length too long");let u=o.bytes;t.consume(u),(e==null?void 0:e.onLength)!=null&&e.onLength(i),n=C0.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>s)throw new fS("Message length length too long");break}throw u}if(n===C0.DATA){if(t.byteLength0)throw new j4("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new j4("Unexpected end of input")}()}jM.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return jM(n,{...e??{},onLength:o=>{t=o}})};var dS=C(ee(),1),A2e=r=>Yp.decode(r);A2e.bytes=0;function YM(r,e={}){let t=Ao();r.sink(t).catch(s=>{t.end(s)}),r.sink=async s=>{for await(let a of s)t.push(a)};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let i=new vt,o={read:async s=>{if(s==null){let{done:c,value:u}=await n.next();return c===!0?new vt:u}for(;i.byteLength{let s=-1,a=new vt,c=(e==null?void 0:e.lengthDecoder)??A2e;for(;;){a.append(await o.read(1));try{s=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(s>-1)break;if((e==null?void 0:e.maxLengthLength)!=null&&a.byteLength>e.maxLengthLength)throw(0,dS.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if((e==null?void 0:e.maxDataLength)!=null&&s>e.maxDataLength)throw(0,dS.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await o.read(s)},readPB:async s=>{let a=await o.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return s.decode(c)},write:s=>{s instanceof Uint8Array?t.push(s):t.push(s.subarray())},writeLP:s=>{o.write(cS.single(s,e))},writePB:(s,a)=>{o.writeLP(a.encode(s))},pb:s=>({read:async()=>await o.readPB(s),write:a=>{o.writePB(a,s)},unwrap:()=>o}),unwrap:()=>{let s=r.source;return r.source=async function*(){yield*i,yield*s}(),r}};return o}function QM(){let r=Qt(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:async function*(){yield*await r.promise}()}}function T2e(){let r=QM(),e=QM();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}var I2e,R2e,C2e=!!((R2e=(I2e=globalThis.process)==null?void 0:I2e.env)!=null&&R2e.DUMP_SESSION_KEYS);var uge=C(B2e(),1),Ng=C(ege(),1),TS=C(rge(),1),hU=C(dU(),1),lge={hashSHA256(r){return(0,TS.hash)(r)},getHKDF(r,e){let i=new uge.HKDF(TS.SHA256,e,r).expand(96),o=i.subarray(0,32),s=i.subarray(32,64),a=i.subarray(64,96);return[o,s,a]},generateX25519KeyPair(){let r=Ng.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=Ng.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return Ng.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new hU.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new hU.ChaCha20Poly1305(n).open(e,r,t,i)}};var pU=C(dU(),1);var Rqe=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),Dg=r=>{let e=Rqe(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};Dg.bytes=2;var J4=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");return r instanceof Uint8Array?new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,!1):r.getUint16(0)};J4.bytes=2;function fge(r){return rt([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function dge(r){return rt([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function hge(r){return rt([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function pge(r){if(r.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:r.subarray(0,32),ciphertext:r.subarray(32,r.length),ns:new Uint8Array(0)}}function mge(r){if(r.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:r.subarray(0,32),ns:r.subarray(32,80),ciphertext:r.subarray(80,r.length)}}function gge(r){if(r.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:r.subarray(0,48),ciphertext:r.subarray(48,r.length)}}function wge(r,e){return async function*(t){for await(let n of t)for(let i=0;in.length&&(o=n.length);let s=r.encrypt(n.subarray(i,o),r.session);e==null||e.encryptedPackets.increment(),yield Dg(s.byteLength),yield s}}}function bge(r,e){return async function*(t){for await(let n of t)for(let i=0;in.length&&(o=n.length),o-pU.TAG_LENGTH(e==null&&(e=kn((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)n.uint32(10),n.bytes(o);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(IS||(IS={}));var t6;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identityKey!=null&&t.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(t.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||t.identitySig!=null&&t.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(t.identitySig??new Uint8Array(0))),t.extensions!=null&&(n.uint32(34),IS.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=IS.codec().decode(t,t.uint32());break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(t6||(t6={}));async function _ge(r,e,t){let n=await Pqe(r,Ege(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return Cqe(r.publicKey,n,t)}function Cqe(r,e,t){return t6.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function Pqe(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await Li(r.privateKey)).sign(e)}async function mU(r){return await Hn(r.identityKey)}function gU(r){return t6.decode(r)}function Ege(r){let e=Ie("noise-libp2p-static-key:");return rt([e,r],e.length+r.length)}async function yU(r,e,t){let n=await Hn(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=Ege(r);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await Bs(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function r6(r){return!(!(r instanceof Uint8Array)||r.length!==32)}var di=j("libp2p:noise");var wa;C2e?wa=di:wa=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function vge(r){wa(`LOCAL_STATIC_PUBLIC_KEY ${re(r.publicKey,"hex")}`),wa(`LOCAL_STATIC_PRIVATE_KEY ${re(r.privateKey,"hex")}`)}function wU(r){r?(wa(`LOCAL_PUBLIC_EPHEMERAL_KEY ${re(r.publicKey,"hex")}`),wa(`LOCAL_PRIVATE_EPHEMERAL_KEY ${re(r.privateKey,"hex")}`)):wa("Missing local ephemeral keys.")}function xge(r){wa(`REMOTE_STATIC_PUBLIC_KEY ${re(r,"hex")}`)}function bU(r){wa(`REMOTE_EPHEMERAL_PUBLIC_KEY ${re(r,"hex")}`)}function Sge(r){r.cs1&&r.cs2?(wa(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${re(r.cs1.k,"hex")}`),wa(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${re(r.cs2.k,"hex")}`)):wa("Missing cipher state.")}var kqe="Cipherstate has reached maximum n, a new handshake must be performed",RS=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(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(kqe)}};var CS=class{constructor(e){this.crypto=e}encryptWithAd(e,t,n){let i=this.encrypt(e.k,e.n,t,n);return e.n.increment(),i}decryptWithAd(e,t,n,i){let{plaintext:o,valid:s}=this.decrypt(e.k,e.n,t,n,i);return s&&e.n.increment(),{plaintext:o,valid:s}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return mt(t,e)}encrypt(e,t,n,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),n,e)}encryptAndHash(e,t){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,n),n}decrypt(e,t,n,i,o){t.assertValue();let s=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,o);return s?{plaintext:s,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,t),{plaintext:n,valid:i}}dh(e,t){try{let n=this.crypto.generateX25519SharedKey(e,t);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return di.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(rt([e,t],e.length+t.length))}mixKey(e,t){let[n,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new RS}}initializeSymmetric(e){let t=Ie(e,"utf-8"),n=this.hashProtocolName(t),i=n,o=this.createEmptyKey();return{cs:this.initializeKey(o),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let t=new Uint8Array(32);return t.set(e),t}else return this.getHash(e,new Uint8Array(0))}split(e){let[t,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(t),o=this.initializeKey(n);return{cs1:i,cs2:o}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),o=new Uint8Array(0);return{ne:i,ns:o,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var PS=class extends CS{initializeInitiator(e,t,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,e);let a=new Uint8Array(32);return{ss:s,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,e);let a=new Uint8Array(32);return{ss:s,s:t,rs:n,psk:i,re:a}}writeMessageA(e,t,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let o=e.e.publicKey;this.mixHash(e.ss,o);let s=this.encryptAndHash(e.ss,t);return{ne:o,ns:i,ciphertext:s}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,o=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t);return{ne:n,ns:o,ciphertext:s}}writeMessageC(e,t){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:o},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,t){return r6(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(r6(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&r6(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:o,valid:s}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:o,valid:i&&s}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&r6(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:o,valid:s}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:o,valid:i&&s,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),o=new Uint8Array(32),s;return e?s=this.initializeInitiator(t,n,o,i):s=this.initializeResponder(t,n,o,i),{hs:s,i:e,mc:0}}sendMessage(e,t,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,t,n);else if(e.mc===1)i=this.writeMessageB(e.hs,t);else if(e.mc===2){let{h:o,messageBuffer:s,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=s,e.h=o,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,t){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,t));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,t));else if(e.mc===2){let{h:o,plaintext:s,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,t);n=s,i=a,e.h=o,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var kS=class{constructor(e,t,n,i,o,s,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=o,this.connection=s,a&&(this.remotePeer=a),this.xx=c??new PS(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(vge(this.session.hs.s),this.isInitiator){di.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(fge(e)),di.trace("Stage 0 - Initiator finished sending first message."),wU(this.session.hs.e)}else{di.trace("Stage 0 - Responder waiting to receive first message...");let e=pge((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new Jl("xx handshake stage 0 validation fail");di.trace("Stage 0 - Responder received first message."),bU(this.session.hs.re)}}async exchange(){if(this.isInitiator){di.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=mge((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Jl("xx handshake stage 1 validation fail");di.trace("Stage 1 - Initiator received the message."),bU(this.session.hs.re),xge(this.session.hs.rs),di.trace("Initiator going to check remote's signature...");try{let i=gU(t);this.remotePeer=this.remotePeer||await mU(i),await yU(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new P0(`Error occurred while verifying signed payload: ${o.message}`)}di.trace("All good with the signature!")}else{di.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(dge(e)),di.trace("Stage 1 - Responder sent the second handshake message with signed payload."),wU(this.session.hs.e)}}async finish(){if(this.isInitiator){di.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(hge(e)),di.trace("Stage 2 - Initiator sent message with signed payload.")}else{di.trace("Stage 2 - Responder waiting for third handshake message...");let e=gge((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Jl("xx handshake stage 2 validation fail");di.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=gU(t);this.remotePeer=this.remotePeer||await mU(i),await yU(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new P0(`Error occurred while verifying signed payload: ${o.message}`)}}Sge(this.session)}encrypt(e,t){let n=this.getCS(t);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,t,n){let i=this.getCS(t,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new Jl("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function Age(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var NS=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:o,metrics:s}=e;this.crypto=i??lge,this.extensions=n,this.metrics=s?Age(s):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=o??new Uint8Array(0)}async secureOutbound(e,t,n){let i=YM(t,{lengthEncoder:Dg,lengthDecoder:J4,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,o),remoteExtensions:o.remoteExtensions,remotePeer:o.remotePeer}}async secureInbound(e,t,n){let i=YM(t,{lengthEncoder:Dg,lengthDecoder:J4,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,o),remotePeer:o.remotePeer,remoteExtensions:o.remoteExtensions}}async performHandshake(e){let t=await _ge(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,t)}async performXXHandshake(e,t){var a,c;let{isInitiator:n,remotePeer:i,connection:o}=e,s=new kS(n,t,this.prologue,this.crypto,this.staticKeys,o,i);try{await s.propose(),await s.exchange(),await s.finish(),(a=this.metrics)==null||a.xxHandshakeSuccesses.increment()}catch(u){if((c=this.metrics)==null||c.xxHandshakeErrors.increment(),u instanceof Error)throw u.message=`Error occurred during XX handshake: ${u.message}`,u}return s}async createSecureConnection(e,t){let[n,i]=T2e(),o=e.unwrap();return await Ne(n,wge(t,this.metrics),o,Xr({lengthDecoder:J4}),bge(t,this.metrics),n),i}};function Tge(r={}){return()=>new NS(r)}var Nqe=et.bind({ignoreUndefined:!0,concatArrays:!0});function n6({options:r={},peerId:e,multiaddrs:t=[],repo:n,keychainConfig:i={},config:o={}}){let{datastore:s}=n,a=Dqe({options:r,config:o,datastore:s,keychainConfig:i,peerId:e,multiaddrs:t});return typeof r.libp2p=="function"?r.libp2p({libp2pOptions:a,options:r,config:o,datastore:s,peerId:e}):(a.start=!1,i1e(a))}function Dqe({options:r,config:e,datastore:t,keychainConfig:n,peerId:i,multiaddrs:o}){var d,p,g,w;let s=()=>{let _=(0,lr.default)(e,"Pubsub.Router")||"gossipsub",x=Wae();if(!x[_])throw(0,Ige.default)(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${_} router.`),"ERR_NOT_SUPPORTED");return x[_]},a={datastore:t,peerId:i},c={addresses:{listen:o.map(_=>_.toString()),announce:(0,lr.default)(r,"addresses.announce",(0,lr.default)(e,"Addresses.Announce",[])),noAnnounce:(0,lr.default)(r,"addresses.noAnnounce",(0,lr.default)(e,"Addresses.NoAnnounce",[]))},connectionManager:(0,lr.default)(r,"connectionManager",{maxConnections:(0,lr.default)(r,"config.Swarm.ConnMgr.HighWater",(0,lr.default)(e,"Swarm.ConnMgr.HighWater")),minConnections:(0,lr.default)(r,"config.Swarm.ConnMgr.LowWater",(0,lr.default)(e,"Swarm.ConnMgr.LowWater"))}),keychain:n,identify:{host:{agentVersion:`js-ipfs/${hp}`}},contentRouters:[],peerRouters:[],peerDiscovery:[],transports:[],streamMuxers:[S2e({maxInboundStreams:256,maxOutboundStreams:1024})],connectionEncryption:[Tge()],relay:{enabled:(0,lr.default)(r,"relay.enabled",(0,lr.default)(e,"relay.enabled",!0)),hop:{enabled:(0,lr.default)(r,"relay.hop.enabled",(0,lr.default)(e,"relay.hop.enabled",!1)),active:(0,lr.default)(r,"relay.hop.active",(0,lr.default)(e,"relay.hop.active",!1))}},nat:{enabled:!(0,lr.default)(e,"Swarm.DisableNatPortMap",!1)}};(0,lr.default)(r,"config.Pubsub.Enabled",(0,lr.default)(e,"Pubsub.Enabled",!0))&&(c.pubsub=s()),(0,lr.default)(e,"Routing.Type","dhtclient")!=="none"&&(c.dht=Q1e({clientMode:(0,lr.default)(e,"Routing.Type","dht")!=="dhtserver",kBucketSize:(0,lr.default)(r,"dht.kBucketSize",20),validators:{ipns:pm},selectors:{ipns:x_}}));let u=(0,lr.default)(r,"config.Bootstrap",(0,lr.default)(e,"Bootstrap",[]));u.length>0&&((d=c.peerDiscovery)==null||d.push(X1e({list:u})));let l=(0,lr.default)(r,"libp2p",void 0);typeof l=="function"&&(l=void 0);let f=Nqe(a,Jfe(),c,l),h=(0,lr.default)(r,"config.Addresses.Delegates",(0,lr.default)(e,"Addresses.Delegates",[]));if(h.length>0){let _=h[Math.floor(Math.random()*h.length)],x=yt(_).toOptions(),m={host:x.host,protocol:parseInt(x.port)===443?"https":"http",port:x.port},y=efe(m);(p=f.contentRouters)==null||p.push(ace(y)),(g=f.peerRouters)==null||g.push(nce(y))}return(0,lr.default)(r,"config.Discovery.MDNS.Enabled",(0,lr.default)(e,"Discovery.MDNS.Enabled",!0))||(f.peerDiscovery=(w=f.peerDiscovery)==null?void 0:w.filter(_=>{try{if(typeof _=="function")return _({})[Symbol.toStringTag]!=="@libp2p/mdns"}catch{}return!0})),f.transports==null&&(f.transports=[]),f.transports.find(_=>{try{if(typeof _=="function")return _({})[Symbol.toStringTag]==="@libp2p/websockets"}catch{}return!1})==null&&f.transports.push(bme()),f}var _U;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(_U||(_U={}));var Rge=async()=>{let r=await Xb("Ed25519"),e=await Pge(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};var Cge=async r=>{let e=await Xb("RSA",(r==null?void 0:r.bits)??2048),t=await Pge(e);if(t.type==="RSA")return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function Pge(r){return Hn(a3(r.public),HC(r))}var EU=C(ee(),1);var Nge=et.bind({ignoreUndefined:!0}),i6=j("ipfs:components:peer:storage"),Og=class{constructor(e,t,n,i,o){this.print=i,this.peerId=e,this.keychain=t,this.repo=n,this.print=i,this.isNew=o}static async start(e,t,n){let{repoAutoMigrate:i,repo:o,onMigrationProgress:s}=n,a=typeof o=="string"||o==null?kse(e,t,{path:o,autoMigrate:i,onMigrationProgress:s}):o,{peerId:c,keychain:u,isNew:l}=await Oqe(e,a,n);return new Og(c,u,a,e,l)}},Oqe=async(r,e,t)=>{if(!e.closed)return{...await kge(e,t),isNew:!1};try{return await e.open(),{...await kge(e,t),isNew:!1}}catch(n){if(n.code!==Pp)throw n;if(t.init&&t.init.allowNew===!1)throw new Na("Initialization of new repos disabled by config, pass `config.init.isNew: true` to enable it");return{...await Lqe(r,e,t),isNew:!0}}},Lqe=async(r,e,t)=>{let n=t.init||{},i=await e.exists();if(i6("repo exists?",i),i===!0)throw new Error("repo already exists");let o=n.privateKey?await Bqe(n.privateKey):await Mqe(r,n),s=Uqe(o);i6("peer identity: %s",s.PeerID);let a={...Nge(Dge(cl(),n.profiles),t.config),Identity:s};await e.init(a),await e.open(),i6("repo opened");let c={pass:t.pass};try{c.dek=await e.config.get("Keychain.DEK")}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}let u=await n6({options:void 0,multiaddrs:void 0,peerId:o,repo:e,config:a,keychainConfig:c});return await e.datastore.has(new pe("/info/self"))||await u.keychain.importPeer("self",o),await e.config.set("Keychain",{DEK:u.keychain.init.dek}),{peerId:o,keychain:u.keychain}},Bqe=async r=>{if(i6("using user-supplied private-key"),Lf(r))return r;let e=Ie(r,"base64pad"),t=await Li(e);return await Hn(t.public.bytes,t.bytes)},Mqe=(r,{algorithm:e="Ed25519",bits:t=2048})=>{if(r("generating %s keypair...",e),e==="Ed25519")return Rge();if(e==="RSA")return Cge({bits:t});throw(0,EU.default)(new Error("Unknown PeerId algorithm"),"ERR_UNKNOWN_PEER_ID_ALGORITHM")},Uqe=r=>{if(r.privateKey==null)throw(0,EU.default)(new Error("Private key missing"),"ERR_MISSING_PRIVATE_KEY");return{PeerID:r.toString(),PrivKey:re(r.privateKey,"base64pad")}},kge=async(r,e)=>{let t=e.config,n=e.init&&e.init.profiles||[],i=e.pass,o=await r.config.getAll(),s=Fqe(Dge(o,n),t);if(o!==s&&await r.config.replace(s),!s.Identity||!s.Identity.PrivKey)throw new Ku("No private key was found in the config, please intialize the repo");let a=Ie(s.Identity.PrivKey,"base64pad"),c=await Li(a),u=await Hn(c.public.bytes,c.bytes),l=await n6({options:void 0,multiaddrs:void 0,peerId:u,repo:r,config:s,keychainConfig:{pass:i,...s.Keychain}});return{peerId:u,keychain:l.keychain}},Fqe=(r,e)=>e?Nge(r,e):r,Dge=(r,e)=>(e||[]).reduce((t,n)=>{let i=Fm[n];if(!i)throw new Error(`Could not find profile with name '${n}'`);return i6("applying profile %s",n),i.transform(t)},r);var Qge=C(jge(),1);var o6=C(Xo(),1);function Jqe(r){let e=new Uint8Array(r.reduce((n,i)=>n+o6.default.encodingLength(i),0)),t=0;for(let n of r)e=o6.encode(n,e,t),t+=o6.default.encodingLength(n);return e}var Wge=Jqe;var s6=class{constructor(e,t,n){this._refCounter=1,this.cid=e,this.priority=t||1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry `}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var lc=C(gc(),1),Iu=lc.default.Reader,a6=lc.default.Writer,ir=lc.default.util,qt=lc.default.roots["ipfs-bitswap"]||(lc.default.roots["ipfs-bitswap"]={}),Ss=qt.Message=(()=>{function r(e){if(this.blocks=[],this.payload=[],this.blockPresences=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:{o.wantlist=qt.Message.Wantlist.decode(t,t.uint32());break}case 2:{o.blocks&&o.blocks.length||(o.blocks=[]),o.blocks.push(t.bytes());break}case 3:{o.payload&&o.payload.length||(o.payload=[]),o.payload.push(qt.Message.Block.decode(t,t.uint32()));break}case 4:{o.blockPresences&&o.blockPresences.length||(o.blockPresences=[]),o.blockPresences.push(qt.Message.BlockPresence.decode(t,t.uint32()));break}case 5:{o.pendingBytes=t.int32();break}default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof qt.Message)return t;var n=new qt.Message;if(t.wantlist!=null){if(typeof t.wantlist!="object")throw TypeError(".Message.wantlist: object expected");n.wantlist=qt.Message.Wantlist.fromObject(t.wantlist)}if(t.blocks){if(!Array.isArray(t.blocks))throw TypeError(".Message.blocks: array expected");n.blocks=[];for(var i=0;i=0&&(n.blocks[i]=t.blocks[i])}if(t.payload){if(!Array.isArray(t.payload))throw TypeError(".Message.payload: array expected");n.payload=[];for(var i=0;i>>3){case 1:{s.entries&&s.entries.length||(s.entries=[]),s.entries.push(qt.Message.Wantlist.Entry.decode(n,n.uint32()));break}case 2:{s.full=n.bool();break}default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof qt.Message.Wantlist)return n;var i=new qt.Message.Wantlist;if(n.entries){if(!Array.isArray(n.entries))throw TypeError(".Message.Wantlist.entries: array expected");i.entries=[];for(var o=0;o>>3){case 1:{a.block=i.bytes();break}case 2:{a.priority=i.int32();break}case 3:{a.cancel=i.bool();break}case 4:{a.wantType=i.int32();break}case 5:{a.sendDontHave=i.bool();break}default:i.skipType(c&7);break}}return a},t.fromObject=function(i){if(i instanceof qt.Message.Wantlist.Entry)return i;var o=new qt.Message.Wantlist.Entry;switch(i.block!=null&&(typeof i.block=="string"?ir.base64.decode(i.block,o.block=ir.newBuffer(ir.base64.length(i.block)),0):i.block.length>=0&&(o.block=i.block)),i.priority!=null&&(o.priority=i.priority|0),i.cancel!=null&&(o.cancel=!!i.cancel),i.wantType){case"Block":case 0:o.wantType=0;break;case"Have":case 1:o.wantType=1;break}return i.sendDontHave!=null&&(o.sendDontHave=!!i.sendDontHave),o},t.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(o.bytes===String?s.block="":(s.block=[],o.bytes!==Array&&(s.block=ir.newBuffer(s.block))),s.priority=0,s.cancel=!1,s.wantType=o.enums===String?"Block":0,s.sendDontHave=!1),i.block!=null&&i.hasOwnProperty("block")&&(s.block=o.bytes===String?ir.base64.encode(i.block,0,i.block.length):o.bytes===Array?Array.prototype.slice.call(i.block):i.block),i.priority!=null&&i.hasOwnProperty("priority")&&(s.priority=i.priority),i.cancel!=null&&i.hasOwnProperty("cancel")&&(s.cancel=i.cancel),i.wantType!=null&&i.hasOwnProperty("wantType")&&(s.wantType=o.enums===String?qt.Message.Wantlist.WantType[i.wantType]:i.wantType),i.sendDontHave!=null&&i.hasOwnProperty("sendDontHave")&&(s.sendDontHave=i.sendDontHave),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,lc.default.util.toJSONOptions)},t.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/Message.Wantlist.Entry"},t}(),e}(),r.Block=function(){function e(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:{s.prefix=n.bytes();break}case 2:{s.data=n.bytes();break}default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof qt.Message.Block)return n;var i=new qt.Message.Block;return n.prefix!=null&&(typeof n.prefix=="string"?ir.base64.decode(n.prefix,i.prefix=ir.newBuffer(ir.base64.length(n.prefix)),0):n.prefix.length>=0&&(i.prefix=n.prefix)),n.data!=null&&(typeof n.data=="string"?ir.base64.decode(n.data,i.data=ir.newBuffer(ir.base64.length(n.data)),0):n.data.length>=0&&(i.data=n.data)),i},e.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.prefix="":(o.prefix=[],i.bytes!==Array&&(o.prefix=ir.newBuffer(o.prefix))),i.bytes===String?o.data="":(o.data=[],i.bytes!==Array&&(o.data=ir.newBuffer(o.data)))),n.prefix!=null&&n.hasOwnProperty("prefix")&&(o.prefix=i.bytes===String?ir.base64.encode(n.prefix,0,n.prefix.length):i.bytes===Array?Array.prototype.slice.call(n.prefix):n.prefix),n.data!=null&&n.hasOwnProperty("data")&&(o.data=i.bytes===String?ir.base64.encode(n.data,0,n.data.length):i.bytes===Array?Array.prototype.slice.call(n.data):n.data),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,lc.default.util.toJSONOptions)},e.getTypeUrl=function(n){return n===void 0&&(n="type.googleapis.com"),n+"/Message.Block"},e}(),r.BlockPresenceType=function(){let e={},t=Object.create(e);return t[e[0]="Have"]=0,t[e[1]="DontHave"]=1,t}(),r.BlockPresence=function(){function e(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:{s.cid=n.bytes();break}case 2:{s.type=n.int32();break}default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof qt.Message.BlockPresence)return n;var i=new qt.Message.BlockPresence;switch(n.cid!=null&&(typeof n.cid=="string"?ir.base64.decode(n.cid,i.cid=ir.newBuffer(ir.base64.length(n.cid)),0):n.cid.length>=0&&(i.cid=n.cid)),n.type){case"Have":case 0:i.type=0;break;case"DontHave":case 1:i.type=1;break}return i},e.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.cid="":(o.cid=[],i.bytes!==Array&&(o.cid=ir.newBuffer(o.cid))),o.type=i.enums===String?"Have":0),n.cid!=null&&n.hasOwnProperty("cid")&&(o.cid=i.bytes===String?ir.base64.encode(n.cid,0,n.cid.length):i.bytes===Array?Array.prototype.slice.call(n.cid):n.cid),n.type!=null&&n.hasOwnProperty("type")&&(o.type=i.enums===String?qt.Message.BlockPresenceType[n.type]:n.type),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,lc.default.util.toJSONOptions)},e.getTypeUrl=function(n){return n===void 0&&(n="type.googleapis.com"),n+"/Message.BlockPresence"},e}(),r})();var Yge={Block:Ss.Wantlist.WantType.Block,Have:Ss.Wantlist.WantType.Have},eHe=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),o=r(n);return io?1:0}),fc=class{constructor(e,t){this.set=t?bs({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(tt),o=this.set.get(i);o?(o.inc(),o.priority=t,o.wantType===Yge.Have&&n===Yge.Block&&(o.wantType=n)):(this.set.set(i,new s6(e,t,n)),this._stats&&this._stats.push(null,"wantListSize",1))}remove(e){let t=e.toString(tt),n=this.set.get(t);n&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats&&this._stats.push(null,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){return this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(eHe(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(tt);return this.set.has(t)}get(e){let t=e.toString(tt);return this.set.get(t)}};fc.Entry=s6;var tHe=fc.Entry,ah=class{constructor(e,t,n,i,o){this.entry=new tHe(e,t,n),this.cancel=!!i,this.sendDontHave=!!o}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(tt)} `}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var ba=(r,e)=>{let t=["bitswap"];return e&&t.push(e),r&&t.push(`${r.toString().slice(0,8)}`),ue(t.join(":"))};var DS=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!rr(n,i)||n instanceof ah&&i instanceof ah&&!n.equals(i))return!1}return!0};var fr=class{constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,o){n==null&&(n=fr.WantType.Block);let s=e.toString(tt),a=this.wantlist.get(s);a?(a.wantType===n&&(a.priority=t),i&&(a.cancel=!!i),o&&(a.sendDontHave=!!o),n===fr.WantType.Block&&a.wantType===fr.WantType.Have&&(a.wantType=n)):this.wantlist.set(s,new ah(e,t,n,i,o))}addBlock(e,t){let n=e.toString(tt);this.blocks.set(n,t)}addHave(e){let t=e.toString(tt);this.blockPresences.has(t)||this.blockPresences.set(t,fr.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(tt);this.blockPresences.has(t)||this.blockPresences.set(t,fr.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(tt);this.wantlist.delete(t),this.addEntry(e,0,fr.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),cancel:!!t.cancel})),full:this.full?!0:void 0},blocks:Array.from(this.blocks.values())};return Ss.encode(e).finish()}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:this.full?!0:void 0},blockPresences:[],payload:[],pendingBytes:this.pendingBytes};for(let[t,n]of this.blocks.entries()){let i=ce.parse(t),o=i.version,s=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=Wge([o,s,a,c]);e.payload.push(new Ss.Block({prefix:u,data:n}))}for(let[t,n]of this.blockPresences)e.blockPresences.push(new Ss.BlockPresence({cid:ce.parse(t).bytes,type:n}));return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),Ss.encode(e).finish()}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!DS(this.wantlist,e.wantlist)||!DS(this.blocks,e.blocks)||!DS(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage `}};fr.deserialize=async(r,e)=>{let t=Ss.decode(r),n=t.wantlist&&t.wantlist.full||!1,i=new fr(n);return t.wantlist&&t.wantlist.entries&&t.wantlist.entries.forEach(o=>{if(!o.block)return;let s=ce.decode(o.block);i.addEntry(s,o.priority||0,o.wantType,!!o.cancel,!!o.sendDontHave)}),t.blockPresences&&t.blockPresences.forEach(o=>{if(!o.cid)return;let s=ce.decode(o.cid);o.type===fr.BlockPresenceType.Have?i.addHave(s):i.addDontHave(s)}),t.blocks.length>0?(await Promise.all(t.blocks.map(async o=>{let s=await mr.digest(o),a=ce.createV0(s);i.addBlock(a,o)})),i):(t.payload.length>0&&(await Promise.all(t.payload.map(async o=>{if(!o.prefix||!o.data)return;let s=(0,Qge.default)(o.prefix),a=s[0],c=s[1],u=s[2],l=u===mr.code?mr:e&&await e.getHasher(u);if(!l)throw new We("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await l.digest(o.data),h=ce.create(a,c,f);i.addBlock(h,o.data)})),i.setPendingBytes(t.pendingBytes)),i)};fr.blockPresenceSize=r=>r.bytes.length+1;fr.Entry=ah;fr.WantType={Block:Ss.Wantlist.WantType.Block,Have:Ss.Wantlist.WantType.Have};fr.BlockPresenceType={Have:Ss.BlockPresenceType.Have,DontHave:Ss.BlockPresenceType.DontHave};var Xge=Math.pow(2,31)-1,Zge=1e3,Jge=1;var eye=rHe;function rHe(r,e,t){var n=null,i=null,o=function(){n&&(clearTimeout(n),i=null,n=null)},s=function(){var c=i;o(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,u=arguments,l=t&&!n;if(o(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var f=i;return i=null,f()}},e),l)return i()};return a.cancel=o,a.flush=s,a}var OS=class{constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=ba(e,"msgqueue"),this.sendEntries=eye(this._sendEntries.bind(this),Jge)}addMessage(e){e.empty||this.send(e)}addEntries(e){this._entries=this._entries.concat(e),this.sendEntries()}_sendEntries(){if(!this._entries.length)return;let e=new fr(!1);this._entries.forEach(t=>{t.cancel?e.cancel(t.cid):e.addEntry(t.cid,t.priority)}),this._entries=[],this.addMessage(e)}async send(e){try{await this.network.connectTo(this.peerId)}catch(t){this._log.error("cant connect to peer %s: %s",this.peerId.toString(),t.message);return}this._log("sending message to peer %s",this.peerId.toString()),this.network.sendMessage(this.peerId,e).catch(t=>{this._log.error("send error: %s",t.message)})}};var LS=class{constructor(e,t,n,i){this.peers=bs({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new fc(n,i),this.network=t,this._stats=n,this._peerId=e,this._log=ba(e,"want")}_addEntries(e,t,n){let i=e.map((o,s)=>new fr.Entry(o,Xge-s,fr.WantType.Block,t));i.forEach(o=>{o.cancel?n?this.wantlist.removeForce(o.cid.toString(tt)):this.wantlist.remove(o.cid):(this._log("adding to wl"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t){t.refcnt++;return}t=new OS(this._peerId,e,this.network);let n=new fr(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1),t&&t.signal&&t.signal.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>this.disconnected(e.peerId))}};var tye=()=>{},SU=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??tye,this.onDisconnect=e.onDisconnect??tye}get[Symbol.toStringTag](){return W9.toString()}get[W9](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function rye(r){return new SU(r)}var nye=C(Kn(),1);var AU="/ipfs/bitswap/1.0.0",TU="/ipfs/bitswap/1.1.0",IU="/ipfs/bitswap/1.2.0",iHe=32,oHe=128,sHe=3e4,BS=class{constructor(e,t,n,i={}){this._log=ba(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[AU],i.b100Only||(this._protocols.unshift(TU),this._protocols.unshift(IU)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader,this._maxInboundStreams=i.maxInboundStreams??iHe,this._maxOutboundStreams=i.maxOutboundStreams??oHe,this._incomingStreamTimeout=i.incomingStreamTimeout??sHe}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=rye({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(t.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let e of this._registrarIds)this._libp2p.unregister(e);this._registrarIds=[]}}_onConnection({stream:e,connection:t}){if(!this._running)return;let n=new nye.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",e.stat.protocol,t.remotePeer),await Ne(sa(e.source,n.signal),Xr(),async i=>{for await(let o of i){try{let s=await fr.deserialize(o.subarray(),this._hashLoader);await this._bitswap._receiveMessage(t.remotePeer,s)}catch(s){this._bitswap._receiveError(s);break}n.reset()}})}).catch(i=>{this._log(i),e.abort(i)}).finally(()=>{n.clear(),e.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){let n=[],i=0;for await(let o of this.findProviders(e,t))if(this._log(`connecting to provider ${o.id}`),n.push(this.connectTo(o.id,t).catch(s=>{this._log.error(s)})),i++,i===3)break;await Promise.all(n)}async provide(e,t){await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t){if(!this._running)throw new Error("network isn't running");let n=e.toString();this._log("sendMessage to %s",n,t);let o=await(await this._libp2p.dial(e)).newStream([IU,TU,AU]);await aHe(o,t,this._log),this._updateSentStats(e,t.blocks)}async connectTo(e,t){if(!this._running)throw new Error("network isn't running");return this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}};async function aHe(r,e,t){try{let n;switch(r.stat.protocol){case AU:n=e.serializeToBitswap100();break;case TU:case IU:n=e.serializeToBitswap110();break;default:throw new Error("Unknown protocol: "+r.stat.protocol)}await Ne([n],vn(),r)}catch(n){t(n)}finally{r.close()}}var MS=class{constructor(e){this.partner=e,this.wantlist=new fc,this.exchangeCount=0,this.sentToPeer=new Map,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var c6=class extends Map{constructor(e,t){super(),this._cmp=t||this._defaultSort,this._keys=[];for(let[n,i]of e||[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n>>1,o=this._kCmp(this._keys[i],e);if(o<0)t=i+1;else if(o>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t){if(e)for(let n of this._keys)e.apply(t,[[n,this.get(n)]])}_defaultSort(e,t){return e[0]t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let o=0;oe+t.task.size,0)}get(e){return(this._tasks.get(e)||{}).task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(!n)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var iye={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var oye=fr.WantType,uHe=16*1024,lHe=1024,zS=class{constructor(e,t,n,i,o,s={}){this._log=ba(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(s),this.ledgerMap=bs({name:"ipfs_bitswap_ledger_map",metrics:o.metrics}),this._running=!1,this._requestQueue=new US(iye)}_processOpts(e){return{maxSizeReplaceHasWithBlock:lHe,targetMessageSize:uHe,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks()})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new fr(!1);i.setPendingBytes(n);let o=[],s=new Map;for(let c of t){let u=ce.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(o.push(u),s.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(o);for(let[c,u]of s){let l=ce.parse(c),f=a.get(c);f?i.addBlock(l,f):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e&&this.messageSent(e,ce.parse(c),u)}catch(c){this._log.error(c)}e&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n?{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}:null}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length){for(let t of this.ledgerMap.values())for(let n of e){let i=t.wantlistContains(n.cid);if(!i)continue;let o=n.data.length,s=this._sendAsBlock(i.wantType,o),a=o;s||(a=fr.blockPresenceSize(i.cid)),this._requestQueue.pushTasks(t.partner,[{topic:i.cid.toString(tt),priority:i.priority,size:a,data:{blockSize:o,isWantBlock:s,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new fc),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],o=[];t.wantlist.forEach(s=>{s.cancel?(n.cancelWant(s.cid),i.push(s.cid)):(n.wants(s.cid,s.priority,s.wantType),o.push(s))}),this._cancelWants(e,i),await this._addWants(e,o),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(tt),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(o=>o.cid)),i=[];for(let o of t){let s=o.cid.toString(tt),a=n.get(s);if(a==null)o.sendDontHave&&i.push({topic:s,priority:o.priority,size:fr.blockPresenceSize(o.cid),data:{isWantBlock:o.wantType===oye.Block,blockSize:0,haveBlock:!1,sendDontHave:o.sendDontHave}});else{let c=this._sendAsBlock(o.wantType,a),u=a;c||(u=fr.blockPresenceSize(o.cid)),i.push({topic:s,priority:o.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:o.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===oye.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(tt),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n)return n;let i=new MS(e);return this.ledgerMap.set(t,i),this._stats&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var cye=C(xi(),1);var sye=r=>`unwant:${Ee(r.multihash.bytes,"base64")}`,aye=r=>`block:${Ee(r.multihash.bytes,"base64")}`,VS=class extends cye.EventEmitter{constructor(e){super(),this.setMaxListeners(Zge),this._log=ba(e,"notif")}hasBlock(e,t){let n=aye(e);this._log(n),this.emit(n,t)}wantBlock(e,t={}){if(!e)throw new Error("Not a valid cid");let n=aye(e),i=sye(e);return this._log(`wantBlock:${e}`),new Promise((o,s)=>{let a=()=>{this.removeListener(n,c),s(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),o(u)};this.once(i,a),this.once(n,c),t&&t.signal&&t.signal.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),s(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=sye(e);this._log(t),this.emit(t)}};var pye=C(xi(),1);var dye=C(xi(),1),CU=C(fye(),1),u6=class extends dye.EventEmitter{constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,CU.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._disabled=!0}stop(){this._timeout&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=null,this._queue.length){let e;for(;this._queue.length;){let t=e=this._queue.shift();t&&this._applyOp(t)}e&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]||0;this._frequencyAccumulators[e]=0;let o=i/t*1e3,s=this._movingAverages[e];s||(s=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=s[a];c||(c=s[a]=(0,CU.default)(a)),c.push(n,o)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]||(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var hye={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},KS=class extends pye.EventEmitter{constructor(e,t=[],n=hye){super();let i=Object.assign({},hye,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new u6(t,i),this._global.on("update",o=>this.emit("update",o)),this._peers=bs({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=typeof e!="string"&&e.toString?e.toString():`${e}`;return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e)){let i=this._peers.get(e);i||(i=new u6(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n&&(n.stop(),this._peers.delete(t))}};var mye=C(Da(),1);var dHe={statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},hHe=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],$S=class extends uu{constructor(e,t,n={}){super(),this._libp2p=e,this._log=ba(this.peerId),this._options=Object.assign({},dHe,n),this._stats=new KS(e,hHe,{enabled:this._options.statsEnabled,computeThrottleTimeout:this._options.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:this._options.statsComputeThrottleMaxQueueSize}),this.network=new BS(e,this,this._stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new zS(this.peerId,t,this.network,this._stats,e),this.wm=new LS(this.peerId,this.network,this._stats,e),this.notifications=new VS(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,o]of t.blocks.entries()){let s=ce.parse(i);n.push({wasWanted:this.wm.wantlist.contains(s),cid:s,data:o})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(({cid:i,wasWanted:o,data:s})=>this._handleReceivedBlock(e,i,s,o)))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let o=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,o),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this._stats.push(e,"blocksReceived",1),this._stats.push(e,"dataReceived",n.length),i&&(this._stats.push(e,"dupBlksReceived",1),this._stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError: %s",e.message)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this._stats.disconnected(e)}enableStats(){this._stats.enable()}disableStats(){this._stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async get(e,t={}){let n=(c,u)=>(this.wm.wantBlocks([c],u),this.notifications.wantBlock(c,u)),i=!1,o=async(c,u)=>{try{return await this.blockstore.get(c,u)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return i||(i=!0,this.network.findAndConnect(c,u).catch(f=>this._log.error(f))),n(c,u)}},s=new AbortController,a=t.signal?(0,mye.anySignal)([t.signal,s.signal]):s.signal;try{return await Promise.race([this.notifications.wantBlock(e,{signal:a}),o(e,{signal:a})])}finally{s.abort()}}async*getMany(e,t={}){for await(let n of e)yield this.get(n,t)}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>this.notifications.unwantBlock(n))}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this._sendHaveBlockNotifications(e,t)}async*putMany(e,t){for await(let{key:n,value:i}of this.blockstore.putMany(e,t))this._sendHaveBlockNotifications(n,i),yield{key:n,value:i}}_sendHaveBlockNotifications(e,t){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,data:t}]),this.network.provide(e).catch(n=>{this._log.error("Failed to provide: %s",n.message)})}getWantlist(){return this.wm.wantlist.entries()}peers(){return this.engine.peers()}stat(){return this._stats}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this._stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}unwrap(){return this.blockstore}has(e){return this.blockstore.has(e)}};var gye=(r,e,t={})=>new $S(r,e,t);var wye=C(ee(),1);var qS={};xe(qS,{abortedError:()=>pHe,notFoundError:()=>yye});var PU=C(ee(),1);function yye(r){return r=r||new Error("Not Found"),(0,PU.default)(r,"ERR_NOT_FOUND")}function pHe(r){return r=r||new Error("Aborted"),(0,PU.default)(r,"ERR_ABORTED")}var yur={...qS};var HS=class extends uu{constructor(e,t){super(),this.child=e,this.bitswap=t}open(){return this.child.open()}close(){return this.child.close()}unwrap(){return this.child}async put(e,t,n={}){await this.has(e)||(this.bitswap.isStarted()?await this.bitswap.put(e,t,n):await this.child.put(e,t,n))}async*putMany(e,t={}){let n=M3(e,async({key:i})=>!await this.has(i));this.bitswap.isStarted()?yield*this.bitswap.putMany(n,t):yield*this.child.putMany(n,t)}async get(e,t={}){return!await this.has(e)&&this.bitswap.isStarted()?this.bitswap.get(e,t):this.child.get(e,t)}async*getMany(e,t={}){let n=Ao({objectMode:!0}),i=Ao({objectMode:!0});Promise.resolve().then(async()=>{for await(let o of e)!await this.has(o)&&this.bitswap.isStarted()?n.push(o):i.push(o);n.end(),i.end()}),yield*ga(this.bitswap.getMany(n,t),this.child.getMany(i,t))}async delete(e,t){await this.child.delete(e,t)}async*deleteMany(e,t){yield*this.child.deleteMany(e,t)}async has(e,t={}){return this.child.has(e,t)}async*query(e,t={}){yield*this.child.query(e,t)}async*queryKeys(e,t={}){yield*this.child.queryKeys(e,t)}};var Lg=class{constructor(e,t,n,i,o){this.peerId=e,this.libp2p=t,this.bitswap=n,this.repo=i,this.blockstore=o}static async start({peerId:e,repo:t,print:n,hashers:i,options:o}){t.closed&&await t.open();let s=await t.config.getAll(),a=await n6({options:o,repo:t,peerId:e,multiaddrs:mHe(e,s),config:s,keychainConfig:void 0});await a.start();for(let l of a.getMultiaddrs())n(`Swarm listening on ${l.toString()}`);let c=gye(a,t.blocks,{statsEnabled:!0,hashLoader:i,maxInboundStreams:1024,maxOutboundStreams:1024});await c.start();let u=new HS(t.blocks,c);return t.blocks=u,t.pins.blockstore=u,new Lg(e,a,c,t,u)}static async stop(e){e.repo.blocks=e.blockstore.unwrap(),e.repo.pins.blockstore=e.blockstore.unwrap(),await e.bitswap.stop(),await e.libp2p.stop()}},mHe=(r,e)=>{let t=r.toString(),n=[],i=e.Addresses&&e.Addresses.Swarm||[];for(let o of i){let s=yt(o);if(s.protoCodes().includes(gHe))throw(0,wye.default)(new Error("websocket-star swarm addresses are not supported. See https://github.com/ipfs/js-ipfs/issues/2779"),"ERR_WEBSOCKET_STAR_SWARM_ADDR_NOT_SUPPORTED");let a=s.getPeerId();a&&a!==t&&(s=s.encapsulate(`/p2p/${t}`)),n.push(s)}return n},gHe=479;function bye({network:r}){async function e(t={}){let n=[],{libp2p:i}=await r.use(t);return await i.peerStore.forEach(o=>{n.push({id:o.id,addrs:o.addresses.map(s=>s.multiaddr)})}),n}return $(e)}function _ye({network:r}){async function e(t,n={}){let{libp2p:i}=await r.use(n);await i.dial(t,n)}return $(e)}function Eye({network:r}){async function e(t,n={}){let{libp2p:i}=await r.use(n);await i.hangUp(t)}return $(e)}function vye({network:r}){async function e(t={}){let{libp2p:n}=await r.use(t);return n.getMultiaddrs()}return $(e)}function xye({network:r}){async function e(t={}){let{libp2p:n}=await r.use(t);if(t.verbose){let o=[];for(let s of n.getConnections()){let a={addr:s.remoteAddr,peer:s.remotePeer};(t.verbose||t.direction)&&(a.direction=s.stat.direction),t.verbose&&(a.muxer=s.stat.multiplexer,a.latency="n/a",a.streams=[]),o.push(a)}return o}let i=new Map;for(let o of n.getConnections()){let s={addr:o.remoteAddr,peer:o.remotePeer};i.set(o.remotePeer.toString(),s)}return Array.from(i.values())}return $(e)}var GS=class{constructor({network:e}){this.addrs=bye({network:e}),this.connect=_ye({network:e}),this.disconnect=Eye({network:e}),this.localAddrs=vye({network:e}),this.peers=xye({network:e})}};var l6={success:!0,time:0,text:""};function Sye({network:r}){async function*e(t,n={}){let{libp2p:i}=await r.use();n.count=n.count||10;let o=await i.peerStore.get(t),s=o&&o.id;if(!s){yield{...l6,text:`Looking up peer ${t}`};let u=await i.peerRouting.findPeer(t);s=u&&u.id}if(!s)throw new Error("Peer was not found");yield{...l6,text:`PING ${s.toString()}`};let a=0,c=0;for(let u=0;u{let n=await r.use(t);if(n.libp2p.dht!=null)return n;{let i=async function*(){yield{from:e,name:"QUERY_ERROR",type:3,error:new Na("dht not enabled")}};return{libp2p:{dht:{get:i,put:i,findProviders:i,findPeer:i,provide:i,getClosestPeers:i}}}}};var Iye=C(ee(),1);var Rye=C(v_(),1);function Cye({network:r,config:e}){let t=(0,Rye.default)(e||{},"Pubsub.Enabled",!0),n={},i;return{subscribe:t?$(o):f6,unsubscribe:t?$(s):f6,publish:t?$(a):f6,ls:t?$(c):f6,peers:t?$(u):f6};async function o(l,f,h={}){let{libp2p:d}=await r.use(h);d.pubsub.subscribe(l),i==null&&(i=p=>{let g=p.detail;n[g.topic]&&n[g.topic].forEach(w=>{if(typeof w=="function"){w(g);return}w!=null&&w.handleEvent!=null&&w.handleEvent(g)})},d.pubsub.addEventListener("message",i)),f!=null&&(n[l]==null&&(n[l]=[]),n[l].push(f))}async function s(l,f,h={}){let{libp2p:d}=await r.use(h);f!=null&&n[l]!=null&&(n[l]=n[l].filter(p=>p!==f),n[l].length===0&&delete n[l]),typeof f!="function"&&delete n[l],n[l]==null&&d.pubsub.unsubscribe(l),Object.keys(n).length===0&&(d.pubsub.removeEventListener("message",i),i=void 0)}async function a(l,f,h={}){let{libp2p:d}=await r.use(h);if(!f)throw(0,Iye.default)(new Error('argument "data" is required'),"ERR_ARG_REQUIRED");await d.pubsub.publish(l,f)}async function c(l={}){let{libp2p:f}=await r.use(l);return f.pubsub.getTopics()}async function u(l,f={}){let{libp2p:h}=await r.use(f);return h.pubsub.getSubscribers(l)}}var f6=async()=>{throw new Na("pubsub not enabled")};var yHe=et.bind({ignoreUndefined:!0}),ch=j("ipfs"),wHe=3e4,NU=class{constructor({print:e,storage:t,codecs:n,options:i}){let{peerId:o,repo:s,keychain:a}=t,c=Pi.create(Lg),u=rre(i.preload),l=pG(),f=mG({network:c}),h=new R_(i),d=Object.values(v8);(i.ipld&&i.ipld.hashers?i.ipld.hashers:[]).forEach(G=>d.push(G)),this.hashers=new V2({hashers:d,loadHasher:i.ipld&&i.ipld.loadHasher});let p=Object.values(Vu);(i.ipld&&i.ipld.bases?i.ipld.bases:[]).forEach(G=>p.push(G)),this.bases=new F2({bases:p,loadBase:i.ipld&&i.ipld.loadBase});let g=new ab({repo:s,codecs:n}),w=new $_({codecs:n,hashers:this.hashers,preload:u,repo:s}),_=new k_({dns:l,ipns:h,repo:s,codecs:n,peerId:o,isOnline:f,keychain:a,options:i}),x=wG({repo:s,codecs:n,bases:this.bases,name:_}),m=new HE({repo:s,codecs:n,hashers:this.hashers,preload:u}),y=Object.assign(bX({repo:s,codecs:n,resolve:x,preload:u}),{local:_X({repo:t.repo})}),{add:b,addAll:E,cat:v,get:S,ls:A}=new BE({preload:u,repo:s,options:i.EXPERIMENTAL,hashers:this.hashers}),I=Gre({repo:s,preload:u,hashers:this.hashers,options:i}),k=nre({files:I,preload:u,options:i.preload});this.preload=u,this.name=_,this.ipns=h,this.pin=g,this.resolve=x,this.block=w,this.refs=y,this.start=DH({network:c,peerId:o,repo:s,preload:u,ipns:h,mfsPreload:k,print:e,keychain:a,hashers:this.hashers,options:i}),this.stop=OH({network:c,preload:u,mfsPreload:k,ipns:h,repo:s}),this.dht=Tye({network:c,repo:s,peerId:o}),this.pubsub=Cye({network:c,config:i.config}),this.dns=l,this.isOnline=f,this.id=Ste({network:c,peerId:o}),this.version=xte({repo:s}),this.bitswap=new D_({network:c}),this.bootstrap=new z_({repo:s}),this.config=Tte({repo:s}),this.ping=Sye({network:c}),this.add=b,this.addAll=E,this.cat=v,this.get=S,this.ls=A,this.dag=m,this.files=I,this.key=new c7({keychain:a}),this.object=new l7({preload:u,codecs:n,repo:s}),this.repo=new d7({repo:s,hashers:this.hashers}),this.stats=new h7({repo:s,network:c}),this.swarm=new GS({network:c}),Object.defineProperty(this,"libp2p",{get(){let G=c.try();return G?G.libp2p:void 0}});let N=()=>Promise.reject((0,jS.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")),O=async function*(){throw(0,jS.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")};this.commands=N,this.diag={cmds:N,net:N,sys:N},this.log={level:N,ls:N,tail:O},this.mount=N,this.codecs=n}async init(){throw new ka}},bHe=async r=>{let e=pt({Data:new st({type:"directory"}).marshal(),Links:[]}),t=await r.block.put(e,{mhtype:"sha2-256",format:"dag-pb"});return await r.pin.add(t),t},_He=()=>({start:!0,EXPERIMENTAL:{},preload:{enabled:!Pye.isTest,addresses:["/dns4/node0.preload.ipfs.io/https","/dns4/node1.preload.ipfs.io/https","/dns4/node2.preload.ipfs.io/https","/dns4/node3.preload.ipfs.io/https"]}});async function Nye(r={}){r=yHe(_He(),r);let e=r.init||{},t={name:Ii.name,code:Ii.code,encode:u=>u,decode:u=>u},n=Object.values(x8);[sr,o1,a1,yy,t].concat(r.ipld&&r.ipld.codecs||[]).forEach(u=>n.push(u));let i=new z2({codecs:n,loadCodec:r.ipld&&r.ipld.loadCodec}),o=r.silent?ch:console.log;ch("creating repo");let s=await Og.start(o,i,r);ch("getting repo config");let a=await s.repo.config.getAll(),c=new NU({storage:s,print:o,codecs:i,options:{...r,config:a}});if(ch("starting preload"),await c.preload.start(),ch("starting storage"),c.ipns.startOffline(s),s.isNew&&!e.emptyRepo){let u=await bHe(c);if(ch("adding default assets"),await(c.addAll,void 0),ch("initializing IPNS keyspace"),s.peerId.publicKey==null)throw(0,jS.default)(new Error("Public key missing"),"ERR_MISSING_PUBLIC_KEY");let l=new kye.TimeoutController(wHe);try{await c.ipns.initializeKeyspace(s.peerId,Ie(`/ipfs/${u}`),{signal:l.signal})}finally{l.clear()}}return r.start!==!1&&(ch("starting node"),await c.start()),c}var EHe=C(dL(),1),Dye=Nye;var Oye=(()=>({toString:function(r){return r.toV1().toString()},fromString:function(r){return z.parse(r)}}))();var WS=(()=>{let r;return{init:async()=>{r||(r=await Dye({repo:String(Math.random()+Date.now())}))},store:async function(e,t){await this.init();let n={path:e,content:t},i=await r.add(n),{cid:o}=i;return Oye.toString(o)},retrieve:async function(e){await this.init();let t=new TextDecoder,n="";for await(let i of r.cat(e))n+=t.decode(i,{stream:!0});return n}}})();var vHe=()=>{let r=Fe.get("gistId");return Fe.get("authToken")?r?"Sync: Notes with my GitHub Gist":"Sync: Pick your Gist to sync with":"Sync: Authorize your GitHub account for synchronisation"},xHe={title:"Share note",icon:Sr(wA,"share note"),sortTitle:"Share",call:qF},SHe={title:"Share public link",key:null,icon:Sr(wA,"share public link"),sortTitle:"Share public link",call:async()=>{Ct.hide(),await Kg(X(".terminal").getValue());let r=hn(),t=(await KU({note:r})).history[0].url,n=await fetch(t).then(l=>l.json()),{files:i}=n,o=Object.values(i),[s]=o,{raw_url:a}=s,c=`${ht.baseUrl}?raw=${a}`;Nu(c,"MiroPad public link copied to clipboard \u{1F4CB}!")}},DU=()=>[{title:"New note",icon:Sr(KF,"new note"),sortTitle:"New",key:"n",call:E6},{title:"Save",key:"s",icon:Sr(TF,"save"),sortTitle:"Save",call:async()=>{Ct.hide(),await Kg(X(".terminal").getValue());let r=hn(),{disableSync:e=!1}=r;e||tA([r]),Pu()}},...navigator.share?[xHe]:[],{title:"Toggle MarkDown Viewer",icon:Sr(LF,"toggle markdown viewer","rotate90"),sortTitle:"Split",key:"m",call:()=>{nf.toggle(),Ct.hide()}},{title:"Full MarkDown view",icon:Sr(BF,"full view"),sortTitle:"Full view",key:"shift m",call:()=>{nf.toggle("full"),Ct.hide()}},{title:"Save to IPFS",key:"i",icon:Sr(zF,"save"),sortTitle:"save->ipfs",call:async()=>{Ct.hide(),await Kg(X(".terminal").getValue());let r=hn(),{disableSync:e=!1}=r;if(e||tA([r]),r){let t=await WS.store(r.title,r.text);Nu(`${ht.baseUrl}#?cid=${t}`)}}},...uF()?[SHe]:[],{title:"Zen mode",icon:Sr($F,"zen mode"),sortTitle:"Zen mode",key:"shift z",call:()=>{!!ht.getSearchParam("zen")?ht.deleteParam("zen"):ht.set(void 0,{zen:!0}),Ct.hide()}},{title:"List saved notes",icon:Sr(AF,"list notes"),sortTitle:"Notes",key:"p",call:()=>Ct.toggle(Ct.getModes().notes)},{title:"Delete note",key:"shift d",icon:Sr(qg,"delete note"),sortTitle:"Delete",call:v6},{title:vHe(),icon:Sr(IF,"sync with github"),key:null,call:async()=>{let r=Fe.get("authToken");if(!r)return await hF();if(!Fe.get("gistId"))return await pF(r);Ct.hide(),await $g()}},{title:"Sync: Reset Gist settings",icon:Sr(RF,"reset github settings"),key:null,call:async()=>{localStorage.removeItem("authToken"),localStorage.removeItem("gistId"),localStorage.removeItem("lastLocalUpdate"),localStorage.removeItem("lastSync"),ze.info("Gist setting have been reset!"),Ct.hide()}},{title:"Toggle sidebar",experimental:!0,key:"shift l",call:()=>{X("aside").toggle()}},{title:"Save to File System...",experimental:!0,icon:Sr(CF,"save file"),key:"shift s",call:async()=>{let{text:r,title:e}=hn();gF(r,e),Ct.hide()}},{title:"Email note to...",experimental:!0,icon:Sr(kF,"email"),key:"e",call:()=>{let r=document.querySelector(".terminal").value;vF(r),Ct.hide()}},{title:"Toggle experimental features",experimental:!1,icon:Sr(NF,"lab"),key:null,call:()=>{let r=!!Fe.get("__experimental__");r?Fe.remove("__experimental__"):Fe.set("__experimental__",!0),ze.showNotification(`Experimental features turned ${r?"off":"on"}`),Ct.hide()}},{title:"Toggle Autocompletion",experimental:!1,icon:Sr(MF,"autocompletion"),key:null,call:()=>{let r=!!Fe.get("__autocomplete__");r?Fe.remove("__autocomplete__"):Fe.set("__autocomplete__",!0),ze.showNotification(`Autocomplete feature turned ${r?"off":"on"}`),Ct.hide(),X(".terminal").focus()}},{title:"Add a cover picture",experimental:!0,icon:Sr(DF,"cover picture"),key:null,call:async()=>{let r=prompt("Paste the image URL in here...");Ct.hide(),await SF(200),Nu(`

`,"\u{1F44C}Copied! Paste the code on the MiroPad editor"),X(".terminal").focus(),ze.info("Paste the cover picture wherever you prefer on the MirPad editor")}},{title:"Print MarkDown output",experimental:!0,icon:Sr(OF,"print"),key:null,call:()=>{X(".preview").show(),nf.init(),window.print(),Ct.hide()}},{key:"j",title:"Prettify JSON document",icon:Sr(UF,"prettify json"),call:()=>{xF(".terminal"),Ct.hide()}},{title:"Toggle command palette",icon:Sr(FF,"toggle command palette"),key:["shift p","k"],call:()=>Ct.toggle(Ct.getModes().commands)},{title:"Find and Replace...",experimental:!0,icon:Sr(VF,"find and replace"),key:"shift f",call:()=>{let r=X(".terminal").getValue().slice(X(".terminal").el.selectionStart,X(".terminal").el.selectionEnd),e=prompt("What do you wanna find?",r);if(!e)return ze.info("Value not found");let t=X(".terminal").getValue().indexOf(e);X(".terminal").el.setSelectionRange(t,t+e.length);let n=prompt(`Replace ${e} with...`);n&&X(".terminal").el.setRangeText(n)}},{title:"Download all notes!",icon:Sr(PF,"Download all notes on your local file system"),call:()=>{let r=Ru({includeDeleted:!0});yF(r),Ct.hide()}},{title:"Permanently delete ALL notes \u2757",icon:Sr(qg,"delete note"),call:()=>{confirm("Are you sure you want do delete ALL your notes?")&&(Ru({includeDeleted:!0}).forEach(t=>{Fe.remove(t.id)}),E6()),Ct.hide()}}];var AHe={events:[],on(r,e){return Array.isArray(r)?(r.forEach(t=>{let n=t.key||t,i=t.call||e;this.on(n,i)}),this):(r&&typeof r=="string"&&e&&typeof e=="function"&&(this.events=[...this.events,{key:r.includes("shift")?r.replace("shift","").trim():r,shift:r.includes("shift"),fn(){e()}}]),this)},listen(){return document.addEventListener("keydown",r=>{this.handleEvent(r)}),this},handleEvent(r){this.events.map(e=>(e.key===r.key&&(r.ctrlKey===!0||r.metaKey===!0)&&r.shiftKey===e.shift&&(r.preventDefault(),e.fn()),!0))}},Lye=AHe;var Bye=(r,e)=>{let t=document.createElement("a");return t.href=e,t.appendChild(D0(r)?r:document.createTextNode(r)),t};var OU=(r,e=new Date)=>{let t=new Date(r).getFullYear(),n=new Date(e).getFullYear();return t===n},Fye=(r,e=new Date)=>{let t=new Date(r).getMonth(),n=new Date(e).getMonth();return t===n},THe=(r,e=new Date)=>{let t=new Date(r).getDate(),n=new Date(e).getDate();return t===n},Mye=(r,e=new Date)=>OU(r,e)&&Fye(r,e)&&THe(r,e),IHe=["January","February","March","April","May","June","July","August","September","October","November","December"],RHe=IHe.map(r=>r.slice(0,3)),Uye=(r=new Date)=>{let e=new Date(r),t=new Date().getDate()-1;return Fye(e)&&OU(e)&&e.getDate()===t},d6=r=>{let e=new Date(r),t=Uye(r)?"":RHe[e.getMonth()],n=OU(e)?"":e.getFullYear(),i=Uye(e)?"Yesterday":e.getDate();return`${Mye(e)?"":`${i} ${t} ${n}`} ${Mye(e)?e.toLocaleTimeString():""}`};var zye=r=>r.reduce((t,n)=>{if(t.length===0)return[n];let i=Math.max(...t);return[...t,...n>=i?[n]:[]]},[]).length===r.length;var LU=(r,e)=>{let t=r.split(" ").map(o=>o.toLowerCase()),i=e.split(" ").map(o=>o.toLowerCase()).map(o=>t.map((c,u)=>c.includes(o)?u:-1).reduce((c,u)=>u>-1?u:c,-1));return i.includes(-1)?!1:zye(i)};var Vye=async()=>{if(!Fe.get("__notification-permission__")){let r=await window.Notification.requestPermission();Fe.set("__notification-permission__",r)}},Kye=async()=>{"serviceWorker"in navigator&&navigator.serviceWorker.register(`${window.location.pathname}service-worker.js?v=2.15.15`)};var $ye=r=>Array.isArray(r)?r.map(e=>$ye(e)).join(", "):r?`\u2318+${r.toUpperCase()}`:"",CHe=(()=>{let r={off:"off",notes:"notes",revisions:"revisions",commands:"commands",gists:"gists"},e={input:"",mode:r.off,options:{selected:0,length:0}};return{getState:function(){return e},getModes:function(){return r},setState:function(t){return e={...e,...t},e},show:function(t=r.commands){switch(X("#commander").show(),X("#commander input").focus(),t){case r.commands:this.generateCommands(),X("#commander input").setValue("> "),this.setState({mode:r.commands});break;case r.notes:this.generateNotes(),X("#commander input").setValue(""),this.setState({mode:r.notes});break;case r.revisions:this.generateRevisions(),X("#commander input").setValue(""),this.setState({mode:r.revisions});break;default:break}return this},hide:function(){return X("#commander").hide(),e.mode=r.off,this},toggle:function(t){return Vye(),e.mode===r.off||e.mode!==t?this.show(t):this.hide(),this},commands:function(){return DU()},selectOption:function(t,n){let i=e.options.selected,o=e.options.length-1,u=n==="down"?i===o?0:i+1:i===0?o:i-1;e.options={...e.options,selected:u}},initCommander:function(){return DU().slice(0,5).map(t=>{X(".mobile-dock").append(A6([t.icon,document.createTextNode(t.sortTitle)],t.call,t.title.toLowerCase().replace(/\s/g,"-")))}),X("#commander button").listen("click",()=>{this.hide()}),X("#commander input").listen("keydown",t=>{t.keyCode===40&&(e.mode===r.revisions&&X("#commands li.selected").click(),this.selectOption(t,"down")),t.keyCode===38&&(e.mode===r.revisions&&X("#commands li.selected").click(),this.selectOption(t,"up"))}).listen("keyup",t=>{t.keyCode===13&&(e.mode===r.commands?X("#commands li.selected div").click():X("#commands li.selected a").click()),t.keyCode===27&&X(".terminal").focus(),e.input!==t.target.value&&(e.options.selected=0),e.input=t.target.value,this.generateOptions(t.target.value)}),this},init:function(){return this.initCommander(),Lye.listen().on(this.commands()),X(".menu").listen("click",()=>this.toggle()),X("#revisions").listen("click",()=>this.generateRevisions()),this},generateRevisions:function(){this.show(),e.mode=r.revisions;let{revisions:t}=hn(),n=e.options.selected,i=Object.keys(t).sort((o,s)=>{let{dateCreated:a}=t[o],{dateCreated:c}=t[s];return c-a}).map((o,s)=>({title:ku({content:`...${o.slice(-10)}`}),secondary:`${d6(t[o].dateCreated)}`,onclick:()=>{ht.set(void 0,{v:o}),e.options.selected=s,this.generateRevisions()}})).map((o,s)=>rf(o,s===n));return X("#commands").html(i),e.options={...e.options,length:i.length},this},generateOptions:function(t){switch(e.mode){case r.commands:case r.notes:t.slice(0,1)===">"?(e.mode=r.commands,this.generateCommands(t.slice(1).trim()),X("#commander input").placeholder("Search for commands...")):(e.mode=r.notes,this.generateNotes(t));return;case r.revisions:return this.generateRevisions();case r.off:break;default:break}},generateNotes:function(t=""){let n=e.options.selected,i=Ru().filter(({title:o})=>LU(o,t)).filter(({id:o,deleted:s})=>!s&&o!==ht.getPageId()).sort((o,s)=>{let a=b6(o.title);return b6(s.title)-a}).map(({id:o,title:s,cid:a},c)=>{let u=b6(s),l=a?`?cid=${a}`:"",f=`${window.location.origin}${window.location.pathname}#${o}${l}`,h=Bye(ku({content:s,highlight:t}),f);return rf({title:h,secondary:d6(u),onclick:()=>{this.hide(),X(".terminal").focus()}},c===n)});return X("#commands").html(i),X("#commander input").placeholder(`Search from ${i.length} saved notes...`),e.options={...e.options,length:i.length},this},generateCommands:async function(t=""){let n=e.options.selected,i=this.commands().filter(({title:o})=>LU(o,t)).filter(({experimental:o=!1})=>Fe.get("__experimental__")?!0:!o).map(({title:o,key:s,call:a,icon:c},u)=>rf({title:ku({content:o,highlight:t}),icon:c,secondary:$ye(s),onclick:a},u===n));return X("#commands").html(i),e.options={...e.options,length:i.length},this}}})(),Ct=CHe;var jye=C(qye());var Hye=(r,e)=>r.split(` +`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),QFe=new RegExp(`(?:^${oc}$)|(?:^${P9}$)`),XFe=new RegExp(`^${oc}$`),ZFe=new RegExp(`^${P9}$`),hB=r=>r&&r.exact?QFe:new RegExp(`(?:${eh(r)}${oc}${eh(r)})|(?:${eh(r)}${P9}${eh(r)})`,"g");hB.v4=r=>r&&r.exact?XFe:new RegExp(`${eh(r)}${oc}${eh(r)}`,"g");hB.v6=r=>r&&r.exact?ZFe:new RegExp(`${eh(r)}${P9}${eh(r)}`,"g");var k9=hB;var xhe=C(_he(),1),{isValid:JFe,parse:eze}=xhe.default,tze=["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"],rze=tze.map(r=>new vhe.Netmask(r));function nze(r){for(let e of rze)if(e.contains(r))return!0;return!1}function Ehe(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}var She=r=>{if(JFe(r)){let e=eze(r);if(e.kind()==="ipv4")return nze(e.toNormalizedString());if(e.kind()==="ipv6")return Ehe(r)}else if(c2(r)&&k9.v6().test(r))return Ehe(r)};var D9=She;function pB(r){let{address:e}=r.nodeAddress();return!!D9(e)}function ig(r,e){let t=pB(r.multiaddr),n=pB(e.multiaddr);return t&&!n?1:!t&&n||r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}var l4=ue("libp2p:auto-relay"),oze=()=>{},O9=class{constructor(e,t){this.components=e,this.addressSorter=t.addressSorter??ig,this.maxListeners=t.maxListeners??1,this.listenRelays=new Set,this.onError=t.onError??oze,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this.components.peerStore.addEventListener("change:protocols",n=>{this._onProtocolChange(n).catch(i=>{l4.error(i)})}),this.components.connectionManager.addEventListener("peer:disconnect",this._onPeerDisconnected)}async _onProtocolChange(e){let{peerId:t,protocols:n}=e.detail,i=t.toString();if(n.find(s=>s===mu)==null){this.listenRelays.has(i)&&await this._removeListenRelay(i);return}if(!this.listenRelays.has(i))try{let s=this.components.connectionManager.getConnections(t);if(s.length===0)return;let a=s[0];if(a.remoteAddr.protoCodes().includes(290)){l4(`relayed connection to ${i} will not be used to hop on`);return}await hhe({connection:a})&&(await this.components.peerStore.metadataBook.setValue(t,lB,fe(fB)),await this._addListenRelay(a,i))}catch(s){this.onError(s)}}_onPeerDisconnected(e){let i=e.detail.remotePeer.toString();this.listenRelays.has(i)&&this._removeListenRelay(i).catch(o=>{l4.error(o)})}async _addListenRelay(e,t){try{if(this.listenRelays.size>=this.maxListeners)return;let n=await Ne(await this.components.peerStore.addressBook.get(e.remotePeer),o=>Id(o,this.addressSorter),async o=>await Wo(o));(await Promise.all(n.map(async o=>{try{let s=o.multiaddr;return s.getPeerId()==null&&(s=s.encapsulate(`/p2p/${e.remotePeer.toString()}`)),s=s.encapsulate("/p2p-circuit"),await this.components.transportManager.listen([s]),!0}catch(s){l4.error("error listening on circuit address",s),this.onError(s)}return!1}))).includes(!0)&&this.listenRelays.add(t)}catch(n){this.onError(n),this.listenRelays.delete(t)}}async _removeListenRelay(e){this.listenRelays.delete(e)&&await this._listenOnAvailableHopRelays([e])}async _listenOnAvailableHopRelays(e=[]){if(this.listenRelays.size>=this.maxListeners)return;let t=[],n=await this.components.peerStore.all();for(let{id:i,metadata:o}of n){let s=i.toString();if(this.listenRelays.has(s)||e.includes(s))continue;let a=o.get(lB);if(a==null||Ee(a)!==fB)continue;let c=this.components.connectionManager.getConnections(i);if(c.length===0){t.push(i);continue}if(await this._addListenRelay(c[0],s),this.listenRelays.size>=this.maxListeners)return}for(let i of t)if(await this._tryToListenOnRelay(i),this.listenRelays.size>=this.maxListeners)return;try{let i=await R9(C9);for await(let o of this.components.contentRouting.findProviders(i)){if(o.multiaddrs.length===0)continue;let s=o.id;if(!s.equals(this.components.peerId)&&(await this.components.peerStore.addressBook.add(s,o.multiaddrs),await this._tryToListenOnRelay(s),this.listenRelays.size>=this.maxListeners))return}}catch(i){this.onError(i)}}async _tryToListenOnRelay(e){try{let t=await this.components.connectionManager.openConnection(e);await this._addListenRelay(t,e.toString())}catch(t){l4.error("Could not use %p as relay",e,t),this.onError(t,`could not connect and listen on known hop relay ${e.toString()}`)}}};var Ahe=ue("libp2p:relay"),L9=class{constructor(e,t){var n;this.components=e,this.autoRelay=((n=t.autoRelay)==null?void 0:n.enabled)!==!1?new O9(e,{addressSorter:t.addressSorter,...t.autoRelay}):void 0,this.started=!1,this.init=t,this._advertiseService=this._advertiseService.bind(this)}isStarted(){return this.started}async start(){this.init.hop.enabled!==!1&&this.init.advertise.enabled!==!1&&(this.timeout=(0,B9.setDelayedInterval)(this._advertiseService,this.init.advertise.ttl,this.init.advertise.bootDelay)),this.started=!0}async stop(){this.timeout!=null&&(0,B9.clearDelayedInterval)(this.timeout),this.started=!1}async _advertiseService(){try{let e=await R9(C9);await this.components.contentRouting.provide(e)}catch(e){e.code===q.ERR_NO_ROUTERS_AVAILABLE?(Ahe.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),await this.stop()):Ahe.error(e)}}};var Lpe=C(Ohe(),1);var fHt=C(Zhe(),1),dHt=C(Rb(),1),Ol=C(at(),1);var uHt=C(gB(),1),epe=C(at(),1),Jhe=epe.default.pki,tpe=(r,e)=>{let t=Jhe.rsa.setPublicKey(e.n,e.e),n=Jhe.createCertificate();n.publicKey=t,n.serialNumber="01",n.validity.notBefore=new Date,n.validity.notAfter=new Date,n.validity.notAfter.setFullYear(n.validity.notBefore.getFullYear()+10);let i=[{name:"organizationName",value:"ipfs"},{shortName:"OU",value:"keystore"},{name:"commonName",value:r.id}];return n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0,codeSigning:!0,emailProtection:!0,timeStamping:!0},{name:"nsCertType",client:!0,server:!0,email:!0,objsign:!0,sslCA:!0,emailCA:!0,objCA:!0}]),n.sign(e),n};async function rpe(r,e){let t=r.map(e),i=(await Promise.all(t)).findIndex(o=>o);return r[i]}var Ll=C(ee(),1);var Lze=ue("libp2p:keychain:cms"),bB=new WeakMap,z9=class{constructor(e,t){if(e==null)throw(0,Ll.default)(new Error("keychain is required"),q.ERR_KEYCHAIN_REQUIRED);this.keychain=e,bB.set(this,{dek:t})}async encrypt(e,t){if(!(t instanceof Uint8Array))throw(0,Ll.default)(new Error("Plain data must be a Uint8Array"),q.ERR_INVALID_PARAMETERS);let n=await this.keychain.findKeyByName(e),i=await this.keychain.getPrivateKey(e),o=bB.get(this);if(o==null)throw(0,Ll.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let s=o.dek,a=Ol.default.pki.decryptRsaPrivateKey(i,s),c=await tpe(n,a),u=Ol.default.pkcs7.createEnvelopedData();u.addRecipient(c),u.content=Ol.default.util.createBuffer(t),u.encrypt();let l=Ol.default.asn1.toDer(u.toAsn1()).getBytes();return fe(l,"ascii")}async decrypt(e){if(!(e instanceof Uint8Array))throw(0,Ll.default)(new Error("CMS data is required"),q.ERR_INVALID_PARAMETERS);let t;try{let l=Ol.default.util.createBuffer(Ee(e,"ascii")),f=Ol.default.asn1.fromDer(l);t=Ol.default.pkcs7.messageFromAsn1(f)}catch(l){throw Lze.error(l),(0,Ll.default)(new Error("Invalid CMS"),q.ERR_INVALID_CMS)}let n=t.recipients.filter(l=>l.issuer.find(f=>f.shortName==="O"&&f.value==="ipfs")).filter(l=>l.issuer.find(f=>f.shortName==="CN")).map(l=>({recipient:l,keyId:l.issuer.find(f=>f.shortName==="CN").value})),i=await rpe(n,async l=>{try{if(await this.keychain.findKeyById(l.keyId)!=null)return!0}catch{return!1}return!1});if(i==null){let l=n.map(f=>f.keyId);throw(0,Ll.default)(new Error(`Decryption needs one of the key(s): ${l.join(", ")}`),q.ERR_MISSING_KEYS,{missingKeys:l})}let o=await this.keychain.findKeyById(i.keyId);if(o==null)throw(0,Ll.default)(new Error("No key available to decrypto"),q.ERR_NO_KEY);let s=await this.keychain.getPrivateKey(o.name),a=bB.get(this);if(a==null)throw(0,Ll.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let c=a.dek,u=Ol.default.pki.decryptRsaPrivateKey(s,c);return t.decrypt(i.recipient,u),fe(t.content.getBytes(),"ascii")}};var nr=C(ee(),1);var Gr;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Gr||(Gr={}));var _B;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(_B||(_B={}));(function(r){r.codec=()=>Jd(_B)})(Gr||(Gr={}));var gu;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Gr.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Gr.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(gu||(gu={}));var yu;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Gr.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Gr.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(yu||(yu={}));var FGt=C(Ic(),1),zGt=C(Rb(),1),q9=C(at(),1);var Io={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var PHt=C(gr(),1),kHt=C(qy(),1),ipe=C(at(),1);function sc(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=yr([new Uint8Array(e-t.length),t])}return Ee(t,"base64url")}function ws(r){let e=ope(r);return new ipe.default.jsbn.BigInteger(Ee(e,"base16"),16)}function ope(r,e){let t=fe(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=yr([new Uint8Array(e-t.length),t])}return t}var Bze={"P-256":256,"P-384":384,"P-521":521},Mze=Object.keys(Bze),KHt=Mze.join(" / ");function K9(r){let e=(r==null?void 0:r.algorithm)??"AES-GCM",t=(r==null?void 0:r.keyLength)??16,n=(r==null?void 0:r.nonceLength)??12,i=(r==null?void 0:r.digest)??"SHA-256",o=(r==null?void 0:r.saltLength)??16,s=(r==null?void 0:r.iterations)??32767,a=Io.get();t*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(o)),p=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:p};typeof h=="string"&&(h=fe(h));let w={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),x=await a.subtle.deriveKey(w,_,{name:e,length:t},!0,["encrypt"]),m=await a.subtle.encrypt(g,x,f);return yr([d,g.iv,new Uint8Array(m)])}async function u(f,h){let d=f.subarray(0,o),p=f.subarray(o,o+n),g=f.subarray(o+n),w={name:e,iv:p};typeof h=="string"&&(h=fe(h));let _={name:"PBKDF2",salt:d,iterations:s,hash:{name:i}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),m=await a.subtle.deriveKey(_,x,{name:e,length:t},!0,["decrypt"]),y=await a.subtle.decrypt(w,m,g);return new Uint8Array(y)}return{encrypt:c,decrypt:u}}async function ape(r,e){let t=wh.decode(r);return await K9().decrypt(t,e)}var xB={};xe(xB,{RsaPrivateKey:()=>ug,RsaPublicKey:()=>d4,fromJwk:()=>Gze,generateKeyPair:()=>jze,unmarshalRsaPrivateKey:()=>qze,unmarshalRsaPublicKey:()=>Hze});var vGt=C(NC(),1),f4=C(at(),1);function Bl(r){if(isNaN(r)||r<=0)throw new We("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ro.randomBytes(r)}var g0={};xe(g0,{jwkToPkcs1:()=>Fze,jwkToPkix:()=>Vze,pkcs1ToJwk:()=>Uze,pkixToJwk:()=>zze});var tGt=C(Ic(),1),rGt=C(Bh(),1),Ml=C(at(),1);function Uze(r){let e=Ml.default.asn1.fromDer(Ee(r,"ascii")),t=Ml.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:sc(t.n),e:sc(t.e),d:sc(t.d),p:sc(t.p),q:sc(t.q),dp:sc(t.dP),dq:sc(t.dQ),qi:sc(t.qInv),alg:"RS256"}}function Fze(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new We("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ml.default.pki.privateKeyToAsn1({n:ws(r.n),e:ws(r.e),d:ws(r.d),p:ws(r.p),q:ws(r.q),dP:ws(r.dp),dQ:ws(r.dq),qInv:ws(r.qi)});return fe(Ml.default.asn1.toDer(e).getBytes(),"ascii")}function zze(r){let e=Ml.default.asn1.fromDer(Ee(r,"ascii")),t=Ml.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:sc(t.n),e:sc(t.e)}}function Vze(r){if(r.n==null||r.e==null)throw new We("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ml.default.pki.publicKeyToAsn1({n:ws(r.n),e:ws(r.e)});return fe(Ml.default.asn1.toDer(e).getBytes(),"ascii")}var aGt=C(Bh(),1),EB=C(at(),1);function cpe(r,e){return e.map(t=>ws(r[t]))}function upe(r){return EB.default.pki.setRsaPrivateKey(...cpe(r,["n","e","d","p","q","dp","dq","qi"]))}function lpe(r){return EB.default.pki.setRsaPublicKey(...cpe(r,["n","e"]))}async function fpe(r){let e=await Io.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await ppe(e);return{privateKey:t[0],publicKey:t[1]}}async function vB(r){let t=[await Io.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Kze(r)],n=await ppe({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function dpe(r,e){let t=await Io.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Io.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function hpe(r,e,t){let n=await Io.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return await Io.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function ppe(r){if(r.privateKey==null||r.publicKey==null)throw new We("Private and public key are required","ERR_INVALID_PARAMETERS");return await Promise.all([Io.get().subtle.exportKey("jwk",r.privateKey),Io.get().subtle.exportKey("jwk",r.publicKey)])}async function Kze(r){return await Io.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function mpe(r,e,t,n){let i=e?lpe(r):upe(r),o=Ee(Uint8Array.from(t),"ascii"),s=n(o,i);return fe(s,"ascii")}function gpe(r,e){return mpe(r,!0,e,(t,n)=>n.encrypt(t))}function ype(r,e){return mpe(r,!1,e,(t,n)=>n.decrypt(t))}async function cg(r,e){let n=await K9().encrypt(r,e);return wh.encode(n)}var d4=class{constructor(e){this._key=e}async verify(e,t){return await hpe(this._key,t,e)}marshal(){return g0.jwkToPkix(this._key)}get bytes(){return gu.encode({Type:Gr.RSA,Data:this.marshal()}).subarray()}encrypt(e){return gpe(this._key,e)}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}},ug=class{constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Bl(16)}async sign(e){return await dpe(this._key,e)}get public(){if(this._publicKey==null)throw new We("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new d4(this._publicKey)}decrypt(e){return ype(this._key,e)}marshal(){return g0.jwkToPkcs1(this._key)}get bytes(){return yu.encode({Type:Gr.RSA,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}async id(){let e=await this.public.hash();return Ee(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new f4.default.util.ByteBuffer(this.marshal()),i=f4.default.asn1.fromDer(n),o=f4.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return f4.default.pki.encryptRsaPrivateKey(o,e,s)}else{if(t==="libp2p-key")return await cg(this.bytes,e);throw new We(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function qze(r){let e=g0.pkcs1ToJwk(r),t=await vB(e);return new ug(t.privateKey,t.publicKey)}function Hze(r){let e=g0.pkixToJwk(r);return new d4(e)}async function Gze(r){let e=await vB(r);return new ug(e.privateKey,e.publicKey)}async function jze(r){let e=await fpe(r);return new ug(e.privateKey,e.publicKey)}var SB={};xe(SB,{Ed25519PrivateKey:()=>y0,Ed25519PublicKey:()=>h4,generateKeyPair:()=>Xze,generateKeyPairFromSeed:()=>xpe,unmarshalEd25519PrivateKey:()=>Yze,unmarshalEd25519PublicKey:()=>Qze});var lg=32,Ul=64,$9=32;async function wpe(){let r=Lc.randomPrivateKey(),e=await H1(r);return{privateKey:vpe(r,e),publicKey:e}}async function bpe(r){if(r.length!==$9)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await H1(e);return{privateKey:vpe(e,t),publicKey:t}}async function _pe(r,e){let t=r.subarray(0,$9);return await Db(e,t)}async function Epe(r,e,t){return await Ob(e,t,r)}function vpe(r,e){let t=new Uint8Array(Ul);for(let n=0;n<$9;n++)t[n]=r[n],t[$9+n]=e[n];return t}var h4=class{constructor(e){this._key=fg(e,lg)}async verify(e,t){return await Epe(this._key,t,e)}marshal(){return this._key}get bytes(){return gu.encode({Type:Gr.Ed25519,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}},y0=class{constructor(e,t){this._key=fg(e,Ul),this._publicKey=fg(t,lg)}async sign(e){return await _pe(this._key,e)}get public(){return new h4(this._publicKey)}marshal(){return this._key}get bytes(){return yu.encode({Type:Gr.Ed25519,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}async id(){let e=await Ns.digest(this.public.bytes);return tt.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return await cg(this.bytes,e);throw new We(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Yze(r){if(r.length>Ul){r=fg(r,Ul+lg);let n=r.subarray(0,Ul),i=r.subarray(Ul,r.length);return new y0(n,i)}r=fg(r,Ul);let e=r.subarray(0,Ul),t=r.subarray(lg);return new y0(e,t)}function Qze(r){return r=fg(r,lg),new h4(r)}async function Xze(){let{privateKey:r,publicKey:e}=await wpe();return new y0(r,e)}async function xpe(r){let{privateKey:e,publicKey:t}=await bpe(r);return new y0(e,t)}function fg(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new We(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var TB={};xe(TB,{Secp256k1PrivateKey:()=>m4,Secp256k1PublicKey:()=>p4,generateKeyPair:()=>tVe,unmarshalSecp256k1PrivateKey:()=>Jze,unmarshalSecp256k1PublicKey:()=>eVe});function Spe(){return ro.randomPrivateKey()}async function Ape(r,e){let{digest:t}=await mr.digest(e);try{return await Wb(t,r)}catch(n){throw new We(String(n),"ERR_INVALID_INPUT")}}async function Tpe(r,e,t){try{let{digest:n}=await mr.digest(t);return Yb(e,n,r)}catch(n){throw new We(String(n),"ERR_INVALID_INPUT")}}function Ipe(r){return Kt.fromHex(r).toRawBytes(!0)}function Rpe(r){try{im(r,!0)}catch(e){throw new We(String(e),"ERR_INVALID_PRIVATE_KEY")}}function AB(r){try{Kt.fromHex(r)}catch(e){throw new We(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Cpe(r){try{return im(r,!0)}catch(e){throw new We(String(e),"ERR_INVALID_PRIVATE_KEY")}}var p4=class{constructor(e){AB(e),this._key=e}async verify(e,t){return await Tpe(this._key,t,e)}marshal(){return Ipe(this._key)}get bytes(){return gu.encode({Type:Gr.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}},m4=class{constructor(e,t){this._key=e,this._publicKey=t??Cpe(e),Rpe(this._key),AB(this._publicKey)}async sign(e){return await Ape(this._key,e)}get public(){return new p4(this._publicKey)}marshal(){return this._key}get bytes(){return yu.encode({Type:Gr.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return rr(this.bytes,e.bytes)}async hash(){let{bytes:e}=await mr.digest(this.bytes);return e}async id(){let e=await this.public.hash();return Ee(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return await cg(this.bytes,e);throw new We(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Jze(r){return new m4(r)}function eVe(r){return new p4(r)}async function tVe(){let r=await Spe();return new m4(r)}var Fl={rsa:xB,ed25519:SB,secp256k1:TB};function IB(r){let e=Object.keys(Fl).join(" / ");return new We(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function RB(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Fl[r];throw IB(r)}async function H9(r,e){return await RB(r).generateKeyPair(e??2048)}function g4(r){let e=gu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Gr.RSA:return Fl.rsa.unmarshalRsaPublicKey(t);case Gr.Ed25519:return Fl.ed25519.unmarshalEd25519PublicKey(t);case Gr.Secp256k1:return Fl.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw IB(e.Type??"RSA")}}function Ppe(r,e){return e=(e??"rsa").toLowerCase(),RB(e),r.bytes}async function dg(r){let e=yu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Gr.RSA:return await Fl.rsa.unmarshalRsaPrivateKey(t);case Gr.Ed25519:return Fl.ed25519.unmarshalEd25519PrivateKey(t);case Gr.Secp256k1:return Fl.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw IB(e.Type??"RSA")}}function kpe(r,e){return e=(e??"rsa").toLowerCase(),RB(e),r.bytes}async function y4(r,e){try{let i=await ape(r,e);return await dg(i)}catch{}let t=q9.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new We("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=q9.default.asn1.toDer(q9.default.pki.privateKeyToAsn1(t));return n=fe(n.getBytes(),"ascii"),await Fl.rsa.unmarshalRsaPrivateKey(n)}var GGt=C(Nh(),1),nVe=C(at(),1);var Dpe=C(bb(),1),Ope=C(gr(),1);var Npe={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function w4(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(Npe).join(" / ");throw new We(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let o=Npe[i],s=(0,Dpe.default)(r,e,t,n,o);return Ope.default.encode64(s,null)}var G9=ue("libp2p:keychain"),sVe="/pkcs8/",Bpe="/info/",rh=new WeakMap,w0={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},CB={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function zl(r){return r==null||typeof r!="string"?!1:r===(0,Lpe.default)(r.trim())&&r.length>0}async function _r(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function wu(r){return new pe(sVe+r)}function Vl(r){return new pe(Bpe+r)}var b0=class{constructor(e,t){var i,o,s,a,c,u,l,f,h,d;if(this.components=e,this.init=et(CB,t),this.init.pass!=null&&((i=this.init.pass)==null?void 0:i.length)<20)throw new Error("pass must be least 20 characters");if(((o=this.init.dek)==null?void 0:o.keyLength)!=null&&this.init.dek.keyLengthn.id===e)}catch(t){throw await _r(),t}}async findKeyByName(e){if(!zl(e))throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);let t=Vl(e);try{let n=await this.components.datastore.get(t);return JSON.parse(Ee(n))}catch(n){throw await _r(),G9.error(n),(0,nr.default)(new Error(`Key '${e}' does not exist.`),q.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!zl(e)||e==="self")throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);let t=wu(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(Vl(e)),await i.commit(),n}async renameKey(e,t){if(!zl(e)||e==="self")throw await _r(),(0,nr.default)(new Error(`Invalid old key name '${e}'`),q.ERR_OLD_KEY_NAME_INVALID);if(!zl(t)||t==="self")throw await _r(),(0,nr.default)(new Error(`Invalid new key name '${t}'`),q.ERR_NEW_KEY_NAME_INVALID);let n=wu(e),i=wu(t),o=Vl(e),s=Vl(t);if(await this.components.datastore.has(i))throw await _r(),(0,nr.default)(new Error(`Key '${t}' already exists`),q.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(o),l=JSON.parse(Ee(u));l.name=t;let f=this.components.datastore.batch();return f.put(i,c),f.put(s,fe(JSON.stringify(l))),f.delete(n),f.delete(o),await f.commit(),l}catch(c){throw await _r(),c}}async exportKey(e,t){if(!zl(e))throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);if(t==null)throw await _r(),(0,nr.default)(new Error("Password is required"),q.ERR_PASSWORD_REQUIRED);let n=wu(e);try{let i=await this.components.datastore.get(n),o=Ee(i),s=rh.get(this);if(s==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let a=s.dek;return await(await y4(o,a)).export(t)}catch(i){throw await _r(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await y4(n,t);return await Yd(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!zl(e)||e==="self")throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);if(t==null)throw await _r(),(0,nr.default)(new Error("PEM encoded key is required"),q.ERR_PEM_REQUIRED);let i=wu(e);if(await this.components.datastore.has(i))throw await _r(),(0,nr.default)(new Error(`Key '${e}' already exists`),q.ERR_KEY_ALREADY_EXISTS);let s;try{s=await y4(t,n)}catch{throw await _r(),(0,nr.default)(new Error("Cannot read the key, most likely the password is wrong"),q.ERR_CANNOT_READ_KEY)}let a;try{a=await s.id();let l=rh.get(this);if(l==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let f=l.dek;t=await s.export(f)}catch(l){throw await _r(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,fe(t)),u.put(Vl(e),fe(JSON.stringify(c))),await u.commit(),c}async importPeer(e,t){try{if(!zl(e))throw(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);if(t==null)throw(0,nr.default)(new Error("PeerId is required"),q.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw(0,nr.default)(new Error("PeerId.privKey is required"),q.ERR_MISSING_PRIVATE_KEY);let n=await dg(t.privateKey),i=wu(e);if(await this.components.datastore.has(i))throw await _r(),(0,nr.default)(new Error(`Key '${e}' already exists`),q.ERR_KEY_ALREADY_EXISTS);let s=rh.get(this);if(s==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let a=s.dek,c=await n.export(a),u={name:e,id:t.toString()},l=this.components.datastore.batch();return l.put(i,fe(c)),l.put(Vl(e),fe(JSON.stringify(u))),await l.commit(),u}catch(n){throw await _r(),n}}async getPrivateKey(e){if(!zl(e))throw await _r(),(0,nr.default)(new Error(`Invalid key name '${e}'`),q.ERR_INVALID_KEY_NAME);try{let t=wu(e),n=await this.components.datastore.get(t);return Ee(n)}catch(t){throw await _r(),G9.error(t),(0,nr.default)(new Error(`Key '${e}' does not exist.`),q.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){var a,c,u,l;if(typeof e!="string")throw await _r(),(0,nr.default)(new Error(`Invalid old pass type '${typeof e}'`),q.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await _r(),(0,nr.default)(new Error(`Invalid new pass type '${typeof t}'`),q.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await _r(),(0,nr.default)(new Error(`Invalid pass length ${t.length}`),q.ERR_INVALID_PASS_LENGTH);G9("recreating keychain");let n=rh.get(this);if(n==null)throw(0,nr.default)(new Error("dek missing"),q.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let o=t!=null&&((a=this.init.dek)==null?void 0:a.salt)!=null?w4(t,this.init.dek.salt,(c=this.init.dek)==null?void 0:c.iterationCount,(u=this.init.dek)==null?void 0:u.keyLength,(l=this.init.dek)==null?void 0:l.hash):"";rh.set(this,{dek:o});let s=await this.listKeys();for(let f of s){let h=await this.components.datastore.get(wu(f.name)),d=Ee(h),p=await y4(d,i),g=o.toString(),w=await p.export(g),_=this.components.datastore.batch(),x={name:f.name,id:f.id};_.put(wu(f.name),fe(w)),_.put(Vl(f.name),fe(JSON.stringify(x))),await _.commit()}G9("keychain reconstructed")}};async function b4(r){try{return{status:"fulfilled",value:await r,isFulfilled:!0,isRejected:!1}}catch(e){return{status:"rejected",reason:e,isFulfilled:!1,isRejected:!0}}}var PB=class{constructor(e){B(this,"value");B(this,"next");this.value=e}},bu,_0,E0,_4=class{constructor(){bt(this,bu,void 0);bt(this,_0,void 0);bt(this,E0,void 0);this.clear()}enqueue(e){let t=new PB(e);ge(this,bu)?(ge(this,_0).next=t,Dt(this,_0,t)):(Dt(this,bu,t),Dt(this,_0,t)),uh(this,E0)._++}dequeue(){let e=ge(this,bu);if(e)return Dt(this,bu,ge(this,bu).next),uh(this,E0)._--,e.value}clear(){Dt(this,bu,void 0),Dt(this,_0,void 0),Dt(this,E0,0)}get size(){return ge(this,E0)}*[Symbol.iterator](){let e=ge(this,bu);for(;e;)yield e.value,e=e.next}};bu=new WeakMap,_0=new WeakMap,E0=new WeakMap;function kB(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=new _4,t=0,n=()=>{t--,e.size>0&&e.dequeue()()},i=async(a,c,u)=>{t++;let l=(async()=>a(...u))();c(l);try{await l}catch{}n()},o=(a,c,u)=>{e.enqueue(i.bind(void 0,a,c,u)),(async()=>(await Promise.resolve(),t0&&e.dequeue()()))()},s=(a,...c)=>new Promise(u=>{o(a,u,c)});return Object.defineProperties(s,{activeCount:{get:()=>t},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),s}async function NB(r,e={}){let{concurrency:t=Number.POSITIVE_INFINITY}=e,n=kB(t);return Promise.all(r.map(i=>i&&typeof i.then=="function"?b4(i):typeof i=="function"?b4(n(()=>i())):b4(Promise.resolve(i))))}var hg=C(ee(),1);var DB=class extends Map{constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function bs(r){let{name:e,metrics:t}=r,n;return t!=null?n=new DB({name:e,metrics:t}):n=new Map,n}var v0=ue("libp2p:transports"),j9=class extends Zt{constructor(e,t={}){super(),this.components=e,this.started=!1,this.transports=new Map,this.listeners=bs({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Qd.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw(0,hg.default)(new Error("Transport must have a valid tag"),q.ERR_INVALID_KEY);if(this.transports.has(t))throw(0,hg.default)(new Error("There is already a transport with this tag"),q.ERR_DUPLICATE_TRANSPORT);v0("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}async start(){let e=this.components.addressManager.getListenAddrs();await this.listen(e),this.started=!0}async stop(){let e=[];for(let[t,n]of this.listeners)for(v0("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),v0("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw(0,hg.default)(new Error(`No transport available for address ${String(e)}`),q.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=q.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(e==null||e.length===0){v0("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){v0("creating listener for %s on %s",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n);f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.dispatchEvent(new ve("listener:listening",{detail:l}))}),l.addEventListener("close",()=>{this.dispatchEvent(new ve("listener:close",{detail:l}))}),s.push(l.listen(u))}if(s.length===0){t.push(n);continue}if((await NB(s)).find(u=>u.isFulfilled)==null&&this.faultTolerance!==Qd.NO_FATAL)throw(0,hg.default)(new Error(`Transport (${n}) could not listen on any available address`),q.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Qd.FATAL_ALL)throw(0,hg.default)(new Error(n),q.ERR_NO_VALID_ADDRESSES);v0(`libp2p in dial mode only: ${n}`)}}async remove(e){v0("removing %s",e);for(let t of this.listeners.get(e)??[])await t.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Wn=C(ee(),1);var Kl="/multistream/1.0.0";var zpe=C(ee(),1);var OB=C(ee(),1);var cVe=ue("libp2p:mss"),Mpe=fe(` +`);function E4(r){let e=new ln(r,Mpe);return vn.single(e)}function x0(r,e,t={}){let n=E4(e);t.writeBytes===!0?r.push(n.subarray()):r.push(n)}function Upe(r,e,t={}){let n=new ln;for(let i of e)n.append(E4(i));t.writeBytes===!0?r.push(n.subarray()):r.push(n)}async function uVe(r,e){let t=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await r.next(t)},i=n;(e==null?void 0:e.signal)!=null&&(i=sa(n,e.signal));let s=await Ne(i,Xr({onLength:a=>{t=a},maxDataLength:1024}),async a=>await Fi(a));if(s==null||s.length===0)throw(0,OB.default)(new Error("no buffer returned"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(s.get(s.byteLength-1)!==Mpe[0])throw cVe.error("Invalid mss message - missing newline - %s",s.subarray()),(0,OB.default)(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return s.sublist(0,-1)}async function pg(r,e){let t=await uVe(r,e);return Ee(t.subarray())}var v4=ue("libp2p:mss:select");async function x4(r,e,t={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:o,stream:s}=ng(r),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");v4('select: write ["%s", "%s"]',Kl,a);let c=fe(Kl),u=fe(a);Upe(i,[c,u],t);let l=await pg(n,t);if(v4('select: read "%s"',l),l===Kl&&(l=await pg(n,t),v4('select: read "%s"',l)),l===a)return o(),{stream:s,protocol:a};for(let f of e){v4('select: write "%s"',f),x0(i,fe(f),t);let h=await pg(n,t);if(v4('select: read "%s" for "%s"',h,f),h===f)return o(),{stream:s,protocol:f}}throw o(),(0,zpe.default)(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}var S4=ue("libp2p:mss:handle");async function A4(r,e,t){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:o,stream:s}=ng(r);for(;;){let a=await pg(i,t);if(S4('read "%s"',a),a===Kl){S4('respond with "%s" for "%s"',Kl,a),x0(n,fe(Kl),t);continue}if(e.includes(a))return x0(n,fe(a),t),S4('respond with "%s" for "%s"',a,a),o(),{stream:s,protocol:a};if(a==="ls"){x0(n,new ln(...e.map(c=>E4(fe(c)))),t),S4('respond with "%s" for %s',e,a);continue}x0(n,fe("na"),t),S4('respond with "na" for "%s"',a)}}var LB=C(ee(),1);var Vpe=Symbol.for("@libp2p/connection");var fVe=ue("libp2p:connection"),BB=class{constructor(e){let{remoteAddr:t,remotePeer:n,newStream:i,close:o,getStreams:s,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.stat={...a,status:y9},this._newStream=i,this._close=o,this._getStreams=s,this.tags=[],this._closing=!1}get[Symbol.toStringTag](){return"Connection"}get[Vpe](){return!0}get streams(){return this._getStreams()}async newStream(e,t){if(this.stat.status===zL)throw(0,LB.default)(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===w9)throw(0,LB.default)(new Error("the connection is closed"),"ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,t);return n.stat.direction="outbound",n}addStream(e){e.stat.direction="inbound"}removeStream(e){}async close(){if(!(this.stat.status===w9||this._closing)){this.stat.status=zL;try{this.streams.forEach(e=>e.close())}catch(e){fVe.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=w9}}};function Kpe(r){return new BB(r)}var Y9=C(ee(),1);var W9=Symbol.for("@libp2p/topology");function $pe(r){return r!=null&&!!r[W9]}var MB=ue("libp2p:registrar"),UB=32,FB=64,Q9=class{constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onProtocolChange=this._onProtocolChange.bind(this),this._onConnect=this._onConnect.bind(this),this.components.connectionManager.addEventListener("peer:disconnect",this._onDisconnect),this.components.connectionManager.addEventListener("peer:connect",this._onConnect),this.components.peerStore.addEventListener("change:protocols",this._onProtocolChange)}getProtocols(){return Array.from(new Set([...this.topologies.keys(),...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw(0,Y9.default)(new Error(`No handler registered for protocol ${e}`),q.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw(0,Y9.default)(new Error(`Handler already registered for protocol ${e}`),q.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=et.bind({ignoreUndefined:!0})({maxInboundStreams:UB,maxOutboundStreams:FB},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.protoBook.add(this.components.peerId,[e])}async unhandle(e){let t=Array.isArray(e)?e:[e];t.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.protoBook.remove(this.components.peerId,t)}async register(e,t){if(!$pe(t))throw MB.error("topology must be an instance of interfaces/topology"),(0,Y9.default)(new Error("topology must be an instance of interfaces/topology"),q.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,t),await t.setRegistrar(this),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.protoBook.get(t.remotePeer).then(n=>{for(let i of n){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect(t.remotePeer)}}).catch(n=>{MB.error(n)})}_onConnect(e){let t=e.detail;this.components.peerStore.protoBook.get(t.remotePeer).then(n=>{for(let i of n){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onConnect(t.remotePeer,t)}}).catch(n=>{MB.error(n)})}_onProtocolChange(e){let{peerId:t,protocols:n,oldProtocols:i}=e.detail,o=i.filter(a=>!n.includes(a)),s=n.filter(a=>!i.includes(a));for(let a of o){let c=this.topologies.get(a);if(c!=null)for(let u of c.values())u.onDisconnect(t)}for(let a of s){let c=this.topologies.get(a);if(c!=null)for(let u of c.values()){let l=this.components.connectionManager.getConnections(t)[0];l!=null&&u.onConnect(t,l)}}}};var zB=C(Kn(),1);var VB=C(xi(),1),Pr=ue("libp2p:upgrader");function dVe(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==q.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return UB}function hVe(r,e){try{let{options:t}=e.getHandler(r);return t.maxOutboundStreams}catch(t){if(t.code!==q.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return FB}function qpe(r,e,t){let n=0;return t.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===r&&n++}),n}var X9=class extends Zt{constructor(e,t){super(),this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout}async upgradeInbound(e,t){var l,f;if(!await this.components.connectionManager.acceptIncomingConnection(e))throw(0,Wn.default)(new Error("connection denied"),q.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=new zB.TimeoutController(this.inboundUpgradeTimeout);try{(l=VB.setMaxListeners)==null||l(1/0,u.signal)}catch{}try{let h=ps(e,u.signal);if(e.source=h.source,e.sink=h.sink,await this.components.connectionGater.denyInboundConnection(e))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptConnection"),q.ERR_CONNECTION_INTERCEPTED);(f=this.components.metrics)==null||f.trackMultiaddrConnection(e),Pr("starting the inbound connection upgrade");let d=e;if((t==null?void 0:t.skipProtection)!==!0){let p=this.components.connectionProtector;p!=null&&(Pr("protecting the inbound connection"),d=await p.protect(e))}try{if(i=d,(t==null?void 0:t.skipEncryption)!==!0){if({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(d),await this.components.connectionGater.denyInboundEncryptedConnection(o,{...d,...i}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED)}else{let p=e.remoteAddr.getPeerId();if(p==null)throw(0,Wn.default)(new Error("inbound connection that skipped encryption must have a peer id"),q.ERR_INVALID_MULTIADDR);let g=xt(p);c="native",o=g}if(s=i,(t==null?void 0:t.muxerFactory)!=null)a=t.muxerFactory;else if(this.muxers.size>0){let p=await this._multiplexInbound({...d,...i},this.muxers);a=p.muxerFactory,s=p.stream}}catch(p){throw Pr.error("Failed to upgrade inbound connection",p),p}if(await this.components.connectionGater.denyInboundUpgradedConnection(o,{...d,...i}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED);return Pr("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,t){var f;let n=e.remoteAddr.getPeerId(),i;if(n!=null&&(i=xt(n),await this.components.connectionGater.denyOutboundConnection(i,e)))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),q.ERR_CONNECTION_INTERCEPTED);let o,s,a,c,u;(f=this.components.metrics)==null||f.trackMultiaddrConnection(e),Pr("Starting the outbound connection upgrade");let l=e;if((t==null?void 0:t.skipProtection)!==!0){let h=this.components.connectionProtector;h!=null&&(l=await h.protect(e))}try{if(o=l,(t==null?void 0:t.skipEncryption)!==!0){if({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i),await this.components.connectionGater.denyOutboundEncryptedConnection(s,{...l,...o}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED)}else{if(i==null)throw(0,Wn.default)(new Error("Encryption was skipped but no peer id was passed"),q.ERR_INVALID_PEER);c="native",s=i}if(a=o,(t==null?void 0:t.muxerFactory)!=null)u=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...l,...o},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw Pr.error("Failed to upgrade outbound connection",h),await e.close(h),h}if(await this.components.connectionGater.denyOutboundUpgradedConnection(s,{...l,...o}))throw(0,Wn.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),q.ERR_CONNECTION_INTERCEPTED);return Pr("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{var m;let p=this.components.registrar.getProtocols(),{stream:g,protocol:w}=await A4(d,p);if(Pr("%s: incoming stream opened on %s",n,w),l==null)return;let _=dVe(w,this.components.registrar);if(qpe(w,"inbound",l)===_){d.abort((0,Wn.default)(new Error(`Too many inbound protocol streams for protocol "${w}" - limit ${_}`),q.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS));return}d.source=g.source,d.sink=g.sink,d.stat.protocol=w,this.components.peerStore.protoBook.add(s,[w]).catch(y=>Pr.error(y)),l.addStream(d),(m=this.components.metrics)==null||m.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:w})}).catch(p=>{Pr.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l==null||l.removeStream(d.id)}}),u=async(d,p={})=>{var _,x;if(c==null)throw(0,Wn.default)(new Error("Stream is not multiplexed"),q.ERR_MUXER_UNAVAILABLE);Pr("%s: starting new stream on %s",n,d);let g=await c.newStream(),w;try{if(p.signal==null){Pr("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),w=new zB.TimeoutController(3e4),p.signal=w.signal;try{(_=VB.setMaxListeners)==null||_(1/0,w.signal)}catch{}}let{stream:m,protocol:y}=await x4(g,d,p),b=hVe(y,this.components.registrar);if(qpe(y,"outbound",l)===b){let v=(0,Wn.default)(new Error(`Too many outbound protocol streams for protocol "${y}" - limit ${b}`),q.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw g.abort(v),v}return this.components.peerStore.protoBook.add(s,[y]).catch(v=>Pr.error(v)),g.source=m.source,g.sink=m.sink,g.stat.protocol=y,(x=this.components.metrics)==null||x.trackProtocolStream(g,l),g}catch(m){throw Pr.error("could not create new stream",m),g.stat.timeline.close==null&&g.close(),m.code!=null?m:(0,Wn.default)(m,q.ERR_UNSUPPORTED_PROTOCOL)}finally{w!=null&&w.clear()}},Promise.all([c.sink(o.source),o.sink(c.source)]).catch(d=>{Pr.error(d)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){Pr.error(p)}finally{this.dispatchEvent(new ve("connectionEnd",{detail:l}))}})().catch(p=>{Pr.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let h=()=>{throw(0,Wn.default)(new Error("connection is not multiplexed"),q.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Kpe({remoteAddr:i.remoteAddr,remotePeer:s,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c==null?void 0:c.protocol,encryption:t},newStream:u??h,getStreams:()=>c!=null?c.streams:h(),close:async()=>{await i.close(),c!=null&&c.close()}}),this.dispatchEvent(new ve("connection",{detail:l})),l}_onStream(e){let{connection:t,stream:n,protocol:i}=e,{handler:o}=this.components.registrar.getHandler(i);o({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());Pr("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:i}=await A4(e,t,{writeBytes:!0}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return Pr("encrypting inbound connection..."),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw(0,Wn.default)(n,q.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());Pr("selecting outbound crypto protocol",n);try{let{stream:i,protocol:o}=await x4(e,n,{writeBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return Pr("encrypting outbound connection to %p",t),{...await s.secureOutbound(this.components.peerId,i,t),protocol:o}}catch(i){throw(0,Wn.default)(i,q.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());Pr("outbound selecting muxer %s",n);try{let{stream:i,protocol:o}=await x4(e,n,{writeBytes:!0});Pr("%s selected as muxer protocol",o);let s=t.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Pr.error("error multiplexing outbound stream",i),(0,Wn.default)(i,q.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());Pr("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await A4(e,n,{writeBytes:!0}),s=t.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Pr.error("error multiplexing inbound stream",i),(0,Wn.default)(i,q.ERR_MUXER_UNAVAILABLE)}}};var A0=C(ee(),1);var S0;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(S0||(S0={}));var Gpe=C(ee(),1);var Hpe={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var T4;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.publicKey!=null&&t.publicKey.byteLength>0)&&(n.uint32(10),n.bytes(t.publicKey)),(i.writeDefaults===!0||t.payloadType!=null&&t.payloadType.byteLength>0)&&(n.uint32(18),n.bytes(t.payloadType)),(i.writeDefaults===!0||t.payload!=null&&t.payload.byteLength>0)&&(n.uint32(26),n.bytes(t.payload)),(i.writeDefaults===!0||t.signature!=null&&t.signature.byteLength>0)&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(T4||(T4={}));var pVe,Yn=class{constructor(e){let{peerId:t,payloadType:n,payload:i,signature:o}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=T4.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return rr(this.marshal(),e.marshal())}async validate(e){let t=jpe(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await g4(this.peerId.publicKey).verify(t.subarray(),this.signature)}};pVe=Yn;Yn.createFromProtobuf=async r=>{let e=T4.decode(r),t=await Yd(e.publicKey);return new Yn({peerId:t,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};Yn.seal=async(r,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let t=r.domain,n=r.codec,i=r.marshal(),o=jpe(t,n,i),a=await(await dg(e.privateKey)).sign(o.subarray());return new Yn({peerId:e,payloadType:n,payload:i,signature:a})};Yn.openAndCertify=async(r,e)=>{let t=await Yn.createFromProtobuf(r);if(!await t.validate(e))throw(0,Gpe.default)(new Error("envelope signature is not valid for the given domain"),Hpe.ERR_SIGNATURE_NOT_VALID);return t};var jpe=(r,e,t)=>{let n=fe(r),i=nc.encode(n.byteLength),o=nc.encode(e.length),s=nc.encode(t.length);return new ln(i,n,o,e,s,t)};function Wpe(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var I4;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=Cr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),(a.writeDefaults===!0||o.multiaddr!=null&&o.multiaddr.byteLength>0)&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>Rr(o,n.codec()),n.decode=o=>Ir(o,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Cr((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),(o.writeDefaults===!0||n.peerId!=null&&n.peerId.byteLength>0)&&(i.uint32(10),i.bytes(n.peerId)),(o.writeDefaults===!0||n.seq!==0n)&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(s,i,{writeDefaults:!0});o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),t),r.encode=n=>Rr(n,r.codec()),r.decode=n=>Ir(n,r.codec())})(I4||(I4={}));var Ype="libp2p-peer-record",Qpe=Uint8Array.from([3,1]);var Mn=class{constructor(e){this.domain=Mn.DOMAIN,this.codec=Mn.CODEC;let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=I4.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Mn)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Wpe(this.multiaddrs,e.multiaddrs))}};Mn.createFromProtobuf=r=>{let e=I4.decode(r),t=Wd(e.peerId),n=(e.addresses??[]).map(o=>lt(o.multiaddr)),i=e.seq;return new Mn({peerId:t,multiaddrs:n,seqNumber:i})};Mn.DOMAIN=Ype;Mn.CODEC=Qpe;var Z9="0.0.0",Xpe="libp2p";var KB=`js-libp2p/${Z9}`;var Zpe="0.1.0",Jpe="id",e0e="id/push",t0e="1.0.0",r0e="1.0.0";var R4=C(Kn(),1);var C4=C(xi(),1),vr=ue("libp2p:identify"),n0e=1024*8,mg=class{constructor(e,t){this.components=e,this.started=!1,this.init=t,this.identifyProtocolStr=`/${t.protocolPrefix}/${Jpe}/${t0e}`,this.identifyPushProtocolStr=`/${t.protocolPrefix}/${e0e}/${r0e}`,this.host={protocolVersion:`${t.protocolPrefix}/${Zpe}`,...t.host},this.components.connectionManager.addEventListener("peer:connect",n=>{let i=n.detail;this.identify(i).catch(vr.error)}),this.components.peerStore.addEventListener("change:multiaddrs",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(o=>vr.error(o))}),this.components.peerStore.addEventListener("change:protocols",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(o=>vr.error(o))})}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.metadataBook.setValue(this.components.peerId,"AgentVersion",fe(this.host.agentVersion)),await this.components.peerStore.metadataBook.setValue(this.components.peerId,"ProtocolVersion",fe(this.host.protocolVersion)),await this.components.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{vr.error(t)})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),await this.components.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{vr.error(t)})},{maxInboundStreams:this.init.maxPushIncomingStreams,maxOutboundStreams:this.init.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.identifyProtocolStr),await this.components.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async push(e){let t=await this.components.peerStore.addressBook.getRawEnvelope(this.components.peerId),n=this.components.addressManager.getAddresses().map(s=>s.bytes),i=await this.components.peerStore.protoBook.get(this.components.peerId),o=e.map(async s=>{var u;let a,c=new R4.TimeoutController(this.init.timeout);try{(u=C4.setMaxListeners)==null||u(1/0,c.signal)}catch{}try{a=await s.newStream([this.identifyPushProtocolStr],{signal:c.signal}),await ps(a,c.signal).sink(Ne([S0.encode({listenAddrs:n,signedPeerRecord:t,protocols:i})],vn()))}catch(l){vr.error("could not push identify update to peer",l)}finally{a!=null&&a.close(),c.clear()}});await Promise.all(o)}async pushToPeerStore(){if(!this.isStarted())return;let e=[];for(let t of this.components.connectionManager.getConnections()){let n=t.remotePeer;(await this.components.peerStore.get(n)).protocols.includes(this.identifyPushProtocolStr)&&e.push(t)}await this.push(e)}async _identify(e,t={}){var s;let n,i=t.signal,o;if(i==null){n=new R4.TimeoutController(this.init.timeout),i=n.signal;try{(s=C4.setMaxListeners)==null||s(1/0,n.signal)}catch{}}try{o=await e.newStream([this.identifyProtocolStr],{signal:i});let a=ps(o,i),c=await Ne([],a,Xr({maxDataLength:this.init.maxIdentifyMessageSize??n0e}),async u=>await Fi(u));if(c==null)throw(0,A0.default)(new Error("No data could be retrieved"),q.ERR_CONNECTION_ENDED);try{return S0.decode(c)}catch(u){throw(0,A0.default)(u,q.ERR_INVALID_MESSAGE)}}finally{n!=null&&n.clear(),o!=null&&o.close()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,listenAddrs:o,protocols:s,observedAddr:a,signedPeerRecord:c,agentVersion:u,protocolVersion:l}=n;if(i==null)throw(0,A0.default)(new Error("public key was missing from identify message"),q.ERR_MISSING_PUBLIC_KEY);let f=await Yd(i);if(!e.remotePeer.equals(f))throw(0,A0.default)(new Error("identified peer does not match the expected peer"),q.ERR_INVALID_PEER);if(this.components.peerId.equals(f))throw(0,A0.default)(new Error("identified peer is our own peer id?"),q.ERR_INVALID_PEER);let h=mg.getCleanMultiaddr(a);if(c!=null){vr("received signed peer record from %p",f);try{let d=await Yn.openAndCertify(c,Mn.DOMAIN);if(!d.peerId.equals(f))throw(0,A0.default)(new Error("identified peer does not match the expected peer"),q.ERR_INVALID_PEER);if(await this.components.peerStore.addressBook.consumePeerRecord(d)){await this.components.peerStore.protoBook.set(f,s),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",fe(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",fe(l)),vr("identify completed for peer %p and protocols %o",f,s);return}}catch(d){vr("received invalid envelope, discard it and fallback to listenAddrs is available",d)}}else vr("no signed peer record received from %p",f);vr("falling back to legacy addresses from %p",f);try{await this.components.peerStore.addressBook.set(f,o.map(d=>lt(d)))}catch(d){vr.error("received invalid addrs",d)}await this.components.peerStore.protoBook.set(f,s),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",fe(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",fe(l)),vr("identify completed for peer %p and protocols %o",f,s),vr("received observed address of %s",h==null?void 0:h.toString())}async _handleIdentify(e){var o;let{connection:t,stream:n}=e,i=new R4.TimeoutController(this.init.timeout);try{(o=C4.setMaxListeners)==null||o(1/0,i.signal)}catch{}try{let s=this.components.peerId.publicKey??new Uint8Array(0),a=await this.components.peerStore.get(this.components.peerId),c=this.components.addressManager.getAddresses().map(d=>d.decapsulateCode(hr("p2p").code)),u=a.peerRecordEnvelope;if(c.length>0&&u==null){let d=new Mn({peerId:this.components.peerId,multiaddrs:c}),p=await Yn.seal(d,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(p),u=p.marshal().subarray()}let l=S0.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:c.map(d=>d.bytes),signedPeerRecord:u,observedAddr:t.remoteAddr.bytes,protocols:a.protocols}),f=ps(n,i.signal),h=Ne([l],vn());await f.sink(h)}catch(s){vr.error("could not respond to identify request",s)}finally{n.close(),i.clear()}}async _handlePush(e){var a;let{connection:t,stream:n}=e,i=new R4.TimeoutController(this.init.timeout);try{(a=C4.setMaxListeners)==null||a(1/0,i.signal)}catch{}let o;try{let c=ps(n,i.signal),u=await Ne([],c,Xr({maxDataLength:this.init.maxIdentifyMessageSize??n0e}),async l=>await Fi(l));u!=null&&(o=S0.decode(u))}catch(c){return vr.error("received invalid message",c)}finally{n.close(),i.clear()}if(o==null)return vr.error("received invalid message");let s=t.remotePeer;if(this.components.peerId.equals(s)){vr("received push from ourselves?");return}if(vr("received push from %p",s),o.signedPeerRecord!=null){vr("received signedPeerRecord in push");try{let c=await Yn.openAndCertify(o.signedPeerRecord,Mn.DOMAIN);if(await this.components.peerStore.addressBook.consumePeerRecord(c)){vr("consumed signedPeerRecord sent in push"),await this.components.peerStore.protoBook.set(s,o.protocols);return}else vr("failed to consume signedPeerRecord sent in push")}catch(c){vr("received invalid envelope, discard it and fallback to listenAddrs is available",c)}}else vr("did not receive signedPeerRecord in push");try{await this.components.peerStore.addressBook.set(s,o.listenAddrs.map(c=>lt(c)))}catch(c){vr.error("received invalid addrs",c)}try{await this.components.peerStore.protoBook.set(s,o.protocols)}catch(c){vr.error("received invalid protocols",c)}vr("handled push from %p",s)}static getCleanMultiaddr(e){if(e!=null&&e.length>0)try{return lt(e)}catch{}}};var gg=C(ee(),1);var P4;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identifier!=="")&&(n.uint32(10),n.string(t.identifier)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identifier:""},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.identifier=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(P4||(P4={}));var ac;(function(r){let e;(function(i){i.OK="OK",i.NOT_FOUND="NOT_FOUND",i.ERROR="ERROR"})(e=r.StatusCode||(r.StatusCode={}));let t;(function(i){i[i.OK=0]="OK",i[i.NOT_FOUND=1]="NOT_FOUND",i[i.ERROR=2]="ERROR"})(t||(t={})),function(i){i.codec=()=>Jd(t)}(e=r.StatusCode||(r.StatusCode={}));let n;r.codec=()=>(n==null&&(n=Cr((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),(s.writeDefaults===!0||i.status!=null&&t[i.status]!==0)&&(o.uint32(8),r.StatusCode.codec().encode(i.status,o)),(s.writeDefaults===!0||i.data!=null&&i.data.byteLength>0)&&(o.uint32(18),o.bytes(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={status:e.OK,data:new Uint8Array(0)},a=o==null?i.len:i.pos+o;for(;i.pos>>3){case 1:s.status=r.StatusCode.codec().decode(i);break;case 2:s.data=i.bytes();break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>Rr(i,r.codec()),r.decode=i=>Ir(i,r.codec())})(ac||(ac={}));var i0e="0.0.1",o0e="fetch";var s0e=C(Kn(),1),a0e=C(xi(),1);var da=ue("libp2p:fetch"),J9=class{constructor(e,t){this.started=!1,this.components=e,this.protocol=`/${t.protocolPrefix??"libp2p"}/${o0e}/${i0e}`,this.lookupFunctions=new Map,this.handleMessage=this.handleMessage.bind(this),this.init=t}async start(){await this.components.registrar.handle(this.protocol,e=>{this.handleMessage(e).catch(t=>{da.error(t)}).finally(()=>{e.stream.close()})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async fetch(e,t,n={}){var c;da("dialing %s to %p",this.protocol,e);let i=await this.components.connectionManager.openConnection(e,n),o,s=n.signal,a;if(s==null){da("using default timeout of %d ms",this.init.timeout),o=new s0e.TimeoutController(this.init.timeout),s=o.signal;try{(c=a0e.setMaxListeners)==null||c(1/0,o.signal)}catch{}}try{a=await i.newStream(this.protocol,{signal:s});let u=ps(a,s);return da("fetch %s",t),await Ne([P4.encode({identifier:t})],vn(),u,Xr(),async function(f){let h=await Fi(f);if(h==null)throw(0,gg.default)(new Error("No data received"),q.ERR_INVALID_MESSAGE);let d=ac.decode(h);switch(d.status){case ac.StatusCode.OK:return da("received status for %s ok",t),d.data;case ac.StatusCode.NOT_FOUND:return da("received status for %s not found",t),null;case ac.StatusCode.ERROR:{da("received status for %s error",t);let p=Ee(d.data);throw(0,gg.default)(new Error("Error in fetch protocol response: "+p),q.ERR_INVALID_PARAMETERS)}default:throw da("received status for %s unknown",t),(0,gg.default)(new Error("Unknown response status"),q.ERR_INVALID_MESSAGE)}})??null}finally{o!=null&&o.clear(),a!=null&&a.close()}}async handleMessage(e){let{stream:t}=e,n=this;await Ne(t,Xr(),async function*(i){let o=await Fi(i);if(o==null)throw(0,gg.default)(new Error("No data received"),q.ERR_INVALID_MESSAGE);let s=P4.decode(o),a,c=n._getLookupFunction(s.identifier);if(c!=null){da("look up data with identifier %s",s.identifier);let u=await c(s.identifier);u!=null?(da("sending status for %s ok",s.identifier),a={status:ac.StatusCode.OK,data:u}):(da("sending status for %s not found",s.identifier),a={status:ac.StatusCode.NOT_FOUND,data:new Uint8Array(0)})}else{da("sending status for %s error",s.identifier);let u=fe(`No lookup function registered for key: ${s.identifier}`);a={status:ac.StatusCode.ERROR,data:u}}yield ac.encode(a)},vn(),t)}_getLookupFunction(e){for(let t of this.lookupFunctions.keys())if(e.startsWith(t))return this.lookupFunctions.get(t)}registerLookupFunction(e,t){if(this.lookupFunctions.has(e))throw(0,gg.default)(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),q.ERR_KEY_ALREADY_EXISTS);this.lookupFunctions.set(e,t)}unregisterLookupFunction(e,t){t!=null&&this.lookupFunctions.get(e)!==t||this.lookupFunctions.delete(e)}};var f0e=C(ee(),1);var c0e="1.0.0",u0e="ping";var d0e=C(Kn(),1),h0e=C(xi(),1),l0e=ue("libp2p:ping"),ex=class{constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix}/${u0e}/${c0e}`,this.init=t}async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){let{stream:t}=e;Ne(t,t).catch(n=>{l0e.error(n)})}async ping(e,t={}){var u;l0e("dialing %s to %p",this.protocol,e);let n=Date.now(),i=Bl(32),o=await this.components.connectionManager.openConnection(e,t),s,a=t.signal,c;if(a==null){s=new d0e.TimeoutController(this.init.timeout),a=s.signal;try{(u=h0e.setMaxListeners)==null||u(1/0,s.signal)}catch{}}try{c=await o.newStream([this.protocol],{signal:a});let l=ps(c,a),f=await Ne([i],l,async d=>await Fi(d)),h=Date.now();if(f==null||!rr(i,f.subarray()))throw(0,f0e.default)(new Error("Received wrong ping ack"),q.ERR_WRONG_PING_ACK);return h-n}finally{s!=null&&s.clear(),c!=null&&c.close()}}};async function p0e(){throw new Error("Not supported in browsers")}var m0e=C(EA(),1),$B=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,tx=(0,m0e.default)(),T0=$B&&!tx,g0e=tx&&!$B,y0e=tx&&$B,w0e=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!tx,rx=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,FYt=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",b0e=typeof navigator<"u"&&navigator.product==="ReactNative";var v0e=C(ee(),1);function _0e(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function E0e(r){let{address:e}=r.nodeAddress();return _0e(e)}var qB=ue("libp2p:nat"),HB=7200;function yVe(r=1024,e=65535){return Math.floor(Math.random()*(e-r+1)+r)}var nx=class{constructor(e,t){if(this.components=e,this.started=!1,this.enabled=t.enabled,this.externalAddress=t.externalAddress,this.localAddress=t.localAddress,this.description=t.description??`${Xpe}@${Z9} ${this.components.peerId.toString()}`,this.ttl=t.ttl??HB,this.keepAlive=t.keepAlive??!0,this.gateway=t.gateway,this.ttl{qB.error(e)}))}async _start(){let e=this.components.transportManager.getAddrs();for(let t of e){let{family:n,host:i,port:o,transport:s}=t.toOptions();if(!t.isThinWaistAddress()||s!=="tcp"||E0e(t)||n!==4)continue;let a=await this._getClient(),c=this.externalAddress??await a.externalIp(),u=D9(c);if(u===!0)throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);if(u==null)throw new Error(`${c} is not an IP address`);let l=yVe();qB(`opening uPnP connection from ${c}:${l} to ${i}:${o}`),await a.map({publicPort:l,localPort:o,localAddress:this.localAddress,protocol:s.toUpperCase()==="TCP"?"TCP":"UDP"}),this.components.addressManager.addObservedAddr(oie({family:4,address:c,port:l},s))}}async _getClient(){return this.client!=null?this.client:(this.client=await p0e({description:this.description,ttl:this.ttl,keepAlive:this.keepAlive,gateway:this.gateway}),this.client)}async stop(){if(!(T0||this.client==null))try{await this.client.close(),this.client=void 0}catch(e){qB.error(e)}}};var wVe=ue("libp2p:peer-record-updater"),ix=class{constructor(e){this.components=e,this.started=!1,this.update=this.update.bind(this)}isStarted(){return this.started}async start(){this.started=!0,this.components.transportManager.addEventListener("listener:listening",this.update),this.components.transportManager.addEventListener("listener:close",this.update),this.components.addressManager.addEventListener("change:addresses",this.update)}async stop(){this.started=!1,this.components.transportManager.removeEventListener("listener:listening",this.update),this.components.transportManager.removeEventListener("listener:close",this.update),this.components.addressManager.removeEventListener("change:addresses",this.update)}update(){Promise.resolve().then(async()=>{let e=new Mn({peerId:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(n=>n.decapsulateCode(hr("p2p").code))}),t=await Yn.seal(e,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(t)}).catch(e=>{wVe.error("Could not update self peer record: %o",e)})}};var x0e=C(ee(),1);var ox=class{constructor(e){this.dht=e}async findPeer(e,t={}){for await(let n of this.dht.findPeer(e,t))if(n.name==="FINAL_PEER")return n.peer;throw(0,x0e.default)(new Error(Rt.NOT_FOUND),q.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){for await(let n of this.dht.getClosestPeers(e,t))n.name==="FINAL_PEER"&&(yield n.peer)}};var ax=C(ee(),1);var St={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_NOT_FOUND:"ERR_NOT_FOUND"};async function*GB(r,e){for await(let t of r)await e(t),yield t}var Er=ue("libp2p:peer-store:address-book"),sx="change:multiaddrs";async function bVe(){return!0}var cx=class{constructor(e,t,n){this.dispatchEvent=e,this.store=t,this.addressFilter=n??bVe}async consumePeerRecord(e){Er.trace("consumePeerRecord await write lock");let t=await this.store.lock.writeLock();Er.trace("consumePeerRecord got write lock");let n,i,o;try{let s;try{s=Mn.createFromProtobuf(e.payload)}catch{return Er.error("invalid peer record received"),!1}n=s.peerId;let a=s.multiaddrs;if(!n.equals(e.peerId))return Er("signing key does not match PeerId in the PeerRecord"),!1;if(a==null||a.length===0)return!1;if(await this.store.has(n)&&(i=await this.store.load(n),i.peerRecordEnvelope!=null)){let u=await Yn.createFromProtobuf(i.peerRecordEnvelope),l=Mn.createFromProtobuf(u.payload);if(l.seqNumber>=s.seqNumber)return Er("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,s.seqNumber),!1}let c=await jB(n,a,this.addressFilter,!0);o=await this.store.patchOrCreate(n,{addresses:c,peerRecordEnvelope:e.marshal().subarray()}),Er("stored provided peer record for %p",s.peerId)}finally{Er.trace("consumePeerRecord release write lock"),t()}return this.dispatchEvent(new ve(sx,{detail:{peerId:n,multiaddrs:o.addresses.map(({multiaddr:s})=>s),oldMultiaddrs:i==null?[]:i.addresses.map(({multiaddr:s})=>s)}})),!0}async getRawEnvelope(e){Er.trace("getRawEnvelope await read lock");let t=await this.store.lock.readLock();Er.trace("getRawEnvelope got read lock");try{return(await this.store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Er.trace("getRawEnvelope release read lock"),t()}}async getPeerRecord(e){let t=await this.getRawEnvelope(e);if(t!=null)return await Yn.createFromProtobuf(t)}async get(e){e=xn(e),Er.trace("get wait for read lock");let t=await this.store.lock.readLock();Er.trace("get got read lock");try{return(await this.store.load(e)).addresses}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Er.trace("get release read lock"),t()}return[]}async set(e,t){if(e=xn(e),!Array.isArray(t))throw Er.error("multiaddrs must be an array of Multiaddrs"),(0,ax.default)(new Error("multiaddrs must be an array of Multiaddrs"),St.ERR_INVALID_PARAMETERS);Er.trace("set await write lock");let n=await this.store.lock.writeLock();Er.trace("set got write lock");let i=!1,o,s;try{let a=await jB(e,t,this.addressFilter);if(a.length===0)return;try{if(o=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...o.addresses.map(({multiaddr:c})=>c.toString())]).size===o.addresses.length&&a.length===o.addresses.length)return}catch(c){if(c.code!==St.ERR_NOT_FOUND)throw c}s=await this.store.patchOrCreate(e,{addresses:a}),Er("set multiaddrs for %p",e)}finally{Er.trace("set multiaddrs for %p",e),Er("set release write lock"),n()}this.dispatchEvent(new ve(sx,{detail:{peerId:e,multiaddrs:s.addresses.map(a=>a.multiaddr),oldMultiaddrs:o==null?[]:o.addresses.map(({multiaddr:a})=>a)}})),i||this.dispatchEvent(new ve("peer",{detail:{id:e,multiaddrs:s.addresses.map(a=>a.multiaddr),protocols:s.protocols}}))}async add(e,t){if(e=xn(e),!Array.isArray(t))throw Er.error("multiaddrs must be an array of Multiaddrs"),(0,ax.default)(new Error("multiaddrs must be an array of Multiaddrs"),St.ERR_INVALID_PARAMETERS);Er.trace("add await write lock");let n=await this.store.lock.writeLock();Er.trace("add got write lock");let i,o,s;try{let a=await jB(e,t,this.addressFilter);if(a.length===0)return;try{if(o=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...o.addresses.map(({multiaddr:c})=>c.toString())]).size===o.addresses.length)return}catch(c){if(c.code!==St.ERR_NOT_FOUND)throw c}s=await this.store.mergeOrCreate(e,{addresses:a}),Er("added multiaddrs for %p",e)}finally{Er.trace("set release write lock"),n()}this.dispatchEvent(new ve(sx,{detail:{peerId:e,multiaddrs:s.addresses.map(a=>a.multiaddr),oldMultiaddrs:o==null?[]:o.addresses.map(({multiaddr:a})=>a)}})),i===!0&&this.dispatchEvent(new ve("peer",{detail:{id:e,multiaddrs:s.addresses.map(a=>a.multiaddr),protocols:s.protocols}}))}async delete(e){e=xn(e),Er.trace("delete await write lock");let t=await this.store.lock.writeLock();Er.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{addresses:[]})}finally{Er.trace("delete release write lock"),t()}n!=null&&this.dispatchEvent(new ve(sx,{detail:{peerId:e,multiaddrs:[],oldMultiaddrs:n==null?[]:n.addresses.map(({multiaddr:i})=>i)}}))}};async function jB(r,e,t,n=!1){return await Ne(e,i=>GB(i,o=>{if(!as(o))throw Er.error("multiaddr must be an instance of Multiaddr"),(0,ax.default)(new Error("multiaddr must be an instance of Multiaddr"),St.ERR_INVALID_PARAMETERS)}),i=>Yt(i,async o=>await t(r,o)),i=>Bi(i,o=>({multiaddr:o,isCertified:n})),async i=>await Wo(i))}var A0e=C(ee(),1);var _u=ue("libp2p:peer-store:key-book"),S0e="change:pubkey",ux=class{constructor(e,t){this.dispatchEvent=e,this.store=t}async set(e,t){if(e=xn(e),!(t instanceof Uint8Array))throw _u.error("publicKey must be an instance of Uint8Array to store data"),(0,A0e.default)(new Error("publicKey must be an instance of PublicKey"),St.ERR_INVALID_PARAMETERS);_u.trace("set await write lock");let n=await this.store.lock.writeLock();_u.trace("set got write lock");let i=!1,o;try{try{if(o=await this.store.load(e),o.pubKey!=null&&rr(o.pubKey,t))return}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}await this.store.patchOrCreate(e,{pubKey:t}),i=!0}finally{_u.trace("set release write lock"),n()}i&&this.dispatchEvent(new ve(S0e,{detail:{peerId:e,publicKey:t,oldPublicKey:o==null?void 0:o.pubKey}}))}async get(e){e=xn(e),_u.trace("get await write lock");let t=await this.store.lock.readLock();_u.trace("get got write lock");try{return(await this.store.load(e)).pubKey}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{_u("get release write lock"),t()}}async delete(e){e=xn(e),_u.trace("delete await write lock");let t=await this.store.lock.writeLock();_u.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{pubKey:void 0})}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}finally{_u.trace("delete release write lock"),t()}this.dispatchEvent(new ve(S0e,{detail:{peerId:e,publicKey:void 0,oldPublicKey:n==null?void 0:n.pubKey}}))}};var WB=C(ee(),1);var Un=ue("libp2p:peer-store:metadata-book"),lx="change:metadata",fx=class{constructor(e,t){this.dispatchEvent=e,this.store=t}async get(e){e=xn(e),Un.trace("get await read lock");let t=await this.store.lock.readLock();Un.trace("get got read lock");try{return(await this.store.load(e)).metadata}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Un.trace("get release read lock"),t()}return new Map}async getValue(e,t){e=xn(e),Un.trace("getValue await read lock");let n=await this.store.lock.readLock();Un.trace("getValue got read lock");try{return(await this.store.load(e)).metadata.get(t)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}finally{Un.trace("getValue release write lock"),n()}}async set(e,t){if(e=xn(e),!(t instanceof Map))throw Un.error("valid metadata must be provided to store data"),(0,WB.default)(new Error("valid metadata must be provided"),St.ERR_INVALID_PARAMETERS);Un.trace("set await write lock");let n=await this.store.lock.writeLock();Un.trace("set got write lock");let i;try{try{i=await this.store.load(e)}catch(o){if(o.code!==St.ERR_NOT_FOUND)throw o}await this.store.mergeOrCreate(e,{metadata:t})}finally{Un.trace("set release write lock"),n()}this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:t,oldMetadata:i==null?new Map:i.metadata}}))}async setValue(e,t,n){if(e=xn(e),typeof t!="string"||!(n instanceof Uint8Array))throw Un.error("valid key and value must be provided to store data"),(0,WB.default)(new Error("valid key and value must be provided"),St.ERR_INVALID_PARAMETERS);Un.trace("setValue await write lock");let i=await this.store.lock.writeLock();Un.trace("setValue got write lock");let o,s;try{try{o=await this.store.load(e);let a=o.metadata.get(t);if(a!=null&&rr(n,a))return}catch(a){if(a.code!==St.ERR_NOT_FOUND)throw a}s=await this.store.mergeOrCreate(e,{metadata:new Map([[t,n]])})}finally{Un.trace("setValue release write lock"),i()}this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:s.metadata,oldMetadata:o==null?new Map:o.metadata}}))}async delete(e){e=xn(e),Un.trace("delete await write lock");let t=await this.store.lock.writeLock();Un.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}n!=null&&await this.store.patch(e,{metadata:new Map})}finally{Un.trace("delete release write lock"),t()}n!=null&&this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:new Map,oldMetadata:n.metadata}}))}async deleteValue(e,t){e=xn(e),Un.trace("deleteValue await write lock");let n=await this.store.lock.writeLock();Un.trace("deleteValue got write lock");let i,o;try{o=await this.store.load(e),i=o.metadata,i.delete(t),await this.store.patch(e,{metadata:i})}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}finally{Un.trace("deleteValue release write lock"),n()}i!=null&&this.dispatchEvent(new ve(lx,{detail:{peerId:e,metadata:i,oldMetadata:o==null?new Map:o.metadata}}))}};var hx=C(ee(),1);var Fn=ue("libp2p:peer-store:proto-book"),dx="change:protocols",px=class{constructor(e,t){this.dispatchEvent=e,this.store=t}async get(e){Fn.trace("get wait for read lock");let t=await this.store.lock.readLock();Fn.trace("get got read lock");try{return(await this.store.load(e)).protocols}catch(n){if(n.code!==St.ERR_NOT_FOUND)throw n}finally{Fn.trace("get release read lock"),t()}return[]}async set(e,t){if(e=xn(e),!Array.isArray(t))throw Fn.error("protocols must be provided to store data"),(0,hx.default)(new Error("protocols must be provided"),St.ERR_INVALID_PARAMETERS);Fn.trace("set await write lock");let n=await this.store.lock.writeLock();Fn.trace("set got write lock");let i,o;try{try{if(i=await this.store.load(e),new Set([...t]).size===i.protocols.length)return}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}o=await this.store.patchOrCreate(e,{protocols:t}),Fn("stored provided protocols for %p",e)}finally{Fn.trace("set release write lock"),n()}this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:o.protocols,oldProtocols:i==null?[]:i.protocols}}))}async add(e,t){if(e=xn(e),!Array.isArray(t))throw Fn.error("protocols must be provided to store data"),(0,hx.default)(new Error("protocols must be provided"),St.ERR_INVALID_PARAMETERS);Fn.trace("add await write lock");let n=await this.store.lock.writeLock();Fn.trace("add got write lock");let i,o;try{try{if(i=await this.store.load(e),new Set([...i.protocols,...t]).size===i.protocols.length)return}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}o=await this.store.mergeOrCreate(e,{protocols:t}),Fn("added provided protocols for %p",e)}finally{Fn.trace("add release write lock"),n()}this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:o.protocols,oldProtocols:i==null?[]:i.protocols}}))}async remove(e,t){if(e=xn(e),!Array.isArray(t))throw Fn.error("protocols must be provided to store data"),(0,hx.default)(new Error("protocols must be provided"),St.ERR_INVALID_PARAMETERS);Fn.trace("remove await write lock");let n=await this.store.lock.writeLock();Fn.trace("remove got write lock");let i,o;try{try{i=await this.store.load(e);let s=new Set(i.protocols);for(let a of t)s.delete(a);if(i.protocols.length===s.size)return;t=Array.from(s)}catch(s){if(s.code!==St.ERR_NOT_FOUND)throw s}o=await this.store.patchOrCreate(e,{protocols:t})}finally{Fn.trace("remove release write lock"),n()}this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:o.protocols,oldProtocols:i==null?[]:i.protocols}}))}async delete(e){e=xn(e),Fn.trace("delete await write lock");let t=await this.store.lock.writeLock();Fn.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{protocols:[]})}finally{Fn.trace("delete release write lock"),t()}n!=null&&this.dispatchEvent(new ve(dx,{detail:{peerId:e,protocols:[],oldProtocols:n.protocols}}))}};var YB=C(ee(),1);var k4;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.addresses!=null)for(let o of t.addresses)n.uint32(10),mx.codec().encode(o,n,{writeDefaults:!0});if(t.protocols!=null)for(let o of t.protocols)n.uint32(18),n.string(o);if(t.metadata!=null)for(let o of t.metadata)n.uint32(26),gx.codec().encode(o,n,{writeDefaults:!0});t.pubKey!=null&&(n.uint32(34),n.bytes(t.pubKey)),t.peerRecordEnvelope!=null&&(n.uint32(42),n.bytes(t.peerRecordEnvelope)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={addresses:[],protocols:[],metadata:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.addresses.push(mx.codec().decode(t,t.uint32()));break;case 2:i.protocols.push(t.string());break;case 3:i.metadata.push(gx.codec().decode(t,t.uint32()));break;case 4:i.pubKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(k4||(k4={}));var mx;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.multiaddr!=null&&t.multiaddr.byteLength>0)&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={multiaddr:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(mx||(mx={}));var gx;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.key!=="")&&(n.uint32(10),n.string(t.key)),(i.writeDefaults===!0||t.value!=null&&t.value.byteLength>0)&&(n.uint32(18),n.bytes(t.value)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={key:"",value:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.string();break;case 2:i.value=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(gx||(gx={}));var T0e=ue("libp2p:peer-store:store"),I0e="/peers/",yx=class{constructor(e){this.components=e,this.lock=e5({name:"peer-store",singleProcess:!0})}_peerIdToDatastoreKey(e){if(e.type==null)throw T0e.error("peerId must be an instance of peer-id to store data"),(0,YB.default)(new Error("peerId must be an instance of peer-id"),St.ERR_INVALID_PARAMETERS);let t=e.toCID().toString();return new pe(`${I0e}${t}`)}async has(e){return await this.components.datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this.components.datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let t=await this.components.datastore.get(this._peerIdToDatastoreKey(e)),n=k4.decode(t),i=new Map;for(let o of n.metadata)i.set(o.key,o.value);return{...n,id:e,addresses:n.addresses.map(({multiaddr:o,isCertified:s})=>({multiaddr:lt(o),isCertified:s??!1})),metadata:i,pubKey:n.pubKey??void 0,peerRecordEnvelope:n.peerRecordEnvelope??void 0}}async save(e){if(e.pubKey!=null&&e.id.publicKey!=null&&!rr(e.pubKey,e.id.publicKey))throw T0e.error("peer publicKey bytes do not match peer id publicKey bytes"),(0,YB.default)(new Error("publicKey bytes do not match peer id publicKey bytes"),St.ERR_INVALID_PARAMETERS);let t=new Set,n=e.addresses.filter(s=>t.has(s.multiaddr.toString())?!1:(t.add(s.multiaddr.toString()),!0)).sort((s,a)=>s.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({multiaddr:s,isCertified:a})=>({multiaddr:s.bytes,isCertified:a})),i=[];[...e.metadata.keys()].sort().forEach(s=>{let a=e.metadata.get(s);a!=null&&i.push({key:s,value:a})});let o=k4.encode({addresses:n,protocols:e.protocols.sort(),pubKey:e.pubKey,metadata:i,peerRecordEnvelope:e.peerRecordEnvelope});return await this.components.datastore.put(this._peerIdToDatastoreKey(e.id),o.subarray()),await this.load(e.id)}async patch(e,t){let n=await this.load(e);return await this._patch(e,t,n)}async patchOrCreate(e,t){let n;try{n=await this.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,t,n)}async _patch(e,t,n){return await this.save({...n,...t,id:e})}async merge(e,t){let n=await this.load(e);return await this._merge(e,t,n)}async mergeOrCreate(e,t){let n;try{n=await this.load(e)}catch(i){if(i.code!==St.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,t,n)}async _merge(e,t,n){var o,s;let i=new Map;return n.addresses.forEach(a=>{i.set(a.multiaddr.toString(),a.isCertified)}),(t.addresses??[]).forEach(a=>{let c=a.multiaddr.toString(),l=!!i.get(c)||a.isCertified;i.set(c,l)}),await this.save({id:e,addresses:Array.from(i.entries()).map(([a,c])=>({multiaddr:lt(a),isCertified:c})),protocols:Array.from(new Set([...n.protocols??[],...t.protocols??[]])),metadata:new Map([...((o=n.metadata)==null?void 0:o.entries())??[],...((s=t.metadata)==null?void 0:s.entries())??[]]),pubKey:t.pubKey??(n!=null?n.pubKey:void 0),peerRecordEnvelope:t.peerRecordEnvelope??(n!=null?n.peerRecordEnvelope:void 0)})}async*all(){for await(let e of this.components.datastore.queryKeys({prefix:I0e})){let t=e.toString().split("/")[2],n=Ot.decode(t);yield this.load(Wd(n))}}};var QB=C(ee(),1);var $l;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.tags!=null)for(let o of t.tags)n.uint32(10),wx.codec().encode(o,n,{writeDefaults:!0});i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={tags:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.tags.push(wx.codec().decode(t,t.uint32()));break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})($l||($l={}));var wx;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.name!=="")&&(n.uint32(10),n.string(t.name)),t.value!=null&&(n.uint32(16),n.uint32(t.value)),t.expiry!=null&&(n.uint32(24),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={name:""},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.name=t.string();break;case 2:i.value=t.uint32();break;case 3:i.expiry=t.uint64();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(wx||(wx={}));var ha=ue("libp2p:peer-store"),bx=class extends Zt{constructor(e,t={}){super(),this.components=e,this.store=new yx(e),this.addressBook=new cx(this.dispatchEvent.bind(this),this.store,t.addressFilter),this.keyBook=new ux(this.dispatchEvent.bind(this),this.store),this.metadataBook=new fx(this.dispatchEvent.bind(this),this.store),this.protoBook=new px(this.dispatchEvent.bind(this),this.store)}async forEach(e){ha.trace("getPeers await read lock");let t=await this.store.lock.readLock();ha.trace("getPeers got read lock");try{for await(let n of this.store.all())n.id.equals(this.components.peerId)||e(n)}finally{ha.trace("getPeers release read lock"),t()}}async all(){let e=[];return await this.forEach(t=>{e.push(t)}),e}async delete(e){ha.trace("delete await write lock");let t=await this.store.lock.writeLock();ha.trace("delete got write lock");try{await this.store.delete(e)}finally{ha.trace("delete release write lock"),t()}}async get(e){ha.trace("get await read lock");let t=await this.store.lock.readLock();ha.trace("get got read lock");try{return await this.store.load(e)}finally{ha.trace("get release read lock"),t()}}async has(e){ha.trace("has await read lock");let t=await this.store.lock.readLock();ha.trace("has got read lock");try{return await this.store.has(e)}finally{ha.trace("has release read lock"),t()}}async tagPeer(e,t,n={}){let i=n.value??0,o=Math.round(i),s=n.ttl??void 0;if(o!==i||o<0||o>100)throw(0,QB.default)(new Error("Tag value must be between 0-100"),"ERR_TAG_VALUE_OUT_OF_BOUNDS");let a=await this.metadataBook.getValue(e,"tags"),c=[];a!=null&&(c=$l.decode(a).tags);for(let u of c)if(u.name===t)throw(0,QB.default)(new Error("Peer already tagged"),"ERR_DUPLICATE_TAG");c.push({name:t,value:o,expiry:s==null?void 0:BigInt(Date.now()+s)}),await this.metadataBook.setValue(e,"tags",$l.encode({tags:c}).subarray())}async unTagPeer(e,t){let n=await this.metadataBook.getValue(e,"tags"),i=[];n!=null&&(i=$l.decode(n).tags),i=i.filter(o=>o.name!==t),await this.metadataBook.setValue(e,"tags",$l.encode({tags:i}).subarray())}async getTags(e){let t=await this.metadataBook.getValue(e,"tags"),n=[];t!=null&&(n=$l.decode(t).tags);let i=BigInt(Date.now()),o=n.filter(s=>s.expiry==null||s.expiry>i);return o.length!==n.length&&await this.metadataBook.setValue(e,"tags",$l.encode({tags:o}).subarray()),o.map(s=>({name:s.name,value:s.value??0}))}};var R0e=C(ee(),1),_x=class{constructor(e){this.dht=e}async provide(e){await on(this.dht.provide(e))}async*findProviders(e,t={}){for await(let n of this.dht.findProviders(e,t))n.name==="PROVIDER"&&(yield*n.providers)}async put(e,t,n){await on(this.dht.put(e,t,n))}async get(e,t){for await(let n of this.dht.get(e,t))if(n.name==="VALUE")return n.value;throw(0,R0e.default)(new Error("Not found"),"ERR_NOT_FOUND")}};var _s=C(ee(),1);var Ex=class{constructor(e={}){this._started=!1,this._peerId=e.peerId,this._addressManager=e.addressManager,this._peerStore=e.peerStore,this._upgrader=e.upgrader,this._metrics=e.metrics,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._connectionGater=e.connectionGater,this._contentRouting=e.contentRouting,this._peerRouting=e.peerRouting,this._datastore=e.datastore,this._connectionProtector=e.connectionProtector,this._dht=e.dht,this._pubsub=e.pubsub,this._dialer=e.dialer}isStarted(){return this._started}async beforeStart(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.beforeStart!=null&&await e.beforeStart()}))}async start(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{await e.start()})),this._started=!0}async afterStart(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async beforeStop(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.beforeStop!=null&&await e.beforeStop()}))}async stop(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{await e.stop()})),this._started=!1}async afterStop(){await Promise.all(Object.values(this).filter(e=>Cl(e)).map(async e=>{e.afterStop!=null&&await e.afterStop()}))}get peerId(){if(this._peerId==null)throw(0,_s.default)(new Error("peerId not set"),"ERR_SERVICE_MISSING");return this._peerId}set peerId(e){this._peerId=e}get addressManager(){if(this._addressManager==null)throw(0,_s.default)(new Error("addressManager not set"),"ERR_SERVICE_MISSING");return this._addressManager}set addressManager(e){this._addressManager=e}get peerStore(){if(this._peerStore==null)throw(0,_s.default)(new Error("peerStore not set"),"ERR_SERVICE_MISSING");return this._peerStore}set peerStore(e){this._peerStore=e}get upgrader(){if(this._upgrader==null)throw(0,_s.default)(new Error("upgrader not set"),"ERR_SERVICE_MISSING");return this._upgrader}set upgrader(e){this._upgrader=e}get registrar(){if(this._registrar==null)throw(0,_s.default)(new Error("registrar not set"),"ERR_SERVICE_MISSING");return this._registrar}set registrar(e){this._registrar=e}get connectionManager(){if(this._connectionManager==null)throw(0,_s.default)(new Error("connectionManager not set"),"ERR_SERVICE_MISSING");return this._connectionManager}set connectionManager(e){this._connectionManager=e}get transportManager(){if(this._transportManager==null)throw(0,_s.default)(new Error("transportManager not set"),"ERR_SERVICE_MISSING");return this._transportManager}set transportManager(e){this._transportManager=e}get connectionGater(){if(this._connectionGater==null)throw(0,_s.default)(new Error("connectionGater not set"),"ERR_SERVICE_MISSING");return this._connectionGater}set connectionGater(e){this._connectionGater=e}get contentRouting(){if(this._contentRouting==null)throw(0,_s.default)(new Error("contentRouting not set"),"ERR_SERVICE_MISSING");return this._contentRouting}set contentRouting(e){this._contentRouting=e}get peerRouting(){if(this._peerRouting==null)throw(0,_s.default)(new Error("peerRouting not set"),"ERR_SERVICE_MISSING");return this._peerRouting}set peerRouting(e){this._peerRouting=e}get datastore(){if(this._datastore==null)throw(0,_s.default)(new Error("datastore not set"),"ERR_SERVICE_MISSING");return this._datastore}set datastore(e){this._datastore=e}get connectionProtector(){return this._connectionProtector}set connectionProtector(e){this._connectionProtector=e}get dialer(){if(this._dialer==null)throw(0,_s.default)(new Error("dialer not set"),"ERR_SERVICE_MISSING");return this._dialer}set dialer(e){this._dialer=e}get metrics(){return this._metrics}set metrics(e){this._metrics=e}get dht(){return this._dht}set dht(e){this._dht=e}get pubsub(){return this._pubsub}set pubsub(e){this._pubsub=e}};var ZB=C($s(),1),JB=C(k0e(),1);var N0e=globalThis.fetch,D0e=globalThis.Headers,uXt=globalThis.Request,lXt=globalThis.Response;function vx(r,e,t){return`${r}?name=${e}&type=${t}`}async function O0e(r,e){return await(await N0e(r,{headers:new D0e({accept:"application/dns-json"}),signal:e})).json()}function I0(r,e){return`${e}_${r}`}var XB=Object.assign((0,ZB.default)("dns-over-http-resolver"),{error:(0,ZB.default)("dns-over-http-resolver:error")}),eM=class{constructor(e={}){this._cache=new JB.default({max:(e==null?void 0:e.maxCache)??100}),this._TXTcache=new JB.default({max:(e==null?void 0:e.maxCache)??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??O0e,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*t),i=e[t];e[t]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(I0(e,t));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(vx(o,e,t),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(I0(e,t),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),XB.error(`${o} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){let t="AAAA",n=this._cache.get(I0(e,t));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(vx(o,e,t),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(I0(e,t),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),XB.error(`${o} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){let t="TXT",n=this._TXTcache.get(I0(e,t));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(vx(o,e,t),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(I0(e,t),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),XB.error(`${o} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},L0e=eM;var B0e=L0e;var{code:SVe}=hr("dnsaddr");async function M0e(r,e={}){let t=new B0e;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,i]=r.stringTuples().find(([a])=>a===SVe)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await t.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var xx=C(ee(),1);var CVe={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{maxConnections:300,minConnections:50,autoDial:!0,autoDialInterval:1e4,maxParallelDials:100,maxDialsPerPeer:4,dialTimeout:3e4,inboundUpgradeTimeout:3e4,resolvers:{dnsaddr:M0e},addressSorter:ig},connectionGater:{},transportManager:{faultTolerance:Qd.FATAL_ALL},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},nat:{enabled:!0,ttl:7200,keepAlive:!0},relay:{enabled:!0,advertise:{bootDelay:9e5,enabled:!1,ttl:18e5},hop:{enabled:!1,active:!1,timeout:3e4},autoRelay:{enabled:!1,maxListeners:2}},identify:{protocolPrefix:"ipfs",host:{agentVersion:KB},timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1},ping:{protocolPrefix:"ipfs",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4},fetch:{protocolPrefix:"libp2p",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4}};function U0e(r){var t,n;let e=et(CVe,r);if(e.transports==null||e.transports.length<1)throw(0,xx.default)(new Error(Rt.ERR_TRANSPORTS_REQUIRED),q.ERR_TRANSPORTS_REQUIRED);if(e.connectionEncryption==null||e.connectionEncryption.length===0)throw(0,xx.default)(new Error(Rt.CONN_ENCRYPTION_REQUIRED),q.CONN_ENCRYPTION_REQUIRED);if(e.connectionProtector===null&&((n=(t=globalThis.process)==null?void 0:t.env)==null?void 0:n.LIBP2P_FORCE_PNET)!=null)throw(0,xx.default)(new Error(Rt.ERR_PROTECTOR_REQUIRED),q.ERR_PROTECTOR_REQUIRED);return e.identify.host.agentVersion===KB&&(w0e||g0e?e.identify.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(T0||rx||y0e||b0e)&&(e.identify.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`)),e}var iM;(function(r){let e;r.codec=()=>(e==null&&(e=Cr((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.id!=null&&t.id.byteLength>0)&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Rr(t,r.codec()),r.decode=t=>Ir(t,r.codec())})(iM||(iM={}));var F0e=async()=>{let r=await H9("Ed25519"),e=await PVe(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function PVe(r){return await Yd(Ppe(r.public),kpe(r))}var D4=C(ee(),1);var pa=C(ee(),1);var Sx=class extends Zt{get[a9](){return!0}get[Symbol.toStringTag](){return"@libp2p/dummy-dht"}get wan(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}get lan(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}get(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}findProviders(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}findPeer(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}getClosestPeers(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}provide(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}put(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}async getMode(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}async setMode(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}async refreshRoutingTable(){throw(0,pa.default)(new Error(Rt.DHT_DISABLED),q.DHT_DISABLED)}};var ql=C(ee(),1);var Ax=class extends Zt{constructor(){super(...arguments),this.topicValidators=new Map}isStarted(){return!1}start(){}stop(){}get globalSignaturePolicy(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}get multicodecs(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}getPeers(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}getTopics(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}subscribe(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}unsubscribe(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}getSubscribers(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}async publish(){throw(0,ql.default)(new Error(Rt.PUBSUB_DISABLED),q.ERR_PUBSUB_DISABLED)}};var yg=C(ee(),1);var t1e=C(Kn(),1),sM=C(Da(),1),r1e=C(xi(),1);var N4=C(ee(),1),Z0e=C(Da(),1),J0e=C(Q0e(),1),oM=C(xi(),1);var X0e=ue("libp2p:dialer:dial-request"),Tx=class{constructor(e){let{addrs:t,dialAction:n,dialer:i}=e;this.addrs=t,this.dialer=i,this.dialAction=n}async run(e={}){var a;let t=this.dialer.getTokens(this.addrs.length);if(t.length<1)throw(0,N4.default)(new Error("No dial tokens available"),q.ERR_NO_DIAL_TOKENS);let n=new J0e.default;for(let c of t)n.push(c).catch(u=>{X0e.error(u)});let i=this.addrs.map(()=>{var u;let c=new AbortController;try{(u=oM.setMaxListeners)==null||u(1/0,c.signal)}catch{}return c});if(e.signal!=null)try{(a=oM.setMaxListeners)==null||a(1/0,e.signal)}catch{}let o=0,s=!1;try{return await Promise.any(this.addrs.map(async(c,u)=>{let l=await n.shift();if(s)throw this.dialer.releaseToken(t.splice(t.indexOf(l),1)[0]),(0,N4.default)(new Error("dialAction already succeeded"),q.ERR_ALREADY_SUCCEEDED);let f=i[u];if(f==null)throw(0,N4.default)(new Error("dialAction did not come with an AbortController"),q.ERR_INVALID_PARAMETERS);let h;try{let d=f.signal;h=await this.dialAction(c,{...e,signal:e.signal!=null?(0,Z0e.anySignal)([d,e.signal]):d}),i[u]=void 0}finally{o++,this.addrs.length-o>=t.length?n.push(l).catch(d=>{X0e.error(d)}):this.dialer.releaseToken(t.splice(t.indexOf(l),1)[0])}if(h==null)throw(0,N4.default)(new Error("dialAction led to empty object"),q.ERR_TRANSPORT_DIAL_FAILED);return s=!0,h}))}finally{i.forEach(c=>{c!==void 0&&c.abort()}),t.forEach(c=>this.dialer.releaseToken(c))}}};var Eu=ue("libp2p:dialer"),Ix=class{constructor(e,t={}){this.started=!1,this.addressSorter=t.addressSorter??ig,this.maxAddrsToDial=t.maxAddrsToDial??25,this.timeout=t.dialTimeout??3e4,this.maxDialsPerPeer=t.maxDialsPerPeer??4,this.tokens=[...new Array(t.maxParallelDials??100)].map((n,i)=>i),this.components=e,this.pendingDials=bs({name:"libp2p_dialler_pending_dials",metrics:e.metrics}),this.pendingDialTargets=bs({name:"libp2p_dialler_pending_dial_targets",metrics:e.metrics});for(let[n,i]of Object.entries(t.resolvers??{}))iD.set(n,i)}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1;for(let e of this.pendingDials.values())try{e.controller.abort()}catch(t){Eu.error(t)}this.pendingDials.clear();for(let e of this.pendingDialTargets.values())e.abort();this.pendingDialTargets.clear()}async dial(e,t={}){let{peerId:n,multiaddr:i}=_9(e);if(n!=null){if(this.components.peerId.equals(n))throw(0,yg.default)(new Error("Tried to dial self"),q.ERR_DIALED_SELF);if(i!=null&&(Eu("storing multiaddrs %p",n,i),await this.components.peerStore.addressBook.add(n,[i])),await this.components.connectionGater.denyDialPeer(n))throw(0,yg.default)(new Error("The dial request is blocked by gater.allowDialPeer"),q.ERR_PEER_DIAL_INTERCEPTED)}Eu("creating dial target for %p",n);let o=new AbortController,s=e1e();this.pendingDialTargets.set(s,o);let a=o.signal;t.signal!=null&&(a=(0,sM.anySignal)([a,t.signal]));let c;try{c=await this._createDialTarget({peerId:n,multiaddr:i},{...t,signal:a})}finally{this.pendingDialTargets.delete(s)}if(c.addrs.length===0)throw(0,yg.default)(new Error("The dial request has no valid addresses"),q.ERR_NO_VALID_ADDRESSES);let u=this.pendingDials.get(c.id)??this._createPendingDial(c,t);try{let l=await u.promise;return Eu("dial succeeded to %s",c.id),l}catch(l){throw Eu("dial failed to %s",c.id,l),u.controller.signal.aborted&&(l.code=q.ERR_TIMEOUT),Eu.error(l),l}finally{u.destroy()}}async _createDialTarget(e,t){let n=[];if(as(e.multiaddr)&&n.push(e.multiaddr),!as(e.multiaddr)&&u0(e.peerId)&&n.push(...await this._loadAddresses(e.peerId)),n=(await Promise.all(n.map(async o=>await this._resolve(o,t)))).flat().filter(o=>!!this.components.transportManager.transportForMultiaddr(o)),n=[...new Set(n.map(o=>o.toString()))].map(o=>lt(o)),n.length>this.maxAddrsToDial)throw(0,yg.default)(new Error("dial with more addresses than allowed"),q.ERR_TOO_MANY_ADDRESSES);let i=u0(e.peerId)?e.peerId:void 0;if(i!=null){let o=`/p2p/${i.toString()}`;n=n.map(s=>{let a=s.getPeerId();return a==null||!i.equals(a)?s.encapsulate(o):s})}return{id:i==null?e1e():i.toString(),addrs:n}}async _loadAddresses(e){let t=await this.components.peerStore.addressBook.get(e);return(await Promise.all(t.map(async n=>await this.components.connectionGater.denyDialMultiaddr(e,n.multiaddr)?!1:n))).filter(DVe).sort(this.addressSorter).map(n=>n.multiaddr)}_createPendingDial(e,t={}){var u;let n=async(l,f={})=>{var h;if(((h=f.signal)==null?void 0:h.aborted)===!0)throw(0,yg.default)(new Error("already aborted"),q.ERR_ALREADY_ABORTED);return await this.components.transportManager.dial(l,f).catch(d=>{throw Eu.error("dial to %s failed",l,d),d})},i=new Tx({addrs:e.addrs,dialAction:n,dialer:this}),o=new t1e.TimeoutController(this.timeout),s=[o.signal];t.signal!=null&&s.push(t.signal);let a=(0,sM.anySignal)(s);try{(u=r1e.setMaxListeners)==null||u(1/0,a)}catch{}let c={dialRequest:i,controller:o,promise:i.run({...t,signal:a}),destroy:()=>{o.clear(),this.pendingDials.delete(e.id)}};return this.pendingDials.set(e.id,c),c}getTokens(e){let t=Math.min(e,this.maxDialsPerPeer,this.tokens.length),n=this.tokens.splice(0,t);return Eu("%d tokens request, returning %d, %d remaining",e,t,this.tokens.length),n}releaseToken(e){this.tokens.includes(e)||(Eu("token %d released",e),this.tokens.push(e))}async _resolve(e,t){if(!e.protoNames().includes("dnsaddr"))return[e];let i=await this._resolveRecord(e,t);return(await Promise.all(i.map(async a=>await this._resolve(a,t)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[])}async _resolveRecord(e,t){try{return e=lt(e.toString()),await e.resolve(t)}catch(n){return Eu.error(`multiaddr ${e.toString()} could not be resolved`,n),[]}}};function DVe(r){return!!r}function e1e(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Hl=ue("libp2p"),aM=class extends Zt{constructor(e){super(),this.started=!1,this.peerId=e.peerId;let t=this.components=new Ex({peerId:e.peerId,datastore:e.datastore??new A3,connectionGater:{denyDialPeer:async()=>await Promise.resolve(!1),denyDialMultiaddr:async()=>await Promise.resolve(!1),denyInboundConnection:async()=>await Promise.resolve(!1),denyOutboundConnection:async()=>await Promise.resolve(!1),denyInboundEncryptedConnection:async()=>await Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>await Promise.resolve(!1),denyInboundUpgradedConnection:async()=>await Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>await Promise.resolve(!1),filterMultiaddrForPeer:async()=>await Promise.resolve(!0),...e.connectionGater}});t.peerStore=new bx(t,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore}),this.services=[t],e.metrics!=null&&(this.metrics=this.components.metrics=this.configureComponent(e.metrics(this.components))),this.peerStore=this.components.peerStore,this.peerStore.addEventListener("peer",s=>{let{detail:a}=s;this.dispatchEvent(new ve("peer:discovery",{detail:a}))}),e.connectionProtector!=null&&(this.components.connectionProtector=e.connectionProtector(t)),this.components.upgrader=new X9(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(s=>this.configureComponent(s(this.components))),muxers:(e.streamMuxers??[]).map(s=>this.configureComponent(s(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.components.dialer=new Ix(this.components,e.connectionManager),this.connectionManager=this.components.connectionManager=new x9(this.components,e.connectionManager),this.components.connectionManager.addEventListener("peer:disconnect",s=>{this.dispatchEvent(new ve("peer:disconnect",{detail:s.detail}))}),this.components.connectionManager.addEventListener("peer:connect",s=>{this.dispatchEvent(new ve("peer:connect",{detail:s.detail}))}),this.registrar=this.components.registrar=new Q9(this.components),this.components.transportManager=new j9(this.components,e.transportManager),this.components.addressManager=new p9(this.components,e.addresses),this.configureComponent(new ix(this.components)),this.configureComponent(new S9(this.components,{enabled:e.connectionManager.autoDial,minConnections:e.connectionManager.minConnections,autoDialInterval:e.connectionManager.autoDialInterval}));let n=b0.generateOptions();this.keychain=this.configureComponent(new b0(this.components,{...n,...e.keychain})),this.services.push(new nx(this.components,e.nat)),e.transports.forEach(s=>{this.components.transportManager.add(this.configureComponent(s(this.components)))}),this.identifyService=new mg(this.components,{...e.identify}),this.configureComponent(this.identifyService),e.dht!=null?this.dht=this.components.dht=e.dht(this.components):this.dht=new Sx,e.pubsub!=null?this.pubsub=this.components.pubsub=e.pubsub(this.components):this.pubsub=new Ax;let i=(e.peerRouters??[]).map(s=>this.configureComponent(s(this.components)));e.dht!=null&&(i.push(this.configureComponent(new ox(this.dht))),this.dht.addEventListener("peer",s=>{this.onDiscoveryPeer(s)})),this.peerRouting=this.components.peerRouting=this.configureComponent(new f9(this.components,{...e.peerRouting,routers:i}));let o=(e.contentRouters??[]).map(s=>this.configureComponent(s(this.components)));e.dht!=null&&o.push(this.configureComponent(new _x(this.dht))),this.contentRouting=this.components.contentRouting=this.configureComponent(new h9(this.components,{routers:o})),e.relay.enabled&&(this.components.transportManager.add(this.configureComponent(new I9(this.components,e.relay))),this.configureComponent(new L9(this.components,{addressSorter:e.connectionManager.addressSorter,...e.relay}))),this.fetchService=this.configureComponent(new J9(this.components,{...e.fetch})),this.pingService=this.configureComponent(new ex(this.components,{...e.ping}));for(let s of e.peerDiscovery??[])this.configureComponent(s(this.components)).addEventListener("peer",c=>{this.onDiscoveryPeer(c)})}configureComponent(e){return Cl(e)&&this.services.push(e),e}async start(){if(!this.started){this.started=!0,Hl("libp2p is starting");try{await Promise.all(this.services.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(this.services.map(e=>e.start())),await Promise.all(this.services.map(async e=>{e.afterStart!=null&&await e.afterStart()})),Hl("libp2p has started")}catch(e){throw Hl.error("An error occurred starting libp2p",e),await this.stop(),e}}}async stop(){this.started&&(Hl("libp2p is stopping"),this.started=!1,await Promise.all(this.services.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(this.services.map(e=>e.stop())),await Promise.all(this.services.map(async e=>{e.afterStop!=null&&await e.afterStop()})),Hl("libp2p has stopped"))}isStarted(){return this.started}getConnections(e){return this.components.connectionManager.getConnections(e)}getPeers(){let e=new Nl;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return await this.components.connectionManager.openConnection(e,t)}async dialProtocol(e,t,n={}){if(t==null)throw(0,D4.default)(new Error("no protocols were provided to open a stream"),q.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw(0,D4.default)(new Error("no protocols were provided to open a stream"),q.ERR_INVALID_PROTOCOLS_FOR_STREAM);return await(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e){as(e)&&(e=xt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,t={}){if(Hl("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.pubKey!=null)return n.pubKey;if(this.dht==null)throw(0,D4.default)(new Error("Public key was not in the peer store and the DHT is not enabled"),q.ERR_NO_ROUTERS_AVAILABLE);let i=yr([fe("/pk/"),e.multihash.digest]);for await(let o of this.dht.get(i,t))if(o.name==="VALUE"){let s=g4(o.value);return await this.peerStore.keyBook.set(e,o.value),s.bytes}throw(0,D4.default)(new Error(`Node not responding with its public key: ${e.toString()}`),q.ERR_INVALID_RECORD)}async fetch(e,t,n={}){if(as(e)){let i=xt(e.getPeerId()??"");await this.components.peerStore.addressBook.add(i,[e]),e=i}return await this.fetchService.fetch(e,t,n)}async ping(e,t={}){if(as(e)){let n=xt(e.getPeerId()??"");await this.components.peerStore.addressBook.add(n,[e]),e=n}return await this.pingService.ping(e,t)}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return await this.registrar.register(e,t)}unregister(e){this.registrar.unregister(e)}onDiscoveryPeer(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){Hl.error(new Error(q.ERR_DISCOVERED_SELF));return}t.multiaddrs.length>0&&this.components.peerStore.addressBook.add(t.id,t.multiaddrs).catch(n=>Hl.error(n)),t.protocols.length>0&&this.components.peerStore.protoBook.set(t.id,t.protocols).catch(n=>Hl.error(n)),this.dispatchEvent(new ve("peer:discovery",{detail:t}))}};async function n1e(r){if(r.peerId==null){let e=r.datastore;if(e!=null)try{let t=new b0({datastore:e},{...b0.generateOptions(),...r.keychain??{}});r.peerId=await t.exportPeerId("self")}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}}return r.peerId==null&&(r.peerId=await F0e()),new aM(U0e(r))}async function i1e(r){let e=await n1e(r);return r.start!==!1&&await e.start(),e}var I1e=C(f1e(),1);var m1e=C(dB(),1);var g1e=C(h1e(),1),{isValid:zVe,parse:VVe}=g1e.default,KVe=["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"],$Ve=KVe.map(r=>new m1e.Netmask(r));function qVe(r){for(let e of $Ve)if(e.contains(r))return!0;return!1}function p1e(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}var y1e=r=>{if(zVe(r)){let e=VVe(r);if(e.kind()==="ipv4")return qVe(e.toNormalizedString());if(e.kind()==="ipv6")return p1e(r)}else if(xc(r)&&k9.v6().test(r))return p1e(r)};var dM=y1e;var w1e="/lan",b1e="/ipfs",_1e="/kad/1.0.0",E1e="/dht/record",hM="/dht/provider";var HVe=Ie("/pk/");function bg(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>{let[[t,n]]=e.stringTuples();if(t===53||t===54||t===55)return n!=="localhost";if(t!==4&&t!==6||n==null)return!1;let i=dM(n);return i==null?!0:!i})}}function _g(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>{let[[t,n]]=e.stringTuples();if(n==="localhost")return!0;if(t!==4&&t!==6||n==null)return!1;let i=dM(n);return i??!1})}}async function xu(r){return(await dt.digest(r)).digest}async function Es(r){return await xu(r.toBytes())}function Gl(r){return new pe(`${E1e}/${re(r,"base32")}`,!1)}function v1e(r){return rt([HVe,r.toBytes()])}function x1e(r){return re(r.subarray(0,4))==="/pk/"}function S1e(r){return Di(r.subarray(4))}function pM(r,e){let t=new Date;return new Yr(r,e,t).serialize()}function A1e(r,e=100){let t;return()=>{clearTimeout(t),t=setTimeout(()=>{r()},e)}}var R1e=C(Kn(),1);function jl(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var gM=class{constructor(e){B(this,"map");if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return jl(this.map.entries(),e=>[Oe(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,Oe(n),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 jl(this.map.keys(),e=>Oe(e))}values(){return this.map.values()}get size(){return this.map.size}};var ma=class{constructor(e){B(this,"set");if(this.set=new Set,e!=null)for(let 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 jl(this.set.entries(),e=>{let t=Oe(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Oe(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return jl(this.set.values(),e=>Oe(e))}intersection(e){let t=new ma;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new ma;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new ma;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Eg=class{constructor(e){B(this,"list");if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return jl(this.list.entries(),e=>Oe(e[1]))}concat(e){let t=new Eg(this);for(let n of e)t.push(n);return t}entries(){return jl(this.list.entries(),e=>[e[0],Oe(e[1])])}every(e){return this.list.every((t,n)=>e(Oe(t),n,this))}filter(e){let t=new Eg;return this.list.forEach((n,i)=>{let o=Oe(n);e(o,i,this)&&t.push(o)}),t}find(e){let t=this.list.find((n,i)=>e(Oe(n),i,this));if(t!=null)return Oe(t)}findIndex(e){return this.list.findIndex((t,n)=>e(Oe(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(Oe(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return Oe(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return Oe(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var GVe="kad-close",jVe=50,T1e=20,WVe=1e4,YVe=10,kx=class{constructor(e,t){let{kBucketSize:n,pingTimeout:i,lan:o,pingConcurrency:s,protocol:a,tagName:c,tagValue:u}=t;this.components=e,this.log=j(`libp2p:kad-dht:${o?"lan":"wan"}:routing-table`),this.kBucketSize=n??T1e,this.pingTimeout=i??WVe,this.pingConcurrency=s??YVe,this.lan=o,this.running=!1,this.protocol=a,this.tagName=c??GVe,this.tagValue=u??jVe;let l=()=>{var f,h;(f=this.metrics)==null||f.pingQueueSize.update(this.pingQueue.size),(h=this.metrics)==null||h.pingRunning.update(this.pingQueue.pending)};this.pingQueue=new qn({concurrency:this.pingConcurrency}),this.pingQueue.addListener("add",l),this.pingQueue.addListener("next",l),this._onPing=this._onPing.bind(this)}isStarted(){return this.running}async start(){this.running=!0,this.components.metrics!=null&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_routing_table_size`),pingQueueSize:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_ping_queue_size`),pingRunning:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_ping_running`)});let e=new I1e.default({localNodeId:await Es(this.components.peerId),numberOfNodesPerKBucket:this.kBucketSize,numberOfNodesToPing:1});this.kb=e,e.on("ping",this._onPing),this._tagPeers(e)}async stop(){this.running=!1,this.pingQueue.clear(),this.kb=void 0}_tagPeers(e){let t=new ma,n=A1e(()=>{let i=new ma(e.closest(e.localNodeId,T1e).map(a=>a.peer)),o=i.difference(t),s=t.difference(i);Promise.resolve().then(async()=>{for(let a of o)await this.components.peerStore.tagPeer(a,this.tagName,{value:this.tagValue});for(let a of s)await this.components.peerStore.unTagPeer(a,this.tagName)}).catch(a=>{this.log.error("Could not update peer tags",a)}),t=i});e.on("added",()=>{n()}),e.on("removed",()=>{n()})}_onPing(e,t){this.pingQueue.add(async()=>{if(!this.running)return;let n=0;try{await Promise.all(e.map(async i=>{var s;let o;try{o=new R1e.TimeoutController(this.pingTimeout);let a={signal:o.signal};this.log("pinging old contact %p",i.peer),(await(await this.components.connectionManager.openConnection(i.peer,a)).newStream(this.protocol,a)).close(),n++}catch(a){this.running&&this.kb!=null&&(this.log.error("could not ping peer %p",i.peer,a),this.log("evicting old contact after ping failed %p",i),this.kb.remove(i.id))}finally{o!=null&&o.clear(),(s=this.metrics)==null||s.routingTableSize.update(this.size)}})),this.running&&n{this.log.error("could not process k-bucket ping event",n)})}get size(){return this.kb==null?0:this.kb.count()}async find(e){let t=await Es(e),n=this.closestPeer(t);if(n!=null&&e.equals(n))return n}closestPeer(e){let t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e,t=this.kBucketSize){return this.kb==null?[]:this.kb.closest(e,t).map(i=>i.peer)}async add(e){var n;if(this.kb==null)throw new Error("RoutingTable is not started");let t=await Es(e);this.kb.add({id:t,peer:e}),this.log("added %p with kad id %b",e,t),(n=this.metrics)==null||n.routingTableSize.update(this.size)}async remove(e){var n;if(this.kb==null)throw new Error("RoutingTable is not started");let t=await Es(e);this.kb.remove(t),(n=this.metrics)==null||n.routingTableSize.update(this.size)}};function Wl(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=vf(r.length);for(let n=0;ni.toISOString()).join(", ")} ]`),Promise.all(n.map(async(i,o)=>{try{if(await this._refreshCommonPrefixLength(o,i,e),this._numPeersForCpl(t)===0){let s=Math.min(2*(o+1),n.length-1);for(let a=o+1;a{this.log.error(i)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),this.refreshTimeoutId.unref!=null&&this.refreshTimeoutId.unref()}).catch(i=>{this.log.error(i)})}async _refreshCommonPrefixLength(e,t,n){if(!n&&t.getTime()>Date.now()-this.refreshInterval){this.log("not running refresh for cpl %s as time since last refresh not above interval",e);return}let i=await this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);let o=new P1e.TimeoutController(this.refreshQueryTimeout);try{let s=await L4(this.peerRouting.getClosestPeers(i.toBytes(),{signal:o.signal}));this.log(`found ${s} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}finally{o.clear()}}_getTrackedCommonPrefixLengthsForRefresh(e){e>Nx&&(e=Nx);let t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}async _generateRandomPeerId(e){if(this.routingTable.kb==null)throw new Error("Routing table not started");let t=Mc(2),n=(t[1]<<8)+t[0],i=await this._makePeerId(this.routingTable.kb.localNodeId,n,e);return Di(i)}async _makePeerId(e,t,n){if(n>Nx)throw new Error(`Cannot generate peer ID for common prefix length greater than ${Nx}`);let s=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1)^32768>>n,a=65535<<16-(n+1),c=s&a|t&~a,u=C1e[c],l=new ArrayBuffer(34),f=new DataView(l,0,l.byteLength);return f.setUint8(0,dt.code),f.setUint8(1,32),f.setUint32(2,u,!1),new Uint8Array(f.buffer,f.byteOffset,f.byteLength)}_maxCommonPrefix(){let e=0;for(let t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(let n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(this.routingTable.kb!=null)for(let{id:e}of this.routingTable.kb.toIterable()){let t=Wl(this.routingTable.kb.localNodeId,e),n=0;for(let i of t)if(i===0)n++;else break;yield n}}};var k1e;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.key!=null&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&(n.uint32(18),n.bytes(t.value)),t.author!=null&&(n.uint32(26),n.bytes(t.author)),t.signature!=null&&(n.uint32(34),n.bytes(t.signature)),t.timeReceived!=null&&(n.uint32(42),n.string(t.timeReceived)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.bytes();break;case 2:i.value=t.bytes();break;case 3:i.author=t.bytes();break;case 4:i.signature=t.bytes();break;case 5:i.timeReceived=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(k1e||(k1e={}));var ih;(function(r){let e;(function(a){a.PUT_VALUE="PUT_VALUE",a.GET_VALUE="GET_VALUE",a.ADD_PROVIDER="ADD_PROVIDER",a.GET_PROVIDERS="GET_PROVIDERS",a.FIND_NODE="FIND_NODE",a.PING="PING"})(e=r.MessageType||(r.MessageType={}));let t;(function(a){a[a.PUT_VALUE=0]="PUT_VALUE",a[a.GET_VALUE=1]="GET_VALUE",a[a.ADD_PROVIDER=2]="ADD_PROVIDER",a[a.GET_PROVIDERS=3]="GET_PROVIDERS",a[a.FIND_NODE=4]="FIND_NODE",a[a.PING=5]="PING"})(t||(t={})),function(a){a.codec=()=>Y1(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(a){a.NOT_CONNECTED="NOT_CONNECTED",a.CONNECTED="CONNECTED",a.CAN_CONNECT="CAN_CONNECT",a.CANNOT_CONNECT="CANNOT_CONNECT"})(n=r.ConnectionType||(r.ConnectionType={}));let i;(function(a){a[a.NOT_CONNECTED=0]="NOT_CONNECTED",a[a.CONNECTED=1]="CONNECTED",a[a.CAN_CONNECT=2]="CAN_CONNECT",a[a.CANNOT_CONNECT=3]="CANNOT_CONNECT"})(i||(i={})),function(a){a.codec=()=>Y1(i)}(n=r.ConnectionType||(r.ConnectionType={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=kn((u,l,f={})=>{if(f.lengthDelimited!==!1&&l.fork(),u.id!=null&&(l.uint32(10),l.bytes(u.id)),u.addrs!=null)for(let h of u.addrs)l.uint32(18),l.bytes(h);u.connection!=null&&(l.uint32(24),r.ConnectionType.codec().encode(u.connection,l)),f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={addrs:[]},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.id=u.bytes();break;case 2:f.addrs.push(u.bytes());break;case 3:f.connection=r.ConnectionType.codec().decode(u);break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>Pn(u,a.codec()),a.decode=u=>Cn(u,a.codec())})(o=r.Peer||(r.Peer={}));let s;r.codec=()=>(s==null&&(s=kn((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.MessageType.codec().encode(a.type,c)),a.clusterLevelRaw!=null&&(c.uint32(80),c.int32(a.clusterLevelRaw)),a.key!=null&&(c.uint32(18),c.bytes(a.key)),a.record!=null&&(c.uint32(26),c.bytes(a.record)),a.closerPeers!=null)for(let l of a.closerPeers)c.uint32(66),r.Peer.codec().encode(l,c);if(a.providerPeers!=null)for(let l of a.providerPeers)c.uint32(74),r.Peer.codec().encode(l,c);u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={closerPeers:[],providerPeers:[]},l=c==null?a.len:a.pos+c;for(;a.pos>>3){case 1:u.type=r.MessageType.codec().decode(a);break;case 10:u.clusterLevelRaw=a.int32();break;case 2:u.key=a.bytes();break;case 3:u.record=a.bytes();break;case 8:u.closerPeers.push(r.Peer.codec().decode(a,a.uint32()));break;case 9:u.providerPeers.push(r.Peer.codec().decode(a,a.uint32()));break;default:a.skipType(f&7);break}}return u})),s),r.encode=a=>Pn(a,r.codec()),r.decode=a=>Cn(a,r.codec())})(ih||(ih={}));var Sn=ih.MessageType,ZVe=ih.ConnectionType,O1e=Object.keys(Sn),jr=class{constructor(e,t,n){if(!(t instanceof Uint8Array))throw new Error("Key must be a Uint8Array");this.type=e,this.key=t,this.clusterLevelRaw=n,this.closerPeers=[],this.providerPeers=[],this.record=void 0}get clusterLevel(){let e=this.clusterLevelRaw-1;return e<0?0:e}set clusterLevel(e){this.clusterLevelRaw=e}serialize(){return ih.encode({key:this.key,type:this.type,clusterLevelRaw:this.clusterLevelRaw,closerPeers:this.closerPeers.map(N1e),providerPeers:this.providerPeers.map(N1e),record:this.record==null?void 0:this.record.serialize().subarray()})}static deserialize(e){var i;let t=ih.decode(e),n=new jr(t.type??ih.MessageType.PUT_VALUE,t.key??Uint8Array.from([]),t.clusterLevelRaw??0);return n.closerPeers=t.closerPeers.map(D1e),n.providerPeers=t.providerPeers.map(D1e),((i=t.record)==null?void 0:i.length)!=null&&(n.record=Yr.deserialize(t.record)),n}};function N1e(r){return{id:r.id.toBytes(),addrs:(r.multiaddrs??[]).map(t=>t.bytes),connection:ZVe.CONNECTED}}function D1e(r){if(r.id==null)throw new Error("Invalid peer in message");return{id:Di(r.id),multiaddrs:(r.addrs??[]).map(e=>yt(e)),protocols:[]}}function yM(r){return{...r,name:"SENDING_QUERY",type:0,messageName:r.type,messageType:O1e.indexOf(r.type.toString())}}function B4(r){return{...r,name:"PEER_RESPONSE",type:1,messageName:r.messageType,closer:r.closer!=null?r.closer:[],providers:r.providers!=null?r.providers:[]}}function M4(r){return{...r,name:"FINAL_PEER",type:2}}function lo(r){return{...r,name:"QUERY_ERROR",type:3}}function wM(r){return{...r,name:"PROVIDER",type:4}}function U4(r){return{...r,name:"VALUE",type:5}}function bM(r){return{...r,name:"DIALING_PEER",type:7}}var Ox=class extends Ki{constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=j(`libp2p:kad-dht:${i?"lan":"wan"}:network`),this.running=!1,this.protocol=n}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield bM({peer:e}),yield yM({to:e,type:t.type});let i;try{let s=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n),a=await this._writeReadMessage(s,t.serialize(),n);yield B4({from:e,messageType:a.type,closer:a.closerPeers,providers:a.providerPeers,record:a.record})}catch(o){yield lo({from:e,error:o})}finally{i!=null&&i.close()}}async*sendMessage(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield bM({peer:e}),yield yM({to:e,type:t.type});let i;try{let s=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n);await this._writeMessage(s,t.serialize(),n),yield B4({from:e,messageType:t.type})}catch(o){yield lo({from:e,error:o})}finally{i!=null&&i.close()}}async _writeMessage(e,t,n){n.signal!=null&&(e=nL(e,n.signal)),await Ne([t],vn(),e,sl)}async _writeReadMessage(e,t,n){n.signal!=null&&(e=nL(e,n.signal));let i=await Ne([t],vn(),e,Xr(),async s=>{let a=await mp(s);if(a!=null)return a;throw new J("No message received","ERR_NO_MESSAGE_RECEIVED")}),o=jr.deserialize(i);return o.closerPeers.forEach(s=>{this.dispatchEvent(new cn("peer",{detail:s}))}),o.providerPeers.forEach(s=>{this.dispatchEvent(new cn("peer",{detail:s}))}),o}};async function vg(r,e){let t=e.key,i=re(t).split("/");if(i.length<3)return;let o=r[i[1].toString()];if(o==null){let s="Invalid record keytype";throw new J(s,"ERR_INVALID_RECORD_KEY_TYPE")}await o(t,e.value)}var JVe=async(r,e)=>{if(!(r instanceof Uint8Array))throw new J('"key" must be a Uint8Array',"ERR_INVALID_RECORD_KEY_NOT_BUFFER");if(r.byteLength<5)throw new J("invalid public key record","ERR_INVALID_RECORD_KEY_TOO_SHORT");if(re(r.subarray(0,4))!=="/pk/")throw new J("key was not prefixed with /pk/","ERR_INVALID_RECORD_KEY_BAD_PREFIX");let n=r.slice(4),i=await dt.digest(e);if(!mt(n,i.bytes))throw new J("public key does not match passed in key","ERR_INVALID_RECORD_HASH_MISMATCH")},L1e={pk:JVe};function B1e(r,e,t){if(t.length===0){let s="No records given";throw new J(s,"ERR_NO_RECORDS_RECEIVED")}let i=re(e).split("/");if(i.length<3){let s="Record key does not have a selector function";throw new J(s,"ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")}let o=r[i[1].toString()];if(o==null){let s=`Unrecognized key prefix: ${i[1]}`;throw new J(s,"ERR_UNRECOGNIZED_KEY_PREFIX")}return t.length===1?0:o(e,t)}function eKe(r,e){return 0}var M1e={pk:eKe};var Lx=class{constructor(e,t){let{validators:n,selectors:i,peerRouting:o,queryManager:s,routingTable:a,network:c,lan:u}=t;this.components=e,this.log=j(`libp2p:kad-dht:${u?"lan":"wan"}:content-fetching`),this.validators=n,this.selectors=i,this.peerRouting=o,this.queryManager=s,this.routingTable=a,this.network=c}async putLocal(e,t){let n=Gl(e);await this.components.datastore.put(n,t)}async getLocal(e){this.log("getLocal %b",e);let t=Gl(e);this.log("fetching record for key %k",t);let n=await this.components.datastore.get(t);this.log("found %k in local datastore",t);let i=Yr.deserialize(n);return await vg(this.validators,i),i}async*sendCorrectionRecord(e,t,n,i={}){this.log("sendCorrection for %b",e);let o=pM(e,n);for(let{value:s,from:a}of t){if(mt(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{let l=Gl(e);this.log(`Storing corrected record for key ${l.toString()}`),await this.components.datastore.put(l,o.subarray())}catch(l){this.log.error("Failed error correcting self",l)}continue}let c=!1,u=new jr(Sn.PUT_VALUE,e,0);u.record=Yr.deserialize(o);for await(let l of this.network.sendRequest(a,u,i))l.name==="PEER_RESPONSE"&&l.record!=null&&mt(l.record.value,Yr.deserialize(o).value)&&(c=!0),yield l;c||(yield lo({from:a,error:new J("value not put correctly","ERR_PUT_VALUE_INVALID")})),this.log.error("Failed error correcting entry")}}async*put(e,t,n={}){this.log("put key %b value %b",e,t);let i=pM(e,t),o=Gl(e);this.log(`storing record for key ${o.toString()}`),await this.components.datastore.put(o,i.subarray()),yield*Ne(this.peerRouting.getClosestPeers(e,{signal:n.signal}),s=>Mi(s,a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[],u=new jr(Sn.PUT_VALUE,e,0);u.record=Yr.deserialize(i),this.log("send put to %p",a.peer.id);for await(let l of this.network.sendRequest(a.peer.id,u,n))c.push(l),l.name==="PEER_RESPONSE"&&(l.record!=null&&mt(l.record.value,Yr.deserialize(i).value)||c.push(lo({from:a.peer.id,error:new J("value not put correctly","ERR_PUT_VALUE_INVALID")})));return c}),s=>ep(s,{ordered:!1,concurrency:3}),async function*(s){for await(let a of s)yield*a})}async*get(e,t={}){this.log("get %b",e);let n=[];for await(let a of this.getMany(e,t))a.name==="VALUE"&&n.push(a),yield a;if(n.length===0)return;let i=n.map(a=>a.value),o=0;try{o=B1e(this.selectors,e,i)}catch(a){if(a.code!=="ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")throw a}let s=i[o];if(this.log("GetValue %b %b",e,s),s==null)throw new J("best value was not found","ERR_NOT_FOUND");yield*this.sendCorrectionRecord(e,n,s,t),yield n[o]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{let a=await this.getLocal(e);yield U4({value:a.value,from:this.components.peerId})}catch(a){this.log("error getting local value for %b",e,a)}let n=await xu(e),i=this.routingTable.closestPeers(n);this.log("found %d peers in routing table",i.length);let o=this,s=async function*({peer:a,signal:c}){for await(let u of o.peerRouting.getValueOrPeers(a,e,{signal:c}))yield u,u.name==="PEER_RESPONSE"&&u.record!=null&&(yield U4({from:a,value:u.record.value}))};yield*this.queryManager.run(e,i,s,t)}};var Bx=class{constructor(e,t){let{network:n,peerRouting:i,queryManager:o,routingTable:s,providers:a,lan:c}=t;this.components=e,this.log=j(`libp2p:kad-dht:${c?"lan":"wan"}:content-routing`),this.network=n,this.peerRouting=i,this.queryManager=o,this.routingTable=s,this.providers=a}async*provide(e,t,n={}){this.log("provide %s",e),await this.providers.addProvider(e,this.components.peerId);let i=new jr(Sn.ADD_PROVIDER,e.multihash.bytes,0);i.providerPeers=[{id:this.components.peerId,multiaddrs:t,protocols:[]}];let o=0,s=a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[];this.log("putProvider %s to %p",e,a.peer.id);try{this.log("sending provider record for %s to %p",e,a.peer.id);for await(let u of this.network.sendMessage(a.peer.id,i,n))u.name==="PEER_RESPONSE"&&(this.log("sent provider record for %s to %p",e,a.peer.id),o++),c.push(u)}catch(u){this.log.error("error sending provide record to peer %p",a.peer.id,u),c.push(lo({from:a.peer.id,error:u}))}return c};yield*Ne(this.peerRouting.getClosestPeers(e.multihash.bytes,n),a=>Mi(a,c=>s(c)),a=>ep(a,{ordered:!1,concurrency:3}),async function*(a){for await(let c of a)yield*c}),this.log("sent provider records to %d peers",o)}async*findProviders(e,t){let n=this.routingTable.kBucketSize,i=e.multihash.bytes,o=await xu(i),s=this;this.log("findProviders %c",e);let a=await this.providers.getProviders(e);if(a.length>0){let l=[];for(let f of a.slice(0,n))l.push({id:f,multiaddrs:(await this.components.peerStore.addressBook.get(f)??[]).map(h=>h.multiaddr),protocols:[]});yield B4({from:this.components.peerId,messageType:Sn.GET_PROVIDERS,providers:l}),yield wM({from:this.components.peerId,providers:l})}if(a.length>=n)return;let c=async function*({peer:l,signal:f}){let h=new jr(Sn.GET_PROVIDERS,i,0);yield*s.network.sendRequest(l,h,{signal:f})},u=new Set(a.map(l=>l.toString()));for await(let l of this.queryManager.run(i,this.routingTable.closestPeers(o),c,t))if(yield l,l.name==="PEER_RESPONSE"){this.log("Found %d provider entries for %c and %d closer peers",l.providers.length,e,l.closer.length);let f=[];for(let h of l.providers)u.has(h.id.toString())||(u.add(h.id.toString()),f.push(h));if(f.length>0&&(yield wM({from:l.from,providers:f})),u.size===n)return}}};function Mx(r,e){if(globalThis.Buffer!=null)return globalThis.Buffer.compare(r,e);for(let t=0;te[t])return 1}return r.byteLength>e.byteLength?1:r.byteLengthe.peerId)}async add(e){if(this.peerDistances.find(i=>i.peerId.equals(e))!=null)return;let t=await Es(e),n={peerId:e,distance:Wl(this.originDhtKey,t)};this.peerDistances.push(n),this.peerDistances.sort((i,o)=>Mx(i.distance,o.distance)),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async anyCloser(e){if(e.length===0)return!1;if(this.length===0)return!0;let t=await Promise.all(e.map(Es)),n=this.peerDistances[this.peerDistances.length-1].distance;for(let i of t){let o=Wl(this.originDhtKey,i);if(Mx(o,n)<0)return!0}return!1}};var Fx=class{constructor(e,t){let{routingTable:n,network:i,validators:o,queryManager:s,lan:a}=t;this.components=e,this.routingTable=n,this.network=i,this.validators=o,this.queryManager=s,this.log=j(`libp2p:kad-dht:${a?"lan":"wan"}:peer-routing`)}async findPeerLocal(e){let t,n=await this.routingTable.find(e);if(n!=null){this.log("findPeerLocal found %p in routing table",e);try{t=await this.components.peerStore.get(n)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}}if(t==null)try{t=await this.components.peerStore.get(e)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(t!=null)return this.log("findPeerLocal found %p in peer store",e),{id:t.id,multiaddrs:t.addresses.map(i=>i.multiaddr),protocols:[]}}async*_getValueSingle(e,t,n={}){let i=new jr(Sn.GET_VALUE,t,0);yield*this.network.sendRequest(e,i,n)}async*getPublicKeyFromNode(e,t={}){let n=v1e(e);for await(let i of this._getValueSingle(e,n,t))if(yield i,i.name==="PEER_RESPONSE"&&i.record!=null){let o=await Hn(Zb.marshalPublicKey({bytes:i.record.value}));if(!o.equals(e))throw new J("public key does not match id","ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID");if(o.publicKey==null)throw new J("public key missing","ERR_PUBLIC_KEY_MISSING");yield U4({from:e,value:o.publicKey})}throw new J(`Node not responding with its public key: ${e.toString()}`,"ERR_INVALID_RECORD")}async*findPeer(e,t={}){this.log("findPeer %p",e);let n=await this.findPeerLocal(e);if(n!=null){this.log("found local"),yield M4({from:this.components.peerId,peer:n});return}let i=await Es(e),o=this.routingTable.closestPeers(i);if(o.find(l=>l.equals(e))!=null)try{let l=await this.components.peerStore.get(e);this.log("found in peerStore"),yield M4({from:this.components.peerId,peer:{id:l.id,multiaddrs:l.addresses.map(f=>f.multiaddr),protocols:[]}});return}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}let a=this,c=async function*({peer:l,signal:f}){let h=new jr(Sn.FIND_NODE,e.toBytes(),0);for await(let d of a.network.sendRequest(l,h,{signal:f}))if(yield d,d.name==="PEER_RESPONSE"){let p=d.closer.find(g=>g.id.equals(e));p!=null&&(yield M4({from:d.from,peer:p}))}},u=!1;for await(let l of this.queryManager.run(e.toBytes(),o,c,t))l.name==="FINAL_PEER"&&(u=!0),yield l;u||(yield lo({from:this.components.peerId,error:new J("Not found","ERR_NOT_FOUND")}))}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);let n=await xu(e),i=this.routingTable.closestPeers(n),o=this,s=new Ux(n,this.routingTable.kBucketSize);await Promise.all(i.map(async c=>{await s.add(c)}));let a=async function*({peer:c,signal:u}){o.log("closerPeersSingle %s from %p",re(e,"base32"),c);let l=new jr(Sn.FIND_NODE,e,0);yield*o.network.sendRequest(c,l,{signal:u})};for await(let c of this.queryManager.run(e,i,a,t))yield c,c.name==="PEER_RESPONSE"&&await Promise.all(c.closer.map(async u=>{await s.add(u.id)}));this.log("found %d peers close to %b",s.length,e);for(let c of s.peers)yield M4({from:this.components.peerId,peer:{id:c,multiaddrs:(await this.components.peerStore.addressBook.get(c)??[]).map(u=>u.multiaddr),protocols:[]}})}async*getValueOrPeers(e,t,n={}){for await(let i of this._getValueSingle(e,t,n)){if(i.name==="PEER_RESPONSE"&&i.record!=null)try{await this._verifyRecordOnline(i.record)}catch{let s="invalid record received, discarded";this.log(s),yield lo({from:i.from,error:new J(s,"ERR_INVALID_RECORD")});continue}yield i}}async _verifyRecordOnline(e){if(e.timeReceived==null)throw new J("invalid record received","ERR_INVALID_RECORD");await vg(this.validators,new Yr(e.key,e.value,e.timeReceived))}async getCloserPeersOffline(e,t){let n=await xu(e),i=this.routingTable.closestPeers(n),o=[];for(let s of i)if(!s.equals(t))try{let a=await this.components.peerStore.addressBook.get(s),c=await this.components.peerStore.protoBook.get(s);o.push({id:s,multiaddrs:a.map(u=>u.multiaddr),protocols:c})}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}return o.length>0?this.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",o.length,e,t):this.log("getCloserPeersOffline could not find peer closer to %b than %p",e,t),o}};var U1e=C(Cy(),1),_M=C(Xo(),1);var Yl=j("libp2p:kad-dht:providers"),zx=class{constructor(e,t={}){let{cacheSize:n,cleanupInterval:i,provideValidity:o}=t;this.components=e,this.cleanupInterval=i??36e5,this.provideValidity=o??864e5,this.cache=(0,U1e.default)(n??256),this.syncQueue=new qn({concurrency:1}),this.started=!1}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cleaner=setInterval(()=>{this._cleanup().catch(e=>{Yl.error(e)})},this.cleanupInterval))}async stop(){this.started=!1,this.cleaner!=null&&(clearInterval(this.cleaner),this.cleaner=void 0)}async _cleanup(){await this.syncQueue.add(async()=>{let e=Date.now(),t=0,n=0,i=new Map,o=this.components.datastore.batch(),s=this.components.datastore.query({prefix:hM});for await(let a of s)try{let{cid:c,peerId:u}=F1e(a.key),l=z1e(a.value).getTime(),f=Date.now(),h=f-l,d=h>this.provideValidity;if(Yl("comparing: %d - %d = %d > %d %s",f,l,h,this.provideValidity,d?"(expired)":""),d){n++,o.delete(a.key);let p=i.get(c)??new Set;p.add(u),i.set(c,p)}t++}catch(c){Yl.error(c.message)}i.size>0?(Yl("deleting %d / %d entries",n,t),await o.commit()):Yl("nothing to delete");for(let[a,c]of i){let u=F4(a),l=this.cache.get(u);if(l!=null){for(let f of c)l.delete(f);l.size===0?this.cache.remove(u):this.cache.set(u,l)}}Yl("Cleanup successful (%dms)",Date.now()-e)})}async _getProvidersMap(e){let t=F4(e),n=this.cache.get(t);return n==null&&(n=await oKe(this.components.datastore,e),this.cache.set(t,n)),n}async addProvider(e,t){await this.syncQueue.add(async()=>{Yl("%p provides %s",t,e);let n=await this._getProvidersMap(e);Yl("loaded %s provs",n.size);let i=new Date;n.set(t.toString(),i);let o=F4(e);this.cache.set(o,n),await iKe(this.components.datastore,e,t,i)})}async getProviders(e){return await this.syncQueue.add(async()=>(Yl("get providers for %s",e),[...(await this._getProvidersMap(e)).keys()].map(n=>Oe(n))),{throwOnTimeout:!0})}};function F4(r){let e=typeof r=="string"?r:re(r.multihash.bytes,"base32");return`${hM}/${e}`}async function iKe(r,e,t,n){let i=[F4(e),"/",t.toString()].join(""),o=new pe(i),s=Uint8Array.from(_M.default.encode(n.getTime()));await r.put(o,s)}function F1e(r){let e=r.toString().split("/");if(e.length!==5)throw new Error(`incorrectly formatted provider entry key in datastore: ${r.toString()}`);return{cid:e[3],peerId:e[4]}}async function oKe(r,e){let t=new Map,n=r.query({prefix:F4(e)});for await(let i of n){let{peerId:o}=F1e(i.key);t.set(o,z1e(i.value))}return t}function z1e(r){return new Date(_M.default.decode(r))}var q1e=C(Kn(),1),H1e=C(Da(),1);var V1e=C(Kn(),1),K1e=C(Da(),1);var sKe=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");async function*$1e(r){let{key:e,startingPeer:t,ourPeerId:n,signal:i,query:o,alpha:s,pathIndex:a,numPaths:c,cleanUp:u,queryFuncTimeout:l,log:f,peersSeen:h}=r,d=new qn({concurrency:s}),p=await xu(e);function g(w,_){if(w==null)return;h.add(w);let x=BigInt("0x"+re(Wl(_,p),"base16"));d.add(async()=>{let m,y=[i];l!=null&&(m=new V1e.TimeoutController(l),y.push(m.signal));let b=(0,K1e.anySignal)(y);try{for await(let E of o({key:e,peer:w,signal:b,pathIndex:a,numPaths:c})){if(b.aborted)return;if(E.name==="PEER_RESPONSE")for(let v of E.closer){if(h.has(v.id)){f("already seen %p in query",v.id);continue}if(n.equals(v.id)){f("not querying ourselves");continue}let S=await Es(v.id);if(BigInt("0x"+re(Wl(S,p),"base16"))>x){f("skipping %p as they are not closer to %b than %p",v.id,e,w);continue}f("querying closer peer %p",v.id),g(v.id,S)}d.emit("completed",E)}m==null||m.clear()}catch(E){i.aborted?d.emit("error",E):d.emit("completed",lo({from:w,error:E}))}finally{m==null||m.clear()}},{priority:sKe-x}).catch(m=>{f.error(m)})}g(t,await Es(t)),yield*aKe(d,i,u,f)}async function*aKe(r,e,t,n){let i=Qt(),o=!0,s=[],a=()=>{o&&(n("clean up queue, results %d, queue size %d, pending tasks %d",s.length,r.size,r.pending),o=!1,r.clear(),s.splice(0,s.length))};for(r.on("completed",c=>{s.push(c),i.resolve()}),r.on("error",c=>{n("queue error",c),a(),i.reject(c)}),r.on("idle",()=>{n("queue idle"),o=!1,i.resolve()}),e.addEventListener("abort",()=>{n("abort queue");let c=o;a(),c&&i.reject(new J("Query aborted","ERR_QUERY_ABORTED"))}),t.addEventListener("cleanup",()=>{a(),i.resolve()});o;)for(await i.promise,i=Qt();s.length>0;){let c=s.shift();c!=null&&(yield c)}yield*s}async function*ga(...r){let e=Ao({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var z4=C(xi(),1);var Kx=class{constructor(e,t){let{lan:n=!1,disjointPaths:i=20,alpha:o=3}=t;this.components=e,this.disjointPaths=i??20,this.controllers=new Set,this.running=!1,this.alpha=o??3,this.lan=n,this.queries=0}isStarted(){return this.running}async start(){this.running=!0,this.components.metrics!=null&&this.metrics==null&&(this.metrics={runningQueries:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_running_queries`),queryTime:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_query_time_seconds`)})}async stop(){this.running=!1;for(let e of this.controllers)e.abort();this.controllers.clear()}async*run(e,t,n,i={}){var p,g,w;if(!this.running)throw new Error("QueryManager not started");let o=(p=this.metrics)==null?void 0:p.queryTime.timer(),s;if(i.signal==null){s=new q1e.TimeoutController(3e4),i.signal=s.signal;try{z4.setMaxListeners!=null&&(0,z4.setMaxListeners)(1/0,s.signal)}catch{}}let a=new AbortController;this.controllers.add(a);let c=[a.signal];i.signal!=null&&c.push(i.signal);let u=(0,H1e.anySignal)(c);try{z4.setMaxListeners!=null&&(0,z4.setMaxListeners)(1/0,u)}catch{}let l=j(`libp2p:kad-dht:${this.lan?"lan":"wan"}:query:`+re(e,"base58btc")),f=t.slice(0,Math.min(this.disjointPaths,t.length)),h=Date.now(),d=new Ki;try{if(l("query:start"),this.queries++,(g=this.metrics)==null||g.runningQueries.update(this.queries),t.length===0){l.error("Running query with no peers");return}let _=new ma,x=f.map((m,y)=>$1e({key:e,startingPeer:m,ourPeerId:this.components.peerId,signal:u,query:n,pathIndex:y,numPaths:f.length,alpha:this.alpha,cleanUp:d,queryFuncTimeout:i.queryFuncTimeout,log:l,peersSeen:_}));for await(let m of ga(...x))yield m,m.name==="QUERY_ERROR"&&l("error",m.error)}catch(_){if(!(!this.running&&_.code==="ERR_QUERY_ABORTED"))throw _}finally{this.controllers.delete(a),s!=null&&s.clear(),this.queries--,(w=this.metrics)==null||w.runningQueries.update(this.queries),o!=null&&o(),d.dispatchEvent(new cn("cleanup")),l("query:done in %dms",Date.now()-h)}}};var V4=j("libp2p:kad-dht:rpc:handlers:add-provider"),$x=class{constructor(e){let{providers:t}=e;this.providers=t}async handle(e,t){if(V4("start"),t.key==null||t.key.length===0)throw new J("Missing key","ERR_MISSING_KEY");let n;try{n=z.decode(t.key)}catch{throw new J("Invalid CID","ERR_INVALID_CID")}(t.providerPeers==null||t.providerPeers.length===0)&&V4.error("no providers found in message"),await Promise.all(t.providerPeers.map(async i=>{if(!i.id.equals(e)){V4("invalid provider peer %p from %p",i.id,e);return}if(i.multiaddrs.length<1){V4("no valid addresses for provider %p. Ignore",e);return}V4("received provider %p for %s (addrs %s)",e,n,i.multiaddrs.map(o=>o.toString())),await this.providers.addProvider(n,i.id)}))}};var G1e=j("libp2p:kad-dht:rpc:handlers:find-node"),qx=class{constructor(e,t){let{peerRouting:n,lan:i}=t;this.components=e,this.peerRouting=n,this.lan=!!i}async handle(e,t){G1e("incoming request from %p for peers closer to %b",e,t.key);let n=[];mt(this.components.peerId.toBytes(),t.key)?n=[{id:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(o=>o.decapsulateCode(Fr("p2p").code)),protocols:[]}]:n=await this.peerRouting.getCloserPeersOffline(t.key,e),n=n.map(this.lan?_g:bg).filter(({multiaddrs:o})=>o.length);let i=new jr(t.type,new Uint8Array(0),t.clusterLevel);return n.length>0?i.closerPeers=n:G1e("could not find any peers closer to %b than %p",t.key,e),i}};var j1e=j("libp2p:kad-dht:rpc:handlers:get-providers"),Hx=class{constructor(e,t){let{peerRouting:n,providers:i,lan:o}=t;this.components=e,this.peerRouting=n,this.providers=i,this.lan=!!o}async handle(e,t){let n;try{n=z.decode(t.key)}catch{throw new J("Invalid CID","ERR_INVALID_CID")}j1e("%p asking for providers for %s",e,n);let[i,o]=await Promise.all([this.providers.getProviders(n),this.peerRouting.getCloserPeersOffline(t.key,e)]),s=await this._getPeers(i),a=await this._getPeers(o.map(({id:u})=>u)),c=new jr(t.type,t.key,t.clusterLevel);return s.length>0&&(c.providerPeers=s),a.length>0&&(c.closerPeers=a),j1e("got %s providers %s closerPeers",s.length,a.length),c}async _getAddresses(e){return(await this.components.peerStore.addressBook.get(e)).map(n=>n.multiaddr)}async _getPeers(e){let t=[],n=this.lan?_g:bg;for(let i of e){let o=n({id:i,multiaddrs:await this._getAddresses(i),protocols:[]});o.multiaddrs.length>0&&t.push(o)}return t}};var Sg=j("libp2p:kad-dht:rpc:handlers:get-value"),Gx=class{constructor(e,t){let{peerRouting:n}=t;this.components=e,this.peerRouting=n}async handle(e,t){let n=t.key;if(Sg("%p asked for key %b",e,n),n==null||n.length===0)throw new J("Invalid key","ERR_INVALID_KEY");let i=new jr(Sn.GET_VALUE,n,t.clusterLevel);if(x1e(n)){Sg("is public key");let a=S1e(n),c;try{let u=await this.components.peerStore.keyBook.get(a);if(u==null)throw new J("No public key found in key book","ERR_NOT_FOUND");c=u}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(c!=null)return Sg("returning found public key"),i.record=new Yr(n,c,new Date),i}let[o,s]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getCloserPeersOffline(t.key,e)]);return o!=null&&(Sg("had record for %b in local datastore",n),i.record=o),s.length>0&&(Sg("had %s closer peers in routing table",s.length),i.closerPeers=s),i}async _checkLocalDatastore(e){Sg("checkLocalDatastore looking for %b",e);let t=Gl(e),n;try{n=await this.components.datastore.get(t)}catch(o){if(o.code==="ERR_NOT_FOUND")return;throw o}let i=Yr.deserialize(n);if(i==null)throw new J("Invalid record","ERR_INVALID_RECORD");if(i.timeReceived==null||Date.now()-i.timeReceived.getTime()>1296e5){await this.components.datastore.delete(t);return}return i}};var lKe=j("libp2p:kad-dht:rpc:handlers:ping"),jx=class{async handle(e,t){return lKe("ping from %p",e),t}};var Wx=class{constructor(e,t){let{validators:n}=t;this.components=e,this.log=j("libp2p:kad-dht:rpc:handlers:put-value"),this.validators=n}async handle(e,t){let n=t.key;this.log("%p asked us to store value for key %b",e,n);let i=t.record;if(i==null){let o=`Empty record from: ${e.toString()}`;throw this.log.error(o),new J(o,"ERR_EMPTY_RECORD")}try{await vg(this.validators,i),i.timeReceived=new Date;let o=Gl(i.key);await this.components.datastore.put(o,i.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,o)}catch(o){this.log("did not put record for key %b into datastore %o",n,o)}return t}};var Yx=class{constructor(e,t){let{providers:n,peerRouting:i,validators:o,lan:s}=t;this.log=j("libp2p:kad-dht:rpc"),this.routingTable=t.routingTable,this.handlers={[Sn.GET_VALUE]:new Gx(e,{peerRouting:i}),[Sn.PUT_VALUE]:new Wx(e,{validators:o}),[Sn.FIND_NODE]:new qx(e,{peerRouting:i,lan:s}),[Sn.ADD_PROVIDER]:new $x({providers:n}),[Sn.GET_PROVIDERS]:new Hx(e,{peerRouting:i,providers:n,lan:s}),[Sn.PING]:new jx}}async handleMessage(e,t){try{await this.routingTable.add(e)}catch(i){this.log.error("Failed to update the kbucket store",i)}let n=this.handlers[t.type];if(n==null){this.log.error(`no handler found for message type: ${t.type}`);return}return await n.handle(e,t)}onIncomingStream(e){Promise.resolve().then(async()=>{let{stream:t,connection:n}=e,i=n.remotePeer;try{await this.routingTable.add(i)}catch(s){this.log.error(s)}let o=this;await Ne(t,Xr(),async function*(s){for await(let a of s){let c=jr.deserialize(a);o.log("incoming %s from %p",c.type,i);let u=await o.handleMessage(i,c);u!=null&&(yield u.serialize())}},vn(),t)}).catch(t=>{this.log.error(t)})}};var Qx=class extends Ki{constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=j(`libp2p:kad-dht:topology-listener:${i?"lan":"wan"}`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){if(this.running)return;this.running=!0;let e=hv({onConnect:t=>{this.log("observed peer %p with protocol %s",t,this.protocol),this.dispatchEvent(new cn("peer",{detail:t}))}});this.registrarId=await this.components.registrar.register(this.protocol,e)}async stop(){this.running=!1,this.registrarId!=null&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}};var vM=C(xi(),1);async function*EM(r,e){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}var W1e=C(Kn(),1),Y1e=C(Da(),1);var Xx=class{constructor(e,t){let{peerRouting:n,lan:i,count:o,interval:s,queryTimeout:a}=t;this.components=e,this.log=j(`libp2p:kad-dht:${i?"lan":"wan"}:query-self`),this.running=!1,this.peerRouting=n,this.count=o??20,this.interval=s??3e5,this.queryTimeout=a??3e4}isStarted(){return this.running}async start(){this.running||(this.running=!0,this._querySelf())}async stop(){this.running=!1,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.controller!=null&&this.controller.abort()}_querySelf(){Promise.resolve().then(async()=>{let e=new W1e.TimeoutController(this.queryTimeout);try{this.controller=new AbortController;let t=(0,Y1e.anySignal)([this.controller.signal,e.signal]);try{vM.setMaxListeners!=null&&(0,vM.setMaxListeners)(1/0,t)}catch{}let n=await Ne(this.peerRouting.getClosestPeers(this.components.peerId.toBytes(),{signal:t}),i=>EM(i,this.count),async i=>await L4(i));this.log("query ran successfully - found %d peers",n)}catch(t){this.log("query error",t)}finally{this.timeoutId=setTimeout(this._querySelf.bind(this),this.interval),e.clear()}}).catch(e=>{this.log("query error",e)})}};var Prr=Symbol.for("@libp2p/peer-discovery"),Ag=Symbol.for("@libp2p/peer-discovery");var hKe=32,pKe=64,K4=class extends Ki{constructor(e,t){super();let{kBucketSize:n,clientMode:i,validators:o,selectors:s,querySelfInterval:a,lan:c,protocolPrefix:u,pingTimeout:l,pingConcurrency:f,maxInboundStreams:h,maxOutboundStreams:d,providers:p}=t;this.running=!1,this.components=e,this.lan=!!c,this.log=j(`libp2p:kad-dht:${c===!0?"lan":"wan"}`),this.protocol=`${u??b1e}${c===!0?w1e:""}${_1e}`,this.kBucketSize=n??20,this.clientMode=i??!0,this.maxInboundStreams=h??hKe,this.maxOutboundStreams=d??pKe,this.routingTable=new kx(e,{kBucketSize:n,lan:this.lan,pingTimeout:l,pingConcurrency:f,protocol:this.protocol}),this.providers=new zx(e,p??{}),this.validators={...L1e,...o},this.selectors={...M1e,...s},this.network=new Ox(e,{protocol:this.protocol,lan:this.lan}),this.queryManager=new Kx(e,{disjointPaths:Math.ceil(this.kBucketSize/2),lan:c}),this.peerRouting=new Fx(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,lan:this.lan}),this.contentFetching=new Lx(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,network:this.network,lan:this.lan}),this.contentRouting=new Bx(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,lan:this.lan}),this.routingTableRefresh=new Dx({peerRouting:this.peerRouting,routingTable:this.routingTable,lan:this.lan}),this.rpc=new Yx(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,lan:this.lan}),this.topologyListener=new Qx(e,{protocol:this.protocol,lan:this.lan}),this.querySelf=new Xx(e,{peerRouting:this.peerRouting,interval:a,lan:this.lan}),this.network.addEventListener("peer",g=>{let w=g.detail;this.onPeerConnect(w).catch(_=>{this.log.error("could not add %p to routing table",w.id,_)}),this.dispatchEvent(new cn("peer",{detail:w}))}),this.topologyListener.addEventListener("peer",g=>{let w=g.detail;Promise.resolve().then(async()=>{let _=await this.components.peerStore.addressBook.get(w),x={id:w,multiaddrs:_.map(m=>m.multiaddr),protocols:[]};await this.onPeerConnect(x)}).catch(_=>{this.log.error("could not add %p to routing table",w,_)})})}get[Ag](){return!0}get[Symbol.toStringTag](){return"@libp2p/kad-dht"}async onPeerConnect(e){if(this.log("peer %p connected with protocols %s",e.id,e.protocols),this.lan?e=_g(e):e=bg(e),e.multiaddrs.length===0){this.log("ignoring %p as they do not have any %s addresses in %s",e.id,this.lan?"private":"public",e.multiaddrs.map(t=>t.toString()));return}try{await this.routingTable.add(e.id)}catch(t){this.log.error("could not add %p to routing table",e.id,t)}}isStarted(){return this.running}async getMode(){return this.clientMode?"client":"server"}async setMode(e){await this.components.registrar.unhandle(this.protocol),e==="client"?(this.log("enabling client mode"),this.clientMode=!0):(this.log("enabling server mode"),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}))}async start(){this.running=!0,await this.setMode(this.clientMode?"client":"server"),await Promise.all([this.providers.start(),this.queryManager.start(),this.network.start(),this.routingTable.start(),this.topologyListener.start(),this.querySelf.start()]),await this.routingTableRefresh.start()}async stop(){this.running=!1,await Promise.all([this.providers.stop(),this.queryManager.stop(),this.network.stop(),this.routingTable.stop(),this.routingTableRefresh.stop(),this.topologyListener.stop(),this.querySelf.stop()])}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(){this.routingTableRefresh.refreshTable(!0)}};var mKe=j("libp2p:kad-dht"),Zx=class extends Ki{constructor(e,t,n){super(),this.components=e,this.wan=t,this.lan=n,this.wan.addEventListener("peer",i=>{this.dispatchEvent(new cn("peer",{detail:i.detail}))}),this.lan.addEventListener("peer",i=>{this.dispatchEvent(new cn("peer",{detail:i.detail}))})}get[Ag](){return!0}get[Symbol.toStringTag](){return"@libp2p/dual-kad-dht"}isStarted(){return this.wan.isStarted()&&this.lan.isStarted()}async getMode(){return await this.wan.getMode()}async setMode(e){await this.wan.setMode(e)}async start(){await Promise.all([this.lan.start(),this.wan.start()])}async stop(){await Promise.all([this.lan.stop(),this.wan.stop()])}async*put(e,t,n={}){for await(let i of ga(this.lan.put(e,t,n),this.wan.put(e,t,n)))yield i}async*get(e,t={}){let n=!1,i=!1;for await(let o of ga(this.lan.get(e,t),this.wan.get(e,t)))yield o,o.name==="DIALING_PEER"&&(n=!0),o.name==="VALUE"&&(n=!0,o.value!=null&&(i=!0)),o.name==="SENDING_QUERY"&&(n=!0);if(!n)throw new J("No peers found in routing table!","ERR_NO_PEERS_IN_ROUTING_TABLE");i||(yield lo({from:this.components.peerId,error:new J("Not found","ERR_NOT_FOUND")}))}async*provide(e,t={}){let n=0,i=0,o=[],s=[this.lan];await this.wan.getMode()==="server"&&s.push(this.wan);for await(let a of ga(...s.map(c=>c.provide(e,t))))yield a,a.name==="SENDING_QUERY"&&n++,a.name==="QUERY_ERROR"&&o.push(a.error),a.name==="PEER_RESPONSE"&&a.messageName==="ADD_PROVIDER"&&(mKe("sent provider record for %s to %p",e,a.from),i++);if(i===0)throw o.length>0?new J(`Failed to provide to ${o.length} of ${n} peers`,"ERR_PROVIDES_FAILED",{errors:o}):new J("Failed to provide - no peers found","ERR_PROVIDES_FAILED")}async*findProviders(e,t={}){yield*ga(this.lan.findProviders(e,t),this.wan.findProviders(e,t))}async*findPeer(e,t={}){let n=!1;for await(let i of ga(this.lan.findPeer(e,t),this.wan.findPeer(e,t)))yield i,(i.name==="SENDING_QUERY"||i.name==="FINAL_PEER")&&(n=!0);if(!n)throw new J("Peer lookup failed","ERR_LOOKUP_FAILED")}async*getClosestPeers(e,t={}){yield*ga(this.lan.getClosestPeers(e,t),this.wan.getClosestPeers(e,t))}async refreshRoutingTable(){await Promise.all([this.lan.refreshRoutingTable(),this.wan.refreshRoutingTable()])}};var xM=class extends Zx{constructor(e,t){super(e,new K4(e,{protocolPrefix:"/ipfs",...t,lan:!1}),new K4(e,{protocolPrefix:"/ipfs",...t,clientMode:!1,lan:!0}))}};function Q1e(r){return e=>new xM(e,r)}var Jx=j("libp2p:bootstrap"),gKe="bootstrap",yKe=50,wKe=12e4,bKe=1e3,eS=class extends Ki{constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.timeout=t.timeout??bKe,this.list=[];for(let n of t.list){if(!rR.matches(n)){Jx.error("Invalid multiaddr");continue}let i=Xi(n),o=i.getPeerId();if(o==null){Jx.error("Invalid bootstrap multiaddr without peer id");continue}let s={id:Oe(o),multiaddrs:[i],protocols:[]};this.list.push(s)}this._init=t}get[Ag](){return!0}get[Symbol.toStringTag](){return"@libp2p/bootstrap"}isStarted(){return!!this.timer}start(){this.isStarted()||(Jx("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{Jx.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.tagPeer(e.id,this._init.tagName??gKe,{value:this._init.tagValue??yKe,ttl:this._init.tagTTL??wKe}),this.timer==null)return;this.dispatchEvent(new cn("peer",{detail:e}))}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};eS.tag="bootstrap";function X1e(r){return e=>new eS(e,r)}var Z1e=WebSocket;var rme=C(eme(),1);function tme(r){var e;return r instanceof ArrayBuffer||((e=r==null?void 0:r.constructor)==null?void 0:e.name)==="ArrayBuffer"&&typeof(r==null?void 0:r.byteLength)=="number"}var nme=r=>{r.binaryType="arraybuffer";let e=async()=>await new Promise((o,s)=>{if(n)return o();if(i!=null)return s(i);let a=l=>{r.removeEventListener("open",c),r.removeEventListener("error",u),l()},c=()=>a(o),u=l=>{a(()=>s(l.error??new Error(`connect ECONNREFUSED ${r.url}`)))};r.addEventListener("open",c),r.addEventListener("error",u)}),t=async function*(){let o=new rme.EventIterator(({push:s,stop:a,fail:c})=>{let u=f=>{let h=null;typeof f.data=="string"&&(h=fe(f.data)),tme(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&s(h)},l=f=>c(f.error??new Error("Socket error"));return r.addEventListener("message",u),r.addEventListener("error",l),r.addEventListener("close",a),()=>{r.removeEventListener("message",u),r.removeEventListener("error",l),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of o)yield tme(s)?new Uint8Array(s):s}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",o=>{n||(i=o.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var ime=r=>{if(r.readyState>=2)throw new Error("socket closed");if(r.readyState!==1)return new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",o)}function i(){n(),e()}function o(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",o)})};var ome=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await ime(r)}catch(o){if(o.message==="socket closed")break;throw o}r.send(i)}if(e.closeOnEnd!=null&&r.readyState<=1)return await new Promise((i,o)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:s});o(a)}}),setTimeout(()=>r.close())})});var sme=(r,e)=>{e=e??{};let t=nme(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,i=parseInt(s.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:ome(r,e),source:t,connected:async()=>await t.connected(),close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var ame=C(F8(),1),EKe={http:"ws",https:"wss"},vKe="ws",cme=(r,e)=>(0,ame.relative)(r,e,EKe,vKe);function ume(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=cme(r,t.toString()),i=new Z1e(n,e.websocket);return sme(i,e)}function lme(){throw new Error("WebSocket Servers can not be created in the browser!")}var fme=j("libp2p:websockets:socket");function dme(r,e,t){t=t??{};let n={async sink(i){(t==null?void 0:t.signal)!=null&&(i=na(i,t.signal));try{await r.sink(i)}catch(o){o.type!=="aborted"&&fme.error(o)}},source:t.signal!=null?na(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let i=Date.now();try{await yp(r.close(),{milliseconds:2e3})}catch{let{host:s,port:a}=n.remoteAddr.toOptions();fme("timeout closing stream to %s:%s after %dms, destroying it manually",s,a,Date.now()-i),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}function mme(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return P1.matches(t)||xh.matches(t)})}function gme(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return xh.matches(t)})}var wme=Symbol.for("@libp2p/transport");var yme;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(yme||(yme={}));var oh=j("libp2p:websockets"),TM=class{constructor(e){this.init=e}get[Symbol.toStringTag](){return"@libp2p/websockets"}get[wme](){return!0}async dial(e,t){oh("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=dme(n,e);oh("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i);return oh("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){var u,l;if(((u=t==null?void 0:t.signal)==null?void 0:u.aborted)===!0)throw new Ph;let n=e.toOptions();oh("dialing %s:%s",n.host,n.port);let i=Qt(),o=f=>{oh.error("connection error:",f),i.reject(f)},s=ume(zm(e),this.init);if(s.socket.on!=null?s.socket.on("error",o):s.socket.onerror=o,t.signal==null)return await Promise.race([s.connected(),i.promise]),oh("connected %s",e),s;let a,c=new Promise((f,h)=>{var d,p;if(a=()=>{h(new Ph),s.close().catch(g=>{oh.error("error closing raw socket",g)})},((d=t==null?void 0:t.signal)==null?void 0:d.aborted)===!0){a();return}(p=t==null?void 0:t.signal)==null||p.addEventListener("abort",a)});try{await Promise.race([c,i.promise,s.connected()])}finally{a!=null&&((l=t==null?void 0:t.signal)==null||l.removeEventListener("abort",a))}return oh("connected %s",e),s}createListener(e){return lme({...this.init,...e})}filter(e){var t,n;return e=Array.isArray(e)?e:[e],((t=this.init)==null?void 0:t.filter)!=null?(n=this.init)==null?void 0:n.filter(e):T0||rx?gme(e):mme(e)}};function bme(r={}){return()=>new TM(r)}var Tg=C(Xo(),1);function IM(r){return new Uint8Array(r)}var Ut;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(Ut||(Ut={}));var q4=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),RM=Object.freeze({NEW_STREAM:Ut.NEW_STREAM,MESSAGE:Ut.MESSAGE_INITIATOR,CLOSE:Ut.CLOSE_INITIATOR,RESET:Ut.RESET_INITIATOR}),_me=Object.freeze({MESSAGE:Ut.MESSAGE_RECEIVER,CLOSE:Ut.CLOSE_RECEIVER,RESET:Ut.RESET_RECEIVER});var Eme=1024*1024,AKe=(r,e)=>{e.append(r)};async function*TKe(r,e={}){let t=new vt,n=!1,i=Qt(),o=Number(e.size??Eme);(isNaN(o)||o===0||o<0)&&(o=Eme);let s=e.yieldAfter??0,a=e.serialize??AKe;for(Promise.resolve().then(async()=>{try{let c;for await(let u of r){if(a(u,t),t.byteLength>=o){clearTimeout(c),i.resolve();continue}c=setTimeout(()=>{i.resolve()},s)}clearTimeout(c),i.resolve()}catch(c){i.reject(c)}finally{n=!0}});!n;)if(await i.promise,i=Qt(),t.byteLength>0){let c=t;t=new vt,yield c.subarray()}}var vme=TKe;var CM=10*1024,PM=class{constructor(){this._pool=IM(CM),this._poolOffset=0}write(e,t){let n=this._pool,i=this._poolOffset;Tg.default.encode(e.id<<3|e.type,n,i),i+=Tg.default.encode.bytes??0,(e.type===Ut.NEW_STREAM||e.type===Ut.MESSAGE_INITIATOR||e.type===Ut.MESSAGE_RECEIVER)&&e.data!=null?Tg.default.encode(e.data.length,n,i):Tg.default.encode(0,n,i),i+=Tg.default.encode.bytes??0;let o=n.subarray(this._poolOffset,i);CM-i<100?(this._pool=IM(CM),this._poolOffset=0):this._poolOffset=i,t.append(o),(e.type===Ut.NEW_STREAM||e.type===Ut.MESSAGE_INITIATOR||e.type===Ut.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},xme=new PM;async function*Sme(r,e=0){if(e==null||e===0){for await(let t of r){let n=new vt;for(let i of t)xme.write(i,n);yield n.subarray()}return}yield*vme(r,{size:e,serialize:(t,n)=>{for(let i of t)xme.write(i,n)}})}var kM=1<<20,IKe=4<<20,nS=class{constructor(e=kM,t=IKe){this._buffer=new vt,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)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"});let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(u){if(u.code==="ERR_MSG_TOO_BIG")throw u;break}let{id:n,type:i,length:o,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:s,offset:n+o,length:i}}},RKe=128,Ame=127;function Tme(r,e=0){let t=0,n=0,i=e,o,s=r.length;do{if(i>=s||n>49)throw e=0,new RangeError("Could not decode varint");o=r.get(i++),t+=n<28?(o&Ame)<=RKe);return e=i-e,{value:t,offset:e}}var cc=j("libp2p:mplex:stream"),NM="ERR_STREAM_RESET",CKe="ERR_STREAM_ABORT",PKe="ERR_SINK_ENDED",kKe="ERR_DOUBLE_SINK";function Ime(r){let{id:e,name:t,send:n,onEnd:i,type:o="initiator",maxMsgSize:s=kM}=r,a=new AbortController,c=new AbortController,u=new AbortController,l=o==="initiator"?RM:_me,f=o==="initiator"?`i${e}`:`r${e}`,h=`${t??e}`,d=!1,p=!1,g=!1,w,_={open:Date.now()},x=E=>{d||(d=!0,cc.trace("%s stream %s source end - err: %o",o,h,E),E!=null&&w==null&&(w=E),p&&(b.stat.timeline.close=Date.now(),i!=null&&i(w)))},m=E=>{p||(p=!0,cc.trace("%s stream %s sink end - err: %o",o,h,E),E!=null&&w==null&&(w=E),d&&(_.close=Date.now(),i!=null&&i(w)))},y=Ao({onEnd:x}),b={close:()=>{cc.trace("%s stream %s close",o,h),b.closeRead(),b.closeWrite()},closeRead:()=>{cc.trace("%s stream %s closeRead",o,h),!d&&y.end()},closeWrite:()=>{if(cc.trace("%s stream %s closeWrite",o,h),!p){u.abort();try{n({id:e,type:l.CLOSE})}catch(E){cc.trace("%s stream %s error sending close",o,t,E)}m()}},abort:E=>{cc.trace("%s stream %s abort",o,h,E),y.end(E),a.abort(),m(E)},reset:()=>{let E=new J("stream reset",NM);c.abort(),y.end(E),m(E)},sink:async E=>{if(g)throw new J("sink already called on stream",kKe);if(g=!0,p)throw new J("stream closed for writing",PKe);let v=ia([a.signal,c.signal,u.signal]);try{E=na(E,v),o==="initiator"&&n({id:e,type:RM.NEW_STREAM,data:new vt(Ie(h))});for await(let S of E)for(;S.length>0;){if(S.length<=s){n({id:e,type:l.MESSAGE,data:S instanceof Uint8Array?new vt(S):S});break}S=S instanceof Uint8Array?new vt(S):S,n({id:e,type:l.MESSAGE,data:S.sublist(0,s)}),S.consume(s)}}catch(S){if(S.type==="aborted"&&S.message==="The operation was aborted"){if(u.signal.aborted)return;c.signal.aborted&&(S.message="stream reset",S.code=NM),a.signal.aborted&&(S.message="stream aborted",S.code=CKe)}if(S.code===NM)cc.trace("%s stream %s reset",o,t);else{cc.trace("%s stream %s error",o,t,S);try{n({id:e,type:l.RESET})}catch(A){cc.trace("%s stream %s error sending reset",o,t,A)}}y.end(S),m(S);return}finally{v.clear()}try{n({id:e,type:l.CLOSE})}catch(S){cc.trace("%s stream %s error sending close",o,t,S)}m()},source:y,sourcePush:E=>{y.push(E)},sourceReadableLength(){return y.readableLength},stat:{direction:o==="initiator"?"outbound":"inbound",timeline:_},metadata:{},id:f};return b}var x2e=C(E2e(),1);var uc=j("libp2p:mplex"),h$e=1024,p$e=1024,m$e=1024*1024*4,g$e=5;function v2e(r){let e={...r,type:`${q4[r.type]} (${r.type})`};return r.type===Ut.NEW_STREAM&&(e.data=re(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===Ut.MESSAGE_INITIATOR||r.type===Ut.MESSAGE_RECEIVER)&&(e.data=re(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var oS=class{constructor(e){this.protocol="/mplex/6.7.0",e=e??{},this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=e,this.sink=this._createSink();let t=this._createSource();this._source=t,this.source=t,this.closeController=new AbortController,this.rateLimiter=new x2e.RateLimiterMemory({points:e.disconnectThreshold??g$e,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let n=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:n})}close(e){this.closeController.signal.aborted||(e!=null?this.streams.forEach(t=>{t.abort(e)}):this.streams.forEach(t=>{t.close()}),this.closeController.abort())}_newReceiverStream(e){let{id:t,name:n}=e,i=this._streams.receivers;return this._newStream({id:t,name:n,type:"receiver",registry:i})}_newStream(e){let{id:t,name:n,type:i,registry:o}=e;if(uc("new %s stream %s",i,t),i==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??p$e))throw new J("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(o.has(t))throw new Error(`${i} stream ${t} already exists!`);let c=Ime({id:t,name:n,send:u=>{uc.enabled&&uc.trace("%s stream %s send",i,t,v2e(u)),this._source.push(u)},type:i,onEnd:()=>{uc("%s stream with id %s and protocol %s ended",i,t,c.stat.protocol),o.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize});return o.set(t,c),c}_createSink(){return async t=>{let n=ia([this.closeController.signal,this._init.signal]);try{t=na(t,n);let i=new nS(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let o of t)for(let s of i.write(o))await this._handleIncoming(s);this._source.end()}catch(i){uc("error in sink",i),this._source.end(i)}finally{n.clear()}}}_createSource(){let t=Bae({objectMode:!0,onEnd:n=>{this.close(n)}});return Object.assign(Sme(t,this._init.minSendBytes),{push:t.push,end:t.end,return:t.return})}async _handleIncoming(e){let{id:t,type:n}=e;if(uc.enabled&&uc.trace("incoming message",v2e(e)),e.type===Ut.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??h$e)){uc("too many inbound streams open"),this._source.push({id:t,type:Ut.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{uc("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this._source.end(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:re(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let o=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(o==null){uc("missing stream %s for message type %s",t,q4[n]);return}let s=this._init.maxStreamBufferSize??m$e;switch(n){case Ut.MESSAGE_INITIATOR:case Ut.MESSAGE_RECEIVER:if(o.sourceReadableLength()>s){this._source.push({id:e.id,type:n===Ut.MESSAGE_INITIATOR?Ut.RESET_RECEIVER:Ut.RESET_INITIATOR});let a=new J("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");o.abort(a);return}o.sourcePush(e.data);break;case Ut.CLOSE_INITIATOR:case Ut.CLOSE_RECEIVER:o.closeRead();break;case Ut.RESET_INITIATOR:case Ut.RESET_RECEIVER:o.reset();break;default:uc("unknown message type %s",n)}}};var GM=class{constructor(e={}){this.protocol="/mplex/6.7.0",this._init=e}createStreamMuxer(e={}){return new oS({...e,...this._init})}};function S2e(r={}){return()=>new GM(r)}function sS(r){return r[Symbol.asyncIterator]!=null}var aS=r=>{let e=ti(r),t=Ri(e);return xf(r,t),aS.bytes=e,t};aS.bytes=0;function cS(r,e){e=e??{};let t=e.lengthEncoder??aS;function*n(i){let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return sS(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}cS.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??aS;return new vt(t(r.byteLength),r)};var uS=class extends Error{constructor(){super(...arguments);B(this,"name","InvalidMessageLengthError");B(this,"code","ERR_INVALID_MSG_LENGTH")}},lS=class extends Error{constructor(){super(...arguments);B(this,"name","InvalidDataLengthError");B(this,"code","ERR_MSG_DATA_TOO_LONG")}},fS=class extends Error{constructor(){super(...arguments);B(this,"name","InvalidDataLengthLengthError");B(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},j4=class extends Error{constructor(){super(...arguments);B(this,"name","UnexpectedEOFError");B(this,"code","ERR_UNEXPECTED_EOF")}};var y$e=8,w$e=1024*1024*4,C0;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(C0||(C0={}));var WM=r=>{let e=Gu(r);return WM.bytes=ti(e),e};WM.bytes=0;function jM(r,e){let t=new vt,n=C0.LENGTH,i=-1,o=(e==null?void 0:e.lengthDecoder)??WM,s=(e==null?void 0:e.maxLengthLength)??y$e,a=(e==null?void 0:e.maxDataLength)??w$e;function*c(){for(;t.byteLength>0;){if(n===C0.LENGTH)try{if(i=o(t),i<0)throw new uS("Invalid message length");if(i>a)throw new lS("Message length too long");let u=o.bytes;t.consume(u),(e==null?void 0:e.onLength)!=null&&e.onLength(i),n=C0.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>s)throw new fS("Message length length too long");break}throw u}if(n===C0.DATA){if(t.byteLength0)throw new j4("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new j4("Unexpected end of input")}()}jM.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return jM(n,{...e??{},onLength:o=>{t=o}})};var dS=C(ee(),1),A2e=r=>Yp.decode(r);A2e.bytes=0;function YM(r,e={}){let t=Ao();r.sink(t).catch(s=>{t.end(s)}),r.sink=async s=>{for await(let a of s)t.push(a)};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let i=new vt,o={read:async s=>{if(s==null){let{done:c,value:u}=await n.next();return c===!0?new vt:u}for(;i.byteLength{let s=-1,a=new vt,c=(e==null?void 0:e.lengthDecoder)??A2e;for(;;){a.append(await o.read(1));try{s=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(s>-1)break;if((e==null?void 0:e.maxLengthLength)!=null&&a.byteLength>e.maxLengthLength)throw(0,dS.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if((e==null?void 0:e.maxDataLength)!=null&&s>e.maxDataLength)throw(0,dS.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await o.read(s)},readPB:async s=>{let a=await o.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return s.decode(c)},write:s=>{s instanceof Uint8Array?t.push(s):t.push(s.subarray())},writeLP:s=>{o.write(cS.single(s,e))},writePB:(s,a)=>{o.writeLP(a.encode(s))},pb:s=>({read:async()=>await o.readPB(s),write:a=>{o.writePB(a,s)},unwrap:()=>o}),unwrap:()=>{let s=r.source;return r.source=async function*(){yield*i,yield*s}(),r}};return o}function QM(){let r=Qt(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:async function*(){yield*await r.promise}()}}function T2e(){let r=QM(),e=QM();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}var I2e,R2e,C2e=!!((R2e=(I2e=globalThis.process)==null?void 0:I2e.env)!=null&&R2e.DUMP_SESSION_KEYS);var uge=C(B2e(),1),Ng=C(ege(),1),TS=C(rge(),1),hU=C(dU(),1),lge={hashSHA256(r){return(0,TS.hash)(r)},getHKDF(r,e){let i=new uge.HKDF(TS.SHA256,e,r).expand(96),o=i.subarray(0,32),s=i.subarray(32,64),a=i.subarray(64,96);return[o,s,a]},generateX25519KeyPair(){let r=Ng.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=Ng.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return Ng.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new hU.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new hU.ChaCha20Poly1305(n).open(e,r,t,i)}};var pU=C(dU(),1);var Rqe=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),Dg=r=>{let e=Rqe(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};Dg.bytes=2;var J4=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");return r instanceof Uint8Array?new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,!1):r.getUint16(0)};J4.bytes=2;function fge(r){return rt([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function dge(r){return rt([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function hge(r){return rt([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function pge(r){if(r.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:r.subarray(0,32),ciphertext:r.subarray(32,r.length),ns:new Uint8Array(0)}}function mge(r){if(r.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:r.subarray(0,32),ns:r.subarray(32,80),ciphertext:r.subarray(80,r.length)}}function gge(r){if(r.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:r.subarray(0,48),ciphertext:r.subarray(48,r.length)}}function wge(r,e){return async function*(t){for await(let n of t)for(let i=0;in.length&&(o=n.length);let s=r.encrypt(n.subarray(i,o),r.session);e==null||e.encryptedPackets.increment(),yield Dg(s.byteLength),yield s}}}function bge(r,e){return async function*(t){for await(let n of t)for(let i=0;in.length&&(o=n.length),o-pU.TAG_LENGTH(e==null&&(e=kn((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)n.uint32(10),n.bytes(o);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(IS||(IS={}));var t6;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identityKey!=null&&t.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(t.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||t.identitySig!=null&&t.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(t.identitySig??new Uint8Array(0))),t.extensions!=null&&(n.uint32(34),IS.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=IS.codec().decode(t,t.uint32());break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(t6||(t6={}));async function _ge(r,e,t){let n=await Pqe(r,Ege(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return Cqe(r.publicKey,n,t)}function Cqe(r,e,t){return t6.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function Pqe(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await Li(r.privateKey)).sign(e)}async function mU(r){return await Hn(r.identityKey)}function gU(r){return t6.decode(r)}function Ege(r){let e=Ie("noise-libp2p-static-key:");return rt([e,r],e.length+r.length)}async function yU(r,e,t){let n=await Hn(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=Ege(r);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await Bs(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function r6(r){return!(!(r instanceof Uint8Array)||r.length!==32)}var di=j("libp2p:noise");var wa;C2e?wa=di:wa=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function vge(r){wa(`LOCAL_STATIC_PUBLIC_KEY ${re(r.publicKey,"hex")}`),wa(`LOCAL_STATIC_PRIVATE_KEY ${re(r.privateKey,"hex")}`)}function wU(r){r?(wa(`LOCAL_PUBLIC_EPHEMERAL_KEY ${re(r.publicKey,"hex")}`),wa(`LOCAL_PRIVATE_EPHEMERAL_KEY ${re(r.privateKey,"hex")}`)):wa("Missing local ephemeral keys.")}function xge(r){wa(`REMOTE_STATIC_PUBLIC_KEY ${re(r,"hex")}`)}function bU(r){wa(`REMOTE_EPHEMERAL_PUBLIC_KEY ${re(r,"hex")}`)}function Sge(r){r.cs1&&r.cs2?(wa(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${re(r.cs1.k,"hex")}`),wa(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${re(r.cs2.k,"hex")}`)):wa("Missing cipher state.")}var kqe="Cipherstate has reached maximum n, a new handshake must be performed",RS=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(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(kqe)}};var CS=class{constructor(e){this.crypto=e}encryptWithAd(e,t,n){let i=this.encrypt(e.k,e.n,t,n);return e.n.increment(),i}decryptWithAd(e,t,n,i){let{plaintext:o,valid:s}=this.decrypt(e.k,e.n,t,n,i);return s&&e.n.increment(),{plaintext:o,valid:s}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return mt(t,e)}encrypt(e,t,n,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),n,e)}encryptAndHash(e,t){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,n),n}decrypt(e,t,n,i,o){t.assertValue();let s=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,o);return s?{plaintext:s,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,t),{plaintext:n,valid:i}}dh(e,t){try{let n=this.crypto.generateX25519SharedKey(e,t);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return di.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(rt([e,t],e.length+t.length))}mixKey(e,t){let[n,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new RS}}initializeSymmetric(e){let t=Ie(e,"utf-8"),n=this.hashProtocolName(t),i=n,o=this.createEmptyKey();return{cs:this.initializeKey(o),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let t=new Uint8Array(32);return t.set(e),t}else return this.getHash(e,new Uint8Array(0))}split(e){let[t,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(t),o=this.initializeKey(n);return{cs1:i,cs2:o}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),o=new Uint8Array(0);return{ne:i,ns:o,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var PS=class extends CS{initializeInitiator(e,t,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,e);let a=new Uint8Array(32);return{ss:s,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,e);let a=new Uint8Array(32);return{ss:s,s:t,rs:n,psk:i,re:a}}writeMessageA(e,t,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let o=e.e.publicKey;this.mixHash(e.ss,o);let s=this.encryptAndHash(e.ss,t);return{ne:o,ns:i,ciphertext:s}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,o=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t);return{ne:n,ns:o,ciphertext:s}}writeMessageC(e,t){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:o},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,t){return r6(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(r6(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&r6(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:o,valid:s}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:o,valid:i&&s}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&r6(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:o,valid:s}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:o,valid:i&&s,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),o=new Uint8Array(32),s;return e?s=this.initializeInitiator(t,n,o,i):s=this.initializeResponder(t,n,o,i),{hs:s,i:e,mc:0}}sendMessage(e,t,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,t,n);else if(e.mc===1)i=this.writeMessageB(e.hs,t);else if(e.mc===2){let{h:o,messageBuffer:s,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=s,e.h=o,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,t){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,t));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,t));else if(e.mc===2){let{h:o,plaintext:s,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,t);n=s,i=a,e.h=o,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var kS=class{constructor(e,t,n,i,o,s,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=o,this.connection=s,a&&(this.remotePeer=a),this.xx=c??new PS(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(vge(this.session.hs.s),this.isInitiator){di.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(fge(e)),di.trace("Stage 0 - Initiator finished sending first message."),wU(this.session.hs.e)}else{di.trace("Stage 0 - Responder waiting to receive first message...");let e=pge((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new Jl("xx handshake stage 0 validation fail");di.trace("Stage 0 - Responder received first message."),bU(this.session.hs.re)}}async exchange(){if(this.isInitiator){di.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=mge((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Jl("xx handshake stage 1 validation fail");di.trace("Stage 1 - Initiator received the message."),bU(this.session.hs.re),xge(this.session.hs.rs),di.trace("Initiator going to check remote's signature...");try{let i=gU(t);this.remotePeer=this.remotePeer||await mU(i),await yU(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new P0(`Error occurred while verifying signed payload: ${o.message}`)}di.trace("All good with the signature!")}else{di.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(dge(e)),di.trace("Stage 1 - Responder sent the second handshake message with signed payload."),wU(this.session.hs.e)}}async finish(){if(this.isInitiator){di.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(hge(e)),di.trace("Stage 2 - Initiator sent message with signed payload.")}else{di.trace("Stage 2 - Responder waiting for third handshake message...");let e=gge((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Jl("xx handshake stage 2 validation fail");di.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=gU(t);this.remotePeer=this.remotePeer||await mU(i),await yU(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new P0(`Error occurred while verifying signed payload: ${o.message}`)}}Sge(this.session)}encrypt(e,t){let n=this.getCS(t);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,t,n){let i=this.getCS(t,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new Jl("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function Age(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var NS=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:o,metrics:s}=e;this.crypto=i??lge,this.extensions=n,this.metrics=s?Age(s):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=o??new Uint8Array(0)}async secureOutbound(e,t,n){let i=YM(t,{lengthEncoder:Dg,lengthDecoder:J4,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,o),remoteExtensions:o.remoteExtensions,remotePeer:o.remotePeer}}async secureInbound(e,t,n){let i=YM(t,{lengthEncoder:Dg,lengthDecoder:J4,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,o),remotePeer:o.remotePeer,remoteExtensions:o.remoteExtensions}}async performHandshake(e){let t=await _ge(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,t)}async performXXHandshake(e,t){var a,c;let{isInitiator:n,remotePeer:i,connection:o}=e,s=new kS(n,t,this.prologue,this.crypto,this.staticKeys,o,i);try{await s.propose(),await s.exchange(),await s.finish(),(a=this.metrics)==null||a.xxHandshakeSuccesses.increment()}catch(u){if((c=this.metrics)==null||c.xxHandshakeErrors.increment(),u instanceof Error)throw u.message=`Error occurred during XX handshake: ${u.message}`,u}return s}async createSecureConnection(e,t){let[n,i]=T2e(),o=e.unwrap();return await Ne(n,wge(t,this.metrics),o,Xr({lengthDecoder:J4}),bge(t,this.metrics),n),i}};function Tge(r={}){return()=>new NS(r)}var Nqe=et.bind({ignoreUndefined:!0,concatArrays:!0});function n6({options:r={},peerId:e,multiaddrs:t=[],repo:n,keychainConfig:i={},config:o={}}){let{datastore:s}=n,a=Dqe({options:r,config:o,datastore:s,keychainConfig:i,peerId:e,multiaddrs:t});return typeof r.libp2p=="function"?r.libp2p({libp2pOptions:a,options:r,config:o,datastore:s,peerId:e}):(a.start=!1,i1e(a))}function Dqe({options:r,config:e,datastore:t,keychainConfig:n,peerId:i,multiaddrs:o}){var d,p,g,w;let s=()=>{let _=(0,lr.default)(e,"Pubsub.Router")||"gossipsub",x=Wae();if(!x[_])throw(0,Ige.default)(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${_} router.`),"ERR_NOT_SUPPORTED");return x[_]},a={datastore:t,peerId:i},c={addresses:{listen:o.map(_=>_.toString()),announce:(0,lr.default)(r,"addresses.announce",(0,lr.default)(e,"Addresses.Announce",[])),noAnnounce:(0,lr.default)(r,"addresses.noAnnounce",(0,lr.default)(e,"Addresses.NoAnnounce",[]))},connectionManager:(0,lr.default)(r,"connectionManager",{maxConnections:(0,lr.default)(r,"config.Swarm.ConnMgr.HighWater",(0,lr.default)(e,"Swarm.ConnMgr.HighWater")),minConnections:(0,lr.default)(r,"config.Swarm.ConnMgr.LowWater",(0,lr.default)(e,"Swarm.ConnMgr.LowWater"))}),keychain:n,identify:{host:{agentVersion:`js-ipfs/${hp}`}},contentRouters:[],peerRouters:[],peerDiscovery:[],transports:[],streamMuxers:[S2e({maxInboundStreams:256,maxOutboundStreams:1024})],connectionEncryption:[Tge()],relay:{enabled:(0,lr.default)(r,"relay.enabled",(0,lr.default)(e,"relay.enabled",!0)),hop:{enabled:(0,lr.default)(r,"relay.hop.enabled",(0,lr.default)(e,"relay.hop.enabled",!1)),active:(0,lr.default)(r,"relay.hop.active",(0,lr.default)(e,"relay.hop.active",!1))}},nat:{enabled:!(0,lr.default)(e,"Swarm.DisableNatPortMap",!1)}};(0,lr.default)(r,"config.Pubsub.Enabled",(0,lr.default)(e,"Pubsub.Enabled",!0))&&(c.pubsub=s()),(0,lr.default)(e,"Routing.Type","dhtclient")!=="none"&&(c.dht=Q1e({clientMode:(0,lr.default)(e,"Routing.Type","dht")!=="dhtserver",kBucketSize:(0,lr.default)(r,"dht.kBucketSize",20),validators:{ipns:pm},selectors:{ipns:x_}}));let u=(0,lr.default)(r,"config.Bootstrap",(0,lr.default)(e,"Bootstrap",[]));u.length>0&&((d=c.peerDiscovery)==null||d.push(X1e({list:u})));let l=(0,lr.default)(r,"libp2p",void 0);typeof l=="function"&&(l=void 0);let f=Nqe(a,Jfe(),c,l),h=(0,lr.default)(r,"config.Addresses.Delegates",(0,lr.default)(e,"Addresses.Delegates",[]));if(h.length>0){let _=h[Math.floor(Math.random()*h.length)],x=yt(_).toOptions(),m={host:x.host,protocol:parseInt(x.port)===443?"https":"http",port:x.port},y=efe(m);(p=f.contentRouters)==null||p.push(ace(y)),(g=f.peerRouters)==null||g.push(nce(y))}return(0,lr.default)(r,"config.Discovery.MDNS.Enabled",(0,lr.default)(e,"Discovery.MDNS.Enabled",!0))||(f.peerDiscovery=(w=f.peerDiscovery)==null?void 0:w.filter(_=>{try{if(typeof _=="function")return _({})[Symbol.toStringTag]!=="@libp2p/mdns"}catch{}return!0})),f.transports==null&&(f.transports=[]),f.transports.find(_=>{try{if(typeof _=="function")return _({})[Symbol.toStringTag]==="@libp2p/websockets"}catch{}return!1})==null&&f.transports.push(bme()),f}var _U;(function(r){let e;r.codec=()=>(e==null&&(e=kn((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>Pn(t,r.codec()),r.decode=t=>Cn(t,r.codec())})(_U||(_U={}));var Rge=async()=>{let r=await Xb("Ed25519"),e=await Pge(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};var Cge=async r=>{let e=await Xb("RSA",(r==null?void 0:r.bits)??2048),t=await Pge(e);if(t.type==="RSA")return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function Pge(r){return Hn(a3(r.public),HC(r))}var EU=C(ee(),1);var Nge=et.bind({ignoreUndefined:!0}),i6=j("ipfs:components:peer:storage"),Og=class{constructor(e,t,n,i,o){this.print=i,this.peerId=e,this.keychain=t,this.repo=n,this.print=i,this.isNew=o}static async start(e,t,n){let{repoAutoMigrate:i,repo:o,onMigrationProgress:s}=n,a=typeof o=="string"||o==null?kse(e,t,{path:o,autoMigrate:i,onMigrationProgress:s}):o,{peerId:c,keychain:u,isNew:l}=await Oqe(e,a,n);return new Og(c,u,a,e,l)}},Oqe=async(r,e,t)=>{if(!e.closed)return{...await kge(e,t),isNew:!1};try{return await e.open(),{...await kge(e,t),isNew:!1}}catch(n){if(n.code!==Pp)throw n;if(t.init&&t.init.allowNew===!1)throw new Na("Initialization of new repos disabled by config, pass `config.init.isNew: true` to enable it");return{...await Lqe(r,e,t),isNew:!0}}},Lqe=async(r,e,t)=>{let n=t.init||{},i=await e.exists();if(i6("repo exists?",i),i===!0)throw new Error("repo already exists");let o=n.privateKey?await Bqe(n.privateKey):await Mqe(r,n),s=Uqe(o);i6("peer identity: %s",s.PeerID);let a={...Nge(Dge(cl(),n.profiles),t.config),Identity:s};await e.init(a),await e.open(),i6("repo opened");let c={pass:t.pass};try{c.dek=await e.config.get("Keychain.DEK")}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}let u=await n6({options:void 0,multiaddrs:void 0,peerId:o,repo:e,config:a,keychainConfig:c});return await e.datastore.has(new pe("/info/self"))||await u.keychain.importPeer("self",o),await e.config.set("Keychain",{DEK:u.keychain.init.dek}),{peerId:o,keychain:u.keychain}},Bqe=async r=>{if(i6("using user-supplied private-key"),Lf(r))return r;let e=Ie(r,"base64pad"),t=await Li(e);return await Hn(t.public.bytes,t.bytes)},Mqe=(r,{algorithm:e="Ed25519",bits:t=2048})=>{if(r("generating %s keypair...",e),e==="Ed25519")return Rge();if(e==="RSA")return Cge({bits:t});throw(0,EU.default)(new Error("Unknown PeerId algorithm"),"ERR_UNKNOWN_PEER_ID_ALGORITHM")},Uqe=r=>{if(r.privateKey==null)throw(0,EU.default)(new Error("Private key missing"),"ERR_MISSING_PRIVATE_KEY");return{PeerID:r.toString(),PrivKey:re(r.privateKey,"base64pad")}},kge=async(r,e)=>{let t=e.config,n=e.init&&e.init.profiles||[],i=e.pass,o=await r.config.getAll(),s=Fqe(Dge(o,n),t);if(o!==s&&await r.config.replace(s),!s.Identity||!s.Identity.PrivKey)throw new Ku("No private key was found in the config, please intialize the repo");let a=Ie(s.Identity.PrivKey,"base64pad"),c=await Li(a),u=await Hn(c.public.bytes,c.bytes),l=await n6({options:void 0,multiaddrs:void 0,peerId:u,repo:r,config:s,keychainConfig:{pass:i,...s.Keychain}});return{peerId:u,keychain:l.keychain}},Fqe=(r,e)=>e?Nge(r,e):r,Dge=(r,e)=>(e||[]).reduce((t,n)=>{let i=Fm[n];if(!i)throw new Error(`Could not find profile with name '${n}'`);return i6("applying profile %s",n),i.transform(t)},r);var Qge=C(jge(),1);var o6=C(Xo(),1);function Jqe(r){let e=new Uint8Array(r.reduce((n,i)=>n+o6.default.encodingLength(i),0)),t=0;for(let n of r)e=o6.encode(n,e,t),t+=o6.default.encodingLength(n);return e}var Wge=Jqe;var s6=class{constructor(e,t,n){this._refCounter=1,this.cid=e,this.priority=t||1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry `}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var lc=C(gc(),1),Iu=lc.default.Reader,a6=lc.default.Writer,ir=lc.default.util,qt=lc.default.roots["ipfs-bitswap"]||(lc.default.roots["ipfs-bitswap"]={}),Ss=qt.Message=(()=>{function r(e){if(this.blocks=[],this.payload=[],this.blockPresences=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:{o.wantlist=qt.Message.Wantlist.decode(t,t.uint32());break}case 2:{o.blocks&&o.blocks.length||(o.blocks=[]),o.blocks.push(t.bytes());break}case 3:{o.payload&&o.payload.length||(o.payload=[]),o.payload.push(qt.Message.Block.decode(t,t.uint32()));break}case 4:{o.blockPresences&&o.blockPresences.length||(o.blockPresences=[]),o.blockPresences.push(qt.Message.BlockPresence.decode(t,t.uint32()));break}case 5:{o.pendingBytes=t.int32();break}default:t.skipType(s&7);break}}return o},r.fromObject=function(t){if(t instanceof qt.Message)return t;var n=new qt.Message;if(t.wantlist!=null){if(typeof t.wantlist!="object")throw TypeError(".Message.wantlist: object expected");n.wantlist=qt.Message.Wantlist.fromObject(t.wantlist)}if(t.blocks){if(!Array.isArray(t.blocks))throw TypeError(".Message.blocks: array expected");n.blocks=[];for(var i=0;i=0&&(n.blocks[i]=t.blocks[i])}if(t.payload){if(!Array.isArray(t.payload))throw TypeError(".Message.payload: array expected");n.payload=[];for(var i=0;i>>3){case 1:{s.entries&&s.entries.length||(s.entries=[]),s.entries.push(qt.Message.Wantlist.Entry.decode(n,n.uint32()));break}case 2:{s.full=n.bool();break}default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof qt.Message.Wantlist)return n;var i=new qt.Message.Wantlist;if(n.entries){if(!Array.isArray(n.entries))throw TypeError(".Message.Wantlist.entries: array expected");i.entries=[];for(var o=0;o>>3){case 1:{a.block=i.bytes();break}case 2:{a.priority=i.int32();break}case 3:{a.cancel=i.bool();break}case 4:{a.wantType=i.int32();break}case 5:{a.sendDontHave=i.bool();break}default:i.skipType(c&7);break}}return a},t.fromObject=function(i){if(i instanceof qt.Message.Wantlist.Entry)return i;var o=new qt.Message.Wantlist.Entry;switch(i.block!=null&&(typeof i.block=="string"?ir.base64.decode(i.block,o.block=ir.newBuffer(ir.base64.length(i.block)),0):i.block.length>=0&&(o.block=i.block)),i.priority!=null&&(o.priority=i.priority|0),i.cancel!=null&&(o.cancel=!!i.cancel),i.wantType){case"Block":case 0:o.wantType=0;break;case"Have":case 1:o.wantType=1;break}return i.sendDontHave!=null&&(o.sendDontHave=!!i.sendDontHave),o},t.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(o.bytes===String?s.block="":(s.block=[],o.bytes!==Array&&(s.block=ir.newBuffer(s.block))),s.priority=0,s.cancel=!1,s.wantType=o.enums===String?"Block":0,s.sendDontHave=!1),i.block!=null&&i.hasOwnProperty("block")&&(s.block=o.bytes===String?ir.base64.encode(i.block,0,i.block.length):o.bytes===Array?Array.prototype.slice.call(i.block):i.block),i.priority!=null&&i.hasOwnProperty("priority")&&(s.priority=i.priority),i.cancel!=null&&i.hasOwnProperty("cancel")&&(s.cancel=i.cancel),i.wantType!=null&&i.hasOwnProperty("wantType")&&(s.wantType=o.enums===String?qt.Message.Wantlist.WantType[i.wantType]:i.wantType),i.sendDontHave!=null&&i.hasOwnProperty("sendDontHave")&&(s.sendDontHave=i.sendDontHave),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,lc.default.util.toJSONOptions)},t.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/Message.Wantlist.Entry"},t}(),e}(),r.Block=function(){function e(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:{s.prefix=n.bytes();break}case 2:{s.data=n.bytes();break}default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof qt.Message.Block)return n;var i=new qt.Message.Block;return n.prefix!=null&&(typeof n.prefix=="string"?ir.base64.decode(n.prefix,i.prefix=ir.newBuffer(ir.base64.length(n.prefix)),0):n.prefix.length>=0&&(i.prefix=n.prefix)),n.data!=null&&(typeof n.data=="string"?ir.base64.decode(n.data,i.data=ir.newBuffer(ir.base64.length(n.data)),0):n.data.length>=0&&(i.data=n.data)),i},e.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.prefix="":(o.prefix=[],i.bytes!==Array&&(o.prefix=ir.newBuffer(o.prefix))),i.bytes===String?o.data="":(o.data=[],i.bytes!==Array&&(o.data=ir.newBuffer(o.data)))),n.prefix!=null&&n.hasOwnProperty("prefix")&&(o.prefix=i.bytes===String?ir.base64.encode(n.prefix,0,n.prefix.length):i.bytes===Array?Array.prototype.slice.call(n.prefix):n.prefix),n.data!=null&&n.hasOwnProperty("data")&&(o.data=i.bytes===String?ir.base64.encode(n.data,0,n.data.length):i.bytes===Array?Array.prototype.slice.call(n.data):n.data),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,lc.default.util.toJSONOptions)},e.getTypeUrl=function(n){return n===void 0&&(n="type.googleapis.com"),n+"/Message.Block"},e}(),r.BlockPresenceType=function(){let e={},t=Object.create(e);return t[e[0]="Have"]=0,t[e[1]="DontHave"]=1,t}(),r.BlockPresence=function(){function e(t){if(t)for(var n=Object.keys(t),i=0;i>>3){case 1:{s.cid=n.bytes();break}case 2:{s.type=n.int32();break}default:n.skipType(a&7);break}}return s},e.fromObject=function(n){if(n instanceof qt.Message.BlockPresence)return n;var i=new qt.Message.BlockPresence;switch(n.cid!=null&&(typeof n.cid=="string"?ir.base64.decode(n.cid,i.cid=ir.newBuffer(ir.base64.length(n.cid)),0):n.cid.length>=0&&(i.cid=n.cid)),n.type){case"Have":case 0:i.type=0;break;case"DontHave":case 1:i.type=1;break}return i},e.toObject=function(n,i){i||(i={});var o={};return i.defaults&&(i.bytes===String?o.cid="":(o.cid=[],i.bytes!==Array&&(o.cid=ir.newBuffer(o.cid))),o.type=i.enums===String?"Have":0),n.cid!=null&&n.hasOwnProperty("cid")&&(o.cid=i.bytes===String?ir.base64.encode(n.cid,0,n.cid.length):i.bytes===Array?Array.prototype.slice.call(n.cid):n.cid),n.type!=null&&n.hasOwnProperty("type")&&(o.type=i.enums===String?qt.Message.BlockPresenceType[n.type]:n.type),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,lc.default.util.toJSONOptions)},e.getTypeUrl=function(n){return n===void 0&&(n="type.googleapis.com"),n+"/Message.BlockPresence"},e}(),r})();var Yge={Block:Ss.Wantlist.WantType.Block,Have:Ss.Wantlist.WantType.Have},eHe=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),o=r(n);return io?1:0}),fc=class{constructor(e,t){this.set=t?bs({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(tt),o=this.set.get(i);o?(o.inc(),o.priority=t,o.wantType===Yge.Have&&n===Yge.Block&&(o.wantType=n)):(this.set.set(i,new s6(e,t,n)),this._stats&&this._stats.push(null,"wantListSize",1))}remove(e){let t=e.toString(tt),n=this.set.get(t);n&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats&&this._stats.push(null,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){return this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(eHe(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(tt);return this.set.has(t)}get(e){let t=e.toString(tt);return this.set.get(t)}};fc.Entry=s6;var tHe=fc.Entry,ah=class{constructor(e,t,n,i,o){this.entry=new tHe(e,t,n),this.cancel=!!i,this.sendDontHave=!!o}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(tt)} `}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var ba=(r,e)=>{let t=["bitswap"];return e&&t.push(e),r&&t.push(`${r.toString().slice(0,8)}`),ue(t.join(":"))};var DS=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!rr(n,i)||n instanceof ah&&i instanceof ah&&!n.equals(i))return!1}return!0};var fr=class{constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,o){n==null&&(n=fr.WantType.Block);let s=e.toString(tt),a=this.wantlist.get(s);a?(a.wantType===n&&(a.priority=t),i&&(a.cancel=!!i),o&&(a.sendDontHave=!!o),n===fr.WantType.Block&&a.wantType===fr.WantType.Have&&(a.wantType=n)):this.wantlist.set(s,new ah(e,t,n,i,o))}addBlock(e,t){let n=e.toString(tt);this.blocks.set(n,t)}addHave(e){let t=e.toString(tt);this.blockPresences.has(t)||this.blockPresences.set(t,fr.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(tt);this.blockPresences.has(t)||this.blockPresences.set(t,fr.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(tt);this.wantlist.delete(t),this.addEntry(e,0,fr.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),cancel:!!t.cancel})),full:this.full?!0:void 0},blocks:Array.from(this.blocks.values())};return Ss.encode(e).finish()}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:this.full?!0:void 0},blockPresences:[],payload:[],pendingBytes:this.pendingBytes};for(let[t,n]of this.blocks.entries()){let i=ce.parse(t),o=i.version,s=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=Wge([o,s,a,c]);e.payload.push(new Ss.Block({prefix:u,data:n}))}for(let[t,n]of this.blockPresences)e.blockPresences.push(new Ss.BlockPresence({cid:ce.parse(t).bytes,type:n}));return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),Ss.encode(e).finish()}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!DS(this.wantlist,e.wantlist)||!DS(this.blocks,e.blocks)||!DS(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage `}};fr.deserialize=async(r,e)=>{let t=Ss.decode(r),n=t.wantlist&&t.wantlist.full||!1,i=new fr(n);return t.wantlist&&t.wantlist.entries&&t.wantlist.entries.forEach(o=>{if(!o.block)return;let s=ce.decode(o.block);i.addEntry(s,o.priority||0,o.wantType,!!o.cancel,!!o.sendDontHave)}),t.blockPresences&&t.blockPresences.forEach(o=>{if(!o.cid)return;let s=ce.decode(o.cid);o.type===fr.BlockPresenceType.Have?i.addHave(s):i.addDontHave(s)}),t.blocks.length>0?(await Promise.all(t.blocks.map(async o=>{let s=await mr.digest(o),a=ce.createV0(s);i.addBlock(a,o)})),i):(t.payload.length>0&&(await Promise.all(t.payload.map(async o=>{if(!o.prefix||!o.data)return;let s=(0,Qge.default)(o.prefix),a=s[0],c=s[1],u=s[2],l=u===mr.code?mr:e&&await e.getHasher(u);if(!l)throw new We("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await l.digest(o.data),h=ce.create(a,c,f);i.addBlock(h,o.data)})),i.setPendingBytes(t.pendingBytes)),i)};fr.blockPresenceSize=r=>r.bytes.length+1;fr.Entry=ah;fr.WantType={Block:Ss.Wantlist.WantType.Block,Have:Ss.Wantlist.WantType.Have};fr.BlockPresenceType={Have:Ss.BlockPresenceType.Have,DontHave:Ss.BlockPresenceType.DontHave};var Xge=Math.pow(2,31)-1,Zge=1e3,Jge=1;var eye=rHe;function rHe(r,e,t){var n=null,i=null,o=function(){n&&(clearTimeout(n),i=null,n=null)},s=function(){var c=i;o(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,u=arguments,l=t&&!n;if(o(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var f=i;return i=null,f()}},e),l)return i()};return a.cancel=o,a.flush=s,a}var OS=class{constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=ba(e,"msgqueue"),this.sendEntries=eye(this._sendEntries.bind(this),Jge)}addMessage(e){e.empty||this.send(e)}addEntries(e){this._entries=this._entries.concat(e),this.sendEntries()}_sendEntries(){if(!this._entries.length)return;let e=new fr(!1);this._entries.forEach(t=>{t.cancel?e.cancel(t.cid):e.addEntry(t.cid,t.priority)}),this._entries=[],this.addMessage(e)}async send(e){try{await this.network.connectTo(this.peerId)}catch(t){this._log.error("cant connect to peer %s: %s",this.peerId.toString(),t.message);return}this._log("sending message to peer %s",this.peerId.toString()),this.network.sendMessage(this.peerId,e).catch(t=>{this._log.error("send error: %s",t.message)})}};var LS=class{constructor(e,t,n,i){this.peers=bs({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new fc(n,i),this.network=t,this._stats=n,this._peerId=e,this._log=ba(e,"want")}_addEntries(e,t,n){let i=e.map((o,s)=>new fr.Entry(o,Xge-s,fr.WantType.Block,t));i.forEach(o=>{o.cancel?n?this.wantlist.removeForce(o.cid.toString(tt)):this.wantlist.remove(o.cid):(this._log("adding to wl"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t){t.refcnt++;return}t=new OS(this._peerId,e,this.network);let n=new fr(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1),t&&t.signal&&t.signal.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>this.disconnected(e.peerId))}};var tye=()=>{},SU=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??tye,this.onDisconnect=e.onDisconnect??tye}get[Symbol.toStringTag](){return W9.toString()}get[W9](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function rye(r){return new SU(r)}var nye=C(Kn(),1);var AU="/ipfs/bitswap/1.0.0",TU="/ipfs/bitswap/1.1.0",IU="/ipfs/bitswap/1.2.0",iHe=32,oHe=128,sHe=3e4,BS=class{constructor(e,t,n,i={}){this._log=ba(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[AU],i.b100Only||(this._protocols.unshift(TU),this._protocols.unshift(IU)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader,this._maxInboundStreams=i.maxInboundStreams??iHe,this._maxOutboundStreams=i.maxOutboundStreams??oHe,this._incomingStreamTimeout=i.incomingStreamTimeout??sHe}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=rye({onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect});this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(t.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let e of this._registrarIds)this._libp2p.unregister(e);this._registrarIds=[]}}_onConnection({stream:e,connection:t}){if(!this._running)return;let n=new nye.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",e.stat.protocol,t.remotePeer),await Ne(sa(e.source,n.signal),Xr(),async i=>{for await(let o of i){try{let s=await fr.deserialize(o.subarray(),this._hashLoader);await this._bitswap._receiveMessage(t.remotePeer,s)}catch(s){this._bitswap._receiveError(s);break}n.reset()}})}).catch(i=>{this._log(i),e.abort(i)}).finally(()=>{n.clear(),e.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){let n=[],i=0;for await(let o of this.findProviders(e,t))if(this._log(`connecting to provider ${o.id}`),n.push(this.connectTo(o.id,t).catch(s=>{this._log.error(s)})),i++,i===3)break;await Promise.all(n)}async provide(e,t){await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t){if(!this._running)throw new Error("network isn't running");let n=e.toString();this._log("sendMessage to %s",n,t);let o=await(await this._libp2p.dial(e)).newStream([IU,TU,AU]);await aHe(o,t,this._log),this._updateSentStats(e,t.blocks)}async connectTo(e,t){if(!this._running)throw new Error("network isn't running");return this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}};async function aHe(r,e,t){try{let n;switch(r.stat.protocol){case AU:n=e.serializeToBitswap100();break;case TU:case IU:n=e.serializeToBitswap110();break;default:throw new Error("Unknown protocol: "+r.stat.protocol)}await Ne([n],vn(),r)}catch(n){t(n)}finally{r.close()}}var MS=class{constructor(e){this.partner=e,this.wantlist=new fc,this.exchangeCount=0,this.sentToPeer=new Map,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var c6=class extends Map{constructor(e,t){super(),this._cmp=t||this._defaultSort,this._keys=[];for(let[n,i]of e||[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n>>1,o=this._kCmp(this._keys[i],e);if(o<0)t=i+1;else if(o>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t){if(e)for(let n of this._keys)e.apply(t,[[n,this.get(n)]])}_defaultSort(e,t){return e[0]t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let o=0;oe+t.task.size,0)}get(e){return(this._tasks.get(e)||{}).task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(!n)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var iye={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var oye=fr.WantType,uHe=16*1024,lHe=1024,zS=class{constructor(e,t,n,i,o,s={}){this._log=ba(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(s),this.ledgerMap=bs({name:"ipfs_bitswap_ledger_map",metrics:o.metrics}),this._running=!1,this._requestQueue=new US(iye)}_processOpts(e){return{maxSizeReplaceHasWithBlock:lHe,targetMessageSize:uHe,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks()})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new fr(!1);i.setPendingBytes(n);let o=[],s=new Map;for(let c of t){let u=ce.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(o.push(u),s.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(o);for(let[c,u]of s){let l=ce.parse(c),f=a.get(c);f?i.addBlock(l,f):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e&&this.messageSent(e,ce.parse(c),u)}catch(c){this._log.error(c)}e&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n?{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}:null}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length){for(let t of this.ledgerMap.values())for(let n of e){let i=t.wantlistContains(n.cid);if(!i)continue;let o=n.data.length,s=this._sendAsBlock(i.wantType,o),a=o;s||(a=fr.blockPresenceSize(i.cid)),this._requestQueue.pushTasks(t.partner,[{topic:i.cid.toString(tt),priority:i.priority,size:a,data:{blockSize:o,isWantBlock:s,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new fc),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],o=[];t.wantlist.forEach(s=>{s.cancel?(n.cancelWant(s.cid),i.push(s.cid)):(n.wants(s.cid,s.priority,s.wantType),o.push(s))}),this._cancelWants(e,i),await this._addWants(e,o),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(tt),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(o=>o.cid)),i=[];for(let o of t){let s=o.cid.toString(tt),a=n.get(s);if(a==null)o.sendDontHave&&i.push({topic:s,priority:o.priority,size:fr.blockPresenceSize(o.cid),data:{isWantBlock:o.wantType===oye.Block,blockSize:0,haveBlock:!1,sendDontHave:o.sendDontHave}});else{let c=this._sendAsBlock(o.wantType,a),u=a;c||(u=fr.blockPresenceSize(o.cid)),i.push({topic:s,priority:o.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:o.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===oye.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(tt),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n)return n;let i=new MS(e);return this.ledgerMap.set(t,i),this._stats&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var cye=C(xi(),1);var sye=r=>`unwant:${Ee(r.multihash.bytes,"base64")}`,aye=r=>`block:${Ee(r.multihash.bytes,"base64")}`,VS=class extends cye.EventEmitter{constructor(e){super(),this.setMaxListeners(Zge),this._log=ba(e,"notif")}hasBlock(e,t){let n=aye(e);this._log(n),this.emit(n,t)}wantBlock(e,t={}){if(!e)throw new Error("Not a valid cid");let n=aye(e),i=sye(e);return this._log(`wantBlock:${e}`),new Promise((o,s)=>{let a=()=>{this.removeListener(n,c),s(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),o(u)};this.once(i,a),this.once(n,c),t&&t.signal&&t.signal.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),s(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=sye(e);this._log(t),this.emit(t)}};var pye=C(xi(),1);var dye=C(xi(),1),CU=C(fye(),1),u6=class extends dye.EventEmitter{constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,CU.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._disabled=!0}stop(){this._timeout&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=null,this._queue.length){let e;for(;this._queue.length;){let t=e=this._queue.shift();t&&this._applyOp(t)}e&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]||0;this._frequencyAccumulators[e]=0;let o=i/t*1e3,s=this._movingAverages[e];s||(s=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=s[a];c||(c=s[a]=(0,CU.default)(a)),c.push(n,o)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]||(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var hye={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},KS=class extends pye.EventEmitter{constructor(e,t=[],n=hye){super();let i=Object.assign({},hye,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new u6(t,i),this._global.on("update",o=>this.emit("update",o)),this._peers=bs({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=typeof e!="string"&&e.toString?e.toString():`${e}`;return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e)){let i=this._peers.get(e);i||(i=new u6(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n&&(n.stop(),this._peers.delete(t))}};var mye=C(Da(),1);var dHe={statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},hHe=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],$S=class extends uu{constructor(e,t,n={}){super(),this._libp2p=e,this._log=ba(this.peerId),this._options=Object.assign({},dHe,n),this._stats=new KS(e,hHe,{enabled:this._options.statsEnabled,computeThrottleTimeout:this._options.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:this._options.statsComputeThrottleMaxQueueSize}),this.network=new BS(e,this,this._stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new zS(this.peerId,t,this.network,this._stats,e),this.wm=new LS(this.peerId,this.network,this._stats,e),this.notifications=new VS(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,o]of t.blocks.entries()){let s=ce.parse(i);n.push({wasWanted:this.wm.wantlist.contains(s),cid:s,data:o})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(({cid:i,wasWanted:o,data:s})=>this._handleReceivedBlock(e,i,s,o)))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let o=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,o),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this._stats.push(e,"blocksReceived",1),this._stats.push(e,"dataReceived",n.length),i&&(this._stats.push(e,"dupBlksReceived",1),this._stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError: %s",e.message)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this._stats.disconnected(e)}enableStats(){this._stats.enable()}disableStats(){this._stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async get(e,t={}){let n=(c,u)=>(this.wm.wantBlocks([c],u),this.notifications.wantBlock(c,u)),i=!1,o=async(c,u)=>{try{return await this.blockstore.get(c,u)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return i||(i=!0,this.network.findAndConnect(c,u).catch(f=>this._log.error(f))),n(c,u)}},s=new AbortController,a=t.signal?(0,mye.anySignal)([t.signal,s.signal]):s.signal;try{return await Promise.race([this.notifications.wantBlock(e,{signal:a}),o(e,{signal:a})])}finally{s.abort()}}async*getMany(e,t={}){for await(let n of e)yield this.get(n,t)}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>this.notifications.unwantBlock(n))}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this._sendHaveBlockNotifications(e,t)}async*putMany(e,t){for await(let{key:n,value:i}of this.blockstore.putMany(e,t))this._sendHaveBlockNotifications(n,i),yield{key:n,value:i}}_sendHaveBlockNotifications(e,t){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,data:t}]),this.network.provide(e).catch(n=>{this._log.error("Failed to provide: %s",n.message)})}getWantlist(){return this.wm.wantlist.entries()}peers(){return this.engine.peers()}stat(){return this._stats}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this._stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}unwrap(){return this.blockstore}has(e){return this.blockstore.has(e)}};var gye=(r,e,t={})=>new $S(r,e,t);var wye=C(ee(),1);var qS={};xe(qS,{abortedError:()=>pHe,notFoundError:()=>yye});var PU=C(ee(),1);function yye(r){return r=r||new Error("Not Found"),(0,PU.default)(r,"ERR_NOT_FOUND")}function pHe(r){return r=r||new Error("Aborted"),(0,PU.default)(r,"ERR_ABORTED")}var wur={...qS};var HS=class extends uu{constructor(e,t){super(),this.child=e,this.bitswap=t}open(){return this.child.open()}close(){return this.child.close()}unwrap(){return this.child}async put(e,t,n={}){await this.has(e)||(this.bitswap.isStarted()?await this.bitswap.put(e,t,n):await this.child.put(e,t,n))}async*putMany(e,t={}){let n=M3(e,async({key:i})=>!await this.has(i));this.bitswap.isStarted()?yield*this.bitswap.putMany(n,t):yield*this.child.putMany(n,t)}async get(e,t={}){return!await this.has(e)&&this.bitswap.isStarted()?this.bitswap.get(e,t):this.child.get(e,t)}async*getMany(e,t={}){let n=Ao({objectMode:!0}),i=Ao({objectMode:!0});Promise.resolve().then(async()=>{for await(let o of e)!await this.has(o)&&this.bitswap.isStarted()?n.push(o):i.push(o);n.end(),i.end()}),yield*ga(this.bitswap.getMany(n,t),this.child.getMany(i,t))}async delete(e,t){await this.child.delete(e,t)}async*deleteMany(e,t){yield*this.child.deleteMany(e,t)}async has(e,t={}){return this.child.has(e,t)}async*query(e,t={}){yield*this.child.query(e,t)}async*queryKeys(e,t={}){yield*this.child.queryKeys(e,t)}};var Lg=class{constructor(e,t,n,i,o){this.peerId=e,this.libp2p=t,this.bitswap=n,this.repo=i,this.blockstore=o}static async start({peerId:e,repo:t,print:n,hashers:i,options:o}){t.closed&&await t.open();let s=await t.config.getAll(),a=await n6({options:o,repo:t,peerId:e,multiaddrs:mHe(e,s),config:s,keychainConfig:void 0});await a.start();for(let l of a.getMultiaddrs())n(`Swarm listening on ${l.toString()}`);let c=gye(a,t.blocks,{statsEnabled:!0,hashLoader:i,maxInboundStreams:1024,maxOutboundStreams:1024});await c.start();let u=new HS(t.blocks,c);return t.blocks=u,t.pins.blockstore=u,new Lg(e,a,c,t,u)}static async stop(e){e.repo.blocks=e.blockstore.unwrap(),e.repo.pins.blockstore=e.blockstore.unwrap(),await e.bitswap.stop(),await e.libp2p.stop()}},mHe=(r,e)=>{let t=r.toString(),n=[],i=e.Addresses&&e.Addresses.Swarm||[];for(let o of i){let s=yt(o);if(s.protoCodes().includes(gHe))throw(0,wye.default)(new Error("websocket-star swarm addresses are not supported. See https://github.com/ipfs/js-ipfs/issues/2779"),"ERR_WEBSOCKET_STAR_SWARM_ADDR_NOT_SUPPORTED");let a=s.getPeerId();a&&a!==t&&(s=s.encapsulate(`/p2p/${t}`)),n.push(s)}return n},gHe=479;function bye({network:r}){async function e(t={}){let n=[],{libp2p:i}=await r.use(t);return await i.peerStore.forEach(o=>{n.push({id:o.id,addrs:o.addresses.map(s=>s.multiaddr)})}),n}return $(e)}function _ye({network:r}){async function e(t,n={}){let{libp2p:i}=await r.use(n);await i.dial(t,n)}return $(e)}function Eye({network:r}){async function e(t,n={}){let{libp2p:i}=await r.use(n);await i.hangUp(t)}return $(e)}function vye({network:r}){async function e(t={}){let{libp2p:n}=await r.use(t);return n.getMultiaddrs()}return $(e)}function xye({network:r}){async function e(t={}){let{libp2p:n}=await r.use(t);if(t.verbose){let o=[];for(let s of n.getConnections()){let a={addr:s.remoteAddr,peer:s.remotePeer};(t.verbose||t.direction)&&(a.direction=s.stat.direction),t.verbose&&(a.muxer=s.stat.multiplexer,a.latency="n/a",a.streams=[]),o.push(a)}return o}let i=new Map;for(let o of n.getConnections()){let s={addr:o.remoteAddr,peer:o.remotePeer};i.set(o.remotePeer.toString(),s)}return Array.from(i.values())}return $(e)}var GS=class{constructor({network:e}){this.addrs=bye({network:e}),this.connect=_ye({network:e}),this.disconnect=Eye({network:e}),this.localAddrs=vye({network:e}),this.peers=xye({network:e})}};var l6={success:!0,time:0,text:""};function Sye({network:r}){async function*e(t,n={}){let{libp2p:i}=await r.use();n.count=n.count||10;let o=await i.peerStore.get(t),s=o&&o.id;if(!s){yield{...l6,text:`Looking up peer ${t}`};let u=await i.peerRouting.findPeer(t);s=u&&u.id}if(!s)throw new Error("Peer was not found");yield{...l6,text:`PING ${s.toString()}`};let a=0,c=0;for(let u=0;u{let n=await r.use(t);if(n.libp2p.dht!=null)return n;{let i=async function*(){yield{from:e,name:"QUERY_ERROR",type:3,error:new Na("dht not enabled")}};return{libp2p:{dht:{get:i,put:i,findProviders:i,findPeer:i,provide:i,getClosestPeers:i}}}}};var Iye=C(ee(),1);var Rye=C(v_(),1);function Cye({network:r,config:e}){let t=(0,Rye.default)(e||{},"Pubsub.Enabled",!0),n={},i;return{subscribe:t?$(o):f6,unsubscribe:t?$(s):f6,publish:t?$(a):f6,ls:t?$(c):f6,peers:t?$(u):f6};async function o(l,f,h={}){let{libp2p:d}=await r.use(h);d.pubsub.subscribe(l),i==null&&(i=p=>{let g=p.detail;n[g.topic]&&n[g.topic].forEach(w=>{if(typeof w=="function"){w(g);return}w!=null&&w.handleEvent!=null&&w.handleEvent(g)})},d.pubsub.addEventListener("message",i)),f!=null&&(n[l]==null&&(n[l]=[]),n[l].push(f))}async function s(l,f,h={}){let{libp2p:d}=await r.use(h);f!=null&&n[l]!=null&&(n[l]=n[l].filter(p=>p!==f),n[l].length===0&&delete n[l]),typeof f!="function"&&delete n[l],n[l]==null&&d.pubsub.unsubscribe(l),Object.keys(n).length===0&&(d.pubsub.removeEventListener("message",i),i=void 0)}async function a(l,f,h={}){let{libp2p:d}=await r.use(h);if(!f)throw(0,Iye.default)(new Error('argument "data" is required'),"ERR_ARG_REQUIRED");await d.pubsub.publish(l,f)}async function c(l={}){let{libp2p:f}=await r.use(l);return f.pubsub.getTopics()}async function u(l,f={}){let{libp2p:h}=await r.use(f);return h.pubsub.getSubscribers(l)}}var f6=async()=>{throw new Na("pubsub not enabled")};var yHe=et.bind({ignoreUndefined:!0}),ch=j("ipfs"),wHe=3e4,NU=class{constructor({print:e,storage:t,codecs:n,options:i}){let{peerId:o,repo:s,keychain:a}=t,c=Pi.create(Lg),u=rre(i.preload),l=pG(),f=mG({network:c}),h=new R_(i),d=Object.values(v8);(i.ipld&&i.ipld.hashers?i.ipld.hashers:[]).forEach(G=>d.push(G)),this.hashers=new V2({hashers:d,loadHasher:i.ipld&&i.ipld.loadHasher});let p=Object.values(Vu);(i.ipld&&i.ipld.bases?i.ipld.bases:[]).forEach(G=>p.push(G)),this.bases=new F2({bases:p,loadBase:i.ipld&&i.ipld.loadBase});let g=new ab({repo:s,codecs:n}),w=new $_({codecs:n,hashers:this.hashers,preload:u,repo:s}),_=new k_({dns:l,ipns:h,repo:s,codecs:n,peerId:o,isOnline:f,keychain:a,options:i}),x=wG({repo:s,codecs:n,bases:this.bases,name:_}),m=new HE({repo:s,codecs:n,hashers:this.hashers,preload:u}),y=Object.assign(bX({repo:s,codecs:n,resolve:x,preload:u}),{local:_X({repo:t.repo})}),{add:b,addAll:E,cat:v,get:S,ls:A}=new BE({preload:u,repo:s,options:i.EXPERIMENTAL,hashers:this.hashers}),I=Gre({repo:s,preload:u,hashers:this.hashers,options:i}),k=nre({files:I,preload:u,options:i.preload});this.preload=u,this.name=_,this.ipns=h,this.pin=g,this.resolve=x,this.block=w,this.refs=y,this.start=DH({network:c,peerId:o,repo:s,preload:u,ipns:h,mfsPreload:k,print:e,keychain:a,hashers:this.hashers,options:i}),this.stop=OH({network:c,preload:u,mfsPreload:k,ipns:h,repo:s}),this.dht=Tye({network:c,repo:s,peerId:o}),this.pubsub=Cye({network:c,config:i.config}),this.dns=l,this.isOnline=f,this.id=Ste({network:c,peerId:o}),this.version=xte({repo:s}),this.bitswap=new D_({network:c}),this.bootstrap=new z_({repo:s}),this.config=Tte({repo:s}),this.ping=Sye({network:c}),this.add=b,this.addAll=E,this.cat=v,this.get=S,this.ls=A,this.dag=m,this.files=I,this.key=new c7({keychain:a}),this.object=new l7({preload:u,codecs:n,repo:s}),this.repo=new d7({repo:s,hashers:this.hashers}),this.stats=new h7({repo:s,network:c}),this.swarm=new GS({network:c}),Object.defineProperty(this,"libp2p",{get(){let G=c.try();return G?G.libp2p:void 0}});let N=()=>Promise.reject((0,jS.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")),O=async function*(){throw(0,jS.default)(new Error("Not implemented"),"ERR_NOT_IMPLEMENTED")};this.commands=N,this.diag={cmds:N,net:N,sys:N},this.log={level:N,ls:N,tail:O},this.mount=N,this.codecs=n}async init(){throw new ka}},bHe=async r=>{let e=pt({Data:new st({type:"directory"}).marshal(),Links:[]}),t=await r.block.put(e,{mhtype:"sha2-256",format:"dag-pb"});return await r.pin.add(t),t},_He=()=>({start:!0,EXPERIMENTAL:{},preload:{enabled:!Pye.isTest,addresses:["/dns4/node0.preload.ipfs.io/https","/dns4/node1.preload.ipfs.io/https","/dns4/node2.preload.ipfs.io/https","/dns4/node3.preload.ipfs.io/https"]}});async function Nye(r={}){r=yHe(_He(),r);let e=r.init||{},t={name:Ii.name,code:Ii.code,encode:u=>u,decode:u=>u},n=Object.values(x8);[sr,o1,a1,yy,t].concat(r.ipld&&r.ipld.codecs||[]).forEach(u=>n.push(u));let i=new z2({codecs:n,loadCodec:r.ipld&&r.ipld.loadCodec}),o=r.silent?ch:console.log;ch("creating repo");let s=await Og.start(o,i,r);ch("getting repo config");let a=await s.repo.config.getAll(),c=new NU({storage:s,print:o,codecs:i,options:{...r,config:a}});if(ch("starting preload"),await c.preload.start(),ch("starting storage"),c.ipns.startOffline(s),s.isNew&&!e.emptyRepo){let u=await bHe(c);if(ch("adding default assets"),await(c.addAll,void 0),ch("initializing IPNS keyspace"),s.peerId.publicKey==null)throw(0,jS.default)(new Error("Public key missing"),"ERR_MISSING_PUBLIC_KEY");let l=new kye.TimeoutController(wHe);try{await c.ipns.initializeKeyspace(s.peerId,Ie(`/ipfs/${u}`),{signal:l.signal})}finally{l.clear()}}return r.start!==!1&&(ch("starting node"),await c.start()),c}var EHe=C(dL(),1),Dye=Nye;var Oye=(()=>({toString:function(r){return r.toV1().toString()},fromString:function(r){return z.parse(r)}}))();var WS=(()=>{let r;return{init:async()=>{r||(r=await Dye({repo:String(Math.random()+Date.now())}))},store:async function(e,t){await this.init();let n={path:e,content:t},i=await r.add(n),{cid:o}=i;return Oye.toString(o)},retrieve:async function(e){await this.init();let t=new TextDecoder,n="";for await(let i of r.cat(e))n+=t.decode(i,{stream:!0});return n}}})();var vHe=()=>{let r=Le.get("gistId");return Le.get("authToken")?r?"Sync: Notes with my GitHub Gist":"Sync: Pick your Gist to sync with":"Sync: Authorize your GitHub account for synchronisation"},xHe={title:"Share note",icon:Sr(wA,"share note"),sortTitle:"Share",call:qF},SHe={title:"Share public link",key:null,icon:Sr(wA,"share public link"),sortTitle:"Share public link",call:async()=>{Ct.hide(),await Kg(X(".terminal").getValue());let r=hn(),t=(await KU({note:r})).history[0].url,n=await fetch(t).then(l=>l.json()),{files:i}=n,o=Object.values(i),[s]=o,{raw_url:a}=s,c=`${ht.baseUrl}?raw=${a}`;Nu(c,"MiroPad public link copied to clipboard \u{1F4CB}!")}},DU=()=>[{title:"New note",icon:Sr(KF,"new note"),sortTitle:"New",key:"n",call:E6},{title:"Save",key:"s",icon:Sr(TF,"save"),sortTitle:"Save",call:async()=>{Ct.hide(),await Kg(X(".terminal").getValue());let r=hn(),{disableSync:e=!1}=r;e||tA([r]),Pu()}},...navigator.share?[xHe]:[],{title:"Toggle MarkDown Viewer",icon:Sr(LF,"toggle markdown viewer","rotate90"),sortTitle:"Split",key:"m",call:()=>{nf.toggle(),Ct.hide()}},{title:"Full MarkDown view",icon:Sr(BF,"full view"),sortTitle:"Full view",key:"shift m",call:()=>{nf.toggle("full"),Ct.hide()}},{title:"Save to IPFS",key:"i",icon:Sr(zF,"save"),sortTitle:"save->ipfs",call:async()=>{Ct.hide(),await Kg(X(".terminal").getValue());let r=hn(),{disableSync:e=!1}=r;if(e||tA([r]),r){let t=await WS.store(r.title,r.text);Nu(`${ht.baseUrl}#?cid=${t}`)}}},...uF()?[SHe]:[],{title:"Zen mode",icon:Sr($F,"zen mode"),sortTitle:"Zen mode",key:"shift z",call:()=>{!!ht.getSearchParam("zen")?ht.deleteParam("zen"):ht.set(void 0,{zen:!0}),Ct.hide()}},{title:"List saved notes",icon:Sr(AF,"list notes"),sortTitle:"Notes",key:"p",call:()=>Ct.toggle(Ct.getModes().notes)},{title:"Delete note",key:"shift d",icon:Sr(qg,"delete note"),sortTitle:"Delete",call:v6},{title:vHe(),icon:Sr(IF,"sync with github"),key:null,call:async()=>{let r=Le.get("authToken");if(!r)return await hF();if(!Le.get("gistId"))return await pF(r);Ct.hide(),await $g()}},{title:"Sync: Reset Gist settings",icon:Sr(RF,"reset github settings"),key:null,call:async()=>{localStorage.removeItem("authToken"),localStorage.removeItem("gistId"),localStorage.removeItem("lastLocalUpdate"),localStorage.removeItem("lastSync"),ze.info("Gist setting have been reset!"),Ct.hide()}},{title:"Toggle sidebar",experimental:!0,key:"shift l",call:()=>{X("aside").toggle()}},{title:"Save to File System...",experimental:!0,icon:Sr(CF,"save file"),key:"shift s",call:async()=>{let{text:r,title:e}=hn();gF(r,e),Ct.hide()}},{title:"Email note to...",experimental:!0,icon:Sr(kF,"email"),key:"e",call:()=>{let r=document.querySelector(".terminal").value;vF(r),Ct.hide()}},{title:"Toggle experimental features",experimental:!1,icon:Sr(NF,"lab"),key:null,call:()=>{let r=!!Le.get("__experimental__");r?Le.remove("__experimental__"):Le.set("__experimental__",!0),ze.showNotification(`Experimental features turned ${r?"off":"on"}`),Ct.hide()}},{title:"Toggle Autocompletion",experimental:!1,icon:Sr(MF,"autocompletion"),key:null,call:()=>{let r=!!Le.get("__autocomplete__");r?Le.remove("__autocomplete__"):Le.set("__autocomplete__",!0),ze.showNotification(`Autocomplete feature turned ${r?"off":"on"}`),Ct.hide(),X(".terminal").focus()}},{title:"Add a cover picture",experimental:!0,icon:Sr(DF,"cover picture"),key:null,call:async()=>{let r=prompt("Paste the image URL in here...");Ct.hide(),await SF(200),Nu(`
`,"\u{1F44C}Copied! Paste the code on the MiroPad editor"),X(".terminal").focus(),ze.info("Paste the cover picture wherever you prefer on the MirPad editor")}},{title:"Print MarkDown output",experimental:!0,icon:Sr(OF,"print"),key:null,call:()=>{X(".preview").show(),nf.init(),window.print(),Ct.hide()}},{key:"j",title:"Prettify JSON document",icon:Sr(UF,"prettify json"),call:()=>{xF(".terminal"),Ct.hide()}},{title:"Toggle command palette",icon:Sr(FF,"toggle command palette"),key:["shift p","k"],call:()=>Ct.toggle(Ct.getModes().commands)},{title:"Find and Replace...",experimental:!0,icon:Sr(VF,"find and replace"),key:"shift f",call:()=>{let r=X(".terminal").getValue().slice(X(".terminal").el.selectionStart,X(".terminal").el.selectionEnd),e=prompt("What do you wanna find?",r);if(!e)return ze.info("Value not found");let t=X(".terminal").getValue().indexOf(e);X(".terminal").el.setSelectionRange(t,t+e.length);let n=prompt(`Replace ${e} with...`);n&&X(".terminal").el.setRangeText(n)}},{title:"Download all notes!",icon:Sr(PF,"Download all notes on your local file system"),call:()=>{let r=Ru({includeDeleted:!0});yF(r),Ct.hide()}},{title:"Permanently delete ALL notes \u2757",icon:Sr(qg,"delete note"),call:()=>{confirm("Are you sure you want do delete ALL your notes?")&&(Ru({includeDeleted:!0}).forEach(t=>{Le.remove(t.id)}),E6()),Ct.hide()}}];var AHe={events:[],on(r,e){return Array.isArray(r)?(r.forEach(t=>{let n=t.key||t,i=t.call||e;this.on(n,i)}),this):(r&&typeof r=="string"&&e&&typeof e=="function"&&(this.events=[...this.events,{key:r.includes("shift")?r.replace("shift","").trim():r,shift:r.includes("shift"),fn(){e()}}]),this)},listen(){return document.addEventListener("keydown",r=>{this.handleEvent(r)}),this},handleEvent(r){this.events.map(e=>(e.key===r.key&&(r.ctrlKey===!0||r.metaKey===!0)&&r.shiftKey===e.shift&&(r.preventDefault(),e.fn()),!0))}},Lye=AHe;var Bye=(r,e)=>{let t=document.createElement("a");return t.href=e,t.appendChild(D0(r)?r:document.createTextNode(r)),t};var OU=(r,e=new Date)=>{let t=new Date(r).getFullYear(),n=new Date(e).getFullYear();return t===n},Fye=(r,e=new Date)=>{let t=new Date(r).getMonth(),n=new Date(e).getMonth();return t===n},THe=(r,e=new Date)=>{let t=new Date(r).getDate(),n=new Date(e).getDate();return t===n},Mye=(r,e=new Date)=>OU(r,e)&&Fye(r,e)&&THe(r,e),IHe=["January","February","March","April","May","June","July","August","September","October","November","December"],RHe=IHe.map(r=>r.slice(0,3)),Uye=(r=new Date)=>{let e=new Date(r),t=new Date().getDate()-1;return Fye(e)&&OU(e)&&e.getDate()===t},d6=r=>{let e=new Date(r),t=Uye(r)?"":RHe[e.getMonth()],n=OU(e)?"":e.getFullYear(),i=Uye(e)?"Yesterday":e.getDate();return`${Mye(e)?"":`${i} ${t} ${n}`} ${Mye(e)?e.toLocaleTimeString():""}`};var zye=r=>r.reduce((t,n)=>{if(t.length===0)return[n];let i=Math.max(...t);return[...t,...n>=i?[n]:[]]},[]).length===r.length;var LU=(r,e)=>{let t=r.split(" ").map(o=>o.toLowerCase()),i=e.split(" ").map(o=>o.toLowerCase()).map(o=>t.map((c,u)=>c.includes(o)?u:-1).reduce((c,u)=>u>-1?u:c,-1));return i.includes(-1)?!1:zye(i)};var Vye=async()=>{if(!Le.get("__notification-permission__")){let r=await window.Notification.requestPermission();Le.set("__notification-permission__",r)}},Kye=async()=>{"serviceWorker"in navigator&&navigator.serviceWorker.register(`${window.location.pathname}service-worker.js?v=2.15.16`)};var $ye=r=>Array.isArray(r)?r.map(e=>$ye(e)).join(", "):r?`\u2318+${r.toUpperCase()}`:"",CHe=(()=>{let r={off:"off",notes:"notes",revisions:"revisions",commands:"commands",gists:"gists"},e={input:"",mode:r.off,options:{selected:0,length:0}};return{getState:function(){return e},getModes:function(){return r},setState:function(t){return e={...e,...t},e},show:function(t=r.commands){switch(X("#commander").show(),X("#commander input").focus(),t){case r.commands:this.generateCommands(),X("#commander input").setValue("> "),this.setState({mode:r.commands});break;case r.notes:this.generateNotes(),X("#commander input").setValue(""),this.setState({mode:r.notes});break;case r.revisions:this.generateRevisions(),X("#commander input").setValue(""),this.setState({mode:r.revisions});break;default:break}return this},hide:function(){return X("#commander").hide(),e.mode=r.off,this},toggle:function(t){return Vye(),e.mode===r.off||e.mode!==t?this.show(t):this.hide(),this},commands:function(){return DU()},selectOption:function(t,n){let i=e.options.selected,o=e.options.length-1,u=n==="down"?i===o?0:i+1:i===0?o:i-1;e.options={...e.options,selected:u}},initCommander:function(){return DU().slice(0,5).map(t=>{X(".mobile-dock").append(A6([t.icon,document.createTextNode(t.sortTitle)],t.call,t.title.toLowerCase().replace(/\s/g,"-")))}),X("#commander button").listen("click",()=>{this.hide()}),X("#commander input").listen("keydown",t=>{t.keyCode===40&&(e.mode===r.revisions&&X("#commands li.selected").click(),this.selectOption(t,"down")),t.keyCode===38&&(e.mode===r.revisions&&X("#commands li.selected").click(),this.selectOption(t,"up"))}).listen("keyup",t=>{t.keyCode===13&&(e.mode===r.commands?X("#commands li.selected div").click():X("#commands li.selected a").click()),t.keyCode===27&&X(".terminal").focus(),e.input!==t.target.value&&(e.options.selected=0),e.input=t.target.value,this.generateOptions(t.target.value)}),this},init:function(){return this.initCommander(),Lye.listen().on(this.commands()),X(".menu").listen("click",()=>this.toggle()),X("#revisions").listen("click",()=>this.generateRevisions()),this},generateRevisions:function(){this.show(),e.mode=r.revisions;let{revisions:t}=hn(),n=e.options.selected,i=Object.keys(t).sort((o,s)=>{let{dateCreated:a}=t[o],{dateCreated:c}=t[s];return c-a}).map((o,s)=>({title:ku({content:`...${o.slice(-10)}`}),secondary:`${d6(t[o].dateCreated)}`,onclick:()=>{ht.set(void 0,{v:o}),e.options.selected=s,this.generateRevisions()}})).map((o,s)=>rf(o,s===n));return X("#commands").html(i),e.options={...e.options,length:i.length},this},generateOptions:function(t){switch(e.mode){case r.commands:case r.notes:t.slice(0,1)===">"?(e.mode=r.commands,this.generateCommands(t.slice(1).trim()),X("#commander input").placeholder("Search for commands...")):(e.mode=r.notes,this.generateNotes(t));return;case r.revisions:return this.generateRevisions();case r.off:break;default:break}},generateNotes:function(t=""){let n=e.options.selected,i=Ru().filter(({title:o})=>LU(o,t)).filter(({id:o,deleted:s})=>!s&&o!==ht.getPageId()).sort((o,s)=>{let a=b6(o.title);return b6(s.title)-a}).map(({id:o,title:s,cid:a},c)=>{let u=b6(s),l=a?`?cid=${a}`:"",f=`${window.location.origin}${window.location.pathname}#${o}${l}`,h=Bye(ku({content:s,highlight:t}),f);return rf({title:h,secondary:d6(u),onclick:()=>{this.hide(),X(".terminal").focus()}},c===n)});return X("#commands").html(i),X("#commander input").placeholder(`Search from ${i.length} saved notes...`),e.options={...e.options,length:i.length},this},generateCommands:async function(t=""){let n=e.options.selected,i=this.commands().filter(({title:o})=>LU(o,t)).filter(({experimental:o=!1})=>Le.get("__experimental__")?!0:!o).map(({title:o,key:s,call:a,icon:c},u)=>rf({title:ku({content:o,highlight:t}),icon:c,secondary:$ye(s),onclick:a},u===n));return X("#commands").html(i),e.options={...e.options,length:i.length},this}}})(),Ct=CHe;var jye=C(qye());var Hye=(r,e)=>r.split(` `).reduce((i,o)=>{let{isFound:s}=i;if(s)return i;let a=`${i.text}${o} `,c=a.length;return e>=c?{text:a,isFound:!1}:{text:o,isFound:!0}},{text:"",isFound:!1}).text;var Gye=r=>{let e=Hye(r.target.value,r.target.selectionEnd),t={"* [":` * [] `,"* ":` * `," * [":` * [] `," * ":` - * `};for(let[n,i]of Object.entries(t))if(e.startsWith(n)){r.preventDefault(),X(".terminal").insertAtCaret(i);break}};var PHe=(r,e)=>r[e]===void 0||r[e].trim()==="",kHe=r=>{let e=(0,jye.default)(r,r.selectionEnd),{top:t,left:n}=e,i=X(".terminal").el.scrollHeight,o=X("main").el;o.style.height=`${i}px`,X(".suggestion").el.style.top=`${t}px`,X(".suggestion").el.style.left=`${n}px`},NHe=(r,e)=>{let t="",n=e-1;do{let i=r[n]||"";n=i.trim()===""?-1:n-1,t=i.trim()!==""?`${i}${t}`:t}while(n>=0);return t},DHe=r=>{let e=r.replace(/[\r\n\t]+/g,"").toLowerCase();return QS.getMatchingWords(e)},xr=(()=>{let r={matches:[],currentWord:null,prediction:null,options:{selected:0,length:0}},e=r;return{el:X(".terminal"),setState:function(t){return e={...e,...t},e},resetState:function(){xr.setState(r)},selectOption:function(t,n){let i=e.options.selected,o=e.options.length-1,u=n==="down"?i===o?0:i+1:i===0?o:i-1;e.options={...e.options,selected:u},xr.setState({prediction:e.matches[e.options.selected]}),xr.renderInlineSuggestion(),xr.renderOptions()},acceptCompletion:t=>{let n=(s,a)=>{let c=s.replace(a.toLowerCase(),"");c?X(".terminal").insertAtCaret(`${c} `):X(".terminal").insertAtCaret(" "),X(".suggestion").hide(),xr.resetState()},{prediction:i,currentWord:o}=e;if(t)return n(t,o);i&&(n(i,o),QS.insert(i))},renderInlineSuggestion:()=>{let{prediction:t,currentWord:n}=e,i=ku({content:`${t.slice(n.length)}`});i.setAttribute("id","inlineSuggestion"),X(".suggestion").show().html(i)},renderOptions:()=>{let t=X(".suggestion .options");t&&t.el&&t.el.remove();let n=e.options.selected,i=e.matches.map((s,a)=>rf({title:ku({content:s}),secondary:Sr(qg,"delete word"),onSecondaryClick:()=>{Fe.removeFromDictionary(s),xr.setState({matches:e.matches.filter(c=>c!==s)}),xr.renderOptions()},onclick:()=>{xr.acceptCompletion(s)}},a===n)),o=document.createElement("ul");o.classList.add("options"),o.classList.add("frost"),i.forEach(s=>o.append(s)),X(".suggestion").el.append(o)},onFocus:()=>{Ct.hide(),X(".note-info").hide()},onInput:t=>{if(!!!Fe.get("__autocomplete__"))return;let i=t.target.selectionEnd,o=xr.el.getValue(),s=o[i-1];if(t.inputType==="deleteContentBackward"||s===" ")return xr.setState({prediction:r.prediction,currentWord:r.currentWord}),X(".suggestion").hide();if(t.inputType==="insertText"&&PHe(o,i)){kHe(t.target);let c=NHe(o,i),u=DHe(c),[l]=u,f=l||"";xr.setState({prediction:f,currentWord:c,matches:u.slice(0,10),options:{selected:0,length:u.length}}),e.currentWord.length>1&&e.prediction?(xr.renderInlineSuggestion(),xr.renderOptions()):X(".suggestion").hide()}},onArrowDown:t=>{e.matches.length>0&&(t.preventDefault(),xr.selectOption(t,"down"))},onArrowUp:t=>{e.matches.length>0&&(t.preventDefault(),xr.selectOption(t,"up"))},setValue:()=>{},onEnter:t=>{e.matches.length>0&&(t.preventDefault(),xr.acceptCompletion()),Gye(t)},onEscape:()=>{xr.resetState(),X(".suggestion").hide()},onTab:t=>{t.preventDefault(),xr.acceptCompletion()},onKeyDown:t=>{t.keyCode===13&&xr.onEnter(t),t.keyCode===40&&xr.onArrowDown(t),t.keyCode===38&&xr.onArrowUp(t),t.keyCode===9&&xr.onTab(t),t.keyCode===32&&xr.setState({prediction:""}),t.keyCode===27&&xr.onEscape(t)},onKeyUp:t=>{let n=hn(),i=U0(t.target.value);X(".title h3").html(i);let{text:o=""}=n||{},s=n&&xr.el.getValue()===o;Pu(s)},onPaste:async()=>{var n;let t=await navigator.clipboard.read();for(let i of t){let o=(n=i.types)==null?void 0:n.filter(s=>s.startsWith("image/"));for(let s of o){let a=await i.getType(s),c=Fe.get("MIROPAD_SECRET_TOKEN");if(c){let[u,l]=s.split("/"),f=`${k1()}.${l}`;X("#logo").addClass("loading");try{let{url:h}=await fetch(`${dc.file_service.api}?fileName=${f}`,{method:"POST",headers:{"x-secret-token":c,accept:"application/json","content-type":"application/octet-stream"},body:a}).then(yA).then(d=>d.json());X(".terminal").insertAtCaret(`![image](${h})`)}catch(h){ze.error(`Uploading file failed \u{1F4A5}! Error$ ${h.message}`)}X("#logo").removeClass("loading")}else{let u=URL.createObjectURL(a);X(".terminal").insertAtCaret(`![image](${u})`)}nf.update()}}},init:function(){this.el.listen("focus",this.onFocus).listen("input",this.onInput).listen("keydown",this.onKeyDown).listen("keyup",this.onKeyUp).listen("paste",this.onPaste)}}})();var Wye=()=>{let{authToken:r,gistId:e}=Fe.get(["authToken","gistId"]);return!!(r&&e)};var OHe=r=>Object.entries(r).reduce((e,[t,n])=>{let i=e[n]||[];return{...e,[n]:[t,...i]}},{}),Yye=()=>({char:null,children:{},frequency:0,hasChildren:function(){return Object.keys(this.children).length>0},isWord:function(){return this.frequency>0},contains:function(r){return Object.keys(this.children).includes(r)},getWords:function(r,e={}){let t=this;if(t.isWord()&&(e={...e,[r]:this.frequency}),t.hasChildren())for(let n of Object.values(t.children))e=n.getWords(`${r}${n.char}`,e);return e},increaseFrequency:function(){this.frequency=this.frequency+1},insert:function(r){let[e,...t]=r;if(e){let n=t.length===0;if(this.contains(e)){let i=this.children[e];return i.char=e,n&&i.increaseFrequency(),i.insert(t)}else return this.insertNode(e,n).insert(t)}},insertNode:function(r,e=!1){let t=Yye();return e&&t.increaseFrequency(),t.char=r,this.children={...this.children,[r]:t},t}}),Qye=()=>{let r=Yye();return{insert:function(e=[]){return(Array.isArray(e)?e:[e]).forEach(n=>r.insert(n)),this},search:function(e=""){let t=r;return e.split("").forEach(n=>{t&&(t=t.children[n])}),t?t.getWords(e):{}},getMatchingWords:function(e=""){let t=OHe(this.search(e));return Object.keys(t).sort((n,i)=>parseInt(i,10)-parseInt(n,10)).flatMap(n=>t[n].sort())}}};var LHe=r=>{let{message:e="Unexpected error occurred!"}=r;ze.error(e)},Xye=LHe;var Zye=async r=>{X(".anchor").show(),X("#logo").addClass("loading");let e=await WS.retrieve(r);X("#logo").removeClass("loading"),Pu(!1),X(".terminal").setValue(e)};var BHe=async r=>{if(r){let e=await fetch(r).then(t=>{if(t.ok)return t.text();throw new Error(`Remote note could not be retrieved! code: ${t.status}`)});X(".terminal").setValue(e)}},MHe=async r=>{if(r)try{let e=await p6(r),{files:t}=e,n=Object.values(t),[i]=n,{content:o}=i;X(".terminal").setValue(o)}catch{ze.error("MiroPad note not found! \u{1F937}\u200D\u2642\uFE0F")}},BU=async(r={})=>{try{let{oldURL:i,newURL:o}=r,s=ht.getPageId(i),a=ht.getPageId(o),c=s!==a,{v:u}=ht.getParamsObject(i),{v:l}=ht.getParamsObject(o);[c,u!==l].some(g=>g)&&_6();let{gistId:d,raw:p}=ht.getParamsObject(o);await MHe(d),await BHe(p)}catch(i){ze.error(i.message)}let e=!ht.getPageId();X("#note-info-button").show(!e),X("#new-note").disable(e),ht.getSearchParam("md")==="full"?X(".terminal").hide():X(".terminal").show(),ht.getSearchParam("zen")==="true"?X(".header").hide():X(".header").show(),ht.getSearchParam("cid")?await Zye(ht.getSearchParam("cid")):X(".anchor").hide(),X(".note-info").hide();let t=ht.getSearchParam("q"),n=cF(t);n&&X(".terminal").setValue(n.text)};var UHe=()=>"production"==="development",Jye=()=>{UHe()&&new EventSource("/esbuild").addEventListener("change",()=>location.reload())};var e3e=()=>{X(".task-list-item").listenAll("click",r=>{r.firstChild.checked=!r.firstChild.checked})};var QS=Qye(),FHe=()=>{X("#note-info-close").listen("click",()=>{X(".note-info").hide()}),X("#note-info-button").listen("click",()=>{let r=hn();if(X(".note-info").show(),X(".note-info .details").innerHTML(`

+ * `};for(let[n,i]of Object.entries(t))if(e.startsWith(n)){r.preventDefault(),X(".terminal").insertAtCaret(i);break}};var PHe=(r,e)=>r[e]===void 0||r[e].trim()==="",kHe=r=>{let e=(0,jye.default)(r,r.selectionEnd),{top:t,left:n}=e,i=X(".terminal").el.scrollHeight,o=X("main").el;o.style.height=`${i}px`,X(".suggestion").el.style.top=`${t}px`,X(".suggestion").el.style.left=`${n}px`},NHe=(r,e)=>{let t="",n=e-1;do{let i=r[n]||"";n=i.trim()===""?-1:n-1,t=i.trim()!==""?`${i}${t}`:t}while(n>=0);return t},DHe=r=>{let e=r.replace(/[\r\n\t]+/g,"").toLowerCase();return QS.getMatchingWords(e)},xr=(()=>{let r={matches:[],currentWord:null,prediction:null,options:{selected:0,length:0}},e=r;return{el:X(".terminal"),setState:function(t){return e={...e,...t},e},resetState:function(){xr.setState(r)},selectOption:function(t,n){let i=e.options.selected,o=e.options.length-1,u=n==="down"?i===o?0:i+1:i===0?o:i-1;e.options={...e.options,selected:u},xr.setState({prediction:e.matches[e.options.selected]}),xr.renderInlineSuggestion(),xr.renderOptions()},acceptCompletion:t=>{let n=(s,a)=>{let c=s.replace(a.toLowerCase(),"");c?X(".terminal").insertAtCaret(`${c} `):X(".terminal").insertAtCaret(" "),X(".suggestion").hide(),xr.resetState()},{prediction:i,currentWord:o}=e;if(t)return n(t,o);i&&(n(i,o),QS.insert(i))},renderInlineSuggestion:()=>{let{prediction:t,currentWord:n}=e,i=ku({content:`${t.slice(n.length)}`});i.setAttribute("id","inlineSuggestion"),X(".suggestion").show().html(i)},renderOptions:()=>{let t=X(".suggestion .options");t&&t.el&&t.el.remove();let n=e.options.selected,i=e.matches.map((s,a)=>rf({title:ku({content:s}),secondary:Sr(qg,"delete word"),onSecondaryClick:()=>{Le.removeFromDictionary(s),xr.setState({matches:e.matches.filter(c=>c!==s)}),xr.renderOptions()},onclick:()=>{xr.acceptCompletion(s)}},a===n)),o=document.createElement("ul");o.classList.add("options"),o.classList.add("frost"),i.forEach(s=>o.append(s)),X(".suggestion").el.append(o)},onFocus:()=>{Ct.hide(),X(".note-info").hide()},onInput:t=>{if(!!!Le.get("__autocomplete__"))return;let i=t.target.selectionEnd,o=xr.el.getValue(),s=o[i-1];if(t.inputType==="deleteContentBackward"||s===" ")return xr.setState({prediction:r.prediction,currentWord:r.currentWord}),X(".suggestion").hide();if(t.inputType==="insertText"&&PHe(o,i)){kHe(t.target);let c=NHe(o,i),u=DHe(c),[l]=u,f=l||"";xr.setState({prediction:f,currentWord:c,matches:u.slice(0,10),options:{selected:0,length:u.length}}),e.currentWord.length>1&&e.prediction?(xr.renderInlineSuggestion(),xr.renderOptions()):X(".suggestion").hide()}},onArrowDown:t=>{e.matches.length>0&&(t.preventDefault(),xr.selectOption(t,"down"))},onArrowUp:t=>{e.matches.length>0&&(t.preventDefault(),xr.selectOption(t,"up"))},setValue:()=>{},onEnter:t=>{e.matches.length>0&&(t.preventDefault(),xr.acceptCompletion()),Gye(t)},onEscape:()=>{xr.resetState(),X(".suggestion").hide()},onTab:t=>{t.preventDefault(),xr.acceptCompletion()},onKeyDown:t=>{t.keyCode===13&&xr.onEnter(t),t.keyCode===40&&xr.onArrowDown(t),t.keyCode===38&&xr.onArrowUp(t),t.keyCode===9&&xr.onTab(t),t.keyCode===32&&xr.setState({prediction:""}),t.keyCode===27&&xr.onEscape(t)},onKeyUp:t=>{let n=hn(),i=U0(t.target.value);X(".title h3").html(i);let{text:o=""}=n||{},s=n&&xr.el.getValue()===o;Pu(s)},onPaste:async()=>{var n;let t=await navigator.clipboard.read();for(let i of t){let o=(n=i.types)==null?void 0:n.filter(s=>s.startsWith("image/"));for(let s of o){let a=await i.getType(s),c=Le.get("MIROPAD_SECRET_TOKEN");if(c){let[u,l]=s.split("/"),f=`${k1()}.${l}`;X("#logo").addClass("loading");try{let{url:h}=await fetch(`${dc.file_service.api}?fileName=${f}`,{method:"POST",headers:{"x-secret-token":c,accept:"application/json","content-type":"application/octet-stream"},body:a}).then(yA).then(d=>d.json());X(".terminal").insertAtCaret(`![image](${h})`)}catch(h){ze.error(`Uploading file failed \u{1F4A5}! Error$ ${h.message}`)}X("#logo").removeClass("loading")}else{let u=URL.createObjectURL(a);X(".terminal").insertAtCaret(`![image](${u})`)}nf.update()}}},init:function(){this.el.listen("focus",this.onFocus).listen("input",this.onInput).listen("keydown",this.onKeyDown).listen("keyup",this.onKeyUp).listen("paste",this.onPaste)}}})();var Wye=()=>{let{authToken:r,gistId:e}=Le.get(["authToken","gistId"]);return!!(r&&e)};var OHe=r=>Object.entries(r).reduce((e,[t,n])=>{let i=e[n]||[];return{...e,[n]:[t,...i]}},{}),Yye=()=>({char:null,children:{},frequency:0,hasChildren:function(){return Object.keys(this.children).length>0},isWord:function(){return this.frequency>0},contains:function(r){return Object.keys(this.children).includes(r)},getWords:function(r,e={}){let t=this;if(t.isWord()&&(e={...e,[r]:this.frequency}),t.hasChildren())for(let n of Object.values(t.children))e=n.getWords(`${r}${n.char}`,e);return e},increaseFrequency:function(){this.frequency=this.frequency+1},insert:function(r){let[e,...t]=r;if(e){let n=t.length===0;if(this.contains(e)){let i=this.children[e];return i.char=e,n&&i.increaseFrequency(),i.insert(t)}else return this.insertNode(e,n).insert(t)}},insertNode:function(r,e=!1){let t=Yye();return e&&t.increaseFrequency(),t.char=r,this.children={...this.children,[r]:t},t}}),Qye=()=>{let r=Yye();return{insert:function(e=[]){return(Array.isArray(e)?e:[e]).forEach(n=>r.insert(n)),this},search:function(e=""){let t=r;return e.split("").forEach(n=>{t&&(t=t.children[n])}),t?t.getWords(e):{}},getMatchingWords:function(e=""){let t=OHe(this.search(e));return Object.keys(t).sort((n,i)=>parseInt(i,10)-parseInt(n,10)).flatMap(n=>t[n].sort())}}};var LHe=r=>{let{message:e="Unexpected error occurred!"}=r;ze.error(e)},Xye=LHe;var Zye=async r=>{X(".anchor").show(),X("#logo").addClass("loading");let e=await WS.retrieve(r);X("#logo").removeClass("loading"),Pu(!1),X(".terminal").setValue(e)};var BHe=async r=>{if(r){let e=await fetch(r).then(t=>{if(t.ok)return t.text();throw new Error(`Remote note could not be retrieved! code: ${t.status}`)});X(".terminal").setValue(e)}},MHe=async r=>{if(r)try{let e=await p6(r),{files:t}=e,n=Object.values(t),[i]=n,{content:o}=i;X(".terminal").setValue(o)}catch{ze.error("MiroPad note not found! \u{1F937}\u200D\u2642\uFE0F")}},BU=async(r={})=>{try{let{oldURL:i,newURL:o}=r,s=ht.getPageId(i),a=ht.getPageId(o),c=s!==a,{v:u}=ht.getParamsObject(i),{v:l}=ht.getParamsObject(o);[c,u!==l].some(g=>g)&&_6();let{gistId:d,raw:p}=ht.getParamsObject(o);await MHe(d),await BHe(p)}catch(i){ze.error(i.message)}let e=!ht.getPageId();X("#note-info-button").show(!e),X("#new-note").disable(e),ht.getSearchParam("md")==="full"?X(".terminal").hide():X(".terminal").show(),ht.getSearchParam("zen")==="true"?X(".header").hide():X(".header").show(),ht.getSearchParam("cid")?await Zye(ht.getSearchParam("cid")):X(".anchor").hide(),X(".note-info").hide();let t=ht.getSearchParam("q"),n=cF(t);n&&X(".terminal").setValue(n.text)};var UHe=()=>"production"==="development",Jye=()=>{UHe()&&new EventSource("/esbuild").addEventListener("change",()=>location.reload())};var e3e=()=>{X(".task-list-item").listenAll("click",r=>{r.firstChild.checked=!r.firstChild.checked})};var QS=Qye(),FHe=()=>{X("#note-info-close").listen("click",()=>{X(".note-info").hide()}),X("#note-info-button").listen("click",()=>{let r=hn();if(X(".note-info").show(),X(".note-info .details").innerHTML(`

@@ -287,7 +287,7 @@ Use Chrome, Firefox or Internet Explorer 11`)}var BVe=a1e().Buffer,Cx=globalThis Delete - `,n})();X(".note-info .details").append(t),X("#delete-note").listen("click",()=>{v6()})})},zHe=async()=>{let r=Fe.getDictionary();QS.insert(r),window.addEventListener("error",Xye),MU(),Ct.init(),FHe(),xr.init(),w6(),_6(ht.getPageId()),X(".logo").listen("click",()=>{Ct.toggle(Ct.getModes().notes)}),X("#permalink").listen("click",async()=>{await Nu(ht.get())}),nf.init(),window.addEventListener("hashchange",BU),BU(),Kye(),e3e(),await $g(),await mF(),Jye()},t3e=zHe;t3e();})(); + `,n})();X(".note-info .details").append(t),X("#delete-note").listen("click",()=>{v6()})})},zHe=async()=>{let r=Le.getDictionary();QS.insert(r),window.addEventListener("error",Xye),MU(),Ct.init(),FHe(),xr.init(),w6(),_6(ht.getPageId()),X(".logo").listen("click",()=>{Ct.toggle(Ct.getModes().notes)}),X("#permalink").listen("click",async()=>{await Nu(ht.get())}),nf.init(),window.addEventListener("hashchange",BU),BU(),Kye(),e3e(),await $g(),await mF(),Jye()},t3e=zHe;t3e();})(); /*! Bundled license information: showdown/dist/showdown.js: diff --git a/out/index.js.map b/out/index.js.map index ebe5ee6..8dde4ea 100644 --- a/out/index.js.map +++ b/out/index.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/options.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/showdown.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/helpers.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/converter.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/anchors.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/autoLinks.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/blockGamut.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/blockQuotes.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/codeBlocks.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/codeSpans.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/completeHTMLDocument.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/detab.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/ellipsis.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/emoji.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/encodeAmpsAndAngles.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/encodeBackslashEscapes.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/encodeCode.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/escapeSpecialCharsWithinTagAttributes.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/githubCodeBlocks.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/hashBlock.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/hashCodeTags.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/hashElement.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/hashHTMLBlocks.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/hashHTMLSpans.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/hashPreCodeTags.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/headers.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/horizontalRule.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/images.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/italicsAndBold.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/lists.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/metadata.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/outdent.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/paragraphs.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/runExtension.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/spanGamut.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/strikethrough.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/stripLinkDefinitions.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/tables.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/underline.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/unescapeSpecialChars.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/blockquote.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/codeBlock.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/codeSpan.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/emphasis.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/header.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/hr.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/image.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/links.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/list.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/listItem.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/node.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/paragraph.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/pre.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/strikethrough.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/strong.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/table.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/tableCell.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/subParsers/makeMarkdown/txt.js", "../node_modules/.pnpm/showdown@2.1.0/node_modules/showdown/src/loader.js", "../node_modules/.pnpm/is-plain-obj@2.1.0/node_modules/is-plain-obj/index.js", "../node_modules/.pnpm/merge-options@3.0.4/node_modules/merge-options/index.js", "../node_modules/.pnpm/is-electron@2.2.2/node_modules/is-electron/index.js", "../node_modules/.pnpm/ipfs-utils@9.0.14_encoding@0.1.13/node_modules/ipfs-utils/src/env.js", "../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../node_modules/.pnpm/debug@4.3.7/node_modules/debug/src/common.js", "../node_modules/.pnpm/debug@4.3.7/node_modules/debug/src/browser.js", "../node_modules/.pnpm/err-code@3.0.1/node_modules/err-code/index.js", "../node_modules/.pnpm/@protobufjs+aspromise@1.1.2/node_modules/@protobufjs/aspromise/index.js", "../node_modules/.pnpm/@protobufjs+base64@1.1.2/node_modules/@protobufjs/base64/index.js", "../node_modules/.pnpm/@protobufjs+eventemitter@1.1.0/node_modules/@protobufjs/eventemitter/index.js", "../node_modules/.pnpm/@protobufjs+float@1.0.2/node_modules/@protobufjs/float/index.js", "../node_modules/.pnpm/@protobufjs+inquire@1.1.0/node_modules/@protobufjs/inquire/index.js", "../node_modules/.pnpm/@protobufjs+utf8@1.1.0/node_modules/@protobufjs/utf8/index.js", "../node_modules/.pnpm/@protobufjs+pool@1.1.0/node_modules/@protobufjs/pool/index.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/util/longbits.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/util/minimal.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/writer.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/writer_buffer.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/reader.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/reader_buffer.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/rpc/service.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/rpc.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/roots.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/src/index-minimal.js", "../node_modules/.pnpm/protobufjs@7.2.2/node_modules/protobufjs/minimal.js", "../node_modules/.pnpm/retimer@3.0.0/node_modules/retimer/time-browser.js", "../node_modules/.pnpm/retimer@3.0.0/node_modules/retimer/retimer.js", "../node_modules/.pnpm/timeout-abort-controller@3.0.0/node_modules/timeout-abort-controller/index.js", "../node_modules/.pnpm/iso-url@1.2.1/node_modules/iso-url/src/url-browser.js", "../node_modules/.pnpm/iso-url@1.2.1/node_modules/iso-url/src/relative.js", "../node_modules/.pnpm/iso-url@1.2.1/node_modules/iso-url/index.js", "../node_modules/.pnpm/any-signal@3.0.1/node_modules/any-signal/index.js", "../node_modules/.pnpm/hashlru@2.3.0/node_modules/hashlru/index.js", "../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js", "../node_modules/.pnpm/ipfs-utils@9.0.14_encoding@0.1.13/node_modules/ipfs-utils/src/http/error.js", "../node_modules/.pnpm/node-fetch@2.7.0_encoding@0.1.13/node_modules/node-fetch/browser.js", "../node_modules/.pnpm/native-fetch@3.0.0_node-fetch@2.7.0_encoding@0.1.13_/node_modules/native-fetch/src/index.js", "../node_modules/.pnpm/ipfs-utils@9.0.14_encoding@0.1.13/node_modules/ipfs-utils/src/fetch.browser.js", "../node_modules/.pnpm/ipfs-utils@9.0.14_encoding@0.1.13/node_modules/ipfs-utils/src/http/fetch.browser.js", "../node_modules/.pnpm/browser-readablestream-to-it@1.0.3/node_modules/browser-readablestream-to-it/index.js", "../node_modules/.pnpm/it-all@1.0.6/node_modules/it-all/index.js", "../node_modules/.pnpm/ipfs-utils@9.0.14_encoding@0.1.13/node_modules/ipfs-utils/src/http.js", "../node_modules/.pnpm/timestamp-nano@1.0.1/node_modules/timestamp-nano/dist/timestamp.min.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/forge.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/baseN.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/util.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/oids.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/asn1.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/cipher.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/cipherModes.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/aes.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/des.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/md.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/hmac.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pbkdf2.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pem.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha256.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/prng.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/random.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/rc2.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/jsbn.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha1.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs1.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/prime.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/rsa.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pbe.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/sha512.js", "../node_modules/.pnpm/protobufjs@7.4.0/node_modules/protobufjs/src/util/longbits.js", "../node_modules/.pnpm/protobufjs@7.4.0/node_modules/protobufjs/src/util/minimal.js", "../node_modules/.pnpm/protobufjs@7.4.0/node_modules/protobufjs/src/reader.js", "../node_modules/.pnpm/protobufjs@7.4.0/node_modules/protobufjs/src/reader_buffer.js", "../node_modules/.pnpm/protobufjs@7.4.0/node_modules/protobufjs/src/writer.js", "../node_modules/.pnpm/protobufjs@7.4.0/node_modules/protobufjs/src/writer_buffer.js", "../node_modules/.pnpm/ms@2.1.2/node_modules/ms/index.js", "../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/common.js", "../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/browser.js", "../node_modules/.pnpm/dlv@1.1.3/node_modules/dlv/index.js", "../node_modules/.pnpm/is-domain-name@1.0.1/node_modules/is-domain-name/index.js", "../node_modules/.pnpm/varint@6.0.0/node_modules/varint/encode.js", "../node_modules/.pnpm/varint@6.0.0/node_modules/varint/decode.js", "../node_modules/.pnpm/varint@6.0.0/node_modules/varint/length.js", "../node_modules/.pnpm/varint@6.0.0/node_modules/varint/index.js", "../node_modules/.pnpm/murmurhash3js-revisited@3.0.0/node_modules/murmurhash3js-revisited/lib/murmurHash3js.js", "../node_modules/.pnpm/murmurhash3js-revisited@3.0.0/node_modules/murmurhash3js-revisited/index.js", "../node_modules/.pnpm/rabin-wasm@0.1.5_encoding@0.1.13/node_modules/rabin-wasm/src/rabin.js", "../node_modules/.pnpm/@assemblyscript+loader@0.9.4/node_modules/@assemblyscript/loader/index.js", "../node_modules/.pnpm/rabin-wasm@0.1.5_encoding@0.1.13/node_modules/rabin-wasm/dist/rabin-wasm.js", "../node_modules/.pnpm/rabin-wasm@0.1.5_encoding@0.1.13/node_modules/rabin-wasm/src/index.js", "../node_modules/.pnpm/sparse-array@1.3.2/node_modules/sparse-array/index.js", "../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js", "../node_modules/.pnpm/iso-constants@0.1.2/node_modules/iso-constants/index.browser.js", "../node_modules/.pnpm/fnv1a@1.1.1/node_modules/fnv1a/index.js", "../node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js", "../node_modules/.pnpm/level-supports@4.0.1/node_modules/level-supports/index.js", "../node_modules/.pnpm/module-error@1.0.2/node_modules/module-error/index.js", "../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js", "../node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js", "../node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js", "../node_modules/.pnpm/level-transcoder@1.0.1/node_modules/level-transcoder/lib/text-endec.js", "../node_modules/.pnpm/level-transcoder@1.0.1/node_modules/level-transcoder/lib/encoding.js", "../node_modules/.pnpm/level-transcoder@1.0.1/node_modules/level-transcoder/lib/formats.js", "../node_modules/.pnpm/level-transcoder@1.0.1/node_modules/level-transcoder/lib/encodings.js", "../node_modules/.pnpm/level-transcoder@1.0.1/node_modules/level-transcoder/index.js", "../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js", "../node_modules/.pnpm/catering@2.1.1/node_modules/catering/next-tick-browser.js", "../node_modules/.pnpm/catering@2.1.1/node_modules/catering/index.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/common.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/abstract-iterator.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/default-kv-iterator.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/deferred-iterator.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/abstract-chained-batch.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/default-chained-batch.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/range-options.js", "../node_modules/.pnpm/queue-microtask@1.2.3/node_modules/queue-microtask/index.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/next-tick-browser.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/abstract-sublevel-iterator.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/lib/abstract-sublevel.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/abstract-level.js", "../node_modules/.pnpm/abstract-level@1.0.3/node_modules/abstract-level/index.js", "../node_modules/.pnpm/run-parallel-limit@1.1.0/node_modules/run-parallel-limit/index.js", "../node_modules/.pnpm/browser-level@1.0.1/node_modules/browser-level/util/key-range.js", "../node_modules/.pnpm/browser-level@1.0.1/node_modules/browser-level/util/deserialize.js", "../node_modules/.pnpm/browser-level@1.0.1/node_modules/browser-level/iterator.js", "../node_modules/.pnpm/browser-level@1.0.1/node_modules/browser-level/util/clear.js", "../node_modules/.pnpm/browser-level@1.0.1/node_modules/browser-level/index.js", "../node_modules/.pnpm/level@8.0.0/node_modules/level/browser.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/util/longbits.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/util/minimal.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/writer.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/writer_buffer.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/reader.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/reader_buffer.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/rpc/service.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/rpc.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/roots.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/src/index-minimal.js", "../node_modules/.pnpm/protobufjs@6.11.4/node_modules/protobufjs/minimal.js", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/dist/src/message/rpc.cjs", "../node_modules/.pnpm/denque@1.5.1/node_modules/denque/index.js", "../node_modules/.pnpm/stream-to-it@0.2.4/node_modules/stream-to-it/source.js", "../node_modules/.pnpm/ipfs-utils@9.0.14_encoding@0.1.13/node_modules/ipfs-utils/src/files/url-source.js", "../node_modules/.pnpm/iso-random-stream@2.0.2/node_modules/iso-random-stream/src/random.browser.js", "../node_modules/.pnpm/delay@5.0.0/node_modules/delay/index.js", "../node_modules/.pnpm/set-delayed-interval@1.0.0/node_modules/set-delayed-interval/src/index.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterAbstract.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/BlockedKeys.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/index.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterRes.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterStoreAbstract.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterRedis.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterMongo.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterMySQL.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterPostgres.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/Record.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/MemoryStorage.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterMemory.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterCluster.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterMemcache.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RLWrapperBlackAndWhite.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterUnion.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterQueueError.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/RateLimiterQueue.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/lib/BurstyRateLimiter.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.1/node_modules/rate-limiter-flexible/index.js", "../node_modules/.pnpm/netmask@2.0.2/node_modules/netmask/lib/netmask.js", "../node_modules/.pnpm/ipaddr.js@2.0.1/node_modules/ipaddr.js/lib/ipaddr.js", "../node_modules/.pnpm/truncate-utf8-bytes@1.0.2/node_modules/truncate-utf8-bytes/lib/truncate.js", "../node_modules/.pnpm/utf8-byte-length@1.0.4/node_modules/utf8-byte-length/browser.js", "../node_modules/.pnpm/truncate-utf8-bytes@1.0.2/node_modules/truncate-utf8-bytes/browser.js", "../node_modules/.pnpm/sanitize-filename@1.6.3/node_modules/sanitize-filename/index.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs7asn1.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/mgf1.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/mgf.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pss.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/x509.js", "../node_modules/.pnpm/node-forge@1.3.1/node_modules/node-forge/lib/pkcs7.js", "../node_modules/.pnpm/receptacle@1.3.2/node_modules/receptacle/index.js", "../node_modules/.pnpm/fast-fifo@1.1.0/node_modules/fast-fifo/fixed-size.js", "../node_modules/.pnpm/fast-fifo@1.1.0/node_modules/fast-fifo/index.js", "../node_modules/.pnpm/p-defer@3.0.0/node_modules/p-defer/index.js", "../node_modules/.pnpm/p-fifo@1.0.0/node_modules/p-fifo/index.js", "../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js", "../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/browser.js", "../node_modules/.pnpm/k-bucket@5.1.0/node_modules/k-bucket/index.js", "../node_modules/.pnpm/ipaddr.js@2.2.0/node_modules/ipaddr.js/lib/ipaddr.js", "../node_modules/.pnpm/event-iterator@2.0.0/node_modules/event-iterator/lib/event-iterator.js", "../node_modules/.pnpm/event-iterator@2.0.0/node_modules/event-iterator/lib/dom.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterAbstract.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/BlockedKeys.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/index.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterRes.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterStoreAbstract.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterRedis.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterMongo.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterMySQL.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterPostgres.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/Record.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/MemoryStorage.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterMemory.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterCluster.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterMemcache.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RLWrapperBlackAndWhite.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterUnion.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/component/RateLimiterQueueError.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/RateLimiterQueue.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/lib/BurstyRateLimiter.js", "../node_modules/.pnpm/rate-limiter-flexible@2.4.2/node_modules/rate-limiter-flexible/index.js", "../node_modules/.pnpm/@stablelib+hash@1.0.1/node_modules/@stablelib/hash/hash.ts", "../node_modules/.pnpm/@stablelib+constant-time@1.0.1/node_modules/@stablelib/constant-time/constant-time.ts", "../node_modules/.pnpm/@stablelib+wipe@1.0.1/node_modules/@stablelib/wipe/wipe.ts", "../node_modules/.pnpm/@stablelib+hmac@1.0.1/node_modules/@stablelib/hmac/hmac.ts", "../node_modules/.pnpm/@stablelib+hkdf@1.0.1/node_modules/@stablelib/hkdf/hkdf.ts", "../node_modules/.pnpm/@stablelib+random@1.0.2/node_modules/@stablelib/random/source/browser.ts", "../node_modules/.pnpm/@stablelib+random@1.0.2/node_modules/@stablelib/random/source/node.ts", "../node_modules/.pnpm/@stablelib+random@1.0.2/node_modules/@stablelib/random/source/system.ts", "../node_modules/.pnpm/@stablelib+int@1.0.1/node_modules/@stablelib/int/int.ts", "../node_modules/.pnpm/@stablelib+binary@1.0.1/node_modules/@stablelib/binary/binary.ts", "../node_modules/.pnpm/@stablelib+random@1.0.2/node_modules/@stablelib/random/random.ts", "../node_modules/.pnpm/@stablelib+x25519@1.0.3/node_modules/@stablelib/x25519/x25519.ts", "../node_modules/.pnpm/@stablelib+sha256@1.0.1/node_modules/@stablelib/sha256/sha256.ts", "../node_modules/.pnpm/@stablelib+chacha@1.0.1/node_modules/@stablelib/chacha/chacha.ts", "../node_modules/.pnpm/@stablelib+poly1305@1.0.1/node_modules/@stablelib/poly1305/poly1305.ts", "../node_modules/.pnpm/@stablelib+chacha20poly1305@1.0.1/node_modules/@stablelib/chacha20poly1305/chacha20poly1305.ts", "../node_modules/.pnpm/varint@5.0.2/node_modules/varint/encode.js", "../node_modules/.pnpm/varint@5.0.2/node_modules/varint/decode.js", "../node_modules/.pnpm/varint@5.0.2/node_modules/varint/length.js", "../node_modules/.pnpm/varint@5.0.2/node_modules/varint/index.js", "../node_modules/.pnpm/varint-decoder@1.0.0/node_modules/varint-decoder/src/index.js", "../node_modules/.pnpm/@vascosantos+moving-average@1.1.0/node_modules/@vascosantos/moving-average/index.js", "../node_modules/.pnpm/textarea-caret@3.1.0/node_modules/textarea-caret/index.js", "../src/js/utils/isArray.ts", "../src/js/utils/dom.js", "../src/js/components/molecules/notify.js", "../src/js/components/molecules/welcome.js", "../src/js/utils/localstorage.js", "../src/configuration.ts", "../src/js/utils/github/api.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/vendor/varint.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/varint.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bytes.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/hashes/digest.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base58.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/vendor/base-x.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base32.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/cid.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/codecs/json.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/hashes/sha2-browser.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/hashes/hasher.js", "../src/js/utils/hashBrowser.ts", "../src/js/utils/isJSON.js", "../src/js/utils/pageTitle.js", "../src/js/utils/urlManager.js", "../src/js/ui/functions/savedState.ts", "../src/js/components/organisms/noteManager/noteManager.ts", "../src/js/utils/isUserLoggedIn.js", "../src/js/components/molecules/commands/command.js", "../src/js/components/molecules/commands/index.js", "../src/js/components/atoms/div/wordParts.ts", "../src/js/components/atoms/div/div.js", "../src/js/utils/github/actions.js", "../src/js/utils/fileSystem/fileSystem.ts", "../src/js/components/organisms/markdown/mdToHtml.ts", "../src/js/utils/mail.js", "../src/js/utils/copyToClipboard.js", "../src/js/components/atoms/button/button.js", "../src/js/components/organisms/markdown/markDownViewer.js", "../src/js/utils/prettifyJSON.js", "../src/js/utils/sleep.js", "../src/js/components/atoms/icon/icon.js", "../src/js/utils/webShare.js", "../node_modules/.pnpm/merge-options@3.0.4/node_modules/merge-options/index.mjs", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/index.js", "../node_modules/.pnpm/@libp2p+logger@2.1.1/node_modules/@libp2p/logger/src/index.ts", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base64.js", "../node_modules/.pnpm/ipfs-unixfs@9.0.1/node_modules/ipfs-unixfs/src/index.js", "../node_modules/.pnpm/ipfs-unixfs@9.0.1/node_modules/ipfs-unixfs/src/unixfs.js", "../node_modules/.pnpm/@ipld+dag-pb@4.1.2/node_modules/@ipld/dag-pb/src/index.js", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base32.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bytes.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/vendor/base-x.js", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base36.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base58.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/vendor/varint.js", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/varint.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/hashes/digest.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/cid.ts", "../node_modules/.pnpm/@ipld+dag-pb@4.1.2/node_modules/@ipld/dag-pb/src/pb-decode.js", "../node_modules/.pnpm/@ipld+dag-pb@4.1.2/node_modules/@ipld/dag-pb/src/pb-encode.js", "../node_modules/.pnpm/@ipld+dag-pb@4.1.2/node_modules/@ipld/dag-pb/src/util.js", "../node_modules/.pnpm/@ipld+dag-cbor@9.2.1/node_modules/@ipld/dag-cbor/src/index.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/is.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/token.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/byte-utils.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/bl.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/common.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/0uint.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/1negint.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/2bytes.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/3string.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/4array.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/5map.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/6tag.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/7float.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/jump.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/encode.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/decode.js", "../node_modules/.pnpm/@ipld+dag-json@10.2.2/node_modules/@ipld/dag-json/src/index.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/json/encode.js", "../node_modules/.pnpm/cborg@4.2.4/node_modules/cborg/lib/json/decode.js", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/hashes/hasher.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base64.ts", "../node_modules/.pnpm/dag-jose@4.0.0/node_modules/dag-jose/src/index.ts", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base64.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/vendor/base-x.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bytes.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base.js", "../node_modules/.pnpm/dag-jose@4.0.0/node_modules/dag-jose/src/utils.ts", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/vendor/varint.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/varint.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/hashes/digest.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base58.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base32.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/cid.js", "../node_modules/.pnpm/dag-jose@4.0.0/node_modules/dag-jose/src/signing.ts", "../node_modules/.pnpm/dag-jose@4.0.0/node_modules/dag-jose/src/encryption.ts", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/is.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/token.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/byte-utils.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/bl.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/common.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/0uint.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/1negint.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/2bytes.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/3string.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/4array.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/5map.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/6tag.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/7float.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/jump.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/encode.js", "../node_modules/.pnpm/cborg@1.10.0/node_modules/cborg/esm/lib/decode.js", "../node_modules/.pnpm/@ipld+dag-cbor@9.0.0/node_modules/@ipld/dag-cbor/src/index.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/hashes/identity.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/identity.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base2.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base8.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base10.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base16.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base36.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/bases/base256emoji.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/codecs/raw.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/basics.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/errors.js", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/util/as-uint8array.ts", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base10.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/vendor/base-x.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bytes.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base16.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base2.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base256emoji.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base32.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base36.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base58.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base64.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base8.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/identity.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/codecs/json.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/identity.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/vendor/varint.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/varint.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/digest.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/sha2-browser.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/hasher.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/cid.js", "../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/basics.js", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/alloc.ts", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/util/bases.ts", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/from-string.ts", "../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/equals.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base10.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base16.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base2.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base256emoji.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/base8.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/bases/identity.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/codecs/json.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/hashes/identity.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/hashes/sha2-browser.ts", "../node_modules/.pnpm/multiformats@13.3.0/node_modules/multiformats/src/basics.ts", "../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/alloc.ts", "../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/util/bases.ts", "../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/to-string.ts", "../node_modules/.pnpm/uint8-varint@2.0.4/node_modules/uint8-varint/src/index.ts", "../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/concat.ts", "../node_modules/.pnpm/@chainsafe+is-ip@2.0.2/node_modules/@chainsafe/is-ip/src/parser.ts", "../node_modules/.pnpm/@chainsafe+is-ip@2.0.2/node_modules/@chainsafe/is-ip/src/parse.ts", "../node_modules/.pnpm/@chainsafe+netmask@2.0.0/node_modules/@chainsafe/netmask/src/ip.ts", "../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/from-string.ts", "../node_modules/.pnpm/@chainsafe+is-ip@2.0.2/node_modules/@chainsafe/is-ip/src/is-ip.ts", "../node_modules/.pnpm/@multiformats+multiaddr@12.3.1/node_modules/@multiformats/multiaddr/src/ip.ts", "../node_modules/.pnpm/@multiformats+multiaddr@12.3.1/node_modules/@multiformats/multiaddr/src/protocols-table.ts", "../node_modules/.pnpm/@multiformats+multiaddr@12.3.1/node_modules/@multiformats/multiaddr/src/convert.ts", "../node_modules/.pnpm/@multiformats+multiaddr@12.3.1/node_modules/@multiformats/multiaddr/src/codec.ts", "../node_modules/.pnpm/@multiformats+multiaddr@12.3.1/node_modules/@multiformats/multiaddr/src/multiaddr.ts", "../node_modules/.pnpm/@multiformats+multiaddr@12.3.1/node_modules/@multiformats/multiaddr/src/index.ts", "../node_modules/.pnpm/@multiformats+mafmt@12.1.6/node_modules/@multiformats/mafmt/src/index.ts", "../node_modules/.pnpm/is-ipfs@8.0.4/node_modules/is-ipfs/src/index.ts", "../node_modules/.pnpm/nanoid@4.0.2/node_modules/nanoid/index.browser.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/identity.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base2.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base8.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base10.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base16.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base36.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/bases/base256emoji.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/hashes/sha2-browser.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/hashes/hasher.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/hashes/identity.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/codecs/raw.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/codecs/json.js", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/basics.js", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/util/as-uint8array.ts", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/alloc.ts", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/util/bases.ts", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/to-string.ts", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/from-string.ts", "../node_modules/.pnpm/interface-datastore@7.0.4/node_modules/interface-datastore/src/key.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/utils.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/with-timeout-option.js", "../node_modules/.pnpm/parse-duration@1.1.0/node_modules/parse-duration/index.mjs", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/errors.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/to-cid-and-path.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/utils/service.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/start.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/stop.js", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/utils/tlru.js", "../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.mjs", "../node_modules/.pnpm/p-timeout@5.1.0/node_modules/p-timeout/index.js", "../node_modules/.pnpm/p-queue@7.4.1/node_modules/p-queue/dist/lower-bound.js", "../node_modules/.pnpm/p-queue@7.4.1/node_modules/p-queue/dist/priority-queue.js", "../node_modules/.pnpm/p-queue@7.4.1/node_modules/p-queue/dist/index.js", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/dns.browser.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dns.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/is-online.js", "../node_modules/.pnpm/@libp2p+interface-peer-id@2.0.2/node_modules/@libp2p/interface-peer-id/src/index.ts", "../node_modules/.pnpm/@libp2p+interfaces@3.3.2/node_modules/@libp2p/interfaces/src/errors.ts", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/equals.ts", "../node_modules/.pnpm/@libp2p+peer-id@2.0.4/node_modules/@libp2p/peer-id/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/resolve.js", "../node_modules/.pnpm/it-last@2.0.1/node_modules/it-last/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pin/add.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/pins/normalise-input.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/pin-types.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pin/add-all.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pin/ls.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pin/rm.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pin/rm-all.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pin/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/index.js", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/errors.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/publisher.js", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/to-string.ts", "../node_modules/.pnpm/ipns@5.0.2/node_modules/ipns/src/index.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/index.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/ed25519-class.ts", "../node_modules/.pnpm/@noble+ed25519@1.7.3/node_modules/@noble/ed25519/lib/esm/index.js", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/ed25519-browser.ts", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/concat.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/webcrypto.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/ciphers/aes-gcm.browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/exporter.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/keys.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/utils/float.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/utils/longbits.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/utils/utf8.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/utils/reader.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/decode.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/utils/pool.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/utils/writer.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/encode.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/codec.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/codecs/enum.ts", "../node_modules/.pnpm/protons-runtime@5.5.0/node_modules/protons-runtime/src/codecs/message.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/util.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/ecdh-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/ephemeral-keys.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/importer.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/hmac/lengths.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/hmac/index-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/key-stretcher.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/rsa-class.ts", "../node_modules/.pnpm/@noble+secp256k1@1.7.1/node_modules/@noble/secp256k1/lib/esm/index.js", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/random-bytes.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/jwk2pem.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/rsa-utils.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/rsa-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/secp256k1-class.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/keys/secp256k1.ts", "../node_modules/.pnpm/ipns@5.0.2/node_modules/ipns/src/utils.ts", "../node_modules/.pnpm/ipns@5.0.2/node_modules/ipns/src/errors.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.8/node_modules/protons-runtime/src/utils.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.8/node_modules/protons-runtime/src/decode.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.8/node_modules/protons-runtime/src/encode.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.8/node_modules/protons-runtime/src/codec.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.8/node_modules/protons-runtime/src/codecs/enum.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.8/node_modules/protons-runtime/src/codecs/message.ts", "../node_modules/.pnpm/ipns@5.0.2/node_modules/ipns/src/pb/ipns.ts", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/is.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/token.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/byte-utils.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/bl.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/common.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/0uint.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/1negint.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/2bytes.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/3string.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/4array.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/5map.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/6tag.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/7float.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/jump.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/encode.js", "../node_modules/.pnpm/cborg@1.10.2/node_modules/cborg/esm/lib/decode.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/republisher.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/resolver.js", "../node_modules/.pnpm/ipns@5.0.2/node_modules/ipns/src/validator.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/utils/tlru.js", "../node_modules/.pnpm/it-all@2.0.0/node_modules/it-all/src/index.ts", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/utils.js", "../node_modules/.pnpm/it-drain@2.0.0/node_modules/it-drain/src/index.ts", "../node_modules/.pnpm/it-filter@2.0.0/node_modules/it-filter/src/index.ts", "../node_modules/.pnpm/it-take@2.0.0/node_modules/it-take/src/index.ts", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/base.js", "../node_modules/.pnpm/@libp2p+logger@2.0.5/node_modules/@libp2p/logger/src/index.ts", "../node_modules/.pnpm/it-pushable@3.1.2/node_modules/it-pushable/src/fifo.ts", "../node_modules/.pnpm/it-pushable@3.1.2/node_modules/it-pushable/src/index.ts", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/tiered.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/routing/config.js", "../node_modules/.pnpm/ipns@5.0.2/node_modules/ipns/src/selector.ts", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/shard.js", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/memory.js", "../node_modules/.pnpm/it-map@2.0.0/node_modules/it-map/src/index.ts", "../node_modules/.pnpm/it-merge@2.0.0/node_modules/it-merge/src/index.ts", "../node_modules/.pnpm/it-pipe@2.0.5/node_modules/it-pipe/src/index.ts", "../node_modules/.pnpm/datastore-core@8.0.4/node_modules/datastore-core/src/sharding.js", "../node_modules/.pnpm/@libp2p+interfaces@3.3.1/node_modules/@libp2p/interfaces/src/errors.ts", "../node_modules/.pnpm/datastore-pubsub@7.0.0/node_modules/datastore-pubsub/src/utils.js", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/equals.ts", "../node_modules/.pnpm/datastore-pubsub@7.0.0/node_modules/datastore-pubsub/src/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/routing/pubsub-datastore.js", "../node_modules/.pnpm/@libp2p+record@3.0.4/node_modules/@libp2p/record/src/record.ts", "../node_modules/.pnpm/@libp2p+record@3.0.4/node_modules/@libp2p/record/src/utils.ts", "../node_modules/.pnpm/@libp2p+record@3.0.4/node_modules/@libp2p/record/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/routing/offline-datastore.js", "../node_modules/.pnpm/it-drain@2.0.1/node_modules/it-drain/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/ipns/routing/dht-datastore.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/ipns.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/publish.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/utils.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/resolve.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/pubsub/utils.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/pubsub/cancel.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/pubsub/state.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/pubsub/subs.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/pubsub/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/name/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/refs/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/refs/local.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bitswap/wantlist.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bitswap/wantlist-for-peer.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bitswap/unwant.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bitswap/stat.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bitswap/index.js", "../node_modules/.pnpm/@multiformats+mafmt@11.1.2/node_modules/@multiformats/mafmt/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/utils.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/add.js", "../node_modules/.pnpm/@multiformats+multiaddr@11.6.1/node_modules/@multiformats/multiaddr/src/ip.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.6.1/node_modules/@multiformats/multiaddr/src/protocols-table.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.6.1/node_modules/@multiformats/multiaddr/src/convert.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.6.1/node_modules/@multiformats/multiaddr/src/codec.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.6.1/node_modules/@multiformats/multiaddr/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/clear.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/list.js", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/config.browser.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/reset.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/rm.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/bootstrap/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/block/get.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/block/put.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/block/rm.js", "../node_modules/.pnpm/p-defer@4.0.1/node_modules/p-defer/index.js", "../node_modules/.pnpm/it-parallel@3.0.8/node_modules/it-parallel/src/index.ts", "../node_modules/.pnpm/it-map@2.0.1/node_modules/it-map/src/index.ts", "../node_modules/.pnpm/it-filter@2.0.2/node_modules/it-filter/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/block/utils.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/block/stat.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/block/index.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-content.js", "../node_modules/.pnpm/browser-readablestream-to-it@2.0.7/node_modules/browser-readablestream-to-it/src/index.ts", "../node_modules/.pnpm/blob-to-it@2.0.7/node_modules/blob-to-it/src/index.ts", "../node_modules/.pnpm/it-peekable@2.0.1/node_modules/it-peekable/src/index.ts", "../node_modules/.pnpm/it-all@2.0.1/node_modules/it-all/src/index.ts", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/utils.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-candidate-single.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-input-single.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/add.js", "../node_modules/.pnpm/it-batch@2.0.1/node_modules/it-batch/src/index.ts", "../node_modules/.pnpm/it-parallel-batch@2.0.1/node_modules/it-parallel-batch/src/index.ts", "../node_modules/.pnpm/@multiformats+murmur3@2.1.8/node_modules/@multiformats/murmur3/src/index.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/options.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/utils/persist.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/dir.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/file/index.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/file/flat.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/file/balanced.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/file/trickle.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/file/buffer-importer.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/index.js", "../node_modules/.pnpm/uint8arraylist@2.4.8/node_modules/uint8arraylist/src/index.ts", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/chunker/rabin.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/chunker/fixed-size.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dag-builder/validate-chunks.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dir.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dir-flat.js", "../node_modules/.pnpm/hamt-sharding@3.0.6/node_modules/hamt-sharding/src/bucket.ts", "../node_modules/.pnpm/hamt-sharding@3.0.6/node_modules/hamt-sharding/src/consumable-buffer.ts", "../node_modules/.pnpm/hamt-sharding@3.0.6/node_modules/hamt-sharding/src/consumable-hash.ts", "../node_modules/.pnpm/hamt-sharding@3.0.6/node_modules/hamt-sharding/src/index.ts", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/dir-sharded.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/flat-to-shard.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/utils/to-path-components.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/tree-builder.js", "../node_modules/.pnpm/ipfs-unixfs-importer@12.0.1_encoding@0.1.13/node_modules/ipfs-unixfs-importer/src/index.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-candidate-multiple.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-input-multiple.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/add-all/utils.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/add-all/index.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/index.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/index.js", "../node_modules/.pnpm/@ipld+dag-pb@4.0.2/node_modules/@ipld/dag-pb/src/pb-decode.js", "../node_modules/.pnpm/@ipld+dag-pb@4.0.2/node_modules/@ipld/dag-pb/src/pb-encode.js", "../node_modules/.pnpm/@ipld+dag-pb@4.0.2/node_modules/@ipld/dag-pb/src/util.js", "../node_modules/.pnpm/@ipld+dag-pb@4.0.2/node_modules/@ipld/dag-pb/src/index.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/index.js", "../node_modules/.pnpm/hamt-sharding@3.0.2/node_modules/hamt-sharding/src/bucket.ts", "../node_modules/.pnpm/hamt-sharding@3.0.2/node_modules/hamt-sharding/src/consumable-buffer.ts", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/concat.ts", "../node_modules/.pnpm/hamt-sharding@3.0.2/node_modules/hamt-sharding/src/consumable-hash.ts", "../node_modules/.pnpm/hamt-sharding@3.0.2/node_modules/hamt-sharding/src/index.ts", "../node_modules/.pnpm/@multiformats+murmur3@2.1.3/node_modules/@multiformats/murmur3/src/index.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/utils/find-cid-in-shard.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/utils/extract-data-from-block.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/utils/validate-offset-and-length.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/file.js", "../node_modules/.pnpm/p-defer@4.0.0/node_modules/p-defer/index.js", "../node_modules/.pnpm/it-parallel@3.0.0/node_modules/it-parallel/src/index.ts", "../node_modules/.pnpm/p-queue@7.3.4/node_modules/p-queue/dist/index.js", "../node_modules/.pnpm/p-queue@7.3.4/node_modules/p-queue/dist/lower-bound.js", "../node_modules/.pnpm/p-queue@7.3.4/node_modules/p-queue/dist/priority-queue.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/directory.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/unixfs-v1/content/hamt-sharded-directory.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/raw.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/dag-cbor.js", "../node_modules/.pnpm/ipfs-unixfs-exporter@10.0.1/node_modules/ipfs-unixfs-exporter/src/resolvers/identity.js", "../node_modules/.pnpm/it-last@2.0.0/node_modules/it-last/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/cat.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/get.js", "../node_modules/.pnpm/it-tar@6.0.5/node_modules/it-tar/src/extract-headers.ts", "../node_modules/.pnpm/it-tar@6.0.5/node_modules/it-tar/src/pack.ts", "../node_modules/.pnpm/it-to-buffer@4.0.7/node_modules/it-to-buffer/src/index.ts", "../node_modules/.pnpm/it-tar@6.0.5/node_modules/it-tar/src/pack-headers.ts", "../node_modules/.pnpm/pako@2.1.0/node_modules/pako/dist/pako.esm.mjs", "../node_modules/.pnpm/it-to-buffer@3.0.1/node_modules/it-to-buffer/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/ls.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/root.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/version.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/version.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/id.js", "../node_modules/.pnpm/just-safe-set@4.2.1/node_modules/just-safe-set/index.mjs", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/config/profiles.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/config/index.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/block.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/decoder-common.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/header-validator.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/decoder.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/encoder.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/iterator-channel.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/writer-browser.js", "../node_modules/.pnpm/multiformats@11.0.2/node_modules/multiformats/src/traversal.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dag/export.js", "../node_modules/.pnpm/it-first@2.0.1/node_modules/it-first/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dag/get.js", "../node_modules/.pnpm/@ipld+car@5.3.2/node_modules/@ipld/car/src/iterator.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dag/import.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dag/put.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dag/resolve.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dag/index.js", "../node_modules/.pnpm/@multiformats+multiaddr-to-uri@9.0.8/node_modules/@multiformats/multiaddr-to-uri/src/index.ts", "../node_modules/.pnpm/array-shuffle@3.0.0/node_modules/array-shuffle/index.js", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/preload.browser.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/preload.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/mfs-preload.js", "../node_modules/.pnpm/p-timeout@6.1.2/node_modules/p-timeout/index.js", "../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/lower-bound.js", "../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/priority-queue.js", "../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/index.js", "../node_modules/.pnpm/observable-webworkers@2.0.1/node_modules/observable-webworkers/src/index.ts", "../node_modules/.pnpm/mortice@3.0.4/node_modules/mortice/src/constants.ts", "../node_modules/.pnpm/mortice@3.0.4/node_modules/mortice/src/utils.ts", "../node_modules/.pnpm/mortice@3.0.4/node_modules/mortice/src/browser.ts", "../node_modules/.pnpm/mortice@3.0.4/node_modules/mortice/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/create-lock.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/with-mfs-root.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/to-path-components.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/to-mfs-path.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/stat.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/chmod.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/to-trail.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/persist.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/hamt-constants.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/dir-sharded.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/hamt-utils.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/add-link.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/update-tree.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/update-mfs-root.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/mkdir.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/create-node.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/cp.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/rm.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/remove-link.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/flush.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/mv.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/touch.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/read.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/utils/to-async-iterator.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/write.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/ls.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/files/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/export.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/gen.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/import.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/info.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/list.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/rename.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/rm.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/key/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/get.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/data.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/links.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/new.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/put.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/stat.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/patch/add-link.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/patch/append-data.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/patch/rm-link.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/patch/set-data.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/patch/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/object/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/repo/gc.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/repo/stat.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/repo/version.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/repo/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/stats/bw.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/stats/index.js", "../node_modules/.pnpm/just-safe-get@4.2.0/node_modules/just-safe-get/index.mjs", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/index.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-8/index.js", "../node_modules/.pnpm/it-length@2.0.0/node_modules/it-length/src/index.ts", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-9/pin.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-9/pin-set.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-9/utils.js", "../node_modules/.pnpm/uint8arrays@4.0.3/node_modules/uint8arrays/src/compare.ts", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-9/index.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/utils.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-10/index.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-11/index.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-12/index.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-12/pb/proto-book.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-12/pb/address-book.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-12/pb/peer.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-12/pb/envelope.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/migration-12/pb/peer-record.js", "../node_modules/.pnpm/@chainsafe+is-ip@2.0.1/node_modules/@chainsafe/is-ip/src/parser.ts", "../node_modules/.pnpm/@chainsafe+is-ip@2.0.1/node_modules/@chainsafe/is-ip/src/parse.ts", "../node_modules/.pnpm/@chainsafe+is-ip@2.0.1/node_modules/@chainsafe/is-ip/src/is-ip.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/ip.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/protocols-table.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/convert.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/codec.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/index.ts", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/migrations/index.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/repo/init.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/errors.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/repo/version.js", "../node_modules/.pnpm/ipfs-repo-migrations@15.0.0/node_modules/ipfs-repo-migrations/src/index.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/version.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/errors.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/utils/level.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/config.js", "../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js", "../node_modules/.pnpm/sort-keys@5.0.0/node_modules/sort-keys/index.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/spec.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/api-addr.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/idstore.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/locks/memory.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/default-options.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/default-datastore.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/pin-manager.js", "../node_modules/.pnpm/it-first@2.0.0/node_modules/it-first/src/index.ts", "../node_modules/.pnpm/multiformats@11.0.1/node_modules/multiformats/src/block.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/utils/blockstore.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/utils/walk-dag.js", "../node_modules/.pnpm/quick-lru@6.1.1/node_modules/quick-lru/index.js", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/pinned-blockstore.js", "../node_modules/.pnpm/p-timeout@6.1.1/node_modules/p-timeout/index.js", "../node_modules/.pnpm/mortice@3.0.1/node_modules/mortice/src/constants.ts", "../node_modules/.pnpm/mortice@3.0.1/node_modules/mortice/src/browser.ts", "../node_modules/.pnpm/mortice@3.0.1/node_modules/mortice/src/index.ts", "../node_modules/.pnpm/ipfs-repo@17.0.0/node_modules/ipfs-repo/src/gc.js", "../node_modules/.pnpm/it-batch@2.0.0/node_modules/it-batch/src/index.ts", "../node_modules/.pnpm/it-parallel-batch@2.0.0/node_modules/it-parallel-batch/src/index.ts", "../node_modules/.pnpm/it-sort@2.0.0/node_modules/it-sort/src/index.ts", "../node_modules/.pnpm/datastore-level@9.0.4/node_modules/datastore-level/src/index.js", "../node_modules/.pnpm/blockstore-datastore-adapter@5.0.0/node_modules/blockstore-datastore-adapter/src/index.js", "../node_modules/.pnpm/blockstore-core@3.0.0/node_modules/blockstore-core/src/base.js", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/repo.browser.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/libp2p.js", "../node_modules/.pnpm/byte-access@1.0.1/node_modules/byte-access/src/index.ts", "../node_modules/.pnpm/longbits@1.1.0/node_modules/longbits/src/index.ts", "../node_modules/.pnpm/uint8-varint@1.0.8/node_modules/uint8-varint/src/index.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.4/node_modules/@libp2p/peer-record/src/errors.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.4/node_modules/@libp2p/peer-record/src/envelope/envelope.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.4/node_modules/@libp2p/peer-record/src/envelope/index.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.4/node_modules/@libp2p/peer-record/src/peer-record/consts.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.4/node_modules/@libp2p/peer-record/src/peer-record/peer-record.ts", "../node_modules/.pnpm/@libp2p+interface-registrar@2.0.12/node_modules/@libp2p/interface-registrar/src/index.ts", "../node_modules/.pnpm/@libp2p+topology@4.0.3/node_modules/@libp2p/topology/src/index.ts", "../node_modules/.pnpm/@libp2p+interfaces@3.3.2/node_modules/@libp2p/interfaces/src/events.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/message-cache.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/dist/src/message/rpc.js", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/constants.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/shuffle.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/messageIdToString.ts", "../node_modules/.pnpm/@libp2p+interface-pubsub@3.0.7/node_modules/@libp2p/interface-pubsub/src/index.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/types.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/publishConfig.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/constants.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/peer-score-params.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/peer-score-thresholds.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/compute-score.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/message-deliveries.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/set.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/peer-score.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/tracer.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/time-cache.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/metrics.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/aes/ciphers-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.17/node_modules/@libp2p/crypto/src/pbkdf2.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/buildRawMessage.ts", "../node_modules/.pnpm/@libp2p+pubsub@6.0.6/node_modules/@libp2p/pubsub/src/utils.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/msgIdFn.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/score/scoreMetrics.ts", "../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/src/fifo.ts", "../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/src/index.ts", "../node_modules/.pnpm/abortable-iterator@4.0.3/node_modules/abortable-iterator/src/abort-error.ts", "../node_modules/.pnpm/get-iterator@2.0.1/node_modules/get-iterator/src/index.ts", "../node_modules/.pnpm/abortable-iterator@4.0.3/node_modules/abortable-iterator/src/index.ts", "../node_modules/.pnpm/uint8arraylist@2.4.3/node_modules/uint8arraylist/src/index.ts", "../node_modules/.pnpm/uint8-varint@1.0.4/node_modules/uint8-varint/src/index.ts", "../node_modules/.pnpm/it-length-prefixed@8.0.4/node_modules/it-length-prefixed/src/alloc.ts", "../node_modules/.pnpm/it-length-prefixed@8.0.4/node_modules/it-length-prefixed/src/encode.ts", "../node_modules/.pnpm/it-length-prefixed@8.0.4/node_modules/it-length-prefixed/src/decode.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/stream.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/message/decodeRpc.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/utils/multiaddr.ts", "../node_modules/.pnpm/@chainsafe+libp2p-gossipsub@6.3.0/node_modules/@chainsafe/libp2p-gossipsub/src/index.ts", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/libp2p-pubsub-routers.browser.js", "../node_modules/.pnpm/@libp2p+logger@3.1.0/node_modules/@libp2p/logger/src/index.ts", "../node_modules/.pnpm/@libp2p+interface@0.1.6/node_modules/@libp2p/interface/src/peer-id/index.ts", "../node_modules/.pnpm/@libp2p+peer-id@3.0.6/node_modules/@libp2p/peer-id/src/index.ts", "../node_modules/.pnpm/any-signal@4.1.1/node_modules/any-signal/src/index.ts", "../node_modules/.pnpm/@libp2p+delegated-peer-routing@4.0.14/node_modules/@libp2p/delegated-peer-routing/src/index.ts", "../node_modules/.pnpm/@libp2p+delegated-content-routing@4.0.11/node_modules/@libp2p/delegated-content-routing/src/index.ts", "../node_modules/.pnpm/it-drain@3.0.7/node_modules/it-drain/src/index.ts", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/multibases.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/multicodecs.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/multihashes.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/core.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/to-url-string.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/agent.browser.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/configure.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/mode-to-string.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/parse-mtime.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/to-url-search-params.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bitswap/wantlist.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bitswap/wantlist-for-peer.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bitswap/stat.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bitswap/unwant.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bitswap/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/block/get.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-content.browser.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/files/normalise-input-multiple.browser.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/mode-to-string.js", "../node_modules/.pnpm/ipfs-core-utils@0.18.1_encoding@0.1.13/node_modules/ipfs-core-utils/src/multipart-request.browser.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/abort-signal.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/block/put.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/block/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/block/stat.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/block/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bootstrap/add.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bootstrap/clear.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bootstrap/list.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bootstrap/reset.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bootstrap/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/bootstrap/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/profiles/apply.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/object-to-camel.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/profiles/list.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/profiles/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/get.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/get-all.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/replace.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/set.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/config/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dag/export.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/resolve.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dag/get.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dag/import.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dag/put.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dag/resolve.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dag/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/map-event.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/find-peer.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/find-provs.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/get.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/provide.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/put.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/query.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dht/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/diag/cmds.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/diag/net.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/diag/sys.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/diag/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/chmod.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/cp.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/flush.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/object-to-camel-with-metadata.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/mkdir.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/mv.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/read.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/stat.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/touch.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/write.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/files/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/export.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/gen.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/import.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/info.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/list.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/rename.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/key/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/log/level.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/log/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/log/tail.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/log/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/publish.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/resolve.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/pubsub/cancel.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/pubsub/state.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/pubsub/subs.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/pubsub/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/name/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/data.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/get.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/links.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/new.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/put.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/stat.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/patch/add-link.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/patch/append-data.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/patch/rm-link.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/patch/set-data.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/patch/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/object/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/add-all.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/add.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/rm-all.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/utils.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/add.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/rm-all.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/service/utils.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/service/add.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/service/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/service/rm.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/service/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/remote/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pin/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/lib/http-rpc-wire-format.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/peers.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/publish.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/subscribe.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/unsubscribe.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/subscription-tracker.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/pubsub/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/refs/local.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/refs/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/repo/gc.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/repo/stat.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/repo/version.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/repo/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/stats/bw.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/stats/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/swarm/addrs.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/swarm/connect.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/swarm/disconnect.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/swarm/local-addrs.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/swarm/peers.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/swarm/index.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/add-all.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/add.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/cat.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/commands.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/dns.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/get-endpoint-config.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/get.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/id.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/is-online.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/ls.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/mount.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/ping.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/resolve.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/start.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/stop.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/version.js", "../node_modules/.pnpm/ipfs-http-client@60.0.1_encoding@0.1.13/node_modules/ipfs-http-client/src/index.js", "../node_modules/.pnpm/@libp2p+webrtc-star@6.0.0/node_modules/@libp2p/webrtc-star/src/transport.ts", "../node_modules/.pnpm/abortable-iterator@4.0.2/node_modules/abortable-iterator/src/abort-error.ts", "../node_modules/.pnpm/get-iterator@2.0.0/node_modules/get-iterator/src/index.ts", "../node_modules/.pnpm/abortable-iterator@4.0.2/node_modules/abortable-iterator/src/index.ts", "../node_modules/.pnpm/@multiformats+mafmt@11.0.3/node_modules/@multiformats/mafmt/src/index.ts", "../node_modules/.pnpm/@libp2p+webrtc-star@6.0.0/node_modules/@libp2p/webrtc-star/src/listener.ts", "../node_modules/.pnpm/engine.io-parser@5.0.6/node_modules/engine.io-parser/build/esm/commons.js", "../node_modules/.pnpm/engine.io-parser@5.0.6/node_modules/engine.io-parser/build/esm/encodePacket.browser.js", "../node_modules/.pnpm/engine.io-parser@5.0.6/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js", "../node_modules/.pnpm/engine.io-parser@5.0.6/node_modules/engine.io-parser/build/esm/decodePacket.browser.js", "../node_modules/.pnpm/engine.io-parser@5.0.6/node_modules/engine.io-parser/build/esm/index.js", "../node_modules/.pnpm/@socket.io+component-emitter@3.1.0/node_modules/@socket.io/component-emitter/index.mjs", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/globalThis.browser.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/util.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/transport.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/contrib/yeast.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/contrib/parseqs.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/contrib/has-cors.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/transports/polling.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/transports/websocket.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/transports/index.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/contrib/parseuri.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/socket.js", "../node_modules/.pnpm/engine.io-client@6.4.0/node_modules/engine.io-client/build/esm/index.js", "../node_modules/.pnpm/socket.io-client@4.6.1/node_modules/socket.io-client/build/esm/url.js", "../node_modules/.pnpm/socket.io-parser@4.2.2/node_modules/socket.io-parser/build/esm/index.js", "../node_modules/.pnpm/socket.io-parser@4.2.2/node_modules/socket.io-parser/build/esm/is-binary.js", "../node_modules/.pnpm/socket.io-parser@4.2.2/node_modules/socket.io-parser/build/esm/binary.js", "../node_modules/.pnpm/socket.io-client@4.6.1/node_modules/socket.io-client/build/esm/on.js", "../node_modules/.pnpm/socket.io-client@4.6.1/node_modules/socket.io-client/build/esm/socket.js", "../node_modules/.pnpm/socket.io-client@4.6.1/node_modules/socket.io-client/build/esm/contrib/backo2.js", "../node_modules/.pnpm/socket.io-client@4.6.1/node_modules/socket.io-client/build/esm/manager.js", "../node_modules/.pnpm/socket.io-client@4.6.1/node_modules/socket.io-client/build/esm/index.js", "../node_modules/.pnpm/@libp2p+interfaces@3.3.1/node_modules/@libp2p/interfaces/src/events.ts", "../node_modules/.pnpm/@libp2p+webrtc-peer@2.0.2/node_modules/@libp2p/webrtc-peer/src/peer.ts", "../node_modules/.pnpm/@libp2p+webrtc-peer@2.0.2/node_modules/@libp2p/webrtc-peer/src/channel.ts", "../node_modules/.pnpm/@libp2p+webrtc-peer@2.0.2/node_modules/@libp2p/webrtc-peer/src/handshake.ts", "../node_modules/.pnpm/@libp2p+webrtc-peer@2.0.2/node_modules/@libp2p/webrtc-peer/src/receiver.ts", "../node_modules/.pnpm/@libp2p+webrtc-peer@2.0.2/node_modules/@libp2p/webrtc-peer/src/initiator.ts", "../node_modules/.pnpm/p-event@5.0.1/node_modules/p-event/index.js", "../node_modules/.pnpm/@libp2p+webrtc-star@6.0.0/node_modules/@libp2p/webrtc-star/src/socket-to-conn.ts", "../node_modules/.pnpm/@libp2p+webrtc-star@6.0.0/node_modules/@libp2p/webrtc-star/src/utils.ts", "../node_modules/.pnpm/@libp2p+interface-peer-id@2.0.1/node_modules/@libp2p/interface-peer-id/src/index.ts", "../node_modules/.pnpm/@libp2p+peer-id@2.0.2/node_modules/@libp2p/peer-id/src/index.ts", "../node_modules/.pnpm/@libp2p+interface-transport@2.1.1/node_modules/@libp2p/interface-transport/src/index.ts", "../node_modules/.pnpm/@libp2p+interface-peer-discovery@1.0.5/node_modules/@libp2p/interface-peer-discovery/src/index.ts", "../node_modules/.pnpm/@libp2p+webrtc-star@6.0.0/node_modules/@libp2p/webrtc-star/src/index.ts", "../node_modules/.pnpm/ipfs-core-config@0.7.1_encoding@0.1.13/node_modules/ipfs-core-config/src/libp2p.browser.js", "../node_modules/.pnpm/@libp2p+interfaces@3.3.1/node_modules/@libp2p/interfaces/src/startable.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/peer-routing.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/errors.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/content-routing/utils.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/content-routing/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/address-manager/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection-manager/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection-manager/visibility-change-emitter.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection-manager/latency-monitor.ts", "../node_modules/.pnpm/@libp2p+interface-connection@3.0.8/node_modules/@libp2p/interface-connection/src/status.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.0/node_modules/@libp2p/peer-collections/src/util.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.0/node_modules/@libp2p/peer-collections/src/map.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.0/node_modules/@libp2p/peer-collections/src/set.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.0/node_modules/@libp2p/peer-collections/src/list.ts", "../node_modules/.pnpm/@libp2p+interface-peer-store@1.2.8/node_modules/@libp2p/interface-peer-store/src/tags.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/get-peer.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection-manager/auto-dialler.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/transport.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.3/node_modules/protons-runtime/src/utils.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.3/node_modules/protons-runtime/src/decode.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.3/node_modules/protons-runtime/src/encode.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.3/node_modules/protons-runtime/src/codec.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.3/node_modules/protons-runtime/src/codecs/enum.ts", "../node_modules/.pnpm/protons-runtime@4.0.2_uint8arraylist@2.4.3/node_modules/protons-runtime/src/codecs/message.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/pb/index.ts", "../node_modules/.pnpm/@libp2p+utils@3.0.4/node_modules/@libp2p/utils/src/stream-to-ma-conn.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/multicodec.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/listener.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/circuit/hop.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/circuit/utils.ts", "../node_modules/.pnpm/it-reader@6.0.2/node_modules/it-reader/src/index.ts", "../node_modules/.pnpm/it-handshake@4.1.2/node_modules/it-handshake/src/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/circuit/stream-handler.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/circuit/stop.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/utils.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/constants.ts", "../node_modules/.pnpm/private-ip@3.0.0/node_modules/private-ip/lib/index.js", "../node_modules/.pnpm/ip-regex@5.0.0/node_modules/ip-regex/index.js", "../node_modules/.pnpm/private-ip@3.0.0/node_modules/private-ip/index.js", "../node_modules/.pnpm/@libp2p+utils@3.0.4/node_modules/@libp2p/utils/src/multiaddr/is-private.ts", "../node_modules/.pnpm/@libp2p+utils@3.0.4/node_modules/@libp2p/utils/src/address-sort.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/circuit/auto-relay.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/keychain/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/keychain/cms.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/keychain/util.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/keys.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/index.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/webcrypto.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/util.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/ecdh-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/ciphers/aes-gcm.browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/importer.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/rsa-class.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/random-bytes.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/rsa-utils.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/jwk2pem.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/rsa-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/exporter.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/ed25519-class.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/ed25519-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/secp256k1-class.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/keys/secp256k1.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/aes/ciphers-browser.ts", "../node_modules/.pnpm/@libp2p+crypto@1.0.12_uint8arraylist@2.4.3/node_modules/@libp2p/crypto/src/pbkdf2.ts", "../node_modules/.pnpm/p-reflect@3.1.0/node_modules/p-reflect/index.js", "../node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js", "../node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js", "../node_modules/.pnpm/p-settle@5.1.0/node_modules/p-settle/index.js", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/transport-manager.ts", "../node_modules/.pnpm/@libp2p+tracked-map@3.0.2/node_modules/@libp2p/tracked-map/src/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/upgrader.ts", "../node_modules/.pnpm/@libp2p+multistream-select@3.1.2/node_modules/@libp2p/multistream-select/src/constants.ts", "../node_modules/.pnpm/@libp2p+multistream-select@3.1.2/node_modules/@libp2p/multistream-select/src/select.ts", "../node_modules/.pnpm/@libp2p+multistream-select@3.1.2/node_modules/@libp2p/multistream-select/src/multistream.ts", "../node_modules/.pnpm/@libp2p+multistream-select@3.1.2/node_modules/@libp2p/multistream-select/src/handle.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection/index.ts", "../node_modules/.pnpm/@libp2p+interface-connection@3.0.8/node_modules/@libp2p/interface-connection/src/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/registrar.ts", "../node_modules/.pnpm/@libp2p+interface-registrar@2.0.8/node_modules/@libp2p/interface-registrar/src/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/identify/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/identify/pb/message.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.0/node_modules/@libp2p/peer-record/src/envelope/index.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.0/node_modules/@libp2p/peer-record/src/errors.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.0/node_modules/@libp2p/peer-record/src/envelope/envelope.ts", "../node_modules/.pnpm/@libp2p+utils@3.0.4/node_modules/@libp2p/utils/src/array-equals.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.0/node_modules/@libp2p/peer-record/src/peer-record/peer-record.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.0/node_modules/@libp2p/peer-record/src/peer-record/consts.ts", "../node_modules/.pnpm/@libp2p+peer-record@5.0.0/node_modules/@libp2p/peer-record/src/peer-record/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/version.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/identify/consts.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/fetch/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/fetch/pb/proto.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/fetch/constants.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/ping/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/ping/constants.ts", "../node_modules/.pnpm/@achingbrain+nat-port-mapper@1.0.7/node_modules/@achingbrain/nat-port-mapper/src/browser.ts", "../node_modules/.pnpm/wherearewe@2.0.1/node_modules/wherearewe/src/index.js", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/nat-manager.ts", "../node_modules/.pnpm/is-loopback-addr@2.0.1/node_modules/is-loopback-addr/src/index.ts", "../node_modules/.pnpm/@libp2p+utils@3.0.4/node_modules/@libp2p/utils/src/multiaddr/is-loopback.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/peer-record-updater.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/dht/dht-peer-routing.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/address-book.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/errors.ts", "../node_modules/.pnpm/it-foreach@1.0.0/node_modules/it-foreach/src/index.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/key-book.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/metadata-book.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/proto-book.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/store.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/pb/peer.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/index.ts", "../node_modules/.pnpm/@libp2p+peer-store@6.0.0/node_modules/@libp2p/peer-store/src/pb/tags.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/dht/dht-content-routing.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/components.ts", "../node_modules/.pnpm/dns-over-http-resolver@2.1.1/node_modules/dns-over-http-resolver/src/index.ts", "../node_modules/.pnpm/native-fetch@4.0.2_undici@5.20.0/node_modules/native-fetch/esm/src/index.js", "../node_modules/.pnpm/dns-over-http-resolver@2.1.1/node_modules/dns-over-http-resolver/src/utils.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/resolvers/dns.browser.ts", "../node_modules/.pnpm/@multiformats+multiaddr@11.4.0/node_modules/@multiformats/multiaddr/src/resolvers/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/config.ts", "../node_modules/.pnpm/@libp2p+peer-id-factory@2.0.1/node_modules/@libp2p/peer-id-factory/src/proto.ts", "../node_modules/.pnpm/@libp2p+peer-id-factory@2.0.1/node_modules/@libp2p/peer-id-factory/src/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/libp2p.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/dht/dummy-dht.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/pubsub/dummy-pubsub.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection-manager/dialer/index.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/connection-manager/dialer/dial-request.ts", "../node_modules/.pnpm/libp2p@0.42.2/node_modules/libp2p/src/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/routing-table/index.ts", "../node_modules/.pnpm/private-ip@3.0.2/node_modules/private-ip/lib/index.js", "../node_modules/.pnpm/private-ip@3.0.2/node_modules/private-ip/index.js", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/constants.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/utils.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.2/node_modules/@libp2p/peer-collections/src/util.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.2/node_modules/@libp2p/peer-collections/src/map.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.2/node_modules/@libp2p/peer-collections/src/set.ts", "../node_modules/.pnpm/@libp2p+peer-collections@3.0.2/node_modules/@libp2p/peer-collections/src/list.ts", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/xor.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/routing-table/generated-prefix-list-browser.ts", "../node_modules/.pnpm/it-length@2.0.1/node_modules/it-length/src/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/routing-table/refresh.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/message/dht.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/message/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/query/events.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/network.ts", "../node_modules/.pnpm/@libp2p+record@3.0.4/node_modules/@libp2p/record/src/validators.ts", "../node_modules/.pnpm/@libp2p+record@3.0.4/node_modules/@libp2p/record/src/selectors.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/content-fetching/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/content-routing/index.ts", "../node_modules/.pnpm/uint8arrays@4.0.10/node_modules/uint8arrays/src/compare.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/peer-list/peer-distance-list.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/peer-routing/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/providers.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/query/manager.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/query/query-path.ts", "../node_modules/.pnpm/it-merge@2.0.1/node_modules/it-merge/src/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/handlers/add-provider.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/handlers/find-node.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/handlers/get-providers.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/handlers/get-value.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/handlers/ping.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/handlers/put-value.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/rpc/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/topology-listener.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/query-self.ts", "../node_modules/.pnpm/it-take@2.0.1/node_modules/it-take/src/index.ts", "../node_modules/.pnpm/@libp2p+interface-peer-discovery@1.1.1/node_modules/@libp2p/interface-peer-discovery/src/index.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/kad-dht.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/dual-kad-dht.ts", "../node_modules/.pnpm/@libp2p+kad-dht@7.0.3/node_modules/@libp2p/kad-dht/src/index.ts", "../node_modules/.pnpm/@libp2p+bootstrap@6.0.3/node_modules/@libp2p/bootstrap/src/index.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/web-socket.browser.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/source.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/ready.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/sink.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/duplex.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/ws-url.ts", "../node_modules/.pnpm/it-ws@5.0.6/node_modules/it-ws/src/client.ts", "../node_modules/.pnpm/@libp2p+websockets@5.0.10/node_modules/@libp2p/websockets/src/listener.browser.ts", "../node_modules/.pnpm/@libp2p+websockets@5.0.10/node_modules/@libp2p/websockets/src/socket-to-conn.ts", "../node_modules/.pnpm/@libp2p+websockets@5.0.10/node_modules/@libp2p/websockets/src/filters.ts", "../node_modules/.pnpm/@libp2p+interface-transport@2.1.3/node_modules/@libp2p/interface-transport/src/index.ts", "../node_modules/.pnpm/@libp2p+websockets@5.0.10/node_modules/@libp2p/websockets/src/index.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/encode.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/alloc-unsafe-browser.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/message-types.ts", "../node_modules/.pnpm/it-batched-bytes@1.0.1/node_modules/it-batched-bytes/src/index.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/decode.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/stream.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/mplex.ts", "../node_modules/.pnpm/@libp2p+mplex@7.1.7/node_modules/@libp2p/mplex/src/index.ts", "../node_modules/.pnpm/it-length-prefixed@9.1.0/node_modules/it-length-prefixed/src/utils.ts", "../node_modules/.pnpm/it-length-prefixed@9.1.0/node_modules/it-length-prefixed/src/encode.ts", "../node_modules/.pnpm/it-length-prefixed@9.1.0/node_modules/it-length-prefixed/src/errors.ts", "../node_modules/.pnpm/it-length-prefixed@9.1.0/node_modules/it-length-prefixed/src/decode.ts", "../node_modules/.pnpm/it-pb-stream@3.2.1/node_modules/it-pb-stream/src/index.ts", "../node_modules/.pnpm/it-pair@2.0.6/node_modules/it-pair/src/index.ts", "../node_modules/.pnpm/it-pair@2.0.6/node_modules/it-pair/src/duplex.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/constants.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/crypto/stablelib.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/crypto/streaming.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/encoder.ts", "../node_modules/.pnpm/@libp2p+interface-connection-encrypter@3.0.6/node_modules/@libp2p/interface-connection-encrypter/src/errors.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/proto/payload.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/utils.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/logger.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/nonce.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/handshakes/abstract-handshake.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/handshakes/xx.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/handshake-xx.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/metrics.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/noise.ts", "../node_modules/.pnpm/@chainsafe+libp2p-noise@11.0.4/node_modules/@chainsafe/libp2p-noise/src/index.ts", "../node_modules/.pnpm/@libp2p+peer-id-factory@2.0.4/node_modules/@libp2p/peer-id-factory/src/proto.ts", "../node_modules/.pnpm/@libp2p+peer-id-factory@2.0.4/node_modules/@libp2p/peer-id-factory/src/index.ts", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/storage.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/message/index.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/utils/varint-encoder.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/wantlist/entry.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/message/message.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/wantlist/index.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/message/entry.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/utils/index.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/constants.js", "../node_modules/.pnpm/just-debounce-it@3.2.0/node_modules/just-debounce-it/index.mjs", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/want-manager/msg-queue.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/want-manager/index.js", "../node_modules/.pnpm/@libp2p+topology@4.0.1/node_modules/@libp2p/topology/src/index.ts", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/network.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/decision-engine/ledger.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/utils/sorted-map.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/decision-engine/req-queue.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/decision-engine/task-merger.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/decision-engine/index.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/notifications.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/stats/index.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/stats/stat.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/bitswap.js", "../node_modules/.pnpm/ipfs-bitswap@15.0.2/node_modules/ipfs-bitswap/src/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/network.js", "../node_modules/.pnpm/blockstore-core@3.0.0/node_modules/blockstore-core/src/errors.js", "../node_modules/.pnpm/blockstore-core@3.0.0/node_modules/blockstore-core/src/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/block-storage.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/swarm/addrs.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/swarm/connect.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/swarm/disconnect.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/swarm/local-addrs.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/swarm/peers.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/swarm/index.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/ping.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/dht.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/components/pubsub.js", "../node_modules/.pnpm/ipfs-core@0.18.1_encoding@0.1.13/node_modules/ipfs-core/src/index.js", "../src/js/Entities/CID.ts", "../src/js/repositories/ipfs.ts", "../src/js/components/organisms/commander/commands.js", "../src/js/utils/keyListener.js", "../src/js/components/atoms/link/link.js", "../src/js/utils/dates.js", "../src/js/utils/isArraySorted.ts", "../src/js/components/organisms/commander/smartFilter.ts", "../src/js/registerServiceWorker.js", "../src/js/components/organisms/commander/commander.js", "../src/js/components/organisms/terminal.js", "../src/js/utils/text/index.ts", "../src/js/utils/text/autoCompleteCheckboxes.js", "../src/js/isSyncEnabled.js", "../src/js/utils/Trie/Trie.ts", "../src/js/utils/errorHandler.js", "../src/js/Functions/retrieveNoteFromIPFS.ts", "../src/js/listeners/urlChange.ts", "../src/js/utils/enableDevelopmentTasks.js", "../src/js/ui/markdown/preview/autoMagicallyCheckBoxes.js", "../src/js/main.js", "../src/index.js"], - "sourcesContent": ["/**\n * Created by Tivie on 13-07-2015.\n */\n\nfunction getDefaultOpts (simple) {\n 'use strict';\n\n var defaultOptions = {\n omitExtraWLInCodeBlocks: {\n defaultValue: false,\n describe: 'Omit the default extra whiteline added to code blocks',\n type: 'boolean'\n },\n noHeaderId: {\n defaultValue: false,\n describe: 'Turn on/off generated header id',\n type: 'boolean'\n },\n prefixHeaderId: {\n defaultValue: false,\n describe: 'Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic \\'section-\\' prefix',\n type: 'string'\n },\n rawPrefixHeaderId: {\n defaultValue: false,\n describe: 'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the \" char is used in the prefix)',\n type: 'boolean'\n },\n ghCompatibleHeaderId: {\n defaultValue: false,\n describe: 'Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)',\n type: 'boolean'\n },\n rawHeaderId: {\n defaultValue: false,\n describe: 'Remove only spaces, \\' and \" from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids',\n type: 'boolean'\n },\n headerLevelStart: {\n defaultValue: false,\n describe: 'The header blocks level start',\n type: 'integer'\n },\n parseImgDimensions: {\n defaultValue: false,\n describe: 'Turn on/off image dimension parsing',\n type: 'boolean'\n },\n simplifiedAutoLink: {\n defaultValue: false,\n describe: 'Turn on/off GFM autolink style',\n type: 'boolean'\n },\n excludeTrailingPunctuationFromURLs: {\n defaultValue: false,\n describe: 'Excludes trailing punctuation from links generated with autoLinking',\n type: 'boolean'\n },\n literalMidWordUnderscores: {\n defaultValue: false,\n describe: 'Parse midword underscores as literal underscores',\n type: 'boolean'\n },\n literalMidWordAsterisks: {\n defaultValue: false,\n describe: 'Parse midword asterisks as literal asterisks',\n type: 'boolean'\n },\n strikethrough: {\n defaultValue: false,\n describe: 'Turn on/off strikethrough support',\n type: 'boolean'\n },\n tables: {\n defaultValue: false,\n describe: 'Turn on/off tables support',\n type: 'boolean'\n },\n tablesHeaderId: {\n defaultValue: false,\n describe: 'Add an id to table headers',\n type: 'boolean'\n },\n ghCodeBlocks: {\n defaultValue: true,\n describe: 'Turn on/off GFM fenced code blocks support',\n type: 'boolean'\n },\n tasklists: {\n defaultValue: false,\n describe: 'Turn on/off GFM tasklist support',\n type: 'boolean'\n },\n smoothLivePreview: {\n defaultValue: false,\n describe: 'Prevents weird effects in live previews due to incomplete input',\n type: 'boolean'\n },\n smartIndentationFix: {\n defaultValue: false,\n describe: 'Tries to smartly fix indentation in es6 strings',\n type: 'boolean'\n },\n disableForced4SpacesIndentedSublists: {\n defaultValue: false,\n describe: 'Disables the requirement of indenting nested sublists by 4 spaces',\n type: 'boolean'\n },\n simpleLineBreaks: {\n defaultValue: false,\n describe: 'Parses simple line breaks as
(GFM Style)',\n type: 'boolean'\n },\n requireSpaceBeforeHeadingText: {\n defaultValue: false,\n describe: 'Makes adding a space between `#` and the header text mandatory (GFM Style)',\n type: 'boolean'\n },\n ghMentions: {\n defaultValue: false,\n describe: 'Enables github @mentions',\n type: 'boolean'\n },\n ghMentionsLink: {\n defaultValue: 'https://github.com/{u}',\n describe: 'Changes the link generated by @mentions. Only applies if ghMentions option is enabled.',\n type: 'string'\n },\n encodeEmails: {\n defaultValue: true,\n describe: 'Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities',\n type: 'boolean'\n },\n openLinksInNewWindow: {\n defaultValue: false,\n describe: 'Open all links in new windows',\n type: 'boolean'\n },\n backslashEscapesHTMLTags: {\n defaultValue: false,\n describe: 'Support for HTML Tag escaping. ex: \\

foo\\
',\n type: 'boolean'\n },\n emoji: {\n defaultValue: false,\n describe: 'Enable emoji support. Ex: `this is a :smile: emoji`',\n type: 'boolean'\n },\n underline: {\n defaultValue: false,\n describe: 'Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `` and ``',\n type: 'boolean'\n },\n ellipsis: {\n defaultValue: true,\n describe: 'Replaces three dots with the ellipsis unicode character',\n type: 'boolean'\n },\n completeHTMLDocument: {\n defaultValue: false,\n describe: 'Outputs a complete html document, including ``, `` and `` tags',\n type: 'boolean'\n },\n metadata: {\n defaultValue: false,\n describe: 'Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).',\n type: 'boolean'\n },\n splitAdjacentBlockquotes: {\n defaultValue: false,\n describe: 'Split adjacent blockquote blocks',\n type: 'boolean'\n }\n };\n if (simple === false) {\n return JSON.parse(JSON.stringify(defaultOptions));\n }\n var ret = {};\n for (var opt in defaultOptions) {\n if (defaultOptions.hasOwnProperty(opt)) {\n ret[opt] = defaultOptions[opt].defaultValue;\n }\n }\n return ret;\n}\n\nfunction allOptionsOn () {\n 'use strict';\n var options = getDefaultOpts(true),\n ret = {};\n for (var opt in options) {\n if (options.hasOwnProperty(opt)) {\n ret[opt] = true;\n }\n }\n return ret;\n}\n", "/**\n * Created by Tivie on 06-01-2015.\n */\n\n// Private properties\nvar showdown = {},\n parsers = {},\n extensions = {},\n globalOptions = getDefaultOpts(true),\n setFlavor = 'vanilla',\n flavor = {\n github: {\n omitExtraWLInCodeBlocks: true,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true,\n literalMidWordUnderscores: true,\n strikethrough: true,\n tables: true,\n tablesHeaderId: true,\n ghCodeBlocks: true,\n tasklists: true,\n disableForced4SpacesIndentedSublists: true,\n simpleLineBreaks: true,\n requireSpaceBeforeHeadingText: true,\n ghCompatibleHeaderId: true,\n ghMentions: true,\n backslashEscapesHTMLTags: true,\n emoji: true,\n splitAdjacentBlockquotes: true\n },\n original: {\n noHeaderId: true,\n ghCodeBlocks: false\n },\n ghost: {\n omitExtraWLInCodeBlocks: true,\n parseImgDimensions: true,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true,\n literalMidWordUnderscores: true,\n strikethrough: true,\n tables: true,\n tablesHeaderId: true,\n ghCodeBlocks: true,\n tasklists: true,\n smoothLivePreview: true,\n simpleLineBreaks: true,\n requireSpaceBeforeHeadingText: true,\n ghMentions: false,\n encodeEmails: true\n },\n vanilla: getDefaultOpts(true),\n allOn: allOptionsOn()\n };\n\n/**\n * helper namespace\n * @type {{}}\n */\nshowdown.helper = {};\n\n/**\n * TODO LEGACY SUPPORT CODE\n * @type {{}}\n */\nshowdown.extensions = {};\n\n/**\n * Set a global option\n * @static\n * @param {string} key\n * @param {*} value\n * @returns {showdown}\n */\nshowdown.setOption = function (key, value) {\n 'use strict';\n globalOptions[key] = value;\n return this;\n};\n\n/**\n * Get a global option\n * @static\n * @param {string} key\n * @returns {*}\n */\nshowdown.getOption = function (key) {\n 'use strict';\n return globalOptions[key];\n};\n\n/**\n * Get the global options\n * @static\n * @returns {{}}\n */\nshowdown.getOptions = function () {\n 'use strict';\n return globalOptions;\n};\n\n/**\n * Reset global options to the default values\n * @static\n */\nshowdown.resetOptions = function () {\n 'use strict';\n globalOptions = getDefaultOpts(true);\n};\n\n/**\n * Set the flavor showdown should use as default\n * @param {string} name\n */\nshowdown.setFlavor = function (name) {\n 'use strict';\n if (!flavor.hasOwnProperty(name)) {\n throw Error(name + ' flavor was not found');\n }\n showdown.resetOptions();\n var preset = flavor[name];\n setFlavor = name;\n for (var option in preset) {\n if (preset.hasOwnProperty(option)) {\n globalOptions[option] = preset[option];\n }\n }\n};\n\n/**\n * Get the currently set flavor\n * @returns {string}\n */\nshowdown.getFlavor = function () {\n 'use strict';\n return setFlavor;\n};\n\n/**\n * Get the options of a specified flavor. Returns undefined if the flavor was not found\n * @param {string} name Name of the flavor\n * @returns {{}|undefined}\n */\nshowdown.getFlavorOptions = function (name) {\n 'use strict';\n if (flavor.hasOwnProperty(name)) {\n return flavor[name];\n }\n};\n\n/**\n * Get the default options\n * @static\n * @param {boolean} [simple=true]\n * @returns {{}}\n */\nshowdown.getDefaultOptions = function (simple) {\n 'use strict';\n return getDefaultOpts(simple);\n};\n\n/**\n * Get or set a subParser\n *\n * subParser(name) - Get a registered subParser\n * subParser(name, func) - Register a subParser\n * @static\n * @param {string} name\n * @param {function} [func]\n * @returns {*}\n */\nshowdown.subParser = function (name, func) {\n 'use strict';\n if (showdown.helper.isString(name)) {\n if (typeof func !== 'undefined') {\n parsers[name] = func;\n } else {\n if (parsers.hasOwnProperty(name)) {\n return parsers[name];\n } else {\n throw Error('SubParser named ' + name + ' not registered!');\n }\n }\n }\n};\n\n/**\n * Gets or registers an extension\n * @static\n * @param {string} name\n * @param {object|object[]|function=} ext\n * @returns {*}\n */\nshowdown.extension = function (name, ext) {\n 'use strict';\n\n if (!showdown.helper.isString(name)) {\n throw Error('Extension \\'name\\' must be a string');\n }\n\n name = showdown.helper.stdExtName(name);\n\n // Getter\n if (showdown.helper.isUndefined(ext)) {\n if (!extensions.hasOwnProperty(name)) {\n throw Error('Extension named ' + name + ' is not registered!');\n }\n return extensions[name];\n\n // Setter\n } else {\n // Expand extension if it's wrapped in a function\n if (typeof ext === 'function') {\n ext = ext();\n }\n\n // Ensure extension is an array\n if (!showdown.helper.isArray(ext)) {\n ext = [ext];\n }\n\n var validExtension = validate(ext, name);\n\n if (validExtension.valid) {\n extensions[name] = ext;\n } else {\n throw Error(validExtension.error);\n }\n }\n};\n\n/**\n * Gets all extensions registered\n * @returns {{}}\n */\nshowdown.getAllExtensions = function () {\n 'use strict';\n return extensions;\n};\n\n/**\n * Remove an extension\n * @param {string} name\n */\nshowdown.removeExtension = function (name) {\n 'use strict';\n delete extensions[name];\n};\n\n/**\n * Removes all extensions\n */\nshowdown.resetExtensions = function () {\n 'use strict';\n extensions = {};\n};\n\n/**\n * Validate extension\n * @param {array} extension\n * @param {string} name\n * @returns {{valid: boolean, error: string}}\n */\nfunction validate (extension, name) {\n 'use strict';\n\n var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',\n ret = {\n valid: true,\n error: ''\n };\n\n if (!showdown.helper.isArray(extension)) {\n extension = [extension];\n }\n\n for (var i = 0; i < extension.length; ++i) {\n var baseMsg = errMsg + ' sub-extension ' + i + ': ',\n ext = extension[i];\n if (typeof ext !== 'object') {\n ret.valid = false;\n ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';\n return ret;\n }\n\n if (!showdown.helper.isString(ext.type)) {\n ret.valid = false;\n ret.error = baseMsg + 'property \"type\" must be a string, but ' + typeof ext.type + ' given';\n return ret;\n }\n\n var type = ext.type = ext.type.toLowerCase();\n\n // normalize extension type\n if (type === 'language') {\n type = ext.type = 'lang';\n }\n\n if (type === 'html') {\n type = ext.type = 'output';\n }\n\n if (type !== 'lang' && type !== 'output' && type !== 'listener') {\n ret.valid = false;\n ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: \"lang/language\", \"output/html\" or \"listener\"';\n return ret;\n }\n\n if (type === 'listener') {\n if (showdown.helper.isUndefined(ext.listeners)) {\n ret.valid = false;\n ret.error = baseMsg + '. Extensions of type \"listener\" must have a property called \"listeners\"';\n return ret;\n }\n } else {\n if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {\n ret.valid = false;\n ret.error = baseMsg + type + ' extensions must define either a \"regex\" property or a \"filter\" method';\n return ret;\n }\n }\n\n if (ext.listeners) {\n if (typeof ext.listeners !== 'object') {\n ret.valid = false;\n ret.error = baseMsg + '\"listeners\" property must be an object but ' + typeof ext.listeners + ' given';\n return ret;\n }\n for (var ln in ext.listeners) {\n if (ext.listeners.hasOwnProperty(ln)) {\n if (typeof ext.listeners[ln] !== 'function') {\n ret.valid = false;\n ret.error = baseMsg + '\"listeners\" property must be an hash of [event name]: [callback]. listeners.' + ln +\n ' must be a function but ' + typeof ext.listeners[ln] + ' given';\n return ret;\n }\n }\n }\n }\n\n if (ext.filter) {\n if (typeof ext.filter !== 'function') {\n ret.valid = false;\n ret.error = baseMsg + '\"filter\" must be a function, but ' + typeof ext.filter + ' given';\n return ret;\n }\n } else if (ext.regex) {\n if (showdown.helper.isString(ext.regex)) {\n ext.regex = new RegExp(ext.regex, 'g');\n }\n if (!(ext.regex instanceof RegExp)) {\n ret.valid = false;\n ret.error = baseMsg + '\"regex\" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';\n return ret;\n }\n if (showdown.helper.isUndefined(ext.replace)) {\n ret.valid = false;\n ret.error = baseMsg + '\"regex\" extensions must implement a replace string or function';\n return ret;\n }\n }\n }\n return ret;\n}\n\n/**\n * Validate extension\n * @param {object} ext\n * @returns {boolean}\n */\nshowdown.validateExtension = function (ext) {\n 'use strict';\n\n var validateExtension = validate(ext, null);\n if (!validateExtension.valid) {\n console.warn(validateExtension.error);\n return false;\n }\n return true;\n};\n", "/**\n * showdownjs helper functions\n */\n\nif (!showdown.hasOwnProperty('helper')) {\n showdown.helper = {};\n}\n\n/**\n * Check if var is string\n * @static\n * @param {string} a\n * @returns {boolean}\n */\nshowdown.helper.isString = function (a) {\n 'use strict';\n return (typeof a === 'string' || a instanceof String);\n};\n\n/**\n * Check if var is a function\n * @static\n * @param {*} a\n * @returns {boolean}\n */\nshowdown.helper.isFunction = function (a) {\n 'use strict';\n var getType = {};\n return a && getType.toString.call(a) === '[object Function]';\n};\n\n/**\n * isArray helper function\n * @static\n * @param {*} a\n * @returns {boolean}\n */\nshowdown.helper.isArray = function (a) {\n 'use strict';\n return Array.isArray(a);\n};\n\n/**\n * Check if value is undefined\n * @static\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n */\nshowdown.helper.isUndefined = function (value) {\n 'use strict';\n return typeof value === 'undefined';\n};\n\n/**\n * ForEach helper function\n * Iterates over Arrays and Objects (own properties only)\n * @static\n * @param {*} obj\n * @param {function} callback Accepts 3 params: 1. value, 2. key, 3. the original array/object\n */\nshowdown.helper.forEach = function (obj, callback) {\n 'use strict';\n // check if obj is defined\n if (showdown.helper.isUndefined(obj)) {\n throw new Error('obj param is required');\n }\n\n if (showdown.helper.isUndefined(callback)) {\n throw new Error('callback param is required');\n }\n\n if (!showdown.helper.isFunction(callback)) {\n throw new Error('callback param must be a function/closure');\n }\n\n if (typeof obj.forEach === 'function') {\n obj.forEach(callback);\n } else if (showdown.helper.isArray(obj)) {\n for (var i = 0; i < obj.length; i++) {\n callback(obj[i], i, obj);\n }\n } else if (typeof (obj) === 'object') {\n for (var prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n callback(obj[prop], prop, obj);\n }\n }\n } else {\n throw new Error('obj does not seem to be an array or an iterable object');\n }\n};\n\n/**\n * Standardidize extension name\n * @static\n * @param {string} s extension name\n * @returns {string}\n */\nshowdown.helper.stdExtName = function (s) {\n 'use strict';\n return s.replace(/[_?*+\\/\\\\.^-]/g, '').replace(/\\s/g, '').toLowerCase();\n};\n\nfunction escapeCharactersCallback (wholeMatch, m1) {\n 'use strict';\n var charCodeToEscape = m1.charCodeAt(0);\n return '¨E' + charCodeToEscape + 'E';\n}\n\n/**\n * Callback used to escape characters when passing through String.replace\n * @static\n * @param {string} wholeMatch\n * @param {string} m1\n * @returns {string}\n */\nshowdown.helper.escapeCharactersCallback = escapeCharactersCallback;\n\n/**\n * Escape characters in a string\n * @static\n * @param {string} text\n * @param {string} charsToEscape\n * @param {boolean} afterBackslash\n * @returns {XML|string|void|*}\n */\nshowdown.helper.escapeCharacters = function (text, charsToEscape, afterBackslash) {\n 'use strict';\n // First we have to escape the escape characters so that\n // we can build a character class out of them\n var regexString = '([' + charsToEscape.replace(/([\\[\\]\\\\])/g, '\\\\$1') + '])';\n\n if (afterBackslash) {\n regexString = '\\\\\\\\' + regexString;\n }\n\n var regex = new RegExp(regexString, 'g');\n text = text.replace(regex, escapeCharactersCallback);\n\n return text;\n};\n\n/**\n * Unescape HTML entities\n * @param txt\n * @returns {string}\n */\nshowdown.helper.unescapeHTMLEntities = function (txt) {\n 'use strict';\n\n return txt\n .replace(/"/g, '\"')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/&/g, '&');\n};\n\nvar rgxFindMatchPos = function (str, left, right, flags) {\n 'use strict';\n var f = flags || '',\n g = f.indexOf('g') > -1,\n x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),\n l = new RegExp(left, f.replace(/g/g, '')),\n pos = [],\n t, s, m, start, end;\n\n do {\n t = 0;\n while ((m = x.exec(str))) {\n if (l.test(m[0])) {\n if (!(t++)) {\n s = x.lastIndex;\n start = s - m[0].length;\n }\n } else if (t) {\n if (!--t) {\n end = m.index + m[0].length;\n var obj = {\n left: {start: start, end: s},\n match: {start: s, end: m.index},\n right: {start: m.index, end: end},\n wholeMatch: {start: start, end: end}\n };\n pos.push(obj);\n if (!g) {\n return pos;\n }\n }\n }\n }\n } while (t && (x.lastIndex = s));\n\n return pos;\n};\n\n/**\n * matchRecursiveRegExp\n *\n * (c) 2007 Steven Levithan \n * MIT License\n *\n * Accepts a string to search, a left and right format delimiter\n * as regex patterns, and optional regex flags. Returns an array\n * of matches, allowing nested instances of left/right delimiters.\n * Use the \"g\" flag to return all matches, otherwise only the\n * first is returned. Be careful to ensure that the left and\n * right format delimiters produce mutually exclusive matches.\n * Backreferences are not supported within the right delimiter\n * due to how it is internally combined with the left delimiter.\n * When matching strings whose format delimiters are unbalanced\n * to the left or right, the output is intentionally as a\n * conventional regex library with recursion support would\n * produce, e.g. \"<\" and \">\" both produce [\"x\"] when using\n * \"<\" and \">\" as the delimiters (both strings contain a single,\n * balanced instance of \"\").\n *\n * examples:\n * matchRecursiveRegExp(\"test\", \"\\\\(\", \"\\\\)\")\n * returns: []\n * matchRecursiveRegExp(\">>t<>\", \"<\", \">\", \"g\")\n * returns: [\"t<>\", \"\"]\n * matchRecursiveRegExp(\"
test
\", \"]*>\", \"\", \"gi\")\n * returns: [\"test\"]\n */\nshowdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {\n 'use strict';\n\n var matchPos = rgxFindMatchPos (str, left, right, flags),\n results = [];\n\n for (var i = 0; i < matchPos.length; ++i) {\n results.push([\n str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),\n str.slice(matchPos[i].match.start, matchPos[i].match.end),\n str.slice(matchPos[i].left.start, matchPos[i].left.end),\n str.slice(matchPos[i].right.start, matchPos[i].right.end)\n ]);\n }\n return results;\n};\n\n/**\n *\n * @param {string} str\n * @param {string|function} replacement\n * @param {string} left\n * @param {string} right\n * @param {string} flags\n * @returns {string}\n */\nshowdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {\n 'use strict';\n\n if (!showdown.helper.isFunction(replacement)) {\n var repStr = replacement;\n replacement = function () {\n return repStr;\n };\n }\n\n var matchPos = rgxFindMatchPos(str, left, right, flags),\n finalStr = str,\n lng = matchPos.length;\n\n if (lng > 0) {\n var bits = [];\n if (matchPos[0].wholeMatch.start !== 0) {\n bits.push(str.slice(0, matchPos[0].wholeMatch.start));\n }\n for (var i = 0; i < lng; ++i) {\n bits.push(\n replacement(\n str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),\n str.slice(matchPos[i].match.start, matchPos[i].match.end),\n str.slice(matchPos[i].left.start, matchPos[i].left.end),\n str.slice(matchPos[i].right.start, matchPos[i].right.end)\n )\n );\n if (i < lng - 1) {\n bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));\n }\n }\n if (matchPos[lng - 1].wholeMatch.end < str.length) {\n bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));\n }\n finalStr = bits.join('');\n }\n return finalStr;\n};\n\n/**\n * Returns the index within the passed String object of the first occurrence of the specified regex,\n * starting the search at fromIndex. Returns -1 if the value is not found.\n *\n * @param {string} str string to search\n * @param {RegExp} regex Regular expression to search\n * @param {int} [fromIndex = 0] Index to start the search\n * @returns {Number}\n * @throws InvalidArgumentError\n */\nshowdown.helper.regexIndexOf = function (str, regex, fromIndex) {\n 'use strict';\n if (!showdown.helper.isString(str)) {\n throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';\n }\n if (regex instanceof RegExp === false) {\n throw 'InvalidArgumentError: second parameter of showdown.helper.regexIndexOf function must be an instance of RegExp';\n }\n var indexOf = str.substring(fromIndex || 0).search(regex);\n return (indexOf >= 0) ? (indexOf + (fromIndex || 0)) : indexOf;\n};\n\n/**\n * Splits the passed string object at the defined index, and returns an array composed of the two substrings\n * @param {string} str string to split\n * @param {int} index index to split string at\n * @returns {[string,string]}\n * @throws InvalidArgumentError\n */\nshowdown.helper.splitAtIndex = function (str, index) {\n 'use strict';\n if (!showdown.helper.isString(str)) {\n throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';\n }\n return [str.substring(0, index), str.substring(index)];\n};\n\n/**\n * Obfuscate an e-mail address through the use of Character Entities,\n * transforming ASCII characters into their equivalent decimal or hex entities.\n *\n * Since it has a random component, subsequent calls to this function produce different results\n *\n * @param {string} mail\n * @returns {string}\n */\nshowdown.helper.encodeEmailAddress = function (mail) {\n 'use strict';\n var encode = [\n function (ch) {\n return '&#' + ch.charCodeAt(0) + ';';\n },\n function (ch) {\n return '&#x' + ch.charCodeAt(0).toString(16) + ';';\n },\n function (ch) {\n return ch;\n }\n ];\n\n mail = mail.replace(/./g, function (ch) {\n if (ch === '@') {\n // this *must* be encoded. I insist.\n ch = encode[Math.floor(Math.random() * 2)](ch);\n } else {\n var r = Math.random();\n // roughly 10% raw, 45% hex, 45% dec\n ch = (\n r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)\n );\n }\n return ch;\n });\n\n return mail;\n};\n\n/**\n *\n * @param str\n * @param targetLength\n * @param padString\n * @returns {string}\n */\nshowdown.helper.padEnd = function padEnd (str, targetLength, padString) {\n 'use strict';\n /*jshint bitwise: false*/\n // eslint-disable-next-line space-infix-ops\n targetLength = targetLength>>0; //floor if number or convert non-number to 0;\n /*jshint bitwise: true*/\n padString = String(padString || ' ');\n if (str.length > targetLength) {\n return String(str);\n } else {\n targetLength = targetLength - str.length;\n if (targetLength > padString.length) {\n padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed\n }\n return String(str) + padString.slice(0,targetLength);\n }\n};\n\n/**\n * POLYFILLS\n */\n// use this instead of builtin is undefined for IE8 compatibility\nif (typeof (console) === 'undefined') {\n console = {\n warn: function (msg) {\n 'use strict';\n alert(msg);\n },\n log: function (msg) {\n 'use strict';\n alert(msg);\n },\n error: function (msg) {\n 'use strict';\n throw msg;\n }\n };\n}\n\n/**\n * Common regexes.\n * We declare some common regexes to improve performance\n */\nshowdown.helper.regexes = {\n asteriskDashAndColon: /([*_:~])/g\n};\n\n/**\n * EMOJIS LIST\n */\nshowdown.helper.emojis = {\n '+1':'\\ud83d\\udc4d',\n '-1':'\\ud83d\\udc4e',\n '100':'\\ud83d\\udcaf',\n '1234':'\\ud83d\\udd22',\n '1st_place_medal':'\\ud83e\\udd47',\n '2nd_place_medal':'\\ud83e\\udd48',\n '3rd_place_medal':'\\ud83e\\udd49',\n '8ball':'\\ud83c\\udfb1',\n 'a':'\\ud83c\\udd70\\ufe0f',\n 'ab':'\\ud83c\\udd8e',\n 'abc':'\\ud83d\\udd24',\n 'abcd':'\\ud83d\\udd21',\n 'accept':'\\ud83c\\ude51',\n 'aerial_tramway':'\\ud83d\\udea1',\n 'airplane':'\\u2708\\ufe0f',\n 'alarm_clock':'\\u23f0',\n 'alembic':'\\u2697\\ufe0f',\n 'alien':'\\ud83d\\udc7d',\n 'ambulance':'\\ud83d\\ude91',\n 'amphora':'\\ud83c\\udffa',\n 'anchor':'\\u2693\\ufe0f',\n 'angel':'\\ud83d\\udc7c',\n 'anger':'\\ud83d\\udca2',\n 'angry':'\\ud83d\\ude20',\n 'anguished':'\\ud83d\\ude27',\n 'ant':'\\ud83d\\udc1c',\n 'apple':'\\ud83c\\udf4e',\n 'aquarius':'\\u2652\\ufe0f',\n 'aries':'\\u2648\\ufe0f',\n 'arrow_backward':'\\u25c0\\ufe0f',\n 'arrow_double_down':'\\u23ec',\n 'arrow_double_up':'\\u23eb',\n 'arrow_down':'\\u2b07\\ufe0f',\n 'arrow_down_small':'\\ud83d\\udd3d',\n 'arrow_forward':'\\u25b6\\ufe0f',\n 'arrow_heading_down':'\\u2935\\ufe0f',\n 'arrow_heading_up':'\\u2934\\ufe0f',\n 'arrow_left':'\\u2b05\\ufe0f',\n 'arrow_lower_left':'\\u2199\\ufe0f',\n 'arrow_lower_right':'\\u2198\\ufe0f',\n 'arrow_right':'\\u27a1\\ufe0f',\n 'arrow_right_hook':'\\u21aa\\ufe0f',\n 'arrow_up':'\\u2b06\\ufe0f',\n 'arrow_up_down':'\\u2195\\ufe0f',\n 'arrow_up_small':'\\ud83d\\udd3c',\n 'arrow_upper_left':'\\u2196\\ufe0f',\n 'arrow_upper_right':'\\u2197\\ufe0f',\n 'arrows_clockwise':'\\ud83d\\udd03',\n 'arrows_counterclockwise':'\\ud83d\\udd04',\n 'art':'\\ud83c\\udfa8',\n 'articulated_lorry':'\\ud83d\\ude9b',\n 'artificial_satellite':'\\ud83d\\udef0',\n 'astonished':'\\ud83d\\ude32',\n 'athletic_shoe':'\\ud83d\\udc5f',\n 'atm':'\\ud83c\\udfe7',\n 'atom_symbol':'\\u269b\\ufe0f',\n 'avocado':'\\ud83e\\udd51',\n 'b':'\\ud83c\\udd71\\ufe0f',\n 'baby':'\\ud83d\\udc76',\n 'baby_bottle':'\\ud83c\\udf7c',\n 'baby_chick':'\\ud83d\\udc24',\n 'baby_symbol':'\\ud83d\\udebc',\n 'back':'\\ud83d\\udd19',\n 'bacon':'\\ud83e\\udd53',\n 'badminton':'\\ud83c\\udff8',\n 'baggage_claim':'\\ud83d\\udec4',\n 'baguette_bread':'\\ud83e\\udd56',\n 'balance_scale':'\\u2696\\ufe0f',\n 'balloon':'\\ud83c\\udf88',\n 'ballot_box':'\\ud83d\\uddf3',\n 'ballot_box_with_check':'\\u2611\\ufe0f',\n 'bamboo':'\\ud83c\\udf8d',\n 'banana':'\\ud83c\\udf4c',\n 'bangbang':'\\u203c\\ufe0f',\n 'bank':'\\ud83c\\udfe6',\n 'bar_chart':'\\ud83d\\udcca',\n 'barber':'\\ud83d\\udc88',\n 'baseball':'\\u26be\\ufe0f',\n 'basketball':'\\ud83c\\udfc0',\n 'basketball_man':'\\u26f9\\ufe0f',\n 'basketball_woman':'\\u26f9\\ufe0f‍\\u2640\\ufe0f',\n 'bat':'\\ud83e\\udd87',\n 'bath':'\\ud83d\\udec0',\n 'bathtub':'\\ud83d\\udec1',\n 'battery':'\\ud83d\\udd0b',\n 'beach_umbrella':'\\ud83c\\udfd6',\n 'bear':'\\ud83d\\udc3b',\n 'bed':'\\ud83d\\udecf',\n 'bee':'\\ud83d\\udc1d',\n 'beer':'\\ud83c\\udf7a',\n 'beers':'\\ud83c\\udf7b',\n 'beetle':'\\ud83d\\udc1e',\n 'beginner':'\\ud83d\\udd30',\n 'bell':'\\ud83d\\udd14',\n 'bellhop_bell':'\\ud83d\\udece',\n 'bento':'\\ud83c\\udf71',\n 'biking_man':'\\ud83d\\udeb4',\n 'bike':'\\ud83d\\udeb2',\n 'biking_woman':'\\ud83d\\udeb4‍\\u2640\\ufe0f',\n 'bikini':'\\ud83d\\udc59',\n 'biohazard':'\\u2623\\ufe0f',\n 'bird':'\\ud83d\\udc26',\n 'birthday':'\\ud83c\\udf82',\n 'black_circle':'\\u26ab\\ufe0f',\n 'black_flag':'\\ud83c\\udff4',\n 'black_heart':'\\ud83d\\udda4',\n 'black_joker':'\\ud83c\\udccf',\n 'black_large_square':'\\u2b1b\\ufe0f',\n 'black_medium_small_square':'\\u25fe\\ufe0f',\n 'black_medium_square':'\\u25fc\\ufe0f',\n 'black_nib':'\\u2712\\ufe0f',\n 'black_small_square':'\\u25aa\\ufe0f',\n 'black_square_button':'\\ud83d\\udd32',\n 'blonde_man':'\\ud83d\\udc71',\n 'blonde_woman':'\\ud83d\\udc71‍\\u2640\\ufe0f',\n 'blossom':'\\ud83c\\udf3c',\n 'blowfish':'\\ud83d\\udc21',\n 'blue_book':'\\ud83d\\udcd8',\n 'blue_car':'\\ud83d\\ude99',\n 'blue_heart':'\\ud83d\\udc99',\n 'blush':'\\ud83d\\ude0a',\n 'boar':'\\ud83d\\udc17',\n 'boat':'\\u26f5\\ufe0f',\n 'bomb':'\\ud83d\\udca3',\n 'book':'\\ud83d\\udcd6',\n 'bookmark':'\\ud83d\\udd16',\n 'bookmark_tabs':'\\ud83d\\udcd1',\n 'books':'\\ud83d\\udcda',\n 'boom':'\\ud83d\\udca5',\n 'boot':'\\ud83d\\udc62',\n 'bouquet':'\\ud83d\\udc90',\n 'bowing_man':'\\ud83d\\ude47',\n 'bow_and_arrow':'\\ud83c\\udff9',\n 'bowing_woman':'\\ud83d\\ude47‍\\u2640\\ufe0f',\n 'bowling':'\\ud83c\\udfb3',\n 'boxing_glove':'\\ud83e\\udd4a',\n 'boy':'\\ud83d\\udc66',\n 'bread':'\\ud83c\\udf5e',\n 'bride_with_veil':'\\ud83d\\udc70',\n 'bridge_at_night':'\\ud83c\\udf09',\n 'briefcase':'\\ud83d\\udcbc',\n 'broken_heart':'\\ud83d\\udc94',\n 'bug':'\\ud83d\\udc1b',\n 'building_construction':'\\ud83c\\udfd7',\n 'bulb':'\\ud83d\\udca1',\n 'bullettrain_front':'\\ud83d\\ude85',\n 'bullettrain_side':'\\ud83d\\ude84',\n 'burrito':'\\ud83c\\udf2f',\n 'bus':'\\ud83d\\ude8c',\n 'business_suit_levitating':'\\ud83d\\udd74',\n 'busstop':'\\ud83d\\ude8f',\n 'bust_in_silhouette':'\\ud83d\\udc64',\n 'busts_in_silhouette':'\\ud83d\\udc65',\n 'butterfly':'\\ud83e\\udd8b',\n 'cactus':'\\ud83c\\udf35',\n 'cake':'\\ud83c\\udf70',\n 'calendar':'\\ud83d\\udcc6',\n 'call_me_hand':'\\ud83e\\udd19',\n 'calling':'\\ud83d\\udcf2',\n 'camel':'\\ud83d\\udc2b',\n 'camera':'\\ud83d\\udcf7',\n 'camera_flash':'\\ud83d\\udcf8',\n 'camping':'\\ud83c\\udfd5',\n 'cancer':'\\u264b\\ufe0f',\n 'candle':'\\ud83d\\udd6f',\n 'candy':'\\ud83c\\udf6c',\n 'canoe':'\\ud83d\\udef6',\n 'capital_abcd':'\\ud83d\\udd20',\n 'capricorn':'\\u2651\\ufe0f',\n 'car':'\\ud83d\\ude97',\n 'card_file_box':'\\ud83d\\uddc3',\n 'card_index':'\\ud83d\\udcc7',\n 'card_index_dividers':'\\ud83d\\uddc2',\n 'carousel_horse':'\\ud83c\\udfa0',\n 'carrot':'\\ud83e\\udd55',\n 'cat':'\\ud83d\\udc31',\n 'cat2':'\\ud83d\\udc08',\n 'cd':'\\ud83d\\udcbf',\n 'chains':'\\u26d3',\n 'champagne':'\\ud83c\\udf7e',\n 'chart':'\\ud83d\\udcb9',\n 'chart_with_downwards_trend':'\\ud83d\\udcc9',\n 'chart_with_upwards_trend':'\\ud83d\\udcc8',\n 'checkered_flag':'\\ud83c\\udfc1',\n 'cheese':'\\ud83e\\uddc0',\n 'cherries':'\\ud83c\\udf52',\n 'cherry_blossom':'\\ud83c\\udf38',\n 'chestnut':'\\ud83c\\udf30',\n 'chicken':'\\ud83d\\udc14',\n 'children_crossing':'\\ud83d\\udeb8',\n 'chipmunk':'\\ud83d\\udc3f',\n 'chocolate_bar':'\\ud83c\\udf6b',\n 'christmas_tree':'\\ud83c\\udf84',\n 'church':'\\u26ea\\ufe0f',\n 'cinema':'\\ud83c\\udfa6',\n 'circus_tent':'\\ud83c\\udfaa',\n 'city_sunrise':'\\ud83c\\udf07',\n 'city_sunset':'\\ud83c\\udf06',\n 'cityscape':'\\ud83c\\udfd9',\n 'cl':'\\ud83c\\udd91',\n 'clamp':'\\ud83d\\udddc',\n 'clap':'\\ud83d\\udc4f',\n 'clapper':'\\ud83c\\udfac',\n 'classical_building':'\\ud83c\\udfdb',\n 'clinking_glasses':'\\ud83e\\udd42',\n 'clipboard':'\\ud83d\\udccb',\n 'clock1':'\\ud83d\\udd50',\n 'clock10':'\\ud83d\\udd59',\n 'clock1030':'\\ud83d\\udd65',\n 'clock11':'\\ud83d\\udd5a',\n 'clock1130':'\\ud83d\\udd66',\n 'clock12':'\\ud83d\\udd5b',\n 'clock1230':'\\ud83d\\udd67',\n 'clock130':'\\ud83d\\udd5c',\n 'clock2':'\\ud83d\\udd51',\n 'clock230':'\\ud83d\\udd5d',\n 'clock3':'\\ud83d\\udd52',\n 'clock330':'\\ud83d\\udd5e',\n 'clock4':'\\ud83d\\udd53',\n 'clock430':'\\ud83d\\udd5f',\n 'clock5':'\\ud83d\\udd54',\n 'clock530':'\\ud83d\\udd60',\n 'clock6':'\\ud83d\\udd55',\n 'clock630':'\\ud83d\\udd61',\n 'clock7':'\\ud83d\\udd56',\n 'clock730':'\\ud83d\\udd62',\n 'clock8':'\\ud83d\\udd57',\n 'clock830':'\\ud83d\\udd63',\n 'clock9':'\\ud83d\\udd58',\n 'clock930':'\\ud83d\\udd64',\n 'closed_book':'\\ud83d\\udcd5',\n 'closed_lock_with_key':'\\ud83d\\udd10',\n 'closed_umbrella':'\\ud83c\\udf02',\n 'cloud':'\\u2601\\ufe0f',\n 'cloud_with_lightning':'\\ud83c\\udf29',\n 'cloud_with_lightning_and_rain':'\\u26c8',\n 'cloud_with_rain':'\\ud83c\\udf27',\n 'cloud_with_snow':'\\ud83c\\udf28',\n 'clown_face':'\\ud83e\\udd21',\n 'clubs':'\\u2663\\ufe0f',\n 'cocktail':'\\ud83c\\udf78',\n 'coffee':'\\u2615\\ufe0f',\n 'coffin':'\\u26b0\\ufe0f',\n 'cold_sweat':'\\ud83d\\ude30',\n 'comet':'\\u2604\\ufe0f',\n 'computer':'\\ud83d\\udcbb',\n 'computer_mouse':'\\ud83d\\uddb1',\n 'confetti_ball':'\\ud83c\\udf8a',\n 'confounded':'\\ud83d\\ude16',\n 'confused':'\\ud83d\\ude15',\n 'congratulations':'\\u3297\\ufe0f',\n 'construction':'\\ud83d\\udea7',\n 'construction_worker_man':'\\ud83d\\udc77',\n 'construction_worker_woman':'\\ud83d\\udc77‍\\u2640\\ufe0f',\n 'control_knobs':'\\ud83c\\udf9b',\n 'convenience_store':'\\ud83c\\udfea',\n 'cookie':'\\ud83c\\udf6a',\n 'cool':'\\ud83c\\udd92',\n 'policeman':'\\ud83d\\udc6e',\n 'copyright':'\\u00a9\\ufe0f',\n 'corn':'\\ud83c\\udf3d',\n 'couch_and_lamp':'\\ud83d\\udecb',\n 'couple':'\\ud83d\\udc6b',\n 'couple_with_heart_woman_man':'\\ud83d\\udc91',\n 'couple_with_heart_man_man':'\\ud83d\\udc68‍\\u2764\\ufe0f‍\\ud83d\\udc68',\n 'couple_with_heart_woman_woman':'\\ud83d\\udc69‍\\u2764\\ufe0f‍\\ud83d\\udc69',\n 'couplekiss_man_man':'\\ud83d\\udc68‍\\u2764\\ufe0f‍\\ud83d\\udc8b‍\\ud83d\\udc68',\n 'couplekiss_man_woman':'\\ud83d\\udc8f',\n 'couplekiss_woman_woman':'\\ud83d\\udc69‍\\u2764\\ufe0f‍\\ud83d\\udc8b‍\\ud83d\\udc69',\n 'cow':'\\ud83d\\udc2e',\n 'cow2':'\\ud83d\\udc04',\n 'cowboy_hat_face':'\\ud83e\\udd20',\n 'crab':'\\ud83e\\udd80',\n 'crayon':'\\ud83d\\udd8d',\n 'credit_card':'\\ud83d\\udcb3',\n 'crescent_moon':'\\ud83c\\udf19',\n 'cricket':'\\ud83c\\udfcf',\n 'crocodile':'\\ud83d\\udc0a',\n 'croissant':'\\ud83e\\udd50',\n 'crossed_fingers':'\\ud83e\\udd1e',\n 'crossed_flags':'\\ud83c\\udf8c',\n 'crossed_swords':'\\u2694\\ufe0f',\n 'crown':'\\ud83d\\udc51',\n 'cry':'\\ud83d\\ude22',\n 'crying_cat_face':'\\ud83d\\ude3f',\n 'crystal_ball':'\\ud83d\\udd2e',\n 'cucumber':'\\ud83e\\udd52',\n 'cupid':'\\ud83d\\udc98',\n 'curly_loop':'\\u27b0',\n 'currency_exchange':'\\ud83d\\udcb1',\n 'curry':'\\ud83c\\udf5b',\n 'custard':'\\ud83c\\udf6e',\n 'customs':'\\ud83d\\udec3',\n 'cyclone':'\\ud83c\\udf00',\n 'dagger':'\\ud83d\\udde1',\n 'dancer':'\\ud83d\\udc83',\n 'dancing_women':'\\ud83d\\udc6f',\n 'dancing_men':'\\ud83d\\udc6f‍\\u2642\\ufe0f',\n 'dango':'\\ud83c\\udf61',\n 'dark_sunglasses':'\\ud83d\\udd76',\n 'dart':'\\ud83c\\udfaf',\n 'dash':'\\ud83d\\udca8',\n 'date':'\\ud83d\\udcc5',\n 'deciduous_tree':'\\ud83c\\udf33',\n 'deer':'\\ud83e\\udd8c',\n 'department_store':'\\ud83c\\udfec',\n 'derelict_house':'\\ud83c\\udfda',\n 'desert':'\\ud83c\\udfdc',\n 'desert_island':'\\ud83c\\udfdd',\n 'desktop_computer':'\\ud83d\\udda5',\n 'male_detective':'\\ud83d\\udd75\\ufe0f',\n 'diamond_shape_with_a_dot_inside':'\\ud83d\\udca0',\n 'diamonds':'\\u2666\\ufe0f',\n 'disappointed':'\\ud83d\\ude1e',\n 'disappointed_relieved':'\\ud83d\\ude25',\n 'dizzy':'\\ud83d\\udcab',\n 'dizzy_face':'\\ud83d\\ude35',\n 'do_not_litter':'\\ud83d\\udeaf',\n 'dog':'\\ud83d\\udc36',\n 'dog2':'\\ud83d\\udc15',\n 'dollar':'\\ud83d\\udcb5',\n 'dolls':'\\ud83c\\udf8e',\n 'dolphin':'\\ud83d\\udc2c',\n 'door':'\\ud83d\\udeaa',\n 'doughnut':'\\ud83c\\udf69',\n 'dove':'\\ud83d\\udd4a',\n 'dragon':'\\ud83d\\udc09',\n 'dragon_face':'\\ud83d\\udc32',\n 'dress':'\\ud83d\\udc57',\n 'dromedary_camel':'\\ud83d\\udc2a',\n 'drooling_face':'\\ud83e\\udd24',\n 'droplet':'\\ud83d\\udca7',\n 'drum':'\\ud83e\\udd41',\n 'duck':'\\ud83e\\udd86',\n 'dvd':'\\ud83d\\udcc0',\n 'e-mail':'\\ud83d\\udce7',\n 'eagle':'\\ud83e\\udd85',\n 'ear':'\\ud83d\\udc42',\n 'ear_of_rice':'\\ud83c\\udf3e',\n 'earth_africa':'\\ud83c\\udf0d',\n 'earth_americas':'\\ud83c\\udf0e',\n 'earth_asia':'\\ud83c\\udf0f',\n 'egg':'\\ud83e\\udd5a',\n 'eggplant':'\\ud83c\\udf46',\n 'eight_pointed_black_star':'\\u2734\\ufe0f',\n 'eight_spoked_asterisk':'\\u2733\\ufe0f',\n 'electric_plug':'\\ud83d\\udd0c',\n 'elephant':'\\ud83d\\udc18',\n 'email':'\\u2709\\ufe0f',\n 'end':'\\ud83d\\udd1a',\n 'envelope_with_arrow':'\\ud83d\\udce9',\n 'euro':'\\ud83d\\udcb6',\n 'european_castle':'\\ud83c\\udff0',\n 'european_post_office':'\\ud83c\\udfe4',\n 'evergreen_tree':'\\ud83c\\udf32',\n 'exclamation':'\\u2757\\ufe0f',\n 'expressionless':'\\ud83d\\ude11',\n 'eye':'\\ud83d\\udc41',\n 'eye_speech_bubble':'\\ud83d\\udc41‍\\ud83d\\udde8',\n 'eyeglasses':'\\ud83d\\udc53',\n 'eyes':'\\ud83d\\udc40',\n 'face_with_head_bandage':'\\ud83e\\udd15',\n 'face_with_thermometer':'\\ud83e\\udd12',\n 'fist_oncoming':'\\ud83d\\udc4a',\n 'factory':'\\ud83c\\udfed',\n 'fallen_leaf':'\\ud83c\\udf42',\n 'family_man_woman_boy':'\\ud83d\\udc6a',\n 'family_man_boy':'\\ud83d\\udc68‍\\ud83d\\udc66',\n 'family_man_boy_boy':'\\ud83d\\udc68‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_man_girl':'\\ud83d\\udc68‍\\ud83d\\udc67',\n 'family_man_girl_boy':'\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_man_girl_girl':'\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_man_man_boy':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc66',\n 'family_man_man_boy_boy':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_man_man_girl':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc67',\n 'family_man_man_girl_boy':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_man_man_girl_girl':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_man_woman_boy_boy':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_man_woman_girl':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc67',\n 'family_man_woman_girl_boy':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_man_woman_girl_girl':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_woman_boy':'\\ud83d\\udc69‍\\ud83d\\udc66',\n 'family_woman_boy_boy':'\\ud83d\\udc69‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_woman_girl':'\\ud83d\\udc69‍\\ud83d\\udc67',\n 'family_woman_girl_boy':'\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_woman_girl_girl':'\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_woman_woman_boy':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc66',\n 'family_woman_woman_boy_boy':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_woman_woman_girl':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc67',\n 'family_woman_woman_girl_boy':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_woman_woman_girl_girl':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'fast_forward':'\\u23e9',\n 'fax':'\\ud83d\\udce0',\n 'fearful':'\\ud83d\\ude28',\n 'feet':'\\ud83d\\udc3e',\n 'female_detective':'\\ud83d\\udd75\\ufe0f‍\\u2640\\ufe0f',\n 'ferris_wheel':'\\ud83c\\udfa1',\n 'ferry':'\\u26f4',\n 'field_hockey':'\\ud83c\\udfd1',\n 'file_cabinet':'\\ud83d\\uddc4',\n 'file_folder':'\\ud83d\\udcc1',\n 'film_projector':'\\ud83d\\udcfd',\n 'film_strip':'\\ud83c\\udf9e',\n 'fire':'\\ud83d\\udd25',\n 'fire_engine':'\\ud83d\\ude92',\n 'fireworks':'\\ud83c\\udf86',\n 'first_quarter_moon':'\\ud83c\\udf13',\n 'first_quarter_moon_with_face':'\\ud83c\\udf1b',\n 'fish':'\\ud83d\\udc1f',\n 'fish_cake':'\\ud83c\\udf65',\n 'fishing_pole_and_fish':'\\ud83c\\udfa3',\n 'fist_raised':'\\u270a',\n 'fist_left':'\\ud83e\\udd1b',\n 'fist_right':'\\ud83e\\udd1c',\n 'flags':'\\ud83c\\udf8f',\n 'flashlight':'\\ud83d\\udd26',\n 'fleur_de_lis':'\\u269c\\ufe0f',\n 'flight_arrival':'\\ud83d\\udeec',\n 'flight_departure':'\\ud83d\\udeeb',\n 'floppy_disk':'\\ud83d\\udcbe',\n 'flower_playing_cards':'\\ud83c\\udfb4',\n 'flushed':'\\ud83d\\ude33',\n 'fog':'\\ud83c\\udf2b',\n 'foggy':'\\ud83c\\udf01',\n 'football':'\\ud83c\\udfc8',\n 'footprints':'\\ud83d\\udc63',\n 'fork_and_knife':'\\ud83c\\udf74',\n 'fountain':'\\u26f2\\ufe0f',\n 'fountain_pen':'\\ud83d\\udd8b',\n 'four_leaf_clover':'\\ud83c\\udf40',\n 'fox_face':'\\ud83e\\udd8a',\n 'framed_picture':'\\ud83d\\uddbc',\n 'free':'\\ud83c\\udd93',\n 'fried_egg':'\\ud83c\\udf73',\n 'fried_shrimp':'\\ud83c\\udf64',\n 'fries':'\\ud83c\\udf5f',\n 'frog':'\\ud83d\\udc38',\n 'frowning':'\\ud83d\\ude26',\n 'frowning_face':'\\u2639\\ufe0f',\n 'frowning_man':'\\ud83d\\ude4d‍\\u2642\\ufe0f',\n 'frowning_woman':'\\ud83d\\ude4d',\n 'middle_finger':'\\ud83d\\udd95',\n 'fuelpump':'\\u26fd\\ufe0f',\n 'full_moon':'\\ud83c\\udf15',\n 'full_moon_with_face':'\\ud83c\\udf1d',\n 'funeral_urn':'\\u26b1\\ufe0f',\n 'game_die':'\\ud83c\\udfb2',\n 'gear':'\\u2699\\ufe0f',\n 'gem':'\\ud83d\\udc8e',\n 'gemini':'\\u264a\\ufe0f',\n 'ghost':'\\ud83d\\udc7b',\n 'gift':'\\ud83c\\udf81',\n 'gift_heart':'\\ud83d\\udc9d',\n 'girl':'\\ud83d\\udc67',\n 'globe_with_meridians':'\\ud83c\\udf10',\n 'goal_net':'\\ud83e\\udd45',\n 'goat':'\\ud83d\\udc10',\n 'golf':'\\u26f3\\ufe0f',\n 'golfing_man':'\\ud83c\\udfcc\\ufe0f',\n 'golfing_woman':'\\ud83c\\udfcc\\ufe0f‍\\u2640\\ufe0f',\n 'gorilla':'\\ud83e\\udd8d',\n 'grapes':'\\ud83c\\udf47',\n 'green_apple':'\\ud83c\\udf4f',\n 'green_book':'\\ud83d\\udcd7',\n 'green_heart':'\\ud83d\\udc9a',\n 'green_salad':'\\ud83e\\udd57',\n 'grey_exclamation':'\\u2755',\n 'grey_question':'\\u2754',\n 'grimacing':'\\ud83d\\ude2c',\n 'grin':'\\ud83d\\ude01',\n 'grinning':'\\ud83d\\ude00',\n 'guardsman':'\\ud83d\\udc82',\n 'guardswoman':'\\ud83d\\udc82‍\\u2640\\ufe0f',\n 'guitar':'\\ud83c\\udfb8',\n 'gun':'\\ud83d\\udd2b',\n 'haircut_woman':'\\ud83d\\udc87',\n 'haircut_man':'\\ud83d\\udc87‍\\u2642\\ufe0f',\n 'hamburger':'\\ud83c\\udf54',\n 'hammer':'\\ud83d\\udd28',\n 'hammer_and_pick':'\\u2692',\n 'hammer_and_wrench':'\\ud83d\\udee0',\n 'hamster':'\\ud83d\\udc39',\n 'hand':'\\u270b',\n 'handbag':'\\ud83d\\udc5c',\n 'handshake':'\\ud83e\\udd1d',\n 'hankey':'\\ud83d\\udca9',\n 'hatched_chick':'\\ud83d\\udc25',\n 'hatching_chick':'\\ud83d\\udc23',\n 'headphones':'\\ud83c\\udfa7',\n 'hear_no_evil':'\\ud83d\\ude49',\n 'heart':'\\u2764\\ufe0f',\n 'heart_decoration':'\\ud83d\\udc9f',\n 'heart_eyes':'\\ud83d\\ude0d',\n 'heart_eyes_cat':'\\ud83d\\ude3b',\n 'heartbeat':'\\ud83d\\udc93',\n 'heartpulse':'\\ud83d\\udc97',\n 'hearts':'\\u2665\\ufe0f',\n 'heavy_check_mark':'\\u2714\\ufe0f',\n 'heavy_division_sign':'\\u2797',\n 'heavy_dollar_sign':'\\ud83d\\udcb2',\n 'heavy_heart_exclamation':'\\u2763\\ufe0f',\n 'heavy_minus_sign':'\\u2796',\n 'heavy_multiplication_x':'\\u2716\\ufe0f',\n 'heavy_plus_sign':'\\u2795',\n 'helicopter':'\\ud83d\\ude81',\n 'herb':'\\ud83c\\udf3f',\n 'hibiscus':'\\ud83c\\udf3a',\n 'high_brightness':'\\ud83d\\udd06',\n 'high_heel':'\\ud83d\\udc60',\n 'hocho':'\\ud83d\\udd2a',\n 'hole':'\\ud83d\\udd73',\n 'honey_pot':'\\ud83c\\udf6f',\n 'horse':'\\ud83d\\udc34',\n 'horse_racing':'\\ud83c\\udfc7',\n 'hospital':'\\ud83c\\udfe5',\n 'hot_pepper':'\\ud83c\\udf36',\n 'hotdog':'\\ud83c\\udf2d',\n 'hotel':'\\ud83c\\udfe8',\n 'hotsprings':'\\u2668\\ufe0f',\n 'hourglass':'\\u231b\\ufe0f',\n 'hourglass_flowing_sand':'\\u23f3',\n 'house':'\\ud83c\\udfe0',\n 'house_with_garden':'\\ud83c\\udfe1',\n 'houses':'\\ud83c\\udfd8',\n 'hugs':'\\ud83e\\udd17',\n 'hushed':'\\ud83d\\ude2f',\n 'ice_cream':'\\ud83c\\udf68',\n 'ice_hockey':'\\ud83c\\udfd2',\n 'ice_skate':'\\u26f8',\n 'icecream':'\\ud83c\\udf66',\n 'id':'\\ud83c\\udd94',\n 'ideograph_advantage':'\\ud83c\\ude50',\n 'imp':'\\ud83d\\udc7f',\n 'inbox_tray':'\\ud83d\\udce5',\n 'incoming_envelope':'\\ud83d\\udce8',\n 'tipping_hand_woman':'\\ud83d\\udc81',\n 'information_source':'\\u2139\\ufe0f',\n 'innocent':'\\ud83d\\ude07',\n 'interrobang':'\\u2049\\ufe0f',\n 'iphone':'\\ud83d\\udcf1',\n 'izakaya_lantern':'\\ud83c\\udfee',\n 'jack_o_lantern':'\\ud83c\\udf83',\n 'japan':'\\ud83d\\uddfe',\n 'japanese_castle':'\\ud83c\\udfef',\n 'japanese_goblin':'\\ud83d\\udc7a',\n 'japanese_ogre':'\\ud83d\\udc79',\n 'jeans':'\\ud83d\\udc56',\n 'joy':'\\ud83d\\ude02',\n 'joy_cat':'\\ud83d\\ude39',\n 'joystick':'\\ud83d\\udd79',\n 'kaaba':'\\ud83d\\udd4b',\n 'key':'\\ud83d\\udd11',\n 'keyboard':'\\u2328\\ufe0f',\n 'keycap_ten':'\\ud83d\\udd1f',\n 'kick_scooter':'\\ud83d\\udef4',\n 'kimono':'\\ud83d\\udc58',\n 'kiss':'\\ud83d\\udc8b',\n 'kissing':'\\ud83d\\ude17',\n 'kissing_cat':'\\ud83d\\ude3d',\n 'kissing_closed_eyes':'\\ud83d\\ude1a',\n 'kissing_heart':'\\ud83d\\ude18',\n 'kissing_smiling_eyes':'\\ud83d\\ude19',\n 'kiwi_fruit':'\\ud83e\\udd5d',\n 'koala':'\\ud83d\\udc28',\n 'koko':'\\ud83c\\ude01',\n 'label':'\\ud83c\\udff7',\n 'large_blue_circle':'\\ud83d\\udd35',\n 'large_blue_diamond':'\\ud83d\\udd37',\n 'large_orange_diamond':'\\ud83d\\udd36',\n 'last_quarter_moon':'\\ud83c\\udf17',\n 'last_quarter_moon_with_face':'\\ud83c\\udf1c',\n 'latin_cross':'\\u271d\\ufe0f',\n 'laughing':'\\ud83d\\ude06',\n 'leaves':'\\ud83c\\udf43',\n 'ledger':'\\ud83d\\udcd2',\n 'left_luggage':'\\ud83d\\udec5',\n 'left_right_arrow':'\\u2194\\ufe0f',\n 'leftwards_arrow_with_hook':'\\u21a9\\ufe0f',\n 'lemon':'\\ud83c\\udf4b',\n 'leo':'\\u264c\\ufe0f',\n 'leopard':'\\ud83d\\udc06',\n 'level_slider':'\\ud83c\\udf9a',\n 'libra':'\\u264e\\ufe0f',\n 'light_rail':'\\ud83d\\ude88',\n 'link':'\\ud83d\\udd17',\n 'lion':'\\ud83e\\udd81',\n 'lips':'\\ud83d\\udc44',\n 'lipstick':'\\ud83d\\udc84',\n 'lizard':'\\ud83e\\udd8e',\n 'lock':'\\ud83d\\udd12',\n 'lock_with_ink_pen':'\\ud83d\\udd0f',\n 'lollipop':'\\ud83c\\udf6d',\n 'loop':'\\u27bf',\n 'loud_sound':'\\ud83d\\udd0a',\n 'loudspeaker':'\\ud83d\\udce2',\n 'love_hotel':'\\ud83c\\udfe9',\n 'love_letter':'\\ud83d\\udc8c',\n 'low_brightness':'\\ud83d\\udd05',\n 'lying_face':'\\ud83e\\udd25',\n 'm':'\\u24c2\\ufe0f',\n 'mag':'\\ud83d\\udd0d',\n 'mag_right':'\\ud83d\\udd0e',\n 'mahjong':'\\ud83c\\udc04\\ufe0f',\n 'mailbox':'\\ud83d\\udceb',\n 'mailbox_closed':'\\ud83d\\udcea',\n 'mailbox_with_mail':'\\ud83d\\udcec',\n 'mailbox_with_no_mail':'\\ud83d\\udced',\n 'man':'\\ud83d\\udc68',\n 'man_artist':'\\ud83d\\udc68‍\\ud83c\\udfa8',\n 'man_astronaut':'\\ud83d\\udc68‍\\ud83d\\ude80',\n 'man_cartwheeling':'\\ud83e\\udd38‍\\u2642\\ufe0f',\n 'man_cook':'\\ud83d\\udc68‍\\ud83c\\udf73',\n 'man_dancing':'\\ud83d\\udd7a',\n 'man_facepalming':'\\ud83e\\udd26‍\\u2642\\ufe0f',\n 'man_factory_worker':'\\ud83d\\udc68‍\\ud83c\\udfed',\n 'man_farmer':'\\ud83d\\udc68‍\\ud83c\\udf3e',\n 'man_firefighter':'\\ud83d\\udc68‍\\ud83d\\ude92',\n 'man_health_worker':'\\ud83d\\udc68‍\\u2695\\ufe0f',\n 'man_in_tuxedo':'\\ud83e\\udd35',\n 'man_judge':'\\ud83d\\udc68‍\\u2696\\ufe0f',\n 'man_juggling':'\\ud83e\\udd39‍\\u2642\\ufe0f',\n 'man_mechanic':'\\ud83d\\udc68‍\\ud83d\\udd27',\n 'man_office_worker':'\\ud83d\\udc68‍\\ud83d\\udcbc',\n 'man_pilot':'\\ud83d\\udc68‍\\u2708\\ufe0f',\n 'man_playing_handball':'\\ud83e\\udd3e‍\\u2642\\ufe0f',\n 'man_playing_water_polo':'\\ud83e\\udd3d‍\\u2642\\ufe0f',\n 'man_scientist':'\\ud83d\\udc68‍\\ud83d\\udd2c',\n 'man_shrugging':'\\ud83e\\udd37‍\\u2642\\ufe0f',\n 'man_singer':'\\ud83d\\udc68‍\\ud83c\\udfa4',\n 'man_student':'\\ud83d\\udc68‍\\ud83c\\udf93',\n 'man_teacher':'\\ud83d\\udc68‍\\ud83c\\udfeb',\n 'man_technologist':'\\ud83d\\udc68‍\\ud83d\\udcbb',\n 'man_with_gua_pi_mao':'\\ud83d\\udc72',\n 'man_with_turban':'\\ud83d\\udc73',\n 'tangerine':'\\ud83c\\udf4a',\n 'mans_shoe':'\\ud83d\\udc5e',\n 'mantelpiece_clock':'\\ud83d\\udd70',\n 'maple_leaf':'\\ud83c\\udf41',\n 'martial_arts_uniform':'\\ud83e\\udd4b',\n 'mask':'\\ud83d\\ude37',\n 'massage_woman':'\\ud83d\\udc86',\n 'massage_man':'\\ud83d\\udc86‍\\u2642\\ufe0f',\n 'meat_on_bone':'\\ud83c\\udf56',\n 'medal_military':'\\ud83c\\udf96',\n 'medal_sports':'\\ud83c\\udfc5',\n 'mega':'\\ud83d\\udce3',\n 'melon':'\\ud83c\\udf48',\n 'memo':'\\ud83d\\udcdd',\n 'men_wrestling':'\\ud83e\\udd3c‍\\u2642\\ufe0f',\n 'menorah':'\\ud83d\\udd4e',\n 'mens':'\\ud83d\\udeb9',\n 'metal':'\\ud83e\\udd18',\n 'metro':'\\ud83d\\ude87',\n 'microphone':'\\ud83c\\udfa4',\n 'microscope':'\\ud83d\\udd2c',\n 'milk_glass':'\\ud83e\\udd5b',\n 'milky_way':'\\ud83c\\udf0c',\n 'minibus':'\\ud83d\\ude90',\n 'minidisc':'\\ud83d\\udcbd',\n 'mobile_phone_off':'\\ud83d\\udcf4',\n 'money_mouth_face':'\\ud83e\\udd11',\n 'money_with_wings':'\\ud83d\\udcb8',\n 'moneybag':'\\ud83d\\udcb0',\n 'monkey':'\\ud83d\\udc12',\n 'monkey_face':'\\ud83d\\udc35',\n 'monorail':'\\ud83d\\ude9d',\n 'moon':'\\ud83c\\udf14',\n 'mortar_board':'\\ud83c\\udf93',\n 'mosque':'\\ud83d\\udd4c',\n 'motor_boat':'\\ud83d\\udee5',\n 'motor_scooter':'\\ud83d\\udef5',\n 'motorcycle':'\\ud83c\\udfcd',\n 'motorway':'\\ud83d\\udee3',\n 'mount_fuji':'\\ud83d\\uddfb',\n 'mountain':'\\u26f0',\n 'mountain_biking_man':'\\ud83d\\udeb5',\n 'mountain_biking_woman':'\\ud83d\\udeb5‍\\u2640\\ufe0f',\n 'mountain_cableway':'\\ud83d\\udea0',\n 'mountain_railway':'\\ud83d\\ude9e',\n 'mountain_snow':'\\ud83c\\udfd4',\n 'mouse':'\\ud83d\\udc2d',\n 'mouse2':'\\ud83d\\udc01',\n 'movie_camera':'\\ud83c\\udfa5',\n 'moyai':'\\ud83d\\uddff',\n 'mrs_claus':'\\ud83e\\udd36',\n 'muscle':'\\ud83d\\udcaa',\n 'mushroom':'\\ud83c\\udf44',\n 'musical_keyboard':'\\ud83c\\udfb9',\n 'musical_note':'\\ud83c\\udfb5',\n 'musical_score':'\\ud83c\\udfbc',\n 'mute':'\\ud83d\\udd07',\n 'nail_care':'\\ud83d\\udc85',\n 'name_badge':'\\ud83d\\udcdb',\n 'national_park':'\\ud83c\\udfde',\n 'nauseated_face':'\\ud83e\\udd22',\n 'necktie':'\\ud83d\\udc54',\n 'negative_squared_cross_mark':'\\u274e',\n 'nerd_face':'\\ud83e\\udd13',\n 'neutral_face':'\\ud83d\\ude10',\n 'new':'\\ud83c\\udd95',\n 'new_moon':'\\ud83c\\udf11',\n 'new_moon_with_face':'\\ud83c\\udf1a',\n 'newspaper':'\\ud83d\\udcf0',\n 'newspaper_roll':'\\ud83d\\uddde',\n 'next_track_button':'\\u23ed',\n 'ng':'\\ud83c\\udd96',\n 'no_good_man':'\\ud83d\\ude45‍\\u2642\\ufe0f',\n 'no_good_woman':'\\ud83d\\ude45',\n 'night_with_stars':'\\ud83c\\udf03',\n 'no_bell':'\\ud83d\\udd15',\n 'no_bicycles':'\\ud83d\\udeb3',\n 'no_entry':'\\u26d4\\ufe0f',\n 'no_entry_sign':'\\ud83d\\udeab',\n 'no_mobile_phones':'\\ud83d\\udcf5',\n 'no_mouth':'\\ud83d\\ude36',\n 'no_pedestrians':'\\ud83d\\udeb7',\n 'no_smoking':'\\ud83d\\udead',\n 'non-potable_water':'\\ud83d\\udeb1',\n 'nose':'\\ud83d\\udc43',\n 'notebook':'\\ud83d\\udcd3',\n 'notebook_with_decorative_cover':'\\ud83d\\udcd4',\n 'notes':'\\ud83c\\udfb6',\n 'nut_and_bolt':'\\ud83d\\udd29',\n 'o':'\\u2b55\\ufe0f',\n 'o2':'\\ud83c\\udd7e\\ufe0f',\n 'ocean':'\\ud83c\\udf0a',\n 'octopus':'\\ud83d\\udc19',\n 'oden':'\\ud83c\\udf62',\n 'office':'\\ud83c\\udfe2',\n 'oil_drum':'\\ud83d\\udee2',\n 'ok':'\\ud83c\\udd97',\n 'ok_hand':'\\ud83d\\udc4c',\n 'ok_man':'\\ud83d\\ude46‍\\u2642\\ufe0f',\n 'ok_woman':'\\ud83d\\ude46',\n 'old_key':'\\ud83d\\udddd',\n 'older_man':'\\ud83d\\udc74',\n 'older_woman':'\\ud83d\\udc75',\n 'om':'\\ud83d\\udd49',\n 'on':'\\ud83d\\udd1b',\n 'oncoming_automobile':'\\ud83d\\ude98',\n 'oncoming_bus':'\\ud83d\\ude8d',\n 'oncoming_police_car':'\\ud83d\\ude94',\n 'oncoming_taxi':'\\ud83d\\ude96',\n 'open_file_folder':'\\ud83d\\udcc2',\n 'open_hands':'\\ud83d\\udc50',\n 'open_mouth':'\\ud83d\\ude2e',\n 'open_umbrella':'\\u2602\\ufe0f',\n 'ophiuchus':'\\u26ce',\n 'orange_book':'\\ud83d\\udcd9',\n 'orthodox_cross':'\\u2626\\ufe0f',\n 'outbox_tray':'\\ud83d\\udce4',\n 'owl':'\\ud83e\\udd89',\n 'ox':'\\ud83d\\udc02',\n 'package':'\\ud83d\\udce6',\n 'page_facing_up':'\\ud83d\\udcc4',\n 'page_with_curl':'\\ud83d\\udcc3',\n 'pager':'\\ud83d\\udcdf',\n 'paintbrush':'\\ud83d\\udd8c',\n 'palm_tree':'\\ud83c\\udf34',\n 'pancakes':'\\ud83e\\udd5e',\n 'panda_face':'\\ud83d\\udc3c',\n 'paperclip':'\\ud83d\\udcce',\n 'paperclips':'\\ud83d\\udd87',\n 'parasol_on_ground':'\\u26f1',\n 'parking':'\\ud83c\\udd7f\\ufe0f',\n 'part_alternation_mark':'\\u303d\\ufe0f',\n 'partly_sunny':'\\u26c5\\ufe0f',\n 'passenger_ship':'\\ud83d\\udef3',\n 'passport_control':'\\ud83d\\udec2',\n 'pause_button':'\\u23f8',\n 'peace_symbol':'\\u262e\\ufe0f',\n 'peach':'\\ud83c\\udf51',\n 'peanuts':'\\ud83e\\udd5c',\n 'pear':'\\ud83c\\udf50',\n 'pen':'\\ud83d\\udd8a',\n 'pencil2':'\\u270f\\ufe0f',\n 'penguin':'\\ud83d\\udc27',\n 'pensive':'\\ud83d\\ude14',\n 'performing_arts':'\\ud83c\\udfad',\n 'persevere':'\\ud83d\\ude23',\n 'person_fencing':'\\ud83e\\udd3a',\n 'pouting_woman':'\\ud83d\\ude4e',\n 'phone':'\\u260e\\ufe0f',\n 'pick':'\\u26cf',\n 'pig':'\\ud83d\\udc37',\n 'pig2':'\\ud83d\\udc16',\n 'pig_nose':'\\ud83d\\udc3d',\n 'pill':'\\ud83d\\udc8a',\n 'pineapple':'\\ud83c\\udf4d',\n 'ping_pong':'\\ud83c\\udfd3',\n 'pisces':'\\u2653\\ufe0f',\n 'pizza':'\\ud83c\\udf55',\n 'place_of_worship':'\\ud83d\\uded0',\n 'plate_with_cutlery':'\\ud83c\\udf7d',\n 'play_or_pause_button':'\\u23ef',\n 'point_down':'\\ud83d\\udc47',\n 'point_left':'\\ud83d\\udc48',\n 'point_right':'\\ud83d\\udc49',\n 'point_up':'\\u261d\\ufe0f',\n 'point_up_2':'\\ud83d\\udc46',\n 'police_car':'\\ud83d\\ude93',\n 'policewoman':'\\ud83d\\udc6e‍\\u2640\\ufe0f',\n 'poodle':'\\ud83d\\udc29',\n 'popcorn':'\\ud83c\\udf7f',\n 'post_office':'\\ud83c\\udfe3',\n 'postal_horn':'\\ud83d\\udcef',\n 'postbox':'\\ud83d\\udcee',\n 'potable_water':'\\ud83d\\udeb0',\n 'potato':'\\ud83e\\udd54',\n 'pouch':'\\ud83d\\udc5d',\n 'poultry_leg':'\\ud83c\\udf57',\n 'pound':'\\ud83d\\udcb7',\n 'rage':'\\ud83d\\ude21',\n 'pouting_cat':'\\ud83d\\ude3e',\n 'pouting_man':'\\ud83d\\ude4e‍\\u2642\\ufe0f',\n 'pray':'\\ud83d\\ude4f',\n 'prayer_beads':'\\ud83d\\udcff',\n 'pregnant_woman':'\\ud83e\\udd30',\n 'previous_track_button':'\\u23ee',\n 'prince':'\\ud83e\\udd34',\n 'princess':'\\ud83d\\udc78',\n 'printer':'\\ud83d\\udda8',\n 'purple_heart':'\\ud83d\\udc9c',\n 'purse':'\\ud83d\\udc5b',\n 'pushpin':'\\ud83d\\udccc',\n 'put_litter_in_its_place':'\\ud83d\\udeae',\n 'question':'\\u2753',\n 'rabbit':'\\ud83d\\udc30',\n 'rabbit2':'\\ud83d\\udc07',\n 'racehorse':'\\ud83d\\udc0e',\n 'racing_car':'\\ud83c\\udfce',\n 'radio':'\\ud83d\\udcfb',\n 'radio_button':'\\ud83d\\udd18',\n 'radioactive':'\\u2622\\ufe0f',\n 'railway_car':'\\ud83d\\ude83',\n 'railway_track':'\\ud83d\\udee4',\n 'rainbow':'\\ud83c\\udf08',\n 'rainbow_flag':'\\ud83c\\udff3\\ufe0f‍\\ud83c\\udf08',\n 'raised_back_of_hand':'\\ud83e\\udd1a',\n 'raised_hand_with_fingers_splayed':'\\ud83d\\udd90',\n 'raised_hands':'\\ud83d\\ude4c',\n 'raising_hand_woman':'\\ud83d\\ude4b',\n 'raising_hand_man':'\\ud83d\\ude4b‍\\u2642\\ufe0f',\n 'ram':'\\ud83d\\udc0f',\n 'ramen':'\\ud83c\\udf5c',\n 'rat':'\\ud83d\\udc00',\n 'record_button':'\\u23fa',\n 'recycle':'\\u267b\\ufe0f',\n 'red_circle':'\\ud83d\\udd34',\n 'registered':'\\u00ae\\ufe0f',\n 'relaxed':'\\u263a\\ufe0f',\n 'relieved':'\\ud83d\\ude0c',\n 'reminder_ribbon':'\\ud83c\\udf97',\n 'repeat':'\\ud83d\\udd01',\n 'repeat_one':'\\ud83d\\udd02',\n 'rescue_worker_helmet':'\\u26d1',\n 'restroom':'\\ud83d\\udebb',\n 'revolving_hearts':'\\ud83d\\udc9e',\n 'rewind':'\\u23ea',\n 'rhinoceros':'\\ud83e\\udd8f',\n 'ribbon':'\\ud83c\\udf80',\n 'rice':'\\ud83c\\udf5a',\n 'rice_ball':'\\ud83c\\udf59',\n 'rice_cracker':'\\ud83c\\udf58',\n 'rice_scene':'\\ud83c\\udf91',\n 'right_anger_bubble':'\\ud83d\\uddef',\n 'ring':'\\ud83d\\udc8d',\n 'robot':'\\ud83e\\udd16',\n 'rocket':'\\ud83d\\ude80',\n 'rofl':'\\ud83e\\udd23',\n 'roll_eyes':'\\ud83d\\ude44',\n 'roller_coaster':'\\ud83c\\udfa2',\n 'rooster':'\\ud83d\\udc13',\n 'rose':'\\ud83c\\udf39',\n 'rosette':'\\ud83c\\udff5',\n 'rotating_light':'\\ud83d\\udea8',\n 'round_pushpin':'\\ud83d\\udccd',\n 'rowing_man':'\\ud83d\\udea3',\n 'rowing_woman':'\\ud83d\\udea3‍\\u2640\\ufe0f',\n 'rugby_football':'\\ud83c\\udfc9',\n 'running_man':'\\ud83c\\udfc3',\n 'running_shirt_with_sash':'\\ud83c\\udfbd',\n 'running_woman':'\\ud83c\\udfc3‍\\u2640\\ufe0f',\n 'sa':'\\ud83c\\ude02\\ufe0f',\n 'sagittarius':'\\u2650\\ufe0f',\n 'sake':'\\ud83c\\udf76',\n 'sandal':'\\ud83d\\udc61',\n 'santa':'\\ud83c\\udf85',\n 'satellite':'\\ud83d\\udce1',\n 'saxophone':'\\ud83c\\udfb7',\n 'school':'\\ud83c\\udfeb',\n 'school_satchel':'\\ud83c\\udf92',\n 'scissors':'\\u2702\\ufe0f',\n 'scorpion':'\\ud83e\\udd82',\n 'scorpius':'\\u264f\\ufe0f',\n 'scream':'\\ud83d\\ude31',\n 'scream_cat':'\\ud83d\\ude40',\n 'scroll':'\\ud83d\\udcdc',\n 'seat':'\\ud83d\\udcba',\n 'secret':'\\u3299\\ufe0f',\n 'see_no_evil':'\\ud83d\\ude48',\n 'seedling':'\\ud83c\\udf31',\n 'selfie':'\\ud83e\\udd33',\n 'shallow_pan_of_food':'\\ud83e\\udd58',\n 'shamrock':'\\u2618\\ufe0f',\n 'shark':'\\ud83e\\udd88',\n 'shaved_ice':'\\ud83c\\udf67',\n 'sheep':'\\ud83d\\udc11',\n 'shell':'\\ud83d\\udc1a',\n 'shield':'\\ud83d\\udee1',\n 'shinto_shrine':'\\u26e9',\n 'ship':'\\ud83d\\udea2',\n 'shirt':'\\ud83d\\udc55',\n 'shopping':'\\ud83d\\udecd',\n 'shopping_cart':'\\ud83d\\uded2',\n 'shower':'\\ud83d\\udebf',\n 'shrimp':'\\ud83e\\udd90',\n 'signal_strength':'\\ud83d\\udcf6',\n 'six_pointed_star':'\\ud83d\\udd2f',\n 'ski':'\\ud83c\\udfbf',\n 'skier':'\\u26f7',\n 'skull':'\\ud83d\\udc80',\n 'skull_and_crossbones':'\\u2620\\ufe0f',\n 'sleeping':'\\ud83d\\ude34',\n 'sleeping_bed':'\\ud83d\\udecc',\n 'sleepy':'\\ud83d\\ude2a',\n 'slightly_frowning_face':'\\ud83d\\ude41',\n 'slightly_smiling_face':'\\ud83d\\ude42',\n 'slot_machine':'\\ud83c\\udfb0',\n 'small_airplane':'\\ud83d\\udee9',\n 'small_blue_diamond':'\\ud83d\\udd39',\n 'small_orange_diamond':'\\ud83d\\udd38',\n 'small_red_triangle':'\\ud83d\\udd3a',\n 'small_red_triangle_down':'\\ud83d\\udd3b',\n 'smile':'\\ud83d\\ude04',\n 'smile_cat':'\\ud83d\\ude38',\n 'smiley':'\\ud83d\\ude03',\n 'smiley_cat':'\\ud83d\\ude3a',\n 'smiling_imp':'\\ud83d\\ude08',\n 'smirk':'\\ud83d\\ude0f',\n 'smirk_cat':'\\ud83d\\ude3c',\n 'smoking':'\\ud83d\\udeac',\n 'snail':'\\ud83d\\udc0c',\n 'snake':'\\ud83d\\udc0d',\n 'sneezing_face':'\\ud83e\\udd27',\n 'snowboarder':'\\ud83c\\udfc2',\n 'snowflake':'\\u2744\\ufe0f',\n 'snowman':'\\u26c4\\ufe0f',\n 'snowman_with_snow':'\\u2603\\ufe0f',\n 'sob':'\\ud83d\\ude2d',\n 'soccer':'\\u26bd\\ufe0f',\n 'soon':'\\ud83d\\udd1c',\n 'sos':'\\ud83c\\udd98',\n 'sound':'\\ud83d\\udd09',\n 'space_invader':'\\ud83d\\udc7e',\n 'spades':'\\u2660\\ufe0f',\n 'spaghetti':'\\ud83c\\udf5d',\n 'sparkle':'\\u2747\\ufe0f',\n 'sparkler':'\\ud83c\\udf87',\n 'sparkles':'\\u2728',\n 'sparkling_heart':'\\ud83d\\udc96',\n 'speak_no_evil':'\\ud83d\\ude4a',\n 'speaker':'\\ud83d\\udd08',\n 'speaking_head':'\\ud83d\\udde3',\n 'speech_balloon':'\\ud83d\\udcac',\n 'speedboat':'\\ud83d\\udea4',\n 'spider':'\\ud83d\\udd77',\n 'spider_web':'\\ud83d\\udd78',\n 'spiral_calendar':'\\ud83d\\uddd3',\n 'spiral_notepad':'\\ud83d\\uddd2',\n 'spoon':'\\ud83e\\udd44',\n 'squid':'\\ud83e\\udd91',\n 'stadium':'\\ud83c\\udfdf',\n 'star':'\\u2b50\\ufe0f',\n 'star2':'\\ud83c\\udf1f',\n 'star_and_crescent':'\\u262a\\ufe0f',\n 'star_of_david':'\\u2721\\ufe0f',\n 'stars':'\\ud83c\\udf20',\n 'station':'\\ud83d\\ude89',\n 'statue_of_liberty':'\\ud83d\\uddfd',\n 'steam_locomotive':'\\ud83d\\ude82',\n 'stew':'\\ud83c\\udf72',\n 'stop_button':'\\u23f9',\n 'stop_sign':'\\ud83d\\uded1',\n 'stopwatch':'\\u23f1',\n 'straight_ruler':'\\ud83d\\udccf',\n 'strawberry':'\\ud83c\\udf53',\n 'stuck_out_tongue':'\\ud83d\\ude1b',\n 'stuck_out_tongue_closed_eyes':'\\ud83d\\ude1d',\n 'stuck_out_tongue_winking_eye':'\\ud83d\\ude1c',\n 'studio_microphone':'\\ud83c\\udf99',\n 'stuffed_flatbread':'\\ud83e\\udd59',\n 'sun_behind_large_cloud':'\\ud83c\\udf25',\n 'sun_behind_rain_cloud':'\\ud83c\\udf26',\n 'sun_behind_small_cloud':'\\ud83c\\udf24',\n 'sun_with_face':'\\ud83c\\udf1e',\n 'sunflower':'\\ud83c\\udf3b',\n 'sunglasses':'\\ud83d\\ude0e',\n 'sunny':'\\u2600\\ufe0f',\n 'sunrise':'\\ud83c\\udf05',\n 'sunrise_over_mountains':'\\ud83c\\udf04',\n 'surfing_man':'\\ud83c\\udfc4',\n 'surfing_woman':'\\ud83c\\udfc4‍\\u2640\\ufe0f',\n 'sushi':'\\ud83c\\udf63',\n 'suspension_railway':'\\ud83d\\ude9f',\n 'sweat':'\\ud83d\\ude13',\n 'sweat_drops':'\\ud83d\\udca6',\n 'sweat_smile':'\\ud83d\\ude05',\n 'sweet_potato':'\\ud83c\\udf60',\n 'swimming_man':'\\ud83c\\udfca',\n 'swimming_woman':'\\ud83c\\udfca‍\\u2640\\ufe0f',\n 'symbols':'\\ud83d\\udd23',\n 'synagogue':'\\ud83d\\udd4d',\n 'syringe':'\\ud83d\\udc89',\n 'taco':'\\ud83c\\udf2e',\n 'tada':'\\ud83c\\udf89',\n 'tanabata_tree':'\\ud83c\\udf8b',\n 'taurus':'\\u2649\\ufe0f',\n 'taxi':'\\ud83d\\ude95',\n 'tea':'\\ud83c\\udf75',\n 'telephone_receiver':'\\ud83d\\udcde',\n 'telescope':'\\ud83d\\udd2d',\n 'tennis':'\\ud83c\\udfbe',\n 'tent':'\\u26fa\\ufe0f',\n 'thermometer':'\\ud83c\\udf21',\n 'thinking':'\\ud83e\\udd14',\n 'thought_balloon':'\\ud83d\\udcad',\n 'ticket':'\\ud83c\\udfab',\n 'tickets':'\\ud83c\\udf9f',\n 'tiger':'\\ud83d\\udc2f',\n 'tiger2':'\\ud83d\\udc05',\n 'timer_clock':'\\u23f2',\n 'tipping_hand_man':'\\ud83d\\udc81‍\\u2642\\ufe0f',\n 'tired_face':'\\ud83d\\ude2b',\n 'tm':'\\u2122\\ufe0f',\n 'toilet':'\\ud83d\\udebd',\n 'tokyo_tower':'\\ud83d\\uddfc',\n 'tomato':'\\ud83c\\udf45',\n 'tongue':'\\ud83d\\udc45',\n 'top':'\\ud83d\\udd1d',\n 'tophat':'\\ud83c\\udfa9',\n 'tornado':'\\ud83c\\udf2a',\n 'trackball':'\\ud83d\\uddb2',\n 'tractor':'\\ud83d\\ude9c',\n 'traffic_light':'\\ud83d\\udea5',\n 'train':'\\ud83d\\ude8b',\n 'train2':'\\ud83d\\ude86',\n 'tram':'\\ud83d\\ude8a',\n 'triangular_flag_on_post':'\\ud83d\\udea9',\n 'triangular_ruler':'\\ud83d\\udcd0',\n 'trident':'\\ud83d\\udd31',\n 'triumph':'\\ud83d\\ude24',\n 'trolleybus':'\\ud83d\\ude8e',\n 'trophy':'\\ud83c\\udfc6',\n 'tropical_drink':'\\ud83c\\udf79',\n 'tropical_fish':'\\ud83d\\udc20',\n 'truck':'\\ud83d\\ude9a',\n 'trumpet':'\\ud83c\\udfba',\n 'tulip':'\\ud83c\\udf37',\n 'tumbler_glass':'\\ud83e\\udd43',\n 'turkey':'\\ud83e\\udd83',\n 'turtle':'\\ud83d\\udc22',\n 'tv':'\\ud83d\\udcfa',\n 'twisted_rightwards_arrows':'\\ud83d\\udd00',\n 'two_hearts':'\\ud83d\\udc95',\n 'two_men_holding_hands':'\\ud83d\\udc6c',\n 'two_women_holding_hands':'\\ud83d\\udc6d',\n 'u5272':'\\ud83c\\ude39',\n 'u5408':'\\ud83c\\ude34',\n 'u55b6':'\\ud83c\\ude3a',\n 'u6307':'\\ud83c\\ude2f\\ufe0f',\n 'u6708':'\\ud83c\\ude37\\ufe0f',\n 'u6709':'\\ud83c\\ude36',\n 'u6e80':'\\ud83c\\ude35',\n 'u7121':'\\ud83c\\ude1a\\ufe0f',\n 'u7533':'\\ud83c\\ude38',\n 'u7981':'\\ud83c\\ude32',\n 'u7a7a':'\\ud83c\\ude33',\n 'umbrella':'\\u2614\\ufe0f',\n 'unamused':'\\ud83d\\ude12',\n 'underage':'\\ud83d\\udd1e',\n 'unicorn':'\\ud83e\\udd84',\n 'unlock':'\\ud83d\\udd13',\n 'up':'\\ud83c\\udd99',\n 'upside_down_face':'\\ud83d\\ude43',\n 'v':'\\u270c\\ufe0f',\n 'vertical_traffic_light':'\\ud83d\\udea6',\n 'vhs':'\\ud83d\\udcfc',\n 'vibration_mode':'\\ud83d\\udcf3',\n 'video_camera':'\\ud83d\\udcf9',\n 'video_game':'\\ud83c\\udfae',\n 'violin':'\\ud83c\\udfbb',\n 'virgo':'\\u264d\\ufe0f',\n 'volcano':'\\ud83c\\udf0b',\n 'volleyball':'\\ud83c\\udfd0',\n 'vs':'\\ud83c\\udd9a',\n 'vulcan_salute':'\\ud83d\\udd96',\n 'walking_man':'\\ud83d\\udeb6',\n 'walking_woman':'\\ud83d\\udeb6‍\\u2640\\ufe0f',\n 'waning_crescent_moon':'\\ud83c\\udf18',\n 'waning_gibbous_moon':'\\ud83c\\udf16',\n 'warning':'\\u26a0\\ufe0f',\n 'wastebasket':'\\ud83d\\uddd1',\n 'watch':'\\u231a\\ufe0f',\n 'water_buffalo':'\\ud83d\\udc03',\n 'watermelon':'\\ud83c\\udf49',\n 'wave':'\\ud83d\\udc4b',\n 'wavy_dash':'\\u3030\\ufe0f',\n 'waxing_crescent_moon':'\\ud83c\\udf12',\n 'wc':'\\ud83d\\udebe',\n 'weary':'\\ud83d\\ude29',\n 'wedding':'\\ud83d\\udc92',\n 'weight_lifting_man':'\\ud83c\\udfcb\\ufe0f',\n 'weight_lifting_woman':'\\ud83c\\udfcb\\ufe0f‍\\u2640\\ufe0f',\n 'whale':'\\ud83d\\udc33',\n 'whale2':'\\ud83d\\udc0b',\n 'wheel_of_dharma':'\\u2638\\ufe0f',\n 'wheelchair':'\\u267f\\ufe0f',\n 'white_check_mark':'\\u2705',\n 'white_circle':'\\u26aa\\ufe0f',\n 'white_flag':'\\ud83c\\udff3\\ufe0f',\n 'white_flower':'\\ud83d\\udcae',\n 'white_large_square':'\\u2b1c\\ufe0f',\n 'white_medium_small_square':'\\u25fd\\ufe0f',\n 'white_medium_square':'\\u25fb\\ufe0f',\n 'white_small_square':'\\u25ab\\ufe0f',\n 'white_square_button':'\\ud83d\\udd33',\n 'wilted_flower':'\\ud83e\\udd40',\n 'wind_chime':'\\ud83c\\udf90',\n 'wind_face':'\\ud83c\\udf2c',\n 'wine_glass':'\\ud83c\\udf77',\n 'wink':'\\ud83d\\ude09',\n 'wolf':'\\ud83d\\udc3a',\n 'woman':'\\ud83d\\udc69',\n 'woman_artist':'\\ud83d\\udc69‍\\ud83c\\udfa8',\n 'woman_astronaut':'\\ud83d\\udc69‍\\ud83d\\ude80',\n 'woman_cartwheeling':'\\ud83e\\udd38‍\\u2640\\ufe0f',\n 'woman_cook':'\\ud83d\\udc69‍\\ud83c\\udf73',\n 'woman_facepalming':'\\ud83e\\udd26‍\\u2640\\ufe0f',\n 'woman_factory_worker':'\\ud83d\\udc69‍\\ud83c\\udfed',\n 'woman_farmer':'\\ud83d\\udc69‍\\ud83c\\udf3e',\n 'woman_firefighter':'\\ud83d\\udc69‍\\ud83d\\ude92',\n 'woman_health_worker':'\\ud83d\\udc69‍\\u2695\\ufe0f',\n 'woman_judge':'\\ud83d\\udc69‍\\u2696\\ufe0f',\n 'woman_juggling':'\\ud83e\\udd39‍\\u2640\\ufe0f',\n 'woman_mechanic':'\\ud83d\\udc69‍\\ud83d\\udd27',\n 'woman_office_worker':'\\ud83d\\udc69‍\\ud83d\\udcbc',\n 'woman_pilot':'\\ud83d\\udc69‍\\u2708\\ufe0f',\n 'woman_playing_handball':'\\ud83e\\udd3e‍\\u2640\\ufe0f',\n 'woman_playing_water_polo':'\\ud83e\\udd3d‍\\u2640\\ufe0f',\n 'woman_scientist':'\\ud83d\\udc69‍\\ud83d\\udd2c',\n 'woman_shrugging':'\\ud83e\\udd37‍\\u2640\\ufe0f',\n 'woman_singer':'\\ud83d\\udc69‍\\ud83c\\udfa4',\n 'woman_student':'\\ud83d\\udc69‍\\ud83c\\udf93',\n 'woman_teacher':'\\ud83d\\udc69‍\\ud83c\\udfeb',\n 'woman_technologist':'\\ud83d\\udc69‍\\ud83d\\udcbb',\n 'woman_with_turban':'\\ud83d\\udc73‍\\u2640\\ufe0f',\n 'womans_clothes':'\\ud83d\\udc5a',\n 'womans_hat':'\\ud83d\\udc52',\n 'women_wrestling':'\\ud83e\\udd3c‍\\u2640\\ufe0f',\n 'womens':'\\ud83d\\udeba',\n 'world_map':'\\ud83d\\uddfa',\n 'worried':'\\ud83d\\ude1f',\n 'wrench':'\\ud83d\\udd27',\n 'writing_hand':'\\u270d\\ufe0f',\n 'x':'\\u274c',\n 'yellow_heart':'\\ud83d\\udc9b',\n 'yen':'\\ud83d\\udcb4',\n 'yin_yang':'\\u262f\\ufe0f',\n 'yum':'\\ud83d\\ude0b',\n 'zap':'\\u26a1\\ufe0f',\n 'zipper_mouth_face':'\\ud83e\\udd10',\n 'zzz':'\\ud83d\\udca4',\n\n /* special emojis :P */\n 'octocat': '\":octocat:\"',\n 'showdown': 'S'\n};\n", "/**\n * Created by Estevao on 31-05-2015.\n */\n\n/**\n * Showdown Converter class\n * @class\n * @param {object} [converterOptions]\n * @returns {Converter}\n */\nshowdown.Converter = function (converterOptions) {\n 'use strict';\n\n var\n /**\n * Options used by this converter\n * @private\n * @type {{}}\n */\n options = {},\n\n /**\n * Language extensions used by this converter\n * @private\n * @type {Array}\n */\n langExtensions = [],\n\n /**\n * Output modifiers extensions used by this converter\n * @private\n * @type {Array}\n */\n outputModifiers = [],\n\n /**\n * Event listeners\n * @private\n * @type {{}}\n */\n listeners = {},\n\n /**\n * The flavor set in this converter\n */\n setConvFlavor = setFlavor,\n\n /**\n * Metadata of the document\n * @type {{parsed: {}, raw: string, format: string}}\n */\n metadata = {\n parsed: {},\n raw: '',\n format: ''\n };\n\n _constructor();\n\n /**\n * Converter constructor\n * @private\n */\n function _constructor () {\n converterOptions = converterOptions || {};\n\n for (var gOpt in globalOptions) {\n if (globalOptions.hasOwnProperty(gOpt)) {\n options[gOpt] = globalOptions[gOpt];\n }\n }\n\n // Merge options\n if (typeof converterOptions === 'object') {\n for (var opt in converterOptions) {\n if (converterOptions.hasOwnProperty(opt)) {\n options[opt] = converterOptions[opt];\n }\n }\n } else {\n throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +\n ' was passed instead.');\n }\n\n if (options.extensions) {\n showdown.helper.forEach(options.extensions, _parseExtension);\n }\n }\n\n /**\n * Parse extension\n * @param {*} ext\n * @param {string} [name='']\n * @private\n */\n function _parseExtension (ext, name) {\n\n name = name || null;\n // If it's a string, the extension was previously loaded\n if (showdown.helper.isString(ext)) {\n ext = showdown.helper.stdExtName(ext);\n name = ext;\n\n // LEGACY_SUPPORT CODE\n if (showdown.extensions[ext]) {\n console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +\n 'Please inform the developer that the extension should be updated!');\n legacyExtensionLoading(showdown.extensions[ext], ext);\n return;\n // END LEGACY SUPPORT CODE\n\n } else if (!showdown.helper.isUndefined(extensions[ext])) {\n ext = extensions[ext];\n\n } else {\n throw Error('Extension \"' + ext + '\" could not be loaded. It was either not found or is not a valid extension.');\n }\n }\n\n if (typeof ext === 'function') {\n ext = ext();\n }\n\n if (!showdown.helper.isArray(ext)) {\n ext = [ext];\n }\n\n var validExt = validate(ext, name);\n if (!validExt.valid) {\n throw Error(validExt.error);\n }\n\n for (var i = 0; i < ext.length; ++i) {\n switch (ext[i].type) {\n\n case 'lang':\n langExtensions.push(ext[i]);\n break;\n\n case 'output':\n outputModifiers.push(ext[i]);\n break;\n }\n if (ext[i].hasOwnProperty('listeners')) {\n for (var ln in ext[i].listeners) {\n if (ext[i].listeners.hasOwnProperty(ln)) {\n listen(ln, ext[i].listeners[ln]);\n }\n }\n }\n }\n\n }\n\n /**\n * LEGACY_SUPPORT\n * @param {*} ext\n * @param {string} name\n */\n function legacyExtensionLoading (ext, name) {\n if (typeof ext === 'function') {\n ext = ext(new showdown.Converter());\n }\n if (!showdown.helper.isArray(ext)) {\n ext = [ext];\n }\n var valid = validate(ext, name);\n\n if (!valid.valid) {\n throw Error(valid.error);\n }\n\n for (var i = 0; i < ext.length; ++i) {\n switch (ext[i].type) {\n case 'lang':\n langExtensions.push(ext[i]);\n break;\n case 'output':\n outputModifiers.push(ext[i]);\n break;\n default:// should never reach here\n throw Error('Extension loader error: Type unrecognized!!!');\n }\n }\n }\n\n /**\n * Listen to an event\n * @param {string} name\n * @param {function} callback\n */\n function listen (name, callback) {\n if (!showdown.helper.isString(name)) {\n throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');\n }\n\n if (typeof callback !== 'function') {\n throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');\n }\n\n if (!listeners.hasOwnProperty(name)) {\n listeners[name] = [];\n }\n listeners[name].push(callback);\n }\n\n function rTrimInputText (text) {\n var rsp = text.match(/^\\s*/)[0].length,\n rgx = new RegExp('^\\\\s{0,' + rsp + '}', 'gm');\n return text.replace(rgx, '');\n }\n\n /**\n * Dispatch an event\n * @private\n * @param {string} evtName Event name\n * @param {string} text Text\n * @param {{}} options Converter Options\n * @param {{}} globals\n * @returns {string}\n */\n this._dispatch = function dispatch (evtName, text, options, globals) {\n if (listeners.hasOwnProperty(evtName)) {\n for (var ei = 0; ei < listeners[evtName].length; ++ei) {\n var nText = listeners[evtName][ei](evtName, text, this, options, globals);\n if (nText && typeof nText !== 'undefined') {\n text = nText;\n }\n }\n }\n return text;\n };\n\n /**\n * Listen to an event\n * @param {string} name\n * @param {function} callback\n * @returns {showdown.Converter}\n */\n this.listen = function (name, callback) {\n listen(name, callback);\n return this;\n };\n\n /**\n * Converts a markdown string into HTML\n * @param {string} text\n * @returns {*}\n */\n this.makeHtml = function (text) {\n //check if text is not falsy\n if (!text) {\n return text;\n }\n\n var globals = {\n gHtmlBlocks: [],\n gHtmlMdBlocks: [],\n gHtmlSpans: [],\n gUrls: {},\n gTitles: {},\n gDimensions: {},\n gListLevel: 0,\n hashLinkCounts: {},\n langExtensions: langExtensions,\n outputModifiers: outputModifiers,\n converter: this,\n ghCodeBlocks: [],\n metadata: {\n parsed: {},\n raw: '',\n format: ''\n }\n };\n\n // This lets us use ¨ trema as an escape char to avoid md5 hashes\n // The choice of character is arbitrary; anything that isn't\n // magic in Markdown will work.\n text = text.replace(/¨/g, '¨T');\n\n // Replace $ with ¨D\n // RegExp interprets $ as a special character\n // when it's in a replacement string\n text = text.replace(/\\$/g, '¨D');\n\n // Standardize line endings\n text = text.replace(/\\r\\n/g, '\\n'); // DOS to Unix\n text = text.replace(/\\r/g, '\\n'); // Mac to Unix\n\n // Stardardize line spaces\n text = text.replace(/\\u00A0/g, ' ');\n\n if (options.smartIndentationFix) {\n text = rTrimInputText(text);\n }\n\n // Make sure text begins and ends with a couple of newlines:\n text = '\\n\\n' + text + '\\n\\n';\n\n // detab\n text = showdown.subParser('detab')(text, options, globals);\n\n /**\n * Strip any lines consisting only of spaces and tabs.\n * This makes subsequent regexs easier to write, because we can\n * match consecutive blank lines with /\\n+/ instead of something\n * contorted like /[ \\t]*\\n+/\n */\n text = text.replace(/^[ \\t]+$/mg, '');\n\n //run languageExtensions\n showdown.helper.forEach(langExtensions, function (ext) {\n text = showdown.subParser('runExtension')(ext, text, options, globals);\n });\n\n // run the sub parsers\n text = showdown.subParser('metadata')(text, options, globals);\n text = showdown.subParser('hashPreCodeTags')(text, options, globals);\n text = showdown.subParser('githubCodeBlocks')(text, options, globals);\n text = showdown.subParser('hashHTMLBlocks')(text, options, globals);\n text = showdown.subParser('hashCodeTags')(text, options, globals);\n text = showdown.subParser('stripLinkDefinitions')(text, options, globals);\n text = showdown.subParser('blockGamut')(text, options, globals);\n text = showdown.subParser('unhashHTMLSpans')(text, options, globals);\n text = showdown.subParser('unescapeSpecialChars')(text, options, globals);\n\n // attacklab: Restore dollar signs\n text = text.replace(/¨D/g, '$$');\n\n // attacklab: Restore tremas\n text = text.replace(/¨T/g, '¨');\n\n // render a complete html document instead of a partial if the option is enabled\n text = showdown.subParser('completeHTMLDocument')(text, options, globals);\n\n // Run output modifiers\n showdown.helper.forEach(outputModifiers, function (ext) {\n text = showdown.subParser('runExtension')(ext, text, options, globals);\n });\n\n // update metadata\n metadata = globals.metadata;\n return text;\n };\n\n /**\n * Converts an HTML string into a markdown string\n * @param src\n * @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used.\n * @returns {string}\n */\n this.makeMarkdown = this.makeMd = function (src, HTMLParser) {\n\n // replace \\r\\n with \\n\n src = src.replace(/\\r\\n/g, '\\n');\n src = src.replace(/\\r/g, '\\n'); // old macs\n\n // due to an edge case, we need to find this: > <\n // to prevent removing of non silent white spaces\n // ex: this is sparta\n src = src.replace(/>[ \\t]+¨NBSP;<');\n\n if (!HTMLParser) {\n if (window && window.document) {\n HTMLParser = window.document;\n } else {\n throw new Error('HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM');\n }\n }\n\n var doc = HTMLParser.createElement('div');\n doc.innerHTML = src;\n\n var globals = {\n preList: substitutePreCodeTags(doc)\n };\n\n // remove all newlines and collapse spaces\n clean(doc);\n\n // some stuff, like accidental reference links must now be escaped\n // TODO\n // doc.innerHTML = doc.innerHTML.replace(/\\[[\\S\\t ]]/);\n\n var nodes = doc.childNodes,\n mdDoc = '';\n\n for (var i = 0; i < nodes.length; i++) {\n mdDoc += showdown.subParser('makeMarkdown.node')(nodes[i], globals);\n }\n\n function clean (node) {\n for (var n = 0; n < node.childNodes.length; ++n) {\n var child = node.childNodes[n];\n if (child.nodeType === 3) {\n if (!/\\S/.test(child.nodeValue) && !/^[ ]+$/.test(child.nodeValue)) {\n node.removeChild(child);\n --n;\n } else {\n child.nodeValue = child.nodeValue.split('\\n').join(' ');\n child.nodeValue = child.nodeValue.replace(/(\\s)+/g, '$1');\n }\n } else if (child.nodeType === 1) {\n clean(child);\n }\n }\n }\n\n // find all pre tags and replace contents with placeholder\n // we need this so that we can remove all indentation from html\n // to ease up parsing\n function substitutePreCodeTags (doc) {\n\n var pres = doc.querySelectorAll('pre'),\n presPH = [];\n\n for (var i = 0; i < pres.length; ++i) {\n\n if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {\n var content = pres[i].firstChild.innerHTML.trim(),\n language = pres[i].firstChild.getAttribute('data-language') || '';\n\n // if data-language attribute is not defined, then we look for class language-*\n if (language === '') {\n var classes = pres[i].firstChild.className.split(' ');\n for (var c = 0; c < classes.length; ++c) {\n var matches = classes[c].match(/^language-(.+)$/);\n if (matches !== null) {\n language = matches[1];\n break;\n }\n }\n }\n\n // unescape html entities in content\n content = showdown.helper.unescapeHTMLEntities(content);\n\n presPH.push(content);\n pres[i].outerHTML = '';\n } else {\n presPH.push(pres[i].innerHTML);\n pres[i].innerHTML = '';\n pres[i].setAttribute('prenum', i.toString());\n }\n }\n return presPH;\n }\n\n return mdDoc;\n };\n\n /**\n * Set an option of this Converter instance\n * @param {string} key\n * @param {*} value\n */\n this.setOption = function (key, value) {\n options[key] = value;\n };\n\n /**\n * Get the option of this Converter instance\n * @param {string} key\n * @returns {*}\n */\n this.getOption = function (key) {\n return options[key];\n };\n\n /**\n * Get the options of this Converter instance\n * @returns {{}}\n */\n this.getOptions = function () {\n return options;\n };\n\n /**\n * Add extension to THIS converter\n * @param {{}} extension\n * @param {string} [name=null]\n */\n this.addExtension = function (extension, name) {\n name = name || null;\n _parseExtension(extension, name);\n };\n\n /**\n * Use a global registered extension with THIS converter\n * @param {string} extensionName Name of the previously registered extension\n */\n this.useExtension = function (extensionName) {\n _parseExtension(extensionName);\n };\n\n /**\n * Set the flavor THIS converter should use\n * @param {string} name\n */\n this.setFlavor = function (name) {\n if (!flavor.hasOwnProperty(name)) {\n throw Error(name + ' flavor was not found');\n }\n var preset = flavor[name];\n setConvFlavor = name;\n for (var option in preset) {\n if (preset.hasOwnProperty(option)) {\n options[option] = preset[option];\n }\n }\n };\n\n /**\n * Get the currently set flavor of this converter\n * @returns {string}\n */\n this.getFlavor = function () {\n return setConvFlavor;\n };\n\n /**\n * Remove an extension from THIS converter.\n * Note: This is a costly operation. It's better to initialize a new converter\n * and specify the extensions you wish to use\n * @param {Array} extension\n */\n this.removeExtension = function (extension) {\n if (!showdown.helper.isArray(extension)) {\n extension = [extension];\n }\n for (var a = 0; a < extension.length; ++a) {\n var ext = extension[a];\n for (var i = 0; i < langExtensions.length; ++i) {\n if (langExtensions[i] === ext) {\n langExtensions.splice(i, 1);\n }\n }\n for (var ii = 0; ii < outputModifiers.length; ++ii) {\n if (outputModifiers[ii] === ext) {\n outputModifiers.splice(ii, 1);\n }\n }\n }\n };\n\n /**\n * Get all extension of THIS converter\n * @returns {{language: Array, output: Array}}\n */\n this.getAllExtensions = function () {\n return {\n language: langExtensions,\n output: outputModifiers\n };\n };\n\n /**\n * Get the metadata of the previously parsed document\n * @param raw\n * @returns {string|{}}\n */\n this.getMetadata = function (raw) {\n if (raw) {\n return metadata.raw;\n } else {\n return metadata.parsed;\n }\n };\n\n /**\n * Get the metadata format of the previously parsed document\n * @returns {string}\n */\n this.getMetadataFormat = function () {\n return metadata.format;\n };\n\n /**\n * Private: set a single key, value metadata pair\n * @param {string} key\n * @param {string} value\n */\n this._setMetadataPair = function (key, value) {\n metadata.parsed[key] = value;\n };\n\n /**\n * Private: set metadata format\n * @param {string} format\n */\n this._setMetadataFormat = function (format) {\n metadata.format = format;\n };\n\n /**\n * Private: set metadata raw text\n * @param {string} raw\n */\n this._setMetadataRaw = function (raw) {\n metadata.raw = raw;\n };\n};\n", "/**\n * Turn Markdown link shortcuts into XHTML tags.\n */\nshowdown.subParser('anchors', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('anchors.before', text, options, globals);\n\n var writeAnchorTag = function (wholeMatch, linkText, linkId, url, m5, m6, title) {\n if (showdown.helper.isUndefined(title)) {\n title = '';\n }\n linkId = linkId.toLowerCase();\n\n // Special case for explicit empty url\n if (wholeMatch.search(/\\(? ?(['\"].*['\"])?\\)$/m) > -1) {\n url = '';\n } else if (!url) {\n if (!linkId) {\n // lower-case and turn embedded newlines into spaces\n linkId = linkText.toLowerCase().replace(/ ?\\n/g, ' ');\n }\n url = '#' + linkId;\n\n if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {\n url = globals.gUrls[linkId];\n if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {\n title = globals.gTitles[linkId];\n }\n } else {\n return wholeMatch;\n }\n }\n\n //url = showdown.helper.escapeCharacters(url, '*_', false); // replaced line to improve performance\n url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n\n var result = '';\n\n return result;\n };\n\n // First, handle reference-style links: [link text] [id]\n text = text.replace(/\\[((?:\\[[^\\]]*]|[^\\[\\]])*)] ?(?:\\n *)?\\[(.*?)]()()()()/g, writeAnchorTag);\n\n // Next, inline-style links: [link text](url \"optional title\")\n // cases with crazy urls like ./image/cat1).png\n text = text.replace(/\\[((?:\\[[^\\]]*]|[^\\[\\]])*)]()[ \\t]*\\([ \\t]?<([^>]*)>(?:[ \\t]*(([\"'])([^\"]*?)\\5))?[ \\t]?\\)/g,\n writeAnchorTag);\n\n // normal cases\n text = text.replace(/\\[((?:\\[[^\\]]*]|[^\\[\\]])*)]()[ \\t]*\\([ \\t]??(?:[ \\t]*(([\"'])([^\"]*?)\\5))?[ \\t]?\\)/g,\n writeAnchorTag);\n\n // handle reference-style shortcuts: [link text]\n // These must come last in case you've also got [link test][1]\n // or [link test](/foo)\n text = text.replace(/\\[([^\\[\\]]+)]()()()()()/g, writeAnchorTag);\n\n // Lastly handle GithubMentions if option is enabled\n if (options.ghMentions) {\n text = text.replace(/(^|\\s)(\\\\)?(@([a-z\\d]+(?:[a-z\\d.-]+?[a-z\\d]+)*))/gmi, function (wm, st, escape, mentions, username) {\n if (escape === '\\\\') {\n return st + mentions;\n }\n\n //check if options.ghMentionsLink is a string\n if (!showdown.helper.isString(options.ghMentionsLink)) {\n throw new Error('ghMentionsLink option must be a string');\n }\n var lnk = options.ghMentionsLink.replace(/\\{u}/g, username),\n target = '';\n if (options.openLinksInNewWindow) {\n target = ' rel=\"noopener noreferrer\" target=\"¨E95Eblank\"';\n }\n return st + '' + mentions + '';\n });\n }\n\n text = globals.converter._dispatch('anchors.after', text, options, globals);\n return text;\n});\n", "// url allowed chars [a-z\\d_.~:/?#[]@!$&'()*+,;=-]\n\nvar simpleURLRegex = /([*~_]+|\\b)(((https?|ftp|dict):\\/\\/|www\\.)[^'\">\\s]+?\\.[^'\">\\s]+?)()(\\1)?(?=\\s|$)(?![\"<>])/gi,\n simpleURLRegex2 = /([*~_]+|\\b)(((https?|ftp|dict):\\/\\/|www\\.)[^'\">\\s]+\\.[^'\">\\s]+?)([.!?,()\\[\\]])?(\\1)?(?=\\s|$)(?![\"<>])/gi,\n delimUrlRegex = /()<(((https?|ftp|dict):\\/\\/|www\\.)[^'\">\\s]+)()>()/gi,\n simpleMailRegex = /(^|\\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)(?=$|\\s)/gmi,\n delimMailRegex = /<()(?:mailto:)?([-.\\w]+@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)>/gi,\n\n replaceLink = function (options) {\n 'use strict';\n return function (wm, leadingMagicChars, link, m2, m3, trailingPunctuation, trailingMagicChars) {\n link = link.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n var lnkTxt = link,\n append = '',\n target = '',\n lmc = leadingMagicChars || '',\n tmc = trailingMagicChars || '';\n if (/^www\\./i.test(link)) {\n link = link.replace(/^www\\./i, 'http://www.');\n }\n if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {\n append = trailingPunctuation;\n }\n if (options.openLinksInNewWindow) {\n target = ' rel=\"noopener noreferrer\" target=\"¨E95Eblank\"';\n }\n return lmc + '' + lnkTxt + '' + append + tmc;\n };\n },\n\n replaceMail = function (options, globals) {\n 'use strict';\n return function (wholeMatch, b, mail) {\n var href = 'mailto:';\n b = b || '';\n mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);\n if (options.encodeEmails) {\n href = showdown.helper.encodeEmailAddress(href + mail);\n mail = showdown.helper.encodeEmailAddress(mail);\n } else {\n href = href + mail;\n }\n return b + '' + mail + '';\n };\n };\n\nshowdown.subParser('autoLinks', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('autoLinks.before', text, options, globals);\n\n text = text.replace(delimUrlRegex, replaceLink(options));\n text = text.replace(delimMailRegex, replaceMail(options, globals));\n\n text = globals.converter._dispatch('autoLinks.after', text, options, globals);\n\n return text;\n});\n\nshowdown.subParser('simplifiedAutoLinks', function (text, options, globals) {\n 'use strict';\n\n if (!options.simplifiedAutoLink) {\n return text;\n }\n\n text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);\n\n if (options.excludeTrailingPunctuationFromURLs) {\n text = text.replace(simpleURLRegex2, replaceLink(options));\n } else {\n text = text.replace(simpleURLRegex, replaceLink(options));\n }\n text = text.replace(simpleMailRegex, replaceMail(options, globals));\n\n text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);\n\n return text;\n});\n", "/**\n * These are all the transformations that form block-level\n * tags like paragraphs, headers, and list items.\n */\nshowdown.subParser('blockGamut', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('blockGamut.before', text, options, globals);\n\n // we parse blockquotes first so that we can have headings and hrs\n // inside blockquotes\n text = showdown.subParser('blockQuotes')(text, options, globals);\n text = showdown.subParser('headers')(text, options, globals);\n\n // Do Horizontal Rules:\n text = showdown.subParser('horizontalRule')(text, options, globals);\n\n text = showdown.subParser('lists')(text, options, globals);\n text = showdown.subParser('codeBlocks')(text, options, globals);\n text = showdown.subParser('tables')(text, options, globals);\n\n // We already ran _HashHTMLBlocks() before, in Markdown(), but that\n // was to escape raw HTML in the original Markdown source. This time,\n // we're escaping the markup we've just created, so that we don't wrap\n //

tags around block-level tags.\n text = showdown.subParser('hashHTMLBlocks')(text, options, globals);\n text = showdown.subParser('paragraphs')(text, options, globals);\n\n text = globals.converter._dispatch('blockGamut.after', text, options, globals);\n\n return text;\n});\n", "showdown.subParser('blockQuotes', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('blockQuotes.before', text, options, globals);\n\n // add a couple extra lines after the text and endtext mark\n text = text + '\\n\\n';\n\n var rgx = /(^ {0,3}>[ \\t]?.+\\n(.+\\n)*\\n*)+/gm;\n\n if (options.splitAdjacentBlockquotes) {\n rgx = /^ {0,3}>[\\s\\S]*?(?:\\n\\n)/gm;\n }\n\n text = text.replace(rgx, function (bq) {\n // attacklab: hack around Konqueror 3.5.4 bug:\n // \"----------bug\".replace(/^-/g,\"\") == \"bug\"\n bq = bq.replace(/^[ \\t]*>[ \\t]?/gm, ''); // trim one level of quoting\n\n // attacklab: clean up hack\n bq = bq.replace(/¨0/g, '');\n\n bq = bq.replace(/^[ \\t]+$/gm, ''); // trim whitespace-only lines\n bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);\n bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse\n\n bq = bq.replace(/(^|\\n)/g, '$1 ');\n // These leading spaces screw with

 content, so we need to fix that:\n    bq = bq.replace(/(\\s*
[^\\r]+?<\\/pre>)/gm, function (wholeMatch, m1) {\n      var pre = m1;\n      // attacklab: hack around Konqueror 3.5.4 bug:\n      pre = pre.replace(/^  /mg, '¨0');\n      pre = pre.replace(/¨0/g, '');\n      return pre;\n    });\n\n    return showdown.subParser('hashBlock')('
\\n' + bq + '\\n
', options, globals);\n });\n\n text = globals.converter._dispatch('blockQuotes.after', text, options, globals);\n return text;\n});\n", "/**\n * Process Markdown `
` blocks.\n */\nshowdown.subParser('codeBlocks', function (text, options, globals) {\n  'use strict';\n\n  text = globals.converter._dispatch('codeBlocks.before', text, options, globals);\n\n  // sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug\n  text += '¨0';\n\n  var pattern = /(?:\\n\\n|^)((?:(?:[ ]{4}|\\t).*\\n+)+)(\\n*[ ]{0,3}[^ \\t\\n]|(?=¨0))/g;\n  text = text.replace(pattern, function (wholeMatch, m1, m2) {\n    var codeblock = m1,\n        nextChar = m2,\n        end = '\\n';\n\n    codeblock = showdown.subParser('outdent')(codeblock, options, globals);\n    codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);\n    codeblock = showdown.subParser('detab')(codeblock, options, globals);\n    codeblock = codeblock.replace(/^\\n+/g, ''); // trim leading newlines\n    codeblock = codeblock.replace(/\\n+$/g, ''); // trim trailing newlines\n\n    if (options.omitExtraWLInCodeBlocks) {\n      end = '';\n    }\n\n    codeblock = '
' + codeblock + end + '
';\n\n return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;\n });\n\n // strip sentinel\n text = text.replace(/¨0/, '');\n\n text = globals.converter._dispatch('codeBlocks.after', text, options, globals);\n return text;\n});\n", "/**\n *\n * * Backtick quotes are used for spans.\n *\n * * You can use multiple backticks as the delimiters if you want to\n * include literal backticks in the code span. So, this input:\n *\n * Just type ``foo `bar` baz`` at the prompt.\n *\n * Will translate to:\n *\n *

Just type foo `bar` baz at the prompt.

\n *\n * There's no arbitrary limit to the number of backticks you\n * can use as delimters. If you need three consecutive backticks\n * in your code, use four for delimiters, etc.\n *\n * * You can use spaces to get literal backticks at the edges:\n *\n * ... type `` `bar` `` ...\n *\n * Turns to:\n *\n * ... type `bar` ...\n */\nshowdown.subParser('codeSpans', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('codeSpans.before', text, options, globals);\n\n if (typeof (text) === 'undefined') {\n text = '';\n }\n text = text.replace(/(^|[^\\\\])(`+)([^\\r]*?[^`])\\2(?!`)/gm,\n function (wholeMatch, m1, m2, m3) {\n var c = m3;\n c = c.replace(/^([ \\t]*)/g, '');\t// leading whitespace\n c = c.replace(/[ \\t]*$/g, '');\t// trailing whitespace\n c = showdown.subParser('encodeCode')(c, options, globals);\n c = m1 + '' + c + '';\n c = showdown.subParser('hashHTMLSpans')(c, options, globals);\n return c;\n }\n );\n\n text = globals.converter._dispatch('codeSpans.after', text, options, globals);\n return text;\n});\n", "/**\n * Create a full HTML document from the processed markdown\n */\nshowdown.subParser('completeHTMLDocument', function (text, options, globals) {\n 'use strict';\n\n if (!options.completeHTMLDocument) {\n return text;\n }\n\n text = globals.converter._dispatch('completeHTMLDocument.before', text, options, globals);\n\n var doctype = 'html',\n doctypeParsed = '\\n',\n title = '',\n charset = '\\n',\n lang = '',\n metadata = '';\n\n if (typeof globals.metadata.parsed.doctype !== 'undefined') {\n doctypeParsed = '\\n';\n doctype = globals.metadata.parsed.doctype.toString().toLowerCase();\n if (doctype === 'html' || doctype === 'html5') {\n charset = '';\n }\n }\n\n for (var meta in globals.metadata.parsed) {\n if (globals.metadata.parsed.hasOwnProperty(meta)) {\n switch (meta.toLowerCase()) {\n case 'doctype':\n break;\n\n case 'title':\n title = '' + globals.metadata.parsed.title + '\\n';\n break;\n\n case 'charset':\n if (doctype === 'html' || doctype === 'html5') {\n charset = '\\n';\n } else {\n charset = '\\n';\n }\n break;\n\n case 'language':\n case 'lang':\n lang = ' lang=\"' + globals.metadata.parsed[meta] + '\"';\n metadata += '\\n';\n break;\n\n default:\n metadata += '\\n';\n }\n }\n }\n\n text = doctypeParsed + '\\n\\n' + title + charset + metadata + '\\n\\n' + text.trim() + '\\n\\n';\n\n text = globals.converter._dispatch('completeHTMLDocument.after', text, options, globals);\n return text;\n});\n", "/**\n * Convert all tabs to spaces\n */\nshowdown.subParser('detab', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('detab.before', text, options, globals);\n\n // expand first n-1 tabs\n text = text.replace(/\\t(?=\\t)/g, ' '); // g_tab_width\n\n // replace the nth with two sentinels\n text = text.replace(/\\t/g, '¨A¨B');\n\n // use the sentinel to anchor our regex so it doesn't explode\n text = text.replace(/¨B(.+?)¨A/g, function (wholeMatch, m1) {\n var leadingText = m1,\n numSpaces = 4 - leadingText.length % 4; // g_tab_width\n\n // there *must* be a better way to do this:\n for (var i = 0; i < numSpaces; i++) {\n leadingText += ' ';\n }\n\n return leadingText;\n });\n\n // clean up sentinels\n text = text.replace(/¨A/g, ' '); // g_tab_width\n text = text.replace(/¨B/g, '');\n\n text = globals.converter._dispatch('detab.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('ellipsis', function (text, options, globals) {\n 'use strict';\n\n if (!options.ellipsis) {\n return text;\n }\n\n text = globals.converter._dispatch('ellipsis.before', text, options, globals);\n\n text = text.replace(/\\.\\.\\./g, '…');\n\n text = globals.converter._dispatch('ellipsis.after', text, options, globals);\n\n return text;\n});\n", "/**\n * Turn emoji codes into emojis\n *\n * List of supported emojis: https://github.com/showdownjs/showdown/wiki/Emojis\n */\nshowdown.subParser('emoji', function (text, options, globals) {\n 'use strict';\n\n if (!options.emoji) {\n return text;\n }\n\n text = globals.converter._dispatch('emoji.before', text, options, globals);\n\n var emojiRgx = /:([\\S]+?):/g;\n\n text = text.replace(emojiRgx, function (wm, emojiCode) {\n if (showdown.helper.emojis.hasOwnProperty(emojiCode)) {\n return showdown.helper.emojis[emojiCode];\n }\n return wm;\n });\n\n text = globals.converter._dispatch('emoji.after', text, options, globals);\n\n return text;\n});\n", "/**\n * Smart processing for ampersands and angle brackets that need to be encoded.\n */\nshowdown.subParser('encodeAmpsAndAngles', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('encodeAmpsAndAngles.before', text, options, globals);\n\n // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:\n // http://bumppo.net/projects/amputator/\n text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)/g, '&');\n\n // Encode naked <'s\n text = text.replace(/<(?![a-z\\/?$!])/gi, '<');\n\n // Encode <\n text = text.replace(/\n text = text.replace(/>/g, '>');\n\n text = globals.converter._dispatch('encodeAmpsAndAngles.after', text, options, globals);\n return text;\n});\n", "/**\n * Returns the string, with after processing the following backslash escape sequences.\n *\n * attacklab: The polite way to do this is with the new escapeCharacters() function:\n *\n * text = escapeCharacters(text,\"\\\\\",true);\n * text = escapeCharacters(text,\"`*_{}[]()>#+-.!\",true);\n *\n * ...but we're sidestepping its use of the (slow) RegExp constructor\n * as an optimization for Firefox. This function gets called a LOT.\n */\nshowdown.subParser('encodeBackslashEscapes', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('encodeBackslashEscapes.before', text, options, globals);\n\n text = text.replace(/\\\\(\\\\)/g, showdown.helper.escapeCharactersCallback);\n text = text.replace(/\\\\([`*_{}\\[\\]()>#+.!~=|:-])/g, showdown.helper.escapeCharactersCallback);\n\n text = globals.converter._dispatch('encodeBackslashEscapes.after', text, options, globals);\n return text;\n});\n", "/**\n * Encode/escape certain characters inside Markdown code runs.\n * The point is that in code, these characters are literals,\n * and lose their special Markdown meanings.\n */\nshowdown.subParser('encodeCode', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('encodeCode.before', text, options, globals);\n\n // Encode all ampersands; HTML entities are not\n // entities within a Markdown code span.\n text = text\n .replace(/&/g, '&')\n // Do the angle bracket song and dance:\n .replace(//g, '>')\n // Now, escape characters that are magic in Markdown:\n .replace(/([*_{}\\[\\]\\\\=~-])/g, showdown.helper.escapeCharactersCallback);\n\n text = globals.converter._dispatch('encodeCode.after', text, options, globals);\n return text;\n});\n", "/**\n * Within tags -- meaning between < and > -- encode [\\ ` * _ ~ =] so they\n * don't conflict with their use in Markdown for code, italics and strong.\n */\nshowdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.before', text, options, globals);\n\n // Build a regex to find HTML tags.\n var tags = /<\\/?[a-z\\d_:-]+(?:[\\s]+[\\s\\S]+?)?>/gi,\n comments = /-]|-[^>])(?:[^-]|-[^-])*)--)>/gi;\n\n text = text.replace(tags, function (wholeMatch) {\n return wholeMatch\n .replace(/(.)<\\/?code>(?=.)/g, '$1`')\n .replace(/([\\\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);\n });\n\n text = text.replace(comments, function (wholeMatch) {\n return wholeMatch\n .replace(/([\\\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);\n });\n\n text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.after', text, options, globals);\n return text;\n});\n", "/**\n * Handle github codeblocks prior to running HashHTML so that\n * HTML contained within the codeblock gets escaped properly\n * Example:\n * ```ruby\n * def hello_world(x)\n * puts \"Hello, #{x}\"\n * end\n * ```\n */\nshowdown.subParser('githubCodeBlocks', function (text, options, globals) {\n 'use strict';\n\n // early exit if option is not enabled\n if (!options.ghCodeBlocks) {\n return text;\n }\n\n text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);\n\n text += '¨0';\n\n text = text.replace(/(?:^|\\n)(?: {0,3})(```+|~~~+)(?: *)([^\\s`~]*)\\n([\\s\\S]*?)\\n(?: {0,3})\\1/g, function (wholeMatch, delim, language, codeblock) {\n var end = (options.omitExtraWLInCodeBlocks) ? '' : '\\n';\n\n // First parse the github code block\n codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);\n codeblock = showdown.subParser('detab')(codeblock, options, globals);\n codeblock = codeblock.replace(/^\\n+/g, ''); // trim leading newlines\n codeblock = codeblock.replace(/\\n+$/g, ''); // trim trailing whitespace\n\n codeblock = '
' + codeblock + end + '
';\n\n codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);\n\n // Since GHCodeblocks can be false positives, we need to\n // store the primitive text and the parsed text in a global var,\n // and then return a token\n return '\\n\\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\\n\\n';\n });\n\n // attacklab: strip sentinel\n text = text.replace(/¨0/, '');\n\n return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);\n});\n", "showdown.subParser('hashBlock', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashBlock.before', text, options, globals);\n text = text.replace(/(^\\n+|\\n+$)/g, '');\n text = '\\n\\n¨K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\\n\\n';\n text = globals.converter._dispatch('hashBlock.after', text, options, globals);\n return text;\n});\n", "/**\n * Hash and escape elements that should not be parsed as markdown\n */\nshowdown.subParser('hashCodeTags', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashCodeTags.before', text, options, globals);\n\n var repFunc = function (wholeMatch, match, left, right) {\n var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;\n return '¨C' + (globals.gHtmlSpans.push(codeblock) - 1) + 'C';\n };\n\n // Hash naked \n text = showdown.helper.replaceRecursiveRegExp(text, repFunc, ']*>', '', 'gim');\n\n text = globals.converter._dispatch('hashCodeTags.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('hashElement', function (text, options, globals) {\n 'use strict';\n\n return function (wholeMatch, m1) {\n var blockText = m1;\n\n // Undo double lines\n blockText = blockText.replace(/\\n\\n/g, '\\n');\n blockText = blockText.replace(/^\\n/, '');\n\n // strip trailing blank lines\n blockText = blockText.replace(/\\n+$/g, '');\n\n // Replace the element text with a marker (\"¨KxK\" where x is its key)\n blockText = '\\n\\n¨K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\\n\\n';\n\n return blockText;\n };\n});\n", "showdown.subParser('hashHTMLBlocks', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashHTMLBlocks.before', text, options, globals);\n\n var blockTags = [\n 'pre',\n 'div',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'blockquote',\n 'table',\n 'dl',\n 'ol',\n 'ul',\n 'script',\n 'noscript',\n 'form',\n 'fieldset',\n 'iframe',\n 'math',\n 'style',\n 'section',\n 'header',\n 'footer',\n 'nav',\n 'article',\n 'aside',\n 'address',\n 'audio',\n 'canvas',\n 'figure',\n 'hgroup',\n 'output',\n 'video',\n 'p'\n ],\n repFunc = function (wholeMatch, match, left, right) {\n var txt = wholeMatch;\n // check if this html element is marked as markdown\n // if so, it's contents should be parsed as markdown\n if (left.search(/\\bmarkdown\\b/) !== -1) {\n txt = left + globals.converter.makeHtml(match) + right;\n }\n return '\\n\\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\\n\\n';\n };\n\n if (options.backslashEscapesHTMLTags) {\n // encode backslash escaped HTML tags\n text = text.replace(/\\\\<(\\/?[^>]+?)>/g, function (wm, inside) {\n return '<' + inside + '>';\n });\n }\n\n // hash HTML Blocks\n for (var i = 0; i < blockTags.length; ++i) {\n\n var opTagPos,\n rgx1 = new RegExp('^ {0,3}(<' + blockTags[i] + '\\\\b[^>]*>)', 'im'),\n patLeft = '<' + blockTags[i] + '\\\\b[^>]*>',\n patRight = '';\n // 1. Look for the first position of the first opening HTML tag in the text\n while ((opTagPos = showdown.helper.regexIndexOf(text, rgx1)) !== -1) {\n\n // if the HTML tag is \\ escaped, we need to escape it and break\n\n\n //2. Split the text in that position\n var subTexts = showdown.helper.splitAtIndex(text, opTagPos),\n //3. Match recursively\n newSubText1 = showdown.helper.replaceRecursiveRegExp(subTexts[1], repFunc, patLeft, patRight, 'im');\n\n // prevent an infinite loop\n if (newSubText1 === subTexts[1]) {\n break;\n }\n text = subTexts[0].concat(newSubText1);\n }\n }\n // HR SPECIAL CASE\n text = text.replace(/(\\n {0,3}(<(hr)\\b([^<>])*?\\/?>)[ \\t]*(?=\\n{2,}))/g,\n showdown.subParser('hashElement')(text, options, globals));\n\n // Special case for standalone HTML comments\n text = showdown.helper.replaceRecursiveRegExp(text, function (txt) {\n return '\\n\\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\\n\\n';\n }, '^ {0,3}', 'gm');\n\n // PHP and ASP-style processor instructions ( and <%...%>)\n text = text.replace(/(?:\\n\\n)( {0,3}(?:<([?%])[^\\r]*?\\2>)[ \\t]*(?=\\n{2,}))/g,\n showdown.subParser('hashElement')(text, options, globals));\n\n text = globals.converter._dispatch('hashHTMLBlocks.after', text, options, globals);\n return text;\n});\n", "/**\n * Hash span elements that should not be parsed as markdown\n */\nshowdown.subParser('hashHTMLSpans', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashHTMLSpans.before', text, options, globals);\n\n function hashHTMLSpan (html) {\n return '¨C' + (globals.gHtmlSpans.push(html) - 1) + 'C';\n }\n\n // Hash Self Closing tags\n text = text.replace(/<[^>]+?\\/>/gi, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n // Hash tags without properties\n text = text.replace(/<([^>]+?)>[\\s\\S]*?<\\/\\1>/g, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n // Hash tags with properties\n text = text.replace(/<([^>]+?)\\s[^>]+?>[\\s\\S]*?<\\/\\1>/g, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n // Hash self closing tags without />\n text = text.replace(/<[^>]+?>/gi, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n /*showdown.helper.matchRecursiveRegExp(text, ']*>', '', 'gi');*/\n\n text = globals.converter._dispatch('hashHTMLSpans.after', text, options, globals);\n return text;\n});\n\n/**\n * Unhash HTML spans\n */\nshowdown.subParser('unhashHTMLSpans', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('unhashHTMLSpans.before', text, options, globals);\n\n for (var i = 0; i < globals.gHtmlSpans.length; ++i) {\n var repText = globals.gHtmlSpans[i],\n // limiter to prevent infinite loop (assume 10 as limit for recurse)\n limit = 0;\n\n while (/¨C(\\d+)C/.test(repText)) {\n var num = RegExp.$1;\n repText = repText.replace('¨C' + num + 'C', globals.gHtmlSpans[num]);\n if (limit === 10) {\n console.error('maximum nesting of 10 spans reached!!!');\n break;\n }\n ++limit;\n }\n text = text.replace('¨C' + i + 'C', repText);\n }\n\n text = globals.converter._dispatch('unhashHTMLSpans.after', text, options, globals);\n return text;\n});\n", "/**\n * Hash and escape
 elements that should not be parsed as markdown\n */\nshowdown.subParser('hashPreCodeTags', function (text, options, globals) {\n  'use strict';\n  text = globals.converter._dispatch('hashPreCodeTags.before', text, options, globals);\n\n  var repFunc = function (wholeMatch, match, left, right) {\n    // encode html entities\n    var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;\n    return '\\n\\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\\n\\n';\n  };\n\n  // Hash 
\n  text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}]*>\\\\s*]*>', '^ {0,3}\\\\s*
', 'gim');\n\n text = globals.converter._dispatch('hashPreCodeTags.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('headers', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('headers.before', text, options, globals);\n\n var headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),\n\n // Set text-style headers:\n //\tHeader 1\n //\t========\n //\n //\tHeader 2\n //\t--------\n //\n setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \\t]*\\n={2,}[ \\t]*\\n+/gm : /^(.+)[ \\t]*\\n=+[ \\t]*\\n+/gm,\n setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \\t]*\\n-{2,}[ \\t]*\\n+/gm : /^(.+)[ \\t]*\\n-+[ \\t]*\\n+/gm;\n\n text = text.replace(setextRegexH1, function (wholeMatch, m1) {\n\n var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),\n hID = (options.noHeaderId) ? '' : ' id=\"' + headerId(m1) + '\"',\n hLevel = headerLevelStart,\n hashBlock = '' + spanGamut + '';\n return showdown.subParser('hashBlock')(hashBlock, options, globals);\n });\n\n text = text.replace(setextRegexH2, function (matchFound, m1) {\n var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),\n hID = (options.noHeaderId) ? '' : ' id=\"' + headerId(m1) + '\"',\n hLevel = headerLevelStart + 1,\n hashBlock = '' + spanGamut + '';\n return showdown.subParser('hashBlock')(hashBlock, options, globals);\n });\n\n // atx-style headers:\n // # Header 1\n // ## Header 2\n // ## Header 2 with closing hashes ##\n // ...\n // ###### Header 6\n //\n var atxStyle = (options.requireSpaceBeforeHeadingText) ? /^(#{1,6})[ \\t]+(.+?)[ \\t]*#*\\n+/gm : /^(#{1,6})[ \\t]*(.+?)[ \\t]*#*\\n+/gm;\n\n text = text.replace(atxStyle, function (wholeMatch, m1, m2) {\n var hText = m2;\n if (options.customizedHeaderId) {\n hText = m2.replace(/\\s?\\{([^{]+?)}\\s*$/, '');\n }\n\n var span = showdown.subParser('spanGamut')(hText, options, globals),\n hID = (options.noHeaderId) ? '' : ' id=\"' + headerId(m2) + '\"',\n hLevel = headerLevelStart - 1 + m1.length,\n header = '' + span + '';\n\n return showdown.subParser('hashBlock')(header, options, globals);\n });\n\n function headerId (m) {\n var title,\n prefix;\n\n // It is separate from other options to allow combining prefix and customized\n if (options.customizedHeaderId) {\n var match = m.match(/\\{([^{]+?)}\\s*$/);\n if (match && match[1]) {\n m = match[1];\n }\n }\n\n title = m;\n\n // Prefix id to prevent causing inadvertent pre-existing style matches.\n if (showdown.helper.isString(options.prefixHeaderId)) {\n prefix = options.prefixHeaderId;\n } else if (options.prefixHeaderId === true) {\n prefix = 'section-';\n } else {\n prefix = '';\n }\n\n if (!options.rawPrefixHeaderId) {\n title = prefix + title;\n }\n\n if (options.ghCompatibleHeaderId) {\n title = title\n .replace(/ /g, '-')\n // replace previously escaped chars (&, ¨ and $)\n .replace(/&/g, '')\n .replace(/¨T/g, '')\n .replace(/¨D/g, '')\n // replace rest of the chars (&~$ are repeated as they might have been escaped)\n // borrowed from github's redcarpet (some they should produce similar results)\n .replace(/[&+$,\\/:;=?@\"#{}|^¨~\\[\\]`\\\\*)(%.!'<>]/g, '')\n .toLowerCase();\n } else if (options.rawHeaderId) {\n title = title\n .replace(/ /g, '-')\n // replace previously escaped chars (&, ¨ and $)\n .replace(/&/g, '&')\n .replace(/¨T/g, '¨')\n .replace(/¨D/g, '$')\n // replace \" and '\n .replace(/[\"']/g, '-')\n .toLowerCase();\n } else {\n title = title\n .replace(/[^\\w]/g, '')\n .toLowerCase();\n }\n\n if (options.rawPrefixHeaderId) {\n title = prefix + title;\n }\n\n if (globals.hashLinkCounts[title]) {\n title = title + '-' + (globals.hashLinkCounts[title]++);\n } else {\n globals.hashLinkCounts[title] = 1;\n }\n return title;\n }\n\n text = globals.converter._dispatch('headers.after', text, options, globals);\n return text;\n});\n", "/**\n * Turn Markdown link shortcuts into XHTML tags.\n */\nshowdown.subParser('horizontalRule', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('horizontalRule.before', text, options, globals);\n\n var key = showdown.subParser('hashBlock')('
', options, globals);\n text = text.replace(/^ {0,2}( ?-){3,}[ \\t]*$/gm, key);\n text = text.replace(/^ {0,2}( ?\\*){3,}[ \\t]*$/gm, key);\n text = text.replace(/^ {0,2}( ?_){3,}[ \\t]*$/gm, key);\n\n text = globals.converter._dispatch('horizontalRule.after', text, options, globals);\n return text;\n});\n", "/**\n * Turn Markdown image shortcuts into tags.\n */\nshowdown.subParser('images', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('images.before', text, options, globals);\n\n var inlineRegExp = /!\\[([^\\]]*?)][ \\t]*()\\([ \\t]??(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*(?:([\"'])([^\"]*?)\\6)?[ \\t]?\\)/g,\n crazyRegExp = /!\\[([^\\]]*?)][ \\t]*()\\([ \\t]?<([^>]*)>(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*(?:(?:([\"'])([^\"]*?)\\6))?[ \\t]?\\)/g,\n base64RegExp = /!\\[([^\\]]*?)][ \\t]*()\\([ \\t]??(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*(?:([\"'])([^\"]*?)\\6)?[ \\t]?\\)/g,\n referenceRegExp = /!\\[([^\\]]*?)] ?(?:\\n *)?\\[([\\s\\S]*?)]()()()()()/g,\n refShortcutRegExp = /!\\[([^\\[\\]]+)]()()()()()/g;\n\n function writeImageTagBase64 (wholeMatch, altText, linkId, url, width, height, m5, title) {\n url = url.replace(/\\s/g, '');\n return writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title);\n }\n\n function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {\n\n var gUrls = globals.gUrls,\n gTitles = globals.gTitles,\n gDims = globals.gDimensions;\n\n linkId = linkId.toLowerCase();\n\n if (!title) {\n title = '';\n }\n // Special case for explicit empty url\n if (wholeMatch.search(/\\(? ?(['\"].*['\"])?\\)$/m) > -1) {\n url = '';\n\n } else if (url === '' || url === null) {\n if (linkId === '' || linkId === null) {\n // lower-case and turn embedded newlines into spaces\n linkId = altText.toLowerCase().replace(/ ?\\n/g, ' ');\n }\n url = '#' + linkId;\n\n if (!showdown.helper.isUndefined(gUrls[linkId])) {\n url = gUrls[linkId];\n if (!showdown.helper.isUndefined(gTitles[linkId])) {\n title = gTitles[linkId];\n }\n if (!showdown.helper.isUndefined(gDims[linkId])) {\n width = gDims[linkId].width;\n height = gDims[linkId].height;\n }\n } else {\n return wholeMatch;\n }\n }\n\n altText = altText\n .replace(/\"/g, '"')\n //altText = showdown.helper.escapeCharacters(altText, '*_', false);\n .replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n //url = showdown.helper.escapeCharacters(url, '*_', false);\n url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n var result = '\"'x \"optional title\")\n\n // base64 encoded images\n text = text.replace(base64RegExp, writeImageTagBase64);\n\n // cases with crazy urls like ./image/cat1).png\n text = text.replace(crazyRegExp, writeImageTag);\n\n // normal cases\n text = text.replace(inlineRegExp, writeImageTag);\n\n // handle reference-style shortcuts: ![img text]\n text = text.replace(refShortcutRegExp, writeImageTag);\n\n text = globals.converter._dispatch('images.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('italicsAndBold', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);\n\n // it's faster to have 3 separate regexes for each case than have just one\n // because of backtracing, in some cases, it could lead to an exponential effect\n // called \"catastrophic backtrace\". Ominous!\n\n function parseInside (txt, left, right) {\n /*\n if (options.simplifiedAutoLink) {\n txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);\n }\n */\n return left + txt + right;\n }\n\n // Parse underscores\n if (options.literalMidWordUnderscores) {\n text = text.replace(/\\b___(\\S[\\s\\S]*?)___\\b/g, function (wm, txt) {\n return parseInside (txt, '', '');\n });\n text = text.replace(/\\b__(\\S[\\s\\S]*?)__\\b/g, function (wm, txt) {\n return parseInside (txt, '', '');\n });\n text = text.replace(/\\b_(\\S[\\s\\S]*?)_\\b/g, function (wm, txt) {\n return parseInside (txt, '', '');\n });\n } else {\n text = text.replace(/___(\\S[\\s\\S]*?)___/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/__(\\S[\\s\\S]*?)__/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/_([^\\s_][\\s\\S]*?)_/g, function (wm, m) {\n // !/^_[^_]/.test(m) - test if it doesn't start with __ (since it seems redundant, we removed it)\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n }\n\n // Now parse asterisks\n if (options.literalMidWordAsterisks) {\n text = text.replace(/([^*]|^)\\B\\*\\*\\*(\\S[\\s\\S]*?)\\*\\*\\*\\B(?!\\*)/g, function (wm, lead, txt) {\n return parseInside (txt, lead + '', '');\n });\n text = text.replace(/([^*]|^)\\B\\*\\*(\\S[\\s\\S]*?)\\*\\*\\B(?!\\*)/g, function (wm, lead, txt) {\n return parseInside (txt, lead + '', '');\n });\n text = text.replace(/([^*]|^)\\B\\*(\\S[\\s\\S]*?)\\*\\B(?!\\*)/g, function (wm, lead, txt) {\n return parseInside (txt, lead + '', '');\n });\n } else {\n text = text.replace(/\\*\\*\\*(\\S[\\s\\S]*?)\\*\\*\\*/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/\\*\\*(\\S[\\s\\S]*?)\\*\\*/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/\\*([^\\s*][\\s\\S]*?)\\*/g, function (wm, m) {\n // !/^\\*[^*]/.test(m) - test if it doesn't start with ** (since it seems redundant, we removed it)\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n }\n\n\n text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);\n return text;\n});\n", "/**\n * Form HTML ordered (numbered) and unordered (bulleted) lists.\n */\nshowdown.subParser('lists', function (text, options, globals) {\n 'use strict';\n\n /**\n * Process the contents of a single ordered or unordered list, splitting it\n * into individual list items.\n * @param {string} listStr\n * @param {boolean} trimTrailing\n * @returns {string}\n */\n function processListItems (listStr, trimTrailing) {\n // The $g_list_level global keeps track of when we're inside a list.\n // Each time we enter a list, we increment it; when we leave a list,\n // we decrement. If it's zero, we're not in a list anymore.\n //\n // We do this because when we're not inside a list, we want to treat\n // something like this:\n //\n // I recommend upgrading to version\n // 8. Oops, now this line is treated\n // as a sub-list.\n //\n // As a single paragraph, despite the fact that the second line starts\n // with a digit-period-space sequence.\n //\n // Whereas when we're inside a list (or sub-list), that line will be\n // treated as the start of a sub-list. What a kludge, huh? This is\n // an aspect of Markdown's syntax that's hard to parse perfectly\n // without resorting to mind-reading. Perhaps the solution is to\n // change the syntax rules such that sub-lists must start with a\n // starting cardinal number; e.g. \"1.\" or \"a.\".\n globals.gListLevel++;\n\n // trim trailing blank lines:\n listStr = listStr.replace(/\\n{2,}$/, '\\n');\n\n // attacklab: add sentinel to emulate \\z\n listStr += '¨0';\n\n var rgx = /(\\n)?(^ {0,3})([*+-]|\\d+[.])[ \\t]+((\\[(x|X| )?])?[ \\t]*[^\\r]+?(\\n{1,2}))(?=\\n*(¨0| {0,3}([*+-]|\\d+[.])[ \\t]+))/gm,\n isParagraphed = (/\\n[ \\t]*\\n(?!¨0)/.test(listStr));\n\n // Since version 1.5, nesting sublists requires 4 spaces (or 1 tab) indentation,\n // which is a syntax breaking change\n // activating this option reverts to old behavior\n if (options.disableForced4SpacesIndentedSublists) {\n rgx = /(\\n)?(^ {0,3})([*+-]|\\d+[.])[ \\t]+((\\[(x|X| )?])?[ \\t]*[^\\r]+?(\\n{1,2}))(?=\\n*(¨0|\\2([*+-]|\\d+[.])[ \\t]+))/gm;\n }\n\n listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {\n checked = (checked && checked.trim() !== '');\n\n var item = showdown.subParser('outdent')(m4, options, globals),\n bulletStyle = '';\n\n // Support for github tasklists\n if (taskbtn && options.tasklists) {\n bulletStyle = ' class=\"task-list-item\" style=\"list-style-type: none;\"';\n item = item.replace(/^[ \\t]*\\[(x|X| )?]/m, function () {\n var otp = '
  • a
  • \n // instead of:\n //
    • - - a
    \n // So, to prevent it, we will put a marker (¨A)in the beginning of the line\n // Kind of hackish/monkey patching, but seems more effective than overcomplicating the list parser\n item = item.replace(/^([-*+]|\\d\\.)[ \\t]+[\\S\\n ]*/g, function (wm2) {\n return '¨A' + wm2;\n });\n\n // m1 - Leading line or\n // Has a double return (multi paragraph) or\n // Has sublist\n if (m1 || (item.search(/\\n{2,}/) > -1)) {\n item = showdown.subParser('githubCodeBlocks')(item, options, globals);\n item = showdown.subParser('blockGamut')(item, options, globals);\n } else {\n // Recursion for sub-lists:\n item = showdown.subParser('lists')(item, options, globals);\n item = item.replace(/\\n$/, ''); // chomp(item)\n item = showdown.subParser('hashHTMLBlocks')(item, options, globals);\n\n // Colapse double linebreaks\n item = item.replace(/\\n\\n+/g, '\\n\\n');\n if (isParagraphed) {\n item = showdown.subParser('paragraphs')(item, options, globals);\n } else {\n item = showdown.subParser('spanGamut')(item, options, globals);\n }\n }\n\n // now we need to remove the marker (¨A)\n item = item.replace('¨A', '');\n // we can finally wrap the line in list item tags\n item = '' + item + '\\n';\n\n return item;\n });\n\n // attacklab: strip sentinel\n listStr = listStr.replace(/¨0/g, '');\n\n globals.gListLevel--;\n\n if (trimTrailing) {\n listStr = listStr.replace(/\\s+$/, '');\n }\n\n return listStr;\n }\n\n function styleStartNumber (list, listType) {\n // check if ol and starts by a number different than 1\n if (listType === 'ol') {\n var res = list.match(/^ *(\\d+)\\./);\n if (res && res[1] !== '1') {\n return ' start=\"' + res[1] + '\"';\n }\n }\n return '';\n }\n\n /**\n * Check and parse consecutive lists (better fix for issue #142)\n * @param {string} list\n * @param {string} listType\n * @param {boolean} trimTrailing\n * @returns {string}\n */\n function parseConsecutiveLists (list, listType, trimTrailing) {\n // check if we caught 2 or more consecutive lists by mistake\n // we use the counterRgx, meaning if listType is UL we look for OL and vice versa\n var olRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?\\d+\\.[ \\t]/gm : /^ {0,3}\\d+\\.[ \\t]/gm,\n ulRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?[*+-][ \\t]/gm : /^ {0,3}[*+-][ \\t]/gm,\n counterRxg = (listType === 'ul') ? olRgx : ulRgx,\n result = '';\n\n if (list.search(counterRxg) !== -1) {\n (function parseCL (txt) {\n var pos = txt.search(counterRxg),\n style = styleStartNumber(list, listType);\n if (pos !== -1) {\n // slice\n result += '\\n\\n<' + listType + style + '>\\n' + processListItems(txt.slice(0, pos), !!trimTrailing) + '\\n';\n\n // invert counterType and listType\n listType = (listType === 'ul') ? 'ol' : 'ul';\n counterRxg = (listType === 'ul') ? olRgx : ulRgx;\n\n //recurse\n parseCL(txt.slice(pos));\n } else {\n result += '\\n\\n<' + listType + style + '>\\n' + processListItems(txt, !!trimTrailing) + '\\n';\n }\n })(list);\n } else {\n var style = styleStartNumber(list, listType);\n result = '\\n\\n<' + listType + style + '>\\n' + processListItems(list, !!trimTrailing) + '\\n';\n }\n\n return result;\n }\n\n /** Start of list parsing **/\n text = globals.converter._dispatch('lists.before', text, options, globals);\n // add sentinel to hack around khtml/safari bug:\n // http://bugs.webkit.org/show_bug.cgi?id=11231\n text += '¨0';\n\n if (globals.gListLevel) {\n text = text.replace(/^(( {0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(¨0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm,\n function (wholeMatch, list, m2) {\n var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';\n return parseConsecutiveLists(list, listType, true);\n }\n );\n } else {\n text = text.replace(/(\\n\\n|^\\n?)(( {0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(¨0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm,\n function (wholeMatch, m1, list, m3) {\n var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';\n return parseConsecutiveLists(list, listType, false);\n }\n );\n }\n\n // strip sentinel\n text = text.replace(/¨0/, '');\n text = globals.converter._dispatch('lists.after', text, options, globals);\n return text;\n});\n", "/**\n * Parse metadata at the top of the document\n */\nshowdown.subParser('metadata', function (text, options, globals) {\n 'use strict';\n\n if (!options.metadata) {\n return text;\n }\n\n text = globals.converter._dispatch('metadata.before', text, options, globals);\n\n function parseMetadataContents (content) {\n // raw is raw so it's not changed in any way\n globals.metadata.raw = content;\n\n // escape chars forbidden in html attributes\n // double quotes\n content = content\n // ampersand first\n .replace(/&/g, '&')\n // double quotes\n .replace(/\"/g, '"');\n\n content = content.replace(/\\n {4}/g, ' ');\n content.replace(/^([\\S ]+): +([\\s\\S]+?)$/gm, function (wm, key, value) {\n globals.metadata.parsed[key] = value;\n return '';\n });\n }\n\n text = text.replace(/^\\s*«««+(\\S*?)\\n([\\s\\S]+?)\\n»»»+\\n/, function (wholematch, format, content) {\n parseMetadataContents(content);\n return '¨M';\n });\n\n text = text.replace(/^\\s*---+(\\S*?)\\n([\\s\\S]+?)\\n---+\\n/, function (wholematch, format, content) {\n if (format) {\n globals.metadata.format = format;\n }\n parseMetadataContents(content);\n return '¨M';\n });\n\n text = text.replace(/¨M/g, '');\n\n text = globals.converter._dispatch('metadata.after', text, options, globals);\n return text;\n});\n", "/**\n * Remove one level of line-leading tabs or spaces\n */\nshowdown.subParser('outdent', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('outdent.before', text, options, globals);\n\n // attacklab: hack around Konqueror 3.5.4 bug:\n // \"----------bug\".replace(/^-/g,\"\") == \"bug\"\n text = text.replace(/^(\\t|[ ]{1,4})/gm, '¨0'); // attacklab: g_tab_width\n\n // attacklab: clean up hack\n text = text.replace(/¨0/g, '');\n\n text = globals.converter._dispatch('outdent.after', text, options, globals);\n return text;\n});\n", "/**\n *\n */\nshowdown.subParser('paragraphs', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('paragraphs.before', text, options, globals);\n // Strip leading and trailing lines:\n text = text.replace(/^\\n+/g, '');\n text = text.replace(/\\n+$/g, '');\n\n var grafs = text.split(/\\n{2,}/g),\n grafsOut = [],\n end = grafs.length; // Wrap

    tags\n\n for (var i = 0; i < end; i++) {\n var str = grafs[i];\n // if this is an HTML marker, copy it\n if (str.search(/¨(K|G)(\\d+)\\1/g) >= 0) {\n grafsOut.push(str);\n\n // test for presence of characters to prevent empty lines being parsed\n // as paragraphs (resulting in undesired extra empty paragraphs)\n } else if (str.search(/\\S/) >= 0) {\n str = showdown.subParser('spanGamut')(str, options, globals);\n str = str.replace(/^([ \\t]*)/g, '

    ');\n str += '

    ';\n grafsOut.push(str);\n }\n }\n\n /** Unhashify HTML blocks */\n end = grafsOut.length;\n for (i = 0; i < end; i++) {\n var blockText = '',\n grafsOutIt = grafsOut[i],\n codeFlag = false;\n // if this is a marker for an html block...\n // use RegExp.test instead of string.search because of QML bug\n while (/¨(K|G)(\\d+)\\1/.test(grafsOutIt)) {\n var delim = RegExp.$1,\n num = RegExp.$2;\n\n if (delim === 'K') {\n blockText = globals.gHtmlBlocks[num];\n } else {\n // we need to check if ghBlock is a false positive\n if (codeFlag) {\n // use encoded version of all text\n blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text, options, globals);\n } else {\n blockText = globals.ghCodeBlocks[num].codeblock;\n }\n }\n blockText = blockText.replace(/\\$/g, '$$$$'); // Escape any dollar signs\n\n grafsOutIt = grafsOutIt.replace(/(\\n\\n)?¨(K|G)\\d+\\2(\\n\\n)?/, blockText);\n // Check if grafsOutIt is a pre->code\n if (/^]*>\\s*]*>/.test(grafsOutIt)) {\n codeFlag = true;\n }\n }\n grafsOut[i] = grafsOutIt;\n }\n text = grafsOut.join('\\n');\n // Strip leading and trailing lines:\n text = text.replace(/^\\n+/g, '');\n text = text.replace(/\\n+$/g, '');\n return globals.converter._dispatch('paragraphs.after', text, options, globals);\n});\n", "/**\n * Run extension\n */\nshowdown.subParser('runExtension', function (ext, text, options, globals) {\n 'use strict';\n\n if (ext.filter) {\n text = ext.filter(text, globals.converter, options);\n\n } else if (ext.regex) {\n // TODO remove this when old extension loading mechanism is deprecated\n var re = ext.regex;\n if (!(re instanceof RegExp)) {\n re = new RegExp(re, 'g');\n }\n text = text.replace(re, ext.replace);\n }\n\n return text;\n});\n", "/**\n * These are all the transformations that occur *within* block-level\n * tags like paragraphs, headers, and list items.\n */\nshowdown.subParser('spanGamut', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('spanGamut.before', text, options, globals);\n text = showdown.subParser('codeSpans')(text, options, globals);\n text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);\n text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);\n\n // Process anchor and image tags. Images must come first,\n // because ![foo][f] looks like an anchor.\n text = showdown.subParser('images')(text, options, globals);\n text = showdown.subParser('anchors')(text, options, globals);\n\n // Make links out of things like ``\n // Must come after anchors, because you can use < and >\n // delimiters in inline links like [this]().\n text = showdown.subParser('autoLinks')(text, options, globals);\n text = showdown.subParser('simplifiedAutoLinks')(text, options, globals);\n text = showdown.subParser('emoji')(text, options, globals);\n text = showdown.subParser('underline')(text, options, globals);\n text = showdown.subParser('italicsAndBold')(text, options, globals);\n text = showdown.subParser('strikethrough')(text, options, globals);\n text = showdown.subParser('ellipsis')(text, options, globals);\n\n // we need to hash HTML tags inside spans\n text = showdown.subParser('hashHTMLSpans')(text, options, globals);\n\n // now we encode amps and angles\n text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);\n\n // Do hard breaks\n if (options.simpleLineBreaks) {\n // GFM style hard breaks\n // only add line breaks if the text does not contain a block (special case for lists)\n if (!/\\n\\n¨K/.test(text)) {\n text = text.replace(/\\n+/g, '
    \\n');\n }\n } else {\n // Vanilla hard breaks\n text = text.replace(/ +\\n/g, '
    \\n');\n }\n\n text = globals.converter._dispatch('spanGamut.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('strikethrough', function (text, options, globals) {\n 'use strict';\n\n function parseInside (txt) {\n if (options.simplifiedAutoLink) {\n txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);\n }\n return '' + txt + '';\n }\n\n if (options.strikethrough) {\n text = globals.converter._dispatch('strikethrough.before', text, options, globals);\n text = text.replace(/(?:~){2}([\\s\\S]+?)(?:~){2}/g, function (wm, txt) { return parseInside(txt); });\n text = globals.converter._dispatch('strikethrough.after', text, options, globals);\n }\n\n return text;\n});\n", "/**\n * Strips link definitions from text, stores the URLs and titles in\n * hash references.\n * Link defs are in the form: ^[id]: url \"optional title\"\n */\nshowdown.subParser('stripLinkDefinitions', function (text, options, globals) {\n 'use strict';\n\n var regex = /^ {0,3}\\[([^\\]]+)]:[ \\t]*\\n?[ \\t]*\\s]+)>?(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*\\n?[ \\t]*(?:(\\n*)[\"|'(](.+?)[\"|')][ \\t]*)?(?:\\n+|(?=¨0))/gm,\n base64Regex = /^ {0,3}\\[([^\\]]+)]:[ \\t]*\\n?[ \\t]*?(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*\\n?[ \\t]*(?:(\\n*)[\"|'(](.+?)[\"|')][ \\t]*)?(?:\\n\\n|(?=¨0)|(?=\\n\\[))/gm;\n\n // attacklab: sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug\n text += '¨0';\n\n var replaceFunc = function (wholeMatch, linkId, url, width, height, blankLines, title) {\n\n // if there aren't two instances of linkId it must not be a reference link so back out\n linkId = linkId.toLowerCase();\n if (text.toLowerCase().split(linkId).length - 1 < 2) {\n return wholeMatch;\n }\n if (url.match(/^data:.+?\\/.+?;base64,/)) {\n // remove newlines\n globals.gUrls[linkId] = url.replace(/\\s/g, '');\n } else {\n globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url, options, globals); // Link IDs are case-insensitive\n }\n\n if (blankLines) {\n // Oops, found blank lines, so it's not a title.\n // Put back the parenthetical statement we stole.\n return blankLines + title;\n\n } else {\n if (title) {\n globals.gTitles[linkId] = title.replace(/\"|'/g, '"');\n }\n if (options.parseImgDimensions && width && height) {\n globals.gDimensions[linkId] = {\n width: width,\n height: height\n };\n }\n }\n // Completely remove the definition from the text\n return '';\n };\n\n // first we try to find base64 link references\n text = text.replace(base64Regex, replaceFunc);\n\n text = text.replace(regex, replaceFunc);\n\n // attacklab: strip sentinel\n text = text.replace(/¨0/, '');\n\n return text;\n});\n", "showdown.subParser('tables', function (text, options, globals) {\n 'use strict';\n\n if (!options.tables) {\n return text;\n }\n\n var tableRgx = /^ {0,3}\\|?.+\\|.+\\n {0,3}\\|?[ \\t]*:?[ \\t]*(?:[-=]){2,}[ \\t]*:?[ \\t]*\\|[ \\t]*:?[ \\t]*(?:[-=]){2,}[\\s\\S]+?(?:\\n\\n|¨0)/gm,\n //singeColTblRgx = /^ {0,3}\\|.+\\|\\n {0,3}\\|[ \\t]*:?[ \\t]*(?:[-=]){2,}[ \\t]*:?[ \\t]*\\|[ \\t]*\\n(?: {0,3}\\|.+\\|\\n)+(?:\\n\\n|¨0)/gm;\n singeColTblRgx = /^ {0,3}\\|.+\\|[ \\t]*\\n {0,3}\\|[ \\t]*:?[ \\t]*(?:[-=]){2,}[ \\t]*:?[ \\t]*\\|[ \\t]*\\n( {0,3}\\|.+\\|[ \\t]*\\n)*(?:\\n|¨0)/gm;\n\n function parseStyles (sLine) {\n if (/^:[ \\t]*--*$/.test(sLine)) {\n return ' style=\"text-align:left;\"';\n } else if (/^--*[ \\t]*:[ \\t]*$/.test(sLine)) {\n return ' style=\"text-align:right;\"';\n } else if (/^:[ \\t]*--*[ \\t]*:$/.test(sLine)) {\n return ' style=\"text-align:center;\"';\n } else {\n return '';\n }\n }\n\n function parseHeaders (header, style) {\n var id = '';\n header = header.trim();\n // support both tablesHeaderId and tableHeaderId due to error in documentation so we don't break backwards compatibility\n if (options.tablesHeaderId || options.tableHeaderId) {\n id = ' id=\"' + header.replace(/ /g, '_').toLowerCase() + '\"';\n }\n header = showdown.subParser('spanGamut')(header, options, globals);\n\n return '' + header + '\\n';\n }\n\n function parseCells (cell, style) {\n var subText = showdown.subParser('spanGamut')(cell, options, globals);\n return '' + subText + '\\n';\n }\n\n function buildTable (headers, cells) {\n var tb = '\\n\\n\\n',\n tblLgn = headers.length;\n\n for (var i = 0; i < tblLgn; ++i) {\n tb += headers[i];\n }\n tb += '\\n\\n\\n';\n\n for (i = 0; i < cells.length; ++i) {\n tb += '\\n';\n for (var ii = 0; ii < tblLgn; ++ii) {\n tb += cells[i][ii];\n }\n tb += '\\n';\n }\n tb += '\\n
    \\n';\n return tb;\n }\n\n function parseTable (rawTable) {\n var i, tableLines = rawTable.split('\\n');\n\n for (i = 0; i < tableLines.length; ++i) {\n // strip wrong first and last column if wrapped tables are used\n if (/^ {0,3}\\|/.test(tableLines[i])) {\n tableLines[i] = tableLines[i].replace(/^ {0,3}\\|/, '');\n }\n if (/\\|[ \\t]*$/.test(tableLines[i])) {\n tableLines[i] = tableLines[i].replace(/\\|[ \\t]*$/, '');\n }\n // parse code spans first, but we only support one line code spans\n tableLines[i] = showdown.subParser('codeSpans')(tableLines[i], options, globals);\n }\n\n var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),\n rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),\n rawCells = [],\n headers = [],\n styles = [],\n cells = [];\n\n tableLines.shift();\n tableLines.shift();\n\n for (i = 0; i < tableLines.length; ++i) {\n if (tableLines[i].trim() === '') {\n continue;\n }\n rawCells.push(\n tableLines[i]\n .split('|')\n .map(function (s) {\n return s.trim();\n })\n );\n }\n\n if (rawHeaders.length < rawStyles.length) {\n return rawTable;\n }\n\n for (i = 0; i < rawStyles.length; ++i) {\n styles.push(parseStyles(rawStyles[i]));\n }\n\n for (i = 0; i < rawHeaders.length; ++i) {\n if (showdown.helper.isUndefined(styles[i])) {\n styles[i] = '';\n }\n headers.push(parseHeaders(rawHeaders[i], styles[i]));\n }\n\n for (i = 0; i < rawCells.length; ++i) {\n var row = [];\n for (var ii = 0; ii < headers.length; ++ii) {\n if (showdown.helper.isUndefined(rawCells[i][ii])) {\n\n }\n row.push(parseCells(rawCells[i][ii], styles[ii]));\n }\n cells.push(row);\n }\n\n return buildTable(headers, cells);\n }\n\n text = globals.converter._dispatch('tables.before', text, options, globals);\n\n // find escaped pipe characters\n text = text.replace(/\\\\(\\|)/g, showdown.helper.escapeCharactersCallback);\n\n // parse multi column tables\n text = text.replace(tableRgx, parseTable);\n\n // parse one column tables\n text = text.replace(singeColTblRgx, parseTable);\n\n text = globals.converter._dispatch('tables.after', text, options, globals);\n\n return text;\n});\n", "showdown.subParser('underline', function (text, options, globals) {\n 'use strict';\n\n if (!options.underline) {\n return text;\n }\n\n text = globals.converter._dispatch('underline.before', text, options, globals);\n\n if (options.literalMidWordUnderscores) {\n text = text.replace(/\\b___(\\S[\\s\\S]*?)___\\b/g, function (wm, txt) {\n return '' + txt + '';\n });\n text = text.replace(/\\b__(\\S[\\s\\S]*?)__\\b/g, function (wm, txt) {\n return '' + txt + '';\n });\n } else {\n text = text.replace(/___(\\S[\\s\\S]*?)___/g, function (wm, m) {\n return (/\\S$/.test(m)) ? '' + m + '' : wm;\n });\n text = text.replace(/__(\\S[\\s\\S]*?)__/g, function (wm, m) {\n return (/\\S$/.test(m)) ? '' + m + '' : wm;\n });\n }\n\n // escape remaining underscores to prevent them being parsed by italic and bold\n text = text.replace(/(_)/g, showdown.helper.escapeCharactersCallback);\n\n text = globals.converter._dispatch('underline.after', text, options, globals);\n\n return text;\n});\n", "/**\n * Swap back in all the special characters we've hidden.\n */\nshowdown.subParser('unescapeSpecialChars', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('unescapeSpecialChars.before', text, options, globals);\n\n text = text.replace(/¨E(\\d+)E/g, function (wholeMatch, m1) {\n var charCodeToReplace = parseInt(m1);\n return String.fromCharCode(charCodeToReplace);\n });\n\n text = globals.converter._dispatch('unescapeSpecialChars.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('makeMarkdown.blockquote', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n var children = node.childNodes,\n childrenLength = children.length;\n\n for (var i = 0; i < childrenLength; ++i) {\n var innerTxt = showdown.subParser('makeMarkdown.node')(children[i], globals);\n\n if (innerTxt === '') {\n continue;\n }\n txt += innerTxt;\n }\n }\n // cleanup\n txt = txt.trim();\n txt = '> ' + txt.split('\\n').join('\\n> ');\n return txt;\n});\n", "showdown.subParser('makeMarkdown.codeBlock', function (node, globals) {\n 'use strict';\n\n var lang = node.getAttribute('language'),\n num = node.getAttribute('precodenum');\n return '```' + lang + '\\n' + globals.preList[num] + '\\n```';\n});\n", "showdown.subParser('makeMarkdown.codeSpan', function (node) {\n 'use strict';\n\n return '`' + node.innerHTML + '`';\n});\n", "showdown.subParser('makeMarkdown.emphasis', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n txt += '*';\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '*';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.header', function (node, globals, headerLevel) {\n 'use strict';\n\n var headerMark = new Array(headerLevel + 1).join('#'),\n txt = '';\n\n if (node.hasChildNodes()) {\n txt = headerMark + ' ';\n var children = node.childNodes,\n childrenLength = children.length;\n\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.hr', function () {\n 'use strict';\n\n return '---';\n});\n", "showdown.subParser('makeMarkdown.image', function (node) {\n 'use strict';\n\n var txt = '';\n if (node.hasAttribute('src')) {\n txt += '![' + node.getAttribute('alt') + '](';\n txt += '<' + node.getAttribute('src') + '>';\n if (node.hasAttribute('width') && node.hasAttribute('height')) {\n txt += ' =' + node.getAttribute('width') + 'x' + node.getAttribute('height');\n }\n\n if (node.hasAttribute('title')) {\n txt += ' \"' + node.getAttribute('title') + '\"';\n }\n txt += ')';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.links', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes() && node.hasAttribute('href')) {\n var children = node.childNodes,\n childrenLength = children.length;\n txt = '[';\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '](';\n txt += '<' + node.getAttribute('href') + '>';\n if (node.hasAttribute('title')) {\n txt += ' \"' + node.getAttribute('title') + '\"';\n }\n txt += ')';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.list', function (node, globals, type) {\n 'use strict';\n\n var txt = '';\n if (!node.hasChildNodes()) {\n return '';\n }\n var listItems = node.childNodes,\n listItemsLenght = listItems.length,\n listNum = node.getAttribute('start') || 1;\n\n for (var i = 0; i < listItemsLenght; ++i) {\n if (typeof listItems[i].tagName === 'undefined' || listItems[i].tagName.toLowerCase() !== 'li') {\n continue;\n }\n\n // define the bullet to use in list\n var bullet = '';\n if (type === 'ol') {\n bullet = listNum.toString() + '. ';\n } else {\n bullet = '- ';\n }\n\n // parse list item\n txt += bullet + showdown.subParser('makeMarkdown.listItem')(listItems[i], globals);\n ++listNum;\n }\n\n // add comment at the end to prevent consecutive lists to be parsed as one\n txt += '\\n\\n';\n return txt.trim();\n});\n", "showdown.subParser('makeMarkdown.listItem', function (node, globals) {\n 'use strict';\n\n var listItemTxt = '';\n\n var children = node.childNodes,\n childrenLenght = children.length;\n\n for (var i = 0; i < childrenLenght; ++i) {\n listItemTxt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n // if it's only one liner, we need to add a newline at the end\n if (!/\\n$/.test(listItemTxt)) {\n listItemTxt += '\\n';\n } else {\n // it's multiparagraph, so we need to indent\n listItemTxt = listItemTxt\n .split('\\n')\n .join('\\n ')\n .replace(/^ {4}$/gm, '')\n .replace(/\\n\\n+/g, '\\n\\n');\n }\n\n return listItemTxt;\n});\n", "\n\nshowdown.subParser('makeMarkdown.node', function (node, globals, spansOnly) {\n 'use strict';\n\n spansOnly = spansOnly || false;\n\n var txt = '';\n\n // edge case of text without wrapper paragraph\n if (node.nodeType === 3) {\n return showdown.subParser('makeMarkdown.txt')(node, globals);\n }\n\n // HTML comment\n if (node.nodeType === 8) {\n return '\\n\\n';\n }\n\n // process only node elements\n if (node.nodeType !== 1) {\n return '';\n }\n\n var tagName = node.tagName.toLowerCase();\n\n switch (tagName) {\n\n //\n // BLOCKS\n //\n case 'h1':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 1) + '\\n\\n'; }\n break;\n case 'h2':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 2) + '\\n\\n'; }\n break;\n case 'h3':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 3) + '\\n\\n'; }\n break;\n case 'h4':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 4) + '\\n\\n'; }\n break;\n case 'h5':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 5) + '\\n\\n'; }\n break;\n case 'h6':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 6) + '\\n\\n'; }\n break;\n\n case 'p':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.paragraph')(node, globals) + '\\n\\n'; }\n break;\n\n case 'blockquote':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.blockquote')(node, globals) + '\\n\\n'; }\n break;\n\n case 'hr':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.hr')(node, globals) + '\\n\\n'; }\n break;\n\n case 'ol':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ol') + '\\n\\n'; }\n break;\n\n case 'ul':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ul') + '\\n\\n'; }\n break;\n\n case 'precode':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.codeBlock')(node, globals) + '\\n\\n'; }\n break;\n\n case 'pre':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.pre')(node, globals) + '\\n\\n'; }\n break;\n\n case 'table':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.table')(node, globals) + '\\n\\n'; }\n break;\n\n //\n // SPANS\n //\n case 'code':\n txt = showdown.subParser('makeMarkdown.codeSpan')(node, globals);\n break;\n\n case 'em':\n case 'i':\n txt = showdown.subParser('makeMarkdown.emphasis')(node, globals);\n break;\n\n case 'strong':\n case 'b':\n txt = showdown.subParser('makeMarkdown.strong')(node, globals);\n break;\n\n case 'del':\n txt = showdown.subParser('makeMarkdown.strikethrough')(node, globals);\n break;\n\n case 'a':\n txt = showdown.subParser('makeMarkdown.links')(node, globals);\n break;\n\n case 'img':\n txt = showdown.subParser('makeMarkdown.image')(node, globals);\n break;\n\n default:\n txt = node.outerHTML + '\\n\\n';\n }\n\n // common normalization\n // TODO eventually\n\n return txt;\n});\n", "showdown.subParser('makeMarkdown.paragraph', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n }\n\n // some text normalization\n txt = txt.trim();\n\n return txt;\n});\n", "showdown.subParser('makeMarkdown.pre', function (node, globals) {\n 'use strict';\n\n var num = node.getAttribute('prenum');\n return '
    ' + globals.preList[num] + '
    ';\n});\n", "showdown.subParser('makeMarkdown.strikethrough', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n txt += '~~';\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '~~';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.strong', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n txt += '**';\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '**';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.table', function (node, globals) {\n 'use strict';\n\n var txt = '',\n tableArray = [[], []],\n headings = node.querySelectorAll('thead>tr>th'),\n rows = node.querySelectorAll('tbody>tr'),\n i, ii;\n for (i = 0; i < headings.length; ++i) {\n var headContent = showdown.subParser('makeMarkdown.tableCell')(headings[i], globals),\n allign = '---';\n\n if (headings[i].hasAttribute('style')) {\n var style = headings[i].getAttribute('style').toLowerCase().replace(/\\s/g, '');\n switch (style) {\n case 'text-align:left;':\n allign = ':---';\n break;\n case 'text-align:right;':\n allign = '---:';\n break;\n case 'text-align:center;':\n allign = ':---:';\n break;\n }\n }\n tableArray[0][i] = headContent.trim();\n tableArray[1][i] = allign;\n }\n\n for (i = 0; i < rows.length; ++i) {\n var r = tableArray.push([]) - 1,\n cols = rows[i].getElementsByTagName('td');\n\n for (ii = 0; ii < headings.length; ++ii) {\n var cellContent = ' ';\n if (typeof cols[ii] !== 'undefined') {\n cellContent = showdown.subParser('makeMarkdown.tableCell')(cols[ii], globals);\n }\n tableArray[r].push(cellContent);\n }\n }\n\n var cellSpacesCount = 3;\n for (i = 0; i < tableArray.length; ++i) {\n for (ii = 0; ii < tableArray[i].length; ++ii) {\n var strLen = tableArray[i][ii].length;\n if (strLen > cellSpacesCount) {\n cellSpacesCount = strLen;\n }\n }\n }\n\n for (i = 0; i < tableArray.length; ++i) {\n for (ii = 0; ii < tableArray[i].length; ++ii) {\n if (i === 1) {\n if (tableArray[i][ii].slice(-1) === ':') {\n tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii].slice(-1), cellSpacesCount - 1, '-') + ':';\n } else {\n tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount, '-');\n }\n } else {\n tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount);\n }\n }\n txt += '| ' + tableArray[i].join(' | ') + ' |\\n';\n }\n\n return txt.trim();\n});\n", "showdown.subParser('makeMarkdown.tableCell', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (!node.hasChildNodes()) {\n return '';\n }\n var children = node.childNodes,\n childrenLength = children.length;\n\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals, true);\n }\n return txt.trim();\n});\n", "showdown.subParser('makeMarkdown.txt', function (node) {\n 'use strict';\n\n var txt = node.nodeValue;\n\n // multiple spaces are collapsed\n txt = txt.replace(/ +/g, ' ');\n\n // replace the custom ¨NBSP; with a space\n txt = txt.replace(/¨NBSP;/g, ' ');\n\n // \", <, > and & should replace escaped html entities\n txt = showdown.helper.unescapeHTMLEntities(txt);\n\n // escape markdown magic characters\n // emphasis, strong and strikethrough - can appear everywhere\n // we also escape pipe (|) because of tables\n // and escape ` because of code blocks and spans\n txt = txt.replace(/([*_~|`])/g, '\\\\$1');\n\n // escape > because of blockquotes\n txt = txt.replace(/^(\\s*)>/g, '\\\\$1>');\n\n // hash character, only troublesome at the beginning of a line because of headers\n txt = txt.replace(/^#/gm, '\\\\#');\n\n // horizontal rules\n txt = txt.replace(/^(\\s*)([-=]{3,})(\\s*)$/, '$1\\\\$2$3');\n\n // dot, because of ordered lists, only troublesome at the beginning of a line when preceded by an integer\n txt = txt.replace(/^( {0,3}\\d+)\\./gm, '$1\\\\.');\n\n // +, * and -, at the beginning of a line becomes a list, so we need to escape them also (asterisk was already escaped)\n txt = txt.replace(/^( {0,3})([+-])/gm, '$1\\\\$2');\n\n // images and links, ] followed by ( is problematic, so we escape it\n txt = txt.replace(/]([\\s]*)\\(/g, '\\\\]$1\\\\(');\n\n // reference URIs must also be escaped\n txt = txt.replace(/^ {0,3}\\[([\\S \\t]*?)]:/gm, '\\\\[$1]:');\n\n return txt;\n});\n", "var root = this;\n\n// AMD Loader\nif (typeof define === 'function' && define.amd) {\n define(function () {\n 'use strict';\n return showdown;\n });\n\n// CommonJS/nodeJS Loader\n} else if (typeof module !== 'undefined' && module.exports) {\n module.exports = showdown;\n\n// Regular Browser loader\n} else {\n root.showdown = showdown;\n}\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", "'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", "// 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'\nconst isElectron = require('is-electron')\n\nconst IS_ENV_WITH_DOM = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\n// @ts-ignore\nconst IS_ELECTRON = isElectron()\nconst IS_BROWSER = IS_ENV_WITH_DOM && !IS_ELECTRON\nconst IS_ELECTRON_MAIN = IS_ELECTRON && !IS_ENV_WITH_DOM\nconst IS_ELECTRON_RENDERER = IS_ELECTRON && IS_ENV_WITH_DOM\nconst IS_NODE = typeof require === 'function' && typeof process !== 'undefined' && typeof process.release !== 'undefined' && process.release.name === 'node' && !IS_ELECTRON\n// @ts-ignore - we either ignore worker scope or dom scope\nconst IS_WEBWORKER = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\nconst IS_TEST = typeof process !== 'undefined' && typeof process.env !== 'undefined' && process.env.NODE_ENV === 'test'\nconst IS_REACT_NATIVE = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n\nmodule.exports = {\n isTest: IS_TEST,\n isElectron: IS_ELECTRON,\n isElectronMain: IS_ELECTRON_MAIN,\n isElectronRenderer: IS_ELECTRON_RENDERER,\n isNode: IS_NODE,\n /**\n * Detects browser main thread **NOT** web worker or service worker\n */\n isBrowser: IS_BROWSER,\n isWebWorker: IS_WEBWORKER,\n isEnvWithDom: IS_ENV_WITH_DOM,\n isReactNative: IS_REACT_NATIVE\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", "\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", "/* 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", "'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\";\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 = 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\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 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", "\"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\";\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 = 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", "\"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 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new this.buf.constructor(0)\n : 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 = 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\";\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 = {};\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\";\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", "// minimal library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index-minimal\");\n", "'use strict'\n\nmodule.exports = function getTime () {\n return Date.now()\n}\n", "'use strict'\n\nconst getTime = require('./time')\n\nclass Retimer {\n constructor (callback, timeout, args) {\n const that = this\n\n this._started = getTime()\n this._rescheduled = 0\n this._scheduled = timeout\n this._args = args\n this._triggered = false\n\n this._timerWrapper = () => {\n if (that._rescheduled > 0) {\n that._scheduled = that._rescheduled - (getTime() - that._started)\n that._schedule(that._scheduled)\n } else {\n that._triggered = true\n callback.apply(null, that._args)\n }\n }\n\n this._timer = setTimeout(this._timerWrapper, timeout)\n }\n\n reschedule (timeout) {\n if (!timeout) {\n timeout = this._scheduled\n }\n const now = getTime()\n if ((now + timeout) - (this._started + this._scheduled) < 0) {\n clearTimeout(this._timer)\n this._schedule(timeout)\n } else if (!this._triggered) {\n this._started = now\n this._rescheduled = timeout\n } else {\n this._schedule(timeout)\n }\n }\n\n _schedule (timeout) {\n this._triggered = false\n this._started = getTime()\n this._rescheduled = 0\n this._scheduled = timeout\n this._timer = setTimeout(this._timerWrapper, timeout)\n }\n\n clear () {\n clearTimeout(this._timer)\n }\n}\n\nfunction retimer () {\n if (typeof arguments[0] !== 'function') {\n throw new Error('callback needed')\n }\n\n if (typeof arguments[1] !== 'number') {\n throw new Error('timeout needed')\n }\n\n let args\n\n if (arguments.length > 0) {\n args = new Array(arguments.length - 2)\n\n /* eslint-disable no-var */\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 2]\n }\n }\n\n return new Retimer(arguments[0], arguments[1], args)\n}\n\nmodule.exports = retimer\n", "'use strict'\n\nconst { AbortController } = globalThis\n\n// @ts-expect-error no types\nconst retimer = require('retimer')\n\nclass TimeoutController extends AbortController {\n /**\n * @constructor\n * @param {number} ms milliseconds\n */\n constructor (ms) {\n super()\n this._ms = ms\n this._timer = retimer(() => this.abort(), ms)\n // Patch for safari not supported extending built in classes\n Object.setPrototypeOf(this, TimeoutController.prototype)\n }\n\n /**\n * Aborts the controller and clears the timer\n */\n abort () {\n this._timer.clear()\n return super.abort()\n }\n\n /**\n * Clears the timer\n */\n clear () {\n this._timer.clear()\n }\n\n /**\n * Resets the timer\n */\n reset () {\n this._timer.clear()\n this._timer = retimer(() => this.abort(), this._ms)\n }\n}\n\nmodule.exports = {\n TimeoutController\n}\n", "'use strict'\n\nconst isReactNative =\n typeof navigator !== 'undefined' &&\n navigator.product === 'ReactNative'\n\nfunction getDefaultBase () {\n if (isReactNative) {\n return 'http://localhost'\n }\n // in some environments i.e. cloudflare workers location is not available\n if (!self.location) {\n return ''\n }\n\n return self.location.protocol + '//' + self.location.host\n}\n\nconst URL = self.URL\nconst defaultBase = getDefaultBase()\n\nclass URLWithLegacySupport {\n constructor (url = '', base = defaultBase) {\n this.super = new URL(url, base)\n this.path = this.pathname + this.search\n this.auth =\n this.username && this.password\n ? this.username + ':' + this.password\n : null\n\n this.query =\n this.search && this.search.startsWith('?')\n ? this.search.slice(1)\n : null\n }\n\n get hash () {\n return this.super.hash\n }\n\n get host () {\n return this.super.host\n }\n\n get hostname () {\n return this.super.hostname\n }\n\n get href () {\n return this.super.href\n }\n\n get origin () {\n return this.super.origin\n }\n\n get password () {\n return this.super.password\n }\n\n get pathname () {\n return this.super.pathname\n }\n\n get port () {\n return this.super.port\n }\n\n get protocol () {\n return this.super.protocol\n }\n\n get search () {\n return this.super.search\n }\n\n get searchParams () {\n return this.super.searchParams\n }\n\n get username () {\n return this.super.username\n }\n\n set hash (hash) {\n this.super.hash = hash\n }\n\n set host (host) {\n this.super.host = host\n }\n\n set hostname (hostname) {\n this.super.hostname = hostname\n }\n\n set href (href) {\n this.super.href = href\n }\n\n set password (password) {\n this.super.password = password\n }\n\n set pathname (pathname) {\n this.super.pathname = pathname\n }\n\n set port (port) {\n this.super.port = port\n }\n\n set protocol (protocol) {\n this.super.protocol = protocol\n }\n\n set search (search) {\n this.super.search = search\n }\n\n set username (username) {\n this.super.username = username\n }\n\n /**\n * @param {any} o\n */\n static createObjectURL (o) {\n return URL.createObjectURL(o)\n }\n\n /**\n * @param {string} o\n */\n static revokeObjectURL (o) {\n URL.revokeObjectURL(o)\n }\n\n toJSON () {\n return this.super.toJSON()\n }\n\n toString () {\n return this.super.toString()\n }\n\n format () {\n return this.toString()\n }\n}\n\n/**\n * @param {string | import('url').UrlObject} obj\n */\nfunction format (obj) {\n if (typeof obj === 'string') {\n const url = new URL(obj)\n\n return url.toString()\n }\n\n if (!(obj instanceof URL)) {\n const userPass =\n // @ts-ignore its not supported in node but we normalise\n obj.username && obj.password\n // @ts-ignore its not supported in node but we normalise\n ? `${obj.username}:${obj.password}@`\n : ''\n const auth = obj.auth ? obj.auth + '@' : ''\n const port = obj.port ? ':' + obj.port : ''\n const protocol = obj.protocol ? obj.protocol + '//' : ''\n const host = obj.host || ''\n const hostname = obj.hostname || ''\n const search = obj.search || (obj.query ? '?' + obj.query : '')\n const hash = obj.hash || ''\n const pathname = obj.pathname || ''\n // @ts-ignore - path is not supported in node but we normalise\n const path = obj.path || pathname + search\n\n return `${protocol}${userPass || auth}${\n host || hostname + port\n }${path}${hash}`\n }\n}\n\nmodule.exports = {\n URLWithLegacySupport,\n URLSearchParams: self.URLSearchParams,\n defaultBase,\n format\n}\n", "'use strict'\n\nconst { URLWithLegacySupport, format } = require('./url')\n\n/**\n * @param {string | undefined} url\n * @param {any} [location]\n * @param {any} [protocolMap]\n * @param {any} [defaultProtocol]\n */\nmodule.exports = (url, location = {}, protocolMap = {}, defaultProtocol) => {\n let protocol = location.protocol\n ? location.protocol.replace(':', '')\n : 'http'\n\n // Check protocol map\n protocol = (protocolMap[protocol] || defaultProtocol || protocol) + ':'\n let urlParsed\n\n try {\n urlParsed = new URLWithLegacySupport(url)\n } catch (err) {\n urlParsed = {}\n }\n\n const base = Object.assign({}, location, {\n protocol: protocol || urlParsed.protocol,\n host: location.host || urlParsed.host\n })\n\n return new URLWithLegacySupport(url, format(base)).toString()\n}\n", "'use strict'\n\nconst {\n URLWithLegacySupport,\n format,\n URLSearchParams,\n defaultBase\n} = require('./src/url')\nconst relative = require('./src/relative')\n\nmodule.exports = {\n URL: URLWithLegacySupport,\n URLSearchParams,\n format,\n relative,\n defaultBase\n}\n", "/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n * @param {Array} signals\n * @returns {AbortSignal}\n */\nfunction anySignal (signals) {\n const controller = new globalThis.AbortController()\n\n function onAbort () {\n controller.abort()\n\n for (const signal of signals) {\n if (!signal || !signal.removeEventListener) continue\n signal.removeEventListener('abort', onAbort)\n }\n }\n\n for (const signal of signals) {\n if (!signal || !signal.addEventListener) continue\n if (signal.aborted) {\n onAbort()\n break\n }\n signal.addEventListener('abort', onAbort)\n }\n\n return controller.signal\n}\n\nmodule.exports = anySignal\nmodule.exports.anySignal = anySignal\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", "'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", "'use strict'\n\nclass TimeoutError extends Error {\n constructor (message = 'Request timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\nexports.TimeoutError = TimeoutError\n\nclass AbortError extends Error {\n constructor (message = 'The operation was aborted.') {\n super(message)\n this.name = 'AbortError'\n }\n}\nexports.AbortError = AbortError\n\nclass HTTPError extends Error {\n /**\n * @param {Response} response\n */\n constructor (response) {\n super(response.statusText)\n this.name = 'HTTPError'\n this.response = response\n }\n}\nexports.HTTPError = HTTPError\n", "\"use strict\";\n\n// ref: https://github.com/tc39/proposal-global\nvar getGlobal = function () {\n\t// the only reliable means to get the global object is\n\t// `Function('return this')()`\n\t// However, this causes CSP violations in Chrome apps.\n\tif (typeof self !== 'undefined') { return self; }\n\tif (typeof window !== 'undefined') { return window; }\n\tif (typeof global !== 'undefined') { return global; }\n\tthrow new Error('unable to locate global object');\n}\n\nvar globalObject = getGlobal();\n\nmodule.exports = exports = globalObject.fetch;\n\n// Needed for TypeScript and Webpack.\nif (globalObject.fetch) {\n\texports.default = globalObject.fetch.bind(globalObject);\n}\n\nexports.Headers = globalObject.Headers;\nexports.Request = globalObject.Request;\nexports.Response = globalObject.Response;\n", "'use strict'\n\nif (globalThis.fetch && globalThis.Headers && globalThis.Request && globalThis.Response) {\n module.exports = {\n default: globalThis.fetch,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response\n }\n} else {\n module.exports = {\n default: require('node-fetch').default,\n Headers: require('node-fetch').Headers,\n Request: require('node-fetch').Request,\n Response: require('node-fetch').Response\n }\n}\n", "'use strict'\n\n/**\n * @typedef {globalThis.Headers} Headers\n * @typedef {globalThis.Request} Request\n * @typedef {globalThis.Response} Response\n */\n\n// use window.fetch if it is available, fall back to node-fetch if not\nmodule.exports = require('native-fetch')\n", "'use strict'\n\nconst { TimeoutError, AbortError } = require('./error')\n// @ts-expect-error\nconst { Response, Request, Headers, default: fetch } = require('../fetch')\n\n/**\n * @typedef {import('../types').FetchOptions} FetchOptions\n * @typedef {import('../types').ProgressFn} ProgressFn\n */\n\n/**\n * Fetch with progress\n *\n * @param {string | Request} url\n * @param {FetchOptions} [options]\n * @returns {Promise}\n */\nconst fetchWithProgress = (url, options = {}) => {\n const request = new XMLHttpRequest()\n request.open(options.method || 'GET', url.toString(), true)\n\n const { timeout, headers } = options\n\n if (timeout && timeout > 0 && timeout < Infinity) {\n request.timeout = timeout\n }\n\n if (options.overrideMimeType != null) {\n request.overrideMimeType(options.overrideMimeType)\n }\n\n if (headers) {\n for (const [name, value] of new Headers(headers)) {\n request.setRequestHeader(name, value)\n }\n }\n\n if (options.signal) {\n options.signal.onabort = () => request.abort()\n }\n\n if (options.onUploadProgress) {\n request.upload.onprogress = options.onUploadProgress\n }\n\n // Note: Need to use `arraybuffer` here instead of `blob` because `Blob`\n // instances coming from JSDOM are not compatible with `Response` from\n // node-fetch (which is the setup we get when testing with jest because\n // it uses JSDOM which does not provide a global fetch\n // https://github.com/jsdom/jsdom/issues/1724)\n request.responseType = 'arraybuffer'\n\n return new Promise((resolve, reject) => {\n /**\n * @param {Event} event\n */\n const handleEvent = (event) => {\n switch (event.type) {\n case 'error': {\n resolve(Response.error())\n break\n }\n case 'load': {\n resolve(\n new ResponseWithURL(request.responseURL, request.response, {\n status: request.status,\n statusText: request.statusText,\n headers: parseHeaders(request.getAllResponseHeaders())\n })\n )\n break\n }\n case 'timeout': {\n reject(new TimeoutError())\n break\n }\n case 'abort': {\n reject(new AbortError())\n break\n }\n default: {\n break\n }\n }\n }\n request.onerror = handleEvent\n request.onload = handleEvent\n request.ontimeout = handleEvent\n request.onabort = handleEvent\n\n // @ts-expect-error options.body can be a node readable stream, which isn't compatible with XHR, but this\n // file is a browser override so you won't get a node readable stream so ignore the error\n request.send(options.body)\n })\n}\n\nconst fetchWithStreaming = fetch\n\n/**\n * @param {string | Request} url\n * @param {FetchOptions} options\n */\nconst fetchWith = (url, options = {}) =>\n (options.onUploadProgress != null)\n ? fetchWithProgress(url, options)\n : fetchWithStreaming(url, options)\n\n/**\n * Parse Headers from a XMLHttpRequest\n *\n * @param {string} input\n * @returns {Headers}\n */\nconst parseHeaders = (input) => {\n const headers = new Headers()\n for (const line of input.trim().split(/[\\r\\n]+/)) {\n const index = line.indexOf(': ')\n if (index > 0) {\n headers.set(line.slice(0, index), line.slice(index + 1))\n }\n }\n\n return headers\n}\n\nclass ResponseWithURL extends Response {\n /**\n * @param {string} url\n * @param {BodyInit} body\n * @param {ResponseInit} options\n */\n constructor (url, body, options) {\n super(body, options)\n Object.defineProperty(this, 'url', { value: url })\n }\n}\n\nmodule.exports = {\n fetch: fetchWith,\n Request,\n Headers\n}\n", "'use strict'\n\n/**\n * Turns a browser readable stream into an async iterable. Async iteration over\n * returned iterable will lock give stream, preventing any other consumer from\n * acquiring a reader. The lock will be released if iteration loop is broken. To\n * prevent stream cancelling optional `{ preventCancel: true }` could be passed\n * as a second argument.\n * @template T\n * @param {ReadableStream} stream\n * @param {Object} [options]\n * @param {boolean} [options.preventCancel=boolean]\n * @returns {AsyncIterable}\n */\nasync function * browserReadableStreamToIt (stream, options = {}) {\n const reader = stream.getReader()\n\n try {\n while (true) {\n const result = await reader.read()\n\n if (result.done) {\n return\n }\n\n yield result.value\n }\n } finally {\n if (options.preventCancel !== true) {\n reader.cancel()\n }\n\n reader.releaseLock()\n }\n}\n\nmodule.exports = browserReadableStreamToIt\n", "'use strict'\n\n/**\n * Collects all values from an (async) iterable into an array and returns it.\n *\n * @template T\n * @param {AsyncIterable|Iterable} source\n */\nconst all = async (source) => {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n\nmodule.exports = all\n", "/* eslint-disable no-undef */\n'use strict'\n\nconst { fetch, Request, Headers } = require('./http/fetch')\nconst { TimeoutError, HTTPError } = require('./http/error')\nconst merge = require('merge-options').bind({ ignoreUndefined: true })\nconst { URL, URLSearchParams } = require('iso-url')\nconst anySignal = require('any-signal')\nconst browserReableStreamToIt = require('browser-readablestream-to-it')\nconst { isBrowser, isWebWorker } = require('./env')\nconst all = require('it-all')\n\n/**\n * @typedef {import('stream').Readable} NodeReadableStream\n * @typedef {import('./types').HTTPOptions} HTTPOptions\n * @typedef {import('./types').ExtendedResponse} ExtendedResponse\n */\n\n/**\n * @template TResponse\n * @param {Promise} promise\n * @param {number | undefined} ms\n * @param {AbortController} abortController\n * @returns {Promise}\n */\nconst timeout = (promise, ms, abortController) => {\n if (ms === undefined) {\n return promise\n }\n\n const start = Date.now()\n\n const timedOut = () => {\n const time = Date.now() - start\n\n return time >= ms\n }\n\n return new Promise((resolve, reject) => {\n const timeoutID = setTimeout(() => {\n if (timedOut()) {\n reject(new TimeoutError())\n abortController.abort()\n }\n }, ms)\n\n /**\n * @param {(value: any) => void } next\n */\n const after = (next) => {\n /**\n * @param {any} res\n */\n const fn = (res) => {\n clearTimeout(timeoutID)\n\n if (timedOut()) {\n reject(new TimeoutError())\n return\n }\n\n next(res)\n }\n return fn\n }\n\n promise\n .then(after(resolve), after(reject))\n })\n}\n\nconst defaults = {\n throwHttpErrors: true,\n credentials: 'same-origin'\n}\n\nclass HTTP {\n /**\n *\n * @param {HTTPOptions} options\n */\n constructor (options = {}) {\n /** @type {HTTPOptions} */\n this.opts = merge(defaults, options)\n }\n\n /**\n * Fetch\n *\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n * @returns {Promise}\n */\n async fetch (resource, options = {}) {\n /** @type {HTTPOptions} */\n const opts = merge(this.opts, options)\n // @ts-expect-error\n const headers = new Headers(opts.headers)\n\n // validate resource type\n // @ts-expect-error\n if (typeof resource !== 'string' && !(resource instanceof URL || resource instanceof Request)) {\n throw new TypeError('`resource` must be a string, URL, or Request')\n }\n\n const url = new URL(resource.toString(), opts.base)\n\n const {\n searchParams,\n transformSearchParams,\n json\n } = opts\n\n if (searchParams) {\n if (typeof transformSearchParams === 'function') {\n // @ts-ignore\n url.search = transformSearchParams(new URLSearchParams(opts.searchParams))\n } else {\n // @ts-ignore\n url.search = new URLSearchParams(opts.searchParams)\n }\n }\n\n if (json) {\n opts.body = JSON.stringify(opts.json)\n headers.set('content-type', 'application/json')\n }\n\n const abortController = new AbortController()\n // @ts-ignore\n const signal = anySignal([abortController.signal, opts.signal])\n\n if (globalThis.ReadableStream != null && opts.body instanceof globalThis.ReadableStream && (isBrowser || isWebWorker)) {\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1387483\n opts.body = new Blob(await all(browserReableStreamToIt(opts.body)))\n }\n\n /** @type {ExtendedResponse} */\n // @ts-expect-error additional fields are assigned below\n const response = await timeout(\n fetch(\n url.toString(),\n {\n ...opts,\n signal,\n // @ts-expect-error non-browser fetch implementations may take extra options\n timeout: undefined,\n headers,\n\n // https://fetch.spec.whatwg.org/#dom-requestinit-duplex\n // https://github.com/whatwg/fetch/issues/1254\n duplex: 'half'\n }\n ),\n opts.timeout,\n abortController\n )\n\n if (!response.ok && opts.throwHttpErrors) {\n if (opts.handleError) {\n await opts.handleError(response)\n }\n throw new HTTPError(response)\n }\n\n response.iterator = async function * () {\n yield * fromStream(response.body)\n }\n\n response.ndjson = async function * () {\n for await (const chunk of ndjson(response.iterator())) {\n if (options.transform) {\n yield options.transform(chunk)\n } else {\n yield chunk\n }\n }\n }\n\n return response\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n post (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'POST' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n get (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'GET' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n put (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'PUT' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n delete (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'DELETE' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n options (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'OPTIONS' })\n }\n}\n\n/**\n * Parses NDJSON chunks from an iterator\n *\n * @param {AsyncIterable} source\n * @returns {AsyncIterable}\n */\nconst ndjson = async function * (source) {\n const decoder = new TextDecoder()\n let buf = ''\n\n for await (const chunk of source) {\n buf += decoder.decode(chunk, { stream: true })\n const lines = buf.split(/\\r?\\n/)\n\n for (let i = 0; i < lines.length - 1; i++) {\n const l = lines[i].trim()\n if (l.length > 0) {\n yield JSON.parse(l)\n }\n }\n buf = lines[lines.length - 1]\n }\n buf += decoder.decode()\n buf = buf.trim()\n if (buf.length !== 0) {\n yield JSON.parse(buf)\n }\n}\n\n/**\n * Stream to AsyncIterable\n *\n * @template TChunk\n * @param {ReadableStream | NodeReadableStream | null} source\n * @returns {AsyncIterable}\n */\nconst fromStream = (source) => {\n if (isAsyncIterable(source)) {\n return source\n }\n\n // Workaround for https://github.com/node-fetch/node-fetch/issues/766\n if (isNodeReadableStream(source)) {\n const iter = source[Symbol.asyncIterator]()\n return {\n [Symbol.asyncIterator] () {\n return {\n next: iter.next.bind(iter),\n return (value) {\n source.destroy()\n if (typeof iter.return === 'function') {\n return iter.return()\n }\n return Promise.resolve({ done: true, value })\n }\n }\n }\n }\n }\n\n if (isWebReadableStream(source)) {\n const reader = source.getReader()\n return (async function * () {\n try {\n while (true) {\n // Read from the stream\n const { done, value } = await reader.read()\n // Exit if we're done\n if (done) return\n // Else yield the chunk\n if (value) {\n yield value\n }\n }\n } finally {\n reader.releaseLock()\n }\n })()\n }\n\n throw new TypeError('Body can\\'t be converted to AsyncIterable')\n}\n\n/**\n * Check if it's an AsyncIterable\n *\n * @template {unknown} TChunk\n * @template {any} Other\n * @param {Other|AsyncIterable} value\n * @returns {value is AsyncIterable}\n */\nconst isAsyncIterable = (value) => {\n return typeof value === 'object' &&\n value !== null &&\n typeof /** @type {any} */(value)[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Check for web readable stream\n *\n * @template {unknown} TChunk\n * @template {any} Other\n * @param {Other|ReadableStream} value\n * @returns {value is ReadableStream}\n */\nconst isWebReadableStream = (value) => {\n return value && typeof /** @type {any} */(value).getReader === 'function'\n}\n\n/**\n * @param {any} value\n * @returns {value is NodeReadableStream}\n */\nconst isNodeReadableStream = (value) =>\n Object.prototype.hasOwnProperty.call(value, 'readable') &&\n Object.prototype.hasOwnProperty.call(value, 'writable')\n\nHTTP.HTTPError = HTTPError\nHTTP.TimeoutError = TimeoutError\nHTTP.streamToAsyncIterator = fromStream\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.post = (resource, options) => new HTTP(options).post(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.get = (resource, options) => new HTTP(options).get(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.put = (resource, options) => new HTTP(options).put(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.delete = (resource, options) => new HTTP(options).delete(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.options = (resource, options) => new HTTP(options).options(resource, options)\n\nmodule.exports = HTTP\n", "var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n 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 * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\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 global;\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 * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n// Deprecated equivalent of sha1WithRSAEncryption\n_IN('1.3.14.3.2.29', 'sha1WithRSASignature');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('2.16.840.1.101.3.4.2.4', 'sha224');\n_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');\n_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');\n_IN('1.2.840.113549.2.2', 'md2');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.4', 'surname');\n_IN('2.5.4.5', 'serialNumber');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.12', 'title');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('2.5.4.42', 'givenName');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n", "/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @throws Will throw an error for various malformed input conditions.\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n remaining -= length;\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n try {\n rval += forge.util.decodeUtf8(obj.value);\n } catch(e) {\n if(e.message === 'URI malformed') {\n rval +=\n '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';\n } else {\n throw e;\n }\n }\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n", "/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n", "/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n", "/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n", "/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n", "/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n", "/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\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 = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\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 * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n // accept \"NEW CERTIFICATE REQUEST\" as \"CERTIFICATE REQUEST\"\n // https://datatracker.ietf.org/doc/html/rfc7468#section-7\n var type = match[1];\n if(type === 'NEW CERTIFICATE REQUEST') {\n type = 'CERTIFICATE REQUEST';\n }\n\n var msg = {\n type: type,\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n", "/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _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 // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\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 = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\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 * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n", "/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,\n 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,\n 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,\n 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,\n 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,\n 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,\n 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,\n 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,\n 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,\n 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,\n 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,\n 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,\n 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n", "// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a 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\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n", "/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n", "/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\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 FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n", "/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n", "/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n // captured only to check existence for md2 and md5\n capture: 'parameters',\n optional: true,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme, options) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // see PKCS1-v1-5DigestAlgorithms in RFC 8017\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha224 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512 ||\n oid === forge.oids['sha512-224'] ||\n oid === forge.oids['sha512-256'])) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n // special check for md2 and md5 that NULL parameters exist\n if(oid === forge.oids.md2 || oid === forge.oids.md5) {\n if(!('parameters' in capture)) {\n throw new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value. ' +\n 'Missing algorithm identifer NULL parameters.');\n }\n }\n\n // compare the given digest to the decrypted one\n return digest === capture.digest;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n", "/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n", "/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _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\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\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 = 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 = 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 * 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 * 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", "/* 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 = 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", "export default function dlv(obj, key, def, p, undef) {\n\tkey = key.split ? key.split('.') : key;\n\tfor (p = 0; p < key.length; p++) {\n\t\tobj = obj ? obj[key[p]] : undef;\n\t}\n\treturn obj === undef ? def : obj;\n}\n", "'use strict'\n\n// Adapted from RFC 2181 (See section 11)\n//\n// The RFC defines a Domain Name to be at most 255 chars including seperators\n// between labels.\n// Subdomains are labels plus a seperator. A label is a string starting and\n// ending with an alphanum, with dashes allowed in the middle. It is between 1 and 63 chars.\n//\n// We make some assumptions below that go beyond the RFC. We assume the TLD\n// to be at least 2 chars. The regex also allows domains longer than 255 chars,\n// but allows at most 127 subdomains, as assuming a lower-bound of one char per\n// subdomain will yield 252, and adding a TLD of 2 chars sums to 254.\n/*\n(?: // Group 1: This is for subdomain, which is composed of a label and a seperator (length = [1, 63] + 1)\n [a-z0-9]\n (?:\n [a-z0-9\\-]{0,61} // Limited to 61 chars as we have at least two chars if we reach this group (61 + 2 = 63 which is the limit)\n [a-z0-9]\n )?\n \\. // Label seperator\n){0,126} // If we assume the lower-bound of 1 char labels, we can at most have 126 groups before approaching the total limit of 255 chars\n(?: // Group 2: Assume that the TLD is at least 2 chars (for sanity)\n [a-z0-9]\n [a-z0-9\\-]{0,61}\n [a-z0-9]\n)\n\\.? // Some consider a trailing dot to be considered valid as it signifies the root of the domain tree\n */\nvar domainNameRegex = /^(?:[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9])?\\.){0,126}(?:[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9]))\\.?$/i\n\n/**\n * Test whether a string is a valid domain name, optionally checking for a root dot as well\n * @param {String} domainName\n * @param {Boolean} rootDot Check for a root dot eg. 'example.com.'. Defaults to false\n * @return {Boolean}\n */\nmodule.exports = function isDomainName (domainName, rootDot) {\n if (rootDot == null) rootDot = false\n\n if (domainName.length < 2) return false\n if (domainName.length > 255) return false\n\n var lastChar = domainName[domainName.length - 1]\n if (rootDot) {\n if (lastChar !== '.') return false\n } else {\n if (lastChar === '.') return false\n }\n\n return domainNameRegex.test(domainName)\n}\n", "module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {\n encode.bytes = 0\n throw new RangeError('Could not encode varint')\n }\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\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 \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n", "module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\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)\n\nmodule.exports = function (value) {\n return (\n 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 )\n}\n", "module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\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", "module.exports = require('./lib/murmurHash3js');\n", "/**\n * Rabin fingerprinting\n *\n * @class Rabin\n */\nclass Rabin {\n /**\n * Creates an instance of Rabin.\n * @param { import(\"./../dist/rabin-wasm\") } asModule\n * @param {number} [bits=12]\n * @param {number} [min=8 * 1024]\n * @param {number} [max=32 * 1024]\n * @param {number} polynomial\n * @memberof Rabin\n */\n constructor(asModule, bits = 12, min = 8 * 1024, max = 32 * 1024, windowSize = 64, polynomial) {\n this.bits = bits\n this.min = min\n this.max = max\n this.asModule = asModule\n this.rabin = new asModule.Rabin(bits, min, max, windowSize, polynomial)\n this.polynomial = polynomial\n }\n\n /**\n * Fingerprints the buffer\n *\n * @param {Uint8Array} buf\n * @returns {Array}\n * @memberof Rabin\n */\n fingerprint(buf) {\n const {\n __retain,\n __release,\n __allocArray,\n __getInt32Array,\n Int32Array_ID,\n Uint8Array_ID\n } = this.asModule\n\n const lengths = new Int32Array(Math.ceil(buf.length/this.min))\n const lengthsPtr = __retain(__allocArray(Int32Array_ID, lengths))\n const pointer = __retain(__allocArray(Uint8Array_ID, buf))\n\n const out = this.rabin.fingerprint(pointer, lengthsPtr)\n const processed = __getInt32Array(out)\n\n __release(pointer)\n __release(lengthsPtr)\n\n const end = processed.indexOf(0);\n return end >= 0 ? processed.subarray(0, end) : processed;\n }\n}\n\nmodule.exports = Rabin", "\"use strict\";\n\n// Runtime header offsets\nconst ID_OFFSET = -8;\nconst SIZE_OFFSET = -4;\n\n// Runtime ids\nconst ARRAYBUFFER_ID = 0;\nconst STRING_ID = 1;\nconst ARRAYBUFFERVIEW_ID = 2;\n\n// Runtime type information\nconst ARRAYBUFFERVIEW = 1 << 0;\nconst ARRAY = 1 << 1;\nconst SET = 1 << 2;\nconst MAP = 1 << 3;\nconst VAL_ALIGN_OFFSET = 5;\nconst VAL_ALIGN = 1 << VAL_ALIGN_OFFSET;\nconst VAL_SIGNED = 1 << 10;\nconst VAL_FLOAT = 1 << 11;\nconst VAL_NULLABLE = 1 << 12;\nconst VAL_MANAGED = 1 << 13;\nconst KEY_ALIGN_OFFSET = 14;\nconst KEY_ALIGN = 1 << KEY_ALIGN_OFFSET;\nconst KEY_SIGNED = 1 << 19;\nconst KEY_FLOAT = 1 << 20;\nconst KEY_NULLABLE = 1 << 21;\nconst KEY_MANAGED = 1 << 22;\n\n// Array(BufferView) layout\nconst ARRAYBUFFERVIEW_BUFFER_OFFSET = 0;\nconst ARRAYBUFFERVIEW_DATASTART_OFFSET = 4;\nconst ARRAYBUFFERVIEW_DATALENGTH_OFFSET = 8;\nconst ARRAYBUFFERVIEW_SIZE = 12;\nconst ARRAY_LENGTH_OFFSET = 12;\nconst ARRAY_SIZE = 16;\n\nconst BIGINT = typeof BigUint64Array !== \"undefined\";\nconst THIS = Symbol();\nconst CHUNKSIZE = 1024;\n\n/** Gets a string from an U32 and an U16 view on a memory. */\nfunction getStringImpl(buffer, ptr) {\n const U32 = new Uint32Array(buffer);\n const U16 = new Uint16Array(buffer);\n var length = U32[(ptr + SIZE_OFFSET) >>> 2] >>> 1;\n var offset = ptr >>> 1;\n if (length <= CHUNKSIZE) return String.fromCharCode.apply(String, U16.subarray(offset, offset + length));\n const parts = [];\n do {\n const last = U16[offset + CHUNKSIZE - 1];\n const size = last >= 0xD800 && last < 0xDC00 ? CHUNKSIZE - 1 : CHUNKSIZE;\n parts.push(String.fromCharCode.apply(String, U16.subarray(offset, offset += size)));\n length -= size;\n } while (length > CHUNKSIZE);\n return parts.join(\"\") + String.fromCharCode.apply(String, U16.subarray(offset, offset + length));\n}\n\n/** Prepares the base module prior to instantiation. */\nfunction preInstantiate(imports) {\n const baseModule = {};\n\n function getString(memory, ptr) {\n if (!memory) return \"\";\n return getStringImpl(memory.buffer, ptr);\n }\n\n // add common imports used by stdlib for convenience\n const env = (imports.env = imports.env || {});\n env.abort = env.abort || function abort(mesg, file, line, colm) {\n const memory = baseModule.memory || env.memory; // prefer exported, otherwise try imported\n throw Error(\"abort: \" + getString(memory, mesg) + \" at \" + getString(memory, file) + \":\" + line + \":\" + colm);\n }\n env.trace = env.trace || function trace(mesg, n) {\n const memory = baseModule.memory || env.memory;\n console.log(\"trace: \" + getString(memory, mesg) + (n ? \" \" : \"\") + Array.prototype.slice.call(arguments, 2, 2 + n).join(\", \"));\n }\n imports.Math = imports.Math || Math;\n imports.Date = imports.Date || Date;\n\n return baseModule;\n}\n\n/** Prepares the final module once instantiation is complete. */\nfunction postInstantiate(baseModule, instance) {\n const rawExports = instance.exports;\n const memory = rawExports.memory;\n const table = rawExports.table;\n const alloc = rawExports[\"__alloc\"];\n const retain = rawExports[\"__retain\"];\n const rttiBase = rawExports[\"__rtti_base\"] || ~0; // oob if not present\n\n /** Gets the runtime type info for the given id. */\n function getInfo(id) {\n const U32 = new Uint32Array(memory.buffer);\n const count = U32[rttiBase >>> 2];\n if ((id >>>= 0) >= count) throw Error(\"invalid id: \" + id);\n return U32[(rttiBase + 4 >>> 2) + id * 2];\n }\n\n /** Gets the runtime base id for the given id. */\n function getBase(id) {\n const U32 = new Uint32Array(memory.buffer);\n const count = U32[rttiBase >>> 2];\n if ((id >>>= 0) >= count) throw Error(\"invalid id: \" + id);\n return U32[(rttiBase + 4 >>> 2) + id * 2 + 1];\n }\n\n /** Gets the runtime alignment of a collection's values. */\n function getValueAlign(info) {\n return 31 - Math.clz32((info >>> VAL_ALIGN_OFFSET) & 31); // -1 if none\n }\n\n /** Gets the runtime alignment of a collection's keys. */\n function getKeyAlign(info) {\n return 31 - Math.clz32((info >>> KEY_ALIGN_OFFSET) & 31); // -1 if none\n }\n\n /** Allocates a new string in the module's memory and returns its retained pointer. */\n function __allocString(str) {\n const length = str.length;\n const ptr = alloc(length << 1, STRING_ID);\n const U16 = new Uint16Array(memory.buffer);\n for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i);\n return ptr;\n }\n\n baseModule.__allocString = __allocString;\n\n /** Reads a string from the module's memory by its pointer. */\n function __getString(ptr) {\n const buffer = memory.buffer;\n const id = new Uint32Array(buffer)[ptr + ID_OFFSET >>> 2];\n if (id !== STRING_ID) throw Error(\"not a string: \" + ptr);\n return getStringImpl(buffer, ptr);\n }\n\n baseModule.__getString = __getString;\n\n /** Gets the view matching the specified alignment, signedness and floatness. */\n function getView(alignLog2, signed, float) {\n const buffer = memory.buffer;\n if (float) {\n switch (alignLog2) {\n case 2: return new Float32Array(buffer);\n case 3: return new Float64Array(buffer);\n }\n } else {\n switch (alignLog2) {\n case 0: return new (signed ? Int8Array : Uint8Array)(buffer);\n case 1: return new (signed ? Int16Array : Uint16Array)(buffer);\n case 2: return new (signed ? Int32Array : Uint32Array)(buffer);\n case 3: return new (signed ? BigInt64Array : BigUint64Array)(buffer);\n }\n }\n throw Error(\"unsupported align: \" + alignLog2);\n }\n\n /** Allocates a new array in the module's memory and returns its retained pointer. */\n function __allocArray(id, values) {\n const info = getInfo(id);\n if (!(info & (ARRAYBUFFERVIEW | ARRAY))) throw Error(\"not an array: \" + id + \" @ \" + info);\n const align = getValueAlign(info);\n const length = values.length;\n const buf = alloc(length << align, ARRAYBUFFER_ID);\n const arr = alloc(info & ARRAY ? ARRAY_SIZE : ARRAYBUFFERVIEW_SIZE, id);\n const U32 = new Uint32Array(memory.buffer);\n U32[arr + ARRAYBUFFERVIEW_BUFFER_OFFSET >>> 2] = retain(buf);\n U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2] = buf;\n U32[arr + ARRAYBUFFERVIEW_DATALENGTH_OFFSET >>> 2] = length << align;\n if (info & ARRAY) U32[arr + ARRAY_LENGTH_OFFSET >>> 2] = length;\n const view = getView(align, info & VAL_SIGNED, info & VAL_FLOAT);\n if (info & VAL_MANAGED) {\n for (let i = 0; i < length; ++i) view[(buf >>> align) + i] = retain(values[i]);\n } else {\n view.set(values, buf >>> align);\n }\n return arr;\n }\n\n baseModule.__allocArray = __allocArray;\n\n /** Gets a live view on an array's values in the module's memory. Infers the array type from RTTI. */\n function __getArrayView(arr) {\n const U32 = new Uint32Array(memory.buffer);\n const id = U32[arr + ID_OFFSET >>> 2];\n const info = getInfo(id);\n if (!(info & ARRAYBUFFERVIEW)) throw Error(\"not an array: \" + id);\n const align = getValueAlign(info);\n var buf = U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2];\n const length = info & ARRAY\n ? U32[arr + ARRAY_LENGTH_OFFSET >>> 2]\n : U32[buf + SIZE_OFFSET >>> 2] >>> align;\n return getView(align, info & VAL_SIGNED, info & VAL_FLOAT)\n .subarray(buf >>>= align, buf + length);\n }\n\n baseModule.__getArrayView = __getArrayView;\n\n /** Copies an array's values from the module's memory. Infers the array type from RTTI. */\n function __getArray(arr) {\n const input = __getArrayView(arr);\n const len = input.length;\n const out = new Array(len);\n for (let i = 0; i < len; i++) out[i] = input[i];\n return out;\n }\n\n baseModule.__getArray = __getArray;\n\n /** Copies an ArrayBuffer's value from the module's memory. */\n function __getArrayBuffer(ptr) {\n const buffer = memory.buffer;\n const length = new Uint32Array(buffer)[ptr + SIZE_OFFSET >>> 2];\n return buffer.slice(ptr, ptr + length);\n }\n\n baseModule.__getArrayBuffer = __getArrayBuffer;\n\n /** Copies a typed array's values from the module's memory. */\n function getTypedArray(Type, alignLog2, ptr) {\n return new Type(getTypedArrayView(Type, alignLog2, ptr));\n }\n\n /** Gets a live view on a typed array's values in the module's memory. */\n function getTypedArrayView(Type, alignLog2, ptr) {\n const buffer = memory.buffer;\n const U32 = new Uint32Array(buffer);\n const bufPtr = U32[ptr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2];\n return new Type(buffer, bufPtr, U32[bufPtr + SIZE_OFFSET >>> 2] >>> alignLog2);\n }\n\n baseModule.__getInt8Array = getTypedArray.bind(null, Int8Array, 0);\n baseModule.__getInt8ArrayView = getTypedArrayView.bind(null, Int8Array, 0);\n baseModule.__getUint8Array = getTypedArray.bind(null, Uint8Array, 0);\n baseModule.__getUint8ArrayView = getTypedArrayView.bind(null, Uint8Array, 0);\n baseModule.__getUint8ClampedArray = getTypedArray.bind(null, Uint8ClampedArray, 0);\n baseModule.__getUint8ClampedArrayView = getTypedArrayView.bind(null, Uint8ClampedArray, 0);\n baseModule.__getInt16Array = getTypedArray.bind(null, Int16Array, 1);\n baseModule.__getInt16ArrayView = getTypedArrayView.bind(null, Int16Array, 1);\n baseModule.__getUint16Array = getTypedArray.bind(null, Uint16Array, 1);\n baseModule.__getUint16ArrayView = getTypedArrayView.bind(null, Uint16Array, 1);\n baseModule.__getInt32Array = getTypedArray.bind(null, Int32Array, 2);\n baseModule.__getInt32ArrayView = getTypedArrayView.bind(null, Int32Array, 2);\n baseModule.__getUint32Array = getTypedArray.bind(null, Uint32Array, 2);\n baseModule.__getUint32ArrayView = getTypedArrayView.bind(null, Uint32Array, 2);\n if (BIGINT) {\n baseModule.__getInt64Array = getTypedArray.bind(null, BigInt64Array, 3);\n baseModule.__getInt64ArrayView = getTypedArrayView.bind(null, BigInt64Array, 3);\n baseModule.__getUint64Array = getTypedArray.bind(null, BigUint64Array, 3);\n baseModule.__getUint64ArrayView = getTypedArrayView.bind(null, BigUint64Array, 3);\n }\n baseModule.__getFloat32Array = getTypedArray.bind(null, Float32Array, 2);\n baseModule.__getFloat32ArrayView = getTypedArrayView.bind(null, Float32Array, 2);\n baseModule.__getFloat64Array = getTypedArray.bind(null, Float64Array, 3);\n baseModule.__getFloat64ArrayView = getTypedArrayView.bind(null, Float64Array, 3);\n\n /** Tests whether an object is an instance of the class represented by the specified base id. */\n function __instanceof(ptr, baseId) {\n const U32 = new Uint32Array(memory.buffer);\n var id = U32[(ptr + ID_OFFSET) >>> 2];\n if (id <= U32[rttiBase >>> 2]) {\n do if (id == baseId) return true;\n while (id = getBase(id));\n }\n return false;\n }\n\n baseModule.__instanceof = __instanceof;\n\n // Pull basic exports to baseModule so code in preInstantiate can use them\n baseModule.memory = baseModule.memory || memory;\n baseModule.table = baseModule.table || table;\n\n // Demangle exports and provide the usual utility on the prototype\n return demangle(rawExports, baseModule);\n}\n\nfunction isResponse(o) {\n return typeof Response !== \"undefined\" && o instanceof Response;\n}\n\n/** Asynchronously instantiates an AssemblyScript module from anything that can be instantiated. */\nasync function instantiate(source, imports) {\n if (isResponse(source = await source)) return instantiateStreaming(source, imports);\n return postInstantiate(\n preInstantiate(imports || (imports = {})),\n await WebAssembly.instantiate(\n source instanceof WebAssembly.Module\n ? source\n : await WebAssembly.compile(source),\n imports\n )\n );\n}\n\nexports.instantiate = instantiate;\n\n/** Synchronously instantiates an AssemblyScript module from a WebAssembly.Module or binary buffer. */\nfunction instantiateSync(source, imports) {\n return postInstantiate(\n preInstantiate(imports || (imports = {})),\n new WebAssembly.Instance(\n source instanceof WebAssembly.Module\n ? source\n : new WebAssembly.Module(source),\n imports\n )\n )\n}\n\nexports.instantiateSync = instantiateSync;\n\n/** Asynchronously instantiates an AssemblyScript module from a response, i.e. as obtained by `fetch`. */\nasync function instantiateStreaming(source, imports) {\n if (!WebAssembly.instantiateStreaming) {\n return instantiate(\n isResponse(source = await source)\n ? source.arrayBuffer()\n : source,\n imports\n );\n }\n return postInstantiate(\n preInstantiate(imports || (imports = {})),\n (await WebAssembly.instantiateStreaming(source, imports)).instance\n );\n}\n\nexports.instantiateStreaming = instantiateStreaming;\n\n/** Demangles an AssemblyScript module's exports to a friendly object structure. */\nfunction demangle(exports, baseModule) {\n var module = baseModule ? Object.create(baseModule) : {};\n var setArgumentsLength = exports[\"__argumentsLength\"]\n ? function(length) { exports[\"__argumentsLength\"].value = length; }\n : exports[\"__setArgumentsLength\"] || exports[\"__setargc\"] || function() {};\n for (let internalName in exports) {\n if (!Object.prototype.hasOwnProperty.call(exports, internalName)) continue;\n const elem = exports[internalName];\n let parts = internalName.split(\".\");\n let curr = module;\n while (parts.length > 1) {\n let part = parts.shift();\n if (!Object.prototype.hasOwnProperty.call(curr, part)) curr[part] = {};\n curr = curr[part];\n }\n let name = parts[0];\n let hash = name.indexOf(\"#\");\n if (hash >= 0) {\n let className = name.substring(0, hash);\n let classElem = curr[className];\n if (typeof classElem === \"undefined\" || !classElem.prototype) {\n let ctor = function(...args) {\n return ctor.wrap(ctor.prototype.constructor(0, ...args));\n };\n ctor.prototype = {\n valueOf: function valueOf() {\n return this[THIS];\n }\n };\n ctor.wrap = function(thisValue) {\n return Object.create(ctor.prototype, { [THIS]: { value: thisValue, writable: false } });\n };\n if (classElem) Object.getOwnPropertyNames(classElem).forEach(name =>\n Object.defineProperty(ctor, name, Object.getOwnPropertyDescriptor(classElem, name))\n );\n curr[className] = ctor;\n }\n name = name.substring(hash + 1);\n curr = curr[className].prototype;\n if (/^(get|set):/.test(name)) {\n if (!Object.prototype.hasOwnProperty.call(curr, name = name.substring(4))) {\n let getter = exports[internalName.replace(\"set:\", \"get:\")];\n let setter = exports[internalName.replace(\"get:\", \"set:\")];\n Object.defineProperty(curr, name, {\n get: function() { return getter(this[THIS]); },\n set: function(value) { setter(this[THIS], value); },\n enumerable: true\n });\n }\n } else {\n if (name === 'constructor') {\n (curr[name] = (...args) => {\n setArgumentsLength(args.length);\n return elem(...args);\n }).original = elem;\n } else { // instance method\n (curr[name] = function(...args) { // !\n setArgumentsLength(args.length);\n return elem(this[THIS], ...args);\n }).original = elem;\n }\n }\n } else {\n if (/^(get|set):/.test(name)) {\n if (!Object.prototype.hasOwnProperty.call(curr, name = name.substring(4))) {\n Object.defineProperty(curr, name, {\n get: exports[internalName.replace(\"set:\", \"get:\")],\n set: exports[internalName.replace(\"get:\", \"set:\")],\n enumerable: true\n });\n }\n } else if (typeof elem === \"function\" && elem !== setArgumentsLength) {\n (curr[name] = (...args) => {\n setArgumentsLength(args.length);\n return elem(...args);\n }).original = elem;\n } else {\n curr[name] = elem;\n }\n }\n }\n return module;\n}\n\nexports.demangle = demangle;\n", "\nconst { instantiate } = require(\"@assemblyscript/loader\");\n\nloadWebAssembly.supported = typeof WebAssembly !== 'undefined'\n\nfunction loadWebAssembly (imp = {}) {\n if (!loadWebAssembly.supported) return null\n \n var wasm = new Uint8Array([0,97,115,109,1,0,0,0,1,78,14,96,2,127,126,0,96,1,127,1,126,96,2,127,127,0,96,1,127,1,127,96,1,127,0,96,2,127,127,1,127,96,3,127,127,127,1,127,96,0,0,96,3,127,127,127,0,96,0,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,1,127,96,1,126,1,127,96,2,126,126,1,126,2,13,1,3,101,110,118,5,97,98,111,114,116,0,10,3,54,53,2,2,8,9,3,5,2,8,6,5,3,4,2,6,9,12,13,2,5,11,3,2,3,2,3,2,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,6,7,7,4,4,5,3,1,0,1,6,47,9,127,1,65,0,11,127,1,65,0,11,127,0,65,3,11,127,0,65,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,240,2,11,127,0,65,6,11,7,240,5,41,6,109,101,109,111,114,121,2,0,7,95,95,97,108,108,111,99,0,10,8,95,95,114,101,116,97,105,110,0,11,9,95,95,114,101,108,101,97,115,101,0,12,9,95,95,99,111,108,108,101,99,116,0,51,11,95,95,114,116,116,105,95,98,97,115,101,3,7,13,73,110,116,51,50,65,114,114,97,121,95,73,68,3,2,13,85,105,110,116,56,65,114,114,97,121,95,73,68,3,3,6,100,101,103,114,101,101,0,16,3,109,111,100,0,17,5,82,97,98,105,110,3,8,16,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,0,21,16,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,0,22,21,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,23,21,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,24,14,82,97,98,105,110,35,103,101,116,58,119,112,111,115,0,25,14,82,97,98,105,110,35,115,101,116,58,119,112,111,115,0,26,15,82,97,98,105,110,35,103,101,116,58,99,111,117,110,116,0,27,15,82,97,98,105,110,35,115,101,116,58,99,111,117,110,116,0,28,13,82,97,98,105,110,35,103,101,116,58,112,111,115,0,29,13,82,97,98,105,110,35,115,101,116,58,112,111,115,0,30,15,82,97,98,105,110,35,103,101,116,58,115,116,97,114,116,0,31,15,82,97,98,105,110,35,115,101,116,58,115,116,97,114,116,0,32,16,82,97,98,105,110,35,103,101,116,58,100,105,103,101,115,116,0,33,16,82,97,98,105,110,35,115,101,116,58,100,105,103,101,115,116,0,34,21,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,35,21,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,36,22,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,37,22,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,38,31,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,39,31,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,40,20,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,0,41,20,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,0,42,17,82,97,98,105,110,35,103,101,116,58,109,105,110,115,105,122,101,0,43,17,82,97,98,105,110,35,115,101,116,58,109,105,110,115,105,122,101,0,44,17,82,97,98,105,110,35,103,101,116,58,109,97,120,115,105,122,101,0,45,17,82,97,98,105,110,35,115,101,116,58,109,97,120,115,105,122,101,0,46,14,82,97,98,105,110,35,103,101,116,58,109,97,115,107,0,47,14,82,97,98,105,110,35,115,101,116,58,109,97,115,107,0,48,17,82,97,98,105,110,35,99,111,110,115,116,114,117,99,116,111,114,0,20,17,82,97,98,105,110,35,102,105,110,103,101,114,112,114,105,110,116,0,49,8,1,50,10,165,31,53,199,1,1,4,127,32,1,40,2,0,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,3,65,4,107,118,65,16,115,33,4,32,3,65,7,107,11,33,3,32,1,40,2,20,33,2,32,1,40,2,16,34,5,4,64,32,5,32,2,54,2,20,11,32,2,4,64,32,2,32,5,54,2,16,11,32,1,32,0,32,4,32,3,65,4,116,106,65,2,116,106,40,2,96,70,4,64,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,2,54,2,96,32,2,69,4,64,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,65,127,115,113,34,1,54,2,4,32,1,69,4,64,32,0,32,0,40,2,0,65,1,32,3,116,65,127,115,113,54,2,0,11,11,11,11,226,2,1,6,127,32,1,40,2,0,33,3,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,5,65,1,113,4,64,32,3,65,124,113,65,16,106,32,5,65,124,113,106,34,2,65,240,255,255,255,3,73,4,64,32,0,32,4,16,1,32,1,32,2,32,3,65,3,113,114,34,3,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,5,11,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,2,40,2,0,34,6,65,124,113,65,16,106,32,3,65,124,113,106,34,7,65,240,255,255,255,3,73,4,64,32,0,32,2,16,1,32,2,32,7,32,6,65,3,113,114,34,3,54,2,0,32,2,33,1,11,11,32,4,32,5,65,2,114,54,2,0,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,2,65,4,107,118,65,16,115,33,4,32,2,65,7,107,11,34,3,65,4,116,32,4,106,65,2,116,106,40,2,96,33,2,32,1,65,0,54,2,16,32,1,32,2,54,2,20,32,2,4,64,32,2,32,1,54,2,16,11,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,3,116,114,54,2,0,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,114,54,2,4,11,119,1,1,127,32,2,2,127,32,0,40,2,160,12,34,2,4,64,32,2,32,1,65,16,107,70,4,64,32,2,40,2,0,33,3,32,1,65,16,107,33,1,11,11,32,1,11,107,34,2,65,48,73,4,64,15,11,32,1,32,3,65,2,113,32,2,65,32,107,65,1,114,114,54,2,0,32,1,65,0,54,2,16,32,1,65,0,54,2,20,32,1,32,2,106,65,16,107,34,2,65,2,54,2,0,32,0,32,2,54,2,160,12,32,0,32,1,16,2,11,155,1,1,3,127,35,0,34,0,69,4,64,65,1,63,0,34,0,74,4,127,65,1,32,0,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,176,3,34,0,65,0,54,2,0,65,208,15,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,176,3,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,176,3,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,176,3,65,224,15,63,0,65,16,116,16,3,65,176,3,36,0,11,32,0,11,45,0,32,0,65,240,255,255,255,3,79,4,64,65,32,65,224,0,65,201,3,65,29,16,0,0,11,32,0,65,15,106,65,112,113,34,0,65,16,32,0,65,16,75,27,11,169,1,1,1,127,32,0,32,1,65,128,2,73,4,127,32,1,65,4,118,33,1,65,0,5,32,1,65,248,255,255,255,1,73,4,64,32,1,65,1,65,27,32,1,103,107,116,106,65,1,107,33,1,11,32,1,65,31,32,1,103,107,34,2,65,4,107,118,65,16,115,33,1,32,2,65,7,107,11,34,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,111,1,1,127,63,0,34,2,32,1,65,248,255,255,255,1,73,4,127,32,1,65,1,65,27,32,1,103,107,116,65,1,107,106,5,32,1,11,65,16,32,0,40,2,160,12,32,2,65,16,116,65,16,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,32,0,32,2,65,16,116,63,0,65,16,116,16,3,11,113,1,2,127,32,1,40,2,0,34,3,65,124,113,32,2,107,34,4,65,32,79,4,64,32,1,32,2,32,3,65,2,113,114,54,2,0,32,2,32,1,65,16,106,106,34,1,32,4,65,16,107,65,1,114,54,2,0,32,0,32,1,16,2,5,32,1,32,3,65,126,113,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,32,1,65,16,106,32,1,40,2,0,65,124,113,106,40,2,0,65,125,113,54,2,0,11,11,91,1,2,127,32,0,32,1,16,5,34,4,16,6,34,3,69,4,64,65,1,36,1,65,0,36,1,32,0,32,4,16,6,34,3,69,4,64,32,0,32,4,16,7,32,0,32,4,16,6,33,3,11,11,32,3,65,0,54,2,4,32,3,32,2,54,2,8,32,3,32,1,54,2,12,32,0,32,3,16,1,32,0,32,3,32,4,16,8,32,3,11,13,0,16,4,32,0,32,1,16,9,65,16,106,11,33,1,1,127,32,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,18,0,32,0,65,172,3,75,4,64,32,0,65,16,107,16,52,11,11,140,3,1,1,127,2,64,32,1,69,13,0,32,0,65,0,58,0,0,32,0,32,1,106,65,1,107,65,0,58,0,0,32,1,65,2,77,13,0,32,0,65,1,106,65,0,58,0,0,32,0,65,2,106,65,0,58,0,0,32,0,32,1,106,34,2,65,2,107,65,0,58,0,0,32,2,65,3,107,65,0,58,0,0,32,1,65,6,77,13,0,32,0,65,3,106,65,0,58,0,0,32,0,32,1,106,65,4,107,65,0,58,0,0,32,1,65,8,77,13,0,32,1,65,0,32,0,107,65,3,113,34,1,107,33,2,32,0,32,1,106,34,0,65,0,54,2,0,32,0,32,2,65,124,113,34,1,106,65,4,107,65,0,54,2,0,32,1,65,8,77,13,0,32,0,65,4,106,65,0,54,2,0,32,0,65,8,106,65,0,54,2,0,32,0,32,1,106,34,2,65,12,107,65,0,54,2,0,32,2,65,8,107,65,0,54,2,0,32,1,65,24,77,13,0,32,0,65,12,106,65,0,54,2,0,32,0,65,16,106,65,0,54,2,0,32,0,65,20,106,65,0,54,2,0,32,0,65,24,106,65,0,54,2,0,32,0,32,1,106,34,2,65,28,107,65,0,54,2,0,32,2,65,24,107,65,0,54,2,0,32,2,65,20,107,65,0,54,2,0,32,2,65,16,107,65,0,54,2,0,32,0,32,0,65,4,113,65,24,106,34,2,106,33,0,32,1,32,2,107,33,1,3,64,32,1,65,32,79,4,64,32,0,66,0,55,3,0,32,0,65,8,106,66,0,55,3,0,32,0,65,16,106,66,0,55,3,0,32,0,65,24,106,66,0,55,3,0,32,1,65,32,107,33,1,32,0,65,32,106,33,0,12,1,11,11,11,11,178,1,1,3,127,32,1,65,240,255,255,255,3,32,2,118,75,4,64,65,144,1,65,192,1,65,23,65,56,16,0,0,11,32,1,32,2,116,34,3,65,0,16,10,34,2,32,3,16,13,32,0,69,4,64,65,12,65,2,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,2,34,1,32,0,40,2,0,34,4,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,32,4,16,12,11,32,0,32,1,54,2,0,32,0,32,2,54,2,4,32,0,32,3,54,2,8,32,0,11,46,1,2,127,65,12,65,5,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,65,128,2,65,3,16,14,11,9,0,65,63,32,0,121,167,107,11,49,1,2,127,65,63,32,1,121,167,107,33,2,3,64,65,63,32,0,121,167,107,32,2,107,34,3,65,0,78,4,64,32,0,32,1,32,3,172,134,133,33,0,12,1,11,11,32,0,11,40,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,163,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,65,0,58,0,0,11,38,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,152,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,45,0,0,11,254,5,2,1,127,4,126,32,0,69,4,64,65,232,0,65,6,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,24,32,0,66,0,55,3,32,32,0,66,0,55,3,40,32,0,66,0,55,3,48,32,0,66,0,55,3,56,32,0,66,0,55,3,64,32,0,66,0,55,3,72,32,0,66,0,55,3,80,32,0,66,0,55,3,88,32,0,66,0,55,3,96,32,0,32,2,173,55,3,80,32,0,32,3,173,55,3,88,65,12,65,4,16,10,34,2,65,172,3,75,4,64,32,2,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,32,4,65,0,16,14,33,2,32,0,40,2,0,16,12,32,0,32,2,54,2,0,32,0,32,4,54,2,4,32,0,66,1,32,1,173,134,66,1,125,55,3,96,32,0,66,243,130,183,218,216,230,232,30,55,3,72,35,4,69,4,64,65,0,33,2,3,64,32,2,65,128,2,72,4,64,32,2,65,255,1,113,173,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,65,0,33,4,3,64,32,4,32,0,40,2,4,65,1,107,72,4,64,32,6,66,8,134,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,32,4,65,1,106,33,4,12,1,11,11,35,6,40,2,4,32,2,65,3,116,106,32,6,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,63,32,0,41,3,72,121,167,107,172,33,7,65,0,33,2,3,64,32,2,65,128,2,72,4,64,35,5,33,1,32,2,172,32,7,134,34,8,33,6,65,63,32,0,41,3,72,34,9,121,167,107,33,3,3,64,65,63,32,6,121,167,107,32,3,107,34,4,65,0,78,4,64,32,6,32,9,32,4,172,134,133,33,6,12,1,11,11,32,1,40,2,4,32,2,65,3,116,106,32,6,32,8,132,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,1,36,4,11,32,0,66,0,55,3,24,32,0,66,0,55,3,32,65,0,33,2,3,64,32,2,32,0,40,2,4,72,4,64,32,0,40,2,0,32,2,16,18,32,2,65,1,106,33,2,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,6,66,45,136,167,65,3,116,106,41,3,0,32,6,66,8,134,66,1,132,133,55,3,40,32,0,11,38,1,1,127,32,0,40,2,0,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,55,1,2,127,32,1,32,0,40,2,0,34,2,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,16,12,11,32,0,32,1,54,2,0,11,7,0,32,0,40,2,4,11,9,0,32,0,32,1,54,2,4,11,7,0,32,0,40,2,8,11,9,0,32,0,32,1,54,2,8,11,7,0,32,0,41,3,16,11,9,0,32,0,32,1,55,3,16,11,7,0,32,0,41,3,24,11,9,0,32,0,32,1,55,3,24,11,7,0,32,0,41,3,32,11,9,0,32,0,32,1,55,3,32,11,7,0,32,0,41,3,40,11,9,0,32,0,32,1,55,3,40,11,7,0,32,0,41,3,48,11,9,0,32,0,32,1,55,3,48,11,7,0,32,0,41,3,56,11,9,0,32,0,32,1,55,3,56,11,7,0,32,0,41,3,64,11,9,0,32,0,32,1,55,3,64,11,7,0,32,0,41,3,72,11,9,0,32,0,32,1,55,3,72,11,7,0,32,0,41,3,80,11,9,0,32,0,32,1,55,3,80,11,7,0,32,0,41,3,88,11,9,0,32,0,32,1,55,3,88,11,7,0,32,0,41,3,96,11,9,0,32,0,32,1,55,3,96,11,172,4,2,5,127,1,126,32,2,65,172,3,75,4,64,32,2,65,16,107,34,4,32,4,40,2,4,65,1,106,54,2,4,11,32,2,33,4,65,0,33,2,32,1,40,2,8,33,5,32,1,40,2,4,33,6,3,64,2,127,65,0,33,3,3,64,32,3,32,5,72,4,64,32,3,32,6,106,45,0,0,33,1,32,0,40,2,0,32,0,40,2,8,16,19,33,7,32,0,40,2,8,32,0,40,2,0,40,2,4,106,32,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,7,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,1,173,32,8,66,8,134,132,133,55,3,40,32,0,32,0,41,3,16,66,1,124,55,3,16,32,0,32,0,41,3,24,66,1,124,55,3,24,32,0,41,3,16,32,0,41,3,80,90,4,127,32,0,41,3,40,32,0,41,3,96,131,80,5,65,0,11,4,127,65,1,5,32,0,41,3,16,32,0,41,3,88,90,11,4,64,32,0,32,0,41,3,32,55,3,48,32,0,32,0,41,3,16,55,3,56,32,0,32,0,41,3,40,55,3,64,65,0,33,1,3,64,32,1,32,0,40,2,4,72,4,64,32,0,40,2,0,32,1,16,18,32,1,65,1,106,33,1,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,8,66,8,134,66,1,132,133,55,3,40,32,3,65,1,106,12,3,11,32,3,65,1,106,33,3,12,1,11,11,65,127,11,34,1,65,0,78,4,64,32,5,32,1,107,33,5,32,1,32,6,106,33,6,32,2,34,1,65,1,106,33,2,32,4,40,2,4,32,1,65,2,116,106,32,0,41,3,56,62,2,0,12,1,11,11,32,4,11,10,0,16,15,36,5,16,15,36,6,11,3,0,1,11,73,1,2,127,32,0,40,2,4,34,1,65,255,255,255,255,0,113,34,2,65,1,70,4,64,32,0,65,16,106,16,53,32,0,32,0,40,2,0,65,1,114,54,2,0,35,0,32,0,16,2,5,32,0,32,2,65,1,107,32,1,65,128,128,128,128,127,113,114,54,2,4,11,11,58,0,2,64,2,64,2,64,32,0,65,8,107,40,2,0,14,7,0,0,1,1,1,1,1,2,11,15,11,32,0,40,2,0,34,0,4,64,32,0,65,172,3,79,4,64,32,0,65,16,107,16,52,11,11,15,11,0,11,11,137,3,7,0,65,16,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,208,0,11,45,30,0,0,0,1,0,0,0,1,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,128,1,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,176,1,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,240,1,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,176,2,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,126,0,108,0,105,0,98,0,47,0,116,0,121,0,112,0,101,0,100,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,240,2,11,53,7,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,145,4,0,0,2,0,0,0,49,0,0,0,2,0,0,0,17,1,0,0,2,0,0,0,16,0,34,16,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,16,46,47,114,97,98,105,110,46,119,97,115,109,46,109,97,112])\n // make it work async because browsers throw when a wasm module is bigger than 4kb and load sync\n return instantiate(new Response(new Blob([wasm], {type: 'application/wasm'})), imp)\n}\nmodule.exports = loadWebAssembly\n", "const Rabin = require('./rabin')\nconst getRabin = require('../dist/rabin-wasm.node.js')\n\nconst create = async (avg, min, max, windowSize, polynomial) => {\n const compiled = await getRabin()\n return new Rabin(compiled, avg, min, max, windowSize, polynomial)\n}\n\nmodule.exports = {\n Rabin,\n create\n}\n", "'use strict'\n\n// JS treats subjects of bitwise operators as SIGNED 32 bit numbers,\n// which means the maximum amount of bits we can store inside each byte\n// is 7..\nconst BITS_PER_BYTE = 7\n\nmodule.exports = class SparseArray {\n constructor () {\n this._bitArrays = []\n this._data = []\n this._length = 0\n this._changedLength = false\n this._changedData = false\n }\n\n set (index, value) {\n let pos = this._internalPositionFor(index, false)\n if (value === undefined) {\n // unsetting\n if (pos !== -1) {\n // remove item from bit array and array itself\n this._unsetInternalPos(pos)\n this._unsetBit(index)\n this._changedLength = true\n this._changedData = true\n }\n } else {\n let needsSort = false\n if (pos === -1) {\n pos = this._data.length\n this._setBit(index)\n this._changedData = true\n } else {\n needsSort = true\n }\n this._setInternalPos(pos, index, value, needsSort)\n this._changedLength = true\n }\n }\n\n unset (index) {\n this.set(index, undefined)\n }\n\n get (index) {\n this._sortData()\n const pos = this._internalPositionFor(index, true)\n if (pos === -1) {\n return undefined\n }\n return this._data[pos][1]\n }\n\n push (value) {\n this.set(this.length, value)\n return this.length\n }\n\n get length () {\n this._sortData()\n if (this._changedLength) {\n const last = this._data[this._data.length - 1]\n this._length = last ? last[0] + 1 : 0\n this._changedLength = false\n }\n return this._length\n }\n\n forEach (iterator) {\n let i = 0\n while(i < this.length) {\n iterator(this.get(i), i, this)\n i++\n }\n }\n\n map (iterator) {\n let i = 0\n let mapped = new Array(this.length)\n while(i < this.length) {\n mapped[i] = iterator(this.get(i), i, this)\n i++\n }\n return mapped\n }\n\n reduce (reducer, initialValue) {\n let i = 0\n let acc = initialValue\n while(i < this.length) {\n const value = this.get(i)\n acc = reducer(acc, value, i)\n i++\n }\n return acc\n }\n\n find (finder) {\n let i = 0, found, last\n while ((i < this.length) && !found) {\n last = this.get(i)\n found = finder(last)\n i++\n }\n return found ? last : undefined\n }\n\n _internalPositionFor (index, noCreate) {\n const bytePos = this._bytePosFor(index, noCreate)\n if (bytePos >= this._bitArrays.length) {\n return -1\n }\n const byte = this._bitArrays[bytePos]\n const bitPos = index - bytePos * BITS_PER_BYTE\n const exists = (byte & (1 << bitPos)) > 0\n if (!exists) {\n return -1\n }\n const previousPopCount = this._bitArrays.slice(0, bytePos).reduce(popCountReduce, 0)\n\n const mask = ~(0xffffffff << (bitPos + 1))\n const bytePopCount = popCount(byte & mask)\n const arrayPos = previousPopCount + bytePopCount - 1\n return arrayPos\n }\n\n _bytePosFor (index, noCreate) {\n const bytePos = Math.floor(index / BITS_PER_BYTE)\n const targetLength = bytePos + 1\n while (!noCreate && this._bitArrays.length < targetLength) {\n this._bitArrays.push(0)\n }\n return bytePos\n }\n\n _setBit (index) {\n const bytePos = this._bytePosFor(index, false)\n this._bitArrays[bytePos] |= (1 << (index - (bytePos * BITS_PER_BYTE)))\n }\n\n _unsetBit(index) {\n const bytePos = this._bytePosFor(index, false)\n this._bitArrays[bytePos] &= ~(1 << (index - (bytePos * BITS_PER_BYTE)))\n }\n\n _setInternalPos(pos, index, value, needsSort) {\n const data =this._data\n const elem = [index, value]\n if (needsSort) {\n this._sortData()\n data[pos] = elem\n } else {\n // new element. just shove it into the array\n // but be nice about where we shove it\n // in order to make sorting it later easier\n if (data.length) {\n if (data[data.length - 1][0] >= index) {\n data.push(elem)\n } else if (data[0][0] <= index) {\n data.unshift(elem)\n } else {\n const randomIndex = Math.round(data.length / 2)\n this._data = data.slice(0, randomIndex).concat(elem).concat(data.slice(randomIndex))\n }\n } else {\n this._data.push(elem)\n }\n this._changedData = true\n this._changedLength = true\n }\n }\n\n _unsetInternalPos (pos) {\n this._data.splice(pos, 1)\n }\n\n _sortData () {\n if (this._changedData) {\n this._data.sort(sortInternal)\n }\n\n this._changedData = false\n }\n\n bitField () {\n const bytes = []\n let pendingBitsForResultingByte = 8\n let pendingBitsForNewByte = 0\n let resultingByte = 0\n let newByte\n const pending = this._bitArrays.slice()\n while (pending.length || pendingBitsForNewByte) {\n if (pendingBitsForNewByte === 0) {\n newByte = pending.shift()\n pendingBitsForNewByte = 7\n }\n\n const usingBits = Math.min(pendingBitsForNewByte, pendingBitsForResultingByte)\n const mask = ~(0b11111111 << usingBits)\n const masked = newByte & mask\n resultingByte |= masked << (8 - pendingBitsForResultingByte)\n newByte = newByte >>> usingBits\n pendingBitsForNewByte -= usingBits\n pendingBitsForResultingByte -= usingBits\n\n if (!pendingBitsForResultingByte || (!pendingBitsForNewByte && !pending.length)) {\n bytes.push(resultingByte)\n resultingByte = 0\n pendingBitsForResultingByte = 8\n }\n }\n\n // remove trailing zeroes\n for(var i = bytes.length - 1; i > 0; i--) {\n const value = bytes[i]\n if (value === 0) {\n bytes.pop()\n } else {\n break\n }\n }\n\n return bytes\n }\n\n compactArray () {\n this._sortData()\n return this._data.map(valueOnly)\n }\n}\n\nfunction popCountReduce (count, byte) {\n return count + popCount(byte)\n}\n\nfunction popCount(_v) {\n let v = _v\n v = v - ((v >> 1) & 0x55555555) // reuse input as temporary\n v = (v & 0x33333333) + ((v >> 2) & 0x33333333) // temp\n return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24\n}\n\nfunction sortInternal (a, b) {\n return a[0] - b[0]\n}\n\nfunction valueOnly (elem) {\n return elem[1]\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", "\n'use strict';\n\nmodule.exports = {\n 'RTLD_LAZY': 1,\n 'RTLD_NOW': 2,\n 'RTLD_GLOBAL': 8,\n 'RTLD_LOCAL': 4,\n 'E2BIG': 7,\n 'EACCES': 13,\n 'EADDRINUSE': 48,\n 'EADDRNOTAVAIL': 49,\n 'EAFNOSUPPORT': 47,\n 'EAGAIN': 35,\n 'EALREADY': 37,\n 'EBADF': 9,\n 'EBADMSG': 94,\n 'EBUSY': 16,\n 'ECANCELED': 89,\n 'ECHILD': 10,\n 'ECONNABORTED': 53,\n 'ECONNREFUSED': 61,\n 'ECONNRESET': 54,\n 'EDEADLK': 11,\n 'EDESTADDRREQ': 39,\n 'EDOM': 33,\n 'EDQUOT': 69,\n 'EEXIST': 17,\n 'EFAULT': 14,\n 'EFBIG': 27,\n 'EHOSTUNREACH': 65,\n 'EIDRM': 90,\n 'EILSEQ': 92,\n 'EINPROGRESS': 36,\n 'EINTR': 4,\n 'EINVAL': 22,\n 'EIO': 5,\n 'EISCONN': 56,\n 'EISDIR': 21,\n 'ELOOP': 62,\n 'EMFILE': 24,\n 'EMLINK': 31,\n 'EMSGSIZE': 40,\n 'EMULTIHOP': 95,\n 'ENAMETOOLONG': 63,\n 'ENETDOWN': 50,\n 'ENETRESET': 52,\n 'ENETUNREACH': 51,\n 'ENFILE': 23,\n 'ENOBUFS': 55,\n 'ENODATA': 96,\n 'ENODEV': 19,\n 'ENOENT': 2,\n 'ENOEXEC': 8,\n 'ENOLCK': 77,\n 'ENOLINK': 97,\n 'ENOMEM': 12,\n 'ENOMSG': 91,\n 'ENOPROTOOPT': 42,\n 'ENOSPC': 28,\n 'ENOSR': 98,\n 'ENOSTR': 99,\n 'ENOSYS': 78,\n 'ENOTCONN': 57,\n 'ENOTDIR': 20,\n 'ENOTEMPTY': 66,\n 'ENOTSOCK': 38,\n 'ENOTSUP': 45,\n 'ENOTTY': 25,\n 'ENXIO': 6,\n 'EOPNOTSUPP': 102,\n 'EOVERFLOW': 84,\n 'EPERM': 1,\n 'EPIPE': 32,\n 'EPROTO': 100,\n 'EPROTONOSUPPORT': 43,\n 'EPROTOTYPE': 41,\n 'ERANGE': 34,\n 'EROFS': 30,\n 'ESPIPE': 29,\n 'ESRCH': 3,\n 'ESTALE': 70,\n 'ETIME': 101,\n 'ETIMEDOUT': 60,\n 'ETXTBSY': 26,\n 'EWOULDBLOCK': 35,\n 'EXDEV': 18,\n 'PRIORITY_LOW': 19,\n 'PRIORITY_BELOW_NORMAL': 10,\n 'PRIORITY_NORMAL': 0,\n 'PRIORITY_ABOVE_NORMAL': -7,\n 'PRIORITY_HIGH': -14,\n 'PRIORITY_HIGHEST': -20,\n 'SIGHUP': 1,\n 'SIGINT': 2,\n 'SIGQUIT': 3,\n 'SIGILL': 4,\n 'SIGTRAP': 5,\n 'SIGABRT': 6,\n 'SIGIOT': 6,\n 'SIGBUS': 10,\n 'SIGFPE': 8,\n 'SIGKILL': 9,\n 'SIGUSR1': 30,\n 'SIGSEGV': 11,\n 'SIGUSR2': 31,\n 'SIGPIPE': 13,\n 'SIGALRM': 14,\n 'SIGTERM': 15,\n 'SIGCHLD': 20,\n 'SIGCONT': 19,\n 'SIGSTOP': 17,\n 'SIGTSTP': 18,\n 'SIGTTIN': 21,\n 'SIGTTOU': 22,\n 'SIGURG': 16,\n 'SIGXCPU': 24,\n 'SIGXFSZ': 25,\n 'SIGVTALRM': 26,\n 'SIGPROF': 27,\n 'SIGWINCH': 28,\n 'SIGIO': 23,\n 'SIGINFO': 29,\n 'SIGSYS': 12,\n 'UV_FS_SYMLINK_DIR': 1,\n 'UV_FS_SYMLINK_JUNCTION': 2,\n 'O_RDONLY': 0,\n 'O_WRONLY': 1,\n 'O_RDWR': 2,\n 'UV_DIRENT_UNKNOWN': 0,\n 'UV_DIRENT_FILE': 1,\n 'UV_DIRENT_DIR': 2,\n 'UV_DIRENT_LINK': 3,\n 'UV_DIRENT_FIFO': 4,\n 'UV_DIRENT_SOCKET': 5,\n 'UV_DIRENT_CHAR': 6,\n 'UV_DIRENT_BLOCK': 7,\n 'S_IFMT': 61440,\n 'S_IFREG': 32768,\n 'S_IFDIR': 16384,\n 'S_IFCHR': 8192,\n 'S_IFBLK': 24576,\n 'S_IFIFO': 4096,\n 'S_IFLNK': 40960,\n 'S_IFSOCK': 49152,\n 'O_CREAT': 512,\n 'O_EXCL': 2048,\n 'UV_FS_O_FILEMAP': 0,\n 'O_NOCTTY': 131072,\n 'O_TRUNC': 1024,\n 'O_APPEND': 8,\n 'O_DIRECTORY': 1048576,\n 'O_NOFOLLOW': 256,\n 'O_SYNC': 128,\n 'O_DSYNC': 4194304,\n 'O_SYMLINK': 2097152,\n 'O_NONBLOCK': 4,\n 'S_IRWXU': 448,\n 'S_IRUSR': 256,\n 'S_IWUSR': 128,\n 'S_IXUSR': 64,\n 'S_IRWXG': 56,\n 'S_IRGRP': 32,\n 'S_IWGRP': 16,\n 'S_IXGRP': 8,\n 'S_IRWXO': 7,\n 'S_IROTH': 4,\n 'S_IWOTH': 2,\n 'S_IXOTH': 1,\n 'F_OK': 0,\n 'R_OK': 4,\n 'W_OK': 2,\n 'X_OK': 1,\n 'UV_FS_COPYFILE_EXCL': 1,\n 'COPYFILE_EXCL': 1,\n 'UV_FS_COPYFILE_FICLONE': 2,\n 'COPYFILE_FICLONE': 2,\n 'UV_FS_COPYFILE_FICLONE_FORCE': 4,\n 'COPYFILE_FICLONE_FORCE': 4,\n 'OPENSSL_VERSION_NUMBER': 805306480,\n 'SSL_OP_ALL': 2147485776,\n 'SSL_OP_ALLOW_NO_DHE_KEX': 1024,\n 'SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION': 262144,\n 'SSL_OP_CIPHER_SERVER_PREFERENCE': 4194304,\n 'SSL_OP_CISCO_ANYCONNECT': 32768,\n 'SSL_OP_COOKIE_EXCHANGE': 8192,\n 'SSL_OP_CRYPTOPRO_TLSEXT_BUG': 2147483648,\n 'SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS': 2048,\n 'SSL_OP_EPHEMERAL_RSA': 0,\n 'SSL_OP_LEGACY_SERVER_CONNECT': 4,\n 'SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER': 0,\n 'SSL_OP_MICROSOFT_SESS_ID_BUG': 0,\n 'SSL_OP_MSIE_SSLV2_RSA_PADDING': 0,\n 'SSL_OP_NETSCAPE_CA_DN_BUG': 0,\n 'SSL_OP_NETSCAPE_CHALLENGE_BUG': 0,\n 'SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG': 0,\n 'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG': 0,\n 'SSL_OP_NO_COMPRESSION': 131072,\n 'SSL_OP_NO_ENCRYPT_THEN_MAC': 524288,\n 'SSL_OP_NO_QUERY_MTU': 4096,\n 'SSL_OP_NO_RENEGOTIATION': 1073741824,\n 'SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION': 65536,\n 'SSL_OP_NO_SSLv2': 0,\n 'SSL_OP_NO_SSLv3': 33554432,\n 'SSL_OP_NO_TICKET': 16384,\n 'SSL_OP_NO_TLSv1': 67108864,\n 'SSL_OP_NO_TLSv1_1': 268435456,\n 'SSL_OP_NO_TLSv1_2': 134217728,\n 'SSL_OP_NO_TLSv1_3': 536870912,\n 'SSL_OP_PKCS1_CHECK_1': 0,\n 'SSL_OP_PKCS1_CHECK_2': 0,\n 'SSL_OP_PRIORITIZE_CHACHA': 2097152,\n 'SSL_OP_SINGLE_DH_USE': 0,\n 'SSL_OP_SINGLE_ECDH_USE': 0,\n 'SSL_OP_SSLEAY_080_CLIENT_DH_BUG': 0,\n 'SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG': 0,\n 'SSL_OP_TLS_BLOCK_PADDING_BUG': 0,\n 'SSL_OP_TLS_D5_BUG': 0,\n 'SSL_OP_TLS_ROLLBACK_BUG': 8388608,\n 'ENGINE_METHOD_RSA': 1,\n 'ENGINE_METHOD_DSA': 2,\n 'ENGINE_METHOD_DH': 4,\n 'ENGINE_METHOD_RAND': 8,\n 'ENGINE_METHOD_EC': 2048,\n 'ENGINE_METHOD_CIPHERS': 64,\n 'ENGINE_METHOD_DIGESTS': 128,\n 'ENGINE_METHOD_PKEY_METHS': 512,\n 'ENGINE_METHOD_PKEY_ASN1_METHS': 1024,\n 'ENGINE_METHOD_ALL': 65535,\n 'ENGINE_METHOD_NONE': 0,\n 'DH_CHECK_P_NOT_SAFE_PRIME': 2,\n 'DH_CHECK_P_NOT_PRIME': 1,\n 'DH_UNABLE_TO_CHECK_GENERATOR': 4,\n 'DH_NOT_SUITABLE_GENERATOR': 8,\n 'ALPN_ENABLED': 1,\n 'RSA_PKCS1_PADDING': 1,\n 'RSA_NO_PADDING': 3,\n 'RSA_PKCS1_OAEP_PADDING': 4,\n 'RSA_X931_PADDING': 5,\n 'RSA_PKCS1_PSS_PADDING': 6,\n 'RSA_PSS_SALTLEN_DIGEST': -1,\n 'RSA_PSS_SALTLEN_MAX_SIGN': -2,\n 'RSA_PSS_SALTLEN_AUTO': -2,\n 'defaultCoreCipherList': 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA',\n 'TLS1_VERSION': 769,\n 'TLS1_1_VERSION': 770,\n 'TLS1_2_VERSION': 771,\n 'TLS1_3_VERSION': 772,\n 'POINT_CONVERSION_COMPRESSED': 2,\n 'POINT_CONVERSION_UNCOMPRESSED': 4,\n 'POINT_CONVERSION_HYBRID': 6,\n 'defaultCipherList': 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA'\n};\n\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * FNV-1a hash generation init value.\n * It's exposed, because this allows user to override it.\n * More info: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV_hash_parameters\n *\n * @type {number}\n */\nhash.BASE = 0x811c9dc5;\n/**\n * Generates 32 bit FNV-1a hash from the given string.\n * As explained here: http://isthe.com/chongo/tech/comp/fnv/\n *\n * @param s {string} String to generate hash from.\n * @param [h] {number} FNV-1a hash generation init value.\n * @returns {number} The result integer hash.\n */\nfunction hash(s, h = hash.BASE) {\n const l = s.length;\n for (let i = 0; i < l; i++) {\n h ^= s.charCodeAt(i);\n h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);\n }\n return h >>> 0;\n}\nexports.default = hash;\nmodule.exports = hash;\n", "/*!\n * bytes\n * Copyright(c) 2012-2014 TJ Holowaychuk\n * Copyright(c) 2015 Jed Watson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = bytes;\nmodule.exports.format = format;\nmodule.exports.parse = parse;\n\n/**\n * Module variables.\n * @private\n */\n\nvar formatThousandsRegExp = /\\B(?=(\\d{3})+(?!\\d))/g;\n\nvar formatDecimalsRegExp = /(?:\\.0*|(\\.[^0]+)0+)$/;\n\nvar map = {\n b: 1,\n kb: 1 << 10,\n mb: 1 << 20,\n gb: 1 << 30,\n tb: Math.pow(1024, 4),\n pb: Math.pow(1024, 5),\n};\n\nvar parseRegExp = /^((-|\\+)?(\\d+(?:\\.\\d+)?)) *(kb|mb|gb|tb|pb)$/i;\n\n/**\n * Convert the given value in bytes into a string or parse to string to an integer in bytes.\n *\n * @param {string|number} value\n * @param {{\n * case: [string],\n * decimalPlaces: [number]\n * fixedDecimals: [boolean]\n * thousandsSeparator: [string]\n * unitSeparator: [string]\n * }} [options] bytes options.\n *\n * @returns {string|number|null}\n */\n\nfunction bytes(value, options) {\n if (typeof value === 'string') {\n return parse(value);\n }\n\n if (typeof value === 'number') {\n return format(value, options);\n }\n\n return null;\n}\n\n/**\n * Format the given value in bytes into a string.\n *\n * If the value is negative, it is kept as such. If it is a float,\n * it is rounded.\n *\n * @param {number} value\n * @param {object} [options]\n * @param {number} [options.decimalPlaces=2]\n * @param {number} [options.fixedDecimals=false]\n * @param {string} [options.thousandsSeparator=]\n * @param {string} [options.unit=]\n * @param {string} [options.unitSeparator=]\n *\n * @returns {string|null}\n * @public\n */\n\nfunction format(value, options) {\n if (!Number.isFinite(value)) {\n return null;\n }\n\n var mag = Math.abs(value);\n var thousandsSeparator = (options && options.thousandsSeparator) || '';\n var unitSeparator = (options && options.unitSeparator) || '';\n var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;\n var fixedDecimals = Boolean(options && options.fixedDecimals);\n var unit = (options && options.unit) || '';\n\n if (!unit || !map[unit.toLowerCase()]) {\n if (mag >= map.pb) {\n unit = 'PB';\n } else if (mag >= map.tb) {\n unit = 'TB';\n } else if (mag >= map.gb) {\n unit = 'GB';\n } else if (mag >= map.mb) {\n unit = 'MB';\n } else if (mag >= map.kb) {\n unit = 'KB';\n } else {\n unit = 'B';\n }\n }\n\n var val = value / map[unit.toLowerCase()];\n var str = val.toFixed(decimalPlaces);\n\n if (!fixedDecimals) {\n str = str.replace(formatDecimalsRegExp, '$1');\n }\n\n if (thousandsSeparator) {\n str = str.split('.').map(function (s, i) {\n return i === 0\n ? s.replace(formatThousandsRegExp, thousandsSeparator)\n : s\n }).join('.');\n }\n\n return str + unitSeparator + unit;\n}\n\n/**\n * Parse the string value into an integer in bytes.\n *\n * If no unit is given, it is assumed the value is in bytes.\n *\n * @param {number|string} val\n *\n * @returns {number|null}\n * @public\n */\n\nfunction parse(val) {\n if (typeof val === 'number' && !isNaN(val)) {\n return val;\n }\n\n if (typeof val !== 'string') {\n return null;\n }\n\n // Test if the string passed is valid\n var results = parseRegExp.exec(val);\n var floatValue;\n var unit = 'b';\n\n if (!results) {\n // Nothing could be extracted from the given string\n floatValue = parseInt(val, 10);\n unit = 'b'\n } else {\n // Retrieve the value and the unit\n floatValue = parseFloat(results[1]);\n unit = results[4].toLowerCase();\n }\n\n if (isNaN(floatValue)) {\n return null;\n }\n\n return Math.floor(map[unit] * floatValue);\n}\n", "'use strict'\n\nexports.supports = function supports (...manifests) {\n const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {})\n\n return Object.assign(manifest, {\n snapshots: manifest.snapshots || false,\n permanence: manifest.permanence || false,\n seek: manifest.seek || false,\n clear: manifest.clear || false,\n getMany: manifest.getMany || false,\n keyIterator: manifest.keyIterator || false,\n valueIterator: manifest.valueIterator || false,\n iteratorNextv: manifest.iteratorNextv || false,\n iteratorAll: manifest.iteratorAll || false,\n status: manifest.status || false,\n createIfMissing: manifest.createIfMissing || false,\n errorIfExists: manifest.errorIfExists || false,\n deferredOpen: manifest.deferredOpen || false,\n promises: manifest.promises || false,\n streams: manifest.streams || false,\n encodings: Object.assign({}, manifest.encodings),\n events: Object.assign({}, manifest.events),\n additionalMethods: Object.assign({}, manifest.additionalMethods)\n })\n}\n", "'use strict'\n\nmodule.exports = class ModuleError extends Error {\n /**\n * @param {string} message Error message\n * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]\n */\n constructor (message, options) {\n super(message || '')\n\n if (typeof options === 'object' && options !== null) {\n if (options.code) this.code = String(options.code)\n if (options.expected) this.expected = true\n if (options.transient) this.transient = true\n if (options.cause) this.cause = options.cause\n }\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n}\n", "'use strict'\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", "/*! 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 * 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'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\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", "'use strict'\n\n/** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */\nlet lazy = null\n\n/**\n * Get semi-global instances of TextEncoder and TextDecoder.\n * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}\n */\nmodule.exports = function () {\n if (lazy === null) {\n lazy = {\n textEncoder: new TextEncoder(),\n textDecoder: new TextDecoder()\n }\n }\n\n return lazy\n}\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst formats = new Set(['buffer', 'view', 'utf8'])\n\n/**\n * @template TIn, TFormat, TOut\n * @abstract\n */\nclass Encoding {\n /**\n * @param {IEncoding} options\n */\n constructor (options) {\n /** @type {(data: TIn) => TFormat} */\n this.encode = options.encode || this.encode\n\n /** @type {(data: TFormat) => TOut} */\n this.decode = options.decode || this.decode\n\n /** @type {string} */\n this.name = options.name || this.name\n\n /** @type {string} */\n this.format = options.format || this.format\n\n if (typeof this.encode !== 'function') {\n throw new TypeError(\"The 'encode' property must be a function\")\n }\n\n if (typeof this.decode !== 'function') {\n throw new TypeError(\"The 'decode' property must be a function\")\n }\n\n this.encode = this.encode.bind(this)\n this.decode = this.decode.bind(this)\n\n if (typeof this.name !== 'string' || this.name === '') {\n throw new TypeError(\"The 'name' property must be a string\")\n }\n\n if (typeof this.format !== 'string' || !formats.has(this.format)) {\n throw new TypeError(\"The 'format' property must be one of 'buffer', 'view', 'utf8'\")\n }\n\n if (options.createViewTranscoder) {\n this.createViewTranscoder = options.createViewTranscoder\n }\n\n if (options.createBufferTranscoder) {\n this.createBufferTranscoder = options.createBufferTranscoder\n }\n\n if (options.createUTF8Transcoder) {\n this.createUTF8Transcoder = options.createUTF8Transcoder\n }\n }\n\n get commonName () {\n return /** @type {string} */ (this.name.split('+')[0])\n }\n\n /** @return {BufferFormat} */\n createBufferTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {ViewFormat} */\n createViewTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'view'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {UTF8Format} */\n createUTF8Transcoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n}\n\nexports.Encoding = Encoding\n\n/**\n * @typedef {import('./encoding').IEncoding} IEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @typedef {import('./formats').BufferFormat} BufferFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').ViewFormat} ViewFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').UTF8Format} UTF8Format\n * @template TIn, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || {}\nconst { Encoding } = require('./encoding')\nconst textEndec = require('./text-endec')\n\n/**\n * @template TIn, TOut\n * @extends {Encoding}\n */\nclass BufferFormat extends Encoding {\n /**\n * @param {Omit, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'buffer' })\n }\n\n /** @override */\n createViewTranscoder () {\n return new ViewFormat({\n encode: this.encode, // Buffer is a view (UInt8Array)\n decode: (data) => this.decode(\n Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n ),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createBufferTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding}\n * @template TIn, TOut\n */\nclass ViewFormat extends Encoding {\n /**\n * @param {Omit, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'view' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => {\n const view = this.encode(data)\n return Buffer.from(view.buffer, view.byteOffset, view.byteLength)\n },\n decode: this.decode, // Buffer is a view (UInt8Array)\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding}\n * @template TIn, TOut\n */\nclass UTF8Format extends Encoding {\n /**\n * @param {Omit, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'utf8' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => Buffer.from(this.encode(data), 'utf8'),\n decode: (data) => this.decode(data.toString('utf8')),\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n const { textEncoder, textDecoder } = textEndec()\n\n return new ViewFormat({\n encode: (data) => textEncoder.encode(this.encode(data)),\n decode: (data) => this.decode(textDecoder.decode(data)),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createUTF8Transcoder () {\n return this\n }\n}\n\nexports.BufferFormat = BufferFormat\nexports.ViewFormat = ViewFormat\nexports.UTF8Format = UTF8Format\n\n/**\n * @typedef {import('./encoding').IEncoding} IEncoding\n * @template TIn, TFormat, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || { Buffer: { isBuffer: () => false } }\nconst { textEncoder, textDecoder } = require('./text-endec')()\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./formats')\n\n/** @type {(v: T) => v} */\nconst identity = (v) => v\n\n/**\n * @type {typeof import('./encodings').utf8}\n */\nexports.utf8 = new UTF8Format({\n encode: function (data) {\n // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder\n return Buffer.isBuffer(data)\n ? data.toString('utf8')\n : ArrayBuffer.isView(data)\n ? textDecoder.decode(data)\n : String(data)\n },\n decode: identity,\n name: 'utf8',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: function (data) {\n return textDecoder.decode(data)\n },\n name: `${this.name}+view`\n })\n },\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return data.toString('utf8')\n },\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').json}\n */\nexports.json = new UTF8Format({\n encode: JSON.stringify,\n decode: JSON.parse,\n name: 'json'\n})\n\n/**\n * @type {typeof import('./encodings').buffer}\n */\nexports.buffer = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: 'buffer',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n },\n name: `${this.name}+view`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').view}\n */\nexports.view = new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: identity,\n name: 'view',\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').hex}\n */\nexports.hex = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')\n },\n decode: function (buffer) {\n return buffer.toString('hex')\n },\n name: 'hex'\n})\n\n/**\n * @type {typeof import('./encodings').base64}\n */\nexports.base64 = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')\n },\n decode: function (buffer) {\n return buffer.toString('base64')\n },\n name: 'base64'\n})\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst encodings = require('./lib/encodings')\nconst { Encoding } = require('./lib/encoding')\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./lib/formats')\n\nconst kFormats = Symbol('formats')\nconst kEncodings = Symbol('encodings')\nconst validFormats = new Set(['buffer', 'view', 'utf8'])\n\n/** @template T */\nclass Transcoder {\n /**\n * @param {Array<'buffer'|'view'|'utf8'>} formats\n */\n constructor (formats) {\n if (!Array.isArray(formats)) {\n throw new TypeError(\"The first argument 'formats' must be an array\")\n } else if (!formats.every(f => validFormats.has(f))) {\n // Note: we only only support aliases in key- and valueEncoding options (where we already did)\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n\n /** @type {Map, Encoding>} */\n this[kEncodings] = new Map()\n this[kFormats] = new Set(formats)\n\n // Register encodings (done early in order to populate encodings())\n for (const k in encodings) {\n try {\n this.encoding(k)\n } catch (err) {\n /* istanbul ignore if: assertion */\n if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err\n }\n }\n }\n\n /**\n * @returns {Array>}\n */\n encodings () {\n return Array.from(new Set(this[kEncodings].values()))\n }\n\n /**\n * @param {string|MixedEncoding} encoding\n * @returns {Encoding}\n */\n encoding (encoding) {\n let resolved = this[kEncodings].get(encoding)\n\n if (resolved === undefined) {\n if (typeof encoding === 'string' && encoding !== '') {\n resolved = lookup[encoding]\n\n if (!resolved) {\n throw new ModuleError(`Encoding '${encoding}' is not found`, {\n code: 'LEVEL_ENCODING_NOT_FOUND'\n })\n }\n } else if (typeof encoding !== 'object' || encoding === null) {\n throw new TypeError(\"First argument 'encoding' must be a string or object\")\n } else {\n resolved = from(encoding)\n }\n\n const { name, format } = resolved\n\n if (!this[kFormats].has(format)) {\n if (this[kFormats].has('view')) {\n resolved = resolved.createViewTranscoder()\n } else if (this[kFormats].has('buffer')) {\n resolved = resolved.createBufferTranscoder()\n } else if (this[kFormats].has('utf8')) {\n resolved = resolved.createUTF8Transcoder()\n } else {\n throw new ModuleError(`Encoding '${name}' cannot be transcoded`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n }\n\n for (const k of [encoding, name, resolved.name, resolved.commonName]) {\n this[kEncodings].set(k, resolved)\n }\n }\n\n return resolved\n }\n}\n\nexports.Transcoder = Transcoder\n\n/**\n * @param {MixedEncoding} options\n * @returns {Encoding}\n */\nfunction from (options) {\n if (options instanceof Encoding) {\n return options\n }\n\n // Loosely typed for ecosystem compatibility\n const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined\n const name = options.name || maybeType || `anonymous-${anonymousCount++}`\n\n switch (detectFormat(options)) {\n case 'view': return new ViewFormat({ ...options, name })\n case 'utf8': return new UTF8Format({ ...options, name })\n case 'buffer': return new BufferFormat({ ...options, name })\n default: {\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n }\n}\n\n/**\n * If format is not provided, fallback to detecting `level-codec`\n * or `multiformats` encodings, else assume a format of buffer.\n * @param {MixedEncoding} options\n * @returns {string}\n */\nfunction detectFormat (options) {\n if ('format' in options && options.format !== undefined) {\n return options.format\n } else if ('buffer' in options && typeof options.buffer === 'boolean') {\n return options.buffer ? 'buffer' : 'utf8' // level-codec\n } else if ('code' in options && Number.isInteger(options.code)) {\n return 'view' // multiformats\n } else {\n return 'buffer'\n }\n}\n\n/**\n * @typedef {import('./lib/encoding').MixedEncoding} MixedEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @type {Object.>}\n */\nconst aliases = {\n binary: encodings.buffer,\n 'utf-8': encodings.utf8\n}\n\n/**\n * @type {Object.>}\n */\nconst lookup = {\n ...encodings,\n ...aliases\n}\n\nlet anonymousCount = 0\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'use strict';\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", "module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)\n", "'use strict'\n\nvar nextTick = require('./next-tick')\n\nexports.fromCallback = function (callback, symbol) {\n if (callback === undefined) {\n var promise = new Promise(function (resolve, reject) {\n callback = function (err, res) {\n if (err) reject(err)\n else resolve(res)\n }\n })\n\n callback[symbol !== undefined ? symbol : 'promise'] = promise\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n return callback\n}\n\nexports.fromPromise = function (promise, callback) {\n if (callback === undefined) return promise\n\n promise\n .then(function (res) { nextTick(() => callback(null, res)) })\n .catch(function (err) { nextTick(() => callback(err)) })\n}\n", "'use strict'\n\nexports.getCallback = function (options, callback) {\n return typeof options === 'function' ? options : callback\n}\n\nexports.getOptions = function (options, def) {\n if (typeof options === 'object' && options !== null) {\n return options\n }\n\n if (def !== undefined) {\n return def\n }\n\n return {}\n}\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getOptions, getCallback } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kCallback = Symbol('callback')\nconst kWorking = Symbol('working')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kAutoClose = Symbol('autoClose')\nconst kFinishWork = Symbol('finishWork')\nconst kReturnMany = Symbol('returnMany')\nconst kClosing = Symbol('closing')\nconst kHandleClose = Symbol('handleClose')\nconst kClosed = Symbol('closed')\nconst kCloseCallbacks = Symbol('closeCallbacks')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst kAbortOnClose = Symbol('abortOnClose')\nconst kLegacy = Symbol('legacy')\nconst kKeys = Symbol('keys')\nconst kValues = Symbol('values')\nconst kLimit = Symbol('limit')\nconst kCount = Symbol('count')\n\nconst emptyOptions = Object.freeze({})\nconst noop = () => {}\nlet warnedEnd = false\n\n// This class is an internal utility for common functionality between AbstractIterator,\n// AbstractKeyIterator and AbstractValueIterator. It's not exported.\nclass CommonIterator {\n constructor (db, options, legacy) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('The second argument must be an options object')\n }\n\n this[kClosed] = false\n this[kCloseCallbacks] = []\n this[kWorking] = false\n this[kClosing] = false\n this[kAutoClose] = false\n this[kCallback] = null\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kHandleClose] = this[kHandleClose].bind(this)\n this[kKeyEncoding] = options[kKeyEncoding]\n this[kValueEncoding] = options[kValueEncoding]\n this[kLegacy] = legacy\n this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity\n this[kCount] = 0\n\n // Undocumented option to abort pending work on close(). Used by the\n // many-level module as a temporary solution to a blocked close().\n // TODO (next major): consider making this the default behavior. Native\n // implementations should have their own logic to safely close iterators.\n this[kAbortOnClose] = !!options.abortOnClose\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get count () {\n return this[kCount]\n }\n\n get limit () {\n return this[kLimit]\n }\n\n next (callback) {\n let promise\n\n if (callback === undefined) {\n promise = new Promise((resolve, reject) => {\n callback = (err, key, value) => {\n if (err) reject(err)\n else if (!this[kLegacy]) resolve(key)\n else if (key === undefined && value === undefined) resolve()\n else resolve([key, value])\n }\n })\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call next() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne], null)\n else this._next(this[kHandleOne])\n }\n\n return promise\n }\n\n _next (callback) {\n this.nextTick(callback)\n }\n\n nextv (size, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (!Number.isInteger(size)) {\n this.nextTick(callback, new TypeError(\"The first argument 'size' must be an integer\"))\n return callback[kPromise]\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call nextv() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n if (size < 1) size = 1\n if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount])\n\n this[kWorking] = true\n this[kCallback] = callback\n\n if (size <= 0) this.nextTick(this[kHandleMany], null, [])\n else this._nextv(size, options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _nextv (size, options, callback) {\n const acc = []\n const onnext = (err, key, value) => {\n if (err) {\n return callback(err)\n } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {\n return callback(null, acc)\n }\n\n acc.push(this[kLegacy] ? [key, value] : key)\n\n if (acc.length === size) {\n callback(null, acc)\n } else {\n this._next(onnext)\n }\n }\n\n this._next(onnext)\n }\n\n all (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call all() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n this[kAutoClose] = true\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany], null, [])\n else this._all(options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _all (options, callback) {\n // Must count here because we're directly calling _nextv()\n let count = this[kCount]\n const acc = []\n\n const nextv = () => {\n // Not configurable, because implementations should optimize _all().\n const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3\n\n if (size <= 0) {\n this.nextTick(callback, null, acc)\n } else {\n this._nextv(size, emptyOptions, onnextv)\n }\n }\n\n const onnextv = (err, items) => {\n if (err) {\n callback(err)\n } else if (items.length === 0) {\n callback(null, acc)\n } else {\n acc.push.apply(acc, items)\n count += items.length\n nextv()\n }\n }\n\n nextv()\n }\n\n [kFinishWork] () {\n const cb = this[kCallback]\n\n // Callback will be null if work was aborted on close\n if (this[kAbortOnClose] && cb === null) return noop\n\n this[kWorking] = false\n this[kCallback] = null\n\n if (this[kClosing]) this._close(this[kHandleClose])\n\n return cb\n }\n\n [kReturnMany] (cb, err, items) {\n if (this[kAutoClose]) {\n this.close(cb.bind(null, err, items))\n } else {\n cb(err, items)\n }\n }\n\n seek (target, options) {\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n // Don't throw here, to be kind to implementations that wrap\n // another db and don't necessarily control when the db is closed\n } else if (this[kWorking]) {\n throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n })\n } else {\n const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding])\n const keyFormat = keyEncoding.format\n\n if (options.keyEncoding !== keyFormat) {\n options = { ...options, keyEncoding: keyFormat }\n }\n\n const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat)\n this._seek(mapped, options)\n }\n }\n\n _seek (target, options) {\n throw new ModuleError('Iterator does not support seek()', {\n code: 'LEVEL_NOT_SUPPORTED'\n })\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kClosed]) {\n this.nextTick(callback)\n } else if (this[kClosing]) {\n this[kCloseCallbacks].push(callback)\n } else {\n this[kClosing] = true\n this[kCloseCallbacks].push(callback)\n\n if (!this[kWorking]) {\n this._close(this[kHandleClose])\n } else if (this[kAbortOnClose]) {\n // Don't wait for work to finish. Subsequently ignore the result.\n const cb = this[kFinishWork]()\n\n cb(new ModuleError('Aborted on iterator close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kHandleClose] () {\n this[kClosed] = true\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n\n async * [Symbol.asyncIterator] () {\n try {\n let item\n\n while ((item = (await this.next())) !== undefined) {\n yield item\n }\n } finally {\n if (!this[kClosed]) await this.close()\n }\n }\n}\n\n// For backwards compatibility this class is not (yet) called AbstractEntryIterator.\nclass AbstractIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, true)\n this[kKeys] = options.keys !== false\n this[kValues] = options.values !== false\n }\n\n [kHandleOne] (err, key, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n value = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('entry', err))\n }\n\n if (!(key === undefined && value === undefined)) {\n this[kCount]++\n }\n\n cb(null, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (const entry of entries) {\n const key = entry[0]\n const value = entry[1]\n\n entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('entries', err))\n }\n\n this[kCount] += entries.length\n this[kReturnMany](cb, null, entries)\n }\n\n end (callback) {\n if (!warnedEnd && typeof console !== 'undefined') {\n warnedEnd = true\n console.warn(new ModuleError(\n 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',\n { code: 'LEVEL_LEGACY' }\n ))\n }\n\n return this.close(callback)\n }\n}\n\nclass AbstractKeyIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, key) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('key', err))\n }\n\n if (key !== undefined) this[kCount]++\n cb(null, key)\n }\n\n [kHandleMany] (err, keys) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n keys[i] = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('keys', err))\n }\n\n this[kCount] += keys.length\n this[kReturnMany](cb, null, keys)\n }\n}\n\nclass AbstractValueIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n value = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('value', err))\n }\n\n if (value !== undefined) this[kCount]++\n cb(null, value)\n }\n\n [kHandleMany] (err, values) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n values[i] = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('values', err))\n }\n\n this[kCount] += values.length\n this[kReturnMany](cb, null, values)\n }\n}\n\n// Internal utility, not typed or exported\nclass IteratorDecodeError extends ModuleError {\n constructor (subject, cause) {\n super(`Iterator could not decode ${subject}`, {\n code: 'LEVEL_DECODE_ERROR',\n cause\n })\n }\n}\n\n// To help migrating to abstract-level\nfor (const k of ['_ended property', '_nexting property', '_end method']) {\n Object.defineProperty(AbstractIterator.prototype, k.split(' ')[0], {\n get () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },\n set () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }\n })\n}\n\n// Exposed so that AbstractLevel can set these options\nAbstractIterator.keyEncoding = kKeyEncoding\nAbstractIterator.valueEncoding = kValueEncoding\n\nexports.AbstractIterator = AbstractIterator\nexports.AbstractKeyIterator = AbstractKeyIterator\nexports.AbstractValueIterator = AbstractValueIterator\n", "'use strict'\n\nconst { AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kIterator = Symbol('iterator')\nconst kCallback = Symbol('callback')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\n\nclass DefaultKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: true, values: false })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nclass DefaultValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: false, values: true })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nfor (const Iterator of [DefaultKeyIterator, DefaultValueIterator]) {\n const keys = Iterator === DefaultKeyIterator\n const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1]\n\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype[kHandleOne] = function (err, key, value) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, keys ? key : value)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n\n Iterator.prototype[kHandleMany] = function (err, entries) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, entries.map(mapEntry))\n }\n\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\n// Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator\nexports.DefaultKeyIterator = DefaultKeyIterator\nexports.DefaultValueIterator = DefaultValueIterator\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\nconst ModuleError = require('module-error')\n\nconst kNut = Symbol('nut')\nconst kUndefer = Symbol('undefer')\nconst kFactory = Symbol('factory')\n\nclass DeferredIterator extends AbstractIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.iterator(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.keys(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.values(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nfor (const Iterator of [DeferredIterator, DeferredKeyIterator, DeferredValueIterator]) {\n Iterator.prototype[kUndefer] = function () {\n if (this.db.status === 'open') {\n this[kNut] = this[kFactory]()\n }\n }\n\n Iterator.prototype._next = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].next(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._next(callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n if (this[kNut] !== null) {\n this[kNut].nextv(size, options, callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._nextv(size, options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._all = function (options, callback) {\n if (this[kNut] !== null) {\n this[kNut].all(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._all(options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._seek = function (target, options) {\n if (this[kNut] !== null) {\n // TODO: explain why we need _seek() rather than seek() here\n this[kNut]._seek(target, options)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._seek(target, options))\n }\n }\n\n Iterator.prototype._close = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].close(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._close(callback))\n } else {\n this.nextTick(callback)\n }\n }\n}\n\nexports.DeferredIterator = DeferredIterator\nexports.DeferredKeyIterator = DeferredKeyIterator\nexports.DeferredValueIterator = DeferredValueIterator\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getCallback, getOptions } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kStatus = Symbol('status')\nconst kOperations = Symbol('operations')\nconst kFinishClose = Symbol('finishClose')\nconst kCloseCallbacks = Symbol('closeCallbacks')\n\nclass AbstractChainedBatch {\n constructor (db) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n this[kOperations] = []\n this[kCloseCallbacks] = []\n this[kStatus] = 'open'\n this[kFinishClose] = this[kFinishClose].bind(this)\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get length () {\n return this[kOperations].length\n }\n\n put (key, value, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call put() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key) || this.db._checkValue(value)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const valueEncoding = db.valueEncoding(options && options.valueEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options)\n this[kOperations].push({ ...original, type: 'put', key, value })\n\n return this\n }\n\n _put (key, value, options) {}\n\n del (key, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call del() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options)\n this[kOperations].push({ ...original, type: 'del', key })\n\n return this\n }\n\n _del (key, options) {}\n\n clear () {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call clear() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n this._clear()\n this[kOperations] = []\n\n return this\n }\n\n _clear () {}\n\n write (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options)\n\n if (this[kStatus] !== 'open') {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n } else if (this.length === 0) {\n this.close(callback)\n } else {\n this[kStatus] = 'writing'\n this._write(options, (err) => {\n this[kStatus] = 'closing'\n this[kCloseCallbacks].push(() => callback(err))\n\n // Emit after setting 'closing' status, because event may trigger a\n // db close which in turn triggers (idempotently) closing this batch.\n if (!err) this.db.emit('batch', this[kOperations])\n\n this._close(this[kFinishClose])\n })\n }\n\n return callback[kPromise]\n }\n\n _write (options, callback) {}\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kStatus] === 'closing') {\n this[kCloseCallbacks].push(callback)\n } else if (this[kStatus] === 'closed') {\n this.nextTick(callback)\n } else {\n this[kCloseCallbacks].push(callback)\n\n if (this[kStatus] !== 'writing') {\n this[kStatus] = 'closing'\n this._close(this[kFinishClose])\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kFinishClose] () {\n this[kStatus] = 'closed'\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n}\n\nexports.AbstractChainedBatch = AbstractChainedBatch\n", "'use strict'\n\nconst { AbstractChainedBatch } = require('../abstract-chained-batch')\nconst ModuleError = require('module-error')\nconst kEncoded = Symbol('encoded')\n\n// Functional default for chained batch, with support of deferred open\nclass DefaultChainedBatch extends AbstractChainedBatch {\n constructor (db) {\n super(db)\n this[kEncoded] = []\n }\n\n _put (key, value, options) {\n this[kEncoded].push({ ...options, type: 'put', key, value })\n }\n\n _del (key, options) {\n this[kEncoded].push({ ...options, type: 'del', key })\n }\n\n _clear () {\n this[kEncoded] = []\n }\n\n // Assumes this[kEncoded] cannot change after write()\n _write (options, callback) {\n if (this.db.status === 'opening') {\n this.db.defer(() => this._write(options, callback))\n } else if (this.db.status === 'open') {\n if (this[kEncoded].length === 0) this.nextTick(callback)\n else this.db._batch(this[kEncoded], options, callback)\n } else {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n }\n }\n}\n\nexports.DefaultChainedBatch = DefaultChainedBatch\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst rangeOptions = new Set(['lt', 'lte', 'gt', 'gte'])\n\nmodule.exports = function (options, keyEncoding) {\n const result = {}\n\n for (const k in options) {\n if (!hasOwnProperty.call(options, k)) continue\n if (k === 'keyEncoding' || k === 'valueEncoding') continue\n\n if (k === 'start' || k === 'end') {\n throw new ModuleError(`The legacy range option '${k}' has been removed`, {\n code: 'LEVEL_LEGACY'\n })\n } else if (k === 'encoding') {\n // To help migrating to abstract-level\n throw new ModuleError(\"The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead\", {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (rangeOptions.has(k)) {\n // Note that we don't reject nullish and empty options here. While\n // those types are invalid as keys, they are valid as range options.\n result[k] = keyEncoding.encode(options[k])\n } else {\n result[k] = options[k]\n }\n }\n\n result.reverse = !!result.reverse\n result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1\n\n return result\n}\n", "/*! queue-microtask. MIT License. Feross Aboukhadijeh */\nlet promise\n\nmodule.exports = typeof queueMicrotask === 'function'\n ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)\n // reuse resolved promise, and allocate it lazily\n : cb => (promise || (promise = Promise.resolve()))\n .then(cb)\n .catch(err => setTimeout(() => { throw err }, 0))\n", "'use strict'\n\nconst queueMicrotask = require('queue-microtask')\n\nmodule.exports = function (fn, ...args) {\n if (args.length === 0) {\n queueMicrotask(fn)\n } else {\n queueMicrotask(() => fn(...args))\n }\n}\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kUnfix = Symbol('unfix')\nconst kIterator = Symbol('iterator')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kCallback = Symbol('callback')\n\n// TODO: unfix natively if db supports it\nclass AbstractSublevelIterator extends AbstractIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key, value) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (const entry of entries) {\n const key = entry[0]\n if (key !== undefined) entry[0] = this[kUnfix](key)\n }\n\n callback(err, entries)\n }\n}\n\nclass AbstractSublevelKeyIterator extends AbstractKeyIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key)\n }\n\n [kHandleMany] (err, keys) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n if (key !== undefined) keys[i] = this[kUnfix](key)\n }\n\n callback(err, keys)\n }\n}\n\nclass AbstractSublevelValueIterator extends AbstractValueIterator {\n constructor (db, options, iterator) {\n super(db, options)\n this[kIterator] = iterator\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n}\n\nfor (const Iterator of [AbstractSublevelValueIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kIterator].next(callback)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kIterator].nextv(size, options, callback)\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kIterator].all(options, callback)\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\nexports.AbstractSublevelIterator = AbstractSublevelIterator\nexports.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator\nexports.AbstractSublevelValueIterator = AbstractSublevelValueIterator\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst { Buffer } = require('buffer') || {}\nconst {\n AbstractSublevelIterator,\n AbstractSublevelKeyIterator,\n AbstractSublevelValueIterator\n} = require('./abstract-sublevel-iterator')\n\nconst kPrefix = Symbol('prefix')\nconst kUpperBound = Symbol('upperBound')\nconst kPrefixRange = Symbol('prefixRange')\nconst kParent = Symbol('parent')\nconst kUnfix = Symbol('unfix')\n\nconst textEncoder = new TextEncoder()\nconst defaults = { separator: '!' }\n\n// Wrapped to avoid circular dependency\nmodule.exports = function ({ AbstractLevel }) {\n class AbstractSublevel extends AbstractLevel {\n static defaults (options) {\n // To help migrating from subleveldown to abstract-level\n if (typeof options === 'string') {\n throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {\n code: 'LEVEL_LEGACY'\n })\n } else if (options && options.open) {\n throw new ModuleError('The subleveldown open option has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (options == null) {\n return defaults\n } else if (!options.separator) {\n return { ...options, separator: '!' }\n } else {\n return options\n }\n }\n\n // TODO: add autoClose option, which if true, does parent.attachResource(this)\n constructor (db, name, options) {\n // Don't forward AbstractSublevel options to AbstractLevel\n const { separator, manifest, ...forward } = AbstractSublevel.defaults(options)\n name = trim(name, separator)\n\n // Reserve one character between separator and name to give us an upper bound\n const reserved = separator.charCodeAt(0) + 1\n const parent = db[kParent] || db\n\n // Keys should sort like ['!a!', '!a!!a!', '!a\"', '!aa!', '!b!'].\n // Use ASCII for consistent length between string, Buffer and Uint8Array\n if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {\n throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {\n code: 'LEVEL_INVALID_PREFIX'\n })\n }\n\n super(mergeManifests(parent, manifest), forward)\n\n const prefix = (db.prefix || '') + separator + name + separator\n const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved)\n\n this[kParent] = parent\n this[kPrefix] = new MultiFormat(prefix)\n this[kUpperBound] = new MultiFormat(upperBound)\n this[kUnfix] = new Unfixer()\n\n this.nextTick = parent.nextTick\n }\n\n prefixKey (key, keyFormat) {\n if (keyFormat === 'utf8') {\n return this[kPrefix].utf8 + key\n } else if (key.byteLength === 0) {\n // Fast path for empty key (no copy)\n return this[kPrefix][keyFormat]\n } else if (keyFormat === 'view') {\n const view = this[kPrefix].view\n const result = new Uint8Array(view.byteLength + key.byteLength)\n\n result.set(view, 0)\n result.set(key, view.byteLength)\n\n return result\n } else {\n const buffer = this[kPrefix].buffer\n return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)\n }\n }\n\n // Not exposed for now.\n [kPrefixRange] (range, keyFormat) {\n if (range.gte !== undefined) {\n range.gte = this.prefixKey(range.gte, keyFormat)\n } else if (range.gt !== undefined) {\n range.gt = this.prefixKey(range.gt, keyFormat)\n } else {\n range.gte = this[kPrefix][keyFormat]\n }\n\n if (range.lte !== undefined) {\n range.lte = this.prefixKey(range.lte, keyFormat)\n } else if (range.lt !== undefined) {\n range.lt = this.prefixKey(range.lt, keyFormat)\n } else {\n range.lte = this[kUpperBound][keyFormat]\n }\n }\n\n get prefix () {\n return this[kPrefix].utf8\n }\n\n get db () {\n return this[kParent]\n }\n\n _open (options, callback) {\n // The parent db must open itself or be (re)opened by the user because\n // a sublevel should not initiate state changes on the rest of the db.\n this[kParent].open({ passive: true }, callback)\n }\n\n _put (key, value, options, callback) {\n this[kParent].put(key, value, options, callback)\n }\n\n _get (key, options, callback) {\n this[kParent].get(key, options, callback)\n }\n\n _getMany (keys, options, callback) {\n this[kParent].getMany(keys, options, callback)\n }\n\n _del (key, options, callback) {\n this[kParent].del(key, options, callback)\n }\n\n _batch (operations, options, callback) {\n this[kParent].batch(operations, options, callback)\n }\n\n _clear (options, callback) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n this[kParent].clear(options, callback)\n }\n\n _iterator (options) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].iterator(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelIterator(this, options, iterator, unfix)\n }\n\n _keys (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].keys(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelKeyIterator(this, options, iterator, unfix)\n }\n\n _values (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].values(options)\n return new AbstractSublevelValueIterator(this, options, iterator)\n }\n }\n\n return { AbstractSublevel }\n}\n\nconst mergeManifests = function (parent, manifest) {\n return {\n // Inherit manifest of parent db\n ...parent.supports,\n\n // Disable unsupported features\n createIfMissing: false,\n errorIfExists: false,\n\n // Unset additional events because we're not forwarding them\n events: {},\n\n // Unset additional methods (like approximateSize) which we can't support here unless\n // the AbstractSublevel class is overridden by an implementation of `abstract-level`.\n additionalMethods: {},\n\n // Inherit manifest of custom AbstractSublevel subclass. Such a class is not\n // allowed to override encodings.\n ...manifest,\n\n encodings: {\n utf8: supportsEncoding(parent, 'utf8'),\n buffer: supportsEncoding(parent, 'buffer'),\n view: supportsEncoding(parent, 'view')\n }\n }\n}\n\nconst supportsEncoding = function (parent, encoding) {\n // Prefer a non-transcoded encoding for optimal performance\n return parent.supports.encodings[encoding]\n ? parent.keyEncoding(encoding).name === encoding\n : false\n}\n\nclass MultiFormat {\n constructor (key) {\n this.utf8 = key\n this.view = textEncoder.encode(key)\n this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {}\n }\n}\n\nclass Unfixer {\n constructor () {\n this.cache = new Map()\n }\n\n get (prefixLength, keyFormat) {\n let unfix = this.cache.get(keyFormat)\n\n if (unfix === undefined) {\n if (keyFormat === 'view') {\n unfix = function (prefixLength, key) {\n // Avoid Uint8Array#slice() because it copies\n return key.subarray(prefixLength)\n }.bind(null, prefixLength)\n } else {\n unfix = function (prefixLength, key) {\n // Avoid Buffer#subarray() because it's slow\n return key.slice(prefixLength)\n }.bind(null, prefixLength)\n }\n\n this.cache.set(keyFormat, unfix)\n }\n\n return unfix\n }\n}\n\nconst trim = function (str, char) {\n let start = 0\n let end = str.length\n\n while (start < end && str[start] === char) start++\n while (end > start && str[end - 1] === char) end--\n\n return str.slice(start, end)\n}\n", "'use strict'\n\nconst { supports } = require('level-supports')\nconst { Transcoder } = require('level-transcoder')\nconst { EventEmitter } = require('events')\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { AbstractIterator } = require('./abstract-iterator')\nconst { DefaultKeyIterator, DefaultValueIterator } = require('./lib/default-kv-iterator')\nconst { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = require('./lib/deferred-iterator')\nconst { DefaultChainedBatch } = require('./lib/default-chained-batch')\nconst { getCallback, getOptions } = require('./lib/common')\nconst rangeOptions = require('./lib/range-options')\n\nconst kPromise = Symbol('promise')\nconst kLanded = Symbol('landed')\nconst kResources = Symbol('resources')\nconst kCloseResources = Symbol('closeResources')\nconst kOperations = Symbol('operations')\nconst kUndefer = Symbol('undefer')\nconst kDeferOpen = Symbol('deferOpen')\nconst kOptions = Symbol('options')\nconst kStatus = Symbol('status')\nconst kDefaultOptions = Symbol('defaultOptions')\nconst kTranscoder = Symbol('transcoder')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst noop = () => {}\n\nclass AbstractLevel extends EventEmitter {\n constructor (manifest, options) {\n super()\n\n if (typeof manifest !== 'object' || manifest === null) {\n throw new TypeError(\"The first argument 'manifest' must be an object\")\n }\n\n options = getOptions(options)\n const { keyEncoding, valueEncoding, passive, ...forward } = options\n\n this[kResources] = new Set()\n this[kOperations] = []\n this[kDeferOpen] = true\n this[kOptions] = forward\n this[kStatus] = 'opening'\n\n this.supports = supports(manifest, {\n status: true,\n promises: true,\n clear: true,\n getMany: true,\n deferredOpen: true,\n\n // TODO (next major): add seek\n snapshots: manifest.snapshots !== false,\n permanence: manifest.permanence !== false,\n\n // TODO: remove from level-supports because it's always supported\n keyIterator: true,\n valueIterator: true,\n iteratorNextv: true,\n iteratorAll: true,\n\n encodings: manifest.encodings || {},\n events: Object.assign({}, manifest.events, {\n opening: true,\n open: true,\n closing: true,\n closed: true,\n put: true,\n del: true,\n batch: true,\n clear: true\n })\n })\n\n this[kTranscoder] = new Transcoder(formats(this))\n this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8')\n this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8')\n\n // Add custom and transcoder encodings to manifest\n for (const encoding of this[kTranscoder].encodings()) {\n if (!this.supports.encodings[encoding.commonName]) {\n this.supports.encodings[encoding.commonName] = true\n }\n }\n\n this[kDefaultOptions] = {\n empty: Object.freeze({}),\n entry: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName,\n valueEncoding: this[kValueEncoding].commonName\n }),\n key: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName\n })\n }\n\n // Let subclass finish its constructor\n this.nextTick(() => {\n if (this[kDeferOpen]) {\n this.open({ passive: false }, noop)\n }\n })\n }\n\n get status () {\n return this[kStatus]\n }\n\n keyEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])\n }\n\n valueEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])\n }\n\n open (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n\n options = { ...this[kOptions], ...getOptions(options) }\n\n options.createIfMissing = options.createIfMissing !== false\n options.errorIfExists = !!options.errorIfExists\n\n const maybeOpened = (err) => {\n if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened)\n } else if (this[kStatus] !== 'open') {\n callback(new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (options.passive) {\n if (this[kStatus] === 'opening') {\n this.once(kLanded, maybeOpened)\n } else {\n this.nextTick(maybeOpened)\n }\n } else if (this[kStatus] === 'closed' || this[kDeferOpen]) {\n this[kDeferOpen] = false\n this[kStatus] = 'opening'\n this.emit('opening')\n\n this._open(options, (err) => {\n if (err) {\n this[kStatus] = 'closed'\n\n // Resources must be safe to close in any db state\n this[kCloseResources](() => {\n this.emit(kLanded)\n maybeOpened(err)\n })\n\n this[kUndefer]()\n return\n }\n\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'open') this.emit('open')\n\n // TODO (next major): remove this alias\n if (this[kStatus] === 'open') this.emit('ready')\n\n maybeOpened()\n })\n } else if (this[kStatus] === 'open') {\n this.nextTick(maybeOpened)\n } else {\n this.once(kLanded, () => this.open(options, callback))\n }\n\n return callback[kPromise]\n }\n\n _open (options, callback) {\n this.nextTick(callback)\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n const maybeClosed = (err) => {\n if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? maybeClosed(err) : maybeClosed)\n } else if (this[kStatus] !== 'closed') {\n callback(new ModuleError('Database is not closed', {\n code: 'LEVEL_DATABASE_NOT_CLOSED',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (this[kStatus] === 'open') {\n this[kStatus] = 'closing'\n this.emit('closing')\n\n const cancel = (err) => {\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n maybeClosed(err)\n }\n\n this[kCloseResources](() => {\n this._close((err) => {\n if (err) return cancel(err)\n\n this[kStatus] = 'closed'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'closed') this.emit('closed')\n\n maybeClosed()\n })\n })\n } else if (this[kStatus] === 'closed') {\n this.nextTick(maybeClosed)\n } else {\n this.once(kLanded, () => this.close(callback))\n }\n\n return callback[kPromise]\n }\n\n [kCloseResources] (callback) {\n if (this[kResources].size === 0) {\n return this.nextTick(callback)\n }\n\n let pending = this[kResources].size\n let sync = true\n\n const next = () => {\n if (--pending === 0) {\n // We don't have tests for generic resources, so dezalgo\n if (sync) this.nextTick(callback)\n else callback()\n }\n }\n\n // In parallel so that all resources know they are closed\n for (const resource of this[kResources]) {\n resource.close(next)\n }\n\n sync = false\n this[kResources].clear()\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n get (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.get(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options to the underlying store\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {\n if (err) {\n // Normalize not found error for backwards compatibility with abstract-leveldown and level(up)\n if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {\n if (!err.code) err.code = 'LEVEL_NOT_FOUND' // Preferred way going forward\n if (!err.notFound) err.notFound = true // Same as level-errors\n if (!err.status) err.status = 404 // Same as level-errors\n }\n\n return callback(err)\n }\n\n try {\n value = valueEncoding.decode(value)\n } catch (err) {\n return callback(new ModuleError('Could not decode value', {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, value)\n })\n\n return callback[kPromise]\n }\n\n _get (key, options, callback) {\n this.nextTick(callback, new Error('NotFound'))\n }\n\n getMany (keys, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.getMany(keys, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(keys)) {\n this.nextTick(callback, new TypeError(\"The first argument 'keys' must be an array\"))\n return callback[kPromise]\n }\n\n if (keys.length === 0) {\n this.nextTick(callback, null, [])\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKeys = new Array(keys.length)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat)\n }\n\n this._getMany(mappedKeys, options, (err, values) => {\n if (err) return callback(err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n if (values[i] !== undefined) {\n values[i] = valueEncoding.decode(values[i])\n }\n }\n } catch (err) {\n return callback(new ModuleError(`Could not decode one or more of ${values.length} value(s)`, {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, values)\n })\n\n return callback[kPromise]\n }\n\n _getMany (keys, options, callback) {\n this.nextTick(callback, null, new Array(keys.length).fill(undefined))\n }\n\n put (key, value, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.put(key, value, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key) || this._checkValue(value)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options, (err) => {\n if (err) return callback(err)\n this.emit('put', key, value)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _put (key, value, options, callback) {\n this.nextTick(callback)\n }\n\n del (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].key)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.del(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat })\n }\n\n this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {\n if (err) return callback(err)\n this.emit('del', key)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _del (key, options, callback) {\n this.nextTick(callback)\n }\n\n batch (operations, options, callback) {\n if (!arguments.length) {\n if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n return this._chainedBatch()\n }\n\n if (typeof operations === 'function') callback = operations\n else callback = getCallback(options, callback)\n\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.batch(operations, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(operations)) {\n this.nextTick(callback, new TypeError(\"The first argument 'operations' must be an array\"))\n return callback[kPromise]\n }\n\n if (operations.length === 0) {\n this.nextTick(callback)\n return callback[kPromise]\n }\n\n const mapped = new Array(operations.length)\n const { keyEncoding: ke, valueEncoding: ve, ...forward } = options\n\n for (let i = 0; i < operations.length; i++) {\n if (typeof operations[i] !== 'object' || operations[i] === null) {\n this.nextTick(callback, new TypeError('A batch operation must be an object'))\n return callback[kPromise]\n }\n\n const op = Object.assign({}, operations[i])\n\n if (op.type !== 'put' && op.type !== 'del') {\n this.nextTick(callback, new TypeError(\"A batch operation must have a type property that is 'put' or 'del'\"))\n return callback[kPromise]\n }\n\n const err = this._checkKey(op.key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const db = op.sublevel != null ? op.sublevel : this\n const keyEncoding = db.keyEncoding(op.keyEncoding || ke)\n const keyFormat = keyEncoding.format\n\n op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat)\n op.keyEncoding = keyFormat\n\n if (op.type === 'put') {\n const valueErr = this._checkValue(op.value)\n\n if (valueErr) {\n this.nextTick(callback, valueErr)\n return callback[kPromise]\n }\n\n const valueEncoding = db.valueEncoding(op.valueEncoding || ve)\n\n op.value = valueEncoding.encode(op.value)\n op.valueEncoding = valueEncoding.format\n }\n\n // Prevent double prefixing\n if (db !== this) {\n op.sublevel = null\n }\n\n mapped[i] = op\n }\n\n this._batch(mapped, forward, (err) => {\n if (err) return callback(err)\n this.emit('batch', operations)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _batch (operations, options, callback) {\n this.nextTick(callback)\n }\n\n sublevel (name, options) {\n return this._sublevel(name, AbstractSublevel.defaults(options))\n }\n\n _sublevel (name, options) {\n return new AbstractSublevel(this, name, options)\n }\n\n prefixKey (key, keyFormat) {\n return key\n }\n\n clear (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.clear(options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const original = options\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keyEncoding = keyEncoding.format\n\n if (options.limit === 0) {\n this.nextTick(callback)\n } else {\n this._clear(options, (err) => {\n if (err) return callback(err)\n this.emit('clear', original)\n callback()\n })\n }\n\n return callback[kPromise]\n }\n\n _clear (options, callback) {\n this.nextTick(callback)\n }\n\n iterator (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keys = options.keys !== false\n options.values = options.values !== false\n\n // We need the original encoding options in AbstractIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._iterator(options)\n }\n\n _iterator (options) {\n return new AbstractIterator(this, options)\n }\n\n keys (options) {\n // Also include valueEncoding (though unused) because we may fallback to _iterator()\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractKeyIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredKeyIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._keys(options)\n }\n\n _keys (options) {\n return new DefaultKeyIterator(this, options)\n }\n\n values (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractValueIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredValueIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._values(options)\n }\n\n _values (options) {\n return new DefaultValueIterator(this, options)\n }\n\n defer (fn) {\n if (typeof fn !== 'function') {\n throw new TypeError('The first argument must be a function')\n }\n\n this[kOperations].push(fn)\n }\n\n [kUndefer] () {\n if (this[kOperations].length === 0) {\n return\n }\n\n const operations = this[kOperations]\n this[kOperations] = []\n\n for (const op of operations) {\n op()\n }\n }\n\n // TODO: docs and types\n attachResource (resource) {\n if (typeof resource !== 'object' || resource === null ||\n typeof resource.close !== 'function') {\n throw new TypeError('The first argument must be a resource object')\n }\n\n this[kResources].add(resource)\n }\n\n // TODO: docs and types\n detachResource (resource) {\n this[kResources].delete(resource)\n }\n\n _chainedBatch () {\n return new DefaultChainedBatch(this)\n }\n\n _checkKey (key) {\n if (key === null || key === undefined) {\n return new ModuleError('Key cannot be null or undefined', {\n code: 'LEVEL_INVALID_KEY'\n })\n }\n }\n\n _checkValue (value) {\n if (value === null || value === undefined) {\n return new ModuleError('Value cannot be null or undefined', {\n code: 'LEVEL_INVALID_VALUE'\n })\n }\n }\n}\n\n// Expose browser-compatible nextTick for dependents\n// TODO: after we drop node 10, also use queueMicrotask in node\nAbstractLevel.prototype.nextTick = require('./lib/next-tick')\n\nconst { AbstractSublevel } = require('./lib/abstract-sublevel')({ AbstractLevel })\n\nexports.AbstractLevel = AbstractLevel\nexports.AbstractSublevel = AbstractSublevel\n\nconst maybeError = function (db, callback) {\n if (db[kStatus] !== 'open') {\n db.nextTick(callback, new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n }))\n return true\n }\n\n return false\n}\n\nconst formats = function (db) {\n return Object.keys(db.supports.encodings)\n .filter(k => !!db.supports.encodings[k])\n}\n", "'use strict'\n\nexports.AbstractLevel = require('./abstract-level').AbstractLevel\nexports.AbstractSublevel = require('./abstract-level').AbstractSublevel\nexports.AbstractIterator = require('./abstract-iterator').AbstractIterator\nexports.AbstractKeyIterator = require('./abstract-iterator').AbstractKeyIterator\nexports.AbstractValueIterator = require('./abstract-iterator').AbstractValueIterator\nexports.AbstractChainedBatch = require('./abstract-chained-batch').AbstractChainedBatch\n", "/*! run-parallel-limit. MIT License. Feross Aboukhadijeh */\nmodule.exports = runParallelLimit\n\nconst queueMicrotask = require('queue-microtask')\n\nfunction runParallelLimit (tasks, limit, cb) {\n if (typeof limit !== 'number') throw new Error('second argument must be a Number')\n let results, len, pending, keys, isErrored\n let isSync = true\n let next\n\n if (Array.isArray(tasks)) {\n results = []\n pending = len = tasks.length\n } else {\n keys = Object.keys(tasks)\n results = {}\n pending = len = keys.length\n }\n\n function done (err) {\n function end () {\n if (cb) cb(err, results)\n cb = null\n }\n if (isSync) queueMicrotask(end)\n else end()\n }\n\n function each (i, err, result) {\n results[i] = result\n if (err) isErrored = true\n if (--pending === 0 || err) {\n done(err)\n } else if (!isErrored && next < len) {\n let key\n if (keys) {\n key = keys[next]\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n } else {\n key = next\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n }\n }\n }\n\n next = limit\n if (!pending) {\n // empty\n done(null)\n } else if (keys) {\n // object\n keys.some(function (key, i) {\n tasks[key](function (err, result) { each(key, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n } else {\n // array\n tasks.some(function (task, i) {\n task(function (err, result) { each(i, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n }\n\n isSync = false\n}\n", "/* global IDBKeyRange */\n\n'use strict'\n\nmodule.exports = function createKeyRange (options) {\n const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined\n const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined\n const lowerExclusive = options.gte === undefined\n const upperExclusive = options.lte === undefined\n\n if (lower !== undefined && upper !== undefined) {\n return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)\n } else if (lower !== undefined) {\n return IDBKeyRange.lowerBound(lower, lowerExclusive)\n } else if (upper !== undefined) {\n return IDBKeyRange.upperBound(upper, upperExclusive)\n } else {\n return null\n }\n}\n", "'use strict'\n\nconst textEncoder = new TextEncoder()\n\nmodule.exports = function (data) {\n if (data instanceof Uint8Array) {\n return data\n } else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data)\n } else {\n // Non-binary data stored with an old version (level-js < 5.0.0)\n return textEncoder.encode(data)\n }\n}\n", "'use strict'\n\nconst { AbstractIterator } = require('abstract-level')\nconst createKeyRange = require('./util/key-range')\nconst deserialize = require('./util/deserialize')\n\nconst kCache = Symbol('cache')\nconst kFinished = Symbol('finished')\nconst kOptions = Symbol('options')\nconst kCurrentOptions = Symbol('currentOptions')\nconst kPosition = Symbol('position')\nconst kLocation = Symbol('location')\nconst kFirst = Symbol('first')\nconst emptyOptions = {}\n\nclass Iterator extends AbstractIterator {\n constructor (db, location, options) {\n super(db, options)\n\n this[kCache] = []\n this[kFinished] = this.limit === 0\n this[kOptions] = options\n this[kCurrentOptions] = { ...options }\n this[kPosition] = undefined\n this[kLocation] = location\n this[kFirst] = true\n }\n\n // Note: if called by _all() then size can be Infinity. This is an internal\n // detail; by design AbstractIterator.nextv() does not support Infinity.\n _nextv (size, options, callback) {\n this[kFirst] = false\n\n if (this[kFinished]) {\n return this.nextTick(callback, null, [])\n } else if (this[kCache].length > 0) {\n // TODO: mixing next and nextv is not covered by test suite\n size = Math.min(size, this[kCache].length)\n return this.nextTick(callback, null, this[kCache].splice(0, size))\n }\n\n // Adjust range by what we already visited\n if (this[kPosition] !== undefined) {\n if (this[kOptions].reverse) {\n this[kCurrentOptions].lt = this[kPosition]\n this[kCurrentOptions].lte = undefined\n } else {\n this[kCurrentOptions].gt = this[kPosition]\n this[kCurrentOptions].gte = undefined\n }\n }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kCurrentOptions])\n } catch (_) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just return 0 results.\n this[kFinished] = true\n return this.nextTick(callback, null, [])\n }\n\n const transaction = this.db.db.transaction([this[kLocation]], 'readonly')\n const store = transaction.objectStore(this[kLocation])\n const entries = []\n\n if (!this[kOptions].reverse) {\n let keys\n let values\n\n const complete = () => {\n // Wait for both requests to complete\n if (keys === undefined || values === undefined) return\n\n const length = Math.max(keys.length, values.length)\n\n if (length === 0 || size === Infinity) {\n this[kFinished] = true\n } else {\n this[kPosition] = keys[length - 1]\n }\n\n // Resize\n entries.length = length\n\n // Merge keys and values\n for (let i = 0; i < length; i++) {\n const key = keys[i]\n const value = values[i]\n\n entries[i] = [\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ]\n }\n\n maybeCommit(transaction)\n }\n\n // If keys were not requested and size is Infinity, we don't have to keep\n // track of position and can thus skip getting keys.\n if (this[kOptions].keys || size < Infinity) {\n store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n keys = ev.target.result\n complete()\n }\n } else {\n keys = []\n this.nextTick(complete)\n }\n\n if (this[kOptions].values) {\n store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n values = ev.target.result\n complete()\n }\n } else {\n values = []\n this.nextTick(complete)\n }\n } else {\n // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time\n // TODO: test if all target browsers support openKeyCursor\n const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n\n store[method](keyRange, 'prev').onsuccess = (ev) => {\n const cursor = ev.target.result\n\n if (cursor) {\n const { key, value } = cursor\n this[kPosition] = key\n\n entries.push([\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ])\n\n if (entries.length < size) {\n cursor.continue()\n } else {\n maybeCommit(transaction)\n }\n } else {\n this[kFinished] = true\n }\n }\n }\n\n // If an error occurs (on the request), the transaction will abort.\n transaction.onabort = () => {\n callback(transaction.error || new Error('aborted by user'))\n callback = null\n }\n\n transaction.oncomplete = () => {\n callback(null, entries)\n callback = null\n }\n }\n\n _next (callback) {\n if (this[kCache].length > 0) {\n const [key, value] = this[kCache].shift()\n this.nextTick(callback, null, key, value)\n } else if (this[kFinished]) {\n this.nextTick(callback)\n } else {\n let size = Math.min(100, this.limit - this.count)\n\n if (this[kFirst]) {\n // It's common to only want one entry initially or after a seek()\n this[kFirst] = false\n size = 1\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n this[kCache] = entries\n this._next(callback)\n })\n }\n }\n\n _all (options, callback) {\n this[kFirst] = false\n\n // TODO: mixing next and all is not covered by test suite\n const cache = this[kCache].splice(0, this[kCache].length)\n const size = this.limit - this.count - cache.length\n\n if (size <= 0) {\n return this.nextTick(callback, null, cache)\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n if (cache.length > 0) entries = cache.concat(entries)\n callback(null, entries)\n })\n }\n\n _seek (target, options) {\n this[kFirst] = true\n this[kCache] = []\n this[kFinished] = false\n this[kPosition] = undefined\n\n // TODO: not covered by test suite\n this[kCurrentOptions] = { ...this[kOptions] }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kOptions])\n } catch (_) {\n this[kFinished] = true\n return\n }\n\n if (keyRange !== null && !keyRange.includes(target)) {\n this[kFinished] = true\n } else if (this[kOptions].reverse) {\n this[kCurrentOptions].lte = target\n } else {\n this[kCurrentOptions].gte = target\n }\n }\n}\n\nexports.Iterator = Iterator\n\nfunction maybeCommit (transaction) {\n // Commit (meaning close) now instead of waiting for auto-commit\n if (typeof transaction.commit === 'function') {\n transaction.commit()\n }\n}\n", "'use strict'\n\nmodule.exports = function clear (db, location, keyRange, options, callback) {\n if (options.limit === 0) return db.nextTick(callback)\n\n const transaction = db.db.transaction([location], 'readwrite')\n const store = transaction.objectStore(location)\n let count = 0\n\n transaction.oncomplete = function () {\n callback()\n }\n\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n // A key cursor is faster (skips reading values) but not supported by IE\n // TODO: we no longer support IE. Test others\n const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n const direction = options.reverse ? 'prev' : 'next'\n\n store[method](keyRange, direction).onsuccess = function (ev) {\n const cursor = ev.target.result\n\n if (cursor) {\n // Wait for a request to complete before continuing, saving CPU.\n store.delete(cursor.key).onsuccess = function () {\n if (options.limit <= 0 || ++count < options.limit) {\n cursor.continue()\n }\n }\n }\n }\n}\n", "/* global indexedDB */\n\n'use strict'\n\nconst { AbstractLevel } = require('abstract-level')\nconst ModuleError = require('module-error')\nconst parallel = require('run-parallel-limit')\nconst { fromCallback } = require('catering')\nconst { Iterator } = require('./iterator')\nconst deserialize = require('./util/deserialize')\nconst clear = require('./util/clear')\nconst createKeyRange = require('./util/key-range')\n\n// Keep as-is for compatibility with existing level-js databases\nconst DEFAULT_PREFIX = 'level-js-'\n\nconst kIDB = Symbol('idb')\nconst kNamePrefix = Symbol('namePrefix')\nconst kLocation = Symbol('location')\nconst kVersion = Symbol('version')\nconst kStore = Symbol('store')\nconst kOnComplete = Symbol('onComplete')\nconst kPromise = Symbol('promise')\n\nclass BrowserLevel extends AbstractLevel {\n constructor (location, options, _) {\n // To help migrating to abstract-level\n if (typeof options === 'function' || typeof _ === 'function') {\n throw new ModuleError('The levelup-style callback argument has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n const { prefix, version, ...forward } = options || {}\n\n super({\n encodings: { view: true },\n snapshots: false,\n createIfMissing: false,\n errorIfExists: false,\n seek: true\n }, forward)\n\n if (typeof location !== 'string') {\n throw new Error('constructor requires a location string argument')\n }\n\n // TODO (next major): remove default prefix\n this[kLocation] = location\n this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix\n this[kVersion] = parseInt(version || 1, 10)\n this[kIDB] = null\n }\n\n get location () {\n return this[kLocation]\n }\n\n get namePrefix () {\n return this[kNamePrefix]\n }\n\n get version () {\n return this[kVersion]\n }\n\n // Exposed for backwards compat and unit tests\n get db () {\n return this[kIDB]\n }\n\n get type () {\n return 'browser-level'\n }\n\n _open (options, callback) {\n const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion])\n\n req.onerror = function () {\n callback(req.error || new Error('unknown error'))\n }\n\n req.onsuccess = () => {\n this[kIDB] = req.result\n callback()\n }\n\n req.onupgradeneeded = (ev) => {\n const db = ev.target.result\n\n if (!db.objectStoreNames.contains(this[kLocation])) {\n db.createObjectStore(this[kLocation])\n }\n }\n }\n\n [kStore] (mode) {\n const transaction = this[kIDB].transaction([this[kLocation]], mode)\n return transaction.objectStore(this[kLocation])\n }\n\n [kOnComplete] (request, callback) {\n const transaction = request.transaction\n\n // Take advantage of the fact that a non-canceled request error aborts\n // the transaction. I.e. no need to listen for \"request.onerror\".\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback(null, request.result)\n }\n }\n\n _get (key, options, callback) {\n const store = this[kStore]('readonly')\n let req\n\n try {\n req = store.get(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, function (err, value) {\n if (err) return callback(err)\n\n if (value === undefined) {\n return callback(new ModuleError('Entry not found', {\n code: 'LEVEL_NOT_FOUND'\n }))\n }\n\n callback(null, deserialize(value))\n })\n }\n\n _getMany (keys, options, callback) {\n const store = this[kStore]('readonly')\n const tasks = keys.map((key) => (next) => {\n let request\n\n try {\n request = store.get(key)\n } catch (err) {\n return next(err)\n }\n\n request.onsuccess = () => {\n const value = request.result\n next(null, value === undefined ? value : deserialize(value))\n }\n\n request.onerror = (ev) => {\n ev.stopPropagation()\n next(request.error)\n }\n })\n\n parallel(tasks, 16, callback)\n }\n\n _del (key, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n req = store.delete(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _put (key, value, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n // Will throw a DataError or DataCloneError if the environment\n // does not support serializing the key or value respectively.\n req = store.put(value, key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n // TODO: implement key and value iterators\n _iterator (options) {\n return new Iterator(this, this[kLocation], options)\n }\n\n _batch (operations, options, callback) {\n const store = this[kStore]('readwrite')\n const transaction = store.transaction\n let index = 0\n let error\n\n transaction.onabort = function () {\n callback(error || transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback()\n }\n\n // Wait for a request to complete before making the next, saving CPU.\n function loop () {\n const op = operations[index++]\n const key = op.key\n\n let req\n\n try {\n req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)\n } catch (err) {\n error = err\n transaction.abort()\n return\n }\n\n if (index < operations.length) {\n req.onsuccess = loop\n } else if (typeof transaction.commit === 'function') {\n // Commit now instead of waiting for auto-commit\n transaction.commit()\n }\n }\n\n loop()\n }\n\n _clear (options, callback) {\n let keyRange\n let req\n\n try {\n keyRange = createKeyRange(options)\n } catch (e) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just do nothing.\n return this.nextTick(callback)\n }\n\n if (options.limit >= 0) {\n // IDBObjectStore#delete(range) doesn't have such an option.\n // Fall back to cursor-based implementation.\n return clear(this, this[kLocation], keyRange, options, callback)\n }\n\n try {\n const store = this[kStore]('readwrite')\n req = keyRange ? store.delete(keyRange) : store.clear()\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _close (callback) {\n this[kIDB].close()\n this.nextTick(callback)\n }\n}\n\nBrowserLevel.destroy = function (location, prefix, callback) {\n if (typeof prefix === 'function') {\n callback = prefix\n prefix = DEFAULT_PREFIX\n }\n\n callback = fromCallback(callback, kPromise)\n const request = indexedDB.deleteDatabase(prefix + location)\n\n request.onsuccess = function () {\n callback()\n }\n\n request.onerror = function (err) {\n callback(err)\n }\n\n return callback[kPromise]\n}\n\nexports.BrowserLevel = BrowserLevel\n", "exports.Level = require('browser-level').BrowserLevel\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)).constructor = CustomError;\n\n Object.defineProperty(CustomError.prototype, \"name\", { get: function() { return name; } });\n\n CustomError.prototype.toString = function toString() {\n return this.name + \": \" + this.message;\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 = 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", "\"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 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new this.buf.constructor(0)\n : 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 = 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\";\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 = {};\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 accross 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\";\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", "// minimal library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index-minimal\");\n", "// @ts-nocheck\n/*eslint-disable*/\n(function(global, factory) { /* global define, require, module */\n\n /* AMD */ if (typeof define === 'function' && define.amd)\n define([\"protobufjs/minimal\"], factory);\n\n /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports)\n module.exports = factory(require(\"protobufjs/minimal\"));\n\n})(this, function($protobuf) {\n \"use strict\";\n\n // Common aliases\n var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n // Exported root namespace\n var $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\n $root.RPC = (function() {\n\n /**\n * Properties of a RPC.\n * @exports IRPC\n * @interface IRPC\n * @property {Array.|null} [subscriptions] RPC subscriptions\n * @property {Array.|null} [messages] RPC messages\n * @property {RPC.IControlMessage|null} [control] RPC control\n */\n\n /**\n * Constructs a new RPC.\n * @exports RPC\n * @classdesc Represents a RPC.\n * @implements IRPC\n * @constructor\n * @param {IRPC=} [p] Properties to set\n */\n function RPC(p) {\n this.subscriptions = [];\n this.messages = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * RPC subscriptions.\n * @member {Array.} subscriptions\n * @memberof RPC\n * @instance\n */\n RPC.prototype.subscriptions = $util.emptyArray;\n\n /**\n * RPC messages.\n * @member {Array.} messages\n * @memberof RPC\n * @instance\n */\n RPC.prototype.messages = $util.emptyArray;\n\n /**\n * RPC control.\n * @member {RPC.IControlMessage|null|undefined} control\n * @memberof RPC\n * @instance\n */\n RPC.prototype.control = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * RPC _control.\n * @member {\"control\"|undefined} _control\n * @memberof RPC\n * @instance\n */\n Object.defineProperty(RPC.prototype, \"_control\", {\n get: $util.oneOfGetter($oneOfFields = [\"control\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified RPC message. Does not implicitly {@link RPC.verify|verify} messages.\n * @function encode\n * @memberof RPC\n * @static\n * @param {IRPC} m RPC message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n RPC.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.subscriptions != null && m.subscriptions.length) {\n for (var i = 0; i < m.subscriptions.length; ++i)\n $root.RPC.SubOpts.encode(m.subscriptions[i], w.uint32(10).fork()).ldelim();\n }\n if (m.messages != null && m.messages.length) {\n for (var i = 0; i < m.messages.length; ++i)\n $root.RPC.Message.encode(m.messages[i], w.uint32(18).fork()).ldelim();\n }\n if (m.control != null && Object.hasOwnProperty.call(m, \"control\"))\n $root.RPC.ControlMessage.encode(m.control, w.uint32(26).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes a RPC message from the specified reader or buffer.\n * @function decode\n * @memberof RPC\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC} RPC\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n RPC.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.subscriptions && m.subscriptions.length))\n m.subscriptions = [];\n m.subscriptions.push($root.RPC.SubOpts.decode(r, r.uint32()));\n break;\n case 2:\n if (!(m.messages && m.messages.length))\n m.messages = [];\n m.messages.push($root.RPC.Message.decode(r, r.uint32()));\n break;\n case 3:\n m.control = $root.RPC.ControlMessage.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a RPC message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC} RPC\n */\n RPC.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC)\n return d;\n var m = new $root.RPC();\n if (d.subscriptions) {\n if (!Array.isArray(d.subscriptions))\n throw TypeError(\".RPC.subscriptions: array expected\");\n m.subscriptions = [];\n for (var i = 0; i < d.subscriptions.length; ++i) {\n if (typeof d.subscriptions[i] !== \"object\")\n throw TypeError(\".RPC.subscriptions: object expected\");\n m.subscriptions[i] = $root.RPC.SubOpts.fromObject(d.subscriptions[i]);\n }\n }\n if (d.messages) {\n if (!Array.isArray(d.messages))\n throw TypeError(\".RPC.messages: array expected\");\n m.messages = [];\n for (var i = 0; i < d.messages.length; ++i) {\n if (typeof d.messages[i] !== \"object\")\n throw TypeError(\".RPC.messages: object expected\");\n m.messages[i] = $root.RPC.Message.fromObject(d.messages[i]);\n }\n }\n if (d.control != null) {\n if (typeof d.control !== \"object\")\n throw TypeError(\".RPC.control: object expected\");\n m.control = $root.RPC.ControlMessage.fromObject(d.control);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a RPC message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC\n * @static\n * @param {RPC} m RPC\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n RPC.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.subscriptions = [];\n d.messages = [];\n }\n if (m.subscriptions && m.subscriptions.length) {\n d.subscriptions = [];\n for (var j = 0; j < m.subscriptions.length; ++j) {\n d.subscriptions[j] = $root.RPC.SubOpts.toObject(m.subscriptions[j], o);\n }\n }\n if (m.messages && m.messages.length) {\n d.messages = [];\n for (var j = 0; j < m.messages.length; ++j) {\n d.messages[j] = $root.RPC.Message.toObject(m.messages[j], o);\n }\n }\n if (m.control != null && m.hasOwnProperty(\"control\")) {\n d.control = $root.RPC.ControlMessage.toObject(m.control, o);\n if (o.oneofs)\n d._control = \"control\";\n }\n return d;\n };\n\n /**\n * Converts this RPC to JSON.\n * @function toJSON\n * @memberof RPC\n * @instance\n * @returns {Object.} JSON object\n */\n RPC.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n RPC.SubOpts = (function() {\n\n /**\n * Properties of a SubOpts.\n * @memberof RPC\n * @interface ISubOpts\n * @property {boolean|null} [subscribe] SubOpts subscribe\n * @property {string|null} [topic] SubOpts topic\n */\n\n /**\n * Constructs a new SubOpts.\n * @memberof RPC\n * @classdesc Represents a SubOpts.\n * @implements ISubOpts\n * @constructor\n * @param {RPC.ISubOpts=} [p] Properties to set\n */\n function SubOpts(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * SubOpts subscribe.\n * @member {boolean|null|undefined} subscribe\n * @memberof RPC.SubOpts\n * @instance\n */\n SubOpts.prototype.subscribe = null;\n\n /**\n * SubOpts topic.\n * @member {string|null|undefined} topic\n * @memberof RPC.SubOpts\n * @instance\n */\n SubOpts.prototype.topic = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * SubOpts _subscribe.\n * @member {\"subscribe\"|undefined} _subscribe\n * @memberof RPC.SubOpts\n * @instance\n */\n Object.defineProperty(SubOpts.prototype, \"_subscribe\", {\n get: $util.oneOfGetter($oneOfFields = [\"subscribe\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * SubOpts _topic.\n * @member {\"topic\"|undefined} _topic\n * @memberof RPC.SubOpts\n * @instance\n */\n Object.defineProperty(SubOpts.prototype, \"_topic\", {\n get: $util.oneOfGetter($oneOfFields = [\"topic\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified SubOpts message. Does not implicitly {@link RPC.SubOpts.verify|verify} messages.\n * @function encode\n * @memberof RPC.SubOpts\n * @static\n * @param {RPC.ISubOpts} m SubOpts message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n SubOpts.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.subscribe != null && Object.hasOwnProperty.call(m, \"subscribe\"))\n w.uint32(8).bool(m.subscribe);\n if (m.topic != null && Object.hasOwnProperty.call(m, \"topic\"))\n w.uint32(18).string(m.topic);\n return w;\n };\n\n /**\n * Decodes a SubOpts message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.SubOpts\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.SubOpts} SubOpts\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n SubOpts.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.SubOpts();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.subscribe = r.bool();\n break;\n case 2:\n m.topic = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a SubOpts message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.SubOpts\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.SubOpts} SubOpts\n */\n SubOpts.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.SubOpts)\n return d;\n var m = new $root.RPC.SubOpts();\n if (d.subscribe != null) {\n m.subscribe = Boolean(d.subscribe);\n }\n if (d.topic != null) {\n m.topic = String(d.topic);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a SubOpts message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.SubOpts\n * @static\n * @param {RPC.SubOpts} m SubOpts\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n SubOpts.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (m.subscribe != null && m.hasOwnProperty(\"subscribe\")) {\n d.subscribe = m.subscribe;\n if (o.oneofs)\n d._subscribe = \"subscribe\";\n }\n if (m.topic != null && m.hasOwnProperty(\"topic\")) {\n d.topic = m.topic;\n if (o.oneofs)\n d._topic = \"topic\";\n }\n return d;\n };\n\n /**\n * Converts this SubOpts to JSON.\n * @function toJSON\n * @memberof RPC.SubOpts\n * @instance\n * @returns {Object.} JSON object\n */\n SubOpts.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return SubOpts;\n })();\n\n RPC.Message = (function() {\n\n /**\n * Properties of a Message.\n * @memberof RPC\n * @interface IMessage\n * @property {Uint8Array|null} [from] Message from\n * @property {Uint8Array|null} [data] Message data\n * @property {Uint8Array|null} [seqno] Message seqno\n * @property {string} topic Message topic\n * @property {Uint8Array|null} [signature] Message signature\n * @property {Uint8Array|null} [key] Message key\n */\n\n /**\n * Constructs a new Message.\n * @memberof RPC\n * @classdesc Represents a Message.\n * @implements IMessage\n * @constructor\n * @param {RPC.IMessage=} [p] Properties to set\n */\n function Message(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Message from.\n * @member {Uint8Array|null|undefined} from\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.from = null;\n\n /**\n * Message data.\n * @member {Uint8Array|null|undefined} data\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.data = null;\n\n /**\n * Message seqno.\n * @member {Uint8Array|null|undefined} seqno\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.seqno = null;\n\n /**\n * Message topic.\n * @member {string} topic\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.topic = \"\";\n\n /**\n * Message signature.\n * @member {Uint8Array|null|undefined} signature\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.signature = null;\n\n /**\n * Message key.\n * @member {Uint8Array|null|undefined} key\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.key = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * Message _from.\n * @member {\"from\"|undefined} _from\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_from\", {\n get: $util.oneOfGetter($oneOfFields = [\"from\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _data.\n * @member {\"data\"|undefined} _data\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_data\", {\n get: $util.oneOfGetter($oneOfFields = [\"data\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _seqno.\n * @member {\"seqno\"|undefined} _seqno\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_seqno\", {\n get: $util.oneOfGetter($oneOfFields = [\"seqno\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _signature.\n * @member {\"signature\"|undefined} _signature\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_signature\", {\n get: $util.oneOfGetter($oneOfFields = [\"signature\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _key.\n * @member {\"key\"|undefined} _key\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_key\", {\n get: $util.oneOfGetter($oneOfFields = [\"key\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Message message. Does not implicitly {@link RPC.Message.verify|verify} messages.\n * @function encode\n * @memberof RPC.Message\n * @static\n * @param {RPC.IMessage} m Message message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Message.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.from != null && Object.hasOwnProperty.call(m, \"from\"))\n w.uint32(10).bytes(m.from);\n if (m.data != null && Object.hasOwnProperty.call(m, \"data\"))\n w.uint32(18).bytes(m.data);\n if (m.seqno != null && Object.hasOwnProperty.call(m, \"seqno\"))\n w.uint32(26).bytes(m.seqno);\n w.uint32(34).string(m.topic);\n if (m.signature != null && Object.hasOwnProperty.call(m, \"signature\"))\n w.uint32(42).bytes(m.signature);\n if (m.key != null && Object.hasOwnProperty.call(m, \"key\"))\n w.uint32(50).bytes(m.key);\n return w;\n };\n\n /**\n * Decodes a Message message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.Message\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.Message} Message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Message.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.Message();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.from = r.bytes();\n break;\n case 2:\n m.data = r.bytes();\n break;\n case 3:\n m.seqno = r.bytes();\n break;\n case 4:\n m.topic = r.string();\n break;\n case 5:\n m.signature = r.bytes();\n break;\n case 6:\n m.key = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"topic\"))\n throw $util.ProtocolError(\"missing required 'topic'\", { instance: m });\n return m;\n };\n\n /**\n * Creates a Message message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.Message\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.Message} Message\n */\n Message.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.Message)\n return d;\n var m = new $root.RPC.Message();\n if (d.from != null) {\n if (typeof d.from === \"string\")\n $util.base64.decode(d.from, m.from = $util.newBuffer($util.base64.length(d.from)), 0);\n else if (d.from.length)\n m.from = d.from;\n }\n if (d.data != null) {\n if (typeof d.data === \"string\")\n $util.base64.decode(d.data, m.data = $util.newBuffer($util.base64.length(d.data)), 0);\n else if (d.data.length)\n m.data = d.data;\n }\n if (d.seqno != null) {\n if (typeof d.seqno === \"string\")\n $util.base64.decode(d.seqno, m.seqno = $util.newBuffer($util.base64.length(d.seqno)), 0);\n else if (d.seqno.length)\n m.seqno = d.seqno;\n }\n if (d.topic != null) {\n m.topic = String(d.topic);\n }\n if (d.signature != null) {\n if (typeof d.signature === \"string\")\n $util.base64.decode(d.signature, m.signature = $util.newBuffer($util.base64.length(d.signature)), 0);\n else if (d.signature.length)\n m.signature = d.signature;\n }\n if (d.key != null) {\n if (typeof d.key === \"string\")\n $util.base64.decode(d.key, m.key = $util.newBuffer($util.base64.length(d.key)), 0);\n else if (d.key.length)\n m.key = d.key;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Message message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.Message\n * @static\n * @param {RPC.Message} m Message\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Message.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.topic = \"\";\n }\n if (m.from != null && m.hasOwnProperty(\"from\")) {\n d.from = o.bytes === String ? $util.base64.encode(m.from, 0, m.from.length) : o.bytes === Array ? Array.prototype.slice.call(m.from) : m.from;\n if (o.oneofs)\n d._from = \"from\";\n }\n if (m.data != null && m.hasOwnProperty(\"data\")) {\n d.data = o.bytes === String ? $util.base64.encode(m.data, 0, m.data.length) : o.bytes === Array ? Array.prototype.slice.call(m.data) : m.data;\n if (o.oneofs)\n d._data = \"data\";\n }\n if (m.seqno != null && m.hasOwnProperty(\"seqno\")) {\n d.seqno = o.bytes === String ? $util.base64.encode(m.seqno, 0, m.seqno.length) : o.bytes === Array ? Array.prototype.slice.call(m.seqno) : m.seqno;\n if (o.oneofs)\n d._seqno = \"seqno\";\n }\n if (m.topic != null && m.hasOwnProperty(\"topic\")) {\n d.topic = m.topic;\n }\n if (m.signature != null && m.hasOwnProperty(\"signature\")) {\n d.signature = o.bytes === String ? $util.base64.encode(m.signature, 0, m.signature.length) : o.bytes === Array ? Array.prototype.slice.call(m.signature) : m.signature;\n if (o.oneofs)\n d._signature = \"signature\";\n }\n if (m.key != null && m.hasOwnProperty(\"key\")) {\n d.key = o.bytes === String ? $util.base64.encode(m.key, 0, m.key.length) : o.bytes === Array ? Array.prototype.slice.call(m.key) : m.key;\n if (o.oneofs)\n d._key = \"key\";\n }\n return d;\n };\n\n /**\n * Converts this Message to JSON.\n * @function toJSON\n * @memberof RPC.Message\n * @instance\n * @returns {Object.} JSON object\n */\n Message.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Message;\n })();\n\n RPC.ControlMessage = (function() {\n\n /**\n * Properties of a ControlMessage.\n * @memberof RPC\n * @interface IControlMessage\n * @property {Array.|null} [ihave] ControlMessage ihave\n * @property {Array.|null} [iwant] ControlMessage iwant\n * @property {Array.|null} [graft] ControlMessage graft\n * @property {Array.|null} [prune] ControlMessage prune\n */\n\n /**\n * Constructs a new ControlMessage.\n * @memberof RPC\n * @classdesc Represents a ControlMessage.\n * @implements IControlMessage\n * @constructor\n * @param {RPC.IControlMessage=} [p] Properties to set\n */\n function ControlMessage(p) {\n this.ihave = [];\n this.iwant = [];\n this.graft = [];\n this.prune = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlMessage ihave.\n * @member {Array.} ihave\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.ihave = $util.emptyArray;\n\n /**\n * ControlMessage iwant.\n * @member {Array.} iwant\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.iwant = $util.emptyArray;\n\n /**\n * ControlMessage graft.\n * @member {Array.} graft\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.graft = $util.emptyArray;\n\n /**\n * ControlMessage prune.\n * @member {Array.} prune\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.prune = $util.emptyArray;\n\n /**\n * Encodes the specified ControlMessage message. Does not implicitly {@link RPC.ControlMessage.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlMessage\n * @static\n * @param {RPC.IControlMessage} m ControlMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.ihave != null && m.ihave.length) {\n for (var i = 0; i < m.ihave.length; ++i)\n $root.RPC.ControlIHave.encode(m.ihave[i], w.uint32(10).fork()).ldelim();\n }\n if (m.iwant != null && m.iwant.length) {\n for (var i = 0; i < m.iwant.length; ++i)\n $root.RPC.ControlIWant.encode(m.iwant[i], w.uint32(18).fork()).ldelim();\n }\n if (m.graft != null && m.graft.length) {\n for (var i = 0; i < m.graft.length; ++i)\n $root.RPC.ControlGraft.encode(m.graft[i], w.uint32(26).fork()).ldelim();\n }\n if (m.prune != null && m.prune.length) {\n for (var i = 0; i < m.prune.length; ++i)\n $root.RPC.ControlPrune.encode(m.prune[i], w.uint32(34).fork()).ldelim();\n }\n return w;\n };\n\n /**\n * Decodes a ControlMessage message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlMessage} ControlMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.ihave && m.ihave.length))\n m.ihave = [];\n m.ihave.push($root.RPC.ControlIHave.decode(r, r.uint32()));\n break;\n case 2:\n if (!(m.iwant && m.iwant.length))\n m.iwant = [];\n m.iwant.push($root.RPC.ControlIWant.decode(r, r.uint32()));\n break;\n case 3:\n if (!(m.graft && m.graft.length))\n m.graft = [];\n m.graft.push($root.RPC.ControlGraft.decode(r, r.uint32()));\n break;\n case 4:\n if (!(m.prune && m.prune.length))\n m.prune = [];\n m.prune.push($root.RPC.ControlPrune.decode(r, r.uint32()));\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlMessage message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlMessage\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlMessage} ControlMessage\n */\n ControlMessage.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlMessage)\n return d;\n var m = new $root.RPC.ControlMessage();\n if (d.ihave) {\n if (!Array.isArray(d.ihave))\n throw TypeError(\".RPC.ControlMessage.ihave: array expected\");\n m.ihave = [];\n for (var i = 0; i < d.ihave.length; ++i) {\n if (typeof d.ihave[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.ihave: object expected\");\n m.ihave[i] = $root.RPC.ControlIHave.fromObject(d.ihave[i]);\n }\n }\n if (d.iwant) {\n if (!Array.isArray(d.iwant))\n throw TypeError(\".RPC.ControlMessage.iwant: array expected\");\n m.iwant = [];\n for (var i = 0; i < d.iwant.length; ++i) {\n if (typeof d.iwant[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.iwant: object expected\");\n m.iwant[i] = $root.RPC.ControlIWant.fromObject(d.iwant[i]);\n }\n }\n if (d.graft) {\n if (!Array.isArray(d.graft))\n throw TypeError(\".RPC.ControlMessage.graft: array expected\");\n m.graft = [];\n for (var i = 0; i < d.graft.length; ++i) {\n if (typeof d.graft[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.graft: object expected\");\n m.graft[i] = $root.RPC.ControlGraft.fromObject(d.graft[i]);\n }\n }\n if (d.prune) {\n if (!Array.isArray(d.prune))\n throw TypeError(\".RPC.ControlMessage.prune: array expected\");\n m.prune = [];\n for (var i = 0; i < d.prune.length; ++i) {\n if (typeof d.prune[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.prune: object expected\");\n m.prune[i] = $root.RPC.ControlPrune.fromObject(d.prune[i]);\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlMessage message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlMessage\n * @static\n * @param {RPC.ControlMessage} m ControlMessage\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlMessage.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.ihave = [];\n d.iwant = [];\n d.graft = [];\n d.prune = [];\n }\n if (m.ihave && m.ihave.length) {\n d.ihave = [];\n for (var j = 0; j < m.ihave.length; ++j) {\n d.ihave[j] = $root.RPC.ControlIHave.toObject(m.ihave[j], o);\n }\n }\n if (m.iwant && m.iwant.length) {\n d.iwant = [];\n for (var j = 0; j < m.iwant.length; ++j) {\n d.iwant[j] = $root.RPC.ControlIWant.toObject(m.iwant[j], o);\n }\n }\n if (m.graft && m.graft.length) {\n d.graft = [];\n for (var j = 0; j < m.graft.length; ++j) {\n d.graft[j] = $root.RPC.ControlGraft.toObject(m.graft[j], o);\n }\n }\n if (m.prune && m.prune.length) {\n d.prune = [];\n for (var j = 0; j < m.prune.length; ++j) {\n d.prune[j] = $root.RPC.ControlPrune.toObject(m.prune[j], o);\n }\n }\n return d;\n };\n\n /**\n * Converts this ControlMessage to JSON.\n * @function toJSON\n * @memberof RPC.ControlMessage\n * @instance\n * @returns {Object.} JSON object\n */\n ControlMessage.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlMessage;\n })();\n\n RPC.ControlIHave = (function() {\n\n /**\n * Properties of a ControlIHave.\n * @memberof RPC\n * @interface IControlIHave\n * @property {string|null} [topicID] ControlIHave topicID\n * @property {Array.|null} [messageIDs] ControlIHave messageIDs\n */\n\n /**\n * Constructs a new ControlIHave.\n * @memberof RPC\n * @classdesc Represents a ControlIHave.\n * @implements IControlIHave\n * @constructor\n * @param {RPC.IControlIHave=} [p] Properties to set\n */\n function ControlIHave(p) {\n this.messageIDs = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlIHave topicID.\n * @member {string|null|undefined} topicID\n * @memberof RPC.ControlIHave\n * @instance\n */\n ControlIHave.prototype.topicID = null;\n\n /**\n * ControlIHave messageIDs.\n * @member {Array.} messageIDs\n * @memberof RPC.ControlIHave\n * @instance\n */\n ControlIHave.prototype.messageIDs = $util.emptyArray;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * ControlIHave _topicID.\n * @member {\"topicID\"|undefined} _topicID\n * @memberof RPC.ControlIHave\n * @instance\n */\n Object.defineProperty(ControlIHave.prototype, \"_topicID\", {\n get: $util.oneOfGetter($oneOfFields = [\"topicID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified ControlIHave message. Does not implicitly {@link RPC.ControlIHave.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlIHave\n * @static\n * @param {RPC.IControlIHave} m ControlIHave message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlIHave.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.topicID != null && Object.hasOwnProperty.call(m, \"topicID\"))\n w.uint32(10).string(m.topicID);\n if (m.messageIDs != null && m.messageIDs.length) {\n for (var i = 0; i < m.messageIDs.length; ++i)\n w.uint32(18).bytes(m.messageIDs[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ControlIHave message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlIHave\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlIHave} ControlIHave\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlIHave.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlIHave();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string();\n break;\n case 2:\n if (!(m.messageIDs && m.messageIDs.length))\n m.messageIDs = [];\n m.messageIDs.push(r.bytes());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlIHave message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlIHave\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlIHave} ControlIHave\n */\n ControlIHave.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlIHave)\n return d;\n var m = new $root.RPC.ControlIHave();\n if (d.topicID != null) {\n m.topicID = String(d.topicID);\n }\n if (d.messageIDs) {\n if (!Array.isArray(d.messageIDs))\n throw TypeError(\".RPC.ControlIHave.messageIDs: array expected\");\n m.messageIDs = [];\n for (var i = 0; i < d.messageIDs.length; ++i) {\n if (typeof d.messageIDs[i] === \"string\")\n $util.base64.decode(d.messageIDs[i], m.messageIDs[i] = $util.newBuffer($util.base64.length(d.messageIDs[i])), 0);\n else if (d.messageIDs[i].length)\n m.messageIDs[i] = d.messageIDs[i];\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlIHave message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlIHave\n * @static\n * @param {RPC.ControlIHave} m ControlIHave\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlIHave.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.messageIDs = [];\n }\n if (m.topicID != null && m.hasOwnProperty(\"topicID\")) {\n d.topicID = m.topicID;\n if (o.oneofs)\n d._topicID = \"topicID\";\n }\n if (m.messageIDs && m.messageIDs.length) {\n d.messageIDs = [];\n for (var j = 0; j < m.messageIDs.length; ++j) {\n d.messageIDs[j] = o.bytes === String ? $util.base64.encode(m.messageIDs[j], 0, m.messageIDs[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.messageIDs[j]) : m.messageIDs[j];\n }\n }\n return d;\n };\n\n /**\n * Converts this ControlIHave to JSON.\n * @function toJSON\n * @memberof RPC.ControlIHave\n * @instance\n * @returns {Object.} JSON object\n */\n ControlIHave.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlIHave;\n })();\n\n RPC.ControlIWant = (function() {\n\n /**\n * Properties of a ControlIWant.\n * @memberof RPC\n * @interface IControlIWant\n * @property {Array.|null} [messageIDs] ControlIWant messageIDs\n */\n\n /**\n * Constructs a new ControlIWant.\n * @memberof RPC\n * @classdesc Represents a ControlIWant.\n * @implements IControlIWant\n * @constructor\n * @param {RPC.IControlIWant=} [p] Properties to set\n */\n function ControlIWant(p) {\n this.messageIDs = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlIWant messageIDs.\n * @member {Array.} messageIDs\n * @memberof RPC.ControlIWant\n * @instance\n */\n ControlIWant.prototype.messageIDs = $util.emptyArray;\n\n /**\n * Encodes the specified ControlIWant message. Does not implicitly {@link RPC.ControlIWant.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlIWant\n * @static\n * @param {RPC.IControlIWant} m ControlIWant message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlIWant.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.messageIDs != null && m.messageIDs.length) {\n for (var i = 0; i < m.messageIDs.length; ++i)\n w.uint32(10).bytes(m.messageIDs[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ControlIWant message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlIWant\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlIWant} ControlIWant\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlIWant.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlIWant();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.messageIDs && m.messageIDs.length))\n m.messageIDs = [];\n m.messageIDs.push(r.bytes());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlIWant message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlIWant\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlIWant} ControlIWant\n */\n ControlIWant.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlIWant)\n return d;\n var m = new $root.RPC.ControlIWant();\n if (d.messageIDs) {\n if (!Array.isArray(d.messageIDs))\n throw TypeError(\".RPC.ControlIWant.messageIDs: array expected\");\n m.messageIDs = [];\n for (var i = 0; i < d.messageIDs.length; ++i) {\n if (typeof d.messageIDs[i] === \"string\")\n $util.base64.decode(d.messageIDs[i], m.messageIDs[i] = $util.newBuffer($util.base64.length(d.messageIDs[i])), 0);\n else if (d.messageIDs[i].length)\n m.messageIDs[i] = d.messageIDs[i];\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlIWant message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlIWant\n * @static\n * @param {RPC.ControlIWant} m ControlIWant\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlIWant.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.messageIDs = [];\n }\n if (m.messageIDs && m.messageIDs.length) {\n d.messageIDs = [];\n for (var j = 0; j < m.messageIDs.length; ++j) {\n d.messageIDs[j] = o.bytes === String ? $util.base64.encode(m.messageIDs[j], 0, m.messageIDs[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.messageIDs[j]) : m.messageIDs[j];\n }\n }\n return d;\n };\n\n /**\n * Converts this ControlIWant to JSON.\n * @function toJSON\n * @memberof RPC.ControlIWant\n * @instance\n * @returns {Object.} JSON object\n */\n ControlIWant.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlIWant;\n })();\n\n RPC.ControlGraft = (function() {\n\n /**\n * Properties of a ControlGraft.\n * @memberof RPC\n * @interface IControlGraft\n * @property {string|null} [topicID] ControlGraft topicID\n */\n\n /**\n * Constructs a new ControlGraft.\n * @memberof RPC\n * @classdesc Represents a ControlGraft.\n * @implements IControlGraft\n * @constructor\n * @param {RPC.IControlGraft=} [p] Properties to set\n */\n function ControlGraft(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlGraft topicID.\n * @member {string|null|undefined} topicID\n * @memberof RPC.ControlGraft\n * @instance\n */\n ControlGraft.prototype.topicID = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * ControlGraft _topicID.\n * @member {\"topicID\"|undefined} _topicID\n * @memberof RPC.ControlGraft\n * @instance\n */\n Object.defineProperty(ControlGraft.prototype, \"_topicID\", {\n get: $util.oneOfGetter($oneOfFields = [\"topicID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified ControlGraft message. Does not implicitly {@link RPC.ControlGraft.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlGraft\n * @static\n * @param {RPC.IControlGraft} m ControlGraft message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlGraft.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.topicID != null && Object.hasOwnProperty.call(m, \"topicID\"))\n w.uint32(10).string(m.topicID);\n return w;\n };\n\n /**\n * Decodes a ControlGraft message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlGraft\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlGraft} ControlGraft\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlGraft.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlGraft();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlGraft message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlGraft\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlGraft} ControlGraft\n */\n ControlGraft.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlGraft)\n return d;\n var m = new $root.RPC.ControlGraft();\n if (d.topicID != null) {\n m.topicID = String(d.topicID);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlGraft message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlGraft\n * @static\n * @param {RPC.ControlGraft} m ControlGraft\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlGraft.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (m.topicID != null && m.hasOwnProperty(\"topicID\")) {\n d.topicID = m.topicID;\n if (o.oneofs)\n d._topicID = \"topicID\";\n }\n return d;\n };\n\n /**\n * Converts this ControlGraft to JSON.\n * @function toJSON\n * @memberof RPC.ControlGraft\n * @instance\n * @returns {Object.} JSON object\n */\n ControlGraft.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlGraft;\n })();\n\n RPC.ControlPrune = (function() {\n\n /**\n * Properties of a ControlPrune.\n * @memberof RPC\n * @interface IControlPrune\n * @property {string|null} [topicID] ControlPrune topicID\n * @property {Array.|null} [peers] ControlPrune peers\n * @property {number|null} [backoff] ControlPrune backoff\n */\n\n /**\n * Constructs a new ControlPrune.\n * @memberof RPC\n * @classdesc Represents a ControlPrune.\n * @implements IControlPrune\n * @constructor\n * @param {RPC.IControlPrune=} [p] Properties to set\n */\n function ControlPrune(p) {\n this.peers = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlPrune topicID.\n * @member {string|null|undefined} topicID\n * @memberof RPC.ControlPrune\n * @instance\n */\n ControlPrune.prototype.topicID = null;\n\n /**\n * ControlPrune peers.\n * @member {Array.} peers\n * @memberof RPC.ControlPrune\n * @instance\n */\n ControlPrune.prototype.peers = $util.emptyArray;\n\n /**\n * ControlPrune backoff.\n * @member {number|null|undefined} backoff\n * @memberof RPC.ControlPrune\n * @instance\n */\n ControlPrune.prototype.backoff = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * ControlPrune _topicID.\n * @member {\"topicID\"|undefined} _topicID\n * @memberof RPC.ControlPrune\n * @instance\n */\n Object.defineProperty(ControlPrune.prototype, \"_topicID\", {\n get: $util.oneOfGetter($oneOfFields = [\"topicID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * ControlPrune _backoff.\n * @member {\"backoff\"|undefined} _backoff\n * @memberof RPC.ControlPrune\n * @instance\n */\n Object.defineProperty(ControlPrune.prototype, \"_backoff\", {\n get: $util.oneOfGetter($oneOfFields = [\"backoff\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified ControlPrune message. Does not implicitly {@link RPC.ControlPrune.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlPrune\n * @static\n * @param {RPC.IControlPrune} m ControlPrune message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlPrune.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.topicID != null && Object.hasOwnProperty.call(m, \"topicID\"))\n w.uint32(10).string(m.topicID);\n if (m.peers != null && m.peers.length) {\n for (var i = 0; i < m.peers.length; ++i)\n $root.RPC.PeerInfo.encode(m.peers[i], w.uint32(18).fork()).ldelim();\n }\n if (m.backoff != null && Object.hasOwnProperty.call(m, \"backoff\"))\n w.uint32(24).uint64(m.backoff);\n return w;\n };\n\n /**\n * Decodes a ControlPrune message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlPrune\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlPrune} ControlPrune\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlPrune.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlPrune();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string();\n break;\n case 2:\n if (!(m.peers && m.peers.length))\n m.peers = [];\n m.peers.push($root.RPC.PeerInfo.decode(r, r.uint32()));\n break;\n case 3:\n m.backoff = r.uint64();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlPrune message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlPrune\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlPrune} ControlPrune\n */\n ControlPrune.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlPrune)\n return d;\n var m = new $root.RPC.ControlPrune();\n if (d.topicID != null) {\n m.topicID = String(d.topicID);\n }\n if (d.peers) {\n if (!Array.isArray(d.peers))\n throw TypeError(\".RPC.ControlPrune.peers: array expected\");\n m.peers = [];\n for (var i = 0; i < d.peers.length; ++i) {\n if (typeof d.peers[i] !== \"object\")\n throw TypeError(\".RPC.ControlPrune.peers: object expected\");\n m.peers[i] = $root.RPC.PeerInfo.fromObject(d.peers[i]);\n }\n }\n if (d.backoff != null) {\n if ($util.Long)\n (m.backoff = $util.Long.fromValue(d.backoff)).unsigned = true;\n else if (typeof d.backoff === \"string\")\n m.backoff = parseInt(d.backoff, 10);\n else if (typeof d.backoff === \"number\")\n m.backoff = d.backoff;\n else if (typeof d.backoff === \"object\")\n m.backoff = new $util.LongBits(d.backoff.low >>> 0, d.backoff.high >>> 0).toNumber(true);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlPrune message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlPrune\n * @static\n * @param {RPC.ControlPrune} m ControlPrune\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlPrune.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.peers = [];\n }\n if (m.topicID != null && m.hasOwnProperty(\"topicID\")) {\n d.topicID = m.topicID;\n if (o.oneofs)\n d._topicID = \"topicID\";\n }\n if (m.peers && m.peers.length) {\n d.peers = [];\n for (var j = 0; j < m.peers.length; ++j) {\n d.peers[j] = $root.RPC.PeerInfo.toObject(m.peers[j], o);\n }\n }\n if (m.backoff != null && m.hasOwnProperty(\"backoff\")) {\n if (typeof m.backoff === \"number\")\n d.backoff = o.longs === String ? String(m.backoff) : m.backoff;\n else\n d.backoff = o.longs === String ? $util.Long.prototype.toString.call(m.backoff) : o.longs === Number ? new $util.LongBits(m.backoff.low >>> 0, m.backoff.high >>> 0).toNumber(true) : m.backoff;\n if (o.oneofs)\n d._backoff = \"backoff\";\n }\n return d;\n };\n\n /**\n * Converts this ControlPrune to JSON.\n * @function toJSON\n * @memberof RPC.ControlPrune\n * @instance\n * @returns {Object.} JSON object\n */\n ControlPrune.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlPrune;\n })();\n\n RPC.PeerInfo = (function() {\n\n /**\n * Properties of a PeerInfo.\n * @memberof RPC\n * @interface IPeerInfo\n * @property {Uint8Array|null} [peerID] PeerInfo peerID\n * @property {Uint8Array|null} [signedPeerRecord] PeerInfo signedPeerRecord\n */\n\n /**\n * Constructs a new PeerInfo.\n * @memberof RPC\n * @classdesc Represents a PeerInfo.\n * @implements IPeerInfo\n * @constructor\n * @param {RPC.IPeerInfo=} [p] Properties to set\n */\n function PeerInfo(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * PeerInfo peerID.\n * @member {Uint8Array|null|undefined} peerID\n * @memberof RPC.PeerInfo\n * @instance\n */\n PeerInfo.prototype.peerID = null;\n\n /**\n * PeerInfo signedPeerRecord.\n * @member {Uint8Array|null|undefined} signedPeerRecord\n * @memberof RPC.PeerInfo\n * @instance\n */\n PeerInfo.prototype.signedPeerRecord = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * PeerInfo _peerID.\n * @member {\"peerID\"|undefined} _peerID\n * @memberof RPC.PeerInfo\n * @instance\n */\n Object.defineProperty(PeerInfo.prototype, \"_peerID\", {\n get: $util.oneOfGetter($oneOfFields = [\"peerID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * PeerInfo _signedPeerRecord.\n * @member {\"signedPeerRecord\"|undefined} _signedPeerRecord\n * @memberof RPC.PeerInfo\n * @instance\n */\n Object.defineProperty(PeerInfo.prototype, \"_signedPeerRecord\", {\n get: $util.oneOfGetter($oneOfFields = [\"signedPeerRecord\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified PeerInfo message. Does not implicitly {@link RPC.PeerInfo.verify|verify} messages.\n * @function encode\n * @memberof RPC.PeerInfo\n * @static\n * @param {RPC.IPeerInfo} m PeerInfo message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n PeerInfo.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.peerID != null && Object.hasOwnProperty.call(m, \"peerID\"))\n w.uint32(10).bytes(m.peerID);\n if (m.signedPeerRecord != null && Object.hasOwnProperty.call(m, \"signedPeerRecord\"))\n w.uint32(18).bytes(m.signedPeerRecord);\n return w;\n };\n\n /**\n * Decodes a PeerInfo message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.PeerInfo\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.PeerInfo} PeerInfo\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n PeerInfo.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.PeerInfo();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.peerID = r.bytes();\n break;\n case 2:\n m.signedPeerRecord = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a PeerInfo message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.PeerInfo\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.PeerInfo} PeerInfo\n */\n PeerInfo.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.PeerInfo)\n return d;\n var m = new $root.RPC.PeerInfo();\n if (d.peerID != null) {\n if (typeof d.peerID === \"string\")\n $util.base64.decode(d.peerID, m.peerID = $util.newBuffer($util.base64.length(d.peerID)), 0);\n else if (d.peerID.length)\n m.peerID = d.peerID;\n }\n if (d.signedPeerRecord != null) {\n if (typeof d.signedPeerRecord === \"string\")\n $util.base64.decode(d.signedPeerRecord, m.signedPeerRecord = $util.newBuffer($util.base64.length(d.signedPeerRecord)), 0);\n else if (d.signedPeerRecord.length)\n m.signedPeerRecord = d.signedPeerRecord;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a PeerInfo message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.PeerInfo\n * @static\n * @param {RPC.PeerInfo} m PeerInfo\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n PeerInfo.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (m.peerID != null && m.hasOwnProperty(\"peerID\")) {\n d.peerID = o.bytes === String ? $util.base64.encode(m.peerID, 0, m.peerID.length) : o.bytes === Array ? Array.prototype.slice.call(m.peerID) : m.peerID;\n if (o.oneofs)\n d._peerID = \"peerID\";\n }\n if (m.signedPeerRecord != null && m.hasOwnProperty(\"signedPeerRecord\")) {\n d.signedPeerRecord = o.bytes === String ? $util.base64.encode(m.signedPeerRecord, 0, m.signedPeerRecord.length) : o.bytes === Array ? Array.prototype.slice.call(m.signedPeerRecord) : m.signedPeerRecord;\n if (o.oneofs)\n d._signedPeerRecord = \"signedPeerRecord\";\n }\n return d;\n };\n\n /**\n * Converts this PeerInfo to JSON.\n * @function toJSON\n * @memberof RPC.PeerInfo\n * @instance\n * @returns {Object.} JSON object\n */\n PeerInfo.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return PeerInfo;\n })();\n\n return RPC;\n })();\n\n return $root;\n});\n", "'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array, options) {\n var options = options || {};\n\n this._head = 0;\n this._tail = 0;\n this._capacity = options.capacity;\n this._capacityMask = 0x3;\n this._list = new Array(4);\n if (Array.isArray(array)) {\n this._fromArray(array);\n }\n}\n\n/**\n * -------------\n * PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var len = this.size();\n if (i >= len || i < -len) return undefined;\n if (i < 0) i += len;\n i = (this._head + i) & this._capacityMask;\n return this._list[i];\n};\n\n/**\n * Alias for peekAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n if (this._head === this._tail) return undefined;\n return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n get: function length() {\n return this.size();\n }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n if (this._head === this._tail) return 0;\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n if (item === undefined) return this.size();\n var len = this._list.length;\n this._head = (this._head - 1 + len) & this._capacityMask;\n this._list[this._head] = item;\n if (this._tail === this._head) this._growArray();\n if (this._capacity && this.size() > this._capacity) this.pop();\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n var head = this._head;\n if (head === this._tail) return undefined;\n var item = this._list[head];\n this._list[head] = undefined;\n this._head = (head + 1) & this._capacityMask;\n if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n if (item === undefined) return this.size();\n var tail = this._tail;\n this._list[tail] = item;\n this._tail = (tail + 1) & this._capacityMask;\n if (this._tail === this._head) {\n this._growArray();\n }\n if (this._capacity && this.size() > this._capacity) {\n this.shift();\n }\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n var tail = this._tail;\n if (tail === this._head) return undefined;\n var len = this._list.length;\n this._tail = (tail - 1 + len) & this._capacityMask;\n var item = this._list[this._tail];\n this._list[this._tail] = undefined;\n if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size) return void 0;\n if (i < 0) i += size;\n i = (this._head + i) & this._capacityMask;\n var item = this._list[i];\n var k;\n if (index < size / 2) {\n for (k = index; k > 0; k--) {\n this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._head = (this._head + 1 + len) & this._capacityMask;\n } else {\n for (k = size - 1 - index; k > 0; k--) {\n this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._tail = (this._tail - 1 + len) & this._capacityMask;\n }\n return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n var i = index;\n var removed;\n var del_count = count;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size || count < 1) return void 0;\n if (i < 0) i += size;\n if (count === 1 || !count) {\n removed = new Array(1);\n removed[0] = this.removeOne(i);\n return removed;\n }\n if (i === 0 && i + count >= size) {\n removed = this.toArray();\n this.clear();\n return removed;\n }\n if (i + count > size) count = size - i;\n var k;\n removed = new Array(count);\n for (k = 0; k < count; k++) {\n removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n }\n i = (this._head + i) & this._capacityMask;\n if (index + count === size) {\n this._tail = (this._tail - count + len) & this._capacityMask;\n for (k = count; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (index === 0) {\n this._head = (this._head + count + len) & this._capacityMask;\n for (k = count - 1; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (i < size / 2) {\n this._head = (this._head + index + count + len) & this._capacityMask;\n for (k = index; k > 0; k--) {\n this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n }\n i = (this._head - 1 + len) & this._capacityMask;\n while (del_count > 0) {\n this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n if (index < 0) this._tail = i;\n } else {\n this._tail = i;\n i = (i + count + len) & this._capacityMask;\n for (k = size - (count + index); k > 0; k--) {\n this.push(this._list[i++]);\n }\n i = this._tail;\n while (del_count > 0) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n }\n if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var size = this.size();\n if (i < 0) i += size;\n if (i > size) return void 0;\n if (arguments.length > 2) {\n var k;\n var temp;\n var removed;\n var arg_len = arguments.length;\n var len = this._list.length;\n var arguments_index = 2;\n if (!size || i < size / 2) {\n temp = new Array(i);\n for (k = 0; k < i; k++) {\n temp[k] = this._list[(this._head + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i > 0) {\n this._head = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._head = (this._head + i + len) & this._capacityMask;\n }\n while (arg_len > arguments_index) {\n this.unshift(arguments[--arg_len]);\n }\n for (k = i; k > 0; k--) {\n this.unshift(temp[k - 1]);\n }\n } else {\n temp = new Array(size - (i + count));\n var leng = temp.length;\n for (k = 0; k < leng; k++) {\n temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i != size) {\n this._tail = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._tail = (this._tail - leng + len) & this._capacityMask;\n }\n while (arguments_index < arg_len) {\n this.push(arguments[arguments_index++]);\n }\n for (k = 0; k < leng; k++) {\n this.push(temp[k]);\n }\n }\n return removed;\n } else {\n return this.remove(i, count);\n }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n this._head = 0;\n this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n return this._copyArray(false);\n};\n\n/**\n * -------------\n * INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n for (var i = 0; i < array.length; i++) this.push(array[i]);\n};\n\n/**\n *\n * @param fullCopy\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy) {\n var newArray = [];\n var list = this._list;\n var len = list.length;\n var i;\n if (fullCopy || this._head > this._tail) {\n for (i = this._head; i < len; i++) newArray.push(list[i]);\n for (i = 0; i < this._tail; i++) newArray.push(list[i]);\n } else {\n for (i = this._head; i < this._tail; i++) newArray.push(list[i]);\n }\n return newArray;\n};\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n if (this._head) {\n // copy existing data, head to end, then beginning to tail.\n this._list = this._copyArray(true);\n this._head = 0;\n }\n\n // head is at 0 and array is now full, safe to extend\n this._tail = this._list.length;\n\n this._list.length <<= 1;\n this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n this._list.length >>>= 1;\n this._capacityMask >>>= 1;\n};\n\n\nmodule.exports = Denque;\n", "module.exports = readable => {\n // Node.js stream\n if (readable[Symbol.asyncIterator]) return readable\n\n // Browser ReadableStream\n if (readable.getReader) {\n return (async function * () {\n const reader = readable.getReader()\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) return\n yield value\n }\n } finally {\n reader.releaseLock()\n }\n })()\n }\n\n throw new Error('unknown stream')\n}\n", "'use strict'\n\nconst HTTP = require('../http')\n\n/**\n *\n * @param {string} url\n * @param {import(\"../types\").HTTPOptions} [options]\n * @returns {{ path: string; content?: AsyncIterable }}\n */\nconst urlSource = (url, options) => {\n return {\n path: decodeURIComponent(new URL(url).pathname.split('/').pop() || ''),\n content: readURLContent(url, options)\n }\n}\n\n/**\n *\n * @param {string} url\n * @param {import(\"../types\").HTTPOptions} [options]\n * @returns {AsyncIterable}\n */\nasync function * readURLContent (url, options) {\n const http = new HTTP()\n const response = await http.get(url, options)\n\n yield * response.iterator()\n}\n\nmodule.exports = urlSource\n", "'use strict'\n\n// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nconst MAX_BYTES = 65536\n\n/**\n * @param {number} size\n */\nfunction randomBytes(size) {\n const bytes = new Uint8Array(size)\n let generated = 0\n\n if (size > 0) {\n // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) {\n while (generated < size) {\n if (generated + MAX_BYTES > size) {\n crypto.getRandomValues(\n bytes.subarray(generated, generated + (size - generated))\n )\n generated += size - generated\n } else {\n crypto.getRandomValues(\n bytes.subarray(generated, generated + MAX_BYTES)\n )\n generated += MAX_BYTES\n }\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n\n return bytes\n}\n\nmodule.exports = randomBytes\n", "'use strict';\n\n// 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 createDelay = ({clearTimeout: defaultClear, setTimeout: set, willResolve}) => (ms, {value, signal} = {}) => {\n\tif (signal && signal.aborted) {\n\t\treturn Promise.reject(createAbortError());\n\t}\n\n\tlet timeoutId;\n\tlet settle;\n\tlet rejectFn;\n\tconst clear = defaultClear || clearTimeout;\n\n\tconst signalListener = () => {\n\t\tclear(timeoutId);\n\t\trejectFn(createAbortError());\n\t};\n\n\tconst cleanup = () => {\n\t\tif (signal) {\n\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t}\n\t};\n\n\tconst delayPromise = new Promise((resolve, reject) => {\n\t\tsettle = () => {\n\t\t\tcleanup();\n\t\t\tif (willResolve) {\n\t\t\t\tresolve(value);\n\t\t\t} else {\n\t\t\t\treject(value);\n\t\t\t}\n\t\t};\n\n\t\trejectFn = reject;\n\t\ttimeoutId = (set || setTimeout)(settle, ms);\n\t});\n\n\tif (signal) {\n\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t}\n\n\tdelayPromise.clear = () => {\n\t\tclear(timeoutId);\n\t\ttimeoutId = null;\n\t\tsettle();\n\t};\n\n\treturn delayPromise;\n};\n\nconst createWithTimers = clearAndSet => {\n\tconst delay = createDelay({...clearAndSet, willResolve: true});\n\tdelay.reject = createDelay({...clearAndSet, willResolve: false});\n\tdelay.range = (minimum, maximum, options) => delay(randomInteger(minimum, maximum), options);\n\treturn delay;\n};\n\nconst delay = createWithTimers();\ndelay.createWithTimers = createWithTimers;\n\nmodule.exports = delay;\n// TODO: Remove this for the next major release\nmodule.exports.default = delay;\n", "'use strict'\n\nconst intervals = new Map()\n\nconst _generateId = () => `${Date.now()}:${Math.floor(Math.random() * 1000000)}`\n\n/**\n * Run a given task each {interval} ms\n *\n * @param {() => Promise} task\n * @param {number} interval\n * @param {string} id\n */\nasync function _runPeriodically (task, interval, id) {\n while (intervals.get(id)) {\n try {\n await task()\n } catch (err) {\n // Throw global context error if handler throws\n setTimeout(() => { throw err }, 1)\n break\n }\n\n if (!intervals.get(id)) {\n break\n }\n\n await new Promise(resolve => {\n const _timeout = setTimeout(resolve, interval)\n\n intervals.set(id, _timeout)\n })\n }\n}\n\n/**\n * Asynchronous setInterval that is properly delayed using promises and can be delayed on boot.\n *\n * @param {() => Promise} task\n * @param {number} interval\n * @param {number} [delay = interval]\n * @returns {string}\n */\nfunction setDelayedInterval (task, interval, delay) {\n delay = delay || interval\n\n const id = _generateId()\n const _timeout = setTimeout(() => {\n _runPeriodically(task, interval, id)\n }, delay)\n\n intervals.set(id, _timeout)\n\n return id\n}\n\n/**\n * Clear delayed interval.\n *\n * @param {string} id\n */\nfunction clearDelayedInterval (id) {\n const _timeout = intervals.get(id)\n\n if (_timeout) {\n clearTimeout(_timeout)\n intervals.delete(id)\n }\n}\n\nmodule.exports = {\n setDelayedInterval,\n clearDelayedInterval\n}\n", "module.exports = class RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * points: 4, // Number of points\n * duration: 1, // Per seconds\n * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds\n * execEvenly: false, // Execute allowed actions evenly over duration\n * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option\n * keyPrefix: 'rlflx',\n * }\n */\n constructor(opts = {}) {\n this.points = opts.points;\n this.duration = opts.duration;\n this.blockDuration = opts.blockDuration;\n this.execEvenly = opts.execEvenly;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs;\n this.keyPrefix = opts.keyPrefix;\n }\n\n get points() {\n return this._points;\n }\n\n set points(value) {\n this._points = value >= 0 ? value : 4;\n }\n\n get duration() {\n return this._duration;\n }\n\n set duration(value) {\n this._duration = typeof value === 'undefined' ? 1 : value;\n }\n\n get msDuration() {\n return this.duration * 1000;\n }\n\n get blockDuration() {\n return this._blockDuration;\n }\n\n set blockDuration(value) {\n this._blockDuration = typeof value === 'undefined' ? 0 : value;\n }\n\n get msBlockDuration() {\n return this.blockDuration * 1000;\n }\n\n get execEvenly() {\n return this._execEvenly;\n }\n\n set execEvenly(value) {\n this._execEvenly = typeof value === 'undefined' ? false : Boolean(value);\n }\n\n get execEvenlyMinDelayMs() {\n return this._execEvenlyMinDelayMs;\n }\n\n set execEvenlyMinDelayMs(value) {\n this._execEvenlyMinDelayMs = typeof value === 'undefined' ? Math.ceil(this.msDuration / this.points) : value;\n }\n\n get keyPrefix() {\n return this._keyPrefix;\n }\n\n set keyPrefix(value) {\n if (typeof value === 'undefined') {\n value = 'rlflx';\n }\n if (typeof value !== 'string') {\n throw new Error('keyPrefix must be string');\n }\n this._keyPrefix = value;\n }\n\n _getKeySecDuration(options = {}) {\n return options && options.customDuration >= 0\n ? options.customDuration\n : this.duration;\n }\n\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n\n consume() {\n throw new Error(\"You have to implement the method 'consume'!\");\n }\n\n penalty() {\n throw new Error(\"You have to implement the method 'penalty'!\");\n }\n\n reward() {\n throw new Error(\"You have to implement the method 'reward'!\");\n }\n\n get() {\n throw new Error(\"You have to implement the method 'get'!\");\n }\n\n set() {\n throw new Error(\"You have to implement the method 'set'!\");\n }\n\n block() {\n throw new Error(\"You have to implement the method 'block'!\");\n }\n\n delete() {\n throw new Error(\"You have to implement the method 'delete'!\");\n }\n};\n", "module.exports = class BlockedKeys {\n constructor() {\n this._keys = {}; // {'key': 1526279430331}\n this._addedKeysAmount = 0;\n }\n\n collectExpired() {\n const now = Date.now();\n\n Object.keys(this._keys).forEach((key) => {\n if (this._keys[key] <= now) {\n delete this._keys[key];\n }\n });\n\n this._addedKeysAmount = Object.keys(this._keys).length;\n }\n\n /**\n * Add new blocked key\n *\n * @param key String\n * @param sec Number\n */\n add(key, sec) {\n this.addMs(key, sec * 1000);\n }\n\n /**\n * Add new blocked key for ms\n *\n * @param key String\n * @param ms Number\n */\n addMs(key, ms) {\n this._keys[key] = Date.now() + ms;\n this._addedKeysAmount++;\n if (this._addedKeysAmount > 999) {\n this.collectExpired();\n }\n }\n\n /**\n * 0 means not blocked\n *\n * @param key\n * @returns {number}\n */\n msBeforeExpire(key) {\n const expire = this._keys[key];\n\n if (expire && expire >= Date.now()) {\n this.collectExpired();\n const now = Date.now();\n return expire >= now ? expire - now : 0;\n }\n\n return 0;\n }\n\n /**\n * If key is not given, delete all data in memory\n * \n * @param {string|undefined} key\n */\n delete(key) {\n if (key) {\n delete this._keys[key];\n } else {\n Object.keys(this._keys).forEach((key) => {\n delete this._keys[key];\n });\n }\n }\n};\n", "const BlockedKeys = require('./BlockedKeys');\n\nmodule.exports = BlockedKeys;\n", "module.exports = class RateLimiterRes {\n constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) {\n this.remainingPoints = typeof remainingPoints === 'undefined' ? 0 : remainingPoints; // Remaining points in current duration\n this.msBeforeNext = typeof msBeforeNext === 'undefined' ? 0 : msBeforeNext; // Milliseconds before next action\n this.consumedPoints = typeof consumedPoints === 'undefined' ? 0 : consumedPoints; // Consumed points in current duration\n this.isFirstInDuration = typeof isFirstInDuration === 'undefined' ? false : isFirstInDuration;\n }\n\n get msBeforeNext() {\n return this._msBeforeNext;\n }\n\n set msBeforeNext(ms) {\n this._msBeforeNext = ms;\n return this;\n }\n\n get remainingPoints() {\n return this._remainingPoints;\n }\n\n set remainingPoints(p) {\n this._remainingPoints = p;\n return this;\n }\n\n get consumedPoints() {\n return this._consumedPoints;\n }\n\n set consumedPoints(p) {\n this._consumedPoints = p;\n return this;\n }\n\n get isFirstInDuration() {\n return this._isFirstInDuration;\n }\n\n set isFirstInDuration(value) {\n this._isFirstInDuration = Boolean(value);\n }\n\n _getDecoratedProperties() {\n return {\n remainingPoints: this.remainingPoints,\n msBeforeNext: this.msBeforeNext,\n consumedPoints: this.consumedPoints,\n isFirstInDuration: this.isFirstInDuration,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this._getDecoratedProperties();\n }\n\n toString() {\n return JSON.stringify(this._getDecoratedProperties());\n }\n\n toJSON() {\n return this._getDecoratedProperties();\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst BlockedKeys = require('./component/BlockedKeys');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RateLimiterStoreAbstract extends RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * ... see other in RateLimiterAbstract\n *\n * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked\n * inMemoryBlockDuration: 10, // Block duration in seconds\n * insuranceLimiter: RateLimiterAbstract\n * }\n */\n constructor(opts = {}) {\n super(opts);\n\n this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed || opts.inmemoryBlockOnConsumed;\n this.inMemoryBlockDuration = opts.inMemoryBlockDuration || opts.inmemoryBlockDuration;\n this.insuranceLimiter = opts.insuranceLimiter;\n this._inMemoryBlockedKeys = new BlockedKeys();\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('storeClient is not set');\n }\n this._client = value;\n }\n\n /**\n * Have to be launched after consume\n * It blocks key and execute evenly depending on result from store\n *\n * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result\n *\n * @param resolve\n * @param reject\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @param {Object} options\n * @private\n */\n _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) {\n const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult);\n\n if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0)\n && res.consumedPoints >= this.inMemoryBlockOnConsumed\n ) {\n this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext);\n if (res.consumedPoints > this.points) {\n return reject(res);\n } else {\n return resolve(res)\n }\n } else if (res.consumedPoints > this.points) {\n let blockPromise = Promise.resolve();\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + changedPoints)) {\n res.msBeforeNext = this.msBlockDuration;\n blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options);\n }\n\n if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) {\n // Block key for this.inMemoryBlockDuration seconds\n this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration);\n res.msBeforeNext = this.msInMemoryBlockDuration;\n }\n\n blockPromise\n .then(() => {\n reject(res);\n })\n .catch((err) => {\n reject(err);\n });\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n }\n\n _handleError(err, funcName, resolve, reject, key, data = false, options = {}) {\n if (!(this.insuranceLimiter instanceof RateLimiterAbstract)) {\n reject(err);\n } else {\n this.insuranceLimiter[funcName](key, data, options)\n .then((res) => {\n resolve(res);\n })\n .catch((res) => {\n reject(res);\n });\n }\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {BlockedKeys}\n * @private\n */\n get _inmemoryBlockedKeys() {\n return this._inMemoryBlockedKeys\n }\n\n /**\n * @deprecated Use camelCase version\n * @param rlKey\n * @returns {number}\n */\n getInmemoryBlockMsBeforeExpire(rlKey) {\n return this.getInMemoryBlockMsBeforeExpire(rlKey)\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockOnConsumed() {\n return this.inMemoryBlockOnConsumed;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockOnConsumed(value) {\n this.inMemoryBlockOnConsumed = value;\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockDuration() {\n return this.inMemoryBlockDuration;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockDuration(value) {\n this.inMemoryBlockDuration = value\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number}\n */\n get msInmemoryBlockDuration() {\n return this.inMemoryBlockDuration * 1000;\n }\n\n getInMemoryBlockMsBeforeExpire(rlKey) {\n if (this.inMemoryBlockOnConsumed > 0) {\n return this._inMemoryBlockedKeys.msBeforeExpire(rlKey);\n }\n\n return 0;\n }\n\n get inMemoryBlockOnConsumed() {\n return this._inMemoryBlockOnConsumed;\n }\n\n set inMemoryBlockOnConsumed(value) {\n this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0;\n if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) {\n throw new Error('inMemoryBlockOnConsumed option must be greater or equal \"points\" option');\n }\n }\n\n get inMemoryBlockDuration() {\n return this._inMemoryBlockDuration;\n }\n\n set inMemoryBlockDuration(value) {\n this._inMemoryBlockDuration = value ? parseInt(value) : 0;\n if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) {\n throw new Error('inMemoryBlockOnConsumed option must be set up');\n }\n }\n\n get msInMemoryBlockDuration() {\n return this._inMemoryBlockDuration * 1000;\n }\n\n get insuranceLimiter() {\n return this._insuranceLimiter;\n }\n\n set insuranceLimiter(value) {\n if (typeof value !== 'undefined' && !(value instanceof RateLimiterAbstract)) {\n throw new Error('insuranceLimiter must be instance of RateLimiterAbstract');\n }\n this._insuranceLimiter = value;\n if (this._insuranceLimiter) {\n this._insuranceLimiter.blockDuration = this.blockDuration;\n this._insuranceLimiter.execEvenly = this.execEvenly;\n }\n }\n\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n block(key, secDuration, options = {}) {\n const msDuration = secDuration * 1000;\n return this._block(this.getKey(key), this.points + 1, msDuration, options);\n }\n\n /**\n * Set points by key for any duration\n *\n * @param key\n * @param points\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n set(key, points, secDuration, options = {}) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n return this._block(this.getKey(key), points, msDuration, options);\n }\n\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns Promise\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const rlKey = this.getKey(key);\n\n const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey);\n if (inMemoryBlockMsBeforeExpire > 0) {\n return reject(new RateLimiterRes(0, inMemoryBlockMsBeforeExpire));\n }\n\n this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n this._afterConsume(resolve, reject, rlKey, pointsToConsume, res);\n })\n .catch((err) => {\n this._handleError(err, 'consume', resolve, reject, key, pointsToConsume, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, points, res));\n })\n .catch((err) => {\n this._handleError(err, 'penalty', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, -points, res));\n })\n .catch((err) => {\n this._handleError(err, 'reward', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise|null\n */\n get(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._get(rlKey, options)\n .then((res) => {\n if (res === null || typeof res === 'undefined') {\n resolve(null);\n } else {\n resolve(this._getRateLimiterRes(rlKey, 0, res));\n }\n })\n .catch((err) => {\n this._handleError(err, 'get', resolve, reject, key, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise\n */\n delete(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._delete(rlKey, options)\n .then((res) => {\n this._inMemoryBlockedKeys.delete(rlKey);\n resolve(res);\n })\n .catch((err) => {\n this._handleError(err, 'delete', resolve, reject, key, options);\n });\n });\n }\n\n /**\n * Cleanup keys no-matter expired or not.\n */\n deleteInMemoryBlockedAll() {\n this._inMemoryBlockedKeys.delete();\n }\n\n /**\n * Get RateLimiterRes object filled depending on storeResult, which specific for exact store\n *\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @private\n */\n _getRateLimiterRes(rlKey, changedPoints, storeResult) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_getRateLimiterRes'!\");\n }\n\n /**\n * Block key for this.msBlockDuration milliseconds\n * Usually, it just prolongs lifetime of key\n *\n * @param rlKey\n * @param initPoints\n * @param msDuration\n * @param {Object} options\n *\n * @return Promise\n */\n _block(rlKey, initPoints, msDuration, options = {}) {\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, initPoints, msDuration, true, options)\n .then(() => {\n resolve(new RateLimiterRes(0, msDuration > 0 ? msDuration : -1, initPoints));\n })\n .catch((err) => {\n this._handleError(err, 'block', resolve, reject, this.parseKey(rlKey), msDuration / 1000, options);\n });\n });\n }\n\n /**\n * Have to be implemented in every limiter\n * Resolve with raw result from Store OR null if rlKey is not set\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _get(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_get'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with true OR false if rlKey doesn't exist\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _delete(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_delete'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}\n *\n * @param {string} rlKey\n * @param {number} points\n * @param {number} msDuration\n * @param {boolean} forceExpire\n * @param {Object} options\n * @abstract\n *\n * @return Promise\n */\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n throw new Error(\"You have to implement the method '_upsert'!\");\n }\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst incrTtlLuaScript = `redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') \\\nlocal consumed = redis.call('incrby', KEYS[1], ARGV[1]) \\\nlocal ttl = redis.call('pttl', KEYS[1]) \\\nif ttl == -1 then \\\n redis.call('expire', KEYS[1], ARGV[2]) \\\n ttl = 1000 * ARGV[2] \\\nend \\\nreturn {consumed, ttl} \\\n`;\n\nclass RateLimiterRedis extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * redis: RedisClient\n * rejectIfRedisNotReady: boolean = false - reject / invoke insuranceLimiter immediately when redis connection is not \"ready\"\n * }\n */\n constructor(opts) {\n super(opts);\n if (opts.redis) {\n this.client = opts.redis;\n } else {\n this.client = opts.storeClient;\n }\n\n this._rejectIfRedisNotReady = !!opts.rejectIfRedisNotReady;\n\n if (typeof this.client.defineCommand === 'function') {\n this.client.defineCommand(\"rlflxIncr\", {\n numberOfKeys: 1,\n lua: incrTtlLuaScript,\n });\n }\n }\n\n /**\n * Prevent actual redis call if redis connection is not ready\n * Because of different connection state checks for ioredis and node-redis, only this clients would be actually checked.\n * For any other clients all the requests would be passed directly to redis client\n * @return {boolean}\n * @private\n */\n _isRedisReady() {\n if (!this._rejectIfRedisNotReady) {\n return true;\n }\n // ioredis client\n if (this.client.status && this.client.status !== 'ready') {\n return false;\n }\n // node-redis client\n if (typeof this.client.isReady === 'function' && !this.client.isReady()) {\n return false;\n }\n return true;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n let [consumed, resTtlMs] = result;\n // Support ioredis results format\n if (Array.isArray(consumed)) {\n [, consumed] = consumed;\n [, resTtlMs] = resTtlMs;\n }\n\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(consumed);\n res.isFirstInDuration = res.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = resTtlMs;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n const secDuration = Math.floor(msDuration / 1000);\n const multi = this.client.multi();\n if (forceExpire) {\n if (secDuration > 0) {\n multi.set(rlKey, points, 'EX', secDuration);\n } else {\n multi.set(rlKey, points);\n }\n\n multi.pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n } else {\n if (secDuration > 0) {\n const incrCallback = function(err, result) {\n if (err) {\n return reject(err);\n }\n\n return resolve(result);\n };\n\n if (typeof this.client.rlflxIncr === 'function') {\n this.client.rlflxIncr(rlKey, points, secDuration, incrCallback);\n } else {\n this.client.eval(incrTtlLuaScript, 1, rlKey, points, secDuration, incrCallback);\n }\n } else {\n multi.incrby(rlKey, points)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n }\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n this.client\n .multi()\n .get(rlKey)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n reject(err);\n } else {\n const [points] = res;\n if (points === null) {\n return resolve(null)\n }\n\n resolve(res);\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res > 0);\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterRedis;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\n/**\n * Get MongoDB driver version as upsert options differ\n * @params {Object} Client instance\n * @returns {Object} Version Object containing major, feature & minor versions.\n */\nfunction getDriverVersion(client) {\n try {\n const _client = client.client ? client.client : client;\n\n const { version } = _client.topology.s.options.metadata.driver;\n const _v = version.split('.').map(v => parseInt(v));\n\n return {\n major: _v[0],\n feature: _v[1],\n patch: _v[2],\n };\n } catch (err) {\n return { major: 0, feature: 0, patch: 0 };\n }\n}\n\nclass RateLimiterMongo extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * indexKeyPrefix: {attr1: 1, attr2: 1}\n * ... see other in RateLimiterStoreAbstract\n *\n * mongo: MongoClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n this.indexKeyPrefix = opts.indexKeyPrefix;\n\n if (opts.mongo) {\n this.client = opts.mongo;\n } else {\n this.client = opts.storeClient;\n }\n if (typeof this.client.then === 'function') {\n // If Promise\n this.client\n .then((conn) => {\n this.client = conn;\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n });\n } else {\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n }\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? RateLimiterMongo.getDbName() : value;\n }\n\n static getDbName() {\n return 'node-rate-limiter-flexible';\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('mongo is not set');\n }\n this._client = value;\n }\n\n get indexKeyPrefix() {\n return this._indexKeyPrefix;\n }\n\n set indexKeyPrefix(obj) {\n this._indexKeyPrefix = obj || {};\n }\n\n _initCollection() {\n const db = typeof this.client.db === 'function'\n ? this.client.db(this.dbName)\n : this.client;\n\n const collection = db.collection(this.tableName);\n collection.createIndex({ expire: -1 }, { expireAfterSeconds: 0 });\n collection.createIndex(Object.assign({}, this.indexKeyPrefix, { key: 1 }), { unique: true });\n\n this._collection = collection;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n\n let doc;\n if (typeof result.value === 'undefined') {\n doc = result;\n } else {\n doc = result.value;\n }\n\n res.isFirstInDuration = doc.points === changedPoints;\n res.consumedPoints = doc.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = doc.expire !== null\n ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsert(key, points, msDuration, forceExpire = false, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n let where;\n let upsertData;\n if (forceExpire) {\n where = { key };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $set: {\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n };\n upsertData.$set = Object.assign(upsertData.$set, docAttrs);\n } else {\n where = {\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $setOnInsert: {\n key,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n $inc: { points },\n };\n upsertData.$setOnInsert = Object.assign(upsertData.$setOnInsert, docAttrs);\n }\n\n // Options for collection updates differ between driver versions\n const upsertOptions = {\n upsert: true,\n };\n if ((this._driverVersion.major >= 4) ||\n (this._driverVersion.major === 3 &&\n (this._driverVersion.feature >=7) || \n (this._driverVersion.feature >= 6 && \n this._driverVersion.patch >= 7 ))) \n {\n upsertOptions.returnDocument = 'after';\n } else {\n upsertOptions.returnOriginal = false;\n }\n\n /*\n * 1. Find actual limit and increment points\n * 2. If limit expired, but Mongo doesn't clean doc by TTL yet, try to replace limit doc completely\n * 3. If 2 or more Mongo threads try to insert the new limit doc, only the first succeed\n * 4. Try to upsert from step 1. Actual limit is created now, points are incremented without problems\n */\n return new Promise((resolve, reject) => {\n this._collection.findOneAndUpdate(\n where,\n upsertData,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errUpsert) => {\n if (errUpsert && errUpsert.code === 11000) { // E11000 duplicate key error collection\n const replaceWhere = Object.assign({ // try to replace OLD limit doc\n $or: [\n { expire: { $lte: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n }, docAttrs);\n\n const replaceTo = {\n $set: Object.assign({\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n }, docAttrs)\n };\n\n this._collection.findOneAndUpdate(\n replaceWhere,\n replaceTo,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errReplace) => {\n if (errReplace && errReplace.code === 11000) { // E11000 duplicate key error collection\n this._upsert(key, points, msDuration, forceExpire)\n .then(res => resolve(res))\n .catch(err => reject(err));\n } else {\n reject(errReplace);\n }\n });\n } else {\n reject(errUpsert);\n }\n });\n });\n }\n\n _get(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n const where = Object.assign({\n key: rlKey,\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n }, docAttrs);\n\n return this._collection.findOne(where);\n }\n\n _delete(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n const where = Object.assign({ key: rlKey }, docAttrs);\n\n return this._collection.deleteOne(where)\n .then(res => res.deletedCount > 0);\n }\n}\n\nmodule.exports = RateLimiterMongo;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMySQL extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: anySqlClient,\n * storeType: 'knex', // required only for Knex instance\n * dbName: 'string',\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createDbAndTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`DELETE FROM ??.?? WHERE expire < ?`, [this.dbName, this.tableName, expire], () => {\n this._releaseConnection(conn);\n resolve();\n });\n })\n .catch(() => {\n resolve();\n });\n });\n }\n\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return new Promise((resolve, reject) => {\n this.client.getConnection((errConn, conn) => {\n if (errConn) {\n return reject(errConn);\n }\n\n resolve(conn);\n });\n });\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return conn.release();\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createDbAndTable() {\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`CREATE DATABASE IF NOT EXISTS \\`${this.dbName}\\`;`, (errDb) => {\n if (errDb) {\n this._releaseConnection(conn);\n return reject(errDb);\n }\n conn.query(this._getCreateTableStmt(), (err) => {\n if (err) {\n this._releaseConnection(conn);\n return reject(err);\n }\n this._releaseConnection(conn);\n resolve();\n });\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS \\`${this.dbName}\\`.\\`${this.tableName}\\` (` +\n '`key` VARCHAR(255) CHARACTER SET utf8 NOT NULL,' +\n '`points` INT(9) NOT NULL default 0,' +\n '`expire` BIGINT UNSIGNED,' +\n 'PRIMARY KEY (`key`)' +\n ') ENGINE = INNODB;';\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n if (typeof value === 'undefined') {\n if (this.client.constructor.name === 'Connection') {\n value = 'connection';\n } else if (this.client.constructor.name === 'Pool') {\n value = 'pool';\n } else if (this.client.constructor.name === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n this._clientType = value.toLowerCase();\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? 'rtlmtrflx' : value;\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const [row] = result;\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsertTransaction(conn, key, points, msDuration, forceExpire) {\n return new Promise((resolve, reject) => {\n conn.query('BEGIN', (errBegin) => {\n if (errBegin) {\n conn.rollback();\n\n return reject(errBegin);\n }\n\n const dateNow = Date.now();\n const newExpire = msDuration > 0 ? dateNow + msDuration : null;\n\n let q;\n let values;\n if (forceExpire) {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = ?, \n expire = ?;`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n points,\n newExpire,\n ];\n } else {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = IF(expire <= ?, ?, points + (?)), \n expire = IF(expire <= ?, ?, expire);`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n dateNow, points, points,\n dateNow, newExpire,\n ];\n }\n\n conn.query(q, values, (errUpsert) => {\n if (errUpsert) {\n conn.rollback();\n\n return reject(errUpsert);\n }\n conn.query('SELECT points, expire FROM ??.?? WHERE `key` = ?;', [this.dbName, this.tableName, key], (errSelect, res) => {\n if (errSelect) {\n conn.rollback();\n\n return reject(errSelect);\n }\n\n conn.query('COMMIT', (err) => {\n if (err) {\n conn.rollback();\n\n return reject(err);\n }\n\n resolve(res);\n });\n });\n });\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n this._upsertTransaction(conn, key, points, msDuration, forceExpire)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)',\n [this.dbName, this.tableName, rlKey, Date.now()],\n (err, res) => {\n if (err) {\n reject(err);\n } else if (res.length === 0) {\n resolve(null);\n } else {\n resolve(res);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'DELETE FROM ??.?? WHERE `key` = ?',\n [this.dbName, this.tableName, rlKey],\n (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res.affectedRows > 0);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMySQL;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterPostgres extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: postgresClient,\n * storeType: 'knex', // required only for Knex instance\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n const q = {\n name: 'rlflx-clear-expired',\n text: `DELETE FROM ${this.tableName} WHERE expire < $1`,\n values: [expire],\n };\n this._query(q)\n .then(() => {\n resolve();\n })\n .catch(() => {\n // Deleting expired query is not critical\n resolve();\n });\n });\n }\n\n /**\n * Delete all rows expired 1 hour ago once per 5 minutes\n *\n * @private\n */\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return Promise.resolve(this.client);\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n case 'typeorm':\n return Promise.resolve(this.client.driver.master);\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return true;\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n case 'typeorm':\n return true;\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createTable() {\n return new Promise((resolve, reject) => {\n this._query({\n text: this._getCreateTableStmt(),\n })\n .then(() => {\n resolve();\n })\n .catch((err) => {\n if (err.code === '23505') {\n // Error: duplicate key value violates unique constraint \"pg_type_typname_nsp_index\"\n // Postgres doesn't handle concurrent table creation\n // It is supposed, that table is created by another worker\n resolve();\n } else {\n reject(err);\n }\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS ${this.tableName} ( \n key varchar(255) PRIMARY KEY,\n points integer NOT NULL DEFAULT 0,\n expire bigint\n );`;\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n const constructorName = this.client.constructor.name;\n\n if (typeof value === 'undefined') {\n if (constructorName === 'Client') {\n value = 'client';\n } else if (\n constructorName === 'Pool' ||\n constructorName === 'BoundPool'\n ) {\n value = 'pool';\n } else if (constructorName === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n\n this._clientType = value.toLowerCase();\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const row = result.rows[0];\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _query(q) {\n const prefix = this.tableName.toLowerCase();\n const queryObj = { name: `${prefix}:${q.name}`, text: q.text, values: q.values };\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(queryObj)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n const newExpire = msDuration > 0 ? Date.now() + msDuration : null;\n const expireQ = forceExpire\n ? ' $3 '\n : ` CASE\n WHEN ${this.tableName}.expire <= $4 THEN $3\n ELSE ${this.tableName}.expire\n END `;\n\n return this._query({\n name: forceExpire ? 'rlflx-upsert-force' : 'rlflx-upsert',\n text: `\n INSERT INTO ${this.tableName} VALUES ($1, $2, $3)\n ON CONFLICT(key) DO UPDATE SET\n points = CASE\n WHEN (${this.tableName}.expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2\n ELSE ${this.tableName}.points + ($2)\n END,\n expire = ${expireQ}\n RETURNING points, expire;`,\n values: [key, points, newExpire, Date.now()],\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._query({\n name: 'rlflx-get',\n text: `\n SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,\n values: [rlKey, Date.now()],\n })\n .then((res) => {\n if (res.rowCount === 0) {\n res = null;\n }\n resolve(res);\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return this._query({\n name: 'rlflx-delete',\n text: `DELETE FROM ${this.tableName} WHERE key = $1`,\n values: [rlKey],\n })\n .then(res => res.rowCount > 0);\n }\n}\n\nmodule.exports = RateLimiterPostgres;\n", "module.exports = class Record {\n /**\n *\n * @param value int\n * @param expiresAt Date|int\n * @param timeoutId\n */\n constructor(value, expiresAt, timeoutId = null) {\n this.value = value;\n this.expiresAt = expiresAt;\n this.timeoutId = timeoutId;\n }\n\n get value() {\n return this._value;\n }\n\n set value(value) {\n this._value = parseInt(value);\n }\n\n get expiresAt() {\n return this._expiresAt;\n }\n\n set expiresAt(value) {\n if (!(value instanceof Date) && Number.isInteger(value)) {\n value = new Date(value);\n }\n this._expiresAt = value;\n }\n\n get timeoutId() {\n return this._timeoutId;\n }\n\n set timeoutId(value) {\n this._timeoutId = value;\n }\n};\n", "const Record = require('./Record');\nconst RateLimiterRes = require('../../RateLimiterRes');\n\nmodule.exports = class MemoryStorage {\n constructor() {\n /**\n * @type {Object.}\n * @private\n */\n this._storage = {};\n }\n\n incrby(key, value, durationSec) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n if (msBeforeExpires !== 0) {\n // Change value\n this._storage[key].value = this._storage[key].value + value;\n\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n\n if (this._storage[key] && this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n\n this._storage[key] = new Record(\n value,\n durationMs > 0 ? new Date(Date.now() + durationMs) : null\n );\n if (durationMs > 0) {\n this._storage[key].timeoutId = setTimeout(() => {\n delete this._storage[key];\n }, durationMs);\n if (this._storage[key].timeoutId.unref) {\n this._storage[key].timeoutId.unref();\n }\n }\n\n return new RateLimiterRes(0, durationMs === 0 ? -1 : durationMs, this._storage[key].value, true);\n }\n\n /**\n *\n * @param key\n * @returns {*}\n */\n get(key) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n return null;\n }\n\n /**\n *\n * @param key\n * @returns {boolean}\n */\n delete(key) {\n if (this._storage[key]) {\n if (this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n delete this._storage[key];\n return true;\n }\n return false;\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst MemoryStorage = require('./component/MemoryStorage/MemoryStorage');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemory extends RateLimiterAbstract {\n constructor(opts = {}) {\n super(opts);\n\n this._memoryStorage = new MemoryStorage();\n }\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\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\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 reject(res);\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n });\n }\n\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\n\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\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\n this._memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, initPoints)\n );\n }\n\n set(key, points, secDuration) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n\n this._memoryStorage.set(this.getKey(key), points, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, points)\n );\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\n return Promise.resolve(res);\n }\n\n delete(key) {\n return Promise.resolve(this._memoryStorage.delete(this.getKey(key)));\n }\n}\n\nmodule.exports = RateLimiterMemory;\n\n", "/**\n * Implements rate limiting in cluster using built-in IPC\n *\n * Two classes are described here: master and worker\n * Master have to be create in the master process without any options.\n * Any number of rate limiters can be created in workers, but each rate limiter must be with unique keyPrefix\n *\n * Workflow:\n * 1. master rate limiter created in master process\n * 2. worker rate limiter sends 'init' message with necessary options during creating\n * 3. master receives options and adds new rate limiter by keyPrefix if it isn't created yet\n * 4. master sends 'init' back to worker's rate limiter\n * 5. worker can process requests immediately,\n * but they will be postponed by 'workerWaitInit' until master sends 'init' to worker\n * 6. every request to worker rate limiter creates a promise\n * 7. if master doesn't response for 'timeout', promise is rejected\n * 8. master sends 'resolve' or 'reject' command to worker\n * 9. worker resolves or rejects promise depending on message from master\n *\n */\n\nconst cluster = require('cluster');\nconst crypto = require('crypto');\nconst RateLimiterAbstract = require('./RateLimiterAbstract');\nconst RateLimiterMemory = require('./RateLimiterMemory');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst channel = 'rate_limiter_flexible';\nlet masterInstance = null;\n\nconst masterSendToWorker = function (worker, msg, type, res) {\n let data;\n if (res === null || res === true || res === false) {\n data = res;\n } else {\n data = {\n remainingPoints: res.remainingPoints,\n msBeforeNext: res.msBeforeNext,\n consumedPoints: res.consumedPoints,\n isFirstInDuration: res.isFirstInDuration,\n };\n }\n worker.send({\n channel,\n keyPrefix: msg.keyPrefix, // which rate limiter exactly\n promiseId: msg.promiseId,\n type,\n data,\n });\n};\n\nconst workerWaitInit = function (payload) {\n setTimeout(() => {\n if (this._initiated) {\n process.send(payload);\n // Promise will be removed by timeout if too long\n } else if (typeof this._promises[payload.promiseId] !== 'undefined') {\n workerWaitInit.call(this, payload);\n }\n }, 30);\n};\n\nconst workerSendToMaster = function (func, promiseId, key, arg, opts) {\n const payload = {\n channel,\n keyPrefix: this.keyPrefix,\n func,\n promiseId,\n data: {\n key,\n arg,\n opts,\n },\n };\n\n if (!this._initiated) {\n // Wait init before sending messages to master\n workerWaitInit.call(this, payload);\n } else {\n process.send(payload);\n }\n};\n\nconst masterProcessMsg = function (worker, msg) {\n if (!msg || msg.channel !== channel || typeof this._rateLimiters[msg.keyPrefix] === 'undefined') {\n return false;\n }\n\n let promise;\n\n switch (msg.func) {\n case 'consume':\n promise = this._rateLimiters[msg.keyPrefix].consume(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'penalty':\n promise = this._rateLimiters[msg.keyPrefix].penalty(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'reward':\n promise = this._rateLimiters[msg.keyPrefix].reward(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'block':\n promise = this._rateLimiters[msg.keyPrefix].block(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'get':\n promise = this._rateLimiters[msg.keyPrefix].get(msg.data.key, msg.data.opts);\n break;\n case 'delete':\n promise = this._rateLimiters[msg.keyPrefix].delete(msg.data.key, msg.data.opts);\n break;\n default:\n return false;\n }\n\n if (promise) {\n promise\n .then((res) => {\n masterSendToWorker(worker, msg, 'resolve', res);\n })\n .catch((rejRes) => {\n masterSendToWorker(worker, msg, 'reject', rejRes);\n });\n }\n};\n\nconst workerProcessMsg = function (msg) {\n if (!msg || msg.channel !== channel || msg.keyPrefix !== this.keyPrefix) {\n return false;\n }\n\n if (this._promises[msg.promiseId]) {\n clearTimeout(this._promises[msg.promiseId].timeoutId);\n let res;\n if (msg.data === null || msg.data === true || msg.data === false) {\n res = msg.data;\n } else {\n res = new RateLimiterRes(\n msg.data.remainingPoints,\n msg.data.msBeforeNext,\n msg.data.consumedPoints,\n msg.data.isFirstInDuration // eslint-disable-line comma-dangle\n );\n }\n\n switch (msg.type) {\n case 'resolve':\n this._promises[msg.promiseId].resolve(res);\n break;\n case 'reject':\n this._promises[msg.promiseId].reject(res);\n break;\n default:\n throw new Error(`RateLimiterCluster: no such message type '${msg.type}'`);\n }\n\n delete this._promises[msg.promiseId];\n }\n};\n/**\n * Prepare options to send to master\n * Master will create rate limiter depending on options\n *\n * @returns {{points: *, duration: *, blockDuration: *, execEvenly: *, execEvenlyMinDelayMs: *, keyPrefix: *}}\n */\nconst getOpts = function () {\n return {\n points: this.points,\n duration: this.duration,\n blockDuration: this.blockDuration,\n execEvenly: this.execEvenly,\n execEvenlyMinDelayMs: this.execEvenlyMinDelayMs,\n keyPrefix: this.keyPrefix,\n };\n};\n\nconst savePromise = function (resolve, reject) {\n const hrtime = process.hrtime();\n let promiseId = hrtime[0].toString() + hrtime[1].toString();\n\n if (typeof this._promises[promiseId] !== 'undefined') {\n promiseId += crypto.randomBytes(12).toString('base64');\n }\n\n this._promises[promiseId] = {\n resolve,\n reject,\n timeoutId: setTimeout(() => {\n delete this._promises[promiseId];\n reject(new Error('RateLimiterCluster timeout: no answer from master in time'));\n }, this.timeoutMs),\n };\n\n return promiseId;\n};\n\nclass RateLimiterClusterMaster {\n constructor() {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n cluster.setMaxListeners(0);\n\n cluster.on('message', (worker, msg) => {\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n worker.send({\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n });\n } else {\n masterProcessMsg.call(this, worker, msg);\n }\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterMasterPM2 {\n constructor(pm2) {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n pm2.launchBus((err, pm2Bus) => {\n pm2Bus.on('process:msg', (packet) => {\n const msg = packet.raw;\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n pm2.sendDataToProcessId(packet.process.pm_id, {\n data: {},\n topic: channel,\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n }, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n } else {\n const worker = {\n send: (msgData) => {\n const pm2Message = msgData;\n pm2Message.topic = channel;\n if (typeof pm2Message.data === 'undefined') {\n pm2Message.data = {};\n }\n pm2.sendDataToProcessId(packet.process.pm_id, pm2Message, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n },\n };\n masterProcessMsg.call(this, worker, msg);\n }\n });\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterWorker extends RateLimiterAbstract {\n get timeoutMs() {\n return this._timeoutMs;\n }\n\n set timeoutMs(value) {\n this._timeoutMs = typeof value === 'undefined' ? 5000 : Math.abs(parseInt(value));\n }\n\n constructor(opts = {}) {\n super(opts);\n\n process.setMaxListeners(0);\n\n this.timeoutMs = opts.timeoutMs;\n\n this._initiated = false;\n\n process.on('message', (msg) => {\n if (msg && msg.channel === channel && msg.type === 'init' && msg.keyPrefix === this.keyPrefix) {\n this._initiated = true;\n } else {\n workerProcessMsg.call(this, msg);\n }\n });\n\n // Create limiter on master with specific options\n process.send({\n channel,\n type: 'init',\n opts: getOpts.call(this),\n });\n\n this._promises = {};\n }\n\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'consume', promiseId, key, pointsToConsume, options);\n });\n }\n\n penalty(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'penalty', promiseId, key, points, options);\n });\n }\n\n reward(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'reward', promiseId, key, points, options);\n });\n }\n\n block(key, secDuration, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'block', promiseId, key, secDuration, options);\n });\n }\n\n get(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'get', promiseId, key, options);\n });\n }\n\n delete(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'delete', promiseId, key, options);\n });\n }\n}\n\nmodule.exports = {\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster: RateLimiterClusterWorker,\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemcache extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: memcacheClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.client = opts.storeClient;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(result.consumedPoints);\n res.isFirstInDuration = result.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = result.msBeforeNext;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n const secDuration = Math.floor(msDuration / 1000);\n\n if (forceExpire) {\n this.client.set(rlKey, points, secDuration, (err) => {\n if (!err) {\n this.client.set(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n } else {\n reject(err);\n }\n });\n } else {\n this.client.incr(rlKey, points, (err, consumedPoints) => {\n if (err || consumedPoints === false) {\n this.client.add(rlKey, points, secDuration, (errAddKey, createdNew) => {\n if (errAddKey || !createdNew) {\n // Try to upsert again in case of race condition\n if (typeof options.attemptNumber === 'undefined' || options.attemptNumber < 3) {\n const nextOptions = Object.assign({}, options);\n nextOptions.attemptNumber = nextOptions.attemptNumber ? (nextOptions.attemptNumber + 1) : 1;\n\n this._upsert(rlKey, points, msDuration, forceExpire, nextOptions)\n .then(resUpsert => resolve(resUpsert))\n .catch(errUpsert => reject(errUpsert));\n } else {\n reject(new Error('Can not add key'));\n }\n } else {\n this.client.add(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n }\n });\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n\n this.client.get(rlKey, (err, consumedPoints) => {\n if (!consumedPoints) {\n resolve(null);\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else if (res === false) {\n resolve(res);\n } else {\n this.client.del(`${rlKey}_expire`, (errDelExpire) => {\n if (errDelExpire) {\n reject(errDelExpire);\n } else {\n resolve(res);\n }\n });\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMemcache;\n", "const RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RLWrapperBlackAndWhite {\n constructor(opts = {}) {\n this.limiter = opts.limiter;\n this.blackList = opts.blackList;\n this.whiteList = opts.whiteList;\n this.isBlackListed = opts.isBlackListed;\n this.isWhiteListed = opts.isWhiteListed;\n this.runActionAnyway = opts.runActionAnyway;\n }\n\n get limiter() {\n return this._limiter;\n }\n\n set limiter(value) {\n if (typeof value === 'undefined') {\n throw new Error('limiter is not set');\n }\n\n this._limiter = value;\n }\n\n get runActionAnyway() {\n return this._runActionAnyway;\n }\n\n set runActionAnyway(value) {\n this._runActionAnyway = typeof value === 'undefined' ? false : value;\n }\n\n get blackList() {\n return this._blackList;\n }\n\n set blackList(value) {\n this._blackList = Array.isArray(value) ? value : [];\n }\n\n get isBlackListed() {\n return this._isBlackListed;\n }\n\n set isBlackListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isBlackListed must be function');\n }\n this._isBlackListed = func;\n }\n\n get whiteList() {\n return this._whiteList;\n }\n\n set whiteList(value) {\n this._whiteList = Array.isArray(value) ? value : [];\n }\n\n get isWhiteListed() {\n return this._isWhiteListed;\n }\n\n set isWhiteListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isWhiteListed must be function');\n }\n this._isWhiteListed = func;\n }\n\n isBlackListedSomewhere(key) {\n return this.blackList.indexOf(key) >= 0 || this.isBlackListed(key);\n }\n\n isWhiteListedSomewhere(key) {\n return this.whiteList.indexOf(key) >= 0 || this.isWhiteListed(key);\n }\n\n getBlackRes() {\n return new RateLimiterRes(0, Number.MAX_SAFE_INTEGER, 0, false);\n }\n\n getWhiteRes() {\n return new RateLimiterRes(Number.MAX_SAFE_INTEGER, 0, 0, false);\n }\n\n rejectBlack() {\n return Promise.reject(this.getBlackRes());\n }\n\n resolveBlack() {\n return Promise.resolve(this.getBlackRes());\n }\n\n resolveWhite() {\n return Promise.resolve(this.getWhiteRes());\n }\n\n consume(key, pointsToConsume = 1) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.rejectBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.consume(key, pointsToConsume);\n }\n\n if (this.runActionAnyway) {\n this.limiter.consume(key, pointsToConsume).catch(() => {});\n }\n return res;\n }\n\n block(key, secDuration) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.block(key, secDuration);\n }\n\n if (this.runActionAnyway) {\n this.limiter.block(key, secDuration).catch(() => {});\n }\n return res;\n }\n\n penalty(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.penalty(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.penalty(key, points).catch(() => {});\n }\n return res;\n }\n\n reward(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.reward(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.reward(key, points).catch(() => {});\n }\n return res;\n }\n\n get(key) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined' || this.runActionAnyway) {\n return this.limiter.get(key);\n }\n\n return res;\n }\n\n delete(key) {\n return this.limiter.delete(key);\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\n\nmodule.exports = class RateLimiterUnion {\n constructor(...limiters) {\n if (limiters.length < 1) {\n throw new Error('RateLimiterUnion: at least one limiter have to be passed');\n }\n limiters.forEach((limiter) => {\n if (!(limiter instanceof RateLimiterAbstract)) {\n throw new Error('RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract');\n }\n });\n\n this._limiters = limiters;\n }\n\n consume(key, points = 1) {\n return new Promise((resolve, reject) => {\n const promises = [];\n this._limiters.forEach((limiter) => {\n promises.push(limiter.consume(key, points).catch(rej => ({ rejected: true, rej })));\n });\n\n Promise.all(promises)\n .then((res) => {\n const resObj = {};\n let rejected = false;\n\n res.forEach((item) => {\n if (item.rejected === true) {\n rejected = true;\n }\n });\n\n for (let i = 0; i < res.length; i++) {\n if (rejected && res[i].rejected === true) {\n resObj[this._limiters[i].keyPrefix] = res[i].rej;\n } else if (!rejected) {\n resObj[this._limiters[i].keyPrefix] = res[i];\n }\n }\n\n if (rejected) {\n reject(resObj);\n } else {\n resolve(resObj);\n }\n });\n });\n }\n};\n", "module.exports = class RateLimiterQueueError extends Error {\n constructor(message, extra) {\n super();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = 'CustomError';\n this.message = message;\n if (extra) {\n this.extra = extra;\n }\n }\n};\n", "const RateLimiterQueueError = require('./component/RateLimiterQueueError')\nconst MAX_QUEUE_SIZE = 4294967295;\nconst KEY_DEFAULT = 'limiter';\n\nmodule.exports = class RateLimiterQueue {\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n }) {\n this._queueLimiters = {\n KEY_DEFAULT: new RateLimiterQueueInternal(limiterFlexible, opts)\n };\n this._limiterFlexible = limiterFlexible;\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining(key = KEY_DEFAULT) {\n if (this._queueLimiters[key]) {\n return this._queueLimiters[key].getTokensRemaining()\n } else {\n return Promise.resolve(this._limiterFlexible.points)\n }\n }\n\n removeTokens(tokens, key = KEY_DEFAULT) {\n if (!this._queueLimiters[key]) {\n this._queueLimiters[key] = new RateLimiterQueueInternal(\n this._limiterFlexible, {\n key,\n maxQueueSize: this._maxQueueSize,\n })\n }\n\n return this._queueLimiters[key].removeTokens(tokens)\n }\n};\n\nclass RateLimiterQueueInternal {\n\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n key: KEY_DEFAULT,\n }) {\n this._key = opts.key;\n this._waitTimeout = null;\n this._queue = [];\n this._limiterFlexible = limiterFlexible;\n\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining() {\n return this._limiterFlexible.get(this._key)\n .then((rlRes) => {\n return rlRes !== null ? rlRes.remainingPoints : this._limiterFlexible.points;\n })\n }\n\n removeTokens(tokens) {\n const _this = this;\n\n return new Promise((resolve, reject) => {\n if (tokens > _this._limiterFlexible.points) {\n reject(new RateLimiterQueueError(`Requested tokens ${tokens} exceeds maximum ${_this._limiterFlexible.points} tokens per interval`));\n return\n }\n\n if (_this._queue.length > 0) {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n } else {\n _this._limiterFlexible.consume(_this._key, tokens)\n .then((res) => {\n resolve(res.remainingPoints);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n reject(rej);\n } else {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n })\n }\n\n _queueRequest(resolve, reject, tokens) {\n const _this = this;\n if (_this._queue.length < _this._maxQueueSize) {\n _this._queue.push({resolve, reject, tokens});\n } else {\n reject(new RateLimiterQueueError(`Number of requests reached it's maximum ${_this._maxQueueSize}`))\n }\n }\n\n _processFIFO() {\n const _this = this;\n\n if (_this._waitTimeout !== null) {\n clearTimeout(_this._waitTimeout);\n _this._waitTimeout = null;\n }\n\n if (_this._queue.length === 0) {\n return;\n }\n\n const item = _this._queue.shift();\n _this._limiterFlexible.consume(_this._key, item.tokens)\n .then((res) => {\n item.resolve(res.remainingPoints);\n _this._processFIFO.call(_this);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n item.reject(rej);\n _this._processFIFO.call(_this);\n } else {\n _this._queue.unshift(item);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n}\n", "const RateLimiterRes = require(\"./RateLimiterRes\");\n\n/**\n * Bursty rate limiter exposes only msBeforeNext time and doesn't expose points from bursty limiter by default\n * @type {BurstyRateLimiter}\n */\nmodule.exports = class BurstyRateLimiter {\n constructor(rateLimiter, burstLimiter) {\n this._rateLimiter = rateLimiter;\n this._burstLimiter = burstLimiter\n }\n\n /**\n * Merge rate limiter response objects. Responses can be null\n *\n * @param {RateLimiterRes} [rlRes] Rate limiter response\n * @param {RateLimiterRes} [blRes] Bursty limiter response\n */\n _combineRes(rlRes, blRes) {\n return new RateLimiterRes(\n rlRes.remainingPoints,\n Math.min(rlRes.msBeforeNext, blRes.msBeforeNext),\n rlRes.consumedPoints,\n rlRes.isFirstInDuration\n )\n }\n\n /**\n * @param key\n * @param pointsToConsume\n * @param options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return this._rateLimiter.consume(key, pointsToConsume, options)\n .catch((rlRej) => {\n if (rlRej instanceof RateLimiterRes) {\n return this._burstLimiter.consume(key, pointsToConsume, options)\n .then((blRes) => {\n return Promise.resolve(this._combineRes(rlRej, blRes))\n })\n .catch((blRej) => {\n if (blRej instanceof RateLimiterRes) {\n return Promise.reject(this._combineRes(rlRej, blRej))\n } else {\n return Promise.reject(blRej)\n }\n }\n )\n } else {\n return Promise.reject(rlRej)\n }\n })\n }\n\n /**\n * It doesn't expose available points from burstLimiter\n *\n * @param key\n * @returns {Promise}\n */\n get(key) {\n return Promise.all([\n this._rateLimiter.get(key),\n this._burstLimiter.get(key),\n ]).then(([rlRes, blRes]) => {\n return this._combineRes(rlRes, blRes);\n });\n }\n\n get points() {\n return this._rateLimiter.points;\n }\n};\n", "const RateLimiterRedis = require('./lib/RateLimiterRedis');\nconst RateLimiterMongo = require('./lib/RateLimiterMongo');\nconst RateLimiterMySQL = require('./lib/RateLimiterMySQL');\nconst RateLimiterPostgres = require('./lib/RateLimiterPostgres');\nconst {RateLimiterClusterMaster, RateLimiterClusterMasterPM2, RateLimiterCluster} = require('./lib/RateLimiterCluster');\nconst RateLimiterMemory = require('./lib/RateLimiterMemory');\nconst RateLimiterMemcache = require('./lib/RateLimiterMemcache');\nconst RLWrapperBlackAndWhite = require('./lib/RLWrapperBlackAndWhite');\nconst RateLimiterUnion = require('./lib/RateLimiterUnion');\nconst RateLimiterQueue = require('./lib/RateLimiterQueue');\nconst BurstyRateLimiter = require('./lib/BurstyRateLimiter');\nconst RateLimiterRes = require('./lib/RateLimiterRes');\n\nmodule.exports = {\n RateLimiterRedis,\n RateLimiterMongo,\n RateLimiterMySQL,\n RateLimiterPostgres,\n RateLimiterMemory,\n RateLimiterMemcache,\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster,\n RLWrapperBlackAndWhite,\n RateLimiterUnion,\n RateLimiterQueue,\n BurstyRateLimiter,\n RateLimiterRes,\n};\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", "(function (root) {\n 'use strict';\n // A list of regular expressions that match arbitrary IPv4 addresses,\n // for which a number of weird notations exist.\n // Note that an address like 0010.0xa5.1.1 is considered legal.\n const ipv4Part = '(0?\\\\d+|0x[a-f0-9]+)';\n const ipv4Regexes = {\n fourOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n threeOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n twoOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n longValue: new RegExp(`^${ipv4Part}$`, 'i')\n };\n\n // Regular Expression for checking Octal numbers\n const octalRegex = new RegExp(`^0[0-7]+$`, 'i');\n const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');\n\n const zoneIndex = '%[0-9a-z]{1,}';\n\n // IPv6-matching regular expressions.\n // For IPv6, the task is simpler: it is enough to match the colon-delimited\n // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at\n // the end.\n const ipv6Part = '(?:[0-9a-f]+::?)+';\n const ipv6Regexes = {\n zoneIndex: new RegExp(zoneIndex, 'i'),\n 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),\n deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),\n transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?$`, 'i')\n };\n\n // Expand :: in an IPv6 address or address part consisting of `parts` groups.\n function expandIPv6 (string, parts) {\n // More than one '::' means invalid adddress\n if (string.indexOf('::') !== string.lastIndexOf('::')) {\n return null;\n }\n\n let colonCount = 0;\n let lastColon = -1;\n let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];\n let replacement, replacementCount;\n\n // Remove zone index and save it for later\n if (zoneId) {\n zoneId = zoneId.substring(1);\n string = string.replace(/%.+$/, '');\n }\n\n // How many parts do we already have?\n while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {\n colonCount++;\n }\n\n // 0::0 is two parts more than ::\n if (string.substr(0, 2) === '::') {\n colonCount--;\n }\n\n if (string.substr(-2, 2) === '::') {\n colonCount--;\n }\n\n // The following loop would hang if colonCount > parts\n if (colonCount > parts) {\n return null;\n }\n\n // replacement = ':' + '0:' * (parts - colonCount)\n replacementCount = parts - colonCount;\n replacement = ':';\n while (replacementCount--) {\n replacement += '0:';\n }\n\n // Insert the missing zeroes\n string = string.replace('::', replacement);\n\n // Trim any garbage which may be hanging around if :: was at the edge in\n // the source strin\n if (string[0] === ':') {\n string = string.slice(1);\n }\n\n if (string[string.length - 1] === ':') {\n string = string.slice(0, -1);\n }\n\n parts = (function () {\n const ref = string.split(':');\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n results.push(parseInt(ref[i], 16));\n }\n\n return results;\n })();\n\n return {\n parts: parts,\n zoneId: zoneId\n };\n }\n\n // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.\n function matchCIDR (first, second, partSize, cidrBits) {\n if (first.length !== second.length) {\n throw new Error('ipaddr: cannot match CIDR for objects with different lengths');\n }\n\n let part = 0;\n let shift;\n\n while (cidrBits > 0) {\n shift = partSize - cidrBits;\n if (shift < 0) {\n shift = 0;\n }\n\n if (first[part] >> shift !== second[part] >> shift) {\n return false;\n }\n\n cidrBits -= partSize;\n part += 1;\n }\n\n return true;\n }\n\n function parseIntAuto (string) {\n // Hexadedimal base 16 (0x#)\n if (hexRegex.test(string)) {\n return parseInt(string, 16);\n }\n // While octal representation is discouraged by ECMAScript 3\n // and forbidden by ECMAScript 5, we silently allow it to\n // work only if the rest of the string has numbers less than 8.\n if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {\n if (octalRegex.test(string)) {\n return parseInt(string, 8);\n }\n throw new Error(`ipaddr: cannot parse ${string} as octal`);\n }\n // Always include the base 10 radix!\n return parseInt(string, 10);\n }\n\n function padPart (part, length) {\n while (part.length < length) {\n part = `0${part}`;\n }\n\n return part;\n }\n\n const ipaddr = {};\n\n // An IPv4 address (RFC791).\n ipaddr.IPv4 = (function () {\n // Constructs a new IPv4 address from an array of four octets\n // in network order (MSB first)\n // Verifies the input.\n function IPv4 (octets) {\n if (octets.length !== 4) {\n throw new Error('ipaddr: ipv4 octet count should be 4');\n }\n\n let i, octet;\n\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n throw new Error('ipaddr: ipv4 octet should fit in 8 bits');\n }\n }\n\n this.octets = octets;\n }\n\n // Special IPv4 address ranges.\n // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses\n IPv4.prototype.SpecialRanges = {\n unspecified: [[new IPv4([0, 0, 0, 0]), 8]],\n broadcast: [[new IPv4([255, 255, 255, 255]), 32]],\n // RFC3171\n multicast: [[new IPv4([224, 0, 0, 0]), 4]],\n // RFC3927\n linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],\n // RFC5735\n loopback: [[new IPv4([127, 0, 0, 0]), 8]],\n // RFC6598\n carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],\n // RFC1918\n 'private': [\n [new IPv4([10, 0, 0, 0]), 8],\n [new IPv4([172, 16, 0, 0]), 12],\n [new IPv4([192, 168, 0, 0]), 16]\n ],\n // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700\n reserved: [\n [new IPv4([192, 0, 0, 0]), 24],\n [new IPv4([192, 0, 2, 0]), 24],\n [new IPv4([192, 88, 99, 0]), 24],\n [new IPv4([198, 51, 100, 0]), 24],\n [new IPv4([203, 0, 113, 0]), 24],\n [new IPv4([240, 0, 0, 0]), 4]\n ]\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv4.prototype.kind = function () {\n return 'ipv4';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv4.prototype.match = function (other, cidrRange) {\n let ref;\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv4') {\n throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');\n }\n\n return matchCIDR(this.octets, other.octets, 8, cidrRange);\n };\n\n // returns a number of leading ones in IPv4 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv4.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 8,\n 128: 7,\n 192: 6,\n 224: 5,\n 240: 4,\n 248: 3,\n 252: 2,\n 254: 1,\n 255: 0\n };\n let i, octet, zeros;\n\n for (i = 3; i >= 0; i -= 1) {\n octet = this.octets[i];\n if (octet in zerotable) {\n zeros = zerotable[octet];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 8) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 32 - cidr;\n };\n\n // Checks if the address corresponds to one of the special ranges.\n IPv4.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv4.prototype.toByteArray = function () {\n return this.octets.slice(0);\n };\n\n // Converts this IPv4 address to an IPv4-mapped IPv6 address.\n IPv4.prototype.toIPv4MappedAddress = function () {\n return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);\n };\n\n // Symmetrical method strictly for aligning with the IPv6 methods.\n IPv4.prototype.toNormalizedString = function () {\n return this.toString();\n };\n\n // Returns the address in convenient, decimal-dotted format.\n IPv4.prototype.toString = function () {\n return this.octets.join('.');\n };\n\n return IPv4;\n })();\n\n // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {\n\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 4) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Checks if a given string is formatted like IPv4 address.\n ipaddr.IPv4.isIPv4 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks if a given string is a valid IPv4 address.\n ipaddr.IPv4.isValid = function (string) {\n try {\n new this(this.parser(string));\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address.\n ipaddr.IPv4.isValidFourPartDecimal = function (string) {\n if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){3}$/)) {\n return true;\n } else {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 4) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Tries to parse and validate a string with IPv4 address.\n // Throws an error if it fails.\n ipaddr.IPv4.parse = function (string) {\n const parts = this.parser(string);\n\n if (parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv4 Address');\n }\n\n return new this(parts);\n };\n\n // Parses the string as an IPv4 Address with CIDR Notation.\n ipaddr.IPv4.parseCIDR = function (string) {\n let match;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n const maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 32) {\n const parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');\n };\n\n // Classful variants (like a.b, where a is an octet, and b is a 24-bit\n // value representing last three octets; this corresponds to a class C\n // address) are omitted due to classless nature of modern Internet.\n ipaddr.IPv4.parser = function (string) {\n let match, part, value;\n\n // parseInt recognizes all that octal & hexadecimal weirdness for us\n if ((match = string.match(ipv4Regexes.fourOctet))) {\n return (function () {\n const ref = match.slice(1, 6);\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n results.push(parseIntAuto(part));\n }\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.longValue))) {\n value = parseIntAuto(match[1]);\n if (value > 0xffffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n return ((function () {\n const results = [];\n let shift;\n\n for (shift = 0; shift <= 24; shift += 8) {\n results.push((value >> shift) & 0xff);\n }\n\n return results;\n })()).reverse();\n } else if ((match = string.match(ipv4Regexes.twoOctet))) {\n return (function () {\n const ref = match.slice(1, 4);\n const results = [];\n\n value = parseIntAuto(ref[1]);\n if (value > 0xffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push((value >> 16) & 0xff);\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.threeOctet))) {\n return (function () {\n const ref = match.slice(1, 5);\n const results = [];\n\n value = parseIntAuto(ref[2]);\n if (value > 0xffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push(parseIntAuto(ref[1]));\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else {\n return null;\n }\n };\n\n // A utility function to return subnet mask in IPv4 format given the prefix length\n ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 32) {\n throw new Error('ipaddr: invalid IPv4 prefix length');\n }\n\n const octets = [0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 4) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // An IPv6 address (RFC2460)\n ipaddr.IPv6 = (function () {\n // Constructs an IPv6 address from an array of eight 16 - bit parts\n // or sixteen 8 - bit parts in network order(MSB first).\n // Throws an error if the input is invalid.\n function IPv6 (parts, zoneId) {\n let i, part;\n\n if (parts.length === 16) {\n this.parts = [];\n for (i = 0; i <= 14; i += 2) {\n this.parts.push((parts[i] << 8) | parts[i + 1]);\n }\n } else if (parts.length === 8) {\n this.parts = parts;\n } else {\n throw new Error('ipaddr: ipv6 part count should be 8 or 16');\n }\n\n for (i = 0; i < this.parts.length; i++) {\n part = this.parts[i];\n if (!((0 <= part && part <= 0xffff))) {\n throw new Error('ipaddr: ipv6 part should fit in 16 bits');\n }\n }\n\n if (zoneId) {\n this.zoneId = zoneId;\n }\n }\n\n // Special IPv6 ranges\n IPv6.prototype.SpecialRanges = {\n // RFC4291, here and after\n unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],\n linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],\n multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],\n loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],\n uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],\n ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],\n // RFC6145\n rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],\n // RFC6052\n rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],\n // RFC3056\n '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],\n // RFC6052, RFC6146\n teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],\n // RFC4291\n reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]\n };\n\n // Checks if this address is an IPv4-mapped IPv6 address.\n IPv6.prototype.isIPv4MappedAddress = function () {\n return this.range() === 'ipv4Mapped';\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv6.prototype.kind = function () {\n return 'ipv6';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv6.prototype.match = function (other, cidrRange) {\n let ref;\n\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv6') {\n throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');\n }\n\n return matchCIDR(this.parts, other.parts, 16, cidrRange);\n };\n\n // returns a number of leading ones in IPv6 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv6.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 16,\n 32768: 15,\n 49152: 14,\n 57344: 13,\n 61440: 12,\n 63488: 11,\n 64512: 10,\n 65024: 9,\n 65280: 8,\n 65408: 7,\n 65472: 6,\n 65504: 5,\n 65520: 4,\n 65528: 3,\n 65532: 2,\n 65534: 1,\n 65535: 0\n };\n let part, zeros;\n\n for (let i = 7; i >= 0; i -= 1) {\n part = this.parts[i];\n if (part in zerotable) {\n zeros = zerotable[part];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 16) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 128 - cidr;\n };\n\n\n // Checks if the address corresponds to one of the special ranges.\n IPv6.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv6.prototype.toByteArray = function () {\n let part;\n const bytes = [];\n const ref = this.parts;\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n bytes.push(part >> 8);\n bytes.push(part & 0xff);\n }\n\n return bytes;\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:0db8:0008:0066:0000:0000:0000:0001\n IPv6.prototype.toFixedLengthString = function () {\n const addr = ((function () {\n const results = [];\n for (let i = 0; i < this.parts.length; i++) {\n results.push(padPart(this.parts[i].toString(16), 4));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.\n // Throws an error otherwise.\n IPv6.prototype.toIPv4Address = function () {\n if (!this.isIPv4MappedAddress()) {\n throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');\n }\n\n const ref = this.parts.slice(-2);\n const high = ref[0];\n const low = ref[1];\n\n return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:db8:8:66:0:0:0:1\n //\n // Deprecated: use toFixedLengthString() instead.\n IPv6.prototype.toNormalizedString = function () {\n const addr = ((function () {\n const results = [];\n\n for (let i = 0; i < this.parts.length; i++) {\n results.push(this.parts[i].toString(16));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)\n IPv6.prototype.toRFC5952String = function () {\n const regex = /((^|:)(0(:|$)){2,})/g;\n const string = this.toNormalizedString();\n let bestMatchIndex = 0;\n let bestMatchLength = -1;\n let match;\n\n while ((match = regex.exec(string))) {\n if (match[0].length > bestMatchLength) {\n bestMatchIndex = match.index;\n bestMatchLength = match[0].length;\n }\n }\n\n if (bestMatchLength < 0) {\n return string;\n }\n\n return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n //\n // Deprecated: use toRFC5952String() instead.\n IPv6.prototype.toString = function () {\n // Replace the first sequence of 1 or more '0' parts with '::'\n return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::');\n };\n\n return IPv6;\n\n })();\n\n // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 16) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Checks if a given string is formatted like IPv6 address.\n ipaddr.IPv6.isIPv6 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks to see if string is a valid IPv6 Address\n ipaddr.IPv6.isValid = function (string) {\n\n // Since IPv6.isValid is always called first, this shortcut\n // provides a substantial performance gain.\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n const addr = this.parser(string);\n new this(addr.parts, addr.zoneId);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 16) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Tries to parse and validate a string with IPv6 address.\n // Throws an error if it fails.\n ipaddr.IPv6.parse = function (string) {\n const addr = this.parser(string);\n\n if (addr.parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv6 Address');\n }\n\n return new this(addr.parts, addr.zoneId);\n };\n\n ipaddr.IPv6.parseCIDR = function (string) {\n let maskLength, match, parsed;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 128) {\n parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');\n };\n\n // Parse an IPv6 address.\n ipaddr.IPv6.parser = function (string) {\n let addr, i, match, octet, octets, zoneId;\n\n if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {\n return this.parser(`::ffff:${match[1]}`);\n }\n if (ipv6Regexes.native.test(string)) {\n return expandIPv6(string, 8);\n }\n if ((match = string.match(ipv6Regexes.transitional))) {\n zoneId = match[6] || '';\n addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);\n if (addr.parts) {\n octets = [\n parseInt(match[2]),\n parseInt(match[3]),\n parseInt(match[4]),\n parseInt(match[5])\n ];\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n return null;\n }\n }\n\n addr.parts.push(octets[0] << 8 | octets[1]);\n addr.parts.push(octets[2] << 8 | octets[3]);\n return {\n parts: addr.parts,\n zoneId: addr.zoneId\n };\n }\n }\n\n return null;\n };\n\n // A utility function to return subnet mask in IPv6 format given the prefix length\n ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 128) {\n throw new Error('ipaddr: invalid IPv6 prefix length');\n }\n\n const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 16) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // Try to parse an array in network order (MSB first) for IPv4 and IPv6\n ipaddr.fromByteArray = function (bytes) {\n const length = bytes.length;\n\n if (length === 4) {\n return new ipaddr.IPv4(bytes);\n } else if (length === 16) {\n return new ipaddr.IPv6(bytes);\n } else {\n throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');\n }\n };\n\n // Checks if the address is valid IP address\n ipaddr.isValid = function (string) {\n return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);\n };\n\n\n // Attempts to parse an IP Address, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parse = function (string) {\n if (ipaddr.IPv6.isValid(string)) {\n return ipaddr.IPv6.parse(string);\n } else if (ipaddr.IPv4.isValid(string)) {\n return ipaddr.IPv4.parse(string);\n } else {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');\n }\n };\n\n // Attempt to parse CIDR notation, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parseCIDR = function (string) {\n try {\n return ipaddr.IPv6.parseCIDR(string);\n } catch (e) {\n try {\n return ipaddr.IPv4.parseCIDR(string);\n } catch (e2) {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');\n }\n }\n };\n\n // Parse an address and return plain IPv4 address if it is an IPv4-mapped address\n ipaddr.process = function (string) {\n const addr = this.parse(string);\n\n if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {\n return addr.toIPv4Address();\n } else {\n return addr;\n }\n };\n\n // An utility function to ease named range matching. See examples below.\n // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors\n // on matching IPv4 addresses to IPv6 ranges or vice versa.\n ipaddr.subnetMatch = function (address, rangeList, defaultName) {\n let i, rangeName, rangeSubnets, subnet;\n\n if (defaultName === undefined || defaultName === null) {\n defaultName = 'unicast';\n }\n\n for (rangeName in rangeList) {\n if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {\n rangeSubnets = rangeList[rangeName];\n // ECMA5 Array.isArray isn't available everywhere\n if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {\n rangeSubnets = [rangeSubnets];\n }\n\n for (i = 0; i < rangeSubnets.length; i++) {\n subnet = rangeSubnets[i];\n if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {\n return rangeName;\n }\n }\n }\n }\n\n return defaultName;\n };\n\n // Export for both the CommonJS and browser-like environment\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = ipaddr;\n\n } else {\n root.ipaddr = ipaddr;\n }\n\n}(this));\n", "'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function truncate(getLength, string, byteLength) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var curByteLength = 0;\n var codePoint;\n var segment;\n\n for (var i = 0; i < charLength; i += 1) {\n codePoint = string.charCodeAt(i);\n segment = string[i];\n\n if (isHighSurrogate(codePoint) && isLowSurrogate(string.charCodeAt(i + 1))) {\n i += 1;\n segment += string[i];\n }\n\n curByteLength += getLength(segment);\n\n if (curByteLength === byteLength) {\n return string.slice(0, i + 1);\n }\n else if (curByteLength > byteLength) {\n return string.slice(0, i - segment.length + 1);\n }\n }\n\n return string;\n};\n\n", "'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function getByteLength(string) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var byteLength = 0;\n var codePoint = null;\n var prevCodePoint = null;\n for (var i = 0; i < charLength; i++) {\n codePoint = string.charCodeAt(i);\n // handle 4-byte non-BMP chars\n // low surrogate\n if (isLowSurrogate(codePoint)) {\n // when parsing previous hi-surrogate, 3 is added to byteLength\n if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) {\n byteLength += 1;\n }\n else {\n byteLength += 3;\n }\n }\n else if (codePoint <= 0x7f ) {\n byteLength += 1;\n }\n else if (codePoint >= 0x80 && codePoint <= 0x7ff) {\n byteLength += 2;\n }\n else if (codePoint >= 0x800 && codePoint <= 0xffff) {\n byteLength += 3;\n }\n prevCodePoint = codePoint;\n }\n\n return byteLength;\n};\n", "'use strict';\n\nvar truncate = require(\"./lib/truncate\");\nvar getLength = require(\"utf8-byte-length/browser\");\nmodule.exports = truncate.bind(null, getLength);\n", "/*jshint node:true*/\n'use strict';\n\n/**\n * Replaces characters in strings that are illegal/unsafe for filenames.\n * Unsafe characters are either removed or replaced by a substitute set\n * in the optional `options` object.\n *\n * Illegal Characters on Various Operating Systems\n * / ? < > \\ : * | \"\n * https://kb.acronis.com/content/39790\n *\n * Unicode Control codes\n * C0 0x00-0x1f & C1 (0x80-0x9f)\n * http://en.wikipedia.org/wiki/C0_and_C1_control_codes\n *\n * Reserved filenames on Unix-based systems (\".\", \"..\")\n * Reserved filenames in Windows (\"CON\", \"PRN\", \"AUX\", \"NUL\", \"COM1\",\n * \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\",\n * \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", and\n * \"LPT9\") case-insesitively and with or without filename extensions.\n *\n * Capped at 255 characters in length.\n * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs\n *\n * @param {String} input Original filename\n * @param {Object} options {replacement: String | Function }\n * @return {String} Sanitized filename\n */\n\nvar truncate = require(\"truncate-utf8-bytes\");\n\nvar illegalRe = /[\\/\\?<>\\\\:\\*\\|\"]/g;\nvar controlRe = /[\\x00-\\x1f\\x80-\\x9f]/g;\nvar reservedRe = /^\\.+$/;\nvar windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i;\nvar windowsTrailingRe = /[\\. ]+$/;\n\nfunction sanitize(input, replacement) {\n if (typeof input !== 'string') {\n throw new Error('Input must be string');\n }\n var sanitized = input\n .replace(illegalRe, replacement)\n .replace(controlRe, replacement)\n .replace(reservedRe, replacement)\n .replace(windowsReservedRe, replacement)\n .replace(windowsTrailingRe, replacement);\n return truncate(sanitized, 255);\n}\n\nmodule.exports = function (input, options) {\n var replacement = (options && options.replacement) || '';\n var output = sanitize(input, replacement);\n if (replacement === '') {\n return output;\n }\n return sanitize(output, '');\n};\n", "/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter',\n optional: true\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n", "/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n", "/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n", "/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n", "/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Create signature digest for OID.\n *\n * @param options\n * signatureOid: the OID specifying the signature algorithm.\n * type: a human readable type for error messages\n * @return a created md instance. throws if unknown oid.\n */\nvar _createSignatureDigest = function(options) {\n switch(oids[options.signatureOid]) {\n case 'sha1WithRSAEncryption':\n // deprecated alias\n case 'sha1WithRSASignature':\n return forge.md.sha1.create();\n case 'md5WithRSAEncryption':\n return forge.md.md5.create();\n case 'sha256WithRSAEncryption':\n return forge.md.sha256.create();\n case 'sha384WithRSAEncryption':\n return forge.md.sha384.create();\n case 'sha512WithRSAEncryption':\n return forge.md.sha512.create();\n case 'RSASSA-PSS':\n return forge.md.sha256.create();\n default:\n var error = new Error(\n 'Could not compute ' + options.type + ' digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = options.signatureOid;\n throw error;\n }\n};\n\n/**\n * Verify signature on certificate or CSR.\n *\n * @param options:\n * certificate the certificate or CSR to verify.\n * md the signature digest.\n * signature the signature\n * @return a created md instance. throws if unknown oid.\n */\nvar _verifySignature = function(options) {\n var cert = options.certificate;\n var scheme;\n\n switch(cert.signatureOid) {\n case oids.sha1WithRSAEncryption:\n // deprecated alias\n case oids.sha1WithRSASignature:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = cert.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[cert.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = cert.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[cert.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = cert.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(\n forge.md[hash].create(), mgf, cert.signatureParameters.saltLength\n );\n break;\n }\n\n // verify signature on cert using public key\n return cert.publicKey.verify(\n options.md.digest().getBytes(), options.signature, scheme\n );\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = subject.attributes;\n error.actualIssuer = issuer.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // create digest for OID signature types\n md = _createSignatureDigest({\n signatureOid: child.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: cert, md: md, signature: child.signature\n });\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // create digest for OID signature type\n cert.md = _createSignatureDigest({\n signatureOid: cert.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n var ibytes = asn1.toDer(capture.certIssuer);\n imd.update(ibytes.getBytes());\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n var sbytes = asn1.toDer(capture.certSubject);\n smd.update(sbytes.getBytes());\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // create digest for OID signature type\n csr.md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: csr, md: md, signature: csr.signature\n });\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n", "/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter ? capture.encParameter.value : undefined,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n !ec.parameter ?\n undefined :\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n", "'use strict'\n\nmodule.exports = Receptacle\nvar toMS = require('ms')\nvar cache = Receptacle.prototype\nvar counter = new Date() % 1e9\n\nfunction getUID () { return (Math.random() * 1e9 >>> 0) + (counter++) }\n\n/**\n * Creates a cache with a maximum key size.\n *\n * @constructor\n * @param {Object} options\n * @param {Number} [options.max=Infinity] the maximum number of keys allowed in the cache (lru).\n * @param {Array} [options.items=[]] the default items in the cache.\n */\nfunction Receptacle (options) {\n options = options || {}\n this.id = options.id || getUID()\n this.max = options.max || Infinity\n this.items = options.items || []\n this._lookup = {}\n this.size = this.items.length\n this.lastModified = new Date(options.lastModified || new Date())\n\n // Setup initial timers and indexes for the cache.\n for (var item, ttl, i = this.items.length; i--;) {\n item = this.items[i]\n ttl = new Date(item.expires) - new Date()\n this._lookup[item.key] = item\n if (ttl > 0) this.expire(item.key, ttl)\n else if (ttl <= 0) this.delete(item.key)\n }\n}\n\n/**\n * Tests if a key is currently in the cache.\n * Does not check if slot is empty.\n *\n * @param {String} key - the key to retrieve from the cache.\n * @return {Boolean}\n */\ncache.has = function (key) {\n return key in this._lookup\n}\n\n/**\n * Retrieves a key from the cache and marks it as recently used.\n *\n * @param {String} key - the key to retrieve from the cache.\n * @return {*}\n */\ncache.get = function (key) {\n if (!this.has(key)) return null\n var record = this._lookup[key]\n // Update expiry for \"refresh\" keys\n if (record.refresh) this.expire(key, record.refresh)\n // Move to front of the line.\n this.items.splice(this.items.indexOf(record), 1)\n this.items.push(record)\n return record.value\n}\n\n/**\n * Retrieves user meta data for a cached item.\n *\n * @param {String} key - the key to retrieve meta data from the cache.\n * @return {*}\n */\ncache.meta = function (key) {\n if (!this.has(key)) return null\n var record = this._lookup[key]\n if (!('meta' in record)) return null\n return record.meta\n}\n\n/**\n * Puts a key into the cache with an optional expiry time.\n *\n * @param {String} key - the key for the value in the cache.\n * @param {*} value - the value to place at the key.\n * @param {Number} [options.ttl] - a time after which the key will be removed.\n * @return {Receptacle}\n */\ncache.set = function (key, value, options) {\n var oldRecord = this._lookup[key]\n var record = this._lookup[key] = { key: key, value: value }\n // Mark cache as modified.\n this.lastModified = new Date()\n\n if (oldRecord) {\n // Replace an old key.\n clearTimeout(oldRecord.timeout)\n this.items.splice(this.items.indexOf(oldRecord), 1, record)\n } else {\n // Remove least used item if needed.\n if (this.size >= this.max) this.delete(this.items[0].key)\n // Add a new key.\n this.items.push(record)\n this.size++\n }\n\n if (options) {\n // Setup key expiry.\n if ('ttl' in options) this.expire(key, options.ttl)\n // Store user options in the record.\n if ('meta' in options) record.meta = options.meta\n // Mark a auto refresh key.\n if (options.refresh) record.refresh = options.ttl\n }\n\n return this\n}\n\n/**\n * Deletes an item from the cache.\n *\n * @param {String} key - the key to remove.\n * @return {Receptacle}\n */\ncache.delete = function (key) {\n var record = this._lookup[key]\n if (!record) return false\n this.lastModified = new Date()\n this.items.splice(this.items.indexOf(record), 1)\n clearTimeout(record.timeout)\n delete this._lookup[key]\n this.size--\n return this\n}\n\n/**\n * Utility to register a key that will be removed after some time.\n *\n * @param {String} key - the key to remove.\n * @param {Number} [ms] - the timeout before removal.\n * @return {Receptacle}\n */\ncache.expire = function (key, ttl) {\n var ms = ttl || 0\n var record = this._lookup[key]\n if (!record) return this\n if (typeof ms === 'string') ms = toMS(ttl)\n if (typeof ms !== 'number') throw new TypeError('Expiration time must be a string or number.')\n clearTimeout(record.timeout)\n record.timeout = setTimeout(this.delete.bind(this, record.key), ms)\n record.expires = Number(new Date()) + ms\n return this\n}\n\n/**\n * Deletes all items from the cache.\n * @return {Receptacle}\n */\ncache.clear = function () {\n for (var i = this.items.length; i--;) this.delete(this.items[i].key)\n return this\n}\n\n/**\n * Fixes serialization issues in polyfilled environments.\n * Ensures non-cyclical serialized object.\n */\ncache.toJSON = function () {\n var items = new Array(this.items.length)\n var item\n for (var i = items.length; i--;) {\n item = this.items[i]\n items[i] = {\n key: item.key,\n meta: item.meta,\n value: item.value,\n expires: item.expires,\n refresh: item.refresh\n }\n }\n\n return {\n id: this.id,\n max: isFinite(this.max) ? this.max : undefined,\n lastModified: this.lastModified,\n items: items\n }\n}\n", "module.exports = class FixedFIFO {\n constructor (hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')\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\n push (data) {\n if (this.buffer[this.top] !== undefined) return false\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n return true\n }\n\n shift () {\n const last = this.buffer[this.btm]\n if (last === undefined) return undefined\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n peek () {\n return this.buffer[this.btm]\n }\n\n isEmpty () {\n return this.buffer[this.btm] === undefined\n }\n}\n", "const FixedFIFO = require('./fixed-size')\n\nmodule.exports = class FastFIFO {\n constructor (hwm) {\n this.hwm = hwm || 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n }\n\n push (val) {\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\n shift () {\n const val = this.tail.shift()\n if (val === undefined && this.tail.next) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n return this.tail.shift()\n }\n return val\n }\n\n peek () {\n return this.tail.peek()\n }\n\n isEmpty () {\n return this.head.isEmpty()\n }\n}\n", "'use strict';\n\nconst 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\nmodule.exports = pDefer;\n", "const Fifo = require('fast-fifo')\nconst defer = require('p-defer')\n\nmodule.exports = class PFifo {\n constructor () {\n this._buffer = new Fifo()\n this._waitingConsumers = new Fifo()\n }\n\n push (chunk) {\n const { promise, resolve } = defer()\n this._buffer.push({ chunk, resolve })\n this._consume()\n return promise\n }\n\n _consume () {\n while (!this._waitingConsumers.isEmpty() && !this._buffer.isEmpty()) {\n const nextConsumer = this._waitingConsumers.shift()\n const nextChunk = this._buffer.shift()\n nextConsumer.resolve(nextChunk.chunk)\n nextChunk.resolve()\n }\n }\n\n shift () {\n const { promise, resolve } = defer()\n this._waitingConsumers.push({ resolve })\n this._consume()\n return promise\n }\n\n isEmpty () {\n return this._buffer.isEmpty()\n }\n}\n", "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\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", "'use strict'\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 = require('safe-buffer').Buffer\nvar crypto = global.crypto || global.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", "/*\nindex.js - Kademlia DHT K-bucket implementation as a binary tree.\n\nThe MIT License (MIT)\n\nCopyright (c) 2013-2021 Tristan Slominski\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n'use strict'\n\nconst randomBytes = require('randombytes')\nconst { EventEmitter } = require('events')\n\n/**\n * @param {Uint8Array} array1\n * @param {Uint8Array} array2\n * @return {Boolean}\n */\nfunction arrayEquals (array1, array2) {\n if (array1 === array2) {\n return true\n }\n if (array1.length !== array2.length) {\n return false\n }\n for (let i = 0, length = array1.length; i < length; ++i) {\n if (array1[i] !== array2[i]) {\n return false\n }\n }\n return true\n}\n\nfunction createNode () {\n return { contacts: [], dontSplit: false, left: null, right: null }\n}\n\nfunction ensureInt8 (name, val) {\n if (!(val instanceof Uint8Array)) {\n throw new TypeError(name + ' is not a Uint8Array')\n }\n}\n\n/**\n * Implementation of a Kademlia DHT k-bucket used for storing\n * contact (peer node) information.\n *\n * @extends EventEmitter\n */\nclass KBucket extends EventEmitter {\n /**\n * `options`:\n * `distance`: _Function_\n * `function (firstId, secondId) { return distance }` An optional\n * `distance` function that gets two `id` Uint8Arrays\n * and return distance (as number) between them.\n * `arbiter`: _Function_ _(Default: vectorClock arbiter)_\n * `function (incumbent, candidate) { return contact; }` An optional\n * `arbiter` function that givent two `contact` objects with the same `id`\n * returns the desired object to be used for updating the k-bucket. For\n * more details, see [arbiter function](#arbiter-function).\n * `localNodeId`: _Uint8Array_ An optional Uint8Array representing the local node id.\n * If not provided, a local node id will be created via `randomBytes(20)`.\n * `metadata`: _Object_ _(Default: {})_ Optional satellite data to include\n * with the k-bucket. `metadata` property is guaranteed not be altered by,\n * it is provided as an explicit container for users of k-bucket to store\n * implementation-specific data.\n * `numberOfNodesPerKBucket`: _Integer_ _(Default: 20)_ The number of nodes\n * that a k-bucket can contain before being full or split.\n * `numberOfNodesToPing`: _Integer_ _(Default: 3)_ The number of nodes to\n * ping when a bucket that should not be split becomes full. KBucket will\n * emit a `ping` event that contains `numberOfNodesToPing` nodes that have\n * not been contacted the longest.\n *\n * @param {Object=} options optional\n */\n constructor (options = {}) {\n super()\n\n this.localNodeId = options.localNodeId || randomBytes(20)\n this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20\n this.numberOfNodesToPing = options.numberOfNodesToPing || 3\n this.distance = options.distance || KBucket.distance\n // use an arbiter from options or vectorClock arbiter by default\n this.arbiter = options.arbiter || KBucket.arbiter\n this.metadata = Object.assign({}, options.metadata)\n\n ensureInt8('option.localNodeId as parameter 1', this.localNodeId)\n\n this.root = createNode()\n }\n\n /**\n * Default arbiter function for contacts with the same id. Uses\n * contact.vectorClock to select which contact to update the k-bucket with.\n * Contact with larger vectorClock field will be selected. If vectorClock is\n * the same, candidat will be selected.\n *\n * @param {Object} incumbent Contact currently stored in the k-bucket.\n * @param {Object} candidate Contact being added to the k-bucket.\n * @return {Object} Contact to updated the k-bucket with.\n */\n static arbiter (incumbent, candidate) {\n return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate\n }\n\n /**\n * Default distance function. Finds the XOR\n * distance between firstId and secondId.\n *\n * @param {Uint8Array} firstId Uint8Array containing first id.\n * @param {Uint8Array} secondId Uint8Array containing second id.\n * @return {Number} Integer The XOR distance between firstId\n * and secondId.\n */\n static distance (firstId, secondId) {\n let distance = 0\n let i = 0\n const min = Math.min(firstId.length, secondId.length)\n const max = Math.max(firstId.length, secondId.length)\n for (; i < min; ++i) {\n distance = distance * 256 + (firstId[i] ^ secondId[i])\n }\n for (; i < max; ++i) distance = distance * 256 + 255\n return distance\n }\n\n /**\n * Adds a contact to the k-bucket.\n *\n * @param {Object} contact the contact object to add\n */\n add (contact) {\n ensureInt8('contact.id', (contact || {}).id)\n\n let bitIndex = 0\n let node = this.root\n\n while (node.contacts === null) {\n // this is not a leaf node but an inner node with 'low' and 'high'\n // branches; we will check the appropriate bit of the identifier and\n // delegate to the appropriate node for further processing\n node = this._determineNode(node, contact.id, bitIndex++)\n }\n\n // check if the contact already exists\n const index = this._indexOf(node, contact.id)\n if (index >= 0) {\n this._update(node, index, contact)\n return this\n }\n\n if (node.contacts.length < this.numberOfNodesPerKBucket) {\n node.contacts.push(contact)\n this.emit('added', contact)\n return this\n }\n\n // the bucket is full\n if (node.dontSplit) {\n // we are not allowed to split the bucket\n // we need to ping the first this.numberOfNodesToPing\n // in order to determine if they are alive\n // only if one of the pinged nodes does not respond, can the new contact\n // be added (this prevents DoS flodding with new invalid contacts)\n this.emit('ping', node.contacts.slice(0, this.numberOfNodesToPing), contact)\n return this\n }\n\n this._split(node, bitIndex)\n return this.add(contact)\n }\n\n /**\n * Get the n closest contacts to the provided node id. \"Closest\" here means:\n * closest according to the XOR metric of the contact node id.\n *\n * @param {Uint8Array} id Contact node id\n * @param {Number=} n Integer (Default: Infinity) The maximum number of\n * closest contacts to return\n * @return {Array} Array Maximum of n closest contacts to the node id\n */\n closest (id, n = Infinity) {\n ensureInt8('id', id)\n\n if ((!Number.isInteger(n) && n !== Infinity) || n <= 0) {\n throw new TypeError('n is not positive number')\n }\n\n let contacts = []\n\n for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n;) {\n const node = nodes.pop()\n if (node.contacts === null) {\n const detNode = this._determineNode(node, id, bitIndex++)\n nodes.push(node.left === detNode ? node.right : node.left)\n nodes.push(detNode)\n } else {\n contacts = contacts.concat(node.contacts)\n }\n }\n\n return contacts\n .map(a => [this.distance(a.id, id), a])\n .sort((a, b) => a[0] - b[0])\n .slice(0, n)\n .map(a => a[1])\n }\n\n /**\n * Counts the total number of contacts in the tree.\n *\n * @return {Number} The number of contacts held in the tree\n */\n count () {\n // return this.toArray().length\n let count = 0\n for (const nodes = [this.root]; nodes.length > 0;) {\n const node = nodes.pop()\n if (node.contacts === null) nodes.push(node.right, node.left)\n else count += node.contacts.length\n }\n return count\n }\n\n /**\n * Determines whether the id at the bitIndex is 0 or 1.\n * Return left leaf if `id` at `bitIndex` is 0, right leaf otherwise\n *\n * @param {Object} node internal object that has 2 leafs: left and right\n * @param {Uint8Array} id Id to compare localNodeId with.\n * @param {Number} bitIndex Integer (Default: 0) The bit index to which bit\n * to check in the id Uint8Array.\n * @return {Object} left leaf if id at bitIndex is 0, right leaf otherwise.\n */\n _determineNode (node, id, bitIndex) {\n // **NOTE** remember that id is a Uint8Array and has granularity of\n // bytes (8 bits), whereas the bitIndex is the _bit_ index (not byte)\n\n // id's that are too short are put in low bucket (1 byte = 8 bits)\n // (bitIndex >> 3) finds how many bytes the bitIndex describes\n // bitIndex % 8 checks if we have extra bits beyond byte multiples\n // if number of bytes is <= no. of bytes described by bitIndex and there\n // are extra bits to consider, this means id has less bits than what\n // bitIndex describes, id therefore is too short, and will be put in low\n // bucket\n const bytesDescribedByBitIndex = bitIndex >> 3\n const bitIndexWithinByte = bitIndex % 8\n if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0)) {\n return node.left\n }\n\n const byteUnderConsideration = id[bytesDescribedByBitIndex]\n\n // byteUnderConsideration is an integer from 0 to 255 represented by 8 bits\n // where 255 is 11111111 and 0 is 00000000\n // in order to find out whether the bit at bitIndexWithinByte is set\n // we construct (1 << (7 - bitIndexWithinByte)) which will consist\n // of all bits being 0, with only one bit set to 1\n // for example, if bitIndexWithinByte is 3, we will construct 00010000 by\n // (1 << (7 - 3)) -> (1 << 4) -> 16\n if (byteUnderConsideration & (1 << (7 - bitIndexWithinByte))) {\n return node.right\n }\n\n return node.left\n }\n\n /**\n * Get a contact by its exact ID.\n * If this is a leaf, loop through the bucket contents and return the correct\n * contact if we have it or null if not. If this is an inner node, determine\n * which branch of the tree to traverse and repeat.\n *\n * @param {Uint8Array} id The ID of the contact to fetch.\n * @return {Object|Null} The contact if available, otherwise null\n */\n get (id) {\n ensureInt8('id', id)\n\n let bitIndex = 0\n\n let node = this.root\n while (node.contacts === null) {\n node = this._determineNode(node, id, bitIndex++)\n }\n\n // index of uses contact id for matching\n const index = this._indexOf(node, id)\n return index >= 0 ? node.contacts[index] : null\n }\n\n /**\n * Returns the index of the contact with provided\n * id if it exists, returns -1 otherwise.\n *\n * @param {Object} node internal object that has 2 leafs: left and right\n * @param {Uint8Array} id Contact node id.\n * @return {Number} Integer Index of contact with provided id if it\n * exists, -1 otherwise.\n */\n _indexOf (node, id) {\n for (let i = 0; i < node.contacts.length; ++i) {\n if (arrayEquals(node.contacts[i].id, id)) return i\n }\n\n return -1\n }\n\n /**\n * Removes contact with the provided id.\n *\n * @param {Uint8Array} id The ID of the contact to remove.\n * @return {Object} The k-bucket itself.\n */\n remove (id) {\n ensureInt8('the id as parameter 1', id)\n\n let bitIndex = 0\n let node = this.root\n\n while (node.contacts === null) {\n node = this._determineNode(node, id, bitIndex++)\n }\n\n const index = this._indexOf(node, id)\n if (index >= 0) {\n const contact = node.contacts.splice(index, 1)[0]\n this.emit('removed', contact)\n }\n\n return this\n }\n\n /**\n * Splits the node, redistributes contacts to the new nodes, and marks the\n * node that was split as an inner node of the binary tree of nodes by\n * setting this.root.contacts = null\n *\n * @param {Object} node node for splitting\n * @param {Number} bitIndex the bitIndex to which byte to check in the\n * Uint8Array for navigating the binary tree\n */\n _split (node, bitIndex) {\n node.left = createNode()\n node.right = createNode()\n\n // redistribute existing contacts amongst the two newly created nodes\n for (const contact of node.contacts) {\n this._determineNode(node, contact.id, bitIndex).contacts.push(contact)\n }\n\n node.contacts = null // mark as inner tree node\n\n // don't split the \"far away\" node\n // we check where the local node would end up and mark the other one as\n // \"dontSplit\" (i.e. \"far away\")\n const detNode = this._determineNode(node, this.localNodeId, bitIndex)\n const otherNode = node.left === detNode ? node.right : node.left\n otherNode.dontSplit = true\n }\n\n /**\n * Returns all the contacts contained in the tree as an array.\n * If this is a leaf, return a copy of the bucket. If this is not a leaf,\n * return the union of the low and high branches (themselves also as arrays).\n *\n * @return {Array} All of the contacts in the tree, as an array\n */\n toArray () {\n let result = []\n for (const nodes = [this.root]; nodes.length > 0;) {\n const node = nodes.pop()\n if (node.contacts === null) nodes.push(node.right, node.left)\n else result = result.concat(node.contacts)\n }\n return result\n }\n\n /**\n * Similar to `toArray()` but instead of buffering everything up into an\n * array before returning it, yields contacts as they are encountered while\n * walking the tree.\n *\n * @return {Iterable} All of the contacts in the tree, as an iterable\n */\n * toIterable () {\n for (const nodes = [this.root]; nodes.length > 0;) {\n const node = nodes.pop()\n if (node.contacts === null) {\n nodes.push(node.right, node.left)\n } else {\n yield * node.contacts\n }\n }\n }\n\n /**\n * Updates the contact selected by the arbiter.\n * If the selection is our old contact and the candidate is some new contact\n * then the new contact is abandoned (not added).\n * If the selection is our old contact and the candidate is our old contact\n * then we are refreshing the contact and it is marked as most recently\n * contacted (by being moved to the right/end of the bucket array).\n * If the selection is our new contact, the old contact is removed and the new\n * contact is marked as most recently contacted.\n *\n * @param {Object} node internal object that has 2 leafs: left and right\n * @param {Number} index the index in the bucket where contact exists\n * (index has already been computed in a previous\n * calculation)\n * @param {Object} contact The contact object to update.\n */\n _update (node, index, contact) {\n // sanity check\n if (!arrayEquals(node.contacts[index].id, contact.id)) {\n throw new Error('wrong index for _update')\n }\n\n const incumbent = node.contacts[index]\n const selection = this.arbiter(incumbent, contact)\n // if the selection is our old contact and the candidate is some new\n // contact, then there is nothing to do\n if (selection === incumbent && incumbent !== contact) return\n\n node.contacts.splice(index, 1) // remove old contact\n node.contacts.push(selection) // add more recent contact version\n this.emit('updated', incumbent, selection)\n }\n}\n\nmodule.exports = KBucket\n", "(function (root) {\n 'use strict';\n // A list of regular expressions that match arbitrary IPv4 addresses,\n // for which a number of weird notations exist.\n // Note that an address like 0010.0xa5.1.1 is considered legal.\n const ipv4Part = '(0?\\\\d+|0x[a-f0-9]+)';\n const ipv4Regexes = {\n fourOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n threeOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n twoOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n longValue: new RegExp(`^${ipv4Part}$`, 'i')\n };\n\n // Regular Expression for checking Octal numbers\n const octalRegex = new RegExp(`^0[0-7]+$`, 'i');\n const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');\n\n const zoneIndex = '%[0-9a-z]{1,}';\n\n // IPv6-matching regular expressions.\n // For IPv6, the task is simpler: it is enough to match the colon-delimited\n // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at\n // the end.\n const ipv6Part = '(?:[0-9a-f]+::?)+';\n const ipv6Regexes = {\n zoneIndex: new RegExp(zoneIndex, 'i'),\n 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),\n deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),\n transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?$`, 'i')\n };\n\n // Expand :: in an IPv6 address or address part consisting of `parts` groups.\n function expandIPv6 (string, parts) {\n // More than one '::' means invalid adddress\n if (string.indexOf('::') !== string.lastIndexOf('::')) {\n return null;\n }\n\n let colonCount = 0;\n let lastColon = -1;\n let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];\n let replacement, replacementCount;\n\n // Remove zone index and save it for later\n if (zoneId) {\n zoneId = zoneId.substring(1);\n string = string.replace(/%.+$/, '');\n }\n\n // How many parts do we already have?\n while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {\n colonCount++;\n }\n\n // 0::0 is two parts more than ::\n if (string.substr(0, 2) === '::') {\n colonCount--;\n }\n\n if (string.substr(-2, 2) === '::') {\n colonCount--;\n }\n\n // The following loop would hang if colonCount > parts\n if (colonCount > parts) {\n return null;\n }\n\n // replacement = ':' + '0:' * (parts - colonCount)\n replacementCount = parts - colonCount;\n replacement = ':';\n while (replacementCount--) {\n replacement += '0:';\n }\n\n // Insert the missing zeroes\n string = string.replace('::', replacement);\n\n // Trim any garbage which may be hanging around if :: was at the edge in\n // the source strin\n if (string[0] === ':') {\n string = string.slice(1);\n }\n\n if (string[string.length - 1] === ':') {\n string = string.slice(0, -1);\n }\n\n parts = (function () {\n const ref = string.split(':');\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n results.push(parseInt(ref[i], 16));\n }\n\n return results;\n })();\n\n return {\n parts: parts,\n zoneId: zoneId\n };\n }\n\n // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.\n function matchCIDR (first, second, partSize, cidrBits) {\n if (first.length !== second.length) {\n throw new Error('ipaddr: cannot match CIDR for objects with different lengths');\n }\n\n let part = 0;\n let shift;\n\n while (cidrBits > 0) {\n shift = partSize - cidrBits;\n if (shift < 0) {\n shift = 0;\n }\n\n if (first[part] >> shift !== second[part] >> shift) {\n return false;\n }\n\n cidrBits -= partSize;\n part += 1;\n }\n\n return true;\n }\n\n function parseIntAuto (string) {\n // Hexadedimal base 16 (0x#)\n if (hexRegex.test(string)) {\n return parseInt(string, 16);\n }\n // While octal representation is discouraged by ECMAScript 3\n // and forbidden by ECMAScript 5, we silently allow it to\n // work only if the rest of the string has numbers less than 8.\n if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {\n if (octalRegex.test(string)) {\n return parseInt(string, 8);\n }\n throw new Error(`ipaddr: cannot parse ${string} as octal`);\n }\n // Always include the base 10 radix!\n return parseInt(string, 10);\n }\n\n function padPart (part, length) {\n while (part.length < length) {\n part = `0${part}`;\n }\n\n return part;\n }\n\n const ipaddr = {};\n\n // An IPv4 address (RFC791).\n ipaddr.IPv4 = (function () {\n // Constructs a new IPv4 address from an array of four octets\n // in network order (MSB first)\n // Verifies the input.\n function IPv4 (octets) {\n if (octets.length !== 4) {\n throw new Error('ipaddr: ipv4 octet count should be 4');\n }\n\n let i, octet;\n\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n throw new Error('ipaddr: ipv4 octet should fit in 8 bits');\n }\n }\n\n this.octets = octets;\n }\n\n // Special IPv4 address ranges.\n // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses\n IPv4.prototype.SpecialRanges = {\n unspecified: [[new IPv4([0, 0, 0, 0]), 8]],\n broadcast: [[new IPv4([255, 255, 255, 255]), 32]],\n // RFC3171\n multicast: [[new IPv4([224, 0, 0, 0]), 4]],\n // RFC3927\n linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],\n // RFC5735\n loopback: [[new IPv4([127, 0, 0, 0]), 8]],\n // RFC6598\n carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],\n // RFC1918\n 'private': [\n [new IPv4([10, 0, 0, 0]), 8],\n [new IPv4([172, 16, 0, 0]), 12],\n [new IPv4([192, 168, 0, 0]), 16]\n ],\n // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700\n reserved: [\n [new IPv4([192, 0, 0, 0]), 24],\n [new IPv4([192, 0, 2, 0]), 24],\n [new IPv4([192, 88, 99, 0]), 24],\n [new IPv4([198, 18, 0, 0]), 15],\n [new IPv4([198, 51, 100, 0]), 24],\n [new IPv4([203, 0, 113, 0]), 24],\n [new IPv4([240, 0, 0, 0]), 4]\n ],\n // RFC7534, RFC7535\n as112: [\n [new IPv4([192, 175, 48, 0]), 24],\n [new IPv4([192, 31, 196, 0]), 24],\n ],\n // RFC7450\n amt: [\n [new IPv4([192, 52, 193, 0]), 24],\n ],\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv4.prototype.kind = function () {\n return 'ipv4';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv4.prototype.match = function (other, cidrRange) {\n let ref;\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv4') {\n throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');\n }\n\n return matchCIDR(this.octets, other.octets, 8, cidrRange);\n };\n\n // returns a number of leading ones in IPv4 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv4.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 8,\n 128: 7,\n 192: 6,\n 224: 5,\n 240: 4,\n 248: 3,\n 252: 2,\n 254: 1,\n 255: 0\n };\n let i, octet, zeros;\n\n for (i = 3; i >= 0; i -= 1) {\n octet = this.octets[i];\n if (octet in zerotable) {\n zeros = zerotable[octet];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 8) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 32 - cidr;\n };\n\n // Checks if the address corresponds to one of the special ranges.\n IPv4.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv4.prototype.toByteArray = function () {\n return this.octets.slice(0);\n };\n\n // Converts this IPv4 address to an IPv4-mapped IPv6 address.\n IPv4.prototype.toIPv4MappedAddress = function () {\n return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);\n };\n\n // Symmetrical method strictly for aligning with the IPv6 methods.\n IPv4.prototype.toNormalizedString = function () {\n return this.toString();\n };\n\n // Returns the address in convenient, decimal-dotted format.\n IPv4.prototype.toString = function () {\n return this.octets.join('.');\n };\n\n return IPv4;\n })();\n\n // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {\n\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 4) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Checks if a given string is formatted like IPv4 address.\n ipaddr.IPv4.isIPv4 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks if a given string is a valid IPv4 address.\n ipaddr.IPv4.isValid = function (string) {\n try {\n new this(this.parser(string));\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv4 address in CIDR notation.\n ipaddr.IPv4.isValidCIDR = function (string) {\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address.\n ipaddr.IPv4.isValidFourPartDecimal = function (string) {\n if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){3}$/)) {\n return true;\n } else {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 4) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Tries to parse and validate a string with IPv4 address.\n // Throws an error if it fails.\n ipaddr.IPv4.parse = function (string) {\n const parts = this.parser(string);\n\n if (parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv4 Address');\n }\n\n return new this(parts);\n };\n\n // Parses the string as an IPv4 Address with CIDR Notation.\n ipaddr.IPv4.parseCIDR = function (string) {\n let match;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n const maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 32) {\n const parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');\n };\n\n // Classful variants (like a.b, where a is an octet, and b is a 24-bit\n // value representing last three octets; this corresponds to a class C\n // address) are omitted due to classless nature of modern Internet.\n ipaddr.IPv4.parser = function (string) {\n let match, part, value;\n\n // parseInt recognizes all that octal & hexadecimal weirdness for us\n if ((match = string.match(ipv4Regexes.fourOctet))) {\n return (function () {\n const ref = match.slice(1, 6);\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n results.push(parseIntAuto(part));\n }\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.longValue))) {\n value = parseIntAuto(match[1]);\n if (value > 0xffffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n return ((function () {\n const results = [];\n let shift;\n\n for (shift = 0; shift <= 24; shift += 8) {\n results.push((value >> shift) & 0xff);\n }\n\n return results;\n })()).reverse();\n } else if ((match = string.match(ipv4Regexes.twoOctet))) {\n return (function () {\n const ref = match.slice(1, 4);\n const results = [];\n\n value = parseIntAuto(ref[1]);\n if (value > 0xffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push((value >> 16) & 0xff);\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.threeOctet))) {\n return (function () {\n const ref = match.slice(1, 5);\n const results = [];\n\n value = parseIntAuto(ref[2]);\n if (value > 0xffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push(parseIntAuto(ref[1]));\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else {\n return null;\n }\n };\n\n // A utility function to return subnet mask in IPv4 format given the prefix length\n ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 32) {\n throw new Error('ipaddr: invalid IPv4 prefix length');\n }\n\n const octets = [0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 4) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // An IPv6 address (RFC2460)\n ipaddr.IPv6 = (function () {\n // Constructs an IPv6 address from an array of eight 16 - bit parts\n // or sixteen 8 - bit parts in network order(MSB first).\n // Throws an error if the input is invalid.\n function IPv6 (parts, zoneId) {\n let i, part;\n\n if (parts.length === 16) {\n this.parts = [];\n for (i = 0; i <= 14; i += 2) {\n this.parts.push((parts[i] << 8) | parts[i + 1]);\n }\n } else if (parts.length === 8) {\n this.parts = parts;\n } else {\n throw new Error('ipaddr: ipv6 part count should be 8 or 16');\n }\n\n for (i = 0; i < this.parts.length; i++) {\n part = this.parts[i];\n if (!((0 <= part && part <= 0xffff))) {\n throw new Error('ipaddr: ipv6 part should fit in 16 bits');\n }\n }\n\n if (zoneId) {\n this.zoneId = zoneId;\n }\n }\n\n // Special IPv6 ranges\n IPv6.prototype.SpecialRanges = {\n // RFC4291, here and after\n unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],\n linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],\n multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],\n loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],\n uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],\n ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],\n // RFC6666\n discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64],\n // RFC6145\n rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],\n // RFC6052\n rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],\n // RFC3056\n '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],\n // RFC6052, RFC6146\n teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],\n // RFC5180\n benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48],\n // RFC7450\n amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32],\n as112v6: [\n [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48],\n [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48],\n ],\n deprecated: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28],\n orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28],\n droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28],\n reserved: [\n // RFC3849\n [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23],\n // RFC2928\n [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32],\n ],\n };\n\n // Checks if this address is an IPv4-mapped IPv6 address.\n IPv6.prototype.isIPv4MappedAddress = function () {\n return this.range() === 'ipv4Mapped';\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv6.prototype.kind = function () {\n return 'ipv6';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv6.prototype.match = function (other, cidrRange) {\n let ref;\n\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv6') {\n throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');\n }\n\n return matchCIDR(this.parts, other.parts, 16, cidrRange);\n };\n\n // returns a number of leading ones in IPv6 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv6.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 16,\n 32768: 15,\n 49152: 14,\n 57344: 13,\n 61440: 12,\n 63488: 11,\n 64512: 10,\n 65024: 9,\n 65280: 8,\n 65408: 7,\n 65472: 6,\n 65504: 5,\n 65520: 4,\n 65528: 3,\n 65532: 2,\n 65534: 1,\n 65535: 0\n };\n let part, zeros;\n\n for (let i = 7; i >= 0; i -= 1) {\n part = this.parts[i];\n if (part in zerotable) {\n zeros = zerotable[part];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 16) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 128 - cidr;\n };\n\n\n // Checks if the address corresponds to one of the special ranges.\n IPv6.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv6.prototype.toByteArray = function () {\n let part;\n const bytes = [];\n const ref = this.parts;\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n bytes.push(part >> 8);\n bytes.push(part & 0xff);\n }\n\n return bytes;\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:0db8:0008:0066:0000:0000:0000:0001\n IPv6.prototype.toFixedLengthString = function () {\n const addr = ((function () {\n const results = [];\n for (let i = 0; i < this.parts.length; i++) {\n results.push(padPart(this.parts[i].toString(16), 4));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.\n // Throws an error otherwise.\n IPv6.prototype.toIPv4Address = function () {\n if (!this.isIPv4MappedAddress()) {\n throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');\n }\n\n const ref = this.parts.slice(-2);\n const high = ref[0];\n const low = ref[1];\n\n return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:db8:8:66:0:0:0:1\n //\n // Deprecated: use toFixedLengthString() instead.\n IPv6.prototype.toNormalizedString = function () {\n const addr = ((function () {\n const results = [];\n\n for (let i = 0; i < this.parts.length; i++) {\n results.push(this.parts[i].toString(16));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)\n IPv6.prototype.toRFC5952String = function () {\n const regex = /((^|:)(0(:|$)){2,})/g;\n const string = this.toNormalizedString();\n let bestMatchIndex = 0;\n let bestMatchLength = -1;\n let match;\n\n while ((match = regex.exec(string))) {\n if (match[0].length > bestMatchLength) {\n bestMatchIndex = match.index;\n bestMatchLength = match[0].length;\n }\n }\n\n if (bestMatchLength < 0) {\n return string;\n }\n\n return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // Calls toRFC5952String under the hood.\n IPv6.prototype.toString = function () {\n return this.toRFC5952String();\n };\n\n return IPv6;\n\n })();\n\n // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 16) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Checks if a given string is formatted like IPv6 address.\n ipaddr.IPv6.isIPv6 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks to see if string is a valid IPv6 Address\n ipaddr.IPv6.isValid = function (string) {\n\n // Since IPv6.isValid is always called first, this shortcut\n // provides a substantial performance gain.\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n const addr = this.parser(string);\n new this(addr.parts, addr.zoneId);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv6 address in CIDR notation.\n ipaddr.IPv6.isValidCIDR = function (string) {\n\n // See note in IPv6.isValid\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 16) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Tries to parse and validate a string with IPv6 address.\n // Throws an error if it fails.\n ipaddr.IPv6.parse = function (string) {\n const addr = this.parser(string);\n\n if (addr.parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv6 Address');\n }\n\n return new this(addr.parts, addr.zoneId);\n };\n\n ipaddr.IPv6.parseCIDR = function (string) {\n let maskLength, match, parsed;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 128) {\n parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');\n };\n\n // Parse an IPv6 address.\n ipaddr.IPv6.parser = function (string) {\n let addr, i, match, octet, octets, zoneId;\n\n if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {\n return this.parser(`::ffff:${match[1]}`);\n }\n if (ipv6Regexes.native.test(string)) {\n return expandIPv6(string, 8);\n }\n if ((match = string.match(ipv6Regexes.transitional))) {\n zoneId = match[6] || '';\n addr = match[1]\n if (!match[1].endsWith('::')) {\n addr = addr.slice(0, -1)\n }\n addr = expandIPv6(addr + zoneId, 6);\n if (addr.parts) {\n octets = [\n parseInt(match[2]),\n parseInt(match[3]),\n parseInt(match[4]),\n parseInt(match[5])\n ];\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n return null;\n }\n }\n\n addr.parts.push(octets[0] << 8 | octets[1]);\n addr.parts.push(octets[2] << 8 | octets[3]);\n return {\n parts: addr.parts,\n zoneId: addr.zoneId\n };\n }\n }\n\n return null;\n };\n\n // A utility function to return subnet mask in IPv6 format given the prefix length\n ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 128) {\n throw new Error('ipaddr: invalid IPv6 prefix length');\n }\n\n const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 16) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // Try to parse an array in network order (MSB first) for IPv4 and IPv6\n ipaddr.fromByteArray = function (bytes) {\n const length = bytes.length;\n\n if (length === 4) {\n return new ipaddr.IPv4(bytes);\n } else if (length === 16) {\n return new ipaddr.IPv6(bytes);\n } else {\n throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');\n }\n };\n\n // Checks if the address is valid IP address\n ipaddr.isValid = function (string) {\n return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);\n };\n\n // Checks if the address is valid IP address in CIDR notation\n ipaddr.isValidCIDR = function (string) {\n return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);\n };\n\n\n // Attempts to parse an IP Address, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parse = function (string) {\n if (ipaddr.IPv6.isValid(string)) {\n return ipaddr.IPv6.parse(string);\n } else if (ipaddr.IPv4.isValid(string)) {\n return ipaddr.IPv4.parse(string);\n } else {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');\n }\n };\n\n // Attempt to parse CIDR notation, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parseCIDR = function (string) {\n try {\n return ipaddr.IPv6.parseCIDR(string);\n } catch (e) {\n try {\n return ipaddr.IPv4.parseCIDR(string);\n } catch (e2) {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');\n }\n }\n };\n\n // Parse an address and return plain IPv4 address if it is an IPv4-mapped address\n ipaddr.process = function (string) {\n const addr = this.parse(string);\n\n if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {\n return addr.toIPv4Address();\n } else {\n return addr;\n }\n };\n\n // An utility function to ease named range matching. See examples below.\n // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors\n // on matching IPv4 addresses to IPv6 ranges or vice versa.\n ipaddr.subnetMatch = function (address, rangeList, defaultName) {\n let i, rangeName, rangeSubnets, subnet;\n\n if (defaultName === undefined || defaultName === null) {\n defaultName = 'unicast';\n }\n\n for (rangeName in rangeList) {\n if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {\n rangeSubnets = rangeList[rangeName];\n // ECMA5 Array.isArray isn't available everywhere\n if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {\n rangeSubnets = [rangeSubnets];\n }\n\n for (i = 0; i < rangeSubnets.length; i++) {\n subnet = rangeSubnets[i];\n if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {\n return rangeName;\n }\n }\n }\n }\n\n return defaultName;\n };\n\n // Export for both the CommonJS and browser-like environment\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = ipaddr;\n\n } else {\n root.ipaddr = ipaddr;\n }\n\n}(this));\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\";\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", "module.exports = class RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * points: 4, // Number of points\n * duration: 1, // Per seconds\n * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds\n * execEvenly: false, // Execute allowed actions evenly over duration\n * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option\n * keyPrefix: 'rlflx',\n * }\n */\n constructor(opts = {}) {\n this.points = opts.points;\n this.duration = opts.duration;\n this.blockDuration = opts.blockDuration;\n this.execEvenly = opts.execEvenly;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs;\n this.keyPrefix = opts.keyPrefix;\n }\n\n get points() {\n return this._points;\n }\n\n set points(value) {\n this._points = value >= 0 ? value : 4;\n }\n\n get duration() {\n return this._duration;\n }\n\n set duration(value) {\n this._duration = typeof value === 'undefined' ? 1 : value;\n }\n\n get msDuration() {\n return this.duration * 1000;\n }\n\n get blockDuration() {\n return this._blockDuration;\n }\n\n set blockDuration(value) {\n this._blockDuration = typeof value === 'undefined' ? 0 : value;\n }\n\n get msBlockDuration() {\n return this.blockDuration * 1000;\n }\n\n get execEvenly() {\n return this._execEvenly;\n }\n\n set execEvenly(value) {\n this._execEvenly = typeof value === 'undefined' ? false : Boolean(value);\n }\n\n get execEvenlyMinDelayMs() {\n return this._execEvenlyMinDelayMs;\n }\n\n set execEvenlyMinDelayMs(value) {\n this._execEvenlyMinDelayMs = typeof value === 'undefined' ? Math.ceil(this.msDuration / this.points) : value;\n }\n\n get keyPrefix() {\n return this._keyPrefix;\n }\n\n set keyPrefix(value) {\n if (typeof value === 'undefined') {\n value = 'rlflx';\n }\n if (typeof value !== 'string') {\n throw new Error('keyPrefix must be string');\n }\n this._keyPrefix = value;\n }\n\n _getKeySecDuration(options = {}) {\n return options && options.customDuration >= 0\n ? options.customDuration\n : this.duration;\n }\n\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n\n consume() {\n throw new Error(\"You have to implement the method 'consume'!\");\n }\n\n penalty() {\n throw new Error(\"You have to implement the method 'penalty'!\");\n }\n\n reward() {\n throw new Error(\"You have to implement the method 'reward'!\");\n }\n\n get() {\n throw new Error(\"You have to implement the method 'get'!\");\n }\n\n set() {\n throw new Error(\"You have to implement the method 'set'!\");\n }\n\n block() {\n throw new Error(\"You have to implement the method 'block'!\");\n }\n\n delete() {\n throw new Error(\"You have to implement the method 'delete'!\");\n }\n};\n", "module.exports = class BlockedKeys {\n constructor() {\n this._keys = {}; // {'key': 1526279430331}\n this._addedKeysAmount = 0;\n }\n\n collectExpired() {\n const now = Date.now();\n\n Object.keys(this._keys).forEach((key) => {\n if (this._keys[key] <= now) {\n delete this._keys[key];\n }\n });\n\n this._addedKeysAmount = Object.keys(this._keys).length;\n }\n\n /**\n * Add new blocked key\n *\n * @param key String\n * @param sec Number\n */\n add(key, sec) {\n this.addMs(key, sec * 1000);\n }\n\n /**\n * Add new blocked key for ms\n *\n * @param key String\n * @param ms Number\n */\n addMs(key, ms) {\n this._keys[key] = Date.now() + ms;\n this._addedKeysAmount++;\n if (this._addedKeysAmount > 999) {\n this.collectExpired();\n }\n }\n\n /**\n * 0 means not blocked\n *\n * @param key\n * @returns {number}\n */\n msBeforeExpire(key) {\n const expire = this._keys[key];\n\n if (expire && expire >= Date.now()) {\n this.collectExpired();\n const now = Date.now();\n return expire >= now ? expire - now : 0;\n }\n\n return 0;\n }\n\n /**\n * If key is not given, delete all data in memory\n * \n * @param {string|undefined} key\n */\n delete(key) {\n if (key) {\n delete this._keys[key];\n } else {\n Object.keys(this._keys).forEach((key) => {\n delete this._keys[key];\n });\n }\n }\n};\n", "const BlockedKeys = require('./BlockedKeys');\n\nmodule.exports = BlockedKeys;\n", "module.exports = class RateLimiterRes {\n constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) {\n this.remainingPoints = typeof remainingPoints === 'undefined' ? 0 : remainingPoints; // Remaining points in current duration\n this.msBeforeNext = typeof msBeforeNext === 'undefined' ? 0 : msBeforeNext; // Milliseconds before next action\n this.consumedPoints = typeof consumedPoints === 'undefined' ? 0 : consumedPoints; // Consumed points in current duration\n this.isFirstInDuration = typeof isFirstInDuration === 'undefined' ? false : isFirstInDuration;\n }\n\n get msBeforeNext() {\n return this._msBeforeNext;\n }\n\n set msBeforeNext(ms) {\n this._msBeforeNext = ms;\n return this;\n }\n\n get remainingPoints() {\n return this._remainingPoints;\n }\n\n set remainingPoints(p) {\n this._remainingPoints = p;\n return this;\n }\n\n get consumedPoints() {\n return this._consumedPoints;\n }\n\n set consumedPoints(p) {\n this._consumedPoints = p;\n return this;\n }\n\n get isFirstInDuration() {\n return this._isFirstInDuration;\n }\n\n set isFirstInDuration(value) {\n this._isFirstInDuration = Boolean(value);\n }\n\n _getDecoratedProperties() {\n return {\n remainingPoints: this.remainingPoints,\n msBeforeNext: this.msBeforeNext,\n consumedPoints: this.consumedPoints,\n isFirstInDuration: this.isFirstInDuration,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this._getDecoratedProperties();\n }\n\n toString() {\n return JSON.stringify(this._getDecoratedProperties());\n }\n\n toJSON() {\n return this._getDecoratedProperties();\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst BlockedKeys = require('./component/BlockedKeys');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RateLimiterStoreAbstract extends RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * ... see other in RateLimiterAbstract\n *\n * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked\n * inMemoryBlockDuration: 10, // Block duration in seconds\n * insuranceLimiter: RateLimiterAbstract\n * }\n */\n constructor(opts = {}) {\n super(opts);\n\n this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed || opts.inmemoryBlockOnConsumed;\n this.inMemoryBlockDuration = opts.inMemoryBlockDuration || opts.inmemoryBlockDuration;\n this.insuranceLimiter = opts.insuranceLimiter;\n this._inMemoryBlockedKeys = new BlockedKeys();\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('storeClient is not set');\n }\n this._client = value;\n }\n\n /**\n * Have to be launched after consume\n * It blocks key and execute evenly depending on result from store\n *\n * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result\n *\n * @param resolve\n * @param reject\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @param {Object} options\n * @private\n */\n _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) {\n const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult);\n\n if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0)\n && res.consumedPoints >= this.inMemoryBlockOnConsumed\n ) {\n this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext);\n if (res.consumedPoints > this.points) {\n return reject(res);\n } else {\n return resolve(res)\n }\n } else if (res.consumedPoints > this.points) {\n let blockPromise = Promise.resolve();\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + changedPoints)) {\n res.msBeforeNext = this.msBlockDuration;\n blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options);\n }\n\n if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) {\n // Block key for this.inMemoryBlockDuration seconds\n this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration);\n res.msBeforeNext = this.msInMemoryBlockDuration;\n }\n\n blockPromise\n .then(() => {\n reject(res);\n })\n .catch((err) => {\n reject(err);\n });\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n }\n\n _handleError(err, funcName, resolve, reject, key, data = false, options = {}) {\n if (!(this.insuranceLimiter instanceof RateLimiterAbstract)) {\n reject(err);\n } else {\n this.insuranceLimiter[funcName](key, data, options)\n .then((res) => {\n resolve(res);\n })\n .catch((res) => {\n reject(res);\n });\n }\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {BlockedKeys}\n * @private\n */\n get _inmemoryBlockedKeys() {\n return this._inMemoryBlockedKeys\n }\n\n /**\n * @deprecated Use camelCase version\n * @param rlKey\n * @returns {number}\n */\n getInmemoryBlockMsBeforeExpire(rlKey) {\n return this.getInMemoryBlockMsBeforeExpire(rlKey)\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockOnConsumed() {\n return this.inMemoryBlockOnConsumed;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockOnConsumed(value) {\n this.inMemoryBlockOnConsumed = value;\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockDuration() {\n return this.inMemoryBlockDuration;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockDuration(value) {\n this.inMemoryBlockDuration = value\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number}\n */\n get msInmemoryBlockDuration() {\n return this.inMemoryBlockDuration * 1000;\n }\n\n getInMemoryBlockMsBeforeExpire(rlKey) {\n if (this.inMemoryBlockOnConsumed > 0) {\n return this._inMemoryBlockedKeys.msBeforeExpire(rlKey);\n }\n\n return 0;\n }\n\n get inMemoryBlockOnConsumed() {\n return this._inMemoryBlockOnConsumed;\n }\n\n set inMemoryBlockOnConsumed(value) {\n this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0;\n if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) {\n throw new Error('inMemoryBlockOnConsumed option must be greater or equal \"points\" option');\n }\n }\n\n get inMemoryBlockDuration() {\n return this._inMemoryBlockDuration;\n }\n\n set inMemoryBlockDuration(value) {\n this._inMemoryBlockDuration = value ? parseInt(value) : 0;\n if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) {\n throw new Error('inMemoryBlockOnConsumed option must be set up');\n }\n }\n\n get msInMemoryBlockDuration() {\n return this._inMemoryBlockDuration * 1000;\n }\n\n get insuranceLimiter() {\n return this._insuranceLimiter;\n }\n\n set insuranceLimiter(value) {\n if (typeof value !== 'undefined' && !(value instanceof RateLimiterAbstract)) {\n throw new Error('insuranceLimiter must be instance of RateLimiterAbstract');\n }\n this._insuranceLimiter = value;\n if (this._insuranceLimiter) {\n this._insuranceLimiter.blockDuration = this.blockDuration;\n this._insuranceLimiter.execEvenly = this.execEvenly;\n }\n }\n\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n block(key, secDuration, options = {}) {\n const msDuration = secDuration * 1000;\n return this._block(this.getKey(key), this.points + 1, msDuration, options);\n }\n\n /**\n * Set points by key for any duration\n *\n * @param key\n * @param points\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n set(key, points, secDuration, options = {}) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n return this._block(this.getKey(key), points, msDuration, options);\n }\n\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns Promise\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const rlKey = this.getKey(key);\n\n const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey);\n if (inMemoryBlockMsBeforeExpire > 0) {\n return reject(new RateLimiterRes(0, inMemoryBlockMsBeforeExpire));\n }\n\n this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n this._afterConsume(resolve, reject, rlKey, pointsToConsume, res);\n })\n .catch((err) => {\n this._handleError(err, 'consume', resolve, reject, key, pointsToConsume, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, points, res));\n })\n .catch((err) => {\n this._handleError(err, 'penalty', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, -points, res));\n })\n .catch((err) => {\n this._handleError(err, 'reward', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise|null\n */\n get(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._get(rlKey, options)\n .then((res) => {\n if (res === null || typeof res === 'undefined') {\n resolve(null);\n } else {\n resolve(this._getRateLimiterRes(rlKey, 0, res));\n }\n })\n .catch((err) => {\n this._handleError(err, 'get', resolve, reject, key, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise\n */\n delete(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._delete(rlKey, options)\n .then((res) => {\n this._inMemoryBlockedKeys.delete(rlKey);\n resolve(res);\n })\n .catch((err) => {\n this._handleError(err, 'delete', resolve, reject, key, options);\n });\n });\n }\n\n /**\n * Cleanup keys no-matter expired or not.\n */\n deleteInMemoryBlockedAll() {\n this._inMemoryBlockedKeys.delete();\n }\n\n /**\n * Get RateLimiterRes object filled depending on storeResult, which specific for exact store\n *\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @private\n */\n _getRateLimiterRes(rlKey, changedPoints, storeResult) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_getRateLimiterRes'!\");\n }\n\n /**\n * Block key for this.msBlockDuration milliseconds\n * Usually, it just prolongs lifetime of key\n *\n * @param rlKey\n * @param initPoints\n * @param msDuration\n * @param {Object} options\n *\n * @return Promise\n */\n _block(rlKey, initPoints, msDuration, options = {}) {\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, initPoints, msDuration, true, options)\n .then(() => {\n resolve(new RateLimiterRes(0, msDuration > 0 ? msDuration : -1, initPoints));\n })\n .catch((err) => {\n this._handleError(err, 'block', resolve, reject, this.parseKey(rlKey), msDuration / 1000, options);\n });\n });\n }\n\n /**\n * Have to be implemented in every limiter\n * Resolve with raw result from Store OR null if rlKey is not set\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _get(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_get'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with true OR false if rlKey doesn't exist\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _delete(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_delete'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}\n *\n * @param {string} rlKey\n * @param {number} points\n * @param {number} msDuration\n * @param {boolean} forceExpire\n * @param {Object} options\n * @abstract\n *\n * @return Promise\n */\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n throw new Error(\"You have to implement the method '_upsert'!\");\n }\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst incrTtlLuaScript = `redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') \\\nlocal consumed = redis.call('incrby', KEYS[1], ARGV[1]) \\\nlocal ttl = redis.call('pttl', KEYS[1]) \\\nif ttl == -1 then \\\n redis.call('expire', KEYS[1], ARGV[2]) \\\n ttl = 1000 * ARGV[2] \\\nend \\\nreturn {consumed, ttl} \\\n`;\n\nclass RateLimiterRedis extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * redis: RedisClient\n * rejectIfRedisNotReady: boolean = false - reject / invoke insuranceLimiter immediately when redis connection is not \"ready\"\n * }\n */\n constructor(opts) {\n super(opts);\n if (opts.redis) {\n this.client = opts.redis;\n } else {\n this.client = opts.storeClient;\n }\n\n this._rejectIfRedisNotReady = !!opts.rejectIfRedisNotReady;\n\n if (typeof this.client.defineCommand === 'function') {\n this.client.defineCommand(\"rlflxIncr\", {\n numberOfKeys: 1,\n lua: incrTtlLuaScript,\n });\n }\n }\n\n /**\n * Prevent actual redis call if redis connection is not ready\n * Because of different connection state checks for ioredis and node-redis, only this clients would be actually checked.\n * For any other clients all the requests would be passed directly to redis client\n * @return {boolean}\n * @private\n */\n _isRedisReady() {\n if (!this._rejectIfRedisNotReady) {\n return true;\n }\n // ioredis client\n if (this.client.status && this.client.status !== 'ready') {\n return false;\n }\n // node-redis client\n if (typeof this.client.isReady === 'function' && !this.client.isReady()) {\n return false;\n }\n return true;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n let [consumed, resTtlMs] = result;\n // Support ioredis results format\n if (Array.isArray(consumed)) {\n [, consumed] = consumed;\n [, resTtlMs] = resTtlMs;\n }\n\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(consumed);\n res.isFirstInDuration = res.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = resTtlMs;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n const secDuration = Math.floor(msDuration / 1000);\n const multi = this.client.multi();\n if (forceExpire) {\n if (secDuration > 0) {\n multi.set(rlKey, points, 'EX', secDuration);\n } else {\n multi.set(rlKey, points);\n }\n\n multi.pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n } else {\n if (secDuration > 0) {\n const incrCallback = function(err, result) {\n if (err) {\n return reject(err);\n }\n\n return resolve(result);\n };\n\n if (typeof this.client.rlflxIncr === 'function') {\n this.client.rlflxIncr(rlKey, points, secDuration, incrCallback);\n } else {\n this.client.eval(incrTtlLuaScript, 1, rlKey, points, secDuration, incrCallback);\n }\n } else {\n multi.incrby(rlKey, points)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n }\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n this.client\n .multi()\n .get(rlKey)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n reject(err);\n } else {\n const [points] = res;\n if (points === null) {\n return resolve(null)\n }\n\n resolve(res);\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res > 0);\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterRedis;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\n/**\n * Get MongoDB driver version as upsert options differ\n * @params {Object} Client instance\n * @returns {Object} Version Object containing major, feature & minor versions.\n */\nfunction getDriverVersion(client) {\n try {\n const _client = client.client ? client.client : client;\n\n const { version } = _client.topology.s.options.metadata.driver;\n const _v = version.split('.').map(v => parseInt(v));\n\n return {\n major: _v[0],\n feature: _v[1],\n patch: _v[2],\n };\n } catch (err) {\n return { major: 0, feature: 0, patch: 0 };\n }\n}\n\nclass RateLimiterMongo extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * indexKeyPrefix: {attr1: 1, attr2: 1}\n * ... see other in RateLimiterStoreAbstract\n *\n * mongo: MongoClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n this.indexKeyPrefix = opts.indexKeyPrefix;\n\n if (opts.mongo) {\n this.client = opts.mongo;\n } else {\n this.client = opts.storeClient;\n }\n if (typeof this.client.then === 'function') {\n // If Promise\n this.client\n .then((conn) => {\n this.client = conn;\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n });\n } else {\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n }\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? RateLimiterMongo.getDbName() : value;\n }\n\n static getDbName() {\n return 'node-rate-limiter-flexible';\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('mongo is not set');\n }\n this._client = value;\n }\n\n get indexKeyPrefix() {\n return this._indexKeyPrefix;\n }\n\n set indexKeyPrefix(obj) {\n this._indexKeyPrefix = obj || {};\n }\n\n _initCollection() {\n const db = typeof this.client.db === 'function'\n ? this.client.db(this.dbName)\n : this.client;\n\n const collection = db.collection(this.tableName);\n collection.createIndex({ expire: -1 }, { expireAfterSeconds: 0 });\n collection.createIndex(Object.assign({}, this.indexKeyPrefix, { key: 1 }), { unique: true });\n\n this._collection = collection;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n\n let doc;\n if (typeof result.value === 'undefined') {\n doc = result;\n } else {\n doc = result.value;\n }\n\n res.isFirstInDuration = doc.points === changedPoints;\n res.consumedPoints = doc.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = doc.expire !== null\n ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsert(key, points, msDuration, forceExpire = false, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n let where;\n let upsertData;\n if (forceExpire) {\n where = { key };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $set: {\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n };\n upsertData.$set = Object.assign(upsertData.$set, docAttrs);\n } else {\n where = {\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $setOnInsert: {\n key,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n $inc: { points },\n };\n upsertData.$setOnInsert = Object.assign(upsertData.$setOnInsert, docAttrs);\n }\n\n // Options for collection updates differ between driver versions\n const upsertOptions = {\n upsert: true,\n };\n if ((this._driverVersion.major >= 4) ||\n (this._driverVersion.major === 3 &&\n (this._driverVersion.feature >=7) || \n (this._driverVersion.feature >= 6 && \n this._driverVersion.patch >= 7 ))) \n {\n upsertOptions.returnDocument = 'after';\n } else {\n upsertOptions.returnOriginal = false;\n }\n\n /*\n * 1. Find actual limit and increment points\n * 2. If limit expired, but Mongo doesn't clean doc by TTL yet, try to replace limit doc completely\n * 3. If 2 or more Mongo threads try to insert the new limit doc, only the first succeed\n * 4. Try to upsert from step 1. Actual limit is created now, points are incremented without problems\n */\n return new Promise((resolve, reject) => {\n this._collection.findOneAndUpdate(\n where,\n upsertData,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errUpsert) => {\n if (errUpsert && errUpsert.code === 11000) { // E11000 duplicate key error collection\n const replaceWhere = Object.assign({ // try to replace OLD limit doc\n $or: [\n { expire: { $lte: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n }, docAttrs);\n\n const replaceTo = {\n $set: Object.assign({\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n }, docAttrs)\n };\n\n this._collection.findOneAndUpdate(\n replaceWhere,\n replaceTo,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errReplace) => {\n if (errReplace && errReplace.code === 11000) { // E11000 duplicate key error collection\n this._upsert(key, points, msDuration, forceExpire)\n .then(res => resolve(res))\n .catch(err => reject(err));\n } else {\n reject(errReplace);\n }\n });\n } else {\n reject(errUpsert);\n }\n });\n });\n }\n\n _get(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n const where = Object.assign({\n key: rlKey,\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n }, docAttrs);\n\n return this._collection.findOne(where);\n }\n\n _delete(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n const where = Object.assign({ key: rlKey }, docAttrs);\n\n return this._collection.deleteOne(where)\n .then(res => res.deletedCount > 0);\n }\n}\n\nmodule.exports = RateLimiterMongo;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMySQL extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: anySqlClient,\n * storeType: 'knex', // required only for Knex instance\n * dbName: 'string',\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createDbAndTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`DELETE FROM ??.?? WHERE expire < ?`, [this.dbName, this.tableName, expire], () => {\n this._releaseConnection(conn);\n resolve();\n });\n })\n .catch(() => {\n resolve();\n });\n });\n }\n\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return new Promise((resolve, reject) => {\n this.client.getConnection((errConn, conn) => {\n if (errConn) {\n return reject(errConn);\n }\n\n resolve(conn);\n });\n });\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return conn.release();\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createDbAndTable() {\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`CREATE DATABASE IF NOT EXISTS \\`${this.dbName}\\`;`, (errDb) => {\n if (errDb) {\n this._releaseConnection(conn);\n return reject(errDb);\n }\n conn.query(this._getCreateTableStmt(), (err) => {\n if (err) {\n this._releaseConnection(conn);\n return reject(err);\n }\n this._releaseConnection(conn);\n resolve();\n });\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS \\`${this.dbName}\\`.\\`${this.tableName}\\` (` +\n '`key` VARCHAR(255) CHARACTER SET utf8 NOT NULL,' +\n '`points` INT(9) NOT NULL default 0,' +\n '`expire` BIGINT UNSIGNED,' +\n 'PRIMARY KEY (`key`)' +\n ') ENGINE = INNODB;';\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n if (typeof value === 'undefined') {\n if (this.client.constructor.name === 'Connection') {\n value = 'connection';\n } else if (this.client.constructor.name === 'Pool') {\n value = 'pool';\n } else if (this.client.constructor.name === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n this._clientType = value.toLowerCase();\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? 'rtlmtrflx' : value;\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const [row] = result;\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsertTransaction(conn, key, points, msDuration, forceExpire) {\n return new Promise((resolve, reject) => {\n conn.query('BEGIN', (errBegin) => {\n if (errBegin) {\n conn.rollback();\n\n return reject(errBegin);\n }\n\n const dateNow = Date.now();\n const newExpire = msDuration > 0 ? dateNow + msDuration : null;\n\n let q;\n let values;\n if (forceExpire) {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = ?, \n expire = ?;`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n points,\n newExpire,\n ];\n } else {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = IF(expire <= ?, ?, points + (?)), \n expire = IF(expire <= ?, ?, expire);`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n dateNow, points, points,\n dateNow, newExpire,\n ];\n }\n\n conn.query(q, values, (errUpsert) => {\n if (errUpsert) {\n conn.rollback();\n\n return reject(errUpsert);\n }\n conn.query('SELECT points, expire FROM ??.?? WHERE `key` = ?;', [this.dbName, this.tableName, key], (errSelect, res) => {\n if (errSelect) {\n conn.rollback();\n\n return reject(errSelect);\n }\n\n conn.query('COMMIT', (err) => {\n if (err) {\n conn.rollback();\n\n return reject(err);\n }\n\n resolve(res);\n });\n });\n });\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n this._upsertTransaction(conn, key, points, msDuration, forceExpire)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)',\n [this.dbName, this.tableName, rlKey, Date.now()],\n (err, res) => {\n if (err) {\n reject(err);\n } else if (res.length === 0) {\n resolve(null);\n } else {\n resolve(res);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'DELETE FROM ??.?? WHERE `key` = ?',\n [this.dbName, this.tableName, rlKey],\n (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res.affectedRows > 0);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMySQL;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterPostgres extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: postgresClient,\n * storeType: 'knex', // required only for Knex instance\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n const q = {\n name: 'rlflx-clear-expired',\n text: `DELETE FROM ${this.tableName} WHERE expire < $1`,\n values: [expire],\n };\n this._query(q)\n .then(() => {\n resolve();\n })\n .catch(() => {\n // Deleting expired query is not critical\n resolve();\n });\n });\n }\n\n /**\n * Delete all rows expired 1 hour ago once per 5 minutes\n *\n * @private\n */\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return Promise.resolve(this.client);\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n case 'typeorm':\n return Promise.resolve(this.client.driver.master);\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return true;\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n case 'typeorm':\n return true;\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createTable() {\n return new Promise((resolve, reject) => {\n this._query({\n text: this._getCreateTableStmt(),\n })\n .then(() => {\n resolve();\n })\n .catch((err) => {\n if (err.code === '23505') {\n // Error: duplicate key value violates unique constraint \"pg_type_typname_nsp_index\"\n // Postgres doesn't handle concurrent table creation\n // It is supposed, that table is created by another worker\n resolve();\n } else {\n reject(err);\n }\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS ${this.tableName} ( \n key varchar(255) PRIMARY KEY,\n points integer NOT NULL DEFAULT 0,\n expire bigint\n );`;\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n const constructorName = this.client.constructor.name;\n\n if (typeof value === 'undefined') {\n if (constructorName === 'Client') {\n value = 'client';\n } else if (\n constructorName === 'Pool' ||\n constructorName === 'BoundPool'\n ) {\n value = 'pool';\n } else if (constructorName === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n\n this._clientType = value.toLowerCase();\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const row = result.rows[0];\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _query(q) {\n const prefix = this.tableName.toLowerCase();\n const queryObj = { name: `${prefix}:${q.name}`, text: q.text, values: q.values };\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(queryObj)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n const newExpire = msDuration > 0 ? Date.now() + msDuration : null;\n const expireQ = forceExpire\n ? ' $3 '\n : ` CASE\n WHEN ${this.tableName}.expire <= $4 THEN $3\n ELSE ${this.tableName}.expire\n END `;\n\n return this._query({\n name: forceExpire ? 'rlflx-upsert-force' : 'rlflx-upsert',\n text: `\n INSERT INTO ${this.tableName} VALUES ($1, $2, $3)\n ON CONFLICT(key) DO UPDATE SET\n points = CASE\n WHEN (${this.tableName}.expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2\n ELSE ${this.tableName}.points + ($2)\n END,\n expire = ${expireQ}\n RETURNING points, expire;`,\n values: [key, points, newExpire, Date.now()],\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._query({\n name: 'rlflx-get',\n text: `\n SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,\n values: [rlKey, Date.now()],\n })\n .then((res) => {\n if (res.rowCount === 0) {\n res = null;\n }\n resolve(res);\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return this._query({\n name: 'rlflx-delete',\n text: `DELETE FROM ${this.tableName} WHERE key = $1`,\n values: [rlKey],\n })\n .then(res => res.rowCount > 0);\n }\n}\n\nmodule.exports = RateLimiterPostgres;\n", "module.exports = class Record {\n /**\n *\n * @param value int\n * @param expiresAt Date|int\n * @param timeoutId\n */\n constructor(value, expiresAt, timeoutId = null) {\n this.value = value;\n this.expiresAt = expiresAt;\n this.timeoutId = timeoutId;\n }\n\n get value() {\n return this._value;\n }\n\n set value(value) {\n this._value = parseInt(value);\n }\n\n get expiresAt() {\n return this._expiresAt;\n }\n\n set expiresAt(value) {\n if (!(value instanceof Date) && Number.isInteger(value)) {\n value = new Date(value);\n }\n this._expiresAt = value;\n }\n\n get timeoutId() {\n return this._timeoutId;\n }\n\n set timeoutId(value) {\n this._timeoutId = value;\n }\n};\n", "const Record = require('./Record');\nconst RateLimiterRes = require('../../RateLimiterRes');\n\nmodule.exports = class MemoryStorage {\n constructor() {\n /**\n * @type {Object.}\n * @private\n */\n this._storage = {};\n }\n\n incrby(key, value, durationSec) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n if (msBeforeExpires !== 0) {\n // Change value\n this._storage[key].value = this._storage[key].value + value;\n\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n\n if (this._storage[key] && this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n\n this._storage[key] = new Record(\n value,\n durationMs > 0 ? new Date(Date.now() + durationMs) : null\n );\n if (durationMs > 0) {\n this._storage[key].timeoutId = setTimeout(() => {\n delete this._storage[key];\n }, durationMs);\n if (this._storage[key].timeoutId.unref) {\n this._storage[key].timeoutId.unref();\n }\n }\n\n return new RateLimiterRes(0, durationMs === 0 ? -1 : durationMs, this._storage[key].value, true);\n }\n\n /**\n *\n * @param key\n * @returns {*}\n */\n get(key) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n return null;\n }\n\n /**\n *\n * @param key\n * @returns {boolean}\n */\n delete(key) {\n if (this._storage[key]) {\n if (this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n delete this._storage[key];\n return true;\n }\n return false;\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst MemoryStorage = require('./component/MemoryStorage/MemoryStorage');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemory extends RateLimiterAbstract {\n constructor(opts = {}) {\n super(opts);\n\n this._memoryStorage = new MemoryStorage();\n }\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\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\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 reject(res);\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n });\n }\n\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\n\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\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\n this._memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, initPoints)\n );\n }\n\n set(key, points, secDuration) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n\n this._memoryStorage.set(this.getKey(key), points, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, points)\n );\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\n return Promise.resolve(res);\n }\n\n delete(key) {\n return Promise.resolve(this._memoryStorage.delete(this.getKey(key)));\n }\n}\n\nmodule.exports = RateLimiterMemory;\n\n", "/**\n * Implements rate limiting in cluster using built-in IPC\n *\n * Two classes are described here: master and worker\n * Master have to be create in the master process without any options.\n * Any number of rate limiters can be created in workers, but each rate limiter must be with unique keyPrefix\n *\n * Workflow:\n * 1. master rate limiter created in master process\n * 2. worker rate limiter sends 'init' message with necessary options during creating\n * 3. master receives options and adds new rate limiter by keyPrefix if it isn't created yet\n * 4. master sends 'init' back to worker's rate limiter\n * 5. worker can process requests immediately,\n * but they will be postponed by 'workerWaitInit' until master sends 'init' to worker\n * 6. every request to worker rate limiter creates a promise\n * 7. if master doesn't response for 'timeout', promise is rejected\n * 8. master sends 'resolve' or 'reject' command to worker\n * 9. worker resolves or rejects promise depending on message from master\n *\n */\n\nconst cluster = require('cluster');\nconst crypto = require('crypto');\nconst RateLimiterAbstract = require('./RateLimiterAbstract');\nconst RateLimiterMemory = require('./RateLimiterMemory');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst channel = 'rate_limiter_flexible';\nlet masterInstance = null;\n\nconst masterSendToWorker = function (worker, msg, type, res) {\n let data;\n if (res === null || res === true || res === false) {\n data = res;\n } else {\n data = {\n remainingPoints: res.remainingPoints,\n msBeforeNext: res.msBeforeNext,\n consumedPoints: res.consumedPoints,\n isFirstInDuration: res.isFirstInDuration,\n };\n }\n worker.send({\n channel,\n keyPrefix: msg.keyPrefix, // which rate limiter exactly\n promiseId: msg.promiseId,\n type,\n data,\n });\n};\n\nconst workerWaitInit = function (payload) {\n setTimeout(() => {\n if (this._initiated) {\n process.send(payload);\n // Promise will be removed by timeout if too long\n } else if (typeof this._promises[payload.promiseId] !== 'undefined') {\n workerWaitInit.call(this, payload);\n }\n }, 30);\n};\n\nconst workerSendToMaster = function (func, promiseId, key, arg, opts) {\n const payload = {\n channel,\n keyPrefix: this.keyPrefix,\n func,\n promiseId,\n data: {\n key,\n arg,\n opts,\n },\n };\n\n if (!this._initiated) {\n // Wait init before sending messages to master\n workerWaitInit.call(this, payload);\n } else {\n process.send(payload);\n }\n};\n\nconst masterProcessMsg = function (worker, msg) {\n if (!msg || msg.channel !== channel || typeof this._rateLimiters[msg.keyPrefix] === 'undefined') {\n return false;\n }\n\n let promise;\n\n switch (msg.func) {\n case 'consume':\n promise = this._rateLimiters[msg.keyPrefix].consume(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'penalty':\n promise = this._rateLimiters[msg.keyPrefix].penalty(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'reward':\n promise = this._rateLimiters[msg.keyPrefix].reward(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'block':\n promise = this._rateLimiters[msg.keyPrefix].block(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'get':\n promise = this._rateLimiters[msg.keyPrefix].get(msg.data.key, msg.data.opts);\n break;\n case 'delete':\n promise = this._rateLimiters[msg.keyPrefix].delete(msg.data.key, msg.data.opts);\n break;\n default:\n return false;\n }\n\n if (promise) {\n promise\n .then((res) => {\n masterSendToWorker(worker, msg, 'resolve', res);\n })\n .catch((rejRes) => {\n masterSendToWorker(worker, msg, 'reject', rejRes);\n });\n }\n};\n\nconst workerProcessMsg = function (msg) {\n if (!msg || msg.channel !== channel || msg.keyPrefix !== this.keyPrefix) {\n return false;\n }\n\n if (this._promises[msg.promiseId]) {\n clearTimeout(this._promises[msg.promiseId].timeoutId);\n let res;\n if (msg.data === null || msg.data === true || msg.data === false) {\n res = msg.data;\n } else {\n res = new RateLimiterRes(\n msg.data.remainingPoints,\n msg.data.msBeforeNext,\n msg.data.consumedPoints,\n msg.data.isFirstInDuration // eslint-disable-line comma-dangle\n );\n }\n\n switch (msg.type) {\n case 'resolve':\n this._promises[msg.promiseId].resolve(res);\n break;\n case 'reject':\n this._promises[msg.promiseId].reject(res);\n break;\n default:\n throw new Error(`RateLimiterCluster: no such message type '${msg.type}'`);\n }\n\n delete this._promises[msg.promiseId];\n }\n};\n/**\n * Prepare options to send to master\n * Master will create rate limiter depending on options\n *\n * @returns {{points: *, duration: *, blockDuration: *, execEvenly: *, execEvenlyMinDelayMs: *, keyPrefix: *}}\n */\nconst getOpts = function () {\n return {\n points: this.points,\n duration: this.duration,\n blockDuration: this.blockDuration,\n execEvenly: this.execEvenly,\n execEvenlyMinDelayMs: this.execEvenlyMinDelayMs,\n keyPrefix: this.keyPrefix,\n };\n};\n\nconst savePromise = function (resolve, reject) {\n const hrtime = process.hrtime();\n let promiseId = hrtime[0].toString() + hrtime[1].toString();\n\n if (typeof this._promises[promiseId] !== 'undefined') {\n promiseId += crypto.randomBytes(12).toString('base64');\n }\n\n this._promises[promiseId] = {\n resolve,\n reject,\n timeoutId: setTimeout(() => {\n delete this._promises[promiseId];\n reject(new Error('RateLimiterCluster timeout: no answer from master in time'));\n }, this.timeoutMs),\n };\n\n return promiseId;\n};\n\nclass RateLimiterClusterMaster {\n constructor() {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n cluster.setMaxListeners(0);\n\n cluster.on('message', (worker, msg) => {\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n worker.send({\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n });\n } else {\n masterProcessMsg.call(this, worker, msg);\n }\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterMasterPM2 {\n constructor(pm2) {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n pm2.launchBus((err, pm2Bus) => {\n pm2Bus.on('process:msg', (packet) => {\n const msg = packet.raw;\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n pm2.sendDataToProcessId(packet.process.pm_id, {\n data: {},\n topic: channel,\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n }, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n } else {\n const worker = {\n send: (msgData) => {\n const pm2Message = msgData;\n pm2Message.topic = channel;\n if (typeof pm2Message.data === 'undefined') {\n pm2Message.data = {};\n }\n pm2.sendDataToProcessId(packet.process.pm_id, pm2Message, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n },\n };\n masterProcessMsg.call(this, worker, msg);\n }\n });\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterWorker extends RateLimiterAbstract {\n get timeoutMs() {\n return this._timeoutMs;\n }\n\n set timeoutMs(value) {\n this._timeoutMs = typeof value === 'undefined' ? 5000 : Math.abs(parseInt(value));\n }\n\n constructor(opts = {}) {\n super(opts);\n\n process.setMaxListeners(0);\n\n this.timeoutMs = opts.timeoutMs;\n\n this._initiated = false;\n\n process.on('message', (msg) => {\n if (msg && msg.channel === channel && msg.type === 'init' && msg.keyPrefix === this.keyPrefix) {\n this._initiated = true;\n } else {\n workerProcessMsg.call(this, msg);\n }\n });\n\n // Create limiter on master with specific options\n process.send({\n channel,\n type: 'init',\n opts: getOpts.call(this),\n });\n\n this._promises = {};\n }\n\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'consume', promiseId, key, pointsToConsume, options);\n });\n }\n\n penalty(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'penalty', promiseId, key, points, options);\n });\n }\n\n reward(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'reward', promiseId, key, points, options);\n });\n }\n\n block(key, secDuration, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'block', promiseId, key, secDuration, options);\n });\n }\n\n get(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'get', promiseId, key, options);\n });\n }\n\n delete(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'delete', promiseId, key, options);\n });\n }\n}\n\nmodule.exports = {\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster: RateLimiterClusterWorker,\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemcache extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: memcacheClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.client = opts.storeClient;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(result.consumedPoints);\n res.isFirstInDuration = result.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = result.msBeforeNext;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n const secDuration = Math.floor(msDuration / 1000);\n\n if (forceExpire) {\n this.client.set(rlKey, points, secDuration, (err) => {\n if (!err) {\n this.client.set(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n } else {\n reject(err);\n }\n });\n } else {\n this.client.incr(rlKey, points, (err, consumedPoints) => {\n if (err || consumedPoints === false) {\n this.client.add(rlKey, points, secDuration, (errAddKey, createdNew) => {\n if (errAddKey || !createdNew) {\n // Try to upsert again in case of race condition\n if (typeof options.attemptNumber === 'undefined' || options.attemptNumber < 3) {\n const nextOptions = Object.assign({}, options);\n nextOptions.attemptNumber = nextOptions.attemptNumber ? (nextOptions.attemptNumber + 1) : 1;\n\n this._upsert(rlKey, points, msDuration, forceExpire, nextOptions)\n .then(resUpsert => resolve(resUpsert))\n .catch(errUpsert => reject(errUpsert));\n } else {\n reject(new Error('Can not add key'));\n }\n } else {\n this.client.add(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n }\n });\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n\n this.client.get(rlKey, (err, consumedPoints) => {\n if (!consumedPoints) {\n resolve(null);\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else if (res === false) {\n resolve(res);\n } else {\n this.client.del(`${rlKey}_expire`, (errDelExpire) => {\n if (errDelExpire) {\n reject(errDelExpire);\n } else {\n resolve(res);\n }\n });\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMemcache;\n", "const RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RLWrapperBlackAndWhite {\n constructor(opts = {}) {\n this.limiter = opts.limiter;\n this.blackList = opts.blackList;\n this.whiteList = opts.whiteList;\n this.isBlackListed = opts.isBlackListed;\n this.isWhiteListed = opts.isWhiteListed;\n this.runActionAnyway = opts.runActionAnyway;\n }\n\n get limiter() {\n return this._limiter;\n }\n\n set limiter(value) {\n if (typeof value === 'undefined') {\n throw new Error('limiter is not set');\n }\n\n this._limiter = value;\n }\n\n get runActionAnyway() {\n return this._runActionAnyway;\n }\n\n set runActionAnyway(value) {\n this._runActionAnyway = typeof value === 'undefined' ? false : value;\n }\n\n get blackList() {\n return this._blackList;\n }\n\n set blackList(value) {\n this._blackList = Array.isArray(value) ? value : [];\n }\n\n get isBlackListed() {\n return this._isBlackListed;\n }\n\n set isBlackListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isBlackListed must be function');\n }\n this._isBlackListed = func;\n }\n\n get whiteList() {\n return this._whiteList;\n }\n\n set whiteList(value) {\n this._whiteList = Array.isArray(value) ? value : [];\n }\n\n get isWhiteListed() {\n return this._isWhiteListed;\n }\n\n set isWhiteListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isWhiteListed must be function');\n }\n this._isWhiteListed = func;\n }\n\n isBlackListedSomewhere(key) {\n return this.blackList.indexOf(key) >= 0 || this.isBlackListed(key);\n }\n\n isWhiteListedSomewhere(key) {\n return this.whiteList.indexOf(key) >= 0 || this.isWhiteListed(key);\n }\n\n getBlackRes() {\n return new RateLimiterRes(0, Number.MAX_SAFE_INTEGER, 0, false);\n }\n\n getWhiteRes() {\n return new RateLimiterRes(Number.MAX_SAFE_INTEGER, 0, 0, false);\n }\n\n rejectBlack() {\n return Promise.reject(this.getBlackRes());\n }\n\n resolveBlack() {\n return Promise.resolve(this.getBlackRes());\n }\n\n resolveWhite() {\n return Promise.resolve(this.getWhiteRes());\n }\n\n consume(key, pointsToConsume = 1) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.rejectBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.consume(key, pointsToConsume);\n }\n\n if (this.runActionAnyway) {\n this.limiter.consume(key, pointsToConsume).catch(() => {});\n }\n return res;\n }\n\n block(key, secDuration) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.block(key, secDuration);\n }\n\n if (this.runActionAnyway) {\n this.limiter.block(key, secDuration).catch(() => {});\n }\n return res;\n }\n\n penalty(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.penalty(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.penalty(key, points).catch(() => {});\n }\n return res;\n }\n\n reward(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.reward(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.reward(key, points).catch(() => {});\n }\n return res;\n }\n\n get(key) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined' || this.runActionAnyway) {\n return this.limiter.get(key);\n }\n\n return res;\n }\n\n delete(key) {\n return this.limiter.delete(key);\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\n\nmodule.exports = class RateLimiterUnion {\n constructor(...limiters) {\n if (limiters.length < 1) {\n throw new Error('RateLimiterUnion: at least one limiter have to be passed');\n }\n limiters.forEach((limiter) => {\n if (!(limiter instanceof RateLimiterAbstract)) {\n throw new Error('RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract');\n }\n });\n\n this._limiters = limiters;\n }\n\n consume(key, points = 1) {\n return new Promise((resolve, reject) => {\n const promises = [];\n this._limiters.forEach((limiter) => {\n promises.push(limiter.consume(key, points).catch(rej => ({ rejected: true, rej })));\n });\n\n Promise.all(promises)\n .then((res) => {\n const resObj = {};\n let rejected = false;\n\n res.forEach((item) => {\n if (item.rejected === true) {\n rejected = true;\n }\n });\n\n for (let i = 0; i < res.length; i++) {\n if (rejected && res[i].rejected === true) {\n resObj[this._limiters[i].keyPrefix] = res[i].rej;\n } else if (!rejected) {\n resObj[this._limiters[i].keyPrefix] = res[i];\n }\n }\n\n if (rejected) {\n reject(resObj);\n } else {\n resolve(resObj);\n }\n });\n });\n }\n};\n", "module.exports = class RateLimiterQueueError extends Error {\n constructor(message, extra) {\n super();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = 'CustomError';\n this.message = message;\n if (extra) {\n this.extra = extra;\n }\n }\n};\n", "const RateLimiterQueueError = require('./component/RateLimiterQueueError')\nconst MAX_QUEUE_SIZE = 4294967295;\nconst KEY_DEFAULT = 'limiter';\n\nmodule.exports = class RateLimiterQueue {\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n }) {\n this._queueLimiters = {\n KEY_DEFAULT: new RateLimiterQueueInternal(limiterFlexible, opts)\n };\n this._limiterFlexible = limiterFlexible;\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining(key = KEY_DEFAULT) {\n if (this._queueLimiters[key]) {\n return this._queueLimiters[key].getTokensRemaining()\n } else {\n return Promise.resolve(this._limiterFlexible.points)\n }\n }\n\n removeTokens(tokens, key = KEY_DEFAULT) {\n if (!this._queueLimiters[key]) {\n this._queueLimiters[key] = new RateLimiterQueueInternal(\n this._limiterFlexible, {\n key,\n maxQueueSize: this._maxQueueSize,\n })\n }\n\n return this._queueLimiters[key].removeTokens(tokens)\n }\n};\n\nclass RateLimiterQueueInternal {\n\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n key: KEY_DEFAULT,\n }) {\n this._key = opts.key;\n this._waitTimeout = null;\n this._queue = [];\n this._limiterFlexible = limiterFlexible;\n\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining() {\n return this._limiterFlexible.get(this._key)\n .then((rlRes) => {\n return rlRes !== null ? rlRes.remainingPoints : this._limiterFlexible.points;\n })\n }\n\n removeTokens(tokens) {\n const _this = this;\n\n return new Promise((resolve, reject) => {\n if (tokens > _this._limiterFlexible.points) {\n reject(new RateLimiterQueueError(`Requested tokens ${tokens} exceeds maximum ${_this._limiterFlexible.points} tokens per interval`));\n return\n }\n\n if (_this._queue.length > 0) {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n } else {\n _this._limiterFlexible.consume(_this._key, tokens)\n .then((res) => {\n resolve(res.remainingPoints);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n reject(rej);\n } else {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n })\n }\n\n _queueRequest(resolve, reject, tokens) {\n const _this = this;\n if (_this._queue.length < _this._maxQueueSize) {\n _this._queue.push({resolve, reject, tokens});\n } else {\n reject(new RateLimiterQueueError(`Number of requests reached it's maximum ${_this._maxQueueSize}`))\n }\n }\n\n _processFIFO() {\n const _this = this;\n\n if (_this._waitTimeout !== null) {\n clearTimeout(_this._waitTimeout);\n _this._waitTimeout = null;\n }\n\n if (_this._queue.length === 0) {\n return;\n }\n\n const item = _this._queue.shift();\n _this._limiterFlexible.consume(_this._key, item.tokens)\n .then((res) => {\n item.resolve(res.remainingPoints);\n _this._processFIFO.call(_this);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n item.reject(rej);\n _this._processFIFO.call(_this);\n } else {\n _this._queue.unshift(item);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n}\n", "const RateLimiterRes = require(\"./RateLimiterRes\");\n\n/**\n * Bursty rate limiter exposes only msBeforeNext time and doesn't expose points from bursty limiter by default\n * @type {BurstyRateLimiter}\n */\nmodule.exports = class BurstyRateLimiter {\n constructor(rateLimiter, burstLimiter) {\n this._rateLimiter = rateLimiter;\n this._burstLimiter = burstLimiter\n }\n\n /**\n * Merge rate limiter response objects. Responses can be null\n *\n * @param {RateLimiterRes} [rlRes] Rate limiter response\n * @param {RateLimiterRes} [blRes] Bursty limiter response\n */\n _combineRes(rlRes, blRes) {\n if (!rlRes) {\n return null\n }\n\n return new RateLimiterRes(\n rlRes.remainingPoints,\n Math.min(rlRes.msBeforeNext, blRes ? blRes.msBeforeNext : 0),\n rlRes.consumedPoints,\n rlRes.isFirstInDuration\n )\n }\n\n /**\n * @param key\n * @param pointsToConsume\n * @param options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return this._rateLimiter.consume(key, pointsToConsume, options)\n .catch((rlRej) => {\n if (rlRej instanceof RateLimiterRes) {\n return this._burstLimiter.consume(key, pointsToConsume, options)\n .then((blRes) => {\n return Promise.resolve(this._combineRes(rlRej, blRes))\n })\n .catch((blRej) => {\n if (blRej instanceof RateLimiterRes) {\n return Promise.reject(this._combineRes(rlRej, blRej))\n } else {\n return Promise.reject(blRej)\n }\n }\n )\n } else {\n return Promise.reject(rlRej)\n }\n })\n }\n\n /**\n * It doesn't expose available points from burstLimiter\n *\n * @param key\n * @returns {Promise}\n */\n get(key) {\n return Promise.all([\n this._rateLimiter.get(key),\n this._burstLimiter.get(key),\n ]).then(([rlRes, blRes]) => {\n return this._combineRes(rlRes, blRes);\n });\n }\n\n get points() {\n return this._rateLimiter.points;\n }\n};\n", "const RateLimiterRedis = require('./lib/RateLimiterRedis');\nconst RateLimiterMongo = require('./lib/RateLimiterMongo');\nconst RateLimiterMySQL = require('./lib/RateLimiterMySQL');\nconst RateLimiterPostgres = require('./lib/RateLimiterPostgres');\nconst {RateLimiterClusterMaster, RateLimiterClusterMasterPM2, RateLimiterCluster} = require('./lib/RateLimiterCluster');\nconst RateLimiterMemory = require('./lib/RateLimiterMemory');\nconst RateLimiterMemcache = require('./lib/RateLimiterMemcache');\nconst RLWrapperBlackAndWhite = require('./lib/RLWrapperBlackAndWhite');\nconst RateLimiterUnion = require('./lib/RateLimiterUnion');\nconst RateLimiterQueue = require('./lib/RateLimiterQueue');\nconst BurstyRateLimiter = require('./lib/BurstyRateLimiter');\nconst RateLimiterRes = require('./lib/RateLimiterRes');\n\nmodule.exports = {\n RateLimiterRedis,\n RateLimiterMongo,\n RateLimiterMySQL,\n RateLimiterPostgres,\n RateLimiterMemory,\n RateLimiterMemcache,\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster,\n RLWrapperBlackAndWhite,\n RateLimiterUnion,\n RateLimiterQueue,\n BurstyRateLimiter,\n RateLimiterRes,\n};\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hash provides interface for hash functions.\n */\n\n/**\n * Hash interface describes properties of\n * cryptographic hash functions.\n */\nexport interface Hash {\n readonly digestLength: number;\n readonly blockSize: number;\n update(data: Uint8Array): this;\n reset(): this;\n finish(out: Uint8Array): this;\n digest(): Uint8Array;\n clean(): void;\n}\n\nexport interface SerializableHash extends Hash {\n saveState(): any;\n restoreState(savedState: any): this;\n cleanSavedState(savedState: any): void;\n}\n\nexport function isSerializableHash(h: Hash): h is SerializableHash {\n return (\n typeof (h as SerializableHash).saveState !== \"undefined\" &&\n typeof (h as SerializableHash).restoreState !== \"undefined\" &&\n typeof (h as SerializableHash).cleanSavedState !== \"undefined\"\n );\n}\n\n// TODO(dchest): figure out the standardized interface for XOF such as\n// SHAKE and BLAKE2X.\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nexport function select(subject: number, resultIfOne: number, resultIfZero: number): number {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\n\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nexport function lessOrEqual(a: number, b: number): number {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\n\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nexport function compare(a: Uint8Array, b: Uint8Array): number {\n if (a.length !== b.length) {\n return 0;\n }\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\n\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package wipe implements functions for zeroing arrays.\n */\n\nexport type NumericArray = number[] | Uint8Array | Int8Array | Uint16Array\n | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;\n\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nexport function wipe(array: NumericArray): NumericArray {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (let i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hmac implements HMAC algorithm.\n */\n\nimport { Hash, SerializableHash, isSerializableHash } from \"@stablelib/hash\";\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC implements hash-based message authentication algorithm.\n */\nexport class HMAC implements SerializableHash {\n readonly blockSize: number;\n readonly digestLength: number;\n\n private _inner: Hash; // inner hash\n private _outer: Hash; // outer hash\n\n private _finished = false; // true if HMAC was finalized\n\n // Copies of hash states after keying.\n // Need for quick reset without hashing the key again.\n private _innerKeyedState: any | undefined;\n private _outerKeyedState: any | undefined;\n\n /**\n * Constructs a new HMAC with the given Hash and secret key.\n */\n constructor(hash: new () => Hash | SerializableHash, key: Uint8Array) {\n // Initialize inner and outer hashes.\n this._inner = new hash();\n this._outer = new hash();\n\n // Set block and digest sizes for this HMAC\n // instance to values from the hash.\n this.blockSize = this._outer.blockSize;\n this.digestLength = this._outer.digestLength;\n\n // Pad temporary stores a key (or its hash) padded with zeroes.\n const pad = new Uint8Array(this.blockSize);\n\n if (key.length > this.blockSize) {\n // If key is bigger than hash block size, it must be\n // hashed and this hash is used as a key instead.\n this._inner.update(key).finish(pad).clean();\n } else {\n // Otherwise, copy the key into pad.\n pad.set(key);\n }\n\n // Now two different keys are derived from padded key\n // by xoring a different byte value to each.\n\n // To make inner hash key, xor byte 0x36 into pad.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n // Update inner hash with the result.\n this._inner.update(pad);\n\n // To make outer hash key, xor byte 0x5c into pad.\n // But since we already xored 0x36 there, we must\n // first undo this by xoring it again.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n // Update outer hash with the result.\n this._outer.update(pad);\n\n // Save states of both hashes, so that we can quickly restore\n // them later in reset() without the need to remember the actual\n // key and perform this initialization again.\n if (isSerializableHash(this._inner) && isSerializableHash(this._outer)) {\n this._innerKeyedState = this._inner.saveState();\n this._outerKeyedState = this._outer.saveState();\n }\n\n // Clean pad.\n wipe(pad);\n }\n\n /**\n * Returns HMAC state to the state initialized with key\n * to make it possible to run HMAC over the other data with the same\n * key without creating a new instance.\n */\n reset(): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't reset() because hash doesn't implement restoreState()\");\n }\n // Restore keyed states of inner and outer hashes.\n this._inner.restoreState(this._innerKeyedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans HMAC state.\n */\n clean() {\n if (isSerializableHash(this._inner)) {\n this._inner.cleanSavedState(this._innerKeyedState);\n }\n if (isSerializableHash(this._outer)) {\n this._outer.cleanSavedState(this._outerKeyedState);\n }\n this._inner.clean();\n this._outer.clean();\n }\n\n /**\n * Updates state with provided data.\n */\n update(data: Uint8Array): this {\n this._inner.update(data);\n return this;\n }\n\n /**\n * Finalizes HMAC and puts the result in out.\n */\n finish(out: Uint8Array): this {\n if (this._finished) {\n // If HMAC was finalized, outer hash is also finalized,\n // so it produces the same digest it produced when it\n // was finalized.\n this._outer.finish(out);\n return this;\n }\n\n // Finalize inner hash and store the result temporarily.\n this._inner.finish(out);\n\n // Update outer hash with digest of inner hash and and finalize it.\n this._outer.update(out.subarray(0, this.digestLength)).finish(out);\n this._finished = true;\n\n return this;\n }\n\n /**\n * Returns the computed message authentication code.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Saves HMAC state.\n * This function is needed for PBKDF2 optimization.\n */\n saveState(): any {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't saveState() because hash doesn't implement it\");\n }\n return this._inner.saveState();\n }\n\n restoreState(savedState: any): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't restoreState() because hash doesn't implement it\");\n }\n this._inner.restoreState(savedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n cleanSavedState(savedState: any) {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't cleanSavedState() because hash doesn't implement it\");\n }\n this._inner.cleanSavedState(savedState);\n }\n}\n\n/**\n * Returns HMAC using the given hash constructor for the key over data.\n */\nexport function hmac(hash: new () => Hash, key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new HMAC(hash, key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two HMAC digests are equal.\n * Uses constant-time comparison to avoid leaking timing information.\n *\n * Example:\n *\n * const receivedDigest = ...\n * const realDigest = hmac(SHA256, key, data);\n * if (!equal(receivedDigest, realDigest)) {\n * throw new Error(\"Authentication error\");\n * }\n */\nexport const equal = constantTimeEqual;\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hkdf implements HKDF key derivation function.\n */\n\nimport { Hash } from \"@stablelib/hash\";\nimport { HMAC, hmac } from \"@stablelib/hmac\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC-based Extract-and-Expand Key Derivation Function.\n *\n * Implements HKDF from RFC5869.\n *\n * Expands the given master key with salt and info into\n * a limited stream of key material.\n */\nexport class HKDF {\n private _hmac: HMAC;\n private _buffer: Uint8Array;\n private _bufpos: number;\n private _counter = new Uint8Array(1); // starts with zero\n private _hash: new () => Hash;\n private _info?: Uint8Array;\n\n /**\n * Create a new HKDF instance for the given hash function\n * with the master key, optional salt, and info.\n *\n * - Master key is a high-entropy secret key (not a password).\n * - Salt is a non-secret random value.\n * - Info is application- and/or context-specific information.\n */\n constructor(hash: new () => Hash,\n key: Uint8Array,\n salt = new Uint8Array(0),\n info?: Uint8Array) {\n\n this._hash = hash;\n this._info = info;\n\n // HKDF-Extract uses salt as HMAC key, and key as data.\n const okm = hmac(this._hash, salt, key);\n\n // Initialize HMAC for expanding with extracted key.\n this._hmac = new HMAC(hash, okm);\n\n // Allocate buffer.\n this._buffer = new Uint8Array(this._hmac.digestLength);\n this._bufpos = this._buffer.length;\n }\n\n // Fill buffer with new block of HKDF-Extract output.\n private _fillBuffer(): void {\n // Increment counter.\n this._counter[0]++;\n\n const ctr = this._counter[0];\n\n // Check if counter overflowed.\n if (ctr === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n\n // Prepare HMAC instance for new data with old key.\n this._hmac.reset();\n\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (ctr > 1) {\n this._hmac.update(this._buffer);\n }\n\n // Hash in info if it exists.\n if (this._info) {\n this._hmac.update(this._info);\n }\n\n // Hash in the counter.\n this._hmac.update(this._counter);\n\n // Output result to buffer and clean HMAC instance.\n this._hmac.finish(this._buffer);\n\n // Reset buffer position.\n this._bufpos = 0;\n }\n\n /**\n * Expand returns next key material of the given length.\n *\n * It throws if expansion limit is reached (which is\n * 254 digests of the underlying HMAC function).\n */\n expand(length: number): Uint8Array {\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i++) {\n if (this._bufpos === this._buffer.length) {\n this._fillBuffer();\n }\n out[i] = this._buffer[this._bufpos++];\n }\n return out;\n }\n\n clean(): void {\n this._hmac.clean();\n wipe(this._buffer);\n wipe(this._counter);\n this._bufpos = 0;\n }\n}\n\n// TODO(dchest): maybe implement deriveKey?\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\n\nconst QUOTA = 65536;\n\nexport class BrowserRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto?: { getRandomValues: typeof window.crypto.getRandomValues };\n\n constructor() {\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || (self as { msCrypto?: any }).msCrypto) // IE11 has msCrypto\n : null;\n\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { wipe } from \"@stablelib/wipe\";\n\ndeclare function require(name: string): any;\n\nexport class NodeRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto: { randomBytes(n: number): Uint8Array } | undefined;\n\n constructor() {\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n\n // Allocate output array.\n const out = new Uint8Array(length);\n\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n\n // Cleanup.\n wipe(buffer);\n\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { BrowserRandomSource } from \"./browser\";\nimport { NodeRandomSource } from \"./node\";\n\nexport class SystemRandomSource implements RandomSource {\n isAvailable = false;\n name = \"\";\n private _source: RandomSource;\n\n constructor() {\n // Try browser.\n this._source = new BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n\n // If no browser source, try Node.\n this._source = new NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n\n // No sources, we're out of options.\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package int provides helper functions for integerss.\n */\n\n// Shim using 16-bit pieces.\nfunction imulShim(a: number, b: number): number {\n const ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n const bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexport const mul = (Math as { imul?(a: number, b: number): number }).imul || imulShim;\n\n/** 32-bit integer addition. */\nexport function add(a: number, b: number): number {\n return (a + b) | 0;\n}\n\n/** 32-bit integer subtraction. */\nexport function sub(a: number, b: number): number {\n return (a - b) | 0;\n}\n\n/** 32-bit integer left rotation */\nexport function rotl(x: number, n: number): number {\n return x << n | x >>> (32 - n);\n}\n\n/** 32-bit integer left rotation */\nexport function rotr(x: number, n: number): number {\n return x << (32 - n) | x >>> n;\n}\n\nfunction isIntegerShim(n: number): boolean {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexport const isInteger = (Number as { isInteger?(n: number): boolean }).isInteger || isIntegerShim;\n\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexport const MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexport const isSafeInteger = (n: number): boolean =>\n isInteger(n) && (n >= -MAX_SAFE_INTEGER && n <= MAX_SAFE_INTEGER);\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\n\nimport { isSafeInteger } from \"@stablelib/int\";\n\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16BE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16BE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16LE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\n\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16BE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\n\nexport const writeInt16BE = writeUint16BE;\n\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16LE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\n\nexport const writeInt16LE = writeUint16LE;\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32BE(array: Uint8Array, offset = 0): number {\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32BE(array: Uint8Array, offset = 0): number {\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32LE(array: Uint8Array, offset = 0): number {\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\n\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\n\nexport const writeInt32BE = writeUint32BE;\n\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\n\n\nexport const writeInt32LE = writeUint32LE;\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64BE(array: Uint8Array, offset = 0): number {\n const hi = readInt32BE(array, offset);\n const lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64BE(array: Uint8Array, offset = 0): number {\n const hi = readUint32BE(array, offset);\n const lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64LE(array: Uint8Array, offset = 0): number {\n const lo = readInt32LE(array, offset);\n const hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64LE(array: Uint8Array, offset = 0): number {\n const lo = readUint32LE(array, offset);\n const hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64BE = writeUint64BE;\n\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64LE = writeUint64LE;\n\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintBE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintLE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintBE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n let div = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintLE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n let div = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\n\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\n\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\n\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\n\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package random provides functions to access system's\n * cryptographically secure random byte generator.\n */\n\nimport { RandomSource } from \"./source\";\nimport { SystemRandomSource } from \"./source/system\";\nimport { readUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { RandomSource } from \"./source\";\n\nexport const defaultRandomSource = new SystemRandomSource();\n\nexport function randomBytes(length: number, prng: RandomSource = defaultRandomSource): Uint8Array {\n return prng.randomBytes(length);\n}\n\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nexport function randomUint32(prng: RandomSource = defaultRandomSource): number {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = readUint32LE(buf);\n\n // Clean the buffer.\n wipe(buf);\n\n return result;\n}\n\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomString(\n length: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n wipe(buf);\n }\n return out;\n}\n\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomStringForEntropy(\n bits: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package x25519 implements X25519 key agreement.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 32;\nexport const SHARED_KEY_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../sign/ed25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which is ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst _121665 = gf([0xdb41, 1]);\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, inp: GF) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\n\nexport function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n\n unpack25519(x, p);\n\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n\n a[0] = d[0] = 1;\n\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\n\nexport function scalarMultBase(n: Uint8Array): Uint8Array {\n return scalarMult(n, _9);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nexport function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {\n if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n\n const result = scalarMult(mySecretKey, theirPublicKey);\n\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n\n return result;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package sha256 implements SHA-2-256 cryptographic hash function.\n */\n\nimport { SerializableHash } from \"@stablelib/hash\";\nimport { readUint32BE, writeUint32BE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 32;\nexport const BLOCK_SIZE = 64;\n\n/**\n * SHA2-256 cryptographic hash algorithm.\n */\nexport class SHA256 implements SerializableHash {\n /** Length of hash output */\n readonly digestLength: number = DIGEST_LENGTH;\n\n /** Block size */\n readonly blockSize: number = BLOCK_SIZE;\n\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n protected _state = new Int32Array(8); // hash state\n private _temp = new Int32Array(64); // temporary state\n private _buffer = new Uint8Array(128); // buffer for data to hash\n private _bufferLength = 0; // number of bytes in buffer\n private _bytesHashed = 0; // number of total bytes hashed\n private _finished = false; // indicates whether the hash was finalized\n\n constructor() {\n this.reset();\n }\n\n protected _initState() {\n this._state[0] = 0x6a09e667;\n this._state[1] = 0xbb67ae85;\n this._state[2] = 0x3c6ef372;\n this._state[3] = 0xa54ff53a;\n this._state[4] = 0x510e527f;\n this._state[5] = 0x9b05688c;\n this._state[6] = 0x1f83d9ab;\n this._state[7] = 0x5be0cd19;\n }\n\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n reset(): this {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans internal buffers and resets hash state.\n */\n clean() {\n wipe(this._buffer);\n wipe(this._temp);\n this.reset();\n }\n\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n update(data: Uint8Array, dataLength: number = data.length): this {\n if (this._finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n let dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < this.blockSize && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n }\n\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n finish(out: Uint8Array): this {\n if (!this._finished) {\n const bytesHashed = this._bytesHashed;\n const left = this._bufferLength;\n const bitLenHi = (bytesHashed / 0x20000000) | 0;\n const bitLenLo = bytesHashed << 3;\n const padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n\n this._buffer[left] = 0x80;\n for (let i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n\n hashBlocks(this._temp, this._state, this._buffer, 0, padLength);\n\n this._finished = true;\n }\n\n for (let i = 0; i < this.digestLength / 4; i++) {\n writeUint32BE(this._state[i], out, i * 4);\n }\n\n return this;\n }\n\n /**\n * Returns the final hash digest.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Returns hash state to be used with restoreState().\n * Only chain value is saved, not buffers or other\n * state variables.\n */\n saveState(): SavedState {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n state: new Int32Array(this._state),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Restores state saved by saveState() and sets bytesHashed\n * to the given value.\n */\n restoreState(savedState: SavedState): this {\n this._state.set(savedState.state);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans state returned by saveState().\n */\n cleanSavedState(savedState: SavedState) {\n wipe(savedState.state);\n if (savedState.buffer) {\n wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n }\n}\n\nexport type SavedState = {\n state: Int32Array;\n buffer: Uint8Array | undefined;\n bufferLength: number;\n bytesHashed: number;\n};\n\n// Constants\nconst K = new Int32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\nfunction hashBlocks(w: Int32Array, v: Int32Array, p: Uint8Array, pos: number, len: number): number {\n while (len >= 64) {\n let a = v[0];\n let b = v[1];\n let c = v[2];\n let d = v[3];\n let e = v[4];\n let f = v[5];\n let g = v[6];\n let h = v[7];\n\n for (let i = 0; i < 16; i++) {\n let j = pos + i * 4;\n w[i] = readUint32BE(p, j);\n }\n\n for (let i = 16; i < 64; i++) {\n let u = w[i - 2];\n let t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n\n u = w[i - 15];\n let t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n\n for (let i = 0; i < 64; i++) {\n let t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n\n let t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (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 v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n\n pos += 64;\n len -= 64;\n }\n return pos;\n}\n\nexport function hash(data: Uint8Array): Uint8Array {\n const h = new SHA256();\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha implements ChaCha stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\n// Number of ChaCha rounds (ChaCha20).\nconst ROUNDS = 20;\n\n// Applies the ChaCha core function to 16-byte input,\n// 32-byte key key, and puts the result into 64-byte array out.\nfunction core(out: Uint8Array, input: Uint8Array, key: Uint8Array): void {\n let j0 = 0x61707865; // \"expa\" -- ChaCha's \"sigma\" constant\n let j1 = 0x3320646E; // \"nd 3\" for 32-byte keys\n let j2 = 0x79622D32; // \"2-by\"\n let j3 = 0x6B206574; // \"te k\"\n let j4 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let j5 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let j6 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let j7 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let j8 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let j9 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let j10 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let j11 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let j12 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n let j13 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n let j14 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n let j15 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n\n let x0 = j0;\n let x1 = j1;\n let x2 = j2;\n let x3 = j3;\n let x4 = j4;\n let x5 = j5;\n let x6 = j6;\n let x7 = j7;\n let x8 = j8;\n let x9 = j9;\n let x10 = j10;\n let x11 = j11;\n let x12 = j12;\n let x13 = j13;\n let x14 = j14;\n let x15 = j15;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 16) | x12 << 16;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 12) | x4 << 12;\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 16) | x13 << 16;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 12) | x5 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 16) | x14 << 16;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 12) | x6 << 12;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 16) | x15 << 16;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 12) | x7 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 8) | x14 << 8;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 7) | x6 << 7;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 8) | x15 << 8;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 7) | x7 << 7;\n\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 8) | x13 << 8;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 7) | x5 << 7;\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 8) | x12 << 8;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 16) | x15 << 16;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 12) | x5 << 12;\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 16) | x12 << 16;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 12) | x6 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 16) | x13 << 16;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 12) | x7 << 12;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 16) | x14 << 16;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 12) | x4 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 8) | x13 << 8;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 7) | x7 << 7;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 8) | x14 << 8;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 8) | x12 << 8;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 7) | x6 << 7;\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 8) | x15 << 8;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 7) | x5 << 7;\n }\n writeUint32LE(x0 + j0 | 0, out, 0);\n writeUint32LE(x1 + j1 | 0, out, 4);\n writeUint32LE(x2 + j2 | 0, out, 8);\n writeUint32LE(x3 + j3 | 0, out, 12);\n writeUint32LE(x4 + j4 | 0, out, 16);\n writeUint32LE(x5 + j5 | 0, out, 20);\n writeUint32LE(x6 + j6 | 0, out, 24);\n writeUint32LE(x7 + j7 | 0, out, 28);\n writeUint32LE(x8 + j8 | 0, out, 32);\n writeUint32LE(x9 + j9 | 0, out, 36);\n writeUint32LE(x10 + j10 | 0, out, 40);\n writeUint32LE(x11 + j11 | 0, out, 44);\n writeUint32LE(x12 + j12 | 0, out, 48);\n writeUint32LE(x13 + j13 | 0, out, 52);\n writeUint32LE(x14 + j14 | 0, out, 56);\n writeUint32LE(x15 + j15 | 0, out, 60);\n}\n\n/**\n * Encrypt src with ChaCha20 stream generated for the given 32-byte key and\n * 8-byte (as in original implementation) or 12-byte (as in RFC7539) nonce and\n * write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * If nonce is 12 bytes, users should not encrypt more than 256 GiB with the\n * same key and nonce, otherwise the stream will repeat. The function will\n * throw error if counter overflows to prevent this.\n *\n * If nonce is 8 bytes, the output is practically unlimited (2^70 bytes, which\n * is more than a million petabytes). However, it is not recommended to\n * generate 8-byte nonces randomly, as the chance of collision is high.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each ChaCha block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array,\n src: Uint8Array, dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"ChaCha: key size must be 32 bytes\");\n }\n\n if (dst.length < src.length) {\n throw new Error(\"ChaCha: destination is shorter than source\");\n }\n\n let nc: Uint8Array;\n let counterLength: number;\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8 && nonce.length !== 12) {\n throw new Error(\"ChaCha nonce must be 8 or 12 bytes\");\n }\n nc = new Uint8Array(16);\n // First counterLength bytes of nc are counter, starting with zero.\n counterLength = nc.length - nonce.length;\n // Last bytes of nc after counterLength are nonce, set them.\n nc.set(nonce, counterLength);\n } else {\n if (nonce.length !== 16) {\n throw new Error(\"ChaCha nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterLength = nonceInplaceCounterLength;\n }\n\n // Allocate temporary space for ChaCha block.\n const block = new Uint8Array(64);\n\n for (let i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n\n // XOR block bytes with src into dst.\n for (let j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n\n // Increment counter.\n incrementCounter(nc, 0, counterLength);\n }\n\n // Cleanup temporary space.\n wipe(block);\n\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe(nc);\n }\n\n return dst;\n}\n\n/**\n * Generate ChaCha20 stream for the given 32-byte key and 8-byte or 12-byte\n * nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same with respect to\n * the nonce as described in the streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\nfunction incrementCounter(counter: Uint8Array, pos: number, len: number) {\n let carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"ChaCha: counter overflow\");\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\n\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 16;\n\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nexport class Poly1305 {\n readonly digestLength = DIGEST_LENGTH;\n\n private _buffer = new Uint8Array(16);\n private _r = new Uint16Array(10);\n private _h = new Uint16Array(10);\n private _pad = new Uint16Array(8);\n private _leftover = 0;\n private _fin = 0;\n private _finished = false;\n\n constructor(key: Uint8Array) {\n let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff;\n let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n\n private _blocks(m: Uint8Array, mpos: number, bytes: number) {\n let hibit = this._fin ? 0 : 1 << 11;\n\n let h0 = this._h[0],\n h1 = this._h[1],\n h2 = this._h[2],\n h3 = this._h[3],\n h4 = this._h[4],\n h5 = this._h[5],\n h6 = this._h[6],\n h7 = this._h[7],\n h8 = this._h[8],\n h9 = this._h[9];\n\n let r0 = this._r[0],\n r1 = this._r[1],\n r2 = this._r[2],\n r3 = this._r[3],\n r4 = this._r[4],\n r5 = this._r[5],\n r6 = this._r[6],\n r7 = this._r[7],\n r8 = this._r[8],\n r9 = this._r[9];\n\n while (bytes >= 16) {\n let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff;\n let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n let c = 0;\n\n let d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n let d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n let d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n let d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n let d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n let d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n let d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n let d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n let d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n let d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n }\n\n finish(mac: Uint8Array, macpos = 0): this {\n const g = new Uint16Array(10);\n let c: number;\n let mask: number;\n let f: number;\n let i: number;\n\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n\n this._finished = true;\n return this;\n }\n\n update(m: Uint8Array): this {\n let mpos = 0;\n let bytes = m.length;\n let want: number;\n\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (let i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (let i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n\n return this;\n }\n\n digest(): Uint8Array {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished \u2014 others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n let mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n }\n\n clean(): this {\n wipe(this._buffer);\n wipe(this._r);\n wipe(this._h);\n wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n }\n}\n\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nexport function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new Poly1305(key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) {\n return false;\n }\n return constantTimeEqual(a, b);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha20poly1305 implements ChaCha20-Poly1305 AEAD.\n */\n\nimport { AEAD } from \"@stablelib/aead\";\nimport { streamXOR, stream } from \"@stablelib/chacha\";\nimport { Poly1305 } from \"@stablelib/poly1305\";\nimport { wipe } from \"@stablelib/wipe\";\nimport { writeUint64LE } from \"@stablelib/binary\";\nimport { equal } from \"@stablelib/constant-time\";\n\nexport const KEY_LENGTH = 32;\nexport const NONCE_LENGTH = 12;\nexport const TAG_LENGTH = 16;\n\nconst ZEROS = new Uint8Array(16);\n\n/**\n * ChaCha20-Poly1305 Authenticated Encryption with Associated Data.\n *\n * Defined in RFC7539.\n */\nexport class ChaCha20Poly1305 implements AEAD {\n readonly nonceLength = NONCE_LENGTH;\n readonly tagLength = TAG_LENGTH;\n\n private _key: Uint8Array;\n\n /**\n * Creates a new instance with the given 32-byte key.\n */\n constructor(key: Uint8Array) {\n if (key.length !== KEY_LENGTH) {\n throw new Error(\"ChaCha20Poly1305 needs 32-byte key\");\n }\n // Copy key.\n this._key = new Uint8Array(key);\n }\n\n /**\n * Encrypts and authenticates plaintext, authenticates associated data,\n * and returns sealed ciphertext, which includes authentication tag.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If dst is given (it must be the size of plaintext + the size of tag\n * length) the result will be put into it. Dst and plaintext must not\n * overlap.\n */\n seal(nonce: Uint8Array, plaintext: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n // We pass full counter, which has 12-byte nonce and 4-byte block counter,\n // and it will get incremented after generating the block, which is\n // exactly what we need: we only use the first 32 bytes of 64-byte\n // ChaCha block and discard the next 32 bytes.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Allocate space for sealed ciphertext.\n const resultLength = plaintext.length + this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Encrypt plaintext.\n streamXOR(this._key, counter, plaintext, result, 4);\n\n // Authenticate.\n // XXX: can \"simplify\" here: pass full result (which is already padded\n // due to zeroes prepared for tag), and ciphertext length instead of\n // subarray of result.\n this._authenticate(result.subarray(result.length - this.tagLength, result.length),\n authKey, result.subarray(0, result.length - this.tagLength), associatedData);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n /**\n * Authenticates sealed ciphertext (which includes authentication tag) and\n * associated data, decrypts ciphertext and returns decrypted plaintext.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If authentication fails, it returns null.\n *\n * If dst is given (it must be of ciphertext length minus tag length),\n * the result will be put into it. Dst and plaintext must not overlap.\n */\n open(nonce: Uint8Array, sealed: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array | null {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Sealed ciphertext should at least contain tag.\n if (sealed.length < this.tagLength) {\n // TODO(dchest): should we throw here instead?\n return null;\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Authenticate.\n // XXX: can simplify and avoid allocation: since authenticate()\n // already allocates tag (from Poly1305.digest(), it can return)\n // it instead of copying to calculatedTag. But then in seal()\n // we'll need to copy it.\n const calculatedTag = new Uint8Array(this.tagLength);\n this._authenticate(calculatedTag, authKey,\n sealed.subarray(0, sealed.length - this.tagLength), associatedData);\n\n // Constant-time compare tags and return null if they differ.\n if (!equal(calculatedTag,\n sealed.subarray(sealed.length - this.tagLength, sealed.length))) {\n return null;\n }\n\n // Allocate space for decrypted plaintext.\n const resultLength = sealed.length - this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Decrypt.\n streamXOR(this._key, counter,\n sealed.subarray(0, sealed.length - this.tagLength), result, 4);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n clean(): this {\n wipe(this._key);\n return this;\n }\n\n private _authenticate(tagOut: Uint8Array, authKey: Uint8Array,\n ciphertext: Uint8Array, associatedData?: Uint8Array) {\n\n // Initialize Poly1305 with authKey.\n const h = new Poly1305(authKey);\n\n // Authenticate padded associated data.\n if (associatedData) {\n h.update(associatedData);\n if (associatedData.length % 16 > 0) {\n h.update(ZEROS.subarray(associatedData.length % 16));\n }\n }\n\n // Authenticate padded ciphertext.\n h.update(ciphertext);\n if (ciphertext.length % 16 > 0) {\n h.update(ZEROS.subarray(ciphertext.length % 16));\n }\n\n // Authenticate length of associated data.\n // XXX: can avoid allocation here?\n const length = new Uint8Array(8);\n if (associatedData) {\n writeUint64LE(associatedData.length, length);\n }\n h.update(length);\n\n // Authenticate length of ciphertext.\n writeUint64LE(ciphertext.length, length);\n h.update(length);\n\n // Get tag and copy it into tagOut.\n const tag = h.digest();\n for (let i = 0; i < tag.length; i++) {\n tagOut[i] = tag[i];\n }\n\n // Cleanup.\n h.clean();\n wipe(tag);\n wipe(length);\n }\n}\n", "module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\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 \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n", "module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\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)\n\nmodule.exports = function (value) {\n return (\n 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 )\n}\n", "module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\n", "'use strict'\n\nconst varint = require('varint')\n\nmodule.exports = (buf) => {\n if (!(buf instanceof Uint8Array)) {\n throw new Error('arg needs to be a Uint8Array')\n }\n\n const result = []\n\n while (buf.length > 0) {\n const num = varint.decode(buf)\n result.push(num)\n buf = buf.slice(varint.decode.bytes)\n }\n\n return result\n}\n", "'use strict'\n\nconst exp = Math.exp\n\nexports =\nmodule.exports =\nfunction MovingAverage (timespan) {\n if (typeof timespan !== 'number') { throw new Error('must provide a timespan to the moving average constructor') }\n\n if (timespan <= 0) { throw new Error('must provide a timespan > 0 to the moving average constructor') }\n\n let ma // moving average\n let v = 0 // variance\n let d = 0 // deviation\n let f = 0 // forecast\n\n let previousTime\n\n let ret = {}\n\n function alpha (t, pt) {\n return 1 - (exp(-(t - pt) / timespan))\n }\n\n ret.push =\n function push (time, value) {\n if (previousTime) {\n // calculate moving average\n const a = alpha(time, previousTime)\n const diff = value - ma\n const incr = a * diff\n ma = a * value + (1 - a) * ma\n // calculate variance & deviation\n v = (1 - a) * (v + diff * incr)\n d = Math.sqrt(v)\n // calculate forecast\n f = ma + a * diff\n } else {\n ma = value\n }\n previousTime = time\n }\n\n // Exponential Moving Average\n\n ret.movingAverage =\n function movingAverage () {\n return ma\n }\n\n // Variance\n ret.variance =\n function variance () {\n return v\n }\n\n ret.deviation =\n function deviation () {\n return d\n }\n\n ret.forecast =\n function forecast () {\n return f\n }\n\n return ret\n}\n", "/* jshint browser: true */\n\n(function () {\n\n// We'll copy the properties below into the mirror div.\n// Note that some browsers, such as Firefox, do not concatenate properties\n// into their shorthand (e.g. padding-top, padding-bottom etc. -> padding),\n// so we have to list every single property explicitly.\nvar properties = [\n 'direction', // RTL support\n 'boxSizing',\n 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does\n 'height',\n 'overflowX',\n 'overflowY', // copy the scrollbar for IE\n\n 'borderTopWidth',\n 'borderRightWidth',\n 'borderBottomWidth',\n 'borderLeftWidth',\n 'borderStyle',\n\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/font\n 'fontStyle',\n 'fontVariant',\n 'fontWeight',\n 'fontStretch',\n 'fontSize',\n 'fontSizeAdjust',\n 'lineHeight',\n 'fontFamily',\n\n 'textAlign',\n 'textTransform',\n 'textIndent',\n 'textDecoration', // might not make a difference, but better be safe\n\n 'letterSpacing',\n 'wordSpacing',\n\n 'tabSize',\n 'MozTabSize'\n\n];\n\nvar isBrowser = (typeof window !== 'undefined');\nvar isFirefox = (isBrowser && window.mozInnerScreenX != null);\n\nfunction getCaretCoordinates(element, position, options) {\n if (!isBrowser) {\n throw new Error('textarea-caret-position#getCaretCoordinates should only be called in a browser');\n }\n\n var debug = options && options.debug || false;\n if (debug) {\n var el = document.querySelector('#input-textarea-caret-position-mirror-div');\n if (el) el.parentNode.removeChild(el);\n }\n\n // The mirror div will replicate the textarea's style\n var div = document.createElement('div');\n div.id = 'input-textarea-caret-position-mirror-div';\n document.body.appendChild(div);\n\n var style = div.style;\n var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9\n var isInput = element.nodeName === 'INPUT';\n\n // Default textarea styles\n style.whiteSpace = 'pre-wrap';\n if (!isInput)\n style.wordWrap = 'break-word'; // only for textarea-s\n\n // Position off-screen\n style.position = 'absolute'; // required to return coordinates properly\n if (!debug)\n style.visibility = 'hidden'; // not 'display: none' because we want rendering\n\n // Transfer the element's properties to the div\n properties.forEach(function (prop) {\n if (isInput && prop === 'lineHeight') {\n // Special case for s because text is rendered centered and line height may be != height\n style.lineHeight = computed.height;\n } else {\n style[prop] = computed[prop];\n }\n });\n\n if (isFirefox) {\n // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275\n if (element.scrollHeight > parseInt(computed.height))\n style.overflowY = 'scroll';\n } else {\n style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'\n }\n\n div.textContent = element.value.substring(0, position);\n // The second special handling for input type=\"text\" vs textarea:\n // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037\n if (isInput)\n div.textContent = div.textContent.replace(/\\s/g, '\\u00a0');\n\n var span = document.createElement('span');\n // Wrapping must be replicated *exactly*, including when a long word gets\n // onto the next line, with whitespace at the end of the line before (#7).\n // The *only* reliable way to do that is to copy the *entire* rest of the\n // textarea's content into the created at the caret position.\n // For inputs, just '.' would be enough, but no need to bother.\n span.textContent = element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all\n div.appendChild(span);\n\n var coordinates = {\n top: span.offsetTop + parseInt(computed['borderTopWidth']),\n left: span.offsetLeft + parseInt(computed['borderLeftWidth']),\n height: parseInt(computed['lineHeight'])\n };\n\n if (debug) {\n span.style.backgroundColor = '#aaa';\n } else {\n document.body.removeChild(div);\n }\n\n return coordinates;\n}\n\nif (typeof module != 'undefined' && typeof module.exports != 'undefined') {\n module.exports = getCaretCoordinates;\n} else if(isBrowser) {\n window.getCaretCoordinates = getCaretCoordinates;\n}\n\n}());\n", "export const isArray = (what): boolean => Array.isArray(what);\n", "import { isArray } from \"./isArray\";\n\nconst select = (selector) => ({\n el: document.querySelector(selector),\n elements: document.querySelectorAll(selector),\n placeholder(what) {\n this.el.placeholder = what;\n return this;\n },\n getValue() {\n return this.el.value;\n },\n insertAtCaret(text) {\n this.el.setRangeText(\n text,\n this.el.selectionStart,\n this.el.selectionEnd,\n \"end\"\n );\n return this;\n },\n setValue(value) {\n this.el.value = value;\n const event = new Event(\"input\", {\n bubbles: true,\n cancelable: true,\n });\n this.el.dispatchEvent(event);\n return this;\n },\n innerHTML(htmlString) {\n this.el.innerHTML = htmlString;\n return this;\n },\n html(content) {\n this.el.innerHTML = \"\";\n this.append(content);\n return this;\n },\n append(el) {\n const elements = isArray(el) ? el : [el];\n elements.forEach((e) => {\n const newContent = isElement(e) ? e : document.createTextNode(e);\n this.el.appendChild(newContent);\n });\n return this;\n },\n appendListElement(text) {\n const li = document.createElement(\"LI\");\n li.appendChild(document.createTextNode(text));\n this.el.appendChild(li);\n return this;\n },\n removeClass(className) {\n this.el.classList.remove(className);\n return this;\n },\n removeClasses(classes = []) {\n classes.map((className) => this.removeClass(className));\n return this;\n },\n addClass(className) {\n this.el.classList.add(className);\n return this;\n },\n hasClass(cls) {\n return (\" \" + this.el.className + \" \").indexOf(\" \" + cls + \" \") > -1;\n },\n show(shouldShow = true) {\n if (shouldShow) {\n this.removeClass(\"hidden\");\n } else {\n this.hide();\n }\n return this;\n },\n hide() {\n this.addClass(\"hidden\");\n return this;\n },\n toggle(className = \"hidden\") {\n if (this.hasClass(className)) this.removeClass(className);\n else this.addClass(className);\n return this;\n },\n focus() {\n this.el.focus();\n return this;\n },\n listenAll(event, fn) {\n const elements = Array.prototype.slice.call(this.elements);\n elements.map((el) => {\n el.addEventListener(event, (e) => fn(e.srcElement));\n });\n return this;\n },\n listen(event, fn) {\n this.el.addEventListener(event, (e) => fn(e, this));\n return this;\n },\n click() {\n if (this.el) {\n this.el.click();\n }\n },\n checked(value) {\n this.el.checked = !!value;\n return this;\n },\n disable(shouldDisable = true) {\n this.el.disabled = shouldDisable;\n return this;\n },\n});\n\nexport const isElement = (obj) => {\n try {\n return obj instanceof HTMLElement;\n } catch (e) {\n //Browsers not supporting W3 DOM2 don't have HTMLElement and\n //an exception is thrown and we end up here. Testing some\n //properties that all elements have (works on IE7)\n return (\n typeof obj === \"object\" &&\n obj.nodeType === 1 &&\n typeof obj.style === \"object\" &&\n typeof obj.ownerDocument === \"object\"\n );\n }\n};\n\nexport default select;\n", "import select from \"../../utils/dom\";\n\nconst notificationTypes = {\n info: \"info\",\n success: \"success\",\n error: \"error\",\n warning: \"warning\",\n};\n\nconst notification = select(\"#notification\");\nconst cleanNotificationClasses = () =>\n notification.removeClasses(Object.values(notificationTypes));\nnotification.el.onclick = () => cleanNotificationClasses();\n\nconst notificationFactory = () =>\n Object.values(notificationTypes).reduce(\n (acc, notificationType) => ({\n ...acc,\n [notificationType](message) {\n this.showNotification(message, notificationType);\n },\n }),\n {}\n );\n\nconst Notification = (autohideDuration = 5) => ({\n autohideDuration,\n timer: undefined,\n removeAfter() {\n this.timer = setTimeout(() => {\n cleanNotificationClasses();\n }, this.autohideDuration * 1000);\n },\n showNotification(message, type = notificationTypes.info) {\n cleanNotificationClasses();\n notification.innerHTML(message).addClass(type);\n clearTimeout(this.timer);\n this.removeAfter();\n },\n ...notificationFactory(),\n});\n\nconst notify = Notification();\nexport default notify;\n", "import notify from \"./notify\";\n\nconst welcomeUser = () => {\n const lastVisit = localStorage.getItem(\"miropad.user\");\n if (lastVisit) {\n notify.info(`\uD83E\uDD17 Happy to see you again from ${lastVisit}`);\n } else {\n notify.info(\n `

    Welcome \uD83D\uDC4B \uD83D\uDE03

    \n

    Use Ctrl+S: to save your note

    \n

    & Ctrl+P: to format a JSON doc

    \n `,\n 100\n );\n }\n localStorage.setItem(\"miropad.user\", new Date().toLocaleDateString());\n};\n\nexport default welcomeUser;\n", "import notify from \"../components/molecules/notify\";\nimport { isArray } from \"./isArray\";\n\nconst storage = (() => {\n return {\n set: function (key, what) {\n localStorage.setItem(key, what);\n return this;\n },\n update: function (key, attr) {\n const current = JSON.parse(this.get(key));\n localStorage.setItem(\n key,\n JSON.stringify({\n ...current,\n ...attr,\n })\n );\n return this;\n },\n remove: function (key) {\n localStorage.removeItem(key);\n return this;\n },\n get: function (key) {\n if (isArray(key)) {\n return key.reduce((acc, k) => {\n return {\n ...acc,\n [k]: this.get(k),\n };\n }, {});\n }\n\n return localStorage.getItem(key);\n },\n getDictionary: function () {\n const savedTxt = localStorage.getItem(\"__dictionary__\");\n return savedTxt ? JSON.parse(savedTxt) : [];\n },\n removeFromDictionary: function (word) {\n const currentDictionary = this.getDictionary();\n const newDictionary = currentDictionary.filter((w) => {\n return w !== word;\n });\n\n localStorage.setItem(\"__dictionary__\", JSON.stringify(newDictionary));\n },\n saveToDictionary: async function (what) {\n if (what.length) {\n try {\n const cleanText = what.toLowerCase().replace(/[^a-zA-Z\u03AC-\u03CE\u0391-\u03A9]/g, \" \");\n const current = await this.getDictionary();\n const words = [\n ...cleanText.split(\" \").filter((w) => w.length > 3),\n ...current,\n ];\n const distinctWords = [...new Set(words)];\n localStorage.setItem(\"__dictionary__\", JSON.stringify(distinctWords));\n } catch (e) {\n notify.error(\n `\uD83D\uDE31 Something went wrong while trying to save to local storage ${e}`\n ); // eslint-disable-line\n }\n } else {\n notify.warning(\"\uD83D\uDE15 Nothing to save!\"); // eslint-disable-line\n }\n return this;\n },\n };\n})();\n\nexport default storage;\n", "export const configuration = {\n github: {\n client_id: \"70c1955dfe4914c52c10\",\n request_state: \"miro-pad\",\n },\n auth_service: \"https://vercel-api-phi.vercel.app/api/auth\",\n mail_service: {\n api: \"https://vercel-api-phi.vercel.app/api/mail\",\n signature: `Theo Mironidis
    \n Software Engineer
    \n https://teomrd.github.io`,\n },\n file_service: {\n api: \"https://vercel-api-phi.vercel.app/api/upload\",\n },\n} as const;\n", "import storage from \"../localstorage\";\nimport { getNotes } from \"../../components/organisms/noteManager/noteManager\";\nimport notify from \"../../components/molecules/notify\";\nimport { configuration } from \"../../../configuration\";\n\nexport const getGist = (id, token = storage.get(\"authToken\")) =>\n fetch(`https://api.github.com/gists/${id}`, {\n headers: {\n Authorization: `token ${token}`,\n },\n }).then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n });\n\nexport const getAuthenticatedUsersGists = (token = storage.get(\"authToken\")) =>\n fetch(\"https://api.github.com/gists\", {\n headers: {\n Authorization: `token ${token}`,\n },\n }).then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n });\n\nexport const deleteFileOnGist = async (\n fileName,\n gistId = storage.get(\"gistId\"),\n token = storage.get(\"authToken\")\n) => {\n return fetch(`https://api.github.com/gists/${gistId}`, {\n method: \"PATCH\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: {\n [fileName]: null,\n },\n description: \"MiroPad Gist\",\n public: false,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n notify.info(`${fileName} deleted on Gist!`);\n return responseAsJson;\n });\n};\n\nexport const updateGist = async (\n notes = getNotes(),\n gistId = storage.get(\"gistId\"),\n token = storage.get(\"authToken\")\n) => {\n if (gistId && token) {\n const noteToFiles = notes.reduce((acc, { id, text, deleted }) => {\n return {\n ...acc,\n [id]: deleted ? null : { content: text },\n };\n }, {});\n return fetch(`https://api.github.com/gists/${gistId}`, {\n method: \"PATCH\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: noteToFiles,\n description: \"MiroPad Gist\",\n public: false,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n notes.map(({ id, deleted }) => {\n if (deleted) localStorage.removeItem(id);\n });\n return responseAsJson;\n });\n }\n};\n\nexport const createNewGist = (token = storage.get(\"authToken\")) => {\n const notes = getNotes();\n const noteToFiles = notes.reduce((acc, note) => {\n return {\n ...acc,\n [note.id]: {\n content: note.text,\n },\n };\n }, {});\n return fetch(\"https://api.github.com/gists\", {\n method: \"POST\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: noteToFiles,\n description: \"MiroPad Gist\",\n public: false,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n return responseAsJson;\n });\n};\n\nexport const getAuthToken = (code, state) =>\n fetch(`${configuration.auth_service}?state=${state}&code=${code}`, {\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n })\n .then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n return responseAsJson;\n });\n\nexport const publishGist = ({\n note,\n token = storage.get(\"authToken\"),\n} = {}) => {\n return fetch(\"https://api.github.com/gists\", {\n method: \"POST\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: {\n [note.id]: {\n content: note.text,\n },\n },\n description: \"MiroPad Gist\",\n public: true,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n return responseAsJson;\n });\n};\n", "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\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 \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const 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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\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", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\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.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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 function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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 function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\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 /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\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}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\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\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const 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", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import * as varint from './varint.js'\nimport * as Digest from './hashes/digest.js'\nimport { base58btc } from './bases/base58.js'\nimport { base32 } from './bases/base32.js'\nimport { coerce } from './bytes.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst 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}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n *\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\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\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\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 /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\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 * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n 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 =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\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 /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\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 * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\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\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst 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\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 } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst 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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst 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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n 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})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n", "import { CID } from \"multiformats/cid\";\nimport * as json from \"multiformats/codecs/json\";\nimport { sha256 } from \"multiformats/hashes/sha2\";\n\nconst hashBrowser = async (val) => {\n const bytes = json.encode(val);\n\n const hash = await sha256.digest(bytes);\n const cid = CID.create(1, json.code, hash);\n\n return cid.toString();\n};\n\nexport default hashBrowser;\n", "const isJSON = (str) => {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n};\n\nexport default isJSON;\n", "import select from \"./dom\";\n\nconst _getBasePageTitle = () => {\n const titleSections = document.title.split(\"|\");\n const baseTitle = titleSections[0];\n return baseTitle;\n};\n\nconst setPageTitle = (what) => {\n const baseTitle = _getBasePageTitle();\n document.title = baseTitle.trim() + \" | \" + what.trim();\n select(\".title h3\").html(what.trim());\n};\n\nconst resetPageTitle = () => {\n const baseTitle = _getBasePageTitle();\n document.title = baseTitle;\n select(\"title\").innerHTML(`${TITLE_NAME} v${VERSION}`);\n select(\".title h3\").innerHTML(\n `${TITLE_NAME} v${VERSION}`\n );\n};\n\nexport { setPageTitle, resetPageTitle };\n", "export const url = {\n baseUrl: `${window.location.origin}${window.location.pathname}`,\n get: function () {\n return window.location.href;\n },\n getPageId: function (url = window.location.href) {\n const URLObject = new URL(url);\n const hash = URLObject.hash.substr(1);\n const hashWithVersion = hash.split(\"?\");\n const pageId = hashWithVersion[0] || null;\n return pageId;\n },\n getSearchParams: function (url = window.location.href) {\n const URLObject = new URL(url);\n const urlParts = URLObject.href.split(\"?\");\n const currentParams = urlParts[1] || \"\";\n const searchParams = new URLSearchParams(currentParams);\n return searchParams;\n },\n getParamsObject: function (url = window.location.href) {\n const params = this.getSearchParams(url);\n let parametersObject = {};\n for (const key of params.keys()) {\n parametersObject = {\n ...parametersObject,\n [key]: this.getSearchParam(key, url),\n };\n }\n return parametersObject;\n },\n getSearchParam(param, url = window.location.href) {\n const params = this.getSearchParams(url);\n const paramValue = params.get(param);\n return paramValue;\n },\n deleteParam: function (param) {\n const searchParams = this.getSearchParams();\n if (typeof param === \"object\" && param.length > 0) {\n param.forEach((p) => {\n searchParams.delete(p);\n });\n } else {\n searchParams.delete(param);\n }\n const { pathname } = window.location;\n const hash = this.getPageId();\n return window.location.assign(\n `${hash ? `#${hash}` : pathname}${\n searchParams.toString() ? `?${searchParams.toString()}` : \"\"\n }`\n );\n },\n set: function (pageId = this.getPageId(), params = this.getParamsObject()) {\n const allParams = {\n ...this.getParamsObject(),\n ...params,\n };\n const newParams = new URLSearchParams(allParams);\n return window.location.assign(`#${pageId}?${newParams.toString()}`);\n },\n};\n", "import select from \"../../utils/dom\";\n\nexport const setSavedState = (saved = true) => {\n if (saved) {\n select(\"#save\").removeClass(\"unsaved\");\n select(\"#logo\").removeClass(\"unsaved\");\n } else {\n select(\"#save\").addClass(\"unsaved\");\n select(\"#logo\").addClass(\"unsaved\");\n }\n};\n", "/* eslint-disable indent */\nimport select from \"../../../utils/dom\";\nimport { deleteFileOnGist } from \"../../../utils/github/api\";\nimport hashBrowser from \"../../../utils/hashBrowser\";\nimport isJSON from \"../../../utils/isJSON\";\nimport storage from \"../../../utils/localstorage\";\nimport { resetPageTitle, setPageTitle } from \"../../../utils/pageTitle\";\nimport { url } from \"../../../utils/urlManager\";\nimport notify from \"../../molecules/notify\";\nimport commander from \"../commander/commander\";\nimport { setSavedState } from \"../../../ui/functions/savedState\";\n\nconst encodeTitle = (title) => {\n const encodedTitle = encodeURIComponent(title);\n if (encodedTitle.length === 0) {\n throw new Error(\"You need to start with a valid title for your note!\");\n }\n return encodedTitle;\n};\n\nexport const getDateCreatedFromTitle = (title) => {\n const titleID = getTitleId(title);\n const note = getNote(titleID);\n const { dateCreated } = note || {};\n return dateCreated;\n};\n\nexport const markNoteForDeletion = (id) => {\n const note = getNote(id);\n localStorage.setItem(\n id,\n JSON.stringify({\n title: note.title,\n deleted: true,\n revisions: note.revisions,\n })\n );\n};\n\nexport type Note = {\n id: string;\n title: string;\n text: string;\n dateCreated: number;\n deleted: boolean;\n lines: Array;\n numberOfRevisions: number;\n revisions: {\n [key: string]: {\n text: string;\n dateCreated: number;\n };\n };\n};\n\nexport const getNote = (titleID = url.getPageId(), revision): Note | null => {\n let doc;\n try {\n doc = JSON.parse(storage.get(titleID));\n if (!doc.revisions) {\n throw new Error(\"This is not a note!\");\n }\n } catch (error) {\n return null;\n }\n\n const newerNote = doc\n ? Object.values(doc.revisions).reduce(\n (acc: any, note: any) =>\n note.dateCreated > acc.dateCreated ? note : acc,\n { dateCreated: 0 }\n )\n : {};\n\n const noteToReturn = revision ? doc.revisions[revision] : newerNote;\n\n return titleID\n ? {\n ...doc,\n id: titleID,\n ...(noteToReturn ? noteToReturn : {}),\n numberOfRevisions:\n doc && doc.revisions ? Object.keys(doc.revisions).length : undefined,\n title: doc.title,\n }\n : null;\n};\n\nexport const disableSyncOnCurrentNote = (value) => {\n const { id, title } = getNote();\n storage.update(id, {\n disableSync: value,\n });\n notify.info(`\"${title}\" cloud sync ${value ? \"disabled \uD83D\uDE36\" : \"enabled \u26A1\uFE0F\"}`);\n};\n\nexport const setNoteFromHash = async (hash = url.getPageId()) => {\n if (hash) {\n const version = url.getSearchParam(\"v\");\n const note = getNote(undefined, version);\n if (note) {\n select(\"#revisions\").html(\n `${note.numberOfRevisions} revision${\n note.numberOfRevisions > 1 ? \"s\" : \"\"\n }`\n );\n setPageTitle(note.title);\n select(\".terminal\").setValue(note.text);\n }\n\n if (!note) {\n notify.error(\"404 Note not found \uD83E\uDD37\u200D\u2642\uFE0F\");\n }\n }\n};\n\nexport const resetNoteManager = () => {\n location.hash = \"\";\n resetPageTitle();\n select(\"#revisions\").html(\"\");\n select(\".terminal\").setValue(\"\").focus();\n setSavedState();\n};\n\nexport const getTitle = (note = \"\") =>\n note.split(\"\\n\")[0].trim().replace(\"#\", \"\").trim();\n\nexport const getTitleId = (note) => {\n const title = getTitle(note);\n return encodeTitle(title);\n};\n\nexport const updateNote = async (what) => {\n if (what.length) {\n const titleID = getTitleId(what);\n const title = getTitle(what);\n const existingNote = getNote(titleID);\n if (existingNote === null) {\n // new existingNote\n return saveNote(what);\n }\n const { text } = existingNote;\n const hashOfIncomingNote = await hashBrowser(what);\n const hashOfCurrentNote = await hashBrowser(text);\n\n if (hashOfIncomingNote === hashOfCurrentNote) {\n return;\n }\n\n const currentNote = storage.get(titleID);\n const note = JSON.parse(currentNote);\n storage.set(\n titleID,\n JSON.stringify({\n ...note,\n title,\n revisions: {\n ...((note && note.revisions) || {}),\n [hashOfIncomingNote]: {\n dateCreated: Date.now(),\n text: what,\n },\n },\n })\n );\n }\n};\n\nexport const saveNote = async (\n what = select(\".terminal\").getValue(),\n cid?: string\n) => {\n await storage.saveToDictionary(what);\n if (what.length) {\n const hash = await hashBrowser(what);\n try {\n const title = what.split(\"\\n\")[0].trim().replace(\"#\", \"\").trim();\n\n setPageTitle(title);\n\n const titleID = encodeTitle(title);\n const currentNote = storage.get(titleID);\n const note = JSON.parse(currentNote);\n storage.set(\n titleID,\n JSON.stringify({\n ...note,\n title,\n lines: what.split(\"\\n\"),\n revisions: {\n ...((note && note.revisions) || {}),\n [hash]: {\n dateCreated: Date.now(),\n text: what,\n ...(cid ? { cid: cid } : {}),\n },\n },\n })\n );\n url.set(titleID, {\n v: hash,\n ...(cid ? { cid: cid } : {}),\n });\n if (!cid) {\n url.deleteParam(\"cid\");\n }\n storage.set(\"lastLocalUpdate\", new Date());\n notify.success(\"\uD83D\uDC4C Note saved!\");\n setSavedState();\n } catch (e) {\n notify.error(\n `\uD83D\uDE31 Something went wrong while trying to save to local storage ${e}`\n ); // eslint-disable-line\n }\n } else {\n notify.warning(\"\uD83D\uDE15 Nothing to save!\"); // eslint-disable-line\n }\n};\n\nexport const getNotes = ({ includeDeleted } = {}) =>\n Object.entries(localStorage)\n .filter(([, body]) => typeof body === \"string\")\n .filter(([id, body]) => !id.startsWith(\"__\") && isJSON(body))\n .map(([id, body]) => [id, JSON.parse(body)])\n .filter(([, body]) => !!body.title) // check if title exists and therefore is a note\n .reduce((acc, [noteId]) => [...acc, getNote(noteId)], [])\n .filter(({ deleted }) => (includeDeleted ? true : !deleted));\n\nexport const search = (q) => {\n if (!q) {\n return undefined;\n }\n\n const results = getNotes()\n .map(({ id }) => getNote(id))\n .filter(({ text }) => text.toLowerCase().includes(q.toLowerCase()));\n\n return results[0];\n};\n\nexport const deleteNote = () => {\n const confirmation = confirm(\"Are you sure you want do that?\");\n if (confirmation) {\n const note = getNote();\n resetNoteManager();\n if (note && note.id) {\n deleteFileOnGist(note.id);\n markNoteForDeletion(note.id);\n }\n }\n commander.hide();\n};\n", "import storage from \"./localstorage\";\n\nexport const isUserLoggedIn = () => {\n return !!storage.get(\"authToken\");\n};\n", "import { isElement } from \"../../../utils/dom\";\n\nexport const command = (\n { title, secondary, onclick, onSecondaryClick, icon },\n selected = false\n) => {\n const li = document.createElement(\"LI\");\n li.className = selected ? \"selected\" : \"\";\n if (icon) {\n const iconClone = icon.cloneNode(true);\n li.appendChild(iconClone);\n }\n const liContent = isElement(title) ? title : document.createTextNode(title);\n liContent.onclick = onclick;\n li.appendChild(liContent);\n\n const span = document.createElement(\"span\");\n if (secondary) {\n span.className = \"secondary\";\n const secondaryElement = isElement(secondary)\n ? secondary\n : document.createTextNode(secondary);\n secondaryElement.onclick = onSecondaryClick;\n span.appendChild(secondaryElement);\n }\n li.appendChild(span);\n\n return li;\n};\n", "import { command } from \"./command\";\n\nexport const commands = (commandsToGen, selectedIndex) =>\n commandsToGen.map((props, i) => {\n const li = command(props, i === selectedIndex);\n return li;\n });\n", "export const wordParts = (word, match) => {\n const parts = word.toLowerCase().split(match);\n\n let indexInWord = 0;\n return parts\n .reduce((acc, part, i) => {\n return [...acc, ...(i === 0 ? [part] : [match, part])];\n }, [])\n .filter((p) => p !== \"\")\n .map((syllable) => {\n indexInWord = indexInWord + syllable.length;\n const start = indexInWord - syllable.length;\n const end = start + syllable.length;\n const originalSyllable = word.slice(start, end);\n return originalSyllable;\n });\n};\n", "import { wordParts } from \"./wordParts\";\n\nconst mark = (word) => {\n const markEl = document.createElement(\"mark\");\n markEl.appendChild(document.createTextNode(word));\n return markEl;\n};\n\nexport const div = ({ content = \"\", highlight = \"\" }) => {\n const div = document.createElement(\"div\");\n const words = content.split(\" \");\n const wordsToHighlight = highlight.toLowerCase().split(\" \");\n if (highlight.trim() === \"\") {\n div.appendChild(document.createTextNode(content));\n return div;\n }\n words\n .map((word) => {\n const matches = wordsToHighlight\n .map((wordToHighlight) => {\n return word.toLocaleLowerCase().includes(wordToHighlight)\n ? wordToHighlight\n : undefined;\n })\n .filter((m) => m !== undefined);\n\n return {\n word: word,\n matches: matches,\n };\n })\n .forEach(({ word, matches }) => {\n if (matches.length > 0) {\n const match = matches[0];\n if (word === match) {\n div.appendChild(mark(` ${word}`));\n } else {\n const parts = wordParts(word, match);\n const wordElements = parts.map((syllable) =>\n syllable.toLowerCase() === match\n ? mark(syllable)\n : document.createTextNode(syllable)\n );\n div.appendChild(document.createTextNode(\" \"));\n wordElements.forEach((w) => {\n div.appendChild(w);\n });\n }\n } else {\n div.appendChild(document.createTextNode(` ${word} `));\n }\n });\n return div;\n};\n", "import {\n getGist,\n getAuthToken,\n getAuthenticatedUsersGists,\n createNewGist,\n} from \"./api\";\nimport storage from \"../localstorage\";\nimport { url } from \"../urlManager\";\nimport select from \"../dom\";\nimport { configuration } from \"../../../configuration\";\nimport { updateNote } from \"../../components/organisms/noteManager/noteManager\";\nimport notify from \"../../components/molecules/notify\";\nimport { commands } from \"../../components/molecules/commands\";\nimport commander from \"../../components/organisms/commander/commander\";\nimport { div } from \"../../components/atoms/div/div\";\n\nexport const goAuthenticate = async () => {\n notify.info(\"You need to be authenticated!\");\n commander.hide();\n return window.location.replace(\n `https://github.com/login/oauth/authorize?client_id=${configuration.github.client_id}&scope=gist&state=${configuration.github.request_state}`\n );\n};\n\nexport const setGistToSyncWith = async (token) => {\n notify.info(\"Downloading my Gists!\");\n const gists = await getAuthenticatedUsersGists(token);\n commander.setState({\n mode: commander.getModes().gists,\n });\n\n notify.info(\"Select Gist to sync with\");\n const gistOptions = gists\n .sort(\n (a, b) =>\n new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()\n )\n .map(({ description, updated_at, id }) => ({\n title: div({ content: `${description}(${id})` }),\n secondary: updated_at,\n onclick: async () => {\n await storage.set(\"gistId\", id);\n notify.success(`${description}(${id}) selected for synchronization!`);\n syncNotesWithGitHub();\n commander.hide();\n },\n }));\n\n const gistOptionComponents = commands([\n {\n title: \"Create a new Gist\",\n onclick: async () => {\n notify.info(\"Syncing your MiroPads to a new Gist\");\n try {\n const { id } = await createNewGist();\n storage.set(\"gistId\", id);\n notify.success(\"MiroPads synced to a new Gist \uD83C\uDF89\");\n } catch (error) {\n notify.error(error.message);\n }\n commander.hide();\n },\n },\n ...gistOptions,\n ]);\n select(\"#commands\").html(\"\");\n select(\"#commands\").append(gistOptionComponents);\n};\n\nexport const syncNotesWithGitHub = async (gistId = storage.get(\"gistId\")) => {\n const authToken = storage.get(\"authToken\");\n if (authToken && gistId) {\n select(\"#logo\").addClass(\"loading\");\n const { files } = await getGist(gistId);\n Object.values(files).forEach(({ content }) => {\n updateNote(content);\n });\n storage.set(\"lastSync\", new Date());\n notify.success(\"\u2B07 MiroPad synced \u2705\");\n select(\"#logo\").removeClass(\"loading\");\n }\n};\n\nexport const setAuthTokenFromCallback = async () => {\n const code = url.getSearchParam(\"code\");\n const state = url.getSearchParam(\"state\");\n if (code && state) {\n select(\"#logo\").addClass(\"loading\");\n notify.info(\"\uD83D\uDD10 Authenticating...\");\n try {\n const { token } = await getAuthToken(code, state);\n storage.set(\"authToken\", token);\n notify.info(\"\u26F3 You have been authenticated!\");\n url.deleteParam([\"code\", \"state\"]);\n } catch (error) {\n notify.error(error.message);\n }\n select(\"#logo\").removeClass(\"loading\");\n }\n};\n", "import notify from \"../../components/molecules/notify\";\n\nconst getNewFileHandle = async (title = \"no-titled\") => {\n const options = {\n suggestedName: `${title}`,\n types: [\n {\n description: \"MiroPad text notes\",\n accept: {\n \"text/plain\": [\".miropad\"],\n },\n },\n ],\n };\n\n const handle = await window.showSaveFilePicker(options);\n return handle;\n};\n\nexport const writeFile = async (fileHandle, contents: string) => {\n // Create a FileSystemWritableFileStream to write to.\n const writable = await fileHandle.createWritable();\n // Write the contents of the file to the stream.\n await writable.write(contents);\n // Close the file and write the contents to disk.\n await writable.close();\n};\n\n/**\n * Saves a new file to disk.\n */\nexport const saveFileAs = async (contents: string, title?: string) => {\n try {\n const fileHandle = await getNewFileHandle(title);\n await writeFile(fileHandle, contents);\n } catch (ex) {\n const msg = \"An error occurred trying to save the file.\";\n notify.error(msg);\n return;\n }\n};\n\nexport const saveDataToFile = (() => {\n const a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style = \"display: none\";\n return (data, fileName = `MiroPad-${new Date().toISOString()}.json`) => {\n const json = JSON.stringify(data),\n blob = new Blob([json], { type: \"octet/stream\" }),\n url = window.URL.createObjectURL(blob);\n a.href = url;\n a.download = fileName;\n a.click();\n window.URL.revokeObjectURL(url);\n };\n})();\n", "import showdown from \"showdown\";\n\nconst converter = new showdown.Converter({\n tasklists: true,\n underline: true,\n emoji: true,\n simplifiedAutoLink: true,\n tables: true,\n openLinksInNewWindow: true,\n});\n\nconverter.setFlavor(\"github\");\n\nexport const convertMarkDownToHtml = (md) => converter.makeHtml(md);\n", "import storage from \"./localstorage\";\nimport notify from \"../components/molecules/notify\";\nimport { configuration } from \"../../configuration\";\nimport { getTitle } from \"../components/organisms/noteManager/noteManager\";\nimport { convertMarkDownToHtml } from \"../components/organisms/markdown/mdToHtml\";\n\nexport const handleErrorResponse = (response) => {\n const isSuccessfulRequest = response.status.toString().slice(0, 1) === \"2\";\n if (isSuccessfulRequest) return response;\n else throw new Error(response);\n};\n\nconst wrapTemplate = (body = \"\") => {\n return `\n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n\n \n
    \n
    \n `;\n};\n\nconst sendMail = async (body, email, subject = \"MiroPad note\") => {\n if (!body) {\n notify.error(\"\uD83D\uDC7B No message to send, type something and try again! \uD83E\uDD13\");\n return undefined;\n }\n try {\n await fetch(`${configuration.mail_service.api}`, {\n method: \"POST\",\n headers: {\n \"x-secret-token\": storage.get(\"MIROPAD_SECRET_TOKEN\"),\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n to: email,\n subject,\n html: wrapTemplate(body),\n }),\n })\n .then(handleErrorResponse)\n .then((response) => response.json());\n\n notify.success(\"Email sent \uD83D\uDE80\");\n } catch (error) {\n notify.error(\n \"Error not went through \uD83D\uDCA5! Check your credentials and try again!\"\n );\n }\n};\n\nconst getUserMailingPreferences = () => {\n const savedMail = storage.get(\"mail\");\n if (savedMail) {\n const mailSameAgainQuestion = window.prompt(\n `Mail ${savedMail} again? (y)es/(no)`,\n \"yeap\"\n );\n if (mailSameAgainQuestion === null) {\n return mailSameAgainQuestion;\n }\n if (mailSameAgainQuestion.slice(0, 1).toLowerCase() === \"y\") {\n return savedMail;\n }\n }\n const whoMailing = window.prompt(\"Where do you wanna send the mail to?\");\n const wannaSaveDat = window.prompt(\n \"Do you wanna save that to your preferences for later on? (y)es/(no)\",\n \"yeap\"\n );\n if (wannaSaveDat && wannaSaveDat.slice(0, 1).toLowerCase() === \"y\") {\n storage.set(\"mail\", whoMailing);\n }\n return whoMailing;\n};\n\nconst mailTo = (what) => {\n const email = getUserMailingPreferences();\n if (email === null) {\n notify.info(\"Sending mail cancelled \uD83D\uDE36\");\n return undefined;\n }\n\n notify.info(\"Sending mail... \uD83D\uDE80\");\n const title = getTitle(what);\n const htmlBody = convertMarkDownToHtml(what);\n\n sendMail(htmlBody, email, title);\n};\n\nexport { mailTo };\n", "import notify from \"../components/molecules/notify\";\n\nexport const copyToClipboard = async (\n what,\n message = \"\uD83D\uDCCB Copied to clipboard\"\n) => {\n try {\n await navigator.clipboard.writeText(what);\n notify.success(message);\n } catch (error) {\n notify.error(error.message);\n }\n};\n", "import { isArray } from \"../../../utils/isArray\";\n\nexport const button = (els, fn, id) => {\n const elements = isArray(els) ? els : [els];\n const button = document.createElement(\"button\");\n button.setAttribute(\"type\", \"button\");\n if (id) {\n button.setAttribute(\"id\", id);\n }\n elements.forEach((element) => {\n if (typeof element === \"string\") {\n button.appendChild(document.createTextNode(element));\n } else {\n button.appendChild(element);\n }\n });\n button.onclick = (e) => fn(e);\n\n return button;\n};\n", "import select from \"../../../utils/dom\";\nimport { url } from \"../../../utils/urlManager\";\nimport { copyToClipboard } from \"../../../utils/copyToClipboard\";\nimport { button } from \"../../atoms/button/button\";\nimport { convertMarkDownToHtml } from \"./mdToHtml\";\n\nconst markDownViewer = (() => {\n return {\n view: select(\".preview\"),\n init: function () {\n this.update();\n select(\".terminal\").listen(\"input\", () => this.update());\n const isVisible = Boolean(url.getSearchParam(\"md\"));\n if (isVisible) {\n this.view.show();\n } else {\n this.view.hide();\n }\n return this;\n },\n update: async function () {\n const md = select(\".terminal\").getValue();\n\n this.view.innerHTML(convertMarkDownToHtml(md));\n\n const { elements } = select(\"pre\");\n Array.prototype.slice.call(elements).forEach((el) => {\n const copyBtn = button(\"\uD83D\uDCCB Copy\", async (e) => {\n e.stopPropagation();\n const codeToCopy = e.srcElement.previousSibling.innerHTML;\n await copyToClipboard(codeToCopy, \"\uD83D\uDCCB Code copied to clipboard\");\n });\n el.appendChild(copyBtn);\n });\n\n select(\"code\").listenAll(\"click\", async ({ innerHTML }) => {\n const result = eval(innerHTML);\n select(\".console\").show().innerHTML(result);\n });\n select(\".console\").listen(\"click\", async (e) => {\n e.srcElement.classList.add(\"hidden\");\n const codeToCopy = e.srcElement.innerHTML;\n await copyToClipboard(codeToCopy, \"\uD83D\uDCCB Code copied to clipboard\");\n });\n },\n show: function (mode = true) {\n this.view.show();\n url.set(undefined, {\n md: mode,\n });\n },\n hide: function () {\n this.view.hide();\n url.deleteParam(\"md\");\n },\n toggle: function (mode = \"true\") {\n if (url.getSearchParam(\"md\") === mode) {\n this.hide();\n } else {\n this.show(mode);\n }\n return this;\n },\n };\n})();\n\nexport default markDownViewer;\n", "import isJSON from \"./isJSON\";\nimport notify from \"../components/molecules/notify\";\n\nconst prettifyJSON = (selector) => {\n const el = document.querySelector(selector);\n if (isJSON(el.value)) {\n const prettifiedJSON = JSON.stringify(JSON.parse(el.value), null, 2);\n el.value = prettifiedJSON;\n notify.success(\"\uD83D\uDC4D JSON value prettified\");\n } else {\n notify.error(\"\uD83D\uDE27 Value is not in valid JSON format\");\n }\n};\n\nexport default prettifyJSON;\n", "export const sleep = (ms = 1000) =>\n new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n", "export const icon = (svgIcon, altText, className) => {\n const image = document.createElement(\"IMG\");\n\n if (className) image.classList.add(className);\n if (altText) image.setAttribute(\"alt\", altText);\n image.setAttribute(\"src\", svgIcon);\n return image;\n};\n", "import notify from \"../components/molecules/notify\";\nimport { getNote } from \"../components/organisms/noteManager/noteManager\";\nimport { url } from \"./urlManager\";\n\nexport const share = async () => {\n try {\n const note = getNote();\n const currentUrl = url.get();\n await navigator.share({\n title: note ? note.title : TITLE_NAME,\n text: note ? note.text : \"Temporary note keeping app for the browser\",\n url: currentUrl,\n });\n } catch (error) {\n notify.info(`${error.message}`);\n }\n};\n", "/**\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 mergeOpts from 'merge-options'\nimport { isTest } from 'ipfs-utils/src/env.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport * as dagPB from '@ipld/dag-pb'\nimport * as dagCBOR from '@ipld/dag-cbor'\nimport * as dagJSON from '@ipld/dag-json'\nimport * as dagJOSE from 'dag-jose'\nimport { identity } from 'multiformats/hashes/identity'\nimport { bases, hashes, codecs } from 'multiformats/basics'\nimport { initAssets } from 'ipfs-core-config/init-assets'\nimport { AlreadyInitializedError } from '../errors.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { createStart } from './start.js'\n\nimport { createStop } from './stop.js'\nimport { createDns } from './dns.js'\nimport { createIsOnline } from './is-online.js'\nimport { createResolve } from './resolve.js'\nimport { PinAPI } from './pin/index.js'\nimport { IPNSAPI } from './ipns.js'\nimport { NameAPI } from './name/index.js'\nimport { createRefs } from './refs/index.js'\nimport { createLocal } from './refs/local.js'\nimport { BitswapAPI } from './bitswap/index.js'\nimport { BootstrapAPI } from './bootstrap/index.js'\nimport { BlockAPI } from './block/index.js'\nimport { RootAPI } from './root.js'\nimport { createVersion } from './version.js'\nimport { createId } from './id.js'\nimport { createConfig } from './config/index.js'\nimport { DagAPI } from './dag/index.js'\nimport { createPreloader } from '../preload.js'\nimport { createMfsPreloader } from '../mfs-preload.js'\nimport { createFiles } from './files/index.js'\nimport { KeyAPI } from './key/index.js'\nimport { ObjectAPI } from './object/index.js'\nimport { RepoAPI } from './repo/index.js'\nimport { StatsAPI } from './stats/index.js'\nimport { Storage } from './storage.js'\nimport { Network } from './network.js'\nimport { Service } from '../utils/service.js'\nimport { SwarmAPI } from './swarm/index.js'\nimport { createPing } from './ping.js'\nimport { createDht } from './dht.js'\nimport { createPubsub } from './pubsub.js'\nimport { Multicodecs } from 'ipfs-core-utils/multicodecs'\nimport { Multihashes } from 'ipfs-core-utils/multihashes'\nimport { Multibases } from 'ipfs-core-utils/multibases'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs')\n\nconst IPNS_INIT_KEYSPACE_TIMEOUT = 30000\n\n/**\n * @typedef {import('../types').Options} Options\n * @typedef {import('../types').Print} Print\n * @typedef {import('./storage')} StorageAPI\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('multiformats/bases/interface').MultibaseCodec} MultibaseCodec\n */\n\nclass IPFS {\n /**\n * @param {object} config\n * @param {Print} config.print\n * @param {Storage} config.storage\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {Options} config.options\n */\n constructor ({ print, storage, codecs, options }) {\n const { peerId, repo, keychain } = storage\n const network = Service.create(Network)\n\n const preload = createPreloader(options.preload)\n\n const dns = createDns()\n const isOnline = createIsOnline({ network })\n // @ts-expect-error This type check fails as options.\n // libp2p can be a function, while IPNS router config expects libp2p config\n const ipns = new IPNSAPI(options)\n\n /** @type {MultihashHasher[]} */\n const multihashHashers = Object.values(hashes);\n\n (options.ipld && options.ipld.hashers ? options.ipld.hashers : []).forEach(hasher => multihashHashers.push(hasher))\n\n this.hashers = new Multihashes({\n hashers: multihashHashers,\n loadHasher: options.ipld && options.ipld.loadHasher\n })\n\n /** @type {MultibaseCodec[]} */\n const multibaseCodecs = Object.values(bases);\n\n (options.ipld && options.ipld.bases ? options.ipld.bases : []).forEach(base => multibaseCodecs.push(base))\n\n this.bases = new Multibases({\n bases: multibaseCodecs,\n loadBase: options.ipld && options.ipld.loadBase\n })\n\n const pin = new PinAPI({ repo, codecs })\n const block = new BlockAPI({ codecs, hashers: this.hashers, preload, repo })\n\n const name = new NameAPI({\n dns,\n ipns,\n repo,\n codecs,\n peerId,\n isOnline,\n keychain,\n options\n })\n\n const resolve = createResolve({ repo, codecs, bases: this.bases, name })\n\n const dag = new DagAPI({ repo, codecs, hashers: this.hashers, preload })\n const refs = Object.assign(createRefs({ repo, codecs, resolve, preload }), {\n local: createLocal({ repo: storage.repo })\n })\n const { add, addAll, cat, get, ls } = new RootAPI({\n preload,\n repo,\n options: options.EXPERIMENTAL,\n hashers: this.hashers\n })\n\n const files = createFiles({\n repo,\n preload,\n hashers: this.hashers,\n options\n })\n\n const mfsPreload = createMfsPreloader({\n files,\n preload,\n options: options.preload\n })\n\n this.preload = preload\n this.name = name\n this.ipns = ipns\n this.pin = pin\n this.resolve = resolve\n this.block = block\n this.refs = refs\n\n this.start = createStart({\n network,\n peerId,\n repo,\n preload,\n ipns,\n mfsPreload,\n print,\n keychain,\n hashers: this.hashers,\n options\n })\n\n this.stop = createStop({\n network,\n preload,\n mfsPreload,\n ipns,\n repo\n })\n\n this.dht = createDht({ network, repo, peerId })\n this.pubsub = createPubsub({ network, config: options.config })\n this.dns = dns\n this.isOnline = isOnline\n this.id = createId({ network, peerId })\n this.version = createVersion({ repo })\n this.bitswap = new BitswapAPI({ network })\n this.bootstrap = new BootstrapAPI({ repo })\n this.config = createConfig({ repo })\n this.ping = createPing({ network })\n\n this.add = add\n this.addAll = addAll\n this.cat = cat\n this.get = get\n this.ls = ls\n\n this.dag = dag\n this.files = files\n this.key = new KeyAPI({ keychain })\n this.object = new ObjectAPI({ preload, codecs, repo })\n this.repo = new RepoAPI({ repo, hashers: this.hashers })\n this.stats = new StatsAPI({ repo, network })\n this.swarm = new SwarmAPI({ network })\n\n // For the backwards compatibility\n Object.defineProperty(this, 'libp2p', {\n get () {\n const net = network.try()\n return net ? net.libp2p : undefined\n }\n })\n\n // unimplemented methods\n const notImplemented = () => Promise.reject(errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED'))\n const notImplementedIter = async function * () { throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED') } // eslint-disable-line require-yield\n this.commands = notImplemented\n this.diag = {\n cmds: notImplemented,\n net: notImplemented,\n sys: notImplemented\n }\n this.log = {\n level: notImplemented,\n ls: notImplemented,\n tail: notImplementedIter\n }\n this.mount = notImplemented\n\n this.codecs = codecs\n }\n\n /**\n * `IPFS.create` will do the initialization. Keep this around for backwards\n * compatibility.\n *\n * @deprecated\n */\n async init () { // eslint-disable-line require-await\n throw new AlreadyInitializedError()\n }\n}\n\n/**\n * @param {IPFS} ipfs\n */\nconst addEmptyDir = async (ipfs) => {\n const buf = dagPB.encode({\n Data: new UnixFS({ type: 'directory' }).marshal(),\n Links: []\n })\n\n const cid = await ipfs.block.put(buf, {\n mhtype: 'sha2-256',\n format: 'dag-pb'\n })\n\n await ipfs.pin.add(cid)\n\n return cid\n}\n\n/**\n * @returns {Options}\n */\nconst getDefaultOptions = () => ({\n start: true,\n EXPERIMENTAL: {},\n preload: {\n enabled: !isTest, // preload by default, unless in test env\n addresses: [\n '/dns4/node0.preload.ipfs.io/https',\n '/dns4/node1.preload.ipfs.io/https',\n '/dns4/node2.preload.ipfs.io/https',\n '/dns4/node3.preload.ipfs.io/https'\n ]\n }\n})\n\n/**\n * @param {Options} options\n */\nexport async function create (options = {}) {\n options = mergeOptions(getDefaultOptions(), options)\n const initOptions = options.init || {}\n\n /**\n * @type {BlockCodec}\n */\n const id = {\n name: identity.name,\n code: identity.code,\n encode: (id) => id,\n decode: (id) => id\n }\n\n /** @type {BlockCodec[]} */\n const blockCodecs = Object.values(codecs);\n\n [dagPB, dagCBOR, dagJSON, dagJOSE, id].concat((options.ipld && options.ipld.codecs) || []).forEach(codec => blockCodecs.push(codec))\n\n const multicodecs = new Multicodecs({\n codecs: blockCodecs,\n loadCodec: options.ipld && options.ipld.loadCodec\n })\n\n // eslint-disable-next-line no-console\n const print = options.silent ? log : console.log\n\n log('creating repo')\n const storage = await Storage.start(print, multicodecs, options)\n\n log('getting repo config')\n const config = await storage.repo.config.getAll()\n\n const ipfs = new IPFS({\n storage,\n print,\n codecs: multicodecs,\n options: { ...options, config }\n })\n\n log('starting preload')\n await ipfs.preload.start()\n\n log('starting storage')\n ipfs.ipns.startOffline(storage)\n\n if (storage.isNew && !initOptions.emptyRepo) {\n // add empty unixfs dir object (go-ipfs assumes this exists)\n const cid = await addEmptyDir(ipfs)\n\n log('adding default assets')\n await initAssets({ addAll: ipfs.addAll, print })\n\n log('initializing IPNS keyspace')\n\n if (storage.peerId.publicKey == null) {\n throw errCode(new Error('Public key missing'), 'ERR_MISSING_PUBLIC_KEY')\n }\n\n const timeoutController = new TimeoutController(IPNS_INIT_KEYSPACE_TIMEOUT)\n try {\n await ipfs.ipns.initializeKeyspace(storage.peerId, uint8ArrayFromString(`/ipfs/${cid}`), {\n signal: timeoutController.signal\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n if (options.start !== false) {\n log('starting node')\n await ipfs.start()\n }\n\n return ipfs\n}\n", "import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\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\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "import errcode from 'err-code'\nimport * as Pb from './unixfs.js'\nconst PBData = Pb.Data\n\n/**\n * @typedef {import('./types').Mtime} Mtime\n * @typedef {import('./types').MtimeLike} MtimeLike\n */\n\nconst types = [\n 'raw',\n 'directory',\n 'file',\n 'metadata',\n 'symlink',\n 'hamt-sharded-directory'\n]\n\nconst dirTypes = [\n 'directory',\n 'hamt-sharded-directory'\n]\n\nconst DEFAULT_FILE_MODE = parseInt('0644', 8)\nconst DEFAULT_DIRECTORY_MODE = parseInt('0755', 8)\n\n/**\n * @param {string | number | undefined} [mode]\n */\nexport function parseMode (mode) {\n if (mode == null) {\n return undefined\n }\n\n if (typeof mode === 'number') {\n return mode & 0xFFF\n }\n\n mode = mode.toString()\n\n if (mode.substring(0, 1) === '0') {\n // octal string\n return parseInt(mode, 8) & 0xFFF\n }\n\n // decimal string\n return parseInt(mode, 10) & 0xFFF\n}\n\n/**\n * @param {any} input\n */\nexport function parseMtime (input) {\n if (input == null) {\n return undefined\n }\n\n /** @type {Mtime | undefined} */\n let mtime\n\n // { secs, nsecs }\n if (input.secs != null) {\n mtime = {\n secs: input.secs,\n nsecs: input.nsecs\n }\n }\n\n // UnixFS TimeSpec\n if (input.Seconds != null) {\n mtime = {\n secs: input.Seconds,\n nsecs: input.FractionalNanoseconds\n }\n }\n\n // process.hrtime()\n if (Array.isArray(input)) {\n mtime = {\n secs: input[0],\n nsecs: input[1]\n }\n }\n\n // Javascript Date\n if (input instanceof Date) {\n const ms = input.getTime()\n const secs = Math.floor(ms / 1000)\n\n mtime = {\n secs: secs,\n nsecs: (ms - (secs * 1000)) * 1000\n }\n }\n\n /*\n TODO: https://github.com/ipfs/aegir/issues/487\n\n // process.hrtime.bigint()\n if (input instanceof BigInt) {\n const secs = input / BigInt(1e9)\n const nsecs = input - (secs * BigInt(1e9))\n\n mtime = {\n secs: parseInt(secs.toString()),\n nsecs: parseInt(nsecs.toString())\n }\n }\n */\n\n if (!Object.prototype.hasOwnProperty.call(mtime, 'secs')) {\n return undefined\n }\n\n if (mtime != null && mtime.nsecs != null && (mtime.nsecs < 0 || mtime.nsecs > 999999999)) {\n throw errcode(new Error('mtime-nsecs must be within the range [0,999999999]'), 'ERR_INVALID_MTIME_NSECS')\n }\n\n return mtime\n}\n\nclass UnixFS {\n /**\n * Decode from protobuf https://github.com/ipfs/specs/blob/master/UNIXFS.md\n *\n * @param {Uint8Array} marshaled\n */\n static unmarshal (marshaled) {\n const message = PBData.decode(marshaled)\n const decoded = PBData.toObject(message, {\n defaults: false,\n arrays: true,\n longs: Number,\n objects: false\n })\n\n const data = new UnixFS({\n type: types[decoded.Type],\n data: decoded.Data,\n blockSizes: decoded.blocksizes,\n mode: decoded.mode,\n mtime: decoded.mtime\n ? {\n secs: decoded.mtime.Seconds,\n nsecs: decoded.mtime.FractionalNanoseconds\n }\n : undefined\n })\n\n // make sure we honour the original mode\n data._originalMode = decoded.mode || 0\n\n return data\n }\n\n /**\n * @param {object} [options]\n * @param {string} [options.type='file']\n * @param {Uint8Array} [options.data]\n * @param {number[]} [options.blockSizes]\n * @param {number} [options.hashType]\n * @param {number} [options.fanout]\n * @param {MtimeLike | null} [options.mtime]\n * @param {number | string} [options.mode]\n */\n constructor (options = {\n type: 'file'\n }) {\n const {\n type,\n data,\n blockSizes,\n hashType,\n fanout,\n mtime,\n mode\n } = options\n\n if (type && !types.includes(type)) {\n throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE')\n }\n\n this.type = type || 'file'\n this.data = data\n this.hashType = hashType\n this.fanout = fanout\n\n /** @type {number[]} */\n this.blockSizes = blockSizes || []\n this._originalMode = 0\n this.mode = parseMode(mode)\n\n if (mtime) {\n this.mtime = parseMtime(mtime)\n\n if (this.mtime && !this.mtime.nsecs) {\n this.mtime.nsecs = 0\n }\n }\n }\n\n /**\n * @param {number | undefined} mode\n */\n set mode (mode) {\n this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE\n\n const parsedMode = parseMode(mode)\n\n if (parsedMode !== undefined) {\n this._mode = parsedMode\n }\n }\n\n /**\n * @returns {number | undefined}\n */\n get mode () {\n return this._mode\n }\n\n isDirectory () {\n return Boolean(this.type && dirTypes.includes(this.type))\n }\n\n /**\n * @param {number} size\n */\n addBlockSize (size) {\n this.blockSizes.push(size)\n }\n\n /**\n * @param {number} index\n */\n removeBlockSize (index) {\n this.blockSizes.splice(index, 1)\n }\n\n /**\n * Returns `0` for directories or `data.length + sum(blockSizes)` for everything else\n */\n fileSize () {\n if (this.isDirectory()) {\n // dirs don't have file size\n return 0\n }\n\n let sum = 0\n this.blockSizes.forEach((size) => {\n sum += size\n })\n\n if (this.data) {\n sum += this.data.length\n }\n\n return sum\n }\n\n /**\n * encode to protobuf Uint8Array\n */\n marshal () {\n let type\n\n switch (this.type) {\n case 'raw': type = PBData.DataType.Raw; break\n case 'directory': type = PBData.DataType.Directory; break\n case 'file': type = PBData.DataType.File; break\n case 'metadata': type = PBData.DataType.Metadata; break\n case 'symlink': type = PBData.DataType.Symlink; break\n case 'hamt-sharded-directory': type = PBData.DataType.HAMTShard; break\n default:\n throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE')\n }\n\n let data = this.data\n\n if (!this.data || !this.data.length) {\n data = undefined\n }\n\n let mode\n\n if (this.mode != null) {\n mode = (this._originalMode & 0xFFFFF000) | (parseMode(this.mode) || 0)\n\n if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) {\n mode = undefined\n }\n\n if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) {\n mode = undefined\n }\n }\n\n let mtime\n\n if (this.mtime != null) {\n const parsed = parseMtime(this.mtime)\n\n if (parsed) {\n mtime = {\n Seconds: parsed.secs,\n FractionalNanoseconds: parsed.nsecs\n }\n\n if (mtime.FractionalNanoseconds === 0) {\n delete mtime.FractionalNanoseconds\n }\n }\n }\n\n const pbData = {\n Type: type,\n Data: data,\n filesize: this.isDirectory() ? undefined : this.fileSize(),\n blocksizes: this.blockSizes,\n hashType: this.hashType,\n fanout: this.fanout,\n mode,\n mtime\n }\n\n return PBData.encode(pbData).finish()\n }\n}\n\nexport { UnixFS }\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"ipfs-unixfs\"] || ($protobuf.roots[\"ipfs-unixfs\"] = {});\n\nexport const Data = $root.Data = (() => {\n\n /**\n * Properties of a Data.\n * @exports IData\n * @interface IData\n * @property {Data.DataType} Type Data Type\n * @property {Uint8Array|null} [Data] Data Data\n * @property {number|null} [filesize] Data filesize\n * @property {Array.|null} [blocksizes] Data blocksizes\n * @property {number|null} [hashType] Data hashType\n * @property {number|null} [fanout] Data fanout\n * @property {number|null} [mode] Data mode\n * @property {IUnixTime|null} [mtime] Data mtime\n */\n\n /**\n * Constructs a new Data.\n * @exports Data\n * @classdesc Represents a Data.\n * @implements IData\n * @constructor\n * @param {IData=} [p] Properties to set\n */\n function Data(p) {\n this.blocksizes = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Data Type.\n * @member {Data.DataType} Type\n * @memberof Data\n * @instance\n */\n Data.prototype.Type = 0;\n\n /**\n * Data Data.\n * @member {Uint8Array} Data\n * @memberof Data\n * @instance\n */\n Data.prototype.Data = $util.newBuffer([]);\n\n /**\n * Data filesize.\n * @member {number} filesize\n * @memberof Data\n * @instance\n */\n Data.prototype.filesize = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data blocksizes.\n * @member {Array.} blocksizes\n * @memberof Data\n * @instance\n */\n Data.prototype.blocksizes = $util.emptyArray;\n\n /**\n * Data hashType.\n * @member {number} hashType\n * @memberof Data\n * @instance\n */\n Data.prototype.hashType = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data fanout.\n * @member {number} fanout\n * @memberof Data\n * @instance\n */\n Data.prototype.fanout = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data mode.\n * @member {number} mode\n * @memberof Data\n * @instance\n */\n Data.prototype.mode = 0;\n\n /**\n * Data mtime.\n * @member {IUnixTime|null|undefined} mtime\n * @memberof Data\n * @instance\n */\n Data.prototype.mtime = null;\n\n /**\n * Encodes the specified Data message. Does not implicitly {@link Data.verify|verify} messages.\n * @function encode\n * @memberof Data\n * @static\n * @param {IData} m Data message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Data.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n w.uint32(8).int32(m.Type);\n if (m.Data != null && Object.hasOwnProperty.call(m, \"Data\"))\n w.uint32(18).bytes(m.Data);\n if (m.filesize != null && Object.hasOwnProperty.call(m, \"filesize\"))\n w.uint32(24).uint64(m.filesize);\n if (m.blocksizes != null && m.blocksizes.length) {\n for (var i = 0; i < m.blocksizes.length; ++i)\n w.uint32(32).uint64(m.blocksizes[i]);\n }\n if (m.hashType != null && Object.hasOwnProperty.call(m, \"hashType\"))\n w.uint32(40).uint64(m.hashType);\n if (m.fanout != null && Object.hasOwnProperty.call(m, \"fanout\"))\n w.uint32(48).uint64(m.fanout);\n if (m.mode != null && Object.hasOwnProperty.call(m, \"mode\"))\n w.uint32(56).uint32(m.mode);\n if (m.mtime != null && Object.hasOwnProperty.call(m, \"mtime\"))\n $root.UnixTime.encode(m.mtime, w.uint32(66).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes a Data message from the specified reader or buffer.\n * @function decode\n * @memberof Data\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Data} Data\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Data.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Data();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.Type = r.int32();\n break;\n case 2:\n m.Data = r.bytes();\n break;\n case 3:\n m.filesize = r.uint64();\n break;\n case 4:\n if (!(m.blocksizes && m.blocksizes.length))\n m.blocksizes = [];\n if ((t & 7) === 2) {\n var c2 = r.uint32() + r.pos;\n while (r.pos < c2)\n m.blocksizes.push(r.uint64());\n } else\n m.blocksizes.push(r.uint64());\n break;\n case 5:\n m.hashType = r.uint64();\n break;\n case 6:\n m.fanout = r.uint64();\n break;\n case 7:\n m.mode = r.uint32();\n break;\n case 8:\n m.mtime = $root.UnixTime.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"Type\"))\n throw $util.ProtocolError(\"missing required 'Type'\", { instance: m });\n return m;\n };\n\n /**\n * Creates a Data message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Data\n * @static\n * @param {Object.} d Plain object\n * @returns {Data} Data\n */\n Data.fromObject = function fromObject(d) {\n if (d instanceof $root.Data)\n return d;\n var m = new $root.Data();\n switch (d.Type) {\n case \"Raw\":\n case 0:\n m.Type = 0;\n break;\n case \"Directory\":\n case 1:\n m.Type = 1;\n break;\n case \"File\":\n case 2:\n m.Type = 2;\n break;\n case \"Metadata\":\n case 3:\n m.Type = 3;\n break;\n case \"Symlink\":\n case 4:\n m.Type = 4;\n break;\n case \"HAMTShard\":\n case 5:\n m.Type = 5;\n break;\n }\n if (d.Data != null) {\n if (typeof d.Data === \"string\")\n $util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0);\n else if (d.Data.length)\n m.Data = d.Data;\n }\n if (d.filesize != null) {\n if ($util.Long)\n (m.filesize = $util.Long.fromValue(d.filesize)).unsigned = true;\n else if (typeof d.filesize === \"string\")\n m.filesize = parseInt(d.filesize, 10);\n else if (typeof d.filesize === \"number\")\n m.filesize = d.filesize;\n else if (typeof d.filesize === \"object\")\n m.filesize = new $util.LongBits(d.filesize.low >>> 0, d.filesize.high >>> 0).toNumber(true);\n }\n if (d.blocksizes) {\n if (!Array.isArray(d.blocksizes))\n throw TypeError(\".Data.blocksizes: array expected\");\n m.blocksizes = [];\n for (var i = 0; i < d.blocksizes.length; ++i) {\n if ($util.Long)\n (m.blocksizes[i] = $util.Long.fromValue(d.blocksizes[i])).unsigned = true;\n else if (typeof d.blocksizes[i] === \"string\")\n m.blocksizes[i] = parseInt(d.blocksizes[i], 10);\n else if (typeof d.blocksizes[i] === \"number\")\n m.blocksizes[i] = d.blocksizes[i];\n else if (typeof d.blocksizes[i] === \"object\")\n m.blocksizes[i] = new $util.LongBits(d.blocksizes[i].low >>> 0, d.blocksizes[i].high >>> 0).toNumber(true);\n }\n }\n if (d.hashType != null) {\n if ($util.Long)\n (m.hashType = $util.Long.fromValue(d.hashType)).unsigned = true;\n else if (typeof d.hashType === \"string\")\n m.hashType = parseInt(d.hashType, 10);\n else if (typeof d.hashType === \"number\")\n m.hashType = d.hashType;\n else if (typeof d.hashType === \"object\")\n m.hashType = new $util.LongBits(d.hashType.low >>> 0, d.hashType.high >>> 0).toNumber(true);\n }\n if (d.fanout != null) {\n if ($util.Long)\n (m.fanout = $util.Long.fromValue(d.fanout)).unsigned = true;\n else if (typeof d.fanout === \"string\")\n m.fanout = parseInt(d.fanout, 10);\n else if (typeof d.fanout === \"number\")\n m.fanout = d.fanout;\n else if (typeof d.fanout === \"object\")\n m.fanout = new $util.LongBits(d.fanout.low >>> 0, d.fanout.high >>> 0).toNumber(true);\n }\n if (d.mode != null) {\n m.mode = d.mode >>> 0;\n }\n if (d.mtime != null) {\n if (typeof d.mtime !== \"object\")\n throw TypeError(\".Data.mtime: object expected\");\n m.mtime = $root.UnixTime.fromObject(d.mtime);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Data message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Data\n * @static\n * @param {Data} m Data\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Data.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.blocksizes = [];\n }\n if (o.defaults) {\n d.Type = o.enums === String ? \"Raw\" : 0;\n if (o.bytes === String)\n d.Data = \"\";\n else {\n d.Data = [];\n if (o.bytes !== Array)\n d.Data = $util.newBuffer(d.Data);\n }\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.filesize = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.filesize = o.longs === String ? \"0\" : 0;\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.hashType = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.hashType = o.longs === String ? \"0\" : 0;\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.fanout = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.fanout = o.longs === String ? \"0\" : 0;\n d.mode = 0;\n d.mtime = null;\n }\n if (m.Type != null && m.hasOwnProperty(\"Type\")) {\n d.Type = o.enums === String ? $root.Data.DataType[m.Type] : m.Type;\n }\n if (m.Data != null && m.hasOwnProperty(\"Data\")) {\n d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data;\n }\n if (m.filesize != null && m.hasOwnProperty(\"filesize\")) {\n if (typeof m.filesize === \"number\")\n d.filesize = o.longs === String ? String(m.filesize) : m.filesize;\n else\n d.filesize = o.longs === String ? $util.Long.prototype.toString.call(m.filesize) : o.longs === Number ? new $util.LongBits(m.filesize.low >>> 0, m.filesize.high >>> 0).toNumber(true) : m.filesize;\n }\n if (m.blocksizes && m.blocksizes.length) {\n d.blocksizes = [];\n for (var j = 0; j < m.blocksizes.length; ++j) {\n if (typeof m.blocksizes[j] === \"number\")\n d.blocksizes[j] = o.longs === String ? String(m.blocksizes[j]) : m.blocksizes[j];\n else\n d.blocksizes[j] = o.longs === String ? $util.Long.prototype.toString.call(m.blocksizes[j]) : o.longs === Number ? new $util.LongBits(m.blocksizes[j].low >>> 0, m.blocksizes[j].high >>> 0).toNumber(true) : m.blocksizes[j];\n }\n }\n if (m.hashType != null && m.hasOwnProperty(\"hashType\")) {\n if (typeof m.hashType === \"number\")\n d.hashType = o.longs === String ? String(m.hashType) : m.hashType;\n else\n d.hashType = o.longs === String ? $util.Long.prototype.toString.call(m.hashType) : o.longs === Number ? new $util.LongBits(m.hashType.low >>> 0, m.hashType.high >>> 0).toNumber(true) : m.hashType;\n }\n if (m.fanout != null && m.hasOwnProperty(\"fanout\")) {\n if (typeof m.fanout === \"number\")\n d.fanout = o.longs === String ? String(m.fanout) : m.fanout;\n else\n d.fanout = o.longs === String ? $util.Long.prototype.toString.call(m.fanout) : o.longs === Number ? new $util.LongBits(m.fanout.low >>> 0, m.fanout.high >>> 0).toNumber(true) : m.fanout;\n }\n if (m.mode != null && m.hasOwnProperty(\"mode\")) {\n d.mode = m.mode;\n }\n if (m.mtime != null && m.hasOwnProperty(\"mtime\")) {\n d.mtime = $root.UnixTime.toObject(m.mtime, o);\n }\n return d;\n };\n\n /**\n * Converts this Data to JSON.\n * @function toJSON\n * @memberof Data\n * @instance\n * @returns {Object.} JSON object\n */\n Data.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * DataType enum.\n * @name Data.DataType\n * @enum {number}\n * @property {number} Raw=0 Raw value\n * @property {number} Directory=1 Directory value\n * @property {number} File=2 File value\n * @property {number} Metadata=3 Metadata value\n * @property {number} Symlink=4 Symlink value\n * @property {number} HAMTShard=5 HAMTShard value\n */\n Data.DataType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Raw\"] = 0;\n values[valuesById[1] = \"Directory\"] = 1;\n values[valuesById[2] = \"File\"] = 2;\n values[valuesById[3] = \"Metadata\"] = 3;\n values[valuesById[4] = \"Symlink\"] = 4;\n values[valuesById[5] = \"HAMTShard\"] = 5;\n return values;\n })();\n\n return Data;\n})();\n\nexport const UnixTime = $root.UnixTime = (() => {\n\n /**\n * Properties of an UnixTime.\n * @exports IUnixTime\n * @interface IUnixTime\n * @property {number} Seconds UnixTime Seconds\n * @property {number|null} [FractionalNanoseconds] UnixTime FractionalNanoseconds\n */\n\n /**\n * Constructs a new UnixTime.\n * @exports UnixTime\n * @classdesc Represents an UnixTime.\n * @implements IUnixTime\n * @constructor\n * @param {IUnixTime=} [p] Properties to set\n */\n function UnixTime(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * UnixTime Seconds.\n * @member {number} Seconds\n * @memberof UnixTime\n * @instance\n */\n UnixTime.prototype.Seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0;\n\n /**\n * UnixTime FractionalNanoseconds.\n * @member {number} FractionalNanoseconds\n * @memberof UnixTime\n * @instance\n */\n UnixTime.prototype.FractionalNanoseconds = 0;\n\n /**\n * Encodes the specified UnixTime message. Does not implicitly {@link UnixTime.verify|verify} messages.\n * @function encode\n * @memberof UnixTime\n * @static\n * @param {IUnixTime} m UnixTime message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n UnixTime.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n w.uint32(8).int64(m.Seconds);\n if (m.FractionalNanoseconds != null && Object.hasOwnProperty.call(m, \"FractionalNanoseconds\"))\n w.uint32(21).fixed32(m.FractionalNanoseconds);\n return w;\n };\n\n /**\n * Decodes an UnixTime message from the specified reader or buffer.\n * @function decode\n * @memberof UnixTime\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {UnixTime} UnixTime\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n UnixTime.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.UnixTime();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.Seconds = r.int64();\n break;\n case 2:\n m.FractionalNanoseconds = r.fixed32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"Seconds\"))\n throw $util.ProtocolError(\"missing required 'Seconds'\", { instance: m });\n return m;\n };\n\n /**\n * Creates an UnixTime message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof UnixTime\n * @static\n * @param {Object.} d Plain object\n * @returns {UnixTime} UnixTime\n */\n UnixTime.fromObject = function fromObject(d) {\n if (d instanceof $root.UnixTime)\n return d;\n var m = new $root.UnixTime();\n if (d.Seconds != null) {\n if ($util.Long)\n (m.Seconds = $util.Long.fromValue(d.Seconds)).unsigned = false;\n else if (typeof d.Seconds === \"string\")\n m.Seconds = parseInt(d.Seconds, 10);\n else if (typeof d.Seconds === \"number\")\n m.Seconds = d.Seconds;\n else if (typeof d.Seconds === \"object\")\n m.Seconds = new $util.LongBits(d.Seconds.low >>> 0, d.Seconds.high >>> 0).toNumber();\n }\n if (d.FractionalNanoseconds != null) {\n m.FractionalNanoseconds = d.FractionalNanoseconds >>> 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an UnixTime message. Also converts values to other types if specified.\n * @function toObject\n * @memberof UnixTime\n * @static\n * @param {UnixTime} m UnixTime\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n UnixTime.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if ($util.Long) {\n var n = new $util.Long(0, 0, false);\n d.Seconds = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.Seconds = o.longs === String ? \"0\" : 0;\n d.FractionalNanoseconds = 0;\n }\n if (m.Seconds != null && m.hasOwnProperty(\"Seconds\")) {\n if (typeof m.Seconds === \"number\")\n d.Seconds = o.longs === String ? String(m.Seconds) : m.Seconds;\n else\n d.Seconds = o.longs === String ? $util.Long.prototype.toString.call(m.Seconds) : o.longs === Number ? new $util.LongBits(m.Seconds.low >>> 0, m.Seconds.high >>> 0).toNumber() : m.Seconds;\n }\n if (m.FractionalNanoseconds != null && m.hasOwnProperty(\"FractionalNanoseconds\")) {\n d.FractionalNanoseconds = m.FractionalNanoseconds;\n }\n return d;\n };\n\n /**\n * Converts this UnixTime to JSON.\n * @function toJSON\n * @memberof UnixTime\n * @instance\n * @returns {Object.} JSON object\n */\n UnixTime.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return UnixTime;\n})();\n\nexport const Metadata = $root.Metadata = (() => {\n\n /**\n * Properties of a Metadata.\n * @exports IMetadata\n * @interface IMetadata\n * @property {string|null} [MimeType] Metadata MimeType\n */\n\n /**\n * Constructs a new Metadata.\n * @exports Metadata\n * @classdesc Represents a Metadata.\n * @implements IMetadata\n * @constructor\n * @param {IMetadata=} [p] Properties to set\n */\n function Metadata(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Metadata MimeType.\n * @member {string} MimeType\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.MimeType = \"\";\n\n /**\n * Encodes the specified Metadata message. Does not implicitly {@link Metadata.verify|verify} messages.\n * @function encode\n * @memberof Metadata\n * @static\n * @param {IMetadata} m Metadata message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Metadata.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.MimeType != null && Object.hasOwnProperty.call(m, \"MimeType\"))\n w.uint32(10).string(m.MimeType);\n return w;\n };\n\n /**\n * Decodes a Metadata message from the specified reader or buffer.\n * @function decode\n * @memberof Metadata\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Metadata} Metadata\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Metadata.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Metadata();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.MimeType = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Metadata message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Metadata\n * @static\n * @param {Object.} d Plain object\n * @returns {Metadata} Metadata\n */\n Metadata.fromObject = function fromObject(d) {\n if (d instanceof $root.Metadata)\n return d;\n var m = new $root.Metadata();\n if (d.MimeType != null) {\n m.MimeType = String(d.MimeType);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Metadata message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Metadata\n * @static\n * @param {Metadata} m Metadata\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Metadata.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.MimeType = \"\";\n }\n if (m.MimeType != null && m.hasOwnProperty(\"MimeType\")) {\n d.MimeType = m.MimeType;\n }\n return d;\n };\n\n /**\n * Converts this Metadata to JSON.\n * @function toJSON\n * @memberof Metadata\n * @instance\n * @returns {Object.} JSON object\n */\n Metadata.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Metadata;\n})();\n\nexport { $root as default };\n", "import { CID } from 'multiformats/cid'\nimport { decodeNode } from './pb-decode.js'\nimport { encodeNode } from './pb-encode.js'\nimport { prepare, validate, createNode, createLink, toByteView } from './util.js'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\n/**\n * @typedef {import('./interface.js').PBLink} PBLink\n * @typedef {import('./interface.js').PBNode} PBNode\n */\n\nexport const name = 'dag-pb'\nexport const code = 0x70\n\n/**\n * @param {PBNode} node\n * @returns {ByteView}\n */\nexport function encode (node) {\n validate(node)\n\n const pbn = {}\n if (node.Links) {\n pbn.Links = node.Links.map((l) => {\n const link = {}\n if (l.Hash) {\n link.Hash = l.Hash.bytes // cid -> bytes\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n if (node.Data) {\n pbn.Data = node.Data\n }\n\n return encodeNode(pbn)\n}\n\n/**\n * @param {ByteView | ArrayBufferView} bytes\n * @returns {PBNode}\n */\nexport function decode (bytes) {\n const buf = toByteView(bytes)\n const pbn = decodeNode(buf)\n\n const node = {}\n\n if (pbn.Data) {\n node.Data = pbn.Data\n }\n\n if (pbn.Links) {\n node.Links = pbn.Links.map((l) => {\n const link = {}\n try {\n link.Hash = CID.decode(l.Hash)\n } catch (e) {}\n if (!link.Hash) {\n throw new Error('Invalid Hash field found in link, expected CID')\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n\n return node\n}\n\nexport { prepare, validate, createNode, createLink }\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\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) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\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 implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\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 implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\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\n decode (text: string): Uint8Array {\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\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}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\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\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\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\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\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\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\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\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 \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\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\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (/** @type {number} */ value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\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 implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode (digest: MultihashDigest, code: T): digest is MultihashDigest {\n return digest.code === code\n}\n", "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'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\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}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\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: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\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 (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\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: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n multihash as API.MultihashDigest,\n 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) as API.MultihashDigest\n return CID.create(version, code, digest)\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 /**\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: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\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: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\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: API.ByteView>): CID {\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 /**\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: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\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: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\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 } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "const textDecoder = new TextDecoder()\n\n/**\n * @typedef {import('./interface.js').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface.js').RawPBNode} RawPBNode\n */\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[number, number]}\n */\nfunction decodeVarint (bytes, offset) {\n let v = 0\n\n for (let shift = 0; ; shift += 7) {\n /* c8 ignore next 3 */\n if (shift >= 64) {\n throw new Error('protobuf: varint overflow')\n }\n /* c8 ignore next 3 */\n if (offset >= bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n const b = bytes[offset++]\n v += shift < 28 ? (b & 0x7f) << shift : (b & 0x7f) * (2 ** shift)\n if (b < 0x80) {\n break\n }\n }\n return [v, offset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[Uint8Array, number]}\n */\nfunction decodeBytes (bytes, offset) {\n let byteLen\n ;[byteLen, offset] = decodeVarint(bytes, offset)\n const postOffset = offset + byteLen\n\n /* c8 ignore next 3 */\n if (byteLen < 0 || postOffset < 0) {\n throw new Error('protobuf: invalid length')\n }\n /* c8 ignore next 3 */\n if (postOffset > bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n return [bytes.subarray(offset, postOffset), postOffset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} index\n * @returns {[number, number, number]}\n */\nfunction decodeKey (bytes, index) {\n let wire\n ;[wire, index] = decodeVarint(bytes, index)\n // [wireType, fieldNum, newIndex]\n return [wire & 0x7, wire >> 3, index]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBLink}\n */\nfunction decodeLink (bytes) {\n /** @type {RawPBLink} */\n const link = {}\n const l = bytes.length\n let index = 0\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (fieldNum === 1) {\n if (link.Hash) {\n throw new Error('protobuf: (PBLink) duplicate Hash section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Hash`)\n }\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Name before Hash')\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Hash')\n }\n\n [link.Hash, index] = decodeBytes(bytes, index)\n } else if (fieldNum === 2) {\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Name section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Name`)\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Name')\n }\n\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n link.Name = textDecoder.decode(byts)\n } else if (fieldNum === 3) {\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Tsize section')\n }\n if (wireType !== 0) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Tsize`)\n }\n\n [link.Tsize, index] = decodeVarint(bytes, index)\n } else {\n throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBLink) unexpected end of data')\n }\n\n return link\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBNode}\n */\nexport function decodeNode (bytes) {\n const l = bytes.length\n let index = 0\n /** @type {RawPBLink[]|void} */\n let links = undefined // eslint-disable-line no-undef-init\n let linksBeforeData = false\n /** @type {Uint8Array|void} */\n let data = undefined // eslint-disable-line no-undef-init\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${wireType}`)\n }\n\n if (fieldNum === 1) {\n if (data) {\n throw new Error('protobuf: (PBNode) duplicate Data section')\n }\n\n [data, index] = decodeBytes(bytes, index)\n if (links) {\n linksBeforeData = true\n }\n } else if (fieldNum === 2) {\n if (linksBeforeData) { // interleaved Links/Data/Links\n throw new Error('protobuf: (PBNode) duplicate Links section')\n } else if (!links) {\n links = []\n }\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n links.push(decodeLink(byts))\n } else {\n throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBNode) unexpected end of data')\n }\n\n /** @type {RawPBNode} */\n const node = {}\n if (data) {\n node.Data = data\n }\n node.Links = links || []\n return node\n}\n", "const textEncoder = new TextEncoder()\nconst maxInt32 = 2 ** 32\nconst maxUInt32 = 2 ** 31\n\n/**\n * @typedef {import('./interface.js').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface.js').RawPBNode} RawPBNode\n */\n\n// the encoders work backward from the end of the bytes array\n\n/**\n * encodeLink() is passed a slice of the parent byte array that ends where this\n * link needs to end, so it packs to the right-most part of the passed `bytes`\n *\n * @param {RawPBLink} link\n * @param {Uint8Array} bytes\n * @returns {number}\n */\nfunction encodeLink (link, bytes) {\n let i = bytes.length\n\n if (typeof link.Tsize === 'number') {\n if (link.Tsize < 0) {\n throw new Error('Tsize cannot be negative')\n }\n if (!Number.isSafeInteger(link.Tsize)) {\n throw new Error('Tsize too large for encoding')\n }\n i = encodeVarint(bytes, i, link.Tsize) - 1\n bytes[i] = 0x18\n }\n\n if (typeof link.Name === 'string') {\n const nameBytes = textEncoder.encode(link.Name)\n i -= nameBytes.length\n bytes.set(nameBytes, i)\n i = encodeVarint(bytes, i, nameBytes.length) - 1\n bytes[i] = 0x12\n }\n\n if (link.Hash) {\n i -= link.Hash.length\n bytes.set(link.Hash, i)\n i = encodeVarint(bytes, i, link.Hash.length) - 1\n bytes[i] = 0xa\n }\n\n return bytes.length - i\n}\n\n/**\n * Encodes a PBNode into a new byte array of precisely the correct size\n *\n * @param {RawPBNode} node\n * @returns {Uint8Array}\n */\nexport function encodeNode (node) {\n const size = sizeNode(node)\n const bytes = new Uint8Array(size)\n let i = size\n\n if (node.Data) {\n i -= node.Data.length\n bytes.set(node.Data, i)\n i = encodeVarint(bytes, i, node.Data.length) - 1\n bytes[i] = 0xa\n }\n\n if (node.Links) {\n for (let index = node.Links.length - 1; index >= 0; index--) {\n const size = encodeLink(node.Links[index], bytes.subarray(0, i))\n i -= size\n i = encodeVarint(bytes, i, size) - 1\n bytes[i] = 0x12\n }\n }\n\n return bytes\n}\n\n/**\n * work out exactly how many bytes this link takes up\n *\n * @param {RawPBLink} link\n * @returns\n */\nfunction sizeLink (link) {\n let n = 0\n\n if (link.Hash) {\n const l = link.Hash.length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Name === 'string') {\n const l = textEncoder.encode(link.Name).length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Tsize === 'number') {\n n += 1 + sov(link.Tsize)\n }\n\n return n\n}\n\n/**\n * Work out exactly how many bytes this node takes up\n *\n * @param {RawPBNode} node\n * @returns {number}\n */\nfunction sizeNode (node) {\n let n = 0\n\n if (node.Data) {\n const l = node.Data.length\n n += 1 + l + sov(l)\n }\n\n if (node.Links) {\n for (const link of node.Links) {\n const l = sizeLink(link)\n n += 1 + l + sov(l)\n }\n }\n\n return n\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @param {number} v\n * @returns {number}\n */\nfunction encodeVarint (bytes, offset, v) {\n offset -= sov(v)\n const base = offset\n\n while (v >= maxUInt32) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v /= 128\n }\n\n while (v >= 128) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v >>>= 7\n }\n\n bytes[offset] = v\n\n return base\n}\n\n/**\n * size of varint\n *\n * @param {number} x\n * @returns {number}\n */\nfunction sov (x) {\n if (x % 2 === 0) {\n x++\n }\n return Math.floor((len64(x) + 6) / 7)\n}\n\n/**\n * golang math/bits, how many bits does it take to represent this integer?\n *\n * @param {number} x\n * @returns {number}\n */\nfunction len64 (x) {\n let n = 0\n if (x >= maxInt32) {\n x = Math.floor(x / maxInt32)\n n = 32\n }\n if (x >= (1 << 16)) {\n x >>>= 16\n n += 16\n }\n if (x >= (1 << 8)) {\n x >>>= 8\n n += 8\n }\n return n + len8tab[x]\n}\n\n// golang math/bits\nconst len8tab = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8\n]\n", "import { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./interface.js').PBLink} PBLink\n * @typedef {import('./interface.js').PBNode} PBNode\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\nconst pbNodeProperties = ['Data', 'Links']\nconst pbLinkProperties = ['Hash', 'Name', 'Tsize']\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {PBLink} a\n * @param {PBLink} b\n * @returns {number}\n */\nfunction linkComparator (a, b) {\n if (a === b) {\n return 0\n }\n\n const abuf = a.Name ? textEncoder.encode(a.Name) : []\n const bbuf = b.Name ? textEncoder.encode(b.Name) : []\n\n let x = abuf.length\n let y = bbuf.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (abuf[i] !== bbuf[i]) {\n x = abuf[i]\n y = bbuf[i]\n break\n }\n }\n\n return x < y ? -1 : y < x ? 1 : 0\n}\n\n/**\n * @param {any} node\n * @param {string[]} properties\n * @returns {boolean}\n */\nfunction hasOnlyProperties (node, properties) {\n return !Object.keys(node).some((p) => !properties.includes(p))\n}\n\n/**\n * Converts a CID, or a PBLink-like object to a PBLink\n *\n * @param {any} link\n * @returns {PBLink}\n */\nfunction asLink (link) {\n if (typeof link.asCID === 'object') {\n const Hash = CID.asCID(link)\n if (!Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n return { Hash }\n }\n\n if (typeof link !== 'object' || Array.isArray(link)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n const pbl = {}\n\n if (link.Hash) {\n let cid = CID.asCID(link.Hash)\n try {\n if (!cid) {\n if (typeof link.Hash === 'string') {\n cid = CID.parse(link.Hash)\n } else if (link.Hash instanceof Uint8Array) {\n cid = CID.decode(link.Hash)\n }\n }\n } catch (/** @type {any} */ e) {\n throw new TypeError(`Invalid DAG-PB form: ${e.message}`)\n }\n\n if (cid) {\n pbl.Hash = cid\n }\n }\n\n if (!pbl.Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (typeof link.Name === 'string') {\n pbl.Name = link.Name\n }\n\n if (typeof link.Tsize === 'number') {\n pbl.Tsize = link.Tsize\n }\n\n return pbl\n}\n\n/**\n * @param {any} node\n * @returns {PBNode}\n */\nexport function prepare (node) {\n if (node instanceof Uint8Array || typeof node === 'string') {\n node = { Data: node }\n }\n\n if (typeof node !== 'object' || Array.isArray(node)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n /** @type {PBNode} */\n const pbn = {}\n\n if (node.Data !== undefined) {\n if (typeof node.Data === 'string') {\n pbn.Data = textEncoder.encode(node.Data)\n } else if (node.Data instanceof Uint8Array) {\n pbn.Data = node.Data\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n }\n\n if (node.Links !== undefined) {\n if (Array.isArray(node.Links)) {\n pbn.Links = node.Links.map(asLink)\n pbn.Links.sort(linkComparator)\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n } else {\n pbn.Links = []\n }\n\n return pbn\n}\n\n/**\n * @param {PBNode} node\n */\nexport function validate (node) {\n /*\n type PBLink struct {\n Hash optional Link\n Name optional String\n Tsize optional Int\n }\n\n type PBNode struct {\n Links [PBLink]\n Data optional Bytes\n }\n */\n // @ts-ignore private property for TS\n if (!node || typeof node !== 'object' || Array.isArray(node) || node instanceof Uint8Array || (node['/'] && node['/'] === node.bytes)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (!hasOnlyProperties(node, pbNodeProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties)')\n }\n\n if (node.Data !== undefined && !(node.Data instanceof Uint8Array)) {\n throw new TypeError('Invalid DAG-PB form (Data must be bytes)')\n }\n\n if (!Array.isArray(node.Links)) {\n throw new TypeError('Invalid DAG-PB form (Links must be a list)')\n }\n\n for (let i = 0; i < node.Links.length; i++) {\n const link = node.Links[i]\n // @ts-ignore private property for TS\n if (!link || typeof link !== 'object' || Array.isArray(link) || link instanceof Uint8Array || (link['/'] && link['/'] === link.bytes)) {\n throw new TypeError('Invalid DAG-PB form (bad link)')\n }\n\n if (!hasOnlyProperties(link, pbLinkProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties on link)')\n }\n\n if (link.Hash === undefined) {\n throw new TypeError('Invalid DAG-PB form (link must have a Hash)')\n }\n\n // @ts-ignore private property for TS\n if (link.Hash == null || !link.Hash['/'] || link.Hash['/'] !== link.Hash.bytes) {\n throw new TypeError('Invalid DAG-PB form (link Hash must be a CID)')\n }\n\n if (link.Name !== undefined && typeof link.Name !== 'string') {\n throw new TypeError('Invalid DAG-PB form (link Name must be a string)')\n }\n\n if (link.Tsize !== undefined) {\n if (typeof link.Tsize !== 'number' || link.Tsize % 1 !== 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize must be an integer)')\n }\n if (link.Tsize < 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize cannot be negative)')\n }\n }\n\n if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) {\n throw new TypeError('Invalid DAG-PB form (links must be sorted by Name bytes)')\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {PBLink[]} [links=[]]\n * @returns {PBNode}\n */\nexport function createNode (data, links = []) {\n return prepare({ Data: data, Links: links })\n}\n\n/**\n * @param {string} name\n * @param {number} size\n * @param {CID} cid\n * @returns {PBLink}\n */\nexport function createLink (name, size, cid) {\n return asLink({ Hash: cid, Name: name, Tsize: size })\n}\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nexport function toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n", "import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nexport function toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst _encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\nexport const encodeOptions = {\n ..._encodeOptions,\n typeEncoders: {\n ..._encodeOptions.typeEncoders\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst _decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\n_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const decodeOptions = {\n ..._decodeOptions,\n tags: _decodeOptions.tags.slice()\n}\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => cborg.encode(node, _encodeOptions)\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\nconst typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n]\n\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeofs.includes(typeOf)) {\n return typeOf\n }\n /* c8 ignore next 4 */\n // not going to bother testing this, it's not going to be valid anyway\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n if (isBuffer(value)) {\n return 'Buffer'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {boolean}\n */\nfunction isBuffer (value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n", "class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textDecoder = new TextDecoder()\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\nexport const toString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')\n : utf8Slice(bytes, start, end)\n }\n /* c8 ignore next 11 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? textDecoder.decode(bytes.subarray(start, end))\n : utf8Slice(bytes, start, end)\n }\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// The below code is mostly taken from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n\n/**\n * @param {Uint8Array} buf\n * @param {number} offset\n * @param {number} end\n * @returns {string}\n */\nfunction utf8Slice (buf, offset, end) {\n const res = []\n\n while (offset < end) {\n const firstByte = buf[offset]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (offset + 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[offset + 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[offset + 1]\n thirdByte = buf[offset + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n fourthByte = buf[offset + 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 /* c8 ignore next 5 */\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 offset += 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\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function 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 /* c8 ignore next 10 */\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", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeUint (buf, token) {\n return encodeUintValue(buf, 0, token.value)\n}\n\n/**\n * @param {Bl} buf\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n buf.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n buf.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n buf.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n buf.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeNegint (buf, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = slice(data, pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeBytes (buf, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length)\n buf.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { toString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeArray (buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeMap (buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeTag (buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nconst MINOR_FALSE = 20\nconst MINOR_TRUE = 21\nconst MINOR_NULL = 22\nconst MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (buf, token, options) {\n const float = token.value\n\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n buf.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n buf.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n buf.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\nimport { encodeUint } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst buf = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const length = isMap ? obj.size : keys.length\n if (!length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n refStack = Ref.createCheck(refStack, obj)\n /** @type {TokenOrNestedTokens[]} */\n const entries = []\n let i = 0\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ]\n }\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/*\n(UPDATE, Dec 2020)\nhttps://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some\nof the questions above with a new recommendation for sorting order being much\ncloser to what would be expected in other environments (i.e. no length-first\nweirdness).\nThis new sorting order is not yet implemented here but could be added as an\noption. \"Determinism\" (canonicity) is system dependent and it's difficult to\nchange existing systems that are built with existing expectations. So if a new\nordering is introduced here, the old needs to be kept as well with the user\nhaving the option.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @param {Bl} buf\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options)\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options) {\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n const buf = new Bl(size)\n encoder(buf, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return asU8A(buf.chunks[0])\n }\n }\n buf.reset()\n tokensToEncoded(buf, tokens, encoders, options)\n return buf.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, cborEncoders, options)\n}\n\nexport { objectToTokens, encode, encodeCustom, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (options.rejectDuplicateMapKeys === true) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (token.type === Type.break) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n const tokeniser = options.tokenizer || new Tokeniser(data, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "/* eslint max-depth: [\"error\", 7] */\nimport { Token, Type } from 'cborg'\nimport * as cborgJson from 'cborg/json'\nimport { CID } from 'multiformats'\nimport { base64 } from 'multiformats/bases/base64'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n/**\n * @template T\n * @typedef {import('multiformats').ToString} ToString\n */\n/**\n * @typedef {import('cborg/interface').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nfunction toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal. Encoding a CID means replacing it with a `{\"/\":\"}`\n * object as per the DAG-JSON spec.\n *\n * @param {any} obj\n * @returns {Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const cidString = cid.toString()\n\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.string, cidString, cidString.length), // value\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * bytesEncoder will receive all Uint8Arrays (and friends) during encode, it\n * needs to replace it with a `{\"/\":{\"bytes\":\"Base64ByteString\"}}` object as\n * per the DAG-JSON spec.\n *\n * @param {Uint8Array} bytes\n * @returns {Token[]|null}\n */\nfunction bytesEncoder (bytes) {\n const bytesString = base64.encode(bytes).slice(1) // no mbase prefix\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.map, Infinity, 1), // value\n new Token(Type.string, 'bytes', 5), // inner key\n new Token(Type.string, bytesString, bytesString.length), // inner value\n new Token(Type.break, undefined, 1),\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * taBytesEncoder wraps bytesEncoder() but for the more exotic typed arrays so\n * that we access the underlying ArrayBuffer data\n *\n * @param {Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|Uint8ClampedArray|BigInt64Array|BigUint64Array} obj\n * @returns {Token[]|null}\n */\nfunction taBytesEncoder (obj) {\n return bytesEncoder(new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n}\n\n/**\n * abBytesEncoder wraps bytesEncoder() but for plain ArrayBuffers\n *\n * @param {ArrayBuffer} ab\n * @returns {Token[]|null}\n */\nfunction abBytesEncoder (ab) {\n return bytesEncoder(new Uint8Array(ab))\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null // process with standard number encoder\n}\n\nconst encodeOptions = {\n typeEncoders: {\n Object: cidEncoder,\n Buffer: bytesEncoder,\n Uint8Array: bytesEncoder,\n Int8Array: taBytesEncoder,\n Uint16Array: taBytesEncoder,\n Int16Array: taBytesEncoder,\n Uint32Array: taBytesEncoder,\n Int32Array: taBytesEncoder,\n Float32Array: taBytesEncoder,\n Float64Array: taBytesEncoder,\n Uint8ClampedArray: taBytesEncoder,\n BigInt64Array: taBytesEncoder,\n BigUint64Array: taBytesEncoder,\n DataView: taBytesEncoder,\n ArrayBuffer: abBytesEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass DagJsonTokenizer extends cborgJson.Tokenizer {\n /**\n * @param {Uint8Array} data\n * @param {object} [options]\n */\n constructor (data, options) {\n super(data, options)\n /** @type {Token[]} */\n this.tokenBuffer = []\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this.tokenBuffer.length === 0 && super.done()\n }\n\n /**\n * @returns {Token}\n */\n _next () {\n if (this.tokenBuffer.length > 0) {\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/30406\n return this.tokenBuffer.pop()\n }\n return super.next()\n }\n\n /**\n * Implements rules outlined in https://github.com/ipld/specs/pull/356\n *\n * @returns {Token}\n */\n next () {\n const token = this._next()\n\n if (token.type === Type.map) {\n const keyToken = this._next()\n if (keyToken.type === Type.string && keyToken.value === '/') {\n const valueToken = this._next()\n if (valueToken.type === Type.string) { // *must* be a CID\n const breakToken = this._next() // swallow the end-of-map token\n if (breakToken.type !== Type.break) {\n throw new Error('Invalid encoded CID form')\n }\n this.tokenBuffer.push(valueToken) // CID.parse will pick this up after our tag token\n return new Token(Type.tag, 42, 0)\n }\n if (valueToken.type === Type.map) {\n const innerKeyToken = this._next()\n if (innerKeyToken.type === Type.string && innerKeyToken.value === 'bytes') {\n const innerValueToken = this._next()\n if (innerValueToken.type === Type.string) { // *must* be Bytes\n for (let i = 0; i < 2; i++) {\n const breakToken = this._next() // swallow two end-of-map tokens\n if (breakToken.type !== Type.break) {\n throw new Error('Invalid encoded Bytes form')\n }\n }\n const bytes = base64.decode(`m${innerValueToken.value}`)\n return new Token(Type.bytes, bytes, innerValueToken.value.length)\n }\n this.tokenBuffer.push(innerValueToken) // bail\n }\n this.tokenBuffer.push(innerKeyToken) // bail\n }\n this.tokenBuffer.push(valueToken) // bail\n }\n this.tokenBuffer.push(keyToken) // bail\n }\n return token\n }\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n allowUndefined: false,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\n\n// we're going to get TAG(42)STRING(\"bafy...\") from the tokenizer so we only need\n// to deal with the STRING(\"bafy...\") at this point\ndecodeOptions.tags[42] = CID.parse\n\nexport const name = 'dag-json'\nexport const code = 0x0129\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => cborgJson.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} data\n * @returns {T}\n */\nexport const decode = (data) => {\n const buf = toByteView(data)\n // the tokenizer is stateful so we need a single instance of it\n const options = Object.assign(decodeOptions, { tokenizer: new DagJsonTokenizer(buf, decodeOptions) })\n return cborgJson.decode(buf, options)\n}\n\n/**\n * @template T\n * @param {T} node\n * @returns {ToString}\n */\nexport const format = (node) => utf8Decoder.decode(encode(node))\nexport { format as stringify }\nconst utf8Decoder = new TextDecoder()\n\n/**\n * @template T\n * @param {ToString} data\n * @returns {T}\n */\nexport const parse = (data) => decode(utf8Encoder.encode(data))\nconst utf8Encoder = new TextEncoder()\n", "import { Type } from '../token.js'\nimport { encodeCustom } from '../encode.js'\nimport { encodeErrPrefix } from '../common.js'\nimport { asU8A, fromString } from '../byte-utils.js'\n\n/**\n * @typedef {import('../../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../token').Token} Token\n * @typedef {import('../bl').Bl} Bl\n */\n\nclass JSONEncoder extends Array {\n constructor () {\n super()\n /** @type {{type:Type,elements:number}[]} */\n this.inRecursive = []\n }\n\n /**\n * @param {Bl} buf\n */\n prefix (buf) {\n const recurs = this.inRecursive[this.inRecursive.length - 1]\n if (recurs) {\n if (recurs.type === Type.array) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n buf.push([44]) // ','\n }\n }\n if (recurs.type === Type.map) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n if (recurs.elements % 2 === 1) { // key\n buf.push([44]) // ','\n } else {\n buf.push([58]) // ':'\n }\n }\n }\n }\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.uint.major] (buf, token) {\n this.prefix(buf)\n const is = String(token.value)\n const isa = []\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n }\n buf.push(isa)\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.negint.major] (buf, token) {\n // @ts-ignore hack\n this[Type.uint.major](buf, token)\n }\n\n /**\n * @param {Bl} _buf\n * @param {Token} _token\n */\n [Type.bytes.major] (_buf, _token) {\n throw new Error(`${encodeErrPrefix} unsupported type: Uint8Array`)\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.string.major] (buf, token) {\n this.prefix(buf)\n // buf.push(34) // '\"'\n // encodeUtf8(token.value, byts)\n // buf.push(34) // '\"'\n const byts = fromString(JSON.stringify(token.value))\n buf.push(byts.length > 32 ? asU8A(byts) : byts)\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} _token\n */\n [Type.array.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.array, elements: 0 })\n buf.push([91]) // '['\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} _token\n */\n [Type.map.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.map, elements: 0 })\n buf.push([123]) // '{'\n }\n\n /**\n * @param {Bl} _buf\n * @param {Token} _token\n */\n [Type.tag.major] (_buf, _token) {}\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.float.major] (buf, token) {\n if (token.type.name === 'break') {\n const recurs = this.inRecursive.pop()\n if (recurs) {\n if (recurs.type === Type.array) {\n buf.push([93]) // ']'\n } else if (recurs.type === Type.map) {\n buf.push([125]) // '}'\n /* c8 ignore next 3 */\n } else {\n throw new Error('Unexpected recursive type; this should not happen!')\n }\n return\n }\n /* c8 ignore next 2 */\n throw new Error('Unexpected break; this should not happen!')\n }\n if (token.value === undefined) {\n throw new Error(`${encodeErrPrefix} unsupported type: undefined`)\n }\n\n this.prefix(buf)\n if (token.type.name === 'true') {\n buf.push([116, 114, 117, 101]) // 'true'\n return\n } else if (token.type.name === 'false') {\n buf.push([102, 97, 108, 115, 101]) // 'false'\n return\n } else if (token.type.name === 'null') {\n buf.push([110, 117, 108, 108]) // 'null'\n return\n }\n\n // number\n const is = String(token.value)\n const isa = []\n let dp = false\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n if (!dp && (isa[i] === 46 || isa[i] === 101 || isa[i] === 69)) { // '[.eE]'\n dp = true\n }\n }\n if (!dp) { // need a decimal point for floats\n isa.push(46) // '.'\n isa.push(48) // '0'\n }\n buf.push(isa)\n }\n}\n\n// The below code is mostly taken and modified from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n// function encodeUtf8 (string, byts) {\n// let codePoint\n// const length = string.length\n// let leadSurrogate = null\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// /* c8 ignore next 9 */\n// if (codePoint > 0xdbff) {\n// // unexpected trail\n// byts.push(0xef, 0xbf, 0xbd)\n// continue\n// } else if (i + 1 === length) {\n// // unpaired lead\n// byts.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// /* c8 ignore next 5 */\n// if (codePoint < 0xdc00) {\n// byts.push(0xef, 0xbf, 0xbd)\n// leadSurrogate = codePoint\n// continue\n// }\n\n// // valid surrogate pair\n// codePoint = (leadSurrogate - 0xd800 << 10 | codePoint - 0xdc00) + 0x10000\n// /* c8 ignore next 4 */\n// } else if (leadSurrogate) {\n// // valid bmp char, but last char was a lead\n// byts.push(0xef, 0xbf, 0xbd)\n// }\n\n// leadSurrogate = null\n\n// // encode utf8\n// if (codePoint < 0x80) {\n// // special JSON escapes\n// switch (codePoint) {\n// case 8: // '\\b'\n// byts.push(92, 98) // '\\\\b'\n// continue\n// case 9: // '\\t'\n// byts.push(92, 116) // '\\\\t'\n// continue\n// case 10: // '\\n'\n// byts.push(92, 110) // '\\\\n'\n// continue\n// case 12: // '\\f'\n// byts.push(92, 102) // '\\\\f'\n// continue\n// case 13: // '\\r'\n// byts.push(92, 114) // '\\\\r'\n// continue\n// case 34: // '\"'\n// byts.push(92, 34) // '\\\\\"'\n// continue\n// case 92: // '\\\\'\n// byts.push(92, 92) // '\\\\\\\\'\n// continue\n// }\n\n// byts.push(codePoint)\n// } else if (codePoint < 0x800) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0x6 | 0xc0,\n// codePoint & 0x3f | 0x80\n// )\n// } else if (codePoint < 0x10000) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0xc | 0xe0,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// /* c8 ignore next 9 */\n// } else if (codePoint < 0x110000) {\n// byts.push(\n// codePoint >> 0x12 | 0xf0,\n// codePoint >> 0xc & 0x3f | 0x80,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// } else {\n// /* c8 ignore next 2 */\n// throw new Error('Invalid code point')\n// }\n// }\n// }\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n if (Array.isArray(e1[0]) || Array.isArray(e2[0])) {\n throw new Error(`${encodeErrPrefix} complex map keys are not supported`)\n }\n const keyToken1 = e1[0]\n const keyToken2 = e2[0]\n if (keyToken1.type !== Type.string || keyToken2.type !== Type.string) {\n throw new Error(`${encodeErrPrefix} non-string map keys are not supported`)\n }\n if (keyToken1 < keyToken2) {\n return -1\n }\n if (keyToken1 > keyToken2) {\n return 1\n }\n /* c8 ignore next 1 */\n throw new Error(`${encodeErrPrefix} unexpected duplicate map keys, this is not supported`)\n}\n\nconst defaultEncodeOptions = { addBreakTokens: true, mapSorter }\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, new JSONEncoder(), options)\n}\n\nexport { encode }\n", "import { decode as _decode, decodeFirst as _decodeFirst } from '../decode.js'\nimport { Token, Type } from '../token.js'\nimport { decodeCodePointsArray } from '../byte-utils.js'\nimport { decodeErrPrefix } from '../common.js'\n\n/**\n * @typedef {import('../../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../../interface').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokenizer {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n /** @type {string[]} */\n this.modeStack = ['value']\n this.lastToken = ''\n }\n\n pos () {\n return this._pos\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this._pos >= this.data.length\n }\n\n /**\n * @returns {number}\n */\n ch () {\n return this.data[this._pos]\n }\n\n /**\n * @returns {string}\n */\n currentMode () {\n return this.modeStack[this.modeStack.length - 1]\n }\n\n skipWhitespace () {\n let c = this.ch()\n // @ts-ignore\n while (c === 32 /* ' ' */ || c === 9 /* '\\t' */ || c === 13 /* '\\r' */ || c === 10 /* '\\n' */) {\n c = this.data[++this._pos]\n }\n }\n\n /**\n * @param {number[]} str\n */\n expect (str) {\n if (this.data.length - this._pos < str.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of input at position ${this._pos}`)\n }\n for (let i = 0; i < str.length; i++) {\n if (this.data[this._pos++] !== str[i]) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...str)}'`)\n }\n }\n }\n\n parseNumber () {\n const startPos = this._pos\n let negative = false\n let float = false\n\n /**\n * @param {number[]} chars\n */\n const swallow = (chars) => {\n while (!this.done()) {\n const ch = this.ch()\n if (chars.includes(ch)) {\n this._pos++\n } else {\n break\n }\n }\n }\n\n // lead\n if (this.ch() === 45) { // '-'\n negative = true\n this._pos++\n }\n if (this.ch() === 48) { // '0'\n this._pos++\n if (this.ch() === 46) { // '.'\n this._pos++\n float = true\n } else {\n return new Token(Type.uint, 0, this._pos - startPos)\n }\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n if (negative && this._pos === startPos + 1) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n if (!this.done() && this.ch() === 46) { // '.'\n if (float) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n float = true\n this._pos++\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n if (!this.done() && (this.ch() === 101 || this.ch() === 69)) { // '[eE]'\n float = true\n this._pos++\n if (!this.done() && (this.ch() === 43 || this.ch() === 45)) { // '+', '-'\n this._pos++\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n // @ts-ignore\n const numStr = String.fromCharCode.apply(null, this.data.subarray(startPos, this._pos))\n const num = parseFloat(numStr)\n if (float) {\n return new Token(Type.float, num, this._pos - startPos)\n }\n if (this.options.allowBigInt !== true || Number.isSafeInteger(num)) {\n return new Token(num >= 0 ? Type.uint : Type.negint, num, this._pos - startPos)\n }\n return new Token(num >= 0 ? Type.uint : Type.negint, BigInt(numStr), this._pos - startPos)\n }\n\n /**\n * @returns {Token}\n */\n parseString () {\n /* c8 ignore next 4 */\n if (this.ch() !== 34) { // '\"'\n // this would be a programming error\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}; this shouldn't happen`)\n }\n this._pos++\n\n // check for simple fast-path, all printable ascii, no escapes\n // >0x10000 elements may fail fn.apply() (http://stackoverflow.com/a/22747272/680742)\n for (let i = this._pos, l = 0; i < this.data.length && l < 0x10000; i++, l++) {\n const ch = this.data[i]\n if (ch === 92 || ch < 32 || ch >= 128) { // '\\', ' ', control-chars or non-trivial\n break\n }\n if (ch === 34) { // '\"'\n // @ts-ignore\n const str = String.fromCharCode.apply(null, this.data.subarray(this._pos, i))\n this._pos = i + 1\n return new Token(Type.string, str, l)\n }\n }\n\n const startPos = this._pos\n const chars = []\n\n const readu4 = () => {\n if (this._pos + 4 >= this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of unicode escape sequence at position ${this._pos}`)\n }\n let u4 = 0\n for (let i = 0; i < 4; i++) {\n let ch = this.ch()\n if (ch >= 48 && ch <= 57) { // '0' && '9'\n ch -= 48\n } else if (ch >= 97 && ch <= 102) { // 'a' && 'f'\n ch = ch - 97 + 10\n } else if (ch >= 65 && ch <= 70) { // 'A' && 'F'\n ch = ch - 65 + 10\n } else {\n throw new Error(`${decodeErrPrefix} unexpected unicode escape character at position ${this._pos}`)\n }\n u4 = u4 * 16 + ch\n this._pos++\n }\n return u4\n }\n\n // mostly taken from feross/buffer and adjusted to fit\n const readUtf8Char = () => {\n const firstByte = this.ch()\n let codePoint = null\n /* c8 ignore next 1 */\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (this._pos + bytesPerSequence > this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected unicode sequence at position ${this._pos}`)\n }\n\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n /* c8 ignore next 6 */\n // this case is dealt with by the caller function\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = this.data[this._pos + 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 = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 2]\n fourthByte = this.data[this._pos + 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 /* c8 ignore next 5 */\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 chars.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n chars.push(codePoint)\n this._pos += bytesPerSequence\n }\n\n // TODO: could take the approach of a quick first scan for special chars like encoding/json/decode.go#unquoteBytes\n // and converting all of the ascii chars from the base array in bulk\n while (!this.done()) {\n const ch = this.ch()\n let ch1\n switch (ch) {\n case 92: // '\\'\n this._pos++\n if (this.done()) {\n throw new Error(`${decodeErrPrefix} unexpected string termination at position ${this._pos}`)\n }\n ch1 = this.ch()\n this._pos++\n switch (ch1) {\n case 34: // '\"'\n case 39: // '\\''\n case 92: // '\\'\n case 47: // '/'\n chars.push(ch1)\n break\n case 98: // 'b'\n chars.push(8)\n break\n case 116: // 't'\n chars.push(9)\n break\n case 110: // 'n'\n chars.push(10)\n break\n case 102: // 'f'\n chars.push(12)\n break\n case 114: // 'r'\n chars.push(13)\n break\n case 117: // 'u'\n chars.push(readu4())\n break\n default:\n throw new Error(`${decodeErrPrefix} unexpected string escape character at position ${this._pos}`)\n }\n break\n case 34: // '\"'\n this._pos++\n return new Token(Type.string, decodeCodePointsArray(chars), this._pos - startPos)\n default:\n if (ch < 32) { // ' '\n throw new Error(`${decodeErrPrefix} invalid control character at position ${this._pos}`)\n } else if (ch < 0x80) {\n chars.push(ch)\n this._pos++\n } else {\n readUtf8Char()\n }\n }\n }\n\n throw new Error(`${decodeErrPrefix} unexpected end of string at position ${this._pos}`)\n }\n\n /**\n * @returns {Token}\n */\n parseValue () {\n switch (this.ch()) {\n case 123: // '{'\n this.modeStack.push('obj-start')\n this._pos++\n return new Token(Type.map, Infinity, 1)\n case 91: // '['\n this.modeStack.push('array-start')\n this._pos++\n return new Token(Type.array, Infinity, 1)\n case 34: { // '\"'\n return this.parseString()\n }\n case 110: // 'n' / null\n this.expect([110, 117, 108, 108]) // 'null'\n return new Token(Type.null, null, 4)\n case 102: // 'f' / // false\n this.expect([102, 97, 108, 115, 101]) // 'false'\n return new Token(Type.false, false, 5)\n case 116: // 't' / // true\n this.expect([116, 114, 117, 101]) // 'true'\n return new Token(Type.true, true, 4)\n case 45: // '-'\n case 48: // '0'\n case 49: // '1'\n case 50: // '2'\n case 51: // '3'\n case 52: // '4'\n case 53: // '5'\n case 54: // '6'\n case 55: // '7'\n case 56: // '8'\n case 57: // '9'\n return this.parseNumber()\n default:\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}`)\n }\n }\n\n /**\n * @returns {Token}\n */\n next () {\n this.skipWhitespace()\n switch (this.currentMode()) {\n case 'value':\n this.modeStack.pop()\n return this.parseValue()\n case 'array-value': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n case 'array-start': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n // @ts-ignore\n case 'obj-key':\n if (this.ch() === 125) { // '}'\n this.modeStack.pop()\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.skipWhitespace()\n case 'obj-start': { // eslint-disable-line no-fallthrough\n this.modeStack.pop()\n if (this.ch() === 125) { // '}'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n const token = this.parseString()\n this.skipWhitespace()\n if (this.ch() !== 58) { // ':'\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('obj-value')\n return token\n }\n case 'obj-value': {\n this.modeStack.pop()\n this.modeStack.push('obj-key')\n this.skipWhitespace()\n return this.parseValue()\n }\n /* c8 ignore next 2 */\n default:\n throw new Error(`${decodeErrPrefix} unexpected parse state at position ${this._pos}; this shouldn't happen`)\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decode(data, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decodeFirst(data, options)\n}\n\nexport { decode, decodeFirst, Tokenizer }\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", null, "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\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.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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 function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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 function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\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 /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\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}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\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\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const 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", null, "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\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 \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const 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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\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", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import * as varint from './varint.js'\nimport * as Digest from './hashes/digest.js'\nimport { base58btc } from './bases/base58.js'\nimport { base32 } from './bases/base32.js'\nimport { coerce } from './bytes.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst 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}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n *\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\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\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\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 /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\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 * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n 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 =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\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 /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\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 * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\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\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst 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\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 } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst 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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst 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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", null, null, "const typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n];\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nexport function is(value) {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return 'undefined';\n }\n if (value === true || value === false) {\n return 'boolean';\n }\n const typeOf = typeof value;\n if (typeofs.includes(typeOf)) {\n return typeOf;\n }\n if (typeOf === 'function') {\n return 'Function';\n }\n if (Array.isArray(value)) {\n return 'Array';\n }\n if (isBuffer(value)) {\n return 'Buffer';\n }\n const objectType = getObjectType(value);\n if (objectType) {\n return objectType;\n }\n return 'Object';\n}\nfunction isBuffer(value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value);\n}\nfunction getObjectType(value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n}", "class Type {\n constructor(major, name, terminal) {\n this.major = major;\n this.majorEncoded = major << 5;\n this.name = name;\n this.terminal = terminal;\n }\n toString() {\n return `Type[${ this.major }].${ this.name }`;\n }\n compare(typ) {\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;\n }\n}\nType.uint = new Type(0, 'uint', true);\nType.negint = new Type(1, 'negint', true);\nType.bytes = new Type(2, 'bytes', true);\nType.string = new Type(3, 'string', true);\nType.array = new Type(4, 'array', false);\nType.map = new Type(5, 'map', false);\nType.tag = new Type(6, 'tag', false);\nType.float = new Type(7, 'float', true);\nType.false = new Type(7, 'false', true);\nType.true = new Type(7, 'true', true);\nType.null = new Type(7, 'null', true);\nType.undefined = new Type(7, 'undefined', true);\nType.break = new Type(7, 'break', true);\nclass Token {\n constructor(type, value, encodedLength) {\n this.type = type;\n this.value = value;\n this.encodedLength = encodedLength;\n this.encodedBytes = undefined;\n this.byteValue = undefined;\n }\n toString() {\n return `Token[${ this.type }].${ this.value }`;\n }\n}\nexport {\n Type,\n Token\n};", "export const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === 'function';\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\nfunction isBuffer(buf) {\n return useBuffer && globalThis.Buffer.isBuffer(buf);\n}\nexport function asU8A(buf) {\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf);\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;\n}\nexport const toString = useBuffer ? (bytes, start, end) => {\n return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8') : utf8Slice(bytes, start, end);\n} : (bytes, start, end) => {\n return end - start > 64 ? textDecoder.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end);\n};\nexport const fromString = useBuffer ? string => {\n return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string);\n} : string => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string);\n};\nexport const fromArray = arr => {\n return Uint8Array.from(arr);\n};\nexport const slice = useBuffer ? (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end));\n }\n return bytes.slice(start, end);\n} : (bytes, start, end) => {\n return bytes.slice(start, end);\n};\nexport const concat = useBuffer ? (chunks, length) => {\n chunks = chunks.map(c => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));\n return asU8A(globalThis.Buffer.concat(chunks, length));\n} : (chunks, length) => {\n const out = new Uint8Array(length);\n let off = 0;\n for (let b of chunks) {\n if (off + b.length > out.length) {\n b = b.subarray(0, out.length - off);\n }\n out.set(b, off);\n off += b.length;\n }\n return out;\n};\nexport const alloc = useBuffer ? size => {\n return globalThis.Buffer.allocUnsafe(size);\n} : size => {\n return new Uint8Array(size);\n};\nexport const toHex = useBuffer ? d => {\n if (typeof d === 'string') {\n return d;\n }\n return globalThis.Buffer.from(toBytes(d)).toString('hex');\n} : d => {\n if (typeof d === 'string') {\n return d;\n }\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${ p }${ c.toString(16).padStart(2, '0') }`, '');\n};\nexport const fromHex = useBuffer ? hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n return globalThis.Buffer.from(hex, 'hex');\n} : hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n if (!hex.length) {\n return new Uint8Array(0);\n }\n return new Uint8Array(hex.split('').map((c, i, d) => i % 2 === 0 ? `0x${ c }${ d[i + 1] }` : '').filter(Boolean).map(e => parseInt(e, 16)));\n};\nfunction toBytes(obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj;\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj);\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function compare(b1, b2) {\n if (isBuffer(b1) && isBuffer(b2)) {\n return b1.compare(b2);\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue;\n }\n return b1[i] < b2[i] ? -1 : 1;\n }\n return 0;\n}\nfunction utf8ToBytes(string, units = Infinity) {\n let codePoint;\n const length = string.length;\n let leadSurrogate = null;\n const bytes = [];\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n if (codePoint > 55295 && codePoint < 57344) {\n if (!leadSurrogate) {\n if (codePoint > 56319) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n } else if (i + 1 === length) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n }\n leadSurrogate = codePoint;\n continue;\n }\n if (codePoint < 56320) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n leadSurrogate = codePoint;\n continue;\n }\n codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;\n } else if (leadSurrogate) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n }\n leadSurrogate = null;\n if (codePoint < 128) {\n if ((units -= 1) < 0)\n break;\n bytes.push(codePoint);\n } else if (codePoint < 2048) {\n if ((units -= 2) < 0)\n break;\n bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);\n } else if (codePoint < 65536) {\n if ((units -= 3) < 0)\n break;\n bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else if (codePoint < 1114112) {\n if ((units -= 4) < 0)\n break;\n bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else {\n throw new Error('Invalid code point');\n }\n }\n return bytes;\n}\nfunction utf8Slice(buf, offset, end) {\n const res = [];\n while (offset < end) {\n const firstByte = buf[offset];\n let codePoint = null;\n let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint;\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 128) {\n codePoint = firstByte;\n }\n break;\n case 2:\n secondByte = buf[offset + 1];\n if ((secondByte & 192) === 128) {\n tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;\n if (tempCodePoint > 127) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 3:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;\n if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 4:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n fourthByte = buf[offset + 3];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;\n if (tempCodePoint > 65535 && tempCodePoint < 1114112) {\n codePoint = tempCodePoint;\n }\n }\n }\n }\n if (codePoint === null) {\n codePoint = 65533;\n bytesPerSequence = 1;\n } else if (codePoint > 65535) {\n codePoint -= 65536;\n res.push(codePoint >>> 10 & 1023 | 55296);\n codePoint = 56320 | codePoint & 1023;\n }\n res.push(codePoint);\n offset += bytesPerSequence;\n }\n return decodeCodePointsArray(res);\n}\nconst MAX_ARGUMENTS_LENGTH = 4096;\nexport function decodeCodePointsArray(codePoints) {\n const len = codePoints.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints);\n }\n let res = '';\n let i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));\n }\n return res;\n}", "import {\n alloc,\n concat,\n slice\n} from './byte-utils.js';\nconst defaultChunkSize = 256;\nexport class Bl {\n constructor(chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize;\n this.cursor = 0;\n this.maxCursor = -1;\n this.chunks = [];\n this._initReuseChunk = null;\n }\n reset() {\n this.cursor = 0;\n this.maxCursor = -1;\n if (this.chunks.length) {\n this.chunks = [];\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk);\n this.maxCursor = this._initReuseChunk.length - 1;\n }\n }\n push(bytes) {\n let topChunk = this.chunks[this.chunks.length - 1];\n const newMax = this.cursor + bytes.length;\n if (newMax <= this.maxCursor + 1) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n topChunk.set(bytes, chunkPos);\n } else {\n if (topChunk) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n if (chunkPos < topChunk.length) {\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);\n this.maxCursor = this.cursor - 1;\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n topChunk = alloc(this.chunkSize);\n this.chunks.push(topChunk);\n this.maxCursor += topChunk.length;\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk;\n }\n topChunk.set(bytes, 0);\n } else {\n this.chunks.push(bytes);\n this.maxCursor += bytes.length;\n }\n }\n this.cursor += bytes.length;\n }\n toBytes(reset = false) {\n let byts;\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0];\n if (reset && this.cursor > chunk.length / 2) {\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);\n this._initReuseChunk = null;\n this.chunks = [];\n } else {\n byts = slice(chunk, 0, this.cursor);\n }\n } else {\n byts = concat(this.chunks, this.cursor);\n }\n if (reset) {\n this.reset();\n }\n return byts;\n }\n}", "const decodeErrPrefix = 'CBOR decode error:';\nconst encodeErrPrefix = 'CBOR encode error:';\nconst uintMinorPrefixBytes = [];\nuintMinorPrefixBytes[23] = 1;\nuintMinorPrefixBytes[24] = 2;\nuintMinorPrefixBytes[25] = 3;\nuintMinorPrefixBytes[26] = 5;\nuintMinorPrefixBytes[27] = 9;\nfunction assertEnoughData(data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${ decodeErrPrefix } not enough data for type`);\n }\n}\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n decodeErrPrefix,\n assertEnoughData\n} from './common.js';\nexport const uintBoundaries = [\n 24,\n 256,\n 65536,\n 4294967296,\n BigInt('18446744073709551616')\n];\nexport function readUint8(data, offset, options) {\n assertEnoughData(data, offset, 1);\n const value = data[offset];\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint16(data, offset, options) {\n assertEnoughData(data, offset, 2);\n const value = data[offset] << 8 | data[offset + 1];\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint32(data, offset, options) {\n assertEnoughData(data, offset, 4);\n const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint64(data, offset, options) {\n assertEnoughData(data, offset, 8);\n const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value);\n }\n if (options.allowBigInt === true) {\n return value;\n }\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n}\nexport function decodeUint8(data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2);\n}\nexport function decodeUint16(data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3);\n}\nexport function decodeUint32(data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5);\n}\nexport function decodeUint64(data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9);\n}\nexport function encodeUint(buf, token) {\n return encodeUintValue(buf, 0, token.value);\n}\nexport function encodeUintValue(buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint);\n buf.push([major | nuint]);\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint);\n buf.push([\n major | 24,\n nuint\n ]);\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint);\n buf.push([\n major | 25,\n nuint >>> 8,\n nuint & 255\n ]);\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint);\n buf.push([\n major | 26,\n nuint >>> 24 & 255,\n nuint >>> 16 & 255,\n nuint >>> 8 & 255,\n nuint & 255\n ]);\n } else {\n const buint = BigInt(uint);\n if (buint < uintBoundaries[4]) {\n const set = [\n major | 27,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ];\n let lo = Number(buint & BigInt(4294967295));\n let hi = Number(buint >> BigInt(32) & BigInt(4294967295));\n set[8] = lo & 255;\n lo = lo >> 8;\n set[7] = lo & 255;\n lo = lo >> 8;\n set[6] = lo & 255;\n lo = lo >> 8;\n set[5] = lo & 255;\n set[4] = hi & 255;\n hi = hi >> 8;\n set[3] = hi & 255;\n hi = hi >> 8;\n set[2] = hi & 255;\n hi = hi >> 8;\n set[1] = hi & 255;\n buf.push(set);\n } else {\n throw new Error(`${ decodeErrPrefix } encountered BigInt larger than allowable range`);\n }\n }\n}\nencodeUint.encodedSize = function encodedSize(token) {\n return encodeUintValue.encodedSize(token.value);\n};\nencodeUintValue.encodedSize = function encodedSize(uint) {\n if (uint < uintBoundaries[0]) {\n return 1;\n }\n if (uint < uintBoundaries[1]) {\n return 2;\n }\n if (uint < uintBoundaries[2]) {\n return 3;\n }\n if (uint < uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeUint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nexport function decodeNegint8(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeNegint16(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeNegint32(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5);\n}\nconst neg1b = BigInt(-1);\nconst pos1b = BigInt(1);\nexport function decodeNegint64(data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options);\n if (typeof int !== 'bigint') {\n const value = -1 - int;\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9);\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9);\n}\nexport function encodeNegint(buf, token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned);\n}\nencodeNegint.encodedSize = function encodedSize(token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n if (unsigned < uint.uintBoundaries[0]) {\n return 1;\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2;\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3;\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeNegint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport {\n compare,\n fromString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length);\n const buf = slice(data, pos + prefix, pos + prefix + length);\n return new Token(Type.bytes, buf, prefix + length);\n}\nexport function decodeBytesCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeBytes8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeBytes16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeBytes32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeBytes64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer bytes lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nfunction tokenBytes(token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value;\n }\n return token.encodedBytes;\n}\nexport function encodeBytes(buf, token) {\n const bytes = tokenBytes(token);\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length);\n buf.push(bytes);\n}\nencodeBytes.encodedSize = function encodedSize(token) {\n const bytes = tokenBytes(token);\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length;\n};\nencodeBytes.compareTokens = function compareTokens(tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2));\n};\nexport function compareBytes(b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);\n}", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport { encodeBytes } from './2bytes.js';\nimport {\n toString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length, options) {\n const totLength = prefix + length;\n assertEnoughData(data, pos, totLength);\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength);\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength);\n }\n return tok;\n}\nexport function decodeStringCompact(data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options);\n}\nexport function decodeString8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options);\n}\nexport function decodeString16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options);\n}\nexport function decodeString32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options);\n}\nexport function decodeString64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer string lengths not supported`);\n }\n return toToken(data, pos, 9, l, options);\n}\nexport const encodeString = encodeBytes;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix);\n}\nexport function decodeArrayCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeArray8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeArray16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeArray32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeArray64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer array lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeArrayIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeArray(buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value);\n}\nencodeArray.compareTokens = uint.encodeUint.compareTokens;\nencodeArray.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix);\n}\nexport function decodeMapCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeMap8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeMap16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeMap32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeMap64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer map lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeMapIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeMap(buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value);\n}\nencodeMap.compareTokens = uint.encodeUint.compareTokens;\nencodeMap.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nexport function decodeTagCompact(_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1);\n}\nexport function decodeTag8(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeTag16(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeTag32(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5);\n}\nexport function decodeTag64(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9);\n}\nexport function encodeTag(buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value);\n}\nencodeTag.compareTokens = uint.encodeUint.compareTokens;\nencodeTag.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport { decodeErrPrefix } from './common.js';\nimport { encodeUint } from './0uint.js';\nconst MINOR_FALSE = 20;\nconst MINOR_TRUE = 21;\nconst MINOR_NULL = 22;\nconst MINOR_UNDEFINED = 23;\nexport function decodeUndefined(_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${ decodeErrPrefix } undefined values are not supported`);\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1);\n }\n return new Token(Type.undefined, undefined, 1);\n}\nexport function decodeBreak(_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return new Token(Type.break, undefined, 1);\n}\nfunction createToken(value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${ decodeErrPrefix } NaN values are not supported`);\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${ decodeErrPrefix } Infinity values are not supported`);\n }\n }\n return new Token(Type.float, value, bytes);\n}\nexport function decodeFloat16(data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options);\n}\nexport function decodeFloat32(data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options);\n}\nexport function decodeFloat64(data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options);\n}\nexport function encodeFloat(buf, token, options) {\n const float = token.value;\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE]);\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE]);\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL]);\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED]);\n } else {\n let decoded;\n let success = false;\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 249;\n buf.push(ui8a.slice(0, 3));\n success = true;\n } else {\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n ui8a[0] = 250;\n buf.push(ui8a.slice(0, 5));\n success = true;\n }\n }\n }\n if (!success) {\n encodeFloat64(float);\n decoded = readFloat64(ui8a, 1);\n ui8a[0] = 251;\n buf.push(ui8a.slice(0, 9));\n }\n }\n}\nencodeFloat.encodedSize = function encodedSize(token, options) {\n const float = token.value;\n if (float === false || float === true || float === null || float === undefined) {\n return 1;\n }\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n let decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n return 3;\n }\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n return 5;\n }\n }\n return 9;\n};\nconst buffer = new ArrayBuffer(9);\nconst dataView = new DataView(buffer, 1);\nconst ui8a = new Uint8Array(buffer, 0);\nfunction encodeFloat16(inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 31744, false);\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 64512, false);\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 32256, false);\n } else {\n dataView.setFloat32(0, inp);\n const valu32 = dataView.getUint32(0);\n const exponent = (valu32 & 2139095040) >> 23;\n const mantissa = valu32 & 8388607;\n if (exponent === 255) {\n dataView.setUint16(0, 31744, false);\n } else if (exponent === 0) {\n dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);\n } else {\n const logicalExponent = exponent - 127;\n if (logicalExponent < -24) {\n dataView.setUint16(0, 0);\n } else if (logicalExponent < -14) {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false);\n } else {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);\n }\n }\n }\n}\nfunction readFloat16(ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${ decodeErrPrefix } not enough data for float16`);\n }\n const half = (ui8a[pos] << 8) + ui8a[pos + 1];\n if (half === 31744) {\n return Infinity;\n }\n if (half === 64512) {\n return -Infinity;\n }\n if (half === 32256) {\n return NaN;\n }\n const exp = half >> 10 & 31;\n const mant = half & 1023;\n let val;\n if (exp === 0) {\n val = mant * 2 ** -24;\n } else if (exp !== 31) {\n val = (mant + 1024) * 2 ** (exp - 25);\n } else {\n val = mant === 0 ? Infinity : NaN;\n }\n return half & 32768 ? -val : val;\n}\nfunction encodeFloat32(inp) {\n dataView.setFloat32(0, inp, false);\n}\nfunction readFloat32(ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${ decodeErrPrefix } not enough data for float32`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false);\n}\nfunction encodeFloat64(inp) {\n dataView.setFloat64(0, inp, false);\n}\nfunction readFloat64(ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${ decodeErrPrefix } not enough data for float64`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false);\n}\nencodeFloat.compareTokens = encodeUint.compareTokens;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport * as negint from './1negint.js';\nimport * as bytes from './2bytes.js';\nimport * as string from './3string.js';\nimport * as array from './4array.js';\nimport * as map from './5map.js';\nimport * as tag from './6tag.js';\nimport * as float from './7float.js';\nimport { decodeErrPrefix } from './common.js';\nimport { fromArray } from './byte-utils.js';\nfunction invalidMinor(data, pos, minor) {\n throw new Error(`${ decodeErrPrefix } encountered invalid minor (${ minor }) for major ${ data[pos] >>> 5 }`);\n}\nfunction errorer(msg) {\n return () => {\n throw new Error(`${ decodeErrPrefix } ${ msg }`);\n };\n}\nexport const jump = [];\nfor (let i = 0; i <= 23; i++) {\n jump[i] = invalidMinor;\n}\njump[24] = uint.decodeUint8;\njump[25] = uint.decodeUint16;\njump[26] = uint.decodeUint32;\njump[27] = uint.decodeUint64;\njump[28] = invalidMinor;\njump[29] = invalidMinor;\njump[30] = invalidMinor;\njump[31] = invalidMinor;\nfor (let i = 32; i <= 55; i++) {\n jump[i] = invalidMinor;\n}\njump[56] = negint.decodeNegint8;\njump[57] = negint.decodeNegint16;\njump[58] = negint.decodeNegint32;\njump[59] = negint.decodeNegint64;\njump[60] = invalidMinor;\njump[61] = invalidMinor;\njump[62] = invalidMinor;\njump[63] = invalidMinor;\nfor (let i = 64; i <= 87; i++) {\n jump[i] = bytes.decodeBytesCompact;\n}\njump[88] = bytes.decodeBytes8;\njump[89] = bytes.decodeBytes16;\njump[90] = bytes.decodeBytes32;\njump[91] = bytes.decodeBytes64;\njump[92] = invalidMinor;\njump[93] = invalidMinor;\njump[94] = invalidMinor;\njump[95] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 96; i <= 119; i++) {\n jump[i] = string.decodeStringCompact;\n}\njump[120] = string.decodeString8;\njump[121] = string.decodeString16;\njump[122] = string.decodeString32;\njump[123] = string.decodeString64;\njump[124] = invalidMinor;\njump[125] = invalidMinor;\njump[126] = invalidMinor;\njump[127] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 128; i <= 151; i++) {\n jump[i] = array.decodeArrayCompact;\n}\njump[152] = array.decodeArray8;\njump[153] = array.decodeArray16;\njump[154] = array.decodeArray32;\njump[155] = array.decodeArray64;\njump[156] = invalidMinor;\njump[157] = invalidMinor;\njump[158] = invalidMinor;\njump[159] = array.decodeArrayIndefinite;\nfor (let i = 160; i <= 183; i++) {\n jump[i] = map.decodeMapCompact;\n}\njump[184] = map.decodeMap8;\njump[185] = map.decodeMap16;\njump[186] = map.decodeMap32;\njump[187] = map.decodeMap64;\njump[188] = invalidMinor;\njump[189] = invalidMinor;\njump[190] = invalidMinor;\njump[191] = map.decodeMapIndefinite;\nfor (let i = 192; i <= 215; i++) {\n jump[i] = tag.decodeTagCompact;\n}\njump[216] = tag.decodeTag8;\njump[217] = tag.decodeTag16;\njump[218] = tag.decodeTag32;\njump[219] = tag.decodeTag64;\njump[220] = invalidMinor;\njump[221] = invalidMinor;\njump[222] = invalidMinor;\njump[223] = invalidMinor;\nfor (let i = 224; i <= 243; i++) {\n jump[i] = errorer('simple values are not supported');\n}\njump[244] = invalidMinor;\njump[245] = invalidMinor;\njump[246] = invalidMinor;\njump[247] = float.decodeUndefined;\njump[248] = errorer('simple values are not supported');\njump[249] = float.decodeFloat16;\njump[250] = float.decodeFloat32;\njump[251] = float.decodeFloat64;\njump[252] = invalidMinor;\njump[253] = invalidMinor;\njump[254] = invalidMinor;\njump[255] = float.decodeBreak;\nexport const quick = [];\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1);\n}\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1);\n}\nquick[64] = new Token(Type.bytes, new Uint8Array(0), 1);\nquick[96] = new Token(Type.string, '', 1);\nquick[128] = new Token(Type.array, 0, 1);\nquick[160] = new Token(Type.map, 0, 1);\nquick[244] = new Token(Type.false, false, 1);\nquick[245] = new Token(Type.true, true, 1);\nquick[246] = new Token(Type.null, null, 1);\nexport function quickEncodeToken(token) {\n switch (token.type) {\n case Type.false:\n return fromArray([244]);\n case Type.true:\n return fromArray([245]);\n case Type.null:\n return fromArray([246]);\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([64]);\n }\n return;\n case Type.string:\n if (token.value === '') {\n return fromArray([96]);\n }\n return;\n case Type.array:\n if (token.value === 0) {\n return fromArray([128]);\n }\n return;\n case Type.map:\n if (token.value === 0) {\n return fromArray([160]);\n }\n return;\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)]);\n }\n return;\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)]);\n }\n }\n}", "import { is } from './is.js';\nimport {\n Token,\n Type\n} from './token.js';\nimport { Bl } from './bl.js';\nimport { encodeErrPrefix } from './common.js';\nimport { quickEncodeToken } from './jump.js';\nimport { asU8A } from './byte-utils.js';\nimport { encodeUint } from './0uint.js';\nimport { encodeNegint } from './1negint.js';\nimport { encodeBytes } from './2bytes.js';\nimport { encodeString } from './3string.js';\nimport { encodeArray } from './4array.js';\nimport { encodeMap } from './5map.js';\nimport { encodeTag } from './6tag.js';\nimport { encodeFloat } from './7float.js';\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n};\nexport function makeCborEncoders() {\n const encoders = [];\n encoders[Type.uint.major] = encodeUint;\n encoders[Type.negint.major] = encodeNegint;\n encoders[Type.bytes.major] = encodeBytes;\n encoders[Type.string.major] = encodeString;\n encoders[Type.array.major] = encodeArray;\n encoders[Type.map.major] = encodeMap;\n encoders[Type.tag.major] = encodeTag;\n encoders[Type.float.major] = encodeFloat;\n return encoders;\n}\nconst cborEncoders = makeCborEncoders();\nconst buf = new Bl();\nclass Ref {\n constructor(obj, parent) {\n this.obj = obj;\n this.parent = parent;\n }\n includes(obj) {\n let p = this;\n do {\n if (p.obj === obj) {\n return true;\n }\n } while (p = p.parent);\n return false;\n }\n static createCheck(stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${ encodeErrPrefix } object contains circular references`);\n }\n return new Ref(obj, stack);\n }\n}\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n};\nconst typeEncoders = {\n number(obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj);\n } else if (obj >= 0) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n bigint(obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n Uint8Array(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj);\n },\n string(obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj);\n },\n boolean(obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false;\n },\n null(_obj, _typ, _options, _refStack) {\n return simpleTokens.null;\n },\n undefined(_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined;\n },\n ArrayBuffer(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj));\n },\n DataView(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));\n },\n Array(obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyArray,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyArray;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack);\n }\n if (options.addBreakTokens) {\n return [\n new Token(Type.array, obj.length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.array, obj.length),\n entries\n ];\n },\n Object(obj, typ, options, refStack) {\n const isMap = typ !== 'Object';\n const keys = isMap ? obj.keys() : Object.keys(obj);\n const length = isMap ? obj.size : keys.length;\n if (!length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyMap,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyMap;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ];\n }\n sortMapEntries(entries, options);\n if (options.addBreakTokens) {\n return [\n new Token(Type.map, length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.map, length),\n entries\n ];\n }\n};\ntypeEncoders.Map = typeEncoders.Object;\ntypeEncoders.Buffer = typeEncoders.Uint8Array;\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${ typ }Array`] = typeEncoders.DataView;\n}\nfunction objectToTokens(obj, options = {}, refStack) {\n const typ = is(obj);\n const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack);\n if (tokens != null) {\n return tokens;\n }\n }\n const typeEncoder = typeEncoders[typ];\n if (!typeEncoder) {\n throw new Error(`${ encodeErrPrefix } unsupported type: ${ typ }`);\n }\n return typeEncoder(obj, typ, options, refStack);\n}\nfunction sortMapEntries(entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter);\n }\n}\nfunction mapSorter(e1, e2) {\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type);\n }\n const major = keyToken1.type.major;\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);\n if (tcmp === 0) {\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone');\n }\n return tcmp;\n}\nfunction tokensToEncoded(buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options);\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options);\n }\n}\nfunction encodeCustom(data, encoders, options) {\n const tokens = objectToTokens(data, options);\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens);\n if (quickBytes) {\n return quickBytes;\n }\n const encoder = encoders[tokens.type.major];\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options);\n const buf = new Bl(size);\n encoder(buf, tokens, options);\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${ tokens } was wrong`);\n }\n return asU8A(buf.chunks[0]);\n }\n }\n buf.reset();\n tokensToEncoded(buf, tokens, encoders, options);\n return buf.toBytes(true);\n}\nfunction encode(data, options) {\n options = Object.assign({}, defaultEncodeOptions, options);\n return encodeCustom(data, cborEncoders, options);\n}\nexport {\n objectToTokens,\n encode,\n encodeCustom,\n Ref\n};", "import { decodeErrPrefix } from './common.js';\nimport { Type } from './token.js';\nimport {\n jump,\n quick\n} from './jump.js';\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n};\nclass Tokeniser {\n constructor(data, options = {}) {\n this.pos = 0;\n this.data = data;\n this.options = options;\n }\n done() {\n return this.pos >= this.data.length;\n }\n next() {\n const byt = this.data[this.pos];\n let token = quick[byt];\n if (token === undefined) {\n const decoder = jump[byt];\n if (!decoder) {\n throw new Error(`${ decodeErrPrefix } no decoder for major type ${ byt >>> 5 } (byte 0x${ byt.toString(16).padStart(2, '0') })`);\n }\n const minor = byt & 31;\n token = decoder(this.data, this.pos, minor, this.options);\n }\n this.pos += token.encodedLength;\n return token;\n }\n}\nconst DONE = Symbol.for('DONE');\nconst BREAK = Symbol.for('BREAK');\nfunction tokenToArray(token, tokeniser, options) {\n const arr = [];\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options);\n if (value === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed array`);\n }\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found array but not enough entries (got ${ i }, expected ${ token.value })`);\n }\n arr[i] = value;\n }\n return arr;\n}\nfunction tokenToMap(token, tokeniser, options) {\n const useMaps = options.useMaps === true;\n const obj = useMaps ? undefined : {};\n const m = useMaps ? new Map() : undefined;\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options);\n if (key === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed map`);\n }\n if (key === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no key], expected ${ token.value })`);\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${ decodeErrPrefix } non-string keys not supported (got ${ typeof key })`);\n }\n if (options.rejectDuplicateMapKeys === true) {\n if (useMaps && m.has(key) || !useMaps && key in obj) {\n throw new Error(`${ decodeErrPrefix } found repeat map key \"${ key }\"`);\n }\n }\n const value = tokensToObject(tokeniser, options);\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no value], expected ${ token.value })`);\n }\n if (useMaps) {\n m.set(key, value);\n } else {\n obj[key] = value;\n }\n }\n return useMaps ? m : obj;\n}\nfunction tokensToObject(tokeniser, options) {\n if (tokeniser.done()) {\n return DONE;\n }\n const token = tokeniser.next();\n if (token.type === Type.break) {\n return BREAK;\n }\n if (token.type.terminal) {\n return token.value;\n }\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options);\n }\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options);\n }\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options);\n return options.tags[token.value](tagged);\n }\n throw new Error(`${ decodeErrPrefix } tag not supported (${ token.value })`);\n }\n throw new Error('unsupported');\n}\nfunction decode(data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${ decodeErrPrefix } data to decode must be a Uint8Array`);\n }\n options = Object.assign({}, defaultDecodeOptions, options);\n const tokeniser = options.tokenizer || new Tokeniser(data, options);\n const decoded = tokensToObject(tokeniser, options);\n if (decoded === DONE) {\n throw new Error(`${ decodeErrPrefix } did not find any content to decode`);\n }\n if (decoded === BREAK) {\n throw new Error(`${ decodeErrPrefix } got unexpected break`);\n }\n if (!tokeniser.done()) {\n throw new Error(`${ decodeErrPrefix } too many terminals, data makes no sense`);\n }\n return decoded;\n}\nexport {\n Tokeniser,\n tokensToObject,\n decode\n};", "import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\ndecodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => cborg.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(data, decodeOptions)\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n", "// @ts-check\n\nimport { from } from './base.js'\nimport { fromString, toString } from '../bytes.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "// @ts-check\n\nimport { coerce } from '../bytes.js'\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nexport const name = 'raw'\nexport const code = 0x55\n\n/**\n * @param {Uint8Array} node\n * @returns {ByteView}\n */\nexport const encode = (node) => coerce(node)\n\n/**\n * @param {ByteView} data\n * @returns {Uint8Array}\n */\nexport const decode = (data) => coerce(data)\n", "// @ts-check\n\nimport * as identityBase from './bases/identity.js'\nimport * as base2 from './bases/base2.js'\nimport * as base8 from './bases/base8.js'\nimport * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.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 base256emoji from './bases/base256emoji.js'\nimport * as sha2 from './hashes/sha2.js'\nimport * as identity from './hashes/identity.js'\n\nimport * as raw from './codecs/raw.js'\nimport * as json from './codecs/json.js'\n\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n", "\nexport class NotInitializedError extends Error {\n constructor (message = 'not initialized') {\n super(message)\n this.name = 'NotInitializedError'\n this.code = NotInitializedError.code\n }\n}\nNotInitializedError.code = 'ERR_NOT_INITIALIZED'\n\nexport class AlreadyInitializingError extends Error {\n constructor (message = 'cannot initialize an initializing node') {\n super(message)\n this.name = 'AlreadyInitializingError'\n this.code = AlreadyInitializedError.code\n }\n}\nAlreadyInitializingError.code = 'ERR_ALREADY_INITIALIZING'\n\nexport class AlreadyInitializedError extends Error {\n constructor (message = 'cannot re-initialize an initialized node') {\n super(message)\n this.name = 'AlreadyInitializedError'\n this.code = AlreadyInitializedError.code\n }\n}\nAlreadyInitializedError.code = 'ERR_ALREADY_INITIALIZED'\n\nexport class NotStartedError extends Error {\n constructor (message = 'not started') {\n super(message)\n this.name = 'NotStartedError'\n this.code = NotStartedError.code\n }\n}\nNotStartedError.code = 'ERR_NOT_STARTED'\n\nexport class AlreadyStartingError extends Error {\n constructor (message = 'cannot start, already startin') {\n super(message)\n this.name = 'AlreadyStartingError'\n this.code = AlreadyStartingError.code\n }\n}\nAlreadyStartingError.code = 'ERR_ALREADY_STARTING'\n\nexport class AlreadyStartedError extends Error {\n constructor (message = 'cannot start, already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n this.code = AlreadyStartedError.code\n }\n}\nAlreadyStartedError.code = 'ERR_ALREADY_STARTED'\n\nexport class NotEnabledError extends Error {\n constructor (message = 'not enabled') {\n super(message)\n this.name = 'NotEnabledError'\n this.code = NotEnabledError.code\n }\n}\nNotEnabledError.code = 'ERR_NOT_ENABLED'\n", "/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n }\n\n return buf\n}\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\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.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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 function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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 function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\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 /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\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}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\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\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const 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", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "// @ts-check\n\nimport { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n", "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\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 \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const 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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\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", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n 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})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n", "import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\nimport * as varint from './varint.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst 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}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\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\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\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 /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n /**\n * @returns {API.LinkJSON}\n */\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\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 * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n 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 =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\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 /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\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 * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\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\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst 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\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 } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst 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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst 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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "// @ts-check\n\nimport * 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'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n", "import { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n if (globalThis.Buffer?.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size))\n }\n\n return new Uint8Array(size)\n}\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: number = 0): Uint8Array {\n if (globalThis.Buffer?.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size))\n }\n\n return new Uint8Array(size)\n}\n", "import { bases } from 'multiformats/basics'\nimport { allocUnsafe } from '../alloc.js'\nimport type { MultibaseCodec } from 'multiformats'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\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})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\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\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import { asUint8Array } from './util/as-uint8array.js'\nimport bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'))\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (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}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "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'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\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: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\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})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\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\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\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\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\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}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\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}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", null, null, "import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\n\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\n\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]);\n\nexport interface IpNetRaw {\n network: Uint8Array;\n mask: Uint8Array;\n}\n\nexport function maskIp(ip: Uint8Array, mask: Uint8Array): Uint8Array {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (\n mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)\n ) {\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}\n\nexport function containsIp(\n net: IpNetRaw,\n ip: Uint8Array | number[] | string\n): boolean {\n if (typeof ip === \"string\") {\n ip = parseIP(ip)!;\n }\n if (ip == null) 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}\n\nexport function iPv4FromIPv6(ip: Uint8Array): Uint8Array {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\n\nexport function isIPv4mappedIPv6(ip: Uint8Array | number[]): boolean {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", null, "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\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: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\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\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\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\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\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: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\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'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\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\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\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\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\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}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\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}\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})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\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}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\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}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\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: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\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\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\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}\n\nfunction onion32bytes (str: string): Uint8Array {\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\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}\n\nfunction bytes2onion (buf: Uint8Array): string {\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", "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'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\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\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\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\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\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\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\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\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\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\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\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\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\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\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\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, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\nclass NoAvailableResolverError extends Error {\n constructor (message = 'No available resolver') {\n super(message)\n this.name = 'NoAvailableResolverError'\n }\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n readonly #string: string\n readonly #tuples: Tuple[]\n readonly #stringTuples: StringTuple[]\n readonly #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\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 } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\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\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\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\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\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\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\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\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\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\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\n decapsulateCode (code: number): Multiaddr {\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\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\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\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\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\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`)\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\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\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\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 /**\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] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\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\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\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 */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\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: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\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/**\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: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\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: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\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?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\nexport const QUICV1 = and(UDP, base('quic-v1'))\n\nconst _WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSockets = or(\n and(_WebSockets, base('p2p')),\n _WebSockets\n)\n\nconst _WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss')),\n and(TCP, base('tls'), base('ws')),\n and(DNS, base('tls'), base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(_WebSocketsSecure, base('p2p')),\n _WebSocketsSecure\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nconst _WebRTCDirect = and(UDP, base('webrtc-direct'), base('certhash'))\nexport const WebRTCDirect = or(\n and(_WebRTCDirect, base('p2p')),\n _WebRTCDirect\n)\n\nconst _WebTransport = and(QUICV1, base('webtransport'), base('certhash'), base('certhash'))\nexport const WebTransport = or(\n and(_WebTransport, base('p2p')),\n _WebTransport\n)\n\n/**\n * @deprecated\n */\nexport const P2PWebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\n/**\n * @deprecated\n */\nexport const P2PWebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n _WebSockets,\n _WebSocketsSecure,\n HTTP,\n HTTPS,\n P2PWebRTCStar,\n P2PWebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS,\n WebRTCDirect,\n WebTransport\n)\n\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(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n P2PWebRTCStar,\n P2PWebRTCDirect,\n WebRTCDirect,\n WebTransport,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = (): Mafmt => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\nexport const WebRTC = or(\n and(Circuit, base('webrtc'), base('p2p')),\n and(Circuit, base('webrtc')),\n and(Reliable, base('webrtc'), base('p2p')),\n and(Reliable, base('webrtc')),\n base('webrtc')\n)\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction): (a: string | Uint8Array | Multiaddr) => boolean {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\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\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches,\n partialMatch\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A suite of util methods that provides efficient validation.\n *\n * Detection of IPFS Paths and identifiers in URLs is a two-stage process:\n *\n * 1. `pathPattern`/`pathGatewayPattern`/`subdomainGatewayPattern` regex is applied to quickly identify potential candidates\n * 2. proper CID validation is applied to remove false-positives\n *\n * @example\n *\n * ```TypeScript\n * import * as isIPFS from 'is-ipfs'\n *\n * isIPFS.multihash('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.multihash('noop') // false\n *\n * isIPFS.cid('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true (CIDv0)\n * isIPFS.cid('bafybeiasb5vpmaounyilfuxbd3lryvosl4yefqrfahsb2esg46q6tu6y5q') // true (CIDv1 in Base32)\n * isIPFS.cid('zdj7WWeQ43G6JJvLWQWZpyHuAMq6uYWRjkBXFad11vE2LHhQ7') // true (CIDv1 in Base58btc)\n * isIPFS.cid('noop') // false\n *\n * isIPFS.base32cid('bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va') // true\n * isIPFS.base32cid('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n *\n * isIPFS.url('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.url('https://ipfs.io/ipfs/QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR?filename=guardian.jpg') // true\n * isIPFS.url('https://ipfs.io/ipns/github.com') // true\n * isIPFS.url('https://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.url('http://en.wikipedia-on-ipfs.org.ipfs.localhost:8080') // true\n * isIPFS.url('https://github.com/ipfs/js-ipfs/blob/master/README.md') // false\n * isIPFS.url('https://google.com') // false\n *\n * isIPFS.path('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.path('/ipfs/QmbcBPAwCDxRMB1Qe7CRQmxdrTSkxKwM9y6rZw2FjGtbsb/?weird-filename=test.jpg') // true\n * isIPFS.path('/ipns/github.com') // true\n * isIPFS.path('/ipfs/js-ipfs/blob/master/README.md') // false\n *\n * isIPFS.urlOrPath('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.urlOrPath('https://ipfs.io/ipns/github.com') // true\n * isIPFS.urlOrPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.urlOrPath('/ipns/github.com') // true\n * isIPFS.urlOrPath('https://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.urlOrPath('https://google.com') // false\n *\n * isIPFS.ipfsUrl('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.ipfsUrl('https://ipfs.io/ipfs/invalid-hash') // false\n *\n * isIPFS.ipnsUrl('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.ipnsUrl('https://ipfs.io/ipns/github.com') // true\n *\n * isIPFS.ipfsPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.ipfsPath('/ipfs/invalid-hash') // false\n *\n * isIPFS.ipnsPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.ipnsPath('/ipns/github.com') // true\n *\n * isIPFS.cidPath('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o/path/to/file') // true\n * isIPFS.cidPath('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o/') // true\n * isIPFS.cidPath('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.cidPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.cidPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o/file') // false\n *\n * isIPFS.subdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.subdomain('http://bafybeiabc2xofh6tdi6vutusorpumwcikw3hf3st4ecjugo6j52f6xwc6q.ipns.dweb.link') // true\n * isIPFS.subdomain('http://www.bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // false\n * isIPFS.subdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.dweb.link') // false\n *\n * isIPFS.ipfsSubdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.ipfsSubdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.dweb.link') // false\n *\n * isIPFS.ipnsSubdomain('http://bafybeiabc2xofh6tdi6vutusorpumwcikw3hf3st4ecjugo6j52f6xwc6q.ipns.dweb.link') // true\n * isIPFS.ipnsSubdomain('http://bafybeiabc2xofh6tdi6vutusorpumwcikw3hf3st4ecjugo6j52f6xwc6q.dweb.link') // false\n * isIPFS.ipnsSubdomain('http://QmcNioXSC1bfJj1dcFErhUfyjFzoX2HodkRccsFFVJJvg8.ipns.dweb.link') // false\n * isIPFS.ipnsSubdomain('http://en.wikipedia-on-ipfs.org.ipns.localhost:8080') // true (assuming DNSLink)\n * isIPFS.ipnsSubdomain('http://en-wikipedia--on--ipfs-org.ipns.localhost:8080') // true (assuming inlined DNSLink)\n * isIPFS.ipnsSubdomain('http://hostname-without-tld-.ipns.dweb.link') // false (not a CID, invalid DNS label)\n *\n * isIPFS.multiaddr('/ip4/127.0.0.1/udp/1234') // true\n * isIPFS.multiaddr('/ip4/127.0.0.1/udp/1234/http') // true\n * isIPFS.multiaddr('/ip6/::1/udp/1234') // true\n * isIPFS.multiaddr('ip6/::1/udp/1234') // false\n * isIPFS.multiaddr('/yoloinvalid/::1/udp/1234') // false\n *\n * isIPFS.peerMultiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSoooo4') // true\n * isIPFS.peerMultiaddr('/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSoooo4') // true (legacy notation)\n * isIPFS.peerMultiaddr('/ip4/127.0.0.1/tcp/1234/ws/p2p/QmUjNmr8TgJCn1Ao7DvMy4cjoZU15b9bwSCBLE3vwXiwgj') // true\n * isIPFS.peerMultiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSoooo4/p2p-circuit/p2p/QmUjNmr8TgJCn1Ao7DvMy4cjoZU15b9bwSCBLE3vwXiwgj') // true\n * isIPFS.peerMultiaddr('/dnsaddr/bootstrap.libp2p.io') // false (key missing, needs additional DNS lookup to tell if this is valid)\n * isIPFS.peerMultiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN') // true (key present, ip and port can be resolved later)\n * isIPFS.peerMultiaddr('/ip4/127.0.0.1/udp/1234') // false (key missing)\n * ```\n */\n\nimport * as mafmt from '@multiformats/mafmt'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { URL } from 'iso-url'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport const pathGatewayPattern = /^https?:\\/\\/[^/]+\\/(ip[fn]s)\\/([^/?#]+)/\nexport const pathPattern = /^\\/(ip[fn]s)\\/([^/?#]+)/\nconst defaultProtocolMatch = 1\nconst defaultHashMath = 2\n\n// CID, libp2p-key or DNSLink\nexport const subdomainGatewayPattern = /^https?:\\/\\/([^/]+)\\.(ip[fn]s)\\.[^/?]+/\nconst subdomainIdMatch = 1\nconst subdomainProtocolMatch = 2\n\n// Fully qualified domain name (FQDN) that has an explicit .tld suffix\nconst fqdnWithTld = /^(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\\.)+([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])$/\n\nfunction isMultihash (hash: Uint8Array | string): boolean {\n const formatted = convertToString(hash)\n\n if (formatted === false) {\n return false\n }\n\n try {\n Digest.decode(base58btc.decode(`z${formatted}`))\n } catch {\n return false\n }\n\n return true\n}\n\nfunction isMultiaddr (input: string | Uint8Array | Multiaddr): input is Multiaddr {\n try {\n return Boolean(multiaddr(input))\n } catch {\n return false\n }\n}\n\nfunction isBase32EncodedMultibase (hash: CID | string | Uint8Array): boolean {\n try {\n let cid: CID | null\n\n if (isString(hash)) {\n cid = CID.parse(hash)\n } else {\n cid = CID.asCID(hash)\n }\n\n if (cid == null) {\n return false\n }\n\n base32.decode(cid.toString())\n } catch {\n return false\n }\n\n return true\n}\n\nfunction isCID (hash: CID | Uint8Array | string): hash is CID {\n try {\n if (isString(hash)) {\n return Boolean(CID.parse(hash))\n }\n\n if (hash instanceof Uint8Array) {\n return Boolean(CID.decode(hash))\n }\n\n return Boolean(CID.asCID(hash)) // eslint-disable-line no-new\n } catch {\n return false\n }\n}\n\n/**\n * @param {string | Uint8Array | Multiaddr} input\n */\nfunction isPeerMultiaddr (input: string | Uint8Array | Multiaddr): boolean {\n return isMultiaddr(input) && mafmt.P2P.matches(input)\n}\n\n/**\n * @param {string | Uint8Array} input\n * @param {RegExp | string} pattern\n * @param {number} [protocolMatch=1]\n * @param {number} [hashMatch=2]\n */\nfunction isIpfs (input: string | Uint8Array, pattern: RegExp | string, protocolMatch: number = defaultProtocolMatch, hashMatch: number = defaultHashMath): boolean {\n const formatted = convertToString(input)\n if (formatted === false) {\n return false\n }\n\n const match = formatted.match(pattern)\n if (match == null) {\n return false\n }\n\n if (match[protocolMatch] !== 'ipfs') {\n return false\n }\n\n let hash = match[hashMatch]\n\n if (hash != null && pattern === subdomainGatewayPattern) {\n // when doing checks for subdomain context\n // ensure hash is case-insensitive\n // (browsers force-lowercase authority component anyway)\n hash = hash.toLowerCase()\n }\n\n return isCID(hash)\n}\n\n/**\n *\n * @param {string | Uint8Array} input\n * @param {string | RegExp} pattern\n * @param {number} [protocolMatch=1]\n * @param {number} [hashMatch=1]\n */\nfunction isIpns (input: string | Uint8Array, pattern: RegExp | string, protocolMatch: number = defaultProtocolMatch, hashMatch: number = defaultHashMath): boolean {\n const formatted = convertToString(input)\n if (formatted === false) {\n return false\n }\n const match = formatted.match(pattern)\n if (match == null) {\n return false\n }\n\n if (match[protocolMatch] !== 'ipns') {\n return false\n }\n\n let ipnsId = match[hashMatch]\n\n if (ipnsId != null && pattern === subdomainGatewayPattern) {\n // when doing checks for subdomain context\n // ensure ipnsId is case-insensitive\n // (browsers force-lowercase authority compotent anyway)\n ipnsId = ipnsId.toLowerCase()\n // Check if it is cidv1\n if (isCID(ipnsId)) return true\n // Check if it looks like FQDN\n try {\n if (!ipnsId.includes('.') && ipnsId.includes('-')) {\n // name without tld, assuming its inlined into a single DNS label\n // (https://github.com/ipfs/in-web-browsers/issues/169)\n // en-wikipedia--on--ipfs-org \u2192 en.wikipedia-on-ipfs.org\n ipnsId = ipnsId.replace(/--/g, '@').replace(/-/g, '.').replace(/@/g, '-')\n }\n // URL implementation in web browsers forces lowercase of the hostname\n const { hostname } = new URL(`http://${ipnsId}`) // eslint-disable-line no-new\n // Check if potential FQDN has an explicit TLD\n return fqdnWithTld.test(hostname)\n } catch (e) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {any} input\n */\nfunction isString (input: any): input is string {\n return typeof input === 'string'\n}\n\n/**\n * @param {Uint8Array | string} input\n */\nfunction convertToString (input: Uint8Array | string): string | false {\n if (input instanceof Uint8Array) {\n return uint8ArrayToString(input, 'base58btc')\n }\n\n if (isString(input)) {\n return input\n }\n\n return false\n}\n\n/**\n * Returns `true` if the provided `url` string includes a valid IPFS subdomain\n * (case-insensitive CIDv1) or `false` otherwise.\n */\nexport const ipfsSubdomain = (url: string | Uint8Array): boolean => isIpfs(url, subdomainGatewayPattern, subdomainProtocolMatch, subdomainIdMatch)\n\n/**\n * Returns `true` if the provided `url` string looks like a valid IPNS subdomain\n * (CIDv1 with `libp2p-key` multicodec or something that looks like a FQDN, for\n * example `en.wikipedia-on-ipfs.org.ipns.localhost:8080`) or `false` otherwise.\n *\n * **Note:** `ipnsSubdomain` method works in offline mode: it does not perform\n * actual IPNS record lookup over DHT or other content routing method. It may\n * return false-positives:\n *\n * - To ensure IPNS record exists, make a call to `/api/v0/name/resolve?arg=`\n * - To ensure DNSLink exists, make a call to `/api/v0/dns?arg=`\n */\nexport const ipnsSubdomain = (url: string | Uint8Array): boolean => isIpns(url, subdomainGatewayPattern, subdomainProtocolMatch, subdomainIdMatch)\n\n/**\n * Returns `true` if the provided `url` string includes a valid IPFS, looks like\n * an IPNS/DNSLink subdomain or `false` otherwise.\n */\nexport const subdomain = (url: string | Uint8Array): boolean => ipfsSubdomain(url) || ipnsSubdomain(url)\n\n/**\n * Returns `true` if the provided string is a valid IPFS url or `false`\n * otherwise.\n */\nexport const ipfsUrl = (url: string | Uint8Array): boolean => isIpfs(url, pathGatewayPattern) || ipfsSubdomain(url)\n\n/**\n * Returns `true` if the provided string is a valid IPNS url or `false`\n * otherwise.\n */\nexport const ipnsUrl = (url: string | Uint8Array): boolean => isIpns(url, pathGatewayPattern) || ipnsSubdomain(url)\n\n/**\n * Returns `true` if the provided string is a valid IPFS or IPNS url or `false`\n * otherwise.\n */\nexport const url = (url: string | Uint8Array): boolean => ipfsUrl(url) || ipnsUrl(url) || subdomain(url)\nexport const path = (path: string | Uint8Array): boolean => isIpfs(path, pathPattern) || isIpns(path, pathPattern)\n\n/**\n * Returns `true` if the provided string or `Uint8Array` is a valid `multihash`\n * or `false` otherwise.\n */\nexport { isMultihash as multihash }\n\n/**\n * Returns `true` if the provided `string`, [`Multiaddr`](https://github.com/multiformats/js-multiaddr)\n * or `Uint8Array` represents a valid multiaddr or `false` otherwise.\n */\nexport { isMultiaddr as multiaddr }\n\n/**\n * Returns `true` if the provided `string`, [`Multiaddr`](https://github.com/multiformats/js-multiaddr)\n * or `Uint8Array` represents a valid libp2p peer multiaddr (matching [`P2P`\n * format from `mafmt`](https://github.com/multiformats/js-mafmt#api)) or\n * `false` otherwise.\n */\nexport { isPeerMultiaddr as peerMultiaddr }\n\n/**\n * Returns `true` if the provided string, `Uint8Array` or [`CID`](https://github.com/multiformats/js-multiformats/#readme)\n * object represents a valid [CID](https://docs.ipfs.io/guides/concepts/cid/) or\n * `false` otherwise.\n */\nexport { isCID as cid }\n\n/**\n * Returns `true` if the provided string is a valid `CID` in Base32 encoding or\n * `false` otherwise.\n */\nexport const base32cid = (cid: CID | string | Uint8Array): boolean => (isCID(cid) && isBase32EncodedMultibase(cid))\n\n/**\n * Returns `true` if the provided string is a valid IPFS or IPNS path or `false`\n * otherwise.\n */\nexport const ipfsPath = (path: string | Uint8Array): boolean => isIpfs(path, pathPattern)\n\n/**\n * Returns `true` if the provided string is a valid IPNS path or `false`\n * otherwise.\n */\nexport const ipnsPath = (path: string | Uint8Array): boolean => isIpns(path, pathPattern)\n\n/**\n * Returns `true` if the provided string is a valid IPFS or IPNS url or path or\n * `false` otherwise.\n */\nexport const urlOrPath = (x: string | Uint8Array): boolean => url(x) || path(x)\n\n/**\n * Returns `true` if the provided string is a valid \"CID path\" (IPFS path\n * without `/ipfs/` prefix) or `false` otherwise.\n */\nexport const cidPath = (path: string | Uint8Array | CID): boolean => isString(path) && !isCID(path) && isIpfs(`/ipfs/${path}`, pathPattern)\n", "export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n", "// @ts-check\n\nimport { from } from './base.js'\nimport { fromString, toString } from '../bytes.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n 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})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n", "// @ts-check\n\nimport { coerce } from '../bytes.js'\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nexport const name = 'raw'\nexport const code = 0x55\n\n/**\n * @param {Uint8Array} node\n * @returns {ByteView}\n */\nexport const encode = (node) => coerce(node)\n\n/**\n * @param {ByteView} data\n * @returns {Uint8Array}\n */\nexport const decode = (data) => coerce(data)\n", "// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n", "// @ts-check\n\nimport * as identityBase from './bases/identity.js'\nimport * as base2 from './bases/base2.js'\nimport * as base8 from './bases/base8.js'\nimport * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.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 base256emoji from './bases/base256emoji.js'\nimport * as sha2 from './hashes/sha2.js'\nimport * as identity from './hashes/identity.js'\n\nimport * as raw from './codecs/raw.js'\nimport * as json from './codecs/json.js'\n\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n", "\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n }\n\n return buf\n}\n", "import { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n if (globalThis.Buffer?.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size))\n }\n\n return new Uint8Array(size)\n}\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: number = 0): Uint8Array {\n if (globalThis.Buffer?.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size))\n }\n\n return new Uint8Array(size)\n}\n", "import type { MultibaseCodec } from 'multiformats'\nimport { bases } from 'multiformats/basics'\nimport { allocUnsafe } from '../alloc.js'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\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})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\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\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import bases, { SupportedEncodings } from './util/bases.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\nexport type { SupportedEncodings }\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 */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'))\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "\nimport { nanoid } from 'nanoid'\nimport { SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\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 private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\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: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\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: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/f98719ea086343f7b71f32ea9d9d521d')\n * ```\n */\n static random (): Key {\n return new Key(nanoid().replace(/-/g, ''))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\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\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\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\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 /**\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: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\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 (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces (): string[] {\n return this.list()\n }\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 (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\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 (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\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 (): string {\n return namespaceType(this.baseNamespace())\n }\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 (): string {\n return namespaceValue(this.baseNamespace())\n }\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: string): Key {\n return new Key(this.toString() + ':' + s)\n }\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 (): Key {\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 /**\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 (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\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: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\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: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\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: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n *\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\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: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\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: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\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: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\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: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "/* eslint-disable no-unreachable */\n\nimport * as isIpfs from 'is-ipfs'\nimport { CID } from 'multiformats/cid'\nimport { Key } from 'interface-datastore/key'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport * as dagPB from '@ipld/dag-pb'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\nconst ERR_BAD_PATH = 'ERR_BAD_PATH'\n\nexport const OFFLINE_ERROR = 'This command must be run in online mode. Try running \\'ipfs daemon\\' first.'\nexport const MFS_ROOT_KEY = new Key('/local/filesroot')\nexport const MFS_MAX_CHUNK_SIZE = 262144\nexport const MFS_MAX_LINKS = 174\n\n/**\n * Returns a well-formed ipfs Path.\n * The returned path will always be prefixed with /ipfs/ or /ipns/.\n *\n * @param {string | CID} pathStr - An ipfs-path, or ipns-path or a cid\n * @returns {string} - ipfs-path or ipns-path\n * @throws on an invalid @param pathStr\n */\nexport const normalizePath = (pathStr) => {\n const cid = CID.asCID(pathStr)\n\n if (cid) {\n return `/ipfs/${pathStr}`\n }\n\n const str = pathStr.toString()\n\n try {\n return `/ipfs/${CID.parse(str)}`\n } catch {}\n\n if (isIpfs.path(str)) {\n return str\n } else {\n throw errCode(new Error(`invalid path: ${pathStr}`), ERR_BAD_PATH)\n }\n}\n\n// TODO: do we need both normalizePath and normalizeCidPath?\n// TODO: don't forget ipfs-core-utils/src/to-cid-and-path\n/**\n * @param {Uint8Array|CID|string} path\n */\nexport const normalizeCidPath = (path) => {\n if (path instanceof Uint8Array) {\n return CID.decode(path).toString()\n }\n\n path = path.toString()\n\n if (path.indexOf('/ipfs/') === 0) {\n path = path.substring('/ipfs/'.length)\n }\n\n if (path.charAt(path.length - 1) === '/') {\n path = path.substring(0, path.length - 1)\n }\n\n return path\n}\n\n/**\n * Resolve various styles of an ipfs-path to the hash of the target node.\n * Follows links in the path\n *\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {CID | string | Uint8Array} ipfsPath - A CID or IPFS path\n * @param {{ path?: string, signal?: AbortSignal }} [options] - Optional options passed directly to dag.resolve\n * @returns {Promise<{ cid: CID, remainderPath: string}>}\n */\nexport const resolvePath = async function (repo, codecs, ipfsPath, options = {}) {\n const {\n cid,\n path\n } = toCidAndPath(ipfsPath)\n\n if (path) {\n options.path = path\n }\n\n let lastCid = cid\n let lastRemainderPath = options.path || ''\n\n if (lastRemainderPath.startsWith('/')) {\n lastRemainderPath = lastRemainderPath.substring(1)\n }\n\n if (options.path) {\n try {\n for await (const { value, remainderPath } of resolve(cid, options.path, codecs, repo, {\n signal: options.signal\n })) {\n if (!CID.asCID(value)) {\n break\n }\n\n lastRemainderPath = remainderPath\n lastCid = value\n }\n } catch (/** @type {any} */ err) {\n // TODO: add error codes to IPLD\n if (err.message.startsWith('Object has no property')) {\n err.message = `no link named \"${lastRemainderPath.split('/')[0]}\" under ${lastCid}`\n err.code = 'ERR_NO_LINK'\n }\n throw err\n }\n }\n\n return {\n cid: lastCid,\n remainderPath: lastRemainderPath || ''\n }\n}\n\n/**\n * @typedef {import('ipfs-unixfs-exporter').UnixFSEntry} UnixFSEntry\n *\n * @param {UnixFSEntry} file\n */\nexport const mapFile = (file) => {\n if (file.type !== 'file' && file.type !== 'directory' && file.type !== 'raw') {\n // file.type === object | identity not supported yet\n throw new Error(`Unknown node type '${file.type}'`)\n }\n\n /** @type {import('ipfs-core-types/src/root').IPFSEntry} */\n const output = {\n cid: file.cid,\n path: file.path,\n name: file.name,\n size: file.size,\n type: 'file'\n }\n\n if (file.type === 'directory') {\n // @ts-expect-error - TS type can't be changed from File to Directory\n output.type = 'dir'\n }\n\n if (file.type === 'file') {\n output.size = file.unixfs.fileSize()\n }\n\n if (file.type === 'file' || file.type === 'directory') {\n output.mode = file.unixfs.mode\n\n if (file.unixfs.mtime !== undefined) {\n output.mtime = file.unixfs.mtime\n }\n }\n\n return output\n}\n\nexport const withTimeout = withTimeoutOption(\n /**\n * @template T\n * @param {Promise|T} promise\n * @param {AbortOptions} [_options]\n * @returns {Promise}\n */\n async (promise, _options) => await promise\n)\n\n/**\n * Retrieves IPLD Nodes along the `path` that is rooted at `cid`.\n *\n * @param {CID} cid - the CID where the resolving starts\n * @param {string} path - the path that should be resolved\n * @param {import('ipfs-core-utils/src/multicodecs').Multicodecs} codecs\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {AbortOptions} [options]\n */\nexport const resolve = async function * (cid, path, codecs, repo, options) {\n /**\n * @param {CID} cid\n */\n const load = async (cid) => {\n const codec = await codecs.getCodec(cid.code)\n const block = await repo.blocks.get(cid, options)\n\n return codec.decode(block)\n }\n\n const parts = path.split('/').filter(Boolean)\n let value = await load(cid)\n let lastCid = cid\n\n // End iteration if there isn't a CID to follow any more\n while (parts.length) {\n const key = parts.shift()\n\n if (!key) {\n throw errCode(new Error(`Could not resolve path \"${path}\"`), 'ERR_INVALID_PATH')\n }\n\n // special case for dag-pb, use the link name as the path segment\n if (cid.code === dagPB.code && Array.isArray(value.Links)) {\n const link = value.Links.find((/** @type {PBLink} */ l) => l.Name === key)\n\n if (link) {\n yield {\n value: link.Hash,\n remainderPath: parts.join('/')\n }\n\n value = await load(link.Hash)\n lastCid = link.Hash\n\n continue\n }\n }\n\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n value = value[key]\n\n yield {\n value,\n remainderPath: parts.join('/')\n }\n } else {\n throw errCode(new Error(`no link named \"${key}\" under ${lastCid}`), 'ERR_NO_LINK')\n }\n\n if (CID.asCID(value)) {\n lastCid = value\n value = await load(value)\n }\n }\n\n yield {\n value,\n remainderPath: ''\n }\n}\n", "/* eslint-disable no-unreachable */\n\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport parseDuration from 'parse-duration'\nimport { TimeoutError } from './errors.js'\n\n/**\n * @template {any[]} Args\n * @template {Promise | AsyncIterable} R - The return type of `fn`\n * @param {(...args:Args) => R} fn\n * @param {number} [optionsArgIndex]\n * @returns {(...args:Args) => R}\n */\nexport function withTimeoutOption (fn, optionsArgIndex) {\n // eslint-disable-next-line\n return /** @returns {R} */(/** @type {Args} */...args) => {\n const options = args[optionsArgIndex == null ? args.length - 1 : optionsArgIndex]\n if (!options || !options.timeout) return fn(...args)\n\n const timeout = typeof options.timeout === 'string'\n ? parseDuration(options.timeout)\n : options.timeout\n\n const controller = new TimeoutController(timeout)\n\n options.signal = anySignal([options.signal, controller.signal])\n\n const fnRes = fn(...args)\n // eslint-disable-next-line promise/param-names\n const timeoutPromise = new Promise((_resolve, reject) => {\n controller.signal.addEventListener('abort', () => {\n reject(new TimeoutError())\n })\n })\n\n const start = Date.now()\n\n const maybeThrowTimeoutError = () => {\n if (controller.signal.aborted) {\n throw new TimeoutError()\n }\n\n const timeTaken = Date.now() - start\n\n // if we have starved the event loop by adding microtasks, we could have\n // timed out already but the TimeoutController will never know because it's\n // setTimeout will not fire until we stop adding microtasks\n if (timeTaken > timeout) {\n controller.abort()\n throw new TimeoutError()\n }\n }\n\n // @ts-expect-error\n if (fnRes[Symbol.asyncIterator]) {\n // @ts-expect-error\n return (async function * () {\n // @ts-expect-error\n const it = fnRes[Symbol.asyncIterator]()\n\n try {\n while (true) {\n const { value, done } = await Promise.race([it.next(), timeoutPromise])\n\n if (done) {\n break\n }\n\n maybeThrowTimeoutError()\n\n yield value\n }\n } catch (/** @type {any} */ err) {\n maybeThrowTimeoutError()\n\n throw err\n } finally {\n controller.clear()\n\n if (it.return) {\n it.return()\n }\n }\n })()\n }\n\n // @ts-expect-error\n return (async () => {\n try {\n const res = await Promise.race([fnRes, timeoutPromise])\n\n maybeThrowTimeoutError()\n\n return res\n } catch (/** @type {any} */ err) {\n maybeThrowTimeoutError()\n\n throw err\n } finally {\n controller.clear()\n }\n })()\n }\n}\n", "let durationRE = /(-?(?:\\d+\\.?\\d*|\\d*\\.?\\d+)(?:e[-+]?\\d+)?)\\s*([\\p{L}]*)/uig\n\n\n/**\n * conversion ratios\n */\n\nparse.nanosecond =\nparse.ns = 1 / 1e6\n\nparse['\u00B5s'] =\nparse['\u03BCs'] =\nparse.us =\nparse.microsecond = 1 / 1e3\n\nparse.millisecond =\nparse.ms =\nparse[''] = 1\n\nparse.second =\nparse.sec =\nparse.s = parse.ms * 1000\n\nparse.minute =\nparse.min =\nparse.m = parse.s * 60\n\nparse.hour =\nparse.hr =\nparse.h = parse.m * 60\n\nparse.day =\nparse.d = parse.h * 24\n\nparse.week =\nparse.wk =\nparse.w = parse.d * 7\n\nparse.month =\nparse.b =\nparse.d * (365.25 / 12)\n\nparse.year =\nparse.yr =\nparse.y = parse.d * 365.25\n\n/**\n * convert `str` to ms\n *\n * @param {String} str\n * @param {String} format\n * @return {Number}\n */\n\nfunction parse(str='', format='ms'){\n var result = null\n // ignore commas/placeholders\n str = (str+'').replace(/(\\d)[,_](\\d)/g, '$1$2')\n var isNegative = str[0] === '-';\n str.replace(durationRE, function(_, n, units){\n units = unitRatio(units)\n if (units) result = (result || 0) + Math.abs(parseFloat(n, 10)) * units\n })\n\n return result && ((result / (unitRatio(format) || 1)) * (isNegative ? -1 : 1))\n}\n\nfunction unitRatio(str) {\n return parse[str] || parse[str.toLowerCase().replace(/s$/, '')]\n}\n\nexport default parse\n", "\nexport class TimeoutError extends Error {\n constructor (message = 'request timed out') {\n super(message)\n this.name = 'TimeoutError'\n this.code = TimeoutError.code\n }\n}\n\nTimeoutError.code = 'ERR_TIMEOUT'\n", "import { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\n\nconst IPFS_PREFIX = '/ipfs/'\n\n/**\n * @param {string|Uint8Array|CID} string\n * @returns {{cid:CID, path?:string}}\n */\nexport function toCidAndPath (string) {\n if (string instanceof Uint8Array) {\n try {\n string = CID.decode(string)\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_CID')\n }\n }\n\n let cid = CID.asCID(string)\n\n if (cid) {\n return {\n cid,\n path: undefined\n }\n }\n\n string = string.toString()\n\n if (string.startsWith(IPFS_PREFIX)) {\n string = string.substring(IPFS_PREFIX.length)\n }\n\n const parts = string.split('/')\n let path\n\n try {\n cid = CID.parse(parts.shift() || '')\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_CID')\n }\n\n if (parts.length) {\n path = `/${parts.join('/')}`\n }\n\n return {\n cid,\n path\n }\n}\n", "import { NotStartedError, AlreadyStartingError, AlreadyStartedError } from '../errors.js'\nimport { withTimeout } from '../utils.js'\n\n/**\n * @template T\n * @typedef {import('ipfs-core-types/src/utils').Await} Await\n */\n/**\n * @template {(options:any) => any} T\n * @typedef {Parameters[0]} Options\n */\n/**\n * @template {(options:any) => any} T\n * @typedef {ReturnType extends ? Promise ? U : ReturnType} State\n */\n/**\n * Represents service state which can be not started in which case\n * it is instance of `Error`. Pending in which case it's promise or\n * ready in which case it is the value itself.\n *\n * @template T\n * @typedef {{ status: 'stopped' }\n * | { status: 'starting', ready: Await }\n * | { status: 'started', value: T }\n * | { status: 'stopping', ready: Await }\n * } ServiceState\n */\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @template Options, T\n *\n * Allows you to create a handle to service that can be started or\n * stopped. It enables defining components that need to use service\n * functionality before service is started.\n *\n */\nexport class Service {\n /**\n * Takes `activation` function that takes `options` and (async) returns\n * an implementation.\n *\n * @template {(options:any) => Await} T\n *\n * @param {object} config\n * @param {T} config.start\n * @param {(state:State) => Await} [config.stop]\n * @returns {Service[0], State>}\n */\n static create ({ start, stop }) {\n return new Service(start, stop)\n }\n\n /**\n * Starts the service (by running actiavtion function). Will (async) throw\n * unless service is stopped.\n *\n * @template Options, T\n * @param {Service} service\n * @param {Options} options\n * @returns {Promise}\n */\n static async start (service, options) {\n const { state, activate } = service\n switch (state.status) {\n // If service is in 'stopped' state we activate and transition to\n // to 'pending' state. Once activation is complete transition state to\n // 'started' state.\n // Note: This is the only code that does state transitions from\n // - stopped\n // - started\n // Which ensures no race conditions can occur.\n case 'stopped': {\n try {\n const promise = activate(options)\n service.state = { status: 'starting', ready: promise }\n // Note: MUST await after state transition above otherwise race\n // condition may occur.\n const result = await promise\n service.state = { status: 'started', value: result }\n return result\n // If failed to start, transiton from 'starting' to 'stopped'\n // state.\n } catch (/** @type {any} */ error) {\n service.state = { status: 'stopped' }\n throw error\n }\n }\n case 'starting': {\n throw new AlreadyStartingError()\n }\n case 'started': {\n throw new AlreadyStartedError()\n }\n // If service is stopping we just wait for that to complete\n // and try again.\n case 'stopping': {\n await state.ready\n return await Service.start(service, options)\n }\n default: {\n return Service.panic(service)\n }\n }\n }\n\n /**\n * Stops the service by executing deactivation. If service is stopped\n * or is stopping this is noop. If service is starting up when called\n * it will await for start to complete and then retry stop afterwards.\n * This may (async) throw if `deactivate` does.\n *\n * @template T\n * @param {Service} service\n * @returns {Promise}\n */\n static async stop (service) {\n const { state, deactivate } = service\n switch (state.status) {\n // If stopped there's nothing to do.\n case 'stopped': {\n break\n }\n // If service is starting we await for it to complete\n // and try again. That way\n case 'starting': {\n // We do not want to error stop if start failed.\n try { await state.ready } catch (/** @type {any} */ _) {}\n return await Service.stop(service)\n }\n // if service is stopping we just await for it to complete.\n case 'stopping': {\n return await state.ready\n }\n case 'started': {\n if (deactivate) {\n await deactivate(state.value)\n }\n service.state = { status: 'stopped' }\n break\n }\n default: {\n Service.panic(state)\n }\n }\n }\n\n /**\n * @template T\n * @param {Service} service\n * @returns {T|null}\n */\n static try ({ state }) {\n switch (state.status) {\n case 'started':\n return state.value\n default:\n return null\n }\n }\n\n /**\n * Unwraps state and returns underlying value. If state is in idle state it\n * will throw an error. If state is pending it will wait and return the\n * result or throw on failure. If state is ready returns result.\n *\n * @template T\n * @param {Service} service\n * @param {AbortOptions} [options]\n * @returns {Promise}\n */\n static async use ({ state }, options) {\n switch (state.status) {\n case 'started':\n return state.value\n case 'starting':\n return await withTimeout(state.ready, options)\n default:\n throw new NotStartedError()\n }\n }\n\n // eslint-disable-next-line jsdoc/require-returns-check\n /**\n * @private\n * @param {Service} service\n * @returns {never}\n */\n static panic ({ state }) {\n const status = JSON.stringify({ status: state.status })\n throw RangeError(`Service in invalid state ${status}, should never happen if you see this please report a bug`)\n }\n\n /**\n * Takes `activation` function that takes `options` and (async) returns\n * an implementation.\n *\n * @private\n * @param {(options:Options) => Await} activate\n * @param {(state:T) => Await} [deactivate]\n */\n constructor (activate, deactivate) {\n this.activate = activate\n this.deactivate = deactivate\n\n /**\n * A state machine for this service.\n *\n * @private\n * @type {ServiceState}\n */\n this.state = { status: 'stopped' }\n }\n\n /**\n * Allows you to asynchronously obtain service implementation. If service\n * is starting it will await for completion. If service is stopped or stopping\n * this will (async) throw exception. This allows components that need to use\n * this service convenient API to do it.\n *\n * @param {AbortOptions} [options] - Abort options.\n * @returns {Promise}\n */\n async use (options) {\n return await Service.use(this, options)\n }\n\n /**\n * @returns {T|null}\n */\n try () {\n return Service.try(this)\n }\n}\n", "import { Service } from '../utils/service.js'\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../types').Print} config.print\n * @param {import('../types').Preload} config.preload\n * @param {import('../types').MfsPreload} config.mfsPreload\n * @param {import('./ipns').IPNSAPI} config.ipns\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('../types').Options} config.options\n */\nexport function createStart ({ network, preload, peerId, keychain, repo, ipns, mfsPreload, print, hashers, options }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"start\"]}\n */\n const start = async () => {\n const { libp2p } = await Service.start(network, {\n peerId,\n repo,\n print,\n hashers,\n options\n })\n\n await Promise.all([\n ipns.startOnline({ keychain, libp2p, peerId, repo }),\n preload.start(),\n mfsPreload.start()\n ])\n }\n\n return start\n}\n", "import { Service } from '../utils/service.js'\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('../types').Preload} config.preload\n * @param {import('./ipns').IPNSAPI} config.ipns\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../types').MfsPreload} config.mfsPreload\n */\nexport function createStop ({ network, preload, ipns, repo, mfsPreload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"stop\"]}\n */\n const stop = async () => {\n await Promise.all([\n preload.stop(),\n ipns.stop(),\n mfsPreload.stop()\n ])\n\n await Service.stop(network)\n\n // must be closed after stopping services as some of them\n // will write into the datastore\n await repo.close()\n }\n\n return stop\n}\n", "import hashlru from 'hashlru'\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n * @todo move this to ipfs-utils or it's own package\n *\n * @template T\n * @class TLRU\n */\nexport class TLRU {\n /**\n * Creates an instance of TLRU.\n *\n * @param {number} maxSize\n */\n constructor (maxSize) {\n this.lru = hashlru(maxSize)\n }\n\n /**\n * Get the value from the a key\n *\n * @param {string} key\n * @returns {T|undefined}\n * @memberof TLoRU\n */\n get (key) {\n const value = this.lru.get(key)\n if (value) {\n if ((value.expire) && (value.expire < Date.now())) {\n this.lru.remove(key)\n return undefined\n }\n return value.value\n }\n return undefined\n }\n\n /**\n * Set a key value pair\n *\n * @param {string} key\n * @param {T} value\n * @param {number} ttl - in miliseconds\n * @returns {void}\n */\n set (key, value, ttl) {\n this.lru.set(key, { value, expire: Date.now() + ttl })\n }\n\n /**\n * Find if the cache has the key\n *\n * @param {string} key\n * @returns {boolean}\n */\n has (key) {\n const value = this.get(key)\n if (value) {\n return true\n }\n return false\n }\n\n /**\n * Remove key\n *\n * @param {string} key\n */\n remove (key) {\n this.lru.remove(key)\n }\n\n /**\n * Clears the cache\n *\n * @memberof TLRU\n */\n clear () {\n this.lru.clear()\n }\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "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\tnew AbortError(errorMessage) :\n\tnew 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\tgetDOMException('This operation was aborted.') :\n\t\tsignal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, milliseconds, fallback, options) {\n\tlet timer;\n\n\tconst cancelablePromise = 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 (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\toptions = {\n\t\t\tcustomTimers: {setTimeout, clearTimeout},\n\t\t\t...options\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\ttimer = options.customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (typeof fallback === 'function') {\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\tconst message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\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} finally {\n\t\t\t\toptions.customTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tclearTimeout(timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\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", "var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nclass PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\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 && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\nexport default PriorityQueue;\n", "var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pending, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_throwOnAbort, _PQueue_onEvent;\nimport { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nclass PQueue extends EventEmitter {\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pending.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\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 Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\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 \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${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 \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\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 __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\"),\n ...options,\n };\n return new Promise((resolve, reject) => {\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pending, (_b = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n // TODO: Use options.signal?.throwIfAborted() when targeting Node.js 18\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n throw new AbortError('The task was aborted.');\n }\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), options.timeout);\n }\n if (options.signal) {\n operation = Promise.race([operation, __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_throwOnAbort).call(this, 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 __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n }\n }, options);\n this.emit('add');\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\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 (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, '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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pending = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pending, (_a = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - 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 __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_throwOnAbort = async function _PQueue_throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n // TODO: Reject with signal.throwIfAborted() when targeting Node.js 18\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n }, { once: true });\n });\n}, _PQueue_onEvent = async function _PQueue_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};\nexport default PQueue;\n", "/* eslint-env browser */\n\nimport { TLRU } from './utils/tlru.js'\nimport PQueue from 'p-queue'\nimport HTTP from 'ipfs-utils/src/http.js'\n\n// Avoid sending multiple queries for the same hostname by caching results\nconst cache = new TLRU(1000)\n// TODO: /api/v0/dns does not return TTL yet: https://github.com/ipfs/go-ipfs/issues/5884\n// However we know browsers themselves cache DNS records for at least 1 minute,\n// which acts a provisional default ttl: https://stackoverflow.com/a/36917902/11518426\nconst ttl = 60 * 1000\n\n// @ts-expect-error PQueue@6 is broken\nconst Queue = PQueue.default ? PQueue.default : PQueue\n\n// browsers limit concurrent connections per host,\n// we don't want preload calls to exhaust the limit (~6)\nconst httpQueue = new Queue({ concurrency: 4 })\n\n/**\n * @param {{ Path: string, Message: string }} response\n */\nconst ipfsPath = (response) => {\n if (response.Path) return response.Path\n throw new Error(response.Message)\n}\n\n/**\n * @param {string} fqdn\n * @param {object} opts\n */\nexport async function resolveDnslink (fqdn, opts) { // eslint-disable-line require-await\n /**\n * @param {string} fqdn\n * @param {object} opts\n * @param {boolean} [opts.nocache]\n */\n const resolve = async (fqdn, opts = {}) => {\n // @ts-expect-error - URLSearchParams does not take boolean options, only strings\n const searchParams = new URLSearchParams(opts)\n searchParams.set('arg', fqdn)\n\n // try cache first\n const query = searchParams.toString()\n if (!opts.nocache && cache.has(query)) {\n const response = cache.get(query)\n return ipfsPath(response)\n }\n\n // fallback to delegated DNS resolver\n const response = await httpQueue.add(async () => {\n // Delegated HTTP resolver sending DNSLink queries to ipfs.io\n // TODO: replace hardcoded host with configurable DNS over HTTPS: https://github.com/ipfs/js-ipfs/issues/2212\n const res = await HTTP.get('https://ipfs.io/api/v0/dns', { searchParams })\n const query = new URL(res.url).search.slice(1)\n const json = await res.json()\n cache.set(query, json, ttl)\n\n return json\n })\n return ipfsPath(response)\n }\n\n return resolve(fqdn, opts)\n}\n", "// dns-nodejs gets replaced by dns-browser when bundled\nimport { resolveDnslink } from 'ipfs-core-config/dns'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {string} domain\n * @returns {string}\n */\nfunction fqdnFixups (domain) {\n // Allow resolution of .eth names via .eth.link\n // More context at the go-ipfs counterpart: https://github.com/ipfs/go-ipfs/pull/6448\n if (domain.endsWith('.eth')) {\n domain = domain.replace(/.eth$/, '.eth.link')\n }\n return domain\n}\n\nexport function createDns () {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"dns\"]}\n */\n const resolveDNS = async (domain, options = { recursive: true }) => { // eslint-disable-line require-await\n if (typeof domain !== 'string') {\n throw new Error('Invalid arguments, domain must be a string')\n }\n\n domain = fqdnFixups(domain)\n\n return resolveDnslink(domain, options)\n }\n\n return withTimeoutOption(resolveDNS)\n}\n", "\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n */\nexport function createIsOnline ({ network }) {\n /**\n * @returns {boolean}\n */\n return () => {\n const net = network.try()\n return net != null && Boolean(net.libp2p.isStarted())\n }\n}\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString: () => string\n toCID: () => CID\n toBytes: () => Uint8Array\n equals: (other: PeerId | Uint8Array | string) => boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const symbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[symbol])\n}\n", "\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 */\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static readonly code = 'ABORT_ERR'\n\n static readonly type = 'aborted'\n}\n\nexport class CodeError = Record> extends Error {\n public readonly props: T\n\n constructor (\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(message)\n\n this.name = props?.name ?? 'CodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "import { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, symbol, type PeerId } from '@libp2p/interface-peer-id'\nimport { CodeError } from '@libp2p/interfaces/errors'\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 type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\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\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [symbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id: PeerId | Uint8Array | string): boolean {\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\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\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\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\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\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 } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n", "import * as isIpfs from 'is-ipfs'\nimport { CID } from 'multiformats/cid'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { resolve as res } from '../utils.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-utils/src/multibases').Multibases} config.bases\n * @param {import('ipfs-core-types/src/name').API} config.name\n */\nexport function createResolve ({ repo, codecs, bases, name }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"resolve\"]}\n */\n async function resolve (path, opts = {}) {\n if (!isIpfs.path(path)) {\n throw new Error('invalid argument ' + path)\n }\n\n if (isIpfs.ipnsPath(path)) {\n for await (const resolvedPath of name.resolve(path, opts)) {\n path = resolvedPath\n }\n }\n\n const [, schema, hash, ...rest] = path.split('/') // ['', 'ipfs', 'hash', ...path]\n const base = opts.cidBase ? await bases.getBase(opts.cidBase) : undefined\n const bytes = parseBytes(hash)\n\n // nothing to resolve return the input\n if (rest.length === 0) {\n const str = base ? base.encoder.encode(bytes) : hash\n\n return `/${schema}/${str}`\n }\n\n const cid = CID.decode(bytes)\n\n path = rest.join('/')\n\n const results = res(cid, path, codecs, repo, opts)\n let value = cid\n let remainderPath = path\n\n for await (const result of results) {\n if (CID.asCID(result.value)) {\n value = result.value\n remainderPath = result.remainderPath\n }\n }\n\n return `/ipfs/${value.toString(base && base.encoder)}${remainderPath ? '/' + remainderPath : ''}`\n }\n\n return withTimeoutOption(resolve)\n}\n\n/**\n * Parse the input as a PeerID or a CID or throw an error\n *\n * @param {string} str\n */\nfunction parseBytes (str) {\n try {\n return peerIdFromString(str).toBytes()\n } catch {\n return CID.parse(str).bytes\n }\n}\n", "/**\n * Returns the last item of an (async) iterable, unless empty, in which case\n * return `undefined`\n */\nexport default async function last (source: AsyncIterable | Iterable): Promise {\n let res\n\n for await (const entry of source) {\n res = entry\n }\n\n return res\n}\n", "import last from 'it-last'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @param {object} config\n * @param {ReturnType} config.addAll\n */\nexport function createAdd ({ addAll }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"add\"]}\n */\n return (path, options = {}) => {\n let iter\n\n const cid = CID.asCID(path)\n\n if (cid) {\n iter = addAll([{\n cid,\n ...options\n }], options)\n } else {\n iter = addAll([{\n path: path.toString(),\n ...options\n }], options)\n }\n\n // @ts-expect-error return value of last can be undefined\n return last(iter)\n }\n}\n", "import errCode from 'err-code'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {object} Pinnable\n * @property {string | InstanceType | CID} [path]\n * @property {CID} [cid]\n * @property {boolean} [recursive]\n * @property {any} [metadata]\n *\n * @typedef {CID|string|InstanceType|Pinnable} ToPin\n * @typedef {ToPin|Iterable|AsyncIterable} Source\n *\n * @typedef {object} Pin\n * @property {string|CID} path\n * @property {boolean} recursive\n * @property {any} [metadata]\n */\n\n/**\n * @param {any} thing\n * @returns {thing is IterableIterator & Iterator}\n */\nfunction isIterable (thing) {\n return Symbol.iterator in thing\n}\n\n/**\n * @param {any} thing\n * @returns {thing is AsyncIterableIterator & AsyncIterator}\n */\nfunction isAsyncIterable (thing) {\n return Symbol.asyncIterator in thing\n}\n\n/**\n * @param {any} thing\n * @returns {thing is CID}\n */\nfunction isCID (thing) {\n return CID.asCID(thing) != null\n}\n\n/**\n * Transform one of:\n *\n * ```ts\n * CID\n * String\n * { cid: CID recursive, metadata }\n * { path: String recursive, metadata }\n * Iterable\n * Iterable\n * Iterable<{ cid: CID recursive, metadata }>\n * Iterable<{ path: String recursive, metadata }>\n * AsyncIterable\n * AsyncIterable\n * AsyncIterable<{ cid: CID recursive, metadata }>\n * AsyncIterable<{ path: String recursive, metadata }>\n * ```\n * Into:\n *\n * ```ts\n * AsyncIterable<{ path: CID|String, recursive:boolean, metadata }>\n * ```\n *\n * @param {Source} input\n * @returns {AsyncIterable}\n */\n// eslint-disable-next-line complexity\nexport async function * normaliseInput (input) {\n // must give us something\n if (input === null || input === undefined) {\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n }\n\n // CID\n const cid = CID.asCID(input)\n\n if (cid) {\n yield toPin({ cid })\n return\n }\n\n if (input instanceof String || typeof input === 'string') {\n yield toPin({ path: input })\n return\n }\n\n // { cid: CID recursive, metadata }\n // @ts-expect-error - it still could be iterable or async iterable\n if (input.cid != null || input.path != null) {\n // @ts-expect-error\n return yield toPin(input)\n }\n\n // Iterable\n if (isIterable(input)) {\n const iterator = input[Symbol.iterator]()\n const first = iterator.next()\n\n if (first.done) {\n return iterator\n }\n\n // Iterable\n if (isCID(first.value)) {\n yield toPin({ cid: first.value })\n for (const cid of iterator) {\n yield toPin({ cid })\n }\n return\n }\n\n // Iterable\n if (first.value instanceof String || typeof first.value === 'string') {\n yield toPin({ path: first.value })\n for (const path of iterator) {\n yield toPin({ path })\n }\n return\n }\n\n // Iterable\n if (first.value.cid != null || first.value.path != null) {\n yield toPin(first.value)\n for (const obj of iterator) {\n yield toPin(obj)\n }\n return\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n }\n\n // AsyncIterable\n if (isAsyncIterable(input)) {\n const iterator = input[Symbol.asyncIterator]()\n const first = await iterator.next()\n if (first.done) return iterator\n\n // AsyncIterable\n if (isCID(first.value)) {\n yield toPin({ cid: first.value })\n for await (const cid of iterator) {\n yield toPin({ cid })\n }\n return\n }\n\n // AsyncIterable\n if (first.value instanceof String || typeof first.value === 'string') {\n yield toPin({ path: first.value })\n for await (const path of iterator) {\n yield toPin({ path })\n }\n return\n }\n\n // AsyncIterable<{ cid: CID|String recursive, metadata }>\n if (first.value.cid != null || first.value.path != null) {\n yield toPin(first.value)\n for await (const obj of iterator) {\n yield toPin(obj)\n }\n return\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {Pinnable} input\n */\nfunction toPin (input) {\n const path = input.cid || `${input.path}`\n\n if (!path) {\n throw errCode(new Error('Unexpected input: Please path either a CID or an IPFS path'), 'ERR_UNEXPECTED_INPUT')\n }\n\n /** @type {Pin} */\n const pin = {\n path,\n recursive: input.recursive !== false\n }\n\n if (input.metadata != null) {\n pin.metadata = input.metadata\n }\n\n return pin\n}\n", "\nexport const PinTypes = {\n /** @type {'direct'} */\n direct: 'direct',\n /** @type {'recursive'} */\n recursive: 'recursive',\n /** @type {'indirect'} */\n indirect: 'indirect',\n /** @type {'all'} */\n all: 'all'\n}\n", "/* eslint max-nested-callbacks: [\"error\", 8] */\n\nimport { resolvePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { PinTypes } from 'ipfs-repo/pin-types'\n\n/**\n * @typedef {import('ipfs-core-utils/src/pins/normalise-input').Source} Source\n * @typedef {import('ipfs-core-utils/src/pins/normalise-input').Pin} PinTarget\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('multiformats/cid').CID} CID\n */\n\n/**\n * @template T\n * @typedef {Iterable|AsyncIterable} AwaitIterable\n */\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createAddAll ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n /**\n * @returns {AsyncIterable}\n */\n const pinAdd = async function * () {\n for await (const { path, recursive, metadata } of normaliseInput(source)) {\n const { cid } = await resolvePath(repo, codecs, path)\n\n // verify that each hash can be pinned\n const { reason } = await repo.pins.isPinnedWithType(cid, [PinTypes.recursive, PinTypes.direct])\n\n if (reason === 'recursive' && !recursive) {\n // only disallow trying to override recursive pins\n throw new Error(`${cid} already pinned recursively`)\n }\n\n if (recursive) {\n await repo.pins.pinRecursively(cid, { metadata })\n } else {\n await repo.pins.pinDirectly(cid, { metadata })\n }\n\n yield cid\n }\n }\n\n // When adding a file, we take a lock that gets released after pinning\n // is complete, so don't take a second lock here\n const lock = Boolean(options.lock)\n\n if (!lock) {\n yield * pinAdd()\n return\n }\n\n const release = await repo.gcLock.readLock()\n\n try {\n yield * pinAdd()\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(addAll)\n}\n", "/* eslint max-nested-callbacks: [\"error\", 8] */\n\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { resolvePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport errCode from 'err-code'\nimport { PinTypes } from 'ipfs-repo/pin-types'\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n */\n\n/**\n * @param {string} type\n * @param {CID} cid\n * @param {Record} [metadata]\n */\nfunction toPin (type, cid, metadata) {\n /** @type {import('ipfs-core-types/src/pin').LsResult} */\n const output = {\n type,\n cid\n }\n\n if (metadata) {\n output.metadata = metadata\n }\n\n return output\n}\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createLs ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"ls\"]}\n */\n async function * ls (options = {}) {\n /** @type {import('ipfs-core-types/src/pin').PinQueryType} */\n let type = PinTypes.all\n\n if (options.type) {\n type = options.type\n\n if (!Object.keys(PinTypes).includes(type)) {\n throw errCode(new Error('Invalid pin type'), 'ERR_INVALID_PIN_TYPE')\n }\n }\n\n if (options.paths) {\n // check the pinned state of specific hashes\n let matched = false\n\n for await (const { path } of normaliseInput(options.paths)) {\n const { cid } = await resolvePath(repo, codecs, path)\n const { reason, pinned, parent, metadata } = await repo.pins.isPinnedWithType(cid, type)\n\n if (!pinned) {\n throw errCode(new Error(`path '${path}' is not pinned`), 'ERR_NOT_PINNED')\n }\n\n switch (reason) {\n case PinTypes.direct:\n case PinTypes.recursive:\n matched = true\n yield toPin(reason, cid, metadata)\n break\n default:\n matched = true\n yield toPin(`${PinTypes.indirect} through ${parent}`, cid, metadata)\n }\n }\n\n if (!matched) {\n throw new Error('No match found')\n }\n\n return\n }\n\n if (type === PinTypes.recursive || type === PinTypes.all) {\n for await (const { cid, metadata } of repo.pins.recursiveKeys()) {\n yield toPin(PinTypes.recursive, cid, metadata)\n }\n }\n\n if (type === PinTypes.indirect || type === PinTypes.all) {\n for await (const cid of repo.pins.indirectKeys(options)) {\n yield toPin(PinTypes.indirect, cid)\n }\n }\n\n if (type === PinTypes.direct || type === PinTypes.all) {\n for await (const { cid, metadata } of repo.pins.directKeys()) {\n yield toPin(PinTypes.direct, cid, metadata)\n }\n }\n }\n\n return withTimeoutOption(ls)\n}\n", "import last from 'it-last'\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-types/src/pin').API<{}>[\"rmAll\"]} config.rmAll\n */\nexport function createRm ({ rmAll }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"rm\"]}\n */\n async function rm (path, options = {}) {\n // @ts-expect-error return value of last can be undefined\n const cid = await last(rmAll([{ path, ...options }], options))\n\n if (!cid) {\n throw new Error('CID expected')\n }\n\n return cid\n }\n\n return rm\n}\n", "import { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { resolvePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { PinTypes } from 'ipfs-repo/pin-types'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createRmAll ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"rmAll\"]}\n */\n async function * rmAll (source, _options = {}) {\n const release = await repo.gcLock.readLock()\n\n try {\n // verify that each hash can be unpinned\n for await (const { path, recursive } of normaliseInput(source)) {\n const { cid } = await resolvePath(repo, codecs, path)\n const { pinned, reason } = await repo.pins.isPinnedWithType(cid, PinTypes.all)\n\n if (!pinned) {\n throw new Error(`${cid} is not pinned`)\n }\n\n switch (reason) {\n case (PinTypes.recursive):\n if (!recursive) {\n throw new Error(`${cid} is pinned recursively`)\n }\n\n await repo.pins.unpin(cid)\n\n yield cid\n\n break\n case (PinTypes.direct):\n await repo.pins.unpin(cid)\n\n yield cid\n\n break\n default:\n throw new Error(`${cid} is pinned indirectly under ${reason}`)\n }\n }\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(rmAll)\n}\n", "import { createAdd } from './add.js'\nimport { createAddAll } from './add-all.js'\nimport { createLs } from './ls.js'\nimport { createRm } from './rm.js'\nimport { createRmAll } from './rm-all.js'\n\nexport class PinAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ codecs, repo }) {\n const addAll = createAddAll({ codecs, repo })\n this.addAll = addAll\n this.add = createAdd({ addAll })\n const rmAll = createRmAll({ codecs, repo })\n this.rmAll = rmAll\n this.rm = createRm({ rmAll })\n this.ls = createLs({ codecs, repo })\n\n /** @type {import('ipfs-core-types/src/pin/remote').API} */\n this.remote = {\n add: (cid, options = {}) => Promise.reject(new Error('Not implemented')),\n ls: async function * (query, options = {}) { return Promise.reject(new Error('Not implemented')) }, // eslint-disable-line require-yield\n rm: (query, options = {}) => Promise.reject(new Error('Not implemented')),\n rmAll: (query, options = {}) => Promise.reject(new Error('Not implemented')),\n service: {\n add: (name, credentials) => Promise.reject(new Error('Not implemented')),\n rm: (name, options = {}) => Promise.reject(new Error('Not implemented')),\n // @ts-expect-error return types seem to be broken by a recent ts release. doesn't matter here because\n // we are just throwing. Will be removed by https://github.com/protocol/web3-dev-team/pull/58\n ls: (options = {}) => Promise.reject(new Error('Not implemented'))\n }\n }\n }\n}\n", "import errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { IpnsPublisher } from './publisher.js'\nimport { IpnsRepublisher } from './republisher.js'\nimport { IpnsResolver } from './resolver.js'\nimport { TLRU } from '../utils/tlru.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst log = logger('ipfs:ipns')\nconst defaultRecordTtl = 60 * 1000\n\n/**\n * @typedef {import('@libp2p/interface-keys').PrivateKey} PrivateKey\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nexport class IPNS {\n /**\n * @param {import('ipfs-core-types/src/utils').BufferStore} routing\n * @param {import('interface-datastore').Datastore} datastore\n * @param {PeerId} peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} keychain\n * @param {object} options\n * @param {string} options.pass\n * @param {number} [options.initialBroadcastInterval]\n * @param {number} [options.broadcastInterval]\n */\n constructor (routing, datastore, peerId, keychain, options) {\n this.publisher = new IpnsPublisher(routing, datastore)\n this.republisher = new IpnsRepublisher(this.publisher, datastore, peerId, keychain, options)\n this.resolver = new IpnsResolver(routing)\n this.cache = new TLRU(1000)\n this.routing = routing\n }\n\n /**\n * Publish\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n async publish (peerId, value, lifetime = IpnsPublisher.defaultRecordLifetime, options) {\n try {\n await this.publisher.publishWithEOL(peerId, value, lifetime, options)\n\n log(`IPNS value ${uint8ArrayToString(value, 'base32')} was published correctly`)\n\n // // Add to cache\n const id = peerId.toString()\n // @ts-expect-error - parseFloat expects string\n const ttEol = parseFloat(lifetime)\n const ttl = (ttEol < defaultRecordTtl) ? ttEol : defaultRecordTtl\n\n this.cache.set(id, value, ttl)\n\n log(`IPNS value ${uint8ArrayToString(value, 'base32')} was cached correctly`)\n\n return {\n name: id,\n value: value\n }\n } catch (/** @type {any} */ err) {\n log.error(err)\n\n throw err\n }\n }\n\n /**\n * Resolve\n *\n * @param {string} name\n * @param {object} options\n * @param {boolean} [options.nocache]\n * @param {boolean} [options.recursive]\n * @param {AbortSignal} [options.signal]\n */\n async resolve (name, options = {}) {\n if (typeof name !== 'string') {\n throw errcode(new Error('name received is not valid'), 'ERR_INVALID_NAME')\n }\n\n // If recursive, we should not try to get the cached value\n if (!options.nocache && !options.recursive) {\n // Try to get the record from cache\n const id = name.split('/')[2]\n const result = this.cache.get(id)\n\n if (result) {\n return result\n }\n }\n\n try {\n const result = await this.resolver.resolve(name, options)\n\n log(`IPNS record from ${name} was resolved correctly`)\n\n return result\n } catch (/** @type {any} */ err) {\n log.error(err)\n\n throw err\n }\n }\n\n /**\n * Initialize keyspace\n *\n * Sets the ipns record for the given key to point to an empty directory\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {AbortOptions} [options]\n */\n async initializeKeyspace (peerId, value, options) { // eslint-disable-line require-await\n return this.publish(peerId, value, IpnsPublisher.defaultRecordLifetime, options)\n }\n}\n", "import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function dbOpenFailedError (err) {\n err = err || new Error('Cannot open database')\n return errCode(err, 'ERR_DB_OPEN_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbDeleteFailedError (err) {\n err = err || new Error('Delete failed')\n return errCode(err, 'ERR_DB_DELETE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbWriteFailedError (err) {\n err = err || new Error('Write failed')\n return errCode(err, 'ERR_DB_WRITE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n", "import { isPeerId } from '@libp2p/interface-peer-id'\nimport { notFoundError } from 'datastore-core/errors'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport * as ipns from 'ipns'\n\nconst log = logger('ipfs:ipns:publisher')\n\n/**\n * @typedef {import('@libp2p/interface-keys').PrivateKey} PrivateKey\n * @typedef {import('@libp2p/interface-keys').PublicKey} PublicKey\n * @typedef {import('ipns').IPNSEntry} IPNSEntry\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nconst ERR_NOT_FOUND = notFoundError().code\nconst defaultRecordLifetime = 60 * 60 * 1000\n\n// IpnsPublisher is capable of publishing and resolving names to the IPFS routing system.\nexport class IpnsPublisher {\n /**\n * @param {import('ipfs-core-types/src/utils').BufferStore} routing\n * @param {import('interface-datastore').Datastore} datastore\n */\n constructor (routing, datastore) {\n this._routing = routing\n this._datastore = datastore\n }\n\n /**\n * Publish record with a eol\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n async publishWithEOL (peerId, value, lifetime, options) {\n const record = await this._updateOrCreateRecord(peerId, value, lifetime, options)\n\n return this._putRecordToRouting(record, peerId, options)\n }\n\n /**\n * Accepts a keypair, as well as a value (ipfsPath), and publishes it out to the routing system\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {AbortOptions} options\n */\n publish (peerId, value, options) {\n return this.publishWithEOL(peerId, value, defaultRecordLifetime, options)\n }\n\n /**\n * @param {Uint8Array} record\n * @param {PeerId} peerId\n * @param {AbortOptions} [options]\n */\n async _putRecordToRouting (record, peerId, options) {\n if (!(isPeerId(peerId))) {\n const errMsg = 'peerId received is not valid'\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')\n }\n\n if (peerId.publicKey == null) {\n throw errcode(new Error('Public key was missing'), 'ERR_MISSING_PUBLIC_KEY')\n }\n\n const routingKey = ipns.peerIdToRoutingKey(peerId)\n\n await this._publishEntry(routingKey, record, options)\n\n return record\n }\n\n /**\n * @param {Uint8Array} key\n * @param {Uint8Array} entry\n * @param {AbortOptions} [options]\n */\n async _publishEntry (key, entry, options) {\n // Add record to routing (buffer key)\n try {\n const res = await this._routing.put(key, entry, options)\n log(`ipns record for ${uint8ArrayToString(key, 'base32')} was stored in the routing`)\n\n return res\n } catch (/** @type {any} */err) {\n const errMsg = `ipns record for ${uint8ArrayToString(key, 'base32')} could not be stored in the routing - ${err.stack}`\n log.error(errMsg)\n log.error(err)\n\n throw errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING')\n }\n }\n\n /**\n * Returns the record this node has published corresponding to the given peer ID.\n *\n * If `checkRouting` is true and we have no existing record, this method will check the routing system for any existing records.\n *\n * @param {PeerId} peerId\n * @param {object} options\n * @param {boolean} [options.checkRouting]\n */\n async _getPublished (peerId, options = {}) {\n if (!(isPeerId(peerId))) {\n const errMsg = 'peerId received is not valid'\n\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')\n }\n\n const checkRouting = options.checkRouting !== false\n\n try {\n const dsVal = await this._datastore.get(ipns.getLocalKey(peerId.toBytes()))\n\n // unmarshal data\n return this._unmarshalData(dsVal)\n } catch (/** @type {any} */ err) {\n if (err.code !== ERR_NOT_FOUND) {\n const errMsg = `unexpected error getting the ipns record ${peerId.toString()} from datastore`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_UNEXPECTED_DATASTORE_RESPONSE')\n }\n\n if (!checkRouting) {\n throw errcode(err, 'ERR_NOT_FOUND_AND_CHECK_ROUTING_NOT_ENABLED')\n }\n\n // Try to get from routing\n try {\n const routingKey = ipns.peerIdToRoutingKey(peerId)\n const res = await this._routing.get(routingKey)\n\n // unmarshal data\n return this._unmarshalData(res)\n } catch (/** @type {any} */ err) {\n log.error(err)\n\n throw err\n }\n }\n }\n\n /**\n * @param {Uint8Array} data\n */\n _unmarshalData (data) {\n try {\n return ipns.unmarshal(data)\n } catch (/** @type {any} */ err) {\n throw errcode(err, 'ERR_INVALID_RECORD_DATA')\n }\n }\n\n /**\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n async _updateOrCreateRecord (peerId, value, lifetime, options) {\n if (!(isPeerId(peerId))) {\n const errMsg = 'peerId received is not valid'\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')\n }\n\n const getPublishedOptions = {\n checkRouting: true\n }\n\n /** @type {IPNSEntry | undefined} */\n let record\n\n try {\n record = await this._getPublished(peerId, getPublishedOptions)\n } catch (/** @type {any} */ err) {\n if (err.code !== ERR_NOT_FOUND) {\n const errMsg = `unexpected error when determining the last published IPNS record for ${peerId.toString()} ${err.stack}`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_DETERMINING_PUBLISHED_RECORD')\n }\n }\n\n // Determinate the record sequence number\n let seqNumber = 0n\n\n if (record && record.sequence !== undefined) {\n // Increment if the published value is different\n seqNumber = uint8ArrayEquals(record.value, value) ? record.sequence : record.sequence + BigInt(1)\n }\n\n /** @type {IPNSEntry} */\n let entryData\n\n try {\n // Create record\n entryData = await ipns.create(peerId, value, seqNumber, lifetime)\n } catch (/** @type {any} */ err) {\n const errMsg = `ipns record for ${value} could not be created`\n\n log.error(err)\n throw errcode(new Error(errMsg), 'ERR_CREATING_IPNS_RECORD')\n }\n\n // TODO IMPROVEMENT - set ttl (still experimental feature for go)\n\n try {\n // Marshal record\n const data = ipns.marshal(entryData)\n\n // Store the new record\n await this._datastore.put(ipns.getLocalKey(peerId.toBytes()), data, options)\n\n log(`ipns record for ${uint8ArrayToString(value, 'base32')} was stored in the datastore`)\n\n return data\n } catch (/** @type {any} */ err) {\n const errMsg = `ipns record for ${value} could not be stored in the datastore`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_STORING_IN_DATASTORE')\n }\n }\n}\n\nIpnsPublisher.defaultRecordLifetime = defaultRecordLifetime\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import NanoDate from 'timestamp-nano'\nimport { Key } from 'interface-datastore/key'\nimport { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport errCode from 'err-code'\nimport { base32upper } from 'multiformats/bases/base32'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { logger } from '@libp2p/logger'\nimport { createCborData, ipnsEntryDataForV1Sig, ipnsEntryDataForV2Sig } from './utils.js'\nimport * as ERRORS from './errors.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { IpnsEntry } from './pb/ipns.js'\nimport type { PrivateKey } from '@libp2p/interface-keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('ipns')\nconst ID_MULTIHASH_CODE = identity.code\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSEntry {\n value: Uint8Array\n signature: Uint8Array // signature of the record\n validityType: IpnsEntry.ValidityType // Type of validation being used\n validity: Uint8Array // expiration datetime for the record in RFC3339 format\n sequence: bigint // number representing the version of the record\n ttl?: bigint // ttl in nanoseconds\n pubKey?: Uint8Array // the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n signatureV2?: Uint8Array // the v2 signature of the record\n data?: Uint8Array // extensible data\n}\n\nexport interface IPNSEntryData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\n/**\n * Creates a new ipns entry and signs it with the given private key.\n * The ipns entry validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * @param {PeerId} peerId - peer id containing private key for signing the record.\n * @param {Uint8Array} value - value to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n */\nexport const create = async (peerId: PeerId, value: Uint8Array, seq: number | bigint, lifetime: number): Promise => {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const [ms, ns] = lifetime.toString().split('.')\n const lifetimeNs = (BigInt(ms) * BigInt(100000)) + BigInt(ns ?? '0')\n\n return await _create(peerId, value, seq, validityType, expirationDate, lifetimeNs)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * @param {PeerId} peerId - PeerId containing private key for signing the record.\n * @param {Uint8Array} value - value to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n */\nexport const createWithExpiration = async (peerId: PeerId, value: Uint8Array, seq: number | bigint, expiration: string): Promise => {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n\n const ttlMs = expirationDate.toDate().getTime() - Date.now()\n const ttlNs = (BigInt(ttlMs) * BigInt(100000)) + BigInt(expirationDate.getNano())\n\n return await _create(peerId, value, seq, validityType, expirationDate, ttlNs)\n}\n\nconst _create = async (peerId: PeerId, value: Uint8Array, seq: number | bigint, validityType: IpnsEntry.ValidityType, expirationDate: NanoDate, ttl: bigint): Promise => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(expirationDate.toString())\n\n if (peerId.privateKey == null) {\n throw errCode(new Error('Missing private key'), ERRORS.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n const signatureV1 = await signLegacyV1(privateKey, value, validityType, isoValidity)\n const data = createCborData(value, isoValidity, validityType, seq, ttl)\n const sigData = ipnsEntryDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData)\n\n const entry: IPNSEntry = {\n value,\n signature: signatureV1,\n validityType,\n validity: isoValidity,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n // if we cannot derive the public key from the PeerId (e.g. RSA PeerIDs),\n // we have to embed it in the IPNS record\n if (peerId.publicKey != null) {\n const digest = Digest.decode(peerId.toBytes())\n\n if (digest.code !== ID_MULTIHASH_CODE || !uint8ArrayEquals(peerId.publicKey, digest.digest)) {\n entry.pubKey = peerId.publicKey\n }\n }\n\n log('ipns entry for %b created', value)\n return entry\n}\n\n/**\n * rawStdEncoding with RFC4648\n */\nconst rawStdEncoding = (key: Uint8Array): string => base32upper.encode(key).slice(1)\n\n/**\n * Get key for storing the record locally.\n * Format: /ipns/${base32()}\n *\n * @param {Uint8Array} key - peer identifier object.\n */\nexport const getLocalKey = (key: Uint8Array): Key => new Key(`/ipns/${rawStdEncoding(key)}`)\n\nexport { unmarshal } from './utils.js'\nexport { marshal } from './utils.js'\nexport { peerIdToRoutingKey } from './utils.js'\nexport { peerIdFromRoutingKey } from './utils.js'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Promise => {\n try {\n const dataForSignature = ipnsEntryDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw errCode(new Error('record signature creation failed'), ERRORS.ERR_SIGNATURE_CREATION)\n }\n}\n", "import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/pbe.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\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 * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface-keys'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\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}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n// Generates a keypair of the given type and bitsize\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise { // eslint-disable-line require-await\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n// Generates a keypair of the given type and bitsize\n// seed is a 32 byte uint8array\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise { // eslint-disable-line require-await\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\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n// Converts a protobuf serialized public key into its\n// representative object\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\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 ?? 'RSA')\n }\n}\n\n// Converts a public key object into a protobuf serialized public key\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\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\n// representative object\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise { // eslint-disable-line require-await\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\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\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n *\n * @param {string} encryptedKey\n * @param {string} password\n */\nexport async function importKey (encryptedKey: string, password: string): Promise { // eslint-disable-line require-await\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n // Only rsa supports pem right now\n const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password)\n if (key === null) {\n throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM')\n }\n let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))\n der = uint8ArrayFromString(der.getBytes(), 'ascii')\n return supportedKeys.rsa.unmarshalRsaPrivateKey(der)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\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 * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n async verify (data: Uint8Array, sig: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n async sign (message: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\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\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}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = await crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = await crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\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", "/*! noble-ed25519 - 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 _8n = BigInt(8);\nconst CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989');\nconst CURVE = Object.freeze({\n a: BigInt(-1),\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'),\n l: CU_O,\n n: CU_O,\n h: BigInt(8),\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n});\nexport { CURVE };\nconst POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');\nconst SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\nconst SQRT_D = BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742');\nconst SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\nconst INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\nconst ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\nconst D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\nclass ExtendedPoint {\n constructor(x, y, z, t) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.t = t;\n }\n static fromAffine(p) {\n if (!(p instanceof Point)) {\n throw new TypeError('ExtendedPoint#fromAffine: expected Point');\n }\n if (p.equals(Point.ZERO))\n return ExtendedPoint.ZERO;\n return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y));\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 this.toAffineBatch(points).map(this.fromAffine);\n }\n equals(other) {\n assertExtPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n const X1Z2 = mod(X1 * Z2);\n const X2Z1 = mod(X2 * Z1);\n const Y1Z2 = mod(Y1 * Z2);\n const Y2Z1 = mod(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n negate() {\n return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));\n }\n double() {\n const { x: X1, y: Y1, z: Z1 } = this;\n const { a } = CURVE;\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(_2n * mod(Z1 * Z1));\n const D = mod(a * A);\n const x1y1 = X1 + Y1;\n const E = mod(mod(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new ExtendedPoint(X3, Y3, Z3, T3);\n }\n add(other) {\n assertExtPoint(other);\n const { x: X1, y: Y1, z: Z1, t: T1 } = this;\n const { x: X2, y: Y2, z: Z2, t: T2 } = other;\n const A = mod((Y1 - X1) * (Y2 + X2));\n const B = mod((Y1 + X1) * (Y2 - X2));\n const F = mod(B - A);\n if (F === _0n)\n return this.double();\n const C = mod(Z1 * _2n * T2);\n const D = mod(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new ExtendedPoint(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n precomputeWindow(W) {\n const windows = 1 + 256 / W;\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(ExtendedPoint.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 = ExtendedPoint.normalizeZ(precomputes);\n pointPrecomputes.set(affinePoint, precomputes);\n }\n }\n let p = ExtendedPoint.ZERO;\n let f = ExtendedPoint.BASE;\n const windows = 1 + 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 ExtendedPoint.normalizeZ([p, f])[0];\n }\n multiply(scalar, affinePoint) {\n return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint);\n }\n multiplyUnsafe(scalar) {\n let n = normalizeScalar(scalar, CURVE.l, false);\n const G = ExtendedPoint.BASE;\n const P0 = ExtendedPoint.ZERO;\n if (n === _0n)\n return P0;\n if (this.equals(P0) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n);\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 isSmallOrder() {\n return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);\n }\n isTorsionFree() {\n let p = this.multiplyUnsafe(CURVE.l / _2n).double();\n if (CURVE.l % _2n)\n p = p.add(this);\n return p.equals(ExtendedPoint.ZERO);\n }\n toAffine(invZ) {\n const { x, y, z } = this;\n const is0 = this.equals(ExtendedPoint.ZERO);\n if (invZ == null)\n invZ = is0 ? _8n : invert(z);\n const ax = mod(x * invZ);\n const ay = mod(y * invZ);\n const zz = mod(z * invZ);\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 fromRistrettoBytes() {\n legacyRist();\n }\n toRistrettoBytes() {\n legacyRist();\n }\n fromRistrettoHash() {\n legacyRist();\n }\n}\nExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy));\nExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nfunction assertExtPoint(other) {\n if (!(other instanceof ExtendedPoint))\n throw new TypeError('ExtendedPoint expected');\n}\nfunction assertRstPoint(other) {\n if (!(other instanceof RistrettoPoint))\n throw new TypeError('RistrettoPoint expected');\n}\nfunction legacyRist() {\n throw new Error('Legacy method: switch to RistrettoPoint');\n}\nclass RistrettoPoint {\n constructor(ep) {\n this.ep = ep;\n }\n static calcElligatorRistrettoMap(r0) {\n const { d } = CURVE;\n const r = mod(SQRT_M1 * r0 * r0);\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ);\n let c = BigInt(-1);\n const D = mod((c - d * r) * mod(r + d));\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);\n let s_ = mod(s * r0);\n if (!edIsNegative(s_))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_;\n if (!Ns_D_is_sq)\n c = r;\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D);\n const s2 = s * s;\n const W0 = mod((s + s) * D);\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE);\n const W2 = mod(_1n - s2);\n const W3 = mod(_1n + s2);\n return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n }\n static hashToCurve(hex) {\n hex = ensureBytes(hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = this.calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = this.calcElligatorRistrettoMap(r2);\n return new RistrettoPoint(R1.add(R2));\n }\n static fromHex(hex) {\n hex = ensureBytes(hex, 32);\n const { a, d } = CURVE;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2);\n const u2 = mod(_1n - a * s2);\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2);\n const { isValid, value: I } = invertSqrt(mod(v * u2_2));\n const Dx = mod(I * u2);\n const Dy = mod(I * Dx * v);\n let x = mod((s + s) * Dx);\n if (edIsNegative(x))\n x = mod(-x);\n const y = mod(u1 * Dy);\n const t = mod(x * y);\n if (!isValid || edIsNegative(t) || y === _0n)\n throw new Error(emsg);\n return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t));\n }\n toRawBytes() {\n let { x, y, z, t } = this.ep;\n const u1 = mod(mod(z + y) * mod(z - y));\n const u2 = mod(x * y);\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));\n const D1 = mod(invsqrt * u1);\n const D2 = mod(invsqrt * u2);\n const zInv = mod(D1 * D2 * t);\n let D;\n if (edIsNegative(t * zInv)) {\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;\n }\n if (edIsNegative(x * zInv))\n y = mod(-y);\n let s = mod((z - y) * D);\n if (edIsNegative(s))\n s = mod(-s);\n return numberTo32BytesLE(s);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n equals(other) {\n assertRstPoint(other);\n const a = this.ep;\n const b = other.ep;\n const one = mod(a.x * b.y) === mod(a.y * b.x);\n const two = mod(a.y * b.y) === mod(a.x * b.x);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistrettoPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistrettoPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistrettoPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistrettoPoint(this.ep.multiplyUnsafe(scalar));\n }\n}\nRistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE);\nRistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO);\nconst pointPrecomputes = new WeakMap();\nclass 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 static fromHex(hex, strict = true) {\n const { d, P } = CURVE;\n hex = ensureBytes(hex, 32);\n const normed = hex.slice();\n normed[31] = hex[31] & ~0x80;\n const y = bytesToNumberLE(normed);\n if (strict && y >= P)\n throw new Error('Expected 0 < hex < P');\n if (!strict && y >= POW_2_256)\n throw new Error('Expected 0 < hex < 2**256');\n const y2 = mod(y * y);\n const u = mod(y2 - _1n);\n const v = mod(d * y2 + _1n);\n let { isValid, value: x } = uvRatio(u, v);\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n;\n const isLastByteOdd = (hex[31] & 0x80) !== 0;\n if (isLastByteOdd !== isXOdd) {\n x = mod(-x);\n }\n return new Point(x, y);\n }\n static async fromPrivateKey(privateKey) {\n return (await getExtendedPublicKey(privateKey)).point;\n }\n toRawBytes() {\n const bytes = numberTo32BytesLE(this.y);\n bytes[31] |= this.x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toX25519() {\n const { y } = this;\n const u = mod((_1n + y) * invert(_1n - y));\n return numberTo32BytesLE(u);\n }\n isTorsionFree() {\n return ExtendedPoint.fromAffine(this).isTorsionFree();\n }\n equals(other) {\n return this.x === other.x && this.y === other.y;\n }\n negate() {\n return new Point(mod(-this.x), this.y);\n }\n add(other) {\n return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiply(scalar) {\n return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();\n }\n}\nPoint.BASE = new Point(CURVE.Gx, CURVE.Gy);\nPoint.ZERO = new Point(_0n, _1n);\nclass Signature {\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, 64);\n const r = Point.fromHex(bytes.slice(0, 32), false);\n const s = bytesToNumberLE(bytes.slice(32, 64));\n return new Signature(r, s);\n }\n assertValidity() {\n const { r, s } = this;\n if (!(r instanceof Point))\n throw new Error('Expected Point instance');\n normalizeScalar(s, CURVE.l, false);\n return this;\n }\n toRawBytes() {\n const u8 = new Uint8Array(64);\n u8.set(this.r.toRawBytes());\n u8.set(numberTo32BytesLE(this.s), 32);\n return u8;\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n}\nexport { ExtendedPoint, RistrettoPoint, Point, Signature };\nfunction concatBytes(...arrays) {\n if (!arrays.every((a) => a instanceof Uint8Array))\n throw new Error('Expected Uint8Array list');\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('Uint8Array expected');\n let hex = '';\n for (let i = 0; i < uint8a.length; i++) {\n hex += hexes[uint8a[i]];\n }\n return 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');\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 numberTo32BytesBE(num) {\n const length = 32;\n const hex = num.toString(16).padStart(length * 2, '0');\n return hexToBytes(hex);\n}\nfunction numberTo32BytesLE(num) {\n return numberTo32BytesBE(num).reverse();\n}\nfunction edIsNegative(num) {\n return (mod(num) & _1n) === _1n;\n}\nfunction bytesToNumberLE(uint8a) {\n if (!(uint8a instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse()));\n}\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nfunction bytes255ToNumberLE(bytes) {\n return mod(bytesToNumberLE(bytes) & MAX_255B);\n}\nfunction mod(a, b = CURVE.P) {\n const res = a % b;\n return res >= _0n ? res : b + res;\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 tmp = new Array(nums.length);\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (num === _0n)\n return acc;\n tmp[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 tmp[i] = mod(acc * tmp[i], p);\n return mod(acc * num, p);\n }, inverted);\n return tmp;\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 pow_2_252_3(x) {\n const { P } = CURVE;\n const _5n = BigInt(5);\n const _10n = BigInt(10);\n const _20n = BigInt(20);\n const _40n = BigInt(40);\n const _80n = BigInt(80);\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P;\n const b4 = (pow2(b2, _2n) * b2) % P;\n const b5 = (pow2(b4, _1n) * x) % P;\n const b10 = (pow2(b5, _5n) * b5) % P;\n const b20 = (pow2(b10, _10n) * b10) % P;\n const b40 = (pow2(b20, _20n) * b20) % P;\n const b80 = (pow2(b40, _40n) * b40) % P;\n const b160 = (pow2(b80, _80n) * b80) % P;\n const b240 = (pow2(b160, _80n) * b80) % P;\n const b250 = (pow2(b240, _10n) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n) * x) % P;\n return { pow_p_5_8, b2 };\n}\nfunction uvRatio(u, v) {\n const v3 = mod(v * v * v);\n const v7 = mod(v3 * v3 * v);\n const pow = pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow);\n const vx2 = mod(v * x * x);\n const root1 = x;\n const root2 = mod(x * SQRT_M1);\n const useRoot1 = vx2 === u;\n const useRoot2 = vx2 === mod(-u);\n const noRoot = vx2 === mod(-u * SQRT_M1);\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2;\n if (edIsNegative(x))\n x = mod(-x);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nfunction invertSqrt(number) {\n return uvRatio(_1n, number);\n}\nfunction modlLE(hash) {\n return mod(bytesToNumberLE(hash), CURVE.l);\n}\nfunction equalBytes(b1, b2) {\n if (b1.length !== b2.length) {\n return false;\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction ensureBytes(hex, expectedLength) {\n const bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);\n if (typeof expectedLength === 'number' && bytes.length !== expectedLength)\n throw new Error(`Expected ${expectedLength} bytes`);\n return bytes;\n}\nfunction normalizeScalar(num, max, strict = true) {\n if (!max)\n throw new TypeError('Specify max value');\n if (typeof num === 'number' && Number.isSafeInteger(num))\n num = BigInt(num);\n if (typeof num === 'bigint' && num < max) {\n if (strict) {\n if (_0n < num)\n return num;\n }\n else {\n if (_0n <= num)\n return num;\n }\n }\n throw new TypeError('Expected valid scalar: 0 < scalar < max');\n}\nfunction adjustBytes25519(bytes) {\n bytes[0] &= 248;\n bytes[31] &= 127;\n bytes[31] |= 64;\n return bytes;\n}\nfunction decodeScalar25519(n) {\n return bytesToNumberLE(adjustBytes25519(ensureBytes(n, 32)));\n}\nfunction checkPrivateKey(key) {\n key =\n typeof key === 'bigint' || typeof key === 'number'\n ? numberTo32BytesBE(normalizeScalar(key, POW_2_256))\n : ensureBytes(key);\n if (key.length !== 32)\n throw new Error(`Expected 32 bytes`);\n return key;\n}\nfunction getKeyFromHash(hashed) {\n const head = adjustBytes25519(hashed.slice(0, 32));\n const prefix = hashed.slice(32, 64);\n const scalar = modlLE(head);\n const point = Point.BASE.multiply(scalar);\n const pointBytes = point.toRawBytes();\n return { head, prefix, scalar, point, pointBytes };\n}\nlet _sha512Sync;\nfunction sha512s(...m) {\n if (typeof _sha512Sync !== 'function')\n throw new Error('utils.sha512Sync must be set to use sync methods');\n return _sha512Sync(...m);\n}\nasync function getExtendedPublicKey(key) {\n return getKeyFromHash(await utils.sha512(checkPrivateKey(key)));\n}\nfunction getExtendedPublicKeySync(key) {\n return getKeyFromHash(sha512s(checkPrivateKey(key)));\n}\nexport async function getPublicKey(privateKey) {\n return (await getExtendedPublicKey(privateKey)).pointBytes;\n}\nfunction getPublicKeySync(privateKey) {\n return getExtendedPublicKeySync(privateKey).pointBytes;\n}\nexport async function sign(message, privateKey) {\n message = ensureBytes(message);\n const { prefix, scalar, pointBytes } = await getExtendedPublicKey(privateKey);\n const r = modlLE(await utils.sha512(prefix, message));\n const R = Point.BASE.multiply(r);\n const k = modlLE(await utils.sha512(R.toRawBytes(), pointBytes, message));\n const s = mod(r + k * scalar, CURVE.l);\n return new Signature(R, s).toRawBytes();\n}\nfunction signSync(message, privateKey) {\n message = ensureBytes(message);\n const { prefix, scalar, pointBytes } = getExtendedPublicKeySync(privateKey);\n const r = modlLE(sha512s(prefix, message));\n const R = Point.BASE.multiply(r);\n const k = modlLE(sha512s(R.toRawBytes(), pointBytes, message));\n const s = mod(r + k * scalar, CURVE.l);\n return new Signature(R, s).toRawBytes();\n}\nfunction prepareVerification(sig, message, publicKey) {\n message = ensureBytes(message);\n if (!(publicKey instanceof Point))\n publicKey = Point.fromHex(publicKey, false);\n const { r, s } = sig instanceof Signature ? sig.assertValidity() : Signature.fromHex(sig);\n const SB = ExtendedPoint.BASE.multiplyUnsafe(s);\n return { r, s, SB, pub: publicKey, msg: message };\n}\nfunction finishVerification(publicKey, r, SB, hashed) {\n const k = modlLE(hashed);\n const kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k);\n const RkA = ExtendedPoint.fromAffine(r).add(kA);\n return RkA.subtract(SB).multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);\n}\nexport async function verify(sig, message, publicKey) {\n const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);\n const hashed = await utils.sha512(r.toRawBytes(), pub.toRawBytes(), msg);\n return finishVerification(pub, r, SB, hashed);\n}\nfunction verifySync(sig, message, publicKey) {\n const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);\n const hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg);\n return finishVerification(pub, r, SB, hashed);\n}\nexport const sync = {\n getExtendedPublicKey: getExtendedPublicKeySync,\n getPublicKey: getPublicKeySync,\n sign: signSync,\n verify: verifySync,\n};\nexport async function getSharedSecret(privateKey, publicKey) {\n const { head } = await getExtendedPublicKey(privateKey);\n const u = Point.fromHex(publicKey).toX25519();\n return curve25519.scalarMult(head, u);\n}\nPoint.BASE._setWindowSize(8);\nfunction cswap(swap, x_2, x_3) {\n const dummy = mod(swap * (x_2 - x_3));\n x_2 = mod(x_2 - dummy);\n x_3 = mod(x_3 + dummy);\n return [x_2, x_3];\n}\nfunction montgomeryLadder(pointU, scalar) {\n const { P } = CURVE;\n const u = normalizeScalar(pointU, P);\n const k = normalizeScalar(scalar, P);\n const a24 = BigInt(121665);\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(255 - 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 = mod(A * A);\n const B = x_2 - z_2;\n const BB = mod(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = mod(D * A);\n const CB = mod(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = mod(dacb * dacb);\n z_3 = mod(x_1 * mod(da_cb * da_cb));\n x_2 = mod(AA * BB);\n z_2 = mod(E * (AA + mod(a24 * E)));\n }\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 const { pow_p_5_8, b2 } = pow_2_252_3(z_2);\n const xp2 = mod(pow2(pow_p_5_8, BigInt(3)) * b2);\n return mod(x_2 * xp2);\n}\nfunction encodeUCoordinate(u) {\n return numberTo32BytesLE(mod(u, CURVE.P));\n}\nfunction decodeUCoordinate(uEnc) {\n const u = ensureBytes(uEnc, 32);\n u[31] &= 127;\n return bytesToNumberLE(u);\n}\nexport const curve25519 = {\n BASE_POINT_U: '0900000000000000000000000000000000000000000000000000000000000000',\n scalarMult(privateKey, publicKey) {\n const u = decodeUCoordinate(publicKey);\n const p = decodeScalar25519(privateKey);\n const pu = montgomeryLadder(u, p);\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n },\n scalarMultBase(privateKey) {\n return curve25519.scalarMult(privateKey, curve25519.BASE_POINT_U);\n },\n};\nconst crypto = {\n node: nodeCrypto,\n web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,\n};\nexport const utils = {\n bytesToHex,\n hexToBytes,\n concatBytes,\n getExtendedPublicKey,\n mod,\n invert,\n TORSION_SUBGROUP: [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n ],\n hashToPrivateScalar: (hash) => {\n hash = ensureBytes(hash);\n if (hash.length < 40 || hash.length > 1024)\n throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');\n return mod(bytesToNumberLE(hash), CURVE.l - _1n) + _1n;\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 new Uint8Array(randomBytes(bytesLength).buffer);\n }\n else {\n throw new Error(\"The environment doesn't have randomBytes function\");\n }\n },\n randomPrivateKey: () => {\n return utils.randomBytes(32);\n },\n sha512: async (...messages) => {\n const message = concatBytes(...messages);\n if (crypto.web) {\n const buffer = await crypto.web.subtle.digest('SHA-512', message.buffer);\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n return Uint8Array.from(crypto.node.createHash('sha512').update(message).digest());\n }\n else {\n throw new Error(\"The environment doesn't have sha512 function\");\n }\n },\n precompute(windowSize = 8, point = Point.BASE) {\n const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);\n cached._setWindowSize(windowSize);\n cached.multiply(_2n);\n return cached;\n },\n sha512Sync: undefined,\n};\nObject.defineProperties(utils, {\n sha512Sync: {\n configurable: false,\n get() {\n return _sha512Sync;\n },\n set(val) {\n if (!_sha512Sync)\n _sha512Sync = val;\n },\n },\n});\n", "import * as ed from '@noble/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface'\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\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport async function generateKey (): Promise {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport async function generateKeyFromSeed (seed: Uint8Array): Promise {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array): Promise {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg, privateKeyRaw)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise {\n return ed.verify(sig, msg, publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\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", "import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed ArrayLikes\n */\nexport function concat (arrays: Array>, length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/* eslint-env browser */\n\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\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n '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-crypto/blob/master/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n", "import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\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// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\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\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\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: Uint8Array, password: string | Uint8Array): Promise { // eslint-disable-line require-await\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: 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 } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\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\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 /**\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: Uint8Array, password: string | Uint8Array): Promise {\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\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: 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 } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\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\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\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 */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\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/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\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}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\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/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\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", "// 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/**\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 public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\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 */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\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 /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\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\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\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 /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\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 /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\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 /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\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) { 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 */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\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}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\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 } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\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 } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // 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 * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\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 if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = 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 */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\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 /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const 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 */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { 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 }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\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\n private readLongVarint (): LongBits {\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) { 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) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { 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) { 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) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\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) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\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 (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "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'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\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 public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\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 implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\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 /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\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\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\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 */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\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: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\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 /**\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 (): this {\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 */\n reset (): this {\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 } 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 */\n ldelim (): this {\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 /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\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}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\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 *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\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}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\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\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\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\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\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 } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\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\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "import 'node-forge/lib/util.js'\nimport 'node-forge/lib/jsbn.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport function bigIntegerToUintBase64url (num: { abs: () => any }, len?: number): string {\n // Call `.abs()` to convert to unsigned\n let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian\n\n // toByteArray() gives us back a signed array, which will include a leading 0\n // byte if the most significant bit of the number is 1:\n // https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer\n // Our number will always be positive so we should remove the leading padding.\n buf = buf[0] === 0 ? buf.subarray(1) : buf\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return uint8ArrayToString(buf, 'base64url')\n}\n\n// Convert a base64url encoded string to a BigInteger\nexport function base64urlToBigInteger (str: string): typeof forge.jsbn.BigInteger {\n const buf = base64urlToBuffer(str)\n return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16)\n}\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { base64urlToBuffer } from '../util.js'\nimport webcrypto from '../webcrypto.js'\nimport type { ECDHKey, ECDHKeyPair, JWKEncodedPrivateKey, JWKEncodedPublicKey } from './interface.js'\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n}\n\nconst curveTypes = Object.keys(bits)\nconst names = curveTypes.join(' / ')\n\nexport async function generateEphmeralKeyPair (curve: string): Promise {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve\n },\n true,\n ['deriveBits']\n )\n\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair): Promise => {\n let privateKey\n\n if (forcePrivate != null) {\n privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPrivateKey(curve, forcePrivate),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n ['deriveBits']\n )\n } else {\n privateKey = pair.privateKey\n }\n\n const key = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPublicKey(curve, theirPub),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n []\n )\n\n const buffer = await webcrypto.get().subtle.deriveBits(\n {\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n },\n privateKey,\n bits[curve]\n )\n\n return new Uint8Array(buffer, 0, buffer.byteLength)\n }\n\n const publicKey = await webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n\n const ecdhKey: ECDHKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n }\n\n return ecdhKey\n}\n\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n}\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: JsonWebKey): Uint8Array {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[jwk.crv]\n\n return uint8ArrayConcat([\n Uint8Array.from([4]), // uncompressed point\n base64urlToBuffer(jwk.x, byteLen),\n base64urlToBuffer(jwk.y, byteLen)\n ], 1 + byteLen * 2)\n}\n\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey (curve: string, key: Uint8Array): JWKEncodedPublicKey {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[curve]\n\n if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT')\n }\n\n return {\n kty: 'EC',\n crv: curve,\n x: uint8ArrayToString(key.subarray(1, byteLen + 1), 'base64url'),\n y: uint8ArrayToString(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n }\n}\n\nconst unmarshalPrivateKey = (curve: string, key: ECDHKeyPair): JWKEncodedPrivateKey => ({\n ...unmarshalPublicKey(curve, key.public),\n d: uint8ArrayToString(key.private, 'base64url')\n})\n", "import { generateEphmeralKeyPair } from './ecdh.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 */\nexport default generateEphmeralKeyPair\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\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 */\nexport async function importer (privateKey: string, password: string): Promise {\n const encryptedKey = base64.decode(privateKey)\n const cipher = ciphers.create()\n return cipher.decrypt(encryptedKey, password)\n}\n", "\nexport default {\n SHA1: 20,\n SHA256: 32,\n SHA512: 64\n}\n", "import webcrypto from '../webcrypto.js'\nimport lengths from './lengths.js'\n\nconst hashTypes = {\n SHA1: 'SHA-1',\n SHA256: 'SHA-256',\n SHA512: 'SHA-512'\n}\n\nconst sign = async (key: CryptoKey, data: Uint8Array): Promise => {\n const buf = await webcrypto.get().subtle.sign({ name: 'HMAC' }, key, data)\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n\nexport async function create (hashType: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise<{ digest: (data: Uint8Array) => Promise, length: number }> {\n const hash = hashTypes[hashType]\n\n const key = await webcrypto.get().subtle.importKey(\n 'raw',\n secret,\n {\n name: 'HMAC',\n hash: { name: hash }\n },\n false,\n ['sign']\n )\n\n return {\n async digest (data: Uint8Array) { // eslint-disable-line require-await\n return sign(key, data)\n },\n length: lengths[hashType]\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport * as hmac from '../hmac/index.js'\nimport type { EnhancedKey, EnhancedKeyPair } from './interface.js'\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/**\n * Generates a set of keys for each party by stretching the shared key.\n * (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)\n */\nexport async function keyStretcher (cipherType: 'AES-128' | 'AES-256' | 'Blowfish', hash: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise {\n const cipher = cipherMap[cipherType]\n\n if (cipher == null) {\n const allowed = Object.keys(cipherMap).join(' / ')\n throw new CodeError(`unknown cipher type '${cipherType}'. Must be ${allowed}`, 'ERR_INVALID_CIPHER_TYPE')\n }\n\n if (hash == null) {\n throw new CodeError('missing hash type', 'ERR_MISSING_HASH_TYPE')\n }\n\n const cipherKeySize = cipher.keySize\n const ivSize = cipher.ivSize\n const hmacKeySize = 20\n const seed = uint8ArrayFromString('key expansion')\n const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize)\n\n const m = await hmac.create(hash, secret)\n let a = await m.digest(seed)\n\n const result = []\n let j = 0\n\n while (j < resultLength) {\n const b = await m.digest(uint8ArrayConcat([a, seed]))\n let todo = b.length\n\n if (j + todo > resultLength) {\n todo = resultLength - j\n }\n\n result.push(b)\n j += todo\n a = await m.digest(a)\n }\n\n const half = resultLength / 2\n const resultBuffer = uint8ArrayConcat(result)\n const r1 = resultBuffer.subarray(0, half)\n const r2 = resultBuffer.subarray(half, resultLength)\n\n const createKey = (res: Uint8Array): EnhancedKey => ({\n iv: res.subarray(0, ivSize),\n cipherKey: res.subarray(ivSize, ivSize + cipherKeySize),\n macKey: res.subarray(ivSize + cipherKeySize)\n })\n\n return {\n k1: createKey(r1),\n k2: createKey(r2)\n }\n}\n", "\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { sha256 } from 'multiformats/hashes/sha2'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport 'node-forge/lib/sha512.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n encrypt (bytes: Uint8Array): Uint8Array {\n return crypto.encrypt(this._key, bytes)\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n async sign (message: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n decrypt (bytes: Uint8Array): Uint8Array {\n return crypto.decrypt(this._key, bytes)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected PEM format\n */\n async export (password: string, format = 'pkcs-8'): Promise> { // eslint-disable-line require-await\n if (format === 'pkcs-8') {\n const buffer = new forge.util.ByteBuffer(this.marshal())\n const asn1 = forge.asn1.fromDer(buffer)\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n const options = {\n algorithm: 'aes256',\n count: 10000,\n saltSize: 128 / 8,\n prfAlgorithm: 'sha512'\n }\n return forge.pki.encryptRsaPrivateKey(privateKey, password, options)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n const keys = await crypto.generateKey(bits)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n", "/*! 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 { CodeError } from '@libp2p/interfaces/errors'\nimport { utils } from '@noble/secp256k1'\n\nexport default function randomBytes (length: number): Uint8Array {\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 utils.randomBytes(length)\n}\n", "import 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { base64urlToBigInteger } from '../util.js'\n\nexport interface JWK {\n encrypt: (msg: string) => string\n decrypt: (msg: string) => string\n}\n\nfunction convert (key: any, types: string[]): Array {\n return types.map(t => base64urlToBigInteger(key[t]))\n}\n\nexport function jwk2priv (key: JsonWebKey): JWK {\n return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']))\n}\n\nexport function jwk2pub (key: JsonWebKey): JWK {\n return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e']))\n}\n", "import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/rsa.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js'\n\n// Convert a PKCS#1 in ASN1 DER format to a JWK key\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n // https://tools.ietf.org/html/rfc7518#section-6.3.1\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(privateKey.n),\n e: bigIntegerToUintBase64url(privateKey.e),\n d: bigIntegerToUintBase64url(privateKey.d),\n p: bigIntegerToUintBase64url(privateKey.p),\n q: bigIntegerToUintBase64url(privateKey.q),\n dp: bigIntegerToUintBase64url(privateKey.dP),\n dq: bigIntegerToUintBase64url(privateKey.dQ),\n qi: bigIntegerToUintBase64url(privateKey.qInv),\n alg: 'RS256'\n }\n}\n\n// Convert a JWK key into PKCS#1 in ASN1 DER format\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\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\n const asn1 = forge.pki.privateKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e),\n d: base64urlToBigInteger(jwk.d),\n p: base64urlToBigInteger(jwk.p),\n q: base64urlToBigInteger(jwk.q),\n dP: base64urlToBigInteger(jwk.dp),\n dQ: base64urlToBigInteger(jwk.dq),\n qInv: base64urlToBigInteger(jwk.qi)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n\n// Convert a PKCIX in ASN1 DER format to a JWK key\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const publicKey = forge.pki.publicKeyFromAsn1(asn1)\n\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(publicKey.n),\n e: bigIntegerToUintBase64url(publicKey.e)\n }\n}\n\n// Convert a JWK key to PKCIX in ASN1 DER format\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const asn1 = forge.pki.publicKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\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 { jwk2pub, jwk2priv } from './jwk2pem.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n Uint8Array.from(msg)\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\n/*\n\nRSA encryption/decryption for the browser with webcrypto workaround\n\"bloody dark magic. webcrypto's why.\"\n\nExplanation:\n - Convert JWK to nodeForge\n - Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a \"binary-string backed buffer\", so let's make our Uint8Array a binary string\n - Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array\n\n*/\n\nfunction convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array, handle: (msg: string, key: { encrypt: (msg: string) => string, decrypt: (msg: string) => string }) => string): Uint8Array {\n const fkey = pub ? jwk2pub(key) : jwk2priv(key)\n const fmsg = uint8ArrayToString(Uint8Array.from(msg), 'ascii')\n const fomsg = handle(fmsg, fkey)\n return uint8ArrayFromString(fomsg, 'ascii')\n}\n\nexport function encrypt (key: JsonWebKey, msg: Uint8Array): Uint8Array {\n return convertKey(key, true, msg, (msg, key) => key.encrypt(msg))\n}\n\nexport function decrypt (key: JsonWebKey, msg: Uint8Array): Uint8Array {\n return convertKey(key, false, msg, (msg, key) => key.decrypt(msg))\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array): Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n async sign (message: Uint8Array): Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport * as secp from '@noble/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport async function hashAndSign (key: Uint8Array, msg: Uint8Array): Promise {\n const { digest } = await sha256.digest(msg)\n try {\n return await secp.sign(digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise {\n try {\n const { digest } = await sha256.digest(msg)\n return secp.verify(sig, digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.Point.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.Point.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.Point.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n", "import errCode from 'err-code'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { IPNSEntry, IPNSEntryData } from './index.js'\nimport * as ERRORS from './errors.js'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'\nimport { logger } from '@libp2p/logger'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport * as cborg from 'cborg'\nimport type { PublicKey } from '@libp2p/interface-keys'\n\nconst log = logger('ipns:utils')\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\n\n/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = milliseconds * 1000 * 1000\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n\n/**\n * Extracts a public key from the passed PeerId, falling\n * back to the pubKey embedded in the ipns record\n */\nexport const extractPublicKey = async (peerId: PeerId, entry: IpnsEntry): Promise => {\n if (entry == null || peerId == null) {\n const error = new Error('one or more of the provided parameters are not defined')\n\n log.error(error)\n throw errCode(error, ERRORS.ERR_UNDEFINED_PARAMETER)\n }\n\n let pubKey: PublicKey | undefined\n\n if (entry.pubKey != null) {\n try {\n pubKey = unmarshalPublicKey(entry.pubKey)\n } catch (err) {\n log.error(err)\n throw err\n }\n\n const otherId = await peerIdFromKeys(entry.pubKey)\n\n if (!otherId.equals(peerId)) {\n throw errCode(new Error('Embedded public key did not match PeerID'), ERRORS.ERR_INVALID_EMBEDDED_KEY)\n }\n } else if (peerId.publicKey != null) {\n pubKey = unmarshalPublicKey(peerId.publicKey)\n }\n\n if (pubKey != null) {\n return pubKey\n }\n\n throw errCode(new Error('no public key is available'), ERRORS.ERR_UNDEFINED_PARAMETER)\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport const ipnsEntryDataForV1Sig = (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array => {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n\n return uint8ArrayConcat([value, validity, validityTypeBuffer])\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport const ipnsEntryDataForV2Sig = (data: Uint8Array): Uint8Array => {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport const marshal = (obj: IPNSEntry): Uint8Array => {\n return IpnsEntry.encode(obj)\n}\n\nexport const unmarshal = (buf: Uint8Array): IPNSEntry => {\n const message = IpnsEntry.decode(buf)\n\n // protobufjs returns bigints as numbers\n if (message.sequence != null) {\n message.sequence = BigInt(message.sequence)\n }\n\n // protobufjs returns bigints as numbers\n if (message.ttl != null) {\n message.ttl = BigInt(message.ttl)\n }\n\n return {\n value: message.value ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n validityType: message.validityType ?? IpnsEntry.ValidityType.EOL,\n validity: message.validity ?? new Uint8Array(0),\n sequence: message.sequence ?? 0n,\n pubKey: message.pubKey,\n ttl: message.ttl ?? undefined,\n signatureV2: message.signatureV2,\n data: message.data\n }\n}\n\nexport const peerIdToRoutingKey = (peerId: PeerId): Uint8Array => {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n peerId.toBytes()\n ])\n}\n\nexport const peerIdFromRoutingKey = (key: Uint8Array): PeerId => {\n return peerIdFromBytes(key.slice(IPNS_PREFIX.length))\n}\n\nexport const createCborData = (value: Uint8Array, validity: Uint8Array, validityType: string, sequence: bigint, ttl: bigint): Uint8Array => {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw errCode(new Error('Unknown validity type'), ERRORS.ERR_UNRECOGNIZED_VALIDITY)\n }\n\n const data = {\n Value: value,\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport const parseCborData = (buf: Uint8Array): IPNSEntryData => {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw errCode(new Error('Unknown validity type'), ERRORS.ERR_UNRECOGNIZED_VALIDITY)\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n", "\nexport const ERR_IPNS_EXPIRED_RECORD = 'ERR_IPNS_EXPIRED_RECORD'\nexport const ERR_UNRECOGNIZED_VALIDITY = 'ERR_UNRECOGNIZED_VALIDITY'\nexport const ERR_SIGNATURE_CREATION = 'ERR_SIGNATURE_CREATION'\nexport const ERR_SIGNATURE_VERIFICATION = 'ERR_SIGNATURE_VERIFICATION'\nexport const ERR_UNRECOGNIZED_FORMAT = 'ERR_UNRECOGNIZED_FORMAT'\nexport const ERR_PEER_ID_FROM_PUBLIC_KEY = 'ERR_PEER_ID_FROM_PUBLIC_KEY'\nexport const ERR_PUBLIC_KEY_FROM_ID = 'ERR_PUBLIC_KEY_FROM_ID'\nexport const ERR_UNDEFINED_PARAMETER = 'ERR_UNDEFINED_PARAMETER'\nexport const ERR_INVALID_RECORD_DATA = 'ERR_INVALID_RECORD_DATA'\nexport const ERR_INVALID_EMBEDDED_KEY = 'ERR_INVALID_EMBEDDED_KEY'\nexport const ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY'\n", "// @ts-expect-error no types\nimport ReaderClass from 'protobufjs/src/reader.js'\n// @ts-expect-error no types\nimport ReaderBufferClass from 'protobufjs/src/reader_buffer.js'\n// @ts-expect-error no types\nimport WriterClass from 'protobufjs/src/writer.js'\n// @ts-expect-error no types\nimport WriterBufferClass from 'protobufjs/src/writer_buffer.js'\n// @ts-expect-error no types\nimport util from 'protobufjs/src/util/minimal.js'\nimport type { Reader, Writer } from './index.js'\n\nfunction configure (): void {\n util._configure()\n ReaderClass._configure(ReaderBufferClass)\n WriterClass._configure(WriterBufferClass)\n}\n\n// Set up buffer utility according to the environment\nconfigure()\n\n// monkey patch the reader to add native bigint support\nconst methods = [\n 'uint64', 'int64', 'sint64', 'fixed64', 'sfixed64'\n]\n\nfunction patchReader (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (): bigint {\n return BigInt(original.call(this).toString())\n }\n }\n\n return obj\n}\n\nexport function reader (buf: Uint8Array): Reader {\n return patchReader(new ReaderClass(buf))\n}\n\nfunction patchWriter (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (val: bigint) {\n return original.call(this, val.toString())\n }\n }\n\n return obj\n}\n\nexport function writer (): Writer {\n return patchWriter(WriterClass.create())\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { reader } from './utils.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n const r = reader(buf instanceof Uint8Array ? buf : buf.subarray())\n\n return codec.decode(r)\n}\n", "import type { Codec } from './codec.js'\nimport { writer } from './utils.js'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8Array {\n const w = writer()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: T, writer: Writer, opts?: EncodeOptions): void\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\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\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, EncodeOptions } from '../codec.js'\nimport type { Codec } from '../codec.js'\nimport type { Reader, Writer } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: (obj: T, writer: Writer, opts?: EncodeOptions) => void, decode: (reader: Reader, length?: number) => T): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface IpnsEntry {\n value?: Uint8Array\n signature?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n pubKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec => {\n return enumeration(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signature != null) {\n w.uint32(18)\n w.bytes(obj.signature)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.pubKey != null) {\n w.uint32(58)\n w.bytes(obj.pubKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.value = reader.bytes()\n break\n case 2:\n obj.signature = reader.bytes()\n break\n case 3:\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n case 4:\n obj.validity = reader.bytes()\n break\n case 5:\n obj.sequence = reader.uint64()\n break\n case 6:\n obj.ttl = reader.uint64()\n break\n case 7:\n obj.pubKey = reader.bytes()\n break\n case 8:\n obj.signatureV2 = reader.bytes()\n break\n case 9:\n obj.data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: IpnsEntry): Uint8Array => {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): IpnsEntry => {\n return decodeMessage(buf, IpnsEntry.codec())\n }\n}\n", "const typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n];\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nexport function is(value) {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return 'undefined';\n }\n if (value === true || value === false) {\n return 'boolean';\n }\n const typeOf = typeof value;\n if (typeofs.includes(typeOf)) {\n return typeOf;\n }\n if (typeOf === 'function') {\n return 'Function';\n }\n if (Array.isArray(value)) {\n return 'Array';\n }\n if (isBuffer(value)) {\n return 'Buffer';\n }\n const objectType = getObjectType(value);\n if (objectType) {\n return objectType;\n }\n return 'Object';\n}\nfunction isBuffer(value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value);\n}\nfunction getObjectType(value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n}", "class Type {\n constructor(major, name, terminal) {\n this.major = major;\n this.majorEncoded = major << 5;\n this.name = name;\n this.terminal = terminal;\n }\n toString() {\n return `Type[${ this.major }].${ this.name }`;\n }\n compare(typ) {\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;\n }\n}\nType.uint = new Type(0, 'uint', true);\nType.negint = new Type(1, 'negint', true);\nType.bytes = new Type(2, 'bytes', true);\nType.string = new Type(3, 'string', true);\nType.array = new Type(4, 'array', false);\nType.map = new Type(5, 'map', false);\nType.tag = new Type(6, 'tag', false);\nType.float = new Type(7, 'float', true);\nType.false = new Type(7, 'false', true);\nType.true = new Type(7, 'true', true);\nType.null = new Type(7, 'null', true);\nType.undefined = new Type(7, 'undefined', true);\nType.break = new Type(7, 'break', true);\nclass Token {\n constructor(type, value, encodedLength) {\n this.type = type;\n this.value = value;\n this.encodedLength = encodedLength;\n this.encodedBytes = undefined;\n this.byteValue = undefined;\n }\n toString() {\n return `Token[${ this.type }].${ this.value }`;\n }\n}\nexport {\n Type,\n Token\n};", "export const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === 'function';\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\nfunction isBuffer(buf) {\n return useBuffer && globalThis.Buffer.isBuffer(buf);\n}\nexport function asU8A(buf) {\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf);\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;\n}\nexport const toString = useBuffer ? (bytes, start, end) => {\n return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8') : utf8Slice(bytes, start, end);\n} : (bytes, start, end) => {\n return end - start > 64 ? textDecoder.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end);\n};\nexport const fromString = useBuffer ? string => {\n return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string);\n} : string => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string);\n};\nexport const fromArray = arr => {\n return Uint8Array.from(arr);\n};\nexport const slice = useBuffer ? (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end));\n }\n return bytes.slice(start, end);\n} : (bytes, start, end) => {\n return bytes.slice(start, end);\n};\nexport const concat = useBuffer ? (chunks, length) => {\n chunks = chunks.map(c => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));\n return asU8A(globalThis.Buffer.concat(chunks, length));\n} : (chunks, length) => {\n const out = new Uint8Array(length);\n let off = 0;\n for (let b of chunks) {\n if (off + b.length > out.length) {\n b = b.subarray(0, out.length - off);\n }\n out.set(b, off);\n off += b.length;\n }\n return out;\n};\nexport const alloc = useBuffer ? size => {\n return globalThis.Buffer.allocUnsafe(size);\n} : size => {\n return new Uint8Array(size);\n};\nexport const toHex = useBuffer ? d => {\n if (typeof d === 'string') {\n return d;\n }\n return globalThis.Buffer.from(toBytes(d)).toString('hex');\n} : d => {\n if (typeof d === 'string') {\n return d;\n }\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${ p }${ c.toString(16).padStart(2, '0') }`, '');\n};\nexport const fromHex = useBuffer ? hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n return globalThis.Buffer.from(hex, 'hex');\n} : hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n if (!hex.length) {\n return new Uint8Array(0);\n }\n return new Uint8Array(hex.split('').map((c, i, d) => i % 2 === 0 ? `0x${ c }${ d[i + 1] }` : '').filter(Boolean).map(e => parseInt(e, 16)));\n};\nfunction toBytes(obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj;\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj);\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function compare(b1, b2) {\n if (isBuffer(b1) && isBuffer(b2)) {\n return b1.compare(b2);\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue;\n }\n return b1[i] < b2[i] ? -1 : 1;\n }\n return 0;\n}\nfunction utf8ToBytes(string, units = Infinity) {\n let codePoint;\n const length = string.length;\n let leadSurrogate = null;\n const bytes = [];\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n if (codePoint > 55295 && codePoint < 57344) {\n if (!leadSurrogate) {\n if (codePoint > 56319) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n } else if (i + 1 === length) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n }\n leadSurrogate = codePoint;\n continue;\n }\n if (codePoint < 56320) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n leadSurrogate = codePoint;\n continue;\n }\n codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;\n } else if (leadSurrogate) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n }\n leadSurrogate = null;\n if (codePoint < 128) {\n if ((units -= 1) < 0)\n break;\n bytes.push(codePoint);\n } else if (codePoint < 2048) {\n if ((units -= 2) < 0)\n break;\n bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);\n } else if (codePoint < 65536) {\n if ((units -= 3) < 0)\n break;\n bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else if (codePoint < 1114112) {\n if ((units -= 4) < 0)\n break;\n bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else {\n throw new Error('Invalid code point');\n }\n }\n return bytes;\n}\nfunction utf8Slice(buf, offset, end) {\n const res = [];\n while (offset < end) {\n const firstByte = buf[offset];\n let codePoint = null;\n let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint;\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 128) {\n codePoint = firstByte;\n }\n break;\n case 2:\n secondByte = buf[offset + 1];\n if ((secondByte & 192) === 128) {\n tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;\n if (tempCodePoint > 127) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 3:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;\n if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 4:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n fourthByte = buf[offset + 3];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;\n if (tempCodePoint > 65535 && tempCodePoint < 1114112) {\n codePoint = tempCodePoint;\n }\n }\n }\n }\n if (codePoint === null) {\n codePoint = 65533;\n bytesPerSequence = 1;\n } else if (codePoint > 65535) {\n codePoint -= 65536;\n res.push(codePoint >>> 10 & 1023 | 55296);\n codePoint = 56320 | codePoint & 1023;\n }\n res.push(codePoint);\n offset += bytesPerSequence;\n }\n return decodeCodePointsArray(res);\n}\nconst MAX_ARGUMENTS_LENGTH = 4096;\nexport function decodeCodePointsArray(codePoints) {\n const len = codePoints.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints);\n }\n let res = '';\n let i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));\n }\n return res;\n}", "import {\n alloc,\n concat,\n slice\n} from './byte-utils.js';\nconst defaultChunkSize = 256;\nexport class Bl {\n constructor(chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize;\n this.cursor = 0;\n this.maxCursor = -1;\n this.chunks = [];\n this._initReuseChunk = null;\n }\n reset() {\n this.cursor = 0;\n this.maxCursor = -1;\n if (this.chunks.length) {\n this.chunks = [];\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk);\n this.maxCursor = this._initReuseChunk.length - 1;\n }\n }\n push(bytes) {\n let topChunk = this.chunks[this.chunks.length - 1];\n const newMax = this.cursor + bytes.length;\n if (newMax <= this.maxCursor + 1) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n topChunk.set(bytes, chunkPos);\n } else {\n if (topChunk) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n if (chunkPos < topChunk.length) {\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);\n this.maxCursor = this.cursor - 1;\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n topChunk = alloc(this.chunkSize);\n this.chunks.push(topChunk);\n this.maxCursor += topChunk.length;\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk;\n }\n topChunk.set(bytes, 0);\n } else {\n this.chunks.push(bytes);\n this.maxCursor += bytes.length;\n }\n }\n this.cursor += bytes.length;\n }\n toBytes(reset = false) {\n let byts;\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0];\n if (reset && this.cursor > chunk.length / 2) {\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);\n this._initReuseChunk = null;\n this.chunks = [];\n } else {\n byts = slice(chunk, 0, this.cursor);\n }\n } else {\n byts = concat(this.chunks, this.cursor);\n }\n if (reset) {\n this.reset();\n }\n return byts;\n }\n}", "const decodeErrPrefix = 'CBOR decode error:';\nconst encodeErrPrefix = 'CBOR encode error:';\nconst uintMinorPrefixBytes = [];\nuintMinorPrefixBytes[23] = 1;\nuintMinorPrefixBytes[24] = 2;\nuintMinorPrefixBytes[25] = 3;\nuintMinorPrefixBytes[26] = 5;\nuintMinorPrefixBytes[27] = 9;\nfunction assertEnoughData(data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${ decodeErrPrefix } not enough data for type`);\n }\n}\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n decodeErrPrefix,\n assertEnoughData\n} from './common.js';\nexport const uintBoundaries = [\n 24,\n 256,\n 65536,\n 4294967296,\n BigInt('18446744073709551616')\n];\nexport function readUint8(data, offset, options) {\n assertEnoughData(data, offset, 1);\n const value = data[offset];\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint16(data, offset, options) {\n assertEnoughData(data, offset, 2);\n const value = data[offset] << 8 | data[offset + 1];\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint32(data, offset, options) {\n assertEnoughData(data, offset, 4);\n const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint64(data, offset, options) {\n assertEnoughData(data, offset, 8);\n const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value);\n }\n if (options.allowBigInt === true) {\n return value;\n }\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n}\nexport function decodeUint8(data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2);\n}\nexport function decodeUint16(data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3);\n}\nexport function decodeUint32(data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5);\n}\nexport function decodeUint64(data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9);\n}\nexport function encodeUint(buf, token) {\n return encodeUintValue(buf, 0, token.value);\n}\nexport function encodeUintValue(buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint);\n buf.push([major | nuint]);\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint);\n buf.push([\n major | 24,\n nuint\n ]);\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint);\n buf.push([\n major | 25,\n nuint >>> 8,\n nuint & 255\n ]);\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint);\n buf.push([\n major | 26,\n nuint >>> 24 & 255,\n nuint >>> 16 & 255,\n nuint >>> 8 & 255,\n nuint & 255\n ]);\n } else {\n const buint = BigInt(uint);\n if (buint < uintBoundaries[4]) {\n const set = [\n major | 27,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ];\n let lo = Number(buint & BigInt(4294967295));\n let hi = Number(buint >> BigInt(32) & BigInt(4294967295));\n set[8] = lo & 255;\n lo = lo >> 8;\n set[7] = lo & 255;\n lo = lo >> 8;\n set[6] = lo & 255;\n lo = lo >> 8;\n set[5] = lo & 255;\n set[4] = hi & 255;\n hi = hi >> 8;\n set[3] = hi & 255;\n hi = hi >> 8;\n set[2] = hi & 255;\n hi = hi >> 8;\n set[1] = hi & 255;\n buf.push(set);\n } else {\n throw new Error(`${ decodeErrPrefix } encountered BigInt larger than allowable range`);\n }\n }\n}\nencodeUint.encodedSize = function encodedSize(token) {\n return encodeUintValue.encodedSize(token.value);\n};\nencodeUintValue.encodedSize = function encodedSize(uint) {\n if (uint < uintBoundaries[0]) {\n return 1;\n }\n if (uint < uintBoundaries[1]) {\n return 2;\n }\n if (uint < uintBoundaries[2]) {\n return 3;\n }\n if (uint < uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeUint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nexport function decodeNegint8(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeNegint16(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeNegint32(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5);\n}\nconst neg1b = BigInt(-1);\nconst pos1b = BigInt(1);\nexport function decodeNegint64(data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options);\n if (typeof int !== 'bigint') {\n const value = -1 - int;\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9);\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9);\n}\nexport function encodeNegint(buf, token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned);\n}\nencodeNegint.encodedSize = function encodedSize(token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n if (unsigned < uint.uintBoundaries[0]) {\n return 1;\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2;\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3;\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeNegint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport {\n compare,\n fromString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length);\n const buf = slice(data, pos + prefix, pos + prefix + length);\n return new Token(Type.bytes, buf, prefix + length);\n}\nexport function decodeBytesCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeBytes8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeBytes16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeBytes32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeBytes64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer bytes lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nfunction tokenBytes(token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value;\n }\n return token.encodedBytes;\n}\nexport function encodeBytes(buf, token) {\n const bytes = tokenBytes(token);\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length);\n buf.push(bytes);\n}\nencodeBytes.encodedSize = function encodedSize(token) {\n const bytes = tokenBytes(token);\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length;\n};\nencodeBytes.compareTokens = function compareTokens(tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2));\n};\nexport function compareBytes(b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);\n}", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport { encodeBytes } from './2bytes.js';\nimport {\n toString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length, options) {\n const totLength = prefix + length;\n assertEnoughData(data, pos, totLength);\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength);\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength);\n }\n return tok;\n}\nexport function decodeStringCompact(data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options);\n}\nexport function decodeString8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options);\n}\nexport function decodeString16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options);\n}\nexport function decodeString32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options);\n}\nexport function decodeString64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer string lengths not supported`);\n }\n return toToken(data, pos, 9, l, options);\n}\nexport const encodeString = encodeBytes;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix);\n}\nexport function decodeArrayCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeArray8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeArray16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeArray32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeArray64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer array lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeArrayIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeArray(buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value);\n}\nencodeArray.compareTokens = uint.encodeUint.compareTokens;\nencodeArray.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix);\n}\nexport function decodeMapCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeMap8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeMap16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeMap32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeMap64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer map lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeMapIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeMap(buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value);\n}\nencodeMap.compareTokens = uint.encodeUint.compareTokens;\nencodeMap.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nexport function decodeTagCompact(_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1);\n}\nexport function decodeTag8(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeTag16(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeTag32(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5);\n}\nexport function decodeTag64(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9);\n}\nexport function encodeTag(buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value);\n}\nencodeTag.compareTokens = uint.encodeUint.compareTokens;\nencodeTag.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport { decodeErrPrefix } from './common.js';\nimport { encodeUint } from './0uint.js';\nconst MINOR_FALSE = 20;\nconst MINOR_TRUE = 21;\nconst MINOR_NULL = 22;\nconst MINOR_UNDEFINED = 23;\nexport function decodeUndefined(_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${ decodeErrPrefix } undefined values are not supported`);\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1);\n }\n return new Token(Type.undefined, undefined, 1);\n}\nexport function decodeBreak(_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return new Token(Type.break, undefined, 1);\n}\nfunction createToken(value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${ decodeErrPrefix } NaN values are not supported`);\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${ decodeErrPrefix } Infinity values are not supported`);\n }\n }\n return new Token(Type.float, value, bytes);\n}\nexport function decodeFloat16(data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options);\n}\nexport function decodeFloat32(data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options);\n}\nexport function decodeFloat64(data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options);\n}\nexport function encodeFloat(buf, token, options) {\n const float = token.value;\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE]);\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE]);\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL]);\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED]);\n } else {\n let decoded;\n let success = false;\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 249;\n buf.push(ui8a.slice(0, 3));\n success = true;\n } else {\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n ui8a[0] = 250;\n buf.push(ui8a.slice(0, 5));\n success = true;\n }\n }\n }\n if (!success) {\n encodeFloat64(float);\n decoded = readFloat64(ui8a, 1);\n ui8a[0] = 251;\n buf.push(ui8a.slice(0, 9));\n }\n }\n}\nencodeFloat.encodedSize = function encodedSize(token, options) {\n const float = token.value;\n if (float === false || float === true || float === null || float === undefined) {\n return 1;\n }\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n let decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n return 3;\n }\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n return 5;\n }\n }\n return 9;\n};\nconst buffer = new ArrayBuffer(9);\nconst dataView = new DataView(buffer, 1);\nconst ui8a = new Uint8Array(buffer, 0);\nfunction encodeFloat16(inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 31744, false);\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 64512, false);\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 32256, false);\n } else {\n dataView.setFloat32(0, inp);\n const valu32 = dataView.getUint32(0);\n const exponent = (valu32 & 2139095040) >> 23;\n const mantissa = valu32 & 8388607;\n if (exponent === 255) {\n dataView.setUint16(0, 31744, false);\n } else if (exponent === 0) {\n dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);\n } else {\n const logicalExponent = exponent - 127;\n if (logicalExponent < -24) {\n dataView.setUint16(0, 0);\n } else if (logicalExponent < -14) {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false);\n } else {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);\n }\n }\n }\n}\nfunction readFloat16(ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${ decodeErrPrefix } not enough data for float16`);\n }\n const half = (ui8a[pos] << 8) + ui8a[pos + 1];\n if (half === 31744) {\n return Infinity;\n }\n if (half === 64512) {\n return -Infinity;\n }\n if (half === 32256) {\n return NaN;\n }\n const exp = half >> 10 & 31;\n const mant = half & 1023;\n let val;\n if (exp === 0) {\n val = mant * 2 ** -24;\n } else if (exp !== 31) {\n val = (mant + 1024) * 2 ** (exp - 25);\n } else {\n val = mant === 0 ? Infinity : NaN;\n }\n return half & 32768 ? -val : val;\n}\nfunction encodeFloat32(inp) {\n dataView.setFloat32(0, inp, false);\n}\nfunction readFloat32(ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${ decodeErrPrefix } not enough data for float32`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false);\n}\nfunction encodeFloat64(inp) {\n dataView.setFloat64(0, inp, false);\n}\nfunction readFloat64(ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${ decodeErrPrefix } not enough data for float64`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false);\n}\nencodeFloat.compareTokens = encodeUint.compareTokens;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport * as negint from './1negint.js';\nimport * as bytes from './2bytes.js';\nimport * as string from './3string.js';\nimport * as array from './4array.js';\nimport * as map from './5map.js';\nimport * as tag from './6tag.js';\nimport * as float from './7float.js';\nimport { decodeErrPrefix } from './common.js';\nimport { fromArray } from './byte-utils.js';\nfunction invalidMinor(data, pos, minor) {\n throw new Error(`${ decodeErrPrefix } encountered invalid minor (${ minor }) for major ${ data[pos] >>> 5 }`);\n}\nfunction errorer(msg) {\n return () => {\n throw new Error(`${ decodeErrPrefix } ${ msg }`);\n };\n}\nexport const jump = [];\nfor (let i = 0; i <= 23; i++) {\n jump[i] = invalidMinor;\n}\njump[24] = uint.decodeUint8;\njump[25] = uint.decodeUint16;\njump[26] = uint.decodeUint32;\njump[27] = uint.decodeUint64;\njump[28] = invalidMinor;\njump[29] = invalidMinor;\njump[30] = invalidMinor;\njump[31] = invalidMinor;\nfor (let i = 32; i <= 55; i++) {\n jump[i] = invalidMinor;\n}\njump[56] = negint.decodeNegint8;\njump[57] = negint.decodeNegint16;\njump[58] = negint.decodeNegint32;\njump[59] = negint.decodeNegint64;\njump[60] = invalidMinor;\njump[61] = invalidMinor;\njump[62] = invalidMinor;\njump[63] = invalidMinor;\nfor (let i = 64; i <= 87; i++) {\n jump[i] = bytes.decodeBytesCompact;\n}\njump[88] = bytes.decodeBytes8;\njump[89] = bytes.decodeBytes16;\njump[90] = bytes.decodeBytes32;\njump[91] = bytes.decodeBytes64;\njump[92] = invalidMinor;\njump[93] = invalidMinor;\njump[94] = invalidMinor;\njump[95] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 96; i <= 119; i++) {\n jump[i] = string.decodeStringCompact;\n}\njump[120] = string.decodeString8;\njump[121] = string.decodeString16;\njump[122] = string.decodeString32;\njump[123] = string.decodeString64;\njump[124] = invalidMinor;\njump[125] = invalidMinor;\njump[126] = invalidMinor;\njump[127] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 128; i <= 151; i++) {\n jump[i] = array.decodeArrayCompact;\n}\njump[152] = array.decodeArray8;\njump[153] = array.decodeArray16;\njump[154] = array.decodeArray32;\njump[155] = array.decodeArray64;\njump[156] = invalidMinor;\njump[157] = invalidMinor;\njump[158] = invalidMinor;\njump[159] = array.decodeArrayIndefinite;\nfor (let i = 160; i <= 183; i++) {\n jump[i] = map.decodeMapCompact;\n}\njump[184] = map.decodeMap8;\njump[185] = map.decodeMap16;\njump[186] = map.decodeMap32;\njump[187] = map.decodeMap64;\njump[188] = invalidMinor;\njump[189] = invalidMinor;\njump[190] = invalidMinor;\njump[191] = map.decodeMapIndefinite;\nfor (let i = 192; i <= 215; i++) {\n jump[i] = tag.decodeTagCompact;\n}\njump[216] = tag.decodeTag8;\njump[217] = tag.decodeTag16;\njump[218] = tag.decodeTag32;\njump[219] = tag.decodeTag64;\njump[220] = invalidMinor;\njump[221] = invalidMinor;\njump[222] = invalidMinor;\njump[223] = invalidMinor;\nfor (let i = 224; i <= 243; i++) {\n jump[i] = errorer('simple values are not supported');\n}\njump[244] = invalidMinor;\njump[245] = invalidMinor;\njump[246] = invalidMinor;\njump[247] = float.decodeUndefined;\njump[248] = errorer('simple values are not supported');\njump[249] = float.decodeFloat16;\njump[250] = float.decodeFloat32;\njump[251] = float.decodeFloat64;\njump[252] = invalidMinor;\njump[253] = invalidMinor;\njump[254] = invalidMinor;\njump[255] = float.decodeBreak;\nexport const quick = [];\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1);\n}\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1);\n}\nquick[64] = new Token(Type.bytes, new Uint8Array(0), 1);\nquick[96] = new Token(Type.string, '', 1);\nquick[128] = new Token(Type.array, 0, 1);\nquick[160] = new Token(Type.map, 0, 1);\nquick[244] = new Token(Type.false, false, 1);\nquick[245] = new Token(Type.true, true, 1);\nquick[246] = new Token(Type.null, null, 1);\nexport function quickEncodeToken(token) {\n switch (token.type) {\n case Type.false:\n return fromArray([244]);\n case Type.true:\n return fromArray([245]);\n case Type.null:\n return fromArray([246]);\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([64]);\n }\n return;\n case Type.string:\n if (token.value === '') {\n return fromArray([96]);\n }\n return;\n case Type.array:\n if (token.value === 0) {\n return fromArray([128]);\n }\n return;\n case Type.map:\n if (token.value === 0) {\n return fromArray([160]);\n }\n return;\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)]);\n }\n return;\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)]);\n }\n }\n}", "import { is } from './is.js';\nimport {\n Token,\n Type\n} from './token.js';\nimport { Bl } from './bl.js';\nimport { encodeErrPrefix } from './common.js';\nimport { quickEncodeToken } from './jump.js';\nimport { asU8A } from './byte-utils.js';\nimport { encodeUint } from './0uint.js';\nimport { encodeNegint } from './1negint.js';\nimport { encodeBytes } from './2bytes.js';\nimport { encodeString } from './3string.js';\nimport { encodeArray } from './4array.js';\nimport { encodeMap } from './5map.js';\nimport { encodeTag } from './6tag.js';\nimport { encodeFloat } from './7float.js';\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n};\nexport function makeCborEncoders() {\n const encoders = [];\n encoders[Type.uint.major] = encodeUint;\n encoders[Type.negint.major] = encodeNegint;\n encoders[Type.bytes.major] = encodeBytes;\n encoders[Type.string.major] = encodeString;\n encoders[Type.array.major] = encodeArray;\n encoders[Type.map.major] = encodeMap;\n encoders[Type.tag.major] = encodeTag;\n encoders[Type.float.major] = encodeFloat;\n return encoders;\n}\nconst cborEncoders = makeCborEncoders();\nconst buf = new Bl();\nclass Ref {\n constructor(obj, parent) {\n this.obj = obj;\n this.parent = parent;\n }\n includes(obj) {\n let p = this;\n do {\n if (p.obj === obj) {\n return true;\n }\n } while (p = p.parent);\n return false;\n }\n static createCheck(stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${ encodeErrPrefix } object contains circular references`);\n }\n return new Ref(obj, stack);\n }\n}\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n};\nconst typeEncoders = {\n number(obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj);\n } else if (obj >= 0) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n bigint(obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n Uint8Array(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj);\n },\n string(obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj);\n },\n boolean(obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false;\n },\n null(_obj, _typ, _options, _refStack) {\n return simpleTokens.null;\n },\n undefined(_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined;\n },\n ArrayBuffer(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj));\n },\n DataView(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));\n },\n Array(obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyArray,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyArray;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack);\n }\n if (options.addBreakTokens) {\n return [\n new Token(Type.array, obj.length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.array, obj.length),\n entries\n ];\n },\n Object(obj, typ, options, refStack) {\n const isMap = typ !== 'Object';\n const keys = isMap ? obj.keys() : Object.keys(obj);\n const length = isMap ? obj.size : keys.length;\n if (!length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyMap,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyMap;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ];\n }\n sortMapEntries(entries, options);\n if (options.addBreakTokens) {\n return [\n new Token(Type.map, length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.map, length),\n entries\n ];\n }\n};\ntypeEncoders.Map = typeEncoders.Object;\ntypeEncoders.Buffer = typeEncoders.Uint8Array;\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${ typ }Array`] = typeEncoders.DataView;\n}\nfunction objectToTokens(obj, options = {}, refStack) {\n const typ = is(obj);\n const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack);\n if (tokens != null) {\n return tokens;\n }\n }\n const typeEncoder = typeEncoders[typ];\n if (!typeEncoder) {\n throw new Error(`${ encodeErrPrefix } unsupported type: ${ typ }`);\n }\n return typeEncoder(obj, typ, options, refStack);\n}\nfunction sortMapEntries(entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter);\n }\n}\nfunction mapSorter(e1, e2) {\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type);\n }\n const major = keyToken1.type.major;\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);\n if (tcmp === 0) {\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone');\n }\n return tcmp;\n}\nfunction tokensToEncoded(buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options);\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options);\n }\n}\nfunction encodeCustom(data, encoders, options) {\n const tokens = objectToTokens(data, options);\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens);\n if (quickBytes) {\n return quickBytes;\n }\n const encoder = encoders[tokens.type.major];\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options);\n const buf = new Bl(size);\n encoder(buf, tokens, options);\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${ tokens } was wrong`);\n }\n return asU8A(buf.chunks[0]);\n }\n }\n buf.reset();\n tokensToEncoded(buf, tokens, encoders, options);\n return buf.toBytes(true);\n}\nfunction encode(data, options) {\n options = Object.assign({}, defaultEncodeOptions, options);\n return encodeCustom(data, cborEncoders, options);\n}\nexport {\n objectToTokens,\n encode,\n encodeCustom,\n Ref\n};", "import { decodeErrPrefix } from './common.js';\nimport { Type } from './token.js';\nimport {\n jump,\n quick\n} from './jump.js';\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n};\nclass Tokeniser {\n constructor(data, options = {}) {\n this.pos = 0;\n this.data = data;\n this.options = options;\n }\n done() {\n return this.pos >= this.data.length;\n }\n next() {\n const byt = this.data[this.pos];\n let token = quick[byt];\n if (token === undefined) {\n const decoder = jump[byt];\n if (!decoder) {\n throw new Error(`${ decodeErrPrefix } no decoder for major type ${ byt >>> 5 } (byte 0x${ byt.toString(16).padStart(2, '0') })`);\n }\n const minor = byt & 31;\n token = decoder(this.data, this.pos, minor, this.options);\n }\n this.pos += token.encodedLength;\n return token;\n }\n}\nconst DONE = Symbol.for('DONE');\nconst BREAK = Symbol.for('BREAK');\nfunction tokenToArray(token, tokeniser, options) {\n const arr = [];\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options);\n if (value === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed array`);\n }\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found array but not enough entries (got ${ i }, expected ${ token.value })`);\n }\n arr[i] = value;\n }\n return arr;\n}\nfunction tokenToMap(token, tokeniser, options) {\n const useMaps = options.useMaps === true;\n const obj = useMaps ? undefined : {};\n const m = useMaps ? new Map() : undefined;\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options);\n if (key === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed map`);\n }\n if (key === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no key], expected ${ token.value })`);\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${ decodeErrPrefix } non-string keys not supported (got ${ typeof key })`);\n }\n if (options.rejectDuplicateMapKeys === true) {\n if (useMaps && m.has(key) || !useMaps && key in obj) {\n throw new Error(`${ decodeErrPrefix } found repeat map key \"${ key }\"`);\n }\n }\n const value = tokensToObject(tokeniser, options);\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no value], expected ${ token.value })`);\n }\n if (useMaps) {\n m.set(key, value);\n } else {\n obj[key] = value;\n }\n }\n return useMaps ? m : obj;\n}\nfunction tokensToObject(tokeniser, options) {\n if (tokeniser.done()) {\n return DONE;\n }\n const token = tokeniser.next();\n if (token.type === Type.break) {\n return BREAK;\n }\n if (token.type.terminal) {\n return token.value;\n }\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options);\n }\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options);\n }\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options);\n return options.tags[token.value](tagged);\n }\n throw new Error(`${ decodeErrPrefix } tag not supported (${ token.value })`);\n }\n throw new Error('unsupported');\n}\nfunction decode(data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${ decodeErrPrefix } data to decode must be a Uint8Array`);\n }\n options = Object.assign({}, defaultDecodeOptions, options);\n const tokeniser = options.tokenizer || new Tokeniser(data, options);\n const decoded = tokensToObject(tokeniser, options);\n if (decoded === DONE) {\n throw new Error(`${ decodeErrPrefix } did not find any content to decode`);\n }\n if (decoded === BREAK) {\n throw new Error(`${ decodeErrPrefix } got unexpected break`);\n }\n if (!tokeniser.done()) {\n throw new Error(`${ decodeErrPrefix } too many terminals, data makes no sense`);\n }\n return decoded;\n}\nexport {\n Tokeniser,\n tokensToObject,\n decode\n};", "import * as ipns from 'ipns'\nimport { importKey } from '@libp2p/crypto/keys'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { TimeoutController } from 'timeout-abort-controller'\n\nconst log = logger('ipfs:ipns:republisher')\n\n/**\n * @typedef {import('@libp2p/interface-keys').PrivateKey} PrivateKey\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nconst minute = 60 * 1000\nconst hour = 60 * minute\n\nconst defaultBroadcastInterval = 4 * hour\nconst defaultRecordLifetime = 24 * hour\n\nexport class IpnsRepublisher {\n /**\n * @param {import('./publisher').IpnsPublisher} publisher\n * @param {import('interface-datastore').Datastore} datastore\n * @param {PeerId} peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} keychain\n * @param {object} options\n * @param {string} options.pass\n * @param {number} [options.initialBroadcastInterval]\n * @param {number} [options.broadcastInterval]\n */\n constructor (publisher, datastore, peerId, keychain, options = { pass: '' }) {\n this._publisher = publisher\n this._datastore = datastore\n this._peerId = peerId\n this._keychain = keychain\n this._options = options\n this._republishHandle = null\n }\n\n async start () { // eslint-disable-line require-await\n if (this._republishHandle) {\n throw errcode(new Error('republisher is already running'), 'ERR_REPUBLISH_ALREADY_RUNNING')\n }\n\n // TODO: this handler should be isolated in another module\n const republishHandle = {\n /** @type {null|(() => Promise)} */\n _task: null,\n /** @type {null|Promise} */\n _inflightTask: null,\n /** @type {null|NodeJS.Timeout} */\n _timeoutId: null,\n /**\n * @param {function(): number} period\n */\n runPeriodically: (period) => {\n republishHandle._timeoutId = setTimeout(async () => {\n republishHandle._timeoutId = null\n\n try {\n // @ts-expect-error - _task could be null\n republishHandle._inflightTask = republishHandle._task()\n await republishHandle._inflightTask\n\n // Schedule next\n if (republishHandle._task) {\n republishHandle.runPeriodically(period)\n }\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }, period())\n },\n cancel: async () => {\n // do not run again\n if (republishHandle._timeoutId != null) {\n clearTimeout(republishHandle._timeoutId)\n }\n republishHandle._task = null\n\n // wait for the currently in flight task to complete\n await republishHandle._inflightTask\n }\n }\n\n const { pass } = this._options\n let firstRun = true\n\n republishHandle._task = async () => {\n const timeoutController = new TimeoutController(30000)\n\n try {\n await this._republishEntries(this._peerId, pass, {\n signal: timeoutController.signal\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n republishHandle.runPeriodically(() => {\n if (firstRun) {\n firstRun = false\n return this._options.initialBroadcastInterval || minute\n }\n\n return this._options.broadcastInterval || defaultBroadcastInterval\n })\n\n this._republishHandle = republishHandle\n }\n\n async stop () {\n const republishHandle = this._republishHandle\n\n if (!republishHandle) {\n throw errcode(new Error('republisher is not running'), 'ERR_REPUBLISH_NOT_RUNNING')\n }\n\n this._republishHandle = null\n\n await republishHandle.cancel()\n }\n\n /**\n * @param {PeerId} peerId\n * @param {string} pass\n * @param {AbortOptions} options\n */\n async _republishEntries (peerId, pass, options) {\n // TODO: Should use list of published entries.\n // We can't currently *do* that because go uses this method for now.\n try {\n await this._republishEntry(peerId, options)\n } catch (/** @type {any} */ err) {\n const errMsg = 'cannot republish entry for the node\\'s private key'\n\n log.error(errMsg)\n return\n }\n\n // keychain needs pass to get the cryptographic keys\n if (pass) {\n try {\n const keys = await this._keychain.listKeys()\n\n for (const key of keys) {\n if (key.name === 'self') {\n continue\n }\n\n const pem = await this._keychain.exportKey(key.name, pass)\n const privKey = await importKey(pem, pass)\n const peerIdKey = await peerIdFromKeys(privKey.public.bytes, privKey.bytes)\n\n await this._republishEntry(peerIdKey, options)\n }\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }\n }\n\n /**\n * @param {PeerId} peerId\n * @param {AbortOptions} options\n */\n async _republishEntry (peerId, options) {\n try {\n const value = await this._getPreviousValue(peerId)\n await this._publisher.publishWithEOL(peerId, value, defaultRecordLifetime, options)\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NO_ENTRY_FOUND') {\n return\n }\n\n throw err\n }\n }\n\n /**\n * @param {PeerId} peerId\n */\n async _getPreviousValue (peerId) {\n if (!(isPeerId(peerId))) {\n throw errcode(new Error('invalid peer ID'), 'ERR_INVALID_PEER_ID')\n }\n\n try {\n const dsVal = await this._datastore.get(ipns.getLocalKey(peerId.toBytes()))\n\n if (!(dsVal instanceof Uint8Array)) {\n throw errcode(new Error(\"found ipns record that we couldn't process\"), 'ERR_INVALID_IPNS_RECORD')\n }\n\n // unmarshal data\n try {\n const record = ipns.unmarshal(dsVal)\n\n return record.value\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(new Error('found ipns record that we couldn\\'t convert to a value'), 'ERR_INVALID_IPNS_RECORD')\n }\n } catch (/** @type {any} */ err) {\n // error handling\n // no need to republish\n if (err && err.notFound) {\n throw errcode(new Error(`no previous entry for record with id: ${peerId.toString()}`), 'ERR_NO_ENTRY_FOUND')\n }\n\n throw err\n }\n }\n}\n", "import * as ipns from 'ipns'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport * as Errors from 'datastore-core/errors'\nimport { ipnsValidator } from 'ipns/validator'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nconst log = logger('ipfs:ipns:resolver')\n\nconst ERR_NOT_FOUND = Errors.notFoundError().code\n\nconst defaultMaximumRecursiveDepth = 32\n\nexport class IpnsResolver {\n /**\n * @param {import('ipfs-core-types/src/utils').BufferStore} routing\n */\n constructor (routing) {\n this._routing = routing\n }\n\n /**\n * @param {string} name\n * @param {object} [options]\n * @param {boolean} [options.recursive]\n * @param {AbortSignal} [options.signal]\n */\n async resolve (name, options = {}) {\n if (typeof name !== 'string') {\n throw errcode(new Error('invalid name'), 'ERR_INVALID_NAME')\n }\n\n const recursive = options.recursive && options.recursive.toString() === 'true'\n\n const nameSegments = name.split('/')\n\n if (nameSegments.length !== 3 || nameSegments[0] !== '') {\n throw errcode(new Error('invalid name'), 'ERR_INVALID_NAME')\n }\n\n const key = nameSegments[2]\n\n // Define a maximum depth if recursive option enabled\n let depth = Infinity\n\n if (recursive) {\n depth = defaultMaximumRecursiveDepth\n }\n\n const res = await this.resolver(key, depth, options)\n\n log(`${name} was locally resolved correctly`)\n return res\n }\n\n /**\n * Recursive resolver according to the specified depth\n *\n * @param {string} name\n * @param {number} depth\n * @param {AbortOptions} options\n * @returns {Promise}\n */\n async resolver (name, depth, options) {\n // Exceeded recursive maximum depth\n if (depth === 0) {\n const errMsg = `could not resolve name (recursion limit of ${defaultMaximumRecursiveDepth} exceeded)`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_RESOLVE_RECURSION_LIMIT')\n }\n\n const res = await this._resolveName(name, options)\n const nameSegments = res.split('/')\n\n // If obtained a ipfs cid or recursive option is disabled\n if (nameSegments[1] === 'ipfs' || !depth) {\n return res\n }\n\n // continue recursively until depth equals 0\n return this.resolver(nameSegments[2], depth - 1, options)\n }\n\n /**\n * Resolve ipns entries from the provided routing\n *\n * @param {string} name\n * @param {AbortOptions} options\n */\n async _resolveName (name, options) {\n const peerId = peerIdFromString(name)\n const routingKey = ipns.peerIdToRoutingKey(peerId)\n let record\n\n try {\n record = await this._routing.get(routingKey, options)\n } catch (/** @type {any} */ err) {\n log.error('could not get record from routing', err)\n\n if (err.code === ERR_NOT_FOUND) {\n throw errcode(new Error(`record requested for ${name} was not found in the network`), 'ERR_NO_RECORD_FOUND')\n }\n\n throw errcode(new Error(`unexpected error getting the ipns record ${peerId.toString()}`), 'ERR_UNEXPECTED_ERROR_GETTING_RECORD')\n }\n\n // We should have the public key by now (inline, or in the entry)\n return this._validateRecord(peerId, record)\n }\n\n /**\n * Validate a resolved record\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} record\n */\n async _validateRecord (peerId, record) {\n // IPNS entry validation\n await ipnsValidator(uint8ArrayConcat([\n uint8ArrayFromString('/ipns/'),\n peerId.toBytes()\n ]), record)\n\n const ipnsEntry = ipns.unmarshal(record)\n\n return uint8ArrayToString(ipnsEntry.value)\n }\n}\n", "import errCode from 'err-code'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { parseRFC3339, extractPublicKey, ipnsEntryDataForV2Sig, unmarshal, peerIdFromRoutingKey, parseCborData } from './utils.js'\nimport * as ERRORS from './errors.js'\nimport type { IPNSEntry } from './index.js'\nimport type { PublicKey } from '@libp2p/interface-keys'\nimport type { ValidateFn } from '@libp2p/interface-dht'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipns:validator')\n\n/**\n * Validates the given ipns entry against the given public key\n */\nexport const validate = async (publicKey: PublicKey, entry: IPNSEntry): Promise => {\n const { value, validityType, validity } = entry\n\n let dataForSignature: Uint8Array\n let signature: Uint8Array\n\n // Check v2 signature if it's available, otherwise use the v1 signature\n if ((entry.signatureV2 != null) && (entry.data != null)) {\n signature = entry.signatureV2\n dataForSignature = ipnsEntryDataForV2Sig(entry.data)\n\n validateCborDataMatchesPbData(entry)\n } else {\n throw errCode(new Error('missing data or signatureV2'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n // Validate Signature\n let isValid\n try {\n isValid = await publicKey.verify(dataForSignature, signature)\n } catch (err) {\n isValid = false\n }\n if (!isValid) {\n log.error('record signature verification failed')\n throw errCode(new Error('record signature verification failed'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n // Validate according to the validity type\n if (validity != null && validityType === IpnsEntry.ValidityType.EOL) {\n let validityDate\n\n try {\n validityDate = parseRFC3339(uint8ArrayToString(validity))\n } catch (e) {\n log.error('unrecognized validity format (not an rfc3339 format)')\n throw errCode(new Error('unrecognized validity format (not an rfc3339 format)'), ERRORS.ERR_UNRECOGNIZED_FORMAT)\n }\n\n if (validityDate.getTime() < Date.now()) {\n log.error('record has expired')\n throw errCode(new Error('record has expired'), ERRORS.ERR_IPNS_EXPIRED_RECORD)\n }\n } else if (validityType != null) {\n log.error('unrecognized validity type')\n throw errCode(new Error('unrecognized validity type'), ERRORS.ERR_UNRECOGNIZED_VALIDITY)\n }\n\n log('ipns entry for %b is valid', value)\n}\n\nconst validateCborDataMatchesPbData = (entry: IPNSEntry): void => {\n if (entry.data == null) {\n throw errCode(new Error('Record data is missing'), ERRORS.ERR_INVALID_RECORD_DATA)\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value)) {\n throw errCode(new Error('Field \"value\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity)) {\n throw errCode(new Error('Field \"validity\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw errCode(new Error('Field \"validityType\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (data.Sequence !== entry.sequence) {\n throw errCode(new Error('Field \"sequence\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (data.TTL !== entry.ttl) {\n throw errCode(new Error('Field \"ttl\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n}\n\nexport const ipnsValidator: ValidateFn = async (key, marshalledData) => {\n const peerId = peerIdFromRoutingKey(key)\n const receivedEntry = unmarshal(marshalledData)\n\n // extract public key\n const pubKey = await extractPublicKey(peerId, receivedEntry)\n\n // Record validation\n await validate(pubKey, receivedEntry)\n}\n", "import hashlru from 'hashlru'\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n * @todo move this to ipfs-utils or it's own package\n *\n * @template T\n * @class TLRU\n */\nexport class TLRU {\n /**\n * Creates an instance of TLRU.\n *\n * @param {number} maxSize\n */\n constructor (maxSize) {\n this.lru = hashlru(maxSize)\n }\n\n /**\n * Get the value from the a key\n *\n * @param {string} key\n * @returns {T|undefined}\n * @memberof TLoRU\n */\n get (key) {\n const value = this.lru.get(key)\n if (value) {\n if ((value.expire) && (value.expire < Date.now())) {\n this.lru.remove(key)\n return undefined\n }\n return value.value\n }\n return undefined\n }\n\n /**\n * Set a key value pair\n *\n * @param {string} key\n * @param {T} value\n * @param {number} ttl - in miliseconds\n * @returns {void}\n */\n set (key, value, ttl) {\n this.lru.set(key, { value, expire: Date.now() + ttl })\n }\n\n /**\n * Find if the cache has the key\n *\n * @param {string} key\n * @returns {boolean}\n */\n has (key) {\n const value = this.get(key)\n if (value) {\n return true\n }\n return false\n }\n\n /**\n * Remove key\n *\n * @param {string} key\n */\n remove (key) {\n this.lru.remove(key)\n }\n\n /**\n * Clears the cache\n *\n * @memberof TLRU\n */\n clear () {\n this.lru.clear()\n }\n}\n", "\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nexport default async function all (source: AsyncIterable|Iterable): Promise {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n", "\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nexport const sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @param {string} s\n * @param {string} r\n */\nexport const replaceStartWith = (s, r) => {\n const matcher = new RegExp('^' + r)\n return s.replace(matcher, '')\n}\n", "/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nexport default async function drain (source: AsyncIterable|Iterable): Promise {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n}\n", "\n/**\n * Filters the passed (async) iterable by using the filter function\n */\nexport default async function * filter (source: AsyncIterable|Iterable, fn: (val: T) => boolean|Promise): AsyncGenerator {\n for await (const entry of source) {\n if (await fn(entry)) {\n yield entry\n }\n }\n}\n", "\n/**\n * Stop iteration after n items have been received\n */\nexport default async function * take (source: AsyncIterable|Iterable, limit: number): AsyncGenerator {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n}\n", "import { sortAll } from './utils.js'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\n\n/**\n * @typedef {import('interface-store').Options} Options\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Batch} Batch\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Datastore}\n */\nexport class BaseDatastore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\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\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {Key[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\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 /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (e) =>\n e.key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (key) =>\n key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key) => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nexport function logger (name: string): Logger {\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace: debug(`${name}:trace`)\n })\n}\n\nexport function disable () {\n debug.disable()\n}\n\nexport function enable (namespaces: string) {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string) {\n return debug.enabled(namespaces)\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nimport type { Next } from './index.js'\n\nclass FixedFIFO {\n public buffer: Array | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO | null\n\n constructor (hwm: number) {\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\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\n push (data: Next) {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift () {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty () {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO\n private tail: FixedFIFO\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next) {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\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\n shift () {\n let val = this.tail.shift()\n\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\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty () {\n return this.head.isEmpty()\n }\n}\n", "/**\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 */\n\nimport { FIFO } from './fifo.js'\n\nexport interface Next {\n done?: boolean\n error?: Error\n value?: T\n}\n\ninterface BasePushable {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end: (err?: Error) => this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push: (value: T) => this\n next: () => Promise>\n return: () => { done: boolean }\n throw: (err: Error) => { done: boolean }\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable extends AsyncIterable, BasePushable {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV extends AsyncIterable, BasePushable {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?: (err?: Error) => void\n}\n\ntype NextResult = { done: false, value: T} | { done: true }\n\ninterface getNext { (buffer: FIFO): NextResult }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable (options?: BytePushableOptions): Pushable\nexport function pushable (options: ObjectPushableOptions): Pushable\nexport function pushable (options: Options = {}): Pushable {\n const getNext = (buffer: FIFO): NextResult => {\n const next: Next | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error\n value: next.value\n }\n }\n\n return _pushable>(getNext, options)\n}\n\nexport function pushableV (options?: BytePushableOptions): PushableV\nexport function pushableV (options: ObjectPushableOptions): PushableV\nexport function pushableV (options: Options = {}): PushableV {\n const getNext = (buffer: FIFO): NextResult => {\n let next: Next | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable>(getNext, options)\n}\n\nfunction _pushable (getNext: getNext, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO()\n let pushable: any\n let onNext: ((next: Next) => ReturnType) | null\n let ended: boolean\n\n const waitNext = async (): Promise> => {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise((resolve, reject) => {\n onNext = (next: Next) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n }\n\n const bufferNext = (next: Next) => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error) => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType) => {\n if (ended) {\n return pushable\n }\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\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error) => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = () => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error) => {\n end(err)\n\n return { done: true }\n }\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 }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n }\n }\n\n return pushable\n}\n", "import { BaseDatastore } from './base.js'\nimport * as Errors from './errors.js'\nimport { logger } from '@libp2p/logger'\nimport { pushable } from 'it-pushable'\nimport drain from 'it-drain'\n\nconst log = logger('datastore:core:tiered')\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} Options\n * @typedef {import('interface-datastore').Batch} Batch\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n */\n\n/**\n * @template TEntry\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * A datastore that can combine multiple stores. Puts and deletes\n * will write through to all datastores. Has and get will\n * try each store sequentially. Query will always try the\n * last one first.\n *\n */\nexport class TieredDatastore extends BaseDatastore {\n /**\n * @param {Datastore[]} stores\n */\n constructor (stores) {\n super()\n\n this.stores = stores.slice()\n }\n\n async open () {\n try {\n await Promise.all(this.stores.map((store) => store.open()))\n } catch (/** @type {any} */ err) {\n throw Errors.dbOpenFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} value\n * @param {Options} [options]\n */\n async put (key, value, options) {\n try {\n await Promise.all(this.stores.map(store => store.put(key, value, options)))\n } catch (/** @type {any} */ err) {\n throw Errors.dbWriteFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n async get (key, options) {\n for (const store of this.stores) {\n try {\n const res = await store.get(key, options)\n if (res) return res\n } catch (err) {\n log.error(err)\n }\n }\n throw Errors.notFoundError()\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n async has (key, options) {\n for (const s of this.stores) {\n if (await s.has(key, options)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n async delete (key, options) {\n try {\n await Promise.all(this.stores.map(store => store.delete(key, options)))\n } catch (/** @type {any} */ err) {\n throw Errors.dbDeleteFailedError(err)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n let error\n const pushables = this.stores.map(store => {\n const source = pushable({\n objectMode: true\n })\n\n drain(store.putMany(source, options))\n .catch(err => {\n // store threw while putting, make sure we bubble the error up\n error = err\n })\n\n return source\n })\n\n try {\n for await (const pair of source) {\n if (error) {\n throw error\n }\n\n pushables.forEach(p => p.push(pair))\n\n yield pair\n }\n } finally {\n pushables.forEach(p => p.end())\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n let error\n const pushables = this.stores.map(store => {\n const source = pushable({\n objectMode: true\n })\n\n drain(store.deleteMany(source, options))\n .catch(err => {\n // store threw while deleting, make sure we bubble the error up\n error = err\n })\n\n return source\n })\n\n try {\n for await (const key of source) {\n if (error) {\n throw error\n }\n\n pushables.forEach(p => p.push(key))\n\n yield key\n }\n } finally {\n pushables.forEach(p => p.end())\n }\n }\n\n async close () {\n await Promise.all(this.stores.map(store => store.close()))\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n const batches = this.stores.map(store => store.batch())\n\n return {\n put: (key, value) => {\n batches.forEach(b => b.put(key, value))\n },\n delete: (key) => {\n batches.forEach(b => b.delete(key))\n },\n commit: async (options) => {\n for (const batch of batches) {\n await batch.commit(options)\n }\n }\n }\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n return this.stores[this.stores.length - 1].query(q, options)\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n return this.stores[this.stores.length - 1].queryKeys(q, options)\n }\n}\n", "import { TieredDatastore } from 'datastore-core/tiered'\nimport get from 'dlv'\nimport { IpnsPubsubDatastore } from './pubsub-datastore.js'\nimport { OfflineDatastore } from './offline-datastore.js'\nimport { DHTDatastore } from './dht-datastore.js'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\n/**\n * @param {object} arg\n * @param {import('libp2p').Libp2p} arg.libp2p\n * @param {import('ipfs-repo').IPFSRepo} arg.repo\n * @param {import('@libp2p/interface-peer-id').PeerId} arg.peerId\n * @param {object} arg.options\n */\nexport function createRouting ({ libp2p, repo, peerId, options }) {\n // Setup online routing for IPNS with a tiered routing composed by a DHT and a Pubsub router (if properly enabled)\n /** @type {any[]} */\n const ipnsStores = []\n\n // Add IPNS pubsub if enabled\n let pubsubDs\n if (get(options, 'EXPERIMENTAL.ipnsPubsub', false)) {\n pubsubDs = new IpnsPubsubDatastore(libp2p.pubsub, repo.datastore, peerId)\n ipnsStores.push(pubsubDs)\n }\n\n // Add DHT datastore if enabled\n if (get(options, 'offline', false) !== true && ['dht', 'dhtclient', 'dhtserver'].includes(get(options, 'config.Routing.Type', 'none'))) {\n ipnsStores.push(new DHTDatastore(libp2p.dht))\n }\n\n // Add an offline datastore if we are offline or no other datastores are configured\n if (get(options, 'offline', false) || ipnsStores.length === 0) {\n const offlineDatastore = new OfflineDatastore(repo.datastore)\n ipnsStores.push(offlineDatastore)\n }\n\n // Create ipns routing with a set of datastores\n return new TieredDatastore(ipnsStores)\n}\n", "import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { parseRFC3339 } from './utils.js'\nimport type { SelectFn } from '@libp2p/interface-dht'\n\nexport const ipnsSelector: SelectFn = (key, data) => {\n const entries = data.map((buf, index) => ({\n entry: IpnsEntry.decode(buf),\n index\n }))\n\n entries.sort((a, b) => {\n // having a newer signature version is better than an older signature version\n if (a.entry.signatureV2 != null && b.entry.signatureV2 == null) {\n return -1\n } else if (a.entry.signatureV2 == null && b.entry.signatureV2 != null) {\n return 1\n }\n\n const aSeq = a.entry.sequence ?? 0n\n const bSeq = b.entry.sequence ?? 0n\n\n // choose later sequence number\n if (aSeq > bSeq) {\n return -1\n } else if (aSeq < bSeq) {\n return 1\n }\n\n const aValidty = a.entry.validity ?? new Uint8Array(0)\n const bValidty = b.entry.validity ?? new Uint8Array(0)\n\n // choose longer lived record if sequence numbers the same\n const entryAValidityDate = parseRFC3339(uint8ArrayToString(aValidty))\n const entryBValidityDate = parseRFC3339(uint8ArrayToString(bValidty))\n\n if (entryAValidityDate.getTime() > entryBValidityDate.getTime()) {\n return -1\n }\n\n if (entryAValidityDate.getTime() < entryBValidityDate.getTime()) {\n return 1\n }\n\n return 0\n })\n\n return entries[0].index\n}\n", "import { Key } from 'interface-datastore/key'\n// @ts-expect-error readme is unused\n// eslint-disable-next-line no-unused-vars\nimport readme from './shard-readme.js'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('./types').Shard} Shard\n */\n\nexport const PREFIX = '/repo/flatfs/shard/'\nexport const SHARDING_FN = 'SHARDING'\nexport const README_FN = '_README'\n\n/**\n * @implements {Shard}\n */\nexport class ShardBase {\n /**\n * @param {any} param\n */\n constructor (param) {\n this.param = param\n this.name = 'base'\n this._padding = ''\n }\n\n /**\n * @param {string} s\n */\n fun (s) {\n return 'implement me'\n }\n\n toString () {\n return `${PREFIX}v1/${this.name}/${this.param}`\n }\n}\n/**\n * @implements {Shard}\n */\nexport class Prefix extends ShardBase {\n /**\n * @param {number} prefixLen\n */\n constructor (prefixLen) {\n super(prefixLen)\n this._padding = ''.padStart(prefixLen, '_')\n this.name = 'prefix'\n }\n\n /**\n * @param {string} noslash\n */\n fun (noslash) {\n return (noslash + this._padding).slice(0, this.param)\n }\n}\n\nexport class Suffix extends ShardBase {\n /**\n * @param {number} suffixLen\n */\n constructor (suffixLen) {\n super(suffixLen)\n this._padding = ''.padStart(suffixLen, '_')\n this.name = 'suffix'\n }\n\n /**\n * @param {string} noslash\n */\n fun (noslash) {\n const s = this._padding + noslash\n return s.slice(s.length - this.param)\n }\n}\n\nexport class NextToLast extends ShardBase {\n /**\n * @param {number} suffixLen\n */\n constructor (suffixLen) {\n super(suffixLen)\n this._padding = ''.padStart(suffixLen + 1, '_')\n this.name = 'next-to-last'\n }\n\n /**\n * @param {string} noslash\n */\n fun (noslash) {\n const s = this._padding + noslash\n const offset = s.length - this.param - 1\n return s.slice(offset, offset + this.param)\n }\n}\n\n/**\n * Convert a given string to the matching sharding function.\n *\n * @param {string} str\n * @returns {Shard}\n */\nexport function parseShardFun (str) {\n str = str.trim()\n\n if (str.length === 0) {\n throw new Error('empty shard string')\n }\n\n if (!str.startsWith(PREFIX)) {\n throw new Error(`invalid or no path prefix: ${str}`)\n }\n\n const parts = str.slice(PREFIX.length).split('/')\n const version = parts[0]\n\n if (version !== 'v1') {\n throw new Error(`expect 'v1' version, got '${version}'`)\n }\n\n const name = parts[1]\n\n if (!parts[2]) {\n throw new Error('missing param')\n }\n\n const param = parseInt(parts[2], 10)\n\n switch (name) {\n case 'prefix':\n return new Prefix(param)\n case 'suffix':\n return new Suffix(param)\n case 'next-to-last':\n return new NextToLast(param)\n default:\n throw new Error(`unkown sharding function: ${name}`)\n }\n}\n\n/**\n * @param {string | Uint8Array} path\n * @param {Datastore} store\n */\nexport const readShardFun = async (path, store) => {\n const key = new Key(path).child(new Key(SHARDING_FN))\n // @ts-ignore\n const get = typeof store.getRaw === 'function' ? store.getRaw.bind(store) : store.get.bind(store)\n const res = await get(key)\n return parseShardFun(new TextDecoder().decode(res || '').trim())\n}\n\nexport { default as readme } from './shard-readme.js'\n", "import { BaseDatastore } from './base.js'\nimport { Key } from 'interface-datastore/key'\nimport * as Errors from './errors.js'\n\n/**\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-store').Options} Options\n */\n\n/**\n * @class MemoryDatastore\n * @implements {Datastore}\n */\nexport class MemoryDatastore extends BaseDatastore {\n constructor () {\n super()\n\n /** @type {Record} */\n this.data = {}\n }\n\n open () {\n return Promise.resolve()\n }\n\n close () {\n return Promise.resolve()\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n */\n async put (key, val) { // eslint-disable-line require-await\n this.data[key.toString()] = val\n }\n\n /**\n * @param {Key} key\n */\n async get (key) {\n const exists = await this.has(key)\n if (!exists) throw Errors.notFoundError()\n return this.data[key.toString()]\n }\n\n /**\n * @param {Key} key\n */\n async has (key) { // eslint-disable-line require-await\n return this.data[key.toString()] !== undefined\n }\n\n /**\n * @param {Key} key\n */\n async delete (key) { // eslint-disable-line require-await\n delete this.data[key.toString()]\n }\n\n async * _all () {\n yield * Object.entries(this.data)\n .map(([key, value]) => ({ key: new Key(key), value }))\n }\n\n async * _allKeys () {\n yield * Object.entries(this.data)\n .map(([key]) => new Key(key))\n }\n}\n", "/**\n * Takes an (async) iterable and returns one with each item mapped by the passed\n * function\n */\nexport default async function * map (source: AsyncIterable|Iterable, func: (val: I) => O | Promise): AsyncGenerator {\n for await (const val of source) {\n yield func(val)\n }\n}\n", "import { pushable } from 'it-pushable'\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nexport default async function * merge (...sources: Array|Iterable>): AsyncGenerator {\n const output = pushable({\n objectMode: true\n })\n\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n output.push(item)\n }\n })\n )\n\n output.end()\n } catch (err: any) {\n output.end(err)\n }\n })\n\n yield * output\n}\n", "import { pushable } from 'it-pushable'\nimport merge from 'it-merge'\nimport type * as it from 'it-stream-types'\n\nexport const rawPipe = (...fns: any) => {\n let res\n while (fns.length > 0) {\n res = fns.shift()(res)\n }\n return res\n}\n\nexport const isIterable = (obj: any): obj is it.Source => {\n return obj != null && (\n typeof obj[Symbol.asyncIterator] === 'function' ||\n typeof obj[Symbol.iterator] === 'function' ||\n typeof obj.next === 'function' // Probably, right?\n )\n}\n\nexport const isDuplex = > (obj: any): obj is it.Duplex => {\n return obj != null && typeof obj.sink === 'function' && isIterable(obj.source)\n}\n\nconst duplexPipelineFn = (duplex: it.Duplex) => {\n return (source: any): it.Source => {\n const p = duplex.sink(source)\n\n if (p.then != null) {\n const stream = pushable({\n objectMode: true\n })\n p.then(() => {\n stream.end()\n }, (err: Error) => {\n stream.end(err)\n })\n\n const sourceWrap = async function * () {\n yield * duplex.source\n stream.end()\n }\n\n return merge(stream, sourceWrap())\n }\n\n return duplex.source\n }\n}\n\nexport type Source = it.Source | (() => it.Source) | it.Duplex\nexport type Transform = it.Transform | it.Duplex\nexport type Sink = it.Sink | it.Duplex\n\nexport function pipe (\n first: Source\n): it.Source\n\nexport function pipe (\n first: Source,\n second: Sink\n): B\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Sink\n): C\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Sink\n): D\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Sink\n): E\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Sink\n): F\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Sink\n): G\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Sink\n): H\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Sink\n): I\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Transform,\n tenth: Sink\n): J\n\nexport function pipe (first: any, ...rest: any[]): any {\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 } else if (isIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\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\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\n return rawPipe(...fns)\n}\n", "import { Key } from 'interface-datastore'\nimport {\n readShardFun,\n SHARDING_FN,\n README_FN,\n readme\n} from './shard.js'\nimport { BaseDatastore } from './base.js'\nimport { KeyTransformDatastore } from './keytransform.js'\nimport * as Errors from './errors.js'\n\nconst shardKey = new Key(SHARDING_FN)\nconst shardReadmeKey = new Key(README_FN)\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} Options\n * @typedef {import('interface-datastore').Batch} Batch\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').QueryFilter} QueryFilter\n * @typedef {import('interface-datastore').QueryOrder} QueryOrder\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').KeyQueryFilter} KeyQueryFilter\n * @typedef {import('interface-datastore').KeyQueryOrder} KeyQueryOrder\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('./types').Shard} Shard\n *\n */\n/**\n * @template TValue\n * @typedef {import('interface-store').Await } Await\n */\n\n/**\n * @template TEntry\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * Backend independent abstraction of go-ds-flatfs.\n *\n * Wraps another datastore such that all values are stored\n * sharded according to the given sharding function.\n */\nexport class ShardingDatastore extends BaseDatastore {\n /**\n * @param {Datastore} store\n * @param {Shard} shard\n */\n constructor (store, shard) {\n super()\n\n this.child = new KeyTransformDatastore(store, {\n convert: this._convertKey.bind(this),\n invert: this._invertKey.bind(this)\n })\n this.shard = shard\n }\n\n async open () {\n await this.child.open()\n\n this.shard = await ShardingDatastore.create(this.child, this.shard)\n }\n\n /**\n * @param {Key} key\n */\n _convertKey (key) {\n const s = key.toString()\n if (s === shardKey.toString() || s === shardReadmeKey.toString()) {\n return key\n }\n\n const parent = new Key(this.shard.fun(s))\n return parent.child(key)\n }\n\n /**\n * @param {Key} key\n */\n _invertKey (key) {\n const s = key.toString()\n if (s === shardKey.toString() || s === shardReadmeKey.toString()) {\n return key\n }\n return Key.withNamespaces(key.list().slice(1))\n }\n\n /**\n * @deprecated\n * @param {Datastore} store\n * @param {Shard} shard\n */\n static async createOrOpen (store, shard) {\n try {\n await ShardingDatastore.create(store, shard)\n } catch (/** @type {any} */ err) {\n if (err && err.message !== 'datastore exists') throw err\n }\n return ShardingDatastore.open(store)\n }\n\n /**\n * @deprecated\n * @param {Datastore} store\n */\n static async open (store) {\n const shard = await readShardFun('/', store)\n return new ShardingDatastore(store, shard)\n }\n\n /**\n * @param {Datastore} store\n * @param {Shard} shard\n */\n static async create (store, shard) {\n const hasShard = await store.has(shardKey)\n if (!hasShard && !shard) {\n throw Errors.dbOpenFailedError(Error('Shard is required when datastore doesn\\'t have a shard key already.'))\n }\n if (!hasShard) {\n // @ts-ignore i have no idea what putRaw is or saw any implementation\n const put = typeof store.putRaw === 'function' ? store.putRaw.bind(store) : store.put.bind(store)\n await Promise.all([\n put(shardKey, new TextEncoder().encode(shard.toString() + '\\n')),\n put(shardReadmeKey, new TextEncoder().encode(readme))\n ])\n\n return shard\n }\n\n // test shards\n const diskShard = await readShardFun('/', store)\n const a = (diskShard || '').toString()\n const b = shard.toString()\n if (a !== b) {\n throw new Error(`specified fun ${b} does not match repo shard fun ${a}`)\n }\n return diskShard\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n */\n put (key, val, options) {\n return this.child.put(key, val, options)\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n get (key, options) {\n return this.child.get(key, options)\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n has (key, options) {\n return this.child.has(key, options)\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n delete (key, options) {\n return this.child.delete(key, options)\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n yield * this.child.putMany(source, options)\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n yield * this.child.getMany(source, options)\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n yield * this.child.deleteMany(source, options)\n }\n\n batch () {\n return this.child.batch()\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n /** @type {Query} */\n const tq = {\n ...q,\n filters: [\n /** @type {QueryFilter} */\n ({ key }) => key.toString() !== shardKey.toString(),\n /** @type {QueryFilter} */\n ({ key }) => key.toString() !== shardReadmeKey.toString()\n ].concat(q.filters || [])\n }\n\n return this.child.query(tq, options)\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n /** @type {KeyQuery} */\n const tq = {\n ...q,\n filters: [\n /** @type {KeyQueryFilter} */\n key => key.toString() !== shardKey.toString(),\n /** @type {KeyQueryFilter} */\n key => key.toString() !== shardReadmeKey.toString()\n ].concat(q.filters || [])\n }\n\n return this.child.queryKeys(tq, options)\n }\n\n close () {\n return this.child.close()\n }\n}\n", "\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 */\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static get code (): string {\n return 'ABORT_ERR'\n }\n\n static get type (): string {\n return 'aborted'\n }\n}\n\nexport class CodeError = Record> extends Error {\n public readonly props: T\n\n constructor (\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(message)\n\n this.name = props?.name ?? 'CodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\n/**\n * @typedef {import('interface-datastore').Key} Key\n */\n\nconst namespace = '/record/'\n\n/**\n * @param {Uint8Array} buf\n */\nexport function encodeBase32 (buf) {\n return uint8ArrayToString(buf, 'base32')\n}\n\n/**\n * converts a binary record key to a pubsub topic key\n *\n * @param {Uint8Array | string} key\n */\nexport function keyToTopic (key) {\n // Record-store keys are arbitrary binary. However, pubsub requires UTF-8 string topic IDs\n // Encodes to \"/record/base64url(key)\"\n if (typeof key === 'string' || key instanceof String) {\n key = uint8ArrayFromString(key.toString())\n }\n\n const b64url = uint8ArrayToString(key, 'base64url')\n\n return `${namespace}${b64url}`\n}\n\n/**\n * converts a pubsub topic key to a binary record key\n *\n * @param {string} topic\n */\nexport function topicToKey (topic) {\n if (topic.substring(0, namespace.length) !== namespace) {\n throw new CodeError('topic received is not from a record', 'ERR_TOPIC_IS_NOT_FROM_RECORD_NAMESPACE')\n }\n\n const key = topic.substring(namespace.length)\n\n return uint8ArrayFromString(key, 'base64url')\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "import { Key } from 'interface-datastore'\nimport { BaseDatastore } from 'datastore-core'\nimport { encodeBase32, keyToTopic, topicToKey } from './utils.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('datastore-pubsub:publisher')\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('./types').SubscriptionKeyFn} SubscriptionKeyFn\n * @typedef {import('@libp2p/interface-pubsub').Message} PubSubMessage\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\n// DatastorePubsub is responsible for providing an api for pubsub to be used as a datastore with\n// [TieredDatastore]{@link https://github.com/ipfs/js-datastore-core/blob/master/src/tiered.js}\nexport class PubSubDatastore extends BaseDatastore {\n /**\n * Creates an instance of DatastorePubsub.\n *\n * @param {import('@libp2p/interface-pubsub').PubSub} pubsub - pubsub implementation\n * @param {import('interface-datastore').Datastore} datastore - datastore instance\n * @param {PeerId} peerId - peer-id instance\n * @param {import('@libp2p/interface-dht').ValidateFn} validator - validator function\n * @param {import('@libp2p/interface-dht').SelectFn} selector - selector function\n * @param {SubscriptionKeyFn} [subscriptionKeyFn] - function to manipulate the key topic received before processing it\n * @memberof DatastorePubsub\n */\n constructor (pubsub, datastore, peerId, validator, selector, subscriptionKeyFn) {\n super()\n\n if (!validator) {\n throw new CodeError('missing validator', 'ERR_INVALID_PARAMETERS')\n }\n\n if (typeof validator !== 'function') {\n throw new CodeError('missing validate function', 'ERR_INVALID_PARAMETERS')\n }\n\n if (typeof selector !== 'function') {\n throw new CodeError('missing select function', 'ERR_INVALID_PARAMETERS')\n }\n\n if (subscriptionKeyFn && typeof subscriptionKeyFn !== 'function') {\n throw new CodeError('invalid subscriptionKeyFn received', 'ERR_INVALID_PARAMETERS')\n }\n\n this._pubsub = pubsub\n this._datastore = datastore\n this._peerId = peerId\n this._validator = validator\n this._selector = selector\n this._handleSubscriptionKeyFn = subscriptionKeyFn\n\n // Bind _onMessage function, which is called by pubsub.\n this._onMessage = this._onMessage.bind(this)\n this._pubsub.addEventListener('message', this._onMessage)\n }\n\n /**\n * Publishes a value through pubsub.\n *\n * @param {Uint8Array} key - identifier of the value to be published.\n * @param {Uint8Array} val - value to be propagated.\n * @param {AbortOptions} [options]\n */\n // @ts-ignore Datastores take keys as Keys, this one takes Uint8Arrays\n async put (key, val, options) {\n if (!(key instanceof Uint8Array)) {\n const errMsg = 'datastore key does not have a valid format'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_DATASTORE_KEY')\n }\n\n if (!(val instanceof Uint8Array)) {\n const errMsg = 'received value is not a Uint8Array'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_VALUE_RECEIVED')\n }\n\n const stringifiedTopic = keyToTopic(key)\n\n log(`publish value for topic ${stringifiedTopic}`)\n\n // Publish record to pubsub\n await this._pubsub.publish(stringifiedTopic, val)\n }\n\n /**\n * Try to subscribe a topic with Pubsub and returns the local value if available.\n *\n * @param {Uint8Array} key - identifier of the value to be subscribed.\n * @param {AbortOptions} [options]\n */\n // @ts-ignore Datastores take keys as Keys, this one takes Uint8Arrays\n async get (key, options) {\n if (!(key instanceof Uint8Array)) {\n const errMsg = 'datastore key does not have a valid format'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_DATASTORE_KEY')\n }\n\n const stringifiedTopic = keyToTopic(key)\n const subscriptions = await this._pubsub.getTopics()\n\n // If already subscribed, just try to get it\n if (subscriptions && Array.isArray(subscriptions) && subscriptions.indexOf(stringifiedTopic) > -1) {\n return this._getLocal(key, options)\n }\n\n // subscribe\n try {\n await this._pubsub.subscribe(stringifiedTopic)\n } catch (/** @type {any} */ err) {\n const errMsg = `cannot subscribe topic ${stringifiedTopic}`\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_SUBSCRIBING_TOPIC')\n }\n log(`subscribed values for key ${stringifiedTopic}`)\n\n return this._getLocal(key)\n }\n\n /**\n * Unsubscribe topic.\n *\n * @param {Uint8Array} key - identifier of the value to unsubscribe.\n * @returns {void}\n */\n unsubscribe (key) {\n const stringifiedTopic = keyToTopic(key)\n\n return this._pubsub.unsubscribe(stringifiedTopic)\n }\n\n /**\n * Get record from local datastore\n *\n * @private\n * @param {Uint8Array} key\n * @param {AbortOptions} [options]\n */\n async _getLocal (key, options) {\n // encode key - base32(/ipns/{cid})\n const routingKey = new Key('/' + encodeBase32(key), false)\n let dsVal\n\n try {\n dsVal = await this._datastore.get(routingKey, options)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n const errMsg = `unexpected error getting the ipns record for ${routingKey.toString()}`\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_UNEXPECTED_ERROR_GETTING_RECORD')\n }\n const errMsg = `local record requested was not found for ${routingKey.toString()}`\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_NOT_FOUND')\n }\n\n if (!(dsVal instanceof Uint8Array)) {\n const errMsg = 'found record that we couldn\\'t convert to a value'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_RECORD_RECEIVED')\n }\n\n return dsVal\n }\n\n /**\n * handles pubsub subscription messages\n *\n * @param {CustomEvent} evt\n */\n async _onMessage (evt) {\n const msg = evt.detail\n\n if (msg.type !== 'signed') {\n log.error('unsigned message received, this module can only work with signed messages')\n return\n }\n\n const { data, from, topic } = msg\n let key\n try {\n key = topicToKey(topic)\n } catch (/** @type {any} */ err) {\n log.error(err)\n return\n }\n\n log(`message received for topic ${topic}`)\n\n // Stop if the message is from the peer (it already stored it while publishing to pubsub)\n if (this._peerId.equals(from)) {\n log('message discarded as it is from the same peer')\n return\n }\n\n if (this._handleSubscriptionKeyFn) {\n let res\n\n try {\n res = await this._handleSubscriptionKeyFn(key)\n } catch (/** @type {any} */ err) {\n log.error('message discarded by the subscriptionKeyFn')\n return\n }\n\n key = res\n }\n\n try {\n await this._storeIfSubscriptionIsBetter(key, data)\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }\n\n /**\n * Store the received record if it is better than the current stored\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @param {AbortOptions} [options]\n */\n async _storeIfSubscriptionIsBetter (key, data, options) {\n let isBetter = false\n\n try {\n isBetter = await this._isBetter(key, data)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_VALID_RECORD') {\n throw err\n }\n }\n\n if (isBetter) {\n await this._storeRecord(key, data, options)\n }\n }\n\n /**\n * Validate record according to the received validation function\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} value\n */\n async _validateRecord (key, value) { // eslint-disable-line require-await\n return this._validator(key, value)\n }\n\n /**\n * Select the best record according to the received select function\n *\n * @param {Uint8Array} key\n * @param {Uint8Array[]} records\n */\n async _selectRecord (key, records) {\n const res = await this._selector(key, records)\n\n // If the selected was the first (0), it should be stored (true)\n return res === 0\n }\n\n /**\n * Verify if the record received through pubsub is valid and better than the one currently stored\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} val\n */\n async _isBetter (key, val) {\n try {\n await this._validateRecord(key, val)\n } catch (/** @type {any} */ err) {\n // If not valid, it is not better than the one currently available\n const errMsg = 'record received through pubsub is not valid'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_NOT_VALID_RECORD')\n }\n\n // Get Local record\n const dsKey = new Key(key)\n let currentRecord\n\n try {\n currentRecord = await this._getLocal(dsKey.uint8Array())\n } catch (/** @type {any} */ err) {\n // if the old one is invalid, the new one is *always* better\n return true\n }\n\n // if the same record, do not need to store\n if (uint8ArrayEquals(currentRecord, val)) {\n return false\n }\n\n // verify if the received record should replace the current one\n return this._selectRecord(key, [currentRecord, val])\n }\n\n /**\n * add record to datastore\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @param {AbortOptions} [options]\n */\n async _storeRecord (key, data, options) {\n // encode key - base32(/ipns/{cid})\n const routingKey = new Key('/' + encodeBase32(key), false)\n\n await this._datastore.put(routingKey, data, options)\n log(`record for ${keyToTopic(key)} was stored in the datastore`)\n }\n}\n", "import { namespaceLength, namespace, peerIdToRoutingKey } from 'ipns'\nimport { ipnsValidator } from 'ipns/validator'\nimport { ipnsSelector } from 'ipns/selector'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { PubSubDatastore } from 'datastore-pubsub'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\nconst log = logger('ipfs:ipns:pubsub')\n\n/**\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\n// Pubsub datastore aims to manage the pubsub subscriptions for IPNS\nexport class IpnsPubsubDatastore {\n /**\n * @param {import('@libp2p/interface-pubsub').PubSub} pubsub\n * @param {import('interface-datastore').Datastore} localDatastore\n * @param {import('@libp2p/interface-peer-id').PeerId} peerId\n */\n constructor (pubsub, localDatastore, peerId) {\n /** @type {Record} */\n this._subscriptions = {}\n\n // Bind _handleSubscriptionKey function, which is called by PubsubDatastore.\n this._handleSubscriptionKey = this._handleSubscriptionKey.bind(this)\n\n this._pubsubDs = new PubSubDatastore(pubsub, localDatastore, peerId, ipnsValidator, ipnsSelector, this._handleSubscriptionKey)\n }\n\n /**\n * Put a value to the pubsub datastore indexed by the received key properly encoded.\n *\n * @param {Uint8Array} key - identifier of the value.\n * @param {Uint8Array} value - value to be stored.\n * @param {AbortOptions} [options]\n */\n async put (key, value, options) {\n try {\n await this._pubsubDs.put(key, value, options)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n }\n\n /**\n * Get a value from the pubsub datastore indexed by the received key properly encoded.\n * Also, the identifier topic is subscribed to and the pubsub datastore records will be\n * updated once new publishes occur.\n *\n * @param {Uint8Array} key - identifier of the value to be obtained.\n * @param {AbortOptions} [options]\n */\n async get (key, options) {\n let res\n let err\n\n try {\n res = await this._pubsubDs.get(key, options)\n } catch (/** @type {any} */ e) {\n err = e\n }\n\n // Add topic subscribed\n const ns = key.slice(0, namespaceLength)\n\n if (uint8ArrayToString(ns) === namespace) {\n const stringifiedTopic = base58btc.encode(key).substring(1)\n const id = base58btc.encode(key.slice(namespaceLength)).substring(1)\n\n this._subscriptions[stringifiedTopic] = id\n\n log(`subscribed to pubsub topic ${stringifiedTopic}, id ${id}`)\n }\n\n // If no data was obtained, after storing the subscription, return the error.\n if (err) {\n throw err\n }\n\n return res\n }\n\n /**\n * Modify subscription key to have a proper encoding\n *\n * @param {Uint8Array | string} key\n */\n _handleSubscriptionKey (key) {\n if (key instanceof Uint8Array) {\n key = uint8ArrayToString(key, 'base58btc')\n }\n\n const subscriber = this._subscriptions[key]\n\n if (!subscriber) {\n throw errcode(new Error(`key ${key} does not correspond to a subscription`), 'ERR_INVALID_KEY')\n }\n\n try {\n const k = peerIdToRoutingKey(peerIdFromString(subscriber))\n return k\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n }\n\n /**\n * Get pubsub subscriptions related to ipns.\n */\n getSubscriptions () {\n const subscriptions = Object.values(this._subscriptions).filter(Boolean)\n\n return subscriptions.map((sub) => `${namespace}${sub}`)\n }\n\n /**\n * Cancel pubsub subscriptions related to ipns.\n *\n * @param {string} name - ipns path to cancel the pubsub subscription.\n */\n async cancel (name) { // eslint-disable-line require-await\n if (typeof name !== 'string') {\n throw errcode(new Error('invalid subscription name'), 'ERR_INVALID_SUBSCRIPTION_NAME')\n }\n\n // Trim /ipns/ prefix from the name\n if (name.startsWith(namespace)) {\n name = name.substring(namespaceLength)\n }\n\n const stringifiedTopic = Object.keys(this._subscriptions).find((key) => this._subscriptions[key] === name)\n\n // Not found topic\n if (!stringifiedTopic) {\n return {\n canceled: false\n }\n }\n\n // Unsubscribe topic\n const bufTopic = uint8ArrayFromString(stringifiedTopic)\n\n this._pubsubDs.unsubscribe(bufTopic)\n\n delete this._subscriptions[stringifiedTopic]\n log(`unsubscribed pubsub ${stringifiedTopic}: ${name}`)\n\n return {\n canceled: true\n }\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key: Uint8Array\n value: Uint8Array\n timeReceived: string\n}\n\nexport namespace Record {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if ((obj.timeReceived != null && obj.timeReceived !== '')) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: new Uint8Array(0),\n value: new Uint8Array(0),\n timeReceived: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.bytes()\n break\n case 2:\n obj.value = reader.bytes()\n break\n case 5:\n obj.timeReceived = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Record.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Record => {\n return decodeMessage(buf, Record.codec())\n }\n}\n", "/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n", "import {\n Record\n} from './record.js'\nimport * as utils from './utils.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Libp2pRecord {\n public key: Uint8Array\n public value: Uint8Array\n public timeReceived: Date\n\n constructor (key: Uint8Array, value: Uint8Array, timeReceived: Date) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('key must be a Uint8Array')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new Error('value must be a Uint8Array')\n }\n\n this.key = key\n this.value = value\n this.timeReceived = timeReceived\n }\n\n serialize (): Uint8Array {\n return Record.encode(this.prepareSerialize())\n }\n\n /**\n * Return the object format ready to be given to the protobuf library.\n */\n prepareSerialize (): Record {\n return {\n key: this.key,\n value: this.value,\n timeReceived: utils.toRFC3339(this.timeReceived)\n }\n }\n\n /**\n * Decode a protobuf encoded record\n */\n static deserialize (raw: Uint8Array | Uint8ArrayList): Libp2pRecord {\n const rec = Record.decode(raw)\n\n return new Libp2pRecord(rec.key, rec.value, new Date(rec.timeReceived))\n }\n\n /**\n * Create a record from the raw object returned from the protobuf library\n */\n static fromDeserialized (obj: Record): Libp2pRecord {\n const recvtime = utils.parseRFC3339(obj.timeReceived)\n\n if (obj.key == null) {\n throw new Error('key missing from deserialized object')\n }\n\n if (obj.value == null) {\n throw new Error('value missing from deserialized object')\n }\n\n const rec = new Libp2pRecord(\n obj.key, obj.value, recvtime\n )\n\n return rec\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport { Libp2pRecord } from '@libp2p/record'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst log = logger('ipfs:ipns:offline-datastore')\n\n/**\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\n// Offline datastore aims to mimic the same encoding as routing when storing records\n// to the local datastore\nexport class OfflineDatastore {\n /**\n * @param {import('interface-datastore').Datastore} datastore\n */\n constructor (datastore) {\n this._datastore = datastore\n /** @type {any[]} */\n this.stores = []\n }\n\n /**\n * Put a value to the local datastore indexed by the received key properly encoded.\n *\n * @param {Uint8Array} key - identifier of the value.\n * @param {Uint8Array} value - value to be stored.\n * @param {AbortOptions} [options]\n */\n async put (key, value, options) { // eslint-disable-line require-await\n if (!(key instanceof Uint8Array)) {\n throw errcode(new Error('Offline datastore key must be a Uint8Array'), 'ERR_INVALID_KEY')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw errcode(new Error('Offline datastore value must be a Uint8Array'), 'ERR_INVALID_VALUE')\n }\n\n let routingKey\n\n try {\n routingKey = this._routingKey(key)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')\n }\n\n // Marshal to libp2p record as the DHT does\n const record = new Libp2pRecord(key, value, new Date())\n\n await this._datastore.put(routingKey, record.serialize(), options)\n }\n\n /**\n * Get a value from the local datastore indexed by the received key properly encoded.\n *\n * @param {Uint8Array} key - identifier of the value to be obtained.\n * @param {AbortOptions} [options]\n */\n async get (key, options) {\n if (!(key instanceof Uint8Array)) {\n throw errcode(new Error('Offline datastore key must be a Uint8Array'), 'ERR_INVALID_KEY')\n }\n\n let routingKey\n\n try {\n routingKey = this._routingKey(key)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')\n }\n\n const res = await this._datastore.get(routingKey, options)\n\n // Unmarshal libp2p record as the DHT does\n let record\n try {\n record = Libp2pRecord.deserialize(res)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n\n return record.value\n }\n\n /**\n * encode key properly - base32(/ipns/{cid})\n *\n * @param {Uint8Array} key\n */\n _routingKey (key) {\n return new Key('/dht/record/' + uint8ArrayToString(key, 'base32'), false)\n }\n}\n", "/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nexport default async function drain (source: AsyncIterable | Iterable): Promise {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n}\n", "import drain from 'it-drain'\nimport { notFoundError } from 'datastore-core/errors'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:ipns:dht-datastore')\n\n/**\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nexport class DHTDatastore {\n /**\n *\n * @param {import('@libp2p/interface-dht').DHT} dht\n */\n constructor (dht) {\n this._dht = dht\n }\n\n /**\n * @param {Uint8Array} key - identifier of the value.\n * @param {Uint8Array} value - value to be stored.\n * @param {AbortOptions} [options]\n */\n async put (key, value, options) {\n try {\n await drain(this._dht.put(key, value, options))\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n }\n\n /**\n * @param {Uint8Array} key - identifier of the value to be obtained.\n * @param {AbortOptions} [options]\n */\n async get (key, options) {\n for await (const event of this._dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw notFoundError()\n }\n}\n", "import { IPNS } from '../ipns/index.js'\nimport { createRouting } from '../ipns/routing/config.js'\nimport { OfflineDatastore } from '../ipns/routing/offline-datastore.js'\nimport { NotInitializedError, AlreadyInitializedError } from '../errors.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:components:ipns')\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n *\n * @typedef {object} ExperimentalOptions\n * @property {boolean} [ipnsPubsub]\n *\n * @typedef {object} LibP2POptions\n * @property {DHTConfig} [config]\n *\n * @typedef {object} DHTConfig\n * @property {boolean} [enabled]\n */\n\nexport class IPNSAPI {\n /**\n * @param {object} options\n * @param {string} options.pass\n * @param {boolean} [options.offline]\n * @param {LibP2POptions} [options.libp2p]\n * @param {ExperimentalOptions} [options.EXPERIMENTAL]\n */\n constructor (options = { pass: '' }) {\n this.options = options\n\n /** @type {IPNS | null} */\n this.offline = null\n\n /** @type {IPNS | null} */\n this.online = null\n }\n\n getIPNS () {\n const ipns = this.online || this.offline\n if (ipns) {\n return ipns\n } else {\n throw new NotInitializedError()\n }\n }\n\n get routing () {\n return this.getIPNS().routing\n }\n\n /**\n * Activates IPNS subsystem in an ofline mode. If it was started once already\n * it will throw an exception.\n *\n * This is primarily used for offline ipns modifications, such as the\n * initializeKeyspace feature.\n *\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\n startOffline ({ repo, peerId, keychain }) {\n if (this.offline != null) {\n throw new AlreadyInitializedError()\n }\n\n log('initializing IPNS keyspace (offline)')\n\n const routing = new OfflineDatastore(repo.datastore)\n const ipns = new IPNS(routing, repo.datastore, peerId, keychain, this.options)\n\n this.offline = ipns\n }\n\n /**\n * @param {object} config\n * @param {import('libp2p').Libp2p} config.libp2p\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\n async startOnline ({ libp2p, repo, peerId, keychain }) {\n if (this.online != null) {\n throw new AlreadyInitializedError()\n }\n const routing = createRouting({ libp2p, repo, peerId, options: this.options })\n\n // @ts-expect-error routing is a TieredDatastore which wants keys to be Keys, IPNS needs keys to be Uint8Arrays\n const ipns = new IPNS(routing, repo.datastore, peerId, keychain, this.options)\n await ipns.republisher.start()\n this.online = ipns\n }\n\n async stop () {\n const ipns = this.online\n if (ipns) {\n await ipns.republisher.stop()\n this.online = null\n }\n }\n\n /**\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n publish (peerId, value, lifetime, options) {\n return this.getIPNS().publish(peerId, value, lifetime, options)\n }\n\n /**\n *\n * @param {string} name\n * @param {object} [options]\n * @param {boolean} [options.nocache]\n * @param {boolean} [options.recursive]\n * @param {AbortSignal} [options.signal]\n */\n resolve (name, options) {\n return this.getIPNS().resolve(name, options)\n }\n\n /**\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {AbortOptions} [options]\n */\n initializeKeyspace (peerId, value, options) {\n return this.getIPNS().initializeKeyspace(peerId, value, options)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport parseDuration from 'parse-duration'\nimport { importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport errcode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { OFFLINE_ERROR, normalizePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { resolvePath } from './utils.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\n\nconst log = logger('ipfs:name:publish')\n\n/**\n * IPNS - Inter-Planetary Naming System\n *\n * @param {object} config\n * @param {import('../ipns').IPNSAPI} config.ipns\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('ipfs-core-types/src/root').API<{}>[\"isOnline\"]} config.isOnline\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createPublish ({ ipns, repo, codecs, peerId, isOnline, keychain }) {\n /**\n * @param {string} keyName\n */\n const lookupKey = async keyName => {\n /** @type {import('@libp2p/interface-keys').PrivateKey} */\n let privateKey\n\n if (keyName === 'self' && peerId.privateKey != null) {\n privateKey = await unmarshalPrivateKey(peerId.privateKey)\n } else {\n try {\n // We're exporting and immediately importing the key, so we can just use a throw away password\n const pem = await keychain.exportKey(keyName, 'temp')\n privateKey = await importKey(pem, 'temp')\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(err, 'ERR_CANNOT_GET_KEY')\n }\n }\n\n return peerIdFromKeys(privateKey.public.bytes, privateKey.bytes)\n }\n\n /**\n * @type {import('ipfs-core-types/src/name').API<{}>[\"publish\"]}\n */\n async function publish (value, options = {}) {\n const resolve = !(options.resolve === false)\n const lifetime = options.lifetime || '24h'\n const key = options.key || 'self'\n\n if (!isOnline()) {\n throw errcode(new Error(OFFLINE_ERROR), 'OFFLINE_ERROR')\n }\n\n // TODO: params related logic should be in the core implementation\n // Normalize path value\n try {\n value = normalizePath(value)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n\n let pubLifetime = 0\n try {\n pubLifetime = parseDuration(lifetime) || 0\n\n // Calculate lifetime with nanoseconds precision\n pubLifetime = parseFloat(pubLifetime.toFixed(6))\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n\n // TODO: ttl human for cache\n const results = await Promise.all([\n // verify if the path exists, if not, an error will stop the execution\n lookupKey(key),\n // if resolving, do a get so we make sure we have the blocks\n resolve ? resolvePath({ ipns, repo, codecs }, value) : Promise.resolve()\n ])\n\n const bytes = uint8ArrayFromString(value)\n\n // Start publishing process\n const result = await ipns.publish(results[0], bytes, pubLifetime, options)\n\n return {\n name: result.name,\n value: uint8ArrayToString(result.value)\n }\n }\n\n return withTimeoutOption(publish)\n}\n", "import * as isIPFS from 'is-ipfs'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport drain from 'it-drain'\nimport { resolve } from '../../utils.js'\n\n/**\n * resolves the given path by parsing out protocol-specific entries\n * (e.g. /ipns/) and then going through the /ipfs/ entries and returning the final node\n *\n * @param {object} context\n * @param {import('../ipns').IPNSAPI} context.ipns\n * @param {import('ipfs-repo').IPFSRepo} context.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} context.codecs\n * @param {string} name\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n */\nexport async function resolvePath ({ ipns, repo, codecs }, name, options) {\n // ipns path\n if (isIPFS.ipnsPath(name)) {\n return ipns.resolve(name)\n }\n\n const {\n cid,\n path\n } = toCidAndPath(name)\n\n // ipfs path\n await drain(resolve(cid, path || '', codecs, repo, options))\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport mergeOpts from 'merge-options'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { base36 } from 'multiformats/bases/base36'\nimport { peerIdFromString } from '@libp2p/peer-id'\n// @ts-expect-error no types\nimport isDomain from 'is-domain-name'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { OFFLINE_ERROR } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\nconst log = logger('ipfs:name:resolve')\n\n/**\n *\n * @param {string} result\n * @param {string[]} remainder\n * @returns {string}\n */\nconst appendRemainder = (result, remainder) =>\n remainder.length > 0\n ? result + '/' + remainder.join('/')\n : result\n\n/**\n * IPNS - Inter-Planetary Naming System\n *\n * @param {object} config\n * @param {import('ipfs-core-types/src/root').API<{}>[\"dns\"]} config.dns\n * @param {import('../ipns').IPNSAPI} config.ipns\n * @param {import('ipfs-core-types/src/root').API<{}>[\"isOnline\"]} config.isOnline\n * @param {import('../../types').Options} config.options\n */\nexport function createResolve ({ dns, ipns, isOnline, options: { offline } }) {\n /**\n * @type {import('ipfs-core-types/src/name').API<{}>[\"resolve\"]}\n */\n async function * resolve (name, options = {}) { // eslint-disable-line require-await\n options = mergeOptions({\n nocache: false,\n recursive: true\n }, options)\n\n // TODO: params related logic should be in the core implementation\n if (offline && options && options.nocache) {\n throw errcode(new Error('cannot specify both offline and nocache'), 'ERR_NOCACHE_AND_OFFLINE')\n }\n\n // IPNS resolve needs a online daemon\n if (!isOnline() && !offline) {\n throw errcode(new Error(OFFLINE_ERROR), 'OFFLINE_ERROR')\n }\n\n let ipnsName = name.toString()\n\n if (!ipnsName.startsWith('/ipns/')) {\n ipnsName = `/ipns/${ipnsName}`\n }\n\n let [namespace, hash, ...remainder] = ipnsName.slice(1).split('/')\n\n try {\n if (hash.substring(0, 1) === '1') {\n const id = peerIdFromString(hash)\n const digest = Digest.decode(id.toBytes())\n const libp2pKey = CID.createV1(0x72, digest)\n hash = libp2pKey.toString(base36)\n } else {\n const cid = CID.parse(hash)\n\n if (cid.version === 1) {\n hash = cid.toString(base36)\n }\n }\n } catch (/** @type {any} */ err) {\n // lets check if we have a domain ex. /ipns/ipfs.io and resolve with dns\n if (isDomain(hash)) {\n yield appendRemainder(await dns(hash, options), remainder)\n return\n }\n\n log.error(err)\n throw errcode(new Error('Invalid IPNS name'), 'ERR_IPNS_INVALID_NAME')\n }\n\n // multihash is valid lets resolve with IPNS\n // TODO: convert ipns.resolve to return an iterator\n const value = await ipns.resolve(`/${namespace}/${hash}`, options)\n yield appendRemainder(value instanceof Uint8Array ? uint8ArrayToString(value) : value, remainder)\n }\n\n return withTimeoutOption(resolve)\n}\n", "import { IpnsPubsubDatastore } from '../../../ipns/routing/pubsub-datastore.js'\nimport errcode from 'err-code'\n\n/**\n * @typedef {import('../../../types').ExperimentalOptions} ExperimentalOptions\n * @property {boolean} [ipnsPubsub] - Enable pub-sub on IPNS. (Default: `false`)\n */\n\n/**\n * Get pubsub from IPNS routing\n *\n * @param {import('../../ipns').IPNSAPI} ipns\n * @param {ExperimentalOptions} [options]\n */\nexport function getPubsubRouting (ipns, options) {\n if (!ipns || !(options && options.ipnsPubsub)) {\n throw errcode(new Error('IPNS pubsub subsystem is not enabled'), 'ERR_IPNS_PUBSUB_NOT_ENABLED')\n }\n\n // Only one store and it is pubsub\n if (ipns.routing instanceof IpnsPubsubDatastore) {\n return ipns.routing\n }\n\n // Find in tiered\n const pubsub = (ipns.routing.stores || []).find(s => s instanceof IpnsPubsubDatastore)\n\n if (!pubsub) {\n throw errcode(new Error('IPNS pubsub datastore not found'), 'ERR_PUBSUB_DATASTORE_NOT_FOUND')\n }\n\n return pubsub\n}\n", "import { getPubsubRouting } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\nexport function createCancel ({ ipns, options }) {\n const experimental = options.EXPERIMENTAL\n\n /**\n * @type {import('ipfs-core-types/src/name/pubsub').API<{}>[\"cancel\"]}\n */\n async function cancel (name, options = {}) { // eslint-disable-line require-await\n const pubsub = getPubsubRouting(ipns, experimental)\n return pubsub.cancel(name, options)\n }\n\n return withTimeoutOption(cancel)\n}\n", "import { getPubsubRouting } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\nexport function createState ({ ipns, options }) {\n const experimental = options.EXPERIMENTAL\n\n /**\n * @type {import('ipfs-core-types/src/name/pubsub').API<{}>[\"state\"]}\n */\n async function state (_options = {}) { // eslint-disable-line require-await\n try {\n return { enabled: Boolean(getPubsubRouting(ipns, experimental)) }\n } catch (/** @type {any} */ err) {\n return { enabled: false }\n }\n }\n\n return withTimeoutOption(state)\n}\n", "import { getPubsubRouting } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\nexport function createSubs ({ ipns, options }) {\n const experimental = options.EXPERIMENTAL\n\n /**\n * @type {import('ipfs-core-types/src/name/pubsub').API<{}>[\"subs\"]}\n */\n async function subs (options = {}) { // eslint-disable-line require-await\n const pubsub = getPubsubRouting(ipns, experimental)\n return pubsub.getSubscriptions(options)\n }\n\n return withTimeoutOption(subs)\n}\n", "import { createCancel } from './cancel.js'\nimport { createState } from './state.js'\nimport { createSubs } from './subs.js'\n\nexport class PubSubAPI {\n /**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\n constructor ({ ipns, options }) {\n this.cancel = createCancel({ ipns, options })\n this.state = createState({ ipns, options })\n this.subs = createSubs({ ipns, options })\n }\n}\n", "import { createPublish } from './publish.js'\nimport { createResolve } from './resolve.js'\nimport { PubSubAPI } from './pubsub/index.js'\n\nexport class NameAPI {\n /**\n * @param {object} config\n * @param {import('../ipns').IPNSAPI} config.ipns\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('../../types').Options} config.options\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-types/src/root').API<{}>[\"isOnline\"]} config.isOnline\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n * @param {import('ipfs-core-types/src/root').API<{}>[\"dns\"]} config.dns\n */\n constructor ({ dns, ipns, repo, codecs, peerId, isOnline, keychain, options }) {\n this.publish = createPublish({ ipns, repo, codecs, peerId, isOnline, keychain })\n this.resolve = createResolve({ dns, ipns, isOnline, options })\n this.pubsub = new PubSubAPI({ ipns, options })\n }\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { notFoundError } from 'datastore-core/errors'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport { CID } from 'multiformats/cid'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\n\nconst ERR_NOT_FOUND = notFoundError().code\n\nexport const Format = {\n default: '',\n edges: ' -> '\n}\n\n/**\n * @typedef {object} Node\n * @property {string} [name]\n * @property {CID} cid\n *\n * @typedef {object} TraversalResult\n * @property {Node} parent\n * @property {Node} node\n * @property {boolean} isDuplicate\n *\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-types/src/root').API<{}>[\"resolve\"]} config.resolve\n * @param {import('../../types').Preload} config.preload\n */\nexport function createRefs ({ repo, codecs, resolve, preload }) {\n /**\n * @type {import('ipfs-core-types/src/refs').API<{}>[\"refs\"]}\n */\n async function * refs (ipfsPath, options = {}) {\n if (options.maxDepth === 0) {\n return\n }\n\n if (options.edges && options.format && options.format !== Format.default) {\n throw new Error('Cannot set edges to true and also specify format')\n }\n\n options.format = options.edges ? Format.edges : options.format\n\n if (typeof options.maxDepth !== 'number') {\n options.maxDepth = options.recursive ? Infinity : 1\n }\n\n if (options.timeout) {\n const controller = new TimeoutController(options.timeout)\n const signals = [controller.signal]\n\n if (options.signal) {\n signals.push(options.signal)\n }\n\n options.signal = anySignal(signals)\n }\n\n /** @type {(string|CID)[]} */\n const rawPaths = Array.isArray(ipfsPath) ? ipfsPath : [ipfsPath]\n\n const paths = rawPaths.map(p => getFullPath(preload, p, options))\n\n for (const path of paths) {\n try {\n yield * refsStream(resolve, repo, codecs, path, options)\n } catch (/** @type {any} */ err) {\n yield {\n ref: '',\n err: err.message\n }\n }\n }\n }\n\n return refs\n}\n\n/**\n * @param {import('../../types').Preload} preload\n * @param {string | CID} ipfsPath\n * @param {import('ipfs-core-types/src/refs').RefsOptions} options\n */\nfunction getFullPath (preload, ipfsPath, options) {\n const {\n cid,\n path\n } = toCidAndPath(ipfsPath)\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return `/ipfs/${cid}${path || ''}`\n}\n\n/**\n * Get a stream of refs at the given path\n *\n * @param {import('ipfs-core-types/src/root').API<{}>[\"resolve\"]} resolve\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {string} path\n * @param {import('ipfs-core-types/src/refs').RefsOptions} options\n */\nasync function * refsStream (resolve, repo, codecs, path, options) {\n // Resolve to the target CID of the path\n const resPath = await resolve(path, options)\n const {\n cid\n } = toCidAndPath(resPath)\n\n const maxDepth = options.maxDepth != null ? options.maxDepth : Infinity\n const unique = options.unique || false\n\n // Traverse the DAG, converting it into a stream\n for await (const obj of objectStream(repo, codecs, cid, maxDepth, unique, options)) {\n // Root object will not have a parent\n if (!obj.parent) {\n continue\n }\n\n // Filter out duplicates (isDuplicate flag is only set if options.unique is set)\n if (obj.isDuplicate) {\n continue\n }\n\n // Format the links\n // Clients expect refs to be in the format { ref: }\n yield {\n ref: formatLink(obj.parent.cid, obj.node.cid, obj.node.name, options.format)\n }\n }\n}\n\n/**\n * Get formatted link\n *\n * @param {CID} srcCid\n * @param {CID} dstCid\n * @param {string} [linkName]\n * @param {string} [format]\n */\nfunction formatLink (srcCid, dstCid, linkName = '', format = Format.default) {\n let out = format.replace(//g, srcCid.toString())\n out = out.replace(//g, dstCid.toString())\n out = out.replace(//g, linkName)\n return out\n}\n\n/**\n * Do a depth first search of the DAG, starting from the given root cid\n *\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {CID} rootCid\n * @param {number} maxDepth\n * @param {boolean} uniqueOnly\n * @param {AbortOptions} options\n */\nasync function * objectStream (repo, codecs, rootCid, maxDepth, uniqueOnly, options) { // eslint-disable-line require-await\n const seen = new Set()\n\n /**\n * @param {Node} parent\n * @param {number} depth\n * @returns {AsyncGenerator}\n */\n async function * traverseLevel (parent, depth) {\n const nextLevelDepth = depth + 1\n\n // Check the depth\n if (nextLevelDepth > maxDepth) {\n return\n }\n\n // Get this object's links\n try {\n // Look at each link, parent and the new depth\n for await (const link of getLinks(repo, codecs, parent.cid, options)) {\n yield {\n parent: parent,\n node: link,\n isDuplicate: uniqueOnly && seen.has(link.cid.toString())\n }\n\n if (uniqueOnly) {\n seen.add(link.cid.toString())\n }\n\n yield * traverseLevel(link, nextLevelDepth)\n }\n } catch (/** @type {any} */ err) {\n if (err.code === ERR_NOT_FOUND) {\n err.message = `Could not find object with CID: ${parent.cid}`\n }\n\n throw err\n }\n }\n\n yield * traverseLevel({ cid: rootCid }, 0)\n}\n\n/**\n * Fetch a node and then get all its links\n *\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {CID} cid\n * @param {AbortOptions} options\n * @returns {AsyncGenerator<{ name: string, cid: CID }, void, undefined>}\n */\nasync function * getLinks (repo, codecs, cid, options) {\n const block = await repo.blocks.get(cid, options)\n const codec = await codecs.getCodec(cid.code)\n const value = codec.decode(block)\n const isDagPb = cid.code === dagPB.code\n /** @type {Array} */\n const base = []\n\n for (const [name, cid] of links(value, base)) {\n // special case for dag-pb - use the name of the link\n // instead of the path within the object\n if (isDagPb) {\n const match = name.match(/^Links\\/(\\d+)\\/Hash$/)\n\n if (match) {\n const index = Number(match[1])\n\n if (index < value.Links.length) {\n yield {\n name: value.Links[index].Name,\n cid\n }\n\n continue\n }\n }\n }\n\n yield {\n name,\n cid\n }\n }\n}\n\n/**\n * @param {*} source\n * @param {Array} base\n * @returns {Iterable<[string, CID]>}\n */\nconst links = function * (source, base) {\n if (source == null) {\n return\n }\n\n if (source instanceof Uint8Array) {\n return\n }\n\n for (const [key, value] of Object.entries(source)) {\n const path = [...base, key]\n\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n\n // eslint-disable-next-line max-depth\n if (cid) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n\n if (cid) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n }\n\n // ts requires a @returns annotation when a function is recursive,\n // eslint requires a return when you use a @returns annotation.\n return []\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createLocal ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/refs').API<{}>[\"local\"]}\n */\n async function * refsLocal (options = {}) {\n for await (const cid of repo.blocks.queryKeys({}, { signal: options.signal })) {\n yield { ref: cid.toString() }\n }\n }\n\n return withTimeoutOption(refsLocal)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createWantlist ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"wantlist\"]}\n */\n async function wantlist (options = {}) {\n const { bitswap } = await network.use(options)\n const list = bitswap.getWantlist()\n\n return Array.from(list).map(e => e[1].cid)\n }\n\n return withTimeoutOption(wantlist)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createWantlistForPeer ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"wantlistForPeer\"]}\n */\n async function wantlistForPeer (peerId, options = {}) {\n const { bitswap } = await network.use(options)\n const list = bitswap.wantlistForPeer(peerId)\n\n return Array.from(list).map(e => e[1].cid)\n }\n\n return withTimeoutOption(wantlistForPeer)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createUnwant ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"unwant\"]}\n */\n async function unwant (cids, options = {}) {\n const { bitswap } = await network.use(options)\n\n if (!Array.isArray(cids)) {\n cids = [cids]\n }\n\n return bitswap.unwant(cids)\n }\n\n return withTimeoutOption(unwant)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createStat ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"stat\"]}\n */\n async function stat (options = {}) {\n /** @type {import('ipfs-bitswap').IPFSBitswap} */\n const bitswap = (await network.use(options)).bitswap\n const snapshot = bitswap.stat().snapshot\n\n return {\n provideBufLen: parseInt(snapshot.providesBufferLength.toString()),\n blocksReceived: BigInt(snapshot.blocksReceived.toString()),\n wantlist: Array.from(bitswap.getWantlist()).map(e => e[1].cid),\n peers: bitswap.peers(),\n dupBlksReceived: BigInt(snapshot.dupBlksReceived.toString()),\n dupDataReceived: BigInt(snapshot.dupDataReceived.toString()),\n dataReceived: BigInt(snapshot.dataReceived.toString()),\n blocksSent: BigInt(snapshot.blocksSent.toString()),\n dataSent: BigInt(snapshot.dataSent.toString())\n }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { createWantlist } from './wantlist.js'\nimport { createWantlistForPeer } from './wantlist-for-peer.js'\nimport { createUnwant } from './unwant.js'\nimport { createStat } from './stat.js'\n\n/**\n * @typedef {import('../../types').NetworkService} NetworkService\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\nexport class BitswapAPI {\n /**\n * @param {object} config\n * @param {NetworkService} config.network\n */\n constructor ({ network }) {\n this.wantlist = createWantlist({ network })\n this.wantlistForPeer = createWantlistForPeer({ network })\n this.unwant = createUnwant({ network })\n this.stat = createStat({ network })\n }\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss')),\n and(TCP, base('tls'), base('ws')),\n and(DNS, base('tls'), base('ws'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nconst _WebRTC = and(UDP, base('webrtc'), base('certhash'))\nexport const WebRTC = or(\n and(_WebRTC, base('p2p')),\n _WebRTC\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS,\n WebRTC\n)\n\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(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n WebRTC,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = (): Mafmt => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction): (a: string | Uint8Array | Multiaddr) => boolean {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\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\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches,\n partialMatch\n }\n}\n", "import { IPFS } from '@multiformats/mafmt'\n\n/**\n * @param {any} ma\n */\nexport function isValidMultiaddr (ma) {\n try {\n return IPFS.matches(ma)\n } catch (/** @type {any} */ err) {\n return false\n }\n}\n", "import { isValidMultiaddr } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createAdd ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"add\"]}\n */\n async function add (multiaddr, options = {}) {\n if (!isValidMultiaddr(multiaddr)) {\n throw new Error(`${multiaddr} is not a valid Multiaddr`)\n }\n\n const config = await repo.config.getAll(options)\n const boostrappers = config.Bootstrap || []\n boostrappers.push(multiaddr.toString())\n\n config.Bootstrap = Array.from(\n new Set(boostrappers)\n ).sort((a, b) => a.localeCompare(b))\n\n await repo.config.replace(config)\n\n return {\n Peers: [multiaddr]\n }\n }\n\n return withTimeoutOption(add)\n}\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\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: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\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\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\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'],\n [281, 0, 'webrtc-w3c'],\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\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\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: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport { CID } from 'multiformats/cid'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport * as Digest from 'multiformats/hashes/digest'\nimport varint from 'varint'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\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\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 uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\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\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 uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\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})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\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}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.decode.bytes)\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\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}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\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: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.decode.bytes)\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.decode.bytes)\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\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\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\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}\n\nfunction onion32bytes (str: string): Uint8Array {\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\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}\n\nfunction bytes2onion (buf: Uint8Array): string {\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", "import { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport varint from 'varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\n/**\n * string -> [[str name, str addr]... ]\n */\nexport function stringToStringTuples (str: string): string[][] {\n const tuples = []\n const parts = str.split('/').slice(1) // skip first empty elem\n if (parts.length === 1 && parts[0] === '') {\n return []\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([part])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n tuples.push([\n part,\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 cleanPath(parts.slice(p).join('/'))\n ])\n break\n }\n\n tuples.push([part, parts[p]])\n }\n\n return tuples\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nexport function stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[str name, str addr]... ] -> [[int code, Uint8Array]... ]\n */\nexport function stringTuplesToTuples (tuples: Array): Tuple[] {\n return tuples.map((tup) => {\n if (!Array.isArray(tup)) {\n tup = [tup]\n }\n const proto = protoFromTuple(tup)\n if (tup.length > 1) {\n return [proto.code, convertToBytes(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * Convert tuples to string tuples\n *\n * [[int code, Uint8Array]... ] -> [[int code, str addr]... ]\n */\nexport function tuplesToStringTuples (tuples: Tuple[]): StringTuple[] {\n return tuples.map(tup => {\n const proto = protoFromTuple(tup)\n if (tup[1] != null) {\n return [proto.code, convertToString(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return fromBytes(uint8ArrayConcat(tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n })))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nexport function sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr)\n return size + (varint.decode.bytes ?? 0)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\n/**\n * Uint8Array -> String\n */\nexport function bytesToString (buf: Uint8Array): string {\n const a = bytesToTuples(buf)\n const b = tuplesToStringTuples(a)\n return stringTuplesToString(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function stringToBytes (str: string): Uint8Array {\n str = cleanPath(str)\n const a = stringToStringTuples(str)\n const b = stringTuplesToTuples(a)\n\n return tuplesToBytes(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function fromString (str: string): Uint8Array {\n return stringToBytes(str)\n}\n\n/**\n * Uint8Array -> Uint8Array\n */\nexport function fromBytes (buf: Uint8Array): Uint8Array {\n const err = validateBytes(buf)\n if (err != null) {\n throw err\n }\n return Uint8Array.from(buf) // copy\n}\n\nexport function validateBytes (buf: Uint8Array): Error | undefined {\n try {\n bytesToTuples(buf) // try to parse. will throw if breaks\n } catch (err: any) {\n return err\n }\n}\n\nexport function isValidBytes (buf: Uint8Array): boolean {\n return validateBytes(buf) === undefined\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n\nexport function protoFromTuple (tup: any[]): Protocol {\n const proto = getProtocol(tup[0])\n return proto\n}\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\nimport * as codec from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport varint from 'varint'\nimport { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport errCode from 'err-code'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A Resolver is a function that takes a {@link Multiaddr} and resolves it into one\n * or more string representations of that {@link Multiaddr}.\n */\nexport interface Resolver { (addr: Multiaddr, options?: AbortOptions): Promise }\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString: () => string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON: () => string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions: () => MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos: () => Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes: () => number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames: () => string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples: () => Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples: () => StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate: (addr: MultiaddrInput) => Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate: (addr: Multiaddr | string) => Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode: (code: number) => Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId: () => string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath: () => string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals: (addr: { bytes: Uint8Array }) => boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve: (options?: AbortOptions) => Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress: () => NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress: (addr?: Multiaddr) => boolean\n}\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 */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\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: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\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 DefaultMultiaddr('/' + [ip, host, transport, addr.port].join('/'))\n}\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: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\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: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass DefaultMultiaddr implements Multiaddr {\n public bytes: Uint8Array\n #string?: string\n #tuples?: Tuple[]\n #stringTuples?: StringTuple[]\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n if (addr instanceof Uint8Array) {\n this.bytes = codec.fromBytes(addr)\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 this.bytes = codec.fromString(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n this.bytes = codec.fromBytes(addr.bytes) // validate + copy buffer\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = codec.bytesToString(this.bytes)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\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\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\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\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\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\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\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.protoCodes().map(code => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n const codes: number[] = []\n const buf = this.bytes\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n const size = codec.sizeForAddr(p, buf.slice(i + n))\n\n i += (size + n)\n codes.push(code)\n }\n\n return codes\n }\n\n protoNames (): string[] {\n return this.protos().map(proto => proto.name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n if (this.#tuples == null) {\n this.#tuples = codec.bytesToTuples(this.bytes)\n }\n\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n if (this.#stringTuples == null) {\n this.#stringTuples = codec.tuplesToStringTuples(this.tuples())\n }\n\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new DefaultMultiaddr(addr)\n return new DefaultMultiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\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 DefaultMultiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new DefaultMultiaddr(codec.tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n const tuples = this.stringTuples().filter((tuple) => {\n if (tuple[0] === names.ipfs.code) {\n return true\n }\n return false\n })\n\n // Get the last ipfs tuple ['ipfs', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\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\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n let path = null\n try {\n path = this.stringTuples().filter((tuple) => {\n const proto = getProtocol(tuple[0])\n if (proto.path === true) {\n return true\n }\n return false\n })[0][1]\n\n if (path == null) {\n path = null\n }\n } catch {\n path = null\n }\n return path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: AbortOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const addresses = await resolver(this, options)\n return addresses.map((a) => new DefaultMultiaddr(a))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\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\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\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 /**\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] (): string {\n return `Multiaddr(${codec.bytesToString(this.bytes)})`\n }\n}\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?: MultiaddrInput): Multiaddr {\n return new DefaultMultiaddr(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createClear ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"clear\"]}\n */\n async function clear (options = {}) {\n const config = await repo.config.getAll(options)\n const removed = config.Bootstrap || []\n config.Bootstrap = []\n\n await repo.config.replace(config)\n\n return { Peers: removed.map(ma => multiaddr(ma)) }\n }\n\n return withTimeoutOption(clear)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createList ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"list\"]}\n */\n async function list (options = {}) {\n /** @type {string[]|null} */\n const peers = (await repo.config.get('Bootstrap', options))\n return { Peers: (peers || []).map(ma => multiaddr(ma)) }\n }\n\n return withTimeoutOption(list)\n}\n", "\nexport default () => ({\n Addresses: {\n Swarm: [\n ],\n Announce: [],\n NoAnnounce: [],\n API: '',\n Gateway: '',\n RPC: '',\n Delegates: [\n '/dns4/node0.delegate.ipfs.io/tcp/443/https',\n '/dns4/node1.delegate.ipfs.io/tcp/443/https',\n '/dns4/node2.delegate.ipfs.io/tcp/443/https',\n '/dns4/node3.delegate.ipfs.io/tcp/443/https'\n ]\n },\n Discovery: {\n MDNS: {\n Enabled: false,\n Interval: 10\n },\n webRTCStar: {\n Enabled: true\n }\n },\n Bootstrap: [\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt',\n '/dns4/node0.preload.ipfs.io/tcp/443/wss/p2p/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic',\n '/dns4/node1.preload.ipfs.io/tcp/443/wss/p2p/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6',\n '/dns4/node2.preload.ipfs.io/tcp/443/wss/p2p/QmV7gnbW5VTcJ3oyM2Xk1rdFBJ3kTkvxc87UFGsun29STS',\n '/dns4/node3.preload.ipfs.io/tcp/443/wss/p2p/QmY7JB6MQXhxHvq7dBDh4HpbH29v4yE9JRadAVpndvzySN'\n ],\n Pubsub: {\n Enabled: true\n },\n Swarm: {\n ConnMgr: {\n LowWater: 5,\n HighWater: 20\n },\n DisableNatPortMap: true\n },\n Routing: {\n Type: 'dhtclient'\n }\n})\n", "import defaultConfig from 'ipfs-core-config/config'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createReset ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"reset\"]}\n */\n async function reset (options = {}) {\n const config = await repo.config.getAll(options)\n config.Bootstrap = defaultConfig().Bootstrap\n\n await repo.config.replace(config)\n\n return {\n Peers: defaultConfig().Bootstrap.map(ma => multiaddr(ma))\n }\n }\n\n return withTimeoutOption(reset)\n}\n", "import { isValidMultiaddr } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createRm ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"rm\"]}\n */\n async function rm (multiaddr, options = {}) {\n if (!isValidMultiaddr(multiaddr)) {\n throw new Error(`${multiaddr} is not a valid Multiaddr`)\n }\n\n const config = await repo.config.getAll(options)\n config.Bootstrap = (config.Bootstrap || []).filter(ma => ma.toString() !== multiaddr.toString())\n\n await repo.config.replace(config)\n\n return { Peers: [multiaddr] }\n }\n\n return withTimeoutOption(rm)\n}\n", "import { createAdd } from './add.js'\nimport { createClear } from './clear.js'\nimport { createList } from './list.js'\nimport { createReset } from './reset.js'\nimport { createRm } from './rm.js'\nexport class BootstrapAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ repo }) {\n this.add = createAdd({ repo })\n this.list = createList({ repo })\n this.rm = createRm({ repo })\n this.clear = createClear({ repo })\n this.reset = createReset({ repo })\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').Preload} config.preload\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createGet ({ preload, repo }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"get\"]}\n */\n async function get (cid, options = {}) { // eslint-disable-line require-await\n if (options.preload !== false) {\n preload(cid)\n }\n\n return repo.blocks.get(cid, options)\n }\n\n return withTimeoutOption(get)\n}\n", "import { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n */\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n *\n */\nexport function createPut ({ codecs, hashers, repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"put\"]}\n */\n async function put (block, options = {}) {\n const release = options.pin ? await repo.gcLock.readLock() : null\n\n try {\n const cidVersion = options.version != null ? options.version : 0\n const codecName = options.format || (cidVersion === 0 ? 'dag-pb' : 'raw')\n\n const hasher = await hashers.getHasher(options.mhtype || 'sha2-256')\n const hash = await hasher.digest(block)\n const codec = await codecs.getCodec(codecName)\n const cid = CID.create(cidVersion, codec.code, hash)\n\n await repo.blocks.put(cid, block, {\n signal: options.signal\n })\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n if (options.pin === true) {\n await repo.pins.pinRecursively(cid, {\n signal: options.signal\n })\n }\n\n return cid\n } finally {\n if (release) {\n release()\n }\n }\n }\n\n return withTimeoutOption(put)\n}\n", "import errCode from 'err-code'\nimport parallel from 'it-parallel'\nimport map from 'it-map'\nimport filter from 'it-filter'\nimport { pipe } from 'it-pipe'\nimport { cleanCid } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst BLOCK_RM_CONCURRENCY = 8\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createRm ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"rm\"]}\n */\n async function * rm (cids, options = {}) {\n if (!Array.isArray(cids)) {\n cids = [cids]\n }\n\n // We need to take a write lock here to ensure that adding and removing\n // blocks are exclusive operations\n const release = await repo.gcLock.writeLock()\n\n try {\n yield * pipe(\n cids,\n source => map(source, cid => {\n return async () => {\n cid = cleanCid(cid)\n\n /** @type {import('ipfs-core-types/src/block').RmResult} */\n const result = { cid }\n\n try {\n const has = await repo.blocks.has(cid)\n\n if (!has) {\n throw errCode(new Error('block not found'), 'ERR_BLOCK_NOT_FOUND')\n }\n\n await repo.blocks.delete(cid)\n } catch (/** @type {any} */ err) {\n if (!options.force) {\n err.message = `cannot remove ${cid}: ${err.message}`\n result.error = err\n }\n }\n\n return result\n }\n }),\n source => parallel(source, { concurrency: BLOCK_RM_CONCURRENCY }),\n source => filter(source, () => !options.quiet)\n )\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(rm)\n}\n", "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", "/**\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 */\n\nimport defer from 'p-defer'\n\ninterface Operation {\n done: boolean\n ok: boolean\n err: Error\n value: T\n}\n\nconst CustomEvent = globalThis.CustomEvent ?? Event\n\nexport interface ParallelOptions {\n /**\n * How many jobs to execute in parallel (default: )\n */\n concurrency?: number\n ordered?: boolean\n}\n\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: Iterable<() => Promise> | AsyncIterable<() => Promise>, options: ParallelOptions = {}): AsyncGenerator {\n let concurrency = options.concurrency ?? Infinity\n\n if (concurrency < 1) {\n concurrency = Infinity\n }\n\n const ordered = options.ordered == null ? false : options.ordered\n const emitter = new EventTarget()\n\n const ops: Array> = []\n let slotAvailable = defer()\n let resultAvailable = defer()\n let sourceFinished = false\n let sourceErr: Error | undefined\n let opErred = false\n\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve()\n })\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\n if (opErred) {\n break\n }\n\n const op: any = {\n done: false\n }\n ops.push(op)\n\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\n sourceFinished = true\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n } catch (err: any) {\n sourceErr = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }\n })\n\n function valuesAvailable (): boolean {\n if (ordered) {\n return ops[0]?.done\n }\n\n return Boolean(ops.find(op => op.done))\n }\n\n function * yieldOrderedValues (): Generator {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0]\n ops.shift()\n\n if (op.ok) {\n yield op.value\n } else {\n // allow the source to exit\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n\n function * yieldUnOrderedValues (): Generator {\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\n if (op.ok) {\n yield op.value\n } else {\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n }\n }\n\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer()\n await resultAvailable.promise\n }\n\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr\n }\n\n if (ordered) {\n yield * yieldOrderedValues()\n } else {\n yield * yieldUnOrderedValues()\n }\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", "/**\n * Takes an (async) iterable and returns one with each item mapped by the passed\n * function\n */\nexport default async function * map (source: AsyncIterable | Iterable, func: (val: I) => O | Promise): AsyncGenerator {\n for await (const val of source) {\n yield func(val)\n }\n}\n", "\n/**\n * Filters the passed (async) iterable by using the filter function\n */\nexport default async function * filter (source: AsyncIterable | Iterable, fn: (val: T) => boolean | Promise): AsyncGenerator {\n for await (const entry of source) {\n if (await fn(entry)) {\n yield entry\n }\n }\n}\n", "import { CID } from 'multiformats/cid'\n\n/**\n * @param {string|Uint8Array|CID} cid\n */\nexport function cleanCid (cid) {\n if (cid instanceof Uint8Array) {\n return CID.decode(cid)\n }\n\n return CID.parse(cid.toString())\n}\n", "import { cleanCid } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\n\nexport function createStat ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n cid = cleanCid(cid)\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n const block = await repo.blocks.get(cid)\n\n return { cid, size: block.length }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { createGet } from './get.js'\nimport { createPut } from './put.js'\nimport { createRm } from './rm.js'\nimport { createStat } from './stat.js'\n\n/**\n * @typedef {import('../../types').Preload} Preload\n */\n\nexport class BlockAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-core-utils/src/multihashes').Multihashes} config.hashers\n * @param {import('ipfs-core-utils/src/multicodecs').Multicodecs} config.codecs\n * @param {Preload} config.preload\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ codecs, hashers, preload, repo }) {\n this.get = createGet({ preload, repo })\n this.put = createPut({ codecs, hashers, preload, repo })\n this.rm = createRm({ repo })\n this.stat = createStat({ preload, repo })\n }\n}\n", "import errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport blobToIt from 'blob-to-it'\nimport itPeekable from 'it-peekable'\nimport all from 'it-all'\nimport map from 'it-map'\nimport {\n isBytes,\n isReadableStream,\n isBlob\n} from './utils.js'\n\n/**\n * @template T\n * @param {T} thing\n */\nasync function * toAsyncIterable (thing) {\n yield thing\n}\n\n/**\n * @param {import('ipfs-core-types/src/utils').ToContent} input\n */\nexport async function normaliseContent (input) {\n // Bytes | String\n if (isBytes(input)) {\n return toAsyncIterable(toBytes(input))\n }\n\n if (typeof input === 'string' || input instanceof String) {\n return toAsyncIterable(toBytes(input.toString()))\n }\n\n // Blob\n if (isBlob(input)) {\n return blobToIt(input)\n }\n\n // Browser stream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // (Async)Iterator\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n /** @type {any} peekable */\n const peekable = itPeekable(input)\n\n /** @type {any} value */\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n return toAsyncIterable(new Uint8Array(0))\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n if (Number.isInteger(value)) {\n return toAsyncIterable(Uint8Array.from(await all(peekable)))\n }\n\n // (Async)Iterable\n if (isBytes(value) || typeof value === 'string' || value instanceof String) {\n return map(peekable, toBytes)\n }\n }\n\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {ArrayBuffer | ArrayBufferView | string | InstanceType | number[]} chunk\n */\nfunction toBytes (chunk) {\n if (chunk instanceof Uint8Array) {\n return chunk\n }\n\n if (ArrayBuffer.isView(chunk)) {\n return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n }\n\n if (chunk instanceof ArrayBuffer) {\n return new Uint8Array(chunk)\n }\n\n if (Array.isArray(chunk)) {\n return Uint8Array.from(chunk)\n }\n\n return uint8ArrayFromString(chunk.toString())\n}\n", "/**\n * @packageDocumentation\n *\n * Allows treating a browser readable stream as an async iterator.\n *\n * @example\n *\n * ```javascript\n * import toIt from 'browser-readablestream-to-it'\n * import all from 'it-all'\n *\n * const content = [0, 1, 2, 3, 4]\n *\n * const stream = new ReadableStream({\n * start(controller) {\n * for (let i = 0; i < content.length; i++) {\n * controller.enqueue(content[i])\n * }\n *\n * controller.close()\n * }\n * })\n *\n * const arr = await all(toIt(stream))\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * ## preventCancel\n *\n * By default a readable stream will have [.cancel](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/cancel) called on it once it has ended or\n * reading has stopped prematurely.\n *\n * To prevent this behaviour, pass `preventCancel: true` as an option:\n *\n * ```javascript\n * const arr = await all(toIt(stream, { preventCancel: true }))\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\n\nexport interface BrowserReadableStreamToItOptions {\n preventCancel?: boolean\n}\n\n/**\n * Turns a browser readable stream into an async iterable. Async iteration over\n * returned iterable will lock give stream, preventing any other consumer from\n * acquiring a reader. The lock will be released if iteration loop is broken. To\n * prevent stream cancelling optional `{ preventCancel: true }` could be passed\n * as a second argument.\n */\nexport default async function * browserReadableStreamToIt (stream: ReadableStream, options: BrowserReadableStreamToItOptions = {}): AsyncGenerator {\n const reader = stream.getReader()\n\n try {\n while (true) {\n const result = await reader.read()\n\n if (result.done) {\n return\n }\n\n yield result.value\n }\n } finally {\n if (options.preventCancel !== true) {\n await reader.cancel()\n }\n\n reader.releaseLock()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Allows reading Blob contents as an async iterator.\n *\n * @example\n *\n * ```javascript\n * import toIt from 'blob-to-it'\n * import all from 'it-all'\n *\n * const content = [ Uint8Array.from([0, 1, 2, 3, 4]) ]\n * const blob = new Blob(content)\n * const arr = await all(toIt(blob))\n *\n * console.info(arr) // [ [ 0, 1, 2, 3, 4 ] ]\n * ```\n */\n\nimport browserReadableStreamToIt from 'browser-readablestream-to-it'\n\nexport default function blobToIt (blob: Blob): AsyncIterable {\n if (typeof blob.stream === 'function') {\n return browserReadableStreamToIt(blob.stream())\n }\n\n // firefox < 69 does not support blob.stream()\n // @ts-expect-error - response.body is optional, but in practice it's a stream.\n return browserReadableStreamToIt(new Response(blob).body)\n}\n", "\ninterface Peek {\n peek: () => IteratorResult\n}\n\ninterface AsyncPeek {\n peek: () => Promise>\n}\n\ninterface Push {\n push: (value: T) => void\n}\n\ntype Peekable = Iterable & Peek & Push & Iterator\n\ntype AsyncPeekable = AsyncIterable & AsyncPeek & Push & AsyncIterator\n\nexport default function peekableIterator | AsyncIterable> (iterable: I): I extends Iterable\n ? Peekable\n : I extends AsyncIterable\n ? AsyncPeekable\n : never {\n // @ts-expect-error\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error\n : [iterable[Symbol.iterator](), Symbol.iterator]\n\n const queue: any[] = []\n\n // @ts-expect-error\n return {\n peek: () => {\n return iterator.next()\n },\n push: (value: any) => {\n queue.push(value)\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n }\n }\n\n return iterator.next()\n },\n [symbol] () {\n return this\n }\n }\n}\n", "\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nexport default async function all (source: AsyncIterable | Iterable): Promise {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n", "/**\n * @param {any} obj\n * @returns {obj is ArrayBufferView|ArrayBuffer}\n */\nexport function isBytes (obj) {\n return ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer\n}\n\n/**\n * @param {any} obj\n * @returns {obj is globalThis.Blob}\n */\nexport function isBlob (obj) {\n return obj.constructor &&\n (obj.constructor.name === 'Blob' || obj.constructor.name === 'File') &&\n typeof obj.stream === 'function'\n}\n\n/**\n * An object with a path or content property\n *\n * @param {any} obj\n * @returns {obj is import('ipfs-core-types/src/utils').ImportCandidate}\n */\nexport function isFileObject (obj) {\n return typeof obj === 'object' && (obj.path || obj.content)\n}\n\n/**\n * @param {any} value\n * @returns {value is ReadableStream}\n */\nexport const isReadableStream = (value) =>\n value && typeof value.getReader === 'function'\n", "import errCode from 'err-code'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport itPeekable from 'it-peekable'\nimport {\n isBytes,\n isBlob,\n isReadableStream,\n isFileObject\n} from './utils.js'\nimport {\n parseMtime,\n parseMode\n} from 'ipfs-unixfs'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ToContent} ToContent\n * @typedef {import('ipfs-unixfs-importer').ImportCandidate} ImporterImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidate} ImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * @param {ImportCandidate} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\n// eslint-disable-next-line complexity\nexport async function * normaliseCandidateSingle (input, normaliseContent) {\n if (input === null || input === undefined) {\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n }\n\n // String\n if (typeof input === 'string' || input instanceof String) {\n yield toFileObject(input.toString(), normaliseContent)\n return\n }\n\n // Uint8Array|ArrayBuffer|TypedArray\n // Blob|File\n if (isBytes(input) || isBlob(input)) {\n yield toFileObject(input, normaliseContent)\n return\n }\n\n // Browser ReadableStream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // Iterable\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n const peekable = itPeekable(input)\n\n /** @type {any} value **/\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n yield { content: [] }\n return\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n // (Async)Iterable\n // (Async)Iterable\n if (Number.isInteger(value) || isBytes(value) || typeof value === 'string' || value instanceof String) {\n yield toFileObject(peekable, normaliseContent)\n return\n }\n\n throw errCode(new Error('Unexpected input: multiple items passed - if you are using ipfs.add, please use ipfs.addAll instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n // { path, content: ? }\n // Note: Detected _after_ (Async)Iterable because Node.js fs.ReadStreams have a\n // `path` property that passes this check.\n if (isFileObject(input)) {\n yield toFileObject(input, normaliseContent)\n return\n }\n\n throw errCode(new Error('Unexpected input: cannot convert \"' + typeof input + '\" into ImportCandidate'), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {ImportCandidate} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\nasync function toFileObject (input, normaliseContent) {\n // @ts-expect-error - Those properties don't exist on most input types\n const { path, mode, mtime, content } = input\n\n /** @type {ImporterImportCandidate} */\n const file = {\n path: path || '',\n mode: parseMode(mode),\n mtime: parseMtime(mtime)\n }\n\n if (content) {\n file.content = await normaliseContent(content)\n } else if (!path) { // Not already a file object with path or content prop\n // @ts-expect-error - input still can be different ToContent\n file.content = await normaliseContent(input)\n }\n\n return file\n}\n", "import { normaliseContent } from './normalise-content.js'\nimport { normaliseCandidateSingle } from './normalise-candidate-single.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidate} ImportCandidate\n */\n\n/**\n * Transforms any of the `ipfs.add` input types into\n *\n * ```\n * AsyncIterable<{ path, mode, mtime, content: AsyncIterable }>\n * ```\n *\n * See https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options\n *\n * @param {ImportCandidate} input\n */\nexport function normaliseInput (input) {\n return normaliseCandidateSingle(input, normaliseContent)\n}\n", "import last from 'it-last'\nimport { normaliseInput } from 'ipfs-core-utils/files/normalise-input-single'\n\n/**\n * @param {object} context\n * @param {import('ipfs-core-types/src/root').API<{}>[\"addAll\"]} context.addAll\n */\nexport function createAdd ({ addAll }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"add\"]}\n */\n async function add (entry, options = {}) {\n // @ts-expect-error TODO: https://github.com/ipfs/js-ipfs/issues/3290\n const result = await last(addAll(normaliseInput(entry), options))\n // Note this should never happen as `addAll` should yield at least one item\n // but to satisfy type checker we perfom this check and for good measure\n // throw an error in case it does happen.\n if (result == null) {\n throw Error('Failed to add a file, if you see this please report a bug')\n }\n\n return result\n }\n\n return add\n}\n", "/**\n * Takes an (async) iterable that emits things and returns an async iterable that\n * emits those things in fixed-sized batches\n */\nexport default async function * batch (source: AsyncIterable | Iterable, size: number = 1): AsyncGenerator {\n let things: T[] = []\n\n if (size < 1) {\n size = 1\n }\n\n for await (const thing of source) {\n things.push(thing)\n\n while (things.length >= size) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n }\n\n while (things.length > 0) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n}\n", "import batch from 'it-batch'\n\ninterface Success {\n ok: true\n value: T\n}\n\ninterface Failure {\n ok: false\n err: Error\n}\n\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 * parallelBatch (source: AsyncIterable<() => Promise> | Iterable<() => Promise>, size: number = 1): AsyncGenerator {\n for await (const tasks of batch(source, size)) {\n const things: Array | Failure>> = tasks.map(\n async (p: () => Promise) => {\n return await p().then(value => ({ ok: true, value }), err => ({ ok: false, err }))\n })\n\n for (let i = 0; i < things.length; i++) {\n const result = await things[i]\n\n if (result.ok) {\n yield result.value\n } else {\n throw result.err\n }\n }\n }\n}\n", "import { bytes } from 'multiformats'\nimport { from } from 'multiformats/hashes/hasher'\n// @ts-expect-error no types\nimport mur from 'murmurhash3js-revisited'\n\n/**\n * @param {number} number\n * @returns {Uint8Array}\n */\nfunction fromNumberTo32BitBuf (number) {\n const bytes = new Array(4)\n for (let i = 0; i < 4; i++) {\n bytes[i] = number & 0xff\n number = number >> 8\n }\n return new Uint8Array(bytes)\n}\n\nexport const murmur332 = from({\n name: 'murmur3-32',\n code: 0x23,\n encode: (input) => fromNumberTo32BitBuf(mur.x86.hash32(input))\n})\n\nexport const murmur3128 = from({\n name: 'murmur3-128',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input))\n})\n\n// A special-use 0x22 that truncates 64 bits, specifically for use in the UnixFS HAMT\nexport const murmur364 = from({\n name: 'murmur3-x64-64',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input)).subarray(0, 8)\n})\n", "import mergeOptions from 'merge-options'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { murmur3128 } from '@multiformats/murmur3'\n\n/**\n * @param {Uint8Array} buf\n */\nasync function hamtHashFn (buf) {\n return (await murmur3128.encode(buf))\n // Murmur3 outputs 128 bit but, accidentally, IPFS Go's\n // implementation only uses the first 64, so we must do the same\n // for parity..\n .slice(0, 8)\n // Invert buffer because that's how Go impl does it\n .reverse()\n}\n\n/**\n * @typedef {import('./types').UserImporterOptions} UserImporterOptions\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n */\n\n/**\n * @type {ImporterOptions}\n */\nconst defaultOptions = {\n chunker: 'fixed',\n strategy: 'balanced', // 'flat', 'trickle'\n rawLeaves: false,\n onlyHash: false,\n reduceSingleLeafToSelf: true,\n hasher: sha256,\n leafType: 'file', // 'raw'\n cidVersion: 0,\n progress: () => () => {},\n shardSplitThreshold: 1000,\n fileImportConcurrency: 50,\n blockWriteConcurrency: 10,\n minChunkSize: 262144,\n maxChunkSize: 262144,\n avgChunkSize: 262144,\n window: 16,\n // FIXME: This number is too big for JavaScript\n // https://github.com/ipfs/go-ipfs-chunker/blob/d0125832512163708c0804a3cda060e21acddae4/rabin.go#L11\n polynomial: 17437180132763653, // eslint-disable-line no-loss-of-precision\n maxChildrenPerNode: 174,\n layerRepeat: 4,\n wrapWithDirectory: false,\n recursive: false,\n hidden: false,\n timeout: undefined,\n hamtHashFn,\n hamtHashCode: 0x22,\n hamtBucketBits: 8\n}\n\n/**\n * @param {UserImporterOptions} options\n * @returns {ImporterOptions}\n */\nexport default (options = {}) => {\n const defaults = mergeOptions.bind({ ignoreUndefined: true })\n return defaults(defaultOptions, options)\n}\n", "import { CID } from 'multiformats/cid'\nimport * as dagPb from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * @param {Uint8Array} buffer\n * @param {import('interface-blockstore').Blockstore} blockstore\n * @param {import('../types').PersistOptions} options\n */\nconst persist = async (buffer, blockstore, options) => {\n if (!options.codec) {\n options.codec = dagPb\n }\n\n if (!options.hasher) {\n options.hasher = sha256\n }\n\n if (options.cidVersion === undefined) {\n options.cidVersion = 1\n }\n\n if (options.codec === dagPb && options.hasher !== sha256) {\n options.cidVersion = 1\n }\n\n const multihash = await options.hasher.digest(buffer)\n const cid = CID.create(options.cidVersion, options.codec.code, multihash)\n\n if (!options.onlyHash) {\n await blockstore.put(cid, buffer, {\n signal: options.signal\n })\n }\n\n return cid\n}\n\nexport default persist\n", "import { UnixFS } from 'ipfs-unixfs'\nimport persist from '../utils/persist.js'\nimport { encode, prepare } from '@ipld/dag-pb'\n\n/**\n * @typedef {import('../types').Directory} Directory\n */\n\n/**\n * @type {import('../types').UnixFSV1DagBuilder}\n */\nconst dirBuilder = async (item, blockstore, options) => {\n const unixfs = new UnixFS({\n type: 'directory',\n mtime: item.mtime,\n mode: item.mode\n })\n\n const buffer = encode(prepare({ Data: unixfs.marshal() }))\n const cid = await persist(buffer, blockstore, options)\n const path = item.path\n\n return {\n cid,\n path,\n unixfs,\n size: buffer.length\n }\n}\n\nexport default dirBuilder\n", "import errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport persist from '../../utils/persist.js'\nimport { encode, prepare } from '@ipld/dag-pb'\nimport parallelBatch from 'it-parallel-batch'\nimport * as rawCodec from 'multiformats/codecs/raw'\nimport * as dagPb from '@ipld/dag-pb'\n\nimport dagFlat from './flat.js'\nimport dagBalanced from './balanced.js'\nimport dagTrickle from './trickle.js'\nimport bufferImporterFn from './buffer-importer.js'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../../types').File} File\n * @typedef {import('../../types').ImporterOptions} ImporterOptions\n * @typedef {import('../../types').Reducer} Reducer\n * @typedef {import('../../types').DAGBuilder} DAGBuilder\n * @typedef {import('../../types').FileDAGBuilder} FileDAGBuilder\n */\n\n/**\n * @type {{ [key: string]: FileDAGBuilder}}\n */\nconst dagBuilders = {\n flat: dagFlat,\n balanced: dagBalanced,\n trickle: dagTrickle\n}\n\n/**\n * @param {File} file\n * @param {Blockstore} blockstore\n * @param {ImporterOptions} options\n */\nasync function * buildFileBatch (file, blockstore, options) {\n let count = -1\n let previous\n let bufferImporter\n\n if (typeof options.bufferImporter === 'function') {\n bufferImporter = options.bufferImporter\n } else {\n bufferImporter = bufferImporterFn\n }\n\n for await (const entry of parallelBatch(bufferImporter(file, blockstore, options), options.blockWriteConcurrency)) {\n count++\n\n if (count === 0) {\n previous = entry\n continue\n } else if (count === 1 && previous) {\n yield previous\n previous = null\n }\n\n yield entry\n }\n\n if (previous) {\n previous.single = true\n yield previous\n }\n}\n\n/**\n * @param {File} file\n * @param {Blockstore} blockstore\n * @param {ImporterOptions} options\n */\nconst reduce = (file, blockstore, options) => {\n /**\n * @type {Reducer}\n */\n async function reducer (leaves) {\n if (leaves.length === 1 && leaves[0].single && options.reduceSingleLeafToSelf) {\n const leaf = leaves[0]\n\n if (file.mtime !== undefined || file.mode !== undefined) {\n // only one leaf node which is a buffer - we have metadata so convert it into a\n // UnixFS entry otherwise we'll have nowhere to store the metadata\n let buffer = await blockstore.get(leaf.cid)\n\n leaf.unixfs = new UnixFS({\n type: 'file',\n mtime: file.mtime,\n mode: file.mode,\n data: buffer\n })\n\n buffer = encode(prepare({ Data: leaf.unixfs.marshal() }))\n\n // // TODO vmx 2021-03-26: This is what the original code does, it checks\n // // the multihash of the original leaf node and uses then the same\n // // hasher. i wonder if that's really needed or if we could just use\n // // the hasher from `options.hasher` instead.\n // const multihash = mh.decode(leaf.cid.multihash.bytes)\n // let hasher\n // switch multihash {\n // case sha256.code {\n // hasher = sha256\n // break;\n // }\n // //case identity.code {\n // // hasher = identity\n // // break;\n // //}\n // default: {\n // throw new Error(`Unsupported hasher \"${multihash}\"`)\n // }\n // }\n leaf.cid = await persist(buffer, blockstore, {\n ...options,\n codec: dagPb,\n hasher: options.hasher,\n cidVersion: options.cidVersion\n })\n leaf.size = buffer.length\n }\n\n return {\n cid: leaf.cid,\n path: file.path,\n unixfs: leaf.unixfs,\n size: leaf.size\n }\n }\n\n // create a parent node and add all the leaves\n const f = new UnixFS({\n type: 'file',\n mtime: file.mtime,\n mode: file.mode\n })\n\n const links = leaves\n .filter(leaf => {\n if (leaf.cid.code === rawCodec.code && leaf.size) {\n return true\n }\n\n if (leaf.unixfs && !leaf.unixfs.data && leaf.unixfs.fileSize()) {\n return true\n }\n\n return Boolean(leaf.unixfs && leaf.unixfs.data && leaf.unixfs.data.length)\n })\n .map((leaf) => {\n if (leaf.cid.code === rawCodec.code) {\n // node is a leaf buffer\n f.addBlockSize(leaf.size)\n\n return {\n Name: '',\n Tsize: leaf.size,\n Hash: leaf.cid\n }\n }\n\n if (!leaf.unixfs || !leaf.unixfs.data) {\n // node is an intermediate node\n f.addBlockSize((leaf.unixfs && leaf.unixfs.fileSize()) || 0)\n } else {\n // node is a unixfs 'file' leaf node\n f.addBlockSize(leaf.unixfs.data.length)\n }\n\n return {\n Name: '',\n Tsize: leaf.size,\n Hash: leaf.cid\n }\n })\n\n const node = {\n Data: f.marshal(),\n Links: links\n }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, blockstore, options)\n\n return {\n cid,\n path: file.path,\n unixfs: f,\n size: buffer.length + node.Links.reduce((acc, curr) => acc + curr.Tsize, 0)\n }\n }\n\n return reducer\n}\n\n/**\n * @type {import('../../types').UnixFSV1DagBuilder}\n */\nfunction fileBuilder (file, block, options) {\n const dagBuilder = dagBuilders[options.strategy]\n\n if (!dagBuilder) {\n throw errCode(new Error(`Unknown importer build strategy name: ${options.strategy}`), 'ERR_BAD_STRATEGY')\n }\n\n return dagBuilder(buildFileBatch(file, block, options), reduce(file, block, options), options)\n}\n\nexport default fileBuilder\n", "import all from 'it-all'\n\n/**\n * @type {import('../../types').FileDAGBuilder}\n */\nasync function flat (source, reduce) {\n return reduce(await all(source))\n}\n\nexport default flat\n", "import batch from 'it-batch'\n\n/**\n * @typedef {import('../../types').FileDAGBuilder} FileDAGBuilder\n */\n\n/**\n * @type {FileDAGBuilder}\n */\nfunction balanced (source, reduce, options) {\n return reduceToParents(source, reduce, options)\n}\n\n/**\n * @type {FileDAGBuilder}\n */\nasync function reduceToParents (source, reduce, options) {\n const roots = []\n\n for await (const chunked of batch(source, options.maxChildrenPerNode)) {\n roots.push(await reduce(chunked))\n }\n\n if (roots.length > 1) {\n return reduceToParents(roots, reduce, options)\n }\n\n return roots[0]\n}\n\nexport default balanced\n", "import batch from 'it-batch'\n\n/**\n * @typedef {import('ipfs-unixfs').UnixFS} UnixFS\n * @typedef {import('../../types').ImporterOptions} ImporterOptions\n * @typedef {import('../../types').InProgressImportResult} InProgressImportResult\n * @typedef {import('../../types').TrickleDagNode} TrickleDagNode\n * @typedef {import('../../types').Reducer} Reducer\n * @typedef {import('../../types').FileDAGBuilder} FileDAGBuilder\n */\n\n/**\n * @type {FileDAGBuilder}\n */\nasync function trickleStream (source, reduce, options) {\n const root = new Root(options.layerRepeat)\n let iteration = 0\n let maxDepth = 1\n\n /** @type {SubTree} */\n let subTree = root\n\n for await (const layer of batch(source, options.maxChildrenPerNode)) {\n if (subTree.isFull()) {\n if (subTree !== root) {\n root.addChild(await subTree.reduce(reduce))\n }\n\n if (iteration && iteration % options.layerRepeat === 0) {\n maxDepth++\n }\n\n subTree = new SubTree(maxDepth, options.layerRepeat, iteration)\n\n iteration++\n }\n\n subTree.append(layer)\n }\n\n if (subTree && subTree !== root) {\n root.addChild(await subTree.reduce(reduce))\n }\n\n return root.reduce(reduce)\n}\n\nexport default trickleStream\n\nclass SubTree {\n /**\n * @param {number} maxDepth\n * @param {number} layerRepeat\n * @param {number} [iteration=0]\n */\n constructor (maxDepth, layerRepeat, iteration = 0) {\n this.maxDepth = maxDepth\n this.layerRepeat = layerRepeat\n this.currentDepth = 1\n this.iteration = iteration\n\n /** @type {TrickleDagNode} */\n this.root = this.node = this.parent = {\n children: [],\n depth: this.currentDepth,\n maxDepth,\n maxChildren: (this.maxDepth - this.currentDepth) * this.layerRepeat\n }\n }\n\n isFull () {\n if (!this.root.data) {\n return false\n }\n\n if (this.currentDepth < this.maxDepth && this.node.maxChildren) {\n // can descend\n this._addNextNodeToParent(this.node)\n\n return false\n }\n\n // try to find new node from node.parent\n const distantRelative = this._findParent(this.node, this.currentDepth)\n\n if (distantRelative) {\n this._addNextNodeToParent(distantRelative)\n\n return false\n }\n\n return true\n }\n\n /**\n * @param {TrickleDagNode} parent\n */\n _addNextNodeToParent (parent) {\n this.parent = parent\n\n // find site for new node\n const nextNode = {\n children: [],\n depth: parent.depth + 1,\n parent,\n maxDepth: this.maxDepth,\n maxChildren: Math.floor(parent.children.length / this.layerRepeat) * this.layerRepeat\n }\n\n // @ts-ignore\n parent.children.push(nextNode)\n\n this.currentDepth = nextNode.depth\n this.node = nextNode\n }\n\n /**\n *\n * @param {InProgressImportResult[]} layer\n */\n append (layer) {\n this.node.data = layer\n }\n\n /**\n * @param {Reducer} reduce\n */\n reduce (reduce) {\n return this._reduce(this.root, reduce)\n }\n\n /**\n * @param {TrickleDagNode} node\n * @param {Reducer} reduce\n * @returns {Promise}\n */\n async _reduce (node, reduce) {\n /** @type {InProgressImportResult[]} */\n let children = []\n\n if (node.children.length) {\n children = await Promise.all(\n node.children\n // @ts-ignore\n .filter(child => child.data)\n // @ts-ignore\n .map(child => this._reduce(child, reduce))\n )\n }\n\n return reduce((node.data || []).concat(children))\n }\n\n /**\n * @param {TrickleDagNode} node\n * @param {number} depth\n * @returns {TrickleDagNode | undefined}\n */\n _findParent (node, depth) {\n const parent = node.parent\n\n if (!parent || parent.depth === 0) {\n return\n }\n\n if (parent.children.length === parent.maxChildren || !parent.maxChildren) {\n // this layer is full, may be able to traverse to a different branch\n return this._findParent(parent, depth)\n }\n\n return parent\n }\n}\n\nclass Root extends SubTree {\n /**\n * @param {number} layerRepeat\n */\n constructor (layerRepeat) {\n super(0, layerRepeat)\n\n this.root.depth = 0\n this.currentDepth = 1\n }\n\n /**\n * @param {InProgressImportResult} child\n */\n addChild (child) {\n this.root.children.push(child)\n }\n\n /**\n * @param {Reducer} reduce\n */\n reduce (reduce) {\n return reduce((this.root.data || []).concat(this.root.children))\n }\n}\n", "import { UnixFS } from 'ipfs-unixfs'\nimport persist from '../../utils/persist.js'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as raw from 'multiformats/codecs/raw'\n\n/**\n * @typedef {import('../../types').BufferImporter} BufferImporter\n */\n\n/**\n * @type {BufferImporter}\n */\nasync function * bufferImporter (file, block, options) {\n for await (let buffer of file.content) {\n yield async () => {\n options.progress(buffer.length, file.path)\n let unixfs\n\n /** @type {import('../../types').PersistOptions} */\n const opts = {\n codec: dagPb,\n cidVersion: options.cidVersion,\n hasher: options.hasher,\n onlyHash: options.onlyHash\n }\n\n if (options.rawLeaves) {\n opts.codec = raw\n opts.cidVersion = 1\n } else {\n unixfs = new UnixFS({\n type: options.leafType,\n data: buffer\n })\n\n buffer = dagPb.encode({\n Data: unixfs.marshal(),\n Links: []\n })\n }\n\n return {\n cid: await persist(buffer, block, opts),\n unixfs,\n size: buffer.length\n }\n }\n }\n}\n\nexport default bufferImporter\n", "import dirBuilder from './dir.js'\nimport fileBuilder from './file/index.js'\nimport errCode from 'err-code'\nimport rabin from '../chunker/rabin.js'\nimport fixedSize from '../chunker/fixed-size.js'\nimport validateChunks from './validate-chunks.js'\n\n/**\n * @typedef {import('../types').File} File\n * @typedef {import('../types').Directory} Directory\n * @typedef {import('../types').DAGBuilder} DAGBuilder\n * @typedef {import('../types').Chunker} Chunker\n * @typedef {import('../types').ChunkValidator} ChunkValidator\n */\n\n/**\n * @param {any} thing\n * @returns {thing is Iterable}\n */\nfunction isIterable (thing) {\n return Symbol.iterator in thing\n}\n\n/**\n * @param {any} thing\n * @returns {thing is AsyncIterable}\n */\nfunction isAsyncIterable (thing) {\n return Symbol.asyncIterator in thing\n}\n\n/**\n * @param {Uint8Array | AsyncIterable | Iterable} content\n * @returns {AsyncIterable}\n */\nfunction contentAsAsyncIterable (content) {\n try {\n if (content instanceof Uint8Array) {\n return (async function * () {\n yield content\n }())\n } else if (isIterable(content)) {\n return (async function * () {\n yield * content\n }())\n } else if (isAsyncIterable(content)) {\n return content\n }\n } catch {\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n }\n\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n}\n\n/**\n * @type {DAGBuilder}\n */\nasync function * dagBuilder (source, blockstore, options) {\n for await (const entry of source) {\n if (entry.path) {\n if (entry.path.substring(0, 2) === './') {\n options.wrapWithDirectory = true\n }\n\n entry.path = entry.path\n .split('/')\n .filter(path => path && path !== '.')\n .join('/')\n }\n\n if (entry.content) {\n /**\n * @type {Chunker}\n */\n let chunker\n\n if (typeof options.chunker === 'function') {\n chunker = options.chunker\n } else if (options.chunker === 'rabin') {\n chunker = rabin\n } else {\n chunker = fixedSize\n }\n\n /**\n * @type {ChunkValidator}\n */\n let chunkValidator\n\n if (typeof options.chunkValidator === 'function') {\n chunkValidator = options.chunkValidator\n } else {\n chunkValidator = validateChunks\n }\n\n /** @type {File} */\n const file = {\n path: entry.path,\n mtime: entry.mtime,\n mode: entry.mode,\n content: chunker(chunkValidator(contentAsAsyncIterable(entry.content), options), options)\n }\n\n yield () => fileBuilder(file, blockstore, options)\n } else if (entry.path) {\n /** @type {Directory} */\n const dir = {\n path: entry.path,\n mtime: entry.mtime,\n mode: entry.mode\n }\n\n yield () => dirBuilder(dir, blockstore, options)\n } else {\n throw new Error('Import candidate must have content or path or both')\n }\n }\n}\n\nexport default dagBuilder\n", "/**\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'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\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: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\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 } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\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 } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\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\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\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\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\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\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\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: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\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\n return true\n }\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: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\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", "import { Uint8ArrayList } from 'uint8arraylist'\n// @ts-ignore\nimport { create } from 'rabin-wasm'\nimport errcode from 'err-code'\n\n/**\n * @typedef {object} RabinOptions\n * @property {number} min\n * @property {number} max\n * @property {number} bits\n * @property {number} window\n * @property {number} polynomial\n */\n\n/**\n * @type {import('../types').Chunker}\n */\nasync function * rabinChunker (source, options) {\n let min, max, avg\n\n if (options.minChunkSize && options.maxChunkSize && options.avgChunkSize) {\n avg = options.avgChunkSize\n min = options.minChunkSize\n max = options.maxChunkSize\n } else if (!options.avgChunkSize) {\n throw errcode(new Error('please specify an average chunk size'), 'ERR_INVALID_AVG_CHUNK_SIZE')\n } else {\n avg = options.avgChunkSize\n min = avg / 3\n max = avg + (avg / 2)\n }\n\n // validate min/max/avg in the same way as go\n if (min < 16) {\n throw errcode(new Error('rabin min must be greater than 16'), 'ERR_INVALID_MIN_CHUNK_SIZE')\n }\n\n if (max < min) {\n max = min\n }\n\n if (avg < min) {\n avg = min\n }\n\n const sizepow = Math.floor(Math.log2(avg))\n\n for await (const chunk of rabin(source, {\n min: min,\n max: max,\n bits: sizepow,\n window: options.window,\n polynomial: options.polynomial\n })) {\n yield chunk\n }\n}\n\nexport default rabinChunker\n\n/**\n * @param {AsyncIterable} source\n * @param {RabinOptions} options\n */\nasync function * rabin (source, options) {\n const r = await create(options.bits, options.min, options.max, options.window)\n const buffers = new Uint8ArrayList()\n\n for await (const chunk of source) {\n buffers.append(chunk)\n\n const sizes = r.fingerprint(chunk)\n\n for (let i = 0; i < sizes.length; i++) {\n const size = sizes[i]\n const buf = buffers.slice(0, size)\n buffers.consume(size)\n\n yield buf\n }\n }\n\n if (buffers.length) {\n yield buffers.subarray(0)\n }\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * @type {import('../types').Chunker}\n */\nasync function * fixedSizeChunker (source, options) {\n let list = new Uint8ArrayList()\n let currentLength = 0\n let emitted = false\n const maxChunkSize = options.maxChunkSize\n\n for await (const buffer of source) {\n list.append(buffer)\n\n currentLength += buffer.length\n\n while (currentLength >= maxChunkSize) {\n yield list.slice(0, maxChunkSize)\n emitted = true\n\n // throw away consumed bytes\n if (maxChunkSize === list.length) {\n list = new Uint8ArrayList()\n currentLength = 0\n } else {\n const newBl = new Uint8ArrayList()\n newBl.append(list.sublist(maxChunkSize))\n list = newBl\n\n // update our offset\n currentLength -= maxChunkSize\n }\n }\n }\n\n if (!emitted || currentLength) {\n // return any remaining bytes or an empty buffer\n yield list.subarray(0, currentLength)\n }\n}\n\nexport default fixedSizeChunker\n", "import errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\n/**\n * @typedef {import('../types').ChunkValidator} ChunkValidator\n */\n\n/**\n * @type {ChunkValidator}\n */\nasync function * validateChunks (source) {\n for await (const content of source) {\n if (content.length === undefined) {\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n }\n\n if (typeof content === 'string' || content instanceof String) {\n yield uint8ArrayFromString(content.toString())\n } else if (Array.isArray(content)) {\n yield Uint8Array.from(content)\n } else if (content instanceof Uint8Array) {\n yield content\n } else {\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n }\n }\n}\n\nexport default validateChunks\n", "/**\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n *\n * @typedef {object} DirProps\n * @property {boolean} root\n * @property {boolean} dir\n * @property {string} path\n * @property {boolean} dirty\n * @property {boolean} flat\n * @property {Dir} [parent]\n * @property {string} [parentKey]\n * @property {import('ipfs-unixfs').UnixFS} [unixfs]\n * @property {number} [mode]\n * @property {import('ipfs-unixfs').Mtime} [mtime]\n */\nclass Dir {\n /**\n * @param {DirProps} props\n * @param {ImporterOptions} options\n */\n constructor (props, options) {\n this.options = options || {}\n\n this.root = props.root\n this.dir = props.dir\n this.path = props.path\n this.dirty = props.dirty\n this.flat = props.flat\n this.parent = props.parent\n this.parentKey = props.parentKey\n this.unixfs = props.unixfs\n this.mode = props.mode\n this.mtime = props.mtime\n\n /** @type {CID | undefined} */\n this.cid = undefined\n /** @type {number | undefined} */\n this.size = undefined\n }\n\n /**\n * @param {string} name\n * @param {InProgressImportResult | Dir} value\n */\n async put (name, value) { }\n\n /**\n * @param {string} name\n * @returns {Promise}\n */\n get (name) {\n return Promise.resolve(this)\n }\n\n /**\n * @returns {AsyncIterable<{ key: string, child: InProgressImportResult | Dir}>}\n */\n async * eachChildSeries () { }\n\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) { }\n}\n\nexport default Dir\n", "import { encode, prepare } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport Dir from './dir.js'\nimport persist from './utils/persist.js'\n\n/**\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./dir').DirProps} DirProps\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\nclass DirFlat extends Dir {\n /**\n * @param {DirProps} props\n * @param {ImporterOptions} options\n */\n constructor (props, options) {\n super(props, options)\n\n /** @type {{ [key: string]: InProgressImportResult | Dir }} */\n this._children = {}\n }\n\n /**\n * @param {string} name\n * @param {InProgressImportResult | Dir} value\n */\n async put (name, value) {\n this.cid = undefined\n this.size = undefined\n\n this._children[name] = value\n }\n\n /**\n * @param {string} name\n */\n get (name) {\n return Promise.resolve(this._children[name])\n }\n\n childCount () {\n return Object.keys(this._children).length\n }\n\n directChildrenCount () {\n return this.childCount()\n }\n\n onlyChild () {\n return this._children[Object.keys(this._children)[0]]\n }\n\n async * eachChildSeries () {\n const keys = Object.keys(this._children)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n\n yield {\n key: key,\n child: this._children[key]\n }\n }\n }\n\n /**\n * @param {Blockstore} block\n * @returns {AsyncIterable}\n */\n async * flush (block) {\n const children = Object.keys(this._children)\n const links = []\n\n for (let i = 0; i < children.length; i++) {\n let child = this._children[children[i]]\n\n if (child instanceof Dir) {\n for await (const entry of child.flush(block)) {\n child = entry\n\n yield child\n }\n }\n\n if (child.size != null && child.cid) {\n links.push({\n Name: children[i],\n Tsize: child.size,\n Hash: child.cid\n })\n }\n }\n\n const unixfs = new UnixFS({\n type: 'directory',\n mtime: this.mtime,\n mode: this.mode\n })\n\n /** @type {PBNode} */\n const node = { Data: unixfs.marshal(), Links: links }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, block, this.options)\n const size = buffer.length + node.Links.reduce(\n /**\n * @param {number} acc\n * @param {PBLink} curr\n */\n (acc, curr) => acc + (curr.Tsize == null ? 0 : curr.Tsize),\n 0)\n\n this.cid = cid\n this.size = size\n\n yield {\n cid,\n unixfs,\n path: this.path,\n size\n }\n }\n}\n\nexport default DirFlat\n", "// @ts-expect-error no types\nimport SparseArray from 'sparse-array'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { InfiniteHash } from './consumable-hash.js'\n\nexport interface BucketChild {\n key: string\n value: V\n hash: InfiniteHash\n}\n\ninterface SA {\n length: number\n compactArray(): B[]\n get(i: number): B\n set(i: number, value: B): void\n reduce (fn: (acc: A, curr: B, index: number) => A, initial: A): B\n find(fn: (item: B) => boolean): B | undefined\n bitField(): number[]\n unset(i: number): void\n}\n\nexport interface BucketPosition {\n bucket: Bucket\n pos: number\n hash: InfiniteHash\n existingChild?: BucketChild\n}\n\nexport interface BucketOptions {\n bits: number\n hash(value: Uint8Array | InfiniteHash): InfiniteHash\n}\n\nexport class Bucket {\n _options: BucketOptions\n _popCount: number\n _parent?: Bucket\n _posAtParent: number\n _children: SA | BucketChild>\n\n key: string | null\n\n constructor (options: BucketOptions, parent?: Bucket, posAtParent = 0) {\n this._options = options\n this._popCount = 0\n this._parent = parent\n this._posAtParent = posAtParent\n this._children = new SparseArray()\n this.key = null\n }\n\n async put (key: string, value: T): Promise {\n const place = await this._findNewBucketAndPos(key)\n\n place.bucket._putAt(place, key, value)\n }\n\n async get (key: string): Promise {\n const child = await this._findChild(key)\n\n if (child != null) {\n return child.value\n }\n }\n\n async del (key: string): Promise {\n const place = await this._findPlace(key)\n const child = place.bucket._at(place.pos)\n\n if (child != null && child.key === key) {\n place.bucket._delAt(place.pos)\n }\n }\n\n leafCount (): number {\n const children = this._children.compactArray()\n\n return children.reduce((acc, child) => {\n if (child instanceof Bucket) {\n return acc + child.leafCount()\n }\n\n return acc + 1\n }, 0)\n }\n\n childrenCount (): number {\n return this._children.length\n }\n\n onlyChild (): Bucket | BucketChild {\n return this._children.get(0)\n }\n\n * eachLeafSeries (): Iterable> {\n const children = this._children.compactArray()\n\n for (const child of children) {\n if (child instanceof Bucket) {\n yield * child.eachLeafSeries()\n } else {\n yield child\n }\n }\n }\n\n serialize (map: (value: BucketChild, index: number) => M, reduce: (reduced: Bucket | BucketChild) => M): M {\n const acc: M[] = []\n // serialize to a custom non-sparse representation\n return reduce(this._children.reduce((acc, child, index) => {\n if (child != null) {\n if (child instanceof Bucket) {\n acc.push(child.serialize(map, reduce))\n } else {\n acc.push(map(child, index))\n }\n }\n return acc\n }, acc))\n }\n\n async asyncTransform (asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise): Promise {\n return asyncTransformBucket(this, asyncMap, asyncReduce)\n }\n\n toJSON (): Record {\n return this.serialize(mapNode, reduceNodes)\n }\n\n prettyPrint (): string {\n return JSON.stringify(this.toJSON(), null, ' ')\n }\n\n tableSize (): number {\n return Math.pow(2, this._options.bits)\n }\n\n async _findChild (key: string): Promise | undefined> {\n const result = await this._findPlace(key)\n const child = result.bucket._at(result.pos)\n\n if (child instanceof Bucket) {\n // should not be possible, this._findPlace should always\n // return a location for a child, not a bucket\n return undefined\n }\n\n if (child != null && child.key === key) {\n return child\n }\n }\n\n async _findPlace (key: string | InfiniteHash): Promise> {\n const hashValue = this._options.hash(typeof key === 'string' ? uint8ArrayFromString(key) : key)\n const index = await hashValue.take(this._options.bits)\n\n const child = this._children.get(index)\n\n if (child instanceof Bucket) {\n return child._findPlace(hashValue)\n }\n\n return {\n bucket: this,\n pos: index,\n hash: hashValue,\n existingChild: child\n }\n }\n\n async _findNewBucketAndPos (key: string | InfiniteHash): Promise> {\n const place = await this._findPlace(key)\n\n if ((place.existingChild != null) && place.existingChild.key !== key) {\n // conflict\n const bucket = new Bucket(this._options, place.bucket, place.pos)\n place.bucket._putObjectAt(place.pos, bucket)\n\n // put the previous value\n const newPlace = await bucket._findPlace(place.existingChild.hash)\n newPlace.bucket._putAt(newPlace, place.existingChild.key, place.existingChild.value)\n\n return bucket._findNewBucketAndPos(place.hash)\n }\n\n // no conflict, we found the place\n return place\n }\n\n _putAt (place: BucketPosition, key: string, value: T): void {\n this._putObjectAt(place.pos, {\n key,\n value,\n hash: place.hash\n })\n }\n\n _putObjectAt (pos: number, object: Bucket | BucketChild): void {\n if (this._children.get(pos) == null) {\n this._popCount++\n }\n this._children.set(pos, object)\n }\n\n _delAt (pos: number): void {\n if (pos === -1) {\n throw new Error('Invalid position')\n }\n\n if (this._children.get(pos) != null) {\n this._popCount--\n }\n this._children.unset(pos)\n this._level()\n }\n\n _level (): void {\n if (this._parent != null && this._popCount <= 1) {\n if (this._popCount === 1) {\n // remove myself from parent, replacing me with my only child\n const onlyChild = this._children.find(exists)\n\n if ((onlyChild != null) && !(onlyChild instanceof Bucket)) {\n const hash = onlyChild.hash\n hash.untake(this._options.bits)\n const place = {\n pos: this._posAtParent,\n hash,\n bucket: this._parent\n }\n this._parent._putAt(place, onlyChild.key, onlyChild.value)\n }\n } else {\n this._parent._delAt(this._posAtParent)\n }\n }\n }\n\n _at (index: number): Bucket | BucketChild {\n return this._children.get(index)\n }\n}\n\nfunction exists (o: any): boolean {\n return Boolean(o)\n}\n\nfunction mapNode (node: { key: string }, _: number): string {\n return node.key\n}\n\nfunction reduceNodes (nodes: T): any {\n return nodes\n}\n\nasync function asyncTransformBucket (bucket: Bucket, asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise): Promise {\n const output = []\n\n for (const child of bucket._children.compactArray()) {\n if (child instanceof Bucket) {\n await asyncTransformBucket(child, asyncMap, asyncReduce)\n } else {\n const mappedChildren = await asyncMap(child)\n\n output.push({\n bitField: bucket._children.bitField(),\n children: mappedChildren\n })\n }\n }\n\n return asyncReduce(output)\n}\n", "const START_MASKS = [\n 0b11111111,\n 0b11111110,\n 0b11111100,\n 0b11111000,\n 0b11110000,\n 0b11100000,\n 0b11000000,\n 0b10000000\n]\n\nconst STOP_MASKS = [\n 0b00000001,\n 0b00000011,\n 0b00000111,\n 0b00001111,\n 0b00011111,\n 0b00111111,\n 0b01111111,\n 0b11111111\n]\n\nexport class ConsumableBuffer {\n _value: Uint8Array\n _currentBytePos: number\n _currentBitPos: number\n\n constructor (value: Uint8Array) {\n this._value = value\n this._currentBytePos = value.length - 1\n this._currentBitPos = 7\n }\n\n availableBits (): number {\n return this._currentBitPos + 1 + this._currentBytePos * 8\n }\n\n totalBits (): number {\n return this._value.length * 8\n }\n\n take (bits: number): number {\n let pendingBits = bits\n let result = 0\n while (pendingBits > 0 && this._haveBits()) {\n const byte = this._value[this._currentBytePos]\n const availableBits = this._currentBitPos + 1\n const taking = Math.min(availableBits, pendingBits)\n const value = byteBitsToInt(byte, availableBits - taking, taking)\n result = (result << taking) + value\n\n pendingBits -= taking\n\n this._currentBitPos -= taking\n if (this._currentBitPos < 0) {\n this._currentBitPos = 7\n this._currentBytePos--\n }\n }\n\n return result\n }\n\n untake (bits: number): void {\n this._currentBitPos += bits\n while (this._currentBitPos > 7) {\n this._currentBitPos -= 8\n this._currentBytePos += 1\n }\n }\n\n _haveBits (): boolean {\n return this._currentBytePos >= 0\n }\n}\n\nfunction byteBitsToInt (byte: number, start: number, length: number): number {\n const mask = maskFor(start, length)\n return (byte & mask) >>> start\n}\n\nfunction maskFor (start: number, length: number): number {\n return START_MASKS[start] & STOP_MASKS[Math.min(length + start - 1, 7)]\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { ConsumableBuffer } from './consumable-buffer.js'\n\nexport function wrapHash (hashFn: (value: Uint8Array) => Promise): (value: InfiniteHash | Uint8Array) => InfiniteHash {\n function hashing (value: InfiniteHash | Uint8Array): InfiniteHash {\n if (value instanceof InfiniteHash) {\n // already a hash. return it\n return value\n } else {\n return new InfiniteHash(value, hashFn)\n }\n }\n\n return hashing\n}\n\nexport class InfiniteHash {\n _value: Uint8Array\n _hashFn: (value: Uint8Array) => Promise\n _depth: number\n _availableBits: number\n _currentBufferIndex: number\n _buffers: ConsumableBuffer[]\n\n constructor (value: Uint8Array, hashFn: (value: Uint8Array) => Promise) {\n if (!(value instanceof Uint8Array)) {\n throw new Error('can only hash Uint8Arrays')\n }\n\n this._value = value\n this._hashFn = hashFn\n this._depth = -1\n this._availableBits = 0\n this._currentBufferIndex = 0\n this._buffers = []\n }\n\n async take (bits: number): Promise {\n let pendingBits = bits\n\n while (this._availableBits < pendingBits) {\n await this._produceMoreBits()\n }\n\n let result = 0\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const available = Math.min(hash.availableBits(), pendingBits)\n const took = hash.take(available)\n result = (result << available) + took\n pendingBits -= available\n this._availableBits -= available\n\n if (hash.availableBits() === 0) {\n this._currentBufferIndex++\n }\n }\n\n return result\n }\n\n untake (bits: number): void {\n let pendingBits = bits\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const availableForUntake = Math.min(hash.totalBits() - hash.availableBits(), pendingBits)\n hash.untake(availableForUntake)\n pendingBits -= availableForUntake\n this._availableBits += availableForUntake\n\n if (this._currentBufferIndex > 0 && hash.totalBits() === hash.availableBits()) {\n this._depth--\n this._currentBufferIndex--\n }\n }\n }\n\n async _produceMoreBits (): Promise {\n this._depth++\n\n const value = this._depth > 0 ? uint8ArrayConcat([this._value, Uint8Array.from([this._depth])]) : this._value\n const hashValue = await this._hashFn(value)\n const buffer = new ConsumableBuffer(hashValue)\n\n this._buffers.push(buffer)\n this._availableBits += buffer.availableBits()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A [Hash Mapped Trie](https://en.wikipedia.org/wiki/Hash_array_mapped_trie) implementation for JavaScript.\n *\n * This is used by [@helia/unixfs](https://www.npmjs.com/package/@helia/unixfs) for it's HAMT-sharded directory implementation.\n *\n * @example\n *\n * ```TypeScript\n * import { createHAMT } from 'hamt-sharding'\n * import crypto from 'crypto-promise'\n *\n * // decide how to hash buffers made from keys, can return a Promise\n * const hashFn = async (buf) => {\n * return crypto\n * .createHash('sha256')\n * .update(buf)\n * .digest()\n * }\n *\n * const bucket = createHAMT({\n * hashFn: hashFn\n * })\n *\n * await bucket.put('key', 'value')\n *\n * const output = await bucket.get('key')\n * // output === 'value'\n * ```\n */\n\nimport { Bucket } from './bucket.js'\nimport { wrapHash } from './consumable-hash.js'\nimport type { BucketOptions, BucketPosition, BucketChild } from './bucket.js'\n\ninterface UserBucketOptions {\n hashFn(value: Uint8Array): Promise\n bits?: number\n}\n\nexport function createHAMT (options: UserBucketOptions): Bucket {\n if (options == null || options.hashFn == null) {\n throw new Error('please define an options.hashFn')\n }\n\n const bucketOptions = {\n bits: options.bits ?? 8,\n hash: wrapHash(options.hashFn)\n }\n\n return new Bucket(bucketOptions)\n}\n\nexport { Bucket }\nexport type { BucketOptions, BucketPosition, BucketChild }\n", "import { encode, prepare } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport Dir from './dir.js'\nimport persist from './utils/persist.js'\nimport { createHAMT, Bucket } from 'hamt-sharding'\n\n/**\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n */\n\n/**\n * @typedef {import('./dir').DirProps} DirProps\n */\n\nclass DirSharded extends Dir {\n /**\n * @param {DirProps} props\n * @param {ImporterOptions} options\n */\n constructor (props, options) {\n super(props, options)\n\n /** @type {Bucket} */\n this._bucket = createHAMT({\n hashFn: options.hamtHashFn,\n bits: options.hamtBucketBits\n })\n }\n\n /**\n * @param {string} name\n * @param {InProgressImportResult | Dir} value\n */\n async put (name, value) {\n await this._bucket.put(name, value)\n }\n\n /**\n * @param {string} name\n */\n get (name) {\n return this._bucket.get(name)\n }\n\n childCount () {\n return this._bucket.leafCount()\n }\n\n directChildrenCount () {\n return this._bucket.childrenCount()\n }\n\n onlyChild () {\n return this._bucket.onlyChild()\n }\n\n async * eachChildSeries () {\n for await (const { key, value } of this._bucket.eachLeafSeries()) {\n yield {\n key,\n child: value\n }\n }\n }\n\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) {\n for await (const entry of flush(this._bucket, blockstore, this, this.options)) {\n yield {\n ...entry,\n path: this.path\n }\n }\n }\n}\n\nexport default DirSharded\n\n/**\n * @param {Bucket} bucket\n * @param {Blockstore} blockstore\n * @param {*} shardRoot\n * @param {ImporterOptions} options\n * @returns {AsyncIterable}\n */\nasync function * flush (bucket, blockstore, shardRoot, options) {\n const children = bucket._children\n const links = []\n let childrenSize = 0\n\n for (let i = 0; i < children.length; i++) {\n const child = children.get(i)\n\n if (!child) {\n continue\n }\n\n const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0')\n\n if (child instanceof Bucket) {\n let shard\n\n for await (const subShard of await flush(child, blockstore, null, options)) {\n shard = subShard\n }\n\n if (!shard) {\n throw new Error('Could not flush sharded directory, no subshard found')\n }\n\n links.push({\n Name: labelPrefix,\n Tsize: shard.size,\n Hash: shard.cid\n })\n childrenSize += shard.size\n } else if (typeof child.value.flush === 'function') {\n const dir = child.value\n let flushedDir\n\n for await (const entry of dir.flush(blockstore)) {\n flushedDir = entry\n\n yield flushedDir\n }\n\n const label = labelPrefix + child.key\n links.push({\n Name: label,\n Tsize: flushedDir.size,\n Hash: flushedDir.cid\n })\n\n childrenSize += flushedDir.size\n } else {\n const value = child.value\n\n if (!value.cid) {\n continue\n }\n\n const label = labelPrefix + child.key\n const size = value.size\n\n links.push({\n Name: label,\n Tsize: size,\n Hash: value.cid\n })\n childrenSize += size\n }\n }\n\n // go-ipfs uses little endian, that's why we have to\n // reverse the bit field before storing it\n const data = Uint8Array.from(children.bitField().reverse())\n const dir = new UnixFS({\n type: 'hamt-sharded-directory',\n data,\n fanout: bucket.tableSize(),\n hashType: options.hamtHashCode,\n mtime: shardRoot && shardRoot.mtime,\n mode: shardRoot && shardRoot.mode\n })\n\n const node = {\n Data: dir.marshal(),\n Links: links\n }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, blockstore, options)\n const size = buffer.length + childrenSize\n\n yield {\n cid,\n unixfs: dir,\n size\n }\n}\n", "import DirSharded from './dir-sharded.js'\nimport DirFlat from './dir-flat.js'\n\n/**\n * @typedef {import('./dir').default} Dir\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n */\n\n/**\n * @param {Dir | null} child\n * @param {Dir} dir\n * @param {number} threshold\n * @param {ImporterOptions} options\n * @returns {Promise}\n */\nasync function flatToShard (child, dir, threshold, options) {\n let newDir = dir\n\n if (dir instanceof DirFlat && dir.directChildrenCount() >= threshold) {\n newDir = await convertToShard(dir, options)\n }\n\n const parent = newDir.parent\n\n if (parent) {\n if (newDir !== dir) {\n if (child) {\n child.parent = newDir\n }\n\n if (!newDir.parentKey) {\n throw new Error('No parent key found')\n }\n\n await parent.put(newDir.parentKey, newDir)\n }\n\n return flatToShard(newDir, parent, threshold, options)\n }\n\n // @ts-ignore\n return newDir\n}\n\n/**\n * @param {DirFlat} oldDir\n * @param {ImporterOptions} options\n */\nasync function convertToShard (oldDir, options) {\n const newDir = new DirSharded({\n root: oldDir.root,\n dir: true,\n parent: oldDir.parent,\n parentKey: oldDir.parentKey,\n path: oldDir.path,\n dirty: oldDir.dirty,\n flat: false,\n mtime: oldDir.mtime,\n mode: oldDir.mode\n }, options)\n\n for await (const { key, child } of oldDir.eachChildSeries()) {\n await newDir.put(key, child)\n }\n\n return newDir\n}\n\nexport default flatToShard\n", "const toPathComponents = (path = '') => {\n // split on / unless escaped with \\\n return (path\n .trim()\n .match(/([^\\\\/]|\\\\\\/)+/g) || [])\n .filter(Boolean)\n}\n\nexport default toPathComponents\n", "import DirFlat from './dir-flat.js'\nimport flatToShard from './flat-to-shard.js'\nimport Dir from './dir.js'\nimport toPathComponents from './utils/to-path-components.js'\n\n/**\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {(source: AsyncIterable, blockstore: Blockstore, options: ImporterOptions) => AsyncIterable} TreeBuilder\n */\n\n/**\n * @param {InProgressImportResult} elem\n * @param {Dir} tree\n * @param {ImporterOptions} options\n */\nasync function addToTree (elem, tree, options) {\n const pathElems = toPathComponents(elem.path || '')\n const lastIndex = pathElems.length - 1\n let parent = tree\n let currentPath = ''\n\n for (let i = 0; i < pathElems.length; i++) {\n const pathElem = pathElems[i]\n\n currentPath += `${currentPath ? '/' : ''}${pathElem}`\n\n const last = (i === lastIndex)\n parent.dirty = true\n parent.cid = undefined\n parent.size = undefined\n\n if (last) {\n await parent.put(pathElem, elem)\n tree = await flatToShard(null, parent, options.shardSplitThreshold, options)\n } else {\n let dir = await parent.get(pathElem)\n\n if (!dir || !(dir instanceof Dir)) {\n dir = new DirFlat({\n root: false,\n dir: true,\n parent: parent,\n parentKey: pathElem,\n path: currentPath,\n dirty: true,\n flat: true,\n mtime: dir && dir.unixfs && dir.unixfs.mtime,\n mode: dir && dir.unixfs && dir.unixfs.mode\n }, options)\n }\n\n await parent.put(pathElem, dir)\n\n parent = dir\n }\n }\n\n return tree\n}\n\n/**\n * @param {Dir | InProgressImportResult} tree\n * @param {Blockstore} blockstore\n */\nasync function * flushAndYield (tree, blockstore) {\n if (!(tree instanceof Dir)) {\n if (tree && tree.unixfs && tree.unixfs.isDirectory()) {\n yield tree\n }\n\n return\n }\n\n yield * tree.flush(blockstore)\n}\n\n/**\n * @type {TreeBuilder}\n */\nasync function * treeBuilder (source, block, options) {\n /** @type {Dir} */\n let tree = new DirFlat({\n root: true,\n dir: true,\n path: '',\n dirty: true,\n flat: true\n }, options)\n\n for await (const entry of source) {\n if (!entry) {\n continue\n }\n\n tree = await addToTree(entry, tree, options)\n\n if (!entry.unixfs || !entry.unixfs.isDirectory()) {\n yield entry\n }\n }\n\n if (options.wrapWithDirectory) {\n yield * flushAndYield(tree, block)\n } else {\n for await (const unwrapped of tree.eachChildSeries()) {\n if (!unwrapped) {\n continue\n }\n\n yield * flushAndYield(unwrapped.child, block)\n }\n }\n}\n\nexport default treeBuilder\n", "import parallelBatch from 'it-parallel-batch'\nimport defaultOptions from './options.js'\nimport dagBuilderFn from './dag-builder/index.js'\nimport treeBuilderFn from './tree-builder.js'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').ImportCandidate} ImportCandidate\n * @typedef {import('./types').UserImporterOptions} UserImporterOptions\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').Directory} Directory\n * @typedef {import('./types').File} File\n * @typedef {import('./types').ImportResult} ImportResult\n *\n * @typedef {import('./types').Chunker} Chunker\n * @typedef {import('./types').DAGBuilder} DAGBuilder\n * @typedef {import('./types').TreeBuilder} TreeBuilder\n * @typedef {import('./types').BufferImporter} BufferImporter\n * @typedef {import('./types').ChunkValidator} ChunkValidator\n * @typedef {import('./types').Reducer} Reducer\n * @typedef {import('./types').ProgressHandler} ProgressHandler\n */\n\n/**\n * @param {AsyncIterable | Iterable | ImportCandidate} source\n * @param {Blockstore} blockstore\n * @param {UserImporterOptions} options\n * @returns {AsyncGenerator}\n */\nexport async function * importer (source, blockstore, options = {}) {\n const opts = defaultOptions(options)\n\n let dagBuilder\n\n if (typeof options.dagBuilder === 'function') {\n dagBuilder = options.dagBuilder\n } else {\n dagBuilder = dagBuilderFn\n }\n\n let treeBuilder\n\n if (typeof options.treeBuilder === 'function') {\n treeBuilder = options.treeBuilder\n } else {\n treeBuilder = treeBuilderFn\n }\n\n /** @type {AsyncIterable | Iterable} */\n let candidates\n\n if (Symbol.asyncIterator in source || Symbol.iterator in source) {\n // @ts-ignore\n candidates = source\n } else {\n // @ts-ignore\n candidates = [source]\n }\n\n for await (const entry of treeBuilder(parallelBatch(dagBuilder(candidates, blockstore, opts), opts.fileImportConcurrency), blockstore, opts)) {\n yield {\n cid: entry.cid,\n path: entry.path,\n unixfs: entry.unixfs,\n size: entry.size\n }\n }\n}\n", "import errCode from 'err-code'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport itPeekable from 'it-peekable'\nimport map from 'it-map'\nimport {\n isBytes,\n isBlob,\n isReadableStream,\n isFileObject\n} from './utils.js'\nimport {\n parseMtime,\n parseMode\n} from 'ipfs-unixfs'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidate} ImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ToContent} ToContent\n * @typedef {import('ipfs-unixfs-importer').ImportCandidate} ImporterImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * @param {ImportCandidateStream} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\n// eslint-disable-next-line complexity\nexport async function * normaliseCandidateMultiple (input, normaliseContent) {\n // String\n // Uint8Array|ArrayBuffer|TypedArray\n // Blob|File\n // fs.ReadStream\n // @ts-expect-error _readableState is a property of a node fs.ReadStream\n if (typeof input === 'string' || input instanceof String || isBytes(input) || isBlob(input) || input._readableState) {\n throw errCode(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n // Browser ReadableStream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // Iterable\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n const peekable = itPeekable(input)\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n yield * []\n return\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n // (Async)Iterable\n if (Number.isInteger(value)) {\n throw errCode(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n // (Async)Iterable\n // @ts-expect-error private field\n if (value._readableState) {\n // @ts-expect-error Node fs.ReadStreams have a `.path` property so we need to pass it as the content\n yield * map(peekable, (/** @type {ImportCandidate} */ value) => toFileObject({ content: value }, normaliseContent))\n return\n }\n\n if (isBytes(value)) {\n // @ts-expect-error peekable is still an iterable of ImportCandidates\n yield toFileObject({ content: peekable }, normaliseContent)\n return\n }\n\n // (Async)Iterable<(Async)Iterable>\n // (Async)Iterable>\n // ReadableStream<(Async)Iterable>\n // ReadableStream>\n if (isFileObject(value) || value[Symbol.iterator] || value[Symbol.asyncIterator] || isReadableStream(value) || isBlob(value)) {\n yield * map(peekable, (/** @type {ImportCandidate} */ value) => toFileObject(value, normaliseContent))\n return\n }\n }\n\n // { path, content: ? }\n // Note: Detected _after_ (Async)Iterable because Node.js fs.ReadStreams have a\n // `path` property that passes this check.\n if (isFileObject(input)) {\n throw errCode(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {ImportCandidate} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\nasync function toFileObject (input, normaliseContent) {\n // @ts-expect-error - Those properties don't exist on most input types\n const { path, mode, mtime, content } = input\n\n /** @type {ImporterImportCandidate} */\n const file = {\n path: path || '',\n mode: parseMode(mode),\n mtime: parseMtime(mtime)\n }\n\n if (content) {\n file.content = await normaliseContent(content)\n } else if (!path) { // Not already a file object with path or content prop\n // @ts-expect-error - input still can be different ToContent\n file.content = await normaliseContent(input)\n }\n\n return file\n}\n", "import { normaliseContent } from './normalise-content.js'\nimport { normaliseCandidateMultiple } from './normalise-candidate-multiple.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * Transforms any of the `ipfs.addAll` input types into\n *\n * ```\n * AsyncIterable<{ path, mode, mtime, content: AsyncIterable }>\n * ```\n *\n * See https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options\n *\n * @param {ImportCandidateStream} input\n */\nexport function normaliseInput (input) {\n return normaliseCandidateMultiple(input, normaliseContent)\n}\n", "/**\n * @typedef {object} FixedChunkerOptions\n * @property {'fixed'} chunker\n * @property {number} [maxChunkSize]\n *\n * @typedef {object} RabinChunkerOptions\n * @property {'rabin'} chunker\n * @property {number} avgChunkSize\n * @property {number} [minChunkSize]\n * @property {number} [maxChunkSize]\n *\n * @typedef {FixedChunkerOptions|RabinChunkerOptions} ChunkerOptions\n *\n * Parses chunker string into options used by DAGBuilder in ipfs-unixfs-engine\n *\n *\n * @param {string} [chunker] - Chunker algorithm supported formats:\n * \"size-{size}\"\n * \"rabin\"\n * \"rabin-{avg}\"\n * \"rabin-{min}-{avg}-{max}\"\n *\n * @returns {ChunkerOptions} Chunker options for DAGBuilder\n */\nexport const parseChunkerString = (chunker) => {\n if (!chunker) {\n return {\n chunker: 'fixed'\n }\n } else if (chunker.startsWith('size-')) {\n const sizeStr = chunker.split('-')[1]\n const size = parseInt(sizeStr)\n if (isNaN(size)) {\n throw new Error('Chunker parameter size must be an integer')\n }\n return {\n chunker: 'fixed',\n maxChunkSize: size\n }\n } else if (chunker.startsWith('rabin')) {\n return {\n chunker: 'rabin',\n ...parseRabinString(chunker)\n }\n } else {\n throw new Error(`Unrecognized chunker option: ${chunker}`)\n }\n}\n\n/**\n * @typedef {object} RabinChunkerSettings\n * @property {number} avgChunkSize\n * @property {number} [minChunkSize]\n * @property {number} [maxChunkSize]\n *\n * Parses rabin chunker string\n *\n * @param {string} chunker - Chunker algorithm supported formats:\n * \"rabin\"\n * \"rabin-{avg}\"\n * \"rabin-{min}-{avg}-{max}\"\n *\n * @returns {RabinChunkerSettings} rabin chunker options\n */\nexport const parseRabinString = (chunker) => {\n const options = {}\n const parts = chunker.split('-')\n switch (parts.length) {\n case 1:\n options.avgChunkSize = 262144\n break\n case 2:\n options.avgChunkSize = parseChunkSize(parts[1], 'avg')\n break\n case 4:\n options.minChunkSize = parseChunkSize(parts[1], 'min')\n options.avgChunkSize = parseChunkSize(parts[2], 'avg')\n options.maxChunkSize = parseChunkSize(parts[3], 'max')\n break\n default:\n throw new Error('Incorrect chunker format (expected \"rabin\" \"rabin-[avg]\" or \"rabin-[min]-[avg]-[max]\"')\n }\n\n return options\n}\n\n/**\n *\n * @param {string} str\n * @param {string} name\n * @returns {number}\n */\nexport const parseChunkSize = (str, name) => {\n const size = parseInt(str)\n if (isNaN(size)) {\n throw new Error(`Chunker parameter ${name} must be an integer`)\n }\n\n return size\n}\n", "import { importer } from 'ipfs-unixfs-importer'\nimport { normaliseInput } from 'ipfs-core-utils/files/normalise-input-multiple'\nimport { parseChunkerString } from './utils.js'\nimport { pipe } from 'it-pipe'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport mergeOpts from 'merge-options'\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-unixfs-importer').ImportResult} ImportResult\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n */\n\n/**\n * @template T\n *\n * @typedef {import('it-stream-types').Source} Source\n */\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../../types').Preload} preload\n * @property {Multihashes} hashers\n * @property {import('ipfs-core-types/src/root').ShardingOptions} [options]\n * @param {Context} context\n */\nexport function createAddAll ({ repo, preload, hashers, options }) {\n const isShardingEnabled = options && options.sharding\n\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n const opts = mergeOptions({\n shardSplitThreshold: isShardingEnabled ? 1000 : Infinity,\n strategy: 'balanced'\n }, options, {\n ...parseChunkerString(options.chunker)\n })\n\n // CID v0 is for multihashes encoded with sha2-256\n if (opts.hashAlg && opts.hashAlg !== 'sha2-256' && opts.cidVersion !== 1) {\n opts.cidVersion = 1\n }\n\n if (opts.trickle) {\n opts.strategy = 'trickle'\n }\n\n if (opts.strategy === 'trickle') {\n opts.leafType = 'raw'\n opts.reduceSingleLeafToSelf = false\n }\n\n if (opts.cidVersion > 0 && opts.rawLeaves === undefined) {\n // if the cid version is 1 or above, use raw leaves as this is\n // what go does.\n opts.rawLeaves = true\n }\n\n if (opts.hashAlg !== undefined && opts.rawLeaves === undefined) {\n // if a non-default hash alg has been specified, use raw leaves as this is\n // what go does.\n opts.rawLeaves = true\n }\n\n delete opts.trickle\n\n /** @type {Record} */\n const totals = {}\n\n if (opts.progress) {\n const prog = opts.progress\n\n /**\n * @param {number} bytes\n * @param {string} path\n */\n opts.progress = (bytes, path) => {\n if (!totals[path]) {\n totals[path] = 0\n }\n\n totals[path] += bytes\n\n prog(totals[path], path)\n }\n }\n\n /** @type {MultihashHasher | undefined} */\n let hasher\n\n if (opts.hashAlg != null) {\n hasher = await hashers.getHasher(opts.hashAlg)\n }\n\n const iterator = pipe(\n normaliseInput(source),\n /**\n * @param {Source} source\n */\n source => importer(source, repo.blocks, {\n ...opts,\n hasher,\n pin: false\n }),\n transformFile(opts),\n preloadFile(preload, opts),\n pinFile(repo, opts)\n )\n\n const releaseLock = await repo.gcLock.readLock()\n\n try {\n for await (const added of iterator) {\n const path = added.path ?? added.cid.toString()\n\n // do not keep file totals around forever\n delete totals[path]\n\n yield {\n ...added,\n path\n }\n }\n } finally {\n releaseLock()\n }\n }\n\n return withTimeoutOption(addAll)\n}\n\n/**\n * @param {import('ipfs-core-types/src/root').AddAllOptions} opts\n */\nfunction transformFile (opts) {\n /**\n * @param {Source} source\n */\n async function * transformFile (source) {\n for await (const file of source) {\n let cid = file.cid\n\n if (opts.cidVersion === 1) {\n cid = cid.toV1()\n }\n\n let path = file.path ? file.path : cid.toString()\n\n if (opts.wrapWithDirectory && !file.path) {\n path = ''\n }\n\n yield {\n path,\n cid: cid,\n size: file.size,\n mode: file.unixfs && file.unixfs.mode,\n mtime: file.unixfs && file.unixfs.mtime\n }\n }\n }\n\n return transformFile\n}\n\n/**\n * @param {(cid: CID) => void} preload\n * @param {import('ipfs-core-types/src/root').AddAllOptions} opts\n */\nfunction preloadFile (preload, opts) {\n /**\n * @param {Source} source\n */\n async function * maybePreloadFile (source) {\n for await (const file of source) {\n const isRootFile = !file.path || opts.wrapWithDirectory\n ? file.path === ''\n : !file.path.includes('/')\n\n const shouldPreload = isRootFile && !opts.onlyHash && opts.preload !== false\n\n if (shouldPreload) {\n preload(file.cid)\n }\n\n yield file\n }\n }\n\n return maybePreloadFile\n}\n\n/**\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-types/src/root').AddAllOptions} opts\n */\nfunction pinFile (repo, opts) {\n /**\n * @param {Source} source\n */\n async function * maybePinFile (source) {\n for await (const file of source) {\n // Pin a file if it is the root dir of a recursive add or the single file\n // of a direct add.\n const isRootDir = !(file.path && file.path.includes('/'))\n const shouldPin = (opts.pin == null ? true : opts.pin) && isRootDir && !opts.onlyHash\n\n if (shouldPin) {\n await repo.pins.pinRecursively(file.cid)\n }\n\n yield file\n }\n }\n\n return maybePinFile\n}\n", "import errCode from 'err-code'\nimport { CID } from 'multiformats/cid'\nimport resolve from './resolvers/index.js'\nimport last from 'it-last'\n\n/**\n * @typedef {import('ipfs-unixfs').UnixFS} UnixFS\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').ExporterOptions} ExporterOptions\n * @typedef {import('./types').UnixFSFile} UnixFSFile\n * @typedef {import('./types').UnixFSDirectory} UnixFSDirectory\n * @typedef {import('./types').ObjectNode} ObjectNode\n * @typedef {import('./types').RawNode} RawNode\n * @typedef {import('./types').IdentityNode} IdentityNode\n * @typedef {import('./types').UnixFSEntry} UnixFSEntry\n */\n\nconst toPathComponents = (path = '') => {\n // split on / unless escaped with \\\n return (path\n .trim()\n .match(/([^\\\\^/]|\\\\\\/)+/g) || [])\n .filter(Boolean)\n}\n\n/**\n * @param {string|Uint8Array|CID} path\n */\nconst cidAndRest = (path) => {\n if (path instanceof Uint8Array) {\n return {\n cid: CID.decode(path),\n toResolve: []\n }\n }\n\n const cid = CID.asCID(path)\n if (cid) {\n return {\n cid,\n toResolve: []\n }\n }\n\n if (typeof path === 'string') {\n if (path.indexOf('/ipfs/') === 0) {\n path = path.substring(6)\n }\n\n const output = toPathComponents(path)\n\n return {\n cid: CID.parse(output[0]),\n toResolve: output.slice(1)\n }\n }\n\n throw errCode(new Error(`Unknown path type ${path}`), 'ERR_BAD_PATH')\n}\n\n/**\n * @param {string | CID} path\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} [options]\n */\nexport async function * walkPath (path, blockstore, options = {}) {\n let {\n cid,\n toResolve\n } = cidAndRest(path)\n let name = cid.toString()\n let entryPath = name\n const startingDepth = toResolve.length\n\n while (true) {\n const result = await resolve(cid, name, entryPath, toResolve, startingDepth, blockstore, options)\n\n if (!result.entry && !result.next) {\n throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND')\n }\n\n if (result.entry) {\n yield result.entry\n }\n\n if (!result.next) {\n return\n }\n\n // resolve further parts\n toResolve = result.next.toResolve\n cid = result.next.cid\n name = result.next.name\n entryPath = result.next.path\n }\n}\n\n/**\n * @param {string | CID} path\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} [options]\n */\nexport async function exporter (path, blockstore, options = {}) {\n const result = await last(walkPath(path, blockstore, options))\n\n if (!result) {\n throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND')\n }\n\n return result\n}\n\n/**\n * @param {string | CID} path\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} [options]\n */\nexport async function * recursive (path, blockstore, options = {}) {\n const node = await exporter(path, blockstore, options)\n\n if (!node) {\n return\n }\n\n yield node\n\n if (node.type === 'directory') {\n for await (const child of recurse(node, options)) {\n yield child\n }\n }\n\n /**\n * @param {UnixFSDirectory} node\n * @param {ExporterOptions} options\n * @returns {AsyncGenerator}\n */\n async function * recurse (node, options) {\n for await (const file of node.content(options)) {\n yield file\n\n if (file instanceof Uint8Array) {\n continue\n }\n\n if (file.type === 'directory') {\n yield * recurse(file, options)\n }\n }\n }\n}\n", "import errCode from 'err-code'\n\nimport * as dagPb from '@ipld/dag-pb'\nimport * as dagCbor from '@ipld/dag-cbor'\nimport * as raw from 'multiformats/codecs/raw'\nimport { identity } from 'multiformats/hashes/identity'\n\nimport dagPbResolver from './unixfs-v1/index.js'\nimport rawResolver from './raw.js'\nimport dagCborResolver from './dag-cbor.js'\nimport identifyResolver from './identity.js'\n\n/**\n * @typedef {import('../types').Resolver} Resolver\n * @typedef {import('../types').Resolve} Resolve\n */\n\n/**\n * @type {{ [ key: string ]: Resolver }}\n */\nconst resolvers = {\n [dagPb.code]: dagPbResolver,\n [raw.code]: rawResolver,\n [dagCbor.code]: dagCborResolver,\n [identity.code]: identifyResolver\n}\n\n/**\n * @type {Resolve}\n */\nfunction resolve (cid, name, path, toResolve, depth, blockstore, options) {\n const resolver = resolvers[cid.code]\n\n if (!resolver) {\n throw errCode(new Error(`No resolver for code ${cid.code}`), 'ERR_NO_RESOLVER')\n }\n\n return resolver(cid, name, path, toResolve, resolve, depth, blockstore, options)\n}\n\nexport default resolve\n", "const textDecoder = new TextDecoder()\n\n/**\n * @typedef {import('./interface').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface').RawPBNode} RawPBNode\n */\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[number, number]}\n */\nfunction decodeVarint (bytes, offset) {\n let v = 0\n\n for (let shift = 0; ; shift += 7) {\n /* c8 ignore next 3 */\n if (shift >= 64) {\n throw new Error('protobuf: varint overflow')\n }\n /* c8 ignore next 3 */\n if (offset >= bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n const b = bytes[offset++]\n v += shift < 28 ? (b & 0x7f) << shift : (b & 0x7f) * (2 ** shift)\n if (b < 0x80) {\n break\n }\n }\n return [v, offset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[Uint8Array, number]}\n */\nfunction decodeBytes (bytes, offset) {\n let byteLen\n ;[byteLen, offset] = decodeVarint(bytes, offset)\n const postOffset = offset + byteLen\n\n /* c8 ignore next 3 */\n if (byteLen < 0 || postOffset < 0) {\n throw new Error('protobuf: invalid length')\n }\n /* c8 ignore next 3 */\n if (postOffset > bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n return [bytes.subarray(offset, postOffset), postOffset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} index\n * @returns {[number, number, number]}\n */\nfunction decodeKey (bytes, index) {\n let wire\n ;[wire, index] = decodeVarint(bytes, index)\n // [wireType, fieldNum, newIndex]\n return [wire & 0x7, wire >> 3, index]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBLink}\n */\nfunction decodeLink (bytes) {\n /** @type {RawPBLink} */\n const link = {}\n const l = bytes.length\n let index = 0\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (fieldNum === 1) {\n if (link.Hash) {\n throw new Error('protobuf: (PBLink) duplicate Hash section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Hash`)\n }\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Name before Hash')\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Hash')\n }\n\n [link.Hash, index] = decodeBytes(bytes, index)\n } else if (fieldNum === 2) {\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Name section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Name`)\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Name')\n }\n\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n link.Name = textDecoder.decode(byts)\n } else if (fieldNum === 3) {\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Tsize section')\n }\n if (wireType !== 0) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Tsize`)\n }\n\n [link.Tsize, index] = decodeVarint(bytes, index)\n } else {\n throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBLink) unexpected end of data')\n }\n\n return link\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBNode}\n */\nexport function decodeNode (bytes) {\n const l = bytes.length\n let index = 0\n /** @type {RawPBLink[]|void} */\n let links\n let linksBeforeData = false\n /** @type {Uint8Array|void} */\n let data\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${wireType}`)\n }\n\n if (fieldNum === 1) {\n if (data) {\n throw new Error('protobuf: (PBNode) duplicate Data section')\n }\n\n [data, index] = decodeBytes(bytes, index)\n if (links) {\n linksBeforeData = true\n }\n } else if (fieldNum === 2) {\n if (linksBeforeData) { // interleaved Links/Data/Links\n throw new Error('protobuf: (PBNode) duplicate Links section')\n } else if (!links) {\n links = []\n }\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n links.push(decodeLink(byts))\n } else {\n throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBNode) unexpected end of data')\n }\n\n /** @type {RawPBNode} */\n const node = {}\n if (data) {\n node.Data = data\n }\n node.Links = links || []\n return node\n}\n", "const textEncoder = new TextEncoder()\nconst maxInt32 = 2 ** 32\nconst maxUInt32 = 2 ** 31\n\n/**\n * @typedef {import('./interface').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface').RawPBNode} RawPBNode\n */\n\n// the encoders work backward from the end of the bytes array\n\n/**\n * encodeLink() is passed a slice of the parent byte array that ends where this\n * link needs to end, so it packs to the right-most part of the passed `bytes`\n *\n * @param {RawPBLink} link\n * @param {Uint8Array} bytes\n * @returns {number}\n */\nfunction encodeLink (link, bytes) {\n let i = bytes.length\n\n if (typeof link.Tsize === 'number') {\n if (link.Tsize < 0) {\n throw new Error('Tsize cannot be negative')\n }\n if (!Number.isSafeInteger(link.Tsize)) {\n throw new Error('Tsize too large for encoding')\n }\n i = encodeVarint(bytes, i, link.Tsize) - 1\n bytes[i] = 0x18\n }\n\n if (typeof link.Name === 'string') {\n const nameBytes = textEncoder.encode(link.Name)\n i -= nameBytes.length\n bytes.set(nameBytes, i)\n i = encodeVarint(bytes, i, nameBytes.length) - 1\n bytes[i] = 0x12\n }\n\n if (link.Hash) {\n i -= link.Hash.length\n bytes.set(link.Hash, i)\n i = encodeVarint(bytes, i, link.Hash.length) - 1\n bytes[i] = 0xa\n }\n\n return bytes.length - i\n}\n\n/**\n * Encodes a PBNode into a new byte array of precisely the correct size\n *\n * @param {RawPBNode} node\n * @returns {Uint8Array}\n */\nexport function encodeNode (node) {\n const size = sizeNode(node)\n const bytes = new Uint8Array(size)\n let i = size\n\n if (node.Data) {\n i -= node.Data.length\n bytes.set(node.Data, i)\n i = encodeVarint(bytes, i, node.Data.length) - 1\n bytes[i] = 0xa\n }\n\n if (node.Links) {\n for (let index = node.Links.length - 1; index >= 0; index--) {\n const size = encodeLink(node.Links[index], bytes.subarray(0, i))\n i -= size\n i = encodeVarint(bytes, i, size) - 1\n bytes[i] = 0x12\n }\n }\n\n return bytes\n}\n\n/**\n * work out exactly how many bytes this link takes up\n *\n * @param {RawPBLink} link\n * @returns\n */\nfunction sizeLink (link) {\n let n = 0\n\n if (link.Hash) {\n const l = link.Hash.length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Name === 'string') {\n const l = textEncoder.encode(link.Name).length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Tsize === 'number') {\n n += 1 + sov(link.Tsize)\n }\n\n return n\n}\n\n/**\n * Work out exactly how many bytes this node takes up\n *\n * @param {RawPBNode} node\n * @returns {number}\n */\nfunction sizeNode (node) {\n let n = 0\n\n if (node.Data) {\n const l = node.Data.length\n n += 1 + l + sov(l)\n }\n\n if (node.Links) {\n for (const link of node.Links) {\n const l = sizeLink(link)\n n += 1 + l + sov(l)\n }\n }\n\n return n\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @param {number} v\n * @returns {number}\n */\nfunction encodeVarint (bytes, offset, v) {\n offset -= sov(v)\n const base = offset\n\n while (v >= maxUInt32) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v /= 128\n }\n\n while (v >= 128) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v >>>= 7\n }\n\n bytes[offset] = v\n\n return base\n}\n\n/**\n * size of varint\n *\n * @param {number} x\n * @returns {number}\n */\nfunction sov (x) {\n if (x % 2 === 0) {\n x++\n }\n return Math.floor((len64(x) + 6) / 7)\n}\n\n/**\n * golang math/bits, how many bits does it take to represent this integer?\n *\n * @param {number} x\n * @returns {number}\n */\nfunction len64 (x) {\n let n = 0\n if (x >= maxInt32) {\n x = Math.floor(x / maxInt32)\n n = 32\n }\n if (x >= (1 << 16)) {\n x >>>= 16\n n += 16\n }\n if (x >= (1 << 8)) {\n x >>>= 8\n n += 8\n }\n return n + len8tab[x]\n}\n\n// golang math/bits\nconst len8tab = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8\n]\n", "import { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./interface').PBLink} PBLink\n * @typedef {import('./interface').PBNode} PBNode\n */\n\nconst pbNodeProperties = ['Data', 'Links']\nconst pbLinkProperties = ['Hash', 'Name', 'Tsize']\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {PBLink} a\n * @param {PBLink} b\n * @returns {number}\n */\nfunction linkComparator (a, b) {\n if (a === b) {\n return 0\n }\n\n const abuf = a.Name ? textEncoder.encode(a.Name) : []\n const bbuf = b.Name ? textEncoder.encode(b.Name) : []\n\n let x = abuf.length\n let y = bbuf.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (abuf[i] !== bbuf[i]) {\n x = abuf[i]\n y = bbuf[i]\n break\n }\n }\n\n return x < y ? -1 : y < x ? 1 : 0\n}\n\n/**\n * @param {any} node\n * @param {string[]} properties\n * @returns {boolean}\n */\nfunction hasOnlyProperties (node, properties) {\n return !Object.keys(node).some((p) => !properties.includes(p))\n}\n\n/**\n * Converts a CID, or a PBLink-like object to a PBLink\n *\n * @param {any} link\n * @returns {PBLink}\n */\nfunction asLink (link) {\n if (typeof link.asCID === 'object') {\n const Hash = CID.asCID(link)\n if (!Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n return { Hash }\n }\n\n if (typeof link !== 'object' || Array.isArray(link)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n const pbl = {}\n\n if (link.Hash) {\n let cid = CID.asCID(link.Hash)\n try {\n if (!cid) {\n if (typeof link.Hash === 'string') {\n cid = CID.parse(link.Hash)\n } else if (link.Hash instanceof Uint8Array) {\n cid = CID.decode(link.Hash)\n }\n }\n } catch (/** @type {any} */ e) {\n throw new TypeError(`Invalid DAG-PB form: ${e.message}`)\n }\n\n if (cid) {\n pbl.Hash = cid\n }\n }\n\n if (!pbl.Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (typeof link.Name === 'string') {\n pbl.Name = link.Name\n }\n\n if (typeof link.Tsize === 'number') {\n pbl.Tsize = link.Tsize\n }\n\n return pbl\n}\n\n/**\n * @param {any} node\n * @returns {PBNode}\n */\nexport function prepare (node) {\n if (node instanceof Uint8Array || typeof node === 'string') {\n node = { Data: node }\n }\n\n if (typeof node !== 'object' || Array.isArray(node)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n /** @type {PBNode} */\n const pbn = {}\n\n if (node.Data !== undefined) {\n if (typeof node.Data === 'string') {\n pbn.Data = textEncoder.encode(node.Data)\n } else if (node.Data instanceof Uint8Array) {\n pbn.Data = node.Data\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n }\n\n if (node.Links !== undefined) {\n if (Array.isArray(node.Links)) {\n pbn.Links = node.Links.map(asLink)\n pbn.Links.sort(linkComparator)\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n } else {\n pbn.Links = []\n }\n\n return pbn\n}\n\n/**\n * @param {PBNode} node\n */\nexport function validate (node) {\n /*\n type PBLink struct {\n Hash optional Link\n Name optional String\n Tsize optional Int\n }\n\n type PBNode struct {\n Links [PBLink]\n Data optional Bytes\n }\n */\n // @ts-ignore private property for TS\n if (!node || typeof node !== 'object' || Array.isArray(node) || node instanceof Uint8Array || (node['/'] && node['/'] === node.bytes)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (!hasOnlyProperties(node, pbNodeProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties)')\n }\n\n if (node.Data !== undefined && !(node.Data instanceof Uint8Array)) {\n throw new TypeError('Invalid DAG-PB form (Data must be bytes)')\n }\n\n if (!Array.isArray(node.Links)) {\n throw new TypeError('Invalid DAG-PB form (Links must be a list)')\n }\n\n for (let i = 0; i < node.Links.length; i++) {\n const link = node.Links[i]\n // @ts-ignore private property for TS\n if (!link || typeof link !== 'object' || Array.isArray(link) || link instanceof Uint8Array || (link['/'] && link['/'] === link.bytes)) {\n throw new TypeError('Invalid DAG-PB form (bad link)')\n }\n\n if (!hasOnlyProperties(link, pbLinkProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties on link)')\n }\n\n if (link.Hash === undefined) {\n throw new TypeError('Invalid DAG-PB form (link must have a Hash)')\n }\n\n // @ts-ignore private property for TS\n if (link.Hash == null || !link.Hash['/'] || link.Hash['/'] !== link.Hash.bytes) {\n throw new TypeError('Invalid DAG-PB form (link Hash must be a CID)')\n }\n\n if (link.Name !== undefined && typeof link.Name !== 'string') {\n throw new TypeError('Invalid DAG-PB form (link Name must be a string)')\n }\n\n if (link.Tsize !== undefined) {\n if (typeof link.Tsize !== 'number' || link.Tsize % 1 !== 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize must be an integer)')\n }\n if (link.Tsize < 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize cannot be negative)')\n }\n }\n\n if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) {\n throw new TypeError('Invalid DAG-PB form (links must be sorted by Name bytes)')\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {PBLink[]} [links=[]]\n * @returns {PBNode}\n */\nexport function createNode (data, links = []) {\n return prepare({ Data: data, Links: links })\n}\n\n/**\n * @param {string} name\n * @param {number} size\n * @param {CID} cid\n * @returns {PBLink}\n */\nexport function createLink (name, size, cid) {\n return asLink({ Hash: cid, Name: name, Tsize: size })\n}\n", "import { CID } from 'multiformats/cid'\nimport { decodeNode } from './pb-decode.js'\nimport { encodeNode } from './pb-encode.js'\nimport { prepare, validate, createNode, createLink } from './util.js'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @typedef {import('./interface').PBLink} PBLink\n * @typedef {import('./interface').PBNode} PBNode\n */\n\nexport const name = 'dag-pb'\nexport const code = 0x70\n\n/**\n * @param {PBNode} node\n * @returns {ByteView}\n */\nexport function encode (node) {\n validate(node)\n\n const pbn = {}\n if (node.Links) {\n pbn.Links = node.Links.map((l) => {\n const link = {}\n if (l.Hash) {\n link.Hash = l.Hash.bytes // cid -> bytes\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n if (node.Data) {\n pbn.Data = node.Data\n }\n\n return encodeNode(pbn)\n}\n\n/**\n * @param {ByteView} bytes\n * @returns {PBNode}\n */\nexport function decode (bytes) {\n const pbn = decodeNode(bytes)\n\n const node = {}\n\n if (pbn.Data) {\n node.Data = pbn.Data\n }\n\n if (pbn.Links) {\n node.Links = pbn.Links.map((l) => {\n const link = {}\n try {\n link.Hash = CID.decode(l.Hash)\n } catch (e) {}\n if (!link.Hash) {\n throw new Error('Invalid Hash field found in link, expected CID')\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n\n return node\n}\n\nexport { prepare, validate, createNode, createLink }\n", "import errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport findShardCid from '../../utils/find-cid-in-shard.js'\nimport { decode } from '@ipld/dag-pb'\n\nimport contentFile from './content/file.js'\nimport contentDirectory from './content/directory.js'\nimport contentHamtShardedDirectory from './content/hamt-sharded-directory.js'\n\n/**\n * @typedef {import('../../types').Resolve} Resolve\n * @typedef {import('../../types').Resolver} Resolver\n * @typedef {import('../../types').UnixfsV1Resolver} UnixfsV1Resolver\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n */\n\n/**\n * @param {PBNode} node\n * @param {string} name\n */\nconst findLinkCid = (node, name) => {\n const link = node.Links.find(link => link.Name === name)\n\n return link && link.Hash\n}\n\n/**\n * @type {{ [key: string]: UnixfsV1Resolver }}\n */\nconst contentExporters = {\n raw: contentFile,\n file: contentFile,\n directory: contentDirectory,\n 'hamt-sharded-directory': contentHamtShardedDirectory,\n metadata: (cid, node, unixfs, path, resolve, depth, blockstore) => {\n return () => []\n },\n symlink: (cid, node, unixfs, path, resolve, depth, blockstore) => {\n return () => []\n }\n}\n\n/**\n * @type {Resolver}\n */\nconst unixFsResolver = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n const block = await blockstore.get(cid, options)\n const node = decode(block)\n let unixfs\n let next\n\n if (!name) {\n name = cid.toString()\n }\n\n if (node.Data == null) {\n throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS')\n }\n\n try {\n unixfs = UnixFS.unmarshal(node.Data)\n } catch (/** @type {any} */ err) {\n // non-UnixFS dag-pb node? It could happen.\n throw errCode(err, 'ERR_NOT_UNIXFS')\n }\n\n if (!path) {\n path = name\n }\n\n if (toResolve.length) {\n let linkCid\n\n if (unixfs && unixfs.type === 'hamt-sharded-directory') {\n // special case - unixfs v1 hamt shards\n linkCid = await findShardCid(node, toResolve[0], blockstore)\n } else {\n linkCid = findLinkCid(node, toResolve[0])\n }\n\n if (!linkCid) {\n throw errCode(new Error('file does not exist'), 'ERR_NOT_FOUND')\n }\n\n // remove the path component we have resolved\n const nextName = toResolve.shift()\n const nextPath = `${path}/${nextName}`\n\n next = {\n cid: linkCid,\n toResolve,\n name: nextName || '',\n path: nextPath\n }\n }\n\n return {\n entry: {\n type: unixfs.isDirectory() ? 'directory' : 'file',\n name,\n path,\n cid,\n // @ts-ignore\n content: contentExporters[unixfs.type](cid, node, unixfs, path, resolve, depth, blockstore),\n unixfs,\n depth,\n node,\n size: unixfs.fileSize()\n },\n next\n }\n}\n\nexport default unixFsResolver\n", "// @ts-expect-error\nimport SparseArray from 'sparse-array'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { InfiniteHash } from './consumable-hash.js'\n\nexport interface BucketChild {\n key: string\n value: V\n hash: InfiniteHash\n}\n\ninterface SA {\n length: number\n compactArray: () => B[]\n get: (i: number) => B\n set: (i: number, value: B) => void\n reduce: (fn: (acc: A, curr: B, index: number) => A, initial: A) => B\n find: (fn: (item: B) => boolean) => B | undefined\n bitField: () => number[]\n unset: (i: number) => void\n}\n\nexport interface BucketPosition {\n bucket: Bucket\n pos: number\n hash: InfiniteHash\n existingChild?: BucketChild\n}\n\nexport interface BucketOptions {\n bits: number\n hash: (value: Uint8Array | InfiniteHash) => InfiniteHash\n}\n\nexport class Bucket {\n _options: BucketOptions\n _popCount: number\n _parent?: Bucket\n _posAtParent: number\n _children: SA | BucketChild>\n\n key: string | null\n\n constructor (options: BucketOptions, parent?: Bucket, posAtParent = 0) {\n this._options = options\n this._popCount = 0\n this._parent = parent\n this._posAtParent = posAtParent\n this._children = new SparseArray()\n this.key = null\n }\n\n async put (key: string, value: T) {\n const place = await this._findNewBucketAndPos(key)\n\n await place.bucket._putAt(place, key, value)\n }\n\n async get (key: string) {\n const child = await this._findChild(key)\n\n if (child != null) {\n return child.value\n }\n }\n\n async del (key: string) {\n const place = await this._findPlace(key)\n const child = place.bucket._at(place.pos)\n\n if (child != null && child.key === key) {\n place.bucket._delAt(place.pos)\n }\n }\n\n leafCount (): number {\n const children = this._children.compactArray()\n\n return children.reduce((acc, child) => {\n if (child instanceof Bucket) {\n return acc + child.leafCount()\n }\n\n return acc + 1\n }, 0)\n }\n\n childrenCount () {\n return this._children.length\n }\n\n onlyChild () {\n return this._children.get(0)\n }\n\n * eachLeafSeries (): Iterable> {\n const children = this._children.compactArray()\n\n for (const child of children) {\n if (child instanceof Bucket) {\n yield * child.eachLeafSeries()\n } else {\n yield child\n }\n }\n }\n\n serialize (map: (value: BucketChild, index: number) => T, reduce: (reduced: any) => any) {\n const acc: T[] = []\n // serialize to a custom non-sparse representation\n return reduce(this._children.reduce((acc, child, index) => {\n if (child != null) {\n if (child instanceof Bucket) {\n acc.push(child.serialize(map, reduce))\n } else {\n acc.push(map(child, index))\n }\n }\n return acc\n }, acc))\n }\n\n async asyncTransform (asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise) {\n return await asyncTransformBucket(this, asyncMap, asyncReduce)\n }\n\n toJSON () {\n return this.serialize(mapNode, reduceNodes)\n }\n\n prettyPrint () {\n return JSON.stringify(this.toJSON(), null, ' ')\n }\n\n tableSize () {\n return Math.pow(2, this._options.bits)\n }\n\n async _findChild (key: string) {\n const result = await this._findPlace(key)\n const child = result.bucket._at(result.pos)\n\n if (child instanceof Bucket) {\n // should not be possible, this._findPlace should always\n // return a location for a child, not a bucket\n return undefined\n }\n\n if (child != null && child.key === key) {\n return child\n }\n }\n\n async _findPlace (key: string | InfiniteHash): Promise> {\n const hashValue = this._options.hash(typeof key === 'string' ? uint8ArrayFromString(key) : key)\n const index = await hashValue.take(this._options.bits)\n\n const child = this._children.get(index)\n\n if (child instanceof Bucket) {\n return await child._findPlace(hashValue)\n }\n\n return {\n bucket: this,\n pos: index,\n hash: hashValue,\n existingChild: child\n }\n }\n\n async _findNewBucketAndPos (key: string | InfiniteHash): Promise> {\n const place = await this._findPlace(key)\n\n if ((place.existingChild != null) && place.existingChild.key !== key) {\n // conflict\n const bucket = new Bucket(this._options, place.bucket, place.pos)\n place.bucket._putObjectAt(place.pos, bucket)\n\n // put the previous value\n const newPlace = await bucket._findPlace(place.existingChild.hash)\n newPlace.bucket._putAt(newPlace, place.existingChild.key, place.existingChild.value)\n\n return await bucket._findNewBucketAndPos(place.hash)\n }\n\n // no conflict, we found the place\n return place\n }\n\n _putAt (place: BucketPosition, key: string, value: T) {\n this._putObjectAt(place.pos, {\n key: key,\n value: value,\n hash: place.hash\n })\n }\n\n _putObjectAt (pos: number, object: Bucket | BucketChild) {\n if (this._children.get(pos) == null) {\n this._popCount++\n }\n this._children.set(pos, object)\n }\n\n _delAt (pos: number) {\n if (pos === -1) {\n throw new Error('Invalid position')\n }\n\n if (this._children.get(pos) != null) {\n this._popCount--\n }\n this._children.unset(pos)\n this._level()\n }\n\n _level () {\n if (this._parent != null && this._popCount <= 1) {\n if (this._popCount === 1) {\n // remove myself from parent, replacing me with my only child\n const onlyChild = this._children.find(exists)\n\n if ((onlyChild != null) && !(onlyChild instanceof Bucket)) {\n const hash = onlyChild.hash\n hash.untake(this._options.bits)\n const place = {\n pos: this._posAtParent,\n hash: hash,\n bucket: this._parent\n }\n this._parent._putAt(place, onlyChild.key, onlyChild.value)\n }\n } else {\n this._parent._delAt(this._posAtParent)\n }\n }\n }\n\n _at (index: number) {\n return this._children.get(index)\n }\n}\n\nfunction exists (o: any) {\n return Boolean(o)\n}\n\nfunction mapNode (node: any, _: number) {\n return node.key\n}\n\nfunction reduceNodes (nodes: any) {\n return nodes\n}\n\nasync function asyncTransformBucket (bucket: Bucket, asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise) {\n const output = []\n\n for (const child of bucket._children.compactArray()) {\n if (child instanceof Bucket) {\n await asyncTransformBucket(child, asyncMap, asyncReduce)\n } else {\n const mappedChildren = await asyncMap(child)\n\n output.push({\n bitField: bucket._children.bitField(),\n children: mappedChildren\n })\n }\n }\n\n return await asyncReduce(output)\n}\n", "const START_MASKS = [\n 0b11111111,\n 0b11111110,\n 0b11111100,\n 0b11111000,\n 0b11110000,\n 0b11100000,\n 0b11000000,\n 0b10000000\n]\n\nconst STOP_MASKS = [\n 0b00000001,\n 0b00000011,\n 0b00000111,\n 0b00001111,\n 0b00011111,\n 0b00111111,\n 0b01111111,\n 0b11111111\n]\n\nexport class ConsumableBuffer {\n _value: Uint8Array\n _currentBytePos: number\n _currentBitPos: number\n\n constructor (value: Uint8Array) {\n this._value = value\n this._currentBytePos = value.length - 1\n this._currentBitPos = 7\n }\n\n availableBits () {\n return this._currentBitPos + 1 + this._currentBytePos * 8\n }\n\n totalBits () {\n return this._value.length * 8\n }\n\n take (bits: number) {\n let pendingBits = bits\n let result = 0\n while (pendingBits > 0 && this._haveBits()) {\n const byte = this._value[this._currentBytePos]\n const availableBits = this._currentBitPos + 1\n const taking = Math.min(availableBits, pendingBits)\n const value = byteBitsToInt(byte, availableBits - taking, taking)\n result = (result << taking) + value\n\n pendingBits -= taking\n\n this._currentBitPos -= taking\n if (this._currentBitPos < 0) {\n this._currentBitPos = 7\n this._currentBytePos--\n }\n }\n\n return result\n }\n\n untake (bits: number) {\n this._currentBitPos += bits\n while (this._currentBitPos > 7) {\n this._currentBitPos -= 8\n this._currentBytePos += 1\n }\n }\n\n _haveBits () {\n return this._currentBytePos >= 0\n }\n}\n\nfunction byteBitsToInt (byte: number, start: number, length: number) {\n const mask = maskFor(start, length)\n return (byte & mask) >>> start\n}\n\nfunction maskFor (start: number, length: number) {\n return START_MASKS[start] & STOP_MASKS[Math.min(length + start - 1, 7)]\n}\n", "import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed ArrayLikes\n */\nexport function concat (arrays: Array>, length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "import { ConsumableBuffer } from './consumable-buffer.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nexport function wrapHash (hashFn: (value: Uint8Array) => Promise) {\n function hashing (value: InfiniteHash | Uint8Array) {\n if (value instanceof InfiniteHash) {\n // already a hash. return it\n return value\n } else {\n return new InfiniteHash(value, hashFn)\n }\n }\n\n return hashing\n}\n\nexport class InfiniteHash {\n _value: Uint8Array\n _hashFn: (value: Uint8Array) => Promise\n _depth: number\n _availableBits: number\n _currentBufferIndex: number\n _buffers: ConsumableBuffer[]\n\n constructor (value: Uint8Array, hashFn: (value: Uint8Array) => Promise) {\n if (!(value instanceof Uint8Array)) {\n throw new Error('can only hash Uint8Arrays')\n }\n\n this._value = value\n this._hashFn = hashFn\n this._depth = -1\n this._availableBits = 0\n this._currentBufferIndex = 0\n this._buffers = []\n }\n\n async take (bits: number) {\n let pendingBits = bits\n\n while (this._availableBits < pendingBits) {\n await this._produceMoreBits()\n }\n\n let result = 0\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const available = Math.min(hash.availableBits(), pendingBits)\n const took = hash.take(available)\n result = (result << available) + took\n pendingBits -= available\n this._availableBits -= available\n\n if (hash.availableBits() === 0) {\n this._currentBufferIndex++\n }\n }\n\n return result\n }\n\n untake (bits: number) {\n let pendingBits = bits\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const availableForUntake = Math.min(hash.totalBits() - hash.availableBits(), pendingBits)\n hash.untake(availableForUntake)\n pendingBits -= availableForUntake\n this._availableBits += availableForUntake\n\n if (this._currentBufferIndex > 0 && hash.totalBits() === hash.availableBits()) {\n this._depth--\n this._currentBufferIndex--\n }\n }\n }\n\n async _produceMoreBits () {\n this._depth++\n\n const value = this._depth > 0 ? uint8ArrayConcat([this._value, Uint8Array.from([this._depth])]) : this._value\n const hashValue = await this._hashFn(value)\n const buffer = new ConsumableBuffer(hashValue)\n\n this._buffers.push(buffer)\n this._availableBits += buffer.availableBits()\n }\n}\n", "import { Bucket } from './bucket.js'\nimport type { BucketOptions, BucketPosition, BucketChild } from './bucket.js'\nimport { wrapHash } from './consumable-hash.js'\n\ninterface UserBucketOptions {\n hashFn: (value: Uint8Array) => Promise\n bits?: number\n}\n\nexport function createHAMT (options: UserBucketOptions) {\n if (options == null || options.hashFn == null) {\n throw new Error('please define an options.hashFn')\n }\n\n const bucketOptions = {\n bits: options.bits ?? 8,\n hash: wrapHash(options.hashFn)\n }\n\n return new Bucket(bucketOptions)\n}\n\nexport { Bucket }\nexport type { BucketOptions, BucketPosition, BucketChild }\n", "import { from } from 'multiformats/hashes/hasher'\nimport { bytes } from 'multiformats'\n// @ts-expect-error no types\nimport mur from 'murmurhash3js-revisited'\n\n/**\n * @param {number} number\n * @returns {Uint8Array}\n */\nfunction fromNumberTo32BitBuf (number) {\n const bytes = new Array(4)\n for (let i = 0; i < 4; i++) {\n bytes[i] = number & 0xff\n number = number >> 8\n }\n return new Uint8Array(bytes)\n}\n\nexport const murmur332 = from({\n name: 'murmur3-32',\n code: 0x23,\n encode: (input) => fromNumberTo32BitBuf(mur.x86.hash32(input))\n})\n\nexport const murmur3128 = from({\n name: 'murmur3-128',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input))\n})\n\n// A special-use 0x22 that truncates 64 bits, specifically for use in the UnixFS HAMT\nexport const murmur364 = from({\n name: 'murmur3-x64-64',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input)).subarray(0, 8)\n})\n", "\nimport { Bucket, createHAMT } from 'hamt-sharding'\nimport { decode } from '@ipld/dag-pb'\nimport { murmur3128 } from '@multiformats/murmur3'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('../types').ExporterOptions} ExporterOptions\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n// FIXME: this is copy/pasted from ipfs-unixfs-importer/src/options.js\n/**\n * @param {Uint8Array} buf\n */\nconst hashFn = async function (buf) {\n return (await murmur3128.encode(buf))\n // Murmur3 outputs 128 bit but, accidentally, IPFS Go's\n // implementation only uses the first 64, so we must do the same\n // for parity..\n .slice(0, 8)\n // Invert buffer because that's how Go impl does it\n .reverse()\n}\n\n/**\n * @param {PBLink[]} links\n * @param {Bucket} bucket\n * @param {Bucket} rootBucket\n */\nconst addLinksToHamtBucket = (links, bucket, rootBucket) => {\n return Promise.all(\n links.map(link => {\n if (link.Name == null) {\n // TODO(@rvagg): what do? this is technically possible\n throw new Error('Unexpected Link without a Name')\n }\n if (link.Name.length === 2) {\n const pos = parseInt(link.Name, 16)\n\n return bucket._putObjectAt(pos, new Bucket({\n hash: rootBucket._options.hash,\n bits: rootBucket._options.bits\n }, bucket, pos))\n }\n\n return rootBucket.put(link.Name.substring(2), true)\n })\n )\n}\n\n/**\n * @param {number} position\n */\nconst toPrefix = (position) => {\n return position\n .toString(16)\n .toUpperCase()\n .padStart(2, '0')\n .substring(0, 2)\n}\n\n/**\n * @param {import('hamt-sharding').BucketPosition} position\n */\nconst toBucketPath = (position) => {\n let bucket = position.bucket\n const path = []\n\n while (bucket._parent) {\n path.push(bucket)\n\n bucket = bucket._parent\n }\n\n path.push(bucket)\n\n return path.reverse()\n}\n\n/**\n * @typedef {import('../types').ShardTraversalContext} ShardTraversalContext\n *\n * @param {PBNode} node\n * @param {string} name\n * @param {Blockstore} blockstore\n * @param {ShardTraversalContext} [context]\n * @param {ExporterOptions} [options]\n * @returns {Promise}\n */\nconst findShardCid = async (node, name, blockstore, context, options) => {\n if (!context) {\n const rootBucket = createHAMT({\n hashFn\n })\n\n context = {\n rootBucket,\n hamtDepth: 1,\n lastBucket: rootBucket\n }\n }\n\n await addLinksToHamtBucket(node.Links, context.lastBucket, context.rootBucket)\n\n const position = await context.rootBucket._findNewBucketAndPos(name)\n let prefix = toPrefix(position.pos)\n const bucketPath = toBucketPath(position)\n\n if (bucketPath.length > context.hamtDepth) {\n context.lastBucket = bucketPath[context.hamtDepth]\n\n prefix = toPrefix(context.lastBucket._posAtParent)\n }\n\n const link = node.Links.find(link => {\n if (link.Name == null) {\n return false\n }\n\n const entryPrefix = link.Name.substring(0, 2)\n const entryName = link.Name.substring(2)\n\n if (entryPrefix !== prefix) {\n // not the entry or subshard we're looking for\n return false\n }\n\n if (entryName && entryName !== name) {\n // not the entry we're looking for\n return false\n }\n\n return true\n })\n\n if (!link) {\n return null\n }\n\n if (link.Name != null && link.Name.substring(2) === name) {\n return link.Hash\n }\n\n context.hamtDepth++\n\n const block = await blockstore.get(link.Hash, options)\n node = decode(block)\n\n return findShardCid(node, name, blockstore, context, options)\n}\n\nexport default findShardCid\n", "/**\n * @param {Uint8Array} block\n * @param {number} blockStart\n * @param {number} requestedStart\n * @param {number} requestedEnd\n */\nfunction extractDataFromBlock (block, blockStart, requestedStart, requestedEnd) {\n const blockLength = block.length\n const blockEnd = blockStart + blockLength\n\n if (requestedStart >= blockEnd || requestedEnd < blockStart) {\n // If we are looking for a byte range that is starts after the start of the block,\n // return an empty block. This can happen when internal nodes contain data\n return new Uint8Array(0)\n }\n\n if (requestedEnd >= blockStart && requestedEnd < blockEnd) {\n // If the end byte is in the current block, truncate the block to the end byte\n block = block.subarray(0, requestedEnd - blockStart)\n }\n\n if (requestedStart >= blockStart && requestedStart < blockEnd) {\n // If the start byte is in the current block, skip to the start byte\n block = block.subarray(requestedStart - blockStart)\n }\n\n return block\n}\n\nexport default extractDataFromBlock\n", "import errCode from 'err-code'\n\n/**\n * @param {number} size\n * @param {number} [offset]\n * @param {number} [length]\n */\nconst validateOffsetAndLength = (size, offset, length) => {\n if (!offset) {\n offset = 0\n }\n\n if (offset < 0) {\n throw errCode(new Error('Offset must be greater than or equal to 0'), 'ERR_INVALID_PARAMS')\n }\n\n if (offset > size) {\n throw errCode(new Error('Offset must be less than the file size'), 'ERR_INVALID_PARAMS')\n }\n\n if (!length && length !== 0) {\n length = size - offset\n }\n\n if (length < 0) {\n throw errCode(new Error('Length must be greater than or equal to 0'), 'ERR_INVALID_PARAMS')\n }\n\n if (offset + length > size) {\n length = size - offset\n }\n\n return {\n offset,\n length\n }\n}\n\nexport default validateOffsetAndLength\n", "import extractDataFromBlock from '../../../utils/extract-data-from-block.js'\nimport validateOffsetAndLength from '../../../utils/validate-offset-and-length.js'\nimport { UnixFS } from 'ipfs-unixfs'\nimport errCode from 'err-code'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as raw from 'multiformats/codecs/raw'\nimport { pushable } from 'it-pushable'\nimport parallel from 'it-parallel'\nimport { pipe } from 'it-pipe'\nimport map from 'it-map'\nimport PQueue from 'p-queue'\n\n/**\n * @typedef {import('../../../types').ExporterOptions} ExporterOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n/**\n * @param {Blockstore} blockstore\n * @param {PBNode | Uint8Array} node\n * @param {import('it-pushable').Pushable} queue\n * @param {number} streamPosition\n * @param {number} start\n * @param {number} end\n * @param {PQueue} walkQueue\n * @param {ExporterOptions} options\n * @returns {Promise}\n */\nasync function walkDAG (blockstore, node, queue, streamPosition, start, end, walkQueue, options) {\n // a `raw` node\n if (node instanceof Uint8Array) {\n queue.push(extractDataFromBlock(node, streamPosition, start, end))\n\n return\n }\n\n if (node.Data == null) {\n throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS')\n }\n\n /** @type {UnixFS} */\n let file\n\n try {\n file = UnixFS.unmarshal(node.Data)\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_NOT_UNIXFS')\n }\n\n // might be a unixfs `raw` node or have data on intermediate nodes\n if (file.data != null) {\n const data = file.data\n const buf = extractDataFromBlock(data, streamPosition, start, end)\n\n queue.push(buf)\n\n streamPosition += buf.byteLength\n }\n\n /** @type {Array<{ link: PBLink, blockStart: number }>} */\n const childOps = []\n\n for (let i = 0; i < node.Links.length; i++) {\n const childLink = node.Links[i]\n const childStart = streamPosition // inclusive\n const childEnd = childStart + file.blockSizes[i] // exclusive\n\n if ((start >= childStart && start < childEnd) || // child has offset byte\n (end >= childStart && end <= childEnd) || // child has end byte\n (start < childStart && end > childEnd)) { // child is between offset and end bytes\n childOps.push({\n link: childLink,\n blockStart: streamPosition\n })\n }\n\n streamPosition = childEnd\n\n if (streamPosition > end) {\n break\n }\n }\n\n await pipe(\n childOps,\n (source) => map(source, (op) => {\n return async () => {\n const block = await blockstore.get(op.link.Hash, {\n signal: options.signal\n })\n\n return {\n ...op,\n block\n }\n }\n }),\n (source) => parallel(source, {\n ordered: true\n }),\n async (source) => {\n for await (const { link, block, blockStart } of source) {\n /** @type {PBNode | Uint8Array} */\n let child\n switch (link.Hash.code) {\n case dagPb.code:\n child = dagPb.decode(block)\n break\n case raw.code:\n child = block\n break\n default:\n queue.end(errCode(new Error(`Unsupported codec: ${link.Hash.code}`), 'ERR_NOT_UNIXFS'))\n return\n }\n\n walkQueue.add(async () => {\n await walkDAG(blockstore, child, queue, blockStart, start, end, walkQueue, options)\n })\n }\n }\n )\n}\n\n/**\n * @type {import('../').UnixfsV1Resolver}\n */\nconst fileContent = (cid, node, unixfs, path, resolve, depth, blockstore) => {\n /**\n * @param {ExporterOptions} options\n */\n async function * yieldFileContent (options = {}) {\n const fileSize = unixfs.fileSize()\n\n if (fileSize === undefined) {\n throw new Error('File was a directory')\n }\n\n const {\n offset,\n length\n } = validateOffsetAndLength(fileSize, options.offset, options.length)\n\n if (length === 0) {\n return\n }\n\n // use a queue to walk the DAG instead of recursion to ensure very deep DAGs\n // don't overflow the stack\n const walkQueue = new PQueue({\n concurrency: 1\n })\n const queue = pushable()\n\n walkQueue.add(async () => {\n await walkDAG(blockstore, node, queue, 0, offset, offset + length, walkQueue, options)\n })\n\n walkQueue.on('error', error => {\n queue.end(error)\n })\n\n let read = 0\n\n for await (const buf of queue) {\n if (buf == null) {\n continue\n }\n\n read += buf.byteLength\n\n if (read === length) {\n queue.end()\n }\n\n yield buf\n }\n }\n\n return yieldFileContent\n}\n\nexport default fileContent\n", "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", "/* global EventTarget Event */\n\nimport defer from 'p-defer'\n\ninterface Operation {\n done: boolean\n ok: boolean\n err: Error\n value: T\n}\n\nconst CustomEvent = globalThis.CustomEvent ?? Event\n\nexport interface ParallelOptions {\n /**\n * How many jobs to execute in parallel (default: )\n */\n concurrency?: number\n ordered?: boolean\n}\n\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: Iterable<() => Promise> | AsyncIterable<() => Promise>, options: ParallelOptions = {}): AsyncGenerator {\n let concurrency = options.concurrency ?? Infinity\n\n if (concurrency < 1) {\n concurrency = Infinity\n }\n\n const ordered = options.ordered == null ? false : options.ordered\n const emitter = new EventTarget()\n\n const ops: Array> = []\n let slotAvailable = defer()\n let resultAvailable = defer()\n let sourceFinished = false\n let sourceErr: Error | undefined\n let opErred = false\n\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve()\n })\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\n if (opErred) {\n break\n }\n\n const op: any = {\n done: false\n }\n ops.push(op)\n\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\n sourceFinished = true\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n } catch (err: any) {\n sourceErr = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }\n })\n\n function valuesAvailable () {\n if (ordered) {\n return ops[0]?.done\n }\n\n return Boolean(ops.find(op => op.done))\n }\n\n function * yieldOrderedValues () {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0]\n ops.shift()\n\n if (op.ok) {\n yield op.value\n } else {\n // allow the source to exit\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\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\n if (op.ok) {\n yield op.value\n } else {\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n }\n }\n\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer()\n await resultAvailable.promise\n }\n\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr\n }\n\n if (ordered) {\n yield * yieldOrderedValues()\n } else {\n yield * yieldUnOrderedValues()\n }\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", "var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pending, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_throwOnAbort, _PQueue_onEvent;\nimport EventEmitter from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pending.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\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 Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\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 \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${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 \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\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 __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\"),\n ...options,\n };\n return new Promise((resolve, reject) => {\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pending, (_b = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n // TODO: Use options.signal?.throwIfAborted() when targeting Node.js 18\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n throw new AbortError('The task was aborted.');\n }\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), options.timeout);\n }\n if (options.signal) {\n operation = Promise.race([operation, __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_throwOnAbort).call(this, 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 __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n }\n }, options);\n this.emit('add');\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\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 (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, '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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pending = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pending, (_a = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - 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 __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_throwOnAbort = async function _PQueue_throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n // TODO: Reject with signal.throwIfAborted() when targeting Node.js 18\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n }, { once: true });\n });\n}, _PQueue_onEvent = async function _PQueue_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", "// 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", "var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\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 && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\n", "/**\n * @typedef {import('../../../types').ExporterOptions} ExporterOptions\n * @typedef {import('../../../types').UnixfsV1DirectoryContent} UnixfsV1DirectoryContent\n * @typedef {import('../../../types').UnixfsV1Resolver} UnixfsV1Resolver\n */\n\n/**\n * @type {UnixfsV1Resolver}\n */\nconst directoryContent = (cid, node, unixfs, path, resolve, depth, blockstore) => {\n /**\n * @param {ExporterOptions} [options]\n * @returns {UnixfsV1DirectoryContent}\n */\n async function * yieldDirectoryContent (options = {}) {\n const offset = options.offset || 0\n const length = options.length || node.Links.length\n const links = node.Links.slice(offset, length)\n\n for (const link of links) {\n const result = await resolve(link.Hash, link.Name || '', `${path}/${link.Name || ''}`, [], depth + 1, blockstore, options)\n\n if (result.entry) {\n yield result.entry\n }\n }\n }\n\n return yieldDirectoryContent\n}\n\nexport default directoryContent\n", "import { decode } from '@ipld/dag-pb'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../../../types').ExporterOptions} ExporterOptions\n * @typedef {import('../../../types').Resolve} Resolve\n * @typedef {import('../../../types').UnixfsV1DirectoryContent} UnixfsV1DirectoryContent\n * @typedef {import('../../../types').UnixfsV1Resolver} UnixfsV1Resolver\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n */\n\n/**\n * @type {UnixfsV1Resolver}\n */\nconst hamtShardedDirectoryContent = (cid, node, unixfs, path, resolve, depth, blockstore) => {\n /**\n * @param {ExporterOptions} options\n *\n */\n function yieldHamtDirectoryContent (options = {}) {\n return listDirectory(node, path, resolve, depth, blockstore, options)\n }\n\n return yieldHamtDirectoryContent\n}\n\n/**\n * @param {PBNode} node\n * @param {string} path\n * @param {Resolve} resolve\n * @param {number} depth\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} options\n *\n * @returns {UnixfsV1DirectoryContent}\n */\nasync function * listDirectory (node, path, resolve, depth, blockstore, options) {\n const links = node.Links\n\n for (const link of links) {\n const name = link.Name != null ? link.Name.substring(2) : null\n\n if (name) {\n const result = await resolve(link.Hash, name, `${path}/${name}`, [], depth + 1, blockstore, options)\n\n yield result.entry\n } else {\n // descend into subshard\n const block = await blockstore.get(link.Hash)\n node = decode(block)\n\n for await (const file of listDirectory(node, path, resolve, depth, blockstore, options)) {\n yield file\n }\n }\n }\n}\n\nexport default hamtShardedDirectoryContent\n", "import errCode from 'err-code'\nimport extractDataFromBlock from '../utils/extract-data-from-block.js'\nimport validateOffsetAndLength from '../utils/validate-offset-and-length.js'\n\n/**\n * @typedef {import('../types').ExporterOptions} ExporterOptions\n */\n\n/**\n * @param {Uint8Array} node\n */\nconst rawContent = (node) => {\n /**\n * @param {ExporterOptions} options\n */\n async function * contentGenerator (options = {}) {\n const {\n offset,\n length\n } = validateOffsetAndLength(node.length, options.offset, options.length)\n\n yield extractDataFromBlock(node, 0, offset, offset + length)\n }\n\n return contentGenerator\n}\n\n/**\n * @type {import('../types').Resolver}\n */\nconst resolve = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n if (toResolve.length) {\n throw errCode(new Error(`No link named ${path} found in raw node ${cid}`), 'ERR_NOT_FOUND')\n }\n\n const block = await blockstore.get(cid, options)\n\n return {\n entry: {\n type: 'raw',\n name,\n path,\n cid,\n content: rawContent(block),\n depth,\n size: block.length,\n node: block\n }\n }\n}\n\nexport default resolve\n", "import { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\nimport * as dagCbor from '@ipld/dag-cbor'\n\n/**\n * @typedef {import('../types').Resolver} Resolver\n */\n\n/**\n * @type {Resolver}\n */\nconst resolve = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n const block = await blockstore.get(cid)\n const object = dagCbor.decode(block)\n let subObject = object\n let subPath = path\n\n while (toResolve.length) {\n const prop = toResolve[0]\n\n if (prop in subObject) {\n // remove the bit of the path we have resolved\n toResolve.shift()\n subPath = `${subPath}/${prop}`\n\n const subObjectCid = CID.asCID(subObject[prop])\n if (subObjectCid) {\n return {\n entry: {\n type: 'object',\n name,\n path,\n cid,\n node: block,\n depth,\n size: block.length,\n content: async function * () {\n yield object\n }\n },\n next: {\n cid: subObjectCid,\n name: prop,\n path: subPath,\n toResolve\n }\n }\n }\n\n subObject = subObject[prop]\n } else {\n // cannot resolve further\n throw errCode(new Error(`No property named ${prop} found in cbor node ${cid}`), 'ERR_NO_PROP')\n }\n }\n\n return {\n entry: {\n type: 'object',\n name,\n path,\n cid,\n node: block,\n depth,\n size: block.length,\n content: async function * () {\n yield object\n }\n }\n }\n}\n\nexport default resolve\n", "import errCode from 'err-code'\nimport extractDataFromBlock from '../utils/extract-data-from-block.js'\nimport validateOffsetAndLength from '../utils/validate-offset-and-length.js'\nimport * as mh from 'multiformats/hashes/digest'\n\n/**\n * @typedef {import('../types').ExporterOptions} ExporterOptions\n * @typedef {import('../types').Resolver} Resolver\n */\n\n/**\n * @param {Uint8Array} node\n */\nconst rawContent = (node) => {\n /**\n * @param {ExporterOptions} options\n */\n async function * contentGenerator (options = {}) {\n const {\n offset,\n length\n } = validateOffsetAndLength(node.length, options.offset, options.length)\n\n yield extractDataFromBlock(node, 0, offset, offset + length)\n }\n\n return contentGenerator\n}\n\n/**\n * @type {Resolver}\n */\nconst resolve = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n if (toResolve.length) {\n throw errCode(new Error(`No link named ${path} found in raw node ${cid}`), 'ERR_NOT_FOUND')\n }\n const buf = await mh.decode(cid.multihash.bytes)\n\n return {\n entry: {\n type: 'identity',\n name,\n path,\n cid,\n content: rawContent(buf.digest),\n depth,\n size: buf.digest.length,\n node: buf.digest\n }\n }\n}\n\nexport default resolve\n", "/**\n * Returns the last item of an (async) iterable, unless empty, in which case\n * return `undefined`\n */\nexport default async function last (source: AsyncIterable|Iterable): Promise {\n let res\n\n for await (const entry of source) {\n res = entry\n }\n\n return res\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport { normalizeCidPath } from '../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../types').Preload} preload\n *\n * @param {Context} context\n */\nexport function createCat ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"cat\"]}\n */\n async function * cat (ipfsPath, options = {}) {\n ipfsPath = normalizeCidPath(ipfsPath)\n\n if (options.preload !== false) {\n const pathComponents = ipfsPath.split('/')\n preload(CID.parse(pathComponents[0]))\n }\n\n const file = await exporter(ipfsPath, repo.blocks, options)\n\n // File may not have unixfs prop if small & imported with rawLeaves true\n if (file.type === 'directory') {\n throw new Error('this dag node is a directory')\n }\n\n if (!file.content) {\n throw new Error('this dag node has no content')\n }\n\n yield * file.content(options)\n }\n\n return withTimeoutOption(cat)\n}\n", "import { exporter, recursive } from 'ipfs-unixfs-exporter'\nimport errCode from 'err-code'\nimport { normalizeCidPath } from '../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\nimport { pack } from 'it-tar'\nimport { pipe } from 'it-pipe'\nimport Pako from 'pako'\nimport toBuffer from 'it-to-buffer'\n\n// https://www.gnu.org/software/gzip/manual/gzip.html\nconst DEFAULT_COMPRESSION_LEVEL = 6\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../types').Preload} preload\n *\n * @param {Context} context\n */\nexport function createGet ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"get\"]}\n */\n async function * get (ipfsPath, options = {}) {\n if (options.compressionLevel != null && (options.compressionLevel < -1 || options.compressionLevel > 9)) {\n throw errCode(new Error('Compression level must be between -1 and 9'), 'ERR_INVALID_PARAMS')\n }\n\n if (options.preload !== false) {\n let pathComponents\n\n try {\n pathComponents = normalizeCidPath(ipfsPath).split('/')\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_PATH')\n }\n\n preload(CID.parse(pathComponents[0]))\n }\n\n const ipfsPathOrCid = CID.asCID(ipfsPath) || ipfsPath\n const file = await exporter(ipfsPathOrCid, repo.blocks, options)\n\n if (file.type === 'file' || file.type === 'raw') {\n const args = []\n\n if (!options.compress || options.archive === true) {\n args.push([{\n header: {\n name: file.path,\n mode: file.type === 'file' && file.unixfs.mode,\n mtime: file.type === 'file' && file.unixfs.mtime ? new Date(file.unixfs.mtime.secs * 1000) : undefined,\n size: file.size,\n type: 'file'\n },\n body: file.content()\n }],\n pack()\n )\n } else {\n args.push(\n file.content\n )\n }\n\n if (options.compress) {\n args.push(\n /**\n * @param {AsyncIterable} source\n */\n async function * (source) {\n const buf = await toBuffer(source)\n\n yield Pako.gzip(buf, {\n level: options.compressionLevel || DEFAULT_COMPRESSION_LEVEL\n })\n }\n )\n }\n\n // @ts-expect-error cannot derive type\n yield * pipe(...args)\n\n return\n }\n\n if (file.type === 'directory') {\n /** @type {any[]} */\n const args = [\n recursive(ipfsPathOrCid, repo.blocks, options),\n /**\n * @param {AsyncIterable} source\n */\n async function * (source) {\n for await (const entry of source) {\n /** @type {import('it-tar').TarImportCandidate} */\n const output = {\n header: {\n name: entry.path,\n size: entry.size\n }\n }\n\n if (entry.type === 'file') {\n output.header.type = 'file'\n output.header.mode = entry.unixfs.mode != null ? entry.unixfs.mode : undefined\n output.header.mtime = entry.unixfs.mtime ? new Date(entry.unixfs.mtime.secs * 1000) : undefined\n output.body = entry.content()\n } else if (entry.type === 'raw') {\n output.header.type = 'file'\n output.body = entry.content()\n } else if (entry.type === 'directory') {\n output.header.type = 'directory'\n output.header.mode = entry.unixfs.mode != null ? entry.unixfs.mode : undefined\n output.header.mtime = entry.unixfs.mtime ? new Date(entry.unixfs.mtime.secs * 1000) : undefined\n } else {\n throw errCode(new Error('Not a UnixFS node'), 'ERR_NOT_UNIXFS')\n }\n\n yield output\n }\n },\n pack()\n ]\n\n if (options.compress) {\n if (!options.archive) {\n throw errCode(new Error('file is not regular'), 'ERR_INVALID_PATH')\n }\n\n if (options.compress) {\n args.push(\n /**\n * @param {AsyncIterable} source\n */\n async function * (source) {\n const buf = await toBuffer(source)\n\n yield Pako.gzip(buf, {\n level: options.compressionLevel || DEFAULT_COMPRESSION_LEVEL\n })\n }\n )\n }\n }\n\n // @ts-expect-error cannot derive type\n yield * pipe(...args)\n\n return\n }\n\n throw errCode(new Error('Not a UnixFS node'), 'ERR_NOT_UNIXFS')\n }\n\n return withTimeoutOption(get)\n}\n", "import { Uint8ArrayList, isUint8ArrayList } from 'uint8arraylist'\nimport { compare as uint8ArrayCompare } from 'uint8arrays/compare'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { EntryType, TarEntryHeader } from './index.js'\n\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = uint8ArrayFromString('ustar\\x00', 'binary')\nconst GNU_MAGIC = uint8ArrayFromString('ustar\\x20', 'binary')\nconst GNU_VER = uint8ArrayFromString('\\x20\\x00', 'binary')\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nconst clamp = function (index: number, len: number, defaultValue: number): number {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nconst toType = function (flag: number): EntryType | undefined {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n default:\n return undefined\n }\n}\n\nconst indexOf = function (block: Uint8ArrayList, num: number, offset: number, end: number): number {\n for (; offset < end; offset++) {\n if (block.get(offset) === num) return offset\n }\n return end\n}\n\nconst cksum = function (block: Uint8ArrayList): number {\n let sum = 8 * 32\n for (let i = 0; i < 148; i++) sum += block.get(i)\n for (let j = 156; j < 512; j++) sum += block.get(j)\n return sum\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf: Uint8ArrayList): number {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n let positive\n if (buf.get(0) === 0x80) {\n positive = true\n } else if (buf.get(0) === 0xFF) {\n positive = false\n } else {\n return 0\n }\n\n // build up a base-256 tuple from the least sig to the highest\n let zero = false\n const tuple = []\n for (let i = buf.length - 1; i > 0; i--) {\n const byte = buf.get(i)\n if (positive) tuple.push(byte)\n else if (zero && byte === 0) tuple.push(0)\n else if (zero) {\n zero = false\n tuple.push(0x100 - byte)\n } else tuple.push(0xFF - byte)\n }\n\n let sum = 0\n const l = tuple.length\n for (let i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nconst decodeOct = function (val: Uint8ArrayList, offset: number, length: number): number {\n val = val.sublist(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if ((val.get(offset) & 0x80) !== 0) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val.get(offset) === 32) {\n offset++\n }\n\n const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n\n while (offset < end && val.get(offset) === 0) {\n offset++\n }\n\n if (end === offset) {\n return 0\n }\n\n return parseInt(uint8ArrayToString(val.subarray(offset, end)), 8)\n }\n}\n\nconst decodeStr = function (val: Uint8ArrayList, offset: number, length: number, encoding?: SupportedEncodings): string {\n return uint8ArrayToString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding)\n}\n\nexport function decodeLongPath (buf: Uint8ArrayList | Uint8Array, encoding?: SupportedEncodings): string {\n const list = isUint8ArrayList(buf) ? buf : new Uint8ArrayList(buf)\n return decodeStr(list, 0, buf.length, encoding)\n}\n\nexport function decodePax (buf: Uint8ArrayList | Uint8Array, encoding?: SupportedEncodings): Record {\n let list = isUint8ArrayList(buf) ? buf : new Uint8ArrayList(buf)\n const result: Record = {}\n\n while (list.length > 0) {\n let i = 0\n while (i < buf.length && list.get(i) !== 32) {\n i++\n }\n\n const len = parseInt(uint8ArrayToString(list.subarray(0, i)), 10)\n\n if (len === 0) {\n return result\n }\n\n const b = uint8ArrayToString(list.subarray(i + 1, len - 1), encoding)\n const keyIndex = b.indexOf('=')\n\n if (keyIndex === -1) {\n return result\n }\n\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n list = list.sublist(len)\n }\n\n return result\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, filenameEncoding?: SupportedEncodings): TarEntryHeader | null {\n const list = isUint8ArrayList(buf) ? buf : new Uint8ArrayList(buf)\n let typeflag = list.get(156) === 0 ? 0 : list.get(156) - ZERO_OFFSET\n\n let name = decodeStr(list, 0, 100, filenameEncoding)\n const mode = decodeOct(list, 100, 8)\n const uid = decodeOct(list, 108, 8)\n const gid = decodeOct(list, 116, 8)\n const size = decodeOct(list, 124, 12)\n const mtime = decodeOct(list, 136, 12)\n const type = toType(typeflag)\n const linkname = list.get(157) === 0 ? undefined : decodeStr(list, 157, 100, filenameEncoding)\n const uname = decodeStr(list, 265, 32)\n const gname = decodeStr(list, 297, 32)\n const devmajor = decodeOct(list, 329, 8)\n const devminor = decodeOct(list, 337, 8)\n\n const c = cksum(list)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) {\n return null\n }\n\n // valid checksum\n if (c !== decodeOct(list, 148, 8)) {\n throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n }\n\n if (uint8ArrayCompare(USTAR_MAGIC, list.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (list.get(345) !== 0) {\n name = decodeStr(list, 345, 155, filenameEncoding) + '/' + name\n }\n } else if (uint8ArrayCompare(GNU_MAGIC, list.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) === 0 &&\n uint8ArrayCompare(GNU_VER, list.subarray(VERSION_OFFSET, VERSION_OFFSET + 2)) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n throw new Error('Invalid tar header: unknown format.')\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name != null && name[name.length - 1] === '/') {\n typeflag = 5\n }\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * (mtime ?? 0)),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n", "// @ts-expect-error no types\nimport isoConstants from 'iso-constants'\nimport toBuffer from 'it-to-buffer'\nimport { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as Headers from './pack-headers.js'\nimport type { EntryType, TarEntryHeader, TarImportCandidate } from './index.js'\nimport type { Source, Transform } from 'it-stream-types'\n\nconst { S_IFMT, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK } = isoConstants\nconst DMODE = parseInt('755', 8)\nconst FMODE = parseInt('644', 8)\nconst END_OF_TAR = new Uint8Array(1024)\n\nfunction modeToType (mode: number = 0): EntryType {\n switch (mode & S_IFMT) {\n case S_IFBLK: return 'block-device'\n case S_IFCHR: return 'character-device'\n case S_IFDIR: return 'directory'\n case S_IFIFO: return 'fifo'\n case S_IFLNK: return 'symlink'\n default: return 'file'\n }\n}\n\nfunction getPadding (size: number): Uint8Array {\n size &= 511\n\n if (size !== 0) {\n return END_OF_TAR.subarray(0, 512 - size)\n }\n\n return new Uint8Array(0)\n}\n\nfunction encode (header: TarEntryHeader): Uint8Array {\n if (header.pax == null) {\n const encoded = Headers.encode(header)\n\n if (encoded != null) {\n return encoded\n }\n }\n return encodePax(header)\n}\n\nfunction encodePax (header: TarEntryHeader): Uint8Array {\n const paxHeader = Headers.encodePax(header)\n\n const newHeader: TarEntryHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname,\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n return new Uint8ArrayList(\n Headers.encode(newHeader) ?? new Uint8Array(0),\n paxHeader,\n getPadding(paxHeader.length),\n Headers.encode({ ...newHeader, size: header.size, type: header.type }) ?? new Uint8Array(0)\n ).subarray()\n}\n\nexport function pack (): Transform, AsyncGenerator> {\n return async function * (source: Source) { // eslint-disable-line complexity\n for await (let { header: partialHeader, body } of source) {\n const header: TarEntryHeader = {\n ...partialHeader,\n size: partialHeader.type === 'symlink' ? 0 : partialHeader.size ?? 0,\n type: partialHeader.type ?? modeToType(partialHeader.mode),\n mode: partialHeader.mode ?? (partialHeader.type === 'directory' ? DMODE : FMODE),\n uid: partialHeader.uid ?? 0,\n gid: partialHeader.gid ?? 0,\n mtime: partialHeader.mtime ?? new Date()\n }\n\n if (typeof body === 'string') {\n body = uint8ArrayFromString(body)\n }\n\n if (body instanceof Uint8Array || isUint8ArrayList(body)) {\n header.size = body.length\n\n yield encode(header)\n yield isUint8ArrayList(body) ? body.subarray() : body\n yield getPadding(header.size)\n\n continue\n }\n\n if (header.type === 'symlink' && header.linkname == null) {\n if (body == null) {\n throw new Error('type was symlink but no linkname or body specified')\n }\n\n header.linkname = uint8ArrayToString(await toBuffer(body))\n yield encode(header)\n continue\n }\n\n yield encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n continue\n }\n\n let written = 0\n for await (const chunk of (body ?? [])) {\n written += chunk.length // eslint-disable-line @typescript-eslint/restrict-plus-operands\n yield isUint8ArrayList(chunk) ? chunk.subarray() : chunk\n }\n\n if (written !== header.size) { // corrupting tar\n throw new Error(`size mismatch, wrote ${written} of ${header.size} bytes`)\n }\n\n yield getPadding(header.size)\n }\n\n yield END_OF_TAR\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Collects all `Uint8Array` values from an (async)iterable and returns them as a single `Uint8Array`.\n *\n * @example\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * // This can also be an iterator, generator, etc\n * const values = [Buffer.from([0, 1]), Buffer.from([2, 3])]\n *\n * const result = toBuffer(values)\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * const values = async function * () {\n * yield Buffer.from([0, 1])\n * yield Buffer.from([2, 3])\n * }\n *\n * const result = await toBuffer(values())\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n */\n\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Takes an (async) iterable that yields buffer-like-objects and concats them\n * into one buffer\n */\nfunction toBuffer (source: Iterable): Uint8Array\nfunction toBuffer (source: Iterable | AsyncIterable): Promise\nfunction toBuffer (source: Iterable | AsyncIterable): Promise | Uint8Array {\n if (isAsyncIterable(source)) {\n return (async () => {\n let buffer = new Uint8Array(0)\n\n for await (const buf of source) {\n buffer = uint8ArrayConcat([buffer, buf], buffer.length + buf.length)\n }\n\n return buffer\n })()\n }\n\n const bufs = []\n let length = 0\n\n for (const buf of source) {\n bufs.push(buf)\n length += buf.byteLength\n }\n\n return uint8ArrayConcat(bufs, length)\n}\n\nexport default toBuffer\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { EntryType, TarEntryHeader } from '.'\n\nconst ZEROS = '0000000000000000000'\nconst SEVENS = '7777777777777777777'\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = uint8ArrayFromString('ustar\\x00', 'binary')\nconst USTAR_VER = uint8ArrayFromString('00', 'binary')\nconst MASK = parseInt('7777', 8)\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nconst toTypeflag = function (flag?: EntryType): number {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n default:\n return 0\n }\n}\n\nconst cksum = function (block: Uint8Array): number {\n let sum = 8 * 32\n for (let i = 0; i < 148; i++) sum += block[i]\n for (let j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nconst encodeOct = function (val: number, n: number): Uint8Array {\n const str = val.toString(8)\n\n if (str.length > n) {\n return uint8ArrayFromString(SEVENS.slice(0, n) + ' ')\n }\n\n return uint8ArrayFromString(ZEROS.slice(0, n - str.length) + str + ' ')\n}\n\nconst addLength = function (str: string): string {\n const len = uint8ArrayFromString(str).byteLength\n let digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n\n if (len + digits >= Math.pow(10, digits)) {\n digits++\n }\n\n return `${len + digits}${str}`\n}\n\nexport function encodePax (opts: TarEntryHeader): Uint8Array { // TODO: encode more stuff in pax\n let result = ''\n if (opts.name != null) {\n result += addLength(' path=' + opts.name + '\\n')\n }\n if (opts.linkname != null) {\n result += addLength(' linkpath=' + opts.linkname + '\\n')\n }\n\n const pax = opts.pax\n\n if (pax != null) {\n for (const key in pax) {\n if (Object.prototype.hasOwnProperty.call(pax, key)) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n }\n\n return uint8ArrayFromString(result)\n}\n\nexport function encode (opts: TarEntryHeader): Uint8Array | null {\n const buf = new Uint8Array(512)\n let name = opts.name\n let prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') {\n name += '/'\n }\n\n if (uint8ArrayFromString(name).byteLength !== name.length) {\n return null // utf-8\n }\n\n while (uint8ArrayFromString(name).byteLength > 100) {\n const i = name.indexOf('/')\n if (i === -1) {\n return null\n }\n prefix += prefix !== '' ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (uint8ArrayFromString(name).byteLength > 100 || uint8ArrayFromString(prefix).byteLength > 155) {\n return null\n }\n\n if (opts.linkname != null && uint8ArrayFromString(opts.linkname).byteLength > 100) {\n return null\n }\n\n buf.set(uint8ArrayFromString(name), 0)\n buf.set(encodeOct(opts.mode & MASK, 6), 100)\n buf.set(encodeOct(opts.uid, 6), 108)\n buf.set(encodeOct(opts.gid, 6), 116)\n buf.set(encodeOct(opts.size, 11), 124)\n buf.set(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname != null) {\n buf.set(uint8ArrayFromString(opts.linkname), 157)\n }\n\n buf.set(USTAR_MAGIC, MAGIC_OFFSET)\n buf.set(USTAR_VER, VERSION_OFFSET)\n\n if (opts.uname != null) {\n buf.set(uint8ArrayFromString(opts.uname), 265)\n }\n\n if (opts.gname != null) {\n buf.set(uint8ArrayFromString(opts.gname), 297)\n }\n\n buf.set(encodeOct(opts.devmajor ?? 0, 6), 329)\n buf.set(encodeOct(opts.devminor ?? 0, 6), 337)\n\n if (prefix != null) {\n buf.set(uint8ArrayFromString(prefix), 345)\n }\n\n buf.set(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n", "\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Tracev((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n code = (code + bl_count[bits - 1]) << 1;\n next_code[bits] = code;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let sx = 0; /* running index in sym_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.sym_next !== 0) {\n do {\n dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n lc = s.pending_buf[s.sym_buf + sx++];\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and sym_buf is ok: */\n //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n } while (sx < s.sym_next);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"block list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* block_mask is the bit mask of block-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let block_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"block-listed\") bytes. */\n for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"allow-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"block-listed\" or \"allow-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n bi_windup(s); /* align on byte boundary */\n put_short(s, stored_len);\n put_short(s, ~stored_len);\n if (stored_len) {\n s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n }\n s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->sym_next / 3));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42; /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */\nconst NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE = 113; /* deflate -> FINISH_STATE */\nconst FINISH_STATE = 666; /* stream complete */\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n let n, m;\n let p;\n let wsize = s.w_size;\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= wsize ? m - wsize : 0);\n } while (--n);\n n = wsize;\n//#ifndef FASTEST\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= wsize ? m - wsize : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let n, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n slide_hash(s);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Smallest worthy block size when not flushing or finishing. By default\n * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n * large input and output buffers, the stored block size will be larger.\n */\n let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n /* Copy as many min_block or larger stored blocks directly to next_out as\n * possible. If flushing, copy the remaining available input to next_out as\n * stored blocks, if there is enough space.\n */\n let len, left, have, last = 0;\n let used = s.strm.avail_in;\n do {\n /* Set len to the maximum size block that we can copy directly with the\n * available input data and output space. Set left to how much of that\n * would be copied from what's left in the window.\n */\n len = 65535/* MAX_STORED */; /* maximum deflate stored block length */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n if (s.strm.avail_out < have) { /* need room for header */\n break;\n }\n /* maximum stored block length that will fit in avail_out: */\n have = s.strm.avail_out - have;\n left = s.strstart - s.block_start; /* bytes left in window */\n if (len > left + s.strm.avail_in) {\n len = left + s.strm.avail_in; /* limit len to the input */\n }\n if (len > have) {\n len = have; /* limit len to the output */\n }\n\n /* If the stored block would be less than min_block in length, or if\n * unable to copy all of the available input when flushing, then try\n * copying to the window and the pending buffer instead. Also don't\n * write an empty block when flushing -- deflate() does that.\n */\n if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n flush === Z_NO_FLUSH$2 ||\n len !== left + s.strm.avail_in)) {\n break;\n }\n\n /* Make a dummy stored block in pending to get the header bytes,\n * including any pending bits. This also updates the debugging counts.\n */\n last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n _tr_stored_block(s, 0, 0, last);\n\n /* Replace the lengths in the dummy stored block with len. */\n s.pending_buf[s.pending - 4] = len;\n s.pending_buf[s.pending - 3] = len >> 8;\n s.pending_buf[s.pending - 2] = ~len;\n s.pending_buf[s.pending - 1] = ~len >> 8;\n\n /* Write the stored block header bytes. */\n flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n// /* Update debugging counts for the data about to be copied. */\n// s->compressed_len += len << 3;\n// s->bits_sent += len << 3;\n//#endif\n\n /* Copy uncompressed bytes from the window to next_out. */\n if (left) {\n if (left > len) {\n left = len;\n }\n //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n s.strm.next_out += left;\n s.strm.avail_out -= left;\n s.strm.total_out += left;\n s.block_start += left;\n len -= left;\n }\n\n /* Copy uncompressed bytes directly from next_in to next_out, updating\n * the check value.\n */\n if (len) {\n read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n s.strm.next_out += len;\n s.strm.avail_out -= len;\n s.strm.total_out += len;\n }\n } while (last === 0);\n\n /* Update the sliding window with the last s->w_size bytes of the copied\n * data, or append all of the copied data to the existing window if less\n * than s->w_size bytes were copied. Also update the number of bytes to\n * insert in the hash tables, in the event that deflateParams() switches to\n * a non-zero compression level.\n */\n used -= s.strm.avail_in; /* number of input bytes directly copied */\n if (used) {\n /* If any input was used, then no unused input remains in the window,\n * therefore s->block_start == s->strstart.\n */\n if (used >= s.w_size) { /* supplant the previous history */\n s.matches = 2; /* clear hash */\n //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n s.strstart = s.w_size;\n s.insert = s.strstart;\n }\n else {\n if (s.window_size - s.strstart <= used) {\n /* Slide the window down. */\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n s.strstart += used;\n s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n }\n s.block_start = s.strstart;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* If the last block was written to next_out, then done. */\n if (last) {\n return BS_FINISH_DONE;\n }\n\n /* If flushing and all input has been consumed, then done. */\n if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n s.strm.avail_in === 0 && s.strstart === s.block_start) {\n return BS_BLOCK_DONE;\n }\n\n /* Fill the window with any remaining input. */\n have = s.window_size - s.strstart;\n if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n /* Slide the window down. */\n s.block_start -= s.w_size;\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n have += s.w_size; /* more space now */\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n if (have > s.strm.avail_in) {\n have = s.strm.avail_in;\n }\n if (have) {\n read_buf(s.strm, s.window, s.strstart, have);\n s.strstart += have;\n s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* There was not enough avail_out to write a complete worthy or flushed\n * stored block to next_out. Write a stored block to pending instead, if we\n * have enough input for a worthy block, or if flushing and there is enough\n * room for the remaining input as a stored block in the pending buffer.\n */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n /* maximum stored block length that will fit in pending: */\n have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n min_block = have > s.w_size ? s.w_size : have;\n left = s.strstart - s.block_start;\n if (left >= min_block ||\n ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n s.strm.avail_in === 0 && left <= have)) {\n len = left > have ? have : left;\n last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n len === left ? 1 : 0;\n _tr_stored_block(s, s.block_start, len, last);\n s.block_start += len;\n flush_pending(s.strm);\n }\n\n /* We've done all we can with the available input and output. */\n return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.sym_buf = 0; /* buffer for distances and literals/lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.sym_next = 0; /* running index in sym_buf */\n this.sym_end = 0; /* symbol table full when sym_next reaches this */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const s = strm.state;\n if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n s.status !== GZIP_STATE &&\n//#endif\n s.status !== EXTRA_STATE &&\n s.status !== NAME_STATE &&\n s.status !== COMMENT_STATE &&\n s.status !== HCRC_STATE &&\n s.status !== BUSY_STATE &&\n s.status !== FINISH_STATE)) {\n return 1;\n }\n return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status =\n//#ifdef GZIP\n s.wrap === 2 ? GZIP_STATE :\n//#endif\n s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = -2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n return Z_STREAM_ERROR$2;\n }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n s.status = INIT_STATE; /* to pass state test in deflateReset() */\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n /* We overlay pending_buf and sym_buf. This works since the average size\n * for length/distance pairs over any compressed block is assured to be 31\n * bits or less.\n *\n * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n * possible fixed-codes length/distance pair is then 31 bits total.\n *\n * sym_buf starts one-fourth of the way into pending_buf. So there are\n * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n * in sym_buf is three bytes -- two for the distance and one for the\n * literal/length. As each symbol is consumed, the pointer to the next\n * sym_buf value to read moves forward three bytes. From that symbol, up to\n * 31 bits are written to pending_buf. The closest the written pending_buf\n * bits gets to the next sym_buf symbol to read is just before the last\n * code is written. At that time, 31*(n-2) bits have been written, just\n * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n * symbols are written.) The closest the writing gets to what is unread is\n * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n * can range from 128 to 32768.\n *\n * Therefore, at a minimum, there are 142 bits of space between what is\n * written and what is read in the overlain buffers, so the symbols cannot\n * be overwritten by the compressed data. That space is actually 139 bits,\n * due to the three-bit fixed-code block header.\n *\n * That covers the case where either Z_FIXED is specified, forcing fixed\n * codes, or when the use of fixed codes is chosen, because that choice\n * results in a smaller compressed block than dynamic codes. That latter\n * condition then assures that the above analysis also covers all dynamic\n * blocks. A dynamic-code block will only be chosen to be emitted if it has\n * fewer bits than a fixed-code block would for the same set of symbols.\n * Therefore its average symbol length is assured to be less than 31. So\n * the compressed data for a dynamic block also cannot overwrite the\n * symbols from which it is being constructed.\n */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->sym_buf = s->pending_buf + s->lit_bufsize;\n s.sym_buf = s.lit_bufsize;\n\n //s->sym_end = (s->lit_bufsize - 1) * 3;\n s.sym_end = (s.lit_bufsize - 1) * 3;\n /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (strm.avail_in !== 0 && !strm.input) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Write the header */\n if (s.status === INIT_STATE && s.wrap === 0) {\n s.status = BUSY_STATE;\n }\n if (s.status === INIT_STATE) {\n /* zlib header */\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#ifdef GZIP\n if (s.status === GZIP_STATE) {\n /* gzip header */\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n while (s.pending + left > s.pending_buf_size) {\n let copy = s.pending_buf_size - s.pending;\n // zmemcpy(s.pending_buf + s.pending,\n // s.gzhead.extra + s.gzindex, copy);\n s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n s.pending = s.pending_buf_size;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex += copy;\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n left -= copy;\n }\n // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n // TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n let gzhead_extra = new Uint8Array(s.gzhead.extra);\n // zmemcpy(s->pending_buf + s->pending,\n // s->gzhead->extra + s->gzindex, left);\n s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n s.pending += left;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = NAME_STATE;\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = COMMENT_STATE;\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n }\n s.status = HCRC_STATE;\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n }\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#endif\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = s.level === 0 ? deflate_stored(s, flush) :\n s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush);\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209; /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n// let shoextra; /* extra bits table to use */\n let match; /* use base and extra for symbol >= match */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n match = 20;\n\n } else if (type === LENS$1) {\n base = lbase;\n extra = lext;\n match = 257;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n match = 0;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] + 1 < match) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] >= match) {\n here_op = extra[work[sym] - match];\n here_val = base[work[sym] - match];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 16180; /* i: waiting for magic header */\nconst FLAGS = 16181; /* i: waiting for method and flags (gzip) */\nconst TIME = 16182; /* i: waiting for modification time (gzip) */\nconst OS = 16183; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 16184; /* i: waiting for extra length (gzip) */\nconst EXTRA = 16185; /* i: waiting for extra bytes (gzip) */\nconst NAME = 16186; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 16187; /* i: waiting for end of comment (gzip) */\nconst HCRC = 16188; /* i: waiting for header crc (gzip) */\nconst DICTID = 16189; /* i: waiting for dictionary check value */\nconst DICT = 16190; /* waiting for inflateSetDictionary() call */\nconst TYPE = 16191; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 16193; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 16194; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16195; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 16196; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 16197; /* i: waiting for code length code lengths */\nconst CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 16199; /* i: same as LEN below, but only first time in */\nconst LEN = 16200; /* i: waiting for length/lit/eob code */\nconst LENEXT = 16201; /* i: waiting for length extra bits */\nconst DIST = 16202; /* i: waiting for distance code */\nconst DISTEXT = 16203; /* i: waiting for distance extra bits */\nconst MATCH = 16204; /* o: waiting for output space to copy string */\nconst LIT = 16205; /* o: waiting for output space to write literal */\nconst CHECK = 16206; /* i: waiting for 32-bit check value */\nconst LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 16208; /* finished check, done -- remain here until reset */\nconst BAD = 16209; /* got a data error -- remain here until reset */\nconst MEM = 16210; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 16211; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,\n bit 2 true to validate check value */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib), or\n -1 if raw or no header yet */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const state = strm.state;\n if (!state || state.strm !== strm ||\n state.mode < HEAD || state.mode > SYNC) {\n return 1;\n }\n return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.flags = -1;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.strm = strm;\n state.window = null/*Z_NULL*/;\n state.mode = HEAD; /* to pass state test in inflateReset2() */\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (inflateStateCheck(strm) || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n if (state.wbits === 0) {\n state.wbits = 15;\n }\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n if (len > 15 || len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n state.flags = 0; /* indicate zlib header */\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check =\n /*UPDATE_CHECK(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (inflateStateCheck(strm)) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { Deflate_1 as Deflate, Inflate_1 as Inflate, constants_1 as constants, pako as default, deflate_1 as deflate, deflateRaw_1 as deflateRaw, gzip_1 as gzip, inflate_1 as inflate, inflateRaw_1 as inflateRaw, ungzip_1 as ungzip };\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\n/**\n * Takes an (async) iterable that yields buffer-like-objects and concats them\n * into one buffer\n */\nexport default async function toBuffer (stream: AsyncIterable | Iterable): Promise {\n let buffer = new Uint8Array(0)\n\n for await (const buf of stream) {\n buffer = uint8ArrayConcat([buffer, buf], buffer.length + buf.length)\n }\n\n return buffer\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport errCode from 'err-code'\nimport { normalizeCidPath, mapFile } from '../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../types').Preload} preload\n *\n * @param {Context} context\n */\nexport function createLs ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"ls\"]}\n */\n async function * ls (ipfsPath, options = {}) {\n const legacyPath = normalizeCidPath(ipfsPath)\n const pathComponents = legacyPath.split('/')\n\n if (options.preload !== false) {\n preload(CID.parse(pathComponents[0]))\n }\n\n const ipfsPathOrCid = CID.asCID(legacyPath) || legacyPath\n const file = await exporter(ipfsPathOrCid, repo.blocks, options)\n\n if (file.type === 'file') {\n yield mapFile(file)\n return\n }\n\n if (file.type === 'directory') {\n for await (const child of file.content()) {\n yield mapFile(child)\n }\n\n return\n }\n\n throw errCode(new Error(`Unknown UnixFS type ${file.type}`), 'ERR_UNKNOWN_UNIXFS_TYPE')\n }\n\n return withTimeoutOption(ls)\n}\n", "import { createAdd } from './add.js'\nimport { createAddAll } from './add-all/index.js'\nimport { createCat } from './cat.js'\nimport { createGet } from './get.js'\nimport { createLs } from './ls.js'\n\n/**\n * @typedef {AddAllContext & CatContext & GetContext & ListContext } Context\n * @typedef {import('./add-all').Context} AddAllContext\n * @typedef {import('./cat').Context} CatContext\n * @typedef {import('./get').Context} GetContext\n * @typedef {import('./ls').Context} ListContext\n */\nexport class RootAPI {\n /**\n * @param {Context} context\n */\n constructor ({ preload, repo, hashers, options }) {\n const addAll = createAddAll({\n preload,\n repo,\n options,\n hashers\n })\n\n this.addAll = addAll\n this.add = createAdd({ addAll })\n this.cat = createCat({ repo, preload })\n this.get = createGet({ repo, preload })\n this.ls = createLs({ repo, preload })\n }\n}\n", "\nexport const ipfsCore = '0.18.1'\nexport const commit = ''\nexport const interfaceIpfsCore = '^0.158.1'\n", "import { ipfsCore, interfaceIpfsCore, commit } from '../version.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createVersion ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"version\"]}\n */\n async function version (_options = {}) {\n const repoVersion = await repo.version.get()\n\n return {\n version: ipfsCore,\n commit,\n repo: `${repoVersion}`,\n 'ipfs-core': ipfsCore,\n 'interface-ipfs-core': interfaceIpfsCore\n }\n }\n\n return withTimeoutOption(version)\n}\n", "import { ipfsCore as pkgversion } from '../version.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { NotStartedError } from '../errors.js'\nimport errCode from 'err-code'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:components:id')\n\n/**\n * @typedef {import('libp2p').Libp2p} Libp2p\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('../types').NetworkService} config.network\n */\nexport function createId ({ peerId, network }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"id\"]}\n */\n async function id (options = {}) { // eslint-disable-line require-await\n const net = network.try()\n\n if (!net) {\n if (options.peerId) {\n throw new NotStartedError()\n }\n\n if (peerId.publicKey == null) {\n throw errCode(new Error('Public key missing'), 'ERR_MISSING_PUBLIC_KEY')\n }\n\n return {\n id: peerId,\n publicKey: uint8ArrayToString(peerId.publicKey, 'base64pad'),\n addresses: [],\n agentVersion: `js-ipfs/${pkgversion}`,\n protocolVersion: '9000',\n protocols: []\n }\n }\n\n const { libp2p } = net\n const peerIdToId = options.peerId ? options.peerId : peerId\n const peer = await findPeer(peerIdToId, libp2p, options)\n const agentVersion = uint8ArrayToString(peer.metadata.get('AgentVersion') || new Uint8Array())\n const protocolVersion = uint8ArrayToString(peer.metadata.get('ProtocolVersion') || new Uint8Array())\n const idStr = peer.id.toString()\n const publicKeyStr = peer.publicKey ? uint8ArrayToString(peer.publicKey, 'base64pad') : ''\n\n return {\n id: peerIdToId,\n publicKey: publicKeyStr,\n addresses: (peer.addresses || [])\n .map(ma => {\n const str = ma.toString()\n\n // some relay-style transports add our peer id to the ma for us\n // so don't double-add\n if (str.endsWith(`/p2p/${idStr}`)) {\n return str\n }\n\n return `${str}/p2p/${idStr}`\n })\n .sort()\n .map(ma => multiaddr(ma)),\n agentVersion,\n protocolVersion,\n protocols: (peer.protocols || []).sort()\n }\n }\n\n return withTimeoutOption(id)\n}\n\n/**\n * @param {PeerId} peerId\n * @param {Libp2p} libp2p\n * @param {AbortOptions} options\n */\nasync function findPeer (peerId, libp2p, options) {\n let peer = await libp2p.peerStore.get(peerId)\n\n if (!peer) {\n peer = await findPeerOnDht(peerId, libp2p, options)\n }\n\n let publicKey = peerId.publicKey ? peerId.publicKey : await libp2p.peerStore.keyBook.get(peerId)\n\n if (publicKey == null) {\n try {\n publicKey = await libp2p.getPublicKey(peerId, options)\n } catch (err) {\n log.error('Could not load public key for', peerId.toString(), err)\n }\n }\n\n return {\n ...peer,\n publicKey,\n metadata: peer.metadata || new Map(),\n addresses: peer.addresses.map(addr => addr.multiaddr)\n }\n}\n\n/**\n * @param {PeerId} peerId\n * @param {Libp2p} libp2p\n * @param {AbortOptions} options\n */\nasync function findPeerOnDht (peerId, libp2p, options) {\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n for await (const event of libp2p.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n break\n }\n }\n\n const peer = await libp2p.peerStore.get(peerId)\n\n if (!peer) {\n throw errCode(new Error('Could not find peer'), 'ERR_NOT_FOUND')\n }\n\n return peer\n}\n", "var objectSafeSet = set;\n\n/*\n var obj1 = {};\n set(obj1, 'a.aa.aaa', 4); // true\n obj1; // {a: {aa: {aaa: 4}}}\n\n var obj2 = {};\n set(obj2, ['a', 'aa', 'aaa'], 4); // true\n obj2; // {a: {aa: {aaa: 4}}}\n\n var obj3 = {a: {aa: {aaa: 2}}};\n set(obj3, 'a.aa.aaa', 3); // true\n obj3; // {a: {aa: {aaa: 3}}}\n\n const obj5 = {a: {}};\n const sym = Symbol();\n set(obj5.a, sym, 7); // true\n obj5; // {a: {Symbol(): 7}}\n*/\n\nfunction set(obj, propsArg, value) {\n var props, lastProp;\n if (Array.isArray(propsArg)) {\n props = propsArg.slice(0);\n }\n if (typeof propsArg == 'string') {\n props = propsArg.split('.');\n }\n if (typeof propsArg == 'symbol') {\n props = [propsArg];\n }\n if (!Array.isArray(props)) {\n throw new Error('props arg must be an array, a string or a symbol');\n }\n lastProp = props.pop();\n if (!lastProp) {\n return false;\n }\n prototypeCheck(lastProp);\n var thisProp;\n while ((thisProp = props.shift())) {\n prototypeCheck(thisProp);\n if (typeof obj[thisProp] == 'undefined') {\n obj[thisProp] = {};\n }\n obj = obj[thisProp];\n if (!obj || typeof obj != 'object') {\n return false;\n }\n }\n obj[lastProp] = value;\n return true;\n}\n\nfunction prototypeCheck(prop) {\n // coercion is intentional to catch prop values like `['__proto__']`\n if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') {\n throw new Error('setting of prototype values not supported');\n }\n}\n\nexport {objectSafeSet as default};\n", "import set from 'just-safe-set'\nimport getDefaultConfig from 'ipfs-core-config/config'\n\n/**\n * @typedef {import('ipfs-core-types/src/config').Config} Config\n *\n * @typedef {object} Transformer\n * @property {string} description\n * @property {(config: Config) => Config} transform\n */\n\n/**\n * @type {Record}\n */\nexport const profiles = {\n server: {\n description: 'Recommended for nodes with public IPv4 address (servers, VPSes, etc.), disables host and content discovery and UPnP in local networks.',\n transform: (config) => {\n set(config, 'Discovery.MDNS.Enabled', false)\n set(config, 'Discovery.webRTCStar.Enabled', false)\n config.Swarm = {\n ...(config.Swarm || {}),\n DisableNatPortMap: true\n }\n\n return config\n }\n },\n 'local-discovery': {\n description: 'Sets default values to fields affected by `server` profile, enables discovery and UPnP in local networks.',\n transform: (config) => {\n set(config, 'Discovery.MDNS.Enabled', true)\n set(config, 'Discovery.webRTCStar.Enabled', true)\n set(config, 'Swarm', {\n ...(config.Swarm || {}),\n DisableNatPortMap: false\n })\n\n return config\n }\n },\n test: {\n description: 'Reduces external interference, useful for running ipfs in test environments. Note that with these settings node won\\'t be able to talk to the rest of the network without manual bootstrap.',\n transform: (config) => {\n const defaultConfig = getDefaultConfig()\n\n set(config, 'Addresses.API', defaultConfig.Addresses.API ? '/ip4/127.0.0.1/tcp/0' : '')\n set(config, 'Addresses.Gateway', defaultConfig.Addresses.Gateway ? '/ip4/127.0.0.1/tcp/0' : '')\n set(config, 'Addresses.Swarm', defaultConfig.Addresses.Swarm.length ? ['/ip4/127.0.0.1/tcp/0'] : [])\n set(config, 'Addresses.Delegates', [])\n set(config, 'Bootstrap', [])\n set(config, 'Discovery.MDNS.Enabled', false)\n set(config, 'Discovery.webRTCStar.Enabled', false)\n set(config, 'Swarm', {\n ...(config.Swarm || {}),\n DisableNatPortMap: true\n })\n\n return config\n }\n },\n 'default-networking': {\n description: 'Restores default network settings. Inverse profile of the `test` profile.',\n transform: (config) => {\n const defaultConfig = getDefaultConfig()\n\n set(config, 'Addresses.API', defaultConfig.Addresses.API)\n set(config, 'Addresses.Gateway', defaultConfig.Addresses.Gateway)\n set(config, 'Addresses.Swarm', defaultConfig.Addresses.Swarm)\n set(config, 'Addresses.Delegates', defaultConfig.Addresses.Delegates)\n set(config, 'Bootstrap', defaultConfig.Bootstrap)\n set(config, 'Discovery.MDNS.Enabled', defaultConfig.Discovery.MDNS.Enabled)\n set(config, 'Discovery.webRTCStar.Enabled', defaultConfig.Discovery.webRTCStar.Enabled)\n set(config, 'Swarm', {\n ...(config.Swarm || {}),\n DisableNatPortMap: false\n })\n\n return config\n }\n },\n lowpower: {\n description: 'Reduces daemon overhead on the system. May affect node functionality,performance of content discovery and data fetching may be degraded. Recommended for low power systems.',\n transform: (config) => {\n const Swarm = config.Swarm || {}\n const ConnMgr = Swarm.ConnMgr || {}\n ConnMgr.LowWater = 20\n ConnMgr.HighWater = 40\n\n Swarm.ConnMgr = ConnMgr\n config.Swarm = Swarm\n\n return config\n }\n },\n 'default-power': {\n description: 'Inverse of \"lowpower\" profile.',\n transform: (config) => {\n const defaultConfig = getDefaultConfig()\n\n config.Swarm = defaultConfig.Swarm\n\n return config\n }\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { logger } from '@libp2p/logger'\nimport { profiles } from './profiles.js'\n\nconst log = logger('ipfs:core:config')\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createConfig ({ repo }) {\n return {\n getAll: withTimeoutOption(getAll),\n get: withTimeoutOption(get),\n set: withTimeoutOption(set),\n replace: withTimeoutOption(replace),\n profiles: {\n apply: withTimeoutOption(applyProfile),\n list: withTimeoutOption(listProfiles)\n }\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"getAll\"]}\n */\n async function getAll (options = {}) { // eslint-disable-line require-await\n return repo.config.getAll(options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"get\"]}\n */\n async function get (key, options) { // eslint-disable-line require-await\n if (!key) {\n return Promise.reject(new Error('key argument is required'))\n }\n\n return repo.config.get(key, options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"set\"]}\n */\n async function set (key, value, options) { // eslint-disable-line require-await\n return repo.config.set(key, value, options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"replace\"]}\n */\n async function replace (value, options) { // eslint-disable-line require-await\n return repo.config.replace(value, options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config/profiles').API<{}>[\"apply\"]}\n */\n async function applyProfile (profileName, options = { dryRun: false }) {\n const { dryRun } = options\n\n const profile = profiles[profileName]\n\n if (!profile) {\n throw new Error(`No profile with name '${profileName}' exists`)\n }\n\n try {\n const oldCfg = await repo.config.getAll(options)\n let newCfg = JSON.parse(JSON.stringify(oldCfg)) // clone\n newCfg = profile.transform(newCfg)\n\n if (!dryRun) {\n await repo.config.replace(newCfg, options)\n }\n\n // Scrub private key from output\n // @ts-expect-error `oldCfg.Identity` maybe undefined\n delete oldCfg.Identity.PrivKey\n delete newCfg.Identity.PrivKey\n\n return { original: oldCfg, updated: newCfg }\n } catch (/** @type {any} */ err) {\n log(err)\n\n throw new Error(`Could not apply profile '${profileName}' to config: ${err.message}`)\n }\n }\n}\n\n/**\n * @type {import('ipfs-core-types/src/config/profiles').API<{}>[\"list\"]}\n */\nasync function listProfiles (_options) { // eslint-disable-line require-await\n return Object.keys(profiles).map(name => ({\n name,\n description: profiles[name].description\n }))\n}\n", "import { bytes as binary, CID } from './index.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\n\nfunction readonly ({ enumerable = true, configurable = false } = {}) {\n return { enumerable, configurable, writable: false }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable<[string, CID]>}\n */\nfunction * linksWithin (path, value) {\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n if (cid) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n if (cid) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable<[string, CID]>}\n */\nfunction * links (source, base) {\n if (source == null || source instanceof Uint8Array) {\n return\n }\n const cid = CID.asCID(source)\n if (cid) {\n yield [base.join('/'), cid]\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield * linksWithin(path, value)\n }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable}\n */\nfunction * treeWithin (path, value) {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n yield elementPath.join('/')\n if (typeof element === 'object' && !CID.asCID(element)) {\n yield * tree(element, elementPath)\n }\n }\n } else {\n yield * tree(value, path)\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable}\n */\nfunction * tree (source, base) {\n if (source == null || typeof source !== 'object') {\n return\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield path.join('/')\n if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && !CID.asCID(value)) {\n yield * treeWithin(path, value)\n }\n }\n}\n\n/**\n *\n * @template T\n * @param {T} source\n * @param {string[]} path\n * @returns {API.BlockCursorView}\n */\nfunction get (source, path) {\n let node = /** @type {Record} */(source)\n for (const [index, key] of path.entries()) {\n node = node[key]\n if (node == null) {\n throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)\n }\n const cid = CID.asCID(node)\n if (cid) {\n return { value: cid, remaining: path.slice(index + 1).join('/') }\n }\n }\n return { value: node }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} C - multicodec code corresponding to codec used to encode the block\n * @template {number} A - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @implements {API.BlockView}\n */\nclass Block {\n /**\n * @param {object} options\n * @param {CID} options.cid\n * @param {API.ByteView} options.bytes\n * @param {T} options.value\n */\n constructor ({ cid, bytes, value }) {\n if (!cid || !bytes || typeof value === 'undefined') { throw new Error('Missing required argument') }\n\n this.cid = cid\n this.bytes = bytes\n this.value = value\n this.asBlock = this\n\n // Mark all the properties immutable\n Object.defineProperties(this, {\n cid: readonly(),\n bytes: readonly(),\n value: readonly(),\n asBlock: readonly()\n })\n }\n\n links () {\n return links(this.value, [])\n }\n\n tree () {\n return tree(this.value, [])\n }\n\n /**\n *\n * @param {string} [path]\n * @returns {API.BlockCursorView}\n */\n get (path = '/') {\n return get(this.value, path.split('/').filter(Boolean))\n }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {T} options.value\n * @param {API.BlockEncoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function encode ({ value, codec, hasher }) {\n if (typeof value === 'undefined') throw new Error('Missing required argument \"value\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const bytes = codec.encode(value)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(\n 1,\n codec.code,\n hash\n )\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function decode ({ bytes, codec, hasher }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(1, codec.code, hash)\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @typedef {object} RequiredCreateOptions\n * @property {CID} options.cid\n */\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {{ cid: API.Link, value:T, codec?: API.BlockDecoder, bytes: API.ByteView }|{cid:API.Link, bytes:API.ByteView, value?:void, codec:API.BlockDecoder}} options\n * @returns {API.BlockView}\n */\nfunction createUnsafe ({ bytes, cid, value: maybeValue, codec }) {\n const value = maybeValue !== undefined\n ? maybeValue\n : (codec && codec.decode(bytes))\n\n if (value === undefined) throw new Error('Missing required argument, must either provide \"value\" or \"codec\"')\n\n return new Block({\n // eslint-disable-next-line object-shorthand\n cid: /** @type {CID} */ (cid),\n bytes,\n value\n })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {object} options\n * @param {API.Link} options.cid\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function create ({ bytes, cid, hasher, codec }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!hasher) throw new Error('Missing required argument \"hasher\"')\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error('CID hash does not match bytes')\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec\n })\n}\n\nexport { encode, decode, create, createUnsafe, Block }\n", "import varint from 'varint'\n\nexport const CIDV0_BYTES = {\n SHA2_256: 0x12,\n LENGTH: 0x20,\n DAG_PB: 0x70\n}\n\nexport const V2_HEADER_LENGTH = /* characteristics */ 16 /* v1 offset */ + 8 /* v1 size */ + 8 /* index offset */ + 8\n\n/**\n * Decodes varint and seeks the buffer\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @param {import('./coding').Seekable} seeker\n * @returns {number}\n */\nexport function decodeVarint (bytes, seeker) {\n if (!bytes.length) {\n throw new Error('Unexpected end of data')\n }\n const i = varint.decode(bytes)\n seeker.seek(/** @type {number} */(varint.decode.bytes))\n return i\n}\n\n/**\n * Decode v2 header\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.exactly(V2_HEADER_LENGTH, true) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @returns {import('./coding').CarV2FixedHeader}\n */\nexport function decodeV2Header (bytes) {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let offset = 0\n const header = {\n version: 2,\n /** @type {[bigint, bigint]} */\n characteristics: [\n dv.getBigUint64(offset, true),\n dv.getBigUint64(offset += 8, true)\n ],\n dataOffset: Number(dv.getBigUint64(offset += 8, true)),\n dataSize: Number(dv.getBigUint64(offset += 8, true)),\n indexOffset: Number(dv.getBigUint64(offset += 8, true))\n }\n return header\n}\n\n/**\n * Checks the length of the multihash to be read afterwards\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n */\nexport function getMultihashLength (bytes) {\n // | code | length | .... |\n // where both code and length are varints, so we have to decode\n // them first before we can know total length\n\n varint.decode(bytes) // code\n const codeLength = /** @type {number} */(varint.decode.bytes)\n const length = varint.decode(bytes.subarray(varint.decode.bytes))\n const lengthLength = /** @type {number} */(varint.decode.bytes)\n const mhLength = codeLength + lengthLength + length\n\n return mhLength\n}\n", "/** Auto-generated with @ipld/schema@v4.2.0 at Thu Sep 14 2023 from IPLD Schema:\n *\n * # CarV1HeaderOrV2Pragma is a more relaxed form, and can parse {version:x} where\n * # roots are optional. This is typically useful for the {verison:2} CARv2\n * # pragma.\n *\n * type CarV1HeaderOrV2Pragma struct {\n * \troots optional [&Any]\n * \t# roots is _not_ optional for CarV1 but we defer that check within code to\n * \t# gracefully handle the V2 case where it's just {version:X}\n * \tversion Int\n * }\n *\n * # CarV1Header is the strict form of the header, and requires roots to be\n * # present. This is compatible with the CARv1 specification.\n *\n * # type CarV1Header struct {\n * # \troots [&Any]\n * # \tversion Int\n * # }\n *\n */\n\nconst Kinds = {\n Null: /** @returns {undefined|null} */ (/** @type {any} */ obj) => obj === null ? obj : undefined,\n Int: /** @returns {undefined|number} */ (/** @type {any} */ obj) => Number.isInteger(obj) ? obj : undefined,\n Float: /** @returns {undefined|number} */ (/** @type {any} */ obj) => typeof obj === 'number' && Number.isFinite(obj) ? obj : undefined,\n String: /** @returns {undefined|string} */ (/** @type {any} */ obj) => typeof obj === 'string' ? obj : undefined,\n Bool: /** @returns {undefined|boolean} */ (/** @type {any} */ obj) => typeof obj === 'boolean' ? obj : undefined,\n Bytes: /** @returns {undefined|Uint8Array} */ (/** @type {any} */ obj) => obj instanceof Uint8Array ? obj : undefined,\n Link: /** @returns {undefined|object} */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID === obj ? obj : undefined,\n List: /** @returns {undefined|Array} */ (/** @type {any} */ obj) => Array.isArray(obj) ? obj : undefined,\n Map: /** @returns {undefined|object} */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : undefined\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Types = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Types['CarV1HeaderOrV2Pragma > roots (anon)'](obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Types.Int(obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Reprs = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Reprs['CarV1HeaderOrV2Pragma > roots (anon)'](value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Reprs.Int(value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n\nexport const CarV1HeaderOrV2Pragma = {\n toTyped: Types.CarV1HeaderOrV2Pragma,\n toRepresentation: Reprs.CarV1HeaderOrV2Pragma\n}\n", "import { decode as decodeDagCbor } from '@ipld/dag-cbor'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CIDV0_BYTES, decodeV2Header, decodeVarint, getMultihashLength, V2_HEADER_LENGTH } from './decoder-common.js'\nimport { CarV1HeaderOrV2Pragma } from './header-validator.js'\n\n/**\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').BlockHeader} BlockHeader\n * @typedef {import('./api').BlockIndex} BlockIndex\n * @typedef {import('./coding').BytesReader} BytesReader\n * @typedef {import('./coding').CarHeader} CarHeader\n * @typedef {import('./coding').CarV2Header} CarV2Header\n * @typedef {import('./coding').CarV2FixedHeader} CarV2FixedHeader\n * @typedef {import('./coding').CarDecoder} CarDecoder\n */\n\n/**\n * Reads header data from a `BytesReader`. The header may either be in the form\n * of a `CarHeader` or `CarV2Header` depending on the CAR being read.\n *\n * @name async decoder.readHeader(reader)\n * @param {BytesReader} reader\n * @param {number} [strictVersion]\n * @returns {Promise}\n */\nexport async function readHeader (reader, strictVersion) {\n const length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR header (zero length)')\n }\n const header = await reader.exactly(length, true)\n const block = decodeDagCbor(header)\n if (CarV1HeaderOrV2Pragma.toTyped(block) === undefined) {\n throw new Error('Invalid CAR header format')\n }\n if ((block.version !== 1 && block.version !== 2) || (strictVersion !== undefined && block.version !== strictVersion)) {\n throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== undefined ? ` (expected ${strictVersion})` : ''}`)\n }\n if (block.version === 1) {\n // CarV1HeaderOrV2Pragma makes roots optional, let's make it mandatory\n if (!Array.isArray(block.roots)) {\n throw new Error('Invalid CAR header format')\n }\n return block\n }\n // version 2\n if (block.roots !== undefined) {\n throw new Error('Invalid CAR header format')\n }\n const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true))\n reader.seek(v2Header.dataOffset - reader.pos)\n const v1Header = await readHeader(reader, 1)\n return Object.assign(v1Header, v2Header)\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nasync function readCid (reader) {\n const first = await reader.exactly(2, false)\n if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) {\n // cidv0 32-byte sha2-256\n const bytes = await reader.exactly(34, true)\n const multihash = Digest.decode(bytes)\n return CID.create(0, CIDV0_BYTES.DAG_PB, multihash)\n }\n\n const version = decodeVarint(await reader.upTo(8), reader)\n if (version !== 1) {\n throw new Error(`Unexpected CID version (${version})`)\n }\n const codec = decodeVarint(await reader.upTo(8), reader)\n const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true)\n const multihash = Digest.decode(bytes)\n return CID.create(version, codec, multihash)\n}\n\n/**\n * Reads the leading data of an individual block from CAR data from a\n * `BytesReader`. Returns a `BlockHeader` object which contains\n * `{ cid, length, blockLength }` which can be used to either index the block\n * or read the block binary data.\n *\n * @name async decoder.readBlockHead(reader)\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nexport async function readBlockHead (reader) {\n // length includes a CID + Binary, where CID has a variable length\n // we have to deal with\n const start = reader.pos\n let length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR section (zero length)')\n }\n length += (reader.pos - start)\n const cid = await readCid(reader)\n const blockLength = length - Number(reader.pos - start) // subtract CID length\n\n return { cid, length, blockLength }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nasync function readBlock (reader) {\n const { cid, blockLength } = await readBlockHead(reader)\n const bytes = await reader.exactly(blockLength, true)\n return { bytes, cid }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nasync function readBlockIndex (reader) {\n const offset = reader.pos\n const { cid, length, blockLength } = await readBlockHead(reader)\n const index = { cid, length, blockLength, offset, blockOffset: reader.pos }\n reader.seek(index.blockLength)\n return index\n}\n\n/**\n * Creates a `CarDecoder` from a `BytesReader`. The `CarDecoder` is as async\n * interface that will consume the bytes from the `BytesReader` to yield a\n * `header()` and either `blocks()` or `blocksIndex()` data.\n *\n * @name decoder.createDecoder(reader)\n * @param {BytesReader} reader\n * @returns {CarDecoder}\n */\nexport function createDecoder (reader) {\n const headerPromise = (async () => {\n const header = await readHeader(reader)\n if (header.version === 2) {\n const v1length = reader.pos - header.dataOffset\n reader = limitReader(reader, header.dataSize - v1length)\n }\n return header\n })()\n\n return {\n header: () => headerPromise,\n\n async * blocks () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlock(reader)\n }\n },\n\n async * blocksIndex () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlockIndex(reader)\n }\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from a `Uint8Array`.\n *\n * @name decoder.bytesReader(bytes)\n * @param {Uint8Array} bytes\n * @returns {BytesReader}\n */\nexport function bytesReader (bytes) {\n let pos = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos))\n return out\n },\n\n async exactly (length, seek = false) {\n if (length > bytes.length - pos) {\n throw new Error('Unexpected end of data')\n }\n const out = bytes.subarray(pos, pos + length)\n if (seek) {\n pos += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * @ignore\n * reusable reader for streams and files, we just need a way to read an\n * additional chunk (of some undetermined size) and a way to close the\n * reader when finished\n * @param {() => Promise} readChunk\n * @returns {BytesReader}\n */\nexport function chunkReader (readChunk /*, closer */) {\n let pos = 0\n let have = 0\n let offset = 0\n let currentChunk = new Uint8Array(0)\n\n const read = async (/** @type {number} */ length) => {\n have = currentChunk.length - offset\n const bufa = [currentChunk.subarray(offset)]\n while (have < length) {\n const chunk = await readChunk()\n if (chunk == null) {\n break\n }\n /* c8 ignore next 8 */\n // undo this ignore ^ when we have a fd implementation that can seek()\n if (have < 0) { // because of a seek()\n /* c8 ignore next 4 */\n // toohard to test the else\n if (chunk.length > have) {\n bufa.push(chunk.subarray(-have))\n } // else discard\n } else {\n bufa.push(chunk)\n }\n have += chunk.length\n }\n currentChunk = new Uint8Array(bufa.reduce((p, c) => p + c.length, 0))\n let off = 0\n for (const b of bufa) {\n currentChunk.set(b, off)\n off += b.length\n }\n offset = 0\n }\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length))\n },\n\n async exactly (length, seek = false) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n if (currentChunk.length - offset < length) {\n throw new Error('Unexpected end of data')\n }\n const out = currentChunk.subarray(offset, offset + length)\n if (seek) {\n pos += length\n offset += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n offset += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from an `AsyncIterable`, which allows for\n * consumption of CAR data from a streaming source.\n *\n * @name decoder.asyncIterableReader(asyncIterable)\n * @param {AsyncIterable} asyncIterable\n * @returns {BytesReader}\n */\nexport function asyncIterableReader (asyncIterable) {\n const iterator = asyncIterable[Symbol.asyncIterator]()\n\n async function readChunk () {\n const next = await iterator.next()\n if (next.done) {\n return null\n }\n return next.value\n }\n\n return chunkReader(readChunk)\n}\n\n/**\n * Wraps a `BytesReader` in a limiting `BytesReader` which limits maximum read\n * to `byteLimit` bytes. It _does not_ update `pos` of the original\n * `BytesReader`.\n *\n * @name decoder.limitReader(reader, byteLimit)\n * @param {BytesReader} reader\n * @param {number} byteLimit\n * @returns {BytesReader}\n */\nexport function limitReader (reader, byteLimit) {\n let bytesRead = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n let bytes = await reader.upTo(length)\n if (bytes.length + bytesRead > byteLimit) {\n bytes = bytes.subarray(0, byteLimit - bytesRead)\n }\n return bytes\n },\n\n async exactly (length, seek = false) {\n const bytes = await reader.exactly(length, seek)\n if (bytes.length + bytesRead > byteLimit) {\n throw new Error('Unexpected end of data')\n }\n if (seek) {\n bytesRead += length\n }\n return bytes\n },\n\n seek (length) {\n bytesRead += length\n reader.seek(length)\n },\n\n get pos () {\n return reader.pos\n }\n }\n}\n", "import { encode as dagCborEncode } from '@ipld/dag-cbor'\nimport varint from 'varint'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./coding').CarEncoder} CarEncoder\n * @typedef {import('./coding').IteratorChannel_Writer} IteratorChannel_Writer\n */\n\nconst CAR_V1_VERSION = 1\n\n/**\n * Create a header from an array of roots.\n *\n * @param {CID[]} roots\n * @returns {Uint8Array}\n */\nexport function createHeader (roots) {\n const headerBytes = dagCborEncode({ version: CAR_V1_VERSION, roots })\n const varintBytes = varint.encode(headerBytes.length)\n const header = new Uint8Array(varintBytes.length + headerBytes.length)\n header.set(varintBytes, 0)\n header.set(headerBytes, varintBytes.length)\n return header\n}\n\n/**\n * @param {IteratorChannel_Writer} writer\n * @returns {CarEncoder}\n */\nfunction createEncoder (writer) {\n // none of this is wrapped in a mutex, that needs to happen above this to\n // avoid overwrites\n\n return {\n /**\n * @param {CID[]} roots\n * @returns {Promise}\n */\n async setRoots (roots) {\n const bytes = createHeader(roots)\n await writer.write(bytes)\n },\n\n /**\n * @param {Block} block\n * @returns {Promise}\n */\n async writeBlock (block) {\n const { cid, bytes } = block\n await writer.write(new Uint8Array(varint.encode(cid.bytes.length + bytes.length)))\n await writer.write(cid.bytes)\n if (bytes.length) {\n // zero-length blocks are valid, but it'd be safer if we didn't write them\n await writer.write(bytes)\n }\n },\n\n /**\n * @returns {Promise}\n */\n async close () {\n await writer.end()\n },\n\n /**\n * @returns {number}\n */\n version () {\n return CAR_V1_VERSION\n }\n }\n}\n\nexport { createEncoder }\n", "/**\n * @template {any} T\n * @typedef {import('./coding').IteratorChannel} IteratorChannel\n */\n\nfunction noop () {}\n\n/**\n * @template {any} T\n * @returns {IteratorChannel}\n */\nexport function create () {\n /** @type {T[]} */\n const chunkQueue = []\n /** @type {Promise | null} */\n let drainer = null\n let drainerResolver = noop\n let ended = false\n /** @type {Promise> | null} */\n let outWait = null\n let outWaitResolver = noop\n\n const makeDrainer = () => {\n if (!drainer) {\n drainer = new Promise((resolve) => {\n drainerResolver = () => {\n drainer = null\n drainerResolver = noop\n resolve()\n }\n })\n }\n return drainer\n }\n\n /**\n * @returns {IteratorChannel}\n */\n const writer = {\n /**\n * @param {T} chunk\n * @returns {Promise}\n */\n write (chunk) {\n chunkQueue.push(chunk)\n const drainer = makeDrainer()\n outWaitResolver()\n return drainer\n },\n\n async end () {\n ended = true\n const drainer = makeDrainer()\n outWaitResolver()\n await drainer\n }\n }\n\n /** @type {AsyncIterator} */\n const iterator = {\n /** @returns {Promise>} */\n async next () {\n const chunk = chunkQueue.shift()\n if (chunk) {\n if (chunkQueue.length === 0) {\n drainerResolver()\n }\n return { done: false, value: chunk }\n }\n\n if (ended) {\n drainerResolver()\n return { done: true, value: undefined }\n }\n\n if (!outWait) {\n outWait = new Promise((resolve) => {\n outWaitResolver = () => {\n outWait = null\n outWaitResolver = noop\n return resolve(iterator.next())\n }\n })\n }\n\n return outWait\n }\n }\n\n return { writer, iterator }\n}\n", "import { CID } from 'multiformats/cid'\nimport { bytesReader, readHeader } from './decoder.js'\nimport { createEncoder, createHeader } from './encoder.js'\nimport { create as iteratorChannel } from './iterator-channel.js'\n\n/**\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').BlockWriter} BlockWriter\n * @typedef {import('./api').WriterChannel} WriterChannel\n * @typedef {import('./coding').CarEncoder} CarEncoder\n * @typedef {import('./coding').IteratorChannel} IteratorChannel\n */\n\n/**\n * Provides a writer interface for the creation of CAR files.\n *\n * Creation of a `CarWriter` involves the instatiation of an input / output pair\n * in the form of a `WriterChannel`, which is a\n * `{ writer:CarWriter, out:AsyncIterable }` pair. These two\n * components form what can be thought of as a stream-like interface. The\n * `writer` component (an instantiated `CarWriter`), has methods to\n * {@link CarWriter.put `put()`} new blocks and {@link CarWriter.put `close()`}\n * the writing operation (finalising the CAR archive). The `out` component is\n * an `AsyncIterable` that yields the bytes of the archive. This can be\n * redirected to a file or other sink. In Node.js, you can use the\n * [`Readable.from()`](https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options)\n * API to convert this to a standard Node.js stream, or it can be directly fed\n * to a\n * [`stream.pipeline()`](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback).\n *\n * The channel will provide a form of backpressure. The `Promise` from a\n * `write()` won't resolve until the resulting data is drained from the `out`\n * iterable.\n *\n * It is also possible to ignore the `Promise` from `write()` calls and allow\n * the generated data to queue in memory. This should be avoided for large CAR\n * archives of course due to the memory costs and potential for memory overflow.\n *\n * Load this class with either\n * `import { CarWriter } from '@ipld/car/writer'`\n * (`const { CarWriter } = require('@ipld/car/writer')`). Or\n * `import { CarWriter } from '@ipld/car'`\n * (`const { CarWriter } = require('@ipld/car')`). The former will likely\n * result in smaller bundle sizes where this is important.\n *\n * @name CarWriter\n * @class\n * @implements {BlockWriter}\n */\nexport class CarWriter {\n /**\n * @param {CID[]} roots\n * @param {CarEncoder} encoder\n */\n constructor (roots, encoder) {\n this._encoder = encoder\n /** @type {Promise} */\n this._mutex = encoder.setRoots(roots)\n this._ended = false\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {Promise} The returned promise will only resolve once the\n * bytes this block generates are written to the `out` iterable.\n */\n async put (block) {\n if (!(block.bytes instanceof Uint8Array) || !block.cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n if (this._ended) {\n throw new Error('Already closed')\n }\n const cid = CID.asCID(block.cid)\n if (!cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n this._mutex = this._mutex.then(() => this._encoder.writeBlock({ cid, bytes: block.bytes }))\n return this._mutex\n }\n\n /**\n * Finalise the CAR archive and signal that the `out` iterable should end once\n * any remaining bytes are written.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @returns {Promise}\n */\n async close () {\n if (this._ended) {\n throw new Error('Already closed')\n }\n await this._mutex\n this._ended = true\n return this._encoder.close()\n }\n\n /**\n * Returns the version number of the CAR file being written\n *\n * @returns {number}\n */\n version () {\n return this._encoder.version()\n }\n\n /**\n * Create a new CAR writer \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable }` pair.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {CID[] | CID | void} roots\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable }`.\n */\n static create (roots) {\n roots = toRoots(roots)\n const { encoder, iterator } = encodeWriter()\n const writer = new CarWriter(roots, encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Create a new CAR appender \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable }` pair.\n * This appender does not consider roots and does not produce a CAR header.\n * It is designed to append blocks to an _existing_ CAR archive. It is\n * expected that `out` will be concatenated onto the end of an existing\n * archive that already has a properly formatted header.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable }`.\n */\n static createAppender () {\n const { encoder, iterator } = encodeWriter()\n encoder.setRoots = () => Promise.resolve()\n const writer = new CarWriter([], encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Update the list of roots in the header of an existing CAR as represented\n * in a Uint8Array.\n *\n * This operation is an _overwrite_, the total length of the CAR will not be\n * modified. A rejection will occur if the new header will not be the same\n * length as the existing header, in which case the CAR will not be modified.\n * It is the responsibility of the user to ensure that the roots being\n * replaced encode as the same length as the new roots.\n *\n * The byte array passed in an argument will be modified and also returned\n * upon successful modification.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {Uint8Array} bytes\n * @param {CID[]} roots - A new list of roots to replace the existing list in\n * the CAR header. The new header must take up the same number of bytes as the\n * existing header, so the roots should collectively be the same byte length\n * as the existing roots.\n * @returns {Promise}\n */\n static async updateRootsInBytes (bytes, roots) {\n const reader = bytesReader(bytes)\n await readHeader(reader)\n const newHeader = createHeader(roots)\n if (Number(reader.pos) !== newHeader.length) {\n throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${reader.pos} bytes, new header is ${newHeader.length} bytes)`)\n }\n bytes.set(newHeader, 0)\n return bytes\n }\n}\n\n/**\n * @class\n * @implements {AsyncIterable}\n */\nexport class CarWriterOut {\n /**\n * @param {AsyncIterator} iterator\n */\n constructor (iterator) {\n this._iterator = iterator\n }\n\n [Symbol.asyncIterator] () {\n if (this._iterating) {\n throw new Error('Multiple iterator not supported')\n }\n this._iterating = true\n return this._iterator\n }\n}\n\nfunction encodeWriter () {\n /** @type {IteratorChannel} */\n const iw = iteratorChannel()\n const { writer, iterator } = iw\n const encoder = createEncoder(writer)\n return { encoder, iterator }\n}\n\n/**\n * @private\n * @param {CID[] | CID | void} roots\n * @returns {CID[]}\n */\nfunction toRoots (roots) {\n if (roots === undefined) {\n return []\n }\n\n if (!Array.isArray(roots)) {\n const cid = CID.asCID(roots)\n if (!cid) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n return [cid]\n }\n\n const _roots = []\n for (const root of roots) {\n const _root = CID.asCID(root)\n if (!_root) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n _roots.push(_root)\n }\n return _roots\n}\n\nexport const __browser = true\n", "import { base58btc } from './bases/base58.js'\n\n/**\n * @template [C=number] - multicodec code corresponding to codec used to encode the block\n * @template [A=number] - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template [V=0|1] - CID version\n * @typedef {import('./cid').CID} CID\n */\n\n/**\n * @template [T=unknown] - Logical type of the data encoded in the block\n * @template [C=number] - multicodec code corresponding to codec used to encode the block\n * @template [A=number] - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template [V=0|1] - CID version\n * @typedef {import('./block/interface.js').BlockView} BlockView\n */\n\n/**\n * @param {object} options\n * @param {CID} options.cid\n * @param {(cid: CID) => Promise} options.load\n * @param {Set} [options.seen]\n */\nconst walk = async ({ cid, load, seen }) => {\n seen = seen || new Set()\n const b58Cid = cid.toString(base58btc)\n if (seen.has(b58Cid)) {\n return\n }\n\n const block = await load(cid)\n seen.add(b58Cid)\n\n if (block === null) { // the loader signals with `null` that we should skip this block\n return\n }\n\n for (const [, cid] of block.links()) {\n await walk({ cid, load, seen })\n }\n}\n\nexport { walk }\n", "import { CID } from 'multiformats/cid'\nimport { createUnsafe } from 'multiformats/block'\nimport { CarWriter } from '@ipld/car/writer'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { logger } from '@libp2p/logger'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as json from 'multiformats/codecs/json'\nimport { walk } from 'multiformats/traversal'\n\nconst log = logger('ipfs:components:dag:import')\n\n// blocks that we're OK with not inspecting for links\n/** @type {number[]} */\nconst NO_LINKS_CODECS = [\n raw.code, // raw\n json.code // JSON\n]\n\n/**\n * @typedef {import('../../types').Preload} Preload\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('@ipld/car/api').BlockWriter} BlockWriter\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @template T\n * @template C\n * @template A\n * @template V\n * @typedef {import('multiformats/block').Block} Block\n */\n\n/**\n * @param {object} config\n * @param {IPFSRepo} config.repo\n * @param {Preload} config.preload\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createExport ({ repo, preload, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"export\"]}\n */\n async function * dagExport (root, options = {}) {\n if (options.preload !== false) {\n preload(root)\n }\n\n const cid = CID.asCID(root)\n if (!cid) {\n throw new Error(`Unexpected error converting CID type: ${root}`)\n }\n\n log(`Exporting ${cid} as car`)\n const { writer, out } = await CarWriter.create([cid])\n\n // we need to write with one async channel and send the CarWriter output\n // with another to the caller, but if the write causes an error we capture\n // that and make sure it gets propagated\n /** @type {Error|null} */\n let err = null\n ;(async () => {\n try {\n const load = makeLoader(repo, writer, {\n signal: options.signal,\n timeout: options.timeout\n }, codecs)\n await walk({ cid, load })\n } catch (/** @type {any} */ e) {\n err = e\n } finally {\n writer.close()\n }\n })()\n\n for await (const chunk of out) {\n if (err) {\n break\n }\n yield chunk\n }\n if (err) {\n throw err\n }\n }\n\n return withTimeoutOption(dagExport)\n}\n\n/**\n * @param {IPFSRepo} repo\n * @param {BlockWriter} writer\n * @param {AbortOptions} options\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @returns {(cid:CID)=>Promise|null>}\n */\nfunction makeLoader (repo, writer, options, codecs) {\n return async (cid) => {\n const codec = await codecs.getCodec(cid.code)\n\n if (!codec) {\n throw new Error(`Can't decode links in block with codec 0x${cid.code.toString(16)} to form complete DAG`)\n }\n\n const bytes = await repo.blocks.get(cid, options)\n\n log(`Adding block ${cid} to car`)\n await writer.put({ cid, bytes })\n\n if (NO_LINKS_CODECS.includes(cid.code)) {\n return null // skip this block, no need to look inside\n }\n\n return createUnsafe({ bytes, cid, codec })\n }\n}\n", "\n/**\n * Returns the first result from an (async) iterable, unless empty, in which\n * case returns `undefined`\n */\nexport default async function first (source: AsyncIterable | Iterable): Promise {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry\n }\n\n return undefined\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport first from 'it-first'\nimport last from 'it-last'\nimport { resolve } from '../../utils.js'\nimport errCode from 'err-code'\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createGet ({ codecs, repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"get\"]}\n */\n const get = async function get (cid, options = {}) {\n if (options.preload !== false) {\n preload(cid)\n }\n\n if (options.path) {\n const entry = options.localResolve\n ? await first(resolve(cid, options.path, codecs, repo, options))\n : await last(resolve(cid, options.path, codecs, repo, options))\n /** @type {import('ipfs-core-types/src/dag').GetResult | undefined} - first and last will return undefined when empty */\n const result = (entry)\n\n if (!result) {\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n\n return result\n }\n\n const codec = await codecs.getCodec(cid.code)\n const block = await repo.blocks.get(cid, options)\n const node = codec.decode(block)\n\n return {\n value: node,\n remainderPath: ''\n }\n }\n\n return withTimeoutOption(get)\n}\n", "import {\n asyncIterableReader,\n bytesReader,\n createDecoder\n} from './decoder.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').RootsReader} RootsReader\n * @typedef {import('./coding').BytesReader} BytesReader\n */\n\n/**\n * @class\n * @implements {RootsReader}\n * @property {number} version The version number of the CAR referenced by this reader (should be `1`).\n */\nexport class CarIteratorBase {\n /**\n * @param {number} version\n * @param {CID[]} roots\n * @param {AsyncIterable|void} iterable\n */\n constructor (version, roots, iterable) {\n this._version = version\n this._roots = roots\n this._iterable = iterable\n this._decoded = false\n }\n\n get version () {\n return this._version\n }\n\n /**\n * @returns {Promise}\n */\n async getRoots () {\n return this._roots\n }\n}\n\n/**\n * Provides an iterator over all of the `Block`s in a CAR. Implements a\n * `BlockIterator` interface, or `AsyncIterable`. Where a `Block` is\n * a `{ cid:CID, bytes:Uint8Array }` pair.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const block of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarBlockiterator.fromBytes} or\n * {@link CarBlockiterator.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarBlockIterator` also implements the `RootsReader` interface and provides\n * the {@link CarBlockiterator.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarBlockIterator } from '@ipld/car/iterator'`\n * (`const { CarBlockIterator } = require('@ipld/car/iterator')`). Or\n * `import { CarBlockIterator } from '@ipld/car'`\n * (`const { CarBlockIterator } = require('@ipld/car')`).\n *\n * @name CarBlockIterator\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable}\n * @property {number} version The version number of the CAR referenced by this\n * iterator (should be `1`).\n */\nexport class CarBlockIterator extends CarIteratorBase {\n // inherited method\n /**\n * Get the list of roots defined by the CAR referenced by this iterator. May be\n * zero or more `CID`s.\n *\n * @function getRoots\n * @memberof CarBlockIterator\n * @instance\n * @async\n * @returns {Promise}\n */\n\n /**\n * @returns {AsyncIterator}\n */\n [Symbol.asyncIterator] () {\n if (this._decoded) {\n throw new Error('Cannot decode more than once')\n }\n /* c8 ignore next 3 */\n if (!this._iterable) {\n throw new Error('Block iterable not found')\n }\n this._decoded = true\n return this._iterable[Symbol.asyncIterator]()\n }\n\n /**\n * Instantiate a {@link CarBlockIterator} from a `Uint8Array` blob. Rather\n * than decoding the entire byte array prior to returning the iterator, as in\n * {@link CarReader.fromBytes}, only the header is decoded and the remainder\n * of the CAR is parsed as the `Block`s as yielded.\n *\n * @async\n * @static\n * @memberof CarBlockIterator\n * @param {Uint8Array} bytes\n * @returns {Promise}\n */\n static async fromBytes (bytes) {\n const { version, roots, iterator } = await fromBytes(bytes)\n return new CarBlockIterator(version, roots, iterator)\n }\n\n /**\n * Instantiate a {@link CarBlockIterator} from a `AsyncIterable`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * Rather than decoding the entire byte array prior to returning the iterator,\n * as in {@link CarReader.fromIterable}, only the header is decoded and the\n * remainder of the CAR is parsed as the `Block`s as yielded.\n *\n * @async\n * @static\n * @param {AsyncIterable} asyncIterable\n * @returns {Promise}\n */\n static async fromIterable (asyncIterable) {\n const { version, roots, iterator } = await fromIterable(asyncIterable)\n return new CarBlockIterator(version, roots, iterator)\n }\n}\n\n/**\n * Provides an iterator over all of the `CID`s in a CAR. Implements a\n * `CIDIterator` interface, or `AsyncIterable`. Similar to\n * {@link CarBlockIterator} but only yields the CIDs in the CAR.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const cid of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarCIDiterator.fromBytes} or\n * {@link CarCIDiterator.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarCIDIterator` also implements the `RootsReader` interface and provides\n * the {@link CarCIDiterator.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarCIDIterator } from '@ipld/car/iterator'`\n * (`const { CarCIDIterator } = require('@ipld/car/iterator')`). Or\n * `import { CarCIDIterator } from '@ipld/car'`\n * (`const { CarCIDIterator } = require('@ipld/car')`).\n *\n * @name CarCIDIterator\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable}\n * @property {number} version The version number of the CAR referenced by this\n * iterator (should be `1`).\n */\nexport class CarCIDIterator extends CarIteratorBase {\n // inherited method\n /**\n * Get the list of roots defined by the CAR referenced by this iterator. May be\n * zero or more `CID`s.\n *\n * @function getRoots\n * @memberof CarCIDIterator\n * @instance\n * @async\n * @returns {Promise}\n */\n\n /**\n * @returns {AsyncIterator}\n */\n [Symbol.asyncIterator] () {\n if (this._decoded) {\n throw new Error('Cannot decode more than once')\n }\n /* c8 ignore next 3 */\n if (!this._iterable) {\n throw new Error('Block iterable not found')\n }\n this._decoded = true\n const iterable = this._iterable[Symbol.asyncIterator]()\n return {\n async next () {\n const next = await iterable.next()\n if (next.done) {\n return next\n }\n return { done: false, value: next.value.cid }\n }\n }\n }\n\n /**\n * Instantiate a {@link CarCIDIterator} from a `Uint8Array` blob. Rather\n * than decoding the entire byte array prior to returning the iterator, as in\n * {@link CarReader.fromBytes}, only the header is decoded and the remainder\n * of the CAR is parsed as the `CID`s as yielded.\n *\n * @async\n * @static\n * @memberof CarCIDIterator\n * @param {Uint8Array} bytes\n * @returns {Promise}\n */\n static async fromBytes (bytes) {\n const { version, roots, iterator } = await fromBytes(bytes)\n return new CarCIDIterator(version, roots, iterator)\n }\n\n /**\n * Instantiate a {@link CarCIDIterator} from a `AsyncIterable`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * Rather than decoding the entire byte array prior to returning the iterator,\n * as in {@link CarReader.fromIterable}, only the header is decoded and the\n * remainder of the CAR is parsed as the `CID`s as yielded.\n *\n * @async\n * @static\n * @memberof CarCIDIterator\n * @param {AsyncIterable} asyncIterable\n * @returns {Promise}\n */\n static async fromIterable (asyncIterable) {\n const { version, roots, iterator } = await fromIterable(asyncIterable)\n return new CarCIDIterator(version, roots, iterator)\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable}>}\n */\nasync function fromBytes (bytes) {\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError('fromBytes() requires a Uint8Array')\n }\n return decodeIterator(bytesReader(bytes))\n}\n\n/**\n * @param {AsyncIterable} asyncIterable\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable}>}\n */\nasync function fromIterable (asyncIterable) {\n if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === 'function')) {\n throw new TypeError('fromIterable() requires an async iterable')\n }\n return decodeIterator(asyncIterableReader(asyncIterable))\n}\n\n/**\n * @private\n * @param {BytesReader} reader\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable}>}\n */\nasync function decodeIterator (reader) {\n const decoder = createDecoder(reader)\n const { version, roots } = await decoder.header()\n return { version, roots, iterator: decoder.blocks() }\n}\n", "import { CarBlockIterator } from '@ipld/car/iterator'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport itPeekable from 'it-peekable'\nimport drain from 'it-drain'\nimport map from 'it-map'\nimport { logger } from '@libp2p/logger'\nconst log = logger('ipfs:components:dag:import')\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('ipfs-core-types/src/dag/').ImportRootStatus} RootStatus\n */\n\n/**\n * @param {object} config\n * @param {IPFSRepo} config.repo\n */\nexport function createImport ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"import\"]}\n */\n async function * dagImport (sources, options = {}) {\n const release = await repo.gcLock.readLock()\n\n try {\n const abortOptions = { signal: options.signal, timeout: options.timeout }\n const peekable = itPeekable(sources)\n\n const { value, done } = await peekable.peek()\n\n if (done) {\n return\n }\n\n if (value) {\n // @ts-expect-error\n peekable.push(value)\n }\n\n /**\n * @type {AsyncIterable> | Iterable>}\n */\n let cars\n\n if (value instanceof Uint8Array) {\n // @ts-expect-error\n cars = [peekable]\n } else {\n // @ts-expect-error\n cars = peekable\n }\n\n for await (const car of cars) {\n const roots = await importCar(repo, abortOptions, car)\n\n if (options.pinRoots !== false) { // default=true\n for (const cid of roots) {\n let pinErrorMsg = ''\n\n try { // eslint-disable-line max-depth\n if (await repo.blocks.has(cid)) { // eslint-disable-line max-depth\n log(`Pinning root ${cid}`)\n await repo.pins.pinRecursively(cid)\n } else {\n pinErrorMsg = 'blockstore: block not found'\n }\n } catch (/** @type {any} */ err) {\n pinErrorMsg = err.message\n }\n\n yield { root: { cid, pinErrorMsg } }\n }\n }\n }\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(dagImport)\n}\n\n/**\n * @param {IPFSRepo} repo\n * @param {AbortOptions} options\n * @param {AsyncIterable} source\n * @returns {Promise}\n */\nasync function importCar (repo, options, source) {\n const reader = await CarBlockIterator.fromIterable(source)\n const roots = await reader.getRoots()\n\n await drain(\n repo.blocks.putMany(\n map(reader, ({ cid: key, bytes: value }) => {\n log(`Import block ${key}`)\n\n return { key, value }\n }),\n { signal: options.signal }\n )\n )\n\n return roots\n}\n", "import { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('../../types').Preload} config.preload\n */\nexport function createPut ({ repo, codecs, hashers, preload }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"put\"]}\n */\n async function put (dagNode, options = {}) {\n const release = options.pin ? await repo.gcLock.readLock() : null\n\n try {\n const storeCodec = await codecs.getCodec(options.storeCodec || 'dag-cbor')\n // TODO: doesn't getCodec throw? verify and possibly remove this\n if (!storeCodec) {\n throw new Error(`Unknown storeCodec ${options.storeCodec}, please configure additional BlockCodecs for this IPFS instance`)\n }\n\n if (options.inputCodec) {\n if (!(dagNode instanceof Uint8Array)) {\n throw new Error('Can only inputCodec on raw bytes that can be decoded')\n }\n const inputCodec = await codecs.getCodec(options.inputCodec)\n if (!inputCodec) {\n throw new Error(`Unknown inputCodec ${options.inputCodec}, please configure additional BlockCodecs for this IPFS instance`)\n }\n dagNode = inputCodec.decode(dagNode)\n }\n\n const cidVersion = options.version != null ? options.version : 1\n const hasher = await hashers.getHasher(options.hashAlg || 'sha2-256')\n\n if (!hasher) {\n throw new Error(`Unknown hash algorithm ${options.hashAlg}, please configure additional MultihashHashers for this IPFS instance`)\n }\n\n const buf = storeCodec.encode(dagNode)\n const hash = await hasher.digest(buf)\n const cid = CID.create(cidVersion, storeCodec.code, hash)\n\n await repo.blocks.put(cid, buf, {\n signal: options.signal\n })\n\n if (options.pin) {\n await repo.pins.pinRecursively(cid)\n }\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return cid\n } finally {\n if (release) {\n release()\n }\n }\n }\n\n return withTimeoutOption(put)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport { resolvePath } from '../../utils.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createResolve ({ repo, codecs, preload }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"resolve\"]}\n */\n async function dagResolve (ipfsPath, options = {}) {\n const {\n cid\n } = toCidAndPath(ipfsPath)\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return resolvePath(repo, codecs, ipfsPath, options)\n }\n\n return withTimeoutOption(dagResolve)\n}\n", "import { createExport } from './export.js'\nimport { createGet } from './get.js'\nimport { createImport } from './import.js'\nimport { createPut } from './put.js'\nimport { createResolve } from './resolve.js'\n\nexport class DagAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('../../types').Preload} config.preload\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ repo, codecs, hashers, preload }) {\n this.export = createExport({ repo, preload, codecs })\n this.get = createGet({ codecs, repo, preload })\n this.import = createImport({ repo })\n this.resolve = createResolve({ repo, codecs, preload })\n this.put = createPut({ repo, codecs, hashers, preload })\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to URLs.\n *\n * @example Converting multiaddrs to URLs\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\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport type { Multiaddr, StringTuple } from '@multiformats/multiaddr'\n\nexport interface MultiaddrToUriOpts {\n assumeHttp?: boolean\n}\n\ninterface Interpreter { (value: string, ma: StringTuple[]): string }\n\nfunction extractSNI (ma: StringTuple[]): string | null {\n let sniProtoCode: number\n try {\n sniProtoCode = protocols('sni').code\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}\n\nfunction hasTLS (ma: StringTuple[]): boolean {\n return ma.some(([proto, _]) => proto === protocols('tls').code)\n}\n\nfunction interpretNext (headProtoCode: number, headProtoVal: string, restMa: StringTuple[]): string {\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}\n\nconst interpreters: Record = {\n ip4: (value: string, restMa: StringTuple[]) => value,\n ip6: (value: string, restMa: StringTuple[]) => {\n if (restMa.length === 0) {\n return value\n }\n return `[${value}]`\n },\n tcp: (value: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => value,\n dns4: (value: string, restMa: StringTuple[]) => value,\n dns6: (value: string, restMa: StringTuple[]) => value,\n dns: (value: string, restMa: StringTuple[]) => value,\n ipfs: (value: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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}\n\nexport function multiaddrToUri (input: Multiaddr | string | Uint8Array, opts?: MultiaddrToUriOpts): string {\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\n const protocol = protocols(head[0])\n const interpreter = interpreters[protocol.name]\n\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`)\n }\n\n let uri = interpreter(head[1] ?? '', parts)\n if (opts?.assumeHttp !== false && head[0] === protocols('tcp').code) {\n // If rightmost proto is tcp, we assume http here\n uri = uri.replace('tcp://', 'http://')\n if (head[1] === '443' || head[1] === '80') {\n if (head[1] === '443') {\n uri = uri.replace('http://', 'https://')\n }\n // Drop the port\n uri = uri.substring(0, uri.lastIndexOf(':'))\n }\n }\n\n return uri\n}\n", "export default function arrayShuffle(array) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new TypeError(`Expected an array, got ${typeof array}`);\n\t}\n\n\tarray = [...array];\n\n\tfor (let index = array.length - 1; index > 0; index--) {\n\t\tconst newIndex = Math.floor(Math.random() * (index + 1));\n\t\t[array[index], array[newIndex]] = [array[newIndex], array[index]];\n\t}\n\n\treturn array;\n}\n", "/* eslint-env browser */\n\nimport HTTP from 'ipfs-utils/src/http.js'\nimport { logger } from '@libp2p/logger'\nimport PQueue from 'p-queue'\n\nconst log = logger('ipfs:preload')\n\n// @ts-expect-error PQueue@6 is broken\nconst Queue = PQueue.default ? PQueue.default : PQueue\n\n// browsers limit concurrent connections per host,\n// we don't want preload calls to exhaust the limit (~6)\nconst httpQueue = new Queue({ concurrency: 4 })\n\n/**\n * @param {string} url\n * @param {import('ipfs-core-types/src/utils').AbortOptions} options\n */\nexport function preload (url, options = {}) {\n log(url)\n\n return httpQueue.add(async () => {\n const res = await HTTP.post(url, { signal: options.signal })\n\n // @ts-expect-error\n const reader = res.body.getReader()\n\n try {\n while (true) {\n const { done } = await reader.read()\n if (done) return\n // Read to completion but do not cache\n }\n } finally {\n reader.releaseLock()\n }\n })\n}\n", "import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\nimport { logger } from '@libp2p/logger'\nimport shuffle from 'array-shuffle'\nimport { preload } from 'ipfs-core-config/preload'\nimport hashlru from 'hashlru'\n\nconst log = logger('ipfs:preload')\n\n/**\n * @param {import('./types').PreloadOptions} [options]\n */\nexport function createPreloader (options = {}) {\n options.enabled = Boolean(options.enabled)\n options.addresses = options.addresses || []\n options.cache = options.cache || 1000\n\n if (!options.enabled || !options.addresses.length) {\n log('preload disabled')\n const api = () => {}\n return Object.assign(api, {\n start: () => {},\n stop: () => {}\n })\n }\n\n let stopped = true\n /** @type {AbortController[]} */\n let requests = []\n const apiUris = options.addresses.map((str) => multiaddrToUri(str))\n\n // Avoid preloading the same CID over and over again\n const cache = hashlru(options.cache)\n\n /**\n * @type {import('./types').Preload}\n */\n const api = async cid => {\n try {\n if (stopped) {\n throw new Error(`preload ${cid} but preloader is not started`)\n }\n\n const path = cid.toString()\n\n if (cache.has(path)) {\n // we've preloaded this recently, don't preload it again\n return\n }\n\n // make sure we don't preload this again any time soon\n cache.set(path, true)\n\n const fallbackApiUris = shuffle(apiUris)\n let success = false\n const now = Date.now()\n\n for (const uri of fallbackApiUris) {\n if (stopped) throw new Error(`preload aborted for ${path}`)\n /** @type {AbortController} */\n let controller\n\n try {\n controller = new AbortController()\n requests = requests.concat(controller)\n await preload(`${uri}/api/v0/refs?r=true&arg=${encodeURIComponent(path)}`, { signal: controller.signal })\n success = true\n } catch (/** @type {any} */ err) {\n if (err.type !== 'aborted') log.error(err)\n } finally {\n requests = requests.filter(r => r !== controller)\n }\n\n if (success) break\n }\n\n log(`${success ? '' : 'un'}successfully preloaded ${path} in ${Date.now() - now}ms`)\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }\n\n /**\n * @returns {void}\n */\n api.start = () => {\n stopped = false\n }\n\n /**\n * @returns {void}\n */\n api.stop = () => {\n stopped = true\n log(`aborting ${requests.length} pending preload request(s)`)\n requests.forEach(r => r.abort())\n requests = []\n }\n\n return api\n}\n", "import { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:mfs-preload')\n\n/**\n * @typedef {PreloadOptions & MFSPreloadOptions} Options\n * @typedef {object} MFSPreloadOptions\n * @property {number} [interval]\n * @typedef {import('./types').PreloadOptions} PreloadOptions\n */\n\n/**\n * @param {object} config\n * @param {import('./types').Preload} config.preload\n * @param {import('ipfs-core-types/src/files').API} config.files\n * @param {Options} [config.options]\n */\nexport function createMfsPreloader ({ preload, files, options = {} }) {\n options.interval = options.interval || 30 * 1000\n\n if (!options.enabled) {\n log('MFS preload disabled')\n const noop = async () => {}\n return { start: noop, stop: noop }\n }\n\n let rootCid = ''\n /** @type {any} */\n let timeoutId\n\n const preloadMfs = async () => {\n try {\n const stats = await files.stat('/')\n const nextRootCid = stats.cid.toString()\n\n if (rootCid !== nextRootCid) {\n log(`preloading updated MFS root ${rootCid} -> ${stats.cid}`)\n await preload(stats.cid)\n rootCid = nextRootCid\n }\n } catch (/** @type {any} */ err) {\n log.error('failed to preload MFS root', err)\n } finally {\n timeoutId = setTimeout(preloadMfs, options.interval)\n }\n }\n\n return {\n /**\n * @returns {Promise}\n */\n async start () {\n const stats = await files.stat('/')\n rootCid = stats.cid.toString()\n log(`monitoring MFS root ${stats.cid}`)\n timeoutId = setTimeout(preloadMfs, options.interval)\n },\n /**\n * @returns {void}\n */\n stop () {\n clearTimeout(timeoutId)\n }\n }\n}\n", "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", "// 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 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", "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", "export interface WebworkerEventListener {\n (worker: Worker, event: MessageEvent): void\n}\n\nconst events: Record = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n", "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'\n\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", "export const nanoid = (size: number = 21): string => {\n return Math.random().toString().substring(2)\n}\n", "import observer from 'observable-webworkers'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport { nanoid } from './utils.js'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent): void => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return new Promise((resolve) => {\n const listener = (event: MessageEvent): void => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\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\n return emitter\n }\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", "/**\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\nimport PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock(): Promise\n writeLock(): Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock(name: string, options: MorticeOptions): Mortice['readLock']\n writeLock(name: string, options: MorticeOptions): Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\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\n return p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\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\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\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\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\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\n return createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler(): Promise\n}\n\nexport default function createMortice (options?: MorticeOptions): Mortice {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n", "import mortice from 'mortice'\n\n/**\n * @typedef {object} Lock\n * @property {(fn: (...args: any) => any) => (...args: any) => any} readLock\n * @property {(fn: (...args: any) => any) => (...args: any) => any} writeLock\n */\n\n/** @type {Lock} */\nlet lock\n\n/**\n * @param {boolean} [repoOwner]\n */\nexport function createLock (repoOwner = false) {\n if (lock) {\n return lock\n }\n\n const mutex = mortice({\n // ordinarily the main thread would store the read/write lock but\n // if we are the thread that owns the repo, we can store the lock\n // on this process even if we are a worker thread\n singleProcess: repoOwner\n })\n\n lock = {\n readLock: (func) => {\n return async (...args) => {\n const releaseLock = await mutex.readLock()\n\n try {\n return await func.apply(null, args)\n } finally {\n releaseLock()\n }\n }\n },\n\n writeLock: (func) => {\n return async (...args) => {\n const releaseLock = await mutex.writeLock()\n\n try {\n return await func.apply(null, args)\n } finally {\n releaseLock()\n }\n }\n }\n }\n\n return lock\n}\n", "import { CID } from 'multiformats/cid'\nimport { UnixFS } from 'ipfs-unixfs'\nimport * as dagPB from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { MFS_ROOT_KEY } from '../../../utils.js'\n\nconst log = logger('ipfs:mfs:utils:with-mfs-root')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n */\n\n/**\n * @param {MfsContext} context\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n */\nexport async function loadMfsRoot (context, options) {\n if (options && options.signal && options.signal.aborted) {\n throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })\n }\n\n // Open the repo if it's been closed\n await context.repo.datastore.open()\n\n // Load the MFS root CID\n let cid\n\n try {\n const buf = await context.repo.datastore.get(MFS_ROOT_KEY)\n\n cid = CID.decode(buf)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n\n log('Creating new MFS root')\n const buf = dagPB.encode({\n Data: new UnixFS({ type: 'directory' }).marshal(),\n Links: []\n })\n const hash = await sha256.digest(buf)\n cid = CID.createV0(hash)\n await context.repo.blocks.put(cid, buf)\n\n if (options && options.signal && options.signal.aborted) {\n throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })\n }\n\n await context.repo.datastore.put(MFS_ROOT_KEY, cid.bytes)\n }\n\n log(`Loaded MFS root /ipfs/${cid}`)\n\n return cid\n}\n", "\n/**\n * @param {string} [path]\n */\nexport function toPathComponents (path = '') {\n // split on / unless escaped with \\\n return (path\n .trim()\n .match(/([^\\\\^/]|\\\\\\/)+/g) || [])\n .filter(Boolean)\n}\n", "import { loadMfsRoot } from './with-mfs-root.js'\nimport { toPathComponents } from './to-path-components.js'\nimport { exporter } from 'ipfs-unixfs-exporter'\nimport errCode from 'err-code'\nimport { CID } from 'multiformats/cid'\n\nconst IPFS_PREFIX = 'ipfs'\n\n/**\n * @typedef {import('ipfs-unixfs-exporter').UnixFSEntry} UnixFSEntry\n * @typedef {import('ipfs-unixfs-exporter').ExporterOptions} ExporterOptions\n * @typedef {import('../').MfsContext} MfsContext\n *\n * @typedef {object} FilePath\n * @property {'mfs' | 'ipfs'} type\n * @property {'file'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {import('ipfs-unixfs').UnixFS} unixfs\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} DirectoryPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'directory'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {import('ipfs-unixfs').UnixFS} unixfs\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} ObjectPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'object'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} RawPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'raw'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} IdentityPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'identity'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {FilePath | DirectoryPath | ObjectPath | RawPath | IdentityPath} MfsPath\n */\n\n/**\n * @param {MfsContext} context\n * @param {string | CID} path\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n */\nexport const toMfsPath = async (context, path, options) => {\n const root = await loadMfsRoot(context, options)\n\n /** @type {MfsPath} */\n // @ts-expect-error fields get set later\n let output = {\n entryType: 'file'\n }\n\n let ipfsPath = ''\n\n if (CID.asCID(path)) {\n ipfsPath = `/ipfs/${path}`\n } else {\n ipfsPath = path.toString()\n }\n\n ipfsPath = ipfsPath.trim()\n ipfsPath = ipfsPath.replace(/(\\/\\/+)/g, '/')\n\n if (ipfsPath.endsWith('/') && ipfsPath.length > 1) {\n ipfsPath = ipfsPath.substring(0, ipfsPath.length - 1)\n }\n\n if (!ipfsPath) {\n throw errCode(new Error('paths must not be empty'), 'ERR_NO_PATH')\n }\n\n if (ipfsPath.substring(0, 1) !== '/') {\n throw errCode(new Error('paths must start with a leading slash'), 'ERR_INVALID_PATH')\n }\n\n if (ipfsPath.substring(ipfsPath.length - 1) === '/') {\n ipfsPath = ipfsPath.substring(0, ipfsPath.length - 1)\n }\n\n const pathComponents = toPathComponents(ipfsPath)\n\n if (pathComponents[0] === IPFS_PREFIX) {\n // e.g. /ipfs/QMfoo or /ipfs/Qmfoo/sub/path\n let mfsDirectory\n\n if (pathComponents.length === 2) {\n mfsDirectory = `/${pathComponents.join('/')}`\n } else {\n mfsDirectory = `/${pathComponents.slice(0, pathComponents.length - 1).join('/')}`\n }\n\n // @ts-expect-error fields being set\n output = {\n type: 'ipfs',\n depth: pathComponents.length - 2,\n entryType: 'file',\n\n mfsPath: `/${pathComponents.join('/')}`,\n mfsDirectory,\n parts: pathComponents,\n path: `/${pathComponents.join('/')}`,\n name: pathComponents[pathComponents.length - 1]\n }\n } else {\n const mfsPath = `/${IPFS_PREFIX}/${root}${pathComponents.length ? '/' + pathComponents.join('/') : ''}`\n const mfsDirectory = `/${IPFS_PREFIX}/${root}/${pathComponents.slice(0, pathComponents.length - 1).join('/')}`\n\n // @ts-expect-error fields being set\n output = {\n type: 'mfs',\n depth: pathComponents.length,\n entryType: 'file',\n\n mfsDirectory,\n mfsPath,\n parts: pathComponents,\n path: `/${pathComponents.join('/')}`,\n name: pathComponents[pathComponents.length - 1]\n }\n }\n\n const cidPath = output.type === 'mfs' ? output.mfsPath : output.path\n\n try {\n const res = await exporter(cidPath, context.repo.blocks, options)\n\n output.cid = res.cid\n output.mfsPath = `/ipfs/${res.path}`\n output.entryType = res.type\n output.content = res.content\n\n if ((output.entryType === 'file' || output.entryType === 'directory') && (res.type === 'file' || res.type === 'directory')) {\n output.unixfs = res.unixfs\n }\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n output.exists = Boolean(output.cid)\n\n return output\n}\n", "import mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { exporter } from 'ipfs-unixfs-exporter'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport * as dagPB from '@ipld/dag-pb'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:stat')\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} withLocal\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n withLocal: false\n}\n\n/**\n * @typedef {import('ipfs-core-types/src/files').StatResult} StatResult\n */\n\n/**\n * @param {MfsContext} context\n */\nexport function createStat (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"stat\"]}\n */\n async function mfsStat (path, options = {}) {\n /** @type {DefaultOptions} */\n options = mergeOptions(defaultOptions, options)\n\n log(`Fetching stats for ${path}`)\n\n const {\n type,\n cid,\n mfsPath\n } = await toMfsPath(context, path, options)\n\n const exportPath = type === 'ipfs' && cid ? cid : mfsPath\n let file\n\n try {\n file = await exporter(exportPath, context.repo.blocks)\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NOT_FOUND') {\n throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND')\n }\n\n throw err\n }\n\n if (!statters[file.type]) {\n throw new Error(`Cannot stat codec ${file.cid.code}`)\n }\n\n return statters[file.type](file)\n }\n\n return withTimeoutOption(mfsStat)\n}\n\n/** @type {Record StatResult>} */\nconst statters = {\n /**\n * @param {import('ipfs-unixfs-exporter').RawNode} file\n */\n raw: (file) => {\n return {\n cid: file.cid,\n size: file.node.length,\n cumulativeSize: file.node.length,\n blocks: 0,\n type: 'file', // for go compatibility\n local: undefined,\n sizeLocal: undefined,\n withLocality: false\n }\n },\n /**\n * @param {import('ipfs-unixfs-exporter').UnixFSFile} file\n */\n file: (file) => {\n /** @type {StatResult} */\n const stat = {\n cid: file.cid,\n type: 'file',\n size: file.unixfs.fileSize(),\n cumulativeSize: dagPB.encode(file.node).length + (file.node.Links || []).reduce((acc, curr) => acc + (curr.Tsize || 0), 0),\n blocks: file.unixfs.blockSizes.length,\n local: undefined,\n sizeLocal: undefined,\n withLocality: false,\n mode: file.unixfs.mode\n }\n\n if (file.unixfs.mtime) {\n stat.mtime = file.unixfs.mtime\n }\n\n return stat\n },\n /**\n * @param {import('ipfs-unixfs-exporter').UnixFSDirectory} file\n */\n directory: (file) => {\n /** @type {StatResult} */\n const stat = {\n cid: file.cid,\n type: 'directory',\n size: 0,\n cumulativeSize: dagPB.encode(file.node).length + (file.node.Links || []).reduce((acc, curr) => acc + (curr.Tsize || 0), 0),\n blocks: file.node.Links.length,\n local: undefined,\n sizeLocal: undefined,\n withLocality: false,\n mode: file.unixfs.mode\n }\n\n if (file.unixfs.mtime) {\n stat.mtime = file.unixfs.mtime\n }\n\n return stat\n },\n /**\n * @param {import('ipfs-unixfs-exporter').ObjectNode} file\n */\n object: (file) => {\n /** @type {StatResult} */\n return {\n cid: file.cid,\n size: file.node.length,\n cumulativeSize: file.node.length,\n type: 'file', // for go compatibility\n blocks: 0,\n local: undefined,\n sizeLocal: undefined,\n withLocality: false\n }\n },\n /**\n * @param {import('ipfs-unixfs-exporter').IdentityNode} file\n */\n identity: (file) => {\n /** @type {StatResult} */\n return {\n cid: file.cid,\n size: file.node.length,\n cumulativeSize: file.node.length,\n blocks: 0,\n type: 'file', // for go compatibility\n local: undefined,\n sizeLocal: undefined,\n withLocality: false\n }\n }\n}\n", "import mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { toTrail } from './utils/to-trail.js'\nimport { addLink } from './utils/add-link.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { pipe } from 'it-pipe'\nimport { importer } from 'ipfs-unixfs-importer'\nimport { recursive } from 'ipfs-unixfs-exporter'\nimport last from 'it-last'\nimport { createCp } from './cp.js'\nimport { createRm } from './rm.js'\nimport { persist } from './utils/persist.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:touch')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('./').MfsContext} MfsContext\n *\n * @typedef {object} DefaultOptions\n * @property {boolean} flush\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {number} shardSplitThreshold\n * @property {boolean} recursive\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n flush: true,\n shardSplitThreshold: 1000,\n hashAlg: 'sha2-256',\n cidVersion: 0,\n recursive: false\n}\n\n/**\n * @param {string} mode\n * @param {number} originalMode\n * @param {boolean} isDirectory\n */\nfunction calculateModification (mode, originalMode, isDirectory) {\n let modification = 0\n\n if (mode.includes('x') || (mode.includes('X') && (isDirectory || (originalMode & 0o1 || originalMode & 0o10 || originalMode & 0o100)))) {\n modification += 1\n }\n\n if (mode.includes('w')) {\n modification += 2\n }\n\n if (mode.includes('r')) {\n modification += 4\n }\n\n return modification\n}\n\n/**\n * @param {string} references\n * @param {number} modification\n */\nfunction calculateUGO (references, modification) {\n let ugo = 0\n\n if (references.includes('u')) {\n ugo += (modification << 6)\n }\n\n if (references.includes('g')) {\n ugo += (modification << 3)\n }\n\n if (references.includes('o')) {\n ugo += (modification)\n }\n\n return ugo\n}\n\n/**\n * @param {string} references\n * @param {string} mode\n * @param {number} modification\n */\nfunction calculateSpecial (references, mode, modification) {\n if (mode.includes('t')) {\n modification += parseInt('1000', 8)\n }\n\n if (mode.includes('s')) {\n if (references.includes('u')) {\n modification += parseInt('4000', 8)\n }\n\n if (references.includes('g')) {\n modification += parseInt('2000', 8)\n }\n }\n\n return modification\n}\n\n/**\n * https://en.wikipedia.org/wiki/Chmod#Symbolic_modes\n *\n * @param {string} input\n * @param {number} originalMode\n * @param {boolean} isDirectory\n */\nfunction parseSymbolicMode (input, originalMode, isDirectory) {\n if (!originalMode) {\n originalMode = 0\n }\n\n const match = input.match(/^(u?g?o?a?)(-?\\+?=?)?(r?w?x?X?s?t?)$/)\n\n if (!match) {\n throw new Error(`Invalid file mode: ${input}`)\n }\n\n let [\n ,\n references,\n operator,\n mode\n ] = match\n\n if (references === 'a' || !references) {\n references = 'ugo'\n }\n\n let modification = calculateModification(mode, originalMode, isDirectory)\n modification = calculateUGO(references, modification)\n modification = calculateSpecial(references, mode, modification)\n\n if (operator === '=') {\n if (references.includes('u')) {\n // blank u bits\n originalMode = originalMode & parseInt('7077', 8)\n\n // or them together\n originalMode = originalMode | modification\n }\n\n if (references.includes('g')) {\n // blank g bits\n originalMode = originalMode & parseInt('7707', 8)\n\n // or them together\n originalMode = originalMode | modification\n }\n\n if (references.includes('o')) {\n // blank o bits\n originalMode = originalMode & parseInt('7770', 8)\n\n // or them together\n originalMode = originalMode | modification\n }\n\n return originalMode\n }\n\n if (operator === '+') {\n return modification | originalMode\n }\n\n if (operator === '-') {\n return modification ^ originalMode\n }\n\n return originalMode\n}\n\n/**\n * @param {string | InstanceType | number} mode\n * @param {UnixFS} metadata\n * @returns {number}\n */\nfunction calculateMode (mode, metadata) {\n if (mode instanceof String || typeof mode === 'string') {\n const strMode = `${mode}`\n\n if (strMode.match(/^\\d+$/g)) {\n mode = parseInt(strMode, 8)\n } else {\n mode = 0 + strMode.split(',').reduce((curr, acc) => {\n return parseSymbolicMode(acc, curr, metadata.isDirectory())\n }, metadata.mode || 0)\n }\n }\n\n return mode\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createChmod (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"chmod\"]}\n */\n async function mfsChmod (path, mode, options = {}) {\n /** @type {DefaultOptions} */\n const opts = mergeOptions(defaultOptions, options)\n\n log(`Fetching stats for ${path}`)\n\n const {\n cid,\n mfsDirectory,\n name\n } = await toMfsPath(context, path, opts)\n\n if (cid.code !== dagPB.code) {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n if (opts.recursive) {\n // recursively export from root CID, change perms of each entry then reimport\n // but do not reimport files, only manipulate dag-pb nodes\n const root = await pipe(\n async function * () {\n for await (const entry of recursive(cid, context.repo.blocks)) {\n if (entry.type !== 'file' && entry.type !== 'directory') {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n entry.unixfs.mode = calculateMode(mode, entry.unixfs)\n\n const node = dagPB.prepare({\n Data: entry.unixfs.marshal(),\n Links: entry.node.Links\n })\n\n yield {\n path: entry.path,\n content: node\n }\n }\n },\n // @ts-expect-error we account for the incompatible source type with our custom dag builder below\n (source) => importer(source, context.repo.blocks, {\n ...opts,\n pin: false,\n dagBuilder: async function * (source, block, opts) {\n for await (const entry of source) {\n yield async function () {\n /** @type {PBNode} */\n // @ts-expect-error - cannot derive type\n const node = entry.content\n\n const buf = dagPB.encode(node)\n const cid = await persist(buf, block, opts)\n\n if (!node.Data) {\n throw errCode(new Error(`${cid} had no data`), 'ERR_INVALID_NODE')\n }\n\n const unixfs = UnixFS.unmarshal(node.Data)\n\n return {\n cid,\n size: buf.length,\n path: entry.path,\n unixfs\n }\n }\n }\n }\n }),\n (nodes) => last(nodes)\n )\n\n if (!root) {\n throw errCode(new Error(`Could not chmod ${path}`), 'ERR_COULD_NOT_CHMOD')\n }\n\n // remove old path from mfs\n await createRm(context)(path, opts)\n\n // add newly created tree to mfs at path\n await createCp(context)(`/ipfs/${root.cid}`, path, opts)\n\n return\n }\n\n const block = await context.repo.blocks.get(cid)\n const node = dagPB.decode(block)\n\n if (!node.Data) {\n throw errCode(new Error(`${cid} had no data`), 'ERR_INVALID_NODE')\n }\n\n const metadata = UnixFS.unmarshal(node.Data)\n metadata.mode = calculateMode(mode, metadata)\n const updatedBlock = dagPB.encode({\n Data: metadata.marshal(),\n Links: node.Links\n })\n\n const hashAlg = opts.hashAlg || defaultOptions.hashAlg\n const hasher = await context.hashers.getHasher(hashAlg)\n const hash = await hasher.digest(updatedBlock)\n const updatedCid = CID.create(opts.cidVersion, dagPB.code, hash)\n\n if (opts.flush) {\n await context.repo.blocks.put(updatedCid, updatedBlock)\n }\n\n const trail = await toTrail(context, mfsDirectory)\n const parent = trail[trail.length - 1]\n const parentCid = CID.decode(parent.cid.bytes)\n const parentBlock = await context.repo.blocks.get(parentCid)\n const parentNode = dagPB.decode(parentBlock)\n\n const result = await addLink(context, {\n parent: parentNode,\n name: name,\n cid: updatedCid,\n size: updatedBlock.length,\n flush: opts.flush,\n // TODO vmx 2021-03-29: decide on the API, whether it should be a `hashAlg` or `hasher`\n hashAlg,\n cidVersion: cid.version,\n shardSplitThreshold: Infinity\n })\n\n parent.cid = result.cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, opts)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, opts)\n }\n\n return withTimeoutOption(mfsChmod)\n}\n", "import { walkPath } from 'ipfs-unixfs-exporter'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:mfs:utils:to-trail')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {object} MfsTrail\n * @property {string} name\n * @property {import('multiformats/cid').CID} cid\n * @property {number} [size]\n * @property {string} [type]\n *\n * TODO: export supported types from unixfs-exporter and use for `type` above\n */\n\n/**\n * @param {MfsContext} context\n * @param {string} path\n * @returns {Promise}\n */\nexport async function toTrail (context, path) {\n log(`Creating trail for path ${path}`)\n\n const output = []\n\n for await (const fsEntry of walkPath(path, context.repo.blocks)) {\n output.push({\n name: fsEntry.name,\n cid: fsEntry.cid,\n size: fsEntry.size,\n type: fsEntry.type\n })\n }\n\n return output\n}\n", "import { CID } from 'multiformats/cid'\nimport * as dagPB from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * @typedef {object} PersistOptions\n * @property {import('multiformats/codecs/interface').BlockCodec} [codec]\n * @property {import('multiformats/hashes/interface').MultihashHasher} [hasher]\n * @property {import('multiformats/cid').Version} [cidVersion]\n * @property {boolean} [onlyHash]\n * @property {AbortSignal} [signal]\n */\n\n/**\n * @param {Uint8Array} buffer\n * @param {import('interface-blockstore').Blockstore} blockstore\n * @param {PersistOptions} options\n */\nexport const persist = async (buffer, blockstore, options) => {\n if (!options.codec) {\n options.codec = dagPB\n }\n\n if (!options.hasher) {\n options.hasher = sha256\n }\n\n if (options.cidVersion === undefined) {\n options.cidVersion = 1\n }\n\n if (options.codec === dagPB && options.hasher !== sha256) {\n options.cidVersion = 1\n }\n\n const multihash = await options.hasher.digest(buffer)\n const cid = CID.create(options.cidVersion, options.codec.code, multihash)\n\n if (!options.onlyHash) {\n await blockstore.put(cid, buffer, {\n signal: options.signal\n })\n }\n\n return cid\n}\n", "import { murmur3128 } from '@multiformats/murmur3'\n\nexport const hamtHashCode = murmur3128.code\nexport const hamtBucketBits = 8\n\n/**\n * @param {Uint8Array} buf\n */\nexport async function hamtHashFn (buf) {\n return (await murmur3128.encode(buf))\n // Murmur3 outputs 128 bit but, accidentally, IPFS Go's\n // implementation only uses the first 64, so we must do the same\n // for parity..\n .subarray(0, 8)\n // Invert buffer because that's how Go impl does it\n .reverse()\n}\n", "import { encode, prepare } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { persist } from './persist.js'\nimport { createHAMT, Bucket } from 'hamt-sharding'\nimport {\n hamtHashCode,\n hamtHashFn,\n hamtBucketBits\n} from './hamt-constants.js'\n\n/**\n * @typedef {import('ipfs-unixfs-importer').ImporterOptions} ImporterOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n *\n * @typedef {object} ImportResult\n * @property {CID} cid\n * @property {import('@ipld/dag-pb').PBNode} node\n * @property {number} size\n *\n * @typedef {object} DirContents\n * @property {CID} [cid]\n * @property {number} [size]\n *\n * @typedef {object} DirOptions\n * @property {Mtime} [mtime]\n * @property {number} [mode]\n * @property {import('multiformats/codecs/interface').BlockCodec} [codec]\n * @property {import('multiformats/cid').Version} [cidVersion]\n * @property {boolean} [onlyHash]\n * @property {AbortSignal} [signal]\n */\n\n/**\n * @typedef {object} DirProps\n * @property {boolean} root\n * @property {boolean} dir\n * @property {string} path\n * @property {boolean} dirty\n * @property {boolean} flat\n * @property {Dir} [parent]\n * @property {string} [parentKey]\n * @property {import('ipfs-unixfs').UnixFS} [unixfs]\n * @property {number} [mode]\n * @property {import('ipfs-unixfs').Mtime} [mtime]\n */\nexport class Dir {\n /**\n * @param {DirProps} props\n * @param {DirOptions} options\n */\n constructor (props, options) {\n this.options = options || {}\n this.root = props.root\n this.dir = props.dir\n this.path = props.path\n this.dirty = props.dirty\n this.flat = props.flat\n this.parent = props.parent\n this.parentKey = props.parentKey\n this.unixfs = props.unixfs\n this.mode = props.mode\n this.mtime = props.mtime\n /** @type {CID | undefined} */\n this.cid = undefined\n /** @type {number | undefined} */\n this.size = undefined\n }\n\n /**\n * @param {string} name\n * @param {DirContents} value\n */\n async put (name, value) { }\n /**\n * @param {string} name\n * @returns {Promise}\n */\n get (name) {\n return Promise.resolve(this)\n }\n\n /**\n * @returns {AsyncIterable<{ key: string, child: DirContents}>}\n */\n async * eachChildSeries () { }\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) { }\n}\n\nexport class DirSharded extends Dir {\n /**\n * @param {DirProps} props\n * @param {DirOptions} options\n */\n constructor (props, options) {\n super(props, options)\n\n /** @type {Bucket} */\n this._bucket = createHAMT({\n hashFn: hamtHashFn,\n bits: hamtBucketBits\n })\n }\n\n /**\n * @param {string} name\n * @param {DirContents} value\n */\n async put (name, value) {\n await this._bucket.put(name, value)\n }\n\n /**\n * @param {string} name\n */\n get (name) {\n return this._bucket.get(name)\n }\n\n childCount () {\n return this._bucket.leafCount()\n }\n\n directChildrenCount () {\n return this._bucket.childrenCount()\n }\n\n onlyChild () {\n return this._bucket.onlyChild()\n }\n\n async * eachChildSeries () {\n for await (const { key, value } of this._bucket.eachLeafSeries()) {\n yield {\n key,\n child: value\n }\n }\n }\n\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) {\n yield * flush(this._bucket, blockstore, this, this.options)\n }\n}\n\n/**\n * @param {Bucket} bucket\n * @param {Blockstore} blockstore\n * @param {*} shardRoot\n * @param {DirOptions} options\n * @returns {AsyncIterable}\n */\nasync function * flush (bucket, blockstore, shardRoot, options) {\n const children = bucket._children\n const links = []\n let childrenSize = 0\n\n for (let i = 0; i < children.length; i++) {\n const child = children.get(i)\n\n if (!child) {\n continue\n }\n\n const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0')\n\n if (child instanceof Bucket) {\n let shard\n\n for await (const subShard of await flush(child, blockstore, null, options)) {\n shard = subShard\n }\n\n if (!shard) {\n throw new Error('Could not flush sharded directory, no subshard found')\n }\n\n links.push({\n Name: labelPrefix,\n Tsize: shard.size,\n Hash: shard.cid\n })\n childrenSize += shard.size\n } else if (typeof child.value.flush === 'function') {\n const dir = child.value\n let flushedDir\n\n for await (const entry of dir.flush(blockstore)) {\n flushedDir = entry\n\n yield flushedDir\n }\n\n const label = labelPrefix + child.key\n links.push({\n Name: label,\n Tsize: flushedDir.size,\n Hash: flushedDir.cid\n })\n\n childrenSize += flushedDir.size\n } else {\n const value = child.value\n\n if (!value.cid) {\n continue\n }\n\n const label = labelPrefix + child.key\n const size = value.size\n\n links.push({\n Name: label,\n Tsize: size,\n Hash: value.cid\n })\n childrenSize += size\n }\n }\n\n // go-ipfs uses little endian, that's why we have to\n // reverse the bit field before storing it\n const data = Uint8Array.from(children.bitField().reverse())\n const dir = new UnixFS({\n type: 'hamt-sharded-directory',\n data,\n fanout: bucket.tableSize(),\n hashType: hamtHashCode,\n mtime: shardRoot && shardRoot.mtime,\n mode: shardRoot && shardRoot.mode\n })\n\n const node = {\n Data: dir.marshal(),\n Links: links\n }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, blockstore, options)\n const size = buffer.length + childrenSize\n\n yield {\n cid,\n node,\n size\n }\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport {\n Bucket,\n createHAMT\n} from 'hamt-sharding'\nimport { DirSharded } from './dir-sharded.js'\nimport { logger } from '@libp2p/logger'\nimport { UnixFS } from 'ipfs-unixfs'\nimport last from 'it-last'\nimport { CID } from 'multiformats/cid'\nimport {\n hamtHashCode,\n hamtHashFn,\n hamtBucketBits\n} from './hamt-constants.js'\n\nconst log = logger('ipfs:mfs:core:utils:hamt-utils')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n/**\n * @param {MfsContext} context\n * @param {PBLink[]} links\n * @param {Bucket} bucket\n * @param {object} options\n * @param {PBNode} options.parent\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {string} options.hashAlg\n */\nexport const updateHamtDirectory = async (context, links, bucket, options) => {\n if (!options.parent.Data) {\n throw new Error('Could not update HAMT directory because parent had no data')\n }\n\n // update parent with new bit field\n const data = Uint8Array.from(bucket._children.bitField().reverse())\n const node = UnixFS.unmarshal(options.parent.Data)\n const dir = new UnixFS({\n type: 'hamt-sharded-directory',\n data,\n fanout: bucket.tableSize(),\n hashType: hamtHashCode,\n mode: node.mode,\n mtime: node.mtime\n })\n\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const parent = {\n Data: dir.marshal(),\n Links: links.sort((a, b) => (a.Name || '').localeCompare(b.Name || ''))\n }\n const buf = dagPB.encode(parent)\n const hash = await hasher.digest(buf)\n const cid = CID.create(options.cidVersion, dagPB.code, hash)\n\n if (options.flush) {\n await context.repo.blocks.put(cid, buf)\n }\n\n return {\n node: parent,\n cid,\n size: links.reduce((sum, link) => sum + (link.Tsize || 0), buf.length)\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {PBLink[]} links\n * @param {Bucket} rootBucket\n * @param {Bucket} parentBucket\n * @param {number} positionAtParent\n */\nexport const recreateHamtLevel = async (context, links, rootBucket, parentBucket, positionAtParent) => {\n // recreate this level of the HAMT\n const bucket = new Bucket({\n hash: rootBucket._options.hash,\n bits: rootBucket._options.bits\n }, parentBucket, positionAtParent)\n parentBucket._putObjectAt(positionAtParent, bucket)\n\n await addLinksToHamtBucket(context, links, bucket, rootBucket)\n\n return bucket\n}\n\n/**\n * @param {PBLink[]} links\n */\nexport const recreateInitialHamtLevel = async (links) => {\n const bucket = createHAMT({\n hashFn: hamtHashFn,\n bits: hamtBucketBits\n })\n\n // populate sub bucket but do not recurse as we do not want to pull whole shard in\n await Promise.all(\n links.map(async link => {\n const linkName = (link.Name || '')\n\n if (linkName.length === 2) {\n const pos = parseInt(linkName, 16)\n\n const subBucket = new Bucket({\n hash: bucket._options.hash,\n bits: bucket._options.bits\n }, bucket, pos)\n bucket._putObjectAt(pos, subBucket)\n\n return Promise.resolve()\n }\n\n return bucket.put(linkName.substring(2), {\n size: link.Tsize,\n cid: link.Hash\n })\n })\n )\n\n return bucket\n}\n\n/**\n * @param {MfsContext} context\n * @param {PBLink[]} links\n * @param {Bucket} bucket\n * @param {Bucket} rootBucket\n */\nexport const addLinksToHamtBucket = async (context, links, bucket, rootBucket) => {\n await Promise.all(\n links.map(async link => {\n const linkName = (link.Name || '')\n\n if (linkName.length === 2) {\n log('Populating sub bucket', linkName)\n const pos = parseInt(linkName, 16)\n const block = await context.repo.blocks.get(link.Hash)\n const node = dagPB.decode(block)\n\n const subBucket = new Bucket({\n hash: rootBucket._options.hash,\n bits: rootBucket._options.bits\n }, bucket, pos)\n bucket._putObjectAt(pos, subBucket)\n\n await addLinksToHamtBucket(context, node.Links, subBucket, rootBucket)\n\n return Promise.resolve()\n }\n\n return rootBucket.put(linkName.substring(2), {\n size: link.Tsize,\n cid: link.Hash\n })\n })\n )\n}\n\n/**\n * @param {number} position\n */\nexport const toPrefix = (position) => {\n return position\n .toString(16)\n .toUpperCase()\n .padStart(2, '0')\n .substring(0, 2)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} fileName\n * @param {PBNode} rootNode\n */\nexport const generatePath = async (context, fileName, rootNode) => {\n // start at the root bucket and descend, loading nodes as we go\n const rootBucket = await recreateInitialHamtLevel(rootNode.Links)\n const position = await rootBucket._findNewBucketAndPos(fileName)\n\n // the path to the root bucket\n /** @type {{ bucket: Bucket, prefix: string, node?: PBNode }[]} */\n const path = [{\n bucket: position.bucket,\n prefix: toPrefix(position.pos)\n }]\n let currentBucket = position.bucket\n\n while (currentBucket !== rootBucket) {\n path.push({\n bucket: currentBucket,\n prefix: toPrefix(currentBucket._posAtParent)\n })\n\n // @ts-expect-error - only the root bucket's parent will be undefined\n currentBucket = currentBucket._parent\n }\n\n path.reverse()\n path[0].node = rootNode\n\n // load PbNode for each path segment\n for (let i = 0; i < path.length; i++) {\n const segment = path[i]\n\n if (!segment.node) {\n throw new Error('Could not generate HAMT path')\n }\n\n // find prefix in links\n const link = segment.node.Links\n .filter(link => (link.Name || '').substring(0, 2) === segment.prefix)\n .pop()\n\n // entry was not in shard\n if (!link) {\n // reached bottom of tree, file will be added to the current bucket\n log(`Link ${segment.prefix}${fileName} will be added`)\n // return path\n continue\n }\n\n // found entry\n if (link.Name === `${segment.prefix}${fileName}`) {\n log(`Link ${segment.prefix}${fileName} will be replaced`)\n // file already existed, file will be added to the current bucket\n // return path\n continue\n }\n\n // found subshard\n log(`Found subshard ${segment.prefix}`)\n const block = await context.repo.blocks.get(link.Hash)\n const node = dagPB.decode(block)\n\n // subshard hasn't been loaded, descend to the next level of the HAMT\n if (!path[i + 1]) {\n log(`Loaded new subshard ${segment.prefix}`)\n\n await recreateHamtLevel(context, node.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16))\n const position = await rootBucket._findNewBucketAndPos(fileName)\n\n // i--\n path.push({\n bucket: position.bucket,\n prefix: toPrefix(position.pos),\n node: node\n })\n\n continue\n }\n\n const nextSegment = path[i + 1]\n\n // add intermediate links to bucket\n await addLinksToHamtBucket(context, node.Links, nextSegment.bucket, rootBucket)\n\n nextSegment.node = node\n }\n\n await rootBucket.put(fileName, true)\n\n path.reverse()\n\n return {\n rootBucket,\n path\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {{ name: string, size: number, cid: CID }[]} contents\n * @param {object} [options]\n * @param {Mtime} [options.mtime]\n * @param {number} [options.mode]\n */\nexport const createShard = async (context, contents, options = {}) => {\n const shard = new DirSharded({\n root: true,\n dir: true,\n parent: undefined,\n parentKey: undefined,\n path: '',\n dirty: true,\n flat: false,\n mtime: options.mtime,\n mode: options.mode\n }, options)\n\n for (let i = 0; i < contents.length; i++) {\n await shard._bucket.put(contents[i].name, {\n size: contents[i].size,\n cid: contents[i].cid\n })\n }\n\n const res = await last(shard.flush(context.repo.blocks))\n\n if (!res) {\n throw new Error('Flushing shard yielded no result')\n }\n\n return res\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { logger } from '@libp2p/logger'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { DirSharded } from './dir-sharded.js'\nimport {\n updateHamtDirectory,\n recreateHamtLevel,\n recreateInitialHamtLevel,\n createShard,\n toPrefix,\n addLinksToHamtBucket\n} from './hamt-utils.js'\nimport errCode from 'err-code'\nimport last from 'it-last'\n\nconst log = logger('ipfs:mfs:core:utils:add-link')\n\n/**\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('hamt-sharding').Bucket} Bucket\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {number} options.shardSplitThreshold\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {CID} [options.parentCid]\n * @param {PBNode} [options.parent]\n */\nexport async function addLink (context, options) {\n let parent = options.parent\n\n if (options.parentCid) {\n const parentCid = CID.asCID(options.parentCid)\n if (parentCid === null) {\n throw errCode(new Error('Invalid CID passed to addLink'), 'EINVALIDPARENTCID')\n }\n\n if (parentCid.code !== dagPB.code) {\n throw errCode(new Error('Unsupported codec. Only DAG-PB is supported'), 'EINVALIDPARENTCID')\n }\n\n log(`Loading parent node ${parentCid}`)\n const block = await context.repo.blocks.get(parentCid)\n parent = dagPB.decode(block)\n }\n\n if (!parent) {\n throw errCode(new Error('No parent node or CID passed to addLink'), 'EINVALIDPARENT')\n }\n\n if (!options.cid) {\n throw errCode(new Error('No child cid passed to addLink'), 'EINVALIDCHILDCID')\n }\n\n if (!options.name) {\n throw errCode(new Error('No child name passed to addLink'), 'EINVALIDCHILDNAME')\n }\n\n if (!options.size && options.size !== 0) {\n throw errCode(new Error('No child size passed to addLink'), 'EINVALIDCHILDSIZE')\n }\n\n if (!parent.Data) {\n throw errCode(new Error('Parent node with no data passed to addLink'), 'ERR_INVALID_PARENT')\n }\n\n const meta = UnixFS.unmarshal(parent.Data)\n\n if (meta.type === 'hamt-sharded-directory') {\n log('Adding link to sharded directory')\n\n return addToShardedDirectory(context, {\n ...options,\n parent\n })\n }\n\n if (parent.Links.length >= options.shardSplitThreshold) {\n log('Converting directory to sharded directory')\n\n return convertToShardedDirectory(context, {\n ...options,\n parent,\n mtime: meta.mtime,\n mode: meta.mode\n })\n }\n\n log(`Adding ${options.name} (${options.cid}) to regular directory`)\n\n return addToDirectory(context, {\n ...options,\n parent\n })\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {Mtime} [options.mtime]\n * @param {number} [options.mode]\n */\nconst convertToShardedDirectory = async (context, options) => {\n const result = await createShard(context, options.parent.Links.map(link => ({\n name: (link.Name || ''),\n size: link.Tsize || 0,\n cid: link.Hash\n })).concat({\n name: options.name,\n size: options.size,\n cid: options.cid\n }), options)\n\n log(`Converted directory to sharded directory ${result.cid}`)\n\n return result\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {Mtime} [options.mtime]\n * @param {number} [options.mode]\n */\nconst addToDirectory = async (context, options) => {\n // Remove existing link if it exists\n const parentLinks = options.parent.Links.filter((link) => {\n return link.Name !== options.name\n })\n parentLinks.push({\n Name: options.name,\n Tsize: options.size,\n Hash: options.cid\n })\n\n if (!options.parent.Data) {\n throw errCode(new Error('Parent node with no data passed to addToDirectory'), 'ERR_INVALID_PARENT')\n }\n\n const node = UnixFS.unmarshal(options.parent.Data)\n\n let data\n if (node.mtime) {\n // Update mtime if previously set\n const ms = Date.now()\n const secs = Math.floor(ms / 1000)\n\n node.mtime = {\n secs: secs,\n nsecs: (ms - (secs * 1000)) * 1000\n }\n\n data = node.marshal()\n } else {\n data = options.parent.Data\n }\n options.parent = dagPB.prepare({\n Data: data,\n Links: parentLinks\n })\n\n // Persist the new parent PbNode\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const buf = dagPB.encode(options.parent)\n const hash = await hasher.digest(buf)\n const cid = CID.create(options.cidVersion, dagPB.code, hash)\n\n if (options.flush) {\n await context.repo.blocks.put(cid, buf)\n }\n\n return {\n node: options.parent,\n cid,\n size: buf.length\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n */\nconst addToShardedDirectory = async (context, options) => {\n const {\n shard, path\n } = await addFileToShardedDirectory(context, options)\n const result = await last(shard.flush(context.repo.blocks))\n\n if (!result) {\n throw new Error('No result from flushing shard')\n }\n\n const block = await context.repo.blocks.get(result.cid)\n const node = dagPB.decode(block)\n\n // we have written out the shard, but only one sub-shard will have been written so replace it in the original shard\n const parentLinks = options.parent.Links.filter((link) => {\n // TODO vmx 2021-03-31: Check that there cannot be multiple ones matching\n // Remove the old link\n return (link.Name || '').substring(0, 2) !== path[0].prefix\n })\n\n const newLink = node.Links\n .find(link => (link.Name || '').substring(0, 2) === path[0].prefix)\n\n if (!newLink) {\n throw new Error(`No link found with prefix ${path[0].prefix}`)\n }\n\n parentLinks.push(newLink)\n\n return updateHamtDirectory(context, parentLinks, path[0].bucket, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n */\nconst addFileToShardedDirectory = async (context, options) => {\n const file = {\n name: options.name,\n cid: options.cid,\n size: options.size\n }\n\n if (!options.parent.Data) {\n throw errCode(new Error('Parent node with no data passed to addFileToShardedDirectory'), 'ERR_INVALID_PARENT')\n }\n\n // start at the root bucket and descend, loading nodes as we go\n const rootBucket = await recreateInitialHamtLevel(options.parent.Links)\n const node = UnixFS.unmarshal(options.parent.Data)\n\n const shard = new DirSharded({\n root: true,\n dir: true,\n parent: undefined,\n parentKey: undefined,\n path: '',\n dirty: true,\n flat: false,\n mode: node.mode\n }, options)\n shard._bucket = rootBucket\n\n if (node.mtime) {\n // update mtime if previously set\n shard.mtime = {\n secs: Math.round(Date.now() / 1000)\n }\n }\n\n // load subshards until the bucket & position no longer changes\n const position = await rootBucket._findNewBucketAndPos(file.name)\n const path = toBucketPath(position)\n path[0].node = options.parent\n let index = 0\n\n while (index < path.length) {\n const segment = path[index]\n index++\n const node = segment.node\n\n if (!node) {\n throw new Error('Segment had no node')\n }\n\n const link = node.Links\n .find(link => (link.Name || '').substring(0, 2) === segment.prefix)\n\n if (!link) {\n // prefix is new, file will be added to the current bucket\n log(`Link ${segment.prefix}${file.name} will be added`)\n index = path.length\n\n break\n }\n\n if (link.Name === `${segment.prefix}${file.name}`) {\n // file already existed, file will be added to the current bucket\n log(`Link ${segment.prefix}${file.name} will be replaced`)\n index = path.length\n\n break\n }\n\n if ((link.Name || '').length > 2) {\n // another file had the same prefix, will be replaced with a subshard\n log(`Link ${link.Name} ${link.Hash} will be replaced with a subshard`)\n index = path.length\n\n break\n }\n\n // load sub-shard\n log(`Found subshard ${segment.prefix}`)\n const block = await context.repo.blocks.get(link.Hash)\n const subShard = dagPB.decode(block)\n\n // subshard hasn't been loaded, descend to the next level of the HAMT\n if (!path[index]) {\n log(`Loaded new subshard ${segment.prefix}`)\n await recreateHamtLevel(context, subShard.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16))\n\n const position = await rootBucket._findNewBucketAndPos(file.name)\n\n path.push({\n bucket: position.bucket,\n prefix: toPrefix(position.pos),\n node: subShard\n })\n\n break\n }\n\n const nextSegment = path[index]\n\n // add next levels worth of links to bucket\n await addLinksToHamtBucket(context, subShard.Links, nextSegment.bucket, rootBucket)\n\n nextSegment.node = subShard\n }\n\n // finally add the new file into the shard\n await shard._bucket.put(file.name, {\n size: file.size,\n cid: file.cid\n })\n\n return {\n shard, path\n }\n}\n\n/**\n * @param {{ pos: number, bucket: Bucket }} position\n * @returns {{ bucket: Bucket, prefix: string, node?: PBNode }[]}\n */\nconst toBucketPath = (position) => {\n const path = [{\n bucket: position.bucket,\n prefix: toPrefix(position.pos)\n }]\n\n let bucket = position.bucket._parent\n let positionInBucket = position.bucket._posAtParent\n\n while (bucket) {\n path.push({\n bucket,\n prefix: toPrefix(positionInBucket)\n })\n\n positionInBucket = bucket._posAtParent\n bucket = bucket._parent\n }\n\n path.reverse()\n\n return path\n}\n", "import { logger } from '@libp2p/logger'\nimport { addLink } from './add-link.js'\nimport {\n decode\n} from '@ipld/dag-pb'\n\nconst log = logger('ipfs:mfs:utils:update-tree')\n\nconst defaultOptions = {\n shardSplitThreshold: 1000\n}\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('./to-trail').MfsTrail} MfsTrail\n */\n\n/**\n * Loop backwards through the trail, replacing links of all components to update CIDs\n *\n * @param {MfsContext} context\n * @param {MfsTrail[]} trail\n * @param {object} options\n * @param {number} options.shardSplitThreshold\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n */\nexport async function updateTree (context, trail, options) {\n options = Object.assign({}, defaultOptions, options)\n\n log('Trail', trail)\n trail = trail.slice().reverse()\n\n let index = 0\n let child\n\n for await (const block of context.repo.blocks.getMany(trail.map(node => node.cid))) {\n const node = decode(block)\n const cid = trail[index].cid\n const name = trail[index].name\n index++\n\n if (!child) {\n child = {\n cid,\n name,\n size: block.length\n }\n\n continue\n }\n\n /** @type {{ cid: CID, size: number }} */\n const result = await addLink(context, {\n parent: node,\n name: child.name,\n cid: child.cid,\n // TODO vmx 2021-04-05: check what to do with the size\n size: child.size,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion\n })\n\n // new child for next loop\n child = {\n cid: result.cid,\n name,\n // TODO vmx 2021-04-05: check what to do with the size\n size: result.size\n }\n }\n\n // @ts-expect-error - child is possibly undefined\n const { cid } = child\n log(`Final CID ${cid}`)\n\n return cid\n}\n", "import { logger } from '@libp2p/logger'\nimport {\n MFS_ROOT_KEY\n} from '../../../utils.js'\nimport errCode from 'err-code'\n\nconst log = logger('ipfs:mfs:utils:update-mfs-root')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n */\n\n/**\n * @param {MfsContext} context\n * @param {import('multiformats/cid').CID} cid\n * @param {import('ipfs-core-types/src/utils').AbortOptions} options\n */\nexport async function updateMfsRoot (context, cid, options) {\n if (options && options.signal && options.signal.aborted) {\n throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })\n }\n\n log(`New MFS root will be ${cid}`)\n\n await context.repo.datastore.put(MFS_ROOT_KEY, cid.bytes)\n\n return cid\n}\n", "import errCode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { exporter } from 'ipfs-unixfs-exporter'\nimport { createNode } from './utils/create-node.js'\nimport { toPathComponents } from './utils/to-path-components.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { addLink } from './utils/add-link.js'\nimport { loadMfsRoot } from './utils/with-mfs-root.js'\nimport mergeOpts from 'merge-options'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:mkdir')\n\n/**\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} parents\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {number} shardSplitThreshold\n * @property {boolean} flush\n * @property {number} [mode]\n * @property {MtimeLike} [mtime]\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n parents: false,\n hashAlg: 'sha2-256',\n cidVersion: 0,\n shardSplitThreshold: 1000,\n flush: true\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createMkdir (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"mkdir\"]}\n */\n async function mfsMkdir (path, options = {}) {\n /** @type {DefaultOptions} */\n const opts = mergeOptions(defaultOptions, options)\n\n if (!path) {\n throw new Error('no path given to Mkdir')\n }\n\n path = path.trim()\n\n if (path === '/') {\n if (opts.parents) {\n return\n }\n\n throw errCode(new Error('cannot create directory \\'/\\': Already exists'), 'ERR_INVALID_PATH')\n }\n\n if (path.substring(0, 1) !== '/') {\n throw errCode(new Error('paths must start with a leading slash'), 'ERR_INVALID_PATH')\n }\n\n log(`Creating ${path}`)\n\n const pathComponents = toPathComponents(path)\n\n if (pathComponents[0] === 'ipfs') {\n throw errCode(new Error(\"path cannot have the prefix 'ipfs'\"), 'ERR_INVALID_PATH')\n }\n\n const root = await loadMfsRoot(context, opts)\n let parent\n const trail = []\n const emptyDir = await createNode(context, 'directory', opts)\n\n // make sure the containing folder exists, creating it if necessary\n for (let i = 0; i <= pathComponents.length; i++) {\n const subPathComponents = pathComponents.slice(0, i)\n const subPath = `/ipfs/${root}/${subPathComponents.join('/')}`\n\n try {\n parent = await exporter(subPath, context.repo.blocks)\n\n if (parent.type !== 'file' && parent.type !== 'directory') {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n if (i === pathComponents.length) {\n if (opts.parents) {\n return\n }\n\n throw errCode(new Error('file already exists'), 'ERR_ALREADY_EXISTS')\n }\n\n trail.push({\n name: parent.name,\n cid: parent.cid\n })\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NOT_FOUND') {\n if (i < pathComponents.length && !opts.parents) {\n throw errCode(new Error(`Intermediate directory path ${subPath} does not exist, use the -p flag to create it`), 'ERR_NOT_FOUND')\n }\n\n // add the intermediate directory\n await addEmptyDir(context, subPathComponents[subPathComponents.length - 1], emptyDir, trail[trail.length - 1], trail, opts)\n } else {\n throw err\n }\n }\n }\n\n // add an empty dir to the last path component\n // await addEmptyDir(context, pathComponents[pathComponents.length - 1], emptyDir, parent, trail)\n\n // update the tree from the leaf to the root\n const newRootCid = await updateTree(context, trail, opts)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, opts)\n }\n\n return withTimeoutOption(mfsMkdir)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} childName\n * @param {{ cid: CID, node?: PBNode }} emptyDir\n * @param {{ cid?: CID, node?: PBNode }} parent\n * @param {{ name: string, cid: CID }[]} trail\n * @param {DefaultOptions} options\n */\nconst addEmptyDir = async (context, childName, emptyDir, parent, trail, options) => {\n log(`Adding empty dir called ${childName} to ${parent.cid}`)\n\n const result = await addLink(context, {\n parent: parent.node,\n parentCid: parent.cid,\n // TODO vmx 2021-03-09: Remove the usage of size completely\n size: 0,\n cid: emptyDir.cid,\n name: childName,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold\n })\n\n trail[trail.length - 1].cid = result.cid\n\n trail.push({\n name: childName,\n cid: emptyDir.cid\n })\n}\n", "import { UnixFS } from 'ipfs-unixfs'\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('../').MfsContext} MfsContext\n */\n\n/**\n * @param {MfsContext} context\n * @param {'file' | 'directory'} type\n * @param {object} options\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {MtimeLike} [options.mtime]\n * @param {number} [options.mode]\n */\nexport async function createNode (context, type, options) {\n const metadata = new UnixFS({\n type,\n mode: options.mode,\n mtime: options.mtime\n })\n\n // Persist the new parent PBNode\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const node = {\n Data: metadata.marshal(),\n Links: []\n }\n const buf = dagPB.encode(node)\n const hash = await hasher.digest(buf)\n const cid = CID.create(options.cidVersion, dagPB.code, hash)\n\n if (options.flush) {\n await context.repo.blocks.put(cid, buf)\n }\n\n return {\n cid,\n node\n }\n}\n", "import { createMkdir } from './mkdir.js'\nimport { createStat } from './stat.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport { addLink } from './utils/add-link.js'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport mergeOpts from 'merge-options'\nimport { toTrail } from './utils/to-trail.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:cp')\n\n/**\n * @typedef {import('@ipld/dag-pb').PBNode} DAGNode\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n * @typedef {import('./utils/to-mfs-path').MfsPath} MfsPath\n * @typedef {import('./utils/to-trail').MfsTrail} MfsTrail\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} parents\n * @property {boolean} flush\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {number} shardSplitThreshold\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n parents: false,\n flush: true,\n hashAlg: 'sha2-256',\n cidVersion: 0,\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createCp (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"cp\"]}\n */\n async function mfsCp (from, to, opts = {}) {\n /** @type {DefaultOptions} */\n const options = mergeOptions(defaultOptions, opts)\n\n if (!Array.isArray(from)) {\n from = [from]\n }\n\n const sources = await Promise.all(\n from.map((/** @type {CID | string} */ path) => toMfsPath(context, path, options))\n )\n let destination = await toMfsPath(context, to, options)\n\n if (!sources.length || !destination) {\n throw errCode(new Error('Please supply at least one source'), 'ERR_INVALID_PARAMS')\n }\n\n // make sure all sources exist\n const missing = sources.find(source => !source.exists)\n\n if (missing) {\n throw errCode(new Error(`${missing.path} does not exist`), 'ERR_INVALID_PARAMS')\n }\n\n const destinationIsDirectory = isDirectory(destination)\n\n if (destination.exists) {\n log('Destination exists')\n\n if (sources.length === 1 && !destinationIsDirectory) {\n throw errCode(new Error('directory already has entry by that name'), 'ERR_ALREADY_EXISTS')\n }\n } else {\n log('Destination does not exist')\n\n if (sources.length > 1) {\n // copying multiple files to one location, destination will be a directory\n if (!options.parents) {\n throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS')\n }\n\n await createMkdir(context)(destination.path, options)\n destination = await toMfsPath(context, destination.path, options)\n } else if (destination.parts.length > 1) {\n // copying to a folder, create it if necessary\n const parentFolder = `/${destination.parts.slice(0, -1).join('/')}`\n\n try {\n await createStat(context)(parentFolder, options)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n\n if (!options.parents) {\n throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS')\n }\n\n await createMkdir(context)(parentFolder, options)\n destination = await toMfsPath(context, destination.path, options)\n }\n }\n }\n\n const destinationPath = isDirectory(destination) ? destination.mfsPath : destination.mfsDirectory\n const trail = await toTrail(context, destinationPath)\n\n if (sources.length === 1) {\n const source = sources.pop()\n\n if (!source) {\n throw errCode(new Error('could not find source'), 'ERR_INVALID_PARAMS')\n }\n\n const destinationName = destinationIsDirectory ? source.name : destination.name\n\n log(`Only one source, copying to destination ${destinationIsDirectory ? 'directory' : 'file'} ${destinationName}`)\n\n return copyToFile(context, source, destinationName, trail, options)\n }\n\n log('Multiple sources, wrapping in a directory')\n return copyToDirectory(context, sources, destination, trail, options)\n }\n\n return withTimeoutOption(mfsCp)\n}\n\n/**\n * @param {*} destination\n */\nconst isDirectory = (destination) => {\n return destination.unixfs &&\n destination.unixfs.type &&\n destination.unixfs.type.includes('directory')\n}\n\n/**\n * @param {MfsContext} context\n * @param {MfsPath} source\n * @param {string} destination\n * @param {MfsTrail[]} destinationTrail\n * @param {DefaultOptions} options\n */\nconst copyToFile = async (context, source, destination, destinationTrail, options) => {\n let parent = destinationTrail.pop()\n\n if (!parent) {\n throw errCode(new Error('destination had no parent'), 'ERR_INVALID_PARAMS')\n }\n\n parent = await addSourceToParent(context, source, destination, parent, options)\n\n // update the tree with the new containing directory\n destinationTrail.push(parent)\n\n const newRootCid = await updateTree(context, destinationTrail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {MfsPath[]} sources\n * @param {*} destination\n * @param {MfsTrail[]} destinationTrail\n * @param {DefaultOptions} options\n */\nconst copyToDirectory = async (context, sources, destination, destinationTrail, options) => {\n // copy all the sources to the destination\n for (let i = 0; i < sources.length; i++) {\n const source = sources[i]\n\n destination = await addSourceToParent(context, source, source.name, destination, options)\n }\n\n // update the tree with the new containing directory\n destinationTrail[destinationTrail.length - 1] = destination\n\n const newRootCid = await updateTree(context, destinationTrail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {MfsPath} source\n * @param {string} childName\n * @param {*} parent\n * @param {DefaultOptions} options\n * @returns {Promise}\n */\nconst addSourceToParent = async (context, source, childName, parent, options) => {\n const sourceBlock = await context.repo.blocks.get(source.cid)\n const {\n node,\n cid,\n size\n } = await addLink(context, {\n parentCid: parent.cid,\n size: sourceBlock.length,\n cid: source.cid,\n name: childName,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold\n })\n\n parent.node = node\n parent.cid = cid\n parent.size = size\n\n return parent\n}\n", "import errCode from 'err-code'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport { removeLink } from './utils/remove-link.js'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { toTrail } from './utils/to-trail.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport mergeOpts from 'merge-options'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} recursive\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {boolean} flush\n * @property {number} shardSplitThreshold\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n recursive: false,\n cidVersion: 0,\n hashAlg: 'sha2-256',\n flush: true,\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createRm (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"rm\"]}\n */\n async function mfsRm (paths, opts = {}) {\n /** @type {DefaultOptions} */\n const options = mergeOptions(defaultOptions, opts)\n\n if (!Array.isArray(paths)) {\n paths = [paths]\n }\n\n const sources = await Promise.all(\n paths.map(path => toMfsPath(context, path, options))\n )\n\n if (!sources.length) {\n throw errCode(new Error('Please supply at least one path to remove'), 'ERR_INVALID_PARAMS')\n }\n\n sources.forEach(source => {\n if (source.path === '/') {\n throw errCode(new Error('Cannot delete root'), 'ERR_INVALID_PARAMS')\n }\n })\n\n for (const source of sources) {\n await removePath(context, source.path, options)\n }\n }\n\n return withTimeoutOption(mfsRm)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} path\n * @param {DefaultOptions} options\n */\nconst removePath = async (context, path, options) => {\n const mfsPath = await toMfsPath(context, path, options)\n const trail = await toTrail(context, mfsPath.mfsPath)\n const child = trail[trail.length - 1]\n trail.pop()\n const parent = trail[trail.length - 1]\n\n if (!parent) {\n throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND')\n }\n\n if (child.type === 'directory' && !options.recursive) {\n throw errCode(new Error(`${path} is a directory, use -r to remove directories`), 'ERR_WAS_DIR')\n }\n\n const {\n cid\n } = await removeLink(context, {\n parentCid: parent.cid,\n name: child.name,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold\n })\n\n parent.cid = cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n}\n", "\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { logger } from '@libp2p/logger'\nimport { UnixFS } from 'ipfs-unixfs'\nimport {\n generatePath,\n updateHamtDirectory\n} from './hamt-utils.js'\nimport errCode from 'err-code'\n\nconst log = logger('ipfs:mfs:core:utils:remove-link')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('hamt-sharding').Bucket} Bucket\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n *\n * @typedef {object} RemoveLinkOptions\n * @property {string} name\n * @property {number} shardSplitThreshold\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {boolean} flush\n * @property {CID} [parentCid]\n * @property {PBNode} [parent]\n *\n * @typedef {object} RemoveLinkOptionsInternal\n * @property {string} name\n * @property {number} shardSplitThreshold\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {boolean} flush\n * @property {PBNode} parent\n */\n\n/**\n * @param {MfsContext} context\n * @param {RemoveLinkOptions} options\n */\nexport async function removeLink (context, options) {\n let parent = options.parent\n\n if (options.parentCid) {\n const parentCid = CID.asCID(options.parentCid)\n if (parentCid === null) {\n throw errCode(new Error('Invalid CID passed to removeLink'), 'EINVALIDPARENTCID')\n }\n\n log(`Loading parent node ${parentCid}`)\n const block = await context.repo.blocks.get(parentCid)\n parent = dagPB.decode(block)\n }\n\n if (!parent) {\n throw errCode(new Error('No parent node or CID passed to removeLink'), 'EINVALIDPARENT')\n }\n\n if (!options.name) {\n throw errCode(new Error('No child name passed to removeLink'), 'EINVALIDCHILDNAME')\n }\n\n if (!parent.Data) {\n throw errCode(new Error('Parent node had no data'), 'ERR_INVALID_NODE')\n }\n\n const meta = UnixFS.unmarshal(parent.Data)\n\n if (meta.type === 'hamt-sharded-directory') {\n log(`Removing ${options.name} from sharded directory`)\n\n return removeFromShardedDirectory(context, {\n ...options,\n parent\n })\n }\n\n log(`Removing link ${options.name} regular directory`)\n\n return removeFromDirectory(context, {\n ...options,\n parent\n })\n}\n\n/**\n * @param {MfsContext} context\n * @param {RemoveLinkOptionsInternal} options\n */\nconst removeFromDirectory = async (context, options) => {\n // Remove existing link if it exists\n options.parent.Links = options.parent.Links.filter((link) => {\n return link.Name !== options.name\n })\n\n const parentBlock = await dagPB.encode(options.parent)\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const hash = await hasher.digest(parentBlock)\n const parentCid = CID.create(options.cidVersion, dagPB.code, hash)\n\n await context.repo.blocks.put(parentCid, parentBlock)\n\n log(`Updated regular directory ${parentCid}`)\n\n return {\n node: options.parent,\n cid: parentCid\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {RemoveLinkOptionsInternal} options\n */\nconst removeFromShardedDirectory = async (context, options) => {\n const {\n rootBucket, path\n } = await generatePath(context, options.name, options.parent)\n\n await rootBucket.del(options.name)\n\n const {\n node\n } = await updateShard(context, path, options.name, options)\n\n return updateHamtDirectory(context, node.Links, rootBucket, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {{ bucket: Bucket, prefix: string, node?: PBNode }[]} positions\n * @param {string} name\n * @param {RemoveLinkOptionsInternal} options\n * @returns {Promise<{ node: PBNode, cid: CID, size: number }>}\n */\nconst updateShard = async (context, positions, name, options) => {\n const last = positions.pop()\n\n if (!last) {\n throw errCode(new Error('Could not find parent'), 'EINVALIDPARENT')\n }\n\n const {\n bucket,\n prefix,\n node\n } = last\n\n if (!node) {\n throw errCode(new Error('Could not find parent'), 'EINVALIDPARENT')\n }\n\n const link = node.Links\n .find(link => (link.Name || '').substring(0, 2) === prefix)\n\n if (!link) {\n throw errCode(new Error(`No link found with prefix ${prefix} for file ${name}`), 'ERR_NOT_FOUND')\n }\n\n if (link.Name === `${prefix}${name}`) {\n log(`Removing existing link ${link.Name}`)\n\n const links = node.Links.filter((nodeLink) => {\n return nodeLink.Name !== link.Name\n })\n\n await bucket.del(name)\n\n return updateHamtDirectory(context, links, bucket, options)\n }\n\n log(`Descending into sub-shard ${link.Name} for ${prefix}${name}`)\n\n const result = await updateShard(context, positions, name, options)\n\n let cid = result.cid\n let size = result.size\n let newName = prefix\n\n if (result.node.Links.length === 1) {\n log(`Removing subshard for ${prefix}`)\n\n // convert shard back to normal dir\n const link = result.node.Links[0]\n\n newName = `${prefix}${(link.Name || '').substring(2)}`\n cid = link.Hash\n size = link.Tsize || 0\n }\n\n log(`Updating shard ${prefix} with name ${newName}`)\n\n return updateShardParent(context, bucket, node, prefix, newName, size, cid, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {Bucket} bucket\n * @param {PBNode} parent\n * @param {string} oldName\n * @param {string} newName\n * @param {number} size\n * @param {CID} cid\n * @param {RemoveLinkOptionsInternal} options\n */\nconst updateShardParent = (context, bucket, parent, oldName, newName, size, cid, options) => {\n // Remove existing link if it exists\n const parentLinks = parent.Links.filter((link) => {\n return link.Name !== oldName\n })\n parentLinks.push({\n Name: newName,\n Tsize: size,\n Hash: cid\n })\n\n return updateHamtDirectory(context, parentLinks, bucket, options)\n}\n", "import { createStat } from './stat.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport mergeOpts from 'merge-options'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {}\n\n/**\n * @param {MfsContext} context\n */\nexport function createFlush (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"flush\"]}\n */\n async function mfsFlush (path, options = {}) {\n /** @type {DefaultOptions} */\n options = mergeOptions(defaultOptions, options)\n\n const { cid } = await createStat(context)(path, options)\n\n return cid\n }\n\n return withTimeoutOption(mfsFlush)\n}\n", "import { createCp } from './cp.js'\nimport { createRm } from './rm.js'\nimport mergeOpts from 'merge-options'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} parents\n * @property {boolean} flush\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {number} shardSplitThreshold\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n parents: false,\n flush: true,\n cidVersion: 0,\n hashAlg: 'sha2-256',\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createMv (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"mv\"]}\n */\n async function mfsMv (from, to, options = {}) {\n /** @type {DefaultOptions} */\n const opts = mergeOptions(defaultOptions, options)\n\n await createCp(context)(from, to, opts)\n await createRm(context)(from, {\n ...opts,\n recursive: true\n })\n }\n\n return withTimeoutOption(mfsMv)\n}\n", "import mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { toTrail } from './utils/to-trail.js'\nimport { addLink } from './utils/add-link.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:touch')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} flush\n * @property {number} shardSplitThreshold\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {MtimeLike} [mtime]\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n flush: true,\n shardSplitThreshold: 1000,\n cidVersion: 0,\n hashAlg: 'sha2-256'\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createTouch (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"touch\"]}\n */\n async function mfsTouch (path, options = {}) {\n /** @type {DefaultOptions} */\n const settings = mergeOptions(defaultOptions, options)\n settings.mtime = settings.mtime || new Date()\n\n log(`Touching ${path} mtime: ${settings.mtime}`)\n\n const {\n cid,\n mfsDirectory,\n name,\n exists\n } = await toMfsPath(context, path, settings)\n\n const hashAlg = options.hashAlg || defaultOptions.hashAlg\n const hasher = await context.hashers.getHasher(hashAlg)\n\n let updatedBlock\n let updatedCid\n\n let cidVersion = settings.cidVersion\n\n if (!exists) {\n const metadata = new UnixFS({\n type: 'file',\n mtime: settings.mtime\n })\n updatedBlock = dagPB.encode({ Data: metadata.marshal(), Links: [] })\n\n const hash = await hasher.digest(updatedBlock)\n\n updatedCid = CID.create(settings.cidVersion, dagPB.code, hash)\n\n if (settings.flush) {\n await context.repo.blocks.put(updatedCid, updatedBlock)\n }\n } else {\n if (cid.code !== dagPB.code) {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n cidVersion = cid.version\n\n const block = await context.repo.blocks.get(cid)\n const node = dagPB.decode(block)\n\n if (!node.Data) {\n throw errCode(new Error(`${path} had no data`), 'ERR_INVALID_NODE')\n }\n\n const metadata = UnixFS.unmarshal(node.Data)\n\n // @ts-expect-error TODO: restore setting all date types as mtime - it's in the code, just not the signature\n metadata.mtime = settings.mtime\n\n updatedBlock = dagPB.encode({\n Data: metadata.marshal(),\n Links: node.Links\n })\n\n const hash = await hasher.digest(updatedBlock)\n updatedCid = CID.create(settings.cidVersion, dagPB.code, hash)\n\n if (settings.flush) {\n await context.repo.blocks.put(updatedCid, updatedBlock)\n }\n }\n\n const trail = await toTrail(context, mfsDirectory)\n const parent = trail[trail.length - 1]\n const parentCid = parent.cid\n const parentBlock = await context.repo.blocks.get(parentCid)\n const parentNode = dagPB.decode(parentBlock)\n\n const result = await addLink(context, {\n parent: parentNode,\n name: name,\n cid: updatedCid,\n size: updatedBlock.length,\n flush: settings.flush,\n shardSplitThreshold: settings.shardSplitThreshold,\n hashAlg: settings.hashAlg,\n cidVersion\n })\n\n parent.cid = result.cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, settings)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, settings)\n }\n\n return withTimeoutOption(mfsTouch)\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {number} offset\n * @property {number} length\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n offset: 0,\n length: Infinity\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createRead (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"read\"]}\n */\n function mfsRead (path, options = {}) {\n /** @type {DefaultOptions} */\n options = mergeOptions(defaultOptions, options)\n\n return {\n [Symbol.asyncIterator]: async function * read () {\n const mfsPath = await toMfsPath(context, path, options)\n const result = await exporter(mfsPath.mfsPath, context.repo.blocks)\n\n if (result.type !== 'file' && result.type !== 'raw') {\n throw errCode(new Error(`${path} was not a file or raw bytes`), 'ERR_NOT_FILE')\n }\n\n if (!result.content) {\n throw errCode(new Error(`Could not load content stream from ${path}`), 'ERR_NO_CONTENT')\n }\n\n for await (const buf of result.content({\n offset: options.offset,\n length: options.length\n })) {\n yield buf\n }\n }\n }\n }\n\n return withTimeoutOption(mfsRead)\n}\n", "import errCode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport browserStreamToIt from 'browser-readablestream-to-it'\n\nconst log = logger('ipfs:mfs:utils:to-async-iterator')\n\n/**\n * @param {*} content\n */\nexport function toAsyncIterator (content) {\n if (!content) {\n throw errCode(new Error('paths must start with a leading slash'), 'ERR_INVALID_PATH')\n }\n\n if (typeof content === 'string' || content instanceof String) {\n log('Content was a string')\n\n content = uint8ArrayFromString(content.toString())\n }\n\n if (content.length) {\n log('Content was array-like')\n\n return {\n [Symbol.asyncIterator]: function * bufferContent () {\n yield content\n }\n }\n }\n\n if (content[Symbol.asyncIterator]) {\n log('Content was an async iterator')\n return content\n }\n\n if (content[Symbol.iterator]) {\n log('Content was an iterator')\n return content\n }\n\n if (global.Blob && content instanceof global.Blob) {\n // HTML5 Blob objects (including Files)\n log('Content was an HTML5 Blob')\n return browserStreamToIt(content.stream())\n }\n\n throw errCode(new Error(`Don't know how to convert ${content} into an async iterator`), 'ERR_INVALID_PARAMS')\n}\n", "import { logger } from '@libp2p/logger'\nimport { importer } from 'ipfs-unixfs-importer'\nimport {\n decode\n} from '@ipld/dag-pb'\nimport { createStat } from './stat.js'\nimport { createMkdir } from './mkdir.js'\nimport { addLink } from './utils/add-link.js'\nimport mergeOpts from 'merge-options'\nimport { createLock } from './utils/create-lock.js'\nimport { toAsyncIterator } from './utils/to-async-iterator.js'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { toPathComponents } from './utils/to-path-components.js'\nimport { toTrail } from './utils/to-trail.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport errCode from 'err-code'\nimport {\n MFS_MAX_CHUNK_SIZE\n} from '../../utils.js'\nimport last from 'it-last'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport {\n parseMode,\n parseMtime\n} from 'ipfs-unixfs'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:write')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {import('./utils/to-mfs-path').FilePath} FilePath\n * @typedef {import('./utils/to-mfs-path').MfsPath} MfsPath\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n *\n * @typedef {object} DefaultOptions\n * @property {number} offset\n * @property {number} length\n * @property {boolean} create\n * @property {boolean} truncate\n * @property {boolean} rawLeaves\n * @property {boolean} reduceSingleLeafToSelf\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {boolean} parents\n * @property {import('ipfs-core-types/src/root').AddProgressFn} progress\n * @property {'trickle' | 'balanced'} strategy\n * @property {boolean} flush\n * @property {'raw' | 'file'} leafType\n * @property {number} shardSplitThreshold\n * @property {MtimeLike} [mtime]\n * @property {number} [mode]\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n offset: 0, // the offset in the file to begin writing\n length: Infinity, // how many bytes from the incoming buffer to write\n create: false, // whether to create the file if it does not exist\n truncate: false, // whether to truncate the file first\n rawLeaves: false,\n reduceSingleLeafToSelf: false,\n cidVersion: 0,\n hashAlg: 'sha2-256',\n parents: false, // whether to create intermediate directories if they do not exist\n progress: (bytes, path) => {},\n strategy: 'trickle',\n flush: true,\n leafType: 'raw',\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createWrite (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"write\"]}\n */\n async function mfsWrite (path, content, opts = {}) {\n /** @type {DefaultOptions} */\n const options = mergeOptions(defaultOptions, opts)\n\n /** @type {AsyncIterable} */\n let source\n /** @type {MfsPath} */\n let destination\n /** @type {MfsPath} */\n let parent\n log('Reading source, destination and parent')\n await createLock().readLock(async () => {\n source = await toAsyncIterator(content)\n destination = await toMfsPath(context, path, options)\n parent = await toMfsPath(context, destination.mfsDirectory, options)\n })()\n log('Read source, destination and parent')\n // @ts-expect-error - parent may be undefined\n if (!options.parents && !parent.exists) {\n throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST')\n }\n\n // @ts-expect-error\n if (source == null) {\n throw errCode(new Error('could not create source'), 'ERR_NO_SOURCE')\n }\n\n // @ts-expect-error\n if (destination == null) {\n throw errCode(new Error('could not create destination'), 'ERR_NO_DESTINATION')\n }\n\n if (!options.create && !destination.exists) {\n throw errCode(new Error('file does not exist'), 'ERR_NO_EXIST')\n }\n\n if (destination.entryType !== 'file') {\n throw errCode(new Error('not a file'), 'ERR_NOT_A_FILE')\n }\n\n return updateOrImport(context, path, source, destination, options)\n }\n\n return withTimeoutOption(mfsWrite)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} path\n * @param {AsyncIterable} source\n * @param {FilePath} destination\n * @param {DefaultOptions} options\n */\nconst updateOrImport = async (context, path, source, destination, options) => {\n const child = await write(context, source, destination, options)\n\n // The slow bit is done, now add or replace the DAGLink in the containing directory\n // re-reading the path to the containing folder in case it has changed in the interim\n await createLock().writeLock(async () => {\n const pathComponents = toPathComponents(path)\n const fileName = pathComponents.pop()\n\n if (fileName == null) {\n throw errCode(new Error('source does not exist'), 'ERR_NO_EXIST')\n }\n\n let parentExists = false\n\n try {\n await createStat(context)(`/${pathComponents.join('/')}`, options)\n parentExists = true\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n if (!parentExists) {\n await createMkdir(context)(`/${pathComponents.join('/')}`, options)\n }\n\n // get an updated mfs path in case the root changed while we were writing\n const updatedPath = await toMfsPath(context, path, options)\n const trail = await toTrail(context, updatedPath.mfsDirectory)\n const parent = trail[trail.length - 1]\n\n if (!parent) {\n throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST')\n }\n\n if (!parent.type || !parent.type.includes('directory')) {\n throw errCode(new Error(`cannot write to ${parent.name}: Not a directory`), 'ERR_NOT_A_DIRECTORY')\n }\n\n const parentBlock = await context.repo.blocks.get(parent.cid)\n const parentNode = decode(parentBlock)\n\n const result = await addLink(context, {\n parent: parentNode,\n name: fileName,\n cid: child.cid,\n size: child.size,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion\n })\n\n parent.cid = result.cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n })()\n}\n\n/**\n * @param {MfsContext} context\n * @param {AsyncIterable} source\n * @param {FilePath} destination\n * @param {DefaultOptions} options\n */\nconst write = async (context, source, destination, options) => {\n if (destination.exists) {\n log(`Overwriting file ${destination.cid} offset ${options.offset} length ${options.length}`)\n } else {\n log(`Writing file offset ${options.offset} length ${options.length}`)\n }\n\n /** @type {Array<() => AsyncIterable>} */\n const sources = []\n\n // pad start of file if necessary\n if (options.offset > 0) {\n if (destination.unixfs) {\n log(`Writing first ${options.offset} bytes of original file`)\n\n sources.push(\n () => {\n return destination.content({\n offset: 0,\n length: options.offset\n })\n }\n )\n\n if (destination.unixfs.fileSize() < options.offset) {\n const extra = options.offset - destination.unixfs.fileSize()\n\n log(`Writing zeros for extra ${extra} bytes`)\n sources.push(\n asyncZeroes(extra)\n )\n }\n } else {\n log(`Writing zeros for first ${options.offset} bytes`)\n sources.push(\n asyncZeroes(options.offset)\n )\n }\n }\n\n sources.push(\n limitAsyncStreamBytes(source, options.length)\n )\n\n const content = countBytesStreamed(catAsyncIterators(sources), (bytesWritten) => {\n if (destination.unixfs && !options.truncate) {\n // if we've done reading from the new source and we are not going\n // to truncate the file, add the end of the existing file to the output\n const fileSize = destination.unixfs.fileSize()\n\n if (fileSize > bytesWritten) {\n log(`Writing last ${fileSize - bytesWritten} of ${fileSize} bytes from original file starting at offset ${bytesWritten}`)\n\n return destination.content({\n offset: bytesWritten\n })\n } else {\n log('Not writing last bytes from original file')\n }\n }\n\n return {\n [Symbol.asyncIterator]: async function * () {}\n }\n })\n\n /** @type {number | undefined} */\n let mode\n\n if (options.mode !== undefined && options.mode !== null) {\n mode = parseMode(options.mode)\n } else if (destination && destination.unixfs) {\n mode = destination.unixfs.mode\n }\n\n /** @type {import('ipfs-unixfs').Mtime | undefined} */\n let mtime\n\n if (options.mtime != null) {\n mtime = parseMtime(options.mtime)\n } else if (destination && destination.unixfs) {\n mtime = destination.unixfs.mtime\n }\n\n const hasher = await context.hashers.getHasher(options.hashAlg)\n\n const result = await last(importer([{\n content: content,\n\n // persist mode & mtime if set previously\n mode,\n mtime\n }], context.repo.blocks, {\n progress: options.progress,\n hasher,\n cidVersion: options.cidVersion,\n strategy: options.strategy,\n rawLeaves: options.rawLeaves,\n reduceSingleLeafToSelf: options.reduceSingleLeafToSelf,\n leafType: options.leafType\n }))\n\n if (!result) {\n throw errCode(new Error(`cannot write to ${parent.name}`), 'ERR_COULD_NOT_WRITE')\n }\n\n log(`Wrote ${result.cid}`)\n\n return {\n cid: result.cid,\n size: result.size\n }\n}\n\n/**\n * @param {AsyncIterable} stream\n * @param {number} limit\n */\nconst limitAsyncStreamBytes = (stream, limit) => {\n return async function * _limitAsyncStreamBytes () {\n let emitted = 0\n\n for await (const buf of stream) {\n emitted += buf.length\n\n if (emitted > limit) {\n yield buf.subarray(0, limit - emitted)\n\n return\n }\n\n yield buf\n }\n }\n}\n\n/**\n * @param {number} count\n * @param {number} chunkSize\n */\nconst asyncZeroes = (count, chunkSize = MFS_MAX_CHUNK_SIZE) => {\n const buf = new Uint8Array(chunkSize)\n\n async function * _asyncZeroes () {\n while (true) {\n yield buf\n }\n }\n\n return limitAsyncStreamBytes(_asyncZeroes(), count)\n}\n\n/**\n * @param {Array<() => AsyncIterable>} sources\n */\nconst catAsyncIterators = async function * (sources) { // eslint-disable-line require-await\n for (let i = 0; i < sources.length; i++) {\n yield * sources[i]()\n }\n}\n\n/**\n * @param {AsyncIterable} source\n * @param {(count: number) => AsyncIterable} notify\n */\nconst countBytesStreamed = async function * (source, notify) {\n let wrote = 0\n\n for await (const buf of source) {\n wrote += buf.length\n\n yield buf\n }\n\n for await (const buf of notify(wrote)) {\n wrote += buf.length\n\n yield buf\n }\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport map from 'it-map'\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {import('ipfs-core-types/src/files').MFSEntry} MFSEntry\n */\n\n/**\n * @param {import('ipfs-unixfs-exporter').UnixFSEntry} fsEntry\n */\nconst toOutput = (fsEntry) => {\n /** @type {MFSEntry} */\n const output = {\n cid: fsEntry.cid,\n name: fsEntry.name,\n type: fsEntry.type === 'directory' ? 'directory' : 'file',\n size: fsEntry.size\n }\n\n if (fsEntry.type === 'file' || fsEntry.type === 'directory') {\n output.mode = fsEntry.unixfs.mode\n output.mtime = fsEntry.unixfs.mtime\n }\n\n return output\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createLs (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"ls\"]}\n */\n async function * mfsLs (path, options = {}) {\n const mfsPath = await toMfsPath(context, path, options)\n const fsEntry = await exporter(mfsPath.mfsPath, context.repo.blocks)\n\n // directory, perhaps sharded\n if (fsEntry.type === 'directory') {\n yield * map(fsEntry.content(options), toOutput)\n\n return\n }\n\n // single file/node\n yield toOutput(fsEntry)\n }\n\n return withTimeoutOption(mfsLs)\n}\n", "import { createLock } from './utils/create-lock.js'\nimport * as isIpfs from 'is-ipfs'\nimport { createStat } from './stat.js'\nimport { createChmod } from './chmod.js'\nimport { createCp } from './cp.js'\nimport { createFlush } from './flush.js'\nimport { createMkdir } from './mkdir.js'\nimport { createMv } from './mv.js'\nimport { createRm } from './rm.js'\nimport { createTouch } from './touch.js'\nimport { createRead } from './read.js'\nimport { createWrite } from './write.js'\nimport { createLs } from './ls.js'\n\n/**\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n *\n * @typedef {object} MfsContext\n * @property {IPFSRepo} repo\n * @property {Multihashes} hashers\n */\n\n/**\n * These operations are read-locked at the function level and will execute simultaneously\n *\n * @type {Record}\n */\nconst readOperations = {\n stat: createStat\n}\n\n/**\n * These operations are locked at the function level and will execute in series\n *\n * @type {Record}\n */\nconst writeOperations = {\n chmod: createChmod,\n cp: createCp,\n flush: createFlush,\n mkdir: createMkdir,\n mv: createMv,\n rm: createRm,\n touch: createTouch\n}\n\n/**\n * These operations are asynchronous and manage their own locking\n *\n * @type {Record}\n */\nconst unwrappedOperations = {\n write: createWrite,\n read: createRead,\n ls: createLs\n}\n\n/**\n * @param {object} arg\n * @param {MfsContext} arg.options\n * @param {*} arg.mfs\n * @param {*} arg.operations\n * @param {*} arg.lock\n */\nconst wrap = ({\n options, mfs, operations, lock\n}) => {\n Object.keys(operations).forEach(key => {\n mfs[key] = lock(operations[key](options))\n })\n}\n\nconst defaultOptions = {\n repoOwner: true,\n repo: null\n}\n\n/**\n * @param {object} options\n * @param {IPFSRepo} options.repo\n * @param {boolean} options.repoOwner\n * @param {Multihashes} options.hashers\n */\nfunction createMfs (options) {\n const {\n repoOwner\n } = Object.assign({}, defaultOptions || {}, options)\n\n const lock = createLock(repoOwner)\n\n /**\n * @param {(fn: (...args: any) => any) => (...args: any) => any} operation\n */\n const readLock = (operation) => {\n return lock.readLock(operation)\n }\n\n /**\n * @param {(fn: (...args: any) => any) => (...args: any) => any} operation\n */\n const writeLock = (operation) => {\n return lock.writeLock(operation)\n }\n\n /** @type {Record} */\n const mfs = {}\n\n wrap({\n options, mfs, operations: readOperations, lock: readLock\n })\n wrap({\n options, mfs, operations: writeOperations, lock: writeLock\n })\n\n Object.keys(unwrappedOperations).forEach(key => {\n mfs[key] = unwrappedOperations[key](options)\n })\n\n return mfs\n}\n\n/**\n * @param {object} context\n * @param {IPFSRepo} context.repo\n * @param {import('../../types').Preload} context.preload\n * @param {import('..').Options} context.options\n * @param {Multihashes} context.hashers\n * @returns {import('ipfs-core-types/src/files').API}\n */\nexport function createFiles ({ repo, preload, hashers, options: constructorOptions }) {\n const methods = createMfs({\n repo,\n repoOwner: constructorOptions.repoOwner !== false,\n hashers\n })\n\n /**\n * @param {any} fn\n */\n const withPreload = fn => {\n /**\n * @param {...any} args\n */\n const wrapped = (...args) => {\n const paths = args.filter(arg => isIpfs.ipfsPath(arg) || isIpfs.cid(arg))\n\n if (paths.length) {\n const options = args[args.length - 1]\n if (options && options.preload !== false) {\n paths.forEach(path => preload(path))\n }\n }\n\n return fn(...args)\n }\n\n return wrapped\n }\n\n return {\n ...methods,\n chmod: methods.chmod,\n cp: withPreload(methods.cp),\n mkdir: methods.mkdir,\n stat: withPreload(methods.stat),\n rm: methods.rm,\n read: withPreload(methods.read),\n touch: methods.touch,\n write: methods.write,\n mv: withPreload(methods.mv),\n flush: methods.flush,\n ls: withPreload(async function * (/** @type {...any} */ ...args) {\n for await (const file of methods.ls(...args)) {\n yield { ...file, size: file.size || 0 }\n }\n })\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createExport ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"export\"]}\n */\n const exportKey = (name, password) =>\n keychain.exportKey(name, password)\n\n return withTimeoutOption(exportKey)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst DEFAULT_KEY_TYPE = 'Ed25519'\nconst DEFAULT_KEY_SIZE = 2048\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createGen ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"gen\"]}\n */\n const gen = (name, options = { type: DEFAULT_KEY_TYPE, size: DEFAULT_KEY_SIZE }) => {\n return keychain.createKey(name, options.type || DEFAULT_KEY_TYPE, options.size || DEFAULT_KEY_SIZE)\n }\n\n return withTimeoutOption(gen)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createImport ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"import\"]}\n */\n const importKey = (name, pem, password) => {\n return keychain.importKey(name, pem, password)\n }\n\n return withTimeoutOption(importKey)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createInfo ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"info\"]}\n */\n const info = (name) => keychain.findKeyByName(name)\n\n return withTimeoutOption(info)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createList ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"list\"]}\n */\n const list = () => keychain.listKeys()\n\n return withTimeoutOption(list)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createRename ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"rename\"]}\n */\n const rename = async (oldName, newName) => {\n const key = await keychain.renameKey(oldName, newName)\n\n return {\n was: oldName,\n now: key.name,\n id: key.id,\n overwrite: false\n }\n }\n\n return withTimeoutOption(rename)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createRm ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"rm\"]}\n */\n const rm = (name) => keychain.removeKey(name)\n\n return withTimeoutOption(rm)\n}\n", "import { createExport } from './export.js'\nimport { createGen } from './gen.js'\nimport { createImport } from './import.js'\nimport { createInfo } from './info.js'\nimport { createList } from './list.js'\nimport { createRename } from './rename.js'\nimport { createRm } from './rm.js'\n\n/**\n * @typedef {import('@libp2p/interface-keychain').KeyChain} Keychain\n */\n\nexport class KeyAPI {\n /**\n * @param {object} config\n * @param {Keychain} config.keychain\n */\n constructor ({ keychain }) {\n this.gen = createGen({ keychain })\n this.list = createList({ keychain })\n this.rm = createRm({ keychain })\n this.rename = createRename({ keychain })\n this.export = createExport({ keychain })\n this.import = createImport({ keychain })\n this.info = createInfo({ keychain })\n }\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createGet ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"get\"]}\n */\n async function get (cid, options = {}) { // eslint-disable-line require-await\n if (options.preload !== false) {\n preload(cid)\n }\n\n const block = await repo.blocks.get(cid, options)\n\n return dagPB.decode(block)\n }\n\n return withTimeoutOption(get)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from './get.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createData ({ repo, preload }) {\n const get = createGet({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"data\"]}\n */\n async function data (multihash, options = {}) {\n const node = await get(multihash, options)\n return node.Data || new Uint8Array(0)\n }\n\n return withTimeoutOption(data)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport * as dagCBOR from '@ipld/dag-cbor'\nimport * as dagJSON from '@ipld/dag-json'\nimport * as raw from 'multiformats/codecs/raw'\nimport { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('@ipld/dag-pb').PBLink} DAGLink\n */\n\n/**\n * @param {any} node\n * @param {DAGLink[]} [links]\n * @returns {DAGLink[]}\n */\nfunction findLinks (node, links = []) {\n for (const key in node) {\n const val = node[key]\n\n if (key === '/' && Object.keys(node).length === 1) {\n try {\n links.push({\n Name: '',\n Tsize: 0,\n Hash: CID.parse(val)\n })\n continue\n } catch (/** @type {any} */ _) {\n // not a CID\n }\n }\n\n const cid = CID.asCID(val)\n\n if (cid) {\n links.push({\n Name: '',\n Tsize: 0,\n Hash: cid\n })\n continue\n }\n\n if (Array.isArray(val)) {\n findLinks(val, links)\n }\n\n if (val && typeof val === 'object') {\n findLinks(val, links)\n }\n }\n\n return links\n}\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createLinks ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"links\"]}\n */\n async function links (cid, options = {}) {\n const codec = await codecs.getCodec(cid.code)\n const block = await repo.blocks.get(cid, options)\n const node = codec.decode(block)\n\n switch (cid.code) {\n case raw.code:\n return []\n case dagPB.code:\n return node.Links\n case dagCBOR.code:\n case dagJSON.code:\n return findLinks(node)\n default:\n throw new Error(`Cannot resolve links from codec ${cid.code}`)\n }\n }\n\n return withTimeoutOption(links)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createNew ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"new\"]}\n */\n async function _new (options = {}) {\n let data\n\n if (options.template) {\n if (options.template === 'unixfs-dir') {\n data = (new UnixFS({ type: 'directory' })).marshal()\n } else {\n throw new Error('unknown template')\n }\n }\n\n const buf = dagPB.encode({\n Data: data,\n Links: []\n })\n const hash = await sha256.digest(buf)\n const cid = CID.createV0(hash)\n\n await repo.blocks.put(cid, buf, {\n signal: options.signal\n })\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return cid\n }\n\n return withTimeoutOption(_new)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createPut ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"put\"]}\n */\n async function put (obj, options = {}) {\n const release = await repo.gcLock.readLock()\n\n try {\n const buf = dagPB.encode(obj)\n const hash = await sha256.digest(buf)\n const cid = CID.createV1(dagPB.code, hash)\n\n await repo.blocks.put(cid, buf, {\n signal: options.signal\n })\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n if (options.pin) {\n await repo.pins.pinRecursively(cid, {\n signal: options.signal\n })\n }\n\n return cid\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(put)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from './get.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createStat ({ repo, preload }) {\n const get = createGet({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n const node = await get(cid, options)\n const serialized = dagPB.encode(node)\n const blockSize = serialized.length\n const linkLength = node.Links.reduce((a, l) => a + (l.Tsize || 0), 0)\n\n return {\n Hash: cid,\n NumLinks: node.Links.length,\n BlockSize: blockSize,\n LinksSize: blockSize - (node.Data || []).length,\n DataSize: (node.Data || []).length,\n CumulativeSize: blockSize + linkLength\n }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createAddLink ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"addLink\"]}\n */\n async function addLink (cid, link, options = {}) {\n const node = await get(cid, options)\n\n return put({\n ...node,\n Links: node.Links.concat([link])\n }, options)\n }\n\n return withTimeoutOption(addLink)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createAppendData ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"appendData\"]}\n */\n async function appendData (cid, data, options = {}) {\n const node = await get(cid, options)\n const newData = uint8ArrayConcat([node.Data || [], data])\n\n return put({\n ...node,\n Data: newData\n }, options)\n }\n\n return withTimeoutOption(appendData)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createRmLink ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"rmLink\"]}\n */\n async function rmLink (cid, link, options = {}) {\n const node = await get(cid, options)\n const name = (typeof link === 'string' ? link : link.Name) || ''\n\n node.Links = node.Links.filter(l => l.Name !== name)\n\n return put(node, options)\n }\n\n return withTimeoutOption(rmLink)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createSetData ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"setData\"]}\n */\n async function setData (cid, data, options = {}) {\n const node = await get(cid, options)\n\n return put({\n ...node,\n Data: data\n }, options)\n }\n\n return withTimeoutOption(setData)\n}\n", "import { createAddLink } from './add-link.js'\nimport { createAppendData } from './append-data.js'\nimport { createRmLink } from './rm-link.js'\nimport { createSetData } from './set-data.js'\n\n/**\n * @typedef {import('../../../types').Preload} Preload\n */\n\nexport class ObjectPatchAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {Preload} config.preload\n */\n constructor ({ repo, preload }) {\n this.addLink = createAddLink({ repo, preload })\n this.appendData = createAppendData({ repo, preload })\n this.rmLink = createRmLink({ repo, preload })\n this.setData = createSetData({ repo, preload })\n }\n}\n", "import { createData } from './data.js'\nimport { createGet } from './get.js'\nimport { createLinks } from './links.js'\nimport { createNew } from './new.js'\nimport { createPut } from './put.js'\nimport { createStat } from './stat.js'\nimport { ObjectPatchAPI } from './patch/index.js'\n\n/**\n * @typedef {import('../../types').Preload} Preload\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\nexport class ObjectAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {Preload} config.preload\n */\n constructor ({ repo, codecs, preload }) {\n this.data = createData({ repo, preload })\n this.get = createGet({ repo, preload })\n this.links = createLinks({ repo, codecs })\n this.new = createNew({ repo, preload })\n this.put = createPut({ repo, preload })\n this.stat = createStat({ repo, preload })\n this.patch = new ObjectPatchAPI({ repo, preload })\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { loadMfsRoot } from '../files/utils/with-mfs-root.js'\n\nconst log = logger('ipfs:repo:gc')\n\n/**\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n * @typedef {import('ipfs-core-types/src/refs').API} RefsAPI\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n */\n\n/**\n * Perform mark and sweep garbage collection\n *\n * @param {object} config\n * @param {IPFSRepo} config.repo\n * @param {Multihashes} config.hashers\n */\nexport function createGc ({ repo, hashers }) {\n /**\n * @type {import('ipfs-core-types/src/repo').API<{}>[\"gc\"]}\n */\n async function * gc (options = {}) {\n const start = Date.now()\n let mfsRootCid\n\n try {\n mfsRootCid = await loadMfsRoot({\n repo,\n hashers\n }, options)\n\n // temporarily pin mfs root\n await repo.pins.pinRecursively(mfsRootCid)\n\n yield * repo.gc()\n } finally {\n // gc complete, unpin mfs root\n if (mfsRootCid) {\n await repo.pins.unpin(mfsRootCid)\n }\n }\n\n log(`Complete (${Date.now() - start}ms)`)\n }\n\n return withTimeoutOption(gc)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createStat ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/repo').API<{}>[\"stat\"]}\n */\n async function stat (options = {}) {\n const stats = await repo.stat()\n\n return {\n numObjects: BigInt(stats.numObjects.toString()),\n repoSize: BigInt(stats.repoSize.toString()),\n repoPath: stats.repoPath,\n version: `${stats.version}`,\n storageMax: BigInt(stats.storageMax.toString())\n }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { repoVersion } from 'ipfs-repo/constants'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createVersion ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/repo').API<{}>[\"version\"]}\n */\n async function version (options = {}) {\n try {\n // @ts-expect-error - not a public API\n await repo._checkInitialized(options)\n } catch (/** @type {any} */ err) {\n // TODO: (dryajov) This is really hacky, there must be a better way\n const match = [\n /Key not found in database \\[\\/version\\]/,\n /ENOENT/,\n /repo is not initialized yet/\n ].some((m) => {\n return m.test(err.message)\n })\n if (match) {\n // this repo has not been initialized\n return repoVersion\n }\n throw err\n }\n\n return repo.version.get()\n }\n\n return withTimeoutOption(version)\n}\n", "import { createGc } from './gc.js'\nimport { createStat } from './stat.js'\nimport { createVersion } from './version.js'\n\n/**\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n */\n\nexport class RepoAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {Multihashes} config.hashers\n */\n constructor ({ repo, hashers }) {\n this.gc = createGc({ repo, hashers })\n this.stat = createStat({ repo })\n this.version = createVersion({ repo })\n\n /**\n * @param {string} addr\n */\n this.setApiAddr = (addr) => repo.apiAddr.set(addr)\n }\n}\n", "import parseDuration from 'parse-duration'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('ipfs-core-types/src/stats').BWOptions} BWOptions\n * @typedef {import('ipfs-core-types/src/stats').BWResult} BandwidthInfo\n * @typedef {import('libp2p').Libp2p} libp2p\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @param {libp2p} libp2p\n * @param {BWOptions} opts\n * @returns {BandwidthInfo}\n */\nfunction getBandwidthStats (libp2p, opts) {\n/*\n let stats\n\n if (!libp2p.metrics) {\n stats = undefined\n } else if (opts.peer) {\n stats = libp2p.metrics.forPeer(opts.peer)\n } else if (opts.proto) {\n stats = libp2p.metrics.forProtocol(opts.proto)\n } else {\n stats = libp2p.metrics.getGlobal()\n }\n*/\n // if (!stats) {\n return {\n totalIn: BigInt(0),\n totalOut: BigInt(0),\n rateIn: 0.0,\n rateOut: 0.0\n }\n // }\n/*\n const movingAverages = stats.getMovingAverages()\n const snapshot = stats.getSnapshot()\n\n return {\n totalIn: snapshot.dataReceived,\n totalOut: snapshot.dataSent,\n rateIn: movingAverages.dataReceived[60000].movingAverage / 60,\n rateOut: movingAverages.dataSent[60000].movingAverage / 60\n }\n*/\n}\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createBw ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/stats').API<{}>[\"bw\"]}\n */\n const bw = async function * (options = {}) {\n const { libp2p } = await network.use(options)\n\n if (!options.poll) {\n yield getBandwidthStats(libp2p, options)\n return\n }\n\n const interval = options.interval || 1000\n let ms = -1\n try {\n ms = typeof interval === 'string' ? parseDuration(interval) || -1 : interval\n if (!ms || ms < 0) throw new Error('invalid duration')\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_POLL_INTERVAL')\n }\n\n let timeoutId\n try {\n while (true) {\n yield getBandwidthStats(libp2p, options)\n // eslint-disable-next-line no-loop-func\n await new Promise(resolve => { timeoutId = setTimeout(resolve, ms) })\n }\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n return withTimeoutOption(bw)\n}\n", "import { createBw } from './bw.js'\nimport { createStat as createRepo } from '../repo/stat.js'\nimport { createStat as createBitswap } from '../bitswap/stat.js'\n\nexport class StatsAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').NetworkService} config.network\n */\n constructor ({ repo, network }) {\n this.repo = createRepo({ repo })\n this.bw = createBw({ network })\n this.bitswap = createBitswap({ network })\n }\n}\n", "var objectSafeGet = get;\n\n/*\n const obj = {a: {aa: {aaa: 2}}, b: 4};\n\n get(obj, 'a.aa.aaa'); // 2\n get(obj, ['a', 'aa', 'aaa']); // 2\n\n get(obj, 'b.bb.bbb'); // undefined\n get(obj, ['b', 'bb', 'bbb']); // undefined\n\n get(obj.a, 'aa.aaa'); // 2\n get(obj.a, ['aa', 'aaa']); // 2\n\n get(obj.b, 'bb.bbb'); // undefined\n get(obj.b, ['bb', 'bbb']); // undefined\n\n get(obj.b, 'bb.bbb', 42); // 42\n get(obj.b, ['bb', 'bbb'], 42); // 42\n\n get(null, 'a'); // undefined\n get(undefined, ['a']); // undefined\n\n get(null, 'a', 42); // 42\n get(undefined, ['a'], 42); // 42\n\n const obj = {a: {}};\n const sym = Symbol();\n obj.a[sym] = 4;\n get(obj.a, sym); // 4\n*/\n\nfunction get(obj, propsArg, defaultValue) {\n if (!obj) {\n return defaultValue;\n }\n var props, prop;\n if (Array.isArray(propsArg)) {\n props = propsArg.slice(0);\n }\n if (typeof propsArg == 'string') {\n props = propsArg.split('.');\n }\n if (typeof propsArg == 'symbol') {\n props = [propsArg];\n }\n if (!Array.isArray(props)) {\n throw new Error('props arg must be an array, a string or a symbol');\n }\n while (props.length) {\n prop = props.shift();\n if (!obj) {\n return defaultValue;\n }\n obj = obj[prop];\n if (obj === undefined) {\n return defaultValue;\n }\n }\n return obj;\n}\n\nexport {objectSafeGet as default};\n", "import _get from 'just-safe-get'\nimport debug from 'debug'\nimport errCode from 'err-code'\nimport * as migrator from 'ipfs-repo-migrations'\nimport bytes from 'bytes'\nimport merge from 'merge-options'\nimport * as CONSTANTS from './constants.js'\nimport { version } from './version.js'\nimport { config } from './config.js'\nimport { spec } from './spec.js'\nimport { apiAddr } from './api-addr.js'\nimport { createIdStore } from './idstore.js'\nimport defaultOptions from './default-options.js'\nimport defaultDatastore from './default-datastore.js'\nimport * as ERRORS from './errors.js'\nimport { PinManager } from './pin-manager.js'\nimport { createPinnedBlockstore } from './pinned-blockstore.js'\n// @ts-ignore - no types\nimport mortice from 'mortice'\nimport { gc } from './gc.js'\n\nconst log = debug('ipfs:repo')\n\nconst noLimit = Number.MAX_SAFE_INTEGER\nconst AUTO_MIGRATE_CONFIG_KEY = 'repoAutoMigrate'\n\n/**\n * @typedef {import('./types').Options} Options\n * @typedef {import('./types').RepoLock} RepoLock\n * @typedef {import('./types').LockCloser} LockCloser\n * @typedef {import('./types').GCLock} GCLock\n * @typedef {import('./types').Stat} Stat\n * @typedef {import('./types').Config} Config\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').Backends} Backends\n * @typedef {import('./types').IPFSRepo} IPFSRepo\n */\n\n/**\n * IPFSRepo implements all required functionality to read and write to an ipfs repo.\n */\nclass Repo {\n /**\n * @param {string} path - Where this repo is stored\n * @param {import('./types').loadCodec} loadCodec - a function that will load multiformat block codecs\n * @param {Backends} backends - backends used by this repo\n * @param {Partial} [options] - Configuration\n */\n constructor (path, loadCodec, backends, options) {\n if (typeof path !== 'string') {\n throw new Error('missing repo path')\n }\n\n if (typeof loadCodec !== 'function') {\n throw new Error('missing codec loader')\n }\n\n /** @type {Options} */\n this.options = merge(defaultOptions, options)\n this.closed = true\n this.path = path\n this.root = backends.root\n this.datastore = backends.datastore\n this.keys = backends.keys\n\n const blockstore = backends.blocks\n const pinstore = backends.pins\n\n this.pins = new PinManager({ pinstore, blockstore, loadCodec })\n\n // this blockstore will not delete blocks that have been pinned\n const pinnedBlockstore = createPinnedBlockstore(this.pins, blockstore)\n\n // this blockstore will extract blocks from multihashes with the identity codec\n this.blocks = createIdStore(pinnedBlockstore)\n\n this.version = version(this.root)\n this.config = config(this.root)\n this.spec = spec(this.root)\n this.apiAddr = apiAddr(this.root)\n\n /** @type {GCLock} */\n this.gcLock = mortice({\n name: path,\n singleProcess: this.options.repoOwner !== false\n })\n\n this.gc = gc({ gcLock: this.gcLock, pins: this.pins, blockstore: this.blocks, root: this.root, loadCodec })\n }\n\n /**\n * Initialize a new repo.\n *\n * @param {import('./types').Config} config - config to write into `config`.\n * @returns {Promise}\n */\n async init (config) {\n log('initializing at: %s', this.path)\n await this._openRoot()\n await this.config.replace(buildConfig(config))\n await this.spec.set(buildDatastoreSpec(config))\n await this.version.set(CONSTANTS.repoVersion)\n }\n\n /**\n * Check if the repo is already initialized.\n *\n * @returns {Promise}\n */\n async isInitialized () {\n if (!this.closed) {\n // repo is open, must be initialized\n return true\n }\n\n try {\n // have to open the root datastore in the browser before\n // we can check whether it's been initialized\n await this._openRoot()\n await this._checkInitialized()\n await this.root.close()\n\n return true\n } catch (/** @type {any} */ err) {\n // FIXME: do not use exceptions for flow control\n return false\n }\n }\n\n /**\n * Open the repo. If the repo is already open an error will be thrown.\n * If the repo is not initialized it will throw an error.\n *\n * @returns {Promise}\n */\n async open () {\n if (!this.closed) {\n throw errCode(new Error('repo is already open'), ERRORS.ERR_REPO_ALREADY_OPEN)\n }\n log('opening at: %s', this.path)\n\n // check if the repo is already initialized\n try {\n await this._openRoot()\n await this._checkInitialized()\n\n this._lockfile = await this._openLock()\n log('acquired repo.lock')\n\n const isCompatible = await this.version.check(CONSTANTS.repoVersion)\n\n if (!isCompatible) {\n if (await this._isAutoMigrationEnabled()) {\n await this._migrate(CONSTANTS.repoVersion, {\n root: this.root,\n datastore: this.datastore,\n pins: this.pins.pinstore,\n blocks: this.pins.blockstore,\n keys: this.keys\n })\n } else {\n throw new ERRORS.InvalidRepoVersionError('Incompatible repo versions. Automatic migrations disabled. Please migrate the repo manually.')\n }\n }\n\n log('creating datastore')\n await this.datastore.open()\n\n log('creating blocks')\n await this.blocks.open()\n\n log('creating keystore')\n await this.keys.open()\n\n log('creating pins')\n await this.pins.pinstore.open()\n\n this.closed = false\n log('all opened')\n } catch (/** @type {any} */ err) {\n if (this._lockfile) {\n try {\n await this._closeLock()\n this._lockfile = null\n } catch (/** @type {any} */ err2) {\n log('error removing lock', err2)\n }\n }\n\n throw err\n }\n }\n\n /**\n * Opens the root backend, catching and ignoring an 'Already open' error\n *\n * @private\n */\n async _openRoot () {\n try {\n await this.root.open()\n } catch (/** @type {any} */ err) {\n if (err.message !== 'Already open') {\n throw err\n }\n }\n }\n\n /**\n * Creates a lock on the repo if a locker is specified. The lockfile object will\n * be returned in the callback if one has been created.\n *\n * @private\n * @returns {Promise}\n */\n async _openLock () {\n const lockfile = await this.options.repoLock.lock(this.path)\n\n if (typeof lockfile.close !== 'function') {\n throw errCode(new Error('Locks must have a close method'), 'ERR_NO_CLOSE_FUNCTION')\n }\n\n return lockfile\n }\n\n /**\n * Closes the lock on the repo\n *\n * @private\n */\n _closeLock () {\n return this._lockfile && this._lockfile.close()\n }\n\n /**\n * Check if the repo is already initialized.\n *\n * @private\n */\n async _checkInitialized () {\n log('init check')\n let config\n try {\n [config] = await Promise.all([\n this.config.exists(),\n this.spec.exists(),\n this.version.exists()\n ])\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NOT_FOUND') {\n throw errCode(new Error('repo is not initialized yet'), ERRORS.ERR_REPO_NOT_INITIALIZED, {\n path: this.path\n })\n }\n\n throw err\n }\n\n if (!config) {\n throw errCode(new Error('repo is not initialized yet'), ERRORS.ERR_REPO_NOT_INITIALIZED, {\n path: this.path\n })\n }\n }\n\n /**\n * Close the repo and cleanup.\n *\n * @returns {Promise}\n */\n async close () {\n if (this.closed) {\n throw errCode(new Error('repo is already closed'), ERRORS.ERR_REPO_ALREADY_CLOSED)\n }\n log('closing at: %s', this.path)\n\n try {\n // Delete api, ignoring irrelevant errors\n await this.apiAddr.delete()\n } catch (/** @type {any} */ err) {\n if (err.code !== ERRORS.ERR_REPO_NOT_INITIALIZED && !err.message.startsWith('ENOENT')) {\n throw err\n }\n }\n\n await Promise.all([\n this.root,\n this.blocks,\n this.keys,\n this.datastore,\n this.pins.pinstore\n ].map((store) => store && store.close()))\n\n log('unlocking')\n this.closed = true\n await this._closeLock()\n }\n\n /**\n * Check if a repo exists.\n *\n * @returns {Promise}\n */\n exists () {\n return this.version.exists()\n }\n\n /**\n * Get repo status.\n *\n * @returns {Promise}\n */\n async stat () {\n if (this.datastore && this.keys) {\n const [storageMax, blocks, version, datastore, keys] = await Promise.all([\n this._storageMaxStat(),\n this._blockStat(),\n this.version.get(),\n getSize(this.datastore),\n getSize(this.keys)\n ])\n const size = blocks.size + datastore + keys\n\n return {\n repoPath: this.path,\n storageMax,\n version: version,\n numObjects: blocks.count,\n repoSize: size\n }\n }\n throw errCode(new Error('repo is not initialized yet'), ERRORS.ERR_REPO_NOT_INITIALIZED, {\n path: this.path\n })\n }\n\n /**\n * @private\n */\n async _isAutoMigrationEnabled () {\n if (this.options.autoMigrate !== undefined) {\n return this.options.autoMigrate\n }\n\n // TODO we need to figure out the priority here, between repo options and config.\n let autoMigrateConfig\n try {\n autoMigrateConfig = await this.config.get(AUTO_MIGRATE_CONFIG_KEY)\n } catch (/** @type {any} */ e) {\n if (e.code === ERRORS.NotFoundError.code) {\n autoMigrateConfig = true // Config's default value is True\n } else {\n throw e\n }\n }\n\n return autoMigrateConfig\n }\n\n /**\n * Internal migration\n *\n * @private\n * @param {number} toVersion\n * @param {Backends} backends\n */\n async _migrate (toVersion, backends) {\n const currentRepoVersion = await this.version.get()\n\n if (currentRepoVersion > toVersion) {\n log(`reverting to version ${toVersion}`)\n return migrator.revert(this.path, backends, this.options, toVersion, {\n ignoreLock: true,\n onProgress: this.options.onMigrationProgress\n })\n } else {\n log(`migrating to version ${toVersion}`)\n return migrator.migrate(this.path, backends, this.options, toVersion, {\n ignoreLock: true,\n onProgress: this.options.onMigrationProgress\n })\n }\n }\n\n /**\n * @private\n */\n async _storageMaxStat () {\n try {\n const max = /** @type {number} */(await this.config.get('Datastore.StorageMax'))\n return BigInt(bytes(max))\n } catch (/** @type {any} */ err) {\n return BigInt(noLimit)\n }\n }\n\n /**\n * @private\n */\n async _blockStat () {\n let count = BigInt(0)\n let size = BigInt(0)\n\n if (this.blocks) {\n for await (const { key, value } of this.blocks.query({})) {\n count += BigInt(1)\n size += BigInt(value.byteLength)\n size += BigInt(key.bytes.byteLength)\n }\n }\n\n return { count, size }\n }\n}\n\n/**\n * @param {Datastore} datastore\n */\nasync function getSize (datastore) {\n let sum = BigInt(0)\n for await (const block of datastore.query({})) {\n sum += BigInt(block.value.byteLength)\n sum += BigInt(block.key.uint8Array().byteLength)\n }\n return sum\n}\n\n/**\n * @param {string} path - Where this repo is stored\n * @param {import('./types').loadCodec} loadCodec - a function that will load multiformat block codecs\n * @param {import('./types').Backends} backends - backends used by this repo\n * @param {Partial} [options] - Configuration\n * @returns {import('./types').IPFSRepo}\n */\nexport function createRepo (path, loadCodec, backends, options) {\n return new Repo(path, loadCodec, backends, options)\n}\n\n/**\n * @param {import('./types').Config} _config\n */\nfunction buildConfig (_config) {\n _config.Datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore'))\n\n return _config\n}\n\n/**\n * @param {import('./types').Config} _config\n */\nfunction buildDatastoreSpec (_config) {\n /** @type { {type: string, mounts: Array<{mountpoint: string, type: string, prefix: string, child: {type: string, path: 'string', sync: boolean, shardFunc: string}}>}} */\n const spec = {\n ...defaultDatastore.Spec,\n ..._get(_config, 'Datastore.Spec')\n }\n\n return {\n type: spec.type,\n mounts: spec.mounts.map((mounting) => ({\n mountpoint: mounting.mountpoint,\n type: mounting.child.type,\n path: mounting.child.path,\n shardFunc: mounting.child.shardFunc\n }))\n }\n}\n", "\nimport { CID } from 'multiformats/cid'\nimport { Key } from 'interface-datastore/key'\nimport debug from 'debug'\nimport length from 'it-length'\nimport { base32 } from 'multiformats/bases/base32'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as mhd from 'multiformats/hashes/digest'\n\nconst log = debug('ipfs:repo:migrator:migration-8')\n\n/**\n * @typedef {import('../../types').Migration} Migration\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\n/**\n * @param {*} blockstore\n * @returns {Datastore}\n */\nfunction unwrap (blockstore) {\n if (blockstore.child) {\n return unwrap(blockstore.child)\n }\n\n return blockstore\n}\n\n/**\n * @param {Key} key\n */\nfunction keyToMultihash (key) {\n try {\n const buf = base32.decode(`b${key.toString().toLowerCase().slice(1)}`)\n\n // Extract multihash from CID\n const multihash = CID.decode(buf).multihash.bytes\n\n // Encode and slice off multibase codec\n // Should be uppercase for interop with go\n const multihashStr = base32.encode(multihash).slice(1).toUpperCase()\n\n return new Key(`/${multihashStr}`, false)\n } catch (/** @type {any} */ err) {\n return key\n }\n}\n\n/**\n * @param {Key} key\n */\nfunction keyToCid (key) {\n try {\n const buf = base32.decode(`b${key.toString().toLowerCase().slice(1)}`)\n const digest = mhd.decode(buf)\n\n // CID to Key\n const multihash = base32.encode(CID.createV1(raw.code, digest).bytes).slice(1)\n\n return new Key(`/${multihash.toUpperCase()}`, false)\n } catch {\n return key\n }\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {(percent: number, message: string) => void} onProgress\n * @param {(key: Key) => Key} keyFunction\n */\nasync function process (backends, onProgress, keyFunction) {\n const blockstore = backends.blocks\n await blockstore.open()\n\n const unwrapped = unwrap(blockstore)\n\n const blockCount = await length(unwrapped.queryKeys({\n filters: [(key) => {\n const newKey = keyFunction(key)\n\n return newKey.toString() !== key.toString()\n }]\n }))\n\n try {\n let counter = 0\n\n for await (const block of unwrapped.query({})) {\n const newKey = keyFunction(block.key)\n\n // If the Key is base32 CIDv0 then there's nothing to do\n if (newKey.toString() !== block.key.toString()) {\n counter += 1\n log(`Migrating Block from ${block.key} to ${newKey}`, await unwrapped.has(block.key))\n\n await unwrapped.delete(block.key)\n await unwrapped.put(newKey, block.value)\n\n onProgress((counter / blockCount) * 100, `Migrated Block from ${block.key} to ${newKey}`)\n }\n }\n } finally {\n await blockstore.close()\n }\n}\n\n/** @type {Migration} */\nexport const migration = {\n version: 8,\n description: 'Transforms key names into base32 encoding and converts Block store to use bare multihashes encoded as base32',\n migrate: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keyToMultihash)\n },\n revert: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keyToCid)\n }\n}\n", "/**\n * Consumes the passed iterator and returns the number of items it contained\n */\nexport default async function length (iterator: AsyncIterable | Iterable): Promise {\n let count = 0\n\n for await (const _ of iterator) { // eslint-disable-line no-unused-vars,@typescript-eslint/no-unused-vars\n count++\n }\n\n return count\n}\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const ipfs = $root.ipfs = (() => {\n\n /**\n * Namespace ipfs.\n * @exports ipfs\n * @namespace\n */\n const ipfs = {};\n\n ipfs.pin = (function() {\n\n /**\n * Namespace pin.\n * @memberof ipfs\n * @namespace\n */\n const pin = {};\n\n pin.Set = (function() {\n\n /**\n * Properties of a Set.\n * @memberof ipfs.pin\n * @interface ISet\n * @property {number|null} [version] Set version\n * @property {number|null} [fanout] Set fanout\n * @property {number|null} [seed] Set seed\n */\n\n /**\n * Constructs a new Set.\n * @memberof ipfs.pin\n * @classdesc Represents a Set.\n * @implements ISet\n * @constructor\n * @param {ipfs.pin.ISet=} [p] Properties to set\n */\n function Set(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Set version.\n * @member {number} version\n * @memberof ipfs.pin.Set\n * @instance\n */\n Set.prototype.version = 0;\n\n /**\n * Set fanout.\n * @member {number} fanout\n * @memberof ipfs.pin.Set\n * @instance\n */\n Set.prototype.fanout = 0;\n\n /**\n * Set seed.\n * @member {number} seed\n * @memberof ipfs.pin.Set\n * @instance\n */\n Set.prototype.seed = 0;\n\n /**\n * Encodes the specified Set message. Does not implicitly {@link ipfs.pin.Set.verify|verify} messages.\n * @function encode\n * @memberof ipfs.pin.Set\n * @static\n * @param {ipfs.pin.ISet} m Set message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Set.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.version != null && Object.hasOwnProperty.call(m, \"version\"))\n w.uint32(8).uint32(m.version);\n if (m.fanout != null && Object.hasOwnProperty.call(m, \"fanout\"))\n w.uint32(16).uint32(m.fanout);\n if (m.seed != null && Object.hasOwnProperty.call(m, \"seed\"))\n w.uint32(29).fixed32(m.seed);\n return w;\n };\n\n /**\n * Decodes a Set message from the specified reader or buffer.\n * @function decode\n * @memberof ipfs.pin.Set\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {ipfs.pin.Set} Set\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Set.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.ipfs.pin.Set();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.version = r.uint32();\n break;\n case 2:\n m.fanout = r.uint32();\n break;\n case 3:\n m.seed = r.fixed32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Set message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof ipfs.pin.Set\n * @static\n * @param {Object.} d Plain object\n * @returns {ipfs.pin.Set} Set\n */\n Set.fromObject = function fromObject(d) {\n if (d instanceof $root.ipfs.pin.Set)\n return d;\n var m = new $root.ipfs.pin.Set();\n if (d.version != null) {\n m.version = d.version >>> 0;\n }\n if (d.fanout != null) {\n m.fanout = d.fanout >>> 0;\n }\n if (d.seed != null) {\n m.seed = d.seed >>> 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Set message. Also converts values to other types if specified.\n * @function toObject\n * @memberof ipfs.pin.Set\n * @static\n * @param {ipfs.pin.Set} m Set\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Set.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.version = 0;\n d.fanout = 0;\n d.seed = 0;\n }\n if (m.version != null && m.hasOwnProperty(\"version\")) {\n d.version = m.version;\n }\n if (m.fanout != null && m.hasOwnProperty(\"fanout\")) {\n d.fanout = m.fanout;\n }\n if (m.seed != null && m.hasOwnProperty(\"seed\")) {\n d.seed = m.seed;\n }\n return d;\n };\n\n /**\n * Converts this Set to JSON.\n * @function toJSON\n * @memberof ipfs.pin.Set\n * @instance\n * @returns {Object.} JSON object\n */\n Set.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Set;\n })();\n\n return pin;\n })();\n\n return ipfs;\n})();\n\nexport { $root as default };\n", "\nimport { CID } from 'multiformats/cid'\nimport { ipfs } from './pin.js'\n// @ts-ignore\nimport fnv1a from 'fnv1a'\nimport varint from 'varint'\nimport * as dagPb from '@ipld/dag-pb'\nimport { DEFAULT_FANOUT, MAX_ITEMS, EMPTY_KEY } from './utils.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { compare as uint8ArrayCompare } from 'uint8arrays/compare'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\nconst PinSet = ipfs.pin.Set\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n *\n * @typedef {object} Pin\n * @property {CID} key\n * @property {Uint8Array} [data]\n */\n\n/**\n * @param {PBNode} rootNode\n */\nfunction readHeader (rootNode) {\n // rootNode.data should be a buffer of the format:\n // < varint(headerLength) | header | itemData... >\n const rootData = rootNode.Data\n\n if (!rootData) {\n throw new Error('No data present')\n }\n\n const hdrLength = varint.decode(rootData)\n const vBytes = varint.decode.bytes ?? 0\n\n if (vBytes <= 0) {\n throw new Error('Invalid Set header length')\n }\n\n if (vBytes + hdrLength > rootData.length) {\n throw new Error('Impossibly large set header length')\n }\n\n const hdrSlice = rootData.slice(vBytes, hdrLength + vBytes)\n const header = PinSet.toObject(PinSet.decode(hdrSlice), {\n defaults: false,\n arrays: true,\n longs: Number,\n objects: false\n })\n\n if (header.version !== 1) {\n throw new Error(`Unsupported Set version: ${header.version}`)\n }\n\n if (header.fanout > rootNode.Links.length) {\n throw new Error('Impossibly large fanout')\n }\n\n return {\n header: header,\n data: rootData.slice(hdrLength + vBytes)\n }\n}\n\n/**\n * @param {number} seed\n * @param {CID} key\n */\nfunction hash (seed, key) {\n const buffer = new Uint8Array(4)\n const dataView = new DataView(buffer.buffer)\n dataView.setUint32(0, seed, true)\n const encodedKey = uint8ArrayFromString(key.toString())\n const data = uint8ArrayConcat([buffer, encodedKey], buffer.byteLength + encodedKey.byteLength)\n\n return fnv1a(uint8ArrayToString(data))\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {PBNode} node\n * @returns {AsyncGenerator}\n */\nasync function * walkItems (blockstore, node) {\n const pbh = readHeader(node)\n let idx = 0\n\n for (const link of node.Links) {\n if (idx < pbh.header.fanout) {\n // the first pbh.header.fanout links are fanout bins\n // if a fanout bin is not 'empty', dig into and walk its DAGLinks\n const linkHash = link.Hash\n\n if (!EMPTY_KEY.equals(linkHash)) {\n // walk the links of this fanout bin\n const buf = await blockstore.get(linkHash)\n const node = dagPb.decode(buf)\n\n yield * walkItems(blockstore, node)\n }\n } else {\n // otherwise, the link is a pin\n yield link.Hash\n }\n\n idx++\n }\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {PBNode} rootNode\n * @param {string} name\n */\nexport async function * loadSet (blockstore, rootNode, name) {\n const link = rootNode.Links.find(l => l.Name === name)\n\n if (!link) {\n throw new Error('No link found with name ' + name)\n }\n\n const buf = await blockstore.get(link.Hash)\n const node = dagPb.decode(buf)\n\n yield * walkItems(blockstore, node)\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {Pin[]} items\n */\nfunction storeItems (blockstore, items) {\n return storePins(items, 0)\n\n /**\n * @param {Pin[]} pins\n * @param {number} depth\n */\n async function storePins (pins, depth) {\n const pbHeader = PinSet.encode({\n version: 1,\n fanout: DEFAULT_FANOUT,\n seed: depth\n }).finish()\n\n const header = varint.encode(pbHeader.length)\n const headerBuf = uint8ArrayConcat([header, pbHeader])\n const fanoutLinks = []\n\n for (let i = 0; i < DEFAULT_FANOUT; i++) {\n fanoutLinks.push({\n Name: '',\n Tsize: 1,\n Hash: EMPTY_KEY\n })\n }\n\n if (pins.length <= MAX_ITEMS) {\n const nodes = pins\n .map(item => {\n return ({\n link: {\n Name: '',\n Tsize: 1,\n Hash: item.key\n },\n data: item.data || new Uint8Array()\n })\n })\n // sorting makes any ordering of `pins` produce the same DAGNode\n .sort((a, b) => {\n return uint8ArrayCompare(a.link.Hash.bytes, b.link.Hash.bytes)\n })\n\n const rootLinks = fanoutLinks.concat(nodes.map(item => item.link))\n const rootData = uint8ArrayConcat([headerBuf, ...nodes.map(item => item.data)])\n\n return {\n Data: rootData,\n Links: rootLinks\n }\n } else {\n // If the array of pins is > MAX_ITEMS, we:\n // - distribute the pins among `DEFAULT_FANOUT` bins\n // - create a DAGNode for each bin\n // - add each pin as a DAGLink to that bin\n // - create a root DAGNode\n // - add each bin as a DAGLink\n // - send that root DAGNode via callback\n // (using go-ipfs' \"wasteful but simple\" approach for consistency)\n // https://github.com/ipfs/go-ipfs/blob/master/pin/set.go#L57\n\n /** @type {Pin[][]} */\n const bins = pins.reduce((bins, pin) => {\n const n = hash(depth, pin.key) % DEFAULT_FANOUT\n // @ts-ignore\n bins[n] = n in bins ? bins[n].concat([pin]) : [pin]\n return bins\n }, [])\n\n let idx = 0\n for (const bin of bins) {\n const child = await storePins(bin, depth + 1)\n\n await storeChild(child, idx)\n\n idx++\n }\n\n return {\n Data: headerBuf,\n Links: fanoutLinks\n }\n }\n\n /**\n * @param {PBNode} child\n * @param {number} binIdx\n */\n async function storeChild (child, binIdx) {\n const buf = dagPb.encode(child)\n const digest = await sha256.digest(buf)\n const cid = CID.createV0(digest)\n\n await blockstore.put(cid, buf)\n\n const size = child.Links.reduce((acc, curr) => acc + (curr.Tsize || 0), 0) + buf.length\n\n fanoutLinks[binIdx] = {\n Name: '',\n Tsize: size,\n Hash: cid\n }\n }\n }\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {string} type\n * @param {CID[]} cids\n */\nexport async function storeSet (blockstore, type, cids) {\n const rootNode = await storeItems(blockstore, cids.map(cid => {\n return {\n key: cid\n }\n }))\n const buf = dagPb.encode(rootNode)\n const digest = await sha256.digest(buf)\n const cid = CID.createV0(digest)\n\n await blockstore.put(cid, buf)\n\n const size = rootNode.Links.reduce((acc, curr) => acc + curr.Tsize, 0) + buf.length\n\n return {\n Name: type,\n Tsize: size,\n Hash: cid\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { CID } from 'multiformats/cid'\n\nexport const PIN_DS_KEY = new Key('/local/pins')\nexport const DEFAULT_FANOUT = 256\nexport const MAX_ITEMS = 8192\nexport const EMPTY_KEY = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n\nexport const PinTypes = {\n direct: 'direct',\n recursive: 'recursive'\n}\n\n/**\n * @param {import('multiformats').CID} cid\n */\nexport function cidToKey (cid) {\n return new Key(`/${base32.encode(cid.multihash.bytes).toUpperCase().substring(1)}`)\n}\n", "/**\n * Can be used with Array.sort to sort and array with Uint8Array entries\n */\nexport function compare (a: Uint8Array, b: Uint8Array): number {\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] < b[i]) {\n return -1\n }\n\n if (a[i] > b[i]) {\n return 1\n }\n }\n\n if (a.byteLength > b.byteLength) {\n return 1\n }\n\n if (a.byteLength < b.byteLength) {\n return -1\n }\n\n return 0\n}\n", "\nimport { CID } from 'multiformats/cid'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as cbor from 'cborg'\nimport * as pinset from './pin-set.js'\nimport { cidToKey, PIN_DS_KEY, PinTypes } from './utils.js'\nimport length from 'it-length'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport * as mhd from 'multiformats/hashes/digest'\nimport { base32 } from 'multiformats/bases/base32'\n\n/**\n * @typedef {import('../../types').Migration} Migration\n * @typedef {import('../../types').MigrationProgressCallback} MigrationProgressCallback\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').Version} CIDVersion\n */\n\n/**\n * @param {Blockstore} blockstore\n * @param {Datastore} datastore\n * @param {Datastore} pinstore\n * @param {MigrationProgressCallback} onProgress\n */\nasync function pinsToDatastore (blockstore, datastore, pinstore, onProgress) {\n if (!await datastore.has(PIN_DS_KEY)) {\n return\n }\n\n const mh = await datastore.get(PIN_DS_KEY)\n const cid = CID.decode(mh)\n const pinRootBuf = await blockstore.get(cid)\n const pinRoot = dagPb.decode(pinRootBuf)\n let counter = 0\n const pinCount = (await length(pinset.loadSet(blockstore, pinRoot, PinTypes.recursive))) + (await length(pinset.loadSet(blockstore, pinRoot, PinTypes.direct)))\n\n for await (const cid of pinset.loadSet(blockstore, pinRoot, PinTypes.recursive)) {\n counter++\n\n /** @type {{ depth: number, version?: CIDVersion, codec?: number }} */\n const pin = {\n depth: Infinity\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n await pinstore.put(cidToKey(cid), cbor.encode(pin))\n\n onProgress((counter / pinCount) * 100, `Migrated recursive pin ${cid}`)\n }\n\n for await (const cid of pinset.loadSet(blockstore, pinRoot, PinTypes.direct)) {\n counter++\n\n /** @type {{ depth: number, version?: CIDVersion, codec?: number }} */\n const pin = {\n depth: 0\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n await pinstore.put(cidToKey(cid), cbor.encode(pin))\n\n onProgress((counter / pinCount) * 100, `Migrated direct pin ${cid}`)\n }\n\n await blockstore.delete(cid)\n await datastore.delete(PIN_DS_KEY)\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {Datastore} datastore\n * @param {Datastore} pinstore\n * @param {MigrationProgressCallback} onProgress\n */\nasync function pinsToDAG (blockstore, datastore, pinstore, onProgress) {\n const recursivePins = []\n const directPins = []\n let counter = 0\n const pinCount = await length(pinstore.queryKeys({}))\n\n for await (const { key, value } of pinstore.query({})) {\n counter++\n const pin = cbor.decode(value)\n const cid = CID.create(\n pin.version || 0,\n pin.codec || dagPb.code,\n mhd.decode(base32.decode('b' + key.toString().toLowerCase().split('/').pop()))\n )\n\n if (pin.depth === 0) {\n onProgress((counter / pinCount) * 100, `Reverted direct pin ${cid}`)\n\n directPins.push(cid)\n } else {\n onProgress((counter / pinCount) * 100, `Reverted recursive pin ${cid}`)\n\n recursivePins.push(cid)\n }\n }\n\n onProgress(100, 'Updating pin root')\n const pinRoot = {\n Links: [\n await pinset.storeSet(blockstore, PinTypes.direct, directPins),\n await pinset.storeSet(blockstore, PinTypes.recursive, recursivePins)\n ]\n }\n const buf = dagPb.encode(pinRoot)\n const digest = await sha256.digest(buf)\n const cid = CID.createV0(digest)\n\n await blockstore.put(cid, buf)\n await datastore.put(PIN_DS_KEY, cid.bytes)\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {MigrationProgressCallback} onProgress\n * @param {*} fn\n */\nasync function process (backends, onProgress, fn) {\n const blockstore = backends.blocks\n const datastore = backends.datastore\n const pinstore = backends.pins\n\n await blockstore.open()\n await datastore.open()\n await pinstore.open()\n\n try {\n await fn(blockstore, datastore, pinstore, onProgress)\n } finally {\n await pinstore.close()\n await datastore.close()\n await blockstore.close()\n }\n}\n\n/** @type {Migration} */\nexport const migration = {\n version: 9,\n description: 'Migrates pins to datastore',\n migrate: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, pinsToDatastore)\n },\n revert: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, pinsToDAG)\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport { notFoundError } from 'datastore-core/errors'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\nexport const CONFIG_KEY = new Key('/config')\nexport const VERSION_KEY = new Key('/version')\n\n/**\n * Level dbs wrap level dbs that wrap level dbs. Find a level-js\n * instance in the chain if one exists.\n *\n * @param {Datastore} store\n * @returns {Datastore | undefined}\n */\nexport function findLevelJs (store) {\n let db = store\n\n // @ts-ignore\n while (db.db || db.child) {\n // @ts-ignore\n db = db.db || db.child\n\n // `Level` is only present in the browser, in node it is LevelDOWN\n // @ts-ignore\n if (db.type === 'level-js' || db.constructor.name === 'Level') {\n return db\n }\n }\n}\n\n/**\n * @param {Key} key\n * @param {function (Key): Promise} has\n * @param {Datastore} store\n * @returns {Promise}\n */\nexport async function hasWithFallback (key, has, store) {\n const result = await has(key)\n\n if (result) {\n return result\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n return false\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n resolve(Boolean(req.result))\n }\n })\n}\n\n/**\n * @param {import('interface-datastore').Key} key\n * @param {function (Key): Promise} get\n * @param {function (Key): Promise} has\n * @param {import('interface-datastore').Datastore} store\n * @returns {Promise}\n */\nasync function getWithFallback (key, get, has, store) {\n if (await has(key)) {\n return get(key)\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n throw notFoundError()\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n if (req.result) {\n return resolve(req.result)\n }\n\n reject(notFoundError())\n }\n })\n}\n\n/**\n * @param {Datastore} store\n */\nfunction wrapStore (store) {\n // necessary since level-js@5 cannot read keys from level-js@4 and earlier\n const originalGet = store.get.bind(store)\n const originalHas = store.has.bind(store)\n /**\n * @param {Key} key\n */\n store.get = (key) => getWithFallback(key, originalGet, originalHas, store)\n /**\n * @param {Key} key\n */\n store.has = (key) => hasWithFallback(key, originalHas, store)\n\n return store\n}\n\n/**\n * @param {import('./types').Backends} backends\n */\nexport function wrapBackends (backends) {\n return {\n ...backends,\n root: wrapStore(backends.root),\n datastore: wrapStore(backends.datastore),\n pins: wrapStore(backends.pins),\n keys: wrapStore(backends.keys)\n }\n}\n", "\nimport { findLevelJs } from '../../utils.js'\nimport { fromString } from 'uint8arrays/from-string'\nimport { toString } from 'uint8arrays/to-string'\n\n/**\n * @typedef {import('../../types').Migration} Migration\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../../types').MigrationProgressCallback} MigrationProgressCallback\n *\n * @typedef {{ type: 'del', key: string | Uint8Array } | { type: 'put', key: string | Uint8Array, value: Uint8Array }} Operation\n * @typedef {function (string, Uint8Array): Operation[]} UpgradeFunction\n * @typedef {function (Uint8Array, Uint8Array): Operation[]} DowngradeFunction\n */\n\n/**\n * @param {string} name\n * @param {Datastore} store\n * @param {(message: string) => void} onProgress\n */\nasync function keysToBinary (name, store, onProgress = () => {}) {\n const db = findLevelJs(store)\n\n // only interested in level-js\n if (!db) {\n onProgress(`${name} did not need an upgrade`)\n\n return\n }\n\n onProgress(`Upgrading ${name}`)\n\n /**\n * @type {UpgradeFunction}\n */\n const upgrade = (key, value) => {\n return [\n { type: 'del', key: key },\n { type: 'put', key: fromString(key), value: value }\n ]\n }\n\n await withEach(db, upgrade)\n}\n\n/**\n * @param {string} name\n * @param {Datastore} store\n * @param {(message: string) => void} onProgress\n */\nasync function keysToStrings (name, store, onProgress = () => {}) {\n const db = findLevelJs(store)\n\n // only interested in level-js\n if (!db) {\n onProgress(`${name} did not need a downgrade`)\n\n return\n }\n\n onProgress(`Downgrading ${name}`)\n\n /**\n * @type {DowngradeFunction}\n */\n const downgrade = (key, value) => {\n return [\n { type: 'del', key: key },\n { type: 'put', key: toString(key), value: value }\n ]\n }\n\n await withEach(db, downgrade)\n}\n\n/**\n * @param {any} store\n * @returns {Datastore}\n */\nfunction unwrap (store) {\n if (store.child) {\n return unwrap(store.child)\n }\n\n return store\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {MigrationProgressCallback} onProgress\n * @param {*} fn\n */\nasync function process (backends, onProgress, fn) {\n /**\n * @type {{ name: string, store: Datastore }[]}\n */\n const datastores = Object.entries(backends)\n .map(([key, backend]) => ({ key, backend: unwrap(backend) }))\n .filter(({ key, backend }) => backend.constructor.name === 'LevelDatastore')\n .map(({ key, backend }) => ({\n name: key,\n store: backend\n }))\n\n onProgress(0, `Migrating ${datastores.length} dbs`)\n let migrated = 0\n\n /**\n * @param {string} message\n */\n const progress = (message) => {\n onProgress(Math.round((migrated / datastores.length) * 100), message)\n }\n\n for (const { name, store } of datastores) {\n await store.open()\n\n try {\n await fn(name, store, progress)\n } finally {\n migrated++\n await store.close()\n }\n }\n\n onProgress(100, `Migrated ${datastores.length} dbs`)\n}\n\n/** @type {Migration} */\nexport const migration = {\n version: 10,\n description: 'Migrates datastore-level keys to binary',\n migrate: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keysToBinary)\n },\n revert: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keysToStrings)\n }\n}\n\n/**\n * Uses the upgrade strategy from level-js@5.x.x - note we can't call the `.upgrade` command\n * directly because it will be removed in level-js@6.x.x and we can't guarantee users will\n * have migrated by then - e.g. they may jump from level-js@4.x.x straight to level-js@6.x.x\n * so we have to duplicate the code here.\n *\n * @param {any} db\n * @param {UpgradeFunction | DowngradeFunction} fn\n * @returns {Promise}\n */\nfunction withEach (db, fn) {\n /**\n * @param {Operation[]} operations\n * @param {(error?: Error) => void} next\n */\n function batch (operations, next) {\n const store = db.store('readwrite')\n const transaction = store.transaction\n let index = 0\n /** @type {Error | undefined} */\n let error\n\n transaction.onabort = () => next(error || transaction.error || new Error('aborted by user'))\n transaction.oncomplete = () => next()\n\n function loop () {\n const op = operations[index++]\n const key = op.key\n let req\n\n try {\n req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)\n } catch (/** @type {any} */ err) {\n error = err\n transaction.abort()\n return\n }\n\n if (index < operations.length) {\n req.onsuccess = loop\n }\n }\n\n loop()\n }\n\n return new Promise((resolve, reject) => {\n const it = db.iterator()\n // raw keys and values only\n /**\n * @template T\n * @param {T} data\n */\n const id = (data) => data\n it._deserializeKey = it._deserializeValue = id\n next()\n\n function next () {\n /**\n * @param {Error | undefined} err\n * @param {string | undefined} key\n * @param {Uint8Array} value\n */\n const handleNext = (err, key, value) => {\n if (err || key === undefined) {\n /**\n * @param {Error | undefined} err2\n */\n const handleEnd = (err2) => {\n if (err2) {\n reject(err2)\n return\n }\n\n resolve()\n }\n\n it.end(handleEnd)\n\n return\n }\n\n // @ts-ignore\n batch(fn(key, value), next)\n }\n it.next(handleNext)\n }\n })\n}\n", "\nimport { Key } from 'interface-datastore/key'\n\nconst MFS_ROOT_KEY = new Key('/local/filesroot')\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storeMfsRootInDatastore (backends, onProgress = () => {}) {\n onProgress(100, 'Migrating MFS root to repo datastore')\n\n await backends.root.open()\n await backends.datastore.open()\n\n if (await backends.root.has(MFS_ROOT_KEY)) {\n const root = await backends.root.get(MFS_ROOT_KEY)\n await backends.datastore.put(MFS_ROOT_KEY, root)\n await backends.root.delete(MFS_ROOT_KEY)\n }\n\n await backends.datastore.close()\n await backends.root.close()\n\n onProgress(100, 'Stored MFS root in repo datastore')\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storeMfsRootInRoot (backends, onProgress = () => {}) {\n onProgress(100, 'Migrating MFS root to repo root datastore')\n\n await backends.root.open()\n await backends.datastore.open()\n\n if (await backends.datastore.has(MFS_ROOT_KEY)) {\n const root = await backends.datastore.get(MFS_ROOT_KEY)\n await backends.root.put(MFS_ROOT_KEY, root)\n await backends.datastore.delete(MFS_ROOT_KEY)\n }\n\n await backends.datastore.close()\n await backends.root.close()\n\n onProgress(100, 'Stored MFS root in repo root datastore')\n}\n\n/** @type {import('../../types').Migration} */\nexport const migration = {\n version: 11,\n description: 'Store mfs root in the datastore',\n migrate: storeMfsRootInDatastore,\n revert: storeMfsRootInRoot\n}\n", "import $protobuf from 'protobufjs/minimal.js'\nimport { Key } from 'interface-datastore/key'\nimport { Protocols } from './pb/proto-book.js'\nimport { Addresses } from './pb/address-book.js'\nimport { Peer } from './pb/peer.js'\nimport { Envelope } from './pb/envelope.js'\nimport { PeerRecord } from './pb/peer-record.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n// @ts-expect-error Explicitly disable long.js support\n$protobuf.util.Long = undefined\n$protobuf.configure()\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storePeerUnderSingleDatastoreKey (backends, onProgress = () => {}) {\n onProgress(0, 'Storing each peerstore key under a single datastore key')\n\n await backends.datastore.open()\n\n /** @type {Record} */\n const peers = {}\n /** @type {Key[]} */\n const keys = []\n\n for await (const { key, value } of backends.datastore.query({\n prefix: '/peers'\n })) {\n keys.push(key)\n const keyStr = key.toString()\n const [, prefix, type, peerId, metadataKey] = keyStr.split('/')\n\n if (prefix !== 'peers') {\n continue\n }\n\n if (!['protos', 'addrs', 'metadata', 'keys'].includes(type)) {\n continue\n }\n\n if (!peerId) {\n continue\n }\n\n peers[peerId] = peers[peerId] || {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n if (type === 'protos') {\n const protos = Protocols.decode(value)\n\n peers[peerId].protocols = protos.protocols.sort()\n } else if (type === 'addrs') {\n const addrs = Addresses.decode(value)\n\n peers[peerId].addresses = addrs.addrs.sort((a, b) => {\n return multiaddr(a.multiaddr).toString().localeCompare(multiaddr(b.multiaddr).toString())\n })\n\n if (addrs.certifiedRecord && addrs.certifiedRecord.raw) {\n peers[peerId].peerRecordEnvelope = addrs.certifiedRecord.raw\n }\n } else if (type === 'metadata') {\n peers[peerId].metadata.push({ key: metadataKey, value })\n } else if (type === 'keys') {\n peers[peerId].pubKey = value\n }\n }\n\n onProgress(33, 'Read peer data from store')\n\n for (const key of keys) {\n await backends.datastore.delete(key)\n }\n\n onProgress(66, 'Removed existing peer data from store')\n\n for (const peerId of Object.keys(peers)) {\n const peer = peers[peerId]\n peer.metadata = peer.metadata.sort((/** @type {{ key: string }} */ a, /** @type {{ key: string }} */ b) => a.key.localeCompare(b.key))\n\n const data = Peer.encode(peer).finish()\n\n await backends.datastore.put(new Key(`/peers/${peerId}`), data)\n }\n\n await backends.datastore.close()\n\n onProgress(100, 'Stored each peerstore key under a single datastore key')\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storePeerUnderMultipleDatastoreKeys (backends, onProgress = () => {}) {\n onProgress(0, 'Storing each peerstore key under a multiple datastore keys')\n\n await backends.datastore.open()\n\n /** @type {Record} */\n const peers = {}\n /** @type {Key[]} */\n const keys = []\n\n for await (const { key, value } of backends.datastore.query({\n prefix: '/peers'\n })) {\n keys.push(key)\n const keyStr = key.toString()\n\n const [, , peerId] = keyStr.split('/')\n\n peers[peerId] = Peer.decode(value)\n }\n\n onProgress(33, 'Read peer data from store')\n\n for (const key of keys) {\n await backends.datastore.delete(key)\n }\n\n onProgress(66, 'Removed existing peer data from store')\n\n for (const [peerId, peer] of Object.entries(peers)) {\n if (peer.protocols && peer.protocols.length > 0) {\n await backends.datastore.put(new Key(`/peers/protos/${peerId}`), Protocols.encode({\n protocols: peer.protocols\n }).finish())\n }\n\n if (peer.addresses && peer.addresses.length > 0) {\n const peerRecordEnvelope = peer.peerRecordEnvelope\n let certifiedRecord\n\n if (peerRecordEnvelope) {\n const envelope = Envelope.decode(peerRecordEnvelope)\n const record = PeerRecord.decode(envelope.payload)\n\n certifiedRecord = {\n raw: peerRecordEnvelope,\n seq: record.seq\n }\n }\n\n await backends.datastore.put(new Key(`/peers/addrs/${peerId}`), Addresses.encode({\n addrs: peer.addresses,\n certifiedRecord\n }).finish())\n }\n\n if (peer.metadata && peer.metadata.length > 0) {\n for (const { key, value } of peer.metadata) {\n await backends.datastore.put(new Key(`/peers/metadata/${peerId}/${key}`), value)\n }\n }\n\n if (peer.pubKey) {\n await backends.datastore.put(new Key(`/peers/keys/${peerId}`), peer.pubKey)\n }\n }\n\n await backends.datastore.close()\n\n onProgress(100, 'Stored each peerstore key under multiple datastore keys')\n}\n\n/** @type {import('../../types').Migration} */\nexport const migration = {\n version: 12,\n description: 'Store each peerstore peer under a single datastore key',\n migrate: storePeerUnderSingleDatastoreKey,\n revert: storePeerUnderMultipleDatastoreKeys\n}\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Protocols = $root.Protocols = (() => {\n\n /**\n * Properties of a Protocols.\n * @exports IProtocols\n * @interface IProtocols\n * @property {Array.|null} [protocols] Protocols protocols\n */\n\n /**\n * Constructs a new Protocols.\n * @exports Protocols\n * @classdesc Represents a Protocols.\n * @implements IProtocols\n * @constructor\n * @param {IProtocols=} [p] Properties to set\n */\n function Protocols(p) {\n this.protocols = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Protocols protocols.\n * @member {Array.} protocols\n * @memberof Protocols\n * @instance\n */\n Protocols.prototype.protocols = $util.emptyArray;\n\n /**\n * Encodes the specified Protocols message. Does not implicitly {@link Protocols.verify|verify} messages.\n * @function encode\n * @memberof Protocols\n * @static\n * @param {IProtocols} m Protocols message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Protocols.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.protocols != null && m.protocols.length) {\n for (var i = 0; i < m.protocols.length; ++i)\n w.uint32(10).string(m.protocols[i]);\n }\n return w;\n };\n\n /**\n * Decodes a Protocols message from the specified reader or buffer.\n * @function decode\n * @memberof Protocols\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Protocols} Protocols\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Protocols.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Protocols();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.protocols && m.protocols.length))\n m.protocols = [];\n m.protocols.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Protocols message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Protocols\n * @static\n * @param {Object.} d Plain object\n * @returns {Protocols} Protocols\n */\n Protocols.fromObject = function fromObject(d) {\n if (d instanceof $root.Protocols)\n return d;\n var m = new $root.Protocols();\n if (d.protocols) {\n if (!Array.isArray(d.protocols))\n throw TypeError(\".Protocols.protocols: array expected\");\n m.protocols = [];\n for (var i = 0; i < d.protocols.length; ++i) {\n m.protocols[i] = String(d.protocols[i]);\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Protocols message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Protocols\n * @static\n * @param {Protocols} m Protocols\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Protocols.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.protocols = [];\n }\n if (m.protocols && m.protocols.length) {\n d.protocols = [];\n for (var j = 0; j < m.protocols.length; ++j) {\n d.protocols[j] = m.protocols[j];\n }\n }\n return d;\n };\n\n /**\n * Converts this Protocols to JSON.\n * @function toJSON\n * @memberof Protocols\n * @instance\n * @returns {Object.} JSON object\n */\n Protocols.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Protocols;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Addresses = $root.Addresses = (() => {\n\n /**\n * Properties of an Addresses.\n * @exports IAddresses\n * @interface IAddresses\n * @property {Array.|null} [addrs] Addresses addrs\n * @property {Addresses.ICertifiedRecord|null} [certifiedRecord] Addresses certifiedRecord\n */\n\n /**\n * Constructs a new Addresses.\n * @exports Addresses\n * @classdesc Represents an Addresses.\n * @implements IAddresses\n * @constructor\n * @param {IAddresses=} [p] Properties to set\n */\n function Addresses(p) {\n this.addrs = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Addresses addrs.\n * @member {Array.} addrs\n * @memberof Addresses\n * @instance\n */\n Addresses.prototype.addrs = $util.emptyArray;\n\n /**\n * Addresses certifiedRecord.\n * @member {Addresses.ICertifiedRecord|null|undefined} certifiedRecord\n * @memberof Addresses\n * @instance\n */\n Addresses.prototype.certifiedRecord = null;\n\n /**\n * Encodes the specified Addresses message. Does not implicitly {@link Addresses.verify|verify} messages.\n * @function encode\n * @memberof Addresses\n * @static\n * @param {IAddresses} m Addresses message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Addresses.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.addrs != null && m.addrs.length) {\n for (var i = 0; i < m.addrs.length; ++i)\n $root.Addresses.Address.encode(m.addrs[i], w.uint32(10).fork()).ldelim();\n }\n if (m.certifiedRecord != null && Object.hasOwnProperty.call(m, \"certifiedRecord\"))\n $root.Addresses.CertifiedRecord.encode(m.certifiedRecord, w.uint32(18).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes an Addresses message from the specified reader or buffer.\n * @function decode\n * @memberof Addresses\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Addresses} Addresses\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Addresses.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Addresses();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.addrs && m.addrs.length))\n m.addrs = [];\n m.addrs.push($root.Addresses.Address.decode(r, r.uint32()));\n break;\n case 2:\n m.certifiedRecord = $root.Addresses.CertifiedRecord.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Addresses message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Addresses\n * @static\n * @param {Object.} d Plain object\n * @returns {Addresses} Addresses\n */\n Addresses.fromObject = function fromObject(d) {\n if (d instanceof $root.Addresses)\n return d;\n var m = new $root.Addresses();\n if (d.addrs) {\n if (!Array.isArray(d.addrs))\n throw TypeError(\".Addresses.addrs: array expected\");\n m.addrs = [];\n for (var i = 0; i < d.addrs.length; ++i) {\n if (typeof d.addrs[i] !== \"object\")\n throw TypeError(\".Addresses.addrs: object expected\");\n m.addrs[i] = $root.Addresses.Address.fromObject(d.addrs[i]);\n }\n }\n if (d.certifiedRecord != null) {\n if (typeof d.certifiedRecord !== \"object\")\n throw TypeError(\".Addresses.certifiedRecord: object expected\");\n m.certifiedRecord = $root.Addresses.CertifiedRecord.fromObject(d.certifiedRecord);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Addresses message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Addresses\n * @static\n * @param {Addresses} m Addresses\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Addresses.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.addrs = [];\n }\n if (o.defaults) {\n d.certifiedRecord = null;\n }\n if (m.addrs && m.addrs.length) {\n d.addrs = [];\n for (var j = 0; j < m.addrs.length; ++j) {\n d.addrs[j] = $root.Addresses.Address.toObject(m.addrs[j], o);\n }\n }\n if (m.certifiedRecord != null && m.hasOwnProperty(\"certifiedRecord\")) {\n d.certifiedRecord = $root.Addresses.CertifiedRecord.toObject(m.certifiedRecord, o);\n }\n return d;\n };\n\n /**\n * Converts this Addresses to JSON.\n * @function toJSON\n * @memberof Addresses\n * @instance\n * @returns {Object.} JSON object\n */\n Addresses.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n Addresses.Address = (function() {\n\n /**\n * Properties of an Address.\n * @memberof Addresses\n * @interface IAddress\n * @property {Uint8Array|null} [multiaddr] Address multiaddr\n * @property {boolean|null} [isCertified] Address isCertified\n */\n\n /**\n * Constructs a new Address.\n * @memberof Addresses\n * @classdesc Represents an Address.\n * @implements IAddress\n * @constructor\n * @param {Addresses.IAddress=} [p] Properties to set\n */\n function Address(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Address multiaddr.\n * @member {Uint8Array} multiaddr\n * @memberof Addresses.Address\n * @instance\n */\n Address.prototype.multiaddr = $util.newBuffer([]);\n\n /**\n * Address isCertified.\n * @member {boolean|null|undefined} isCertified\n * @memberof Addresses.Address\n * @instance\n */\n Address.prototype.isCertified = null;\n\n // OneOf field names bound to virtual getters and setters\n let $oneOfFields;\n\n /**\n * Address _isCertified.\n * @member {\"isCertified\"|undefined} _isCertified\n * @memberof Addresses.Address\n * @instance\n */\n Object.defineProperty(Address.prototype, \"_isCertified\", {\n get: $util.oneOfGetter($oneOfFields = [\"isCertified\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Address message. Does not implicitly {@link Addresses.Address.verify|verify} messages.\n * @function encode\n * @memberof Addresses.Address\n * @static\n * @param {Addresses.IAddress} m Address message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Address.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.multiaddr != null && Object.hasOwnProperty.call(m, \"multiaddr\"))\n w.uint32(10).bytes(m.multiaddr);\n if (m.isCertified != null && Object.hasOwnProperty.call(m, \"isCertified\"))\n w.uint32(16).bool(m.isCertified);\n return w;\n };\n\n /**\n * Decodes an Address message from the specified reader or buffer.\n * @function decode\n * @memberof Addresses.Address\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Addresses.Address} Address\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Address.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Addresses.Address();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.multiaddr = r.bytes();\n break;\n case 2:\n m.isCertified = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Address message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Addresses.Address\n * @static\n * @param {Object.} d Plain object\n * @returns {Addresses.Address} Address\n */\n Address.fromObject = function fromObject(d) {\n if (d instanceof $root.Addresses.Address)\n return d;\n var m = new $root.Addresses.Address();\n if (d.multiaddr != null) {\n if (typeof d.multiaddr === \"string\")\n $util.base64.decode(d.multiaddr, m.multiaddr = $util.newBuffer($util.base64.length(d.multiaddr)), 0);\n else if (d.multiaddr.length)\n m.multiaddr = d.multiaddr;\n }\n if (d.isCertified != null) {\n m.isCertified = Boolean(d.isCertified);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Address message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Addresses.Address\n * @static\n * @param {Addresses.Address} m Address\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Address.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.multiaddr = \"\";\n else {\n d.multiaddr = [];\n if (o.bytes !== Array)\n d.multiaddr = $util.newBuffer(d.multiaddr);\n }\n }\n if (m.multiaddr != null && m.hasOwnProperty(\"multiaddr\")) {\n d.multiaddr = o.bytes === String ? $util.base64.encode(m.multiaddr, 0, m.multiaddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.multiaddr) : m.multiaddr;\n }\n if (m.isCertified != null && m.hasOwnProperty(\"isCertified\")) {\n d.isCertified = m.isCertified;\n if (o.oneofs)\n d._isCertified = \"isCertified\";\n }\n return d;\n };\n\n /**\n * Converts this Address to JSON.\n * @function toJSON\n * @memberof Addresses.Address\n * @instance\n * @returns {Object.} JSON object\n */\n Address.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Address;\n })();\n\n Addresses.CertifiedRecord = (function() {\n\n /**\n * Properties of a CertifiedRecord.\n * @memberof Addresses\n * @interface ICertifiedRecord\n * @property {number|null} [seq] CertifiedRecord seq\n * @property {Uint8Array|null} [raw] CertifiedRecord raw\n */\n\n /**\n * Constructs a new CertifiedRecord.\n * @memberof Addresses\n * @classdesc Represents a CertifiedRecord.\n * @implements ICertifiedRecord\n * @constructor\n * @param {Addresses.ICertifiedRecord=} [p] Properties to set\n */\n function CertifiedRecord(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * CertifiedRecord seq.\n * @member {number} seq\n * @memberof Addresses.CertifiedRecord\n * @instance\n */\n CertifiedRecord.prototype.seq = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * CertifiedRecord raw.\n * @member {Uint8Array} raw\n * @memberof Addresses.CertifiedRecord\n * @instance\n */\n CertifiedRecord.prototype.raw = $util.newBuffer([]);\n\n /**\n * Encodes the specified CertifiedRecord message. Does not implicitly {@link Addresses.CertifiedRecord.verify|verify} messages.\n * @function encode\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {Addresses.ICertifiedRecord} m CertifiedRecord message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n CertifiedRecord.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.seq != null && Object.hasOwnProperty.call(m, \"seq\"))\n w.uint32(8).uint64(m.seq);\n if (m.raw != null && Object.hasOwnProperty.call(m, \"raw\"))\n w.uint32(18).bytes(m.raw);\n return w;\n };\n\n /**\n * Decodes a CertifiedRecord message from the specified reader or buffer.\n * @function decode\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Addresses.CertifiedRecord} CertifiedRecord\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n CertifiedRecord.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Addresses.CertifiedRecord();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.seq = r.uint64();\n break;\n case 2:\n m.raw = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a CertifiedRecord message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {Object.} d Plain object\n * @returns {Addresses.CertifiedRecord} CertifiedRecord\n */\n CertifiedRecord.fromObject = function fromObject(d) {\n if (d instanceof $root.Addresses.CertifiedRecord)\n return d;\n var m = new $root.Addresses.CertifiedRecord();\n if (d.seq != null) {\n if ($util.Long)\n (m.seq = $util.Long.fromValue(d.seq)).unsigned = true;\n else if (typeof d.seq === \"string\")\n m.seq = parseInt(d.seq, 10);\n else if (typeof d.seq === \"number\")\n m.seq = d.seq;\n else if (typeof d.seq === \"object\")\n m.seq = new $util.LongBits(d.seq.low >>> 0, d.seq.high >>> 0).toNumber(true);\n }\n if (d.raw != null) {\n if (typeof d.raw === \"string\")\n $util.base64.decode(d.raw, m.raw = $util.newBuffer($util.base64.length(d.raw)), 0);\n else if (d.raw.length)\n m.raw = d.raw;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a CertifiedRecord message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {Addresses.CertifiedRecord} m CertifiedRecord\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n CertifiedRecord.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.seq = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.seq = o.longs === String ? \"0\" : 0;\n if (o.bytes === String)\n d.raw = \"\";\n else {\n d.raw = [];\n if (o.bytes !== Array)\n d.raw = $util.newBuffer(d.raw);\n }\n }\n if (m.seq != null && m.hasOwnProperty(\"seq\")) {\n if (typeof m.seq === \"number\")\n d.seq = o.longs === String ? String(m.seq) : m.seq;\n else\n d.seq = o.longs === String ? $util.Long.prototype.toString.call(m.seq) : o.longs === Number ? new $util.LongBits(m.seq.low >>> 0, m.seq.high >>> 0).toNumber(true) : m.seq;\n }\n if (m.raw != null && m.hasOwnProperty(\"raw\")) {\n d.raw = o.bytes === String ? $util.base64.encode(m.raw, 0, m.raw.length) : o.bytes === Array ? Array.prototype.slice.call(m.raw) : m.raw;\n }\n return d;\n };\n\n /**\n * Converts this CertifiedRecord to JSON.\n * @function toJSON\n * @memberof Addresses.CertifiedRecord\n * @instance\n * @returns {Object.} JSON object\n */\n CertifiedRecord.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return CertifiedRecord;\n })();\n\n return Addresses;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Peer = $root.Peer = (() => {\n\n /**\n * Properties of a Peer.\n * @exports IPeer\n * @interface IPeer\n * @property {Array.|null} [addresses] Peer addresses\n * @property {Array.|null} [protocols] Peer protocols\n * @property {Array.|null} [metadata] Peer metadata\n * @property {Uint8Array|null} [pubKey] Peer pubKey\n * @property {Uint8Array|null} [peerRecordEnvelope] Peer peerRecordEnvelope\n */\n\n /**\n * Constructs a new Peer.\n * @exports Peer\n * @classdesc Represents a Peer.\n * @implements IPeer\n * @constructor\n * @param {IPeer=} [p] Properties to set\n */\n function Peer(p) {\n this.addresses = [];\n this.protocols = [];\n this.metadata = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Peer addresses.\n * @member {Array.} addresses\n * @memberof Peer\n * @instance\n */\n Peer.prototype.addresses = $util.emptyArray;\n\n /**\n * Peer protocols.\n * @member {Array.} protocols\n * @memberof Peer\n * @instance\n */\n Peer.prototype.protocols = $util.emptyArray;\n\n /**\n * Peer metadata.\n * @member {Array.} metadata\n * @memberof Peer\n * @instance\n */\n Peer.prototype.metadata = $util.emptyArray;\n\n /**\n * Peer pubKey.\n * @member {Uint8Array|null|undefined} pubKey\n * @memberof Peer\n * @instance\n */\n Peer.prototype.pubKey = null;\n\n /**\n * Peer peerRecordEnvelope.\n * @member {Uint8Array|null|undefined} peerRecordEnvelope\n * @memberof Peer\n * @instance\n */\n Peer.prototype.peerRecordEnvelope = null;\n\n // OneOf field names bound to virtual getters and setters\n let $oneOfFields;\n\n /**\n * Peer _pubKey.\n * @member {\"pubKey\"|undefined} _pubKey\n * @memberof Peer\n * @instance\n */\n Object.defineProperty(Peer.prototype, \"_pubKey\", {\n get: $util.oneOfGetter($oneOfFields = [\"pubKey\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Peer _peerRecordEnvelope.\n * @member {\"peerRecordEnvelope\"|undefined} _peerRecordEnvelope\n * @memberof Peer\n * @instance\n */\n Object.defineProperty(Peer.prototype, \"_peerRecordEnvelope\", {\n get: $util.oneOfGetter($oneOfFields = [\"peerRecordEnvelope\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Peer message. Does not implicitly {@link Peer.verify|verify} messages.\n * @function encode\n * @memberof Peer\n * @static\n * @param {IPeer} m Peer message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Peer.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.addresses != null && m.addresses.length) {\n for (var i = 0; i < m.addresses.length; ++i)\n $root.Address.encode(m.addresses[i], w.uint32(10).fork()).ldelim();\n }\n if (m.protocols != null && m.protocols.length) {\n for (var i = 0; i < m.protocols.length; ++i)\n w.uint32(18).string(m.protocols[i]);\n }\n if (m.metadata != null && m.metadata.length) {\n for (var i = 0; i < m.metadata.length; ++i)\n $root.Metadata.encode(m.metadata[i], w.uint32(26).fork()).ldelim();\n }\n if (m.pubKey != null && Object.hasOwnProperty.call(m, \"pubKey\"))\n w.uint32(34).bytes(m.pubKey);\n if (m.peerRecordEnvelope != null && Object.hasOwnProperty.call(m, \"peerRecordEnvelope\"))\n w.uint32(42).bytes(m.peerRecordEnvelope);\n return w;\n };\n\n /**\n * Decodes a Peer message from the specified reader or buffer.\n * @function decode\n * @memberof Peer\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Peer} Peer\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Peer.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Peer();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.addresses && m.addresses.length))\n m.addresses = [];\n m.addresses.push($root.Address.decode(r, r.uint32()));\n break;\n case 2:\n if (!(m.protocols && m.protocols.length))\n m.protocols = [];\n m.protocols.push(r.string());\n break;\n case 3:\n if (!(m.metadata && m.metadata.length))\n m.metadata = [];\n m.metadata.push($root.Metadata.decode(r, r.uint32()));\n break;\n case 4:\n m.pubKey = r.bytes();\n break;\n case 5:\n m.peerRecordEnvelope = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Peer message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Peer\n * @static\n * @param {Object.} d Plain object\n * @returns {Peer} Peer\n */\n Peer.fromObject = function fromObject(d) {\n if (d instanceof $root.Peer)\n return d;\n var m = new $root.Peer();\n if (d.addresses) {\n if (!Array.isArray(d.addresses))\n throw TypeError(\".Peer.addresses: array expected\");\n m.addresses = [];\n for (var i = 0; i < d.addresses.length; ++i) {\n if (typeof d.addresses[i] !== \"object\")\n throw TypeError(\".Peer.addresses: object expected\");\n m.addresses[i] = $root.Address.fromObject(d.addresses[i]);\n }\n }\n if (d.protocols) {\n if (!Array.isArray(d.protocols))\n throw TypeError(\".Peer.protocols: array expected\");\n m.protocols = [];\n for (var i = 0; i < d.protocols.length; ++i) {\n m.protocols[i] = String(d.protocols[i]);\n }\n }\n if (d.metadata) {\n if (!Array.isArray(d.metadata))\n throw TypeError(\".Peer.metadata: array expected\");\n m.metadata = [];\n for (var i = 0; i < d.metadata.length; ++i) {\n if (typeof d.metadata[i] !== \"object\")\n throw TypeError(\".Peer.metadata: object expected\");\n m.metadata[i] = $root.Metadata.fromObject(d.metadata[i]);\n }\n }\n if (d.pubKey != null) {\n if (typeof d.pubKey === \"string\")\n $util.base64.decode(d.pubKey, m.pubKey = $util.newBuffer($util.base64.length(d.pubKey)), 0);\n else if (d.pubKey.length)\n m.pubKey = d.pubKey;\n }\n if (d.peerRecordEnvelope != null) {\n if (typeof d.peerRecordEnvelope === \"string\")\n $util.base64.decode(d.peerRecordEnvelope, m.peerRecordEnvelope = $util.newBuffer($util.base64.length(d.peerRecordEnvelope)), 0);\n else if (d.peerRecordEnvelope.length)\n m.peerRecordEnvelope = d.peerRecordEnvelope;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Peer message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Peer\n * @static\n * @param {Peer} m Peer\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Peer.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.addresses = [];\n d.protocols = [];\n d.metadata = [];\n }\n if (m.addresses && m.addresses.length) {\n d.addresses = [];\n for (var j = 0; j < m.addresses.length; ++j) {\n d.addresses[j] = $root.Address.toObject(m.addresses[j], o);\n }\n }\n if (m.protocols && m.protocols.length) {\n d.protocols = [];\n for (var j = 0; j < m.protocols.length; ++j) {\n d.protocols[j] = m.protocols[j];\n }\n }\n if (m.metadata && m.metadata.length) {\n d.metadata = [];\n for (var j = 0; j < m.metadata.length; ++j) {\n d.metadata[j] = $root.Metadata.toObject(m.metadata[j], o);\n }\n }\n if (m.pubKey != null && m.hasOwnProperty(\"pubKey\")) {\n d.pubKey = o.bytes === String ? $util.base64.encode(m.pubKey, 0, m.pubKey.length) : o.bytes === Array ? Array.prototype.slice.call(m.pubKey) : m.pubKey;\n if (o.oneofs)\n d._pubKey = \"pubKey\";\n }\n if (m.peerRecordEnvelope != null && m.hasOwnProperty(\"peerRecordEnvelope\")) {\n d.peerRecordEnvelope = o.bytes === String ? $util.base64.encode(m.peerRecordEnvelope, 0, m.peerRecordEnvelope.length) : o.bytes === Array ? Array.prototype.slice.call(m.peerRecordEnvelope) : m.peerRecordEnvelope;\n if (o.oneofs)\n d._peerRecordEnvelope = \"peerRecordEnvelope\";\n }\n return d;\n };\n\n /**\n * Converts this Peer to JSON.\n * @function toJSON\n * @memberof Peer\n * @instance\n * @returns {Object.} JSON object\n */\n Peer.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Peer;\n})();\n\nexport const Address = $root.Address = (() => {\n\n /**\n * Properties of an Address.\n * @exports IAddress\n * @interface IAddress\n * @property {Uint8Array|null} [multiaddr] Address multiaddr\n * @property {boolean|null} [isCertified] Address isCertified\n */\n\n /**\n * Constructs a new Address.\n * @exports Address\n * @classdesc Represents an Address.\n * @implements IAddress\n * @constructor\n * @param {IAddress=} [p] Properties to set\n */\n function Address(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Address multiaddr.\n * @member {Uint8Array} multiaddr\n * @memberof Address\n * @instance\n */\n Address.prototype.multiaddr = $util.newBuffer([]);\n\n /**\n * Address isCertified.\n * @member {boolean|null|undefined} isCertified\n * @memberof Address\n * @instance\n */\n Address.prototype.isCertified = null;\n\n // OneOf field names bound to virtual getters and setters\n let $oneOfFields;\n\n /**\n * Address _isCertified.\n * @member {\"isCertified\"|undefined} _isCertified\n * @memberof Address\n * @instance\n */\n Object.defineProperty(Address.prototype, \"_isCertified\", {\n get: $util.oneOfGetter($oneOfFields = [\"isCertified\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Address message. Does not implicitly {@link Address.verify|verify} messages.\n * @function encode\n * @memberof Address\n * @static\n * @param {IAddress} m Address message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Address.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.multiaddr != null && Object.hasOwnProperty.call(m, \"multiaddr\"))\n w.uint32(10).bytes(m.multiaddr);\n if (m.isCertified != null && Object.hasOwnProperty.call(m, \"isCertified\"))\n w.uint32(16).bool(m.isCertified);\n return w;\n };\n\n /**\n * Decodes an Address message from the specified reader or buffer.\n * @function decode\n * @memberof Address\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Address} Address\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Address.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Address();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.multiaddr = r.bytes();\n break;\n case 2:\n m.isCertified = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Address message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Address\n * @static\n * @param {Object.} d Plain object\n * @returns {Address} Address\n */\n Address.fromObject = function fromObject(d) {\n if (d instanceof $root.Address)\n return d;\n var m = new $root.Address();\n if (d.multiaddr != null) {\n if (typeof d.multiaddr === \"string\")\n $util.base64.decode(d.multiaddr, m.multiaddr = $util.newBuffer($util.base64.length(d.multiaddr)), 0);\n else if (d.multiaddr.length)\n m.multiaddr = d.multiaddr;\n }\n if (d.isCertified != null) {\n m.isCertified = Boolean(d.isCertified);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Address message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Address\n * @static\n * @param {Address} m Address\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Address.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.multiaddr = \"\";\n else {\n d.multiaddr = [];\n if (o.bytes !== Array)\n d.multiaddr = $util.newBuffer(d.multiaddr);\n }\n }\n if (m.multiaddr != null && m.hasOwnProperty(\"multiaddr\")) {\n d.multiaddr = o.bytes === String ? $util.base64.encode(m.multiaddr, 0, m.multiaddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.multiaddr) : m.multiaddr;\n }\n if (m.isCertified != null && m.hasOwnProperty(\"isCertified\")) {\n d.isCertified = m.isCertified;\n if (o.oneofs)\n d._isCertified = \"isCertified\";\n }\n return d;\n };\n\n /**\n * Converts this Address to JSON.\n * @function toJSON\n * @memberof Address\n * @instance\n * @returns {Object.} JSON object\n */\n Address.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Address;\n})();\n\nexport const Metadata = $root.Metadata = (() => {\n\n /**\n * Properties of a Metadata.\n * @exports IMetadata\n * @interface IMetadata\n * @property {string|null} [key] Metadata key\n * @property {Uint8Array|null} [value] Metadata value\n */\n\n /**\n * Constructs a new Metadata.\n * @exports Metadata\n * @classdesc Represents a Metadata.\n * @implements IMetadata\n * @constructor\n * @param {IMetadata=} [p] Properties to set\n */\n function Metadata(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Metadata key.\n * @member {string} key\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.key = \"\";\n\n /**\n * Metadata value.\n * @member {Uint8Array} value\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.value = $util.newBuffer([]);\n\n /**\n * Encodes the specified Metadata message. Does not implicitly {@link Metadata.verify|verify} messages.\n * @function encode\n * @memberof Metadata\n * @static\n * @param {IMetadata} m Metadata message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Metadata.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.key != null && Object.hasOwnProperty.call(m, \"key\"))\n w.uint32(10).string(m.key);\n if (m.value != null && Object.hasOwnProperty.call(m, \"value\"))\n w.uint32(18).bytes(m.value);\n return w;\n };\n\n /**\n * Decodes a Metadata message from the specified reader or buffer.\n * @function decode\n * @memberof Metadata\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Metadata} Metadata\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Metadata.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Metadata();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.key = r.string();\n break;\n case 2:\n m.value = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Metadata message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Metadata\n * @static\n * @param {Object.} d Plain object\n * @returns {Metadata} Metadata\n */\n Metadata.fromObject = function fromObject(d) {\n if (d instanceof $root.Metadata)\n return d;\n var m = new $root.Metadata();\n if (d.key != null) {\n m.key = String(d.key);\n }\n if (d.value != null) {\n if (typeof d.value === \"string\")\n $util.base64.decode(d.value, m.value = $util.newBuffer($util.base64.length(d.value)), 0);\n else if (d.value.length)\n m.value = d.value;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Metadata message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Metadata\n * @static\n * @param {Metadata} m Metadata\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Metadata.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.key = \"\";\n if (o.bytes === String)\n d.value = \"\";\n else {\n d.value = [];\n if (o.bytes !== Array)\n d.value = $util.newBuffer(d.value);\n }\n }\n if (m.key != null && m.hasOwnProperty(\"key\")) {\n d.key = m.key;\n }\n if (m.value != null && m.hasOwnProperty(\"value\")) {\n d.value = o.bytes === String ? $util.base64.encode(m.value, 0, m.value.length) : o.bytes === Array ? Array.prototype.slice.call(m.value) : m.value;\n }\n return d;\n };\n\n /**\n * Converts this Metadata to JSON.\n * @function toJSON\n * @memberof Metadata\n * @instance\n * @returns {Object.} JSON object\n */\n Metadata.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Metadata;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Envelope = $root.Envelope = (() => {\n\n /**\n * Properties of an Envelope.\n * @exports IEnvelope\n * @interface IEnvelope\n * @property {Uint8Array|null} [publicKey] Envelope publicKey\n * @property {Uint8Array|null} [payloadType] Envelope payloadType\n * @property {Uint8Array|null} [payload] Envelope payload\n * @property {Uint8Array|null} [signature] Envelope signature\n */\n\n /**\n * Constructs a new Envelope.\n * @exports Envelope\n * @classdesc Represents an Envelope.\n * @implements IEnvelope\n * @constructor\n * @param {IEnvelope=} [p] Properties to set\n */\n function Envelope(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Envelope publicKey.\n * @member {Uint8Array} publicKey\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.publicKey = $util.newBuffer([]);\n\n /**\n * Envelope payloadType.\n * @member {Uint8Array} payloadType\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.payloadType = $util.newBuffer([]);\n\n /**\n * Envelope payload.\n * @member {Uint8Array} payload\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.payload = $util.newBuffer([]);\n\n /**\n * Envelope signature.\n * @member {Uint8Array} signature\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.signature = $util.newBuffer([]);\n\n /**\n * Encodes the specified Envelope message. Does not implicitly {@link Envelope.verify|verify} messages.\n * @function encode\n * @memberof Envelope\n * @static\n * @param {IEnvelope} m Envelope message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Envelope.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.publicKey != null && Object.hasOwnProperty.call(m, \"publicKey\"))\n w.uint32(10).bytes(m.publicKey);\n if (m.payloadType != null && Object.hasOwnProperty.call(m, \"payloadType\"))\n w.uint32(18).bytes(m.payloadType);\n if (m.payload != null && Object.hasOwnProperty.call(m, \"payload\"))\n w.uint32(26).bytes(m.payload);\n if (m.signature != null && Object.hasOwnProperty.call(m, \"signature\"))\n w.uint32(42).bytes(m.signature);\n return w;\n };\n\n /**\n * Decodes an Envelope message from the specified reader or buffer.\n * @function decode\n * @memberof Envelope\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Envelope} Envelope\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Envelope.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Envelope();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.publicKey = r.bytes();\n break;\n case 2:\n m.payloadType = r.bytes();\n break;\n case 3:\n m.payload = r.bytes();\n break;\n case 5:\n m.signature = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Envelope message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Envelope\n * @static\n * @param {Object.} d Plain object\n * @returns {Envelope} Envelope\n */\n Envelope.fromObject = function fromObject(d) {\n if (d instanceof $root.Envelope)\n return d;\n var m = new $root.Envelope();\n if (d.publicKey != null) {\n if (typeof d.publicKey === \"string\")\n $util.base64.decode(d.publicKey, m.publicKey = $util.newBuffer($util.base64.length(d.publicKey)), 0);\n else if (d.publicKey.length)\n m.publicKey = d.publicKey;\n }\n if (d.payloadType != null) {\n if (typeof d.payloadType === \"string\")\n $util.base64.decode(d.payloadType, m.payloadType = $util.newBuffer($util.base64.length(d.payloadType)), 0);\n else if (d.payloadType.length)\n m.payloadType = d.payloadType;\n }\n if (d.payload != null) {\n if (typeof d.payload === \"string\")\n $util.base64.decode(d.payload, m.payload = $util.newBuffer($util.base64.length(d.payload)), 0);\n else if (d.payload.length)\n m.payload = d.payload;\n }\n if (d.signature != null) {\n if (typeof d.signature === \"string\")\n $util.base64.decode(d.signature, m.signature = $util.newBuffer($util.base64.length(d.signature)), 0);\n else if (d.signature.length)\n m.signature = d.signature;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Envelope message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Envelope\n * @static\n * @param {Envelope} m Envelope\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Envelope.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.publicKey = \"\";\n else {\n d.publicKey = [];\n if (o.bytes !== Array)\n d.publicKey = $util.newBuffer(d.publicKey);\n }\n if (o.bytes === String)\n d.payloadType = \"\";\n else {\n d.payloadType = [];\n if (o.bytes !== Array)\n d.payloadType = $util.newBuffer(d.payloadType);\n }\n if (o.bytes === String)\n d.payload = \"\";\n else {\n d.payload = [];\n if (o.bytes !== Array)\n d.payload = $util.newBuffer(d.payload);\n }\n if (o.bytes === String)\n d.signature = \"\";\n else {\n d.signature = [];\n if (o.bytes !== Array)\n d.signature = $util.newBuffer(d.signature);\n }\n }\n if (m.publicKey != null && m.hasOwnProperty(\"publicKey\")) {\n d.publicKey = o.bytes === String ? $util.base64.encode(m.publicKey, 0, m.publicKey.length) : o.bytes === Array ? Array.prototype.slice.call(m.publicKey) : m.publicKey;\n }\n if (m.payloadType != null && m.hasOwnProperty(\"payloadType\")) {\n d.payloadType = o.bytes === String ? $util.base64.encode(m.payloadType, 0, m.payloadType.length) : o.bytes === Array ? Array.prototype.slice.call(m.payloadType) : m.payloadType;\n }\n if (m.payload != null && m.hasOwnProperty(\"payload\")) {\n d.payload = o.bytes === String ? $util.base64.encode(m.payload, 0, m.payload.length) : o.bytes === Array ? Array.prototype.slice.call(m.payload) : m.payload;\n }\n if (m.signature != null && m.hasOwnProperty(\"signature\")) {\n d.signature = o.bytes === String ? $util.base64.encode(m.signature, 0, m.signature.length) : o.bytes === Array ? Array.prototype.slice.call(m.signature) : m.signature;\n }\n return d;\n };\n\n /**\n * Converts this Envelope to JSON.\n * @function toJSON\n * @memberof Envelope\n * @instance\n * @returns {Object.} JSON object\n */\n Envelope.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Envelope;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const PeerRecord = $root.PeerRecord = (() => {\n\n /**\n * Properties of a PeerRecord.\n * @exports IPeerRecord\n * @interface IPeerRecord\n * @property {Uint8Array|null} [peerId] PeerRecord peerId\n * @property {number|null} [seq] PeerRecord seq\n * @property {Array.|null} [addresses] PeerRecord addresses\n */\n\n /**\n * Constructs a new PeerRecord.\n * @exports PeerRecord\n * @classdesc Represents a PeerRecord.\n * @implements IPeerRecord\n * @constructor\n * @param {IPeerRecord=} [p] Properties to set\n */\n function PeerRecord(p) {\n this.addresses = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * PeerRecord peerId.\n * @member {Uint8Array} peerId\n * @memberof PeerRecord\n * @instance\n */\n PeerRecord.prototype.peerId = $util.newBuffer([]);\n\n /**\n * PeerRecord seq.\n * @member {number} seq\n * @memberof PeerRecord\n * @instance\n */\n PeerRecord.prototype.seq = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * PeerRecord addresses.\n * @member {Array.} addresses\n * @memberof PeerRecord\n * @instance\n */\n PeerRecord.prototype.addresses = $util.emptyArray;\n\n /**\n * Encodes the specified PeerRecord message. Does not implicitly {@link PeerRecord.verify|verify} messages.\n * @function encode\n * @memberof PeerRecord\n * @static\n * @param {IPeerRecord} m PeerRecord message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n PeerRecord.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.peerId != null && Object.hasOwnProperty.call(m, \"peerId\"))\n w.uint32(10).bytes(m.peerId);\n if (m.seq != null && Object.hasOwnProperty.call(m, \"seq\"))\n w.uint32(16).uint64(m.seq);\n if (m.addresses != null && m.addresses.length) {\n for (var i = 0; i < m.addresses.length; ++i)\n $root.PeerRecord.AddressInfo.encode(m.addresses[i], w.uint32(26).fork()).ldelim();\n }\n return w;\n };\n\n /**\n * Decodes a PeerRecord message from the specified reader or buffer.\n * @function decode\n * @memberof PeerRecord\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {PeerRecord} PeerRecord\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n PeerRecord.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.PeerRecord();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.peerId = r.bytes();\n break;\n case 2:\n m.seq = r.uint64();\n break;\n case 3:\n if (!(m.addresses && m.addresses.length))\n m.addresses = [];\n m.addresses.push($root.PeerRecord.AddressInfo.decode(r, r.uint32()));\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a PeerRecord message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof PeerRecord\n * @static\n * @param {Object.} d Plain object\n * @returns {PeerRecord} PeerRecord\n */\n PeerRecord.fromObject = function fromObject(d) {\n if (d instanceof $root.PeerRecord)\n return d;\n var m = new $root.PeerRecord();\n if (d.peerId != null) {\n if (typeof d.peerId === \"string\")\n $util.base64.decode(d.peerId, m.peerId = $util.newBuffer($util.base64.length(d.peerId)), 0);\n else if (d.peerId.length)\n m.peerId = d.peerId;\n }\n if (d.seq != null) {\n if ($util.Long)\n (m.seq = $util.Long.fromValue(d.seq)).unsigned = true;\n else if (typeof d.seq === \"string\")\n m.seq = parseInt(d.seq, 10);\n else if (typeof d.seq === \"number\")\n m.seq = d.seq;\n else if (typeof d.seq === \"object\")\n m.seq = new $util.LongBits(d.seq.low >>> 0, d.seq.high >>> 0).toNumber(true);\n }\n if (d.addresses) {\n if (!Array.isArray(d.addresses))\n throw TypeError(\".PeerRecord.addresses: array expected\");\n m.addresses = [];\n for (var i = 0; i < d.addresses.length; ++i) {\n if (typeof d.addresses[i] !== \"object\")\n throw TypeError(\".PeerRecord.addresses: object expected\");\n m.addresses[i] = $root.PeerRecord.AddressInfo.fromObject(d.addresses[i]);\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a PeerRecord message. Also converts values to other types if specified.\n * @function toObject\n * @memberof PeerRecord\n * @static\n * @param {PeerRecord} m PeerRecord\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n PeerRecord.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.addresses = [];\n }\n if (o.defaults) {\n if (o.bytes === String)\n d.peerId = \"\";\n else {\n d.peerId = [];\n if (o.bytes !== Array)\n d.peerId = $util.newBuffer(d.peerId);\n }\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.seq = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.seq = o.longs === String ? \"0\" : 0;\n }\n if (m.peerId != null && m.hasOwnProperty(\"peerId\")) {\n d.peerId = o.bytes === String ? $util.base64.encode(m.peerId, 0, m.peerId.length) : o.bytes === Array ? Array.prototype.slice.call(m.peerId) : m.peerId;\n }\n if (m.seq != null && m.hasOwnProperty(\"seq\")) {\n if (typeof m.seq === \"number\")\n d.seq = o.longs === String ? String(m.seq) : m.seq;\n else\n d.seq = o.longs === String ? $util.Long.prototype.toString.call(m.seq) : o.longs === Number ? new $util.LongBits(m.seq.low >>> 0, m.seq.high >>> 0).toNumber(true) : m.seq;\n }\n if (m.addresses && m.addresses.length) {\n d.addresses = [];\n for (var j = 0; j < m.addresses.length; ++j) {\n d.addresses[j] = $root.PeerRecord.AddressInfo.toObject(m.addresses[j], o);\n }\n }\n return d;\n };\n\n /**\n * Converts this PeerRecord to JSON.\n * @function toJSON\n * @memberof PeerRecord\n * @instance\n * @returns {Object.} JSON object\n */\n PeerRecord.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n PeerRecord.AddressInfo = (function() {\n\n /**\n * Properties of an AddressInfo.\n * @memberof PeerRecord\n * @interface IAddressInfo\n * @property {Uint8Array|null} [multiaddr] AddressInfo multiaddr\n */\n\n /**\n * Constructs a new AddressInfo.\n * @memberof PeerRecord\n * @classdesc Represents an AddressInfo.\n * @implements IAddressInfo\n * @constructor\n * @param {PeerRecord.IAddressInfo=} [p] Properties to set\n */\n function AddressInfo(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * AddressInfo multiaddr.\n * @member {Uint8Array} multiaddr\n * @memberof PeerRecord.AddressInfo\n * @instance\n */\n AddressInfo.prototype.multiaddr = $util.newBuffer([]);\n\n /**\n * Encodes the specified AddressInfo message. Does not implicitly {@link PeerRecord.AddressInfo.verify|verify} messages.\n * @function encode\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {PeerRecord.IAddressInfo} m AddressInfo message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n AddressInfo.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.multiaddr != null && Object.hasOwnProperty.call(m, \"multiaddr\"))\n w.uint32(10).bytes(m.multiaddr);\n return w;\n };\n\n /**\n * Decodes an AddressInfo message from the specified reader or buffer.\n * @function decode\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {PeerRecord.AddressInfo} AddressInfo\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n AddressInfo.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.PeerRecord.AddressInfo();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.multiaddr = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an AddressInfo message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {Object.} d Plain object\n * @returns {PeerRecord.AddressInfo} AddressInfo\n */\n AddressInfo.fromObject = function fromObject(d) {\n if (d instanceof $root.PeerRecord.AddressInfo)\n return d;\n var m = new $root.PeerRecord.AddressInfo();\n if (d.multiaddr != null) {\n if (typeof d.multiaddr === \"string\")\n $util.base64.decode(d.multiaddr, m.multiaddr = $util.newBuffer($util.base64.length(d.multiaddr)), 0);\n else if (d.multiaddr.length)\n m.multiaddr = d.multiaddr;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an AddressInfo message. Also converts values to other types if specified.\n * @function toObject\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {PeerRecord.AddressInfo} m AddressInfo\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n AddressInfo.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.multiaddr = \"\";\n else {\n d.multiaddr = [];\n if (o.bytes !== Array)\n d.multiaddr = $util.newBuffer(d.multiaddr);\n }\n }\n if (m.multiaddr != null && m.hasOwnProperty(\"multiaddr\")) {\n d.multiaddr = o.bytes === String ? $util.base64.encode(m.multiaddr, 0, m.multiaddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.multiaddr) : m.multiaddr;\n }\n return d;\n };\n\n /**\n * Converts this AddressInfo to JSON.\n * @function toJSON\n * @memberof PeerRecord.AddressInfo\n * @instance\n * @returns {Object.} JSON object\n */\n AddressInfo.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return AddressInfo;\n })();\n\n return PeerRecord;\n})();\n\nexport { $root as default };\n", null, null, null, "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\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: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\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\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\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'],\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 [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\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\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: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport { CID } from 'multiformats/cid'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport * as Digest from 'multiformats/hashes/digest'\nimport varint from 'varint'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 777: // memory\n return bytes2str(buf)\n\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 uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 777: // memory\n return str2bytes(str)\n\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 uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\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})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\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}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.decode.bytes)\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\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}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\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: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.decode.bytes)\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.decode.bytes)\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\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\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\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}\n\nfunction onion32bytes (str: string): Uint8Array {\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\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}\n\nfunction bytes2onion (buf: Uint8Array): string {\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", "import { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport varint from 'varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\n/**\n * string -> [[str name, str addr]... ]\n */\nexport function stringToStringTuples (str: string): string[][] {\n const tuples = []\n const parts = str.split('/').slice(1) // skip first empty elem\n if (parts.length === 1 && parts[0] === '') {\n return []\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([part])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n tuples.push([\n part,\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 cleanPath(parts.slice(p).join('/'))\n ])\n break\n }\n\n tuples.push([part, parts[p]])\n }\n\n return tuples\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nexport function stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[str name, str addr]... ] -> [[int code, Uint8Array]... ]\n */\nexport function stringTuplesToTuples (tuples: Array): Tuple[] {\n return tuples.map((tup) => {\n if (!Array.isArray(tup)) {\n tup = [tup]\n }\n const proto = protoFromTuple(tup)\n if (tup.length > 1) {\n return [proto.code, convertToBytes(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * Convert tuples to string tuples\n *\n * [[int code, Uint8Array]... ] -> [[int code, str addr]... ]\n */\nexport function tuplesToStringTuples (tuples: Tuple[]): StringTuple[] {\n return tuples.map(tup => {\n const proto = protoFromTuple(tup)\n if (tup[1] != null) {\n return [proto.code, convertToString(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return fromBytes(uint8ArrayConcat(tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n })))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nexport function sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr)\n return size + (varint.decode.bytes ?? 0)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\n/**\n * Uint8Array -> String\n */\nexport function bytesToString (buf: Uint8Array): string {\n const a = bytesToTuples(buf)\n const b = tuplesToStringTuples(a)\n return stringTuplesToString(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function stringToBytes (str: string): Uint8Array {\n str = cleanPath(str)\n const a = stringToStringTuples(str)\n const b = stringTuplesToTuples(a)\n\n return tuplesToBytes(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function fromString (str: string): Uint8Array {\n return stringToBytes(str)\n}\n\n/**\n * Uint8Array -> Uint8Array\n */\nexport function fromBytes (buf: Uint8Array): Uint8Array {\n const err = validateBytes(buf)\n if (err != null) {\n throw err\n }\n return Uint8Array.from(buf) // copy\n}\n\nexport function validateBytes (buf: Uint8Array): Error | undefined {\n try {\n bytesToTuples(buf) // try to parse. will throw if breaks\n } catch (err: any) {\n return err\n }\n}\n\nexport function isValidBytes (buf: Uint8Array): boolean {\n return validateBytes(buf) === undefined\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n\nexport function protoFromTuple (tup: any[]): Protocol {\n const proto = getProtocol(tup[0])\n return proto\n}\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\nimport * as codec from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport varint from 'varint'\nimport { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport errCode from 'err-code'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A Resolver is a function that takes a {@link Multiaddr} and resolves it into one\n * or more string representations of that {@link Multiaddr}.\n */\nexport interface Resolver { (addr: Multiaddr, options?: AbortOptions): Promise }\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString: () => string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON: () => string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions: () => MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos: () => Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes: () => number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames: () => string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples: () => Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples: () => StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate: (addr: MultiaddrInput) => Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate: (addr: Multiaddr | string) => Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode: (code: number) => Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId: () => string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath: () => string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals: (addr: { bytes: Uint8Array }) => boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve: (options?: AbortOptions) => Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress: () => NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress: (addr?: Multiaddr) => boolean\n}\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 */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\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: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\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 DefaultMultiaddr('/' + [ip, host, transport, addr.port].join('/'))\n}\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: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\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: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass DefaultMultiaddr implements Multiaddr {\n public bytes: Uint8Array\n #string?: string\n #tuples?: Tuple[]\n #stringTuples?: StringTuple[]\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n if (addr instanceof Uint8Array) {\n this.bytes = codec.fromBytes(addr)\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 this.bytes = codec.fromString(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n this.bytes = codec.fromBytes(addr.bytes) // validate + copy buffer\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = codec.bytesToString(this.bytes)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\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\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\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\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\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\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\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.protoCodes().map(code => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n const codes: number[] = []\n const buf = this.bytes\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n const size = codec.sizeForAddr(p, buf.slice(i + n))\n\n i += (size + n)\n codes.push(code)\n }\n\n return codes\n }\n\n protoNames (): string[] {\n return this.protos().map(proto => proto.name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n if (this.#tuples == null) {\n this.#tuples = codec.bytesToTuples(this.bytes)\n }\n\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n if (this.#stringTuples == null) {\n this.#stringTuples = codec.tuplesToStringTuples(this.tuples())\n }\n\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new DefaultMultiaddr(addr)\n return new DefaultMultiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\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 DefaultMultiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new DefaultMultiaddr(codec.tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n const tuples = this.stringTuples().filter((tuple) => {\n if (tuple[0] === names.ipfs.code) {\n return true\n }\n return false\n })\n\n // Get the last ipfs tuple ['ipfs', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\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\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n let path = null\n try {\n path = this.stringTuples().filter((tuple) => {\n const proto = getProtocol(tuple[0])\n if (proto.path === true) {\n return true\n }\n return false\n })[0][1]\n\n if (path == null) {\n path = null\n }\n } catch {\n path = null\n }\n return path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: AbortOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const addresses = await resolver(this, options)\n return addresses.map((a) => new DefaultMultiaddr(a))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\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\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\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 /**\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] (): string {\n return `Multiaddr(${codec.bytesToString(this.bytes)})`\n }\n}\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?: MultiaddrInput): Multiaddr {\n return new DefaultMultiaddr(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { migration as migration8 } from './migration-8/index.js'\nimport { migration as migration9 } from './migration-9/index.js'\nimport { migration as migration10 } from './migration-10/index.js'\nimport { migration as migration11 } from './migration-11/index.js'\nimport { migration as migration12 } from './migration-12/index.js'\n\n/**\n * @type {import('../types').Migration}\n */\nconst emptyMigration = {\n description: 'Empty migration.',\n // @ts-ignore\n migrate: () => {},\n // @ts-ignore\n revert: () => {},\n empty: true\n}\n\nexport default [\n Object.assign({ version: 1 }, emptyMigration),\n Object.assign({ version: 2 }, emptyMigration),\n Object.assign({ version: 3 }, emptyMigration),\n Object.assign({ version: 4 }, emptyMigration),\n Object.assign({ version: 5 }, emptyMigration),\n Object.assign({ version: 6 }, emptyMigration),\n Object.assign({ version: 7 }, emptyMigration),\n migration8,\n migration9,\n migration10,\n migration11,\n migration12\n]\n", "\nimport debug from 'debug'\nimport { CONFIG_KEY, VERSION_KEY } from '../utils.js'\nimport { MissingRepoOptionsError } from '../errors.js'\n\nconst log = debug('ipfs:repo:migrator:repo:init')\n\n/**\n * @param {import('../types').Backends} backends\n */\nexport async function isRepoInitialized (backends) {\n if (!backends) {\n throw new MissingRepoOptionsError('Please pass repo options when trying to open a repo')\n }\n\n const root = backends.root\n\n try {\n await root.open()\n const versionCheck = await root.has(VERSION_KEY)\n const configCheck = await root.has(CONFIG_KEY)\n if (!versionCheck || !configCheck) {\n log(`Version entry present: ${versionCheck}`)\n log(`Config entry present: ${configCheck}`)\n return false\n }\n\n return true\n } catch (/** @type {any} */ e) {\n log('While checking if repo is initialized error was thrown: ' + e.message)\n return false\n } finally {\n if (root !== undefined) {\n try {\n await root.close()\n } catch {}\n }\n }\n}\n", "\n/**\n * Exception raised when trying to revert migration that is not possible\n * to revert.\n */\nexport class NonReversibleMigrationError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'NonReversibleMigrationError'\n this.code = NonReversibleMigrationError.code\n this.message = message\n }\n}\nNonReversibleMigrationError.code = 'ERR_NON_REVERSIBLE_MIGRATION'\n\n/**\n * Exception raised when repo is not initialized.\n */\nexport class NotInitializedRepoError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'NotInitializedRepoError'\n this.code = NotInitializedRepoError.code\n this.message = message\n }\n}\nNotInitializedRepoError.code = 'ERR_NOT_INITIALIZED_REPO'\n\n/**\n * Exception raised when required parameter is not provided.\n */\nexport class RequiredParameterError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'RequiredParameterError'\n this.code = RequiredParameterError.code\n this.message = message\n }\n}\nRequiredParameterError.code = 'ERR_REQUIRED_PARAMETER'\n\n/**\n * Exception raised when value is not valid.\n */\nexport class InvalidValueError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'InvalidValueError'\n this.code = InvalidValueError.code\n this.message = message\n }\n}\nInvalidValueError.code = 'ERR_INVALID_VALUE'\n\n/**\n * Exception raised when config is not passed.\n */\nexport class MissingRepoOptionsError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'MissingRepoOptionsError'\n this.code = MissingRepoOptionsError.code\n this.message = message\n }\n}\nMissingRepoOptionsError.code = 'ERR_MISSING_REPO_OPTIONS'\n", "\nimport { isRepoInitialized } from './init.js'\nimport { MissingRepoOptionsError, NotInitializedRepoError } from '../errors.js'\nimport { VERSION_KEY } from '../utils.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\n/**\n * Function that has responsibility to retrieve version of repo from its root datastore's instance.\n * This function needs to be cross-repo-version functional to be able to fetch any version number,\n * even in case of change of repo's versioning.\n *\n * @param {import('../types').Backends} backends\n */\nexport async function getVersion (backends) {\n if (!(await isRepoInitialized(backends))) {\n throw new NotInitializedRepoError('Repo is not initialized!')\n }\n\n const store = backends.root\n await store.open()\n\n try {\n return parseInt(uint8ArrayToString(await store.get(VERSION_KEY)))\n } finally {\n await store.close()\n }\n}\n\n/**\n * Function for setting a version in cross-repo-version manner.\n *\n * @param {number} version\n * @param {import('../types').Backends} backends\n */\nexport async function setVersion (version, backends) {\n if (!backends) {\n throw new MissingRepoOptionsError('Please pass repo options when trying to open a repo')\n }\n\n const store = backends.root\n await store.open()\n await store.put(VERSION_KEY, uint8ArrayFromString(String(version)))\n await store.close()\n}\n", "/* eslint complexity: [\"error\", 28] */\n\nimport defaultMigrations from './migrations/index.js'\nimport * as repoVersion from './repo/version.js'\nimport * as Errors from './errors.js'\nimport { wrapBackends } from './utils.js'\nimport debug from 'debug'\n\nconst log = debug('ipfs:repo:migrator')\n\n/**\n * @typedef {import('./types').Migration} Migration\n * @typedef {import('./types').MigrationOptions} MigrationOptions\n * @typedef {import('./types').ProgressCallback} ProgressCallback\n * @typedef {import('./types').MigrationProgressCallback} MigrationProgressCallback\n */\n\n/**\n * Returns the version of latest migration.\n * If no migrations are present returns 0.\n *\n * @param {Migration[]} [migrations] - Array of migrations to consider. If undefined, the bundled migrations are used. Mainly for testing purpose.\n */\nexport function getLatestMigrationVersion (migrations) {\n migrations = migrations || defaultMigrations\n\n if (!Array.isArray(migrations) || migrations.length === 0) {\n return 0\n }\n\n return migrations[migrations.length - 1].version\n}\n\n/**\n * Main function to execute forward migrations.\n * It acquire lock on the provided path before doing any migrations.\n *\n * Signature of the progress callback is: function(migrationObject: object, currentMigrationNumber: int, totalMigrationsCount: int)\n *\n * @param {string} path - Path to initialized (!) JS-IPFS repo\n * @param {import('./types').Backends} backends\n * @param {import('./types').RepoOptions} repoOptions - Options that are passed to migrations, that can use them to correctly construct datastore. Options are same like for IPFSRepo.\n * @param {number} toVersion - Version to which the repo should be migrated.\n * @param {MigrationOptions} [options] - Options for migration\n */\nexport async function migrate (path, backends, repoOptions, toVersion, options = {}) {\n const ignoreLock = options.ignoreLock ?? false\n const onProgress = options.onProgress\n const isDryRun = options.isDryRun ?? false\n const migrations = options.migrations ?? defaultMigrations\n\n if (!path) {\n throw new errors.RequiredParameterError('Path argument is required!')\n }\n\n if (!repoOptions) {\n throw new errors.RequiredParameterError('repoOptions argument is required!')\n }\n\n if (!toVersion) {\n throw new errors.RequiredParameterError('toVersion argument is required!')\n }\n\n if (!Number.isInteger(toVersion) || toVersion <= 0) {\n throw new errors.InvalidValueError('Version has to be positive integer!')\n }\n\n // make sure we can read pre-level@5 datastores\n backends = wrapBackends(backends)\n\n const currentVersion = await repoVersion.getVersion(backends)\n\n if (currentVersion === toVersion) {\n log('Nothing to migrate.')\n return\n }\n\n if (currentVersion > toVersion) {\n throw new errors.InvalidValueError(`Current repo's version (${currentVersion}) is higher then toVersion (${toVersion}), you probably wanted to revert it?`)\n }\n\n verifyAvailableMigrations(migrations, currentVersion, toVersion)\n\n let lock\n\n if (!isDryRun && !ignoreLock) {\n lock = await repoOptions.repoLock.lock(path)\n }\n\n try {\n for (const migration of migrations) {\n if (toVersion !== undefined && migration.version > toVersion) {\n break\n }\n\n if (migration.version <= currentVersion) {\n continue\n }\n\n log(`Migrating version ${migration.version}`)\n\n try {\n if (!isDryRun) {\n /** @type {MigrationProgressCallback} */\n let progressCallback = () => {}\n\n if (onProgress) { // eslint-disable-line max-depth\n progressCallback = (percent, message) => onProgress(migration.version, percent.toFixed(2), message)\n }\n\n await migration.migrate(backends, progressCallback)\n }\n } catch (/** @type {any} */ e) {\n const lastSuccessfullyMigratedVersion = migration.version - 1\n\n log(`An exception was raised during execution of migration. Setting the repo's version to last successfully migrated version: ${lastSuccessfullyMigratedVersion}`)\n await repoVersion.setVersion(lastSuccessfullyMigratedVersion, backends)\n\n throw new Error(`During migration to version ${migration.version} exception was raised: ${e.stack || e.message || e}`)\n }\n\n log(`Migrating to version ${migration.version} finished`)\n }\n\n if (!isDryRun) {\n await repoVersion.setVersion(toVersion || getLatestMigrationVersion(migrations), backends)\n }\n\n log('Repo successfully migrated', toVersion !== undefined ? `to version ${toVersion}!` : 'to latest version!')\n } finally {\n if (!isDryRun && !ignoreLock && lock) {\n await lock.close()\n }\n }\n}\n\n/**\n * Main function to execute backward migration (reversion).\n * It acquire lock on the provided path before doing any migrations.\n *\n * Signature of the progress callback is: function(migrationObject: object, currentMigrationNumber: int, totalMigrationsCount: int)\n *\n * @param {string} path - Path to initialized (!) JS-IPFS repo\n * @param {import('./types').Backends} backends\n * @param {import('./types').RepoOptions} repoOptions - Options that are passed to migrations, that can use them to correctly construct datastore. Options are same like for IPFSRepo.\n * @param {number} toVersion - Version to which the repo will be reverted.\n * @param {MigrationOptions} [options] - Options for the reversion\n */\nexport async function revert (path, backends, repoOptions, toVersion, options = {}) {\n const ignoreLock = options.ignoreLock ?? false\n const onProgress = options.onProgress\n const isDryRun = options.isDryRun ?? false\n const migrations = options.migrations ?? defaultMigrations\n\n if (!path) {\n throw new errors.RequiredParameterError('Path argument is required!')\n }\n\n if (!repoOptions) {\n throw new errors.RequiredParameterError('repoOptions argument is required!')\n }\n\n if (!toVersion) {\n throw new errors.RequiredParameterError('When reverting migrations, you have to specify to which version to revert!')\n }\n\n if (!Number.isInteger(toVersion) || toVersion <= 0) {\n throw new errors.InvalidValueError('Version has to be positive integer!')\n }\n\n // make sure we can read pre-level@5 datastores\n backends = wrapBackends(backends)\n\n const currentVersion = await repoVersion.getVersion(backends)\n\n if (currentVersion === toVersion) {\n log('Nothing to revert.')\n return\n }\n\n if (currentVersion < toVersion) {\n throw new errors.InvalidValueError(`Current repo's version (${currentVersion}) is lower then toVersion (${toVersion}), you probably wanted to migrate it?`)\n }\n\n verifyAvailableMigrations(migrations, toVersion, currentVersion, true)\n\n let lock\n if (!isDryRun && !ignoreLock) {\n lock = await repoOptions.repoLock.lock(path)\n }\n\n log(`Reverting from version ${currentVersion} to ${toVersion}`)\n\n try {\n const reversedMigrationArray = migrations.slice().reverse()\n\n for (const migration of reversedMigrationArray) {\n if (migration.version <= toVersion) {\n break\n }\n\n if (migration.version > currentVersion) {\n continue\n }\n\n log(`Reverting migration version ${migration.version}`)\n\n try {\n if (!isDryRun) {\n /** @type {MigrationProgressCallback} */\n let progressCallback = () => {}\n\n if (onProgress) { // eslint-disable-line max-depth\n progressCallback = (percent, message) => onProgress(migration.version, percent.toFixed(2), message)\n }\n\n await migration.revert(backends, progressCallback)\n }\n } catch (/** @type {any} */ e) {\n const lastSuccessfullyRevertedVersion = migration.version\n log(`An exception was raised during execution of migration. Setting the repo's version to last successfully reverted version: ${lastSuccessfullyRevertedVersion}`)\n await repoVersion.setVersion(lastSuccessfullyRevertedVersion, backends)\n\n e.message = `During reversion to version ${migration.version} exception was raised: ${e.message}`\n throw e\n }\n\n log(`Reverting to version ${migration.version} finished`)\n }\n\n if (!isDryRun) {\n await repoVersion.setVersion(toVersion, backends)\n }\n\n log(`All migrations successfully reverted to version ${toVersion}!`)\n } finally {\n if (!isDryRun && !ignoreLock && lock) {\n await lock.close()\n }\n }\n}\n\n/**\n * Function checks if all migrations in given range are available.\n *\n * @param {Migration[]} migrations\n * @param {number} fromVersion\n * @param {number} toVersion\n * @param {boolean} checkReversibility - Will additionally checks if all the migrations in the range are reversible\n */\nfunction verifyAvailableMigrations (migrations, fromVersion, toVersion, checkReversibility = false) {\n let migrationCounter = 0\n for (const migration of migrations) {\n if (migration.version > toVersion) {\n break\n }\n\n if (migration.version > fromVersion) {\n if (checkReversibility && !migration.revert) {\n throw new errors.NonReversibleMigrationError(`It is not possible to revert to version ${fromVersion} because migration version ${migration.version} is not reversible. Cancelling reversion.`)\n }\n\n migrationCounter++\n }\n }\n\n if (migrationCounter !== (toVersion - fromVersion)) {\n throw new errors.InvalidValueError(`The ipfs-repo-migrations package does not have all migration to migrate from version ${fromVersion} to ${toVersion}`)\n }\n}\n\nexport const getCurrentRepoVersion = repoVersion.getVersion\nexport const errors = Errors\nexport const migrations = defaultMigrations\n", "\nimport { Key } from 'interface-datastore/key'\nimport debug from 'debug'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { getWithFallback, hasWithFallback } from './utils/level.js'\n\nconst log = debug('ipfs:repo:version')\nconst versionKey = new Key('version')\n\n/**\n *\n * @param {import('interface-datastore').Datastore} store\n */\nexport function version (store) {\n return {\n /**\n * Check if a version file exists.\n *\n */\n async exists () { // eslint-disable-line require-await\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migratiion to v10 or above\n return hasWithFallback(versionKey, store.has.bind(store), store)\n },\n /**\n * Get the current version.\n *\n * @returns {Promise}\n */\n async get () {\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migratiion to v10 or above\n const buf = await getWithFallback(versionKey, store.get.bind(store), store.has.bind(store), store)\n return parseInt(uint8ArrayToString(buf), 10)\n },\n /**\n * Set the version of the repo, writing it to the underlying store.\n *\n * @param {number} version\n * @returns {Promise}\n */\n set (version) {\n return store.put(versionKey, uint8ArrayFromString(String(version)))\n },\n /**\n * Check the current version, and returns true if versions matches\n *\n * @param {number} expected\n */\n async check (expected) {\n const version = await this.get()\n log('comparing version: %s and %s', version, expected)\n // Version 6 and 7 are the same\n // TODO: Clean up the compatibility logic. Repo feature detection would be ideal, or a better version schema\n const compatibleVersion = (version === 6 && expected === 7) || (expected === 6 && version === 7)\n\n return version === expected || compatibleVersion\n }\n }\n}\n", "/**\n * Error raised when there is lock already in place when repo is being opened.\n */\nexport class LockExistsError extends Error {\n /**\n * @param {string} [message]\n */\n constructor (message) {\n super(message)\n this.name = 'LockExistsError'\n this.code = LockExistsError.code\n }\n}\nLockExistsError.code = 'ERR_LOCK_EXISTS'\n\n/**\n * Error raised when requested item is not found.\n */\nexport class NotFoundError extends Error {\n /**\n * @param {string} [message]\n */\n constructor (message) {\n super(message)\n this.name = 'NotFoundError'\n this.code = NotFoundError.code\n }\n}\nNotFoundError.code = 'ERR_NOT_FOUND'\n\n/**\n * Error raised when version of the stored repo is not compatible with version of this package.\n */\nexport class InvalidRepoVersionError extends Error {\n /**\n * @param {string} [message]\n */\n constructor (message) {\n super(message)\n this.name = 'InvalidRepoVersionError'\n this.code = InvalidRepoVersionError.code\n }\n}\nInvalidRepoVersionError.code = 'ERR_INVALID_REPO_VERSION'\n\nexport const ERR_REPO_NOT_INITIALIZED = 'ERR_REPO_NOT_INITIALIZED'\nexport const ERR_REPO_ALREADY_OPEN = 'ERR_REPO_ALREADY_OPEN'\nexport const ERR_REPO_ALREADY_CLOSED = 'ERR_REPO_ALREADY_CLOSED'\n", "\nimport { NotFoundError } from '../errors.js'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Key} Key\n */\n\n/**\n * @param {Key} key\n * @param {function (Key): Promise} has\n * @param {Datastore} store\n * @returns {Promise}\n */\nexport async function hasWithFallback (key, has, store) {\n const result = await has(key)\n\n if (result) {\n return result\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n return false\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n resolve(Boolean(req.result))\n }\n })\n}\n\n/**\n * @param {import('interface-datastore').Key} key\n * @param {function (Key): Promise} get\n * @param {function (Key): Promise} has\n * @param {import('interface-datastore').Datastore} store\n * @returns {Promise}\n */\nexport async function getWithFallback (key, get, has, store) {\n if (await has(key)) {\n return get(key)\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n throw new NotFoundError()\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n if (req.result) {\n return resolve(req.result)\n }\n\n reject(new NotFoundError())\n }\n })\n}\n\n/**\n * Level dbs wrap level dbs that wrap level dbs. Find a level-js\n * instance in the chain if one exists.\n *\n * @param {Datastore} store\n * @returns {Datastore | undefined}\n */\nfunction findLevelJs (store) {\n let db = store\n\n // @ts-ignore\n while (db.db || db.child) {\n // @ts-ignore\n db = db.db || db.child\n\n // `Level` is only present in the browser, in node it is LevelDOWN\n // @ts-ignore\n if (db.type === 'level-js' || db.constructor.name === 'Level') {\n return db\n }\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport PQueue from 'p-queue'\nimport _get from 'just-safe-get'\nimport _set from 'just-safe-set'\nimport errCode from 'err-code'\nimport { NotFoundError } from './errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { getWithFallback, hasWithFallback } from './utils/level.js'\n\n// @ts-ignore types are broken in p-queue@6.x.x - also, if we imported via esm\n// we can use the default, if via cjs we need to get the default via prop access\nconst Queue = PQueue.default ? PQueue.default : PQueue\n\nconst configKey = new Key('config')\n\n/**\n * @typedef {import('./types').Config} Config\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\n/**\n * @param {Datastore} store\n */\nexport function config (store) {\n const setQueue = new Queue({ concurrency: 1 })\n\n const configStore = {\n /**\n * Get the current configuration from the repo.\n *\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config read\n * @returns {Promise}\n */\n async getAll (options = {}) { // eslint-disable-line require-await\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migratiion to v10 or above\n const encodedValue = await getWithFallback(configKey, store.get.bind(store), store.has.bind(store), store)\n\n return JSON.parse(uint8ArrayToString(encodedValue))\n },\n\n /**\n * Get the value for the passed configuration key from the repo.\n *\n * @param {string} key - the config key to get\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config read\n */\n async get (key, options = {}) {\n if (key == null) {\n throw new NotFoundError(`Key ${key} does not exist in config`)\n }\n\n const config = await this.getAll(options)\n const value = _get(config, key)\n\n if (value === undefined) {\n throw new NotFoundError(`Key ${key} does not exist in config`)\n }\n\n return value\n },\n\n /**\n * Set the current configuration for this repo.\n *\n * @param {string} key - the config key to be written\n * @param {any} [value] - the config value to be written\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config write\n */\n set (key, value, options = {}) {\n // @ts-ignore ts thinks key will only be a string, but it may not be\n if (typeof key !== 'string' && !(key instanceof String)) {\n throw errCode(new Error('Invalid key type: ' + typeof key), 'ERR_INVALID_KEY')\n }\n\n if (value === undefined || (value instanceof Uint8Array)) {\n throw errCode(new Error('Invalid value type: ' + typeof value), 'ERR_INVALID_VALUE')\n }\n\n return setQueue.add(() => _maybeDoSet({\n key: key,\n value: value\n }, options.signal))\n },\n\n /**\n * Set the current configuration for this repo.\n *\n * @param {Config} [value] - the config value to be written\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config write\n */\n replace (value, options = {}) {\n if (!value || (value instanceof Uint8Array)) {\n throw errCode(new Error('Invalid value type: ' + typeof value), 'ERR_INVALID_VALUE')\n }\n\n return setQueue.add(() => _maybeDoSet({\n key: undefined,\n value: value\n }, options.signal))\n },\n\n /**\n * Check if a config file exists.\n *\n */\n async exists () { // eslint-disable-line require-await\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migration to v10 or above\n return hasWithFallback(configKey, store.has.bind(store), store)\n }\n }\n\n return configStore\n\n /**\n * @param {{ key: any; value: any; }} m\n * @param {AbortSignal | undefined} signal\n */\n async function _maybeDoSet (m, signal) {\n if (signal && signal.aborted) {\n return\n }\n\n const key = m.key\n const value = m.value\n if (key) {\n const config = await configStore.getAll()\n if (typeof config === 'object' && config !== null) {\n _set(config, key, value)\n }\n return _saveAll(config)\n }\n return _saveAll(value)\n }\n\n /**\n * @param {unknown} config\n */\n function _saveAll (config) {\n const buf = uint8ArrayFromString(JSON.stringify(config, null, 2))\n return store.put(configKey, buf)\n }\n}\n", "export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n", "import isPlainObject from 'is-plain-obj';\n\nexport default function sortKeys(object, options = {}) {\n\tif (!isPlainObject(object) && !Array.isArray(object)) {\n\t\tthrow new TypeError('Expected a plain object or array');\n\t}\n\n\tconst {deep, compare} = options;\n\tconst seenInput = [];\n\tconst seenOutput = [];\n\n\tconst deepSortArray = array => {\n\t\tconst seenIndex = seenInput.indexOf(array);\n\t\tif (seenIndex !== -1) {\n\t\t\treturn seenOutput[seenIndex];\n\t\t}\n\n\t\tconst result = [];\n\t\tseenInput.push(array);\n\t\tseenOutput.push(result);\n\n\t\tresult.push(...array.map(item => {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\treturn deepSortArray(item);\n\t\t\t}\n\n\t\t\tif (isPlainObject(item)) {\n\t\t\t\treturn _sortKeys(item);\n\t\t\t}\n\n\t\t\treturn item;\n\t\t}));\n\n\t\treturn result;\n\t};\n\n\tconst _sortKeys = object => {\n\t\tconst seenIndex = seenInput.indexOf(object);\n\t\tif (seenIndex !== -1) {\n\t\t\treturn seenOutput[seenIndex];\n\t\t}\n\n\t\tconst result = {};\n\t\tconst keys = Object.keys(object).sort(compare);\n\n\t\tseenInput.push(object);\n\t\tseenOutput.push(result);\n\n\t\tfor (const key of keys) {\n\t\t\tconst value = object[key];\n\t\t\tlet newValue;\n\n\t\t\tif (deep && Array.isArray(value)) {\n\t\t\t\tnewValue = deepSortArray(value);\n\t\t\t} else {\n\t\t\t\tnewValue = deep && isPlainObject(value) ? _sortKeys(value) : value;\n\t\t\t}\n\n\t\t\tObject.defineProperty(result, key, {\n\t\t\t\t...Object.getOwnPropertyDescriptor(object, key),\n\t\t\t\tvalue: newValue\n\t\t\t});\n\t\t}\n\n\t\treturn result;\n\t};\n\n\tif (Array.isArray(object)) {\n\t\treturn deep ? deepSortArray(object) : object.slice();\n\t}\n\n\treturn _sortKeys(object);\n}\n", "\nimport { Key } from 'interface-datastore'\nimport sortKeys from 'sort-keys'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst specKey = new Key('datastore_spec')\n\n/**\n *\n * @param {import('interface-datastore').Datastore} store\n */\nexport function spec (store) {\n return {\n /**\n * Check if a datastore spec file exists.\n *\n */\n exists () {\n return store.has(specKey)\n },\n /**\n * Get the current datastore spec.\n *\n * @returns {Promise}\n */\n async get () {\n const buf = await store.get(specKey)\n return JSON.parse(uint8ArrayToString(buf))\n },\n /**\n * Set the datastore spec of the repo, writing it to the underlying store.\n * TODO unclear on what the type should be or if it's required\n *\n * @param {any} spec\n * @returns {Promise}\n */\n async set (spec) {\n return store.put(specKey, uint8ArrayFromString(JSON.stringify(sortKeys(spec, { deep: true }))))\n }\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst apiFile = new Key('api')\n\n/**\n *\n * @param {import('interface-datastore').Datastore} store\n */\nexport function apiAddr (store) {\n return {\n /**\n * Get the current configuration from the repo.\n *\n * @returns {Promise}\n */\n async get () {\n const value = await store.get(apiFile)\n return value && value.toString()\n },\n /**\n * Set the current configuration for this repo.\n * TODO: fix find the proper type or remove this API\n *\n * @param {string} value - the api address to be written\n */\n set (value) {\n return store.put(apiFile, uint8ArrayFromString(value.toString()))\n },\n /**\n * Deletes api file\n */\n delete () {\n return store.delete(apiFile)\n }\n }\n}\n", "\nimport filter from 'it-filter'\nimport { pushable } from 'it-pushable'\nimport drain from 'it-drain'\nimport { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\nimport { identity } from 'multiformats/hashes/identity'\n\n/**\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} DatastoreOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n */\n\n/**\n * @param {Blockstore} store\n * @returns {Blockstore}\n */\nexport function createIdStore (store) {\n return {\n open () {\n return store.open()\n },\n\n close () {\n return store.close()\n },\n\n query (query, options) {\n return store.query(query, options)\n },\n\n queryKeys (query, options) {\n return store.queryKeys(query, options)\n },\n\n async get (cid, options) {\n const extracted = extractContents(cid)\n if (extracted.isIdentity) {\n return Promise.resolve(extracted.digest)\n }\n return store.get(cid, options)\n },\n\n async * getMany (cids, options) {\n for await (const cid of cids) {\n yield this.get(cid, options)\n }\n },\n\n async put (cid, buf, options) {\n const { isIdentity } = extractContents(cid)\n\n if (isIdentity) {\n return\n }\n\n await store.put(cid, buf, options)\n },\n\n async * putMany (pairs, options) {\n // in order to return all blocks. we're going to assemble a seperate iterable\n // return rather than return the resolves of store.putMany using the same\n // process used by blockstore.putMany\n const output = pushable({\n objectMode: true\n })\n\n // process.nextTick runs on the microtask queue, setImmediate runs on the next\n // event loop iteration so is slower. Use process.nextTick if it is available.\n const runner = globalThis.process && globalThis.process.nextTick ? globalThis.process.nextTick : (globalThis.setImmediate || globalThis.setTimeout)\n\n runner(async () => {\n try {\n await drain(store.putMany(async function * () {\n for await (const { key, value } of pairs) {\n if (!extractContents(key).isIdentity) {\n yield { key, value }\n }\n\n // if non identity blocks successfully write, blocks are included in output\n output.push({ key, value })\n }\n }()))\n\n output.end()\n } catch (/** @type {any} */ err) {\n output.end(err)\n }\n })\n\n yield * output\n },\n\n has (cid, options) {\n const { isIdentity } = extractContents(cid)\n if (isIdentity) {\n return Promise.resolve(true)\n }\n return store.has(cid, options)\n },\n\n delete (cid, options) {\n const { isIdentity } = extractContents(cid)\n if (isIdentity) {\n return Promise.resolve()\n }\n return store.delete(cid, options)\n },\n\n deleteMany (cids, options) {\n return store.deleteMany(filter(cids, (cid) => !extractContents(cid).isIdentity), options)\n },\n\n batch () {\n const batch = store.batch()\n\n return {\n put (cid, buf) {\n const { isIdentity } = extractContents(cid)\n\n if (isIdentity) {\n return\n }\n\n batch.put(cid, buf)\n },\n delete (cid) {\n const { isIdentity } = extractContents(cid)\n\n if (isIdentity) {\n return\n }\n\n batch.delete(cid)\n },\n commit: (options) => {\n return batch.commit(options)\n }\n }\n }\n }\n}\n\n/**\n * @param {CID} k\n * @returns {{ isIdentity: false } | { isIdentity: true, digest: Uint8Array}}\n */\nfunction extractContents (k) {\n const cid = CID.asCID(k)\n\n if (cid == null) {\n throw errCode(new Error('Not a valid cid'), 'ERR_INVALID_CID')\n }\n\n if (cid.multihash.code !== identity.code) {\n return {\n isIdentity: false\n }\n }\n\n return {\n isIdentity: true,\n digest: cid.multihash.digest\n }\n}\n", "\nimport { LockExistsError } from '../errors.js'\nimport debug from 'debug'\n\nconst log = debug('ipfs:repo:lock:memory')\nconst lockFile = 'repo.lock'\n\n/** @type {Record} */\nconst LOCKS = {}\n\n/**\n * @typedef {import('../types').LockCloser} LockCloser\n */\n\n/**\n * Lock the repo in the given dir.\n *\n * @param {string} dir\n * @returns {Promise}\n */\nasync function lock (dir) {\n const file = dir + '/' + lockFile\n log('locking %s', file)\n\n if (LOCKS[file] === true) {\n throw new LockExistsError(`Lock already being held for file: ${file}`)\n }\n\n LOCKS[file] = true\n const closer = {\n async close () {\n if (LOCKS[file]) {\n delete LOCKS[file]\n }\n }\n }\n return closer\n}\n\n/**\n * Check if the repo in the given directory is locked.\n *\n * @param {string} dir\n * @returns {Promise}\n */\nasync function locked (dir) {\n const file = dir + '/' + lockFile\n log(`checking lock: ${file}`)\n\n return Boolean(LOCKS[file])\n}\n\nexport const MemoryLock = {\n lock,\n locked\n}\n", "import { MemoryLock } from './locks/memory.js'\n\n/**\n * @type {Partial}\n */\nexport default {\n autoMigrate: true,\n onMigrationProgress: () => {},\n repoOwner: true,\n repoLock: MemoryLock\n}\n", "\n// Default configuration for the datastore spec in node.js\nexport default {\n Spec: {\n type: 'mount',\n mounts: [\n {\n mountpoint: '/blocks',\n type: 'measure',\n prefix: 'flatfs.datastore',\n child: {\n type: 'flatfs',\n path: 'blocks',\n sync: true,\n shardFunc: '/repo/flatfs/shard/v1/next-to-last/2'\n }\n },\n {\n mountpoint: '/',\n type: 'measure',\n prefix: 'leveldb.datastore',\n child: {\n type: 'levelds',\n path: 'datastore',\n compression: 'none'\n }\n }\n ]\n }\n}\n", "/* eslint max-nested-callbacks: [\"error\", 8] */\n\nimport { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\nimport debug from 'debug'\nimport first from 'it-first'\nimport { createUnsafe } from 'multiformats/block'\nimport * as cborg from 'cborg'\nimport * as dagPb from '@ipld/dag-pb'\nimport {\n cidToKey,\n keyToMultihash\n} from './utils/blockstore.js'\nimport { walkDag } from './utils/walk-dag.js'\nimport { PinTypes } from './pin-types.js'\nimport QuickLRU from 'quick-lru'\n\n/**\n * @typedef {import('./types').PinType} PinType\n * @typedef {import('./types').PinQueryType} PinQueryType\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('./types').PinOptions} PinOptions\n * @typedef {import('./types').AbortOptions} AbortOptions\n * @typedef {import('./types').Pins} Pins\n */\n\n/**\n * @typedef {object} PinInternal\n * @property {number} depth\n * @property {import('multiformats/cid').Version} [version]\n * @property {number} [codec]\n * @property {Record} [metadata]\n */\n\n/**\n * @typedef {object} FetchCompleteDagOptions\n * @property {AbortSignal} [signal]\n * @property {number} [cidCacheMaxSize]\n */\n\nconst CID_CACHE_MAX_SIZE = 2048\n\n/**\n * @param {string} type\n */\nfunction invalidPinTypeErr (type) {\n const errMsg = `Invalid type '${type}', must be one of {direct, indirect, recursive, all}`\n return errCode(new Error(errMsg), 'ERR_INVALID_PIN_TYPE')\n}\n\n/**\n * @implements {Pins}\n */\nexport class PinManager {\n /**\n * @param {object} config\n * @param {import('interface-datastore').Datastore} config.pinstore\n * @param {import('interface-blockstore').Blockstore} config.blockstore\n * @param {import('./types').loadCodec} config.loadCodec\n */\n constructor ({ pinstore, blockstore, loadCodec }) {\n this.pinstore = pinstore\n this.blockstore = blockstore\n this.loadCodec = loadCodec\n this.log = debug('ipfs:repo:pin')\n this.directPins = new Set()\n this.recursivePins = new Set()\n }\n\n /**\n * @param {CID} cid\n * @param {PinOptions & AbortOptions} [options]\n */\n async pinDirectly (cid, options = {}) {\n await this.blockstore.get(cid, options)\n\n /** @type {PinInternal} */\n const pin = {\n depth: 0\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n if (options.metadata) {\n pin.metadata = options.metadata\n }\n\n return this.pinstore.put(cidToKey(cid), cborg.encode(pin))\n }\n\n /**\n * @param {CID} cid\n * @param {AbortOptions} [options]\n */\n unpin (cid, options) {\n return this.pinstore.delete(cidToKey(cid), options)\n }\n\n /**\n * @param {CID} cid\n * @param {PinOptions & FetchCompleteDagOptions & AbortOptions} [options]\n */\n async pinRecursively (cid, options = {}) {\n await this.fetchCompleteDag(cid, options)\n\n /** @type {PinInternal} */\n const pin = {\n depth: Infinity\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n if (options.metadata) {\n pin.metadata = options.metadata\n }\n\n await this.pinstore.put(cidToKey(cid), cborg.encode(pin))\n }\n\n /**\n * @param {AbortOptions} [options]\n */\n async * directKeys (options) {\n for await (const entry of this.pinstore.query({\n filters: [(entry) => {\n const pin = cborg.decode(entry.value)\n\n return pin.depth === 0\n }]\n })) {\n const pin = cborg.decode(entry.value)\n const version = pin.version || 0\n const codec = pin.codec != null ? pin.codec : dagPb.code\n const multihash = keyToMultihash(entry.key)\n\n yield {\n cid: CID.create(version, codec, multihash),\n metadata: pin.metadata\n }\n }\n }\n\n /**\n * @param {AbortOptions} [options]\n */\n async * recursiveKeys (options) {\n for await (const entry of this.pinstore.query({\n filters: [(entry) => {\n const pin = cborg.decode(entry.value)\n\n return pin.depth === Infinity\n }]\n })) {\n const pin = cborg.decode(entry.value)\n const version = pin.version || 0\n const codec = pin.codec != null ? pin.codec : dagPb.code\n const multihash = keyToMultihash(entry.key)\n\n yield {\n cid: CID.create(version, codec, multihash),\n metadata: pin.metadata\n }\n }\n }\n\n /**\n * @param {AbortOptions} [options]\n */\n async * indirectKeys (options) {\n for await (const { cid } of this.recursiveKeys()) {\n for await (const childCid of walkDag(cid, this.blockstore, this.loadCodec, options)) {\n // recursive pins override indirect pins\n const types = [\n PinTypes.recursive\n ]\n\n const result = await this.isPinnedWithType(childCid, types)\n\n if (result.pinned) {\n continue\n }\n\n yield childCid\n }\n }\n }\n\n /**\n * @param {CID} cid\n * @param {PinQueryType|PinQueryType[]} types\n * @param {AbortOptions} [options]\n */\n async isPinnedWithType (cid, types, options) {\n if (!Array.isArray(types)) {\n types = [types]\n }\n\n const all = types.includes(PinTypes.all)\n const direct = types.includes(PinTypes.direct)\n const recursive = types.includes(PinTypes.recursive)\n const indirect = types.includes(PinTypes.indirect)\n\n if (recursive || direct || all) {\n const result = await first(this.pinstore.query({\n prefix: cidToKey(cid).toString(),\n filters: [entry => {\n if (all) {\n return true\n }\n\n const pin = cborg.decode(entry.value)\n\n return types.includes(pin.depth === 0 ? PinTypes.direct : PinTypes.recursive)\n }],\n limit: 1\n }))\n\n if (result) {\n const pin = cborg.decode(result.value)\n\n return {\n cid,\n pinned: true,\n reason: pin.depth === 0 ? PinTypes.direct : PinTypes.recursive,\n metadata: pin.metadata\n }\n }\n }\n\n const self = this\n\n /**\n * @param {CID} key\n * @param {AsyncIterable<{ cid: CID, metadata: any }>} source\n */\n async function * findChild (key, source) {\n for await (const { cid: parentCid } of source) {\n for await (const childCid of walkDag(parentCid, self.blockstore, self.loadCodec)) {\n if (childCid.equals(key)) {\n yield parentCid\n return\n }\n }\n }\n }\n\n if (all || indirect) {\n // indirect (default)\n // check each recursive key to see if multihash is under it\n\n const parentCid = await first(findChild(cid, this.recursiveKeys()))\n\n if (parentCid) {\n return {\n cid,\n pinned: true,\n reason: PinTypes.indirect,\n parent: parentCid\n }\n }\n }\n\n return {\n cid,\n pinned: false\n }\n }\n\n /**\n * @param {CID} cid\n * @param {FetchCompleteDagOptions} [options]\n */\n async fetchCompleteDag (cid, options = {}) {\n const seen = new QuickLRU({ maxSize: options.cidCacheMaxSize ?? CID_CACHE_MAX_SIZE })\n\n /**\n * @param {CID} cid\n * @param {AbortOptions} options\n */\n const walkDag = async (cid, options) => {\n if (seen.has(cid.toString())) {\n return\n }\n\n seen.set(cid.toString(), true)\n\n const bytes = await this.blockstore.get(cid, options)\n const codec = await this.loadCodec(cid.code)\n const block = createUnsafe({ bytes, cid, codec })\n\n await Promise.all(\n [...block.links()].map(([, childCid]) => walkDag(childCid, options))\n )\n }\n\n await walkDag(cid, options)\n }\n\n /**\n * Throws an error if the pin type is invalid\n *\n * @param {any} type\n * @returns {type is PinType}\n */\n static checkPinType (type) {\n if (typeof type !== 'string' || !Object.keys(PinTypes).includes(type)) {\n throw invalidPinTypeErr(type)\n }\n return true\n }\n}\n", "\n/**\n * Returns the first result from an (async) iterable, unless empty, in which\n * case returns `undefined`\n */\nexport default async function first (source: AsyncIterable|Iterable): Promise {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry\n }\n\n return undefined\n}\n", "import { bytes as binary, CID } from './index.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\n\nfunction readonly ({ enumerable = true, configurable = false } = {}) {\n return { enumerable, configurable, writable: false }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable<[string, CID]>}\n */\nfunction * linksWithin (path, value) {\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n if (cid) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n if (cid) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable<[string, CID]>}\n */\nfunction * links (source, base) {\n if (source == null || source instanceof Uint8Array) {\n return\n }\n const cid = CID.asCID(source)\n if (cid) {\n yield [base.join('/'), cid]\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield * linksWithin(path, value)\n }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable}\n */\nfunction * treeWithin (path, value) {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n yield elementPath.join('/')\n if (typeof element === 'object' && !CID.asCID(element)) {\n yield * tree(element, elementPath)\n }\n }\n } else {\n yield * tree(value, path)\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable}\n */\nfunction * tree (source, base) {\n if (source == null || typeof source !== 'object') {\n return\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield path.join('/')\n if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && !CID.asCID(value)) {\n yield * treeWithin(path, value)\n }\n }\n}\n\n/**\n *\n * @template T\n * @param {T} source\n * @param {string[]} path\n * @returns {API.BlockCursorView}\n */\nfunction get (source, path) {\n let node = /** @type {Record} */(source)\n for (const [index, key] of path.entries()) {\n node = node[key]\n if (node == null) {\n throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)\n }\n const cid = CID.asCID(node)\n if (cid) {\n return { value: cid, remaining: path.slice(index + 1).join('/') }\n }\n }\n return { value: node }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} C - multicodec code corresponding to codec used to encode the block\n * @template {number} A - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @implements {API.BlockView}\n */\nclass Block {\n /**\n * @param {object} options\n * @param {CID} options.cid\n * @param {API.ByteView} options.bytes\n * @param {T} options.value\n */\n constructor ({ cid, bytes, value }) {\n if (!cid || !bytes || typeof value === 'undefined') { throw new Error('Missing required argument') }\n\n this.cid = cid\n this.bytes = bytes\n this.value = value\n this.asBlock = this\n\n // Mark all the properties immutable\n Object.defineProperties(this, {\n cid: readonly(),\n bytes: readonly(),\n value: readonly(),\n asBlock: readonly()\n })\n }\n\n links () {\n return links(this.value, [])\n }\n\n tree () {\n return tree(this.value, [])\n }\n\n /**\n *\n * @param {string} [path]\n * @returns {API.BlockCursorView}\n */\n get (path = '/') {\n return get(this.value, path.split('/').filter(Boolean))\n }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {T} options.value\n * @param {API.BlockEncoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function encode ({ value, codec, hasher }) {\n if (typeof value === 'undefined') throw new Error('Missing required argument \"value\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const bytes = codec.encode(value)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(\n 1,\n codec.code,\n hash\n )\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function decode ({ bytes, codec, hasher }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(1, codec.code, hash)\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @typedef {object} RequiredCreateOptions\n * @property {CID} options.cid\n */\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {{ cid: API.Link, value:T, codec?: API.BlockDecoder, bytes: API.ByteView }|{cid:API.Link, bytes:API.ByteView, value?:void, codec:API.BlockDecoder}} options\n * @returns {API.BlockView}\n */\nfunction createUnsafe ({ bytes, cid, value: maybeValue, codec }) {\n const value = maybeValue !== undefined\n ? maybeValue\n : (codec && codec.decode(bytes))\n\n if (value === undefined) throw new Error('Missing required argument, must either provide \"value\" or \"codec\"')\n\n return new Block({\n // eslint-disable-next-line object-shorthand\n cid: /** @type {CID} */ (cid),\n bytes,\n value\n })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {object} options\n * @param {API.Link} options.cid\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function create ({ bytes, cid, hasher, codec }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!hasher) throw new Error('Missing required argument \"hasher\"')\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error('CID hash does not match bytes')\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec\n })\n}\n\nexport { encode, decode, create, createUnsafe, Block }\n", "import { Key } from 'interface-datastore/key'\nimport { CID } from 'multiformats'\nimport * as raw from 'multiformats/codecs/raw'\nimport errCode from 'err-code'\nimport { base32 } from 'multiformats/bases/base32'\nimport * as Digest from 'multiformats/hashes/digest'\n\n/**\n * Transform a cid to the appropriate datastore key.\n *\n * @param {CID} c\n */\nexport function cidToKey (c) {\n const cid = CID.asCID(c)\n\n if (cid == null) {\n throw errCode(new Error('Not a valid cid'), 'ERR_INVALID_CID')\n }\n\n const encoded = base32.encode(cid.multihash.bytes)\n\n return new Key('/' + encoded.slice(1).toUpperCase(), false)\n}\n\n/**\n * Transform a datastore Key instance to a CID\n * As Key is a multihash of the CID, it is reconstructed using IPLD's RAW codec.\n * Hence it is highly probable that stored CID will differ from a CID retrieved from blockstore.\n *\n * @param {Key} key\n */\nexport function keyToCid (key) {\n // Block key is of the form /\n return CID.createV1(raw.code, keyToMultihash(key))\n}\n\n/**\n * @param {Key | string} key\n */\nexport function keyToMultihash (key) {\n return Digest.decode(base32.decode(`b${key.toString().toLowerCase().substring(1)}`))\n}\n", "import debug from 'debug'\nimport { createUnsafe } from 'multiformats/block'\n\nconst log = debug('ipfs:repo:utils:walk-dag')\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../types').loadCodec} loadCodec\n * @typedef {import('../types').AbortOptions} AbortOptions\n */\n\n/**\n * @param {CID} cid\n * @param {Blockstore} blockstore\n * @param {loadCodec} loadCodec\n * @param {AbortOptions} [options]\n * @returns {AsyncGenerator}\n */\nexport async function * walkDag (cid, blockstore, loadCodec, options) {\n try {\n const bytes = await blockstore.get(cid, options)\n const codec = await loadCodec(cid.code)\n const block = createUnsafe({ bytes, cid, codec })\n\n for (const [, childCid] of block.links()) {\n yield childCid\n yield * walkDag(childCid, blockstore, loadCodec, options)\n }\n } catch (/** @type {any} */ err) {\n log('Could not walk DAG for CID', cid.toString(), err)\n\n throw err\n }\n}\n", "export default class QuickLRU extends Map {\n\tconstructor(options = {}) {\n\t\tsuper();\n\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tif (typeof options.maxAge === 'number' && options.maxAge === 0) {\n\t\t\tthrow new TypeError('`maxAge` must be a number greater than 0');\n\t\t}\n\n\t\t// TODO: Use private class fields when ESLint supports them.\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.maxAge = options.maxAge || Number.POSITIVE_INFINITY;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t// TODO: Use private class methods when targeting Node.js 16.\n\t_emitEvictions(cache) {\n\t\tif (typeof this.onEviction !== 'function') {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const [key, item] of cache) {\n\t\t\tthis.onEviction(key, item.value);\n\t\t}\n\t}\n\n\t_deleteIfExpired(key, item) {\n\t\tif (typeof item.expiry === 'number' && item.expiry <= Date.now()) {\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tthis.onEviction(key, item.value);\n\t\t\t}\n\n\t\t\treturn this.delete(key);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t_getOrDeleteIfExpired(key, item) {\n\t\tconst deleted = this._deleteIfExpired(key, item);\n\t\tif (deleted === false) {\n\t\t\treturn item.value;\n\t\t}\n\t}\n\n\t_getItemValue(key, item) {\n\t\treturn item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;\n\t}\n\n\t_peek(key, cache) {\n\t\tconst item = cache.get(key);\n\n\t\treturn this._getItemValue(key, item);\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\t\t\tthis._emitEvictions(this.oldCache);\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\t_moveToRecent(key, item) {\n\t\tthis.oldCache.delete(key);\n\t\tthis._set(key, item);\n\t}\n\n\t* _entriesAscending() {\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield item;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.cache) {\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\tconst item = this.cache.get(key);\n\n\t\t\treturn this._getItemValue(key, item);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst item = this.oldCache.get(key);\n\t\t\tif (this._deleteIfExpired(key, item) === false) {\n\t\t\t\tthis._moveToRecent(key, item);\n\t\t\t\treturn item.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tset(key, value, {maxAge = this.maxAge} = {}) {\n\t\tconst expiry =\n\t\t\ttypeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?\n\t\t\t\tDate.now() + maxAge :\n\t\t\t\tundefined;\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, {\n\t\t\t\tvalue,\n\t\t\t\texpiry\n\t\t\t});\n\t\t} else {\n\t\t\tthis._set(key, {value, expiry});\n\t\t}\n\t}\n\n\thas(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn !this._deleteIfExpired(key, this.cache.get(key));\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn !this._deleteIfExpired(key, this.oldCache.get(key));\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this._peek(key, this.cache);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this._peek(key, this.oldCache);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\tresize(newSize) {\n\t\tif (!(newSize && newSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tconst items = [...this._entriesAscending()];\n\t\tconst removeCount = items.length - newSize;\n\t\tif (removeCount < 0) {\n\t\t\tthis.cache = new Map(items);\n\t\t\tthis.oldCache = new Map();\n\t\t\tthis._size = items.length;\n\t\t} else {\n\t\t\tif (removeCount > 0) {\n\t\t\t\tthis._emitEvictions(items.slice(0, removeCount));\n\t\t\t}\n\n\t\t\tthis.oldCache = new Map(items.slice(removeCount));\n\t\t\tthis.cache = new Map();\n\t\t\tthis._size = 0;\n\t\t}\n\n\t\tthis.maxSize = newSize;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield [key, value.value];\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t* entriesDescending() {\n\t\tlet items = [...this.cache];\n\t\tfor (let i = items.length - 1; i >= 0; --i) {\n\t\t\tconst item = items[i];\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield [key, value.value];\n\t\t\t}\n\t\t}\n\n\t\titems = [...this.oldCache];\n\t\tfor (let i = items.length - 1; i >= 0; --i) {\n\t\t\tconst item = items[i];\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t* entriesAscending() {\n\t\tfor (const [key, value] of this._entriesAscending()) {\n\t\t\tyield [key, value.value];\n\t\t}\n\t}\n\n\tget size() {\n\t\tif (!this._size) {\n\t\t\treturn this.oldCache.size;\n\t\t}\n\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n\n\tentries() {\n\t\treturn this.entriesAscending();\n\t}\n\n\tforEach(callbackFunction, thisArgument = this) {\n\t\tfor (const [key, value] of this.entriesAscending()) {\n\t\t\tcallbackFunction.call(thisArgument, value, key, this);\n\t\t}\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn JSON.stringify([...this.entriesAscending()]);\n\t}\n}\n", "\nimport map from 'it-map'\nimport errCode from 'err-code'\nimport { PinTypes } from './pin-types.js'\n\n/**\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} DatastoreOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('./pin-manager').Pins} Pins\n */\n\n/**\n * @param {Pins} pins\n * @param {Blockstore} store\n * @returns {Blockstore}\n */\nexport function createPinnedBlockstore (pins, store) {\n return {\n open () {\n return store.open()\n },\n\n close () {\n return store.close()\n },\n\n query (query, options) {\n return store.query(query, options)\n },\n\n queryKeys (query, options) {\n return store.queryKeys(query, options)\n },\n\n async get (cid, options) {\n return store.get(cid, options)\n },\n\n async * getMany (cids, options) {\n yield * store.getMany(cids, options)\n },\n\n async put (cid, buf, options) {\n await store.put(cid, buf, options)\n },\n\n async * putMany (pairs, options) {\n yield * store.putMany(pairs, options)\n },\n\n has (cid, options) {\n return store.has(cid, options)\n },\n\n async delete (cid, options) {\n await ensureNotPinned(cid, pins)\n\n return store.delete(cid, options)\n },\n\n deleteMany (cids, options) {\n return store.deleteMany(map(cids, async cid => {\n await ensureNotPinned(cid, pins)\n\n return cid\n }), options)\n },\n\n batch () {\n return store.batch()\n }\n }\n}\n\n/**\n * @param {CID} cid\n * @param {Pins} pins\n */\nasync function ensureNotPinned (cid, pins) {\n const { pinned, reason } = await pins.isPinnedWithType(cid, PinTypes.all)\n\n if (pinned) {\n throw errCode(new Error(`pinned: ${reason}`), 'ERR_BLOCK_PINNED')\n }\n}\n", "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 cancelablePromise = 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 (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\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\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} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\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", "\nexport 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'\n\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", "import { nanoid } from 'nanoid'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport observer from 'observable-webworkers'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n return await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return await new Promise((resolve) => {\n const listener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\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\n return emitter\n }\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", "import PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock: () => Promise\n writeLock: () => Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock: (name: string, options: MorticeOptions) => Mortice['readLock']\n writeLock: (name: string, options: MorticeOptions) => Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => await pTimeout((async () => {\n return await new Promise((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return await p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\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 await createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\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\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 return await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return await 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\n return await createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler: () => Promise\n}\n\nexport default function createMortice (options?: MorticeOptions) {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n", "\nimport { CID } from 'multiformats/cid'\nimport debug from 'debug'\nimport { notFoundError } from 'datastore-core/errors'\nimport parallelBatch from 'it-parallel-batch'\nimport { pipe } from 'it-pipe'\nimport merge from 'it-merge'\nimport map from 'it-map'\nimport filter from 'it-filter'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { walkDag } from './utils/walk-dag.js'\n\nconst log = debug('ipfs:repo:gc')\nconst ERR_NOT_FOUND = notFoundError().code\n\n// Limit on the number of parallel block remove operations\nconst BLOCK_RM_CONCURRENCY = 256\n\nconst MFS_ROOT_KEY = new Key('/local/filesroot')\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').loadCodec} loadCodec\n * @typedef {import('./types').GCErrorResult} GCErrorResult\n * @typedef {import('./types').GCSuccessResult} GCSuccessResult\n */\n\n/**\n * Perform mark and sweep garbage collection\n *\n * @param {object} config\n * @param {import('./types').GCLock} config.gcLock\n * @param {import('./types').Pins} config.pins\n * @param {Blockstore} config.blockstore\n * @param {import('interface-datastore').Datastore} config.root\n * @param {loadCodec} config.loadCodec\n */\nexport function gc ({ gcLock, pins, blockstore, root, loadCodec }) {\n /**\n * @returns {AsyncGenerator}\n */\n async function * gc () {\n const start = Date.now()\n log('Creating set of marked blocks')\n\n const release = await gcLock.writeLock()\n\n try {\n // Mark all blocks that are being used\n const markedSet = await createMarkedSet({ pins, blockstore, root, loadCodec })\n // Get all blocks keys from the blockstore\n const blockKeys = blockstore.queryKeys({})\n\n // Delete blocks that are not being used\n // @ts-ignore ts cannot tell that we filter out null results\n yield * deleteUnmarkedBlocks({ blockstore }, markedSet, blockKeys)\n\n log(`Complete (${Date.now() - start}ms)`)\n } finally {\n release()\n }\n }\n\n return gc\n}\n\n/**\n * Get Set of CIDs of blocks to keep\n *\n * @param {object} config\n * @param {import('./pin-manager').Pins} config.pins\n * @param {import('interface-blockstore').Blockstore} config.blockstore\n * @param {import('interface-datastore').Datastore} config.root\n * @param {loadCodec} config.loadCodec\n */\nasync function createMarkedSet ({ pins, blockstore, loadCodec, root }) {\n const mfsSource = (async function * () {\n let mh\n try {\n mh = await root.get(MFS_ROOT_KEY)\n } catch (/** @type {any} */ err) {\n if (err.code === ERR_NOT_FOUND) {\n log('No blocks in MFS')\n return\n }\n\n throw err\n }\n\n const rootCid = CID.decode(mh)\n yield rootCid\n yield * walkDag(rootCid, blockstore, loadCodec)\n })()\n\n const pinsSource = merge(\n map(pins.recursiveKeys(), ({ cid }) => cid),\n pins.indirectKeys(),\n map(pins.directKeys(), ({ cid }) => cid),\n mfsSource\n )\n\n const output = new Set()\n\n for await (const cid of merge(pinsSource, mfsSource)) {\n output.add(base32.encode(cid.multihash.bytes))\n }\n\n return output\n}\n\n/**\n * Delete all blocks that are not marked as in use\n *\n * @param {object} arg\n * @param {Blockstore} arg.blockstore\n * @param {Set} markedSet\n * @param {AsyncIterable} blockKeys\n */\nasync function * deleteUnmarkedBlocks ({ blockstore }, markedSet, blockKeys) {\n // Iterate through all blocks and find those that are not in the marked set\n // blockKeys yields { key: Key() }\n let blocksCount = 0\n let removedBlocksCount = 0\n\n /**\n * @param {CID} cid\n */\n const removeBlock = async (cid) => {\n return async function remove () {\n blocksCount++\n\n try {\n const b32 = base32.encode(cid.multihash.bytes)\n\n if (markedSet.has(b32)) {\n return null\n }\n\n try {\n await blockstore.delete(cid)\n removedBlocksCount++\n } catch (/** @type {any} */ err) {\n return {\n err: new Error(`Could not delete block with CID ${cid}: ${err.message}`)\n }\n }\n\n return { cid }\n } catch (/** @type {any} */ err) {\n const msg = `Could delete block with CID ${cid}`\n log(msg, err)\n return { err: new Error(msg + `: ${err.message}`) }\n }\n }\n }\n\n yield * pipe(\n parallelBatch(map(blockKeys, removeBlock), BLOCK_RM_CONCURRENCY),\n // filter nulls (blocks that were retained)\n source => filter(source, Boolean)\n )\n\n log(`Marked set has ${markedSet.size} unique blocks. Blockstore has ${blocksCount} blocks. ` +\n `Deleted ${removedBlocksCount} blocks.`)\n}\n", "/**\n * Takes an (async) iterable that emits things and returns an async iterable that\n * emits those things in fixed-sized batches\n */\nexport default async function * batch (source: AsyncIterable | Iterable, size: number = 1): AsyncGenerator {\n let things: T[] = []\n\n if (size < 1) {\n size = 1\n }\n\n for await (const thing of source) {\n things.push(thing)\n\n while (things.length >= size) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n }\n\n while (things.length > 0) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n}\n", "import batch from 'it-batch'\n\ninterface Success {\n ok: true\n value: T\n}\n\ninterface Failure {\n ok: false\n err: Error\n}\n\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 * parallelBatch (source: AsyncIterable<() => Promise>|Iterable<() => Promise>, size: number = 1): AsyncGenerator {\n for await (const tasks of batch(source, size)) {\n const things: Array|Failure>> = tasks.map(\n async (p: () => Promise) => {\n return await p().then(value => ({ ok: true, value }), err => ({ ok: false, err }))\n })\n\n for (let i = 0; i < things.length; i++) {\n const result = await things[i]\n\n if (result.ok) {\n yield result.value\n } else {\n throw result.err\n }\n }\n }\n}\n", "import all from 'it-all'\n\nexport interface CompareFunction {\n (a: T, b: T): number\n}\n\n/**\n * Collects all values from an async iterator, sorts them\n * using the passed function and yields them\n */\nexport default async function * sort (source: AsyncIterable | Iterable, sorter: CompareFunction): AsyncGenerator {\n const arr = await all(source)\n\n yield * arr.sort(sorter)\n}\n", "import { Key } from 'interface-datastore'\nimport { BaseDatastore, Errors } from 'datastore-core'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport take from 'it-take'\nimport sort from 'it-sort'\nimport { Level } from 'level'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Batch} Batch\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Options} QueryOptions\n * @typedef {import('abstract-level').AbstractLevel} LevelDb\n */\n\n/**\n * A datastore backed by leveldb\n */\nexport class LevelDatastore extends BaseDatastore {\n /**\n * @param {string | LevelDb} path\n * @param {import('level').DatabaseOptions & import('level').OpenOptions} [opts]\n */\n constructor (path, opts = {}) {\n super()\n\n /** @type {LevelDb} */\n this.db = typeof path === 'string'\n ? new Level(path, {\n ...opts,\n keyEncoding: 'utf8',\n valueEncoding: 'view'\n })\n : path\n\n /** @type {import('level').OpenOptions} */\n this.opts = {\n createIfMissing: true,\n compression: false, // same default as go\n ...opts\n }\n }\n\n async open () {\n try {\n await this.db.open(this.opts)\n } catch (/** @type {any} */ err) {\n throw Errors.dbOpenFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} value\n */\n async put (key, value) {\n try {\n await this.db.put(key.toString(), value)\n } catch (/** @type {any} */ err) {\n throw Errors.dbWriteFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @returns {Promise}\n */\n async get (key) {\n let data\n try {\n data = await this.db.get(key.toString())\n } catch (/** @type {any} */ err) {\n if (err.notFound) throw Errors.notFoundError(err)\n throw Errors.dbWriteFailedError(err)\n }\n return data\n }\n\n /**\n * @param {Key} key\n * @returns {Promise}\n */\n async has (key) {\n try {\n await this.db.get(key.toString())\n } catch (/** @type {any} */ err) {\n if (err.notFound) return false\n throw err\n }\n return true\n }\n\n /**\n * @param {Key} key\n * @returns {Promise}\n */\n async delete (key) {\n try {\n await this.db.del(key.toString())\n } catch (/** @type {any} */ err) {\n throw Errors.dbDeleteFailedError(err)\n }\n }\n\n close () {\n return this.db && this.db.close()\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Array<{ type: 'put', key: string, value: Uint8Array; } | { type: 'del', key: string }>} */\n const ops = []\n return {\n put: (key, value) => {\n ops.push({\n type: 'put',\n key: key.toString(),\n value: value\n })\n },\n delete: (key) => {\n ops.push({\n type: 'del',\n key: key.toString()\n })\n },\n commit: () => {\n return this.db.batch(ops)\n }\n }\n }\n\n /**\n * @param {Query} q\n */\n query (q) {\n let it = this._query({\n values: true,\n prefix: q.prefix\n })\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n const { offset, limit } = q\n if (offset) {\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (limit) {\n it = take(it, limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n */\n queryKeys (q) {\n let it = map(this._query({\n values: false,\n prefix: q.prefix\n }), ({ key }) => key)\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n const { offset, limit } = q\n if (offset) {\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (limit) {\n it = take(it, limit)\n }\n\n return it\n }\n\n /**\n * @param {object} opts\n * @param {boolean} opts.values\n * @param {string} [opts.prefix]\n * @returns {AsyncIterable}\n */\n _query (opts) {\n /** @type {import('level').IteratorOptions} */\n const iteratorOpts = {\n keys: true,\n keyEncoding: 'buffer',\n values: opts.values\n }\n\n // Let the db do the prefix matching\n if (opts.prefix != null) {\n const prefix = opts.prefix.toString()\n // Match keys greater than or equal to `prefix` and\n iteratorOpts.gte = prefix\n // less than `prefix` + \\xFF (hex escape sequence)\n iteratorOpts.lt = prefix + '\\xFF'\n }\n\n const iterator = this.db.iterator(iteratorOpts)\n\n if (iterator[Symbol.asyncIterator]) {\n return levelIteratorToIterator(iterator)\n }\n\n // @ts-expect-error support older level\n if (iterator.next != null && iterator.end != null) {\n // @ts-expect-error support older level\n return oldLevelIteratorToIterator(iterator)\n }\n\n throw new Error('Level returned incompatible iterator')\n }\n}\n\n/**\n * @param {import('level').Iterator} li - Level iterator\n * @returns {AsyncIterable}\n */\nasync function * levelIteratorToIterator (li) {\n for await (const [key, value] of li) {\n yield { key: new Key(key, false), value }\n }\n\n await li.close()\n}\n\n/**\n * @typedef {object} LevelIterator\n * @property {(cb: (err: Error, key: string | Uint8Array | null, value: any)=> void)=>void} next\n * @property {(cb: (err: Error) => void) => void } end\n */\n\n/**\n * @param {LevelIterator} li - Level iterator\n * @returns {AsyncIterable}\n */\nfunction oldLevelIteratorToIterator (li) {\n return {\n [Symbol.asyncIterator] () {\n return {\n next: () => new Promise((resolve, reject) => {\n li.next((err, key, value) => {\n if (err) return reject(err)\n if (key == null) {\n return li.end(err => {\n if (err) return reject(err)\n resolve({ done: true, value: undefined })\n })\n }\n resolve({ done: false, value: { key: new Key(key, false), value } })\n })\n }),\n return: () => new Promise((resolve, reject) => {\n li.end(err => {\n if (err) return reject(err)\n resolve({ done: true, value: undefined })\n })\n })\n }\n }\n }\n}\n", "import drain from 'it-drain'\nimport { pushable } from 'it-pushable'\nimport { Key } from 'interface-datastore/key'\nimport { CID } from 'multiformats/cid'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { base32, base32pad } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport errcode from 'err-code'\nimport { BaseBlockstore } from 'blockstore-core/base'\n\n/**\n * Transform a cid to the appropriate datastore key.\n *\n * @param {CID} cid\n * @returns {Key}\n */\nfunction cidToKey (cid) {\n const c = CID.asCID(cid)\n\n if (!c) {\n throw errcode(new Error('Not a valid cid'), 'ERR_INVALID_CID')\n }\n\n return new Key('/' + base32.encode(c.multihash.bytes).slice(1).toUpperCase(), false)\n}\n\n/**\n * Transform a datastore Key instance to a CID\n * As Key is a multihash of the CID, it is reconstructed using IPLD's RAW codec.\n * Hence it is highly probable that stored CID will differ from a CID retrieved from blockstore.\n *\n * @param {Key} key\n * @returns {CID}\n */\nfunction keyToCid (key) {\n // Block key is of the form \n return CID.createV1(raw.code, Digest.decode(base32.decode('b' + key.toString().slice(1).toLowerCase())))\n}\n\n/**\n * Tries to decode a prefix as the first part of a CID and then\n * strip off the version and codec bytes to just leave part of\n * the multihash.\n *\n * Only really works if the prefix length aligns with the byte\n * boundaries of the encoding.\n *\n * @param {string} prefix\n * @returns {string}\n */\nfunction convertPrefix (prefix) {\n const firstChar = prefix.substring(0, 1)\n\n if (firstChar === '/') {\n return convertPrefix(prefix.substring(1))\n }\n\n /** @type {(input: string) => Uint8Array } */\n let decoder\n\n if (firstChar.toLowerCase() === 'b') {\n // v1 cid prefix, remove version and codec bytes\n decoder = (input) => base32.decode(input.toLowerCase()).subarray(2)\n } else if (firstChar.toLowerCase() === 'c') {\n // v1 cid prefix, remove version and codec bytes\n decoder = (input) => base32pad.decode(input.toLowerCase()).subarray(2)\n } else if (firstChar === 'z') {\n // v1 cid\n decoder = (input) => base58btc.decode(input).subarray(2)\n } else if (firstChar === 'Q') {\n // v0 cid prefix\n decoder = (input) => base58btc.decode('z' + input)\n } else {\n decoder = (input) => base32.decode('b' + input.toLowerCase()).subarray(2)\n }\n\n let bytes\n\n // find the longest prefix that we can safely decode\n for (let i = 1; i < prefix.length; i++) {\n try {\n bytes = decoder(prefix.substring(0, i))\n } catch (/** @type {any} */ err) {\n if (err.message !== 'Unexpected end of data') {\n throw err\n }\n }\n }\n\n let str = '/C'\n\n if (bytes) {\n // slice one character from the end of the string to ensure we don't end up\n // with a padded value which could have a non-matching string at the end\n str = `/${base32.encode(bytes).slice(1, -1).toUpperCase() || 'C'}`\n }\n\n return str\n}\n\n/**\n * @param {import('interface-blockstore').Query} query\n * @returns {import('interface-datastore').Query}\n */\nfunction convertQuery (query) {\n return {\n ...query,\n prefix: query.prefix ? convertPrefix(query.prefix) : undefined,\n filters: query.filters\n ? query.filters.map(\n filter => (pair) => {\n return filter({ key: keyToCid(pair.key), value: pair.value })\n }\n )\n : undefined,\n orders: query.orders\n ? query.orders.map(\n order => (a, b) => {\n return order({ key: keyToCid(a.key), value: a.value }, { key: keyToCid(b.key), value: b.value })\n }\n )\n : undefined\n }\n}\n\n/**\n * @param {import('interface-blockstore').KeyQuery} query\n * @returns {import('interface-datastore').KeyQuery}\n */\nfunction convertKeyQuery (query) {\n return {\n ...query,\n prefix: query.prefix ? convertPrefix(query.prefix) : undefined,\n filters: query.filters\n ? query.filters.map(\n filter => (key) => {\n return filter(keyToCid(key))\n }\n )\n : undefined,\n orders: query.orders\n ? query.orders.map(\n order => (a, b) => {\n return order(keyToCid(a), keyToCid(b))\n }\n )\n : undefined\n }\n}\n\n/**\n * @typedef {import('interface-blockstore').Query} Query\n * @typedef {import('interface-blockstore').KeyQuery} KeyQuery\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Options} Options\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n */\n\n/**\n * @implements {Blockstore}\n */\nexport class BlockstoreDatastoreAdapter extends BaseBlockstore {\n /**\n * @param {Datastore} datastore\n */\n constructor (datastore) {\n super()\n\n this.child = datastore\n }\n\n open () {\n return this.child.open()\n }\n\n close () {\n return this.child.close()\n }\n\n /**\n * @param {Query} query\n * @param {Options} [options]\n */\n async * query (query, options) {\n for await (const { key, value } of this.child.query(convertQuery(query), options)) {\n yield { key: keyToCid(key), value }\n }\n }\n\n /**\n * @param {KeyQuery} query\n * @param {Options} [options]\n */\n async * queryKeys (query, options) {\n for await (const key of this.child.queryKeys(convertKeyQuery(query), options)) {\n yield keyToCid(key)\n }\n }\n\n /**\n * @param {CID} cid\n * @param {Options} [options]\n * @returns\n */\n async get (cid, options) {\n return this.child.get(cidToKey(cid), options)\n }\n\n /**\n * @param {AsyncIterable | Iterable} cids\n * @param {Options} [options]\n */\n async * getMany (cids, options) {\n for await (const cid of cids) {\n yield this.get(cid, options)\n }\n }\n\n /**\n * @param {CID} cid\n * @param {Uint8Array} value\n * @param {Options} [options]\n */\n async put (cid, value, options) {\n await this.child.put(cidToKey(cid), value, options)\n }\n\n /**\n * @param {AsyncIterable | Iterable} blocks\n * @param {Options} [options]\n */\n async * putMany (blocks, options) { // eslint-disable-line require-await\n // we cannot simply chain to `store.putMany` because we convert a CID into\n // a key based on the multihash only, so we lose the version & codec and\n // cannot give the user back the CID they used to create the block, so yield\n // to `store.putMany` but return the actual block the user passed in.\n //\n // nb. we want to use `store.putMany` here so bitswap can control batching\n // up block HAVEs to send to the network - if we use multiple `store.put`s\n // it will not be able to guess we are about to `store.put` more blocks\n const output = pushable({\n objectMode: true\n })\n\n // process.nextTick runs on the microtask queue, setImmediate runs on the next\n // event loop iteration so is slower. Use process.nextTick if it is available.\n const runner = globalThis.process && globalThis.process.nextTick ? globalThis.process.nextTick : (globalThis.setImmediate || globalThis.setTimeout)\n\n runner(async () => {\n try {\n const store = this.child\n\n await drain(this.child.putMany(async function * () {\n for await (const block of blocks) {\n const key = cidToKey(block.key)\n const exists = await store.has(key, options)\n\n if (!exists) {\n yield { key, value: block.value }\n }\n\n // there is an assumption here that after the yield has completed\n // the underlying datastore has finished writing the block\n output.push(block)\n }\n }()))\n\n output.end()\n } catch (/** @type {any} */ err) {\n output.end(err)\n }\n })\n\n yield * output\n }\n\n /**\n * @param {CID} cid\n * @param {Options} [options]\n */\n has (cid, options) {\n return this.child.has(cidToKey(cid), options)\n }\n\n /**\n * @param {CID} cid\n * @param {Options} [options]\n */\n delete (cid, options) {\n return this.child.delete(cidToKey(cid), options)\n }\n\n /**\n * @param {AsyncIterable | Iterable} cids\n * @param {Options} [options]\n */\n deleteMany (cids, options) {\n const out = pushable({\n objectMode: true\n })\n\n drain(this.child.deleteMany((async function * () {\n for await (const cid of cids) {\n yield cidToKey(cid)\n\n out.push(cid)\n }\n\n out.end()\n }()), options)).catch(err => {\n out.end(err)\n })\n\n return out\n }\n}\n", "import drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nconst sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @typedef {import('interface-blockstore').Options} Options\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Query} Query\n * @typedef {import('interface-blockstore').KeyQuery} KeyQuery\n * @typedef {import('interface-blockstore').Batch} Batch\n *\n * @typedef {import('multiformats').CID} CID\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Blockstore}\n */\nexport class BaseBlockstore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\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\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {CID[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\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 /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (/** @type {Pair} */ e) =>\n e.key.toString().startsWith(q.prefix || '')\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= (q.offset || 0))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (/** @type {CID} */ cid) => cid.toString().startsWith(q.prefix || ''))\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import { createRepo as create } from 'ipfs-repo'\nimport { LevelDatastore } from 'datastore-level'\nimport { BlockstoreDatastoreAdapter } from 'blockstore-datastore-adapter'\nimport { MemoryLock } from 'ipfs-repo/locks/memory'\n\n/**\n * @typedef {import('ipfs-repo-migrations').ProgressCallback} MigrationProgressCallback\n */\n\n/**\n * @param {(...args: any[]) => void} print\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {object} options\n * @param {string} [options.path]\n * @param {boolean} [options.autoMigrate]\n * @param {MigrationProgressCallback} [options.onMigrationProgress]\n * @param {number} [options.peerStoreCacheSize]\n */\nexport function createRepo (print, codecs, options) {\n const repoPath = options.path || 'ipfs'\n\n return create(repoPath, (codeOrName) => codecs.getCodec(codeOrName), {\n root: new LevelDatastore(repoPath, {\n prefix: '',\n version: 2\n }),\n blocks: new BlockstoreDatastoreAdapter(\n new LevelDatastore(`${repoPath}/blocks`, {\n prefix: '',\n version: 2\n })\n ),\n datastore: new LevelDatastore(`${repoPath}/datastore`, {\n prefix: '',\n version: 2\n }),\n keys: new LevelDatastore(`${repoPath}/keys`, {\n prefix: '',\n version: 2\n }),\n pins: new LevelDatastore(`${repoPath}/pins`, {\n prefix: '',\n version: 2\n })\n }, {\n autoMigrate: options.autoMigrate,\n onMigrationProgress: options.onMigrationProgress || print,\n repoLock: MemoryLock\n })\n}\n", "import get from 'dlv'\nimport mergeOpts from 'merge-options'\nimport errCode from 'err-code'\nimport { routers } from 'ipfs-core-config/libp2p-pubsub-routers'\nimport { delegatedPeerRouting } from '@libp2p/delegated-peer-routing'\nimport { delegatedContentRouting } from '@libp2p/delegated-content-routing'\nimport { create as ipfsHttpClient } from 'ipfs-http-client'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { ipfsCore as pkgversion } from '../version.js'\nimport { libp2pConfig as getEnvLibp2pOptions } from 'ipfs-core-config/libp2p'\nimport { createLibp2p as createNode } from 'libp2p'\nimport { kadDHT } from '@libp2p/kad-dht'\nimport { bootstrap } from '@libp2p/bootstrap'\nimport { ipnsValidator } from 'ipns/validator'\nimport { ipnsSelector } from 'ipns/selector'\nimport { webSockets } from '@libp2p/websockets'\nimport { mplex } from '@libp2p/mplex'\nimport { noise } from '@chainsafe/libp2p-noise'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true, concatArrays: true })\n\n/**\n * @typedef {object} DekOptions\n * @property {string} hash\n * @property {string} salt\n * @property {number} iterationCount\n * @property {number} keyLength\n *\n * @typedef {object} KeychainConfig\n * @property {string} [pass]\n * @property {DekOptions} [dek]\n *\n * @typedef {import('ipfs-repo').IPFSRepo} Repo\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('../types').Options} IPFSOptions\n * @typedef {import('libp2p').Libp2p} LibP2P\n * @typedef {import('libp2p').Libp2pOptions} Libp2pOptions\n * @typedef {import('ipfs-core-types/src/config').Config} IPFSConfig\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {object} config\n * @param {Repo} config.repo\n * @param {IPFSOptions|undefined} config.options\n * @param {PeerId} config.peerId\n * @param {Multiaddr[]|undefined} config.multiaddrs\n * @param {KeychainConfig|undefined} config.keychainConfig\n * @param {Partial|undefined} config.config\n */\nexport function createLibp2p ({\n options = {},\n peerId,\n multiaddrs = [],\n repo,\n keychainConfig = {},\n config = {}\n}) {\n const { datastore } = repo\n\n const libp2pOptions = getLibp2pOptions({\n options,\n config,\n datastore,\n keychainConfig,\n peerId,\n multiaddrs\n })\n\n if (typeof options.libp2p === 'function') {\n return options.libp2p({ libp2pOptions, options, config, datastore, peerId })\n }\n\n // do not start by default\n libp2pOptions.start = false\n\n return createNode(libp2pOptions)\n}\n\n/**\n * @param {object} input\n * @param {IPFSOptions} input.options\n * @param {Partial} input.config\n * @param {Repo['datastore']} input.datastore\n * @param {KeychainConfig} input.keychainConfig\n * @param {PeerId} input.peerId\n * @param {Multiaddr[]} input.multiaddrs\n * @returns {Libp2pOptions}\n */\nfunction getLibp2pOptions ({ options, config, datastore, keychainConfig, peerId, multiaddrs }) {\n const getPubsubRouter = () => {\n const router = get(config, 'Pubsub.Router') || 'gossipsub'\n\n const availableRouters = routers()\n\n if (!availableRouters[router]) {\n throw errCode(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${router} router.`), 'ERR_NOT_SUPPORTED')\n }\n\n return availableRouters[router]\n }\n\n /** @type {Libp2pOptions} */\n const libp2pDefaults = {\n datastore,\n peerId: peerId\n }\n\n /** @type {Libp2pOptions} */\n const libp2pOptions = {\n addresses: {\n listen: multiaddrs.map(ma => ma.toString()),\n announce: get(options, 'addresses.announce', get(config, 'Addresses.Announce', [])),\n noAnnounce: get(options, 'addresses.noAnnounce', get(config, 'Addresses.NoAnnounce', []))\n },\n connectionManager: get(options, 'connectionManager', {\n maxConnections: get(options, 'config.Swarm.ConnMgr.HighWater', get(config, 'Swarm.ConnMgr.HighWater')),\n minConnections: get(options, 'config.Swarm.ConnMgr.LowWater', get(config, 'Swarm.ConnMgr.LowWater'))\n }),\n keychain: keychainConfig,\n identify: {\n host: {\n agentVersion: `js-ipfs/${pkgversion}`\n }\n },\n contentRouters: [],\n peerRouters: [],\n peerDiscovery: [],\n transports: [],\n streamMuxers: [\n mplex({\n maxInboundStreams: 256,\n maxOutboundStreams: 1024\n })\n ],\n connectionEncryption: [\n noise()\n ],\n relay: {\n enabled: get(options, 'relay.enabled', get(config, 'relay.enabled', true)),\n hop: {\n enabled: get(options, 'relay.hop.enabled', get(config, 'relay.hop.enabled', false)),\n active: get(options, 'relay.hop.active', get(config, 'relay.hop.active', false))\n }\n },\n nat: {\n enabled: !get(config, 'Swarm.DisableNatPortMap', false)\n }\n }\n\n if (get(options, 'config.Pubsub.Enabled', get(config, 'Pubsub.Enabled', true))) {\n libp2pOptions.pubsub = getPubsubRouter()\n }\n\n if (get(config, 'Routing.Type', 'dhtclient') !== 'none') {\n libp2pOptions.dht = kadDHT({\n clientMode: get(config, 'Routing.Type', 'dht') !== 'dhtserver',\n kBucketSize: get(options, 'dht.kBucketSize', 20),\n validators: {\n ipns: ipnsValidator\n },\n selectors: {\n ipns: ipnsSelector\n }\n })\n }\n\n const boostrapNodes = get(options, 'config.Bootstrap', get(config, 'Bootstrap', []))\n\n if (boostrapNodes.length > 0) {\n libp2pOptions.peerDiscovery?.push(\n bootstrap({\n list: boostrapNodes\n })\n )\n }\n\n /** @type {import('libp2p').Libp2pOptions | undefined} */\n let constructorOptions = get(options, 'libp2p', undefined)\n\n if (typeof constructorOptions === 'function') {\n constructorOptions = undefined\n }\n\n // Merge defaults with Node.js/browser/other environments options and configuration\n /** @type {Libp2pOptions} */\n const libp2pFinalConfig = mergeOptions(\n libp2pDefaults,\n getEnvLibp2pOptions(),\n libp2pOptions,\n constructorOptions\n )\n\n // Set up Delegate Routing based on the presence of Delegates in the config\n const delegateHosts = get(options, 'config.Addresses.Delegates',\n get(config, 'Addresses.Delegates', [])\n )\n\n if (delegateHosts.length > 0) {\n // Pick a random delegate host\n const delegateString = delegateHosts[Math.floor(Math.random() * delegateHosts.length)]\n const delegateAddr = multiaddr(delegateString).toOptions()\n const delegateApiOptions = {\n host: delegateAddr.host,\n // port is a string atm, so we need to convert for the check\n // @ts-expect-error - parseInt(input:string) => number\n protocol: parseInt(delegateAddr.port) === 443 ? 'https' : 'http',\n port: delegateAddr.port\n }\n\n const delegateHttpClient = ipfsHttpClient(delegateApiOptions)\n\n libp2pFinalConfig.contentRouters?.push(delegatedContentRouting(delegateHttpClient))\n libp2pFinalConfig.peerRouters?.push(delegatedPeerRouting(delegateHttpClient))\n }\n\n // TODO: fixme\n if (!get(options, 'config.Discovery.MDNS.Enabled', get(config, 'Discovery.MDNS.Enabled', true))) {\n libp2pFinalConfig.peerDiscovery = libp2pFinalConfig.peerDiscovery?.filter(d => {\n try {\n if (typeof d === 'function') {\n // @ts-expect-error not components\n return d({})[Symbol.toStringTag] !== '@libp2p/mdns'\n }\n } catch {}\n return true\n })\n }\n\n if (libp2pFinalConfig.transports == null) {\n libp2pFinalConfig.transports = []\n }\n\n // add WebSocket transport if not overridden by user config\n if (libp2pFinalConfig.transports.find(t => {\n try {\n if (typeof t === 'function') {\n return t({})[Symbol.toStringTag] === '@libp2p/websockets'\n }\n } catch {}\n return false\n }) == null) {\n libp2pFinalConfig.transports.push(webSockets())\n }\n\n return libp2pFinalConfig\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from 'byte-access'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n /**\n * Returns these hi/lo bits as a BigInt\n */\n toBigInt (unsigned?: boolean): bigint {\n if (unsigned === true) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Returns these hi/lo bits as a Number - this may overflow, toBigInt\n * should be preferred\n */\n toNumber (unsigned?: boolean): number {\n return Number(this.toBigInt(unsigned))\n }\n\n /**\n * ZigZag decode a LongBits object\n */\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * ZigZag encode a LongBits object\n */\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Encode a LongBits object as a varint byte array\n */\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n /**\n * Parse a LongBits object from a BigInt\n */\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a Number\n */\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a varint byte array\n */\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n\n i = 0\n } else {\n for (; i < 4; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n } else if (offset < buf.byteLength) {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw RangeError('invalid varint encoding')\n }\n}\n", "import { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\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)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\ninterface VarintCodec {\n encodingLength: (value: number) => number\n encode: ((value: number) => Uint8Array) & ((value: number, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: number, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => number\n}\n\nexport const unsigned: VarintCodec = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf?: any, offset: number = 0) {\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(true)\n }\n}\n\nexport const signed: VarintCodec = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0) {\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(false)\n }\n}\n\nexport const zigzag: VarintCodec = {\n encodingLength (value: number): number {\n return unsigned.encodingLength(value >= 0 ? value * 2 : value * -2 - 1)\n },\n\n // @ts-expect-error types are wrong\n encode (value: any, buf?: any, offset?: any) {\n value = value >= 0 ? value * 2 : (value * -2) - 1\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n const value = unsigned.decode(buf, offset)\n\n return (value & 1) !== 0 ? (value + 1) / -2 : value / 2\n }\n}\n", "\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n", "import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { unsigned } 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'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\n\nexport interface RecordEnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList): Promise => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\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: Record, peerId: PeerId): Promise => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\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\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\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: Uint8Array | Uint8ArrayList, domain: string): Promise => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw new CodeError('envelope signature is not valid for the given domain', codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\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\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope): boolean {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string): Promise {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\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\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n", "\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\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", "/* 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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.peerId)\n }\n\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16)\n w.uint64(obj.seq)\n }\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\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n", "import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 32)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 64)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n /**\n * Return the list of protocols with registered handlers\n */\n getProtocols: () => string[]\n\n /**\n * Add a protocol handler\n */\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n\n /**\n * Remove a protocol handler\n */\n unhandle: (protocol: string) => Promise\n\n /**\n * Return the handler for the passed protocol\n */\n getHandler: (protocol: string) => StreamHandlerRecord\n\n /**\n * Register a topology handler for a protocol - the topology will be\n * invoked when peers are discovered on the network that support the\n * passed protocol.\n *\n * An id will be returned that can later be used to unregister the\n * topology.\n */\n register: (protocol: string, topology: Topology) => Promise\n\n /**\n * Remove the topology handler with the passed id.\n */\n unregister: (id: string) => void\n\n /**\n * Return all topology handlers that wish to be informed about peers\n * that support the passed protocol.\n */\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n\n /**\n * Invoked when a new peer is connects that supports the configured\n * protocol\n */\n onConnect?: onConnectHandler\n\n /**\n * Invoked when a peer that supports the configured protocol disconnects\n */\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n", "import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = (): void => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] (): string {\n return symbol.toString()\n }\n\n readonly [symbol] = true\n\n async setRegistrar (registrar: Registrar): Promise {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId): void {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n", "\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter> extends EventTarget {\n #listeners = new Map()\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit): boolean {\n return this.dispatchEvent(new CustomEvent(type as string, detail))\n }\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 public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n", "import type { RPC } from './message/rpc.js'\nimport type { MessageId, MsgIdStr, PeerIdStr, TopicStr, MsgIdToStrFn } from './types.js'\n\nexport type CacheEntry = MessageId & {\n topic: TopicStr\n}\n\ninterface MessageCacheEntry {\n message: RPC.IMessage\n /**\n * Tracks if the message has been validated by the app layer and thus forwarded\n */\n validated: boolean\n /**\n * Tracks peers that sent this message before it has been validated by the app layer\n */\n originatingPeers: Set\n /**\n * For every message and peer the number of times this peer asked for the message\n */\n iwantCounts: Map\n}\n\nexport class MessageCache {\n msgs = new Map()\n\n msgIdToStrFn: MsgIdToStrFn\n\n history: CacheEntry[][] = []\n\n /** Track with accounting of messages in the mcache that are not yet validated */\n notValidatedCount = 0\n\n /**\n * Holds history of messages in timebounded history arrays\n */\n constructor(\n /**\n * The number of indices in the cache history used for gossiping. That means that a message\n * won't get gossiped anymore when shift got called `gossip` many times after inserting the\n * message in the cache.\n */\n private readonly gossip: number,\n historyCapacity: number,\n msgIdToStrFn: MsgIdToStrFn\n ) {\n this.msgIdToStrFn = msgIdToStrFn\n for (let i = 0; i < historyCapacity; i++) {\n this.history[i] = []\n }\n }\n\n get size(): number {\n return this.msgs.size\n }\n\n /**\n * Adds a message to the current window and the cache\n * Returns true if the message is not known and is inserted in the cache\n */\n put(messageId: MessageId, msg: RPC.IMessage, validated = false): boolean {\n const { msgIdStr } = messageId\n // Don't add duplicate entries to the cache.\n if (this.msgs.has(msgIdStr)) {\n return false\n }\n\n this.msgs.set(msgIdStr, {\n message: msg,\n validated,\n originatingPeers: new Set(),\n iwantCounts: new Map()\n })\n\n this.history[0].push({ ...messageId, topic: msg.topic })\n\n if (!validated) {\n this.notValidatedCount++\n }\n\n return true\n }\n\n observeDuplicate(msgId: MsgIdStr, fromPeerIdStr: PeerIdStr): void {\n const entry = this.msgs.get(msgId)\n\n if (\n entry &&\n // if the message is already validated, we don't need to store extra peers sending us\n // duplicates as the message has already been forwarded\n !entry.validated\n ) {\n entry.originatingPeers.add(fromPeerIdStr)\n }\n }\n\n /**\n * Retrieves a message from the cache by its ID, if it is still present\n */\n get(msgId: Uint8Array): RPC.IMessage | undefined {\n return this.msgs.get(this.msgIdToStrFn(msgId))?.message\n }\n\n /**\n * Increases the iwant count for the given message by one and returns the message together\n * with the iwant if the message exists.\n */\n getWithIWantCount(msgIdStr: string, p: string): { msg: RPC.IMessage; count: number } | null {\n const msg = this.msgs.get(msgIdStr)\n if (!msg) {\n return null\n }\n\n const count = (msg.iwantCounts.get(p) ?? 0) + 1\n msg.iwantCounts.set(p, count)\n\n return { msg: msg.message, count }\n }\n\n /**\n * Retrieves a list of message IDs for a set of topics\n */\n getGossipIDs(topics: Set): Map {\n const msgIdsByTopic = new Map()\n for (let i = 0; i < this.gossip; i++) {\n this.history[i].forEach((entry) => {\n const msg = this.msgs.get(entry.msgIdStr)\n if (msg && msg.validated && topics.has(entry.topic)) {\n let msgIds = msgIdsByTopic.get(entry.topic)\n if (!msgIds) {\n msgIds = []\n msgIdsByTopic.set(entry.topic, msgIds)\n }\n msgIds.push(entry.msgId)\n }\n })\n }\n\n return msgIdsByTopic\n }\n\n /**\n * Gets a message with msgId and tags it as validated.\n * This function also returns the known peers that have sent us this message. This is used to\n * prevent us sending redundant messages to peers who have already propagated it.\n */\n validate(msgId: MsgIdStr): { message: RPC.IMessage; originatingPeers: Set } | null {\n const entry = this.msgs.get(msgId)\n if (!entry) {\n return null\n }\n\n if (!entry.validated) {\n this.notValidatedCount--\n }\n\n const { message, originatingPeers } = entry\n entry.validated = true\n // Clear the known peers list (after a message is validated, it is forwarded and we no\n // longer need to store the originating peers).\n entry.originatingPeers = new Set()\n return { message, originatingPeers }\n }\n\n /**\n * Shifts the current window, discarding messages older than this.history.length of the cache\n */\n shift(): void {\n const lastCacheEntries = this.history[this.history.length - 1]\n lastCacheEntries.forEach((cacheEntry) => {\n const entry = this.msgs.get(cacheEntry.msgIdStr)\n if (entry) {\n this.msgs.delete(cacheEntry.msgIdStr)\n if (!entry.validated) {\n this.notValidatedCount--\n }\n }\n })\n\n this.history.pop()\n this.history.unshift([])\n }\n\n remove(msgId: MsgIdStr): MessageCacheEntry | null {\n const entry = this.msgs.get(msgId)\n if (!entry) {\n return null\n }\n\n // Keep the message on the history vector, it will be dropped on a shift()\n this.msgs.delete(msgId)\n return entry\n }\n}\n", "import cjs from \"./rpc.cjs\"\n\nexport const {RPC} = cjs\n", "export const second = 1000\nexport const minute = 60 * second\n\n// Protocol identifiers\n\nexport const FloodsubID = '/floodsub/1.0.0'\n\n/**\n * The protocol ID for version 1.0.0 of the Gossipsub protocol\n * It is advertised along with GossipsubIDv11 for backwards compatability\n */\nexport const GossipsubIDv10 = '/meshsub/1.0.0'\n\n/**\n * The protocol ID for version 1.1.0 of the Gossipsub protocol\n * See the spec for details about how v1.1.0 compares to v1.0.0:\n * https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md\n */\nexport const GossipsubIDv11 = '/meshsub/1.1.0'\n\n// Overlay parameters\n\n/**\n * GossipsubD sets the optimal degree for a Gossipsub topic mesh. For example, if GossipsubD == 6,\n * each peer will want to have about six peers in their mesh for each topic they're subscribed to.\n * GossipsubD should be set somewhere between GossipsubDlo and GossipsubDhi.\n */\nexport const GossipsubD = 6\n\n/**\n * GossipsubDlo sets the lower bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have fewer than GossipsubDlo peers, we will attempt to graft some more into the mesh at\n * the next heartbeat.\n */\nexport const GossipsubDlo = 4\n\n/**\n * GossipsubDhi sets the upper bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have more than GossipsubDhi peers, we will select some to prune from the mesh at the next heartbeat.\n */\nexport const GossipsubDhi = 12\n\n/**\n * GossipsubDscore affects how peers are selected when pruning a mesh due to over subscription.\n * At least GossipsubDscore of the retained peers will be high-scoring, while the remainder are\n * chosen randomly.\n */\nexport const GossipsubDscore = 4\n\n/**\n * GossipsubDout sets the quota for the number of outbound connections to maintain in a topic mesh.\n * When the mesh is pruned due to over subscription, we make sure that we have outbound connections\n * to at least GossipsubDout of the survivor peers. This prevents sybil attackers from overwhelming\n * our mesh with incoming connections.\n *\n * GossipsubDout must be set below GossipsubDlo, and must not exceed GossipsubD / 2.\n */\nexport const GossipsubDout = 2\n\n// Gossip parameters\n\n/**\n * GossipsubHistoryLength controls the size of the message cache used for gossip.\n * The message cache will remember messages for GossipsubHistoryLength heartbeats.\n */\nexport const GossipsubHistoryLength = 5\n\n/**\n * GossipsubHistoryGossip controls how many cached message ids we will advertise in\n * IHAVE gossip messages. When asked for our seen message IDs, we will return\n * only those from the most recent GossipsubHistoryGossip heartbeats. The slack between\n * GossipsubHistoryGossip and GossipsubHistoryLength allows us to avoid advertising messages\n * that will be expired by the time they're requested.\n *\n * GossipsubHistoryGossip must be less than or equal to GossipsubHistoryLength to\n * avoid a runtime panic.\n */\nexport const GossipsubHistoryGossip = 3\n\n/**\n * GossipsubDlazy affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to at least GossipsubDlazy peers outside our mesh. The actual\n * number may be more, depending on GossipsubGossipFactor and how many peers we're\n * connected to.\n */\nexport const GossipsubDlazy = 6\n\n/**\n * GossipsubGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to GossipsubGossipFactor * (total number of non-mesh peers), or\n * GossipsubDlazy, whichever is greater.\n */\nexport const GossipsubGossipFactor = 0.25\n\n/**\n * GossipsubGossipRetransmission controls how many times we will allow a peer to request\n * the same message id through IWANT gossip before we start ignoring them. This is designed\n * to prevent peers from spamming us with requests and wasting our resources.\n */\nexport const GossipsubGossipRetransmission = 3\n\n// Heartbeat interval\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const GossipsubHeartbeatInitialDelay = 100\n\n/**\n * GossipsubHeartbeatInterval controls the time between heartbeats.\n */\nexport const GossipsubHeartbeatInterval = second\n\n/**\n * GossipsubFanoutTTL controls how long we keep track of the fanout state. If it's been\n * GossipsubFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const GossipsubFanoutTTL = minute\n\n/**\n * GossipsubPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to GossipsubPrunePeers other peers that we\n * know of.\n */\nexport const GossipsubPrunePeers = 16\n\n/**\n * GossipsubPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of GossipsubPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least GossipsubPruneBackoff\n * before attempting to re-graft.\n */\nexport const GossipsubPruneBackoff = minute\n\n/**\n * GossipsubPruneBackoffTicks is the number of heartbeat ticks for attempting to prune expired\n * backoff timers.\n */\nexport const GossipsubPruneBackoffTicks = 15\n\n/**\n * GossipsubConnectors controls the number of active connection attempts for peers obtained through PX.\n */\nexport const GossipsubConnectors = 8\n\n/**\n * GossipsubMaxPendingConnections sets the maximum number of pending connections for peers attempted through px.\n */\nexport const GossipsubMaxPendingConnections = 128\n\n/**\n * GossipsubConnectionTimeout controls the timeout for connection attempts.\n */\nexport const GossipsubConnectionTimeout = 30 * second\n\n/**\n * GossipsubDirectConnectTicks is the number of heartbeat ticks for attempting to reconnect direct peers\n * that are not currently connected.\n */\nexport const GossipsubDirectConnectTicks = 300\n\n/**\n * GossipsubDirectConnectInitialDelay is the initial delay before opening connections to direct peers\n */\nexport const GossipsubDirectConnectInitialDelay = second\n\n/**\n * GossipsubOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every GossipsubOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const GossipsubOpportunisticGraftTicks = 60\n\n/**\n * GossipsubOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const GossipsubOpportunisticGraftPeers = 2\n\n/**\n * If a GRAFT comes before GossipsubGraftFloodThreshold has elapsed since the last PRUNE,\n * then there is an extra score penalty applied to the peer through P7.\n */\nexport const GossipsubGraftFloodThreshold = 10 * second\n\n/**\n * GossipsubMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const GossipsubMaxIHaveLength = 5000\n\n/**\n * GossipsubMaxIHaveMessages is the maximum number of IHAVE messages to accept from a peer within a heartbeat.\n */\nexport const GossipsubMaxIHaveMessages = 10\n\n/**\n * Time to wait for a message requested through IWANT following an IHAVE advertisement.\n * If the message is not received within this window, a broken promise is declared and\n * the router may apply bahavioural penalties.\n */\nexport const GossipsubIWantFollowupTime = 3 * second\n\n/**\n * Time in milliseconds to keep message ids in the seen cache\n */\nexport const GossipsubSeenTTL = 2 * minute\n\nexport const TimeCacheDuration = 120 * 1000\n\nexport const ERR_TOPIC_VALIDATOR_REJECT = 'ERR_TOPIC_VALIDATOR_REJECT'\nexport const ERR_TOPIC_VALIDATOR_IGNORE = 'ERR_TOPIC_VALIDATOR_IGNORE'\n\n/**\n * If peer score is better than this, we accept messages from this peer\n * within ACCEPT_FROM_WHITELIST_DURATION_MS from the last time computing score.\n **/\nexport const ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE = 0\n\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept up to this\n * number of messages from that peer.\n */\nexport const ACCEPT_FROM_WHITELIST_MAX_MESSAGES = 128\n\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept messages from\n * this peer up to this time duration.\n */\nexport const ACCEPT_FROM_WHITELIST_DURATION_MS = 1000\n\n/**\n * The default MeshMessageDeliveriesWindow to be used in metrics.\n */\nexport const DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS = 1000\n", "/**\n * Pseudo-randomly shuffles an array\n *\n * Mutates the input array\n */\nexport function shuffle(arr: T[]): T[] {\n if (arr.length <= 1) {\n return arr\n }\n const randInt = () => {\n return Math.floor(Math.random() * Math.floor(arr.length))\n }\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", "import { toString } from 'uint8arrays/to-string'\n\n/**\n * Browser friendly function to convert Uint8Array message id to base64 string.\n */\nexport function messageIdToString(msgId: Uint8Array): string {\n return toString(msgId, 'base64')\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Pushable } from 'it-pushable'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\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 */\nexport const StrictSign = 'StrictSign'\n\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 */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface SignedMessage {\n type: 'signed'\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber: bigint\n signature: Uint8Array\n key: Uint8Array\n}\n\nexport interface UnsignedMessage {\n type: 'unsigned'\n topic: string\n data: Uint8Array\n}\n\nexport type Message = SignedMessage | UnsignedMessage\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends EventEmitter {\n id: PeerId\n protocol: string\n outboundStream?: Pushable\n inboundStream?: AsyncIterable\n isWritable: boolean\n\n close: () => void\n write: (buf: Uint8Array | Uint8ArrayList) => void\n attachInboundStream: (stream: Stream) => AsyncIterable\n attachOutboundStream: (stream: Stream) => Promise>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\ninterface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent\n 'message': CustomEvent\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport enum TopicValidatorResult {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n Accept = 'accept',\n /**\n * The message is neither delivered nor forwarded to the network\n */\n Ignore = 'ignore',\n /**\n * The message is considered invalid, and it should be rejected\n */\n Reject = 'reject'\n}\n\nexport interface TopicValidatorFn {\n (peer: PeerId, message: Message): TopicValidatorResult | Promise\n}\n\nexport interface PubSub = PubSubEvents> extends EventEmitter {\n /**\n * The global signature policy controls whether or not we sill send and receive\n * signed or unsigned messages.\n *\n * Signed messages prevent spoofing message senders and should be preferred to\n * using unsigned messages.\n */\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n\n /**\n * A list of multicodecs that contain the pubsub protocol name.\n */\n multicodecs: string[]\n\n /**\n * Pubsub routers support message validators per topic, which will validate the message\n * before its propagations. They are stored in a map where keys are the topic name and\n * values are the validators.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const validateMessage = (msgTopic, msg) => {\n * const input = uint8ArrayToString(msg.data)\n * const validInputs = ['a', 'b', 'c']\n *\n * if (!validInputs.includes(input)) {\n * throw new Error('no valid input received')\n * }\n * }\n * libp2p.pubsub.topicValidators.set(topic, validateMessage)\n * ```\n */\n topicValidators: Map\n\n getPeers: () => PeerId[]\n\n /**\n * Gets a list of topics the node is subscribed to.\n *\n * ```js\n * const topics = libp2p.pubsub.getTopics()\n * ```\n */\n getTopics: () => string[]\n\n /**\n * Subscribes to a pubsub topic.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const handler = (msg) => {\n * if (msg.topic === topic) {\n * // msg.data - pubsub data received\n * }\n * }\n *\n * libp2p.pubsub.addEventListener('message', handler)\n * libp2p.pubsub.subscribe(topic)\n * ```\n */\n subscribe: (topic: string) => void\n\n /**\n * Unsubscribes from a pubsub topic.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const handler = (msg) => {\n * // msg.data - pubsub data received\n * }\n *\n * libp2p.pubsub.removeEventListener(topic handler)\n * libp2p.pubsub.unsubscribe(topic)\n * ```\n */\n unsubscribe: (topic: string) => void\n\n /**\n * Gets a list of the PeerIds that are subscribed to one topic.\n *\n * @example\n *\n * ```js\n * const peerIds = libp2p.pubsub.getSubscribers(topic)\n * ```\n */\n getSubscribers: (topic: string) => PeerId[]\n\n /**\n * Publishes messages to the given topic.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const data = uint8ArrayFromString('data')\n *\n * await libp2p.pubsub.publish(topic, data)\n * ```\n */\n publish: (topic: string, data: Uint8Array) => Promise\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent\n 'stream:outbound': CustomEvent\n 'close': CustomEvent\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PrivateKey } from '@libp2p/interface-keys'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { RPC } from './message/rpc.js'\nimport { Message, TopicValidatorResult } from '@libp2p/interface-pubsub'\n\nexport type MsgIdStr = string\nexport type PeerIdStr = string\nexport type TopicStr = string\nexport type IPStr = string\n\nexport interface AddrInfo {\n id: PeerId\n addrs: Multiaddr[]\n}\n\n/**\n * Compute a local non-spec'ed msg-id for faster de-duplication of seen messages.\n * Used exclusively for a local seen_cache\n */\nexport type FastMsgIdFn = (msg: RPC.IMessage) => string | number\n\n/**\n * By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n * Application could use this option to provide a more efficient function.\n */\nexport type MsgIdToStrFn = (msgId: Uint8Array) => string\n\n/**\n * Compute spec'ed msg-id. Used for IHAVE / IWANT messages\n */\nexport interface MsgIdFn {\n (msg: Message): Promise | Uint8Array\n}\n\nexport interface DataTransform {\n /**\n * Takes the data published by peers on a topic and transforms the data.\n * Should be the reverse of outboundTransform(). Example:\n * - `inboundTransform()`: decompress snappy payload\n * - `outboundTransform()`: compress snappy payload\n */\n inboundTransform(topic: TopicStr, data: Uint8Array): Uint8Array\n\n /**\n * Takes the data to be published (a topic and associated data) transforms the data. The\n * transformed data will then be used to create a `RawGossipsubMessage` to be sent to peers.\n */\n outboundTransform(topic: TopicStr, data: Uint8Array): Uint8Array\n}\n\nexport enum SignaturePolicy {\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 */\n 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 */\n StrictNoSign = 'StrictNoSign'\n}\n\nexport type PublishOpts = {\n allowPublishToZeroPeers?: boolean\n ignoreDuplicatePublishError?: boolean\n}\n\nexport enum PublishConfigType {\n Signing,\n Anonymous\n}\n\nexport type PublishConfig =\n | {\n type: PublishConfigType.Signing\n author: PeerId\n key: Uint8Array\n privateKey: PrivateKey\n }\n | { type: PublishConfigType.Anonymous }\n\nexport type RejectReasonObj =\n | { reason: RejectReason.Error; error: ValidateError }\n | { reason: Exclude }\n\nexport enum RejectReason {\n /**\n * The message failed the configured validation during decoding.\n * SelfOrigin is considered a ValidationError\n */\n Error = 'error',\n /**\n * Custom validator fn reported status IGNORE.\n */\n Ignore = 'ignore',\n /**\n * Custom validator fn reported status REJECT.\n */\n Reject = 'reject',\n /**\n * The peer that sent the message OR the source from field is blacklisted.\n * Causes messages to be ignored, not penalized, neither do score record creation.\n */\n Blacklisted = 'blacklisted'\n}\n\nexport enum ValidateError {\n /// The message has an invalid signature,\n InvalidSignature = 'invalid_signature',\n /// The sequence number was the incorrect size\n InvalidSeqno = 'invalid_seqno',\n /// The PeerId was invalid\n InvalidPeerId = 'invalid_peerid',\n /// Signature existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n SignaturePresent = 'signature_present',\n /// Sequence number existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n SeqnoPresent = 'seqno_present',\n /// Message source existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n FromPresent = 'from_present',\n /// The data transformation failed.\n TransformFailed = 'transform_failed'\n}\n\nexport enum MessageStatus {\n duplicate = 'duplicate',\n invalid = 'invalid',\n valid = 'valid'\n}\n\n/**\n * Store both Uint8Array and string message id so that we don't have to convert data between the two.\n * See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/274\n */\nexport type MessageId = {\n msgId: Uint8Array\n msgIdStr: MsgIdStr\n}\n\n/**\n * Typesafe conversion of MessageAcceptance -> RejectReason. TS ensures all values covered\n */\nexport function rejectReasonFromAcceptance(\n acceptance: Exclude\n): RejectReason.Ignore | RejectReason.Reject {\n switch (acceptance) {\n case TopicValidatorResult.Ignore:\n return RejectReason.Ignore\n case TopicValidatorResult.Reject:\n return RejectReason.Reject\n }\n}\n", "import { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport { StrictSign, StrictNoSign } from '@libp2p/interface-pubsub'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { PublishConfig, PublishConfigType } from '../types.js'\n\n/**\n * Prepare a PublishConfig object from a PeerId.\n */\nexport async function getPublishConfigFromPeerId(\n signaturePolicy: typeof StrictSign | typeof StrictNoSign,\n peerId?: PeerId\n): Promise {\n switch (signaturePolicy) {\n case StrictSign: {\n if (!peerId) {\n throw Error('Must provide PeerId')\n }\n\n if (peerId.privateKey == null) {\n throw Error('Cannot sign message, no private key present')\n }\n\n if (peerId.publicKey == null) {\n throw Error('Cannot sign message, no public key present')\n }\n\n // Transform privateKey once at initialization time instead of once per message\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return {\n type: PublishConfigType.Signing,\n author: peerId,\n key: peerId.publicKey,\n privateKey\n }\n }\n\n case StrictNoSign:\n return {\n type: PublishConfigType.Anonymous\n }\n\n default:\n throw new Error(`Unknown signature policy \"${signaturePolicy}\"`)\n }\n}\n", "export const ERR_INVALID_PEER_SCORE_PARAMS = 'ERR_INVALID_PEER_SCORE_PARAMS'\nexport const ERR_INVALID_PEER_SCORE_THRESHOLDS = 'ERR_INVALID_PEER_SCORE_THRESHOLDS'\n", "import { ERR_INVALID_PEER_SCORE_PARAMS } from './constants.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n// This file defines PeerScoreParams and TopicScoreParams interfaces\n// as well as constructors, default constructors, and validation functions\n// for these interfaces\n\nexport interface PeerScoreParams {\n /**\n * Score parameters per topic.\n */\n topics: Record\n\n /**\n * Aggregate topic score cap; this limits the total contribution of topics towards a positive\n * score. It must be positive (or 0 for no cap).\n */\n topicScoreCap: number\n\n /**\n * P5: Application-specific peer scoring\n */\n appSpecificScore: (p: string) => number\n appSpecificWeight: number\n\n /**\n * P6: IP-colocation factor.\n * The parameter has an associated counter which counts the number of peers with the same IP.\n * If the number of peers in the same IP exceeds IPColocationFactorThreshold, then the value\n * is the square of the difference, ie (PeersInSameIP - IPColocationThreshold)^2.\n * If the number of peers in the same IP is less than the threshold, then the value is 0.\n * The weight of the parameter MUST be negative, unless you want to disable for testing.\n * Note: In order to simulate many IPs in a managable manner when testing, you can set the weight to 0\n * thus disabling the IP colocation penalty.\n */\n IPColocationFactorWeight: number\n IPColocationFactorThreshold: number\n IPColocationFactorWhitelist: Set\n\n /**\n * P7: behavioural pattern penalties.\n * This parameter has an associated counter which tracks misbehaviour as detected by the\n * router. The router currently applies penalties for the following behaviors:\n * - attempting to re-graft before the prune backoff time has elapsed.\n * - not following up in IWANT requests for messages advertised with IHAVE.\n *\n * The value of the parameter is the square of the counter, which decays with BehaviourPenaltyDecay.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n behaviourPenaltyWeight: number\n behaviourPenaltyThreshold: number\n behaviourPenaltyDecay: number\n\n /**\n * the decay interval for parameter counters.\n */\n decayInterval: number\n\n /**\n * counter value below which it is considered 0.\n */\n decayToZero: number\n\n /**\n * time to remember counters for a disconnected peer.\n */\n retainScore: number\n}\n\nexport interface TopicScoreParams {\n /**\n * The weight of the topic.\n */\n topicWeight: number\n\n /**\n * P1: time in the mesh\n * This is the time the peer has ben grafted in the mesh.\n * The value of the parameter is the time/TimeInMeshQuantum, capped by TimeInMeshCap\n * The weight of the parameter MUST be positive (or zero to disable).\n */\n timeInMeshWeight: number\n timeInMeshQuantum: number\n timeInMeshCap: number\n\n /**\n * P2: first message deliveries\n * This is the number of message deliveries in the topic.\n * The value of the parameter is a counter, decaying with FirstMessageDeliveriesDecay, and capped\n * by FirstMessageDeliveriesCap.\n * The weight of the parameter MUST be positive (or zero to disable).\n */\n firstMessageDeliveriesWeight: number\n firstMessageDeliveriesDecay: number\n firstMessageDeliveriesCap: number\n\n /**\n * P3: mesh message deliveries\n * This is the number of message deliveries in the mesh, within the MeshMessageDeliveriesWindow of\n * message validation; deliveries during validation also count and are retroactively applied\n * when validation succeeds.\n * This window accounts for the minimum time before a hostile mesh peer trying to game the score\n * could replay back a valid message we just sent them.\n * It effectively tracks first and near-first deliveries, ie a message seen from a mesh peer\n * before we have forwarded it to them.\n * The parameter has an associated counter, decaying with MeshMessageDeliveriesDecay.\n * If the counter exceeds the threshold, its value is 0.\n * If the counter is below the MeshMessageDeliveriesThreshold, the value is the square of\n * the deficit, ie (MessageDeliveriesThreshold - counter)^2\n * The penalty is only activated after MeshMessageDeliveriesActivation time in the mesh.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n meshMessageDeliveriesWeight: number\n meshMessageDeliveriesDecay: number\n meshMessageDeliveriesCap: number\n meshMessageDeliveriesThreshold: number\n meshMessageDeliveriesWindow: number\n meshMessageDeliveriesActivation: number\n\n /**\n * P3b: sticky mesh propagation failures\n * This is a sticky penalty that applies when a peer gets pruned from the mesh with an active\n * mesh message delivery penalty.\n * The weight of the parameter MUST be negative (or zero to disable)\n */\n meshFailurePenaltyWeight: number\n meshFailurePenaltyDecay: number\n\n /**\n * P4: invalid messages\n * This is the number of invalid messages in the topic.\n * The value of the parameter is the square of the counter, decaying with\n * InvalidMessageDeliveriesDecay.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n invalidMessageDeliveriesWeight: number\n invalidMessageDeliveriesDecay: number\n}\n\nexport const defaultPeerScoreParams: PeerScoreParams = {\n topics: {},\n topicScoreCap: 10.0,\n appSpecificScore: () => 0.0,\n appSpecificWeight: 10.0,\n IPColocationFactorWeight: -5.0,\n IPColocationFactorThreshold: 10.0,\n IPColocationFactorWhitelist: new Set(),\n behaviourPenaltyWeight: -10.0,\n behaviourPenaltyThreshold: 0.0,\n behaviourPenaltyDecay: 0.2,\n decayInterval: 1000.0,\n decayToZero: 0.1,\n retainScore: 3600 * 1000\n}\n\nexport const defaultTopicScoreParams: TopicScoreParams = {\n topicWeight: 0.5,\n timeInMeshWeight: 1,\n timeInMeshQuantum: 1,\n timeInMeshCap: 3600,\n\n firstMessageDeliveriesWeight: 1,\n firstMessageDeliveriesDecay: 0.5,\n firstMessageDeliveriesCap: 2000,\n\n meshMessageDeliveriesWeight: -1,\n meshMessageDeliveriesDecay: 0.5,\n meshMessageDeliveriesCap: 100,\n meshMessageDeliveriesThreshold: 20,\n meshMessageDeliveriesWindow: 10,\n meshMessageDeliveriesActivation: 5000,\n\n meshFailurePenaltyWeight: -1,\n meshFailurePenaltyDecay: 0.5,\n\n invalidMessageDeliveriesWeight: -1,\n invalidMessageDeliveriesDecay: 0.3\n}\n\nexport function createPeerScoreParams(p: Partial = {}): PeerScoreParams {\n return {\n ...defaultPeerScoreParams,\n ...p,\n topics: p.topics\n ? Object.entries(p.topics).reduce((topics, [topic, topicScoreParams]) => {\n topics[topic] = createTopicScoreParams(topicScoreParams)\n return topics\n }, {} as Record)\n : {}\n }\n}\n\nexport function createTopicScoreParams(p: Partial = {}): TopicScoreParams {\n return {\n ...defaultTopicScoreParams,\n ...p\n }\n}\n\n// peer score parameter validation\nexport function validatePeerScoreParams(p: PeerScoreParams): void {\n for (const [topic, params] of Object.entries(p.topics)) {\n try {\n validateTopicScoreParams(params)\n } catch (e) {\n throw new CodeError(\n `invalid score parameters for topic ${topic}: ${(e as Error).message}`,\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n }\n\n // check that the topic score is 0 or something positive\n if (p.topicScoreCap < 0) {\n throw new CodeError('invalid topic score cap; must be positive (or 0 for no cap)', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check that we have an app specific score; the weight can be anything (but expected positive)\n if (p.appSpecificScore === null || p.appSpecificScore === undefined) {\n throw new CodeError('missing application specific score function', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the IP colocation factor\n if (p.IPColocationFactorWeight > 0) {\n throw new CodeError(\n 'invalid IPColocationFactorWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.IPColocationFactorWeight !== 0 && p.IPColocationFactorThreshold < 1) {\n throw new CodeError('invalid IPColocationFactorThreshold; must be at least 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the behaviour penalty\n if (p.behaviourPenaltyWeight > 0) {\n throw new CodeError(\n 'invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.behaviourPenaltyWeight !== 0 && (p.behaviourPenaltyDecay <= 0 || p.behaviourPenaltyDecay >= 1)) {\n throw new CodeError('invalid BehaviourPenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the decay parameters\n if (p.decayInterval < 1000) {\n throw new CodeError('invalid DecayInterval; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.decayToZero <= 0 || p.decayToZero >= 1) {\n throw new CodeError('invalid DecayToZero; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // no need to check the score retention; a value of 0 means that we don't retain scores\n}\n\nexport function validateTopicScoreParams(p: TopicScoreParams): void {\n // make sure we have a sane topic weight\n if (p.topicWeight < 0) {\n throw new CodeError('invalid topic weight; must be >= 0', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P1\n if (p.timeInMeshQuantum === 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be non zero', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight < 0) {\n throw new CodeError('invalid TimeInMeshWeight; must be positive (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshQuantum <= 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshCap <= 0) {\n throw new CodeError('invalid TimeInMeshCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P2\n if (p.firstMessageDeliveriesWeight < 0) {\n throw new CodeError(\n 'invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (\n p.firstMessageDeliveriesWeight !== 0 &&\n (p.firstMessageDeliveriesDecay <= 0 || p.firstMessageDeliveriesDecay >= 1)\n ) {\n throw new CodeError('invalid FirstMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.firstMessageDeliveriesWeight !== 0 && p.firstMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid FirstMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P3\n if (p.meshMessageDeliveriesWeight > 0) {\n throw new CodeError(\n 'invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.meshMessageDeliveriesWeight !== 0 && (p.meshMessageDeliveriesDecay <= 0 || p.meshMessageDeliveriesDecay >= 1)) {\n throw new CodeError('invalid MeshMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesThreshold <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesThreshold; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWindow < 0) {\n throw new CodeError('invalid MeshMessageDeliveriesWindow; must be non-negative', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesActivation < 1000) {\n throw new CodeError('invalid MeshMessageDeliveriesActivation; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P3b\n if (p.meshFailurePenaltyWeight > 0) {\n throw new CodeError(\n 'invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.meshFailurePenaltyWeight !== 0 && (p.meshFailurePenaltyDecay <= 0 || p.meshFailurePenaltyDecay >= 1)) {\n throw new CodeError('invalid MeshFailurePenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P4\n if (p.invalidMessageDeliveriesWeight > 0) {\n throw new CodeError(\n 'invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.invalidMessageDeliveriesDecay <= 0 || p.invalidMessageDeliveriesDecay >= 1) {\n throw new CodeError('invalid InvalidMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n}\n", "import { ERR_INVALID_PEER_SCORE_THRESHOLDS } from './constants.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n// This file defines PeerScoreThresholds interface\n// as well as a constructor, default constructor, and validation function\n// for this interface\n\nexport interface PeerScoreThresholds {\n /**\n * gossipThreshold is the score threshold below which gossip propagation is supressed;\n * should be negative.\n */\n gossipThreshold: number\n\n /**\n * publishThreshold is the score threshold below which we shouldn't publish when using flood\n * publishing (also applies to fanout and floodsub peers); should be negative and <= GossipThreshold.\n */\n publishThreshold: number\n\n /**\n * graylistThreshold is the score threshold below which message processing is supressed altogether,\n * implementing an effective graylist according to peer score; should be negative and <= PublisThreshold.\n */\n graylistThreshold: number\n\n /**\n * acceptPXThreshold is the score threshold below which PX will be ignored; this should be positive\n * and limited to scores attainable by bootstrappers and other trusted nodes.\n */\n acceptPXThreshold: number\n\n /**\n * opportunisticGraftThreshold is the median mesh score threshold before triggering opportunistic\n * grafting; this should have a small positive value.\n */\n opportunisticGraftThreshold: number\n}\n\nexport const defaultPeerScoreThresholds: PeerScoreThresholds = {\n gossipThreshold: -10,\n publishThreshold: -50,\n graylistThreshold: -80,\n acceptPXThreshold: 10,\n opportunisticGraftThreshold: 20\n}\n\nexport function createPeerScoreThresholds(p: Partial = {}): PeerScoreThresholds {\n return {\n ...defaultPeerScoreThresholds,\n ...p\n }\n}\n\nexport function validatePeerScoreThresholds(p: PeerScoreThresholds): void {\n if (p.gossipThreshold > 0) {\n throw new CodeError('invalid gossip threshold; it must be <= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n if (p.publishThreshold > 0 || p.publishThreshold > p.gossipThreshold) {\n throw new CodeError(\n 'invalid publish threshold; it must be <= 0 and <= gossip threshold',\n ERR_INVALID_PEER_SCORE_THRESHOLDS\n )\n }\n if (p.graylistThreshold > 0 || p.graylistThreshold > p.publishThreshold) {\n throw new CodeError(\n 'invalid graylist threshold; it must be <= 0 and <= publish threshold',\n ERR_INVALID_PEER_SCORE_THRESHOLDS\n )\n }\n if (p.acceptPXThreshold < 0) {\n throw new CodeError('invalid accept PX threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n if (p.opportunisticGraftThreshold < 0) {\n throw new CodeError('invalid opportunistic grafting threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n}\n", "import type { PeerStats } from './peer-stats.js'\nimport type { PeerScoreParams } from './peer-score-params.js'\n\nexport function computeScore(\n peer: string,\n pstats: PeerStats,\n params: PeerScoreParams,\n peerIPs: Map>\n): number {\n let score = 0\n\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n const topicParams = params.topics[topic]\n if (topicParams === undefined) {\n // we are not scoring this topic\n return\n }\n\n let topicScore = 0\n\n // P1: time in Mesh\n if (tstats.inMesh) {\n let p1 = tstats.meshTime / topicParams.timeInMeshQuantum\n if (p1 > topicParams.timeInMeshCap) {\n p1 = topicParams.timeInMeshCap\n }\n topicScore += p1 * topicParams.timeInMeshWeight\n }\n\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap\n }\n topicScore += p2 * topicParams.firstMessageDeliveriesWeight\n\n // P3: mesh message deliveries\n if (\n tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold\n ) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries\n const p3 = deficit * deficit\n topicScore += p3 * topicParams.meshMessageDeliveriesWeight\n }\n\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty\n topicScore += p3b * topicParams.meshFailurePenaltyWeight\n\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries\n topicScore += p4 * topicParams.invalidMessageDeliveriesWeight\n\n // update score, mixing with topic weight\n score += topicScore * topicParams.topicWeight\n })\n\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap\n }\n\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer)\n score += p5 * params.appSpecificWeight\n\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return\n }\n\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip)\n const numPeersInIP = peersInIP ? peersInIP.size : 0\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold\n const p6 = surplus * surplus\n score += p6 * params.IPColocationFactorWeight\n }\n })\n\n // P7: behavioural pattern penalty\n if (pstats.behaviourPenalty > params.behaviourPenaltyThreshold) {\n const excess = pstats.behaviourPenalty - params.behaviourPenaltyThreshold\n const p7 = excess * excess\n score += p7 * params.behaviourPenaltyWeight\n }\n\n return score\n}\n", "import { TimeCacheDuration } from '../constants.js'\nimport Denque from 'denque'\n\nexport enum DeliveryRecordStatus {\n /**\n * we don't know (yet) if the message is valid\n */\n unknown,\n /**\n * we know the message is valid\n */\n valid,\n /**\n * we know the message is invalid\n */\n invalid,\n /**\n * we were instructed by the validator to ignore the message\n */\n ignored\n}\n\nexport interface DeliveryRecord {\n status: DeliveryRecordStatus\n firstSeen: number\n validated: number\n peers: Set\n}\n\ninterface DeliveryQueueEntry {\n msgId: string\n expire: number\n}\n\n/**\n * Map of canonical message ID to DeliveryRecord\n *\n * Maintains an internal queue for efficient gc of old messages\n */\nexport class MessageDeliveries {\n private records: Map\n public queue: Denque\n\n constructor() {\n this.records = new Map()\n this.queue = new Denque()\n }\n\n ensureRecord(msgIdStr: string): DeliveryRecord {\n let drec = this.records.get(msgIdStr)\n if (drec) {\n return drec\n }\n\n // record doesn't exist yet\n // create record\n drec = {\n status: DeliveryRecordStatus.unknown,\n firstSeen: Date.now(),\n validated: 0,\n peers: new Set()\n }\n this.records.set(msgIdStr, drec)\n\n // and add msgId to the queue\n const entry: DeliveryQueueEntry = {\n msgId: msgIdStr,\n expire: Date.now() + TimeCacheDuration\n }\n this.queue.push(entry)\n\n return drec\n }\n\n gc(): void {\n const now = Date.now()\n // queue is sorted by expiry time\n // remove expired messages, remove from queue until first un-expired message found\n let head = this.queue.peekFront()\n while (head && head.expire < now) {\n this.records.delete(head.msgId)\n this.queue.shift()\n head = this.queue.peekFront()\n }\n }\n\n clear(): void {\n this.records.clear()\n this.queue.clear()\n }\n}\n", "/**\n * Exclude up to `ineed` items from a set if item meets condition `cond`\n */\nexport function removeItemsFromSet(\n superSet: Set,\n ineed: number,\n cond: (peer: T) => boolean = () => true\n): Set {\n const subset = new Set()\n if (ineed <= 0) return subset\n\n for (const id of superSet) {\n if (subset.size >= ineed) break\n if (cond(id)) {\n subset.add(id)\n superSet.delete(id)\n }\n }\n\n return subset\n}\n\n/**\n * Exclude up to `ineed` items from a set\n */\nexport function removeFirstNItemsFromSet(superSet: Set, ineed: number): Set {\n return removeItemsFromSet(superSet, ineed, () => true)\n}\n\nexport class MapDef extends Map {\n constructor(private readonly getDefault: () => V) {\n super()\n }\n\n getOrDefault(key: K): V {\n let value = super.get(key)\n if (value === undefined) {\n value = this.getDefault()\n this.set(key, value)\n }\n return value\n }\n}\n", "import { PeerScoreParams, validatePeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats, TopicStats } from './peer-stats.js'\nimport { computeScore } from './compute-score.js'\nimport { MessageDeliveries, DeliveryRecordStatus } from './message-deliveries.js'\nimport { logger } from '@libp2p/logger'\nimport { MsgIdStr, PeerIdStr, RejectReason, TopicStr, IPStr } from '../types.js'\nimport type { Metrics, ScorePenalty } from '../metrics.js'\nimport { MapDef } from '../utils/set.js'\n\nconst log = logger('libp2p:gossipsub:score')\n\ninterface PeerScoreOpts {\n /**\n * Miliseconds to cache computed score per peer\n */\n scoreCacheValidityMs: number\n\n computeScore?: typeof computeScore\n}\n\ninterface ScoreCacheEntry {\n /** The cached score */\n score: number\n /** Unix timestamp in miliseconds, the time after which the cached score for a peer is no longer valid */\n cacheUntil: number\n}\n\nexport type PeerScoreStatsDump = Record\n\nexport class PeerScore {\n /**\n * Per-peer stats for score calculation\n */\n readonly peerStats = new Map()\n /**\n * IP colocation tracking; maps IP => set of peers.\n */\n readonly peerIPs = new MapDef>(() => new Set())\n /**\n * Cache score up to decayInterval if topic stats are unchanged.\n */\n readonly scoreCache = new Map()\n /**\n * Recent message delivery timing/participants\n */\n readonly deliveryRecords = new MessageDeliveries()\n\n _backgroundInterval?: ReturnType\n\n private readonly scoreCacheValidityMs: number\n private readonly computeScore: typeof computeScore\n\n constructor(readonly params: PeerScoreParams, private readonly metrics: Metrics | null, opts: PeerScoreOpts) {\n validatePeerScoreParams(params)\n this.scoreCacheValidityMs = opts.scoreCacheValidityMs\n this.computeScore = opts.computeScore ?? computeScore\n }\n\n get size(): number {\n return this.peerStats.size\n }\n\n /**\n * Start PeerScore instance\n */\n start(): void {\n if (this._backgroundInterval) {\n log('Peer score already running')\n return\n }\n this._backgroundInterval = setInterval(() => this.background(), this.params.decayInterval)\n log('started')\n }\n\n /**\n * Stop PeerScore instance\n */\n stop(): void {\n if (!this._backgroundInterval) {\n log('Peer score already stopped')\n return\n }\n clearInterval(this._backgroundInterval)\n delete this._backgroundInterval\n this.peerIPs.clear()\n this.peerStats.clear()\n this.deliveryRecords.clear()\n log('stopped')\n }\n\n /**\n * Periodic maintenance\n */\n background(): void {\n this.refreshScores()\n this.deliveryRecords.gc()\n }\n\n dumpPeerScoreStats(): PeerScoreStatsDump {\n return Object.fromEntries(Array.from(this.peerStats.entries()).map(([peer, stats]) => [peer, stats]))\n }\n\n /**\n * Decays scores, and purges score records for disconnected peers once their expiry has elapsed.\n */\n public refreshScores(): void {\n const now = Date.now()\n const decayToZero = this.params.decayToZero\n\n this.peerStats.forEach((pstats, id) => {\n if (!pstats.connected) {\n // has the retention period expired?\n if (now > pstats.expire) {\n // yes, throw it away (but clean up the IP tracking first)\n this.removeIPsForPeer(id, pstats.knownIPs)\n this.peerStats.delete(id)\n this.scoreCache.delete(id)\n }\n\n // we don't decay retained scores, as the peer is not active.\n // this way the peer cannot reset a negative score by simply disconnecting and reconnecting,\n // unless the retention period has elapsed.\n // similarly, a well behaved peer does not lose its score by getting disconnected.\n return\n }\n\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n const tparams = this.params.topics[topic]\n if (tparams === undefined) {\n // we are not scoring this topic\n // should be unreachable, we only add scored topics to pstats\n return\n }\n\n // decay counters\n tstats.firstMessageDeliveries *= tparams.firstMessageDeliveriesDecay\n if (tstats.firstMessageDeliveries < decayToZero) {\n tstats.firstMessageDeliveries = 0\n }\n\n tstats.meshMessageDeliveries *= tparams.meshMessageDeliveriesDecay\n if (tstats.meshMessageDeliveries < decayToZero) {\n tstats.meshMessageDeliveries = 0\n }\n\n tstats.meshFailurePenalty *= tparams.meshFailurePenaltyDecay\n if (tstats.meshFailurePenalty < decayToZero) {\n tstats.meshFailurePenalty = 0\n }\n\n tstats.invalidMessageDeliveries *= tparams.invalidMessageDeliveriesDecay\n if (tstats.invalidMessageDeliveries < decayToZero) {\n tstats.invalidMessageDeliveries = 0\n }\n\n // update mesh time and activate mesh message delivery parameter if need be\n if (tstats.inMesh) {\n tstats.meshTime = now - tstats.graftTime\n if (tstats.meshTime > tparams.meshMessageDeliveriesActivation) {\n tstats.meshMessageDeliveriesActive = true\n }\n }\n })\n\n // decay P7 counter\n pstats.behaviourPenalty *= this.params.behaviourPenaltyDecay\n if (pstats.behaviourPenalty < decayToZero) {\n pstats.behaviourPenalty = 0\n }\n })\n }\n\n /**\n * Return the score for a peer\n */\n score(id: PeerIdStr): number {\n this.metrics?.scoreFnCalls.inc()\n\n const pstats = this.peerStats.get(id)\n if (!pstats) {\n return 0\n }\n\n const now = Date.now()\n const cacheEntry = this.scoreCache.get(id)\n\n // Found cached score within validity period\n if (cacheEntry && cacheEntry.cacheUntil > now) {\n return cacheEntry.score\n }\n\n this.metrics?.scoreFnRuns.inc()\n\n const score = this.computeScore(id, pstats, this.params, this.peerIPs)\n const cacheUntil = now + this.scoreCacheValidityMs\n\n if (cacheEntry) {\n this.metrics?.scoreCachedDelta.observe(Math.abs(score - cacheEntry.score))\n cacheEntry.score = score\n cacheEntry.cacheUntil = cacheUntil\n } else {\n this.scoreCache.set(id, { score, cacheUntil })\n }\n\n return score\n }\n\n /**\n * Apply a behavioural penalty to a peer\n */\n addPenalty(id: PeerIdStr, penalty: number, penaltyLabel: ScorePenalty): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n pstats.behaviourPenalty += penalty\n this.metrics?.onScorePenalty(penaltyLabel)\n }\n }\n\n addPeer(id: PeerIdStr): void {\n // create peer stats (not including topic stats for each topic to be scored)\n // topic stats will be added as needed\n const pstats: PeerStats = {\n connected: true,\n expire: 0,\n topics: {},\n knownIPs: new Set(),\n behaviourPenalty: 0\n }\n this.peerStats.set(id, pstats)\n }\n\n /** Adds a new IP to a peer, if the peer is not known the update is ignored */\n addIP(id: PeerIdStr, ip: string): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n pstats.knownIPs.add(ip)\n }\n\n this.peerIPs.getOrDefault(ip).add(id)\n }\n\n /** Remove peer association with IP */\n removeIP(id: PeerIdStr, ip: string): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n pstats.knownIPs.delete(ip)\n }\n\n const peersWithIP = this.peerIPs.get(ip)\n if (peersWithIP) {\n peersWithIP.delete(id)\n if (peersWithIP.size === 0) {\n this.peerIPs.delete(ip)\n }\n }\n }\n\n removePeer(id: PeerIdStr): void {\n const pstats = this.peerStats.get(id)\n if (!pstats) {\n return\n }\n\n // decide whether to retain the score; this currently only retains non-positive scores\n // to dissuade attacks on the score function.\n if (this.score(id) > 0) {\n this.removeIPsForPeer(id, pstats.knownIPs)\n this.peerStats.delete(id)\n return\n }\n\n // furthermore, when we decide to retain the score, the firstMessageDelivery counters are\n // reset to 0 and mesh delivery penalties applied.\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n tstats.firstMessageDeliveries = 0\n\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold\n if (tstats.inMesh && tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries\n tstats.meshFailurePenalty += deficit * deficit\n }\n\n tstats.inMesh = false\n tstats.meshMessageDeliveriesActive = false\n })\n\n pstats.connected = false\n pstats.expire = Date.now() + this.params.retainScore\n }\n\n /** Handles scoring functionality as a peer GRAFTs to a topic. */\n graft(id: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n // if we are scoring the topic, update the mesh status.\n tstats.inMesh = true\n tstats.graftTime = Date.now()\n tstats.meshTime = 0\n tstats.meshMessageDeliveriesActive = false\n }\n }\n }\n\n /** Handles scoring functionality as a peer PRUNEs from a topic. */\n prune(id: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n // sticky mesh delivery rate failure penalty\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold\n if (tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries\n tstats.meshFailurePenalty += deficit * deficit\n }\n tstats.meshMessageDeliveriesActive = false\n tstats.inMesh = false\n\n // TODO: Consider clearing score cache on important penalties\n // this.scoreCache.delete(id)\n }\n }\n }\n\n validateMessage(msgIdStr: MsgIdStr): void {\n this.deliveryRecords.ensureRecord(msgIdStr)\n }\n\n deliverMessage(from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr): void {\n this.markFirstMessageDelivery(from, topic)\n\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n const now = Date.now()\n\n // defensive check that this is the first delivery trace -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n log(\n 'unexpected delivery: message from %s was first seen %s ago and has delivery status %s',\n from,\n now - drec.firstSeen,\n DeliveryRecordStatus[drec.status]\n )\n return\n }\n\n // mark the message as valid and reward mesh peers that have already forwarded it to us\n drec.status = DeliveryRecordStatus.valid\n drec.validated = now\n drec.peers.forEach((p) => {\n // this check is to make sure a peer can't send us a message twice and get a double count\n // if it is a first delivery.\n if (p !== from.toString()) {\n this.markDuplicateMessageDelivery(p, topic)\n }\n })\n }\n\n /**\n * Similar to `rejectMessage` except does not require the message id or reason for an invalid message.\n */\n rejectInvalidMessage(from: PeerIdStr, topic: TopicStr): void {\n this.markInvalidMessageDelivery(from, topic)\n }\n\n rejectMessage(from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr, reason: RejectReason): void {\n switch (reason) {\n // these messages are not tracked, but the peer is penalized as they are invalid\n case RejectReason.Error:\n this.markInvalidMessageDelivery(from, topic)\n return\n\n // we ignore those messages, so do nothing.\n case RejectReason.Blacklisted:\n return\n\n // the rest are handled after record creation\n }\n\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n\n // defensive check that this is the first rejection -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n log(\n 'unexpected rejection: message from %s was first seen %s ago and has delivery status %d',\n from,\n Date.now() - drec.firstSeen,\n DeliveryRecordStatus[drec.status]\n )\n return\n }\n\n if (reason === RejectReason.Ignore) {\n // we were explicitly instructed by the validator to ignore the message but not penalize the peer\n drec.status = DeliveryRecordStatus.ignored\n drec.peers.clear()\n return\n }\n\n // mark the message as invalid and penalize peers that have already forwarded it.\n drec.status = DeliveryRecordStatus.invalid\n\n this.markInvalidMessageDelivery(from, topic)\n drec.peers.forEach((p) => {\n this.markInvalidMessageDelivery(p, topic)\n })\n\n // release the delivery time tracking map to free some memory early\n drec.peers.clear()\n }\n\n duplicateMessage(from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr): void {\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n\n if (drec.peers.has(from)) {\n // we have already seen this duplicate\n return\n }\n\n switch (drec.status) {\n case DeliveryRecordStatus.unknown:\n // the message is being validated; track the peer delivery and wait for\n // the Deliver/Reject/Ignore notification.\n drec.peers.add(from)\n break\n\n case DeliveryRecordStatus.valid:\n // mark the peer delivery time to only count a duplicate delivery once.\n drec.peers.add(from)\n this.markDuplicateMessageDelivery(from, topic, drec.validated)\n break\n\n case DeliveryRecordStatus.invalid:\n // we no longer track delivery time\n this.markInvalidMessageDelivery(from, topic)\n break\n\n case DeliveryRecordStatus.ignored:\n // the message was ignored; do nothing (we don't know if it was valid)\n break\n }\n }\n\n /**\n * Increments the \"invalid message deliveries\" counter for all scored topics the message is published in.\n */\n public markInvalidMessageDelivery(from: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(from)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n tstats.invalidMessageDeliveries += 1\n }\n }\n }\n\n /**\n * Increments the \"first message deliveries\" counter for all scored topics the message is published in,\n * as well as the \"mesh message deliveries\" counter, if the peer is in the mesh for the topic.\n * Messages already known (with the seenCache) are counted with markDuplicateMessageDelivery()\n */\n public markFirstMessageDelivery(from: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(from)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n let cap = this.params.topics[topic].firstMessageDeliveriesCap\n tstats.firstMessageDeliveries = Math.min(cap, tstats.firstMessageDeliveries + 1)\n\n if (tstats.inMesh) {\n cap = this.params.topics[topic].meshMessageDeliveriesCap\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1)\n }\n }\n }\n }\n\n /**\n * Increments the \"mesh message deliveries\" counter for messages we've seen before,\n * as long the message was received within the P3 window.\n */\n public markDuplicateMessageDelivery(from: PeerIdStr, topic: TopicStr, validatedTime?: number): void {\n const pstats = this.peerStats.get(from)\n if (pstats) {\n const now = validatedTime !== undefined ? Date.now() : 0\n\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats && tstats.inMesh) {\n const tparams = this.params.topics[topic]\n\n // check against the mesh delivery window -- if the validated time is passed as 0, then\n // the message was received before we finished validation and thus falls within the mesh\n // delivery window.\n if (validatedTime !== undefined) {\n const deliveryDelayMs = now - validatedTime\n const isLateDelivery = deliveryDelayMs > tparams.meshMessageDeliveriesWindow\n this.metrics?.onDuplicateMsgDelivery(topic, deliveryDelayMs, isLateDelivery)\n\n if (isLateDelivery) {\n return\n }\n }\n\n const cap = tparams.meshMessageDeliveriesCap\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1)\n }\n }\n }\n\n /**\n * Removes an IP list from the tracking list for a peer.\n */\n private removeIPsForPeer(id: PeerIdStr, ipsToRemove: Set): void {\n for (const ipToRemove of ipsToRemove) {\n const peerSet = this.peerIPs.get(ipToRemove)\n if (peerSet) {\n peerSet.delete(id)\n if (peerSet.size === 0) {\n this.peerIPs.delete(ipToRemove)\n }\n }\n }\n }\n\n /**\n * Returns topic stats if they exist, otherwise if the supplied parameters score the\n * topic, inserts the default stats and returns a reference to those. If neither apply, returns None.\n */\n private getPtopicStats(pstats: PeerStats, topic: TopicStr): TopicStats | null {\n let topicStats: TopicStats | undefined = pstats.topics[topic]\n\n if (topicStats !== undefined) {\n return topicStats\n }\n\n if (this.params.topics[topic] !== undefined) {\n topicStats = {\n inMesh: false,\n graftTime: 0,\n meshTime: 0,\n firstMessageDeliveries: 0,\n meshMessageDeliveries: 0,\n meshMessageDeliveriesActive: false,\n meshFailurePenalty: 0,\n invalidMessageDeliveries: 0\n }\n pstats.topics[topic] = topicStats\n\n return topicStats\n }\n\n return null\n }\n}\n", "import { MsgIdStr, MsgIdToStrFn, PeerIdStr, RejectReason } from './types.js'\nimport type { Metrics } from './metrics.js'\n\n/**\n * IWantTracer is an internal tracer that tracks IWANT requests in order to penalize\n * peers who don't follow up on IWANT requests after an IHAVE advertisement.\n * The tracking of promises is probabilistic to avoid using too much memory.\n *\n * Note: Do not confuse these 'promises' with JS Promise objects.\n * These 'promises' are merely expectations of a peer's behavior.\n */\nexport class IWantTracer {\n /**\n * Promises to deliver a message\n * Map per message id, per peer, promise expiration time\n */\n private readonly promises = new Map>()\n /**\n * First request time by msgId. Used for metrics to track expire times.\n * Necessary to know if peers are actually breaking promises or simply sending them a bit later\n */\n private readonly requestMsByMsg = new Map()\n private readonly requestMsByMsgExpire: number\n\n constructor(\n private readonly gossipsubIWantFollowupMs: number,\n private readonly msgIdToStrFn: MsgIdToStrFn,\n private readonly metrics: Metrics | null\n ) {\n this.requestMsByMsgExpire = 10 * gossipsubIWantFollowupMs\n }\n\n get size(): number {\n return this.promises.size\n }\n\n get requestMsByMsgSize(): number {\n return this.requestMsByMsg.size\n }\n\n /**\n * Track a promise to deliver a message from a list of msgIds we are requesting\n */\n addPromise(from: PeerIdStr, msgIds: Uint8Array[]): void {\n // pick msgId randomly from the list\n const ix = Math.floor(Math.random() * msgIds.length)\n const msgId = msgIds[ix]\n const msgIdStr = this.msgIdToStrFn(msgId)\n\n let expireByPeer = this.promises.get(msgIdStr)\n if (!expireByPeer) {\n expireByPeer = new Map()\n this.promises.set(msgIdStr, expireByPeer)\n }\n\n const now = Date.now()\n\n // If a promise for this message id and peer already exists we don't update the expiry\n if (!expireByPeer.has(from)) {\n expireByPeer.set(from, now + this.gossipsubIWantFollowupMs)\n\n if (this.metrics) {\n this.metrics.iwantPromiseStarted.inc(1)\n if (!this.requestMsByMsg.has(msgIdStr)) {\n this.requestMsByMsg.set(msgIdStr, now)\n }\n }\n }\n }\n\n /**\n * Returns the number of broken promises for each peer who didn't follow up on an IWANT request.\n *\n * This should be called not too often relative to the expire times, since it iterates over the whole data.\n */\n getBrokenPromises(): Map {\n const now = Date.now()\n const result = new Map()\n\n let brokenPromises = 0\n\n this.promises.forEach((expireByPeer, msgId) => {\n expireByPeer.forEach((expire, p) => {\n // the promise has been broken\n if (expire < now) {\n // add 1 to result\n result.set(p, (result.get(p) ?? 0) + 1)\n // delete from tracked promises\n expireByPeer.delete(p)\n // for metrics\n brokenPromises++\n }\n })\n // clean up empty promises for a msgId\n if (!expireByPeer.size) {\n this.promises.delete(msgId)\n }\n })\n\n this.metrics?.iwantPromiseBroken.inc(brokenPromises)\n\n return result\n }\n\n /**\n * Someone delivered a message, stop tracking promises for it\n */\n deliverMessage(msgIdStr: MsgIdStr, isDuplicate = false): void {\n this.trackMessage(msgIdStr)\n\n const expireByPeer = this.promises.get(msgIdStr)\n\n // Expired promise, check requestMsByMsg\n if (expireByPeer) {\n this.promises.delete(msgIdStr)\n\n if (this.metrics) {\n this.metrics.iwantPromiseResolved.inc(1)\n if (isDuplicate) this.metrics.iwantPromiseResolvedFromDuplicate.inc(1)\n this.metrics.iwantPromiseResolvedPeers.inc(expireByPeer.size)\n }\n }\n }\n\n /**\n * A message got rejected, so we can stop tracking promises and let the score penalty apply from invalid message delivery,\n * unless its an obviously invalid message.\n */\n rejectMessage(msgIdStr: MsgIdStr, reason: RejectReason): void {\n this.trackMessage(msgIdStr)\n\n // A message got rejected, so we can stop tracking promises and let the score penalty apply.\n // With the expection of obvious invalid messages\n switch (reason) {\n case RejectReason.Error:\n return\n }\n\n this.promises.delete(msgIdStr)\n }\n\n clear(): void {\n this.promises.clear()\n }\n\n prune(): void {\n const maxMs = Date.now() - this.requestMsByMsgExpire\n let count = 0\n\n for (const [k, v] of this.requestMsByMsg.entries()) {\n if (v < maxMs) {\n // messages that stay too long in the requestMsByMsg map, delete\n this.requestMsByMsg.delete(k)\n count++\n } else {\n // recent messages, keep them\n // sort by insertion order\n break\n }\n }\n\n this.metrics?.iwantMessagePruned.inc(count)\n }\n\n private trackMessage(msgIdStr: MsgIdStr): void {\n if (this.metrics) {\n const requestMs = this.requestMsByMsg.get(msgIdStr)\n if (requestMs !== undefined) {\n this.metrics.iwantPromiseDeliveryTime.observe((Date.now() - requestMs) / 1000)\n this.requestMsByMsg.delete(msgIdStr)\n }\n }\n }\n}\n", "type SimpleTimeCacheOpts = {\n validityMs: number\n}\n\ntype CacheValue = {\n value: T\n validUntilMs: number\n}\n\n/**\n * This is similar to https://github.com/daviddias/time-cache/blob/master/src/index.js\n * for our own need, we don't use lodash throttle to improve performance.\n * This gives 4x - 5x performance gain compared to npm TimeCache\n */\nexport class SimpleTimeCache {\n private readonly entries = new Map>()\n private readonly validityMs: number\n\n constructor(opts: SimpleTimeCacheOpts) {\n this.validityMs = opts.validityMs\n\n // allow negative validityMs so that this does not cache anything, spec test compliance.spec.js\n // sends duplicate messages and expect peer to receive all. Application likely uses positive validityMs\n }\n\n get size(): number {\n return this.entries.size\n }\n\n /** Returns true if there was a key collision and the entry is dropped */\n put(key: string | number, value: T): boolean {\n if (this.entries.has(key)) {\n // Key collisions break insertion order in the entries cache, which break prune logic.\n // prune relies on each iterated entry to have strictly ascending validUntilMs, else it\n // won't prune expired entries and SimpleTimeCache will grow unexpectedly.\n // As of Oct 2022 NodeJS v16, inserting the same key twice with different value does not\n // change the key position in the iterator stream. A unit test asserts this behaviour.\n return true\n }\n\n this.entries.set(key, { value, validUntilMs: Date.now() + this.validityMs })\n return false\n }\n\n prune(): void {\n const now = Date.now()\n\n for (const [k, v] of this.entries.entries()) {\n if (v.validUntilMs < now) {\n this.entries.delete(k)\n } else {\n // Entries are inserted with strictly ascending validUntilMs.\n // Stop early to save iterations\n break\n }\n }\n }\n\n has(key: string): boolean {\n return this.entries.has(key)\n }\n\n get(key: string | number): T | undefined {\n const value = this.entries.get(key)\n return value && value.validUntilMs >= Date.now() ? value.value : undefined\n }\n\n clear(): void {\n this.entries.clear()\n }\n}\n", "import { TopicValidatorResult } from '@libp2p/interface-pubsub'\nimport type { IRPC } from './message/rpc.js'\nimport type { PeerScoreThresholds } from './score/peer-score-thresholds.js'\nimport { MessageStatus, PeerIdStr, RejectReason, RejectReasonObj, TopicStr, ValidateError } from './types.js'\n\n/** Topic label as provided in `topicStrToLabel` */\nexport type TopicLabel = string\nexport type TopicStrToLabel = Map\n\nexport enum MessageSource {\n forward = 'forward',\n publish = 'publish'\n}\n\ntype LabelsGeneric = Record\ntype CollectFn = (metric: Gauge) => void\n\ninterface Gauge {\n // Sorry for this mess, `prom-client` API choices are not great\n // If the function signature was `inc(value: number, labels?: Labels)`, this would be simpler\n inc(value?: number): void\n inc(labels: Labels, value?: number): void\n inc(arg1?: Labels | number, arg2?: number): void\n\n set(value: number): void\n set(labels: Labels, value: number): void\n set(arg1?: Labels | number, arg2?: number): void\n\n addCollect(collectFn: CollectFn): void\n}\n\ninterface Histogram {\n startTimer(): () => void\n\n observe(value: number): void\n observe(labels: Labels, values: number): void\n observe(arg1: Labels | number, arg2?: number): void\n\n reset(): void\n}\n\ninterface AvgMinMax {\n set(values: number[]): void\n set(labels: Labels, values: number[]): void\n set(arg1?: Labels | number[], arg2?: number[]): void\n}\n\ntype GaugeConfig = {\n name: string\n help: string\n labelNames?: keyof Labels extends string ? (keyof Labels)[] : undefined\n}\n\ntype HistogramConfig = {\n name: string\n help: string\n labelNames?: (keyof Labels)[]\n buckets?: number[]\n}\n\ntype AvgMinMaxConfig = GaugeConfig\n\nexport interface MetricsRegister {\n gauge(config: GaugeConfig): Gauge\n histogram(config: HistogramConfig): Histogram\n avgMinMax(config: AvgMinMaxConfig): AvgMinMax\n}\n\nexport enum InclusionReason {\n /** Peer was a fanaout peer. */\n Fanout = 'fanout',\n /** Included from random selection. */\n Random = 'random',\n /** Peer subscribed. */\n Subscribed = 'subscribed',\n /** On heartbeat, peer was included to fill the outbound quota. */\n Outbound = 'outbound',\n /** On heartbeat, not enough peers in mesh */\n NotEnough = 'not_enough',\n /** On heartbeat opportunistic grafting due to low mesh score */\n Opportunistic = 'opportunistic'\n}\n\n/// Reasons why a peer was removed from the mesh.\nexport enum ChurnReason {\n /// Peer disconnected.\n Dc = 'disconnected',\n /// Peer had a bad score.\n BadScore = 'bad_score',\n /// Peer sent a PRUNE.\n Prune = 'prune',\n /// Peer unsubscribed.\n Unsub = 'unsubscribed',\n /// Too many peers.\n Excess = 'excess'\n}\n\n/// Kinds of reasons a peer's score has been penalized\nexport enum ScorePenalty {\n /// A peer grafted before waiting the back-off time.\n GraftBackoff = 'graft_backoff',\n /// A Peer did not respond to an IWANT request in time.\n BrokenPromise = 'broken_promise',\n /// A Peer did not send enough messages as expected.\n MessageDeficit = 'message_deficit',\n /// Too many peers under one IP address.\n IPColocation = 'IP_colocation'\n}\n\nexport enum IHaveIgnoreReason {\n LowScore = 'low_score',\n MaxIhave = 'max_ihave',\n MaxIasked = 'max_iasked'\n}\n\nexport enum ScoreThreshold {\n graylist = 'graylist',\n publish = 'publish',\n gossip = 'gossip',\n mesh = 'mesh'\n}\n\nexport type PeersByScoreThreshold = Record\n\nexport type ToSendGroupCount = {\n direct: number\n floodsub: number\n mesh: number\n fanout: number\n}\n\nexport type ToAddGroupCount = {\n fanout: number\n random: number\n}\n\nexport type PromiseDeliveredStats =\n | { expired: false; requestedCount: number; maxDeliverMs: number }\n | { expired: true; maxDeliverMs: number }\n\nexport type TopicScoreWeights = { p1w: T; p2w: T; p3w: T; p3bw: T; p4w: T }\nexport type ScoreWeights = {\n byTopic: Map>\n p5w: T\n p6w: T\n p7w: T\n score: T\n}\n\nexport type Metrics = ReturnType\n\n/**\n * A collection of metrics used throughout the Gossipsub behaviour.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function getMetrics(\n register: MetricsRegister,\n topicStrToLabel: TopicStrToLabel,\n opts: { gossipPromiseExpireSec: number; behaviourPenaltyThreshold: number; maxMeshMessageDeliveriesWindowSec: number }\n) {\n // Using function style instead of class to prevent having to re-declare all MetricsPrometheus types.\n\n return {\n /* Metrics for static config */\n protocolsEnabled: register.gauge<{ protocol: string }>({\n name: 'gossipsub_protocol',\n help: 'Status of enabled protocols',\n labelNames: ['protocol']\n }),\n\n /* Metrics per known topic */\n /** Status of our subscription to this topic. This metric allows analyzing other topic metrics\n * filtered by our current subscription status.\n * = rust-libp2p `topic_subscription_status` */\n topicSubscriptionStatus: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_topic_subscription_status',\n help: 'Status of our subscription to this topic',\n labelNames: ['topicStr']\n }),\n /** Number of peers subscribed to each topic. This allows us to analyze a topic's behaviour\n * regardless of our subscription status. */\n topicPeersCount: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_topic_peer_count',\n help: 'Number of peers subscribed to each topic',\n labelNames: ['topicStr']\n }),\n\n /* Metrics regarding mesh state */\n /** Number of peers in our mesh. This metric should be updated with the count of peers for a\n * topic in the mesh regardless of inclusion and churn events.\n * = rust-libp2p `mesh_peer_counts` */\n meshPeerCounts: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_mesh_peer_count',\n help: 'Number of peers in our mesh',\n labelNames: ['topicStr']\n }),\n /** Number of times we include peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_inclusion_events` */\n meshPeerInclusionEvents: register.gauge<{ topic: TopicLabel; reason: InclusionReason }>({\n name: 'gossipsub_mesh_peer_inclusion_events_total',\n help: 'Number of times we include peers in a topic mesh for different reasons',\n labelNames: ['topic', 'reason']\n }),\n /** Number of times we remove peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_churn_events` */\n meshPeerChurnEvents: register.gauge<{ topic: TopicLabel; reason: ChurnReason }>({\n name: 'gossipsub_peer_churn_events_total',\n help: 'Number of times we remove peers in a topic mesh for different reasons',\n labelNames: ['topic', 'reason']\n }),\n\n /* General Metrics */\n /** Gossipsub supports floodsub, gossipsub v1.0 and gossipsub v1.1. Peers are classified based\n * on which protocol they support. This metric keeps track of the number of peers that are\n * connected of each type. */\n peersPerProtocol: register.gauge<{ protocol: string }>({\n name: 'gossipsub_peers_per_protocol_count',\n help: 'Peers connected for each topic',\n labelNames: ['protocol']\n }),\n /** The time it takes to complete one iteration of the heartbeat. */\n heartbeatDuration: register.histogram({\n name: 'gossipsub_heartbeat_duration_seconds',\n help: 'The time it takes to complete one iteration of the heartbeat',\n // Should take <10ms, over 1s it's a huge issue that needs debugging, since a heartbeat will be cancelled\n buckets: [0.01, 0.1, 1]\n }),\n /** Heartbeat run took longer than heartbeat interval so next is skipped */\n heartbeatSkipped: register.gauge({\n name: 'gossipsub_heartbeat_skipped',\n help: 'Heartbeat run took longer than heartbeat interval so next is skipped'\n }),\n\n /** Message validation results for each topic.\n * Invalid == Reject?\n * = rust-libp2p `invalid_messages`, `accepted_messages`, `ignored_messages`, `rejected_messages` */\n asyncValidationResult: register.gauge<{ topic: TopicLabel; acceptance: TopicValidatorResult }>({\n name: 'gossipsub_async_validation_result_total',\n help: 'Message validation result for each topic',\n labelNames: ['topic', 'acceptance']\n }),\n /** When the user validates a message, it tries to re propagate it to its mesh peers. If the\n * message expires from the memcache before it can be validated, we count this a cache miss\n * and it is an indicator that the memcache size should be increased.\n * = rust-libp2p `mcache_misses` */\n asyncValidationMcacheHit: register.gauge<{ hit: 'hit' | 'miss' }>({\n name: 'gossipsub_async_validation_mcache_hit_total',\n help: 'Async validation result reported by the user layer',\n labelNames: ['hit']\n }),\n\n // peer stream\n peerReadStreamError: register.gauge({\n name: 'gossipsub_peer_read_stream_err_count_total',\n help: 'Peer read stream error'\n }),\n\n // RPC outgoing. Track byte length + data structure sizes\n rpcRecvBytes: register.gauge({ name: 'gossipsub_rpc_recv_bytes_total', help: 'RPC recv' }),\n rpcRecvCount: register.gauge({ name: 'gossipsub_rpc_recv_count_total', help: 'RPC recv' }),\n rpcRecvSubscription: register.gauge({ name: 'gossipsub_rpc_recv_subscription_total', help: 'RPC recv' }),\n rpcRecvMessage: register.gauge({ name: 'gossipsub_rpc_recv_message_total', help: 'RPC recv' }),\n rpcRecvControl: register.gauge({ name: 'gossipsub_rpc_recv_control_total', help: 'RPC recv' }),\n rpcRecvIHave: register.gauge({ name: 'gossipsub_rpc_recv_ihave_total', help: 'RPC recv' }),\n rpcRecvIWant: register.gauge({ name: 'gossipsub_rpc_recv_iwant_total', help: 'RPC recv' }),\n rpcRecvGraft: register.gauge({ name: 'gossipsub_rpc_recv_graft_total', help: 'RPC recv' }),\n rpcRecvPrune: register.gauge({ name: 'gossipsub_rpc_recv_prune_total', help: 'RPC recv' }),\n rpcDataError: register.gauge({ name: 'gossipsub_rpc_data_err_count_total', help: 'RPC data error' }),\n rpcRecvError: register.gauge({ name: 'gossipsub_rpc_recv_err_count_total', help: 'RPC recv error' }),\n\n /** Total count of RPC dropped because acceptFrom() == false */\n rpcRecvNotAccepted: register.gauge({\n name: 'gossipsub_rpc_rcv_not_accepted_total',\n help: 'Total count of RPC dropped because acceptFrom() == false'\n }),\n\n // RPC incoming. Track byte length + data structure sizes\n rpcSentBytes: register.gauge({ name: 'gossipsub_rpc_sent_bytes_total', help: 'RPC sent' }),\n rpcSentCount: register.gauge({ name: 'gossipsub_rpc_sent_count_total', help: 'RPC sent' }),\n rpcSentSubscription: register.gauge({ name: 'gossipsub_rpc_sent_subscription_total', help: 'RPC sent' }),\n rpcSentMessage: register.gauge({ name: 'gossipsub_rpc_sent_message_total', help: 'RPC sent' }),\n rpcSentControl: register.gauge({ name: 'gossipsub_rpc_sent_control_total', help: 'RPC sent' }),\n rpcSentIHave: register.gauge({ name: 'gossipsub_rpc_sent_ihave_total', help: 'RPC sent' }),\n rpcSentIWant: register.gauge({ name: 'gossipsub_rpc_sent_iwant_total', help: 'RPC sent' }),\n rpcSentGraft: register.gauge({ name: 'gossipsub_rpc_sent_graft_total', help: 'RPC sent' }),\n rpcSentPrune: register.gauge({ name: 'gossipsub_rpc_sent_prune_total', help: 'RPC sent' }),\n\n // publish message. Track peers sent to and bytes\n /** Total count of msg published by topic */\n msgPublishCount: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_count_total',\n help: 'Total count of msg published by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we publish a msg to */\n msgPublishPeers: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_peers_total',\n help: 'Total count of peers that we publish a msg to',\n labelNames: ['topic']\n }),\n /** Total count of peers (by group) that we publish a msg to */\n // NOTE: Do not use 'group' label since it's a generic already used by Prometheus to group instances\n msgPublishPeersByGroup: register.gauge<{ topic: TopicLabel; peerGroup: keyof ToSendGroupCount }>({\n name: 'gossipsub_msg_publish_peers_by_group',\n help: 'Total count of peers (by group) that we publish a msg to',\n labelNames: ['topic', 'peerGroup']\n }),\n /** Total count of msg publish data.length bytes */\n msgPublishBytes: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_bytes_total',\n help: 'Total count of msg publish data.length bytes',\n labelNames: ['topic']\n }),\n\n /** Total count of msg forwarded by topic */\n msgForwardCount: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_forward_count_total',\n help: 'Total count of msg forwarded by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we forward a msg to */\n msgForwardPeers: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_forward_peers_total',\n help: 'Total count of peers that we forward a msg to',\n labelNames: ['topic']\n }),\n\n /** Total count of recv msgs before any validation */\n msgReceivedPreValidation: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_prevalidation_total',\n help: 'Total count of recv msgs before any validation',\n labelNames: ['topic']\n }),\n /** Total count of recv msgs error */\n msgReceivedError: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_error_total',\n help: 'Total count of recv msgs error',\n labelNames: ['topic']\n }),\n /** Tracks distribution of recv msgs by duplicate, invalid, valid */\n msgReceivedStatus: register.gauge<{ topic: TopicLabel; status: MessageStatus }>({\n name: 'gossipsub_msg_received_status_total',\n help: 'Tracks distribution of recv msgs by duplicate, invalid, valid',\n labelNames: ['topic', 'status']\n }),\n /** Tracks specific reason of invalid */\n msgReceivedInvalid: register.gauge<{ topic: TopicLabel; error: RejectReason | ValidateError }>({\n name: 'gossipsub_msg_received_invalid_total',\n help: 'Tracks specific reason of invalid',\n labelNames: ['topic', 'error']\n }),\n /** Track duplicate message delivery time */\n duplicateMsgDeliveryDelay: register.histogram({\n name: 'gossisub_duplicate_msg_delivery_delay_seconds',\n help: 'Time since the 1st duplicated message validated',\n labelNames: ['topic'],\n buckets: [\n 0.25 * opts.maxMeshMessageDeliveriesWindowSec,\n 0.5 * opts.maxMeshMessageDeliveriesWindowSec,\n 1 * opts.maxMeshMessageDeliveriesWindowSec,\n 2 * opts.maxMeshMessageDeliveriesWindowSec,\n 4 * opts.maxMeshMessageDeliveriesWindowSec\n ]\n }),\n /** Total count of late msg delivery total by topic */\n duplicateMsgLateDelivery: register.gauge<{ topic: TopicLabel }>({\n name: 'gossisub_duplicate_msg_late_delivery_total',\n help: 'Total count of late duplicate message delivery by topic, which triggers P3 penalty',\n labelNames: ['topic']\n }),\n\n duplicateMsgIgnored: register.gauge<{ topic: TopicLabel }>({\n name: 'gossisub_ignored_published_duplicate_msgs_total',\n help: 'Total count of published duplicate message ignored by topic',\n labelNames: ['topic']\n }),\n\n /* Metrics related to scoring */\n /** Total times score() is called */\n scoreFnCalls: register.gauge({\n name: 'gossipsub_score_fn_calls_total',\n help: 'Total times score() is called'\n }),\n /** Total times score() call actually computed computeScore(), no cache */\n scoreFnRuns: register.gauge({\n name: 'gossipsub_score_fn_runs_total',\n help: 'Total times score() call actually computed computeScore(), no cache'\n }),\n scoreCachedDelta: register.histogram({\n name: 'gossipsub_score_cache_delta',\n help: 'Delta of score between cached values that expired',\n buckets: [10, 100, 1000]\n }),\n /** Current count of peers by score threshold */\n peersByScoreThreshold: register.gauge<{ threshold: ScoreThreshold }>({\n name: 'gossipsub_peers_by_score_threshold_count',\n help: 'Current count of peers by score threshold',\n labelNames: ['threshold']\n }),\n score: register.avgMinMax({\n name: 'gossipsub_score',\n help: 'Avg min max of gossip scores',\n labelNames: ['topic', 'p']\n }),\n /** Separate score weights */\n scoreWeights: register.avgMinMax<{ topic?: TopicLabel; p: string }>({\n name: 'gossipsub_score_weights',\n help: 'Separate score weights',\n labelNames: ['topic', 'p']\n }),\n /** Histogram of the scores for each mesh topic. */\n // TODO: Not implemented\n scorePerMesh: register.avgMinMax<{ topic: TopicLabel }>({\n name: 'gossipsub_score_per_mesh',\n help: 'Histogram of the scores for each mesh topic',\n labelNames: ['topic']\n }),\n /** A counter of the kind of penalties being applied to peers. */\n // TODO: Not fully implemented\n scoringPenalties: register.gauge<{ penalty: ScorePenalty }>({\n name: 'gossipsub_scoring_penalties_total',\n help: 'A counter of the kind of penalties being applied to peers',\n labelNames: ['penalty']\n }),\n behaviourPenalty: register.histogram({\n name: 'gossipsub_peer_stat_behaviour_penalty',\n help: 'Current peer stat behaviour_penalty at each scrape',\n buckets: [\n 0.25 * opts.behaviourPenaltyThreshold,\n 0.5 * opts.behaviourPenaltyThreshold,\n 1 * opts.behaviourPenaltyThreshold,\n 2 * opts.behaviourPenaltyThreshold,\n 4 * opts.behaviourPenaltyThreshold\n ]\n }),\n\n // TODO:\n // - iasked per peer (on heartbeat)\n // - when promise is resolved, track messages from promises\n\n /** Total received IHAVE messages that we ignore for some reason */\n ihaveRcvIgnored: register.gauge<{ reason: IHaveIgnoreReason }>({\n name: 'gossipsub_ihave_rcv_ignored_total',\n help: 'Total received IHAVE messages that we ignore for some reason',\n labelNames: ['reason']\n }),\n /** Total received IHAVE messages by topic */\n ihaveRcvMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ihave_rcv_msgids_total',\n help: 'Total received IHAVE messages by topic',\n labelNames: ['topic']\n }),\n /** Total messages per topic we don't have. Not actual requests.\n * The number of times we have decided that an IWANT control message is required for this\n * topic. A very high metric might indicate an underperforming network.\n * = rust-libp2p `topic_iwant_msgs` */\n ihaveRcvNotSeenMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ihave_rcv_not_seen_msgids_total',\n help: 'Total messages per topic we do not have, not actual requests',\n labelNames: ['topic']\n }),\n\n /** Total received IWANT messages by topic */\n iwantRcvMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_iwant_rcv_msgids_total',\n help: 'Total received IWANT messages by topic',\n labelNames: ['topic']\n }),\n /** Total requested messageIDs that we don't have */\n iwantRcvDonthaveMsgids: register.gauge({\n name: 'gossipsub_iwant_rcv_dont_have_msgids_total',\n help: 'Total requested messageIDs that we do not have'\n }),\n iwantPromiseStarted: register.gauge({\n name: 'gossipsub_iwant_promise_sent_total',\n help: 'Total count of started IWANT promises'\n }),\n /** Total count of resolved IWANT promises */\n iwantPromiseResolved: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_total',\n help: 'Total count of resolved IWANT promises'\n }),\n /** Total count of resolved IWANT promises from duplicate messages */\n iwantPromiseResolvedFromDuplicate: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_from_duplicate_total',\n help: 'Total count of resolved IWANT promises from duplicate messages'\n }),\n /** Total count of peers we have asked IWANT promises that are resolved */\n iwantPromiseResolvedPeers: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_peers',\n help: 'Total count of peers we have asked IWANT promises that are resolved'\n }),\n iwantPromiseBroken: register.gauge({\n name: 'gossipsub_iwant_promise_broken',\n help: 'Total count of broken IWANT promises'\n }),\n iwantMessagePruned: register.gauge({\n name: 'gossipsub_iwant_message_pruned',\n help: 'Total count of pruned IWANT messages'\n }),\n /** Histogram of delivery time of resolved IWANT promises */\n iwantPromiseDeliveryTime: register.histogram({\n name: 'gossipsub_iwant_promise_delivery_seconds',\n help: 'Histogram of delivery time of resolved IWANT promises',\n buckets: [\n 0.5 * opts.gossipPromiseExpireSec,\n 1 * opts.gossipPromiseExpireSec,\n 2 * opts.gossipPromiseExpireSec,\n 4 * opts.gossipPromiseExpireSec\n ]\n }),\n iwantPromiseUntracked: register.gauge({\n name: 'gossip_iwant_promise_untracked',\n help: 'Total count of untracked IWANT promise'\n }),\n\n /* Data structure sizes */\n /** Unbounded cache sizes */\n cacheSize: register.gauge<{ cache: string }>({\n name: 'gossipsub_cache_size',\n help: 'Unbounded cache sizes',\n labelNames: ['cache']\n }),\n /** Current mcache msg count */\n mcacheSize: register.gauge({\n name: 'gossipsub_mcache_size',\n help: 'Current mcache msg count'\n }),\n mcacheNotValidatedCount: register.gauge({\n name: 'gossipsub_mcache_not_validated_count',\n help: 'Current mcache msg count not validated'\n }),\n\n fastMsgIdCacheCollision: register.gauge({\n name: 'gossipsub_fastmsgid_cache_collision_total',\n help: 'Total count of key collisions on fastmsgid cache put'\n }),\n\n newConnectionCount: register.gauge<{ status: string }>({\n name: 'gossipsub_new_connection_total',\n help: 'Total new connection by status',\n labelNames: ['status']\n }),\n\n topicStrToLabel: topicStrToLabel,\n\n toTopic(topicStr: TopicStr): TopicLabel {\n return this.topicStrToLabel.get(topicStr) ?? topicStr\n },\n\n /** We joined a topic */\n onJoin(topicStr: TopicStr): void {\n this.topicSubscriptionStatus.set({ topicStr }, 1)\n this.meshPeerCounts.set({ topicStr }, 0) // Reset count\n },\n\n /** We left a topic */\n onLeave(topicStr: TopicStr): void {\n this.topicSubscriptionStatus.set({ topicStr }, 0)\n this.meshPeerCounts.set({ topicStr }, 0) // Reset count\n },\n\n /** Register the inclusion of peers in our mesh due to some reason. */\n onAddToMesh(topicStr: TopicStr, reason: InclusionReason, count: number): void {\n const topic = this.toTopic(topicStr)\n this.meshPeerInclusionEvents.inc({ topic, reason }, count)\n },\n\n /** Register the removal of peers in our mesh due to some reason */\n // - remove_peer_from_mesh()\n // - heartbeat() Churn::BadScore\n // - heartbeat() Churn::Excess\n // - on_disconnect() Churn::Ds\n onRemoveFromMesh(topicStr: TopicStr, reason: ChurnReason, count: number): void {\n const topic = this.toTopic(topicStr)\n this.meshPeerChurnEvents.inc({ topic, reason }, count)\n },\n\n onReportValidationMcacheHit(hit: boolean): void {\n this.asyncValidationMcacheHit.inc({ hit: hit ? 'hit' : 'miss' })\n },\n\n onReportValidation(topicStr: TopicStr, acceptance: TopicValidatorResult): void {\n const topic = this.toTopic(topicStr)\n this.asyncValidationResult.inc({ topic: topic, acceptance })\n },\n\n /**\n * - in handle_graft() Penalty::GraftBackoff\n * - in apply_iwant_penalties() Penalty::BrokenPromise\n * - in metric_score() P3 Penalty::MessageDeficit\n * - in metric_score() P6 Penalty::IPColocation\n */\n onScorePenalty(penalty: ScorePenalty): void {\n // Can this be labeled by topic too?\n this.scoringPenalties.inc({ penalty }, 1)\n },\n\n onIhaveRcv(topicStr: TopicStr, ihave: number, idonthave: number): void {\n const topic = this.toTopic(topicStr)\n this.ihaveRcvMsgids.inc({ topic }, ihave)\n this.ihaveRcvNotSeenMsgids.inc({ topic }, idonthave)\n },\n\n onIwantRcv(iwantByTopic: Map, iwantDonthave: number): void {\n for (const [topicStr, iwant] of iwantByTopic) {\n const topic = this.toTopic(topicStr)\n this.iwantRcvMsgids.inc({ topic }, iwant)\n }\n\n this.iwantRcvDonthaveMsgids.inc(iwantDonthave)\n },\n\n onForwardMsg(topicStr: TopicStr, tosendCount: number): void {\n const topic = this.toTopic(topicStr)\n this.msgForwardCount.inc({ topic }, 1)\n this.msgForwardPeers.inc({ topic }, tosendCount)\n },\n\n onPublishMsg(topicStr: TopicStr, tosendGroupCount: ToSendGroupCount, tosendCount: number, dataLen: number): void {\n const topic = this.toTopic(topicStr)\n this.msgPublishCount.inc({ topic }, 1)\n this.msgPublishBytes.inc({ topic }, tosendCount * dataLen)\n this.msgPublishPeers.inc({ topic }, tosendCount)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'direct' }, tosendGroupCount.direct)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'floodsub' }, tosendGroupCount.floodsub)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'mesh' }, tosendGroupCount.mesh)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'fanout' }, tosendGroupCount.fanout)\n },\n\n onMsgRecvPreValidation(topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedPreValidation.inc({ topic }, 1)\n },\n\n onMsgRecvError(topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedError.inc({ topic }, 1)\n },\n\n onMsgRecvResult(topicStr: TopicStr, status: MessageStatus): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedStatus.inc({ topic, status })\n },\n\n onMsgRecvInvalid(topicStr: TopicStr, reason: RejectReasonObj): void {\n const topic = this.toTopic(topicStr)\n\n const error = reason.reason === RejectReason.Error ? reason.error : reason.reason\n this.msgReceivedInvalid.inc({ topic, error }, 1)\n },\n\n onDuplicateMsgDelivery(topicStr: TopicStr, deliveryDelayMs: number, isLateDelivery: boolean): void {\n this.duplicateMsgDeliveryDelay.observe(deliveryDelayMs / 1000)\n if (isLateDelivery) {\n const topic = this.toTopic(topicStr)\n this.duplicateMsgLateDelivery.inc({ topic }, 1)\n }\n },\n\n onPublishDuplicateMsg(topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.duplicateMsgIgnored.inc({ topic }, 1)\n },\n\n onPeerReadStreamError(): void {\n this.peerReadStreamError.inc(1)\n },\n\n onRpcRecvError(): void {\n this.rpcRecvError.inc(1)\n },\n\n onRpcDataError(): void {\n this.rpcDataError.inc(1)\n },\n\n onRpcRecv(rpc: IRPC, rpcBytes: number): void {\n this.rpcRecvBytes.inc(rpcBytes)\n this.rpcRecvCount.inc(1)\n if (rpc.subscriptions) this.rpcRecvSubscription.inc(rpc.subscriptions.length)\n if (rpc.messages) this.rpcRecvMessage.inc(rpc.messages.length)\n if (rpc.control) {\n this.rpcRecvControl.inc(1)\n if (rpc.control.ihave) this.rpcRecvIHave.inc(rpc.control.ihave.length)\n if (rpc.control.iwant) this.rpcRecvIWant.inc(rpc.control.iwant.length)\n if (rpc.control.graft) this.rpcRecvGraft.inc(rpc.control.graft.length)\n if (rpc.control.prune) this.rpcRecvPrune.inc(rpc.control.prune.length)\n }\n },\n\n onRpcSent(rpc: IRPC, rpcBytes: number): void {\n this.rpcSentBytes.inc(rpcBytes)\n this.rpcSentCount.inc(1)\n if (rpc.subscriptions) this.rpcSentSubscription.inc(rpc.subscriptions.length)\n if (rpc.messages) this.rpcSentMessage.inc(rpc.messages.length)\n if (rpc.control) {\n const ihave = rpc.control.ihave?.length ?? 0\n const iwant = rpc.control.iwant?.length ?? 0\n const graft = rpc.control.graft?.length ?? 0\n const prune = rpc.control.prune?.length ?? 0\n if (ihave > 0) this.rpcSentIHave.inc(ihave)\n if (iwant > 0) this.rpcSentIWant.inc(iwant)\n if (graft > 0) this.rpcSentGraft.inc(graft)\n if (prune > 0) this.rpcSentPrune.inc(prune)\n if (ihave > 0 || iwant > 0 || graft > 0 || prune > 0) this.rpcSentControl.inc(1)\n }\n },\n\n registerScores(scores: number[], scoreThresholds: PeerScoreThresholds): void {\n let graylist = 0\n let publish = 0\n let gossip = 0\n let mesh = 0\n\n for (const score of scores) {\n if (score >= scoreThresholds.graylistThreshold) graylist++\n if (score >= scoreThresholds.publishThreshold) publish++\n if (score >= scoreThresholds.gossipThreshold) gossip++\n if (score >= 0) mesh++\n }\n\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.graylist }, graylist)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.publish }, publish)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.gossip }, gossip)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.mesh }, mesh)\n\n // Register full score too\n this.score.set(scores)\n },\n\n registerScoreWeights(sw: ScoreWeights): void {\n for (const [topic, wsTopic] of sw.byTopic) {\n this.scoreWeights.set({ topic, p: 'p1' }, wsTopic.p1w)\n this.scoreWeights.set({ topic, p: 'p2' }, wsTopic.p2w)\n this.scoreWeights.set({ topic, p: 'p3' }, wsTopic.p3w)\n this.scoreWeights.set({ topic, p: 'p3b' }, wsTopic.p3bw)\n this.scoreWeights.set({ topic, p: 'p4' }, wsTopic.p4w)\n }\n\n this.scoreWeights.set({ p: 'p5' }, sw.p5w)\n this.scoreWeights.set({ p: 'p6' }, sw.p6w)\n this.scoreWeights.set({ p: 'p7' }, sw.p7w)\n },\n\n registerScorePerMesh(mesh: Map>, scoreByPeer: Map): void {\n const peersPerTopicLabel = new Map>()\n\n mesh.forEach((peers, topicStr) => {\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = this.topicStrToLabel.get(topicStr) ?? 'unknown'\n let peersInMesh = peersPerTopicLabel.get(topicLabel)\n if (!peersInMesh) {\n peersInMesh = new Set()\n peersPerTopicLabel.set(topicLabel, peersInMesh)\n }\n peers.forEach((p) => peersInMesh?.add(p))\n })\n\n for (const [topic, peers] of peersPerTopicLabel) {\n const meshScores: number[] = []\n peers.forEach((peer) => {\n meshScores.push(scoreByPeer.get(peer) ?? 0)\n })\n this.scorePerMesh.set({ topic }, meshScores)\n }\n }\n }\n}\n", "\nimport 'node-forge/lib/aes.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport interface Cipher {\n update: (data: Uint8Array) => Uint8Array\n}\n\nexport function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array): Cipher {\n const cipher2 = forge.cipher.createCipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n\nexport function createDecipheriv (mode: any, key: Uint8Array, iv: Uint8Array): Cipher {\n const cipher2 = forge.cipher.createDecipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\n// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw new CodeError(`Hash '${hash}' is unknown or not supported. Must be ${types}`, 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { randomBytes } from '@libp2p/crypto'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { PublicKey } from '@libp2p/interface-keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { RPC } from '../message/rpc.js'\nimport { PublishConfig, PublishConfigType, TopicStr, ValidateError } from '../types.js'\nimport { StrictSign, StrictNoSign, Message } from '@libp2p/interface-pubsub'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport const SignPrefix = uint8ArrayFromString('libp2p-pubsub:')\n\nexport type RawMessageAndMessage = {\n raw: RPC.IMessage\n msg: Message\n}\n\nexport async function buildRawMessage(\n publishConfig: PublishConfig,\n topic: TopicStr,\n originalData: Uint8Array,\n transformedData: Uint8Array\n): Promise {\n switch (publishConfig.type) {\n case PublishConfigType.Signing: {\n const rpcMsg: RPC.IMessage = {\n from: publishConfig.author.toBytes(),\n data: transformedData,\n seqno: randomBytes(8),\n topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsg).finish()])\n\n rpcMsg.signature = await publishConfig.privateKey.sign(bytes)\n rpcMsg.key = publishConfig.key\n\n const msg: Message = {\n type: 'signed',\n from: publishConfig.author,\n data: originalData,\n sequenceNumber: BigInt(`0x${uint8ArrayToString(rpcMsg.seqno as Uint8Array, 'base16')}`),\n topic,\n signature: rpcMsg.signature,\n key: rpcMsg.key\n }\n return {\n raw: rpcMsg,\n msg: msg\n }\n }\n\n case PublishConfigType.Anonymous: {\n return {\n raw: {\n from: undefined,\n data: transformedData,\n seqno: undefined,\n topic,\n signature: undefined,\n key: undefined\n },\n msg: {\n type: 'unsigned',\n data: originalData,\n topic\n }\n }\n }\n }\n}\n\nexport type ValidationResult = { valid: true; message: Message } | { valid: false; error: ValidateError }\n\nexport async function validateToRawMessage(\n signaturePolicy: typeof StrictNoSign | typeof StrictSign,\n msg: RPC.IMessage\n): Promise {\n // If strict-sign, verify all\n // If anonymous (no-sign), ensure no preven\n\n switch (signaturePolicy) {\n case StrictNoSign:\n if (msg.signature != null) return { valid: false, error: ValidateError.SignaturePresent }\n if (msg.seqno != null) return { valid: false, error: ValidateError.SeqnoPresent }\n if (msg.key != null) return { valid: false, error: ValidateError.FromPresent }\n\n return { valid: true, message: { type: 'unsigned', topic: msg.topic, data: msg.data ?? new Uint8Array(0) } }\n\n case StrictSign: {\n // Verify seqno\n if (msg.seqno == null) return { valid: false, error: ValidateError.InvalidSeqno }\n if (msg.seqno.length !== 8) {\n return { valid: false, error: ValidateError.InvalidSeqno }\n }\n\n if (msg.signature == null) return { valid: false, error: ValidateError.InvalidSignature }\n if (msg.from == null) return { valid: false, error: ValidateError.InvalidPeerId }\n\n let fromPeerId: PeerId\n try {\n // TODO: Fix PeerId types\n fromPeerId = peerIdFromBytes(msg.from)\n } catch (e) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n\n // - check from defined\n // - transform source to PeerId\n // - parse signature\n // - get .key, else from source\n // - check key == source if present\n // - verify sig\n\n let publicKey: PublicKey\n if (msg.key) {\n publicKey = unmarshalPublicKey(msg.key)\n // TODO: Should `fromPeerId.pubKey` be optional?\n if (fromPeerId.publicKey !== undefined && !uint8ArrayEquals(publicKey.bytes, fromPeerId.publicKey)) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n } else {\n if (fromPeerId.publicKey == null) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n publicKey = unmarshalPublicKey(fromPeerId.publicKey)\n }\n\n const rpcMsgPreSign: RPC.IMessage = {\n from: msg.from,\n data: msg.data,\n seqno: msg.seqno,\n topic: msg.topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsgPreSign).finish()])\n\n if (!(await publicKey.verify(bytes, msg.signature))) {\n return { valid: false, error: ValidateError.InvalidSignature }\n }\n\n return {\n valid: true,\n message: {\n type: 'signed',\n from: fromPeerId,\n data: msg.data ?? new Uint8Array(0),\n sequenceNumber: BigInt(`0x${uint8ArrayToString(msg.seqno, 'base16')}`),\n topic: msg.topic,\n signature: msg.signature,\n key: msg.key ?? marshalPublicKey(publicKey)\n }\n }\n }\n }\n}\n", "import { randomBytes } from '@libp2p/crypto'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message, PubSubRPCMessage } from '@libp2p/interface-pubsub'\nimport { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'\nimport { codes } from './errors.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: Uint8Array, seqno: bigint): Uint8Array => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n\n const msgId = new Uint8Array(key.length + seqnoBytes.length)\n msgId.set(key, 0)\n msgId.set(seqnoBytes, key.length)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array): Uint8Array | Promise => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set | number[], b: Set | number[]): boolean => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray: T | T[]): T[] {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nconst isSigned = async (message: PubSubRPCMessage): Promise => {\n if ((message.sequenceNumber == null) || (message.from == null) || (message.signature == null)) {\n return false\n }\n // if a public key is present in the `from` field, the message should be signed\n const fromID = peerIdFromBytes(message.from)\n if (fromID.publicKey != null) {\n return true\n }\n\n if (message.key != null) {\n const signingID = await peerIdFromKeys(message.key)\n return signingID.equals(fromID)\n }\n\n return false\n}\n\nexport const toMessage = async (message: PubSubRPCMessage): Promise => {\n if (message.from == null) {\n throw new CodeError('RPC message was missing from', codes.ERR_MISSING_FROM)\n }\n\n if (!await isSigned(message)) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n const from = peerIdFromBytes(message.from)\n\n const msg: Message = {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber ?? new Uint8Array(0)),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n key: message.key ?? from.publicKey ?? new Uint8Array(0)\n }\n\n if (msg.key.length === 0) {\n throw new CodeError('Signed RPC message was missing key', codes.ERR_MISSING_KEY)\n }\n\n return msg\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n", "import { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message } from '@libp2p/interface-pubsub'\nimport { msgId } from '@libp2p/pubsub/utils'\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport function msgIdFnStrictSign(msg: Message): Uint8Array {\n if (msg.type !== 'signed') {\n throw new Error('expected signed message type')\n }\n // Should never happen\n if (msg.sequenceNumber == null) throw Error('missing seqno field')\n\n // TODO: Should use .from here or key?\n return msgId(msg.from.toBytes(), msg.sequenceNumber)\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport async function msgIdFnStrictNoSign(msg: Message): Promise {\n return await sha256.encode(msg.data)\n}\n", "import type { PeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats } from './peer-stats.js'\n\ntype TopicLabel = string\ntype TopicStr = string\ntype TopicStrToLabel = Map\n\nexport interface TopicScoreWeights {\n p1w: T\n p2w: T\n p3w: T\n p3bw: T\n p4w: T\n}\nexport interface ScoreWeights {\n byTopic: Map>\n p5w: T\n p6w: T\n p7w: T\n score: T\n}\n\nexport function computeScoreWeights(\n peer: string,\n pstats: PeerStats,\n params: PeerScoreParams,\n peerIPs: Map>,\n topicStrToLabel: TopicStrToLabel\n): ScoreWeights {\n let score = 0\n\n const byTopic = new Map>()\n\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = topicStrToLabel.get(topic) ?? 'unknown'\n const topicParams = params.topics[topic]\n if (topicParams === undefined) {\n // we are not scoring this topic\n return\n }\n\n let topicScores = byTopic.get(topicLabel)\n if (!topicScores) {\n topicScores = {\n p1w: 0,\n p2w: 0,\n p3w: 0,\n p3bw: 0,\n p4w: 0\n }\n byTopic.set(topicLabel, topicScores)\n }\n\n let p1w = 0\n let p2w = 0\n let p3w = 0\n let p3bw = 0\n let p4w = 0\n\n // P1: time in Mesh\n if (tstats.inMesh) {\n const p1 = Math.max(tstats.meshTime / topicParams.timeInMeshQuantum, topicParams.timeInMeshCap)\n p1w += p1 * topicParams.timeInMeshWeight\n }\n\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap\n }\n p2w += p2 * topicParams.firstMessageDeliveriesWeight\n\n // P3: mesh message deliveries\n if (\n tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold\n ) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries\n const p3 = deficit * deficit\n p3w += p3 * topicParams.meshMessageDeliveriesWeight\n }\n\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty\n p3bw += p3b * topicParams.meshFailurePenaltyWeight\n\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries\n p4w += p4 * topicParams.invalidMessageDeliveriesWeight\n\n // update score, mixing with topic weight\n score += (p1w + p2w + p3w + p3bw + p4w) * topicParams.topicWeight\n\n topicScores.p1w += p1w\n topicScores.p2w += p2w\n topicScores.p3w += p3w\n topicScores.p3bw += p3bw\n topicScores.p4w += p4w\n })\n\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap\n\n // Proportionally apply cap to all individual contributions\n const capF = params.topicScoreCap / score\n for (const ws of byTopic.values()) {\n ws.p1w *= capF\n ws.p2w *= capF\n ws.p3w *= capF\n ws.p3bw *= capF\n ws.p4w *= capF\n }\n }\n\n let p5w = 0\n let p6w = 0\n let p7w = 0\n\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer)\n p5w += p5 * params.appSpecificWeight\n\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return\n }\n\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip)\n const numPeersInIP = peersInIP ? peersInIP.size : 0\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold\n const p6 = surplus * surplus\n p6w += p6 * params.IPColocationFactorWeight\n }\n })\n\n // P7: behavioural pattern penalty\n const p7 = pstats.behaviourPenalty * pstats.behaviourPenalty\n p7w += p7 * params.behaviourPenaltyWeight\n\n score += p5w + p6w + p7w\n\n return {\n byTopic,\n p5w,\n p6w,\n p7w,\n score\n }\n}\n\nexport function computeAllPeersScoreWeights(\n peerIdStrs: Iterable,\n peerStats: Map,\n params: PeerScoreParams,\n peerIPs: Map>,\n topicStrToLabel: TopicStrToLabel\n): ScoreWeights {\n const sw: ScoreWeights = {\n byTopic: new Map(),\n p5w: [],\n p6w: [],\n p7w: [],\n score: []\n }\n\n for (const peerIdStr of peerIdStrs) {\n const pstats = peerStats.get(peerIdStr)\n if (pstats) {\n const swPeer = computeScoreWeights(peerIdStr, pstats, params, peerIPs, topicStrToLabel)\n\n for (const [topic, swPeerTopic] of swPeer.byTopic) {\n let swTopic = sw.byTopic.get(topic)\n if (!swTopic) {\n swTopic = {\n p1w: [],\n p2w: [],\n p3w: [],\n p3bw: [],\n p4w: []\n }\n sw.byTopic.set(topic, swTopic)\n }\n\n swTopic.p1w.push(swPeerTopic.p1w)\n swTopic.p2w.push(swPeerTopic.p2w)\n swTopic.p3w.push(swPeerTopic.p3w)\n swTopic.p3bw.push(swPeerTopic.p3bw)\n swTopic.p4w.push(swPeerTopic.p4w)\n }\n\n sw.p5w.push(swPeer.p5w)\n sw.p6w.push(swPeer.p6w)\n sw.p7w.push(swPeer.p7w)\n sw.score.push(swPeer.score)\n } else {\n sw.p5w.push(0)\n sw.p6w.push(0)\n sw.p7w.push(0)\n sw.score.push(0)\n }\n }\n\n return sw\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO {\n public buffer: Array | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO | null\n\n constructor (hwm: number) {\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\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\n push (data: Next): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO\n private tail: FixedFIFO\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\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\n shift (): Next | undefined {\n let val = this.tail.shift()\n\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\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\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 */\n\nimport deferred from 'p-defer'\nimport { FIFO, type Next } from './fifo.js'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable extends AsyncGenerator, BasePushable {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV extends AsyncGenerator, BasePushable {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult { done: false, value: T }\nexport type NextResult = ValueResult | DoneResult\n\ninterface getNext { (buffer: FIFO): NextResult }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable (options?: BytePushableOptions): Pushable\nexport function pushable (options: ObjectPushableOptions): Pushable\nexport function pushable (options: Options = {}): Pushable {\n const getNext = (buffer: FIFO): NextResult => {\n const next: Next | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\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\n return _pushable>(getNext, options)\n}\n\nexport function pushableV (options?: BytePushableOptions): PushableV\nexport function pushableV (options: ObjectPushableOptions): PushableV\nexport function pushableV (options: Options = {}): PushableV {\n const getNext = (buffer: FIFO): NextResult => {\n let next: Next | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\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\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable>(getNext, options)\n}\n\nfunction _pushable (getNext: getNext, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO()\n let pushable: any\n let onNext: ((next: Next) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise>((resolve, reject) => {\n onNext = (next: Next) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\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\n const bufferNext = (next: Next): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\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\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n", "\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\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", "import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n", "import { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\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: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n\n constructor (...data: Appendable[]) {\n // Define symbol\n Object.defineProperty(this, symbol, { value: true })\n\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] () {\n yield * this.bufs\n }\n\n get byteLength () {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]) {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]) {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\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 } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\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 } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number) {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\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\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\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\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\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\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\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: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\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\n return true\n }\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: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\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", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\n\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)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\ninterface VarintCodec {\n encodingLength: (value: number) => number\n encode: ((value: number) => Uint8Array) & ((value: number, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: number, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => number\n}\n\nexport const unsigned: VarintCodec = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf?: any, offset: number = 0) {\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(true)\n }\n}\n\nexport const signed: VarintCodec = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0) {\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(false)\n }\n}\n\nexport const zigzag: VarintCodec = {\n encodingLength (value: number): number {\n return unsigned.encodingLength(value >= 0 ? value * 2 : value * -2 - 1)\n },\n\n // @ts-expect-error\n encode (value: any, buf?: any, offset?: any) {\n value = value >= 0 ? value * 2 : (value * -2) - 1\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n const value = unsigned.decode(buf, offset)\n\n return (value & 1) !== 0 ? (value + 1) / -2 : value / 2\n }\n}\n", "\nexport function alloc (len: number) {\n return new Uint8Array(len)\n}\n\nexport function allocUnsafe (len: number) {\n if (globalThis?.Buffer?.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport type { LengthEncoderFunction } from './index.js'\nimport type { Source, Transform } from 'it-stream-types'\nimport { allocUnsafe } from './alloc.js'\n\ninterface EncoderOptions {\n lengthEncoder?: LengthEncoderFunction\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = unsigned.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n unsigned.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (options?: EncoderOptions): Transform {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n const encoder = async function * (source: Source): Source {\n for await (const chunk of source) {\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\n }\n }\n\n return encoder\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n", "/* eslint max-depth: [\"error\", 6] */\n\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport errCode from 'err-code'\nimport type { LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport interface ReadState {\n dataLength: number\n}\n\nexport interface DecoderOptions {\n lengthDecoder?: LengthDecoderFunction\n onData?: (data: Uint8ArrayList) => void\n onLength?: (length: number) => void\n maxLengthLength?: number\n maxDataLength?: number\n}\n\nexport interface ReadResult {\n mode: string\n chunk?: Uint8ArrayList\n buffer: Uint8ArrayList\n state?: ReadState\n data?: Uint8ArrayList\n}\n\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\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = unsigned.decode(buf)\n defaultDecoder.bytes = unsigned.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (options?: DecoderOptions): Transform {\n const decoder = async function * (source: Source): Source {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n for await (const buf of source) {\n buffer.append(buf)\n\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\n if (dataLength < 0) {\n throw errCode(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH')\n }\n\n if (dataLength > maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (buffer.byteLength > 0) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF')\n }\n }\n\n return decoder\n}\n\n/**\n * @param {*} reader\n * @param {import('./types').DecoderOptions} [options]\n * @returns\n */\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number) => { byteLength = l }\n return decode({\n ...(options ?? {}),\n onLength\n })(varByteSource)\n}\n", "import { Stream } from '@libp2p/interface-connection'\nimport { abortableSource } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport { pushable, Pushable } from 'it-pushable'\nimport { encode, decode } from 'it-length-prefixed'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\ntype OutboundStreamOpts = {\n /** Max size in bytes for pushable buffer. If full, will throw on .push */\n maxBufferSize?: number\n}\n\ntype InboundStreamOpts = {\n /** Max size in bytes for reading messages from the stream */\n maxDataLength?: number\n}\n\nexport class OutboundStream {\n private readonly pushable: Pushable\n private readonly closeController: AbortController\n private readonly maxBufferSize: number\n\n constructor(private readonly rawStream: Stream, errCallback: (e: Error) => void, opts: OutboundStreamOpts) {\n this.pushable = pushable({ objectMode: false })\n this.closeController = new AbortController()\n this.maxBufferSize = opts.maxBufferSize ?? Infinity\n\n pipe(\n abortableSource(this.pushable, this.closeController.signal, { returnOnAbort: true }),\n encode(),\n this.rawStream\n ).catch(errCallback)\n }\n\n get protocol(): string {\n // TODO remove this non-nullish assertion after https://github.com/libp2p/js-libp2p-interfaces/pull/265 is incorporated\n return this.rawStream.stat.protocol!\n }\n\n push(data: Uint8Array): void {\n if (this.pushable.readableLength > this.maxBufferSize) {\n throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`)\n }\n\n this.pushable.push(data)\n }\n\n close(): void {\n this.closeController.abort()\n // similar to pushable.end() but clear the internal buffer\n this.pushable.return()\n this.rawStream.close()\n }\n}\n\nexport class InboundStream {\n public readonly source: AsyncIterable\n\n private readonly rawStream: Stream\n private readonly closeController: AbortController\n\n constructor(rawStream: Stream, opts: InboundStreamOpts = {}) {\n this.rawStream = rawStream\n this.closeController = new AbortController()\n\n this.source = abortableSource(pipe(this.rawStream, decode(opts)), this.closeController.signal, {\n returnOnAbort: true\n })\n }\n\n close(): void {\n this.closeController.abort()\n this.rawStream.close()\n }\n}\n", "import type { IRPC, RPC } from './rpc.js'\nimport protobuf from 'protobufjs/minimal.js'\n\nexport type DecodeRPCLimits = {\n maxSubscriptions: number\n maxMessages: number\n maxIhaveMessageIDs: number\n maxIwantMessageIDs: number\n maxControlMessages: number\n maxPeerInfos: number\n}\n\nexport const defaultDecodeRpcLimits: DecodeRPCLimits = {\n maxSubscriptions: Infinity,\n maxMessages: Infinity,\n maxIhaveMessageIDs: Infinity,\n maxIwantMessageIDs: Infinity,\n maxControlMessages: Infinity,\n maxPeerInfos: Infinity\n}\n\n/**\n * Copied code from src/message/rpc.cjs but with decode limits to prevent OOM attacks\n */\nexport function decodeRpc(bytes: Uint8Array, opts: DecodeRPCLimits): IRPC {\n // Mutate to use the option as stateful counter. Must limit the total count of messageIDs across all IWANT, IHAVE\n // else one count put 100 messageIDs into each 100 IWANT and \"get around\" the limit\n opts = { ...opts }\n\n const r = protobuf.Reader.create(bytes)\n const l = bytes.length\n\n const c = l === undefined ? r.len : r.pos + l\n const m: IRPC = {}\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n if (!(m.subscriptions && m.subscriptions.length)) m.subscriptions = []\n if (m.subscriptions.length < opts.maxSubscriptions) m.subscriptions.push(decodeSubOpts(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 2:\n if (!(m.messages && m.messages.length)) m.messages = []\n if (m.messages.length < opts.maxMessages) m.messages.push(decodeMessage(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 3:\n m.control = decodeControlMessage(r, r.uint32(), opts)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeSubOpts(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m: RPC.ISubOpts = {}\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.subscribe = r.bool()\n break\n case 2:\n m.topic = r.string()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeMessage(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IMessage\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.from = r.bytes()\n break\n case 2:\n m.data = r.bytes()\n break\n case 3:\n m.seqno = r.bytes()\n break\n case 4:\n m.topic = r.string()\n break\n case 5:\n m.signature = r.bytes()\n break\n case 6:\n m.key = r.bytes()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n if (!m.topic) throw Error(\"missing required 'topic'\")\n return m\n}\n\nfunction decodeControlMessage(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlMessage\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n if (!(m.ihave && m.ihave.length)) m.ihave = []\n if (m.ihave.length < opts.maxControlMessages) m.ihave.push(decodeControlIHave(r, r.uint32(), opts))\n else r.skipType(t & 7)\n break\n case 2:\n if (!(m.iwant && m.iwant.length)) m.iwant = []\n if (m.iwant.length < opts.maxControlMessages) m.iwant.push(decodeControlIWant(r, r.uint32(), opts))\n else r.skipType(t & 7)\n break\n case 3:\n if (!(m.graft && m.graft.length)) m.graft = []\n if (m.graft.length < opts.maxControlMessages) m.graft.push(decodeControlGraft(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 4:\n if (!(m.prune && m.prune.length)) m.prune = []\n if (m.prune.length < opts.maxControlMessages) m.prune.push(decodeControlPrune(r, r.uint32(), opts))\n else r.skipType(t & 7)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlIHave(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlIHave\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string()\n break\n case 2:\n if (!(m.messageIDs && m.messageIDs.length)) m.messageIDs = []\n if (opts.maxIhaveMessageIDs-- > 0) m.messageIDs.push(r.bytes())\n else r.skipType(t & 7)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlIWant(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlIWant\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n if (!(m.messageIDs && m.messageIDs.length)) m.messageIDs = []\n if (opts.maxIwantMessageIDs-- > 0) m.messageIDs.push(r.bytes())\n else r.skipType(t & 7)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlGraft(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlGraft\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlPrune(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlPrune\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string()\n break\n case 2:\n if (!(m.peers && m.peers.length)) m.peers = []\n if (opts.maxPeerInfos-- > 0) m.peers.push(decodePeerInfo(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 3:\n m.backoff = r.uint64() as unknown as number\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodePeerInfo(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IPeerInfo\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.peerID = r.bytes()\n break\n case 2:\n m.signedPeerRecord = r.bytes()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n", "import { Multiaddr } from '@multiformats/multiaddr'\nimport { convertToString } from '@multiformats/multiaddr/convert'\n\n// Protocols https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n// code size name\n// 4 32 ip4\n// 41 128 ip6\nenum Protocol {\n ip4 = 4,\n ip6 = 41\n}\n\nexport function multiaddrToIPStr(multiaddr: Multiaddr): string | null {\n for (const tuple of multiaddr.tuples()) {\n switch (tuple[0]) {\n case Protocol.ip4:\n case Protocol.ip6:\n return convertToString(tuple[0], tuple[1]!)\n }\n }\n\n return null\n}\n", "import { pipe } from 'it-pipe'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport { RecordEnvelope } from '@libp2p/peer-record'\nimport { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id'\nimport { Logger, logger } from '@libp2p/logger'\nimport { createTopology } from '@libp2p/topology'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\n\nimport { MessageCache } from './message-cache.js'\nimport { RPC, IRPC } from './message/rpc.js'\nimport * as constants from './constants.js'\nimport { shuffle, messageIdToString } from './utils/index.js'\nimport {\n PeerScore,\n PeerScoreParams,\n PeerScoreThresholds,\n createPeerScoreParams,\n createPeerScoreThresholds,\n PeerScoreStatsDump\n} from './score/index.js'\nimport { IWantTracer } from './tracer.js'\nimport { SimpleTimeCache } from './utils/time-cache.js'\nimport {\n ACCEPT_FROM_WHITELIST_DURATION_MS,\n ACCEPT_FROM_WHITELIST_MAX_MESSAGES,\n ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE\n} from './constants.js'\nimport {\n ChurnReason,\n getMetrics,\n IHaveIgnoreReason,\n InclusionReason,\n Metrics,\n MetricsRegister,\n ScorePenalty,\n TopicStrToLabel,\n ToSendGroupCount\n} from './metrics.js'\nimport {\n MsgIdFn,\n PublishConfig,\n TopicStr,\n MsgIdStr,\n ValidateError,\n PeerIdStr,\n MessageStatus,\n RejectReason,\n RejectReasonObj,\n FastMsgIdFn,\n AddrInfo,\n DataTransform,\n rejectReasonFromAcceptance,\n MsgIdToStrFn,\n MessageId,\n PublishOpts\n} from './types.js'\nimport { buildRawMessage, validateToRawMessage } from './utils/buildRawMessage.js'\nimport { msgIdFnStrictNoSign, msgIdFnStrictSign } from './utils/msgIdFn.js'\nimport { computeAllPeersScoreWeights } from './score/scoreMetrics.js'\nimport { getPublishConfigFromPeerId } from './utils/publishConfig.js'\nimport type { GossipsubOptsSpec } from './config.js'\nimport {\n Message,\n PublishResult,\n PubSub,\n PubSubEvents,\n PubSubInit,\n StrictNoSign,\n StrictSign,\n SubscriptionChangeData,\n TopicValidatorFn,\n TopicValidatorResult\n} from '@libp2p/interface-pubsub'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport { removeFirstNItemsFromSet, removeItemsFromSet } from './utils/set.js'\nimport { pushable } from 'it-pushable'\nimport { InboundStream, OutboundStream } from './stream.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { decodeRpc, DecodeRPCLimits, defaultDecodeRpcLimits } from './message/decodeRpc.js'\nimport { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport { PeerStore } from '@libp2p/interface-peer-store'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddrToIPStr } from './utils/multiaddr.js'\n\ntype ConnectionDirection = 'inbound' | 'outbound'\n\ntype ReceivedMessageResult =\n | { code: MessageStatus.duplicate; msgIdStr: MsgIdStr }\n | ({ code: MessageStatus.invalid; msgIdStr?: MsgIdStr } & RejectReasonObj)\n | { code: MessageStatus.valid; messageId: MessageId; msg: Message }\n\nexport const multicodec: string = constants.GossipsubIDv11\n\nexport interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {\n /** if dial should fallback to floodsub */\n fallbackToFloodsub: boolean\n /** if self-published messages should be sent to all peers */\n floodPublish: boolean\n /** whether PX is enabled; this should be enabled in bootstrappers and other well connected/trusted nodes. */\n doPX: boolean\n /** peers with which we will maintain direct connections */\n directPeers: AddrInfo[]\n /**\n * If true will not forward messages to mesh peers until reportMessageValidationResult() is called.\n * Messages will be cached in mcache for some time after which they are evicted. Calling\n * reportMessageValidationResult() after the message is dropped from mcache won't forward the message.\n */\n asyncValidation: boolean\n /** Do not throw `InsufficientPeers` error if publishing to zero peers */\n allowPublishToZeroPeers: boolean\n /** Do not throw `PublishError.Duplicate` if publishing duplicate messages */\n ignoreDuplicatePublishError: boolean\n /** For a single stream, await processing each RPC before processing the next */\n awaitRpcHandler: boolean\n /** For a single RPC, await processing each message before processing the next */\n awaitRpcMessageHandler: boolean\n\n /** message id function */\n msgIdFn: MsgIdFn\n /** fast message id function */\n fastMsgIdFn: FastMsgIdFn\n /** Uint8Array message id to string function */\n msgIdToStrFn: MsgIdToStrFn\n /** override the default MessageCache */\n messageCache: MessageCache\n /** peer score parameters */\n scoreParams: Partial\n /** peer score thresholds */\n scoreThresholds: Partial\n /** customize GossipsubIWantFollowupTime in order not to apply IWANT penalties */\n gossipsubIWantFollowupMs: number\n\n /** override constants for fine tuning */\n prunePeers?: number\n pruneBackoff?: number\n graftFloodThreshold?: number\n opportunisticGraftPeers?: number\n opportunisticGraftTicks?: number\n directConnectTicks?: number\n\n dataTransform?: DataTransform\n metricsRegister?: MetricsRegister | null\n metricsTopicStrToLabel?: TopicStrToLabel\n\n // Debug\n /** Prefix tag for debug logs */\n debugName?: string\n\n /**\n * Specify the maximum number of inbound gossipsub protocol\n * streams that are allowed to be open concurrently\n */\n maxInboundStreams?: number\n\n /**\n * Specify the maximum number of outbound gossipsub protocol\n * streams that are allowed to be open concurrently\n */\n maxOutboundStreams?: number\n\n /**\n * Specify max buffer size in bytes for OutboundStream.\n * If full it will throw and reject sending any more data.\n */\n maxOutboundBufferSize?: number\n\n /**\n * Specify max size to skip decoding messages whose data\n * section exceeds this size.\n *\n */\n maxInboundDataLength?: number\n\n /**\n * If provided, only allow topics in this list\n */\n allowedTopics?: string[] | Set\n\n /**\n * Limits to bound protobuf decoding\n */\n decodeRpcLimits?: DecodeRPCLimits\n}\n\nexport interface GossipsubMessage {\n propagationSource: PeerId\n msgId: MsgIdStr\n msg: Message\n}\n\nexport interface GossipsubEvents extends PubSubEvents {\n 'gossipsub:heartbeat': CustomEvent\n 'gossipsub:message': CustomEvent\n}\n\nenum GossipStatusCode {\n started,\n stopped\n}\n\ntype GossipStatus =\n | {\n code: GossipStatusCode.started\n registrarTopologyIds: string[]\n heartbeatTimeout: ReturnType\n hearbeatStartMs: number\n }\n | {\n code: GossipStatusCode.stopped\n }\n\ninterface GossipOptions extends GossipsubOpts {\n scoreParams: PeerScoreParams\n scoreThresholds: PeerScoreThresholds\n}\n\ninterface AcceptFromWhitelistEntry {\n /** number of messages accepted since recomputing the peer's score */\n messagesAccepted: number\n /** have to recompute score after this time */\n acceptUntil: number\n}\n\nexport interface GossipSubComponents {\n peerId: PeerId\n peerStore: PeerStore\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport class GossipSub extends EventEmitter implements PubSub {\n /**\n * The signature policy to follow by default\n */\n public readonly globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n public multicodecs: string[] = [constants.GossipsubIDv11, constants.GossipsubIDv10]\n\n private publishConfig: PublishConfig | undefined\n\n private readonly dataTransform: DataTransform | undefined\n\n // State\n\n public readonly peers = new Set()\n public readonly streamsInbound = new Map()\n public readonly streamsOutbound = new Map()\n\n /** Ensures outbound streams are created sequentially */\n private outboundInflightQueue = pushable<{ peerId: PeerId; connection: Connection }>({ objectMode: true })\n\n /** Direct peers */\n public readonly direct = new Set()\n\n /** Floodsub peers */\n private readonly floodsubPeers = new Set()\n\n /** Cache of seen messages */\n private readonly seenCache: SimpleTimeCache\n\n /**\n * Map of peer id and AcceptRequestWhileListEntry\n */\n private readonly acceptFromWhitelist = new Map()\n\n /**\n * Map of topics to which peers are subscribed to\n */\n private readonly topics = new Map>()\n\n /**\n * List of our subscriptions\n */\n private readonly subscriptions = new Set()\n\n /**\n * Map of topic meshes\n * topic => peer id set\n */\n public readonly mesh = new Map>()\n\n /**\n * Map of topics to set of peers. These mesh peers are the ones to which we are publishing without a topic membership\n * topic => peer id set\n */\n public readonly fanout = new Map>()\n\n /**\n * Map of last publish time for fanout topics\n * topic => last publish time\n */\n private readonly fanoutLastpub = new Map()\n\n /**\n * Map of pending messages to gossip\n * peer id => control messages\n */\n public readonly gossip = new Map()\n\n /**\n * Map of control messages\n * peer id => control message\n */\n public readonly control = new Map()\n\n /**\n * Number of IHAVEs received from peer in the last heartbeat\n */\n private readonly peerhave = new Map()\n\n /** Number of messages we have asked from peer in the last heartbeat */\n private readonly iasked = new Map()\n\n /** Prune backoff map */\n private readonly backoff = new Map>()\n\n /**\n * Connection direction cache, marks peers with outbound connections\n * peer id => direction\n */\n private readonly outbound = new Map()\n private readonly msgIdFn: MsgIdFn\n\n /**\n * A fast message id function used for internal message de-duplication\n */\n private readonly fastMsgIdFn: FastMsgIdFn | undefined\n\n private readonly msgIdToStrFn: MsgIdToStrFn\n\n /** Maps fast message-id to canonical message-id */\n private readonly fastMsgIdCache: SimpleTimeCache | undefined\n\n /**\n * Short term cache for published message ids. This is used for penalizing peers sending\n * our own messages back if the messages are anonymous or use a random author.\n */\n private readonly publishedMessageIds: SimpleTimeCache\n\n /**\n * A message cache that contains the messages for last few heartbeat ticks\n */\n private readonly mcache: MessageCache\n\n /** Peer score tracking */\n public readonly score: PeerScore\n\n /**\n * Custom validator function per topic.\n * Must return or resolve quickly (< 100ms) to prevent causing penalties for late messages.\n * If you need to apply validation that may require longer times use `asyncValidation` option and callback the\n * validation result through `Gossipsub.reportValidationResult`\n */\n public readonly topicValidators = new Map()\n\n /**\n * Make this protected so child class may want to redirect to its own log.\n */\n protected readonly log: Logger\n\n /**\n * Number of heartbeats since the beginning of time\n * This allows us to amortize some resource cleanup -- eg: backoff cleanup\n */\n private heartbeatTicks = 0\n\n /**\n * Tracks IHAVE/IWANT promises broken by peers\n */\n readonly gossipTracer: IWantTracer\n\n private readonly components: GossipSubComponents\n\n private directPeerInitial: ReturnType | null = null\n\n public static multicodec: string = constants.GossipsubIDv11\n\n // Options\n readonly opts: Required\n private readonly decodeRpcLimits: DecodeRPCLimits\n\n private readonly metrics: Metrics | null\n private status: GossipStatus = { code: GossipStatusCode.stopped }\n private maxInboundStreams?: number\n private maxOutboundStreams?: number\n private allowedTopics: Set | null\n\n private heartbeatTimer: {\n _intervalId: ReturnType | undefined\n runPeriodically: (fn: () => void, period: number) => void\n cancel: () => void\n } | null = null\n\n constructor(components: GossipSubComponents, options: Partial = {}) {\n super()\n\n const opts = {\n fallbackToFloodsub: true,\n floodPublish: true,\n doPX: false,\n directPeers: [],\n D: constants.GossipsubD,\n Dlo: constants.GossipsubDlo,\n Dhi: constants.GossipsubDhi,\n Dscore: constants.GossipsubDscore,\n Dout: constants.GossipsubDout,\n Dlazy: constants.GossipsubDlazy,\n heartbeatInterval: constants.GossipsubHeartbeatInterval,\n fanoutTTL: constants.GossipsubFanoutTTL,\n mcacheLength: constants.GossipsubHistoryLength,\n mcacheGossip: constants.GossipsubHistoryGossip,\n seenTTL: constants.GossipsubSeenTTL,\n gossipsubIWantFollowupMs: constants.GossipsubIWantFollowupTime,\n prunePeers: constants.GossipsubPrunePeers,\n pruneBackoff: constants.GossipsubPruneBackoff,\n graftFloodThreshold: constants.GossipsubGraftFloodThreshold,\n opportunisticGraftPeers: constants.GossipsubOpportunisticGraftPeers,\n opportunisticGraftTicks: constants.GossipsubOpportunisticGraftTicks,\n directConnectTicks: constants.GossipsubDirectConnectTicks,\n ...options,\n scoreParams: createPeerScoreParams(options.scoreParams),\n scoreThresholds: createPeerScoreThresholds(options.scoreThresholds)\n }\n\n this.components = components\n this.decodeRpcLimits = opts.decodeRpcLimits ?? defaultDecodeRpcLimits\n\n this.globalSignaturePolicy = opts.globalSignaturePolicy ?? StrictSign\n\n // Also wants to get notified of peers connected using floodsub\n if (opts.fallbackToFloodsub) {\n this.multicodecs.push(constants.FloodsubID)\n }\n\n // From pubsub\n this.log = logger(opts.debugName ?? 'libp2p:gossipsub')\n\n // Gossipsub\n\n this.opts = opts as Required\n this.direct = new Set(opts.directPeers.map((p) => p.id.toString()))\n this.seenCache = new SimpleTimeCache({ validityMs: opts.seenTTL })\n this.publishedMessageIds = new SimpleTimeCache({ validityMs: opts.seenTTL })\n\n if (options.msgIdFn) {\n // Use custom function\n this.msgIdFn = options.msgIdFn\n } else {\n switch (this.globalSignaturePolicy) {\n case StrictSign:\n this.msgIdFn = msgIdFnStrictSign\n break\n case StrictNoSign:\n this.msgIdFn = msgIdFnStrictNoSign\n break\n }\n }\n\n if (options.fastMsgIdFn) {\n this.fastMsgIdFn = options.fastMsgIdFn\n this.fastMsgIdCache = new SimpleTimeCache({ validityMs: opts.seenTTL })\n }\n\n // By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n this.msgIdToStrFn = options.msgIdToStrFn ?? messageIdToString\n\n this.mcache = options.messageCache || new MessageCache(opts.mcacheGossip, opts.mcacheLength, this.msgIdToStrFn)\n\n if (options.dataTransform) {\n this.dataTransform = options.dataTransform\n }\n\n if (options.metricsRegister) {\n if (!options.metricsTopicStrToLabel) {\n throw Error('Must set metricsTopicStrToLabel with metrics')\n }\n\n // in theory, each topic has its own meshMessageDeliveriesWindow param\n // however in lodestar, we configure it mostly the same so just pick the max of positive ones\n // (some topics have meshMessageDeliveriesWindow as 0)\n const maxMeshMessageDeliveriesWindowMs = Math.max(\n ...Object.values(opts.scoreParams.topics).map((topicParam) => topicParam.meshMessageDeliveriesWindow),\n constants.DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS\n )\n\n const metrics = getMetrics(options.metricsRegister, options.metricsTopicStrToLabel, {\n gossipPromiseExpireSec: this.opts.gossipsubIWantFollowupMs / 1000,\n behaviourPenaltyThreshold: opts.scoreParams.behaviourPenaltyThreshold,\n maxMeshMessageDeliveriesWindowSec: maxMeshMessageDeliveriesWindowMs / 1000\n })\n\n metrics.mcacheSize.addCollect(() => this.onScrapeMetrics(metrics))\n for (const protocol of this.multicodecs) {\n metrics.protocolsEnabled.set({ protocol }, 1)\n }\n\n this.metrics = metrics\n } else {\n this.metrics = null\n }\n\n this.gossipTracer = new IWantTracer(this.opts.gossipsubIWantFollowupMs, this.msgIdToStrFn, this.metrics)\n\n /**\n * libp2p\n */\n this.score = new PeerScore(this.opts.scoreParams, this.metrics, {\n scoreCacheValidityMs: opts.heartbeatInterval\n })\n\n this.maxInboundStreams = options.maxInboundStreams\n this.maxOutboundStreams = options.maxOutboundStreams\n\n this.allowedTopics = opts.allowedTopics ? new Set(opts.allowedTopics) : null\n }\n\n getPeers(): PeerId[] {\n return [...this.peers.keys()].map((str) => peerIdFromString(str))\n }\n\n isStarted(): boolean {\n return this.status.code === GossipStatusCode.started\n }\n\n // LIFECYCLE METHODS\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node and sends our\n * our subscriptions to every peer connected\n */\n async start(): Promise {\n // From pubsub\n if (this.isStarted()) {\n return\n }\n\n this.log('starting')\n\n this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId)\n\n // Create the outbound inflight queue\n // This ensures that outbound stream creation happens sequentially\n this.outboundInflightQueue = pushable({ objectMode: true })\n pipe(this.outboundInflightQueue, async (source) => {\n for await (const { peerId, connection } of source) {\n await this.createOutboundStream(peerId, connection)\n }\n }).catch((e) => this.log.error('outbound inflight queue error', e))\n\n // set direct peer addresses in the address book\n await Promise.all(\n this.opts.directPeers.map(async (p) => {\n await this.components.peerStore.addressBook.add(p.id, p.addrs)\n })\n )\n\n const registrar = this.components.registrar\n // Incoming streams\n // Called after a peer dials us\n await Promise.all(\n this.multicodecs.map((multicodec) =>\n registrar.handle(multicodec, this.onIncomingStream.bind(this), {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams\n })\n )\n )\n\n // # How does Gossipsub interact with libp2p? Rough guide from Mar 2022\n //\n // ## Setup:\n // Gossipsub requests libp2p to callback, TBD\n //\n // `this.libp2p.handle()` registers a handler for `/meshsub/1.1.0` and other Gossipsub protocols\n // The handler callback is registered in libp2p Upgrader.protocols map.\n //\n // Upgrader receives an inbound connection from some transport and (`Upgrader.upgradeInbound`):\n // - Adds encryption (NOISE in our case)\n // - Multiplex stream\n // - Create a muxer and register that for each new stream call Upgrader.protocols handler\n //\n // ## Topology\n // - new instance of Topology (unlinked to libp2p) with handlers\n // - registar.register(topology)\n\n // register protocol with topology\n // Topology callbacks called on connection manager changes\n const topology = createTopology({\n onConnect: this.onPeerConnected.bind(this),\n onDisconnect: this.onPeerDisconnected.bind(this)\n })\n const registrarTopologyIds = await Promise.all(\n this.multicodecs.map((multicodec) => registrar.register(multicodec, topology))\n )\n\n // Schedule to start heartbeat after `GossipsubHeartbeatInitialDelay`\n const heartbeatTimeout = setTimeout(this.runHeartbeat, constants.GossipsubHeartbeatInitialDelay)\n // Then, run heartbeat every `heartbeatInterval` offset by `GossipsubHeartbeatInitialDelay`\n\n this.status = {\n code: GossipStatusCode.started,\n registrarTopologyIds,\n heartbeatTimeout: heartbeatTimeout,\n hearbeatStartMs: Date.now() + constants.GossipsubHeartbeatInitialDelay\n }\n\n this.score.start()\n // connect to direct peers\n this.directPeerInitial = setTimeout(() => {\n Promise.resolve()\n .then(async () => {\n await Promise.all(Array.from(this.direct).map(async (id) => await this.connect(id)))\n })\n .catch((err) => {\n this.log(err)\n })\n }, constants.GossipsubDirectConnectInitialDelay)\n\n this.log('started')\n }\n\n /**\n * Unmounts the gossipsub protocol and shuts down every connection\n */\n async stop(): Promise {\n this.log('stopping')\n // From pubsub\n\n if (this.status.code !== GossipStatusCode.started) {\n return\n }\n\n const { registrarTopologyIds } = this.status\n this.status = { code: GossipStatusCode.stopped }\n\n // unregister protocol and handlers\n const registrar = this.components.registrar\n registrarTopologyIds.forEach((id) => registrar.unregister(id))\n\n this.outboundInflightQueue.end()\n\n for (const outboundStream of this.streamsOutbound.values()) {\n outboundStream.close()\n }\n this.streamsOutbound.clear()\n\n for (const inboundStream of this.streamsInbound.values()) {\n inboundStream.close()\n }\n this.streamsInbound.clear()\n\n this.peers.clear()\n this.subscriptions.clear()\n\n // Gossipsub\n\n if (this.heartbeatTimer) {\n this.heartbeatTimer.cancel()\n this.heartbeatTimer = null\n }\n\n this.score.stop()\n\n this.mesh.clear()\n this.fanout.clear()\n this.fanoutLastpub.clear()\n this.gossip.clear()\n this.control.clear()\n this.peerhave.clear()\n this.iasked.clear()\n this.backoff.clear()\n this.outbound.clear()\n this.gossipTracer.clear()\n this.seenCache.clear()\n if (this.fastMsgIdCache) this.fastMsgIdCache.clear()\n if (this.directPeerInitial) clearTimeout(this.directPeerInitial)\n\n this.log('stopped')\n }\n\n /** FOR DEBUG ONLY - Dump peer stats for all peers. Data is cloned, safe to mutate */\n dumpPeerScoreStats(): PeerScoreStatsDump {\n return this.score.dumpPeerScoreStats()\n }\n\n /**\n * On an inbound stream opened\n */\n private onIncomingStream({ stream, connection }: IncomingStreamData) {\n if (!this.isStarted()) {\n return\n }\n\n const peerId = connection.remotePeer\n // add peer to router\n this.addPeer(peerId, connection.stat.direction, connection.remoteAddr)\n // create inbound stream\n this.createInboundStream(peerId, stream)\n // attempt to create outbound stream\n this.outboundInflightQueue.push({ peerId, connection })\n }\n\n /**\n * Registrar notifies an established connection with pubsub protocol\n */\n private onPeerConnected(peerId: PeerId, connection: Connection): void {\n this.metrics?.newConnectionCount.inc({ status: connection.stat.status })\n // libp2p may emit a closed connection and never issue peer:disconnect event\n // see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/398\n if (!this.isStarted() || connection.stat.status !== 'OPEN') {\n return\n }\n\n this.addPeer(peerId, connection.stat.direction, connection.remoteAddr)\n this.outboundInflightQueue.push({ peerId, connection })\n }\n\n /**\n * Registrar notifies a closing connection with pubsub protocol\n */\n private onPeerDisconnected(peerId: PeerId): void {\n this.log('connection ended %p', peerId)\n this.removePeer(peerId)\n }\n\n private async createOutboundStream(peerId: PeerId, connection: Connection): Promise {\n if (!this.isStarted()) {\n return\n }\n\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // TODO make this behavior more robust\n // This behavior is different than for inbound streams\n // If an outbound stream already exists, don't create a new stream\n if (this.streamsOutbound.has(id)) {\n return\n }\n\n try {\n const stream = new OutboundStream(\n await connection.newStream(this.multicodecs),\n (e) => this.log.error('outbound pipe error', e),\n { maxBufferSize: this.opts.maxOutboundBufferSize }\n )\n\n this.log('create outbound stream %p', peerId)\n\n this.streamsOutbound.set(id, stream)\n\n const protocol = stream.protocol\n if (protocol === constants.FloodsubID) {\n this.floodsubPeers.add(id)\n }\n this.metrics?.peersPerProtocol.inc({ protocol }, 1)\n\n // Immediately send own subscriptions via the newly attached stream\n if (this.subscriptions.size > 0) {\n this.log('send subscriptions to', id)\n this.sendSubscriptions(id, Array.from(this.subscriptions), true)\n }\n } catch (e) {\n this.log.error('createOutboundStream error', e)\n }\n }\n\n private async createInboundStream(peerId: PeerId, stream: Stream): Promise {\n if (!this.isStarted()) {\n return\n }\n\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // TODO make this behavior more robust\n // This behavior is different than for outbound streams\n // If a peer initiates a new inbound connection\n // we assume that one is the new canonical inbound stream\n const priorInboundStream = this.streamsInbound.get(id)\n if (priorInboundStream !== undefined) {\n this.log('replacing existing inbound steam %s', id)\n priorInboundStream.close()\n }\n\n this.log('create inbound stream %s', id)\n\n const inboundStream = new InboundStream(stream, { maxDataLength: this.opts.maxInboundDataLength })\n this.streamsInbound.set(id, inboundStream)\n\n this.pipePeerReadStream(peerId, inboundStream.source).catch((err) => this.log(err))\n }\n\n /**\n * Add a peer to the router\n */\n private addPeer(peerId: PeerId, direction: ConnectionDirection, addr: Multiaddr): void {\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n this.log('new peer %p', peerId)\n\n this.peers.add(id)\n\n // Add to peer scoring\n this.score.addPeer(id)\n const currentIP = multiaddrToIPStr(addr)\n if (currentIP !== null) {\n this.score.addIP(id, currentIP)\n } else {\n this.log('Added peer has no IP in current address %s %s', id, addr.toString())\n }\n\n // track the connection direction. Don't allow to unset outbound\n if (!this.outbound.has(id)) {\n this.outbound.set(id, direction === 'outbound')\n }\n }\n }\n\n /**\n * Removes a peer from the router\n */\n private removePeer(peerId: PeerId): void {\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // delete peer\n this.log('delete peer %p', peerId)\n this.peers.delete(id)\n\n const outboundStream = this.streamsOutbound.get(id)\n const inboundStream = this.streamsInbound.get(id)\n\n if (outboundStream) {\n this.metrics?.peersPerProtocol.inc({ protocol: outboundStream.protocol }, -1)\n }\n\n // close streams\n outboundStream?.close()\n inboundStream?.close()\n\n // remove streams\n this.streamsOutbound.delete(id)\n this.streamsInbound.delete(id)\n\n // remove peer from topics map\n for (const peers of this.topics.values()) {\n peers.delete(id)\n }\n\n // Remove this peer from the mesh\n for (const [topicStr, peers] of this.mesh) {\n if (peers.delete(id) === true) {\n this.metrics?.onRemoveFromMesh(topicStr, ChurnReason.Dc, 1)\n }\n }\n\n // Remove this peer from the fanout\n for (const peers of this.fanout.values()) {\n peers.delete(id)\n }\n\n // Remove from floodsubPeers\n this.floodsubPeers.delete(id)\n // Remove from gossip mapping\n this.gossip.delete(id)\n // Remove from control mapping\n this.control.delete(id)\n // Remove from backoff mapping\n this.outbound.delete(id)\n\n // Remove from peer scoring\n this.score.removePeer(id)\n\n this.acceptFromWhitelist.delete(id)\n }\n\n // API METHODS\n\n get started(): boolean {\n return this.status.code === GossipStatusCode.started\n }\n\n /**\n * Get a the peer-ids in a topic mesh\n */\n getMeshPeers(topic: TopicStr): PeerIdStr[] {\n const peersInTopic = this.mesh.get(topic)\n return peersInTopic ? Array.from(peersInTopic) : []\n }\n\n /**\n * Get a list of the peer-ids that are subscribed to one topic.\n */\n getSubscribers(topic: TopicStr): PeerId[] {\n const peersInTopic = this.topics.get(topic)\n return (peersInTopic ? Array.from(peersInTopic) : []).map((str) => peerIdFromString(str))\n }\n\n /**\n * Get the list of topics which the peer is subscribed to.\n */\n getTopics(): TopicStr[] {\n return Array.from(this.subscriptions)\n }\n\n // TODO: Reviewing Pubsub API\n\n // MESSAGE METHODS\n\n /**\n * Responsible for processing each RPC message received by other peers.\n */\n private async pipePeerReadStream(peerId: PeerId, stream: AsyncIterable): Promise {\n try {\n await pipe(stream, async (source) => {\n for await (const data of source) {\n try {\n // TODO: Check max gossip message size, before decodeRpc()\n const rpcBytes = data.subarray()\n // Note: This function may throw, it must be wrapped in a try {} catch {} to prevent closing the stream.\n // TODO: What should we do if the entire RPC is invalid?\n const rpc = decodeRpc(rpcBytes, this.decodeRpcLimits)\n\n this.metrics?.onRpcRecv(rpc, rpcBytes.length)\n\n // Since processRpc may be overridden entirely in unsafe ways,\n // the simplest/safest option here is to wrap in a function and capture all errors\n // to prevent a top-level unhandled exception\n // This processing of rpc messages should happen without awaiting full validation/execution of prior messages\n if (this.opts.awaitRpcHandler) {\n try {\n await this.handleReceivedRpc(peerId, rpc)\n } catch (err) {\n this.metrics?.onRpcRecvError()\n this.log(err)\n }\n } else {\n this.handleReceivedRpc(peerId, rpc).catch((err) => {\n this.metrics?.onRpcRecvError()\n this.log(err)\n })\n }\n } catch (e) {\n this.metrics?.onRpcDataError()\n this.log(e as Error)\n }\n }\n })\n } catch (err) {\n this.metrics?.onPeerReadStreamError()\n this.handlePeerReadStreamError(err as Error, peerId)\n }\n }\n\n /**\n * Handle error when read stream pipe throws, less of the functional use but more\n * to for testing purposes to spy on the error handling\n * */\n private handlePeerReadStreamError(err: Error, peerId: PeerId): void {\n this.log.error(err)\n this.onPeerDisconnected(peerId)\n }\n\n /**\n * Handles an rpc request from a peer\n */\n public async handleReceivedRpc(from: PeerId, rpc: IRPC): Promise {\n // Check if peer is graylisted in which case we ignore the event\n if (!this.acceptFrom(from.toString())) {\n this.log('received message from unacceptable peer %p', from)\n this.metrics?.rpcRecvNotAccepted.inc()\n return\n }\n\n const subscriptions = rpc.subscriptions ? rpc.subscriptions.length : 0\n const messages = rpc.messages ? rpc.messages.length : 0\n let ihave = 0\n let iwant = 0\n let graft = 0\n let prune = 0\n if (rpc.control) {\n if (rpc.control.ihave) ihave = rpc.control.ihave.length\n if (rpc.control.iwant) iwant = rpc.control.iwant.length\n if (rpc.control.graft) graft = rpc.control.graft.length\n if (rpc.control.prune) prune = rpc.control.prune.length\n }\n this.log(\n `rpc.from ${from.toString()} subscriptions ${subscriptions} messages ${messages} ihave ${ihave} iwant ${iwant} graft ${graft} prune ${prune}`\n )\n\n // Handle received subscriptions\n if (rpc.subscriptions && rpc.subscriptions.length > 0) {\n // update peer subscriptions\n\n const subscriptions: { topic: TopicStr; subscribe: boolean }[] = []\n\n rpc.subscriptions.forEach((subOpt) => {\n const topic = subOpt.topic\n const subscribe = subOpt.subscribe === true\n\n if (topic != null) {\n if (this.allowedTopics && !this.allowedTopics.has(topic)) {\n // Not allowed: subscription data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n return\n }\n\n this.handleReceivedSubscription(from, topic, subscribe)\n\n subscriptions.push({ topic, subscribe })\n }\n })\n\n this.dispatchEvent(\n new CustomEvent('subscription-change', {\n detail: { peerId: from, subscriptions }\n })\n )\n }\n\n // Handle messages\n // TODO: (up to limit)\n if (rpc.messages) {\n for (const message of rpc.messages) {\n if (this.allowedTopics && !this.allowedTopics.has(message.topic)) {\n // Not allowed: message cache data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n continue\n }\n\n const handleReceivedMessagePromise = this.handleReceivedMessage(from, message)\n // Should never throw, but handle just in case\n .catch((err) => {\n this.metrics?.onMsgRecvError(message.topic)\n this.log(err)\n })\n\n if (this.opts.awaitRpcMessageHandler) {\n await handleReceivedMessagePromise\n }\n }\n }\n\n // Handle control messages\n if (rpc.control) {\n await this.handleControlMessage(from.toString(), rpc.control)\n }\n }\n\n /**\n * Handles a subscription change from a peer\n */\n private handleReceivedSubscription(from: PeerId, topic: TopicStr, subscribe: boolean): void {\n this.log('subscription update from %p topic %s', from, topic)\n\n let topicSet = this.topics.get(topic)\n if (topicSet == null) {\n topicSet = new Set()\n this.topics.set(topic, topicSet)\n }\n\n if (subscribe) {\n // subscribe peer to new topic\n topicSet.add(from.toString())\n } else {\n // unsubscribe from existing topic\n topicSet.delete(from.toString())\n }\n\n // TODO: rust-libp2p has A LOT more logic here\n }\n\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n private async handleReceivedMessage(from: PeerId, rpcMsg: RPC.IMessage): Promise {\n this.metrics?.onMsgRecvPreValidation(rpcMsg.topic)\n\n const validationResult = await this.validateReceivedMessage(from, rpcMsg)\n\n this.metrics?.onMsgRecvResult(rpcMsg.topic, validationResult.code)\n\n switch (validationResult.code) {\n case MessageStatus.duplicate:\n // Report the duplicate\n this.score.duplicateMessage(from.toString(), validationResult.msgIdStr, rpcMsg.topic)\n // due to the collision of fastMsgIdFn, 2 different messages may end up the same fastMsgId\n // so we need to also mark the duplicate message as delivered or the promise is not resolved\n // and peer gets penalized. See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/385\n this.gossipTracer.deliverMessage(validationResult.msgIdStr, true)\n this.mcache.observeDuplicate(validationResult.msgIdStr, from.toString())\n return\n\n case MessageStatus.invalid:\n // invalid messages received\n // metrics.register_invalid_message(&raw_message.topic)\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n if (validationResult.msgIdStr) {\n const msgIdStr = validationResult.msgIdStr\n this.score.rejectMessage(from.toString(), msgIdStr, rpcMsg.topic, validationResult.reason)\n this.gossipTracer.rejectMessage(msgIdStr, validationResult.reason)\n } else {\n this.score.rejectInvalidMessage(from.toString(), rpcMsg.topic)\n }\n\n this.metrics?.onMsgRecvInvalid(rpcMsg.topic, validationResult)\n return\n\n case MessageStatus.valid:\n // Tells score that message arrived (but is maybe not fully validated yet).\n // Consider the message as delivered for gossip promises.\n this.score.validateMessage(validationResult.messageId.msgIdStr)\n this.gossipTracer.deliverMessage(validationResult.messageId.msgIdStr)\n\n // Add the message to our memcache\n // if no validation is required, mark the message as validated\n this.mcache.put(validationResult.messageId, rpcMsg, !this.opts.asyncValidation)\n\n // Dispatch the message to the user if we are subscribed to the topic\n if (this.subscriptions.has(rpcMsg.topic)) {\n const isFromSelf = this.components.peerId.equals(from)\n\n if (!isFromSelf || this.opts.emitSelf) {\n super.dispatchEvent(\n new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: from,\n msgId: validationResult.messageId.msgIdStr,\n msg: validationResult.msg\n }\n })\n )\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: validationResult.msg }))\n }\n }\n\n // Forward the message to mesh peers, if no validation is required\n // If asyncValidation is ON, expect the app layer to call reportMessageValidationResult(), then forward\n if (!this.opts.asyncValidation) {\n // TODO: in rust-libp2p\n // .forward_msg(&msg_id, raw_message, Some(propagation_source))\n this.forwardMessage(validationResult.messageId.msgIdStr, rpcMsg, from.toString())\n }\n }\n }\n\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n private async validateReceivedMessage(\n propagationSource: PeerId,\n rpcMsg: RPC.IMessage\n ): Promise {\n // Fast message ID stuff\n const fastMsgIdStr = this.fastMsgIdFn?.(rpcMsg)\n const msgIdCached = fastMsgIdStr !== undefined ? this.fastMsgIdCache?.get(fastMsgIdStr) : undefined\n\n if (msgIdCached) {\n // This message has been seen previously. Ignore it\n return { code: MessageStatus.duplicate, msgIdStr: msgIdCached }\n }\n\n // Perform basic validation on message and convert to RawGossipsubMessage for fastMsgIdFn()\n const validationResult = await validateToRawMessage(this.globalSignaturePolicy, rpcMsg)\n\n if (!validationResult.valid) {\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: validationResult.error }\n }\n\n const msg = validationResult.message\n\n // Try and perform the data transform to the message. If it fails, consider it invalid.\n try {\n if (this.dataTransform) {\n msg.data = this.dataTransform.inboundTransform(rpcMsg.topic, msg.data)\n }\n } catch (e) {\n this.log('Invalid message, transform failed', e)\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: ValidateError.TransformFailed }\n }\n\n // TODO: Check if message is from a blacklisted source or propagation origin\n // - Reject any message from a blacklisted peer\n // - Also reject any message that originated from a blacklisted peer\n // - reject messages claiming to be from ourselves but not locally published\n\n // Calculate the message id on the transformed data.\n const msgId = await this.msgIdFn(msg)\n const msgIdStr = this.msgIdToStrFn(msgId)\n const messageId = { msgId, msgIdStr }\n\n // Add the message to the duplicate caches\n if (fastMsgIdStr !== undefined && this.fastMsgIdCache) {\n const collision = this.fastMsgIdCache.put(fastMsgIdStr, msgIdStr)\n if (collision) {\n this.metrics?.fastMsgIdCacheCollision.inc()\n }\n }\n\n if (this.seenCache.has(msgIdStr)) {\n return { code: MessageStatus.duplicate, msgIdStr }\n } else {\n this.seenCache.put(msgIdStr)\n }\n\n // (Optional) Provide custom validation here with dynamic validators per topic\n // NOTE: This custom topicValidator() must resolve fast (< 100ms) to allow scores\n // to not penalize peers for long validation times.\n const topicValidator = this.topicValidators.get(rpcMsg.topic)\n if (topicValidator != null) {\n let acceptance: TopicValidatorResult\n // Use try {} catch {} in case topicValidator() is synchronous\n try {\n acceptance = await topicValidator(propagationSource, msg)\n } catch (e) {\n const errCode = (e as { code: string }).code\n if (errCode === constants.ERR_TOPIC_VALIDATOR_IGNORE) acceptance = TopicValidatorResult.Ignore\n if (errCode === constants.ERR_TOPIC_VALIDATOR_REJECT) acceptance = TopicValidatorResult.Reject\n else acceptance = TopicValidatorResult.Ignore\n }\n\n if (acceptance !== TopicValidatorResult.Accept) {\n return { code: MessageStatus.invalid, reason: rejectReasonFromAcceptance(acceptance), msgIdStr }\n }\n }\n\n return { code: MessageStatus.valid, messageId, msg }\n }\n\n /**\n * Return score of a peer.\n */\n getScore(peerId: PeerIdStr): number {\n return this.score.score(peerId)\n }\n\n /**\n * Send an rpc object to a peer with subscriptions\n */\n private sendSubscriptions(toPeer: PeerIdStr, topics: string[], subscribe: boolean): void {\n this.sendRpc(toPeer, {\n subscriptions: topics.map((topic) => ({ topic, subscribe }))\n })\n }\n\n /**\n * Handles an rpc control message from a peer\n */\n private async handleControlMessage(id: PeerIdStr, controlMsg: RPC.IControlMessage): Promise {\n if (controlMsg === undefined) {\n return\n }\n\n const iwant = controlMsg.ihave ? this.handleIHave(id, controlMsg.ihave) : []\n const ihave = controlMsg.iwant ? this.handleIWant(id, controlMsg.iwant) : []\n const prune = controlMsg.graft ? await this.handleGraft(id, controlMsg.graft) : []\n controlMsg.prune && (await this.handlePrune(id, controlMsg.prune))\n\n if (!iwant.length && !ihave.length && !prune.length) {\n return\n }\n\n const sent = this.sendRpc(id, { messages: ihave, control: { iwant, prune } })\n const iwantMessageIds = iwant[0]?.messageIDs\n if (iwantMessageIds) {\n if (sent) {\n this.gossipTracer.addPromise(id, iwantMessageIds)\n } else {\n this.metrics?.iwantPromiseUntracked.inc(1)\n }\n }\n }\n\n /**\n * Whether to accept a message from a peer\n */\n public acceptFrom(id: PeerIdStr): boolean {\n if (this.direct.has(id)) {\n return true\n }\n\n const now = Date.now()\n const entry = this.acceptFromWhitelist.get(id)\n\n if (entry && entry.messagesAccepted < ACCEPT_FROM_WHITELIST_MAX_MESSAGES && entry.acceptUntil >= now) {\n entry.messagesAccepted += 1\n return true\n }\n\n const score = this.score.score(id)\n if (score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE) {\n // peer is unlikely to be able to drop its score to `graylistThreshold`\n // after 128 messages or 1s\n this.acceptFromWhitelist.set(id, {\n messagesAccepted: 0,\n acceptUntil: now + ACCEPT_FROM_WHITELIST_DURATION_MS\n })\n } else {\n this.acceptFromWhitelist.delete(id)\n }\n\n return score >= this.opts.scoreThresholds.graylistThreshold\n }\n\n /**\n * Handles IHAVE messages\n */\n private handleIHave(id: PeerIdStr, ihave: RPC.IControlIHave[]): RPC.IControlIWant[] {\n if (!ihave.length) {\n return []\n }\n\n // we ignore IHAVE gossip from any peer whose score is below the gossips threshold\n const score = this.score.score(id)\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IHAVE: ignoring peer %s with score below threshold [ score = %d ]', id, score)\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.LowScore })\n return []\n }\n\n // IHAVE flood protection\n const peerhave = (this.peerhave.get(id) ?? 0) + 1\n this.peerhave.set(id, peerhave)\n if (peerhave > constants.GossipsubMaxIHaveMessages) {\n this.log(\n 'IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring',\n id,\n peerhave\n )\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIhave })\n return []\n }\n\n const iasked = this.iasked.get(id) ?? 0\n if (iasked >= constants.GossipsubMaxIHaveLength) {\n this.log('IHAVE: peer %s has already advertised too many messages (%d); ignoring', id, iasked)\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIasked })\n return []\n }\n\n // string msgId => msgId\n const iwant = new Map()\n\n ihave.forEach(({ topicID, messageIDs }) => {\n if (!topicID || !messageIDs || !this.mesh.has(topicID)) {\n return\n }\n\n let idonthave = 0\n\n messageIDs.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId)\n if (!this.seenCache.has(msgIdStr)) {\n iwant.set(msgIdStr, msgId)\n idonthave++\n }\n })\n\n this.metrics?.onIhaveRcv(topicID, messageIDs.length, idonthave)\n })\n\n if (!iwant.size) {\n return []\n }\n\n let iask = iwant.size\n if (iask + iasked > constants.GossipsubMaxIHaveLength) {\n iask = constants.GossipsubMaxIHaveLength - iasked\n }\n\n this.log('IHAVE: Asking for %d out of %d messages from %s', iask, iwant.size, id)\n\n let iwantList = Array.from(iwant.values())\n // ask in random order\n shuffle(iwantList)\n\n // truncate to the messages we are actually asking for and update the iasked counter\n iwantList = iwantList.slice(0, iask)\n this.iasked.set(id, iasked + iask)\n\n // do not add gossipTracer promise here until a successful sendRpc()\n\n return [\n {\n messageIDs: iwantList\n }\n ]\n }\n\n /**\n * Handles IWANT messages\n * Returns messages to send back to peer\n */\n private handleIWant(id: PeerIdStr, iwant: RPC.IControlIWant[]): RPC.IMessage[] {\n if (!iwant.length) {\n return []\n }\n\n // we don't respond to IWANT requests from any per whose score is below the gossip threshold\n const score = this.score.score(id)\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IWANT: ignoring peer %s with score below threshold [score = %d]', id, score)\n return []\n }\n\n const ihave = new Map()\n const iwantByTopic = new Map()\n let iwantDonthave = 0\n\n iwant.forEach(({ messageIDs }) => {\n messageIDs &&\n messageIDs.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId)\n const entry = this.mcache.getWithIWantCount(msgIdStr, id)\n if (entry == null) {\n iwantDonthave++\n return\n }\n\n iwantByTopic.set(entry.msg.topic, 1 + (iwantByTopic.get(entry.msg.topic) ?? 0))\n\n if (entry.count > constants.GossipsubGossipRetransmission) {\n this.log('IWANT: Peer %s has asked for message %s too many times: ignoring request', id, msgId)\n return\n }\n\n ihave.set(msgIdStr, entry.msg)\n })\n })\n\n this.metrics?.onIwantRcv(iwantByTopic, iwantDonthave)\n\n if (!ihave.size) {\n this.log('IWANT: Could not provide any wanted messages to %s', id)\n return []\n }\n\n this.log('IWANT: Sending %d messages to %s', ihave.size, id)\n\n return Array.from(ihave.values())\n }\n\n /**\n * Handles Graft messages\n */\n private async handleGraft(id: PeerIdStr, graft: RPC.IControlGraft[]): Promise {\n const prune: TopicStr[] = []\n const score = this.score.score(id)\n const now = Date.now()\n let doPX = this.opts.doPX\n\n graft.forEach(({ topicID }) => {\n if (!topicID) {\n return\n }\n const peersInMesh = this.mesh.get(topicID)\n if (!peersInMesh) {\n // don't do PX when there is an unknown topic to avoid leaking our peers\n doPX = false\n // spam hardening: ignore GRAFTs for unknown topics\n return\n }\n\n // check if peer is already in the mesh; if so do nothing\n if (peersInMesh.has(id)) {\n return\n }\n\n // we don't GRAFT to/from direct peers; complain loudly if this happens\n if (this.direct.has(id)) {\n this.log('GRAFT: ignoring request from direct peer %s', id)\n // this is possibly a bug from a non-reciprical configuration; send a PRUNE\n prune.push(topicID)\n // but don't px\n doPX = false\n return\n }\n\n // make sure we are not backing off that peer\n const expire = this.backoff.get(topicID)?.get(id)\n if (typeof expire === 'number' && now < expire) {\n this.log('GRAFT: ignoring backed off peer %s', id)\n // add behavioral penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff)\n // no PX\n doPX = false\n // check the flood cutoff -- is the GRAFT coming too fast?\n const floodCutoff = expire + this.opts.graftFloodThreshold - this.opts.pruneBackoff\n if (now < floodCutoff) {\n // extra penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff)\n }\n // refresh the backoff\n this.addBackoff(id, topicID)\n prune.push(topicID)\n return\n }\n\n // check the score\n if (score < 0) {\n // we don't GRAFT peers with negative score\n this.log('GRAFT: ignoring peer %s with negative score: score=%d, topic=%s', id, score, topicID)\n // we do send them PRUNE however, because it's a matter of protocol correctness\n prune.push(topicID)\n // but we won't PX to them\n doPX = false\n // add/refresh backoff so that we don't reGRAFT too early even if the score decays\n this.addBackoff(id, topicID)\n return\n }\n\n // check the number of mesh peers; if it is at (or over) Dhi, we only accept grafts\n // from peers with outbound connections; this is a defensive check to restrict potential\n // mesh takeover attacks combined with love bombing\n if (peersInMesh.size >= this.opts.Dhi && !this.outbound.get(id)) {\n prune.push(topicID)\n this.addBackoff(id, topicID)\n return\n }\n\n this.log('GRAFT: Add mesh link from %s in %s', id, topicID)\n this.score.graft(id, topicID)\n peersInMesh.add(id)\n\n this.metrics?.onAddToMesh(topicID, InclusionReason.Subscribed, 1)\n })\n\n if (!prune.length) {\n return []\n }\n\n return await Promise.all(prune.map((topic) => this.makePrune(id, topic, doPX)))\n }\n\n /**\n * Handles Prune messages\n */\n private async handlePrune(id: PeerIdStr, prune: RPC.IControlPrune[]): Promise {\n const score = this.score.score(id)\n\n for (const { topicID, backoff, peers } of prune) {\n if (topicID == null) {\n continue\n }\n\n const peersInMesh = this.mesh.get(topicID)\n if (!peersInMesh) {\n return\n }\n\n this.log('PRUNE: Remove mesh link to %s in %s', id, topicID)\n this.score.prune(id, topicID)\n if (peersInMesh.has(id)) {\n peersInMesh.delete(id)\n this.metrics?.onRemoveFromMesh(topicID, ChurnReason.Unsub, 1)\n }\n\n // is there a backoff specified by the peer? if so obey it\n if (typeof backoff === 'number' && backoff > 0) {\n this.doAddBackoff(id, topicID, backoff * 1000)\n } else {\n this.addBackoff(id, topicID)\n }\n\n // PX\n if (peers && peers.length) {\n // we ignore PX from peers with insufficient scores\n if (score < this.opts.scoreThresholds.acceptPXThreshold) {\n this.log(\n 'PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]',\n id,\n score,\n topicID\n )\n continue\n }\n await this.pxConnect(peers)\n }\n }\n }\n\n /**\n * Add standard backoff log for a peer in a topic\n */\n private addBackoff(id: PeerIdStr, topic: TopicStr): void {\n this.doAddBackoff(id, topic, this.opts.pruneBackoff)\n }\n\n /**\n * Add backoff expiry interval for a peer in a topic\n *\n * @param id\n * @param topic\n * @param interval - backoff duration in milliseconds\n */\n private doAddBackoff(id: PeerIdStr, topic: TopicStr, interval: number): void {\n let backoff = this.backoff.get(topic)\n if (!backoff) {\n backoff = new Map()\n this.backoff.set(topic, backoff)\n }\n const expire = Date.now() + interval\n const existingExpire = backoff.get(id) ?? 0\n if (existingExpire < expire) {\n backoff.set(id, expire)\n }\n }\n\n /**\n * Apply penalties from broken IHAVE/IWANT promises\n */\n private applyIwantPenalties(): void {\n this.gossipTracer.getBrokenPromises().forEach((count, p) => {\n this.log(\"peer %s didn't follow up in %d IWANT requests; adding penalty\", p, count)\n this.score.addPenalty(p, count, ScorePenalty.BrokenPromise)\n })\n }\n\n /**\n * Clear expired backoff expiries\n */\n private clearBackoff(): void {\n // we only clear once every GossipsubPruneBackoffTicks ticks to avoid iterating over the maps too much\n if (this.heartbeatTicks % constants.GossipsubPruneBackoffTicks !== 0) {\n return\n }\n\n const now = Date.now()\n this.backoff.forEach((backoff, topic) => {\n backoff.forEach((expire, id) => {\n if (expire < now) {\n backoff.delete(id)\n }\n })\n if (backoff.size === 0) {\n this.backoff.delete(topic)\n }\n })\n }\n\n /**\n * Maybe reconnect to direct peers\n */\n private async directConnect(): Promise {\n const toconnect: string[] = []\n this.direct.forEach((id) => {\n if (!this.streamsOutbound.has(id)) {\n toconnect.push(id)\n }\n })\n\n await Promise.all(toconnect.map(async (id) => await this.connect(id)))\n }\n\n /**\n * Maybe attempt connection given signed peer records\n */\n private async pxConnect(peers: RPC.IPeerInfo[]): Promise {\n if (peers.length > this.opts.prunePeers) {\n shuffle(peers)\n peers = peers.slice(0, this.opts.prunePeers)\n }\n const toconnect: string[] = []\n\n await Promise.all(\n peers.map(async (pi) => {\n if (!pi.peerID) {\n return\n }\n\n const p = peerIdFromBytes(pi.peerID).toString()\n\n if (this.peers.has(p)) {\n return\n }\n\n if (!pi.signedPeerRecord) {\n toconnect.push(p)\n return\n }\n\n // The peer sent us a signed record\n // This is not a record from the peer who sent the record, but another peer who is connected with it\n // Ensure that it is valid\n try {\n const envelope = await RecordEnvelope.openAndCertify(pi.signedPeerRecord, 'libp2p-peer-record')\n const eid = envelope.peerId\n if (!envelope.peerId.equals(p)) {\n this.log(\"bogus peer record obtained through px: peer ID %p doesn't match expected peer %p\", eid, p)\n return\n }\n if (!(await this.components.peerStore.addressBook.consumePeerRecord(envelope))) {\n this.log('bogus peer record obtained through px: could not add peer record to address book')\n return\n }\n toconnect.push(p)\n } catch (e) {\n this.log('bogus peer record obtained through px: invalid signature or not a peer record')\n }\n })\n )\n\n if (!toconnect.length) {\n return\n }\n\n await Promise.all(toconnect.map(async (id) => await this.connect(id)))\n }\n\n /**\n * Connect to a peer using the gossipsub protocol\n */\n private async connect(id: PeerIdStr): Promise {\n this.log('Initiating connection with %s', id)\n const peerId = peerIdFromString(id)\n const connection = await this.components.connectionManager.openConnection(peerId)\n for (const multicodec of this.multicodecs) {\n for (const topology of this.components.registrar.getTopologies(multicodec)) {\n topology.onConnect(peerId, connection)\n }\n }\n }\n\n /**\n * Subscribes to a topic\n */\n subscribe(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub has not started')\n }\n\n if (!this.subscriptions.has(topic)) {\n this.subscriptions.add(topic)\n\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], true)\n }\n }\n\n this.join(topic)\n }\n\n /**\n * Unsubscribe to a topic\n */\n unsubscribe(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub is not started')\n }\n\n const wasSubscribed = this.subscriptions.delete(topic)\n\n this.log('unsubscribe from %s - am subscribed %s', topic, wasSubscribed)\n\n if (wasSubscribed) {\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], false)\n }\n }\n\n this.leave(topic)\n }\n\n /**\n * Join topic\n */\n private join(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started')\n }\n\n // if we are already in the mesh, return\n if (this.mesh.has(topic)) {\n return\n }\n\n this.log('JOIN %s', topic)\n this.metrics?.onJoin(topic)\n\n const toAdd = new Set()\n\n // check if we have mesh_n peers in fanout[topic] and add them to the mesh if we do,\n // removing the fanout entry.\n const fanoutPeers = this.fanout.get(topic)\n if (fanoutPeers) {\n // Remove fanout entry and the last published time\n this.fanout.delete(topic)\n this.fanoutLastpub.delete(topic)\n\n // remove explicit peers, peers with negative scores, and backoffed peers\n fanoutPeers.forEach((id) => {\n // TODO:rust-libp2p checks `self.backoffs.is_backoff_with_slack()`\n if (!this.direct.has(id) && this.score.score(id) >= 0) {\n toAdd.add(id)\n }\n })\n\n this.metrics?.onAddToMesh(topic, InclusionReason.Fanout, toAdd.size)\n }\n\n // check if we need to get more peers, which we randomly select\n if (toAdd.size < this.opts.D) {\n const fanoutCount = toAdd.size\n const newPeers = this.getRandomGossipPeers(\n topic,\n this.opts.D,\n (id: PeerIdStr): boolean =>\n // filter direct peers and peers with negative score\n !toAdd.has(id) && !this.direct.has(id) && this.score.score(id) >= 0\n )\n\n newPeers.forEach((peer) => {\n toAdd.add(peer)\n })\n\n this.metrics?.onAddToMesh(topic, InclusionReason.Random, toAdd.size - fanoutCount)\n }\n\n this.mesh.set(topic, toAdd)\n\n toAdd.forEach((id) => {\n this.log('JOIN: Add mesh link to %s in %s', id, topic)\n this.sendGraft(id, topic)\n\n // rust-libp2p\n // - peer_score.graft()\n // - Self::control_pool_add()\n // - peer_added_to_mesh()\n })\n }\n\n /**\n * Leave topic\n */\n private leave(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started')\n }\n\n this.log('LEAVE %s', topic)\n this.metrics?.onLeave(topic)\n\n // Send PRUNE to mesh peers\n const meshPeers = this.mesh.get(topic)\n if (meshPeers) {\n Promise.all(\n Array.from(meshPeers).map(async (id) => {\n this.log('LEAVE: Remove mesh link to %s in %s', id, topic)\n return await this.sendPrune(id, topic)\n })\n ).catch((err) => {\n this.log('Error sending prunes to mesh peers', err)\n })\n this.mesh.delete(topic)\n }\n }\n\n private selectPeersToForward(topic: TopicStr, propagationSource?: PeerIdStr, excludePeers?: Set) {\n const tosend = new Set()\n\n // Add explicit peers\n const peersInTopic = this.topics.get(topic)\n if (peersInTopic) {\n this.direct.forEach((peer) => {\n if (peersInTopic.has(peer) && propagationSource !== peer && !excludePeers?.has(peer)) {\n tosend.add(peer)\n }\n })\n\n // As of Mar 2022, spec + golang-libp2p include this while rust-libp2p does not\n // rust-libp2p: https://github.com/libp2p/rust-libp2p/blob/6cc3b4ec52c922bfcf562a29b5805c3150e37c75/protocols/gossipsub/src/behaviour.rs#L2693\n // spec: https://github.com/libp2p/specs/blob/10712c55ab309086a52eec7d25f294df4fa96528/pubsub/gossipsub/gossipsub-v1.0.md?plain=1#L361\n this.floodsubPeers.forEach((peer) => {\n if (\n peersInTopic.has(peer) &&\n propagationSource !== peer &&\n !excludePeers?.has(peer) &&\n this.score.score(peer) >= this.opts.scoreThresholds.publishThreshold\n ) {\n tosend.add(peer)\n }\n })\n }\n\n // add mesh peers\n const meshPeers = this.mesh.get(topic)\n if (meshPeers && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n if (propagationSource !== peer && !excludePeers?.has(peer)) {\n tosend.add(peer)\n }\n })\n }\n\n return tosend\n }\n\n private selectPeersToPublish(topic: TopicStr): {\n tosend: Set\n tosendCount: ToSendGroupCount\n } {\n const tosend = new Set()\n const tosendCount: ToSendGroupCount = {\n direct: 0,\n floodsub: 0,\n mesh: 0,\n fanout: 0\n }\n\n const peersInTopic = this.topics.get(topic)\n if (peersInTopic) {\n // flood-publish behavior\n // send to direct peers and _all_ peers meeting the publishThreshold\n if (this.opts.floodPublish) {\n peersInTopic.forEach((id) => {\n if (this.direct.has(id)) {\n tosend.add(id)\n tosendCount.direct++\n } else if (this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id)\n tosendCount.floodsub++\n }\n })\n } else {\n // non-flood-publish behavior\n // send to direct peers, subscribed floodsub peers\n // and some mesh peers above publishThreshold\n\n // direct peers (if subscribed)\n this.direct.forEach((id) => {\n if (peersInTopic.has(id)) {\n tosend.add(id)\n tosendCount.direct++\n }\n })\n\n // floodsub peers\n // Note: if there are no floodsub peers, we save a loop through peersInTopic Map\n this.floodsubPeers.forEach((id) => {\n if (peersInTopic.has(id) && this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id)\n tosendCount.floodsub++\n }\n })\n\n // Gossipsub peers handling\n const meshPeers = this.mesh.get(topic)\n if (meshPeers && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.mesh++\n })\n }\n\n // We are not in the mesh for topic, use fanout peers\n else {\n const fanoutPeers = this.fanout.get(topic)\n if (fanoutPeers && fanoutPeers.size > 0) {\n fanoutPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.fanout++\n })\n }\n\n // We have no fanout peers, select mesh_n of them and add them to the fanout\n else {\n // If we are not in the fanout, then pick peers in topic above the publishThreshold\n const newFanoutPeers = this.getRandomGossipPeers(topic, this.opts.D, (id) => {\n return this.score.score(id) >= this.opts.scoreThresholds.publishThreshold\n })\n\n if (newFanoutPeers.size > 0) {\n // eslint-disable-line max-depth\n this.fanout.set(topic, newFanoutPeers)\n\n newFanoutPeers.forEach((peer) => {\n // eslint-disable-line max-depth\n tosend.add(peer)\n tosendCount.fanout++\n })\n }\n }\n\n // We are publishing to fanout peers - update the time we published\n this.fanoutLastpub.set(topic, Date.now())\n }\n }\n }\n\n return { tosend, tosendCount }\n }\n\n /**\n * Forwards a message from our peers.\n *\n * For messages published by us (the app layer), this class uses `publish`\n */\n private forwardMessage(\n msgIdStr: string,\n rawMsg: RPC.IMessage,\n propagationSource?: PeerIdStr,\n excludePeers?: Set\n ): void {\n // message is fully validated inform peer_score\n if (propagationSource) {\n this.score.deliverMessage(propagationSource, msgIdStr, rawMsg.topic)\n }\n\n const tosend = this.selectPeersToForward(rawMsg.topic, propagationSource, excludePeers)\n\n // Note: Don't throw if tosend is empty, we can have a mesh with a single peer\n\n // forward the message to peers\n tosend.forEach((id) => {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n this.sendRpc(id, { messages: [rawMsg] })\n })\n\n this.metrics?.onForwardMsg(rawMsg.topic, tosend.size)\n }\n\n /**\n * App layer publishes a message to peers, return number of peers this message is published to\n * Note: `async` due to crypto only if `StrictSign`, otherwise it's a sync fn.\n *\n * For messages not from us, this class uses `forwardMessage`.\n */\n async publish(topic: TopicStr, data: Uint8Array, opts?: PublishOpts): Promise {\n const transformedData = this.dataTransform ? this.dataTransform.outboundTransform(topic, data) : data\n\n if (this.publishConfig == null) {\n throw Error('PublishError.Uninitialized')\n }\n\n // Prepare raw message with user's publishConfig\n const { raw: rawMsg, msg } = await buildRawMessage(this.publishConfig, topic, data, transformedData)\n\n // calculate the message id from the un-transformed data\n const msgId = await this.msgIdFn(msg)\n const msgIdStr = this.msgIdToStrFn(msgId)\n\n // Current publish opt takes precedence global opts, while preserving false value\n const ignoreDuplicatePublishError = opts?.ignoreDuplicatePublishError ?? this.opts.ignoreDuplicatePublishError\n\n if (this.seenCache.has(msgIdStr)) {\n // This message has already been seen. We don't re-publish messages that have already\n // been published on the network.\n if (ignoreDuplicatePublishError) {\n this.metrics?.onPublishDuplicateMsg(topic)\n return { recipients: [] }\n }\n throw Error('PublishError.Duplicate')\n }\n\n const { tosend, tosendCount } = this.selectPeersToPublish(topic)\n const willSendToSelf = this.opts.emitSelf === true && this.subscriptions.has(topic)\n\n // Current publish opt takes precedence global opts, while preserving false value\n const allowPublishToZeroPeers = opts?.allowPublishToZeroPeers ?? this.opts.allowPublishToZeroPeers\n\n if (tosend.size === 0 && !allowPublishToZeroPeers && !willSendToSelf) {\n throw Error('PublishError.InsufficientPeers')\n }\n\n // If the message isn't a duplicate and we have sent it to some peers add it to the\n // duplicate cache and memcache.\n this.seenCache.put(msgIdStr)\n // all published messages are valid\n this.mcache.put({ msgId, msgIdStr }, rawMsg, true)\n\n // If the message is anonymous or has a random author add it to the published message ids cache.\n this.publishedMessageIds.put(msgIdStr)\n\n // Send to set of peers aggregated from direct, mesh, fanout\n for (const id of tosend) {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n const sent = this.sendRpc(id, { messages: [rawMsg] })\n\n // did not actually send the message\n if (!sent) {\n tosend.delete(id)\n }\n }\n\n this.metrics?.onPublishMsg(topic, tosendCount, tosend.size, rawMsg.data != null ? rawMsg.data.length : 0)\n\n // Dispatch the message to the user if we are subscribed to the topic\n if (willSendToSelf) {\n tosend.add(this.components.peerId.toString())\n\n super.dispatchEvent(\n new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: this.components.peerId,\n msgId: msgIdStr,\n msg\n }\n })\n )\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: msg }))\n }\n\n return {\n recipients: Array.from(tosend.values()).map((str) => peerIdFromString(str))\n }\n }\n\n /**\n * This function should be called when `asyncValidation` is `true` after\n * the message got validated by the caller. Messages are stored in the `mcache` and\n * validation is expected to be fast enough that the messages should still exist in the cache.\n * There are three possible validation outcomes and the outcome is given in acceptance.\n *\n * If acceptance = `MessageAcceptance.Accept` the message will get propagated to the\n * network. The `propagation_source` parameter indicates who the message was received by and\n * will not be forwarded back to that peer.\n *\n * If acceptance = `MessageAcceptance.Reject` the message will be deleted from the memcache\n * and the P\u2084 penalty will be applied to the `propagationSource`.\n *\n * If acceptance = `MessageAcceptance.Ignore` the message will be deleted from the memcache\n * but no P\u2084 penalty will be applied.\n *\n * This function will return true if the message was found in the cache and false if was not\n * in the cache anymore.\n *\n * This should only be called once per message.\n */\n reportMessageValidationResult(msgId: MsgIdStr, propagationSource: PeerId, acceptance: TopicValidatorResult): void {\n if (acceptance === TopicValidatorResult.Accept) {\n const cacheEntry = this.mcache.validate(msgId)\n this.metrics?.onReportValidationMcacheHit(cacheEntry !== null)\n\n if (cacheEntry != null) {\n const { message: rawMsg, originatingPeers } = cacheEntry\n // message is fully validated inform peer_score\n this.score.deliverMessage(propagationSource.toString(), msgId, rawMsg.topic)\n\n this.forwardMessage(msgId, cacheEntry.message, propagationSource.toString(), originatingPeers)\n this.metrics?.onReportValidation(rawMsg.topic, acceptance)\n }\n // else, Message not in cache. Ignoring forwarding\n }\n\n // Not valid\n else {\n const cacheEntry = this.mcache.remove(msgId)\n this.metrics?.onReportValidationMcacheHit(cacheEntry !== null)\n\n if (cacheEntry) {\n const rejectReason = rejectReasonFromAcceptance(acceptance)\n const { message: rawMsg, originatingPeers } = cacheEntry\n\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n this.score.rejectMessage(propagationSource.toString(), msgId, rawMsg.topic, rejectReason)\n for (const peer of originatingPeers) {\n this.score.rejectMessage(peer, msgId, rawMsg.topic, rejectReason)\n }\n\n this.metrics?.onReportValidation(rawMsg.topic, acceptance)\n }\n // else, Message not in cache. Ignoring forwarding\n }\n }\n\n /**\n * Sends a GRAFT message to a peer\n */\n private sendGraft(id: PeerIdStr, topic: string): void {\n const graft = [\n {\n topicID: topic\n }\n ]\n\n this.sendRpc(id, { control: { graft } })\n }\n\n /**\n * Sends a PRUNE message to a peer\n */\n private async sendPrune(id: PeerIdStr, topic: string): Promise {\n const prune = [await this.makePrune(id, topic, this.opts.doPX)]\n\n this.sendRpc(id, { control: { prune } })\n }\n\n /**\n * Send an rpc object to a peer\n */\n private sendRpc(id: PeerIdStr, rpc: IRPC): boolean {\n const outboundStream = this.streamsOutbound.get(id)\n if (!outboundStream) {\n this.log(`Cannot send RPC to ${id} as there is no open stream to it available`)\n return false\n }\n\n // piggyback control message retries\n const ctrl = this.control.get(id)\n if (ctrl) {\n this.piggybackControl(id, rpc, ctrl)\n this.control.delete(id)\n }\n\n // piggyback gossip\n const ihave = this.gossip.get(id)\n if (ihave) {\n this.piggybackGossip(id, rpc, ihave)\n this.gossip.delete(id)\n }\n\n const rpcBytes = RPC.encode(rpc).finish()\n try {\n outboundStream.push(rpcBytes)\n } catch (e) {\n this.log.error(`Cannot send rpc to ${id}`, e)\n\n // if the peer had control messages or gossip, re-attach\n if (ctrl) {\n this.control.set(id, ctrl)\n }\n if (ihave) {\n this.gossip.set(id, ihave)\n }\n\n return false\n }\n\n this.metrics?.onRpcSent(rpc, rpcBytes.length)\n\n return true\n }\n\n /** Mutates `outRpc` adding graft and prune control messages */\n public piggybackControl(id: PeerIdStr, outRpc: IRPC, ctrl: RPC.IControlMessage): void {\n if (ctrl.graft) {\n if (!outRpc.control) outRpc.control = {}\n if (!outRpc.control.graft) outRpc.control.graft = []\n for (const graft of ctrl.graft) {\n if (graft.topicID && this.mesh.get(graft.topicID)?.has(id)) {\n outRpc.control.graft.push(graft)\n }\n }\n }\n\n if (ctrl.prune) {\n if (!outRpc.control) outRpc.control = {}\n if (!outRpc.control.prune) outRpc.control.prune = []\n for (const prune of ctrl.prune) {\n if (prune.topicID && !this.mesh.get(prune.topicID)?.has(id)) {\n outRpc.control.prune.push(prune)\n }\n }\n }\n }\n\n /** Mutates `outRpc` adding ihave control messages */\n private piggybackGossip(id: PeerIdStr, outRpc: IRPC, ihave: RPC.IControlIHave[]): void {\n if (!outRpc.control) outRpc.control = {}\n outRpc.control.ihave = ihave\n }\n\n /**\n * Send graft and prune messages\n *\n * @param tograft - peer id => topic[]\n * @param toprune - peer id => topic[]\n */\n private async sendGraftPrune(\n tograft: Map,\n toprune: Map,\n noPX: Map\n ): Promise {\n const doPX = this.opts.doPX\n for (const [id, topics] of tograft) {\n const graft = topics.map((topicID) => ({ topicID }))\n let prune: RPC.IControlPrune[] = []\n // If a peer also has prunes, process them now\n const pruning = toprune.get(id)\n if (pruning) {\n prune = await Promise.all(\n pruning.map(async (topicID) => await this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false)))\n )\n toprune.delete(id)\n }\n\n this.sendRpc(id, { control: { graft, prune } })\n }\n for (const [id, topics] of toprune) {\n const prune = await Promise.all(\n topics.map(async (topicID) => await this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false)))\n )\n this.sendRpc(id, { control: { prune } })\n }\n }\n\n /**\n * Emits gossip - Send IHAVE messages to a random set of gossip peers\n */\n private emitGossip(peersToGossipByTopic: Map>): void {\n const gossipIDsByTopic = this.mcache.getGossipIDs(new Set(peersToGossipByTopic.keys()))\n for (const [topic, peersToGossip] of peersToGossipByTopic) {\n this.doEmitGossip(topic, peersToGossip, gossipIDsByTopic.get(topic) ?? [])\n }\n }\n\n /**\n * Send gossip messages to GossipFactor peers above threshold with a minimum of D_lazy\n * Peers are randomly selected from the heartbeat which exclude mesh + fanout peers\n * We also exclude direct peers, as there is no reason to emit gossip to them\n * @param topic\n * @param candidateToGossip - peers to gossip\n * @param messageIDs - message ids to gossip\n */\n private doEmitGossip(topic: string, candidateToGossip: Set, messageIDs: Uint8Array[]): void {\n if (!messageIDs.length) {\n return\n }\n\n // shuffle to emit in random order\n shuffle(messageIDs)\n\n // if we are emitting more than GossipsubMaxIHaveLength ids, truncate the list\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // we do the truncation (with shuffling) per peer below\n this.log('too many messages for gossip; will truncate IHAVE list (%d messages)', messageIDs.length)\n }\n\n if (!candidateToGossip.size) return\n let target = this.opts.Dlazy\n const factor = constants.GossipsubGossipFactor * candidateToGossip.size\n let peersToGossip: Set | PeerIdStr[] = candidateToGossip\n if (factor > target) {\n target = factor\n }\n if (target > peersToGossip.size) {\n target = peersToGossip.size\n } else {\n // only shuffle if needed\n peersToGossip = shuffle(Array.from(peersToGossip)).slice(0, target)\n }\n\n // Emit the IHAVE gossip to the selected peers up to the target\n peersToGossip.forEach((id) => {\n let peerMessageIDs = messageIDs\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // shuffle and slice message IDs per peer so that we emit a different set for each peer\n // we have enough reduncancy in the system that this will significantly increase the message\n // coverage when we do truncate\n peerMessageIDs = shuffle(peerMessageIDs.slice()).slice(0, constants.GossipsubMaxIHaveLength)\n }\n this.pushGossip(id, {\n topicID: topic,\n messageIDs: peerMessageIDs\n })\n })\n }\n\n /**\n * Flush gossip and control messages\n */\n private flush(): void {\n // send gossip first, which will also piggyback control\n for (const [peer, ihave] of this.gossip.entries()) {\n this.gossip.delete(peer)\n this.sendRpc(peer, { control: { ihave } })\n }\n // send the remaining control messages\n for (const [peer, control] of this.control.entries()) {\n this.control.delete(peer)\n this.sendRpc(peer, { control: { graft: control.graft, prune: control.prune } })\n }\n }\n\n /**\n * Adds new IHAVE messages to pending gossip\n */\n private pushGossip(id: PeerIdStr, controlIHaveMsgs: RPC.IControlIHave): void {\n this.log('Add gossip to %s', id)\n const gossip = this.gossip.get(id) || []\n this.gossip.set(id, gossip.concat(controlIHaveMsgs))\n }\n\n /**\n * Make a PRUNE control message for a peer in a topic\n */\n private async makePrune(id: PeerIdStr, topic: string, doPX: boolean): Promise {\n this.score.prune(id, topic)\n if (this.streamsOutbound.get(id)!.protocol === constants.GossipsubIDv10) {\n // Gossipsub v1.0 -- no backoff, the peer won't be able to parse it anyway\n return {\n topicID: topic,\n peers: []\n }\n }\n // backoff is measured in seconds\n // GossipsubPruneBackoff is measured in milliseconds\n // The protobuf has it as a uint64\n const backoff = this.opts.pruneBackoff / 1000\n if (!doPX) {\n return {\n topicID: topic,\n peers: [],\n backoff: backoff\n }\n }\n // select peers for Peer eXchange\n const peers = this.getRandomGossipPeers(topic, this.opts.prunePeers, (xid) => {\n return xid !== id && this.score.score(xid) >= 0\n })\n const px = await Promise.all(\n Array.from(peers).map(async (peerId) => {\n // see if we have a signed record to send back; if we don't, just send\n // the peer ID and let the pruned peer find them in the DHT -- we can't trust\n // unsigned address records through PX anyways\n // Finding signed records in the DHT is not supported at the time of writing in js-libp2p\n const id = peerIdFromString(peerId)\n\n return {\n peerID: id.toBytes(),\n signedPeerRecord: await this.components.peerStore.addressBook.getRawEnvelope(id)\n }\n })\n )\n return {\n topicID: topic,\n peers: px,\n backoff: backoff\n }\n }\n\n private readonly runHeartbeat = () => {\n const timer = this.metrics?.heartbeatDuration.startTimer()\n\n this.heartbeat()\n .catch((err) => {\n this.log('Error running heartbeat', err)\n })\n .finally(() => {\n if (timer != null) {\n timer()\n }\n\n // Schedule the next run if still in started status\n if (this.status.code === GossipStatusCode.started) {\n // Clear previous timeout before overwriting `status.heartbeatTimeout`, it should be completed tho.\n clearTimeout(this.status.heartbeatTimeout)\n\n // NodeJS setInterval function is innexact, calls drift by a few miliseconds on each call.\n // To run the heartbeat precisely setTimeout() must be used recomputing the delay on every loop.\n let msToNextHeartbeat =\n this.opts.heartbeatInterval - ((Date.now() - this.status.hearbeatStartMs) % this.opts.heartbeatInterval)\n\n // If too close to next heartbeat, skip one\n if (msToNextHeartbeat < this.opts.heartbeatInterval * 0.25) {\n msToNextHeartbeat += this.opts.heartbeatInterval\n this.metrics?.heartbeatSkipped.inc()\n }\n\n this.status.heartbeatTimeout = setTimeout(this.runHeartbeat, msToNextHeartbeat)\n }\n })\n }\n\n /**\n * Maintains the mesh and fanout maps in gossipsub.\n */\n public async heartbeat(): Promise {\n const { D, Dlo, Dhi, Dscore, Dout, fanoutTTL } = this.opts\n\n this.heartbeatTicks++\n\n // cache scores throught the heartbeat\n const scores = new Map()\n const getScore = (id: string): number => {\n let s = scores.get(id)\n if (s === undefined) {\n s = this.score.score(id)\n scores.set(id, s)\n }\n return s\n }\n\n // peer id => topic[]\n const tograft = new Map()\n // peer id => topic[]\n const toprune = new Map()\n // peer id => don't px\n const noPX = new Map()\n\n // clean up expired backoffs\n this.clearBackoff()\n\n // clean up peerhave/iasked counters\n this.peerhave.clear()\n this.metrics?.cacheSize.set({ cache: 'iasked' }, this.iasked.size)\n this.iasked.clear()\n\n // apply IWANT request penalties\n this.applyIwantPenalties()\n\n // ensure direct peers are connected\n if (this.heartbeatTicks % this.opts.directConnectTicks === 0) {\n // we only do this every few ticks to allow pending connections to complete and account for restarts/downtime\n await this.directConnect()\n }\n\n // EXTRA: Prune caches\n this.fastMsgIdCache?.prune()\n this.seenCache.prune()\n this.gossipTracer.prune()\n this.publishedMessageIds.prune()\n\n /**\n * Instead of calling getRandomGossipPeers multiple times to:\n * + get more mesh peers\n * + more outbound peers\n * + oppportunistic grafting\n * + emitGossip\n *\n * We want to loop through the topic peers only a single time and prepare gossip peers for all topics to improve the performance\n */\n\n const peersToGossipByTopic = new Map>()\n // maintain the mesh for topics we have joined\n this.mesh.forEach((peers, topic) => {\n const peersInTopic = this.topics.get(topic)\n const candidateMeshPeers = new Set()\n const peersToGossip = new Set()\n peersToGossipByTopic.set(topic, peersToGossip)\n\n if (peersInTopic) {\n const shuffledPeers = shuffle(Array.from(peersInTopic))\n const backoff = this.backoff.get(topic)\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id)\n if (\n peerStreams &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !peers.has(id) &&\n !this.direct.has(id)\n ) {\n const score = getScore(id)\n if ((!backoff || !backoff.has(id)) && score >= 0) candidateMeshPeers.add(id)\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n }\n }\n }\n\n // prune/graft helper functions (defined per topic)\n const prunePeer = (id: PeerIdStr, reason: ChurnReason): void => {\n this.log('HEARTBEAT: Remove mesh link to %s in %s', id, topic)\n // no need to update peer score here as we do it in makePrune\n // add prune backoff record\n this.addBackoff(id, topic)\n // remove peer from mesh\n peers.delete(id)\n // after pruning a peer from mesh, we want to gossip topic to it if its score meet the gossip threshold\n if (getScore(id) >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n this.metrics?.onRemoveFromMesh(topic, reason, 1)\n // add to toprune\n const topics = toprune.get(id)\n if (!topics) {\n toprune.set(id, [topic])\n } else {\n topics.push(topic)\n }\n }\n\n const graftPeer = (id: PeerIdStr, reason: InclusionReason): void => {\n this.log('HEARTBEAT: Add mesh link to %s in %s', id, topic)\n // update peer score\n this.score.graft(id, topic)\n // add peer to mesh\n peers.add(id)\n // when we add a new mesh peer, we don't want to gossip messages to it\n peersToGossip.delete(id)\n this.metrics?.onAddToMesh(topic, reason, 1)\n // add to tograft\n const topics = tograft.get(id)\n if (!topics) {\n tograft.set(id, [topic])\n } else {\n topics.push(topic)\n }\n }\n\n // drop all peers with negative score, without PX\n peers.forEach((id) => {\n const score = getScore(id)\n\n // Record the score\n\n if (score < 0) {\n this.log('HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s', id, score, topic)\n prunePeer(id, ChurnReason.BadScore)\n noPX.set(id, true)\n }\n })\n\n // do we have enough peers?\n if (peers.size < Dlo) {\n const ineed = D - peers.size\n // slice up to first `ineed` items and remove them from candidateMeshPeers\n // same to `const newMeshPeers = candidateMeshPeers.slice(0, ineed)`\n const newMeshPeers = removeFirstNItemsFromSet(candidateMeshPeers, ineed)\n\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.NotEnough)\n })\n }\n\n // do we have to many peers?\n if (peers.size > Dhi) {\n let peersArray = Array.from(peers)\n // sort by score\n peersArray.sort((a, b) => getScore(b) - getScore(a))\n // We keep the first D_score peers by score and the remaining up to D randomly\n // under the constraint that we keep D_out peers in the mesh (if we have that many)\n peersArray = peersArray.slice(0, Dscore).concat(shuffle(peersArray.slice(Dscore)))\n\n // count the outbound peers we are keeping\n let outbound = 0\n peersArray.slice(0, D).forEach((p) => {\n if (this.outbound.get(p)) {\n outbound++\n }\n })\n\n // if it's less than D_out, bubble up some outbound peers from the random selection\n if (outbound < Dout) {\n const rotate = (i: number): void => {\n // rotate the peersArray to the right and put the ith peer in the front\n const p = peersArray[i]\n for (let j = i; j > 0; j--) {\n peersArray[j] = peersArray[j - 1]\n }\n peersArray[0] = p\n }\n\n // first bubble up all outbound peers already in the selection to the front\n if (outbound > 0) {\n let ihave = outbound\n for (let i = 1; i < D && ihave > 0; i++) {\n if (this.outbound.get(peersArray[i])) {\n rotate(i)\n ihave--\n }\n }\n }\n\n // now bubble up enough outbound peers outside the selection to the front\n let ineed = D - outbound\n for (let i = D; i < peersArray.length && ineed > 0; i++) {\n if (this.outbound.get(peersArray[i])) {\n rotate(i)\n ineed--\n }\n }\n }\n\n // prune the excess peers\n peersArray.slice(D).forEach((p) => {\n prunePeer(p, ChurnReason.Excess)\n })\n }\n\n // do we have enough outbound peers?\n if (peers.size >= Dlo) {\n // count the outbound peers we have\n let outbound = 0\n peers.forEach((p) => {\n if (this.outbound.get(p)) {\n outbound++\n }\n })\n\n // if it's less than D_out, select some peers with outbound connections and graft them\n if (outbound < Dout) {\n const ineed = Dout - outbound\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => this.outbound.get(id) === true)\n\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.Outbound)\n })\n }\n }\n\n // should we try to improve the mesh with opportunistic grafting?\n if (this.heartbeatTicks % this.opts.opportunisticGraftTicks === 0 && peers.size > 1) {\n // Opportunistic grafting works as follows: we check the median score of peers in the\n // mesh; if this score is below the opportunisticGraftThreshold, we select a few peers at\n // random with score over the median.\n // The intention is to (slowly) improve an underperforming mesh by introducing good\n // scoring peers that may have been gossiping at us. This allows us to get out of sticky\n // situations where we are stuck with poor peers and also recover from churn of good peers.\n\n // now compute the median peer score in the mesh\n const peersList = Array.from(peers).sort((a, b) => getScore(a) - getScore(b))\n const medianIndex = Math.floor(peers.size / 2)\n const medianScore = getScore(peersList[medianIndex])\n\n // if the median score is below the threshold, select a better peer (if any) and GRAFT\n if (medianScore < this.opts.scoreThresholds.opportunisticGraftThreshold) {\n const ineed = this.opts.opportunisticGraftPeers\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => getScore(id) > medianScore)\n for (const id of newMeshPeers) {\n this.log('HEARTBEAT: Opportunistically graft peer %s on topic %s', id, topic)\n graftPeer(id, InclusionReason.Opportunistic)\n }\n }\n }\n })\n\n // expire fanout for topics we haven't published to in a while\n const now = Date.now()\n this.fanoutLastpub.forEach((lastpb, topic) => {\n if (lastpb + fanoutTTL < now) {\n this.fanout.delete(topic)\n this.fanoutLastpub.delete(topic)\n }\n })\n\n // maintain our fanout for topics we are publishing but we have not joined\n this.fanout.forEach((fanoutPeers, topic) => {\n // checks whether our peers are still in the topic and have a score above the publish threshold\n const topicPeers = this.topics.get(topic)\n fanoutPeers.forEach((id) => {\n if (!topicPeers!.has(id) || getScore(id) < this.opts.scoreThresholds.publishThreshold) {\n fanoutPeers.delete(id)\n }\n })\n\n const peersInTopic = this.topics.get(topic)\n const candidateFanoutPeers = []\n // the fanout map contains topics to which we are not subscribed.\n const peersToGossip = new Set()\n peersToGossipByTopic.set(topic, peersToGossip)\n\n if (peersInTopic) {\n const shuffledPeers = shuffle(Array.from(peersInTopic))\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id)\n if (\n peerStreams &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !fanoutPeers.has(id) &&\n !this.direct.has(id)\n ) {\n const score = getScore(id)\n if (score >= this.opts.scoreThresholds.publishThreshold) candidateFanoutPeers.push(id)\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n }\n }\n }\n\n // do we need more peers?\n if (fanoutPeers.size < D) {\n const ineed = D - fanoutPeers.size\n candidateFanoutPeers.slice(0, ineed).forEach((id) => {\n fanoutPeers.add(id)\n peersToGossip?.delete(id)\n })\n }\n })\n\n this.emitGossip(peersToGossipByTopic)\n\n // send coalesced GRAFT/PRUNE messages (will piggyback gossip)\n await this.sendGraftPrune(tograft, toprune, noPX)\n\n // flush pending gossip that wasn't piggybacked above\n this.flush()\n\n // advance the message history window\n this.mcache.shift()\n\n this.dispatchEvent(new CustomEvent('gossipsub:heartbeat'))\n }\n\n /**\n * Given a topic, returns up to count peers subscribed to that topic\n * that pass an optional filter function\n *\n * @param topic\n * @param count\n * @param filter - a function to filter acceptable peers\n */\n private getRandomGossipPeers(\n topic: string,\n count: number,\n filter: (id: string) => boolean = () => true\n ): Set {\n const peersInTopic = this.topics.get(topic)\n\n if (!peersInTopic) {\n return new Set()\n }\n\n // Adds all peers using our protocol\n // that also pass the filter function\n let peers: string[] = []\n peersInTopic.forEach((id) => {\n const peerStreams = this.streamsOutbound.get(id)\n if (!peerStreams) {\n return\n }\n if (this.multicodecs.includes(peerStreams.protocol) && filter(id)) {\n peers.push(id)\n }\n })\n\n // Pseudo-randomly shuffles peers\n peers = shuffle(peers)\n if (count > 0 && peers.length > count) {\n peers = peers.slice(0, count)\n }\n\n return new Set(peers)\n }\n\n private onScrapeMetrics(metrics: Metrics): void {\n /* Data structure sizes */\n metrics.mcacheSize.set(this.mcache.size)\n metrics.mcacheNotValidatedCount.set(this.mcache.notValidatedCount)\n // Arbitrary size\n metrics.cacheSize.set({ cache: 'direct' }, this.direct.size)\n metrics.cacheSize.set({ cache: 'seenCache' }, this.seenCache.size)\n metrics.cacheSize.set({ cache: 'fastMsgIdCache' }, this.fastMsgIdCache?.size ?? 0)\n metrics.cacheSize.set({ cache: 'publishedMessageIds' }, this.publishedMessageIds.size)\n metrics.cacheSize.set({ cache: 'mcache' }, this.mcache.size)\n metrics.cacheSize.set({ cache: 'score' }, this.score.size)\n metrics.cacheSize.set({ cache: 'gossipTracer.promises' }, this.gossipTracer.size)\n metrics.cacheSize.set({ cache: 'gossipTracer.requests' }, this.gossipTracer.requestMsByMsgSize)\n // Bounded by topic\n metrics.cacheSize.set({ cache: 'topics' }, this.topics.size)\n metrics.cacheSize.set({ cache: 'subscriptions' }, this.subscriptions.size)\n metrics.cacheSize.set({ cache: 'mesh' }, this.mesh.size)\n metrics.cacheSize.set({ cache: 'fanout' }, this.fanout.size)\n // Bounded by peer\n metrics.cacheSize.set({ cache: 'peers' }, this.peers.size)\n metrics.cacheSize.set({ cache: 'streamsOutbound' }, this.streamsOutbound.size)\n metrics.cacheSize.set({ cache: 'streamsInbound' }, this.streamsInbound.size)\n metrics.cacheSize.set({ cache: 'acceptFromWhitelist' }, this.acceptFromWhitelist.size)\n metrics.cacheSize.set({ cache: 'gossip' }, this.gossip.size)\n metrics.cacheSize.set({ cache: 'control' }, this.control.size)\n metrics.cacheSize.set({ cache: 'peerhave' }, this.peerhave.size)\n metrics.cacheSize.set({ cache: 'outbound' }, this.outbound.size)\n // 2D nested data structure\n let backoffSize = 0\n for (const backoff of this.backoff.values()) {\n backoffSize += backoff.size\n }\n metrics.cacheSize.set({ cache: 'backoff' }, backoffSize)\n\n // Peer counts\n\n for (const [topicStr, peers] of this.topics) {\n metrics.topicPeersCount.set({ topicStr }, peers.size)\n }\n\n for (const [topicStr, peers] of this.mesh) {\n metrics.meshPeerCounts.set({ topicStr }, peers.size)\n }\n\n // Peer scores\n\n const scores: number[] = []\n const scoreByPeer = new Map()\n metrics.behaviourPenalty.reset()\n\n for (const peerIdStr of this.peers.keys()) {\n const score = this.score.score(peerIdStr)\n scores.push(score)\n scoreByPeer.set(peerIdStr, score)\n metrics.behaviourPenalty.observe(this.score.peerStats.get(peerIdStr)?.behaviourPenalty ?? 0)\n }\n\n metrics.registerScores(scores, this.opts.scoreThresholds)\n\n // Breakdown score per mesh topicLabel\n\n metrics.registerScorePerMesh(this.mesh, scoreByPeer)\n\n // Breakdown on each score weight\n\n const sw = computeAllPeersScoreWeights(\n this.peers.keys(),\n this.score.peerStats,\n this.score.params,\n this.score.peerIPs,\n metrics.topicStrToLabel\n )\n\n metrics.registerScoreWeights(sw)\n }\n}\n\nexport function gossipsub(\n init: Partial = {}\n): (components: GossipSubComponents) => PubSub {\n return (components: GossipSubComponents) => new GossipSub(components, init)\n}\n", "import { gossipsub } from '@chainsafe/libp2p-gossipsub'\n\n/** @typedef {import('@libp2p/interface-pubsub').PubSub} PubSub */\n\n/** @type {() => Record PubSub>}>} */\nexport const routers = () => ({\n gossipsub: gossipsub({\n fallbackToFloodsub: true,\n emitSelf: true,\n maxInboundStreams: 64,\n maxOutboundStreams: 128\n })\n})\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug)\n * module.\n *\n * @example\n *\n * ```JavaScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * log('something happened: %s', 'it was ok')\n * log.error('something bad happened: %o', err)\n *\n * log('with this peer: %p', aPeerId)\n * log('and this base58btc: %b', aUint8Array)\n * log('and this base32: %t', aUint8Array)\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\nimport debug from 'debug'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId } from '@libp2p/interface/peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\nexport interface ComponentLogger {\n forComponent(name: string): Logger\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\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\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\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: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\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 (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\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: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\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\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString(): string\n toCID(): CID\n toBytes(): Uint8Array\n equals(other: PeerId | Uint8Array | string): boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const symbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[symbol])\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```JavaScript\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\nimport { CodeError } from '@libp2p/interface/errors'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, symbol, type PeerId } from '@libp2p/interface/peer-id'\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 type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\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\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [symbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id: PeerId | Uint8Array | string): boolean {\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\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\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\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\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\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 } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n", "\nexport interface ClearableSignal extends AbortSignal {\n clear: () => void\n}\n\n/**\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: Array): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n controller.abort()\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { anySignal } from 'any-signal'\nimport { CID } from 'multiformats/cid'\nimport defer from 'p-defer'\nimport PQueue from 'p-queue'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { AbortOptions } from 'ipfs-core-types/src/utils'\n\nconst log = logger('libp2p:delegated-peer-routing')\n\nconst DEFAULT_TIMEOUT = 30e3 // 30 second default\nconst CONCURRENT_HTTP_REQUESTS = 4\n\nexport interface HTTPClientExtraOptions {\n headers?: Record\n searchParams?: URLSearchParams\n}\n\nexport enum EventTypes {\n SENDING_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADDING_PEER,\n DIALING_PEER\n}\n\n/**\n * The types of messages set/received during DHT queries\n */\nexport enum MessageType {\n PUT_VALUE = 0,\n GET_VALUE,\n ADD_PROVIDER,\n GET_PROVIDERS,\n FIND_NODE,\n PING\n}\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport interface SendingQueryEvent {\n type: EventTypes.SENDING_QUERY\n name: 'SENDING_QUERY'\n}\n\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageType: MessageType\n messageName: MessageName\n providers: PeerInfo[]\n closer: PeerInfo[]\n record?: DHTRecord\n}\n\nexport interface FinalPeerEvent {\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n}\n\nexport interface QueryErrorEvent {\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n}\n\nexport interface ProviderEvent {\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n}\n\nexport interface ValueEvent {\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n}\n\nexport interface AddingPeerEvent {\n type: EventTypes.ADDING_PEER\n name: 'ADDING_PEER'\n peer: PeerId\n}\n\nexport interface DialingPeerEvent {\n peer: PeerId\n type: EventTypes.DIALING_PEER\n name: 'DIALING_PEER'\n}\n\nexport type QueryEvent = SendingQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddingPeerEvent | DialingPeerEvent\n\nexport interface Delegate {\n getEndpointConfig(): { protocol: string, host: string, port: string }\n\n dht: {\n findPeer(peerId: PeerId, options?: AbortOptions): AsyncIterable\n query(peerId: PeerId | CID, options?: AbortOptions): AsyncIterable\n }\n}\n\nclass DelegatedPeerRouting implements PeerRouting, Startable {\n private readonly client: Delegate\n private readonly httpQueue: PQueue\n private started: boolean\n private abortController: AbortController\n\n /**\n * Create a new DelegatedPeerRouting instance\n */\n constructor (client: Delegate) {\n if (client == null) {\n throw new Error('missing ipfs http client')\n }\n\n this.client = client\n this.started = false\n this.abortController = new AbortController()\n\n // limit concurrency to avoid request flood in web browser\n // https://github.com/libp2p/js-libp2p-delegated-content-routing/issues/12\n this.httpQueue = new PQueue({\n concurrency: CONCURRENT_HTTP_REQUESTS\n })\n\n const {\n protocol,\n host,\n port\n } = client.getEndpointConfig()\n\n log(`enabled DelegatedPeerRouting via ${protocol}://${host}:${port}`)\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n stop (): void {\n this.httpQueue.clear()\n this.abortController.abort()\n this.abortController = new AbortController()\n this.started = false\n }\n\n /**\n * Attempts to find the given peer\n */\n async findPeer (id: PeerId, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('findPeer starts: %p', id)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.findPeer(id, {\n ...options,\n signal\n })) {\n if (event.name === 'FINAL_PEER' && event.peer.multiaddrs.length > 0) {\n const peerInfo: PeerInfo = {\n id: event.peer.id,\n multiaddrs: event.peer.multiaddrs,\n protocols: []\n }\n\n return peerInfo\n }\n }\n\n throw new CodeError('Not found', 'ERR_NOT_FOUND')\n } catch (err: any) {\n log.error('findPeer errored: %o', err)\n\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('findPeer finished: %p', id)\n }\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options: HTTPClientExtraOptions & AbortOptions = {}): AsyncGenerator {\n let cidOrPeerId: CID | PeerId\n const cid = CID.asCID(key)\n\n if (cid != null) {\n cidOrPeerId = cid\n } else {\n cidOrPeerId = peerIdFromBytes(key)\n }\n\n log('getClosestPeers starts: %s', cidOrPeerId)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.query(cidOrPeerId, {\n ...options,\n signal\n })) {\n if (event.name === 'PEER_RESPONSE') {\n yield * event.closer.map(closer => ({\n id: closer.id,\n multiaddrs: closer.multiaddrs,\n protocols: []\n }))\n }\n }\n } catch (err) {\n log.error('getClosestPeers errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('getClosestPeers finished: %b', key)\n }\n }\n}\n\nexport function delegatedPeerRouting (client: Delegate): (components?: any) => PeerRouting {\n return () => new DelegatedPeerRouting(client)\n}\n", "import { logger } from '@libp2p/logger'\nimport { anySignal } from 'any-signal'\nimport errCode from 'err-code'\nimport drain from 'it-drain'\nimport defer from 'p-defer'\nimport PQueue from 'p-queue'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { AbortOptions } from 'ipfs-core-types/src/utils'\nimport type { CID } from 'multiformats/cid'\n\nconst log = logger('libp2p:delegated-content-routing')\n\nconst DEFAULT_TIMEOUT = 30e3 // 30 second default\nconst CONCURRENT_HTTP_REQUESTS = 4\nconst CONCURRENT_HTTP_REFS_REQUESTS = 2\n\nexport interface HTTPClientExtraOptions {\n headers?: Record\n searchParams?: URLSearchParams\n}\n\nexport enum EventTypes {\n SENDING_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADDING_PEER,\n DIALING_PEER\n}\n\n/**\n * The types of messages set/received during DHT queries\n */\nexport enum MessageType {\n PUT_VALUE = 0,\n GET_VALUE,\n ADD_PROVIDER,\n GET_PROVIDERS,\n FIND_NODE,\n PING\n}\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport interface SendingQueryEvent {\n type: EventTypes.SENDING_QUERY\n name: 'SENDING_QUERY'\n}\n\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageType: MessageType\n messageName: MessageName\n providers: PeerInfo[]\n closer: PeerInfo[]\n record?: DHTRecord\n}\n\nexport interface FinalPeerEvent {\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n}\n\nexport interface QueryErrorEvent {\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n}\n\nexport interface ProviderEvent {\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n}\n\nexport interface ValueEvent {\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n}\n\nexport interface AddingPeerEvent {\n type: EventTypes.ADDING_PEER\n name: 'ADDING_PEER'\n peer: PeerId\n}\n\nexport interface DialingPeerEvent {\n peer: PeerId\n type: EventTypes.DIALING_PEER\n name: 'DIALING_PEER'\n}\n\nexport type QueryEvent = SendingQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddingPeerEvent | DialingPeerEvent\n\nexport interface DHTProvideOptions extends AbortOptions {\n recursive?: boolean\n}\n\nexport interface StatResult {\n cid: CID\n size: number\n}\n\nexport interface Delegate {\n getEndpointConfig(): { protocol: string, host: string, port: string }\n\n block: {\n stat(cid: CID, options?: AbortOptions): Promise\n }\n\n dht: {\n findProvs(cid: CID, options?: HTTPClientExtraOptions & AbortOptions): AsyncIterable\n provide(cid: CID, options?: HTTPClientExtraOptions & DHTProvideOptions): AsyncIterable\n put(key: string | Uint8Array, value: Uint8Array, options?: HTTPClientExtraOptions & AbortOptions): AsyncIterable\n get(key: string | Uint8Array, options?: HTTPClientExtraOptions & AbortOptions): AsyncIterable\n }\n}\n\n/**\n * An implementation of content routing, using a delegated peer\n */\nclass DelegatedContentRouting implements ContentRouting, Startable {\n private readonly client: Delegate\n private readonly httpQueue: PQueue\n private readonly httpQueueRefs: PQueue\n private started: boolean\n private abortController: AbortController\n\n /**\n * Create a new DelegatedContentRouting instance\n */\n constructor (client: Delegate) {\n if (client == null) {\n throw new Error('missing ipfs http client')\n }\n\n this.client = client\n this.started = false\n this.abortController = new AbortController()\n\n // limit concurrency to avoid request flood in web browser\n // https://github.com/libp2p/js-libp2p-delegated-content-routing/issues/12\n this.httpQueue = new PQueue({\n concurrency: CONCURRENT_HTTP_REQUESTS\n })\n // sometimes refs requests take long time, they need separate queue\n // to not suffocate regular business\n this.httpQueueRefs = new PQueue({\n concurrency: CONCURRENT_HTTP_REFS_REQUESTS\n })\n\n const {\n protocol,\n host,\n port\n } = client.getEndpointConfig()\n\n log(`enabled DelegatedContentRouting via ${protocol}://${host}:${port}`)\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n stop (): void {\n this.httpQueue.clear()\n this.httpQueueRefs.clear()\n this.abortController.abort()\n this.abortController = new AbortController()\n this.started = false\n }\n\n /**\n * Search the dht for providers of the given CID.\n *\n * - call `findProviders` on the delegated node.\n */\n async * findProviders (key: CID, options: HTTPClientExtraOptions & AbortOptions = {}): AsyncIterable {\n log('findProviders starts: %c', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.findProvs(key, {\n ...options,\n signal\n })) {\n if (event.name === 'PROVIDER') {\n yield * event.providers.map(prov => {\n const peerInfo: PeerInfo = {\n id: prov.id,\n protocols: [],\n multiaddrs: prov.multiaddrs\n }\n\n return peerInfo\n })\n }\n }\n } catch (err) {\n log.error('findProviders errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('findProviders finished: %c', key)\n }\n }\n\n /**\n * Announce to the network that the delegated node can provide the given key.\n *\n * Currently this uses the following hack\n * - delegate is one of bootstrap nodes, so we are always connected to it\n * - call block stat on the delegated node, so it fetches the content\n * - call dht provide with the passed cid\n *\n * N.B. this must be called for every block in the dag you want provided otherwise\n * the delegate will only be able to supply the root block of the dag when asked\n * for the data by an interested peer.\n */\n async provide (key: CID, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('provide starts: %c', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n await this.client.block.stat(key, {\n ...options,\n signal\n })\n await drain(this.client.dht.provide(key, {\n ...options,\n signal\n }))\n } catch (err) {\n log.error('provide errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('provide finished: %c', key)\n }\n }\n\n /**\n * Stores a value in the backing key/value store of the delegated content router.\n * This may fail if the delegated node's content routing implementation does not\n * use a key/value store, or if the delegated operation fails.\n */\n async put (key: Uint8Array, value: Uint8Array, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('put value start: %b', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n await drain(this.client.dht.put(key, value, {\n ...options,\n signal\n }))\n } catch (err) {\n log.error('put errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('put finished: %b', key)\n }\n }\n\n /**\n * Fetches an value from the backing key/value store of the delegated content router.\n * This may fail if the delegated node's content routing implementation does not\n * use a key/value store, or if the delegated operation fails.\n */\n async get (key: Uint8Array, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('get value start: %b', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.get(key, {\n ...options,\n signal\n })) {\n if (event.name === 'VALUE') {\n log('get value finished: %b', key)\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n } catch (err) {\n log.error('put errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('put finished: %b', key)\n }\n }\n}\n\nexport function delegatedContentRouting (client: Delegate): (components?: any) => ContentRouting {\n return () => new DelegatedContentRouting(client)\n}\n", "/**\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 */\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nfunction drain (source: Iterable): void\nfunction drain (source: Iterable | AsyncIterable): Promise\nfunction drain (source: Iterable | AsyncIterable): Promise | void {\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 } else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\n\nexport default drain\n", "/**\n * @typedef {import('multiformats/bases/interface').MultibaseCodec} MultibaseCodec\n * @typedef {import('./types').LoadBaseFn} LoadBaseFn\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @type {LoadBaseFn}\n */\nconst LOAD_BASE = (name) => Promise.reject(new Error(`No base found for \"${name}\"`))\n\nexport class Multibases {\n /**\n * @param {object} options\n * @param {LoadBaseFn} [options.loadBase]\n * @param {MultibaseCodec[]} options.bases\n */\n constructor (options) {\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._basesByName = {}\n\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._basesByPrefix = {}\n\n this._loadBase = options.loadBase || LOAD_BASE\n\n // Enable all supplied codecs\n for (const base of options.bases) {\n this.addBase(base)\n }\n }\n\n /**\n * Add support for a multibase codec\n *\n * @param {MultibaseCodec} base\n */\n addBase (base) {\n if (this._basesByName[base.name] || this._basesByPrefix[base.prefix]) {\n throw new Error(`Codec already exists for codec \"${base.name}\"`)\n }\n\n this._basesByName[base.name] = base\n this._basesByPrefix[base.prefix] = base\n }\n\n /**\n * Remove support for a multibase codec\n *\n * @param {MultibaseCodec} base\n */\n removeBase (base) {\n delete this._basesByName[base.name]\n delete this._basesByPrefix[base.prefix]\n }\n\n /**\n * @param {string} nameOrPrefix\n */\n async getBase (nameOrPrefix) {\n if (this._basesByName[nameOrPrefix]) {\n return this._basesByName[nameOrPrefix]\n }\n\n if (this._basesByPrefix[nameOrPrefix]) {\n return this._basesByPrefix[nameOrPrefix]\n }\n\n // If not supported, attempt to dynamically load this codec\n const base = await this._loadBase(nameOrPrefix)\n\n if (this._basesByName[base.name] == null && this._basesByPrefix[base.prefix] == null) {\n this.addBase(base)\n }\n\n return base\n }\n\n listBases () {\n return Object.values(this._basesByName)\n }\n}\n", "/**\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('./types').LoadCodecFn} LoadCodecFn\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @type {LoadCodecFn}\n */\nconst LOAD_CODEC = (codeOrName) => Promise.reject(new Error(`No codec found for \"${codeOrName}\"`))\n\nexport class Multicodecs {\n /**\n * @param {object} options\n * @param {LoadCodecFn} [options.loadCodec]\n * @param {BlockCodec[]} options.codecs\n */\n constructor (options) {\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._codecsByName = {}\n\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._codecsByCode = {}\n\n this._loadCodec = options.loadCodec || LOAD_CODEC\n\n // Enable all supplied codecs\n for (const codec of options.codecs) {\n this.addCodec(codec)\n }\n }\n\n /**\n * Add support for a block codec\n *\n * @param {BlockCodec} codec\n */\n addCodec (codec) {\n if (this._codecsByName[codec.name] || this._codecsByCode[codec.code]) {\n throw new Error(`Resolver already exists for codec \"${codec.name}\"`)\n }\n\n this._codecsByName[codec.name] = codec\n this._codecsByCode[codec.code] = codec\n }\n\n /**\n * Remove support for a block codec\n *\n * @param {BlockCodec} codec\n */\n removeCodec (codec) {\n delete this._codecsByName[codec.name]\n delete this._codecsByCode[codec.code]\n }\n\n /**\n * @param {number | string} code\n */\n async getCodec (code) {\n const table = typeof code === 'string' ? this._codecsByName : this._codecsByCode\n\n if (table[code]) {\n return table[code]\n }\n\n // If not supported, attempt to dynamically load this codec\n const codec = await this._loadCodec(code)\n\n if (table[code] == null) {\n this.addCodec(codec)\n }\n\n return codec\n }\n\n listCodecs () {\n return Object.values(this._codecsByName)\n }\n}\n", "/**\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('./types').LoadHasherFn} LoadHasherFn\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @type {LoadHasherFn}\n */\nconst LOAD_HASHER = (codeOrName) => Promise.reject(new Error(`No hasher found for \"${codeOrName}\"`))\n\nexport class Multihashes {\n /**\n * @param {object} options\n * @param {LoadHasherFn} [options.loadHasher]\n * @param {MultihashHasher[]} options.hashers\n */\n constructor (options) {\n // Object with current list of active hashers\n /** @type {Record}} */\n this._hashersByName = {}\n\n // Object with current list of active hashers\n /** @type {Record}} */\n this._hashersByCode = {}\n\n this._loadHasher = options.loadHasher || LOAD_HASHER\n\n // Enable all supplied hashers\n for (const hasher of options.hashers) {\n this.addHasher(hasher)\n }\n }\n\n /**\n * Add support for a multibase hasher\n *\n * @param {MultihashHasher} hasher\n */\n addHasher (hasher) {\n if (this._hashersByName[hasher.name] || this._hashersByCode[hasher.code]) {\n throw new Error(`Resolver already exists for codec \"${hasher.name}\"`)\n }\n\n this._hashersByName[hasher.name] = hasher\n this._hashersByCode[hasher.code] = hasher\n }\n\n /**\n * Remove support for a multibase hasher\n *\n * @param {MultihashHasher} hasher\n */\n removeHasher (hasher) {\n delete this._hashersByName[hasher.name]\n delete this._hashersByCode[hasher.code]\n }\n\n /**\n * @param {number | string} code\n */\n async getHasher (code) {\n const table = typeof code === 'string' ? this._hashersByName : this._hashersByCode\n\n if (table[code]) {\n return table[code]\n }\n\n // If not supported, attempt to dynamically load this hasher\n const hasher = await this._loadHasher(code)\n\n if (table[code] == null) {\n this.addHasher(hasher)\n }\n\n return hasher\n }\n\n listHashers () {\n return Object.values(this._hashersByName)\n }\n}\n", "\n/* eslint-env browser */\n\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport { isBrowser, isWebWorker, isNode } from 'ipfs-utils/src/env.js'\nimport parseDuration from 'parse-duration'\nimport { logger } from '@libp2p/logger'\nimport HTTP from 'ipfs-utils/src/http.js'\nimport mergeOpts from 'merge-options'\nimport { toUrlString } from 'ipfs-core-utils/to-url-string'\nimport getAgent from 'ipfs-core-utils/agent'\n\nconst log = logger('ipfs-http-client:lib:error-handler')\nconst merge = mergeOpts.bind({ ignoreUndefined: true })\n\nconst DEFAULT_PROTOCOL = isBrowser || isWebWorker ? location.protocol : 'http'\nconst DEFAULT_HOST = isBrowser || isWebWorker ? location.hostname : 'localhost'\nconst DEFAULT_PORT = isBrowser || isWebWorker ? location.port : '5001'\n\n/**\n * @typedef {import('ipfs-utils/src/types').HTTPOptions} HTTPOptions\n * @typedef {import('../types').Options} Options\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {Options|URL|Multiaddr|string} [options]\n * @returns {Options}\n */\nconst normalizeOptions = (options = {}) => {\n let url\n /** @type {Options} */\n let opts = {}\n let agent\n\n if (typeof options === 'string' || isMultiaddr(options)) {\n url = new URL(toUrlString(options))\n } else if (options instanceof URL) {\n url = options\n } else if (typeof options.url === 'string' || isMultiaddr(options.url)) {\n url = new URL(toUrlString(options.url))\n opts = options\n } else if (options.url instanceof URL) {\n url = options.url\n opts = options\n } else {\n opts = options || {}\n\n const protocol = (opts.protocol || DEFAULT_PROTOCOL).replace(':', '')\n const host = (opts.host || DEFAULT_HOST).split(':')[0]\n const port = (opts.port || DEFAULT_PORT)\n\n url = new URL(`${protocol}://${host}:${port}`)\n }\n\n if (opts.apiPath) {\n url.pathname = opts.apiPath\n } else if (url.pathname === '/' || url.pathname === undefined) {\n url.pathname = 'api/v0'\n }\n\n if (isNode) {\n const Agent = getAgent(url)\n\n agent = opts.agent || new Agent({\n keepAlive: true,\n // Similar to browsers which limit connections to six per host\n maxSockets: 6\n })\n }\n\n return {\n ...opts,\n host: url.host,\n protocol: url.protocol.replace(':', ''),\n port: Number(url.port),\n apiPath: url.pathname,\n url,\n agent\n }\n}\n\n/**\n * @param {Response} response\n */\nexport const errorHandler = async (response) => {\n let msg\n\n try {\n if ((response.headers.get('Content-Type') || '').startsWith('application/json')) {\n const data = await response.json()\n log(data)\n msg = data.Message || data.message\n } else {\n msg = await response.text()\n }\n } catch (/** @type {any} */ err) {\n log('Failed to parse error response', err)\n // Failed to extract/parse error message from response\n msg = err.message\n }\n\n /** @type {Error} */\n let error = new HTTP.HTTPError(response)\n\n if (msg) {\n // This is what rs-ipfs returns where there's a timeout\n if (msg.includes('deadline has elapsed')) {\n error = new HTTP.TimeoutError()\n }\n\n // This is what go-ipfs returns where there's a timeout\n if (msg && msg.includes('context deadline exceeded')) {\n error = new HTTP.TimeoutError()\n }\n }\n\n // This also gets returned\n if (msg && msg.includes('request timed out')) {\n error = new HTTP.TimeoutError()\n }\n\n // If we managed to extract a message from the response, use it\n if (msg) {\n error.message = msg\n }\n\n throw error\n}\n\nconst KEBAB_REGEX = /[A-Z\\u00C0-\\u00D6\\u00D8-\\u00DE]/g\n\n/**\n * @param {string} str\n */\nconst kebabCase = (str) => {\n return str.replace(KEBAB_REGEX, function (match) {\n return '-' + match.toLowerCase()\n })\n}\n\n/**\n * @param {string | number} value\n */\nconst parseTimeout = (value) => {\n return typeof value === 'string' ? parseDuration(value) : value\n}\n\nexport class Client extends HTTP {\n /**\n * @param {Options|URL|Multiaddr|string} [options]\n */\n constructor (options = {}) {\n const opts = normalizeOptions(options)\n\n super({\n timeout: parseTimeout(opts.timeout || 0) || undefined,\n headers: opts.headers,\n base: `${opts.url}`,\n handleError: errorHandler,\n transformSearchParams: (search) => {\n const out = new URLSearchParams()\n\n for (const [key, value] of search) {\n if (\n value !== 'undefined' &&\n value !== 'null' &&\n key !== 'signal'\n ) {\n out.append(kebabCase(key), value)\n }\n\n // @ts-expect-error server timeouts are strings\n if (key === 'timeout' && !isNaN(value)) {\n out.append(kebabCase(key), value)\n }\n }\n\n return out\n },\n // @ts-expect-error this can be a https agent or a http agent\n agent: opts.agent\n })\n\n // @ts-expect-error - cannot delete no-optional fields\n delete this.get\n // @ts-expect-error - cannot delete no-optional fields\n delete this.put\n // @ts-expect-error - cannot delete no-optional fields\n delete this.delete\n // @ts-expect-error - cannot delete no-optional fields\n delete this.options\n\n const fetch = this.fetch\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n this.fetch = (resource, options = {}) => {\n if (typeof resource === 'string' && !resource.startsWith('/')) {\n resource = `${opts.url}/${resource}`\n }\n\n return fetch.call(this, resource, merge(options, {\n method: 'POST'\n }))\n }\n }\n}\n\nexport const HTTPError = HTTP.HTTPError\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n\n/**\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {string|Multiaddr|URL} url - A string, multiaddr or URL to convert to a url string\n * @returns {string}\n */\nexport function toUrlString (url) {\n try {\n // @ts-expect-error\n url = multiaddrToUri(multiaddr(url))\n } catch (/** @type {any} */ err) { }\n\n url = url.toString()\n\n return url\n}\n", "\nexport default () => {}\n", "\n/* eslint-env browser */\n\nimport { Client } from './core.js'\n\n// Set default configuration and call create function with them\n/**\n * @typedef { import(\"../types\").Options } Options\n */\n\n/**\n * @template T\n * @typedef {(client: Client, clientOptions: Options) => T} Fn\n */\n\n/**\n * @template T\n * @typedef {(clientOptions: Options) => T} Factory\n */\n\n/**\n * @template T\n * @param {Fn} fn\n * @returns {Factory}\n */\nexport const configure = (fn) => {\n return (options) => {\n return fn(new Client(options), options)\n }\n}\n", "\n/**\n * @param {number | string | undefined} mode\n */\nexport function modeToString (mode) {\n if (mode == null) {\n return undefined\n }\n\n if (typeof mode === 'string') {\n return mode\n }\n\n return mode.toString(8).padStart(4, '0')\n}\n", "import errCode from 'err-code'\n\n/**\n * @param {any} input\n */\nexport function parseMtime (input) {\n if (input == null) {\n return undefined\n }\n\n /** @type {{ secs: number, nsecs?: number } | undefined} */\n let mtime\n\n // { secs, nsecs }\n if (input.secs != null) {\n mtime = {\n secs: input.secs,\n nsecs: input.nsecs\n }\n }\n\n // UnixFS TimeSpec\n if (input.Seconds != null) {\n mtime = {\n secs: input.Seconds,\n nsecs: input.FractionalNanoseconds\n }\n }\n\n // process.hrtime()\n if (Array.isArray(input)) {\n mtime = {\n secs: input[0],\n nsecs: input[1]\n }\n }\n\n // Javascript Date\n if (input instanceof Date) {\n const ms = input.getTime()\n const secs = Math.floor(ms / 1000)\n\n mtime = {\n secs: secs,\n nsecs: (ms - (secs * 1000)) * 1000\n }\n }\n\n /*\n TODO: https://github.com/ipfs/aegir/issues/487\n\n // process.hrtime.bigint()\n if (input instanceof BigInt) {\n const secs = input / BigInt(1e9)\n const nsecs = input - (secs * BigInt(1e9))\n\n mtime = {\n secs: parseInt(secs.toString()),\n nsecs: parseInt(nsecs.toString())\n }\n }\n */\n\n if (!Object.prototype.hasOwnProperty.call(mtime, 'secs')) {\n return undefined\n }\n\n if (mtime != null && mtime.nsecs != null && (mtime.nsecs < 0 || mtime.nsecs > 999999999)) {\n throw errCode(new Error('mtime-nsecs must be within the range [0,999999999]'), 'ERR_INVALID_MTIME_NSECS')\n }\n\n return mtime\n}\n", "import { modeToString } from './mode-to-string.js'\nimport { parseMtime } from '../lib/parse-mtime.js'\n\n/**\n * @param {*} params\n * @returns {URLSearchParams}\n */\nexport function toUrlSearchParams ({ arg, searchParams, hashAlg, mtime, mode, ...options } = {}) {\n if (searchParams) {\n options = {\n ...options,\n ...searchParams\n }\n }\n\n if (hashAlg) {\n options.hash = hashAlg\n }\n\n if (mtime != null) {\n mtime = parseMtime(mtime)\n\n options.mtime = mtime.secs\n options.mtimeNsecs = mtime.nsecs\n }\n\n if (mode != null) {\n options.mode = modeToString(mode)\n }\n\n if (options.timeout && !isNaN(options.timeout)) {\n // server API expects timeouts as strings\n options.timeout = `${options.timeout}ms`\n }\n\n if (arg === undefined || arg === null) {\n arg = []\n } else if (!Array.isArray(arg)) {\n arg = [arg]\n }\n\n const urlSearchParams = new URLSearchParams(options)\n\n arg.forEach((/** @type {any} */ arg) => urlSearchParams.append('arg', arg))\n\n return urlSearchParams\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createWantlist = configure(api => {\n /**\n * @type {BitswapAPI[\"wantlist\"]}\n */\n async function wantlist (options = {}) {\n const res = await (await api.post('bitswap/wantlist', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })).json()\n\n return (res.Keys || []).map((/** @type {{ '/': string }} */ k) => CID.parse(k['/']))\n }\n return wantlist\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createWantlistForPeer = configure(api => {\n /**\n * @type {BitswapAPI[\"wantlistForPeer\"]}\n */\n async function wantlistForPeer (peerId, options = {}) {\n const res = await (await api.post('bitswap/wantlist', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n peer: peerId.toString()\n }),\n headers: options.headers\n })).json()\n\n return (res.Keys || []).map((/** @type {{ '/': string }} */ k) => CID.parse(k['/']))\n }\n return wantlistForPeer\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {BitswapAPI[\"stat\"]}\n */\n async function stat (options = {}) {\n const res = await api.post('bitswap/stat', {\n searchParams: toUrlSearchParams(options),\n signal: options.signal,\n headers: options.headers\n })\n\n return toCoreInterface(await res.json())\n }\n return stat\n})\n\n/**\n * @param {any} res\n */\nfunction toCoreInterface (res) {\n return {\n provideBufLen: res.ProvideBufLen,\n wantlist: (res.Wantlist || []).map((/** @type {{ '/': string }} */ k) => CID.parse(k['/'])),\n peers: (res.Peers || []).map((/** @type {string} */ str) => peerIdFromString(str)),\n blocksReceived: BigInt(res.BlocksReceived),\n dataReceived: BigInt(res.DataReceived),\n blocksSent: BigInt(res.BlocksSent),\n dataSent: BigInt(res.DataSent),\n dupBlksReceived: BigInt(res.DupBlksReceived),\n dupDataReceived: BigInt(res.DupDataReceived)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createUnwant = configure(api => {\n /**\n * @type {BitswapAPI[\"unwant\"]}\n */\n async function unwant (cid, options = {}) {\n const res = await api.post('bitswap/unwant', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n return res.json()\n }\n return unwant\n})\n", "import { createWantlist } from './wantlist.js'\nimport { createWantlistForPeer } from './wantlist-for-peer.js'\nimport { createStat } from './stat.js'\nimport { createUnwant } from './unwant.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createBitswap (config) {\n return {\n wantlist: createWantlist(config),\n wantlistForPeer: createWantlistForPeer(config),\n unwant: createUnwant(config),\n stat: createStat(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {BlockAPI[\"get\"]}\n */\n async function get (cid, options = {}) {\n const res = await api.post('block/get', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n return new Uint8Array(await res.arrayBuffer())\n }\n return get\n})\n", "import errCode from 'err-code'\nimport itPeekable from 'it-peekable'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport all from 'it-all'\nimport {\n isBytes,\n isBlob,\n isReadableStream\n} from './utils.js'\n\n/**\n * @param {import('ipfs-core-types/src/utils').ToContent} input\n */\nexport async function normaliseContent (input) {\n // Bytes\n if (isBytes(input)) {\n return new Blob([input])\n }\n\n // String\n if (typeof input === 'string' || input instanceof String) {\n return new Blob([input.toString()])\n }\n\n // Blob | File\n if (isBlob(input)) {\n return input\n }\n\n // Browser stream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // (Async)Iterator\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n /** @type {any} peekable */\n const peekable = itPeekable(input)\n\n /** @type {any} value **/\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n return itToBlob(peekable)\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n if (Number.isInteger(value)) {\n return new Blob([Uint8Array.from(await all(peekable))])\n }\n\n // (Async)Iterable\n if (isBytes(value) || typeof value === 'string' || value instanceof String) {\n return itToBlob(peekable)\n }\n }\n\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {AsyncIterable|Iterable} stream\n */\nasync function itToBlob (stream) {\n const parts = []\n\n for await (const chunk of stream) {\n parts.push(chunk)\n }\n\n return new Blob(parts)\n}\n", "import { normaliseContent } from './normalise-content.browser.js'\nimport { normaliseCandidateMultiple } from './normalise-candidate-multiple.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n * @typedef {import('ipfs-core-types/src/utils').BrowserImportCandidate} BrowserImportCandidate\n */\n\n/**\n * Transforms any of the `ipfs.addAll` input types into\n *\n * ```\n * AsyncIterable<{ path, mode, mtime, content: Blob }>\n * ```\n *\n * See https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options\n *\n * @param {ImportCandidateStream} input\n * @returns {AsyncGenerator}\n */\nexport function normaliseInput (input) {\n // @ts-expect-error browser normaliseContent returns a Blob not an AsyncIterable\n return normaliseCandidateMultiple(input, normaliseContent, true)\n}\n", "\n/**\n * @param {number | string | undefined} mode\n */\nexport function modeToString (mode) {\n if (mode == null) {\n return undefined\n }\n\n if (typeof mode === 'string') {\n return mode\n }\n\n return mode.toString(8).padStart(4, '0')\n}\n", "\n// Import browser version otherwise electron-renderer will end up with node\n// version and fail.\nimport { normaliseInput } from './files/normalise-input-multiple.browser.js'\nimport { modeToString } from './mode-to-string.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * @param {ImportCandidateStream} source\n * @param {AbortController} abortController\n * @param {Headers|Record} [headers]\n */\nexport async function multipartRequest (source, abortController, headers = {}) {\n const parts = []\n const formData = new FormData()\n let index = 0\n let total = 0\n\n for await (const { content, path, mode, mtime } of normaliseInput(source)) {\n let fileSuffix = ''\n const type = content ? 'file' : 'dir'\n\n if (index > 0) {\n fileSuffix = `-${index}`\n }\n\n let fieldName = type + fileSuffix\n const qs = []\n\n if (mode !== null && mode !== undefined) {\n qs.push(`mode=${modeToString(mode)}`)\n }\n\n if ((mtime) != null) {\n const { secs, nsecs } = (mtime)\n\n qs.push(`mtime=${secs}`)\n\n if (nsecs != null) {\n qs.push(`mtime-nsecs=${nsecs}`)\n }\n }\n\n if (qs.length) {\n fieldName = `${fieldName}?${qs.join('&')}`\n }\n\n if (content) {\n formData.set(fieldName, content, path != null ? encodeURIComponent(path) : undefined)\n const end = total + content.size\n parts.push({ name: path, start: total, end })\n total = end\n } else if (path != null) {\n formData.set(fieldName, new File([''], encodeURIComponent(path), { type: 'application/x-directory' }))\n } else {\n throw new Error('path or content or both must be set')\n }\n\n index++\n }\n\n return {\n total,\n parts,\n headers,\n body: formData\n }\n}\n", "import { anySignal } from 'any-signal'\n\n/**\n * @param {any[]} signals\n * @returns {AbortSignal[]}\n */\nfunction filter (signals) {\n return signals.filter(Boolean)\n}\n\n/**\n * @param {...AbortSignal|undefined} signals\n */\nexport function abortSignal (...signals) {\n return anySignal(filter(signals))\n}\n", "import { CID } from 'multiformats/cid'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n */\n\nexport const createPut = configure(api => {\n /**\n * @type {BlockAPI[\"put\"]}\n */\n async function put (data, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n let res\n try {\n const response = await api.post('block/put', {\n signal: signal,\n searchParams: toUrlSearchParams(options),\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n res = await response.json()\n } catch (/** @type {any} */ err) {\n // Retry with \"protobuf\"/\"cbor\" format for go-ipfs\n // TODO: remove when https://github.com/ipfs/go-cid/issues/75 resolved\n if (options.format === 'dag-pb') {\n return put(data, { ...options, format: 'protobuf' })\n } else if (options.format === 'dag-cbor') {\n return put(data, { ...options, format: 'cbor' })\n }\n\n throw err\n }\n\n return CID.parse(res.Key)\n }\n\n return put\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n * @typedef {import('ipfs-core-types/src/block').RmResult} RmResult\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {BlockAPI[\"rm\"]}\n */\n async function * rm (cid, options = {}) {\n if (!Array.isArray(cid)) {\n cid = [cid]\n }\n\n const res = await api.post('block/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.map(cid => cid.toString()),\n 'stream-channels': true,\n ...options\n }),\n headers: options.headers\n })\n\n for await (const removed of res.ndjson()) {\n yield toCoreInterface(removed)\n }\n }\n\n return rm\n})\n\n/**\n * @param {*} removed\n */\nfunction toCoreInterface (removed) {\n /** @type {RmResult} */\n const out = {\n cid: CID.parse(removed.Hash)\n }\n\n if (removed.Error) {\n out.error = new Error(removed.Error)\n }\n\n return out\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {BlockAPI[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n const res = await api.post('block/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return { cid: CID.parse(data.Key), size: data.Size }\n }\n\n return stat\n})\n", "import { createGet } from './get.js'\nimport { createPut } from './put.js'\nimport { createRm } from './rm.js'\nimport { createStat } from './stat.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createBlock (config) {\n return {\n get: createGet(config),\n put: createPut(config),\n rm: createRm(config),\n stat: createStat(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createAdd = configure(api => {\n /**\n * @type {BootstrapAPI[\"add\"]}\n */\n async function add (addr, options = {}) {\n const res = await api.post('bootstrap/add', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return add\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createClear = configure(api => {\n /**\n * @type {BootstrapAPI[\"clear\"]}\n */\n async function clear (options = {}) {\n const res = await api.post('bootstrap/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n all: true\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return clear\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createList = configure(api => {\n /**\n * @type {BootstrapAPI[\"list\"]}\n */\n async function list (options = {}) {\n const res = await api.post('bootstrap/list', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return list\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createReset = configure(api => {\n /**\n * @type {BootstrapAPI[\"reset\"]}\n */\n async function reset (options = {}) {\n const res = await api.post('bootstrap/add', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n default: true\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return reset\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {BootstrapAPI[\"rm\"]}\n */\n async function rm (addr, options = {}) {\n const res = await api.post('bootstrap/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return rm\n})\n", "import { createAdd } from './add.js'\nimport { createClear } from './clear.js'\nimport { createList } from './list.js'\nimport { createReset } from './reset.js'\nimport { createRm } from './rm.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createBootstrap (config) {\n return {\n add: createAdd(config),\n clear: createClear(config),\n list: createList(config),\n reset: createReset(config),\n rm: createRm(config)\n }\n}\n", "import { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config/profiles').API} ConfigProfilesAPI\n */\n\nexport const createApply = configure(api => {\n /**\n * @type {ConfigProfilesAPI[\"apply\"]}\n */\n async function apply (profile, options = {}) {\n const res = await api.post('config/profile/apply', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: profile,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return {\n original: data.OldCfg, updated: data.NewCfg\n }\n }\n\n return apply\n})\n", "\n/**\n * Convert object properties to camel case.\n * NOT recursive!\n * e.g.\n * AgentVersion => agentVersion\n * ID => id\n *\n * @param {Record} obj\n */\nexport function objectToCamel (obj) {\n if (obj == null) {\n return obj\n }\n\n const caps = /^[A-Z]+$/\n\n /** @type {Record} */\n const output = {}\n\n return Object.keys(obj).reduce((camelObj, k) => {\n if (caps.test(k)) { // all caps\n camelObj[k.toLowerCase()] = obj[k]\n } else if (caps.test(k[0])) { // pascal\n camelObj[k[0].toLowerCase() + k.slice(1)] = obj[k]\n } else {\n camelObj[k] = obj[k]\n }\n return camelObj\n }, output)\n}\n", "import { objectToCamel } from '../../lib/object-to-camel.js'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config/profiles').API} ConfigProfilesAPI\n */\n\nexport const createList = configure(api => {\n /**\n * @type {ConfigProfilesAPI[\"list\"]}\n */\n async function list (options = {}) {\n const res = await api.post('config/profile/list', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n const data = await res.json()\n\n return data.map((/** @type {Record} */ profile) => objectToCamel(profile))\n }\n return list\n})\n", "import { createApply } from './apply.js'\nimport { createList } from './list.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createProfiles (config) {\n return {\n apply: createApply(config),\n list: createList(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {ConfigAPI[\"get\"]}\n */\n const get = async (key, options = {}) => {\n if (!key) {\n throw new Error('key argument is required')\n }\n\n const res = await api.post('config', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: key,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return data.Value\n }\n\n return get\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createGetAll = configure(api => {\n /**\n * @type {ConfigAPI[\"getAll\"]}\n */\n const getAll = async (options = {}) => {\n const res = await api.post('config/show', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return data\n }\n\n return getAll\n})\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createReplace = configure(api => {\n /**\n * @type {ConfigAPI[\"replace\"]}\n */\n const replace = async (config, options = {}) => {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('config/replace', {\n signal,\n searchParams: toUrlSearchParams(options),\n ...(\n await multipartRequest([uint8ArrayFromString(JSON.stringify(config))], controller, options.headers)\n )\n })\n\n await res.text()\n }\n\n return replace\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createSet = configure(api => {\n /**\n * @type {ConfigAPI[\"set\"]}\n */\n const set = async (key, value, options = {}) => {\n if (typeof key !== 'string') {\n throw new Error('Invalid key type')\n }\n\n const params = {\n ...options,\n ...encodeParam(key, value)\n }\n\n const res = await api.post('config', {\n signal: options.signal,\n searchParams: toUrlSearchParams(params),\n headers: options.headers\n })\n\n await res.text()\n }\n\n return set\n})\n\n/**\n * @param {*} key\n * @param {*} value\n */\nconst encodeParam = (key, value) => {\n switch (typeof value) {\n case 'boolean':\n return { arg: [key, value.toString()], bool: true }\n case 'string':\n return { arg: [key, value] }\n default:\n return { arg: [key, JSON.stringify(value)], json: true }\n }\n}\n", "import { createProfiles } from './profiles/index.js'\nimport { createGet } from './get.js'\nimport { createGetAll } from './get-all.js'\nimport { createReplace } from './replace.js'\nimport { createSet } from './set.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createConfig (config) {\n return {\n getAll: createGetAll(config),\n get: createGet(config),\n set: createSet(config),\n replace: createReplace(config),\n profiles: createProfiles(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\nexport const createExport = configure(api => {\n /**\n * @type {DAGAPI[\"export\"]}\n */\n async function * dagExport (root, options = {}) {\n const res = await api.post('dag/export', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: root.toString()\n }),\n headers: options.headers\n })\n\n yield * res.iterator()\n }\n\n return dagExport\n})\n", "import { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * Retrieves IPLD Nodes along the `path` that is rooted at `cid`.\n *\n * @param {CID} cid - the CID where the resolving starts\n * @param {string} path - the path that should be resolved\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {(cid: CID, options?: AbortOptions) => Promise} getBlock\n * @param {AbortOptions} [options]\n */\nexport async function * resolve (cid, path, codecs, getBlock, options) {\n /**\n * @param {CID} cid\n */\n const load = async (cid) => {\n const codec = await codecs.getCodec(cid.code)\n const block = await getBlock(cid, options)\n\n return codec.decode(block)\n }\n\n const parts = path.split('/').filter(Boolean)\n let value = await load(cid)\n let lastCid = cid\n\n // End iteration if there isn't a CID to follow any more\n while (parts.length) {\n const key = parts.shift()\n\n if (!key) {\n throw errCode(new Error(`Could not resolve path \"${path}\"`), 'ERR_INVALID_PATH')\n }\n\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n value = value[key]\n\n yield {\n value,\n remainderPath: parts.join('/')\n }\n } else {\n throw errCode(new Error(`no link named \"${key}\" under ${lastCid}`), 'ERR_NO_LINK')\n }\n\n const cid = CID.asCID(value)\n\n if (cid) {\n lastCid = cid\n value = await load(value)\n }\n }\n\n yield {\n value,\n remainderPath: ''\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { resolve } from '../lib/resolve.js'\nimport first from 'it-first'\nimport last from 'it-last'\nimport errCode from 'err-code'\nimport { createGet as createBlockGet } from '../block/get.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} options\n */\nexport const createGet = (codecs, options) => {\n const fn = configure((api, opts) => {\n const getBlock = createBlockGet(opts)\n\n /**\n * @type {DAGAPI[\"get\"]}\n */\n const get = async (cid, options = {}) => {\n if (options.path) {\n const entry = options.localResolve\n ? await first(resolve(cid, options.path, codecs, getBlock, options))\n : await last(resolve(cid, options.path, codecs, getBlock, options))\n /** @type {import('ipfs-core-types/src/dag').GetResult | undefined} - first and last will return undefined when empty */\n const result = (entry)\n\n if (!result) {\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n\n return result\n }\n\n const codec = await codecs.getCodec(cid.code)\n const block = await getBlock(cid, options)\n const node = codec.decode(block)\n\n return {\n value: node,\n remainderPath: ''\n }\n }\n\n return get\n })\n\n return fn(options)\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\nexport const createImport = configure(api => {\n /**\n * @type {DAGAPI[\"import\"]}\n */\n async function * dagImport (source, options = {}) {\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n const { headers, body } = await multipartRequest(source, controller, options.headers)\n\n const res = await api.post('dag/import', {\n signal,\n headers,\n body,\n searchParams: toUrlSearchParams({ 'pin-roots': options.pinRoots })\n })\n\n for await (const { Root } of res.ndjson()) {\n if (Root !== undefined) {\n const { Cid: { '/': Cid }, PinErrorMsg } = Root\n\n yield {\n root: {\n cid: CID.parse(Cid),\n pinErrorMsg: PinErrorMsg\n }\n }\n }\n }\n }\n\n return dagImport\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} options\n */\nexport const createPut = (codecs, options) => {\n const fn = configure((api) => {\n /**\n * @type {DAGAPI[\"put\"]}\n */\n const put = async (dagNode, options = {}) => {\n const settings = {\n storeCodec: 'dag-cbor',\n hashAlg: 'sha2-256',\n ...options\n }\n\n let serialized\n\n if (settings.inputCodec) {\n // if you supply an inputCodec, we assume you're passing in a raw, encoded\n // block using that codec, so we'll just pass that on to the server and let\n // it deal with the decode/encode/store cycle\n if (!(dagNode instanceof Uint8Array)) {\n throw new Error('Can only inputCodec on raw bytes that can be decoded')\n }\n serialized = dagNode\n } else {\n // if you don't supply an inputCodec, we assume you've passed in a JavaScript\n // object you want to have encoded using storeCodec, so we'll prepare it for\n // you if we have the codec\n const storeCodec = await codecs.getCodec(settings.storeCodec)\n serialized = storeCodec.encode(dagNode)\n // now we have a serialized form, the server should be told to receive it\n // in that format\n settings.inputCodec = settings.storeCodec\n }\n\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, settings.signal)\n\n const res = await api.post('dag/put', {\n timeout: settings.timeout,\n signal,\n searchParams: toUrlSearchParams(settings),\n ...(\n await multipartRequest([serialized], controller, settings.headers)\n )\n })\n const data = await res.json()\n\n return CID.parse(data.Cid['/'])\n }\n\n return put\n })\n\n return fn(options)\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\nexport const createResolve = configure(api => {\n /**\n * @type {DAGAPI[\"resolve\"]}\n */\n const resolve = async (ipfsPath, options = {}) => {\n const res = await api.post('dag/resolve', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${ipfsPath}${options.path ? `/${options.path}`.replace(/\\/[/]+/g, '/') : ''}`,\n ...options\n }),\n headers: options.headers\n })\n\n const data = await res.json()\n\n return { cid: CID.parse(data.Cid['/']), remainderPath: data.RemPath }\n }\n\n return resolve\n})\n", "import { createExport } from './export.js'\nimport { createGet } from './get.js'\nimport { createImport } from './import.js'\nimport { createPut } from './put.js'\nimport { createResolve } from './resolve.js'\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} config\n */\nexport function createDag (codecs, config) {\n return {\n export: createExport(config),\n get: createGet(codecs, config),\n import: createImport(config),\n put: createPut(codecs, config),\n resolve: createResolve(config)\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport {\n SendingQuery,\n PeerResponse,\n FinalPeer,\n QueryError,\n Provider,\n Value,\n AddingPeer,\n DialingPeer\n} from './response-types.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {{Type: number, ID: string, Extra: string, Responses: {ID: string, Addrs: string[]}[]}} event\n * @returns {import('ipfs-core-types/src/dht').QueryEvent}\n */\nexport const mapEvent = (event) => {\n if (event.Type === SendingQuery) {\n return {\n name: 'SENDING_QUERY',\n type: event.Type\n }\n }\n\n if (event.Type === PeerResponse) {\n return {\n from: peerIdFromString(event.ID),\n name: 'PEER_RESPONSE',\n type: event.Type,\n // TODO: how to infer this from the go-ipfs response\n messageType: 0,\n // TODO: how to infer this from the go-ipfs response\n messageName: 'PUT_VALUE',\n closer: (event.Responses || []).map(({ ID, Addrs }) => ({ id: peerIdFromString(ID), multiaddrs: Addrs.map(addr => multiaddr(addr)), protocols: [] })),\n providers: (event.Responses || []).map(({ ID, Addrs }) => ({ id: peerIdFromString(ID), multiaddrs: Addrs.map(addr => multiaddr(addr)), protocols: [] }))\n // TODO: how to infer this from the go-ipfs response\n // record: ???\n }\n }\n\n if (event.Type === FinalPeer) {\n // dht.query ends with a FinalPeer event with no Responses\n /** @type {import('@libp2p/interface-peer-info').PeerInfo} */\n let peer = {\n // @ts-expect-error go-ipfs does not return this\n id: event.ID ?? peerIdFromString(event.ID),\n /** @type {Multiaddr[]} */\n multiaddrs: [],\n protocols: []\n }\n\n if (event.Responses && event.Responses.length) {\n // dht.findPeer has the result in the Responses field\n peer = {\n id: peerIdFromString(event.Responses[0].ID),\n multiaddrs: event.Responses[0].Addrs.map(addr => multiaddr(addr)),\n protocols: []\n }\n }\n\n return {\n name: 'FINAL_PEER',\n type: event.Type,\n peer\n }\n }\n\n if (event.Type === QueryError) {\n return {\n name: 'QUERY_ERROR',\n type: event.Type,\n error: new Error(event.Extra)\n }\n }\n\n if (event.Type === Provider) {\n return {\n name: 'PROVIDER',\n type: event.Type,\n providers: event.Responses.map(({ ID, Addrs }) => ({ id: peerIdFromString(ID), multiaddrs: Addrs.map(addr => multiaddr(addr)), protocols: [] }))\n }\n }\n\n if (event.Type === Value) {\n return {\n name: 'VALUE',\n type: event.Type,\n value: uint8ArrayFromString(event.Extra, 'base64pad')\n }\n }\n\n if (event.Type === AddingPeer) {\n const peers = event.Responses.map(({ ID }) => peerIdFromString(ID))\n\n if (!peers.length) {\n throw new Error('No peer found')\n }\n\n return {\n name: 'ADDING_PEER',\n type: event.Type,\n peer: peers[0]\n }\n }\n\n if (event.Type === DialingPeer) {\n return {\n name: 'DIALING_PEER',\n type: event.Type,\n peer: peerIdFromString(event.ID)\n }\n }\n\n throw new Error('Unknown DHT event type')\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createFindPeer = configure(api => {\n /**\n * @type {DHTAPI[\"findPeer\"]}\n */\n async function * findPeer (peerId, options = {}) {\n const res = await api.post('dht/findpeer', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: peerId,\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return findPeer\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createFindProvs = configure(api => {\n /**\n * @type {DHTAPI[\"findProvs\"]}\n */\n async function * findProvs (cid, options = {}) {\n const res = await api.post('dht/findprovs', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return findProvs\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {DHTAPI[\"get\"]}\n */\n async function * get (key, options = {}) {\n const res = await api.post('dht/get', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n // arg: base36.encode(key),\n arg: key instanceof Uint8Array ? uint8ArrayToString(key) : key.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return get\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n * @typedef {import('multiformats/cid').CID} CID\n */\n\nexport const createProvide = configure(api => {\n /**\n * @type {DHTAPI[\"provide\"]}\n */\n async function * provide (cids, options = { recursive: false }) {\n /** @type {CID[]} */\n const cidArr = Array.isArray(cids) ? cids : [cids]\n\n const res = await api.post('dht/provide', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cidArr.map(cid => cid.toString()),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return provide\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { abortSignal } from '../lib/abort-signal.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createPut = configure(api => {\n /**\n * @type {DHTAPI[\"put\"]}\n */\n async function * put (key, value, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('dht/put', {\n signal,\n searchParams: toUrlSearchParams({\n arg: key instanceof Uint8Array ? uint8ArrayToString(key) : key.toString(),\n ...options\n }),\n ...(\n await multipartRequest([value], controller, options.headers)\n )\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return put\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createQuery = configure(api => {\n /**\n * @type {DHTAPI[\"query\"]}\n */\n async function * query (peerId, options = {}) {\n const res = await api.post('dht/query', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: peerId.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return query\n})\n", "import { createFindPeer } from './find-peer.js'\nimport { createFindProvs } from './find-provs.js'\nimport { createGet } from './get.js'\nimport { createProvide } from './provide.js'\nimport { createPut } from './put.js'\nimport { createQuery } from './query.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createDht (config) {\n return {\n findPeer: createFindPeer(config),\n findProvs: createFindProvs(config),\n get: createGet(config),\n provide: createProvide(config),\n put: createPut(config),\n query: createQuery(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/diag').API} DiagAPI\n */\n\nexport const createCmds = configure(api => {\n /**\n * @type {DiagAPI[\"cmds\"]}\n */\n async function cmds (options = {}) {\n const res = await api.post('diag/cmds', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return res.json()\n }\n return cmds\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/diag').API} DiagAPI\n */\n\nexport const createNet = configure(api => {\n /**\n * @type {DiagAPI[\"net\"]}\n */\n async function net (options = {}) {\n const res = await api.post('diag/net', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n return res.json()\n }\n return net\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/diag').API} DiagAPI\n */\n\nexport const createSys = configure(api => {\n /**\n * @type {DiagAPI[\"sys\"]}\n */\n async function sys (options = {}) {\n const res = await api.post('diag/sys', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return res.json()\n }\n return sys\n})\n", "import { createCmds } from './cmds.js'\nimport { createNet } from './net.js'\nimport { createSys } from './sys.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createDiag (config) {\n return {\n cmds: createCmds(config),\n net: createNet(config),\n sys: createSys(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createChmod = configure(api => {\n /**\n * @type {FilesAPI[\"chmod\"]}\n */\n async function chmod (path, mode, options = {}) {\n const res = await api.post('files/chmod', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n mode,\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return chmod\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createCp = configure(api => {\n /**\n * @type {FilesAPI[\"cp\"]}\n */\n async function cp (sources, destination, options = {}) {\n /** @type {import('ipfs-core-types/src/utils').IPFSPath[]} */\n const sourceArr = Array.isArray(sources) ? sources : [sources]\n\n const res = await api.post('files/cp', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: sourceArr.concat(destination).map(src => CID.asCID(src) ? `/ipfs/${src}` : src),\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return cp\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createFlush = configure(api => {\n /**\n * @type {FilesAPI[\"flush\"]}\n */\n async function flush (path, options = {}) {\n if (!path || typeof path !== 'string') {\n throw new Error('ipfs.files.flush requires a path')\n }\n\n const res = await api.post('files/flush', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return CID.parse(data.Cid)\n }\n return flush\n})\n", "import { objectToCamel } from './object-to-camel.js'\n\n/**\n * @param {Record} entry\n */\nexport function objectToCamelWithMetadata (entry) {\n const file = objectToCamel(entry)\n\n if (Object.prototype.hasOwnProperty.call(file, 'mode')) {\n file.mode = parseInt(file.mode, 8)\n }\n\n if (Object.prototype.hasOwnProperty.call(file, 'mtime')) {\n file.mtime = {\n secs: file.mtime,\n nsecs: file.mtimeNsecs || 0\n }\n\n delete file.mtimeNsecs\n }\n\n return file\n}\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamelWithMetadata } from '../lib/object-to-camel-with-metadata.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\nexport const createLs = configure(api => {\n /**\n * @type {FilesAPI[\"ls\"]}\n */\n async function * ls (path, options = {}) {\n if (!path) {\n throw new Error('ipfs.files.ls requires a path')\n }\n\n const res = await api.post('files/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: CID.asCID(path) ? `/ipfs/${path}` : path,\n // default long to true, diverges from go-ipfs where its false by default\n long: true,\n ...options,\n stream: true\n }),\n headers: options.headers\n })\n\n for await (const result of res.ndjson()) {\n // go-ipfs does not yet support the \"stream\" option\n if ('Entries' in result) {\n for (const entry of result.Entries || []) {\n yield toCoreInterface(objectToCamelWithMetadata(entry))\n }\n } else {\n yield toCoreInterface(objectToCamelWithMetadata(result))\n }\n }\n }\n return ls\n})\n\n/**\n * @param {*} entry\n */\nfunction toCoreInterface (entry) {\n if (entry.hash) {\n entry.cid = CID.parse(entry.hash)\n }\n\n delete entry.hash\n\n entry.type = entry.type === 1 ? 'directory' : 'file'\n\n return entry\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createMkdir = configure(api => {\n /**\n * @type {FilesAPI[\"mkdir\"]}\n */\n async function mkdir (path, options = {}) {\n const res = await api.post('files/mkdir', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return mkdir\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createMv = configure(api => {\n /**\n * @type {FilesAPI[\"mv\"]}\n */\n async function mv (sources, destination, options = {}) {\n if (!Array.isArray(sources)) {\n sources = [sources]\n }\n\n const res = await api.post('files/mv', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: sources.concat(destination),\n ...options\n }),\n headers: options.headers\n })\n await res.text()\n }\n\n return mv\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n// @ts-expect-error no types\nimport toIterable from 'stream-to-it/source.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createRead = configure(api => {\n /**\n * @type {FilesAPI[\"read\"]}\n */\n async function * read (path, options = {}) {\n const res = await api.post('files/read', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n count: options.length,\n ...options\n }),\n headers: options.headers\n })\n\n yield * toIterable(res.body)\n }\n return read\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport HTTP from 'ipfs-utils/src/http.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {FilesAPI[\"rm\"]}\n */\n async function rm (path, options = {}) {\n const res = await api.post('files/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n\n const body = await res.text()\n // we don't expect text body to be ever present\n // (if so, it means an error such as https://github.com/ipfs/go-ipfs/issues/8606)\n if (body !== '') {\n /** @type {Error} */\n const error = new HTTP.HTTPError(res)\n error.message = body\n throw error\n }\n }\n return rm\n})\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamelWithMetadata } from '../lib/object-to-camel-with-metadata.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {FilesAPI[\"stat\"]}\n */\n async function stat (path, options = {}) {\n const res = await api.post('files/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n data.WithLocality = data.WithLocality || false\n return toCoreInterface(objectToCamelWithMetadata(data))\n }\n return stat\n})\n\n/**\n * @param {*} entry\n */\nfunction toCoreInterface (entry) {\n entry.cid = CID.parse(entry.hash)\n delete entry.hash\n return entry\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createTouch = configure(api => {\n /**\n * @type {FilesAPI[\"touch\"]}\n */\n async function touch (path, options = {}) {\n const res = await api.post('files/touch', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return touch\n})\n", "import { modeToString } from '../lib/mode-to-string.js'\nimport { parseMtime } from '../lib/parse-mtime.js'\nimport { configure } from '../lib/configure.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createWrite = configure(api => {\n /**\n * @type {FilesAPI[\"write\"]}\n */\n async function write (path, input, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('files/write', {\n signal,\n searchParams: toUrlSearchParams({\n arg: path,\n streamChannels: true,\n count: options.length,\n ...options\n }),\n ...(\n await multipartRequest([{\n content: input,\n path: 'arg',\n mode: modeToString(options.mode),\n mtime: parseMtime(options.mtime)\n }], controller, options.headers)\n )\n })\n\n await res.text()\n }\n return write\n})\n", "import { createChmod } from './chmod.js'\nimport { createCp } from './cp.js'\nimport { createFlush } from './flush.js'\nimport { createLs } from './ls.js'\nimport { createMkdir } from './mkdir.js'\nimport { createMv } from './mv.js'\nimport { createRead } from './read.js'\nimport { createRm } from './rm.js'\nimport { createStat } from './stat.js'\nimport { createTouch } from './touch.js'\nimport { createWrite } from './write.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createFiles (config) {\n return {\n chmod: createChmod(config),\n cp: createCp(config),\n flush: createFlush(config),\n ls: createLs(config),\n mkdir: createMkdir(config),\n mv: createMv(config),\n read: createRead(config),\n rm: createRm(config),\n stat: createStat(config),\n touch: createTouch(config),\n write: createWrite(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createExport = configure(api => {\n /**\n * @type {KeyAPI[\"export\"]}\n */\n const exportKey = async (name, password, options = {}) => {\n throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED')\n }\n\n return exportKey\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createGen = configure(api => {\n /**\n * @type {KeyAPI[\"gen\"]}\n */\n async function gen (name, options) {\n const opts = options ?? { type: 'Ed25519' }\n\n const res = await api.post('key/gen', {\n signal: opts.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n ...opts\n }),\n headers: opts.headers\n })\n const data = await res.json()\n\n // @ts-expect-error server output is not typed\n return objectToCamel(data)\n }\n return gen\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createImport = configure(api => {\n /**\n * @type {KeyAPI[\"import\"]}\n */\n async function importKey (name, pem, password, options = {}) {\n const res = await api.post('key/import', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n pem,\n password,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n // @ts-expect-error server output is not typed\n return objectToCamel(data)\n }\n return importKey\n})\n", "import { configure } from '../lib/configure.js'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createInfo = configure(api => {\n /**\n * @type {KeyAPI[\"info\"]}\n */\n const info = async (name, options = {}) => {\n throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED')\n }\n\n return info\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createList = configure(api => {\n /**\n * @type {KeyAPI[\"list\"]}\n */\n async function list (options = {}) {\n const res = await api.post('key/list', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n const data = await res.json()\n\n return (data.Keys || []).map((/** @type {any} **/ k) => objectToCamel(k))\n }\n return list\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createRename = configure(api => {\n /**\n * @type {KeyAPI[\"rename\"]}\n */\n async function rename (oldName, newName, options = {}) {\n const res = await api.post('key/rename', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n oldName,\n newName\n ],\n ...options\n }),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return rename\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {KeyAPI[\"rm\"]}\n */\n async function rm (name, options = {}) {\n const res = await api.post('key/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n // @ts-expect-error server output is not typed\n return objectToCamel(data.Keys[0])\n }\n return rm\n})\n", "import { createExport } from './export.js'\nimport { createGen } from './gen.js'\nimport { createImport } from './import.js'\nimport { createInfo } from './info.js'\nimport { createList } from './list.js'\nimport { createRename } from './rename.js'\nimport { createRm } from './rm.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createKey (config) {\n return {\n export: createExport(config),\n gen: createGen(config),\n import: createImport(config),\n info: createInfo(config),\n list: createList(config),\n rename: createRename(config),\n rm: createRm(config)\n }\n}\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/log').API} LogAPI\n */\n\nexport const createLevel = configure(api => {\n /**\n * @type {LogAPI[\"level\"]}\n */\n async function level (subsystem, level, options = {}) {\n const res = await api.post('log/level', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n subsystem,\n level\n ],\n ...options\n }),\n headers: options.headers\n })\n\n return objectToCamel(await res.json())\n }\n return level\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/log').API} LogAPI\n */\n\nexport const createLs = configure(api => {\n /**\n * @type {LogAPI[\"ls\"]}\n */\n async function ls (options = {}) {\n const res = await api.post('log/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n const data = await res.json()\n return data.Strings\n }\n return ls\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/log').API} LogAPI\n */\n\nexport const createTail = configure(api => {\n /**\n * @type {LogAPI[\"tail\"]}\n */\n async function * tail (options = {}) {\n const res = await api.post('log/tail', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n yield * res.ndjson()\n }\n return tail\n})\n", "import { createLevel } from './level.js'\nimport { createLs } from './ls.js'\nimport { createTail } from './tail.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createLog (config) {\n return {\n level: createLevel(config),\n ls: createLs(config),\n tail: createTail(config)\n }\n}\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name').API} NameAPI\n */\n\nexport const createPublish = configure(api => {\n /**\n * @type {NameAPI[\"publish\"]}\n */\n async function publish (path, options = {}) {\n const res = await api.post('name/publish', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${path}`,\n ...options\n }),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return publish\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name').API} NameAPI\n */\n\nexport const createResolve = configure(api => {\n /**\n * @type {NameAPI[\"resolve\"]}\n */\n async function * resolve (path, options = {}) {\n const res = await api.post('name/resolve', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n stream: true,\n ...options\n }),\n headers: options.headers\n })\n\n for await (const result of res.ndjson()) {\n yield result.Path\n }\n }\n return resolve\n})\n", "import { objectToCamel } from '../../lib/object-to-camel.js'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name/pubsub').API} NamePubsubAPI\n */\n\nexport const createCancel = configure(api => {\n /**\n * @type {NamePubsubAPI[\"cancel\"]}\n */\n async function cancel (name, options = {}) {\n const res = await api.post('name/pubsub/cancel', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n ...options\n }),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return cancel\n})\n", "import { objectToCamel } from '../../lib/object-to-camel.js'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name/pubsub').API} NamePubsubAPI\n */\n\nexport const createState = configure(api => {\n /**\n * @type {NamePubsubAPI[\"state\"]}\n */\n async function state (options = {}) {\n const res = await api.post('name/pubsub/state', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return state\n})\n", "import { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name/pubsub').API} NamePubsubAPI\n */\n\nexport const createSubs = configure(api => {\n /**\n * @type {NamePubsubAPI[\"subs\"]}\n */\n async function subs (options = {}) {\n const res = await api.post('name/pubsub/subs', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n const data = await res.json()\n\n return data.Strings || []\n }\n return subs\n})\n", "import { createCancel } from './cancel.js'\nimport { createState } from './state.js'\nimport { createSubs } from './subs.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createPubsub (config) {\n return {\n cancel: createCancel(config),\n state: createState(config),\n subs: createSubs(config)\n }\n}\n", "import { createPublish } from './publish.js'\nimport { createResolve } from './resolve.js'\nimport { createPubsub } from './pubsub/index.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createName (config) {\n return {\n publish: createPublish(config),\n resolve: createResolve(config),\n pubsub: createPubsub(config)\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createData = configure(api => {\n /**\n * @type {ObjectAPI[\"data\"]}\n */\n async function data (cid, options = {}) {\n const res = await api.post('object/data', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid instanceof Uint8Array ? CID.decode(cid) : cid}`,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.arrayBuffer()\n\n return new Uint8Array(data, 0, data.byteLength)\n }\n return data\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {ObjectAPI[\"get\"]}\n */\n async function get (cid, options = {}) {\n const res = await api.post('object/get', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid instanceof Uint8Array ? CID.decode(cid) : cid}`,\n dataEncoding: 'base64',\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return {\n Data: uint8ArrayFromString(data.Data, 'base64pad'),\n Links: (data.Links || []).map((/** @type {any} */ link) => ({\n Name: link.Name,\n Hash: CID.parse(link.Hash),\n Tsize: link.Size\n }))\n }\n }\n return get\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createLinks = configure(api => {\n /**\n * @type {ObjectAPI[\"links\"]}\n */\n async function links (cid, options = {}) {\n const res = await api.post('object/links', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid instanceof Uint8Array ? CID.decode(cid) : cid}`,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return (data.Links || []).map((/** @type {any} */ l) => ({\n Name: l.Name,\n Tsize: l.Size,\n Hash: CID.parse(l.Hash)\n }))\n }\n return links\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createNew = configure(api => {\n /**\n * @type {ObjectAPI[\"new\"]}\n */\n async function newObject (options = {}) {\n const res = await api.post('object/new', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: options.template,\n ...options\n }),\n headers: options.headers\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return newObject\n})\n", "import { configure } from '../lib/configure.js'\nimport { createPut as createDagPut } from '../dag/put.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} options\n */\nexport const createPut = (codecs, options) => {\n const fn = configure((api) => {\n const dagPut = createDagPut(codecs, options)\n\n /**\n * @type {ObjectAPI[\"put\"]}\n */\n async function put (obj, options = {}) {\n return dagPut(obj, {\n ...options,\n storeCodec: 'dag-pb',\n hashAlg: 'sha2-256',\n version: 1\n })\n }\n return put\n })\n\n return fn(options)\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {ObjectAPI[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n const res = await api.post('object/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid}`,\n ...options\n }),\n headers: options.headers\n })\n\n const output = await res.json()\n\n return {\n ...output,\n Hash: CID.parse(output.Hash)\n }\n }\n return stat\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createAddLink = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"addLink\"]}\n */\n async function addLink (cid, dLink, options = {}) {\n const res = await api.post('object/patch/add-link', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n `${cid}`,\n // @ts-expect-error loose types\n dLink.Name || dLink.name || '',\n // @ts-expect-error loose types\n (dLink.Hash || dLink.cid || '').toString() || null\n ],\n ...options\n }),\n headers: options.headers\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n\n return addLink\n})\n", "import { CID } from 'multiformats/cid'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\nimport { abortSignal } from '../../lib/abort-signal.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createAppendData = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"appendData\"]}\n */\n async function appendData (cid, data, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('object/patch/append-data', {\n signal,\n searchParams: toUrlSearchParams({\n arg: `${cid}`,\n ...options\n }),\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return appendData\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createRmLink = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"rmLink\"]}\n */\n async function rmLink (cid, dLink, options = {}) {\n const res = await api.post('object/patch/rm-link', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n `${cid}`,\n // @ts-expect-error loose types\n dLink.Name || dLink.name || null\n ],\n ...options\n }),\n headers: options.headers\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return rmLink\n})\n", "import { CID } from 'multiformats/cid'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\nimport { abortSignal } from '../../lib/abort-signal.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createSetData = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"setData\"]}\n */\n async function setData (cid, data, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('object/patch/set-data', {\n signal,\n searchParams: toUrlSearchParams({\n arg: [\n `${cid}`\n ],\n ...options\n }),\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return setData\n})\n", "import { createAddLink } from './add-link.js'\nimport { createAppendData } from './append-data.js'\nimport { createRmLink } from './rm-link.js'\nimport { createSetData } from './set-data.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createPatch (config) {\n return {\n addLink: createAddLink(config),\n appendData: createAppendData(config),\n rmLink: createRmLink(config),\n setData: createSetData(config)\n }\n}\n", "import { createData } from './data.js'\nimport { createGet } from './get.js'\nimport { createLinks } from './links.js'\nimport { createNew } from './new.js'\nimport { createPut } from './put.js'\nimport { createStat } from './stat.js'\nimport { createPatch } from './patch/index.js'\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} config\n */\nexport function createObject (codecs, config) {\n return {\n data: createData(config),\n get: createGet(config),\n links: createLinks(config),\n new: createNew(config),\n put: createPut(codecs, config),\n stat: createStat(config),\n patch: createPatch(config)\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\nexport const createAddAll = configure(api => {\n /**\n * @type {PinAPI[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n for await (const { path, recursive, metadata } of normaliseInput(source)) {\n const res = await api.post('pin/add', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n arg: path,\n recursive,\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n stream: true\n }),\n headers: options.headers\n })\n\n for await (const pin of res.ndjson()) {\n if (pin.Pins) { // non-streaming response\n for (const cid of pin.Pins) {\n yield CID.parse(cid)\n }\n continue\n }\n\n yield CID.parse(pin)\n }\n }\n }\n return addAll\n})\n", "import { createAddAll } from './add-all.js'\nimport last from 'it-last'\nimport { configure } from '../lib/configure.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createAdd (config) {\n const all = createAddAll(config)\n\n return configure(() => {\n /**\n * @type {PinAPI[\"add\"]}\n */\n async function add (path, options = {}) {\n // @ts-expect-error last can return undefined\n return last(all([{\n path,\n ...options\n }], options))\n }\n return add\n })(config)\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\n/**\n * @param {string} type\n * @param {string} cid\n * @param {Record} metadata\n */\nfunction toPin (type, cid, metadata) {\n /** @type {import('ipfs-core-types/src/pin').LsResult} */\n const pin = {\n type,\n cid: CID.parse(cid)\n }\n\n if (metadata) {\n pin.metadata = metadata\n }\n\n return pin\n}\n\nexport const createLs = configure(api => {\n /**\n * @type {PinAPI[\"ls\"]}\n */\n async function * ls (options = {}) {\n /** @type {any[]} */\n let paths = []\n\n if (options.paths) {\n paths = Array.isArray(options.paths) ? options.paths : [options.paths]\n }\n\n const res = await api.post('pin/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n arg: paths.map(path => `${path}`),\n stream: true\n }),\n headers: options.headers\n })\n\n for await (const pin of res.ndjson()) {\n if (pin.Keys) { // non-streaming response\n for (const cid of Object.keys(pin.Keys)) {\n yield toPin(pin.Keys[cid].Type, cid, pin.Keys[cid].Metadata)\n }\n return\n }\n\n yield toPin(pin.Type, pin.Cid, pin.Metadata)\n }\n }\n return ls\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\nexport const createRmAll = configure(api => {\n /**\n * @type {PinAPI[\"rmAll\"]}\n */\n async function * rmAll (source, options = {}) {\n for await (const { path, recursive } of normaliseInput(source)) {\n const searchParams = new URLSearchParams(options.searchParams)\n searchParams.append('arg', `${path}`)\n\n if (recursive != null) searchParams.set('recursive', String(recursive))\n\n const res = await api.post('pin/rm', {\n signal: options.signal,\n headers: options.headers,\n searchParams: toUrlSearchParams({\n ...options,\n arg: `${path}`,\n recursive\n })\n })\n\n for await (const pin of res.ndjson()) {\n if (pin.Pins) { // non-streaming response\n yield * pin.Pins.map((/** @type {string} */ cid) => CID.parse(cid))\n continue\n }\n yield CID.parse(pin)\n }\n }\n }\n return rmAll\n})\n", "import { createRmAll } from './rm-all.js'\nimport last from 'it-last'\nimport { configure } from '../lib/configure.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\n/**\n * @param {import('../types').Options} config\n */\nexport const createRm = (config) => {\n const all = createRmAll(config)\n\n return configure(() => {\n /**\n * @type {PinAPI[\"rm\"]}\n */\n async function rm (path, options = {}) {\n // @ts-expect-error last can return undefined\n return last(all([{\n path,\n ...options\n }], options))\n }\n return rm\n })(config)\n}\n", "import { CID } from 'multiformats/cid'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').Pin} Pin\n * @typedef {import('ipfs-core-types/src/pin/remote').AddOptions} AddOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').Query} Query\n * @typedef {import('ipfs-core-types/src/pin/remote').Status} Status\n */\n\n/**\n * @param {object} json\n * @param {string} json.Name\n * @param {string} json.Cid\n * @param {Status} json.Status\n * @returns {Pin}\n */\nexport const decodePin = ({ Name: name, Status: status, Cid: cid }) => {\n return {\n cid: CID.parse(cid),\n name,\n status\n }\n}\n\n/**\n * @param {any} service\n * @returns {string}\n */\nexport const encodeService = (service) => {\n if (typeof service === 'string' && service !== '') {\n return service\n } else {\n throw new TypeError('service name must be passed')\n }\n}\n\n/**\n * @param {any} cid\n * @returns {string}\n */\nexport const encodeCID = (cid) => {\n if (CID.asCID(cid)) {\n return cid.toString()\n } else {\n throw new TypeError(`CID instance expected instead of ${typeof cid}`)\n }\n}\n\n/**\n * @param {Query & { all?: boolean }} query\n * @returns {URLSearchParams}\n */\nexport const encodeQuery = ({ service, cid, name, status, all }) => {\n const query = toUrlSearchParams({\n service: encodeService(service),\n name,\n force: all ? true : undefined\n })\n\n if (cid) {\n for (const value of cid) {\n query.append('cid', encodeCID(value))\n }\n }\n\n if (status) {\n for (const value of status) {\n query.append('status', value)\n }\n }\n\n return query\n}\n\n/**\n * @param {AddOptions & {cid:CID}} options\n * @returns {URLSearchParams}\n */\nexport const encodeAddParams = ({ cid, service, background, name, origins }) => {\n const params = toUrlSearchParams({\n arg: encodeCID(cid),\n service: encodeService(service),\n name,\n background: background ? true : undefined\n })\n\n if (origins) {\n for (const origin of origins) {\n params.append('origin', origin.toString())\n }\n }\n\n return params\n}\n", "import { encodeAddParams, decodePin } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createAdd (client) {\n /**\n * @type {RemotePiningAPI[\"add\"]}\n */\n async function add (cid, { timeout, signal, headers, ...query }) {\n const response = await client.post('pin/remote/add', {\n timeout,\n signal,\n headers,\n searchParams: encodeAddParams({ cid, ...query })\n })\n\n return decodePin(await response.json())\n }\n\n return add\n}\n", "import { encodeQuery, decodePin } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createLs (client) {\n /**\n * @type {RemotePiningAPI[\"ls\"]}\n */\n async function * ls ({ timeout, signal, headers, ...query }) {\n const response = await client.post('pin/remote/ls', {\n timeout,\n signal,\n headers,\n searchParams: encodeQuery(query)\n })\n\n for await (const pin of response.ndjson()) {\n yield decodePin(pin)\n }\n }\n\n return ls\n}\n", "import { encodeQuery } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createRm (client) {\n /**\n * @type {RemotePiningAPI[\"rm\"]}\n */\n async function rm ({ timeout, signal, headers, ...query }) {\n await client.post('pin/remote/rm', {\n timeout,\n signal,\n headers,\n searchParams: encodeQuery({\n ...query,\n all: false\n })\n })\n }\n\n return rm\n}\n", "import { encodeQuery } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createRmAll (client) {\n /**\n * @type {RemotePiningAPI[\"rmAll\"]}\n */\n async function rmAll ({ timeout, signal, headers, ...query }) {\n await client.post('pin/remote/rm', {\n timeout,\n signal,\n headers,\n searchParams: encodeQuery({\n ...query,\n all: true\n })\n })\n }\n\n return rmAll\n}\n", "/**\n * @typedef {import('ipfs-core-types/src/pin/remote/service').RemotePinServiceWithStat} RemotePinServiceWithStat\n */\n\n/**\n * @param {URL} url\n */\nexport function encodeEndpoint (url) {\n const href = String(url)\n if (href === 'undefined') {\n throw Error('endpoint is required')\n }\n // Workaround trailing `/` issue in go-ipfs\n // @see https://github.com/ipfs/go-ipfs/issues/7826\n return href[href.length - 1] === '/' ? href.slice(0, -1) : href\n}\n\n/**\n * @param {any} json\n * @returns {RemotePinServiceWithStat}\n */\nexport function decodeRemoteService (json) {\n return {\n service: json.Service,\n endpoint: new URL(json.ApiEndpoint),\n ...(json.Stat && { stat: decodeStat(json.Stat) })\n }\n}\n\n/**\n * @param {any} json\n * @returns {import('ipfs-core-types/src/pin/remote/service').Stat}\n */\nexport function decodeStat (json) {\n switch (json.Status) {\n case 'valid': {\n const { Pinning, Pinned, Queued, Failed } = json.PinCount\n return {\n status: 'valid',\n pinCount: {\n queued: Queued,\n pinning: Pinning,\n pinned: Pinned,\n failed: Failed\n }\n }\n }\n case 'invalid': {\n return { status: 'invalid' }\n }\n default: {\n return { status: json.Status }\n }\n }\n}\n", "import { toUrlSearchParams } from '../../../lib/to-url-search-params.js'\nimport { encodeEndpoint } from './utils.js'\n\n/**\n * @typedef {import('../../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote/service').API} RemotePiningServiceAPI\n */\n\n/**\n * @param {import('../../../lib/core').Client} client\n */\nexport function createAdd (client) {\n /**\n * @type {RemotePiningServiceAPI[\"add\"]}\n */\n async function add (name, options) {\n const { endpoint, key, headers, timeout, signal } = options\n\n await client.post('pin/remote/service/add', {\n timeout,\n signal,\n searchParams: toUrlSearchParams({\n arg: [name, encodeEndpoint(endpoint), key]\n }),\n headers\n })\n }\n\n return add\n}\n", "import { toUrlSearchParams } from '../../../lib/to-url-search-params.js'\nimport { decodeRemoteService } from './utils.js'\n\n/**\n * @typedef {import('../../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote/service').API} RemotePiningServiceAPI\n */\n\n/**\n * @param {import('../../../lib/core').Client} client\n */\nexport function createLs (client) {\n /**\n * @type {RemotePiningServiceAPI[\"ls\"]}\n */\n async function ls (options = {}) {\n // @ts-expect-error cannot derive option type from typedef\n const { stat, headers, timeout, signal } = options\n\n const response = await client.post('pin/remote/service/ls', {\n timeout,\n signal,\n headers,\n searchParams: stat === true ? toUrlSearchParams({ stat }) : undefined\n })\n\n /** @type {{RemoteServices: object[]}} */\n const { RemoteServices } = await response.json()\n\n return RemoteServices.map(decodeRemoteService)\n }\n\n return ls\n}\n", "import { toUrlSearchParams } from '../../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote/service').API} RemotePiningServiceAPI\n */\n\n/**\n * @param {import('../../../lib/core').Client} client\n */\nexport function createRm (client) {\n /**\n * @type {RemotePiningServiceAPI[\"rm\"]}\n */\n async function rm (name, options = {}) {\n await client.post('pin/remote/service/rm', {\n signal: options.signal,\n headers: options.headers,\n searchParams: toUrlSearchParams({\n arg: name\n })\n })\n }\n\n return rm\n}\n", "import { Client } from '../../../lib/core.js'\nimport { createAdd } from './add.js'\nimport { createLs } from './ls.js'\nimport { createRm } from './rm.js'\n\n/**\n * @param {import('../../../types').Options} config\n */\nexport function createService (config) {\n const client = new Client(config)\n\n return {\n add: createAdd(client),\n ls: createLs(client),\n rm: createRm(client)\n }\n}\n", "import { Client } from '../../lib/core.js'\nimport { createAdd } from './add.js'\nimport { createLs } from './ls.js'\nimport { createRm } from './rm.js'\nimport { createRmAll } from './rm-all.js'\nimport { createService } from './service/index.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createRemote (config) {\n const client = new Client(config)\n\n return {\n add: createAdd(client),\n ls: createLs(client),\n rm: createRm(client),\n rmAll: createRmAll(client),\n service: createService(config)\n }\n}\n", "import { createAddAll } from './add-all.js'\nimport { createAdd } from './add.js'\nimport { createLs } from './ls.js'\nimport { createRmAll } from './rm-all.js'\nimport { createRm } from './rm.js'\nimport { createRemote } from './remote/index.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createPin (config) {\n return {\n addAll: createAddAll(config),\n add: createAdd(config),\n ls: createLs(config),\n rmAll: createRmAll(config),\n rm: createRm(config),\n remote: createRemote(config)\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { base64url } from 'multiformats/bases/base64'\n\n/* HTTP RPC:\n * - wraps binary data in multibase. base64url is used to avoid issues\n * when a binary data is passed as search param in URL.\n * Historical context: https://github.com/ipfs/go-ipfs/issues/7939\n * Multibase wrapping introduced in: https://github.com/ipfs/go-ipfs/pull/8183\n */\n\n/**\n * @param {Array} strings\n * @returns {Array} strings\n */\nconst rpcArrayToTextArray = strings => {\n if (Array.isArray(strings)) {\n return strings.map(rpcToText)\n }\n return strings\n}\n\n/**\n * @param {string} mb\n * @returns {string}\n */\nconst rpcToText = mb => uint8ArrayToString(rpcToBytes(mb))\n\n/**\n * @param {string} mb\n * @returns {Uint8Array}\n */\nconst rpcToBytes = mb => base64url.decode(mb)\n\n/**\n * @param {string} mb\n * @returns {bigint}\n */\nconst rpcToBigInt = mb => BigInt(`0x${uint8ArrayToString(base64url.decode(mb), 'base16')}`)\n\n/**\n * @param {string} text\n * @returns {string}\n */\nconst textToUrlSafeRpc = text => base64url.encode(uint8ArrayFromString(text))\n\nexport { rpcArrayToTextArray, rpcToText, rpcToBytes, rpcToBigInt, textToUrlSafeRpc }\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { rpcArrayToTextArray } from '../lib/http-rpc-wire-format.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n */\n\nexport const createLs = configure(api => {\n /**\n * @type {PubsubAPI[\"ls\"]}\n */\n async function ls (options = {}) {\n const { Strings } = await (await api.post('pubsub/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })).json()\n\n return rpcArrayToTextArray(Strings) || []\n }\n return ls\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { textToUrlSafeRpc } from '../lib/http-rpc-wire-format.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n */\n\nexport const createPeers = configure(api => {\n /**\n * @type {PubsubAPI[\"peers\"]}\n */\n async function peers (topic, options = {}) {\n const res = await api.post('pubsub/peers', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: textToUrlSafeRpc(topic),\n ...options\n }),\n headers: options.headers\n })\n\n const { Strings } = await res.json()\n\n return Strings || []\n }\n return peers\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { abortSignal } from '../lib/abort-signal.js'\nimport { textToUrlSafeRpc } from '../lib/http-rpc-wire-format.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n */\n\nexport const createPublish = configure(api => {\n /**\n * @type {PubsubAPI[\"publish\"]}\n */\n async function publish (topic, data, options = {}) {\n const searchParams = toUrlSearchParams({\n arg: textToUrlSafeRpc(topic),\n ...options\n })\n\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('pubsub/pub', {\n signal,\n searchParams,\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n\n await res.text()\n }\n return publish\n})\n", "import { logger } from '@libp2p/logger'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { textToUrlSafeRpc, rpcToText, rpcToBytes, rpcToBigInt } from '../lib/http-rpc-wire-format.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\nconst log = logger('ipfs-http-client:pubsub:subscribe')\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('@libp2p/interface-pubsub').Message} Message\n * @typedef {(err: Error, fatal: boolean, msg?: Message) => void} ErrorHandlerFn\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n * @typedef {import('../types').Options} Options\n */\n\n/**\n * @param {Options} options\n * @param {import('./subscription-tracker').SubscriptionTracker} subsTracker\n */\nexport const createSubscribe = (options, subsTracker) => {\n return configure((api) => {\n /**\n * @type {PubsubAPI[\"subscribe\"]}\n */\n async function subscribe (topic, handler, options = {}) { // eslint-disable-line require-await\n options.signal = subsTracker.subscribe(topic, handler, options.signal)\n\n /** @type {(value?: any) => void} */\n let done\n /** @type {(error: Error) => void} */\n let fail\n\n const result = new Promise((resolve, reject) => {\n done = resolve\n fail = reject\n })\n\n // In Firefox, the initial call to fetch does not resolve until some data\n // is received. If this doesn't happen within 1 second assume success\n const ffWorkaround = setTimeout(() => done(), 1000)\n\n // Do this async to not block Firefox\n api.post('pubsub/sub', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: textToUrlSafeRpc(topic),\n ...options\n }),\n headers: options.headers\n })\n .catch((err) => {\n // Initial subscribe fail, ensure we clean up\n subsTracker.unsubscribe(topic, handler)\n\n fail(err)\n })\n .then((response) => {\n clearTimeout(ffWorkaround)\n\n if (!response) {\n // if there was no response, the subscribe failed\n return\n }\n\n readMessages(response, {\n onMessage: (message) => {\n if (!handler) {\n return\n }\n\n if (typeof handler === 'function') {\n handler(message)\n return\n }\n\n if (typeof handler.handleEvent === 'function') {\n handler.handleEvent(message)\n }\n },\n onEnd: () => subsTracker.unsubscribe(topic, handler),\n onError: options.onError\n })\n\n done()\n })\n\n return result\n }\n return subscribe\n })(options)\n}\n\n/**\n * @param {import('ipfs-utils/src/types').ExtendedResponse} response\n * @param {object} options\n * @param {(message: Message) => void} options.onMessage\n * @param {() => void} options.onEnd\n * @param {ErrorHandlerFn} [options.onError]\n */\nasync function readMessages (response, { onMessage, onEnd, onError }) {\n onError = onError || log\n\n try {\n for await (const msg of response.ndjson()) {\n try {\n if (!msg.from) {\n continue\n }\n\n if (msg.from != null && msg.seqno != null) {\n onMessage({\n type: 'signed',\n from: peerIdFromString(msg.from),\n data: rpcToBytes(msg.data),\n sequenceNumber: rpcToBigInt(msg.seqno),\n topic: rpcToText(msg.topicIDs[0]),\n key: rpcToBytes(msg.key ?? 'u'),\n signature: rpcToBytes(msg.signature ?? 'u')\n })\n } else {\n onMessage({\n type: 'unsigned',\n data: rpcToBytes(msg.data),\n topic: rpcToText(msg.topicIDs[0])\n })\n }\n } catch (/** @type {any} */ err) {\n err.message = `Failed to parse pubsub message: ${err.message}`\n onError(err, false, msg) // Not fatal\n }\n }\n } catch (/** @type {any} */ err) {\n if (!isAbortError(err)) {\n onError(err, true) // Fatal\n }\n } finally {\n onEnd()\n }\n}\n\n/**\n * @param {Error & {type?:string}} error\n * @returns {boolean}\n */\nconst isAbortError = error => {\n switch (error.type) {\n case 'aborted':\n return true\n // It is `abort` in Electron instead of `aborted`\n case 'abort':\n return true\n default:\n // FIXME: In testing with Chrome, err.type is undefined (should not be!)\n // Temporarily use the name property instead.\n return error.name === 'AbortError'\n }\n}\n", "\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n * @typedef {import('../types').Options} Options\n */\n\n/**\n * @param {Options} options\n * @param {import('./subscription-tracker').SubscriptionTracker} subsTracker\n */\nexport const createUnsubscribe = (options, subsTracker) => {\n /**\n * @type {PubsubAPI[\"unsubscribe\"]}\n */\n async function unsubscribe (topic, handler) {\n subsTracker.unsubscribe(topic, handler)\n }\n return unsubscribe\n}\n", "\n/**\n * @typedef {import('@libp2p/interface-pubsub').Message} Message\n * @typedef {import('@libp2p/interfaces/events').EventHandler} MessageHandlerFn\n *\n * @typedef {object} Subscription\n * @property {MessageHandlerFn} handler\n * @property {AbortController} controller\n */\n\nexport class SubscriptionTracker {\n constructor () {\n /** @type {Map} */\n this._subs = new Map()\n }\n\n /**\n * @param {string} topic\n * @param {MessageHandlerFn} handler\n * @param {AbortSignal} [signal]\n */\n subscribe (topic, handler, signal) {\n const topicSubs = this._subs.get(topic) || []\n\n if (topicSubs.find(s => s.handler === handler)) {\n throw new Error(`Already subscribed to ${topic} with this handler`)\n }\n\n // Create controller so a call to unsubscribe can cancel the request\n const controller = new AbortController()\n\n this._subs.set(topic, [{ handler, controller }].concat(topicSubs))\n\n // If there is an external signal, forward the abort event\n if (signal) {\n signal.addEventListener('abort', () => this.unsubscribe(topic, handler))\n }\n\n return controller.signal\n }\n\n /**\n * @param {string} topic\n * @param {MessageHandlerFn} [handler]\n */\n unsubscribe (topic, handler) {\n const subs = this._subs.get(topic) || []\n let unsubs\n\n if (handler) {\n this._subs.set(topic, subs.filter(s => s.handler !== handler))\n unsubs = subs.filter(s => s.handler === handler)\n } else {\n this._subs.set(topic, [])\n unsubs = subs\n }\n\n if (!(this._subs.get(topic) || []).length) {\n this._subs.delete(topic)\n }\n\n unsubs.forEach(s => s.controller.abort())\n }\n}\n", "import { createLs } from './ls.js'\nimport { createPeers } from './peers.js'\nimport { createPublish } from './publish.js'\nimport { createSubscribe } from './subscribe.js'\nimport { createUnsubscribe } from './unsubscribe.js'\nimport { SubscriptionTracker } from './subscription-tracker.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createPubsub (config) {\n const subscriptionTracker = new SubscriptionTracker()\n\n return {\n ls: createLs(config),\n peers: createPeers(config),\n publish: createPublish(config),\n subscribe: createSubscribe(config, subscriptionTracker),\n unsubscribe: createUnsubscribe(config, subscriptionTracker)\n }\n}\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/refs').API} RefsAPI\n */\n\nexport const createLocal = configure(api => {\n /**\n * @type {RefsAPI[\"local\"]}\n */\n async function * refsLocal (options = {}) {\n const res = await api.post('refs/local', {\n signal: options.signal,\n transform: objectToCamel,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n yield * res.ndjson()\n }\n return refsLocal\n})\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { createLocal } from './local.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/refs').API} RefsAPI\n */\n\nexport const createRefs = configure((api, opts) => {\n /**\n * @type {RefsAPI[\"refs\"]}\n */\n const refs = async function * (args, options = {}) {\n /** @type {import('ipfs-core-types/src/utils').IPFSPath[]} */\n const argsArr = Array.isArray(args) ? args : [args]\n\n const res = await api.post('refs', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: argsArr.map(arg => `${arg instanceof Uint8Array ? CID.decode(arg) : arg}`),\n ...options\n }),\n headers: options.headers,\n transform: objectToCamel\n })\n\n yield * res.ndjson()\n }\n\n return Object.assign(refs, {\n local: createLocal(opts)\n })\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/repo').API} RepoAPI\n */\n\nexport const createGc = configure(api => {\n /**\n * @type {RepoAPI[\"gc\"]}\n */\n async function * gc (options = {}) {\n const res = await api.post('repo/gc', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers,\n transform: (res) => {\n return {\n err: res.Error ? new Error(res.Error) : null,\n cid: (res.Key || {})['/'] ? CID.parse(res.Key['/']) : null\n }\n }\n })\n\n yield * res.ndjson()\n }\n return gc\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/repo').API} RepoAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {RepoAPI[\"stat\"]}\n */\n async function stat (options = {}) {\n const res = await api.post('repo/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n const data = await res.json()\n\n return {\n numObjects: BigInt(data.NumObjects),\n repoSize: BigInt(data.RepoSize),\n repoPath: data.RepoPath,\n version: data.Version,\n storageMax: BigInt(data.StorageMax)\n }\n }\n return stat\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/repo').API} RepoAPI\n */\n\nexport const createVersion = configure(api => {\n /**\n * @type {RepoAPI[\"version\"]}\n */\n async function version (options = {}) {\n const res = await (await api.post('repo/version', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })).json()\n\n return res.Version\n }\n return version\n})\n", "import { createGc } from './gc.js'\nimport { createStat } from './stat.js'\nimport { createVersion } from './version.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createRepo (config) {\n return {\n gc: createGc(config),\n stat: createStat(config),\n version: createVersion(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/stats').API} StatsAPI\n */\n\nexport const createBw = configure(api => {\n /**\n * @type {StatsAPI[\"bw\"]}\n */\n async function * bw (options = {}) {\n const res = await api.post('stats/bw', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers,\n transform: (stats) => ({\n totalIn: BigInt(stats.TotalIn),\n totalOut: BigInt(stats.TotalOut),\n rateIn: parseFloat(stats.RateIn),\n rateOut: parseFloat(stats.RateOut)\n })\n })\n\n yield * res.ndjson()\n }\n return bw\n})\n", "import { createStat as createBitswap } from '../bitswap/stat.js'\nimport { createStat as createRepo } from '../repo/stat.js'\nimport { createBw } from './bw.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createStats (config) {\n return {\n bitswap: createBitswap(config),\n repo: createRepo(config),\n bw: createBw(config)\n }\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createAddrs = configure(api => {\n /**\n * @type {SwarmAPI[\"addrs\"]}\n */\n async function addrs (options = {}) {\n const res = await api.post('swarm/addrs', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n /** @type {{ Addrs: Record }} */\n const { Addrs } = await res.json()\n\n return Object.keys(Addrs).map(id => ({\n id: peerIdFromString(id),\n addrs: (Addrs[id] || []).map(a => multiaddr(a))\n }))\n }\n return addrs\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createConnect = configure(api => {\n /**\n * @type {SwarmAPI[\"connect\"]}\n */\n async function connect (addr, options = {}) {\n const res = await api.post('swarm/connect', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n const { Strings } = await res.json()\n\n return Strings || []\n }\n return connect\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createDisconnect = configure(api => {\n /**\n * @type {SwarmAPI[\"disconnect\"]}\n */\n async function disconnect (addr, options = {}) {\n const res = await api.post('swarm/disconnect', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n const { Strings } = await res.json()\n\n return Strings || []\n }\n return disconnect\n})\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createLocalAddrs = configure(api => {\n /**\n * @type {SwarmAPI[\"localAddrs\"]}\n */\n async function localAddrs (options = {}) {\n const res = await api.post('swarm/addrs/local', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n /** @type {{ Strings: string[] }} */\n const { Strings } = await res.json()\n\n return (Strings || []).map(a => multiaddr(a))\n }\n return localAddrs\n})\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createPeers = configure(api => {\n /**\n * @type {SwarmAPI[\"peers\"]}\n */\n async function peers (options = {}) {\n const res = await api.post('swarm/peers', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n /** @type {{ Peers: { Peer: string, Addr: string, Muxer?: string, Latency?: string, Streams?: string[], Direction?: 0 | 1 }[] }} */\n const { Peers } = await res.json()\n\n return (Peers || []).map(peer => {\n return {\n addr: multiaddr(peer.Addr),\n peer: peerIdFromString(peer.Peer),\n muxer: peer.Muxer,\n latency: peer.Latency,\n streams: peer.Streams,\n direction: peer.Direction == null ? undefined : peer.Direction === 0 ? 'inbound' : 'outbound'\n }\n })\n }\n return peers\n})\n", "import { createAddrs } from './addrs.js'\nimport { createConnect } from './connect.js'\nimport { createDisconnect } from './disconnect.js'\nimport { createLocalAddrs } from './local-addrs.js'\nimport { createPeers } from './peers.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createSwarm (config) {\n return {\n addrs: createAddrs(config),\n connect: createConnect(config),\n disconnect: createDisconnect(config),\n localAddrs: createLocalAddrs(config),\n peers: createPeers(config)\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\nimport { abortSignal } from './lib/abort-signal.js'\n\n/**\n * @typedef {import('ipfs-utils/src/types').ProgressFn} IPFSUtilsHttpUploadProgressFn\n * @typedef {import('ipfs-core-types/src/root').AddProgressFn} IPFSCoreAddProgressFn\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n * @typedef {import('ipfs-core-types/src/root').AddResult} AddResult\n */\n\nexport const createAddAll = configure((api) => {\n /**\n * @type {RootAPI[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n const { headers, body, total, parts } =\n await multipartRequest(source, controller, options.headers)\n\n // In browser response body only starts streaming once upload is\n // complete, at which point all the progress updates are invalid. If\n // length of the content is computable we can interpret progress from\n // `{ total, loaded}` passed to `onUploadProgress` and `multipart.total`\n // in which case we disable progress updates to be written out.\n const [progressFn, onUploadProgress] = typeof options.progress === 'function'\n ? createProgressHandler(total, parts, options.progress)\n : [undefined, undefined]\n\n const res = await api.post('add', {\n searchParams: toUrlSearchParams({\n 'stream-channels': true,\n ...options,\n progress: Boolean(progressFn)\n }),\n onUploadProgress,\n signal,\n headers,\n body\n })\n\n for await (let file of res.ndjson()) {\n file = objectToCamel(file)\n\n if (file.hash !== undefined) {\n yield toCoreInterface(file)\n } else if (progressFn) {\n progressFn(file.bytes || 0, file.name)\n }\n }\n }\n return addAll\n})\n\n/**\n * Returns simple progress callback when content length isn't computable or a\n * progress event handler that calculates progress from upload progress events.\n *\n * @param {number} total\n * @param {{name:string, start:number, end:number}[]|null} parts\n * @param {IPFSCoreAddProgressFn} progress\n * @returns {[IPFSCoreAddProgressFn|undefined, IPFSUtilsHttpUploadProgressFn|undefined]}\n */\nconst createProgressHandler = (total, parts, progress) =>\n parts ? [undefined, createOnUploadProgress(total, parts, progress)] : [progress, undefined]\n\n/**\n * Creates a progress handler that interpolates progress from upload progress\n * events and total size of the content that is added.\n *\n * @param {number} size - actual content size\n * @param {{name:string, start:number, end:number}[]} parts\n * @param {IPFSCoreAddProgressFn} progress\n * @returns {IPFSUtilsHttpUploadProgressFn}\n */\nconst createOnUploadProgress = (size, parts, progress) => {\n let index = 0\n const count = parts.length\n return ({ loaded, total }) => {\n // Derive position from the current progress.\n const position = Math.floor(loaded / total * size)\n while (index < count) {\n const { start, end, name } = parts[index]\n // If within current part range report progress and break the loop\n if (position < end) {\n progress(position - start, name)\n break\n // If passed current part range report final byte for the chunk and\n // move to next one.\n } else {\n progress(end - start, name)\n index += 1\n }\n }\n }\n}\n\n/**\n * @param {object} input\n * @param {string} input.name\n * @param {string} input.hash\n * @param {string} input.size\n * @param {string} [input.mode]\n * @param {number} [input.mtime]\n * @param {number} [input.mtimeNsecs]\n */\nfunction toCoreInterface ({ name, hash, size, mode, mtime, mtimeNsecs }) {\n /** @type {AddResult} */\n const output = {\n path: name,\n cid: CID.parse(hash),\n size: parseInt(size)\n }\n\n if (mode != null) {\n output.mode = parseInt(mode, 8)\n }\n\n if (mtime != null) {\n output.mtime = {\n secs: mtime,\n nsecs: mtimeNsecs || 0\n }\n }\n\n return output\n}\n", "import { createAddAll } from './add-all.js'\nimport last from 'it-last'\nimport { configure } from './lib/configure.js'\nimport { normaliseInput } from 'ipfs-core-utils/files/normalise-input-single'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\n/**\n * @param {import('./types').Options} options\n */\nexport function createAdd (options) {\n const all = createAddAll(options)\n return configure(() => {\n /**\n * @type {RootAPI[\"add\"]}\n */\n async function add (input, options = {}) {\n // @ts-expect-error - last may return undefined if source is empty\n return await last(all(normaliseInput(input), options))\n }\n return add\n })(options)\n}\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createCat = configure(api => {\n /**\n * @type {RootAPI[\"cat\"]}\n */\n async function * cat (path, options = {}) {\n const res = await api.post('cat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n yield * res.iterator()\n }\n\n return cat\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createCommands = configure(api => {\n /**\n * @type {RootAPI[\"commands\"]}\n */\n const commands = async (options = {}) => {\n const res = await api.post('commands', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return res.json()\n }\n return commands\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createDns = configure(api => {\n /**\n * @type {RootAPI[\"dns\"]}\n */\n const dns = async (domain, options = {}) => {\n const res = await api.post('dns', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: domain,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return data.Path\n }\n\n return dns\n})\n", "import { configure } from './lib/configure.js'\n\nexport const createGetEndpointConfig = configure(api => {\n return () => {\n const url = new URL(api.opts.base || '')\n return {\n host: url.hostname,\n port: url.port,\n protocol: url.protocol,\n pathname: url.pathname,\n 'api-path': url.pathname\n }\n }\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {RootAPI[\"get\"]}\n */\n async function * get (path, options = {}) {\n /** @type {Record} */\n const opts = {\n arg: `${path instanceof Uint8Array ? CID.decode(path) : path}`,\n ...options\n }\n\n if (opts.compressionLevel) {\n opts['compression-level'] = opts.compressionLevel\n delete opts.compressionLevel\n }\n\n const res = await api.post('get', {\n signal: options.signal,\n searchParams: toUrlSearchParams(opts),\n headers: options.headers\n })\n\n yield * res.iterator()\n }\n\n return get\n})\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createId = configure(api => {\n /**\n * @type {RootAPI[\"id\"]}\n */\n async function id (options = {}) {\n const res = await api.post('id', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: options.peerId ? options.peerId.toString() : undefined,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n const output = {\n ...objectToCamel(data)\n }\n\n output.id = peerIdFromString(output.id)\n\n if (output.addresses) {\n output.addresses = output.addresses.map((/** @type {string} */ ma) => multiaddr(ma))\n }\n\n // @ts-expect-error server output is not typed\n return output\n }\n return id\n})\n", "import { createId } from './id.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\n/**\n * @param {import('./types').Options} options\n */\nexport const createIsOnline = options => {\n const id = createId(options)\n\n /**\n * @type {RootAPI[\"isOnline\"]}\n */\n async function isOnline (options = {}) {\n const res = await id(options)\n\n return Boolean(res && res.addresses && res.addresses.length)\n }\n return isOnline\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\nimport { createStat } from './files/stat.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createLs = configure((api, opts) => {\n /**\n * @type {RootAPI[\"ls\"]}\n */\n async function * ls (path, options = {}) {\n const pathStr = `${path instanceof Uint8Array ? CID.decode(path) : path}`\n\n /**\n * @param {*} link\n */\n async function mapLink (link) {\n let hash = link.Hash\n\n if (hash.includes('/')) {\n // the hash is a path, but we need the CID\n const ipfsPath = hash.startsWith('/ipfs/') ? hash : `/ipfs/${hash}`\n const stats = await createStat(opts)(ipfsPath)\n\n hash = stats.cid\n } else {\n hash = CID.parse(hash)\n }\n\n /** @type {import('ipfs-core-types/src/root').IPFSEntry} */\n const entry = {\n name: link.Name,\n path: pathStr + (link.Name ? `/${link.Name}` : ''),\n size: link.Size,\n cid: hash,\n type: typeOf(link)\n }\n\n if (link.Mode) {\n entry.mode = parseInt(link.Mode, 8)\n }\n\n if (link.Mtime !== undefined && link.Mtime !== null) {\n entry.mtime = {\n secs: link.Mtime\n }\n\n if (link.MtimeNsecs !== undefined && link.MtimeNsecs !== null) {\n entry.mtime.nsecs = link.MtimeNsecs\n }\n }\n\n return entry\n }\n\n const res = await api.post('ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: pathStr,\n ...options\n }),\n headers: options.headers\n })\n\n for await (let result of res.ndjson()) {\n result = result.Objects\n\n if (!result) {\n throw new Error('expected .Objects in results')\n }\n\n result = result[0]\n if (!result) {\n throw new Error('expected one array in results.Objects')\n }\n\n const links = result.Links\n if (!Array.isArray(links)) {\n throw new Error('expected one array in results.Objects[0].Links')\n }\n\n if (!links.length) {\n // no links, this is a file, yield a single result\n yield mapLink(result)\n\n return\n }\n\n yield * links.map(mapLink)\n }\n }\n return ls\n})\n\n/**\n * @param {any} link\n */\nfunction typeOf (link) {\n switch (link.Type) {\n case 1:\n case 5:\n return 'dir'\n case 2:\n return 'file'\n default:\n return 'file'\n }\n}\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createMount = configure(api => {\n /**\n * @type {RootAPI[\"mount\"]}\n */\n async function mount (options = {}) {\n const res = await api.post('dns', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return objectToCamel(await res.json())\n }\n return mount\n})\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createPing = configure(api => {\n /**\n * @type {RootAPI[\"ping\"]}\n */\n async function * ping (peerId, options = {}) {\n const res = await api.post('ping', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${peerId}`,\n ...options\n }),\n headers: options.headers,\n transform: objectToCamel\n })\n\n yield * res.ndjson()\n }\n return ping\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createResolve = configure(api => {\n /**\n * @type {RootAPI[\"resolve\"]}\n */\n async function resolve (path, options = {}) {\n const res = await api.post('resolve', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n const { Path } = await res.json()\n return Path\n }\n return resolve\n})\n", "import { configure } from './lib/configure.js'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createStart = configure(api => {\n /**\n * @type {RootAPI[\"start\"]}\n */\n const start = async (options = {}) => {\n throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED')\n }\n\n return start\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createStop = configure(api => {\n /**\n * @type {RootAPI[\"stop\"]}\n */\n async function stop (options = {}) {\n const res = await api.post('shutdown', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n await res.text()\n }\n return stop\n})\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createVersion = configure(api => {\n /**\n * @type {RootAPI[\"version\"]}\n */\n async function version (options = {}) {\n const res = await api.post('version', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return {\n ...objectToCamel(await res.json()),\n 'ipfs-http-client': '1.0.0'\n }\n }\n\n return version\n})\n", "/* eslint-env browser */\n\nimport { Multibases } from 'ipfs-core-utils/multibases'\nimport { Multicodecs } from 'ipfs-core-utils/multicodecs'\nimport { Multihashes } from 'ipfs-core-utils/multihashes'\nimport * as dagPB from '@ipld/dag-pb'\nimport * as dagCBOR from '@ipld/dag-cbor'\nimport * as dagJSON from '@ipld/dag-json'\nimport * as dagJOSE from 'dag-jose'\nimport { identity } from 'multiformats/hashes/identity'\nimport { bases, hashes, codecs } from 'multiformats/basics'\nimport { createBitswap } from './bitswap/index.js'\nimport { createBlock } from './block/index.js'\nimport { createBootstrap } from './bootstrap/index.js'\nimport { createConfig } from './config/index.js'\nimport { createDag } from './dag/index.js'\nimport { createDht } from './dht/index.js'\nimport { createDiag } from './diag/index.js'\nimport { createFiles } from './files/index.js'\nimport { createKey } from './key/index.js'\nimport { createLog } from './log/index.js'\nimport { createName } from './name/index.js'\nimport { createObject } from './object/index.js'\nimport { createPin } from './pin/index.js'\nimport { createPubsub } from './pubsub/index.js'\nimport { createRefs } from './refs/index.js'\nimport { createRepo } from './repo/index.js'\nimport { createStats } from './stats/index.js'\nimport { createSwarm } from './swarm/index.js'\nimport { createAdd } from './add.js'\nimport { createAddAll } from './add-all.js'\nimport { createCat } from './cat.js'\nimport { createCommands } from './commands.js'\nimport { createDns } from './dns.js'\nimport { createGetEndpointConfig } from './get-endpoint-config.js'\nimport { createGet } from './get.js'\nimport { createId } from './id.js'\nimport { createIsOnline } from './is-online.js'\nimport { createLs } from './ls.js'\nimport { createMount } from './mount.js'\nimport { createPing } from './ping.js'\nimport { createResolve } from './resolve.js'\nimport { createStart } from './start.js'\nimport { createStop } from './stop.js'\nimport { createVersion } from './version.js'\nimport globSourceImport from 'ipfs-utils/src/files/glob-source.js'\n\n/**\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('multiformats/bases/interface').MultibaseCodec} MultibaseCodec\n * @typedef {import('./types').Options} Options\n * @typedef {import('./types').LoadBaseFn} LoadBaseFn\n * @typedef {import('./types').LoadCodecFn} LoadCodecFn\n * @typedef {import('./types').LoadHasherFn} LoadHasherFn\n * @typedef {import('./types').IPLDOptions} IPLDOptions\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('./types').EndpointConfig} EndpointConfig\n * @typedef {import('./types').IPFSHTTPClient} IPFSHTTPClient\n */\n\n/**\n * @param {Options} options\n */\nexport function create (options = {}) {\n /**\n * @type {BlockCodec}\n */\n const id = {\n name: identity.name,\n code: identity.code,\n encode: (id) => id,\n decode: (id) => id\n }\n\n /** @type {MultibaseCodec[]} */\n const multibaseCodecs = Object.values(bases);\n\n (options.ipld && options.ipld.bases ? options.ipld.bases : []).forEach(base => multibaseCodecs.push(base))\n\n const multibases = new Multibases({\n bases: multibaseCodecs,\n loadBase: options.ipld && options.ipld.loadBase\n })\n\n /** @type {BlockCodec[]} */\n const blockCodecs = Object.values(codecs);\n\n [dagPB, dagCBOR, dagJSON, dagJOSE, id].concat((options.ipld && options.ipld.codecs) || []).forEach(codec => blockCodecs.push(codec))\n\n const multicodecs = new Multicodecs({\n codecs: blockCodecs,\n loadCodec: options.ipld && options.ipld.loadCodec\n })\n\n /** @type {MultihashHasher[]} */\n const multihashHashers = Object.values(hashes);\n\n (options.ipld && options.ipld.hashers ? options.ipld.hashers : []).forEach(hasher => multihashHashers.push(hasher))\n\n const multihashes = new Multihashes({\n hashers: multihashHashers,\n loadHasher: options.ipld && options.ipld.loadHasher\n })\n\n /** @type {IPFSHTTPClient} */\n const client = {\n add: createAdd(options),\n addAll: createAddAll(options),\n bitswap: createBitswap(options),\n block: createBlock(options),\n bootstrap: createBootstrap(options),\n cat: createCat(options),\n commands: createCommands(options),\n config: createConfig(options),\n dag: createDag(multicodecs, options),\n dht: createDht(options),\n diag: createDiag(options),\n dns: createDns(options),\n files: createFiles(options),\n get: createGet(options),\n getEndpointConfig: createGetEndpointConfig(options),\n id: createId(options),\n isOnline: createIsOnline(options),\n key: createKey(options),\n log: createLog(options),\n ls: createLs(options),\n mount: createMount(options),\n name: createName(options),\n object: createObject(multicodecs, options),\n pin: createPin(options),\n ping: createPing(options),\n pubsub: createPubsub(options),\n refs: createRefs(options),\n repo: createRepo(options),\n resolve: createResolve(options),\n start: createStart(options),\n stats: createStats(options),\n stop: createStop(options),\n swarm: createSwarm(options),\n version: createVersion(options),\n bases: multibases,\n codecs: multicodecs,\n hashers: multihashes\n }\n\n return client\n}\n\nexport { CID } from 'multiformats/cid'\nexport { multiaddr } from '@multiformats/multiaddr'\nexport { default as urlSource } from 'ipfs-utils/src/files/url-source.js'\nexport const globSource = globSourceImport\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { AbortError } from 'abortable-iterator'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport * as mafmt from '@multiformats/mafmt'\nimport { CODE_CIRCUIT } from './constants.js'\nimport { createListener } from './listener.js'\nimport { toMultiaddrConnection } from './socket-to-conn.js'\nimport { cleanMultiaddr, cleanUrlSIO } from './utils.js'\nimport { WebRTCInitiator } from '@libp2p/webrtc-peer'\nimport randomBytes from 'iso-random-stream/src/random.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { symbol } from '@libp2p/interface-transport'\nimport type { WRTC, WebRTCInitiatorInit, WebRTCReceiver, WebRTCReceiverInit } from '@libp2p/webrtc-peer'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Transport, Listener, DialOptions, CreateListenerOptions } from '@libp2p/interface-transport'\nimport type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport type { WebRTCStarSocket, HandshakeSignal } from '@libp2p/webrtc-star-protocol'\nimport { symbol as peerDiscoverySymbol } from '@libp2p/interface-peer-discovery'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst webrtcSupport = 'RTCPeerConnection' in globalThis\nconst log = logger('libp2p:webrtc-star')\n\nconst noop = () => {}\n\nexport class WebRTCStarDiscovery extends EventEmitter implements PeerDiscovery, Startable {\n private started = false\n\n get [peerDiscoverySymbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/webrtc-star-discovery'\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n dispatchEvent (event: CustomEvent) {\n if (!this.isStarted()) {\n return false\n }\n\n return super.dispatchEvent(event)\n }\n}\n\nexport interface WebRTCStarInit {\n wrtc?: WRTC\n}\n\nexport interface WebRTCStarDialOptions extends DialOptions {\n channelOptions?: WebRTCInitiatorInit\n}\n\nexport interface WebRTCStarListenerOptions extends CreateListenerOptions, WebRTCInitiatorInit {\n channelOptions?: WebRTCReceiverInit\n}\n\nexport interface SignalServerServerEvents {\n 'error': CustomEvent\n 'listening': CustomEvent\n 'peer': CustomEvent\n 'connection': CustomEvent\n 'disconnect': CustomEvent\n 'reconnect': CustomEvent\n}\n\nexport interface SignalServer extends EventEmitter {\n signallingAddr: Multiaddr\n socket: WebRTCStarSocket\n connections: MultiaddrConnection[]\n channels: Map\n pendingSignals: Map\n close: () => Promise\n}\n\nexport interface WebRTCStarComponents {\n peerId: PeerId\n}\n\n/**\n * @class WebRTCStar\n */\nexport class WebRTCStar implements Transport {\n public wrtc?: WRTC\n public discovery: () => PeerDiscovery & Startable\n public sigServers: Map\n private readonly _discovery: WebRTCStarDiscovery\n public peerId?: PeerId\n\n constructor (init?: WebRTCStarInit) {\n if (init?.wrtc != null) {\n this.wrtc = init.wrtc\n }\n\n // Keep Signalling references\n this.sigServers = new Map()\n\n // Discovery\n this._discovery = new WebRTCStarDiscovery()\n this.discovery = () => this._discovery\n this.peerDiscovered = this.peerDiscovered.bind(this)\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/webrtc-star'\n }\n\n async dial (ma: Multiaddr, options: WebRTCStarDialOptions) {\n const rawConn = await this._connect(ma, options)\n const maConn = toMultiaddrConnection(rawConn, { remoteAddr: ma, signal: options.signal })\n log('new outbound connection %s', maConn.remoteAddr)\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: WebRTCStarDialOptions) {\n if (options.signal?.aborted === true) {\n throw new AbortError()\n }\n\n const channelOptions = {\n ...(options.channelOptions ?? {})\n }\n\n // Use custom WebRTC implementation\n if (this.wrtc != null) {\n channelOptions.wrtc = this.wrtc\n }\n\n const cOpts = ma.toOptions()\n const intentId = uint8ArrayToString(randomBytes(36), 'hex')\n\n return await new Promise((resolve, reject) => {\n const sio = this.sigServers.get(cleanUrlSIO(ma))\n\n if (sio?.socket == null) {\n return reject(errcode(new Error('unknown signal server to use'), 'ERR_UNKNOWN_SIGNAL_SERVER'))\n }\n\n let connected: boolean = false\n\n log('dialing %s:%s', cOpts.host, cOpts.port)\n const channel = new WebRTCInitiator(channelOptions)\n\n const onError = (evt: CustomEvent) => {\n const err = evt.detail\n\n if (!connected) {\n const msg = `connection error ${cOpts.host}:${cOpts.port}: ${err.message}`\n log.error(msg)\n done(err)\n }\n }\n\n const onReady = () => {\n connected = true\n\n log('connection opened %s:%s', cOpts.host, cOpts.port)\n done()\n }\n\n const onAbort = () => {\n log.error('connection aborted %s:%s', cOpts.host, cOpts.port)\n channel.close().finally(() => {\n done(new AbortError())\n })\n }\n\n const done = (err?: Error) => {\n channel.removeEventListener('ready', onReady)\n options.signal?.removeEventListener('abort', onAbort)\n\n if (err == null) {\n resolve(channel)\n } else {\n reject(err)\n }\n }\n\n channel.addEventListener('ready', onReady, {\n once: true\n })\n channel.addEventListener('close', () => {\n channel.removeEventListener('error', onError)\n })\n options.signal?.addEventListener('abort', onAbort)\n\n channel.addEventListener('signal', (evt) => {\n const signal = evt.detail\n\n sio.socket.emit('ss-handshake', {\n intentId: intentId,\n srcMultiaddr: sio.signallingAddr.toString(),\n dstMultiaddr: ma.toString(),\n signal: signal\n })\n })\n\n sio.socket.on('ws-handshake', (offer) => {\n if (offer.intentId === intentId && offer.err != null) {\n channel.close().finally(() => {\n reject(errcode(new Error(offer.err), 'ERR_SIGNALLING_FAILED'))\n })\n }\n\n if (offer.intentId !== intentId || offer.answer == null || channel.closed) {\n return\n }\n\n channel.handleSignal(offer.signal)\n })\n })\n }\n\n /**\n * Creates a WebrtcStar 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: WebRTCStarListenerOptions): Listener {\n if (!webrtcSupport && this.wrtc == null) {\n throw errcode(new Error('no WebRTC support'), 'ERR_NO_WEBRTC_SUPPORT')\n }\n\n options.channelOptions = options.channelOptions ?? {}\n\n if (this.wrtc != null) {\n options.channelOptions.wrtc = this.wrtc\n }\n\n if (this.peerId == null) {\n throw errcode(new Error('PeerId not set'), 'ERR_MISSING_PEER_ID')\n }\n\n return createListener(options.upgrader, options.handler ?? noop, this.peerId, this, options)\n }\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid TCP addresses\n */\n filter (multiaddrs: Multiaddr[]) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n return mafmt.WebRTCStar.matches(ma)\n })\n }\n\n peerDiscovered (maStr: string) {\n log('peer discovered: %s', maStr)\n maStr = cleanMultiaddr(maStr)\n\n const ma = multiaddr(maStr)\n const peerIdStr = ma.getPeerId()\n\n if (peerIdStr == null) {\n return\n }\n\n const peerId = peerIdFromString(peerIdStr)\n\n this._discovery.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: [ma],\n protocols: []\n }\n }))\n }\n}\n", "\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n", "\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\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", "import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS\n)\n\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(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = () => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction) {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\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\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr) {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches: matches,\n partialMatch: partialMatch\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { connect, ManagerOptions, SocketOptions } from 'socket.io-client'\nimport pDefer from 'p-defer'\nimport { WebRTCReceiver } from '@libp2p/webrtc-peer'\nimport { toMultiaddrConnection } from './socket-to-conn.js'\nimport { cleanUrlSIO } from './utils.js'\nimport { CODE_P2P } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Upgrader, ConnectionHandler, Listener, ListenerEvents } from '@libp2p/interface-transport'\nimport type { WebRTCStar, WebRTCStarListenerOptions, SignalServer, SignalServerServerEvents } from './transport.js'\nimport type { WebRTCReceiverInit } from '@libp2p/webrtc-peer'\nimport type { WebRTCStarSocket, HandshakeSignal } from '@libp2p/webrtc-star-protocol'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\n\nconst log = logger('libp2p:webrtc-star:listener')\n\nconst sioOptions: Partial = {\n transports: ['websocket'],\n path: '/socket.io-next/' // This should be removed when socket.io@2 support is removed\n}\n\nclass SigServer extends EventEmitter implements SignalServer {\n public signallingAddr: Multiaddr\n public socket: WebRTCStarSocket\n public connections: MultiaddrConnection[]\n public channels: Map\n public pendingSignals: Map\n\n private readonly upgrader: Upgrader\n private readonly handler: ConnectionHandler\n private readonly channelOptions?: WebRTCReceiverInit\n\n constructor (signallingUrl: string, signallingAddr: Multiaddr, upgrader: Upgrader, handler: ConnectionHandler, channelOptions?: WebRTCReceiverInit) {\n super()\n\n this.signallingAddr = signallingAddr\n this.socket = connect(signallingUrl, sioOptions)\n this.connections = []\n this.channels = new Map()\n this.pendingSignals = new Map()\n\n this.upgrader = upgrader\n this.handler = handler\n this.channelOptions = channelOptions\n\n this.handleWsHandshake = this.handleWsHandshake.bind(this)\n\n let previouslyConnected = false\n\n this.socket.on('connect_error', err => {\n // @ts-expect-error `.type` is missing from the types\n if (previouslyConnected && err.type === 'TransportError') {\n // if we've had an open connection before, and this is a\n // transport error, let socket.io's reconnect logic take over\n return\n }\n\n this.dispatchEvent(new CustomEvent('error', {\n detail: err\n }))\n })\n this.socket.on('error', (err: Error) => {\n this.dispatchEvent(new CustomEvent('error', {\n detail: err\n }))\n })\n this.socket.on('ws-handshake', this.handleWsHandshake)\n this.socket.on('ws-peer', (maStr) => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: maStr\n }))\n })\n this.socket.on('connect', () => {\n this.socket.emit('ss-join', this.signallingAddr.toString())\n\n if (previouslyConnected) {\n this.dispatchEvent(new CustomEvent('reconnect'))\n }\n })\n this.socket.once('connect', () => {\n // make sure we can reconnect in future\n previouslyConnected = true\n this.dispatchEvent(new CustomEvent('listening'))\n })\n this.socket.on('disconnect', () => {\n this.dispatchEvent(new CustomEvent('disconnect'))\n })\n }\n\n _createChannel (intentId: string, srcMultiaddr: string, dstMultiaddr: string) {\n const channelOptions: WebRTCReceiverInit = {\n ...this.channelOptions\n }\n\n const channel = new WebRTCReceiver(channelOptions)\n\n const onError = (evt: CustomEvent) => {\n const err = evt.detail\n\n log.error('incoming connection errored', err)\n }\n\n channel.addEventListener('error', onError)\n channel.addEventListener('close', () => {\n channel.removeEventListener('error', onError)\n }, {\n once: true\n })\n\n channel.addEventListener('signal', (evt) => {\n const signal = evt.detail\n\n this.socket.emit('ss-handshake', {\n intentId,\n srcMultiaddr,\n dstMultiaddr,\n answer: true,\n signal\n })\n })\n\n channel.addEventListener('ready', () => {\n const maConn = toMultiaddrConnection(channel, { remoteAddr: this.signallingAddr })\n log('new inbound connection %s', maConn.remoteAddr)\n\n try {\n this.upgrader.upgradeInbound(maConn)\n .then(conn => {\n log('inbound connection %s upgraded', maConn.remoteAddr)\n\n this.connections.push(maConn)\n\n const untrackConn = () => {\n this.connections = this.connections.filter(c => c !== maConn)\n this.channels.delete(intentId)\n this.pendingSignals.delete(intentId)\n }\n\n channel.addEventListener('close', untrackConn, {\n once: true\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: conn\n }))\n this.handler(conn)\n })\n .catch(err => {\n log.error('inbound connection failed to upgrade', err)\n maConn.close().catch(err => {\n log.error('inbound connection failed to close after failing to upgrade', err)\n })\n })\n } catch (err: any) {\n log.error('inbound connection failed to upgrade', err)\n maConn.close().catch(err => {\n log.error('inbound connection failed to close after failing to upgrade', err)\n })\n }\n }, {\n once: true\n })\n\n return channel\n }\n\n handleWsHandshake (offer: HandshakeSignal) {\n log('incoming handshake. signal type \"%s\" is answer %s', offer.signal.type, offer.answer)\n\n if (offer.answer === true || offer.err != null || offer.intentId == null) {\n return\n }\n\n const intentId = offer.intentId\n let pendingSignals = this.pendingSignals.get(intentId)\n\n if (pendingSignals == null) {\n pendingSignals = []\n this.pendingSignals.set(intentId, pendingSignals)\n }\n\n pendingSignals.push(offer)\n\n let channel = this.channels.get(intentId)\n\n if (channel == null) {\n if (offer.signal.type !== 'offer') {\n log('handshake is not an offer and channel does not exist, buffering until we receive an offer')\n return\n }\n\n log('creating new channel to handle offer handshake')\n channel = this._createChannel(offer.intentId, offer.srcMultiaddr, offer.dstMultiaddr)\n this.channels.set(intentId, channel)\n } else {\n log('channel already exists, using it to handle handshake')\n }\n\n while (pendingSignals.length > 0) {\n const handshake = pendingSignals.shift()\n\n if (handshake?.signal != null) {\n channel.handleSignal(handshake.signal)\n }\n }\n }\n\n async close () {\n // Close listener\n this.socket.emit('ss-leave', this.signallingAddr.toString())\n this.socket.removeAllListeners()\n this.socket.close()\n\n await Promise.all([\n ...this.connections.map(async maConn => await maConn.close()),\n ...Array.from(this.channels.values()).map(async channel => await channel.close())\n ])\n\n this.dispatchEvent(new CustomEvent('close'))\n }\n}\n\nclass WebRTCListener extends EventEmitter implements Listener {\n private listeningAddr?: Multiaddr\n private signallingUrl?: string\n private readonly upgrader: Upgrader\n private readonly handler: ConnectionHandler\n private readonly peerId: PeerId\n private readonly transport: WebRTCStar\n private readonly options: WebRTCStarListenerOptions\n\n constructor (upgrader: Upgrader, handler: ConnectionHandler, peerId: PeerId, transport: WebRTCStar, options: WebRTCStarListenerOptions) {\n super()\n\n this.upgrader = upgrader\n this.handler = handler\n this.peerId = peerId\n this.transport = transport\n this.options = options\n }\n\n async listen (ma: Multiaddr) {\n // Should only be used if not already listening\n if (this.listeningAddr != null) {\n throw errCode(new Error('listener already in use'), 'ERR_ALREADY_LISTENING')\n }\n\n const defer = pDefer() // eslint-disable-line @typescript-eslint/no-invalid-void-type\n\n // Should be kept unmodified\n this.listeningAddr = ma\n\n let signallingAddr: Multiaddr\n if (!ma.protoCodes().includes(CODE_P2P)) {\n signallingAddr = ma.encapsulate(`/p2p/${this.peerId.toString()}`)\n } else {\n signallingAddr = ma\n }\n\n const signallingUrl = this.signallingUrl = cleanUrlSIO(ma)\n\n log('connecting to signalling server on: %s', this.signallingUrl)\n const server: SignalServer = new SigServer(this.signallingUrl, signallingAddr, this.upgrader, this.handler, this.options.channelOptions)\n server.addEventListener('error', (evt) => {\n const err = evt.detail\n\n log('error connecting to signalling server %o', err)\n server.close().catch(err => {\n log.error('error closing server after error', err)\n })\n defer.reject(err)\n })\n server.addEventListener('listening', () => {\n log('connected to signalling server')\n this.dispatchEvent(new CustomEvent('listening'))\n defer.resolve()\n })\n server.addEventListener('peer', (evt) => {\n this.transport.peerDiscovered(evt.detail)\n })\n server.addEventListener('connection', (evt) => {\n const conn = evt.detail\n\n if (conn.remoteAddr == null) {\n try {\n conn.remoteAddr = ma.decapsulateCode(CODE_P2P).encapsulate(`/p2p/${conn.remotePeer.toString()}`)\n } catch (err) {\n log.error('could not determine remote address', err)\n }\n }\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: conn\n }))\n })\n server.addEventListener('disconnect', () => {\n // Ensure we error if we try to dial while we are disconnected from\n // the signalling server\n this.transport.sigServers.delete(signallingUrl)\n })\n server.addEventListener('reconnect', () => {\n // We can dial via the signalling server again\n this.transport.sigServers.set(signallingUrl, server)\n })\n\n // Store listen and signal reference addresses\n this.transport.sigServers.set(this.signallingUrl, server)\n\n return await defer.promise\n }\n\n async close () {\n if (this.signallingUrl != null) {\n const server = this.transport.sigServers.get(this.signallingUrl)\n\n if (server != null) {\n await server.close()\n this.transport.sigServers.delete(this.signallingUrl)\n }\n }\n\n this.dispatchEvent(new CustomEvent('close'))\n\n // Reset state\n this.listeningAddr = undefined\n }\n\n getAddrs () {\n if (this.listeningAddr != null) {\n return [\n this.listeningAddr\n ]\n }\n\n return []\n }\n}\n\nexport function createListener (upgrader: Upgrader, handler: ConnectionHandler, peerId: PeerId, transport: WebRTCStar, options: WebRTCStarListenerOptions) {\n return new WebRTCListener(upgrader, handler, peerId, transport, options)\n}\n", "const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n", "import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n", "// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nexport const decode = (base64) => {\n let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n", "import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"./contrib/base64-arraybuffer.js\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n", "import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n", "/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n", "export const globalThisShim = (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n", "import { globalThisShim as globalThis } from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = globalThis.setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = globalThis.clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = globalThis.setTimeout.bind(globalThis);\n obj.clearTimeoutFn = globalThis.clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n", "import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} opts - options\n * @protected\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n */\n open() {\n this.readyState = \"opening\";\n this.doOpen();\n return this;\n }\n /**\n * Closes the transport.\n */\n close() {\n if (this.readyState === \"opening\" || this.readyState === \"open\") {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n */\n send(packets) {\n if (this.readyState === \"open\") {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n /**\n * Pauses the transport, in order not to lose packets during an upgrade.\n *\n * @param onPause\n */\n pause(onPause) { }\n}\n", "// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n", "// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n", "// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n", "// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nexport function XHR(opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n", "import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport { XHR as XMLHttpRequest } from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false,\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @package\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @protected\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} onPause - callback upon buffers are flushed and transport is paused\n * @package\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @private\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @protected\n */\n onData(data) {\n const callback = (packet) => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @protected\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} packets - data packets\n * @protected\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, (data) => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data,\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @package\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @package\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n", "import { globalThisShim as globalThis } from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return (cb) => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n", "import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket, } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @param {Object} opts - connection options\n * @protected\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n get name() {\n return \"websocket\";\n }\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = (closeEvent) => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent,\n });\n this.ws.onmessage = (ev) => this.onData(ev.data);\n this.ws.onerror = (e) => this.onError(\"websocket error\", e);\n }\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, (data) => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @private\n */\n check() {\n return !!WebSocket;\n }\n}\n", "import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling,\n};\n", "// imported from https://github.com/galkn/parseuri\n/**\n * Parses a URI\n *\n * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.\n *\n * See:\n * - https://developer.mozilla.org/en-US/docs/Web/API/URL\n * - https://caniuse.com/url\n * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B\n *\n * History of the parse() method:\n * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c\n * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3\n * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@\\/?#]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@\\/?#]*)(?::([^:@\\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.slice(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.slice(-1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n", "import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri - uri or options\n * @param {Object} opts - options\n */\n constructor(uri, opts = {}) {\n super();\n this.writeBuffer = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n addTrailingSlash: true,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024,\n },\n transportOptions: {},\n closeOnBeforeunload: true,\n }, opts);\n this.opts.path =\n this.opts.path.replace(/\\/$/, \"\") +\n (this.opts.addTrailingSlash ? \"/\" : \"\");\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n this.beforeunloadEventListener = () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n };\n addEventListener(\"beforeunload\", this.beforeunloadEventListener, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\",\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} name - transport name\n * @return {Transport}\n * @private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port,\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", (reason) => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} name - transport name\n * @private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", (msg) => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = (err) => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState && this.opts.upgrade) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} msg - message.\n * @param {Object} options.\n * @param {Function} callback function.\n * @return {Socket} for chaining.\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} type: packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} fn - callback function.\n * @private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options,\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"beforeunload\", this.beforeunloadEventListener, false);\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} upgrades - server upgrades\n * @private\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n", "import { Socket } from \"./socket.js\";\nexport { Socket };\nexport const protocol = Socket.protocol;\nexport { Transport } from \"./transport.js\";\nexport { transports } from \"./transports/index.js\";\nexport { installTimerFunctions } from \"./util.js\";\nexport { parse } from \"./contrib/parseuri.js\";\nexport { nextTick } from \"./transports/websocket-constructor.js\";\n", "import { parse } from \"engine.io-client\";\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n * Defaults to window.location.\n * @public\n */\nexport function url(uri, path = \"\", loc) {\n let obj = uri;\n // default to window.location\n loc = loc || (typeof location !== \"undefined\" && location);\n if (null == uri)\n uri = loc.protocol + \"//\" + loc.host;\n // relative path support\n if (typeof uri === \"string\") {\n if (\"/\" === uri.charAt(0)) {\n if (\"/\" === uri.charAt(1)) {\n uri = loc.protocol + uri;\n }\n else {\n uri = loc.host + uri;\n }\n }\n if (!/^(https?|wss?):\\/\\//.test(uri)) {\n if (\"undefined\" !== typeof loc) {\n uri = loc.protocol + \"//\" + uri;\n }\n else {\n uri = \"https://\" + uri;\n }\n }\n // parse\n obj = parse(uri);\n }\n // make sure we treat `localhost:80` and `localhost` equally\n if (!obj.port) {\n if (/^(http|ws)$/.test(obj.protocol)) {\n obj.port = \"80\";\n }\n else if (/^(http|ws)s$/.test(obj.protocol)) {\n obj.port = \"443\";\n }\n }\n obj.path = obj.path || \"/\";\n const ipv6 = obj.host.indexOf(\":\") !== -1;\n const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n // define unique id\n obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n // define href\n obj.href =\n obj.protocol +\n \"://\" +\n host +\n (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n return obj;\n}\n", "import { Emitter } from \"@socket.io/component-emitter\";\nimport { deconstructPacket, reconstructPacket } from \"./binary.js\";\nimport { isBinary, hasBinary } from \"./is-binary.js\";\n/**\n * Protocol version.\n *\n * @public\n */\nexport const protocol = 5;\nexport var PacketType;\n(function (PacketType) {\n PacketType[PacketType[\"CONNECT\"] = 0] = \"CONNECT\";\n PacketType[PacketType[\"DISCONNECT\"] = 1] = \"DISCONNECT\";\n PacketType[PacketType[\"EVENT\"] = 2] = \"EVENT\";\n PacketType[PacketType[\"ACK\"] = 3] = \"ACK\";\n PacketType[PacketType[\"CONNECT_ERROR\"] = 4] = \"CONNECT_ERROR\";\n PacketType[PacketType[\"BINARY_EVENT\"] = 5] = \"BINARY_EVENT\";\n PacketType[PacketType[\"BINARY_ACK\"] = 6] = \"BINARY_ACK\";\n})(PacketType || (PacketType = {}));\n/**\n * A socket.io Encoder instance\n */\nexport class Encoder {\n /**\n * Encoder constructor\n *\n * @param {function} replacer - custom replacer to pass down to JSON.parse\n */\n constructor(replacer) {\n this.replacer = replacer;\n }\n /**\n * Encode a packet as a single string if non-binary, or as a\n * buffer sequence, depending on packet type.\n *\n * @param {Object} obj - packet object\n */\n encode(obj) {\n if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {\n if (hasBinary(obj)) {\n return this.encodeAsBinary({\n type: obj.type === PacketType.EVENT\n ? PacketType.BINARY_EVENT\n : PacketType.BINARY_ACK,\n nsp: obj.nsp,\n data: obj.data,\n id: obj.id,\n });\n }\n }\n return [this.encodeAsString(obj)];\n }\n /**\n * Encode packet as string.\n */\n encodeAsString(obj) {\n // first is type\n let str = \"\" + obj.type;\n // attachments if we have them\n if (obj.type === PacketType.BINARY_EVENT ||\n obj.type === PacketType.BINARY_ACK) {\n str += obj.attachments + \"-\";\n }\n // if we have a namespace other than `/`\n // we append it followed by a comma `,`\n if (obj.nsp && \"/\" !== obj.nsp) {\n str += obj.nsp + \",\";\n }\n // immediately followed by the id\n if (null != obj.id) {\n str += obj.id;\n }\n // json data\n if (null != obj.data) {\n str += JSON.stringify(obj.data, this.replacer);\n }\n return str;\n }\n /**\n * Encode packet as 'buffer sequence' by removing blobs, and\n * deconstructing packet into object with placeholders and\n * a list of buffers.\n */\n encodeAsBinary(obj) {\n const deconstruction = deconstructPacket(obj);\n const pack = this.encodeAsString(deconstruction.packet);\n const buffers = deconstruction.buffers;\n buffers.unshift(pack); // add packet info to beginning of data list\n return buffers; // write all the buffers\n }\n}\n/**\n * A socket.io Decoder instance\n *\n * @return {Object} decoder\n */\nexport class Decoder extends Emitter {\n /**\n * Decoder constructor\n *\n * @param {function} reviver - custom reviver to pass down to JSON.stringify\n */\n constructor(reviver) {\n super();\n this.reviver = reviver;\n }\n /**\n * Decodes an encoded packet string into packet JSON.\n *\n * @param {String} obj - encoded packet\n */\n add(obj) {\n let packet;\n if (typeof obj === \"string\") {\n if (this.reconstructor) {\n throw new Error(\"got plaintext data when reconstructing a packet\");\n }\n packet = this.decodeString(obj);\n const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;\n if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {\n packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;\n // binary packet's json\n this.reconstructor = new BinaryReconstructor(packet);\n // no attachments, labeled binary but no binary data to follow\n if (packet.attachments === 0) {\n super.emitReserved(\"decoded\", packet);\n }\n }\n else {\n // non-binary full packet\n super.emitReserved(\"decoded\", packet);\n }\n }\n else if (isBinary(obj) || obj.base64) {\n // raw binary data\n if (!this.reconstructor) {\n throw new Error(\"got binary data when not reconstructing a packet\");\n }\n else {\n packet = this.reconstructor.takeBinaryData(obj);\n if (packet) {\n // received final buffer\n this.reconstructor = null;\n super.emitReserved(\"decoded\", packet);\n }\n }\n }\n else {\n throw new Error(\"Unknown type: \" + obj);\n }\n }\n /**\n * Decode a packet String (JSON data)\n *\n * @param {String} str\n * @return {Object} packet\n */\n decodeString(str) {\n let i = 0;\n // look up type\n const p = {\n type: Number(str.charAt(0)),\n };\n if (PacketType[p.type] === undefined) {\n throw new Error(\"unknown packet type \" + p.type);\n }\n // look up attachments if type binary\n if (p.type === PacketType.BINARY_EVENT ||\n p.type === PacketType.BINARY_ACK) {\n const start = i + 1;\n while (str.charAt(++i) !== \"-\" && i != str.length) { }\n const buf = str.substring(start, i);\n if (buf != Number(buf) || str.charAt(i) !== \"-\") {\n throw new Error(\"Illegal attachments\");\n }\n p.attachments = Number(buf);\n }\n // look up namespace (if any)\n if (\"/\" === str.charAt(i + 1)) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (\",\" === c)\n break;\n if (i === str.length)\n break;\n }\n p.nsp = str.substring(start, i);\n }\n else {\n p.nsp = \"/\";\n }\n // look up id\n const next = str.charAt(i + 1);\n if (\"\" !== next && Number(next) == next) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (null == c || Number(c) != c) {\n --i;\n break;\n }\n if (i === str.length)\n break;\n }\n p.id = Number(str.substring(start, i + 1));\n }\n // look up json data\n if (str.charAt(++i)) {\n const payload = this.tryParse(str.substr(i));\n if (Decoder.isPayloadValid(p.type, payload)) {\n p.data = payload;\n }\n else {\n throw new Error(\"invalid payload\");\n }\n }\n return p;\n }\n tryParse(str) {\n try {\n return JSON.parse(str, this.reviver);\n }\n catch (e) {\n return false;\n }\n }\n static isPayloadValid(type, payload) {\n switch (type) {\n case PacketType.CONNECT:\n return typeof payload === \"object\";\n case PacketType.DISCONNECT:\n return payload === undefined;\n case PacketType.CONNECT_ERROR:\n return typeof payload === \"string\" || typeof payload === \"object\";\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n return Array.isArray(payload) && payload.length > 0;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n return Array.isArray(payload);\n }\n }\n /**\n * Deallocates a parser's resources\n */\n destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n this.reconstructor = null;\n }\n }\n}\n/**\n * A manager of a binary event's 'buffer sequence'. Should\n * be constructed whenever a packet of type BINARY_EVENT is\n * decoded.\n *\n * @param {Object} packet\n * @return {BinaryReconstructor} initialized reconstructor\n */\nclass BinaryReconstructor {\n constructor(packet) {\n this.packet = packet;\n this.buffers = [];\n this.reconPack = packet;\n }\n /**\n * Method to be called when binary data received from connection\n * after a BINARY_EVENT packet.\n *\n * @param {Buffer | ArrayBuffer} binData - the raw binary data received\n * @return {null | Object} returns null if more binary data is expected or\n * a reconstructed packet object if all buffers have been received.\n */\n takeBinaryData(binData) {\n this.buffers.push(binData);\n if (this.buffers.length === this.reconPack.attachments) {\n // done with buffer list\n const packet = reconstructPacket(this.reconPack, this.buffers);\n this.finishedReconstruction();\n return packet;\n }\n return null;\n }\n /**\n * Cleans up binary packet reconstruction variables.\n */\n finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }\n}\n", "const withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj.buffer instanceof ArrayBuffer;\n};\nconst toString = Object.prototype.toString;\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeFile = typeof File === \"function\" ||\n (typeof File !== \"undefined\" &&\n toString.call(File) === \"[object FileConstructor]\");\n/**\n * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.\n *\n * @private\n */\nexport function isBinary(obj) {\n return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||\n (withNativeBlob && obj instanceof Blob) ||\n (withNativeFile && obj instanceof File));\n}\nexport function hasBinary(obj, toJSON) {\n if (!obj || typeof obj !== \"object\") {\n return false;\n }\n if (Array.isArray(obj)) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (hasBinary(obj[i])) {\n return true;\n }\n }\n return false;\n }\n if (isBinary(obj)) {\n return true;\n }\n if (obj.toJSON &&\n typeof obj.toJSON === \"function\" &&\n arguments.length === 1) {\n return hasBinary(obj.toJSON(), true);\n }\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {\n return true;\n }\n }\n return false;\n}\n", "import { isBinary } from \"./is-binary.js\";\n/**\n * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.\n *\n * @param {Object} packet - socket.io event packet\n * @return {Object} with deconstructed packet and list of buffers\n * @public\n */\nexport function deconstructPacket(packet) {\n const buffers = [];\n const packetData = packet.data;\n const pack = packet;\n pack.data = _deconstructPacket(packetData, buffers);\n pack.attachments = buffers.length; // number of binary 'attachments'\n return { packet: pack, buffers: buffers };\n}\nfunction _deconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (isBinary(data)) {\n const placeholder = { _placeholder: true, num: buffers.length };\n buffers.push(data);\n return placeholder;\n }\n else if (Array.isArray(data)) {\n const newData = new Array(data.length);\n for (let i = 0; i < data.length; i++) {\n newData[i] = _deconstructPacket(data[i], buffers);\n }\n return newData;\n }\n else if (typeof data === \"object\" && !(data instanceof Date)) {\n const newData = {};\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n newData[key] = _deconstructPacket(data[key], buffers);\n }\n }\n return newData;\n }\n return data;\n}\n/**\n * Reconstructs a binary packet from its placeholder packet and buffers\n *\n * @param {Object} packet - event packet with placeholders\n * @param {Array} buffers - binary buffers to put in placeholder positions\n * @return {Object} reconstructed packet\n * @public\n */\nexport function reconstructPacket(packet, buffers) {\n packet.data = _reconstructPacket(packet.data, buffers);\n delete packet.attachments; // no longer useful\n return packet;\n}\nfunction _reconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (data && data._placeholder === true) {\n const isIndexValid = typeof data.num === \"number\" &&\n data.num >= 0 &&\n data.num < buffers.length;\n if (isIndexValid) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n }\n else {\n throw new Error(\"illegal attachments\");\n }\n }\n else if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n }\n else if (typeof data === \"object\") {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n }\n return data;\n}\n", "export function on(obj, ev, fn) {\n obj.on(ev, fn);\n return function subDestroy() {\n obj.off(ev, fn);\n };\n}\n", "import { PacketType } from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n connect: 1,\n connect_error: 1,\n disconnect: 1,\n disconnecting: 1,\n // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n newListener: 1,\n removeListener: 1,\n});\n/**\n * A Socket is the fundamental class for interacting with the server.\n *\n * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n * console.log(\"connected\");\n * });\n *\n * // send an event to the server\n * socket.emit(\"foo\", \"bar\");\n *\n * socket.on(\"foobar\", () => {\n * // an event was received from the server\n * });\n *\n * // upon disconnection\n * socket.on(\"disconnect\", (reason) => {\n * console.log(`disconnected due to ${reason}`);\n * });\n */\nexport class Socket extends Emitter {\n /**\n * `Socket` constructor.\n */\n constructor(io, nsp, opts) {\n super();\n /**\n * Whether the socket is currently connected to the server.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n * console.log(socket.connected); // true\n * });\n *\n * socket.on(\"disconnect\", () => {\n * console.log(socket.connected); // false\n * });\n */\n this.connected = false;\n /**\n * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will\n * be transmitted by the server.\n */\n this.recovered = false;\n /**\n * Buffer for packets received before the CONNECT packet\n */\n this.receiveBuffer = [];\n /**\n * Buffer for packets that will be sent once the socket is connected\n */\n this.sendBuffer = [];\n /**\n * The queue of packets to be sent with retry in case of failure.\n *\n * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.\n * @private\n */\n this._queue = [];\n /**\n * A sequence to generate the ID of the {@link QueuedPacket}.\n * @private\n */\n this._queueSeq = 0;\n this.ids = 0;\n this.acks = {};\n this.flags = {};\n this.io = io;\n this.nsp = nsp;\n if (opts && opts.auth) {\n this.auth = opts.auth;\n }\n this._opts = Object.assign({}, opts);\n if (this.io._autoConnect)\n this.open();\n }\n /**\n * Whether the socket is currently disconnected\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n * console.log(socket.disconnected); // false\n * });\n *\n * socket.on(\"disconnect\", () => {\n * console.log(socket.disconnected); // true\n * });\n */\n get disconnected() {\n return !this.connected;\n }\n /**\n * Subscribe to open, close and packet events\n *\n * @private\n */\n subEvents() {\n if (this.subs)\n return;\n const io = this.io;\n this.subs = [\n on(io, \"open\", this.onopen.bind(this)),\n on(io, \"packet\", this.onpacket.bind(this)),\n on(io, \"error\", this.onerror.bind(this)),\n on(io, \"close\", this.onclose.bind(this)),\n ];\n }\n /**\n * Whether the Socket will try to reconnect when its Manager connects or reconnects.\n *\n * @example\n * const socket = io();\n *\n * console.log(socket.active); // true\n *\n * socket.on(\"disconnect\", (reason) => {\n * if (reason === \"io server disconnect\") {\n * // the disconnection was initiated by the server, you need to manually reconnect\n * console.log(socket.active); // false\n * }\n * // else the socket will automatically try to reconnect\n * console.log(socket.active); // true\n * });\n */\n get active() {\n return !!this.subs;\n }\n /**\n * \"Opens\" the socket.\n *\n * @example\n * const socket = io({\n * autoConnect: false\n * });\n *\n * socket.connect();\n */\n connect() {\n if (this.connected)\n return this;\n this.subEvents();\n if (!this.io[\"_reconnecting\"])\n this.io.open(); // ensure open\n if (\"open\" === this.io._readyState)\n this.onopen();\n return this;\n }\n /**\n * Alias for {@link connect()}.\n */\n open() {\n return this.connect();\n }\n /**\n * Sends a `message` event.\n *\n * This method mimics the WebSocket.send() method.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send\n *\n * @example\n * socket.send(\"hello\");\n *\n * // this is equivalent to\n * socket.emit(\"message\", \"hello\");\n *\n * @return self\n */\n send(...args) {\n args.unshift(\"message\");\n this.emit.apply(this, args);\n return this;\n }\n /**\n * Override `emit`.\n * If the event is in `events`, it's emitted normally.\n *\n * @example\n * socket.emit(\"hello\", \"world\");\n *\n * // all serializable datastructures are supported (no need to call JSON.stringify)\n * socket.emit(\"hello\", 1, \"2\", { 3: [\"4\"], 5: Uint8Array.from([6]) });\n *\n * // with an acknowledgement from the server\n * socket.emit(\"hello\", \"world\", (val) => {\n * // ...\n * });\n *\n * @return self\n */\n emit(ev, ...args) {\n if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n throw new Error('\"' + ev.toString() + '\" is a reserved event name');\n }\n args.unshift(ev);\n if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {\n this._addToQueue(args);\n return this;\n }\n const packet = {\n type: PacketType.EVENT,\n data: args,\n };\n packet.options = {};\n packet.options.compress = this.flags.compress !== false;\n // event ack callback\n if (\"function\" === typeof args[args.length - 1]) {\n const id = this.ids++;\n const ack = args.pop();\n this._registerAckCallback(id, ack);\n packet.id = id;\n }\n const isTransportWritable = this.io.engine &&\n this.io.engine.transport &&\n this.io.engine.transport.writable;\n const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);\n if (discardPacket) {\n }\n else if (this.connected) {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n }\n else {\n this.sendBuffer.push(packet);\n }\n this.flags = {};\n return this;\n }\n /**\n * @private\n */\n _registerAckCallback(id, ack) {\n var _a;\n const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;\n if (timeout === undefined) {\n this.acks[id] = ack;\n return;\n }\n // @ts-ignore\n const timer = this.io.setTimeoutFn(() => {\n delete this.acks[id];\n for (let i = 0; i < this.sendBuffer.length; i++) {\n if (this.sendBuffer[i].id === id) {\n this.sendBuffer.splice(i, 1);\n }\n }\n ack.call(this, new Error(\"operation has timed out\"));\n }, timeout);\n this.acks[id] = (...args) => {\n // @ts-ignore\n this.io.clearTimeoutFn(timer);\n ack.apply(this, [null, ...args]);\n };\n }\n /**\n * Emits an event and waits for an acknowledgement\n *\n * @example\n * // without timeout\n * const response = await socket.emitWithAck(\"hello\", \"world\");\n *\n * // with a specific timeout\n * try {\n * const response = await socket.timeout(1000).emitWithAck(\"hello\", \"world\");\n * } catch (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n *\n * @return a Promise that will be fulfilled when the server acknowledges the event\n */\n emitWithAck(ev, ...args) {\n // the timeout flag is optional\n const withErr = this.flags.timeout !== undefined || this._opts.ackTimeout !== undefined;\n return new Promise((resolve, reject) => {\n args.push((arg1, arg2) => {\n if (withErr) {\n return arg1 ? reject(arg1) : resolve(arg2);\n }\n else {\n return resolve(arg1);\n }\n });\n this.emit(ev, ...args);\n });\n }\n /**\n * Add the packet to the queue.\n * @param args\n * @private\n */\n _addToQueue(args) {\n let ack;\n if (typeof args[args.length - 1] === \"function\") {\n ack = args.pop();\n }\n const packet = {\n id: this._queueSeq++,\n tryCount: 0,\n pending: false,\n args,\n flags: Object.assign({ fromQueue: true }, this.flags),\n };\n args.push((err, ...responseArgs) => {\n if (packet !== this._queue[0]) {\n // the packet has already been acknowledged\n return;\n }\n const hasError = err !== null;\n if (hasError) {\n if (packet.tryCount > this._opts.retries) {\n this._queue.shift();\n if (ack) {\n ack(err);\n }\n }\n }\n else {\n this._queue.shift();\n if (ack) {\n ack(null, ...responseArgs);\n }\n }\n packet.pending = false;\n return this._drainQueue();\n });\n this._queue.push(packet);\n this._drainQueue();\n }\n /**\n * Send the first packet of the queue, and wait for an acknowledgement from the server.\n * @param force - whether to resend a packet that has not been acknowledged yet\n *\n * @private\n */\n _drainQueue(force = false) {\n if (!this.connected || this._queue.length === 0) {\n return;\n }\n const packet = this._queue[0];\n if (packet.pending && !force) {\n return;\n }\n packet.pending = true;\n packet.tryCount++;\n this.flags = packet.flags;\n this.emit.apply(this, packet.args);\n }\n /**\n * Sends a packet.\n *\n * @param packet\n * @private\n */\n packet(packet) {\n packet.nsp = this.nsp;\n this.io._packet(packet);\n }\n /**\n * Called upon engine `open`.\n *\n * @private\n */\n onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this._sendConnectPacket(data);\n });\n }\n else {\n this._sendConnectPacket(this.auth);\n }\n }\n /**\n * Sends a CONNECT packet to initiate the Socket.IO session.\n *\n * @param data\n * @private\n */\n _sendConnectPacket(data) {\n this.packet({\n type: PacketType.CONNECT,\n data: this._pid\n ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)\n : data,\n });\n }\n /**\n * Called upon engine or manager `error`.\n *\n * @param err\n * @private\n */\n onerror(err) {\n if (!this.connected) {\n this.emitReserved(\"connect_error\", err);\n }\n }\n /**\n * Called upon engine `close`.\n *\n * @param reason\n * @param description\n * @private\n */\n onclose(reason, description) {\n this.connected = false;\n delete this.id;\n this.emitReserved(\"disconnect\", reason, description);\n }\n /**\n * Called with socket packet.\n *\n * @param packet\n * @private\n */\n onpacket(packet) {\n const sameNamespace = packet.nsp === this.nsp;\n if (!sameNamespace)\n return;\n switch (packet.type) {\n case PacketType.CONNECT:\n if (packet.data && packet.data.sid) {\n this.onconnect(packet.data.sid, packet.data.pid);\n }\n else {\n this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n }\n break;\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n this.onevent(packet);\n break;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n this.onack(packet);\n break;\n case PacketType.DISCONNECT:\n this.ondisconnect();\n break;\n case PacketType.CONNECT_ERROR:\n this.destroy();\n const err = new Error(packet.data.message);\n // @ts-ignore\n err.data = packet.data.data;\n this.emitReserved(\"connect_error\", err);\n break;\n }\n }\n /**\n * Called upon a server event.\n *\n * @param packet\n * @private\n */\n onevent(packet) {\n const args = packet.data || [];\n if (null != packet.id) {\n args.push(this.ack(packet.id));\n }\n if (this.connected) {\n this.emitEvent(args);\n }\n else {\n this.receiveBuffer.push(Object.freeze(args));\n }\n }\n emitEvent(args) {\n if (this._anyListeners && this._anyListeners.length) {\n const listeners = this._anyListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, args);\n }\n }\n super.emit.apply(this, args);\n if (this._pid && args.length && typeof args[args.length - 1] === \"string\") {\n this._lastOffset = args[args.length - 1];\n }\n }\n /**\n * Produces an ack callback to emit with an event.\n *\n * @private\n */\n ack(id) {\n const self = this;\n let sent = false;\n return function (...args) {\n // prevent double callbacks\n if (sent)\n return;\n sent = true;\n self.packet({\n type: PacketType.ACK,\n id: id,\n data: args,\n });\n };\n }\n /**\n * Called upon a server acknowlegement.\n *\n * @param packet\n * @private\n */\n onack(packet) {\n const ack = this.acks[packet.id];\n if (\"function\" === typeof ack) {\n ack.apply(this, packet.data);\n delete this.acks[packet.id];\n }\n else {\n }\n }\n /**\n * Called upon server connect.\n *\n * @private\n */\n onconnect(id, pid) {\n this.id = id;\n this.recovered = pid && this._pid === pid;\n this._pid = pid; // defined only if connection state recovery is enabled\n this.connected = true;\n this.emitBuffered();\n this.emitReserved(\"connect\");\n this._drainQueue(true);\n }\n /**\n * Emit buffered events (received and emitted).\n *\n * @private\n */\n emitBuffered() {\n this.receiveBuffer.forEach((args) => this.emitEvent(args));\n this.receiveBuffer = [];\n this.sendBuffer.forEach((packet) => {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n });\n this.sendBuffer = [];\n }\n /**\n * Called upon server disconnect.\n *\n * @private\n */\n ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }\n /**\n * Called upon forced client/server side disconnections,\n * this method ensures the manager stops tracking us and\n * that reconnections don't get triggered for this.\n *\n * @private\n */\n destroy() {\n if (this.subs) {\n // clean subscriptions to avoid reconnections\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs = undefined;\n }\n this.io[\"_destroy\"](this);\n }\n /**\n * Disconnects the socket manually. In that case, the socket will not try to reconnect.\n *\n * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"disconnect\", (reason) => {\n * // console.log(reason); prints \"io client disconnect\"\n * });\n *\n * socket.disconnect();\n *\n * @return self\n */\n disconnect() {\n if (this.connected) {\n this.packet({ type: PacketType.DISCONNECT });\n }\n // remove socket from pool\n this.destroy();\n if (this.connected) {\n // fire events\n this.onclose(\"io client disconnect\");\n }\n return this;\n }\n /**\n * Alias for {@link disconnect()}.\n *\n * @return self\n */\n close() {\n return this.disconnect();\n }\n /**\n * Sets the compress flag.\n *\n * @example\n * socket.compress(false).emit(\"hello\");\n *\n * @param compress - if `true`, compresses the sending data\n * @return self\n */\n compress(compress) {\n this.flags.compress = compress;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n * ready to send messages.\n *\n * @example\n * socket.volatile.emit(\"hello\"); // the server may or may not receive it\n *\n * @returns self\n */\n get volatile() {\n this.flags.volatile = true;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n * given number of milliseconds have elapsed without an acknowledgement from the server:\n *\n * @example\n * socket.timeout(5000).emit(\"my-event\", (err) => {\n * if (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n * });\n *\n * @returns self\n */\n timeout(timeout) {\n this.flags.timeout = timeout;\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @example\n * socket.onAny((event, ...args) => {\n * console.log(`got ${event}`);\n * });\n *\n * @param listener\n */\n onAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @example\n * socket.prependAny((event, ...args) => {\n * console.log(`got event ${event}`);\n * });\n *\n * @param listener\n */\n prependAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @example\n * const catchAllListener = (event, ...args) => {\n * console.log(`got event ${event}`);\n * }\n *\n * socket.onAny(catchAllListener);\n *\n * // remove a specific listener\n * socket.offAny(catchAllListener);\n *\n * // or remove all listeners\n * socket.offAny();\n *\n * @param listener\n */\n offAny(listener) {\n if (!this._anyListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n */\n listenersAny() {\n return this._anyListeners || [];\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * Note: acknowledgements sent to the server are not included.\n *\n * @example\n * socket.onAnyOutgoing((event, ...args) => {\n * console.log(`sent event ${event}`);\n * });\n *\n * @param listener\n */\n onAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * Note: acknowledgements sent to the server are not included.\n *\n * @example\n * socket.prependAnyOutgoing((event, ...args) => {\n * console.log(`sent event ${event}`);\n * });\n *\n * @param listener\n */\n prependAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @example\n * const catchAllListener = (event, ...args) => {\n * console.log(`sent event ${event}`);\n * }\n *\n * socket.onAnyOutgoing(catchAllListener);\n *\n * // remove a specific listener\n * socket.offAnyOutgoing(catchAllListener);\n *\n * // or remove all listeners\n * socket.offAnyOutgoing();\n *\n * @param [listener] - the catch-all listener (optional)\n */\n offAnyOutgoing(listener) {\n if (!this._anyOutgoingListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyOutgoingListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyOutgoingListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n */\n listenersAnyOutgoing() {\n return this._anyOutgoingListeners || [];\n }\n /**\n * Notify the listeners for each packet sent\n *\n * @param packet\n *\n * @private\n */\n notifyOutgoingListeners(packet) {\n if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n const listeners = this._anyOutgoingListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, packet.data);\n }\n }\n }\n}\n", "/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nexport function Backoff(opts) {\n opts = opts || {};\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n this.factor = opts.factor || 2;\n this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n this.jitter = jitter;\n};\n", "import { Socket as Engine, installTimerFunctions, nextTick, } from \"engine.io-client\";\nimport { Socket } from \"./socket.js\";\nimport * as parser from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Backoff } from \"./contrib/backo2.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\nexport class Manager extends Emitter {\n constructor(uri, opts) {\n var _a;\n super();\n this.nsps = {};\n this.subs = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n opts.path = opts.path || \"/socket.io\";\n this.opts = opts;\n installTimerFunctions(this, opts);\n this.reconnection(opts.reconnection !== false);\n this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n this.reconnectionDelay(opts.reconnectionDelay || 1000);\n this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n this.backoff = new Backoff({\n min: this.reconnectionDelay(),\n max: this.reconnectionDelayMax(),\n jitter: this.randomizationFactor(),\n });\n this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n this._readyState = \"closed\";\n this.uri = uri;\n const _parser = opts.parser || parser;\n this.encoder = new _parser.Encoder();\n this.decoder = new _parser.Decoder();\n this._autoConnect = opts.autoConnect !== false;\n if (this._autoConnect)\n this.open();\n }\n reconnection(v) {\n if (!arguments.length)\n return this._reconnection;\n this._reconnection = !!v;\n return this;\n }\n reconnectionAttempts(v) {\n if (v === undefined)\n return this._reconnectionAttempts;\n this._reconnectionAttempts = v;\n return this;\n }\n reconnectionDelay(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelay;\n this._reconnectionDelay = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n return this;\n }\n randomizationFactor(v) {\n var _a;\n if (v === undefined)\n return this._randomizationFactor;\n this._randomizationFactor = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n return this;\n }\n reconnectionDelayMax(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelayMax;\n this._reconnectionDelayMax = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n return this;\n }\n timeout(v) {\n if (!arguments.length)\n return this._timeout;\n this._timeout = v;\n return this;\n }\n /**\n * Starts trying to reconnect if reconnection is enabled and we have not\n * started reconnecting yet\n *\n * @private\n */\n maybeReconnectOnOpen() {\n // Only try to reconnect if it's the first time we're connecting\n if (!this._reconnecting &&\n this._reconnection &&\n this.backoff.attempts === 0) {\n // keeps reconnection from firing twice for the same reconnection loop\n this.reconnect();\n }\n }\n /**\n * Sets the current transport `socket`.\n *\n * @param {Function} fn - optional, callback\n * @return self\n * @public\n */\n open(fn) {\n if (~this._readyState.indexOf(\"open\"))\n return this;\n this.engine = new Engine(this.uri, this.opts);\n const socket = this.engine;\n const self = this;\n this._readyState = \"opening\";\n this.skipReconnect = false;\n // emit `open`\n const openSubDestroy = on(socket, \"open\", function () {\n self.onopen();\n fn && fn();\n });\n // emit `error`\n const errorSub = on(socket, \"error\", (err) => {\n self.cleanup();\n self._readyState = \"closed\";\n this.emitReserved(\"error\", err);\n if (fn) {\n fn(err);\n }\n else {\n // Only do this if there is no fn to handle the error\n self.maybeReconnectOnOpen();\n }\n });\n if (false !== this._timeout) {\n const timeout = this._timeout;\n if (timeout === 0) {\n openSubDestroy(); // prevents a race condition with the 'open' event\n }\n // set timer\n const timer = this.setTimeoutFn(() => {\n openSubDestroy();\n socket.close();\n // @ts-ignore\n socket.emit(\"error\", new Error(\"timeout\"));\n }, timeout);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n this.subs.push(openSubDestroy);\n this.subs.push(errorSub);\n return this;\n }\n /**\n * Alias for open()\n *\n * @return self\n * @public\n */\n connect(fn) {\n return this.open(fn);\n }\n /**\n * Called upon transport open.\n *\n * @private\n */\n onopen() {\n // clear old subs\n this.cleanup();\n // mark as open\n this._readyState = \"open\";\n this.emitReserved(\"open\");\n // add new subs\n const socket = this.engine;\n this.subs.push(on(socket, \"ping\", this.onping.bind(this)), on(socket, \"data\", this.ondata.bind(this)), on(socket, \"error\", this.onerror.bind(this)), on(socket, \"close\", this.onclose.bind(this)), on(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n }\n /**\n * Called upon a ping.\n *\n * @private\n */\n onping() {\n this.emitReserved(\"ping\");\n }\n /**\n * Called with data.\n *\n * @private\n */\n ondata(data) {\n try {\n this.decoder.add(data);\n }\n catch (e) {\n this.onclose(\"parse error\", e);\n }\n }\n /**\n * Called when parser fully decodes a packet.\n *\n * @private\n */\n ondecoded(packet) {\n // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a \"parse error\"\n nextTick(() => {\n this.emitReserved(\"packet\", packet);\n }, this.setTimeoutFn);\n }\n /**\n * Called upon socket error.\n *\n * @private\n */\n onerror(err) {\n this.emitReserved(\"error\", err);\n }\n /**\n * Creates a new socket for the given `nsp`.\n *\n * @return {Socket}\n * @public\n */\n socket(nsp, opts) {\n let socket = this.nsps[nsp];\n if (!socket) {\n socket = new Socket(this, nsp, opts);\n this.nsps[nsp] = socket;\n }\n else if (this._autoConnect && !socket.active) {\n socket.connect();\n }\n return socket;\n }\n /**\n * Called upon a socket close.\n *\n * @param socket\n * @private\n */\n _destroy(socket) {\n const nsps = Object.keys(this.nsps);\n for (const nsp of nsps) {\n const socket = this.nsps[nsp];\n if (socket.active) {\n return;\n }\n }\n this._close();\n }\n /**\n * Writes a packet.\n *\n * @param packet\n * @private\n */\n _packet(packet) {\n const encodedPackets = this.encoder.encode(packet);\n for (let i = 0; i < encodedPackets.length; i++) {\n this.engine.write(encodedPackets[i], packet.options);\n }\n }\n /**\n * Clean up transport subscriptions and packet buffer.\n *\n * @private\n */\n cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }\n /**\n * Close the current socket.\n *\n * @private\n */\n _close() {\n this.skipReconnect = true;\n this._reconnecting = false;\n this.onclose(\"forced close\");\n if (this.engine)\n this.engine.close();\n }\n /**\n * Alias for close()\n *\n * @private\n */\n disconnect() {\n return this._close();\n }\n /**\n * Called upon engine close.\n *\n * @private\n */\n onclose(reason, description) {\n this.cleanup();\n this.backoff.reset();\n this._readyState = \"closed\";\n this.emitReserved(\"close\", reason, description);\n if (this._reconnection && !this.skipReconnect) {\n this.reconnect();\n }\n }\n /**\n * Attempt a reconnection.\n *\n * @private\n */\n reconnect() {\n if (this._reconnecting || this.skipReconnect)\n return this;\n const self = this;\n if (this.backoff.attempts >= this._reconnectionAttempts) {\n this.backoff.reset();\n this.emitReserved(\"reconnect_failed\");\n this._reconnecting = false;\n }\n else {\n const delay = this.backoff.duration();\n this._reconnecting = true;\n const timer = this.setTimeoutFn(() => {\n if (self.skipReconnect)\n return;\n this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n // check again for the case socket closed in above events\n if (self.skipReconnect)\n return;\n self.open((err) => {\n if (err) {\n self._reconnecting = false;\n self.reconnect();\n this.emitReserved(\"reconnect_error\", err);\n }\n else {\n self.onreconnect();\n }\n });\n }, delay);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n }\n /**\n * Called upon successful reconnect.\n *\n * @private\n */\n onreconnect() {\n const attempt = this.backoff.attempts;\n this._reconnecting = false;\n this.backoff.reset();\n this.emitReserved(\"reconnect\", attempt);\n }\n}\n", "import { url } from \"./url.js\";\nimport { Manager } from \"./manager.js\";\nimport { Socket } from \"./socket.js\";\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n if (typeof uri === \"object\") {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n const parsed = url(uri, opts.path || \"/socket.io\");\n const source = parsed.source;\n const id = parsed.id;\n const path = parsed.path;\n const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n const newConnection = opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n let io;\n if (newConnection) {\n io = new Manager(source, opts);\n }\n else {\n if (!cache[id]) {\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n Manager,\n Socket,\n io: lookup,\n connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nexport { protocol } from \"socket.io-parser\";\n/**\n * Expose constructors for standalone build.\n *\n * @public\n */\nexport { Manager, Socket, lookup as io, lookup as connect, lookup as default, };\n", "\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter> extends EventTarget {\n #listeners: Map = new Map()\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit): boolean {\n return this.dispatchEvent(new CustomEvent(type as string, detail))\n }\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 public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n", "import { Logger, logger } from '@libp2p/logger'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport errCode from 'err-code'\nimport randombytes from 'iso-random-stream/src/random.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { Pushable, pushable } from 'it-pushable'\nimport defer, { DeferredPromise } from 'p-defer'\nimport { WebRTCDataChannel } from './channel.js'\nimport delay from 'delay'\nimport type { WebRTCPeerInit, WebRTCPeerEvents, WRTC } from './index.js'\nimport type { Duplex, Sink } from 'it-stream-types'\n\n// const ICECOMPLETE_TIMEOUT = 5 * 1000\n\nconst DEFAULT_PEER_CONNECTION_CONFIG: RTCConfiguration = {\n iceServers: [{\n urls: [\n 'stun:stun.l.google.com:19302',\n 'stun:global.stun.twilio.com:3478'\n ]\n }]\n}\n\nfunction getBrowserRTC (): WRTC {\n if (typeof globalThis === 'undefined') {\n throw errCode(new Error('No WebRTC support detected'), 'ERR_WEBRTC_SUPPORT')\n }\n\n const wrtc: WRTC = {\n // @ts-expect-error browser-specific properties\n RTCPeerConnection: globalThis.RTCPeerConnection ?? globalThis.mozRTCPeerConnection ?? globalThis.webkitRTCPeerConnection,\n // @ts-expect-error browser-specific properties\n RTCSessionDescription: globalThis.RTCSessionDescription ?? globalThis.mozRTCSessionDescription ?? globalThis.webkitRTCSessionDescription,\n // @ts-expect-error browser-specific properties\n RTCIceCandidate: globalThis.RTCIceCandidate ?? globalThis.mozRTCIceCandidate ?? globalThis.webkitRTCIceCandidate\n }\n\n if (wrtc.RTCPeerConnection == null) {\n throw errCode(new Error('No WebRTC support detected'), 'ERR_WEBRTC_SUPPORT')\n }\n\n return wrtc\n}\n\nexport class WebRTCPeer extends EventEmitter implements Duplex {\n public id: string\n public source: Pushable\n public sink: Sink\n public closed: boolean\n protected wrtc: WRTC\n protected peerConnection: RTCPeerConnection\n protected channel?: WebRTCDataChannel\n protected log: Logger\n private readonly connected: DeferredPromise\n\n constructor (opts: WebRTCPeerInit & { logPrefix: string }) {\n super()\n\n this.id = opts.id ?? uint8ArrayToString(randombytes(4), 'hex').slice(0, 7)\n this.log = logger(`libp2p:webrtc-peer:${opts.logPrefix}:${this.id}`)\n this.wrtc = opts.wrtc ?? getBrowserRTC()\n this.peerConnection = new this.wrtc.RTCPeerConnection(\n Object.assign({}, DEFAULT_PEER_CONNECTION_CONFIG, opts.peerConnectionConfig)\n )\n this.closed = false\n this.connected = defer()\n\n // duplex properties\n this.source = pushable()\n this.sink = async (source) => {\n await this.connected.promise\n\n if (this.channel == null) {\n throw errCode(new Error('Connected but no channel?!'), 'ERR_DATA_CHANNEL')\n }\n\n for await (const buf of source) {\n await this.channel.send(buf)\n }\n\n await this.close()\n }\n }\n\n protected handleDataChannelEvent (event: { channel?: RTCDataChannel}) {\n const dataChannel = event.channel\n\n if (dataChannel == null) {\n // In some situations `pc.createDataChannel()` returns `undefined` (in wrtc),\n // which is invalid behavior. Handle it gracefully.\n // See: https://github.com/feross/simple-peer/issues/163\n this.close(errCode(new Error('Data channel event is missing `channel` property'), 'ERR_DATA_CHANNEL'))\n .catch(err => {\n this.log('Error closing after event channel was found to be null', err)\n })\n\n return\n }\n\n this.channel = new WebRTCDataChannel(dataChannel, {\n log: this.log,\n onMessage: (event) => {\n this.source.push(new Uint8Array(event.data))\n },\n onOpen: () => {\n this.connected.resolve()\n this.dispatchEvent(new CustomEvent('ready'))\n },\n onClose: () => {\n this.close().catch(err => {\n this.log('error closing connection after channel close', err)\n })\n },\n onError: (err) => {\n this.close(err).catch(err => {\n this.log('error closing connection after channel error', err)\n })\n }\n })\n }\n\n async close (err?: Error) {\n this.closed = true\n\n if (err == null && this.channel != null) {\n // wait for the channel to flush all data before closing the channel\n while (this.channel.bufferedAmount > 0) {\n await delay(100)\n }\n }\n\n this.channel?.close()\n this.peerConnection.close()\n this.source.end(err)\n this.dispatchEvent(new CustomEvent('close'))\n }\n}\n", "import errCode from 'err-code'\nimport defer, { DeferredPromise } from 'p-defer'\nimport type { Logger } from '@libp2p/logger'\n\nconst MAX_BUFFERED_AMOUNT = 64 * 1024\nconst CHANNEL_CLOSING_TIMEOUT = 5 * 1000\n\nexport interface WebRTCDataChannelOptions {\n onMessage: (event: MessageEvent) => void\n onOpen: () => void\n onClose: () => void\n onError: (err: Error) => void\n log: Logger\n}\n\nexport class WebRTCDataChannel {\n public label: string\n private readonly channel: RTCDataChannel\n private readonly closingInterval: NodeJS.Timer\n private open: DeferredPromise\n private readonly log: Logger\n\n constructor (channel: RTCDataChannel, opts: WebRTCDataChannelOptions) {\n this.label = channel.label\n this.open = defer()\n this.channel = channel\n this.channel.binaryType = 'arraybuffer'\n this.log = opts.log\n\n if (typeof this.channel.bufferedAmountLowThreshold === 'number') {\n this.channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT\n }\n\n channel.addEventListener('message', event => {\n opts.onMessage(event)\n })\n channel.addEventListener('bufferedamountlow', () => {\n this.log('stop backpressure: bufferedAmount %d', this.channel.bufferedAmount)\n this.open.resolve()\n })\n channel.addEventListener('open', () => {\n this.open.resolve()\n opts.onOpen()\n })\n channel.addEventListener('close', () => {\n opts.onClose()\n })\n channel.addEventListener('error', event => {\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n if (event.error?.message === 'Transport channel closed') {\n return this.close()\n }\n\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n opts.log.error('channel encounter an error in state \"%s\" message: \"%s\" detail: \"%s', channel.readyState, event.error?.message, event.error?.errorDetail) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n const err = event.error instanceof Error\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n ? event.error\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n : new Error(`datachannel error: ${event.error?.message} ${event.error?.errorDetail}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n\n opts.onError(errCode(err, 'ERR_DATA_CHANNEL'))\n })\n\n // HACK: Chrome will sometimes get stuck in readyState \"closing\", let's check for this condition\n // https://bugs.chromium.org/p/chromium/issues/detail?id=882743\n let isClosing = false\n this.closingInterval = setInterval(() => { // No \"onclosing\" event\n if (channel.readyState === 'closing') {\n if (isClosing) {\n opts.onClose() // closing timed out: equivalent to onclose firing\n }\n isClosing = true\n } else {\n isClosing = false\n }\n }, CHANNEL_CLOSING_TIMEOUT)\n }\n\n async send (data: Uint8Array) {\n await this.open.promise\n\n this.channel.send(data)\n\n if (this.channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {\n this.log('start backpressure: bufferedAmount %d', this.channel.bufferedAmount)\n this.open = defer()\n }\n }\n\n close () {\n clearInterval(this.closingInterval)\n this.channel.close()\n }\n\n get bufferedAmount () {\n return this.channel.bufferedAmount\n }\n}\n", "import { EventEmitter } from '@libp2p/interfaces/events'\nimport errCode from 'err-code'\nimport type { WebRTCPeerEvents, WRTC, Signal, OfferSignal, AnswerSignal, CandidateSignal, RenegotiateSignal, GoodbyeSignal } from './index.js'\nimport type { Logger } from '@libp2p/logger'\n\nexport interface WebRTCHandshakeOptions {\n log: Logger\n peerConnection: RTCPeerConnection\n offerOptions?: RTCOfferOptions\n wrtc: WRTC\n}\n\nexport class WebRTCHandshake extends EventEmitter {\n protected log: Logger\n protected peerConnection: RTCPeerConnection\n protected status: 'idle' | 'negotiating'\n protected wrtc: WRTC\n\n constructor (options: WebRTCHandshakeOptions) {\n super()\n\n this.log = options.log\n this.peerConnection = options.peerConnection\n this.wrtc = options.wrtc\n this.status = 'idle'\n\n this.peerConnection.addEventListener('negotiationneeded', () => {\n this.log('peer connection negotiation needed')\n\n this.handleRenegotiate({ type: 'renegotiate' }).catch(err => {\n this.log.error('could not renegotiate %o', err)\n })\n })\n }\n\n async handleSignal (signal: Signal) {\n this.log('incoming signal \"%s\"', signal.type)\n\n if (signal.type === 'offer') {\n return await this.handleOffer(signal)\n } else if (signal.type === 'answer') {\n return await this.handleAnswer(signal)\n } else if (signal.type === 'candidate') {\n return await this.handleCandidate(signal)\n } else if (signal.type === 'renegotiate') {\n return await this.handleRenegotiate(signal)\n } else if (signal.type === 'goodbye') {\n return await this.handleGoodye(signal)\n } else {\n // @ts-expect-error all types are handled above\n this.log(`Unknown signal type ${signal.type}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n }\n }\n\n async handleOffer (signal: OfferSignal) {}\n async handleAnswer (signal: AnswerSignal) {}\n async handleRenegotiate (signal: RenegotiateSignal) {}\n async handleGoodye (signal: GoodbyeSignal) {\n this.peerConnection.close()\n }\n\n async handleCandidate (signal: CandidateSignal) {\n const iceCandidate = new this.wrtc.RTCIceCandidate(signal.candidate)\n\n try {\n await this.peerConnection.addIceCandidate(iceCandidate)\n } catch (err) {\n if (iceCandidate.address == null || iceCandidate.address.endsWith('.local')) {\n this.log('ignoring unsupported ICE candidate.')\n } else {\n throw errCode(err, 'ERR_ADD_ICE_CANDIDATE')\n }\n }\n }\n}\n", "import { WebRTCPeer } from './peer.js'\nimport { WebRTCHandshake } from './handshake.js'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { WebRTCHandshakeOptions } from './handshake.js'\nimport type { WebRTCReceiverInit, OfferSignal, Signal, CandidateSignal } from './index.js'\n\nconst log = logger('libp2p:webrtc-peer:receiver')\n\nexport class WebRTCReceiver extends WebRTCPeer {\n private readonly handshake: WebRTCReceiverHandshake\n\n constructor (opts: WebRTCReceiverInit = {}) {\n super({\n ...opts,\n logPrefix: 'receiver'\n })\n\n this.handshake = new WebRTCReceiverHandshake({\n log: this.log,\n peerConnection: this.peerConnection,\n wrtc: this.wrtc,\n answerOptions: opts.answerOptions\n })\n\n this.handshake.addEventListener('signal', event => this.dispatchEvent(new CustomEvent('signal', {\n detail: event.detail\n })))\n this.peerConnection.addEventListener('datachannel', (event) => {\n this.handleDataChannelEvent(event)\n })\n }\n\n handleSignal (signal: Signal) {\n this.handshake.handleSignal(signal).catch(err => {\n this.log('error handling signal %o %o', signal, err)\n })\n }\n}\n\ninterface WebRTCReceiverHandshakeOptions extends WebRTCHandshakeOptions {\n answerOptions?: RTCAnswerOptions\n}\n\nclass WebRTCReceiverHandshake extends WebRTCHandshake {\n private readonly options: WebRTCReceiverHandshakeOptions\n private iceCandidates: CandidateSignal[]\n\n constructor (options: WebRTCReceiverHandshakeOptions) {\n super(options)\n\n this.options = options\n this.status = 'idle'\n this.iceCandidates = []\n }\n\n async handleRenegotiate () {\n log.trace('renegotiate')\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: {\n type: 'renegotiate'\n }\n }))\n }\n\n async handleOffer (signal: OfferSignal) {\n await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(signal))\n\n // add any candidates we were sent before the offer arrived\n for (const candidate of this.iceCandidates) {\n await this.handleCandidate(candidate)\n }\n this.iceCandidates = []\n\n const answer = await this.peerConnection.createAnswer(this.options.answerOptions)\n\n await this.peerConnection.setLocalDescription(answer)\n\n log.trace('handle offer', this.peerConnection.localDescription)\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: this.peerConnection.localDescription ?? answer\n }))\n }\n\n async handleCandidate (signal: CandidateSignal) {\n if (this.peerConnection.remoteDescription == null || this.peerConnection.remoteDescription.type == null) {\n // we haven't been sent an offer yet, cache the remote ICE candidates\n this.iceCandidates.push(signal)\n\n return\n }\n\n await super.handleCandidate(signal)\n }\n}\n", "import { WebRTCPeer } from './peer.js'\nimport { WebRTCHandshake } from './handshake.js'\nimport randombytes from 'iso-random-stream/src/random.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { pEvent } from 'p-event'\nimport delay from 'delay'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { WebRTCHandshakeOptions } from './handshake.js'\nimport type { WebRTCInitiatorInit, AnswerSignal, Signal } from './index.js'\n\nconst log = logger('libp2p:webrtc-peer:initator')\n\nconst ICECOMPLETE_TIMEOUT = 1000\n\nexport class WebRTCInitiator extends WebRTCPeer {\n private readonly handshake: WebRTCInitiatorHandshake\n\n constructor (opts: WebRTCInitiatorInit = {}) {\n super({\n ...opts,\n logPrefix: 'initiator'\n })\n\n this.handleDataChannelEvent({\n channel: this.peerConnection.createDataChannel(\n opts.dataChannelLabel ?? uint8ArrayToString(randombytes(20), 'hex').slice(0, 7),\n opts.dataChannelInit\n )\n })\n\n this.handshake = new WebRTCInitiatorHandshake({\n log: this.log,\n peerConnection: this.peerConnection,\n wrtc: this.wrtc,\n offerOptions: opts.offerOptions\n })\n this.handshake.addEventListener('signal', event => {\n this.dispatchEvent(new CustomEvent('signal', { detail: event.detail }))\n })\n }\n\n handleSignal (signal: Signal) {\n this.handshake.handleSignal(signal).catch(err => {\n this.log('error handling signal %o %o', signal, err)\n })\n }\n}\n\ninterface WebRTCInitiatorHandshakeOptions extends WebRTCHandshakeOptions {\n offerOptions?: RTCOfferOptions\n}\n\nclass WebRTCInitiatorHandshake extends WebRTCHandshake {\n private readonly options: WebRTCInitiatorHandshakeOptions\n\n constructor (options: WebRTCInitiatorHandshakeOptions) {\n super(options)\n\n this.options = options\n this.status = 'idle'\n\n this.peerConnection.addEventListener('icecandidate', (event) => {\n if (event.candidate == null) {\n return\n }\n\n const signal = {\n type: 'candidate',\n candidate: {\n candidate: event.candidate.candidate,\n sdpMLineIndex: event.candidate.sdpMLineIndex,\n sdpMid: event.candidate.sdpMid\n }\n }\n\n log.trace('create candidate', signal)\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: signal\n }))\n this.dispatchEvent(new CustomEvent('ice-candidate'))\n })\n }\n\n async handleRenegotiate () {\n if (this.status === 'negotiating') {\n this.log('already negotiating, queueing')\n return\n }\n\n this.status = 'negotiating'\n\n const offer = await this.peerConnection.createOffer(this.options.offerOptions)\n\n await this.peerConnection.setLocalDescription(offer)\n\n // wait for at least one candidate before sending the offer\n await pEvent(this, 'ice-candidate')\n await delay(ICECOMPLETE_TIMEOUT)\n\n log.trace('renegotiate', this.peerConnection.localDescription)\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: this.peerConnection.localDescription ?? offer\n }))\n }\n\n async handleAnswer (signal: AnswerSignal) {\n log.trace('handle answer', signal)\n\n await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(signal))\n this.status = 'idle'\n }\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.on || emitter.addListener || emitter.addEventListener;\n\tconst removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\t\tif (options.filter && !options.filter(value)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = error => {\n\t\t\tcancel();\n\t\t\treject(error);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, options.timeout);\n\t\ttimeout.cancel = cancel;\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\tif (options.filter && !options.filter(value)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport { logger } from '@libp2p/logger'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { WebRTCPeer } from '@libp2p/webrtc-peer'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:webrtc-star:socket')\n\nexport interface ToMultiaddrConnectionOptions extends AbortOptions {\n remoteAddr: Multiaddr\n}\n\n/**\n * Convert a socket into a MultiaddrConnection\n * https://github.com/libp2p/js-libp2p-interfaces/tree/master/src/transport#multiaddrconnection\n */\nexport function toMultiaddrConnection (socket: WebRTCPeer, options: ToMultiaddrConnectionOptions): MultiaddrConnection {\n const { sink, source } = socket\n\n const maConn: MultiaddrConnection = {\n remoteAddr: options.remoteAddr,\n\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(source, options.signal) : source,\n\n timeline: { open: Date.now() },\n\n async close () {\n if (socket.closed) {\n return\n }\n\n const start = Date.now()\n\n // Attempt to end the socket. If it takes longer to close than the\n // timeout, destroy it manually.\n const timeout = setTimeout(() => {\n if (maConn.remoteAddr != null) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing socket to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n }\n\n if (!socket.closed) {\n socket.close().catch(err => {\n log.error('could not close socket', err)\n })\n }\n }, CLOSE_TIMEOUT)\n\n try {\n await socket.close()\n } finally {\n clearTimeout(timeout)\n }\n }\n }\n\n 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 }, {\n once: true\n })\n\n return maConn\n}\n", "import { multiaddr, isName } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport function cleanUrlSIO (ma: Multiaddr) {\n const maStrSplit = ma.toString().split('/')\n const tcpProto = ma.protos()[1].name\n const wsProto = ma.protos()[2].name\n const tcpPort = ma.stringTuples()[1][1]\n\n if (tcpProto !== 'tcp' || (wsProto !== 'ws' && wsProto !== 'wss')) {\n throw new Error(`invalid multiaddr: ${ma.toString()}`)\n }\n\n if (!isName(ma)) {\n return `http://${maStrSplit[2]}:${maStrSplit[4]}`\n }\n\n if (wsProto === 'ws') {\n return `http://${maStrSplit[2]}${tcpPort == null || tcpPort === '80' ? '' : `:${tcpPort}`}`\n }\n\n if (wsProto === 'wss') {\n return `https://${maStrSplit[2]}${tcpPort == null || tcpPort === '443' ? '' : `:${tcpPort}`}`\n }\n\n throw new Error('invalid multiaddr: ' + ma.toString())\n}\n\nexport function cleanMultiaddr (maStr: string) {\n const legacy = '/libp2p-webrtc-star'\n\n if (maStr.startsWith(legacy)) {\n maStr = maStr.substring(legacy.length, maStr.length)\n let ma = multiaddr(maStr)\n const tuppleIPFS = ma.stringTuples().filter((tupple) => {\n return tupple[0] === 421 // ipfs code\n })[0]\n\n if (tuppleIPFS[1] == null) {\n throw new Error('invalid multiaddr: ' + maStr)\n }\n\n ma = ma.decapsulate('p2p')\n ma = ma.encapsulate('/p2p-webrtc-star')\n ma = ma.encapsulate(`/p2p/${tuppleIPFS[1]}`)\n maStr = ma.toString()\n }\n\n return maStr\n}\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString: () => string\n toCID: () => CID\n toBytes: () => Uint8Array\n equals: (other: PeerId | Uint8Array | string) => boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const symbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[symbol])\n}\n", "import { CID } from 'multiformats/cid'\nimport { bases } from 'multiformats/basics'\nimport { base58btc } from 'multiformats/bases/base58'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { Ed25519PeerId, PeerIdType, RSAPeerId, Secp256k1PeerId, symbol } from '@libp2p/interface-peer-id'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\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\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n get [symbol] (): boolean {\n return true\n }\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id: PeerId | Uint8Array | string): boolean {\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\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\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\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\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\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 } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n", "import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface UpgraderOptions {\n skipEncryption?: boolean\n skipProtection?: boolean\n muxerFactory?: StreamMuxerFactory\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n", "import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n", "import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { Transport } from '@libp2p/interface-transport'\nimport { WebRTCStar, WebRTCStarComponents, WebRTCStarInit } from './transport.js'\n\nexport interface WebRTCStarTuple {\n transport: (components: WebRTCStarComponents) => Transport\n discovery: (components?: WebRTCStarComponents) => PeerDiscovery\n}\n\nexport function webRTCStar (init: WebRTCStarInit = {}): WebRTCStarTuple {\n const transport = new WebRTCStar(init)\n\n return {\n transport: (components: WebRTCStarComponents) => {\n transport.peerId = components.peerId\n return transport\n },\n discovery: transport.discovery\n }\n}\n", "import { webRTCStar } from '@libp2p/webrtc-star'\n\nexport function libp2pConfig () {\n const webRtcStar = webRTCStar()\n\n /** @type {import('libp2p').Libp2pOptions} */\n const options = {\n transports: [\n webRtcStar.transport\n ],\n peerDiscovery: [\n webRtcStar.discovery\n ],\n connectionManager: {\n maxParallelDials: 150, // 150 total parallel multiaddr dials\n maxDialsPerPeer: 4, // Allow 4 multiaddrs to be dialed per peer in parallel\n dialTimeout: 10e3, // 10 second dial timeout per peer dial\n autoDial: true\n },\n nat: {\n enabled: false\n }\n }\n\n return options\n}\n", "\n/**\n * Implemented by components that have a lifecycle\n */\nexport interface Startable {\n isStarted: () => boolean\n\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?: () => void | Promise\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?: () => void | Promise\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?: () => void | Promise\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?: () => void | Promise\n}\n\nexport function isStartable (obj: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\nexport async function start (...objs: any[]): Promise {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\nexport async function stop (...objs: any[]): Promise {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes, messages } from './errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './content-routing/utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error module with no types\n} from 'set-delayed-interval'\nimport { setMaxListeners } from 'events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:peer-routing')\n\nexport interface RefreshManagerInit {\n /**\n * Whether to enable the Refresh manager\n */\n enabled?: boolean\n\n /**\n * Boot delay to start the Refresh Manager (in ms)\n */\n bootDelay?: number\n\n /**\n * Interval between each Refresh Manager run (in ms)\n */\n interval?: number\n\n /**\n * How long to let each refresh run (in ms)\n */\n timeout?: number\n}\n\nexport interface PeerRoutingInit {\n routers?: PeerRouting[]\n refreshManager?: RefreshManagerInit\n}\n\nexport interface DefaultPeerRoutingComponents {\n peerId: PeerId\n peerStore: PeerStore\n}\n\nexport class DefaultPeerRouting implements PeerRouting, Startable {\n private readonly components: DefaultPeerRoutingComponents\n private readonly routers: PeerRouting[]\n private readonly refreshManagerInit: RefreshManagerInit\n private timeoutId?: ReturnType\n private started: boolean\n private abortController?: TimeoutController\n\n constructor (components: DefaultPeerRoutingComponents, init: PeerRoutingInit) {\n this.components = components\n this.routers = init.routers ?? []\n this.refreshManagerInit = init.refreshManager ?? {}\n this.started = false\n\n this._findClosestPeersTask = this._findClosestPeersTask.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start peer routing service.\n */\n async start () {\n if (this.started || this.routers.length === 0 || this.timeoutId != null || this.refreshManagerInit.enabled === false) {\n return\n }\n\n this.timeoutId = setDelayedInterval(\n this._findClosestPeersTask, this.refreshManagerInit.interval, this.refreshManagerInit.bootDelay\n )\n\n this.started = true\n }\n\n /**\n * Recurrent task to find closest peers and add their addresses to the Address Book.\n */\n async _findClosestPeersTask () {\n if (this.abortController != null) {\n // we are already running the query\n return\n }\n\n try {\n this.abortController = new TimeoutController(this.refreshManagerInit.timeout ?? 10e3)\n\n // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning\n // appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.abortController.signal)\n } catch {}\n\n // nb getClosestPeers adds the addresses to the address book\n await drain(this.getClosestPeers(this.components.peerId.toBytes(), { signal: this.abortController.signal }))\n } catch (err: any) {\n log.error(err)\n } finally {\n this.abortController?.clear()\n this.abortController = undefined\n }\n }\n\n /**\n * Stop peer routing service.\n */\n async stop () {\n clearDelayedInterval(this.timeoutId)\n\n // abort query if it is in-flight\n this.abortController?.abort()\n\n this.started = false\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: AbortOptions): Promise {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n if (id.toString() === this.components.peerId.toString()) {\n throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF)\n }\n\n const output = await pipe(\n merge(\n ...this.routers.map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n log.error(err)\n }\n })())\n ),\n (source) => filter(source, Boolean),\n (source) => storeAddresses(source, this.components.peerStore),\n async (source) => await first(source)\n )\n\n if (output != null) {\n return output\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.getClosestPeers(key, options))\n ),\n (source) => storeAddresses(source, this.components.peerStore),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n}\n", "export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n DHT_DISABLED = 'DHT is not available',\n PUBSUB_DISABLED = 'PubSub is not available',\n CONN_ENCRYPTION_REQUIRED = 'At least one connection encryption module is required',\n ERR_TRANSPORTS_REQUIRED = 'At least one transport module is required',\n ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',\n NOT_FOUND = 'Not found'\n}\n\nexport enum codes {\n DHT_DISABLED = 'ERR_DHT_DISABLED',\n ERR_PUBSUB_DISABLED = 'ERR_PUBSUB_DISABLED',\n PUBSUB_NOT_STARTED = 'ERR_PUBSUB_NOT_STARTED',\n DHT_NOT_STARTED = 'ERR_DHT_NOT_STARTED',\n CONN_ENCRYPTION_REQUIRED = 'ERR_CONN_ENCRYPTION_REQUIRED',\n ERR_TRANSPORTS_REQUIRED = 'ERR_TRANSPORTS_REQUIRED',\n ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',\n ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',\n ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',\n ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',\n ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',\n ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',\n ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',\n ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',\n ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',\n ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',\n ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',\n ERR_DIALED_SELF = 'ERR_DIALED_SELF',\n ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',\n ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',\n ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',\n ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',\n ERR_INVALID_KEY = 'ERR_INVALID_KEY',\n ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',\n ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',\n ERR_INVALID_PEER = 'ERR_INVALID_PEER',\n ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',\n ERR_NOT_FOUND = 'ERR_NOT_FOUND',\n ERR_TIMEOUT = 'ERR_TIMEOUT',\n ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',\n ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',\n ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',\n ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',\n ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',\n ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',\n ERR_FIND_SELF = 'ERR_FIND_SELF',\n ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',\n ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',\n ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',\n ERR_KEYCHAIN_REQUIRED = 'ERR_KEYCHAIN_REQUIRED',\n ERR_INVALID_CMS = 'ERR_INVALID_CMS',\n ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',\n ERR_NO_KEY = 'ERR_NO_KEY',\n ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',\n ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',\n ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',\n ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',\n ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',\n ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',\n ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',\n ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',\n ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',\n ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',\n ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',\n ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',\n ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',\n ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',\n ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',\n ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',\n ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',\n ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',\n ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',\n ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',\n ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',\n ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS',\n ERR_CONNECTION_DENIED = 'ERR_CONNECTION_DENIED'\n}\n", "import errCode from 'err-code'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport type { Source } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\n/**\n * Store the multiaddrs from every peer in the passed peer store\n */\nexport async function * storeAddresses (source: Source, peerStore: PeerStore) {\n yield * map(source, async (peer) => {\n // ensure we have the addresses for a given peer\n await peerStore.addressBook.add(peer.id, peer.multiaddrs)\n\n return peer\n })\n}\n\n/**\n * Filter peers by unique peer id\n */\nexport function uniquePeers (source: Source) {\n /** @type Set */\n const seen = new Set()\n\n return filter(source, (peer) => {\n // dedupe by peer id\n if (seen.has(peer.id.toString())) {\n return false\n }\n\n seen.add(peer.id.toString())\n\n return true\n })\n}\n\n/**\n * Require at least `min` peers to be yielded from `source`\n */\nexport async function * requirePeers (source: Source, min: number = 1) {\n let seen = 0\n\n for await (const peer of source) {\n seen++\n\n yield peer\n }\n\n if (seen < min) {\n throw errCode(new Error('not found'), 'NOT_FOUND')\n }\n}\n", "import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './utils.js'\nimport drain from 'it-drain'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats/cid'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport interface CompoundContentRoutingComponents {\n peerStore: PeerStore\n dht?: DualDHT\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: CompoundContentRoutingComponents\n\n constructor (components: CompoundContentRoutingComponents, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.findProviders(key, options))\n ),\n (source) => storeAddresses(source, this.components.peerStore),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\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: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n await Promise.all(this.routers.map(async (router) => 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: Uint8Array, value: Uint8Array, options?: AbortOptions) {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.dht\n\n if (dht != null) {\n await drain(dht.put(key, value, options))\n }\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.dht\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, nVals: number, options: AbortOptions) { // eslint-disable-line require-await\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n if (nVals == null || nVals === 0) {\n return\n }\n\n let gotValues = 0\n const dht = this.components.dht\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n yield { from: event.from, val: event.value }\n\n gotValues++\n\n if (gotValues === nVals) {\n break\n }\n }\n }\n }\n\n if (gotValues === 0) {\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n }\n}\n", "import type { AddressManagerEvents } from '@libp2p/interface-address-manager'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { TransportManager } from '@libp2p/interface-transport'\n\nexport interface AddressManagerInit {\n /**\n * Pass an function in this field to override the list of addresses\n * that are announced to the network\n */\n announceFilter?: AddressFilter\n\n /**\n * list of multiaddrs string representation to listen\n */\n listen?: string[]\n\n /**\n * list of multiaddrs string representation to announce\n */\n announce?: string[]\n\n /**\n * list of multiaddrs string representation to never announce\n */\n noAnnounce?: string[]\n}\n\nexport interface DefaultAddressManagerComponents {\n peerId: PeerId\n transportManager: TransportManager\n}\n\n/**\n * A function that takes a list of multiaddrs and returns a list\n * to announce\n */\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\nexport class DefaultAddressManager extends EventEmitter {\n private readonly components: DefaultAddressManagerComponents\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n private readonly listen: string[]\n private readonly announce: Set\n private readonly observed: Set\n private readonly announceFilter: AddressFilter\n\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: DefaultAddressManagerComponents, init: AddressManagerInit) {\n super()\n\n const { listen = [], announce = [] } = init\n\n this.components = components\n this.listen = listen.map(ma => ma.toString())\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.observed = new Set()\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return Array.from(this.observed).map((a) => multiaddr(a))\n }\n\n /**\n * Add peer observed addresses\n * Signal that we have confidence an observed multiaddr is publicly dialable -\n * this will make it appear in the output of getAddresses()\n */\n confirmObservedAddr (addr: Multiaddr): void {\n\n }\n\n /**\n * Signal that we do not have confidence an observed multiaddr is publicly dialable -\n * this will remove it from the output of getObservedAddrs()\n */\n removeObservedAddr (addr: Multiaddr): void {\n\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: string | Multiaddr): void {\n let ma = multiaddr(addr)\n const remotePeer = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (remotePeer != null) {\n const remotePeerId = peerIdFromString(remotePeer)\n\n // use same encoding for comparison\n if (remotePeerId.equals(this.components.peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${this.components.peerId.toString()}`))\n }\n }\n\n const addrString = ma.toString()\n\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\n this.observed.add(addrString)\n this.dispatchEvent(new CustomEvent('change:addresses'))\n }\n\n getAddresses (): Multiaddr[] {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString())\n\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\n addrs = addrs.concat(this.getObservedAddrs().map(ma => ma.toString()))\n\n // dedupe multiaddrs\n const addrSet = new Set(addrs)\n\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\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`)\n })\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport mergeOptions from 'merge-options'\nimport { LatencyMonitor, SummaryObject } from './latency-monitor.js'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { codes } from '../errors.js'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { setMaxListeners } from 'events'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { ConnectionManager, ConnectionManagerEvents, Dialer } from '@libp2p/interface-connection-manager'\nimport * as STATUS from '@libp2p/interface-connection/status'\nimport type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'\nimport { multiaddr, Multiaddr, Resolver } from '@multiformats/multiaddr'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'\nimport { RateLimiterMemory } from 'rate-limiter-flexible'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { Upgrader } from '@libp2p/interface-transport'\nimport { getPeerAddress } from '../get-peer.js'\n\nconst log = logger('libp2p:connection-manager')\n\nexport interface ConnectionManagerConfig {\n /**\n * The maximum number of connections libp2p is willing to have before it starts disconnecting. Defaults to `Infinity`\n */\n maxConnections: number\n\n /**\n * The minimum number of connections below which libp2p not activate preemptive disconnections. Defaults to `0`.\n */\n minConnections: number\n\n /**\n * Sets the maximum event loop delay (measured in milliseconds) this node is willing to endure before it starts disconnecting peers. Defaults to `Infinity`.\n */\n maxEventLoopDelay?: number\n\n /**\n * Sets the poll interval (in milliseconds) for assessing the current state and determining if this peer needs to force a disconnect. Defaults to `2000` (2 seconds).\n */\n pollInterval?: number\n\n /**\n * If true, try to connect to all discovered peers up to the connection manager limit\n */\n autoDial?: boolean\n\n /**\n * How long to wait between attempting to keep our number of concurrent connections\n * above minConnections\n */\n autoDialInterval: number\n\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n */\n dialTimeout?: number\n\n /**\n * When a new inbound connection is opened, the upgrade process (e.g. protect,\n * encrypt, multiplex etc) must complete within this number of ms.\n */\n inboundUpgradeTimeout: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n\n /**\n * On startup we try to dial any peer that has previously been\n * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)\n */\n startupReconnectTimeout?: number\n\n /**\n * A list of multiaddrs that will always be allowed (except if they are in the\n * deny list) to open connections to this node even if we've reached maxConnections\n */\n allow?: string[]\n\n /**\n * A list of multiaddrs that will never be allowed to open connections to\n * this node under any circumstances\n */\n deny?: string[]\n\n /**\n * If more than this many connections are opened per second by a single\n * host, reject subsequent connections\n */\n inboundConnectionThreshold?: number\n\n /**\n * The maximum number of parallel incoming connections allowed that have yet to\n * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc\n */\n maxIncomingPendingConnections?: number\n}\n\nconst defaultOptions: Partial = {\n maxConnections: Infinity,\n minConnections: 0,\n maxEventLoopDelay: Infinity,\n pollInterval: 2000,\n autoDialInterval: 10000,\n inboundConnectionThreshold: 5,\n maxIncomingPendingConnections: 10\n}\n\nconst STARTUP_RECONNECT_TIMEOUT = 60000\n\nexport interface DefaultConnectionManagerComponents {\n peerId: PeerId\n metrics?: Metrics\n upgrader: Upgrader\n peerStore: PeerStore\n dialer: Dialer\n}\n\nexport type ConnectionManagerInit = ConnectionManagerConfig\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager extends EventEmitter implements ConnectionManager, Startable {\n private readonly components: DefaultConnectionManagerComponents\n private readonly opts: ConnectionManagerInit\n private readonly connections: Map\n private started: boolean\n private readonly latencyMonitor?: LatencyMonitor\n private readonly startupReconnectTimeout: number\n private connectOnStartupController?: TimeoutController\n private readonly dialTimeout: number\n private readonly allow: Multiaddr[]\n private readonly deny: Multiaddr[]\n private readonly inboundConnectionRateLimiter: RateLimiterMemory\n private incomingPendingConnections: number\n\n constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerConfig) {\n super()\n\n this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n\n if (this.opts.maxConnections < this.opts.minConnections) {\n throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log('options: %o', this.opts)\n\n this.components = components\n\n /**\n * Map of connections per peer\n */\n this.connections = new Map()\n\n this.started = false\n\n if (init.maxEventLoopDelay != null && init.maxEventLoopDelay > 0 && init.maxEventLoopDelay !== Infinity) {\n this.latencyMonitor = new LatencyMonitor({\n latencyCheckIntervalMs: init.pollInterval,\n dataEmitIntervalMs: init.pollInterval\n })\n }\n\n try {\n // This emitter gets listened to a lot\n setMaxListeners?.(Infinity, this)\n } catch {}\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n\n this.startupReconnectTimeout = init.startupReconnectTimeout ?? STARTUP_RECONNECT_TIMEOUT\n this.dialTimeout = init.dialTimeout ?? 30000\n\n this.allow = (init.allow ?? []).map(ma => multiaddr(ma))\n this.deny = (init.deny ?? []).map(ma => multiaddr(ma))\n\n this.inboundConnectionRateLimiter = new RateLimiterMemory({\n points: this.opts.inboundConnectionThreshold,\n duration: 1\n })\n\n this.incomingPendingConnections = 0\n }\n\n isStarted () {\n return this.started\n }\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.components.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.stat.direction === 'inbound') {\n metric.inbound++\n } else {\n metric.outbound++\n }\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.components.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric: Record = {}\n\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.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.components.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n\n // latency monitor\n this.latencyMonitor?.start()\n this._onLatencyMeasure = this._onLatencyMeasure.bind(this)\n this.latencyMonitor?.addEventListener('data', this._onLatencyMeasure)\n\n this.started = true\n log('started')\n }\n\n async afterStart () {\n this.components.upgrader.addEventListener('connection', this.onConnect)\n this.components.upgrader.addEventListener('connectionEnd', this.onDisconnect)\n\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: PeerId[] = []\n\n for (const peer of await this.components.peerStore.all()) {\n const tags = await this.components.peerStore.getTags(peer.id)\n const hasKeepAlive = tags.filter(tag => tag.name === KEEP_ALIVE).length > 0\n\n if (hasKeepAlive) {\n keepAlivePeers.push(peer.id)\n }\n }\n\n this.connectOnStartupController?.clear()\n this.connectOnStartupController = new TimeoutController(this.startupReconnectTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.connectOnStartupController.signal)\n } catch {}\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.openConnection(peer, {\n signal: this.connectOnStartupController?.signal\n })\n .catch(err => {\n log.error(err)\n })\n })\n )\n })\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n this.connectOnStartupController?.clear()\n })\n }\n\n async beforeStop () {\n // if we are still dialing KEEP_ALIVE peers, abort those dials\n this.connectOnStartupController?.abort()\n this.components.upgrader.removeEventListener('connection', this.onConnect)\n this.components.upgrader.removeEventListener('connectionEnd', this.onDisconnect)\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop () {\n this.latencyMonitor?.removeEventListener('data', this._onLatencyMeasure)\n this.latencyMonitor?.stop()\n\n this.started = false\n await this._close()\n log('stopped')\n }\n\n /**\n * Cleans up the connections\n */\n async _close () {\n // Close all connections we're tracking\n const tasks: Array> = []\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 } catch (err) {\n log.error(err)\n }\n })())\n }\n }\n\n log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n }\n\n onConnect (evt: CustomEvent) {\n void this._onConnect(evt).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\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\n const peerId = connection.remotePeer\n const peerIdStr = peerId.toString()\n const storedConns = this.connections.get(peerIdStr)\n\n if (storedConns != null) {\n storedConns.push(connection)\n } else {\n this.connections.set(peerIdStr, [connection])\n }\n\n if (peerId.publicKey != null) {\n await this.components.peerStore.keyBook.set(peerId, peerId.publicKey)\n }\n\n const numConnections = this.getConnections().length\n const toPrune = numConnections - this.opts.maxConnections\n\n await this._checkMaxLimit('maxConnections', numConnections, toPrune)\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: connection }))\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return\n }\n\n const peerId = connection.remotePeer.toString()\n let storedConn = this.connections.get(peerId)\n\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id)\n this.connections.set(peerId, storedConn)\n } else if (storedConn != null) {\n this.connections.delete(peerId)\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: connection }))\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId.toString()) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { peerId, multiaddr } = getPeerAddress(peerIdOrMultiaddr)\n\n if (peerId == null && multiaddr == null) {\n throw errCode(new TypeError('Can only open connections to PeerIds or Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n if (peerId != null) {\n log('dial to', peerId)\n\n const existingConnections = this.getConnections(peerId)\n\n if (existingConnections.length > 0) {\n log('had an existing connection to %p', peerId)\n\n return existingConnections[0]\n }\n }\n\n let timeoutController: TimeoutController | undefined\n\n if (options?.signal == null) {\n timeoutController = new TimeoutController(this.dialTimeout)\n options.signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n const connection = await this.components.dialer.dial(peerIdOrMultiaddr, options)\n let peerConnections = this.connections.get(connection.remotePeer.toString())\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(connection.remotePeer.toString(), peerConnections)\n }\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\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n }\n }\n\n async closeConnections (peerId: PeerId): Promise {\n const connections = this.connections.get(peerId.toString()) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n return await connection.close()\n })\n )\n }\n\n /**\n * Get all open connections with a peer\n */\n getAll (peerId: PeerId): Connection[] {\n if (!isPeerId(peerId)) {\n throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const id = peerId.toString()\n const connections = this.connections.get(id)\n\n // Return all open connections\n if (connections != null) {\n return connections.filter(connection => connection.stat.status === STATUS.OPEN)\n }\n\n return []\n }\n\n /**\n * If the event loop is slow, maybe close a connection\n */\n _onLatencyMeasure (evt: CustomEvent) {\n const { detail: summary } = evt\n\n this._checkMaxLimit('maxEventLoopDelay', summary.avgMs, 1)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * If the `value` of `name` has exceeded its limit, maybe close a connection\n */\n async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {\n const limit = this.opts[name]\n\n if (limit == null) {\n log.trace('limit %s was not set so it cannot be applied', name)\n return\n }\n\n log.trace('checking limit of %s. current value: %d of %d', name, value, limit)\n if (value > limit) {\n log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.peerId, name, value, limit, toPrune)\n await this._pruneConnections(toPrune)\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 _pruneConnections (toPrune: number) {\n const connections = this.getConnections()\n const peerValues = new PeerMap()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n const tags = await this.components.peerStore.getTags(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, tags.reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\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\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n // if the peers have an equal tag value then we want to close short-lived connections first\n const connectionALifespan = a.stat.timeline.open\n const connectionBLifespan = b.stat.timeline.open\n\n if (connectionALifespan < connectionBLifespan) {\n return 1\n }\n\n if (connectionALifespan > connectionBLifespan) {\n return -1\n }\n\n return 0\n })\n\n // close some connections\n const toClose = []\n\n for (const connection of sortedConnections) {\n log('too many connections open - closing a connection to %p', connection.remotePeer)\n toClose.push(connection)\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n\n // TODO: should not need to invoke this manually\n this.onDisconnect(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n })\n )\n }\n\n async acceptIncomingConnection (maConn: MultiaddrConnection): Promise {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString())\n })\n\n if (denyConnection) {\n log('connection from %s refused - connection remote address was in deny list', maConn.remoteAddr)\n return false\n }\n\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString())\n })\n\n if (allowConnection) {\n this.incomingPendingConnections++\n\n return true\n }\n\n // check pending connections\n if (this.incomingPendingConnections === this.opts.maxIncomingPendingConnections) {\n log('connection from %s refused - incomingPendingConnections exceeded by peer %s', maConn.remoteAddr)\n return false\n }\n\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address\n\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1)\n } catch {\n log('connection from %s refused - inboundConnectionThreshold exceeded by host %s', host, maConn.remoteAddr)\n return false\n }\n }\n\n if (this.getConnections().length < this.opts.maxConnections) {\n this.incomingPendingConnections++\n\n return true\n }\n\n log('connection from %s refused - maxConnections exceeded', maConn.remoteAddr)\n return false\n }\n\n afterUpgradeInbound () {\n this.incomingPendingConnections--\n }\n}\n", "/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor:visibility-change-emitter')\n\ninterface VisibilityChangeEmitterEvents {\n 'visibilityChange': CustomEvent\n}\n\ntype Hidden = 'hidden' | 'mozHidden' | 'msHidden' | 'webkitHidden'\n\n/**\n * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.\n *\n * Warning: This does not work on all browsers, but should work on all modern browsers\n *\n * @example\n *\n * const myVisibilityEmitter = new VisibilityChangeEmitter();\n *\n * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {\n * if ( pageInFocus ){\n * // Page is in focus\n * console.log('In focus');\n * }\n * else {\n * // Page is blurred\n * console.log('Out of focus');\n * }\n * });\n * // To access the visibility state directly, call:\n * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());\n */\nexport class VisibilityChangeEmitter extends EventEmitter {\n private hidden: Hidden\n private visibilityChange: string\n\n constructor () {\n super()\n\n this.hidden = 'hidden'\n this.visibilityChange = 'visibilityChange'\n\n if (globalThis.document != null) {\n this._initializeVisibilityVarNames()\n this._addVisibilityChangeListener()\n }\n }\n\n /**\n * document.hidden and document.visibilityChange are the two variables we need to check for;\n * Since these variables are named differently in different browsers, this function sets\n * the appropriate name based on the browser being used. Once executed, tha actual names of\n * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange\n * respectively\n *\n * @private\n */\n _initializeVisibilityVarNames () {\n let hidden: Hidden = 'hidden'\n let visibilityChange = 'visibilitychange'\n\n if (typeof globalThis.document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support\n hidden = 'hidden'\n visibilityChange = 'visibilitychange'\n // @ts-expect-error mozHidden is a non-standard field name\n } else if (typeof globalThis.document.mozHidden !== 'undefined') {\n hidden = 'mozHidden'\n visibilityChange = 'mozvisibilitychange'\n // @ts-expect-error msHidden is a non-standard field name\n } else if (typeof globalThis.document.msHidden !== 'undefined') {\n hidden = 'msHidden'\n visibilityChange = 'msvisibilitychange'\n // @ts-expect-error webkitHidden is a non-standard field name\n } else if (typeof globalThis.document.webkitHidden !== 'undefined') {\n hidden = 'webkitHidden'\n visibilityChange = 'webkitvisibilitychange'\n }\n\n this.hidden = hidden\n this.visibilityChange = visibilityChange\n }\n\n /**\n * Adds an event listener on the document that listens to changes in document.visibilityChange\n * (or whatever name by which the visibilityChange variable is known in the browser)\n *\n * @private\n */\n _addVisibilityChangeListener () {\n // @ts-expect-error cannot index document object with string key\n if (typeof globalThis.document.addEventListener === 'undefined' || typeof document[this.hidden] === 'undefined') {\n log('Checking page visibility requires a browser that supports the Page Visibility API.')\n } else {\n // Handle page visibility change\n globalThis.document.addEventListener(this.visibilityChange, this._handleVisibilityChange.bind(this), false)\n }\n }\n\n /**\n * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and\n * ```undefined``` if the page visibility API is not supported by the browser.\n */\n isVisible () {\n // @ts-expect-error cannot index document object with string key\n if (this.hidden === undefined || document[this.hidden] === undefined) {\n return undefined\n }\n\n // @ts-expect-error cannot index document object with string key\n return document[this.hidden] == null\n }\n\n /**\n * The function that is called when document.visibilityChange has changed\n * It emits an event called visibilityChange and sends the value of document.hidden as a\n * parameter\n *\n * @private\n */\n _handleVisibilityChange () {\n // @ts-expect-error cannot index document object with string key\n const visible = globalThis.document[this.hidden] === false\n log(visible ? 'Page Visible' : 'Page Hidden')\n\n // Emit the event\n this.dispatchEvent(new CustomEvent('visibilityChange', {\n detail: visible\n }))\n }\n}\n", "/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { VisibilityChangeEmitter } from './visibility-change-emitter.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor')\n\nexport interface LatencyMonitorEvents {\n 'data': CustomEvent\n}\n\nexport interface LatencyMonitorInit {\n /**\n * How often to add a latency check event (ms)\n */\n latencyCheckIntervalMs?: number\n\n /**\n * How often to summarize latency check events. null or 0 disables event firing\n */\n dataEmitIntervalMs?: number\n\n /**\n * What cb-style async function to use\n */\n asyncTestFn?: (cb: () => void) => void\n\n /**\n * What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.\n */\n latencyRandomPercentage?: number\n}\n\nexport interface SummaryObject {\n /**\n * How many events were called\n */\n events: number\n\n /**\n * What was the min time for a cb to be called\n */\n minMs: number\n\n /**\n * What was the max time for a cb to be called\n */\n maxMs: number\n\n /**\n * What was the average time for a cb to be called\n */\n avgMs: number\n\n /**\n * How long this interval was in ms\n */\n lengthMs: number\n}\n\ninterface LatencyData {\n startTime: number\n events: number\n minMs: number\n maxMs: number\n totalMs: number\n}\n\n/**\n * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling\n * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.\n * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.\n *\n * @extends {EventEmitter}\n *\n * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop\n * and timing how long it takes to get back.\n *\n * @example\n * const monitor = new LatencyMonitor();\n * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));\n *\n * @example\n * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});\n * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));\n */\nexport class LatencyMonitor extends EventEmitter {\n private readonly latencyCheckIntervalMs: number\n private readonly latencyRandomPercentage: number\n private readonly latencyCheckMultiply: number\n private readonly latencyCheckSubtract: number\n private readonly dataEmitIntervalMs?: number\n private readonly asyncTestFn?: (cb: () => void) => void\n\n private readonly now: (num?: any) => any\n private readonly getDeltaMS: (num: number) => number\n private visibilityChangeEmitter?: VisibilityChangeEmitter\n private latencyData: LatencyData\n private checkLatencyID?: NodeJS.Timeout\n private emitIntervalID?: NodeJS.Timeout\n\n constructor (init: LatencyMonitorInit = {}) {\n super()\n\n const { latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = init\n\n // 0 isn't valid here, so its ok to use ||\n this.latencyCheckIntervalMs = latencyCheckIntervalMs ?? 500 // 0.5s\n this.latencyRandomPercentage = latencyRandomPercentage ?? 10\n this.latencyCheckMultiply = 2 * (this.latencyRandomPercentage / 100.0) * this.latencyCheckIntervalMs\n this.latencyCheckSubtract = this.latencyCheckMultiply / 2\n\n this.dataEmitIntervalMs = (dataEmitIntervalMs === null || dataEmitIntervalMs === 0)\n ? undefined\n : dataEmitIntervalMs ?? 5 * 1000 // 5s\n log('latencyCheckIntervalMs: %s dataEmitIntervalMs: %s',\n this.latencyCheckIntervalMs, this.dataEmitIntervalMs)\n if (this.dataEmitIntervalMs != null) {\n log('Expecting ~%s events per summary', this.latencyCheckIntervalMs / this.dataEmitIntervalMs)\n } else {\n log('Not emitting summaries')\n }\n\n this.asyncTestFn = asyncTestFn // If there is no asyncFn, we measure latency\n\n // If process: use high resolution timer\n if (globalThis.process?.hrtime != null) {\n log('Using process.hrtime for timing')\n this.now = globalThis.process.hrtime // eslint-disable-line no-undef\n this.getDeltaMS = (startTime) => {\n const hrtime = this.now(startTime)\n return (hrtime[0] * 1000) + (hrtime[1] / 1000000)\n }\n // Let's try for a timer that only monotonically increases\n } else if (typeof window !== 'undefined' && window.performance?.now != null) {\n log('Using performance.now for timing')\n this.now = window.performance.now.bind(window.performance)\n this.getDeltaMS = (startTime) => Math.round(this.now() - startTime)\n } else {\n log('Using Date.now for timing')\n this.now = Date.now\n this.getDeltaMS = (startTime) => this.now() - startTime\n }\n\n this.latencyData = this.initLatencyData()\n }\n\n start () {\n // We check for isBrowser because of browsers set max rates of timeouts when a page is hidden,\n // so we fall back to another library\n // See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs\n if (isBrowser()) {\n this.visibilityChangeEmitter = new VisibilityChangeEmitter()\n\n this.visibilityChangeEmitter.addEventListener('visibilityChange', (evt) => {\n const { detail: pageInFocus } = evt\n\n if (pageInFocus) {\n this._startTimers()\n } else {\n this._emitSummary()\n this._stopTimers()\n }\n })\n }\n\n if (this.visibilityChangeEmitter?.isVisible() === true) {\n this._startTimers()\n }\n }\n\n stop () {\n this._stopTimers()\n }\n\n /**\n * Start internal timers\n *\n * @private\n */\n _startTimers () {\n // Timer already started, ignore this\n if (this.checkLatencyID != null) {\n return\n }\n\n this.checkLatency()\n\n if (this.dataEmitIntervalMs != null) {\n this.emitIntervalID = setInterval(() => this._emitSummary(), this.dataEmitIntervalMs)\n if (typeof this.emitIntervalID.unref === 'function') {\n this.emitIntervalID.unref() // Doesn't block exit\n }\n }\n }\n\n /**\n * Stop internal timers\n *\n * @private\n */\n _stopTimers () {\n if (this.checkLatencyID != null) {\n clearTimeout(this.checkLatencyID)\n this.checkLatencyID = undefined\n }\n if (this.emitIntervalID != null) {\n clearInterval(this.emitIntervalID)\n this.emitIntervalID = undefined\n }\n }\n\n /**\n * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show\n *\n * @private\n */\n _emitSummary () {\n const summary = this.getSummary()\n if (summary.events > 0) {\n this.dispatchEvent(new CustomEvent('data', {\n detail: summary\n }))\n }\n }\n\n /**\n * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,\n * it will not count for this time period\n */\n getSummary (): SummaryObject {\n // We might want to adjust for the number of expected events\n // Example: first 1 event it comes back, then such a long blocker that the next emit check comes\n // Then this fires - looks like no latency!!\n const latency = {\n events: this.latencyData.events,\n minMs: this.latencyData.minMs,\n maxMs: this.latencyData.maxMs,\n avgMs: this.latencyData.events > 0\n ? this.latencyData.totalMs / this.latencyData.events\n : Number.POSITIVE_INFINITY,\n lengthMs: this.getDeltaMS(this.latencyData.startTime)\n }\n this.latencyData = this.initLatencyData() // Clear\n\n log.trace('Summary: %O', latency)\n return latency\n }\n\n /**\n * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found,\n * it will simply report on event loop latency.\n */\n checkLatency () {\n // Randomness is needed to avoid alignment by accident to regular things in the event loop\n const randomness = (Math.random() * this.latencyCheckMultiply) - this.latencyCheckSubtract\n\n // We use this to ensure that in case some overlap somehow, we don't take the wrong startTime/offset\n const localData = {\n deltaOffset: Math.ceil(this.latencyCheckIntervalMs + randomness),\n startTime: this.now()\n }\n\n const cb = () => {\n // We are already stopped, ignore this datapoint\n if (this.checkLatencyID == null) {\n return\n }\n const deltaMS = this.getDeltaMS(localData.startTime) - localData.deltaOffset\n this.checkLatency() // Start again ASAP\n\n // Add the data point. If this gets complex, refactor it\n this.latencyData.events++\n this.latencyData.minMs = Math.min(this.latencyData.minMs, deltaMS)\n this.latencyData.maxMs = Math.max(this.latencyData.maxMs, deltaMS)\n this.latencyData.totalMs += deltaMS\n log.trace('MS: %s Data: %O', deltaMS, this.latencyData)\n }\n log.trace('localData: %O', localData)\n\n this.checkLatencyID = setTimeout(() => {\n // This gets rid of including event loop\n if (this.asyncTestFn != null) {\n // Clear timing related things\n localData.deltaOffset = 0\n localData.startTime = this.now()\n this.asyncTestFn(cb)\n } else {\n // setTimeout is not more accurate than 1ms, so this will ensure positive numbers. Add 1 to emitted data to remove.\n // This is not the best, but for now it'll be just fine. This isn't meant to be sub ms accurate.\n localData.deltaOffset -= 1\n // If there is no function to test, we mean check latency which is a special case that is really cb => cb()\n // We avoid that for the few extra function all overheads. Also, we want to keep the timers different\n cb()\n }\n }, localData.deltaOffset)\n\n if (typeof this.checkLatencyID.unref === 'function') {\n this.checkLatencyID.unref() // Doesn't block exit\n }\n }\n\n initLatencyData (): LatencyData {\n return {\n startTime: this.now(),\n minMs: Number.POSITIVE_INFINITY,\n maxMs: Number.NEGATIVE_INFINITY,\n events: 0,\n totalMs: 0\n }\n }\n}\n\nfunction isBrowser () {\n return typeof globalThis.window !== 'undefined'\n}\n", "\nexport const OPEN = 'OPEN'\nexport const CLOSING = 'CLOSING'\nexport const CLOSED = 'CLOSED'\n", "\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\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 * ```JavaScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator<[PeerId, T]> {\n return this.entries()\n }\n\n clear (): void {\n this.map.clear()\n }\n\n delete (peer: PeerId): void {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T): void {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values (): IterableIterator {\n return this.map.values()\n }\n\n get size (): number {\n return this.map.size\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\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 * ```JavaScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as list entries because list 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 * ```JavaScript\n * import { peerList } from '@libp2p/peer-collections'\n *\n * const list = peerList()\n * list.push(peerId)\n * ```\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList | Iterable) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList): PeerList {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]): void {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]): number {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length (): number {\n return this.list.length\n }\n}\n", "\nexport const KEEP_ALIVE = 'keep-alive'\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr\n */\nexport function getPeerAddress (peer: PeerId | Multiaddr): { peerId?: PeerId, multiaddr?: Multiaddr } {\n if (isPeerId(peer)) {\n return {\n peerId: peer\n }\n }\n\n if (isMultiaddr(peer)) {\n const peerId = peer.getPeerId()\n\n return {\n multiaddr: peer,\n peerId: peerId == null ? undefined : peerIdFromString(peerId)\n }\n }\n\n throw errCode(\n new Error(`${peer} is not a PeerId or a Multiaddr`), // eslint-disable-line @typescript-eslint/restrict-template-expressions\n codes.ERR_INVALID_MULTIADDR\n )\n}\n", "import { logger } from '@libp2p/logger'\nimport mergeOptions from 'merge-options'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:connection-manager:auto-dialler')\n\nexport interface AutoDiallerInit {\n /**\n * Should preemptively guarantee connections are above the low watermark\n */\n enabled?: boolean\n\n /**\n * The minimum number of connections to avoid pruning\n */\n minConnections?: number\n\n /**\n * How often, in milliseconds, it should preemptively guarantee connections are above the low watermark\n */\n autoDialInterval?: number\n}\n\nexport interface AutoDiallerComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n peerStore: PeerStore\n}\n\nconst defaultOptions: Partial = {\n enabled: true,\n minConnections: 0,\n autoDialInterval: 10000\n}\n\nexport class AutoDialler implements Startable {\n private readonly components: AutoDiallerComponents\n private readonly options: Required\n private running: boolean\n private autoDialTimeout?: ReturnType\n\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 wether we know their keys and protocols.\n */\n constructor (components: AutoDiallerComponents, init: AutoDiallerInit) {\n this.components = components\n this.options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n this.running = false\n this._autoDial = this._autoDial.bind(this)\n\n log('options: %j', this.options)\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Starts the auto dialer\n */\n async start () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = true\n\n void this._autoDial().catch(err => {\n log.error('could start autodial', err)\n })\n\n log('started')\n }\n\n /**\n * Stops the auto dialler\n */\n async stop () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = false\n\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n log('stopped')\n }\n\n async _autoDial () {\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n const minConnections = this.options.minConnections\n\n // Already has enough connections\n if (this.components.connectionManager.getConnections().length >= minConnections) {\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n\n return\n }\n\n // Sort peers on whether we know protocols or public keys for them\n const allPeers = await this.components.peerStore.all()\n\n const peers = await pipe(\n // shuffle the peers\n allPeers.sort(() => Math.random() > 0.5 ? 1 : -1),\n (source) => filter(source, (peer) => !peer.id.equals(this.components.peerId)),\n (source) => sort(source, (a, b) => {\n if (b.protocols.length > a.protocols.length) {\n return 1\n } else if (b.id.publicKey != null && a.id.publicKey == null) {\n return 1\n }\n return -1\n }),\n async (source) => await all(source)\n )\n\n for (let i = 0; this.running && i < peers.length && this.components.connectionManager.getConnections().length < minConnections; i++) {\n // Connection Manager was stopped during async dial\n if (!this.running) {\n return\n }\n\n const peer = peers[i]\n\n if (this.components.connectionManager.getConnections(peer.id).length === 0) {\n log('connecting to a peerStore stored peer %p', peer.id)\n try {\n await this.components.connectionManager.openConnection(peer.id)\n } catch (err: any) {\n log.error('could not connect to peerStore stored peer', err)\n }\n }\n }\n\n // Connection Manager was stopped\n if (!this.running) {\n return\n }\n\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay as CircuitPB } from './pb/index.js'\nimport { codes } from '../errors.js'\nimport { streamToMaConnection } from '@libp2p/utils/stream-to-ma-conn'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { createListener } from './listener.js'\nimport { handleCanHop, handleHop, hop } from './circuit/hop.js'\nimport { handleStop } from './circuit/stop.js'\nimport { StreamHandler } from './circuit/stream-handler.js'\nimport { symbol, Upgrader } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { RelayConfig } from './index.js'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:circuit')\n\nexport interface CircuitComponents {\n peerId: PeerId\n peerStore: PeerStore\n registrar: Registrar\n connectionManager: ConnectionManager\n upgrader: Upgrader\n addressManager: AddressManager\n}\n\nexport class Circuit implements Transport, Startable {\n private handler?: ConnectionHandler\n private readonly components: CircuitComponents\n private readonly _init: RelayConfig\n private _started: boolean\n\n constructor (components: CircuitComponents, init: RelayConfig) {\n this._init = init\n this.components = components\n this._started = false\n }\n\n isStarted () {\n return this._started\n }\n\n async start (): Promise {\n if (this._started) {\n return\n }\n\n this._started = true\n\n await this.components.registrar.handle(RELAY_CODEC, (data) => {\n void this._onProtocol(data).catch(err => {\n log.error(err)\n })\n }, { ...this._init })\n .catch(err => {\n log.error(err)\n })\n }\n\n async stop () {\n await this.components.registrar.unhandle(RELAY_CODEC)\n }\n\n hopEnabled () {\n return true\n }\n\n hopActive () {\n return true\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return 'libp2p/circuit-relay-v1'\n }\n\n async _onProtocol (data: IncomingStreamData) {\n const { connection, stream } = data\n const controller = new TimeoutController(this._init.hop.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n try {\n const source = abortableDuplex(stream, controller.signal)\n const streamHandler = new StreamHandler({\n stream: {\n ...stream,\n ...source\n }\n })\n const request = await streamHandler.read()\n\n if (request == null) {\n log('request was invalid, could not read from stream')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n\n let virtualConnection: Duplex | undefined\n\n switch (request.type) {\n case CircuitPB.Type.CAN_HOP: {\n log('received CAN_HOP request from %p', connection.remotePeer)\n await handleCanHop({ circuit: this, connection, streamHandler })\n break\n }\n case CircuitPB.Type.HOP: {\n log('received HOP request from %p', connection.remotePeer)\n await handleHop({\n connection,\n request,\n streamHandler,\n circuit: this,\n connectionManager: this.components.connectionManager\n })\n break\n }\n case CircuitPB.Type.STOP: {\n log('received STOP request from %p', connection.remotePeer)\n virtualConnection = await handleStop({\n connection,\n request,\n streamHandler\n })\n break\n }\n default: {\n log('Request of type %s not supported', request.type)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n }\n\n if (virtualConnection != null) {\n const remoteAddr = connection.remoteAddr\n .encapsulate('/p2p-circuit')\n .encapsulate(multiaddr(request.dstPeer?.addrs[0]))\n const localAddr = multiaddr(request.srcPeer?.addrs[0])\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr,\n localAddr\n })\n const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'\n log('new %s connection %s', type, maConn.remoteAddr)\n\n const conn = await this.components.upgrader.upgradeInbound(maConn)\n log('%s connection %s upgraded', type, maConn.remoteAddr)\n\n if (this.handler != null) {\n this.handler(conn)\n }\n }\n } finally {\n controller.clear()\n }\n }\n\n /**\n * Dial a peer over a relay\n */\n async dial (ma: Multiaddr, options: AbortOptions = {}): Promise {\n // Check the multiaddr to see if it contains a relay and a destination peer\n const addrs = ma.toString().split('/p2p-circuit')\n const relayAddr = multiaddr(addrs[0])\n const destinationAddr = multiaddr(addrs[addrs.length - 1])\n const relayId = relayAddr.getPeerId()\n const destinationId = destinationAddr.getPeerId()\n\n if (relayId == null || destinationId == null) {\n const errMsg = 'Circuit relay dial failed as addresses did not have peer id'\n log.error(errMsg)\n throw errCode(new Error(errMsg), codes.ERR_RELAYED_DIAL)\n }\n\n const relayPeer = peerIdFromString(relayId)\n const destinationPeer = peerIdFromString(destinationId)\n\n let disconnectOnFailure = false\n const relayConnections = this.components.connectionManager.getConnections(relayPeer)\n let relayConnection = relayConnections[0]\n\n if (relayConnection == null) {\n await this.components.peerStore.addressBook.add(relayPeer, [relayAddr])\n relayConnection = await this.components.connectionManager.openConnection(relayPeer, options)\n disconnectOnFailure = true\n }\n\n try {\n const virtualConnection = await hop({\n ...options,\n connection: relayConnection,\n request: {\n type: CircuitPB.Type.HOP,\n srcPeer: {\n id: this.components.peerId.toBytes(),\n addrs: this.components.addressManager.getAddresses().map(addr => addr.bytes)\n },\n dstPeer: {\n id: destinationPeer.toBytes(),\n addrs: [multiaddr(destinationAddr).bytes]\n }\n }\n })\n\n const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`)\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr: ma,\n localAddr\n })\n log('new outbound connection %s', maConn.remoteAddr)\n\n return await this.components.upgrader.upgradeOutbound(maConn)\n } catch (err: any) {\n log.error('Circuit relay dial failed', err)\n disconnectOnFailure && await relayConnection.close()\n throw err\n }\n }\n\n /**\n * Create a listener\n */\n createListener (options: CreateListenerOptions): Listener {\n // Called on successful HOP and STOP requests\n this.handler = options.handler\n\n return createListener({\n connectionManager: this.components.connectionManager,\n peerStore: this.components.peerStore\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can dial on\n *\n * @param {Multiaddr[]} multiaddrs\n * @returns {Multiaddr[]}\n */\n filter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return mafmt.Circuit.matches(ma)\n })\n }\n}\n", "// @ts-expect-error no types\nimport ReaderClass from 'protobufjs/src/reader.js'\n// @ts-expect-error no types\nimport ReaderBufferClass from 'protobufjs/src/reader_buffer.js'\n// @ts-expect-error no types\nimport WriterClass from 'protobufjs/src/writer.js'\n// @ts-expect-error no types\nimport WriterBufferClass from 'protobufjs/src/writer_buffer.js'\n// @ts-expect-error no types\nimport util from 'protobufjs/src/util/minimal.js'\nimport type { Reader, Writer } from './index.js'\n\nfunction configure (): void {\n util._configure()\n ReaderClass._configure(ReaderBufferClass)\n WriterClass._configure(WriterBufferClass)\n}\n\n// Set up buffer utility according to the environment\nconfigure()\n\n// monkey patch the reader to add native bigint support\nconst methods = [\n 'uint64', 'int64', 'sint64', 'fixed64', 'sfixed64'\n]\n\nfunction patchReader (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (): bigint {\n return BigInt(original.call(this).toString())\n }\n }\n\n return obj\n}\n\nexport function reader (buf: Uint8Array): Reader {\n return patchReader(new ReaderClass(buf))\n}\n\nfunction patchWriter (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (val: bigint) {\n return original.call(this, val.toString())\n }\n }\n\n return obj\n}\n\nexport function writer (): Writer {\n return patchWriter(WriterClass.create())\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { reader } from './utils.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n const r = reader(buf instanceof Uint8Array ? buf : buf.subarray())\n\n return codec.decode(r)\n}\n", "import type { Codec } from './codec.js'\nimport { writer } from './utils.js'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8Array {\n const w = writer()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: T, writer: Writer, opts?: EncodeOptions): void\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\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\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, EncodeOptions } from '../codec.js'\nimport type { Codec } from '../codec.js'\nimport type { Reader, Writer } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: (obj: T, writer: Writer, opts?: EncodeOptions) => void, decode: (reader: Reader, length?: number) => T): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface CircuitRelay {\n type?: CircuitRelay.Type\n srcPeer?: CircuitRelay.Peer\n dstPeer?: CircuitRelay.Peer\n code?: CircuitRelay.Status\n}\n\nexport namespace CircuitRelay {\n export enum Status {\n SUCCESS = 'SUCCESS',\n HOP_SRC_ADDR_TOO_LONG = 'HOP_SRC_ADDR_TOO_LONG',\n HOP_DST_ADDR_TOO_LONG = 'HOP_DST_ADDR_TOO_LONG',\n HOP_SRC_MULTIADDR_INVALID = 'HOP_SRC_MULTIADDR_INVALID',\n HOP_DST_MULTIADDR_INVALID = 'HOP_DST_MULTIADDR_INVALID',\n HOP_NO_CONN_TO_DST = 'HOP_NO_CONN_TO_DST',\n HOP_CANT_DIAL_DST = 'HOP_CANT_DIAL_DST',\n HOP_CANT_OPEN_DST_STREAM = 'HOP_CANT_OPEN_DST_STREAM',\n HOP_CANT_SPEAK_RELAY = 'HOP_CANT_SPEAK_RELAY',\n HOP_CANT_RELAY_TO_SELF = 'HOP_CANT_RELAY_TO_SELF',\n STOP_SRC_ADDR_TOO_LONG = 'STOP_SRC_ADDR_TOO_LONG',\n STOP_DST_ADDR_TOO_LONG = 'STOP_DST_ADDR_TOO_LONG',\n STOP_SRC_MULTIADDR_INVALID = 'STOP_SRC_MULTIADDR_INVALID',\n STOP_DST_MULTIADDR_INVALID = 'STOP_DST_MULTIADDR_INVALID',\n STOP_RELAY_REFUSED = 'STOP_RELAY_REFUSED',\n MALFORMED_MESSAGE = 'MALFORMED_MESSAGE'\n }\n\n enum __StatusValues {\n SUCCESS = 100,\n HOP_SRC_ADDR_TOO_LONG = 220,\n HOP_DST_ADDR_TOO_LONG = 221,\n HOP_SRC_MULTIADDR_INVALID = 250,\n HOP_DST_MULTIADDR_INVALID = 251,\n HOP_NO_CONN_TO_DST = 260,\n HOP_CANT_DIAL_DST = 261,\n HOP_CANT_OPEN_DST_STREAM = 262,\n HOP_CANT_SPEAK_RELAY = 270,\n HOP_CANT_RELAY_TO_SELF = 280,\n STOP_SRC_ADDR_TOO_LONG = 320,\n STOP_DST_ADDR_TOO_LONG = 321,\n STOP_SRC_MULTIADDR_INVALID = 350,\n STOP_DST_MULTIADDR_INVALID = 351,\n STOP_RELAY_REFUSED = 390,\n MALFORMED_MESSAGE = 400\n }\n\n export namespace Status {\n export const codec = () => {\n return enumeration(__StatusValues)\n }\n }\n\n export enum Type {\n HOP = 'HOP',\n STOP = 'STOP',\n STATUS = 'STATUS',\n CAN_HOP = 'CAN_HOP'\n }\n\n enum __TypeValues {\n HOP = 1,\n STOP = 2,\n STATUS = 3,\n CAN_HOP = 4\n }\n\n export namespace Type {\n export const codec = () => {\n return enumeration(__TypeValues)\n }\n }\n\n export interface Peer {\n id: Uint8Array\n addrs: Uint8Array[]\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.id != null && obj.id.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0),\n addrs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.type != null) {\n w.uint32(8)\n CircuitRelay.Type.codec().encode(obj.type, w)\n }\n\n if (obj.srcPeer != null) {\n w.uint32(18)\n CircuitRelay.Peer.codec().encode(obj.srcPeer, w, {\n writeDefaults: false\n })\n }\n\n if (obj.dstPeer != null) {\n w.uint32(26)\n CircuitRelay.Peer.codec().encode(obj.dstPeer, w, {\n writeDefaults: false\n })\n }\n\n if (obj.code != null) {\n w.uint32(32)\n CircuitRelay.Status.codec().encode(obj.code, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = CircuitRelay.Type.codec().decode(reader)\n break\n case 2:\n obj.srcPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 3:\n obj.dstPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 4:\n obj.code = CircuitRelay.Status.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: CircuitRelay): Uint8Array => {\n return encodeMessage(obj, CircuitRelay.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): CircuitRelay => {\n return decodeMessage(buf, CircuitRelay.codec())\n }\n}\n", "import { abortableSource } from 'abortable-iterator'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:stream:converter')\n\nexport interface Timeline {\n /**\n * Connection opening timestamp\n */\n open: number\n\n /**\n * Connection upgraded timestamp\n */\n upgraded?: number\n\n /**\n * Connection closed timestamp\n */\n close?: number\n}\n\nexport interface StreamOptions {\n signal?: AbortSignal\n\n}\n\nexport interface StreamProperties {\n stream: Duplex\n remoteAddr: Multiaddr\n localAddr: Multiaddr\n}\n\n/**\n * Convert a duplex iterable into a MultiaddrConnection.\n * https://github.com/libp2p/interface-transport#multiaddrconnection\n */\nexport function streamToMaConnection (props: StreamProperties, options: StreamOptions = {}) {\n const { stream, remoteAddr } = props\n const { sink, source } = stream\n\n const mapSource = (async function * () {\n for await (const list of source) {\n yield * list\n }\n }())\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n await close()\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log(err)\n }\n }\n },\n source: (options.signal != null) ? abortableSource(mapSource, options.signal) : mapSource,\n remoteAddr,\n /** @type {Timeline} */\n timeline: { open: Date.now(), close: undefined },\n async close () {\n await sink(async function * () {\n yield new Uint8Array(0)\n }())\n await close()\n }\n }\n\n async function close () {\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n return await Promise.resolve()\n }\n\n return maConn\n}\n", "\nexport const RELAY_CODEC = '/libp2p/circuit/relay/0.1.0'\n", "import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Listener } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\n\nexport interface ListenerOptions {\n peerStore: PeerStore\n connectionManager: ConnectionManager\n}\n\nexport function createListener (options: ListenerOptions): Listener {\n const listeningAddrs = new Map()\n\n /**\n * Add swarm handler and listen for incoming connections\n */\n async function listen (addr: Multiaddr): Promise {\n const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')\n const ma = multiaddr(addrString)\n\n const relayPeerStr = ma.getPeerId()\n\n if (relayPeerStr == null) {\n throw new Error('Could not determine relay peer from multiaddr')\n }\n\n const relayPeerId = peerIdFromString(relayPeerStr)\n\n await options.peerStore.addressBook.add(relayPeerId, [ma])\n\n const relayConn = await options.connectionManager.openConnection(relayPeerId)\n const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')\n\n listeningAddrs.set(relayConn.remotePeer.toString(), relayedAddr)\n listener.dispatchEvent(new CustomEvent('listening'))\n }\n\n /**\n * Get fixed up multiaddrs\n *\n * NOTE: This method will grab the peers multiaddrs and expand them such that:\n *\n * a) If it's an existing /p2p-circuit address for a specific relay i.e.\n * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the\n * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where\n * `QmPeer` is this peers id\n * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit\n * addr, such when dialing over a relay with this address, it will create the circuit using\n * the encapsulated transport address. This is useful when for example, a peer should only\n * be dialed over TCP rather than any other transport\n *\n * @returns {Multiaddr[]}\n */\n function getAddrs () {\n const addrs = []\n for (const addr of listeningAddrs.values()) {\n addrs.push(addr)\n }\n return addrs\n }\n\n const listener: Listener = Object.assign(new EventEmitter(), {\n close: async () => await Promise.resolve(),\n listen,\n getAddrs\n })\n\n // Remove listeningAddrs when a peer disconnects\n options.connectionManager.addEventListener('peer:disconnect', (evt) => {\n const { detail: connection } = evt\n const deleted = listeningAddrs.delete(connection.remotePeer.toString())\n\n if (deleted) {\n // Announce listen addresses change\n listener.dispatchEvent(new CustomEvent('close'))\n }\n })\n\n return listener\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { validateAddrs } from './utils.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { pipe } from 'it-pipe'\nimport { codes as Errors } from '../../errors.js'\nimport { stop } from './stop.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { Duplex } from 'it-stream-types'\nimport type { Circuit } from '../transport.js'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:hop')\n\nexport interface HopRequest {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n circuit: Circuit\n connectionManager: ConnectionManager\n}\n\nexport async function handleHop (hopRequest: HopRequest): Promise {\n const {\n connection,\n request,\n streamHandler,\n circuit,\n connectionManager\n } = hopRequest\n\n // Ensure hop is enabled\n if (!circuit.hopEnabled()) {\n log('HOP request received but we are not acting as a relay')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n }\n\n // Validate the HOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid hop request via peer %p %o', connection.remotePeer, err)\n\n return\n }\n\n if (request.dstPeer == null) {\n log('HOP request received but we do not receive a dstPeer')\n return\n }\n\n // Get the connection to the destination (stop) peer\n const destinationPeer = peerIdFromBytes(request.dstPeer.id)\n\n const destinationConnections = connectionManager.getConnections(destinationPeer)\n if (destinationConnections.length === 0 && !circuit.hopActive()) {\n log('HOP request received but we are not connected to the destination peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // TODO: Handle being an active relay\n if (destinationConnections.length === 0) {\n log('did not have connection to remote peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // Handle the incoming HOP request by performing a STOP request\n const stopRequest = {\n type: CircuitPB.Type.STOP,\n dstPeer: request.dstPeer,\n srcPeer: request.srcPeer\n }\n\n let destinationStream: Duplex\n try {\n log('performing STOP request')\n const result = await stop({\n connection: destinationConnections[0],\n request: stopRequest\n })\n\n if (result == null) {\n throw new Error('Could not stop')\n }\n\n destinationStream = result\n } catch (err: any) {\n log.error(err)\n\n return\n }\n\n log('hop request from %p is valid', connection.remotePeer)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n const sourceStream = streamHandler.rest()\n\n log('creating related connections')\n // Short circuit the two streams to create the relayed connection\n return await pipe(\n sourceStream,\n destinationStream,\n sourceStream\n )\n}\n\nexport interface HopConfig extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Performs a HOP request to a relay peer, to request a connection to another\n * peer. A new, virtual, connection will be created between the two via the relay.\n */\nexport async function hop (options: HopConfig): Promise> {\n const {\n connection,\n request,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write(request)\n\n const response = await streamHandler.read()\n\n if (response == null) {\n throw errCode(new Error('HOP request had no response'), Errors.ERR_HOP_REQUEST_FAILED)\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('hop request was successful')\n\n return streamHandler.rest()\n }\n\n log('hop request failed with code %d, closing stream', response.code)\n streamHandler.close()\n\n throw errCode(new Error(`HOP request failed with code \"${response.code ?? 'unknown'}\"`), Errors.ERR_HOP_REQUEST_FAILED)\n}\n\nexport interface CanHopOptions extends AbortOptions {\n connection: Connection\n}\n\n/**\n * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities\n */\nexport async function canHop (options: CanHopOptions) {\n const {\n connection,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write({\n type: CircuitPB.Type.CAN_HOP\n })\n\n const response = await streamHandler.read()\n await streamHandler.close()\n\n if (response == null || response.code !== CircuitPB.Status.SUCCESS) {\n return false\n }\n\n return true\n}\n\nexport interface HandleCanHopOptions {\n connection: Connection\n streamHandler: StreamHandler\n circuit: Circuit\n}\n\n/**\n * Creates an unencoded CAN_HOP response based on the Circuits configuration\n */\nexport function handleCanHop (options: HandleCanHopOptions) {\n const {\n connection,\n streamHandler,\n circuit\n } = options\n const canHop = circuit.hopEnabled()\n log('can hop (%s) request from %p', canHop, connection.remotePeer)\n streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: canHop ? CircuitPB.Status.SUCCESS : CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { StreamHandler } from './stream-handler.js'\n\n/**\n * Write a response\n */\nfunction writeResponse (streamHandler: StreamHandler, status: CircuitRelay.Status) {\n streamHandler.write({\n type: CircuitRelay.Type.STATUS,\n code: status\n })\n}\n\n/**\n * Validate incomming HOP/STOP message\n */\nexport function validateAddrs (msg: CircuitRelay, streamHandler: StreamHandler) {\n try {\n if (msg.dstPeer?.addrs != null) {\n msg.dstPeer.addrs.forEach((addr) => {\n return multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_DST_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_DST_MULTIADDR_INVALID)\n throw err\n }\n\n try {\n if (msg.srcPeer?.addrs != null) {\n msg.srcPeer.addrs.forEach((addr) => {\n return multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_SRC_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_SRC_MULTIADDR_INVALID)\n throw err\n }\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\n\n/**\n * A specialized `AsyncGenerator` that lets you pass a number to the `.next` method which\n * will attempt to return only that many bytes.\n */\nexport interface Reader extends AsyncGenerator {\n next: (...args: [] | [number | undefined]) => Promise>\n}\n\n/**\n * Returns an `AsyncGenerator` that allows reading a set number of bytes from the passed source.\n *\n * @example\n *\n * ```javascript\n * import { reader } from 'it-reader'\n *\n * const stream = reader(source)\n *\n * // read 10 bytes from the stream\n * const { done, value } = await stream.next(10)\n *\n * if (done === true) {\n * // stream finished\n * }\n *\n * if (value != null) {\n * // do something with value\n * }\n * ```\n */\nexport function reader (source: Source) {\n const reader: Reader = (async function * (): AsyncGenerator {\n // @ts-expect-error first yield in stream is ignored\n let bytes: number | undefined = yield // Allows us to receive 8 when reader.next(8) is called\n let bl = new Uint8ArrayList()\n\n for await (const chunk of source) {\n if (bytes == null) {\n bl.append(chunk)\n bytes = yield bl\n bl = new Uint8ArrayList()\n continue\n }\n\n bl.append(chunk)\n\n while (bl.length >= bytes) {\n const data = bl.sublist(0, bytes)\n bl.consume(bytes)\n bytes = yield data\n\n // If we no longer want a specific byte length, we yield the rest now\n if (bytes == null) {\n if (bl.length > 0) {\n bytes = yield bl\n bl = new Uint8ArrayList()\n }\n break // bytes is null and/or no more buffer to yield\n }\n }\n }\n\n // Consumer wants more bytes but the source has ended and our buffer\n // is not big enough to satisfy.\n if (bytes != null) {\n throw Object.assign(\n new Error(`stream ended before ${bytes} bytes became available`),\n { code: 'ERR_UNDER_READ', buffer: bl }\n )\n }\n })()\n\n void reader.next()\n return reader\n}\n", "import { Reader, reader } from 'it-reader'\nimport { pushable } from 'it-pushable'\nimport defer from 'p-defer'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Handshake {\n reader: Reader\n writer: Pushable\n stream: Duplex\n rest: () => Source\n write: (data: TSink) => void\n read: () => Promise\n}\n\n// Convert a duplex stream into a reader and writer and rest stream\nexport function handshake (stream: Duplex): Handshake {\n const writer = pushable() // Write bytes on demand to the sink\n const source = reader(stream.source) // Read bytes on demand from the source\n\n // Waits for a source to be passed to the rest stream's sink\n const sourcePromise = defer>()\n let sinkErr: Error\n\n const sinkPromise = stream.sink((async function * () {\n yield * writer\n const source = await sourcePromise.promise\n yield * source\n })())\n\n sinkPromise.catch(err => {\n sinkErr = err\n })\n\n const rest: Duplex = {\n sink: async source => {\n if (sinkErr != null) {\n return await Promise.reject(sinkErr)\n }\n\n sourcePromise.resolve(source)\n return await sinkPromise\n },\n source\n }\n\n return {\n reader: source,\n writer,\n stream: rest,\n rest: () => writer.end(),\n write: writer.push,\n read: async () => {\n const res = await source.next()\n\n if (res.value != null) {\n return res.value\n }\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport * as lp from 'it-length-prefixed'\nimport { Handshake, handshake } from 'it-handshake'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stream-handler')\n\nexport interface StreamHandlerOptions {\n /**\n * A duplex iterable\n */\n stream: Stream\n\n /**\n * max bytes length of message\n */\n maxLength?: number\n}\n\nexport class StreamHandler {\n private readonly stream: Stream\n private readonly shake: Handshake\n private readonly decoder: Source\n\n constructor (options: StreamHandlerOptions) {\n const { stream, maxLength = 4096 } = options\n\n this.stream = stream\n this.shake = handshake(this.stream)\n this.decoder = lp.decode.fromReader(this.shake.reader, { maxDataLength: maxLength })\n }\n\n /**\n * Read and decode message\n */\n async read () {\n // @ts-expect-error FIXME is a source, needs to be a generator\n const msg = await this.decoder.next()\n\n if (msg.value != null) {\n const value = CircuitRelay.decode(msg.value)\n log('read message type', value.type)\n return value\n }\n\n log('read received no value, closing stream')\n // End the stream, we didn't get data\n this.close()\n }\n\n /**\n * Encode and write array of buffers\n */\n write (msg: CircuitRelay) {\n log('write message type %s', msg.type)\n this.shake.write(lp.encode.single(CircuitRelay.encode(msg)))\n }\n\n /**\n * Return the handshake rest stream and invalidate handler\n */\n rest () {\n this.shake.rest()\n return this.shake.stream\n }\n\n /**\n * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message\n */\n end (msg: CircuitRelay) {\n this.write(msg)\n this.close()\n }\n\n /**\n * Close the stream\n */\n close () {\n log('closing the stream')\n void this.rest().sink([]).catch(err => {\n log.error(err)\n })\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { validateAddrs } from './utils.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stop')\n\nexport interface HandleStopOptions {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n}\n\n/**\n * Handles incoming STOP requests\n */\nexport function handleStop (options: HandleStopOptions): Duplex | undefined {\n const {\n connection,\n request,\n streamHandler\n } = options\n\n // Validate the STOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid stop request via peer %p %o', connection.remotePeer, err)\n return\n }\n\n // The request is valid\n log('stop request is valid')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n\n return streamHandler.rest()\n}\n\nexport interface StopOptions extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Creates a STOP request\n */\nexport async function stop (options: StopOptions) {\n const {\n connection,\n request,\n signal\n } = options\n\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n log('starting stop request to %p', connection.remotePeer)\n const streamHandler = new StreamHandler({ stream })\n\n streamHandler.write(request)\n const response = await streamHandler.read()\n\n if (response == null) {\n streamHandler.close()\n return\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('stop request to %p was successful', connection.remotePeer)\n return streamHandler.rest()\n }\n\n log('stop request failed with code %d', response.code)\n streamHandler.close()\n}\n", "import { logger } from '@libp2p/logger'\nimport { codes } from '../errors.js'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error set-delayed-interval does not export types\n} from 'set-delayed-interval'\nimport { AutoRelay } from './auto-relay.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { TransportManager } from '@libp2p/interface-transport'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { StreamHandlerOptions } from '@libp2p/interface-registrar'\n\nexport interface RelayConfig extends StreamHandlerOptions {\n enabled: boolean\n advertise: RelayAdvertiseConfig\n hop: HopConfig\n autoRelay: AutoRelayConfig\n}\n\nexport interface HopConfig {\n enabled?: boolean\n active?: boolean\n timeout: number\n}\n\nconst log = logger('libp2p:relay')\n\nexport interface RelayAdvertiseConfig {\n bootDelay?: number\n enabled?: boolean\n ttl?: number\n}\n\nexport interface AutoRelayConfig {\n enabled?: boolean\n\n /**\n * maximum number of relays to listen\n */\n maxListeners: number\n}\n\nexport interface RelayInit extends RelayConfig {\n addressSorter?: AddressSorter\n}\n\nexport interface RelayComponents {\n peerId: PeerId\n contentRouting: ContentRouting\n peerStore: PeerStore\n connectionManager: ConnectionManager\n transportManager: TransportManager\n}\n\nexport class Relay implements Startable {\n private readonly components: RelayComponents\n private readonly init: RelayInit\n // @ts-expect-error this field isn't used anywhere?\n private readonly autoRelay?: AutoRelay\n private timeout?: any\n private started: boolean\n\n /**\n * Creates an instance of Relay\n */\n constructor (components: RelayComponents, init: RelayInit) {\n this.components = components\n // Create autoRelay if enabled\n this.autoRelay = init.autoRelay?.enabled !== false\n ? new AutoRelay(components, {\n addressSorter: init.addressSorter,\n ...init.autoRelay\n })\n : undefined\n\n this.started = false\n this.init = init\n this._advertiseService = this._advertiseService.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start Relay service\n */\n async start () {\n // Advertise service if HOP enabled\n if (this.init.hop.enabled !== false && this.init.advertise.enabled !== false) {\n this.timeout = setDelayedInterval(\n this._advertiseService, this.init.advertise.ttl, this.init.advertise.bootDelay\n )\n }\n\n this.started = true\n }\n\n /**\n * Stop Relay service\n */\n async stop () {\n if (this.timeout != null) {\n clearDelayedInterval(this.timeout)\n }\n\n this.started = false\n }\n\n /**\n * Advertise hop relay service in the network.\n */\n async _advertiseService () {\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n await this.components.contentRouting.provide(cid)\n } catch (err: any) {\n if (err.code === codes.ERR_NO_ROUTERS_AVAILABLE) {\n log.error('a content router, such as a DHT, must be provided in order to advertise the relay service', err)\n // Stop the advertise\n await this.stop()\n } else {\n log.error(err)\n }\n }\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * Convert a namespace string into a cid\n */\nexport async function namespaceToCid (namespace: string): Promise {\n const bytes = new TextEncoder().encode(namespace)\n const hash = await sha256.digest(bytes)\n\n return CID.createV0(hash)\n}\n", "const minute = 60 * 1000\n\n/**\n * Delay before HOP relay service is advertised on the network\n */\nexport const ADVERTISE_BOOT_DELAY = 15 * minute\n\n/**\n * Delay Between HOP relay service advertisements on the network\n */\nexport const ADVERTISE_TTL = 30 * minute\n\n/**\n * Multicodec code\n */\nexport const CIRCUIT_PROTO_CODE = 290\n\n/**\n * PeerStore metadaBook key for HOP relay service\n */\nexport const HOP_METADATA_KEY = 'hop_relay'\n\n/**\n * PeerStore metadaBook value for HOP relay service\n */\nexport const HOP_METADATA_VALUE = 'true'\n\n/**\n * Relay HOP relay service namespace for discovery\n */\nexport const RELAY_RENDEZVOUS_NS = '/libp2p/relay'\n", "import { Netmask } from 'netmask';\nimport ip_regex from 'ip-regex';\nimport { isIP } from '@chainsafe/is-ip';\nimport ipaddr from 'ipaddr.js';\nconst { isValid: is_valid, parse } = ipaddr;\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(ip_range => new Netmask(ip_range));\nfunction ipv4_check(ip_addr) {\n for (let r of NETMASK_RANGES) {\n if (r.contains(ip_addr))\n return true;\n }\n return false;\n}\nfunction ipv6_check(ip_addr) {\n return /^::$/.test(ip_addr) ||\n /^::1$/.test(ip_addr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ip_addr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ip_addr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ip_addr);\n}\nexport default (ip) => {\n if (is_valid(ip)) {\n const parsed = parse(ip);\n if (parsed.kind() === 'ipv4')\n return ipv4_check(parsed.toNormalizedString());\n else if (parsed.kind() === 'ipv6')\n return ipv6_check(ip);\n }\n else if (isIP(ip) && ip_regex.v6().test(ip))\n return ipv6_check(ip);\n return undefined;\n};\n", "const word = '[a-fA-F\\\\d:]';\n\nconst boundry = options => options && options.includeBoundaries\n\t? `(?:(?<=\\\\s|^)(?=${word})|(?<=${word})(?=\\\\s|$))`\n\t: '';\n\nconst v4 = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]\\\\d|\\\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]\\\\d|\\\\d)){3}';\n\nconst v6segment = '[a-fA-F\\\\d]{1,4}';\n\nconst v6 = `\n(?:\n(?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\\s*\\/\\/.*$/gm, '').replace(/\\n/g, '').trim();\n\n// Pre-compile only the exact regexes because adding a global flag make regexes stateful\nconst v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);\nconst v4exact = new RegExp(`^${v4}$`);\nconst v6exact = new RegExp(`^${v6}$`);\n\nconst ipRegex = options => options && options.exact\n\t? v46Exact\n\t: new RegExp(`(?:${boundry(options)}${v4}${boundry(options)})|(?:${boundry(options)}${v6}${boundry(options)})`, 'g');\n\nipRegex.v4 = options => options && options.exact ? v4exact : new RegExp(`${boundry(options)}${v4}${boundry(options)}`, 'g');\nipRegex.v6 = options => options && options.exact ? v6exact : new RegExp(`${boundry(options)}${v6}${boundry(options)}`, 'g');\n\nexport default ipRegex;\n", "'use strict'\n\nimport is_ip_private from './lib/index.js'\nexport default is_ip_private", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport isIpPrivate from 'private-ip'\n\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return Boolean(isIpPrivate(address))\n}\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\nimport type { Address } from '@libp2p/interface-peer-store'\nimport { isPrivate } from './multiaddr/is-private.js'\n\n/**\n * Compare function for array.sort().\n * This sort aims to move the private addresses to the end of the array.\n * In case of equality, a certified address will come first.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n // Check certified?\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n\n/**\n * A test thing\n */\nexport async function something (): Promise {\n return Uint8Array.from([0, 1, 2])\n}\n", "import { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { canHop } from './circuit/hop.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n CIRCUIT_PROTO_CODE,\n HOP_METADATA_KEY,\n HOP_METADATA_VALUE,\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressSorter, PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport sort from 'it-sort'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport type { RelayComponents } from './index.js'\n\nconst log = logger('libp2p:auto-relay')\n\nconst noop = () => {}\n\nexport interface AutoRelayInit {\n addressSorter?: AddressSorter\n maxListeners?: number\n onError?: (error: Error, msg?: string) => void\n}\n\nexport class AutoRelay {\n private readonly components: RelayComponents\n private readonly addressSorter: AddressSorter\n private readonly maxListeners: number\n private readonly listenRelays: Set\n private readonly onError: (error: Error, msg?: string) => void\n\n constructor (components: RelayComponents, init: AutoRelayInit) {\n this.components = components\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxListeners = init.maxListeners ?? 1\n this.listenRelays = new Set()\n this.onError = init.onError ?? noop\n\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n\n this.components.peerStore.addEventListener('change:protocols', (evt) => {\n void this._onProtocolChange(evt).catch(err => {\n log.error(err)\n })\n })\n this.components.connectionManager.addEventListener('peer:disconnect', this._onPeerDisconnected)\n }\n\n /**\n * Check if a peer supports the relay protocol.\n * If the protocol is not supported, check if it was supported before and remove it as a listen relay.\n * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if\n * inside the threshold.\n */\n async _onProtocolChange (evt: CustomEvent) {\n const {\n peerId,\n protocols\n } = evt.detail\n const id = peerId.toString()\n\n // Check if it has the protocol\n const hasProtocol = protocols.find(protocol => protocol === RELAY_CODEC)\n\n // If no protocol, check if we were keeping the peer before as a listenRelay\n if (hasProtocol == null) {\n if (this.listenRelays.has(id)) {\n await this._removeListenRelay(id)\n }\n\n return\n }\n\n if (this.listenRelays.has(id)) {\n return\n }\n\n // If protocol, check if can hop, store info in the metadataBook and listen on it\n try {\n const connections = this.components.connectionManager.getConnections(peerId)\n\n if (connections.length === 0) {\n return\n }\n\n const connection = connections[0]\n\n // Do not hop on a relayed connection\n if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {\n log(`relayed connection to ${id} will not be used to hop on`)\n return\n }\n\n const supportsHop = await canHop({ connection })\n\n if (supportsHop) {\n await this.components.peerStore.metadataBook.setValue(peerId, HOP_METADATA_KEY, uint8ArrayFromString(HOP_METADATA_VALUE))\n await this._addListenRelay(connection, id)\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n /**\n * Peer disconnects\n */\n _onPeerDisconnected (evt: CustomEvent) {\n const connection = evt.detail\n const peerId = connection.remotePeer\n const id = peerId.toString()\n\n // Not listening on this relay\n if (!this.listenRelays.has(id)) {\n return\n }\n\n this._removeListenRelay(id).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Attempt to listen on the given relay connection\n */\n async _addListenRelay (connection: Connection, id: string): Promise {\n try {\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n // Get peer known addresses and sort them with public addresses first\n const remoteAddrs = await pipe(\n await this.components.peerStore.addressBook.get(connection.remotePeer),\n (source) => sort(source, this.addressSorter),\n async (source) => await all(source)\n )\n\n // Attempt to listen on relay\n const result = await Promise.all(\n remoteAddrs.map(async addr => {\n try {\n let multiaddr = addr.multiaddr\n\n if (multiaddr.getPeerId() == null) {\n multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)\n }\n\n multiaddr = multiaddr.encapsulate('/p2p-circuit')\n\n // Announce multiaddrs will update on listen success by TransportManager event being triggered\n await this.components.transportManager.listen([multiaddr])\n return true\n } catch (err: any) {\n log.error('error listening on circuit address', err)\n this.onError(err)\n }\n\n return false\n })\n )\n\n if (result.includes(true)) {\n this.listenRelays.add(id)\n }\n } catch (err: any) {\n this.onError(err)\n this.listenRelays.delete(id)\n }\n }\n\n /**\n * Remove listen relay\n */\n async _removeListenRelay (id: string) {\n if (this.listenRelays.delete(id)) {\n // TODO: this should be responsibility of the connMgr\n await this._listenOnAvailableHopRelays([id])\n }\n }\n\n /**\n * Try to listen on available hop relay connections.\n * The following order will happen while we do not have enough relays.\n * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.\n * 2. Dial and try to listen on the peers we know that support hop but are not connected.\n * 3. Search the network.\n */\n async _listenOnAvailableHopRelays (peersToIgnore: string[] = []) {\n // TODO: The peer redial issue on disconnect should be handled by connection gating\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n const knownHopsToDial = []\n const peers = await this.components.peerStore.all()\n\n // Check if we have known hop peers to use and attempt to listen on the already connected\n for (const { id, metadata } of peers) {\n const idStr = id.toString()\n\n // Continue to next if listening on this or peer to ignore\n if (this.listenRelays.has(idStr)) {\n continue\n }\n\n if (peersToIgnore.includes(idStr)) {\n continue\n }\n\n const supportsHop = metadata.get(HOP_METADATA_KEY)\n\n // Continue to next if it does not support Hop\n if ((supportsHop == null) || uint8ArrayToString(supportsHop) !== HOP_METADATA_VALUE) {\n continue\n }\n\n const connections = this.components.connectionManager.getConnections(id)\n\n // If not connected, store for possible later use.\n if (connections.length === 0) {\n knownHopsToDial.push(id)\n continue\n }\n\n await this._addListenRelay(connections[0], idStr)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to listen on known peers that are not connected\n for (const peerId of knownHopsToDial) {\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to find relays to hop on the network\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n for await (const provider of this.components.contentRouting.findProviders(cid)) {\n if (provider.multiaddrs.length === 0) {\n continue\n }\n\n const peerId = provider.id\n\n if (peerId.equals(this.components.peerId)) {\n // Skip the provider if it's us as dialing will fail\n continue\n }\n\n await this.components.peerStore.addressBook.add(peerId, provider.multiaddrs)\n\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n async _tryToListenOnRelay (peerId: PeerId) {\n try {\n const connection = await this.components.connectionManager.openConnection(peerId)\n await this._addListenRelay(connection, peerId.toString())\n } catch (err: any) {\n log.error('Could not use %p as relay', peerId, err)\n this.onError(err, `could not connect and listen on known hop relay ${peerId.toString()}`)\n }\n }\n}\n", "/* eslint max-nested-callbacks: [\"error\", 5] */\n\nimport { logger } from '@libp2p/logger'\nimport sanitize from 'sanitize-filename'\nimport mergeOptions from 'merge-options'\nimport { Key } from 'interface-datastore/key'\nimport { CMS } from './cms.js'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { pbkdf2, randomBytes } from '@libp2p/crypto'\nimport type { Startable } from '@libp2p/interfaces/dist/src/startable'\nimport type { Datastore } from 'interface-datastore'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { KeyTypes } from '@libp2p/crypto/keys'\n\nconst log = logger('libp2p:keychain')\n\nexport interface DEKConfig {\n hash: string\n salt: string\n iterationCount: number\n keyLength: number\n}\n\nexport interface KeyChainInit {\n pass?: string\n dek?: DEKConfig\n}\n\n/**\n * Information about a key.\n */\nexport interface KeyInfo {\n /**\n * The universally unique key id\n */\n id: string\n\n /**\n * The local key name.\n */\n name: string\n}\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\nconst privates = new WeakMap()\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterationCount: 1000\n}\n\nconst defaultOptions = {\n // See https://cryptosense.com/parametesr-choice-for-pbkdf2/\n dek: {\n keyLength: 512 / 8,\n iterationCount: 10000,\n salt: 'you should override this value with a crypto secure random number',\n hash: 'sha2-512'\n }\n}\n\nfunction validateKeyName (name: string) {\n if (name == null) {\n return false\n }\n if (typeof name !== 'string') {\n return false\n }\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Throws an error after a delay\n *\n * This assumes than an error indicates that the keychain is under attack. Delay returning an\n * error to make brute force attacks harder.\n */\nasync function randomDelay () {\n const min = 200\n const max = 1000\n const delay = Math.random() * (max - min) + min\n\n await new Promise(resolve => setTimeout(resolve, delay))\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction DsName (name: string) {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction DsInfoName (name: string) {\n return new Key(infoPrefix + name)\n}\n\nexport interface KeyChainComponents {\n peerId: PeerId\n datastore: Datastore\n}\n\n/**\n * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n *\n */\nexport class KeyChain implements Startable {\n private readonly components: KeyChainComponents\n private readonly init: KeyChainInit\n private started: boolean\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: KeyChainComponents, init: KeyChainInit) {\n this.components = components\n this.init = mergeOptions(defaultOptions, init)\n\n // Enforce NIST SP 800-132\n if (this.init.pass != null && this.init.pass?.length < 20) {\n throw new Error('pass must be least 20 characters')\n }\n if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {\n throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)\n }\n if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {\n throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)\n }\n\n const dek = this.init.pass != null && this.init.dek?.salt != null\n ? pbkdf2(\n this.init.pass,\n this.init.dek?.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n\n privates.set(this, { dek })\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n const dsname = DsInfoName('self')\n\n if (!(await this.components.datastore.has(dsname))) {\n await this.importPeer('self', this.components.peerId)\n }\n\n this.started = true\n }\n\n stop () {\n this.started = false\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data\n * using the Cryptographic Message Syntax (CMS).\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content\n */\n get cms () {\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n\n return new CMS(this, dek)\n }\n\n /**\n * Generates the options for a keychain. A random salt is produced.\n *\n * @returns {object}\n */\n static generateOptions (): KeyChainInit {\n const options = Object.assign({}, defaultOptions)\n const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding\n options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')\n return options\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data.\n * The default options for a keychain.\n *\n * @returns {object}\n */\n static get options () {\n return defaultOptions\n }\n\n /**\n * Create a new key.\n *\n * @param {string} name - The local key name; cannot already exist.\n * @param {string} type - One of the key types; 'rsa'.\n * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only\n */\n async createKey (name: string, type: KeyTypes, size = 2048): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error('Invalid key name'), codes.ERR_INVALID_KEY_NAME)\n }\n\n if (typeof type !== 'string') {\n await randomDelay()\n throw errCode(new Error('Invalid key type'), codes.ERR_INVALID_KEY_TYPE)\n }\n\n const dsname = DsName(name)\n const exists = await this.components.datastore.has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error('Key name already exists'), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n switch (type.toLowerCase()) {\n case 'rsa':\n if (!Number.isSafeInteger(size) || size < 2048) {\n await randomDelay()\n throw errCode(new Error('Invalid RSA key size'), codes.ERR_INVALID_KEY_SIZE)\n }\n break\n default:\n break\n }\n\n let keyInfo\n try {\n const keypair = await generateKeyPair(type, size)\n const kid = await keypair.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await keypair.export(dek)\n keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.datastore.batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n\n await batch.commit()\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n return keyInfo\n }\n\n /**\n * List all the keys.\n *\n * @returns {Promise}\n */\n async listKeys () {\n const query = {\n prefix: infoPrefix\n }\n\n const info = []\n for await (const value of this.components.datastore.query(query)) {\n info.push(JSON.parse(uint8ArrayToString(value.value)))\n }\n\n return info\n }\n\n /**\n * Find a key by it's id\n */\n async findKeyById (id: string): Promise {\n try {\n const keys = await this.listKeys()\n return keys.find((k) => k.id === id)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Find a key by it's name.\n *\n * @param {string} name - The local key name.\n * @returns {Promise}\n */\n async findKeyByName (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n const dsname = DsInfoName(name)\n try {\n const res = await this.components.datastore.get(dsname)\n return JSON.parse(uint8ArrayToString(res))\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Remove an existing key.\n *\n * @param {string} name - The local key name; must already exist.\n * @returns {Promise}\n */\n async removeKey (name: string) {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n const dsname = DsName(name)\n const keyInfo = await this.findKeyByName(name)\n const batch = this.components.datastore.batch()\n batch.delete(dsname)\n batch.delete(DsInfoName(name))\n await batch.commit()\n return keyInfo\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise}\n */\n async renameKey (oldName: string, newName: string): Promise {\n if (!validateKeyName(oldName) || oldName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid old key name '${oldName}'`), codes.ERR_OLD_KEY_NAME_INVALID)\n }\n if (!validateKeyName(newName) || newName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid new key name '${newName}'`), codes.ERR_NEW_KEY_NAME_INVALID)\n }\n const oldDsname = DsName(oldName)\n const newDsname = DsName(newName)\n const oldInfoName = DsInfoName(oldName)\n const newInfoName = DsInfoName(newName)\n\n const exists = await this.components.datastore.has(newDsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${newName}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n try {\n const pem = await this.components.datastore.get(oldDsname)\n const res = await this.components.datastore.get(oldInfoName)\n\n const keyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n const batch = this.components.datastore.batch()\n batch.put(newDsname, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDsname)\n batch.delete(oldInfoName)\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PEM encrypted PKCS #8 string\n */\n async exportKey (name: string, password: string) {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (password == null) {\n await randomDelay()\n throw errCode(new Error('Password is required'), codes.ERR_PASSWORD_REQUIRED)\n }\n\n const dsname = DsName(name)\n try {\n const res = await this.components.datastore.get(dsname)\n const pem = uint8ArrayToString(res)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = await importKey(pem, dek)\n return await privateKey.export(password)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PeerId\n */\n async exportPeerId (name: string) {\n const password = 'temporary-password'\n const pem = await this.exportKey(name, password)\n const privateKey = await importKey(pem, password)\n\n return await peerIdFromKeys(privateKey.public.bytes, privateKey.bytes)\n }\n\n /**\n * Import a new key from a PEM encoded PKCS #8 string\n *\n * @param {string} name - The local key name; must not already exist.\n * @param {string} pem - The PEM encoded PKCS #8 string\n * @param {string} password - The password.\n * @returns {Promise}\n */\n async importKey (name: string, pem: string, password: string): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (pem == null) {\n await randomDelay()\n throw errCode(new Error('PEM encoded key is required'), codes.ERR_PEM_REQUIRED)\n }\n const dsname = DsName(name)\n const exists = await this.components.datastore.has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n let privateKey\n try {\n privateKey = await importKey(pem, password)\n } catch (err: any) {\n await randomDelay()\n throw errCode(new Error('Cannot read the key, most likely the password is wrong'), codes.ERR_CANNOT_READ_KEY)\n }\n\n let kid\n try {\n kid = await privateKey.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n pem = await privateKey.export(dek)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n const keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.datastore.batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n\n return keyInfo\n }\n\n /**\n * Import a peer key\n */\n async importPeer (name: string, peer: PeerId): Promise {\n try {\n if (!validateKeyName(name)) {\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (peer == null) {\n throw errCode(new Error('PeerId is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n if (peer.privateKey == null) {\n throw errCode(new Error('PeerId.privKey is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peer.privateKey)\n\n const dsname = DsName(name)\n const exists = await this.components.datastore.has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await privateKey.export(dek)\n const keyInfo: KeyInfo = {\n name: name,\n id: peer.toString()\n }\n const batch = this.components.datastore.batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Gets the private key as PEM encoded PKCS #8 string\n */\n async getPrivateKey (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n try {\n const dsname = DsName(name)\n const res = await this.components.datastore.get(dsname)\n return uint8ArrayToString(res)\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (oldPass: string, newPass: string) {\n if (typeof oldPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid old pass type '${typeof oldPass}'`), codes.ERR_INVALID_OLD_PASS_TYPE)\n }\n if (typeof newPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid new pass type '${typeof newPass}'`), codes.ERR_INVALID_NEW_PASS_TYPE)\n }\n if (newPass.length < 20) {\n await randomDelay()\n throw errCode(new Error(`Invalid pass length ${newPass.length}`), codes.ERR_INVALID_PASS_LENGTH)\n }\n log('recreating keychain')\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const oldDek = cached.dek\n this.init.pass = newPass\n const newDek = newPass != null && this.init.dek?.salt != null\n ? pbkdf2(\n newPass,\n this.init.dek.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n privates.set(this, { dek: newDek })\n const keys = await this.listKeys()\n for (const key of keys) {\n const res = await this.components.datastore.get(DsName(key.name))\n const pem = uint8ArrayToString(res)\n const privateKey = await importKey(pem, oldDek)\n const password = newDek.toString()\n const keyAsPEM = await privateKey.export(password)\n\n // Update stored key\n const batch = this.components.datastore.batch()\n const keyInfo = {\n name: key.name,\n id: key.id\n }\n batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))\n batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n }\n log('keychain reconstructed')\n }\n}\n", "import 'node-forge/lib/pkcs7.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { certificateForKey, findAsync } from './util.js'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { codes } from '../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { KeyChain } from './index.js'\n\nconst log = logger('libp2p:keychain:cms')\n\nconst privates = new WeakMap()\n\n/**\n * Cryptographic Message Syntax (aka PKCS #7)\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content.\n *\n * See RFC 5652 for all the details.\n */\nexport class CMS {\n private readonly keychain: KeyChain\n\n /**\n * Creates a new instance with a keychain\n */\n constructor (keychain: KeyChain, dek: string) {\n if (keychain == null) {\n throw errCode(new Error('keychain is required'), codes.ERR_KEYCHAIN_REQUIRED)\n }\n\n this.keychain = keychain\n privates.set(this, { dek })\n }\n\n /**\n * Creates some protected data.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n */\n async encrypt (name: string, plain: Uint8Array): Promise {\n if (!(plain instanceof Uint8Array)) {\n throw errCode(new Error('Plain data must be a Uint8Array'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const key = await this.keychain.findKeyByName(name)\n const pem = await this.keychain.getPrivateKey(name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n const certificate = await certificateForKey(key, privateKey)\n\n // create a p7 enveloped message\n const p7 = forge.pkcs7.createEnvelopedData()\n p7.addRecipient(certificate)\n p7.content = forge.util.createBuffer(plain)\n p7.encrypt()\n\n // convert message to DER\n const der = forge.asn1.toDer(p7.toAsn1()).getBytes()\n return uint8ArrayFromString(der, 'ascii')\n }\n\n /**\n * Reads some protected data.\n *\n * The keychain must contain one of the keys used to encrypt the data. If none of the keys\n * exists, an Error is returned with the property 'missingKeys'. It is array of key ids.\n */\n async decrypt (cmsData: Uint8Array): Promise {\n if (!(cmsData instanceof Uint8Array)) {\n throw errCode(new Error('CMS data is required'), codes.ERR_INVALID_PARAMETERS)\n }\n\n let cms: any\n try {\n const buf = forge.util.createBuffer(uint8ArrayToString(cmsData, 'ascii'))\n const obj = forge.asn1.fromDer(buf)\n\n cms = forge.pkcs7.messageFromAsn1(obj)\n } catch (err: any) {\n log.error(err)\n throw errCode(new Error('Invalid CMS'), codes.ERR_INVALID_CMS)\n }\n\n // Find a recipient whose key we hold. We only deal with recipient certs\n // issued by ipfs (O=ipfs).\n const recipients: any = cms.recipients\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'O' && a.value === 'ipfs'))\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'CN'))\n // @ts-expect-error cms types not defined\n .map(r => {\n return {\n recipient: r,\n // @ts-expect-error cms types not defined\n keyId: r.issuer.find(a => a.shortName === 'CN').value\n }\n })\n\n const r = await findAsync(recipients, async (recipient: any) => {\n try {\n const key = await this.keychain.findKeyById(recipient.keyId)\n if (key != null) {\n return true\n }\n } catch (err: any) {\n return false\n }\n return false\n })\n\n if (r == null) {\n // @ts-expect-error cms types not defined\n const missingKeys: string[] = recipients.map(r => r.keyId)\n throw errCode(new Error(`Decryption needs one of the key(s): ${missingKeys.join(', ')}`), codes.ERR_MISSING_KEYS, {\n missingKeys\n })\n }\n\n const key = await this.keychain.findKeyById(r.keyId)\n\n if (key == null) {\n throw errCode(new Error('No key available to decrypto'), codes.ERR_NO_KEY)\n }\n\n const pem = await this.keychain.getPrivateKey(key.name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n cms.decrypt(r.recipient, privateKey)\n return uint8ArrayFromString(cms.content.getBytes(), 'ascii')\n }\n}\n", "import 'node-forge/lib/x509.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\n\nconst pki = forge.pki\n\n/**\n * Gets a self-signed X.509 certificate for the key.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n *\n * TODO: move to libp2p-crypto package\n */\nexport const certificateForKey = (key: any, privateKey: forge.pki.rsa.PrivateKey) => {\n const publicKey = pki.rsa.setPublicKey(privateKey.n, privateKey.e)\n const cert = pki.createCertificate()\n cert.publicKey = publicKey\n cert.serialNumber = '01'\n cert.validity.notBefore = new Date()\n cert.validity.notAfter = new Date()\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10) // eslint-disable-line @typescript-eslint/restrict-plus-operands\n const attrs = [{\n name: 'organizationName',\n value: 'ipfs'\n }, {\n shortName: 'OU',\n value: 'keystore'\n }, {\n name: 'commonName',\n value: key.id\n }]\n cert.setSubject(attrs)\n cert.setIssuer(attrs)\n cert.setExtensions([{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n emailProtection: true,\n timeStamping: true\n }, {\n name: 'nsCertType',\n client: true,\n server: true,\n email: true,\n objsign: true,\n sslCA: true,\n emailCA: true,\n objCA: true\n }])\n // self-sign certificate\n cert.sign(privateKey)\n\n return cert\n}\n\n/**\n * Finds the first item in a collection that is matched in the\n * `asyncCompare` function.\n *\n * `asyncCompare` is an async function that must\n * resolve to either `true` or `false`.\n *\n * @param {Array} array\n * @param {function(*)} asyncCompare - An async function that returns a boolean\n */\nexport async function findAsync (array: T[], asyncCompare: (val: T) => Promise) {\n const promises = array.map(asyncCompare)\n const results = await Promise.all(promises)\n const index = results.findIndex(result => result)\n return array[index]\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = () => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PublicKey): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PrivateKey): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n", "import * as keysPBM from './keys.js'\nimport 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { keyStretcher } from './key-stretcher.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport * as RSA from './rsa-class.js'\nimport * as Ed25519 from './ed25519-class.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface-keys'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string) {\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}\n\nfunction typeToKey (type: string) {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n// Generates a keypair of the given type and bitsize\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise { // eslint-disable-line require-await\n return await typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n// Generates a keypair of the given type and bitsize\n// seed is a 32 byte uint8array\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise { // eslint-disable-line require-await\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\n return await Ed25519.generateKeyPairFromSeed(seed)\n}\n\n// Converts a protobuf serialized public key into its\n// representative object\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\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 ?? 'RSA')\n }\n}\n\n// Converts a public key object into a protobuf serialized public key\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\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\n// representative object\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise { // eslint-disable-line require-await\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return await 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\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n *\n * @param {string} encryptedKey\n * @param {string} password\n */\nexport async function importKey (encryptedKey: string, password: string): Promise { // eslint-disable-line require-await\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n // Only rsa supports pem right now\n const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password)\n if (key === null) {\n throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM')\n }\n let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))\n der = uint8ArrayFromString(der.getBytes(), 'ascii')\n return await supportedKeys.rsa.unmarshalRsaPrivateKey(der)\n}\n", "/* eslint-env browser */\n\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\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n '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-crypto/blob/master/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n", "import 'node-forge/lib/util.js'\nimport 'node-forge/lib/jsbn.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nexport function bigIntegerToUintBase64url (num: { abs: () => any}, len?: number) {\n // Call `.abs()` to convert to unsigned\n let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian\n\n // toByteArray() gives us back a signed array, which will include a leading 0\n // byte if the most significant bit of the number is 1:\n // https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer\n // Our number will always be positive so we should remove the leading padding.\n buf = buf[0] === 0 ? buf.subarray(1) : buf\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return uint8ArrayToString(buf, 'base64url')\n}\n\n// Convert a base64url encoded string to a BigInteger\nexport function base64urlToBigInteger (str: string): typeof forge.jsbn.BigInteger {\n const buf = base64urlToBuffer(str)\n return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16)\n}\n\nexport function base64urlToBuffer (str: string, len?: number) {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport webcrypto from '../webcrypto.js'\nimport { base64urlToBuffer } from '../util.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { ECDHKey, ECDHKeyPair } from './interface.js'\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n}\n\nconst curveTypes = Object.keys(bits)\nconst names = curveTypes.join(' / ')\n\nexport async function generateEphmeralKeyPair (curve: string) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve\n },\n true,\n ['deriveBits']\n )\n\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair) => {\n let privateKey\n\n if (forcePrivate != null) {\n privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPrivateKey(curve, forcePrivate),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n ['deriveBits']\n )\n } else {\n privateKey = pair.privateKey\n }\n\n const key = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPublicKey(curve, theirPub),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n []\n )\n\n const buffer = await webcrypto.get().subtle.deriveBits(\n {\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n },\n privateKey,\n bits[curve]\n )\n\n return new Uint8Array(buffer, 0, buffer.byteLength)\n }\n\n const publicKey = await webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n\n const ecdhKey: ECDHKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n }\n\n return ecdhKey\n}\n\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n}\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: JsonWebKey) {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[jwk.crv]\n\n return uint8ArrayConcat([\n Uint8Array.from([4]), // uncompressed point\n base64urlToBuffer(jwk.x, byteLen),\n base64urlToBuffer(jwk.y, byteLen)\n ], 1 + byteLen * 2)\n}\n\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey (curve: string, key: Uint8Array) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[curve]\n\n if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT')\n }\n\n return {\n kty: 'EC',\n crv: curve,\n x: uint8ArrayToString(key.subarray(1, byteLen + 1), 'base64url'),\n y: uint8ArrayToString(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n }\n}\n\nconst unmarshalPrivateKey = (curve: string, key: ECDHKeyPair) => ({\n ...unmarshalPublicKey(curve, key.public),\n d: uint8ArrayToString(key.private, 'base64url')\n})\n", "import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions) {\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\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\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: Uint8Array, password: string | Uint8Array) { // eslint-disable-line require-await\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\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', 'deriveBits'])\n const 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 /**\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: Uint8Array, password: string | Uint8Array) {\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\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\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', 'deriveBits'])\n const 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\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\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 */\nexport async function importer (privateKey: string, password: string) {\n const encryptedKey = base64.decode(privateKey)\n const cipher = ciphers.create()\n return await cipher.decrypt(encryptedKey, password)\n}\n", "\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport 'node-forge/lib/sha512.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport * as crypto from './rsa.js'\nimport * as pbm from './keys.js'\nimport { exporter } from './exporter.js'\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal () {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes () {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n encrypt (bytes: Uint8Array) {\n return crypto.encrypt(this._key, bytes)\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret () {\n return crypto.getRandomValues(16)\n }\n\n async sign (message: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndSign(this._key, message)\n }\n\n get public () {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n decrypt (bytes: Uint8Array) {\n return crypto.decrypt(this._key, bytes)\n }\n\n marshal () {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes () {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 /**\n * Exports the key into a password protected PEM format\n */\n async export (password: string, format = 'pkcs-8') { // eslint-disable-line require-await\n if (format === 'pkcs-8') {\n const buffer = new forge.util.ByteBuffer(this.marshal())\n const asn1 = forge.asn1.fromDer(buffer)\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n const options = {\n algorithm: 'aes256',\n count: 10000,\n saltSize: 128 / 8,\n prfAlgorithm: 'sha512'\n }\n return forge.pki.encryptRsaPrivateKey(privateKey, password, options)\n } else if (format === 'libp2p-key') {\n return await exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array) {\n const jwk = crypto.utils.pkixToJwk(bytes)\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey) {\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number) {\n const keys = await crypto.generateKey(bits)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n", "import { utils } from '@noble/secp256k1'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\nexport default function randomBytes (length: number): Uint8Array {\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 utils.randomBytes(length)\n}\n", "import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n// Convert a PKCS#1 in ASN1 DER format to a JWK key\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n // https://tools.ietf.org/html/rfc7518#section-6.3.1\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(privateKey.n),\n e: bigIntegerToUintBase64url(privateKey.e),\n d: bigIntegerToUintBase64url(privateKey.d),\n p: bigIntegerToUintBase64url(privateKey.p),\n q: bigIntegerToUintBase64url(privateKey.q),\n dp: bigIntegerToUintBase64url(privateKey.dP),\n dq: bigIntegerToUintBase64url(privateKey.dQ),\n qi: bigIntegerToUintBase64url(privateKey.qInv),\n alg: 'RS256'\n }\n}\n\n// Convert a JWK key into PKCS#1 in ASN1 DER format\nexport function jwkToPkcs1 (jwk: JsonWebKey) {\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\n const asn1 = forge.pki.privateKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e),\n d: base64urlToBigInteger(jwk.d),\n p: base64urlToBigInteger(jwk.p),\n q: base64urlToBigInteger(jwk.q),\n dP: base64urlToBigInteger(jwk.dp),\n dQ: base64urlToBigInteger(jwk.dq),\n qInv: base64urlToBigInteger(jwk.qi)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n\n// Convert a PKCIX in ASN1 DER format to a JWK key\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const publicKey = forge.pki.publicKeyFromAsn1(asn1)\n\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(publicKey.n),\n e: bigIntegerToUintBase64url(publicKey.e)\n }\n}\n\n// Convert a JWK key to PKCIX in ASN1 DER format\nexport function jwkToPkix (jwk: JsonWebKey) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const asn1 = forge.pki.publicKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n", "import 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { base64urlToBigInteger } from '../util.js'\n\nfunction convert (key: any, types: string[]) {\n return types.map(t => base64urlToBigInteger(key[t]))\n}\n\nexport function jwk2priv (key: JsonWebKey) {\n return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']))\n}\n\nexport function jwk2pub (key: JsonWebKey) {\n return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e']))\n}\n", "import webcrypto from '../webcrypto.js'\nimport randomBytes from '../random-bytes.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport * as utils from './rsa-utils.js'\nimport { jwk2pub, jwk2priv } from './jwk2pem.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\nexport { utils }\n\nexport async function generateKey (bits: number) {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey) {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array) {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n Uint8Array.from(msg)\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array) {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return await webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return await Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey) {\n return await webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\n/*\n\nRSA encryption/decryption for the browser with webcrypto workaround\n\"bloody dark magic. webcrypto's why.\"\n\nExplanation:\n - Convert JWK to nodeForge\n - Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a \"binary-string backed buffer\", so let's make our Uint8Array a binary string\n - Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array\n\n*/\n\nfunction convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array, handle: (msg: string, key: { encrypt: (msg: string) => string, decrypt: (msg: string) => string}) => string) {\n const fkey = pub ? jwk2pub(key) : jwk2priv(key)\n const fmsg = uint8ArrayToString(Uint8Array.from(msg), 'ascii')\n const fomsg = handle(fmsg, fkey)\n return uint8ArrayFromString(fomsg, 'ascii')\n}\n\nexport function encrypt (key: JsonWebKey, msg: Uint8Array) {\n return convertKey(key, true, msg, (msg, key) => key.encrypt(msg))\n}\n\nexport function decrypt (key: JsonWebKey, msg: Uint8Array) {\n return convertKey(key, false, msg, (msg, key) => key.decrypt(msg))\n}\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\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 */\nexport async function exporter (privateKey: Uint8Array, password: string) {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport * as crypto from './ed25519.js'\nimport * as pbm from './keys.js'\nimport { exporter } from './exporter.js'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n async verify (data: Uint8Array, sig: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal () {\n return this._key\n }\n\n get bytes () {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n async sign (message: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndSign(this._key, message)\n }\n\n get public () {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal () {\n return this._key\n }\n\n get bytes () {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 = await identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key') { // eslint-disable-line require-await\n if (format === 'libp2p-key') {\n return await exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array) {\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\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}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array) {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair () {\n const { privateKey, publicKey } = await crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array) {\n const { privateKey, publicKey } = await crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number) {\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", "import * as ed from '@noble/ed25519'\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\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport async function generateKey () {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport async function generateKeyFromSeed (seed: Uint8Array) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return await ed.sign(msg, privateKeyRaw)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array) {\n return await ed.verify(sig, msg, publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array) {\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", "import { sha256 } from 'multiformats/hashes/sha2'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as crypto from './secp256k1.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array) {\n return await crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal () {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes () {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n async sign (message: Uint8Array) {\n return await crypto.hashAndSign(this._key, message)\n }\n\n get public () {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal () {\n return this._key\n }\n\n get bytes () {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key') { // eslint-disable-line require-await\n if (format === 'libp2p-key') {\n return await exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array) {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array) {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair () {\n const privateKeyBytes = await crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport * as secp from '@noble/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey () {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport async function hashAndSign (key: Uint8Array, msg: Uint8Array) {\n const { digest } = await sha256.digest(msg)\n try {\n return await secp.sign(digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array) {\n try {\n const { digest } = await sha256.digest(msg)\n return secp.verify(sig, digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array) {\n const point = secp.Point.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array) {\n const point = secp.Point.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array) {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array) {\n try {\n secp.Point.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array) {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n", "\nimport 'node-forge/lib/aes.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array) {\n const cipher2 = forge.cipher.createCipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n\nexport function createDecipheriv (mode: any, key: Uint8Array, iv: Uint8Array) {\n const cipher2 = forge.cipher.createDecipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n", "// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw new CodeError(`Hash '${hash}' is unknown or not supported. Must be ${types}`, 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n", "export default async function pReflect(promise) {\n\ttry {\n\t\tconst value = await promise;\n\n\t\treturn {\n\t\t\tstatus: 'fulfilled',\n\t\t\tvalue,\n\t\t\tisFulfilled: true,\n\t\t\tisRejected: false\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: 'rejected',\n\t\t\treason: error,\n\t\t\tisFulfilled: false,\n\t\t\tisRejected: true\n\t\t};\n\t}\n}\n\nexport function isFulfilled(promiseResult) {\n\treturn 'value' in promiseResult;\n}\n\nexport function isRejected(promiseResult) {\n\treturn 'reason' in promiseResult;\n}\n", "/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\t\treturn current.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n}\n", "import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n", "import pReflect from 'p-reflect';\nimport pLimit from 'p-limit';\n\nexport default async function pSettle(array, options = {}) {\n\tconst {concurrency = Number.POSITIVE_INFINITY} = options;\n\tconst limit = pLimit(concurrency);\n\n\treturn Promise.all(array.map(element => {\n\t\tif (element && typeof element.then === 'function') {\n\t\t\treturn pReflect(element);\n\t\t}\n\n\t\tif (typeof element === 'function') {\n\t\t\treturn pReflect(limit(() => element()));\n\t\t}\n\n\t\treturn pReflect(Promise.resolve(element));\n\t}));\n}\n", "import { logger } from '@libp2p/logger'\nimport pSettle from 'p-settle'\nimport { codes } from './errors.js'\nimport errCode from 'err-code'\nimport { FaultTolerance } from '@libp2p/interface-transport'\nimport type { Listener, Transport, TransportManager, TransportManagerEvents, Upgrader } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:transports')\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport interface DefaultTransportManagerComponents {\n metrics?: Metrics\n addressManager: AddressManager\n upgrader: Upgrader\n}\n\nexport class DefaultTransportManager extends EventEmitter implements TransportManager, Startable {\n private readonly components: DefaultTransportManagerComponents\n private readonly transports: Map\n private readonly listeners: Map\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: DefaultTransportManagerComponents, init: TransportManagerInit = {}) {\n super()\n\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\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport) {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw errCode(new Error('Transport must have a valid tag'), codes.ERR_INVALID_KEY)\n }\n\n if (this.transports.has(tag)) {\n throw errCode(new Error('There is already a transport with this tag'), codes.ERR_DUPLICATE_TRANSPORT)\n }\n\n log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs()\n\n await this.listen(addrs)\n\n this.started = true\n }\n\n /**\n * Stops all listeners\n */\n async stop () {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: AbortOptions): Promise {\n const transport = this.transportForMultiaddr(ma)\n\n if (transport == null) {\n throw errCode(new Error(`No transport available for address ${String(ma)}`), codes.ERR_TRANSPORT_UNAVAILABLE)\n }\n\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n })\n } catch (err: any) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED\n }\n\n throw err\n }\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\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 /**\n * Returns all the transports instances\n */\n getTransports () {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr (ma: Multiaddr) {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]) {\n if (addrs == null || addrs.length === 0) {\n log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n const couldNotListen = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs)\n const tasks = []\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n log('creating listener for %s on %s', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n })\n\n let listeners = this.listeners.get(key)\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.dispatchEvent(new CustomEvent('listener:listening', {\n detail: listener\n }))\n })\n listener.addEventListener('close', () => {\n this.dispatchEvent(new CustomEvent('listener:close', {\n detail: listener\n }))\n })\n\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr))\n }\n\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key)\n continue\n }\n\n const results = await pSettle(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.isFulfilled)\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES)\n }\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 errCode(new Error(message), codes.ERR_NO_VALID_ADDRESSES)\n }\n log(`libp2p in dial mode only: ${message}`)\n }\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: string) {\n log('removing %s', key)\n\n // Close any running listeners\n for (const listener of this.listeners.get(key) ?? []) {\n await listener.close()\n }\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\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\n await Promise.all(tasks)\n }\n}\n", "import type { Metric, Metrics } from '@libp2p/interface-metrics'\n\nexport interface TrackedMapInit {\n name: string\n metrics: Metrics\n}\n\nclass TrackedMap extends Map {\n private readonly metric: Metric\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { name, metrics } = init\n\n this.metric = metrics.registerMetric(name)\n this.updateComponentMetric()\n }\n\n set (key: K, value: V) {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K) {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear () {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric () {\n this.metric.update(this.size)\n }\n}\n\nexport interface CreateTrackedMapInit {\n /**\n * The metric name to use\n */\n name: string\n\n /**\n * A metrics implementation\n */\n metrics?: Metrics\n}\n\nexport function trackedMap (config: CreateTrackedMapInit): Map {\n const { name, metrics } = config\n let map: Map\n\n if (metrics != null) {\n map = new TrackedMap({ name, metrics })\n } else {\n map = new Map()\n }\n\n return map\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mss from '@libp2p/multistream-select'\nimport { codes } from './errors.js'\nimport { createConnection } from './connection/index.js'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { MultiaddrConnection, Connection, Stream, ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Upgrader, UpgraderEvents, UpgraderOptions } from '@libp2p/interface-transport'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:upgrader')\n\ninterface CreateConectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: Duplex\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncryption: ConnectionEncrypter[]\n muxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade\n * must complete\n */\n inboundUpgradeTimeout: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxOutboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection) {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.stat.direction === direction && stream.stat.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport interface DefaultUpgraderComponents {\n peerId: PeerId\n metrics?: Metrics\n connectionManager: ConnectionManager\n connectionGater: ConnectionGater\n connectionProtector?: ConnectionProtector\n registrar: Registrar\n peerStore: PeerStore\n}\n\nexport class DefaultUpgrader extends EventEmitter implements Upgrader {\n private readonly components: DefaultUpgraderComponents\n private readonly connectionEncryption: Map\n private readonly muxers: Map\n private readonly inboundUpgradeTimeout: number\n\n constructor (components: DefaultUpgraderComponents, init: UpgraderInit) {\n super()\n\n this.components = components\n this.connectionEncryption = new Map()\n\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter)\n })\n\n this.muxers = new Map()\n\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)\n\n if (!accept) {\n throw errCode(new Error('connection denied'), codes.ERR_CONNECTION_DENIED)\n }\n\n let encryptedConn\n let remotePeer\n let upgradedConn: Duplex\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n\n const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const abortableStream = abortableDuplex(maConn, timeoutController.signal)\n maConn.source = abortableStream.source\n maConn.sink = abortableStream.sink\n\n if (await this.components.connectionGater.denyInboundConnection(maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n log('starting the inbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n log('protecting the inbound connection')\n protectedConn = await protector.protect(maConn)\n }\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\n if (await this.components.connectionGater.denyInboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n } else {\n const idStr = maConn.remoteAddr.getPeerId()\n\n if (idStr == null) {\n throw errCode(new Error('inbound connection that skipped encryption must have a peer id'), codes.ERR_INVALID_MULTIADDR)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\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 } catch (err: any) {\n log.error('Failed to upgrade inbound connection', err)\n throw err\n }\n\n if (await this.components.connectionGater.denyInboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n log('Successfully upgraded inbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n } finally {\n this.components.connectionManager.afterUpgradeInbound()\n timeoutController.clear()\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise {\n const idStr = maConn.remoteAddr.getPeerId()\n let remotePeerId: PeerId | undefined\n\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr)\n\n if (await this.components.connectionGater.denyOutboundConnection(remotePeerId, maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n }\n\n let encryptedConn\n let remotePeer: PeerId\n let upgradedConn\n let cryptoProtocol\n let muxerFactory\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n log('Starting the outbound connection upgrade')\n\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n\n // Protect\n let protectedConn = maConn\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n protectedConn = await protector.protect(maConn)\n }\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\n if (await this.components.connectionGater.denyOutboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n } else {\n if (remotePeerId == null) {\n throw errCode(new Error('Encryption was skipped but no peer id was passed'), codes.ERR_INVALID_PEER)\n }\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\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 } catch (err: any) {\n log.error('Failed to upgrade outbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.connectionGater.denyOutboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n log('Successfully upgraded outbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\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\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('%s: incoming stream opened on %s', direction, protocol)\n\n if (connection == null) {\n return\n }\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS))\n\n return\n }\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.stat.protocol = protocol\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 this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n connection.addStream(muxedStream)\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n this._onStream({ connection, stream: muxedStream, protocol })\n })\n .catch(err => {\n log.error(err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n })\n },\n // Run anytime a stream closes\n onStreamEnd: muxedStream => {\n connection?.removeStream(muxedStream.id)\n }\n })\n\n newStream = async (protocols: string[], options: AbortOptions = {}): Promise => {\n if (muxer == null) {\n throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)\n }\n\n log('%s: starting new stream on %s', direction, protocols)\n const muxedStream = await muxer.newStream()\n let controller: TimeoutController | undefined\n\n try {\n if (options.signal == null) {\n log('No abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n controller = new TimeoutController(30000)\n options.signal = controller.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n }\n\n const { stream, protocol } = await mss.select(muxedStream, protocols, options)\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar)\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount === outgoingLimit) {\n const err = errCode(new Error(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\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 this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(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.stat.protocol = protocol\n\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n return muxedStream\n } catch (err: any) {\n log.error('could not create new stream', err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n\n if (err.code != null) {\n throw err\n }\n\n throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL)\n } finally {\n if (controller != null) {\n controller.clear()\n }\n }\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 log.error(err)\n })\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.stat.status === 'OPEN') {\n await connection.close()\n }\n } catch (err: any) {\n log.error(err)\n } finally {\n this.dispatchEvent(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n }\n })().catch(err => {\n log.error(err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = () => {\n throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED)\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer: remotePeer,\n stat: {\n status: 'OPEN',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol\n },\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => muxer != null ? muxer.streams : errConnectionNotMultiplexed(),\n close: async () => {\n await maConn.close()\n // Ensure remaining streams are closed\n if (muxer != null) {\n muxer.close()\n }\n }\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: connection\n }))\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler } = this.components.registrar.getHandler(protocol)\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: Duplex): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('handling inbound crypto protocol selection', protocols)\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting inbound connection...')\n\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\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: MultiaddrConnection, remotePeerId?: PeerId): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('selecting outbound crypto protocol', protocols)\n\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting outbound connection to %p', remotePeerId)\n\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\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: MultiaddrConnection, muxers: Map): Promise<{stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('outbound selecting muxer %s', protocols)\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n log('%s selected as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing outbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\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: MultiaddrConnection, muxers: Map): Promise<{stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing inbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n}\n", "\nexport const PROTOCOL_ID = '/multistream/1.0.0'\n\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", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { PROTOCOL_ID } from './index.js'\nimport type { Duplex } from 'it-stream-types'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { pushable } from 'it-pushable'\nimport merge from 'it-merge'\nimport { reader } from 'it-reader'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:select')\n\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 * ```js\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: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options: MultistreamSelectInit = {}): Promise> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n const { reader, writer, rest, stream: shakeStream } = handshake(stream)\n\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n log('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n multistream.writeAll(writer, [p1, p2], options)\n\n let response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n rest()\n return { stream: shakeStream, protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n log('select: write \"%s\"', protocol)\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n const response = await multistream.readString(reader, options)\n log('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n rest() // End our writer so others can start writing to stream\n return { stream: shakeStream, protocol }\n }\n }\n\n rest()\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n}\n\n/**\n * Lazily 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 */\nexport function lazySelect (stream: Duplex, protocol: string): ProtocolStream\nexport function lazySelect (stream: Duplex, protocol: string): ProtocolStream\nexport function lazySelect (stream: Duplex, protocol: string): ProtocolStream {\n // This is a signal to write the multistream headers if the consumer tries to\n // read from the source\n const negotiateTrigger = pushable()\n let negotiated = false\n return {\n stream: {\n sink: async source => await stream.sink((async function * () {\n let first = true\n for await (const chunk of merge(source, negotiateTrigger)) {\n if (first) {\n first = false\n negotiated = true\n negotiateTrigger.end()\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n const list = new Uint8ArrayList(multistream.encode(p1), multistream.encode(p2))\n if (chunk.length > 0) list.append(chunk)\n yield * list\n } else {\n yield chunk\n }\n }\n })()),\n source: (async function * () {\n if (!negotiated) negotiateTrigger.push(new Uint8Array())\n const byteReader = reader(stream.source)\n let response = await multistream.readString(byteReader)\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(byteReader)\n }\n if (response !== protocol) {\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n }\n for await (const chunk of byteReader) {\n yield * chunk\n }\n })()\n },\n protocol\n }\n}\n", "\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport first from 'it-first'\nimport { abortableSource } from 'abortable-iterator'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Pushable } from 'it-pushable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Source } from 'it-stream-types'\nimport type { Reader } from 'it-reader'\nimport type { MultistreamSelectInit } from '.'\nimport { MAX_PROTOCOL_LENGTH } from './constants.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:mss')\n\nconst NewLine = uint8ArrayFromString('\\n')\n\nexport function encode (buffer: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const list = new Uint8ArrayList(buffer, NewLine)\n\n return lp.encode.single(list)\n}\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport function write (writer: Pushable, buffer: Uint8Array | Uint8ArrayList, options: MultistreamSelectInit = {}) {\n const encoded = encode(buffer)\n\n if (options.writeBytes === true) {\n writer.push(encoded.subarray())\n } else {\n writer.push(encoded)\n }\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport function writeAll (writer: Pushable, buffers: Uint8Array[], options: MultistreamSelectInit = {}) {\n const list = new Uint8ArrayList()\n\n for (const buf of buffers) {\n list.append(encode(buf))\n }\n\n if (options.writeBytes === true) {\n writer.push(list.subarray())\n } else {\n writer.push(list)\n }\n}\n\nexport async function read (reader: Reader, options?: AbortOptions): Promise {\n let byteLength = 1 // Read single byte chunks until the length is known\n const varByteSource = { // No return impl - we want the reader to remain readable\n [Symbol.asyncIterator]: () => varByteSource,\n next: async () => await reader.next(byteLength)\n }\n\n let input: Source = varByteSource\n\n // If we have been passed an abort signal, wrap the input source in an abortable\n // iterator that will throw if the operation is aborted\n if (options?.signal != null) {\n input = abortableSource(varByteSource, options.signal)\n }\n\n // Once the length has been parsed, read chunk for that length\n const onLength = (l: number) => {\n byteLength = l\n }\n\n const buf = await pipe(\n input,\n lp.decode({ onLength, maxDataLength: MAX_PROTOCOL_LENGTH }),\n async (source) => await first(source)\n )\n\n if (buf == null || buf.length === 0) {\n throw errCode(new Error('no buffer returned'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n if (buf.get(buf.byteLength - 1) !== NewLine[0]) {\n log.error('Invalid mss message - missing newline - %s', buf.subarray())\n throw errCode(new Error('missing newline'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\nexport async function readString (reader: Reader, options?: AbortOptions) {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n", "import { logger } from '@libp2p/logger'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { PROTOCOL_ID } from './constants.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:handle')\n\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 * ```js\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: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n const { writer, reader, rest, stream: shakeStream } = handshake(stream)\n\n while (true) {\n const protocol = await multistream.readString(reader, options)\n log('read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n log('respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n multistream.write(writer, uint8ArrayFromString(PROTOCOL_ID), options)\n continue\n }\n\n if (protocols.includes(protocol)) {\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n log('respond with \"%s\" for \"%s\"', protocol, protocol)\n rest()\n return { stream: shakeStream, protocol }\n }\n\n if (protocol === 'ls') {\n // \\n\\n\\n\n multistream.write(writer, new Uint8ArrayList(...protocols.map(p => multistream.encode(uint8ArrayFromString(p)))), options)\n // multistream.writeAll(writer, protocols.map(p => uint8ArrayFromString(p)))\n log('respond with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n multistream.write(writer, uint8ArrayFromString('na'), options)\n log('respond with \"na\" for \"%s\"', protocol)\n }\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'\nimport { symbol } from '@libp2p/interface-connection'\nimport type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\nconst log = logger('libp2p:connection')\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream: (protocols: string[], options?: AbortOptions) => Promise\n close: () => Promise\n getStreams: () => Stream[]\n stat: ConnectionStat\n}\n\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 implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n /**\n * Connection metadata\n */\n public readonly stat: ConnectionStat\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: AbortOptions) => Promise\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: () => Promise\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n private _closing: boolean\n\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: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, getStreams, stat } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.stat = {\n ...stat,\n status: OPEN\n }\n this._newStream = newStream\n this._close = close\n this._getStreams = getStreams\n this.tags = []\n this._closing = false\n }\n\n get [Symbol.toStringTag] () {\n return 'Connection'\n }\n\n get [symbol] () {\n return true\n }\n\n /**\n * Get all the streams of the muxer\n */\n get streams () {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: AbortOptions): Promise {\n if (this.stat.status === CLOSING) {\n throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')\n }\n\n if (this.stat.status === CLOSED) {\n throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.stat.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Add a stream when it is opened to the registry\n */\n addStream (stream: Stream) {\n stream.stat.direction = 'inbound'\n }\n\n /**\n * Remove stream registry after it is closed\n */\n removeStream (id: string) {\n\n }\n\n /**\n * Close the connection\n */\n async close () {\n if (this.stat.status === CLOSED || this._closing) {\n return\n }\n\n this.stat.status = CLOSING\n\n // close all streams - this can throw if we're not multiplexed\n try {\n this.streams.forEach(s => s.close())\n } catch (err) {\n log.error(err)\n }\n\n // Close raw connection\n this._closing = true\n await this._close()\n this._closing = false\n\n this.stat.timeline.close = Date.now()\n this.stat.status = CLOSED\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type * as Status from './status.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface ConnectionStat {\n /**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * Once a multiplexer has been negotiated for this stream, it will be set on the stat object\n */\n multiplexer?: string\n\n /**\n * Once a connection encrypter has been negotiated for this stream, it will be set on the stat object\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: keyof typeof Status\n}\n\nexport interface StreamTimeline {\n open: number\n close?: number\n}\n\nexport interface StreamStat {\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * Once a protocol has been negotiated for this stream, it will be set on the stat object\n */\n protocol?: string\n}\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex {\n /**\n * Closes the stream for **reading** *and* **writing**.\n *\n * Any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `CLOSE` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink and the source will return normally.\n */\n close: () => void\n\n /**\n * Closes the stream for **reading**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * This function is called automatically by the muxer when it receives a `CLOSE` message from the remote.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeRead: () => void\n\n /**\n * Closes the stream for **writing**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeWrite: () => void\n\n /**\n * Closes the stream for **reading** *and* **writing**. This should be called when a *local error* has occurred.\n *\n * Note, if called without an error any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `RESET` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink will return and the source will throw if an error is passed or return normally if not.\n */\n abort: (err: Error) => void\n\n /**\n * Closes the stream *immediately* for **reading** *and* **writing**. This should be called when a *remote error* has occurred.\n *\n * This function is called automatically by the muxer when it receives a `RESET` message from the remote.\n *\n * The sink will return and the source will throw.\n */\n reset: () => void\n\n /**\n * Unique identifier for a stream. Identifiers are not unique across muxers.\n */\n id: string\n\n /**\n * Stats about this stream\n */\n stat: StreamStat\n\n /**\n * User defined stream metadata\n */\n metadata: Record\n}\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n id: string\n stat: ConnectionStat\n remoteAddr: Multiaddr\n remotePeer: PeerId\n tags: string[]\n streams: Stream[]\n\n newStream: (multicodecs: string | string[], options?: AbortOptions) => Promise\n addStream: (stream: Stream) => void\n removeStream: (id: string) => void\n close: () => Promise\n}\n\nexport const symbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface ConnectionGater {\n /**\n * denyDialMultiaddr tests whether we're permitted to Dial the\n * specified peer.\n *\n * This is called by the dialer.connectToPeer implementation before\n * dialling a peer.\n *\n * Return true to prevent dialing the passed peer.\n */\n denyDialPeer: (peerId: PeerId) => Promise\n\n /**\n * denyDialMultiaddr tests whether we're permitted to dial the specified\n * multiaddr for the given peer.\n *\n * This is called by the dialer.connectToPeer implementation after it has\n * resolved the peer's addrs, and prior to dialling each.\n *\n * Return true to prevent dialing the passed peer on the passed multiaddr.\n */\n denyDialMultiaddr: (peerId: PeerId, multiaddr: Multiaddr) => Promise\n\n /**\n * denyInboundConnection tests whether an incipient inbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has accepted a connection from its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyInboundConnection: (maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundConnection tests whether an incipient outbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has created a connection with its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyOutboundConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyInboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyOutboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyInboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyOutboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * Used by the address book to filter passed addresses.\n *\n * Return true to allow storing the passed multiaddr for the passed peer.\n */\n filterMultiaddrForPeer: (peer: PeerId, multiaddr: Multiaddr) => Promise\n}\n\nexport interface ConnectionProtector {\n\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect: (connection: MultiaddrConnection) => Promise\n}\n\nexport interface MultiaddrConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex {\n close: (err?: Error) => Promise\n remoteAddr: Multiaddr\n timeline: MultiaddrConnectionTimeline\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar'\nimport merge from 'merge-options'\nimport type { Registrar, StreamHandler, Topology } from '@libp2p/interface-registrar'\nimport type { PeerProtocolsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:registrar')\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\nexport interface RegistrarComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n peerStore: PeerStore\n}\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar implements Registrar {\n private readonly topologies: Map>\n private readonly handlers: Map\n private readonly components: RegistrarComponents\n\n constructor (components: RegistrarComponents) {\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onConnect = this._onConnect.bind(this)\n\n this.components.connectionManager.addEventListener('peer:disconnect', this._onDisconnect)\n this.components.connectionManager.addEventListener('peer:connect', this._onConnect)\n\n // happens after identify\n this.components.peerStore.addEventListener('change:protocols', this._onProtocolChange)\n }\n\n getProtocols () {\n return Array.from(new Set([\n ...this.topologies.keys(),\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string) {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL)\n }\n\n return handler\n }\n\n getTopologies (protocol: string) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise {\n if (this.handlers.has(protocol)) {\n throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocols to self protocols in the Protobook\n await this.components.peerStore.protoBook.add(this.components.peerId, [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: string | string[]) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Remove protocols from self protocols in the Protobook\n await this.components.peerStore.protoBook.remove(this.components.peerId, protocolList)\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise {\n if (!isTopology(topology)) {\n log.error('topology must be an instance of interfaces/topology')\n throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n // Set registrar\n await topology.setRegistrar(this)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.peerStore.protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(connection.remotePeer)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * On peer connected if we already have their protocols. Usually used for reconnects\n * as change:protocols event won't be emitted due to identical protocols.\n */\n _onConnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.peerStore.protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onConnect(connection.remotePeer, connection)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Check if a new peer support the multicodecs for this topology\n */\n _onProtocolChange (evt: CustomEvent) {\n const { peerId, protocols, oldProtocols } = evt.detail\n const removed = oldProtocols.filter(protocol => !protocols.includes(protocol))\n const added = protocols.filter(protocol => !oldProtocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(peerId)\n }\n }\n\n for (const protocol of added) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n const connection = this.components.connectionManager.getConnections(peerId)[0]\n\n if (connection == null) {\n continue\n }\n topology.onConnect(peerId, connection)\n }\n }\n }\n}\n", "import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n getProtocols: () => string[]\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n unhandle: (protocol: string) => Promise\n getHandler: (protocol: string) => StreamHandlerRecord\n\n register: (protocol: string, topology: Topology) => Promise\n unregister: (id: string) => void\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n onConnect?: onConnectHandler\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport { Identify } from './pb/message.js'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport {\n MULTICODEC_IDENTIFY,\n MULTICODEC_IDENTIFY_PUSH,\n IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION\n} from './consts.js'\nimport { codes } from '../errors.js'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:identify')\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8\n\nexport interface HostProperties {\n agentVersion: string\n}\n\nexport interface IdentifyServiceInit {\n /**\n * The prefix to use for the protocol (default: 'ipfs')\n */\n protocolPrefix: string\n\n /**\n * What details we should send as part of an identify message\n */\n host: HostProperties\n\n /**\n * How long we should wait for a remote peer to send their identify response\n */\n timeout: number\n\n /**\n * Identify responses larger than this in bytes will be rejected (default: 8192)\n */\n maxIdentifyMessageSize?: number\n\n maxInboundStreams: number\n maxOutboundStreams: number\n\n maxPushIncomingStreams: number\n maxPushOutgoingStreams: number\n}\n\nexport interface IdentifyServiceComponents {\n peerId: PeerId\n peerStore: PeerStore\n connectionManager: ConnectionManager\n registrar: Registrar\n addressManager: AddressManager\n}\n\nexport class IdentifyService implements Startable {\n private readonly components: IdentifyServiceComponents\n private readonly identifyProtocolStr: string\n private readonly identifyPushProtocolStr: string\n public readonly host: {\n protocolVersion: string\n agentVersion: string\n }\n\n private readonly init: IdentifyServiceInit\n private started: boolean\n\n constructor (components: IdentifyServiceComponents, init: IdentifyServiceInit) {\n this.components = components\n this.started = false\n this.init = init\n\n this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`\n this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`\n\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n ...init.host\n }\n\n // When a new connection happens, trigger identify\n this.components.connectionManager.addEventListener('peer:connect', (evt) => {\n const connection = evt.detail\n this.identify(connection).catch(log.error)\n })\n\n // When self multiaddrs change, trigger identify-push\n this.components.peerStore.addEventListener('change:multiaddrs', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.peerId.equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n\n // When self protocols change, trigger identify-push\n this.components.peerStore.addEventListener('change:protocols', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.peerId.equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n if (this.started) {\n return\n }\n\n await this.components.peerStore.metadataBook.setValue(this.components.peerId, 'AgentVersion', uint8ArrayFromString(this.host.agentVersion))\n await this.components.peerStore.metadataBook.setValue(this.components.peerId, 'ProtocolVersion', uint8ArrayFromString(this.host.protocolVersion))\n\n await this.components.registrar.handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n await this.components.registrar.handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxPushIncomingStreams,\n maxOutboundStreams: this.init.maxPushOutgoingStreams\n })\n\n this.started = true\n }\n\n async stop () {\n await this.components.registrar.unhandle(this.identifyProtocolStr)\n await this.components.registrar.unhandle(this.identifyPushProtocolStr)\n\n this.started = false\n }\n\n /**\n * Send an Identify Push update to the list of connections\n */\n async push (connections: Connection[]): Promise {\n const signedPeerRecord = await this.components.peerStore.addressBook.getRawEnvelope(this.components.peerId)\n const listenAddrs = this.components.addressManager.getAddresses().map((ma) => ma.bytes)\n const protocols = await this.components.peerStore.protoBook.get(this.components.peerId)\n\n const pushes = connections.map(async connection => {\n let stream: Stream | undefined\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n stream = await connection.newStream([this.identifyPushProtocolStr], {\n signal: timeoutController.signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await source.sink(pipe(\n [Identify.encode({\n listenAddrs,\n signedPeerRecord,\n protocols\n })],\n lp.encode()\n ))\n } catch (err: any) {\n // Just log errors\n log.error('could not push identify update to peer', err)\n } finally {\n if (stream != null) {\n stream.close()\n }\n\n timeoutController.clear()\n }\n })\n\n await Promise.all(pushes)\n }\n\n /**\n * Calls `push` on all peer connections\n */\n async pushToPeerStore () {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return\n }\n\n const connections: Connection[] = []\n\n for (const conn of this.components.connectionManager.getConnections()) {\n const peerId = conn.remotePeer\n const peer = await this.components.peerStore.get(peerId)\n\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n continue\n }\n\n connections.push(conn)\n }\n\n await this.push(connections)\n }\n\n async _identify (connection: Connection, options: AbortOptions = {}): Promise {\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.identifyProtocolStr], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data == null) {\n throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED)\n }\n\n try {\n return Identify.decode(data)\n } catch (err: any) {\n throw errCode(err, codes.ERR_INVALID_MESSAGE)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Requests the `Identify` message from peer associated with the given `connection`.\n * If the identified peer does not match the `PeerId` associated with the connection,\n * an error will be thrown.\n */\n async identify (connection: Connection, options: AbortOptions = {}): Promise {\n const message = await this._identify(connection, options)\n\n const {\n publicKey,\n listenAddrs,\n protocols,\n observedAddr,\n signedPeerRecord,\n agentVersion,\n protocolVersion\n } = message\n\n if (publicKey == null) {\n throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY)\n }\n\n const id = await peerIdFromKeys(publicKey)\n\n if (!connection.remotePeer.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (this.components.peerId.equals(id)) {\n throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER)\n }\n\n // Get the observedAddr if there is one\n const cleanObservedAddr = IdentifyService.getCleanMultiaddr(observedAddr)\n\n if (signedPeerRecord != null) {\n log('received signed peer record from %p', id)\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN)\n\n if (!envelope.peerId.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (await this.components.peerStore.addressBook.consumePeerRecord(envelope)) {\n await this.components.peerStore.protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n return\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('no signed peer record received from %p', id)\n }\n\n log('falling back to legacy addresses from %p', id)\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.peerStore.addressBook.set(id, listenAddrs.map((addr) => multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n await this.components.peerStore.protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n // TODO: Add and score our observed addr\n log('received observed address of %s', cleanObservedAddr?.toString())\n // this.components.addressManager.addObservedAddr(observedAddr)\n }\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: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const publicKey = this.components.peerId.publicKey ?? new Uint8Array(0)\n const peerData = await this.components.peerStore.get(this.components.peerId)\n const multiaddrs = this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n let signedPeerRecord = peerData.peerRecordEnvelope\n\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.components.peerId,\n multiaddrs\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.peerId)\n await this.components.peerStore.addressBook.consumePeerRecord(envelope)\n signedPeerRecord = envelope.marshal().subarray()\n }\n\n const message = Identify.encode({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr: connection.remoteAddr.bytes,\n protocols: peerData.protocols\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const msgWithLenPrefix = pipe([message], lp.encode())\n await source.sink(msgWithLenPrefix)\n } catch (err: any) {\n log.error('could not respond to identify request', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n }\n\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n let message: Identify | undefined\n try {\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data != null) {\n message = Identify.decode(data)\n }\n } catch (err: any) {\n return log.error('received invalid message', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n\n if (message == null) {\n return log.error('received invalid message')\n }\n\n const id = connection.remotePeer\n\n if (this.components.peerId.equals(id)) {\n log('received push from ourselves?')\n return\n }\n\n log('received push from %p', id)\n\n if (message.signedPeerRecord != null) {\n log('received signedPeerRecord in push')\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(message.signedPeerRecord, PeerRecord.DOMAIN)\n\n if (await this.components.peerStore.addressBook.consumePeerRecord(envelope)) {\n log('consumed signedPeerRecord sent in push')\n\n await this.components.peerStore.protoBook.set(id, message.protocols)\n return\n } else {\n log('failed to consume signedPeerRecord sent in push')\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('did not receive signedPeerRecord in push')\n }\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.peerStore.addressBook.set(id,\n message.listenAddrs.map((addr) => multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n // Update the protocols\n try {\n await this.components.peerStore.protoBook.set(id, message.protocols)\n } catch (err: any) {\n log.error('received invalid protocols', err)\n }\n\n log('handled push from %p', id)\n }\n\n /**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\n static getCleanMultiaddr (addr: Uint8Array | string | null | undefined) {\n if (addr != null && addr.length > 0) {\n try {\n return multiaddr(addr)\n } catch {\n\n }\n }\n }\n}\n\n/**\n * The protocols the IdentifyService supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n}\n\nexport const Message = { Identify }\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Identify {\n protocolVersion?: string\n agentVersion?: string\n publicKey?: Uint8Array\n listenAddrs: Uint8Array[]\n observedAddr?: Uint8Array\n protocols: string[]\n signedPeerRecord?: Uint8Array\n}\n\nexport namespace Identify {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.protocolVersion != null) {\n w.uint32(42)\n w.string(obj.protocolVersion)\n }\n\n if (obj.agentVersion != null) {\n w.uint32(50)\n w.string(obj.agentVersion)\n }\n\n if (obj.publicKey != null) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (obj.observedAddr != null) {\n w.uint32(34)\n w.bytes(obj.observedAddr)\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(26)\n w.string(value)\n }\n }\n\n if (obj.signedPeerRecord != null) {\n w.uint32(66)\n w.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n listenAddrs: [],\n protocols: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Identify): Uint8Array => {\n return encodeMessage(obj, Identify.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {\n return decodeMessage(buf, Identify.codec())\n }\n}\n", "import errCode from 'err-code'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\n\nexport interface RecordEnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\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: Record, peerId: PeerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\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\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\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: Uint8Array | Uint8ArrayList, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\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\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\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\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n", "\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if (opts.writeDefaults === true || (obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if (opts.writeDefaults === true || (obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if (opts.writeDefaults === true || (obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\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/**\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: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n\n if (a.length !== b.length) {\n return false\n }\n\n b.sort(sort)\n\n return a.sort(sort).every((item, index) => b[index].equals(item))\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.peerId)\n }\n\n if (opts.writeDefaults === true || obj.seq !== 0n) {\n w.uint32(16)\n w.uint64(obj.seq)\n }\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 writeDefaults: true\n })\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n", "\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\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", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\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 */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\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\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\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\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n", "export const version = '0.42.2'\nexport const name = 'libp2p'\n", "\nimport { version } from '../version.js'\n\nexport const PROTOCOL_VERSION = 'ipfs/0.1.0' // deprecated\nexport const AGENT_VERSION = `js-libp2p/${version}`\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0' // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0' // deprecated\n\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", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport * as lp from 'it-length-prefixed'\nimport { FetchRequest, FetchResponse } from './pb/proto.js'\nimport { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport { fromString as uint8arrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8arrayToString } from 'uint8arrays/to-string'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nconst log = logger('libp2p:fetch')\n\nexport interface FetchServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a remote peer to send any data\n */\n timeout: number\n}\n\nexport interface HandleMessageOptions {\n stream: Stream\n protocol: string\n}\n\nexport interface LookupFunction {\n (key: string): Promise\n}\n\nexport interface FetchServiceComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\n/**\n * A simple libp2p protocol for requesting a value corresponding to a key from a peer.\n * Developers can register one or more lookup function for retrieving the value corresponding to\n * a given key. Each lookup function must act on a distinct part of the overall key space, defined\n * by a fixed prefix that all keys that should be routed to that lookup function will start with.\n */\nexport class FetchService implements Startable {\n public readonly protocol: string\n private readonly components: FetchServiceComponents\n private readonly lookupFunctions: Map\n private started: boolean\n private readonly init: FetchServiceInit\n\n constructor (components: FetchServiceComponents, init: FetchServiceInit) {\n this.started = false\n this.components = components\n this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.lookupFunctions = new Map() // Maps key prefix to value lookup function\n this.handleMessage = this.handleMessage.bind(this)\n this.init = init\n }\n\n async start () {\n await this.components.registrar.handle(this.protocol, (data) => {\n void this.handleMessage(data)\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n data.stream.close()\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer\n */\n async fetch (peer: PeerId, key: string, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const connection = await this.components.connectionManager.openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n log('using default timeout of %d ms', this.init.timeout)\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream(this.protocol, {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n log('fetch %s', key)\n\n const result = await pipe(\n [FetchRequest.encode({ identifier: key })],\n lp.encode(),\n source,\n lp.decode(),\n async function (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n const response = FetchResponse.decode(buf)\n\n switch (response.status) {\n case (FetchResponse.StatusCode.OK): {\n log('received status for %s ok', key)\n return response.data\n }\n case (FetchResponse.StatusCode.NOT_FOUND): {\n log('received status for %s not found', key)\n return null\n }\n case (FetchResponse.StatusCode.ERROR): {\n log('received status for %s error', key)\n const errmsg = uint8arrayToString(response.data)\n throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)\n }\n default: {\n log('received status for %s unknown', key)\n throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)\n }\n }\n }\n )\n\n return result ?? null\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Invoked when a fetch request is received. Reads the request message off the given stream and\n * responds based on looking up the key in the request via the lookup callback that corresponds\n * to the key's prefix.\n */\n async handleMessage (data: IncomingStreamData) {\n const { stream } = data\n const self = this\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n // for await (const buf of source) {\n const request = FetchRequest.decode(buf)\n\n let response: FetchResponse\n const lookup = self._getLookupFunction(request.identifier)\n if (lookup != null) {\n log('look up data with identifier %s', request.identifier)\n const data = await lookup(request.identifier)\n if (data != null) {\n log('sending status for %s ok', request.identifier)\n response = { status: FetchResponse.StatusCode.OK, data }\n } else {\n log('sending status for %s not found', request.identifier)\n response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }\n }\n } else {\n log('sending status for %s error', request.identifier)\n const errmsg = uint8arrayFromString(`No lookup function registered for key: ${request.identifier}`)\n response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }\n }\n\n yield FetchResponse.encode(response)\n },\n lp.encode(),\n stream\n )\n }\n\n /**\n * Given a key, finds the appropriate function for looking up its corresponding value, based on\n * the key's prefix.\n */\n _getLookupFunction (key: string) {\n for (const prefix of this.lookupFunctions.keys()) {\n if (key.startsWith(prefix)) {\n return this.lookupFunctions.get(prefix)\n }\n }\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix\n *\n * @example\n *\n * ```js\n * // ...\n * libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })\n * ```\n */\n registerLookupFunction (prefix: string, lookup: LookupFunction) {\n if (this.lookupFunctions.has(prefix)) {\n throw errCode(new Error(\"Fetch protocol handler for key prefix '\" + prefix + \"' already registered\"), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n this.lookupFunctions.set(prefix, lookup)\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix.\n *\n * @example\n *\n * ```js\n * // ...\n * libp2p.fetchService.unregisterLookupFunction('/prefix')\n * ```\n */\n unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {\n if (lookup != null) {\n const existingLookup = this.lookupFunctions.get(prefix)\n\n if (existingLookup !== lookup) {\n return\n }\n }\n\n this.lookupFunctions.delete(prefix)\n }\n}\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\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface FetchRequest {\n identifier: string\n}\n\nexport namespace FetchRequest {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || obj.identifier !== '') {\n w.uint32(10)\n w.string(obj.identifier)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n identifier: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identifier = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchRequest): Uint8Array => {\n return encodeMessage(obj, FetchRequest.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchRequest => {\n return decodeMessage(buf, FetchRequest.codec())\n }\n}\n\nexport interface FetchResponse {\n status: FetchResponse.StatusCode\n data: Uint8Array\n}\n\nexport namespace FetchResponse {\n export enum StatusCode {\n OK = 'OK',\n NOT_FOUND = 'NOT_FOUND',\n ERROR = 'ERROR'\n }\n\n enum __StatusCodeValues {\n OK = 0,\n NOT_FOUND = 1,\n ERROR = 2\n }\n\n export namespace StatusCode {\n export const codec = () => {\n return enumeration(__StatusCodeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.status != null && __StatusCodeValues[obj.status] !== 0)) {\n w.uint32(8)\n FetchResponse.StatusCode.codec().encode(obj.status, w)\n }\n\n if (opts.writeDefaults === true || (obj.data != null && obj.data.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n status: StatusCode.OK,\n data: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.status = FetchResponse.StatusCode.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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchResponse): Uint8Array => {\n return encodeMessage(obj, FetchResponse.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchResponse => {\n return decodeMessage(buf, FetchResponse.codec())\n }\n}\n", "\n// https://github.com/libp2p/specs/tree/master/fetch#wire-protocol\nexport const PROTOCOL_VERSION = '0.0.1'\nexport const PROTOCOL_NAME = 'fetch'\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { randomBytes } from '@libp2p/crypto'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION } from './constants.js'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { setMaxListeners } from 'events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nconst log = logger('libp2p:ping')\n\nexport interface PingServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a ping response\n */\n timeout: number\n}\n\nexport interface PingServiceComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport class PingService implements Startable {\n public readonly protocol: string\n private readonly components: PingServiceComponents\n private started: boolean\n private readonly init: PingServiceInit\n\n constructor (components: PingServiceComponents, init: PingServiceInit) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.init = init\n }\n\n async start () {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData) {\n const { stream } = data\n\n void pipe(stream, stream)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n *\n * @param {PeerId|Multiaddr} peer\n * @returns {Promise}\n */\n async ping (peer: PeerId, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.connectionManager.openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [data],\n source,\n async (source) => await first(source)\n )\n const end = Date.now()\n\n if (result == null || !uint8ArrayEquals(data, result.subarray())) {\n throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK)\n }\n\n return end - start\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n}\n", "\nexport const PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\n", "\nexport async function upnpNat () {\n throw new Error('Not supported in browsers')\n}\n\nexport async function pmpNat () {\n throw new Error('Not supported in browsers')\n}\n", "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 { upnpNat, NatAPI } from '@achingbrain/nat-port-mapper'\nimport { logger } from '@libp2p/logger'\nimport { fromNodeAddress } from '@multiformats/multiaddr'\nimport { isBrowser } from 'wherearewe'\nimport isPrivateIp from 'private-ip'\nimport * as pkg from './version.js'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { TransportManager } from '@libp2p/interface-transport'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:nat')\nconst DEFAULT_TTL = 7200\n\nfunction highPort (min = 1024, max = 65535) {\n return Math.floor(Math.random() * (max - min + 1) + min)\n}\n\nexport interface PMPOptions {\n /**\n * Whether to enable PMP as well as UPnP\n */\n enabled?: boolean\n}\n\nexport interface NatManagerInit {\n /**\n * Whether to enable the NAT manager\n */\n enabled: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n externalAddress?: string\n\n /**\n * Pass a value to use instead of auto-detection\n */\n localAddress?: string\n\n /**\n * A string value to use for the port mapping description on the gateway\n */\n description?: string\n\n /**\n * How long UPnP port mappings should last for in seconds (minimum 1200)\n */\n ttl?: number\n\n /**\n * Whether to automatically refresh UPnP port mappings when their TTL is reached\n */\n keepAlive: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n gateway?: string\n}\n\nexport interface NatManagerComponents {\n peerId: PeerId\n transportManager: TransportManager\n addressManager: AddressManager\n}\n\nexport class NatManager implements Startable {\n private readonly components: NatManagerComponents\n private readonly enabled: boolean\n private readonly externalAddress?: string\n private readonly localAddress?: string\n private readonly description: string\n private readonly ttl: number\n private readonly keepAlive: boolean\n private readonly gateway?: string\n private started: boolean\n private client?: NatAPI\n\n constructor (components: NatManagerComponents, init: NatManagerInit) {\n this.components = components\n\n this.started = false\n this.enabled = init.enabled\n this.externalAddress = init.externalAddress\n this.localAddress = init.localAddress\n this.description = init.description ?? `${pkg.name}@${pkg.version} ${this.components.peerId.toString()}`\n this.ttl = init.ttl ?? DEFAULT_TTL\n this.keepAlive = init.keepAlive ?? true\n this.gateway = init.gateway\n\n if (this.ttl < DEFAULT_TTL) {\n throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n start () {}\n\n /**\n * Attempt to use uPnP to configure port mapping using the current gateway.\n *\n * Run after start to ensure the transport manager has all addresses configured.\n */\n afterStart () {\n if (isBrowser || !this.enabled || this.started) {\n return\n }\n\n this.started = true\n\n // done async to not slow down startup\n void this._start().catch((err) => {\n // hole punching errors are non-fatal\n log.error(err)\n })\n }\n\n async _start () {\n const addrs = this.components.transportManager.getAddrs()\n\n for (const addr of addrs) {\n // try to open uPnP ports for each thin waist address\n const { family, host, port, transport } = addr.toOptions()\n\n if (!addr.isThinWaistAddress() || transport !== 'tcp') {\n // only bare tcp addresses\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (isLoopback(addr)) {\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (family !== 4) {\n // ignore ipv6\n // eslint-disable-next-line no-continue\n continue\n }\n\n const client = await this._getClient()\n const publicIp = this.externalAddress ?? await client.externalIp()\n const isPrivate = isPrivateIp(publicIp)\n\n if (isPrivate === true) {\n throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)\n }\n\n if (isPrivate == null) {\n throw new Error(`${publicIp} is not an IP address`)\n }\n\n const publicPort = highPort()\n\n log(`opening uPnP connection from ${publicIp}:${publicPort} to ${host}:${port}`)\n\n await client.map({\n publicPort,\n localPort: port,\n localAddress: this.localAddress,\n protocol: transport.toUpperCase() === 'TCP' ? 'TCP' : 'UDP'\n })\n\n this.components.addressManager.addObservedAddr(fromNodeAddress({\n family: 4,\n address: publicIp,\n port: publicPort\n }, transport))\n }\n }\n\n async _getClient () {\n if (this.client != null) {\n return this.client\n }\n\n this.client = await upnpNat({\n description: this.description,\n ttl: this.ttl,\n keepAlive: this.keepAlive,\n gateway: this.gateway\n })\n\n return this.client\n }\n\n /**\n * Stops the NAT manager\n */\n async stop () {\n if (isBrowser || this.client == null) {\n return\n }\n\n try {\n await this.client.close()\n this.client = undefined\n } catch (err: any) {\n log.error(err)\n }\n }\n}\n", "/**\n * Check if a given ip address is a loopback address\n */\nexport function isLoopbackAddr (ip: string) {\n return /^127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n /^::1$/.test(ip)\n}\n", "import { isLoopbackAddr } from 'is-loopback-addr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr is a loopback address.\n */\nexport function isLoopback (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return isLoopbackAddr(address)\n}\n", "import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { logger } from '@libp2p/logger'\nimport { protocols } from '@multiformats/multiaddr'\nimport type { TransportManager } from '@libp2p/interface-transport'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:peer-record-updater')\n\nexport interface PeerRecordUpdaterComponents {\n peerId: PeerId\n peerStore: PeerStore\n transportManager: TransportManager\n addressManager: AddressManager\n}\n\nexport class PeerRecordUpdater implements Startable {\n private readonly components: PeerRecordUpdaterComponents\n private started: boolean\n\n constructor (components: PeerRecordUpdaterComponents) {\n this.components = components\n this.started = false\n this.update = this.update.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n this.components.transportManager.addEventListener('listener:listening', this.update)\n this.components.transportManager.addEventListener('listener:close', this.update)\n this.components.addressManager.addEventListener('change:addresses', this.update)\n }\n\n async stop () {\n this.started = false\n this.components.transportManager.removeEventListener('listener:listening', this.update)\n this.components.transportManager.removeEventListener('listener:close', this.update)\n this.components.addressManager.removeEventListener('change:addresses', this.update)\n }\n\n /**\n * Create (or update if existing) self peer record and store it in the AddressBook.\n */\n update () {\n Promise.resolve()\n .then(async () => {\n const peerRecord = new PeerRecord({\n peerId: this.components.peerId,\n multiaddrs: this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.peerId)\n await this.components.peerStore.addressBook.consumePeerRecord(envelope)\n })\n .catch(err => {\n log.error('Could not update self peer record: %o', err)\n })\n }\n}\n", "import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTPeerRouting implements PeerRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async findPeer (peerId: PeerId, options: AbortOptions = {}) {\n for await (const event of this.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n return event.peer\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}) {\n for await (const event of this.dht.getClosestPeers(key, options)) {\n if (event.name === 'FINAL_PEER') {\n yield event.peer\n }\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport { codes } from './errors.js'\nimport { PeerRecord, RecordEnvelope } from '@libp2p/peer-record'\nimport { pipe } from 'it-pipe'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport each from 'it-foreach'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { AddressFilter, Peer, PeerMultiaddrsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Store } from './store.js'\nimport type { Envelope } from '@libp2p/interface-record'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:peer-store:address-book')\nconst EVENT_NAME = 'change:multiaddrs'\n\nasync function allowAll () {\n return true\n}\n\nexport class PeerStoreAddressBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n private readonly addressFilter: AddressFilter\n\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store, addressFilter?: AddressFilter) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n this.addressFilter = addressFilter ?? allowAll\n }\n\n /**\n * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope.\n * This will return a boolean that indicates if the record was successfully processed and added\n * into the AddressBook.\n */\n async consumePeerRecord (envelope: Envelope) {\n log.trace('consumePeerRecord await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('consumePeerRecord got write lock')\n\n let peerId\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n let peerRecord\n try {\n peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n } catch (err: any) {\n log.error('invalid peer record received')\n return false\n }\n\n peerId = peerRecord.peerId\n const multiaddrs = peerRecord.multiaddrs\n\n // Verify peerId\n if (!peerId.equals(envelope.peerId)) {\n log('signing key does not match PeerId in the PeerRecord')\n return false\n }\n\n // ensure the record has multiaddrs\n if (multiaddrs == null || multiaddrs.length === 0) {\n return false\n }\n\n if (await this.store.has(peerId)) {\n peer = await this.store.load(peerId)\n\n if (peer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\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 return false\n }\n }\n }\n\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter, true)\n\n // Replace unsigned addresses by the new ones from the record\n // TODO: Once we have ttls for the addresses, we should merge these in\n updatedPeer = await this.store.patchOrCreate(peerId, {\n addresses,\n peerRecordEnvelope: envelope.marshal().subarray()\n })\n\n log('stored provided peer record for %p', peerRecord.peerId)\n } finally {\n log.trace('consumePeerRecord release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(({ multiaddr }) => multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n return true\n }\n\n async getRawEnvelope (peerId: PeerId) {\n log.trace('getRawEnvelope await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getRawEnvelope got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.peerRecordEnvelope\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getRawEnvelope release read lock')\n release()\n }\n }\n\n /**\n * Get an Envelope containing a PeerRecord for the given peer.\n * Returns undefined if no record exists.\n */\n async getPeerRecord (peerId: PeerId) {\n const raw = await this.getRawEnvelope(peerId)\n\n if (raw == null) {\n return undefined\n }\n\n return await RecordEnvelope.createFromProtobuf(raw)\n }\n\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.addresses\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let hasPeer = false\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length && addresses.length === peer.addresses.length) {\n // not changing anything, no need to update\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, { addresses })\n\n log('set multiaddrs for %p', peerId)\n } finally {\n log.trace('set multiaddrs for %p', peerId)\n log('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (!hasPeer) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async add (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let hasPeer\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, { addresses })\n\n log('added multiaddrs for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (hasPeer === true) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n addresses: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: [],\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n }\n }\n}\n\nasync function filterMultiaddrs (peerId: PeerId, multiaddrs: Multiaddr[], addressFilter: AddressFilter, isCertified: boolean = false) {\n return await pipe(\n multiaddrs,\n (source) => each(source, (multiaddr) => {\n if (!isMultiaddr(multiaddr)) {\n log.error('multiaddr must be an instance of Multiaddr')\n throw errcode(new Error('multiaddr must be an instance of Multiaddr'), codes.ERR_INVALID_PARAMETERS)\n }\n }),\n (source) => filter(source, async (multiaddr) => await addressFilter(peerId, multiaddr)),\n (source) => map(source, (multiaddr) => {\n return {\n multiaddr,\n isCertified\n }\n }),\n async (source) => await all(source)\n )\n}\n", "\nexport const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS',\n ERR_NOT_FOUND: 'ERR_NOT_FOUND'\n}\n", "\n/**\n * Invokes the passed function for each item in an iterable\n */\nexport default async function * forEach (source: AsyncIterable|Iterable, fn: (thing: T) => void | Promise): AsyncGenerator {\n for await (const thing of source) {\n await fn(thing)\n yield thing\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, KeyBook, PeerPublicKeyChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:key-book')\n\nconst EVENT_NAME = 'change:pubkey'\n\nexport class PeerStoreKeyBook implements KeyBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The KeyBook is responsible for keeping the known public keys of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Set the Peer public key\n */\n async set (peerId: PeerId, publicKey: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(publicKey instanceof Uint8Array)) {\n log.error('publicKey must be an instance of Uint8Array to store data')\n throw errcode(new Error('publicKey must be an instance of PublicKey'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let updatedKey = false\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if ((peer.pubKey != null) && uint8arrayEquals(peer.pubKey, publicKey)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: publicKey\n })\n updatedKey = true\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n if (updatedKey) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: publicKey,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n }\n\n /**\n * Get Public key of the given PeerId, if stored\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await write lock')\n const release = await this.store.lock.readLock()\n log.trace('get got write lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.pubKey\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log('get release write lock')\n release()\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: undefined\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: undefined,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, MetadataBook, PeerMetadataChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:metadata-book')\n\nconst EVENT_NAME = 'change:metadata'\n\nexport class PeerStoreMetadataBook implements MetadataBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The MetadataBook is responsible for keeping metadata\n * about known peers\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Get the known data of a provided peer\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return new Map()\n }\n\n /**\n * Get specific metadata value, if it exists\n */\n async getValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('getValue await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getValue got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata.get(key)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getValue release write lock')\n release()\n }\n }\n\n async set (peerId: PeerId, metadata: Map) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(metadata instanceof Map)) {\n log.error('valid metadata must be provided to store data')\n throw errcode(new Error('valid metadata must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.mergeOrCreate(peerId, {\n metadata\n })\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n /**\n * Set metadata key and value of a provided peer\n */\n async setValue (peerId: PeerId, key: string, value: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (typeof key !== 'string' || !(value instanceof Uint8Array)) {\n log.error('valid key and value must be provided to store data')\n throw errcode(new Error('valid key and value must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('setValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('setValue got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const existingValue = peer.metadata.get(key)\n\n if (existingValue != null && uint8ArrayEquals(value, existingValue)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n metadata: new Map([[key, value]])\n })\n } finally {\n log.trace('setValue release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: updatedPeer.metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n if (peer != null) {\n await this.store.patch(peerId, {\n metadata: new Map()\n })\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: new Map(),\n oldMetadata: peer.metadata\n }\n }))\n }\n }\n\n async deleteValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('deleteValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('deleteValue got write lock')\n\n let metadata\n let peer: Peer | undefined\n\n try {\n peer = await this.store.load(peerId)\n metadata = peer.metadata\n\n metadata.delete(key)\n\n await this.store.patch(peerId, {\n metadata\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('deleteValue release write lock')\n release()\n }\n\n if (metadata != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { Peer, PeerProtocolsChangeData, PeerStore, ProtoBook } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:proto-book')\n\nconst EVENT_NAME = 'change:protocols'\n\nexport class PeerStoreProtoBook implements ProtoBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The ProtoBook is responsible for keeping the known supported\n * protocols of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n async get (peerId: PeerId) {\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.protocols\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n\n log('stored provided protocols for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async add (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...peer.protocols,\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n protocols\n })\n\n log('added provided protocols for %p', peerId)\n } finally {\n log.trace('add release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async remove (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('remove await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('remove got write lock')\n\n let peer: Peer | undefined\n let updatedPeer: Peer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const protocolSet = new Set(peer.protocols)\n\n for (const protocol of protocols) {\n protocolSet.delete(protocol)\n }\n\n if (peer.protocols.length === protocolSet.size) {\n return\n }\n\n protocols = Array.from(protocolSet)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n } finally {\n log.trace('remove release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n protocols: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: [],\n oldProtocols: peer.protocols\n }\n }))\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { Metadata, Peer as PeerPB } from './pb/peer.js'\nimport mortice from 'mortice'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport type { Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PersistentPeerStoreComponents } from './index.js'\n\nconst log = logger('libp2p:peer-store:store')\n\nconst NAMESPACE_COMMON = '/peers/'\n\nexport interface Store {\n has: (peerId: PeerId) => Promise\n save: (peer: Peer) => Promise\n load: (peerId: PeerId) => Promise\n delete: (peerId: PeerId) => Promise\n merge: (peerId: PeerId, data: Partial) => Promise\n mergeOrCreate: (peerId: PeerId, data: Partial) => Promise\n patch: (peerId: PeerId, data: Partial) => Promise\n patchOrCreate: (peerId: PeerId, data: Partial) => Promise\n all: () => AsyncIterable\n\n lock: {\n readLock: () => Promise<() => void>\n writeLock: () => Promise<() => void>\n }\n}\n\nexport class PersistentStore {\n private readonly components: PersistentPeerStoreComponents\n public lock: any\n\n constructor (components: PersistentPeerStoreComponents) {\n this.components = components\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n }\n\n _peerIdToDatastoreKey (peerId: PeerId) {\n if (peerId.type == null) {\n log.error('peerId must be an instance of peer-id to store data')\n throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n }\n\n async has (peerId: PeerId) {\n return await this.components.datastore.has(this._peerIdToDatastoreKey(peerId))\n }\n\n async delete (peerId: PeerId) {\n await this.components.datastore.delete(this._peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise {\n const buf = await this.components.datastore.get(this._peerIdToDatastoreKey(peerId))\n const peer = PeerPB.decode(buf)\n const metadata = new Map()\n\n for (const meta of peer.metadata) {\n metadata.set(meta.key, meta.value)\n }\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,\n pubKey: peer.pubKey ?? undefined,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined\n }\n }\n\n async save (peer: Peer) {\n if (peer.pubKey != null && peer.id.publicKey != null && !uint8arrayEquals(peer.pubKey, peer.id.publicKey)) {\n log.error('peer publicKey bytes do not match peer id publicKey bytes')\n throw errcode(new Error('publicKey bytes do not match peer id publicKey bytes'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // dedupe addresses\n const addressSet = new Set()\n const addresses = peer.addresses\n .filter(address => {\n if (addressSet.has(address.multiaddr.toString())) {\n return false\n }\n\n addressSet.add(address.multiaddr.toString())\n return true\n })\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ multiaddr, isCertified }) => ({\n multiaddr: multiaddr.bytes,\n isCertified\n }))\n\n const metadata: Metadata[] = []\n\n ;[...peer.metadata.keys()].sort().forEach(key => {\n const value = peer.metadata.get(key)\n\n if (value != null) {\n metadata.push({ key, value })\n }\n })\n\n const buf = PeerPB.encode({\n addresses,\n protocols: peer.protocols.sort(),\n pubKey: peer.pubKey,\n metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope\n })\n\n await this.components.datastore.put(this._peerIdToDatastoreKey(peer.id), buf.subarray())\n\n return await this.load(peer.id)\n }\n\n async patch (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._patch(peerId, data, peer)\n }\n\n async patchOrCreate (peerId: PeerId, data: Partial) {\n let peer: Peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._patch(peerId, data, peer)\n }\n\n async _patch (peerId: PeerId, data: Partial, peer: Peer) {\n return await this.save({\n ...peer,\n ...data,\n id: peerId\n })\n }\n\n async merge (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._merge(peerId, data, peer)\n }\n\n async mergeOrCreate (peerId: PeerId, data: Partial) {\n /** @type {Peer} */\n let peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._merge(peerId, data, peer)\n }\n\n async _merge (peerId: PeerId, data: Partial, peer: Peer) {\n // if the peer has certified addresses, use those in\n // favour of the supplied versions\n const addresses = new Map()\n\n peer.addresses.forEach((addr) => {\n addresses.set(addr.multiaddr.toString(), addr.isCertified)\n })\n\n ;(data.addresses ?? []).forEach(addr => {\n const addrString = addr.multiaddr.toString()\n const isAlreadyCertified = Boolean(addresses.get(addrString))\n\n const isCertified = isAlreadyCertified || addr.isCertified\n\n addresses.set(addrString, isCertified)\n })\n\n return await this.save({\n id: peerId,\n addresses: Array.from(addresses.entries()).map(([addrStr, isCertified]) => {\n return {\n multiaddr: multiaddr(addrStr),\n isCertified\n }\n }),\n protocols: Array.from(new Set([\n ...(peer.protocols ?? []),\n ...(data.protocols ?? [])\n ])),\n metadata: new Map([\n ...(peer.metadata?.entries() ?? []),\n ...(data.metadata?.entries() ?? [])\n ]),\n pubKey: data.pubKey ?? (peer != null ? peer.pubKey : undefined),\n peerRecordEnvelope: data.peerRecordEnvelope ?? (peer != null ? peer.peerRecordEnvelope : undefined)\n })\n }\n\n async * all () {\n for await (const key of this.components.datastore.queryKeys({\n prefix: NAMESPACE_COMMON\n })) {\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\n yield this.load(peerIdFromBytes(buf))\n }\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n metadata: Metadata[]\n pubKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n}\n\nexport namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10)\n Address.codec().encode(value, w, {\n writeDefaults: true\n })\n }\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\n if (obj.metadata != null) {\n for (const value of obj.metadata) {\n w.uint32(26)\n Metadata.codec().encode(value, w, {\n writeDefaults: true\n })\n }\n }\n\n if (obj.pubKey != null) {\n w.uint32(34)\n w.bytes(obj.pubKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42)\n w.bytes(obj.peerRecordEnvelope)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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 3:\n obj.metadata.push(Metadata.codec().decode(reader, reader.uint32()))\n break\n case 4:\n obj.pubKey = reader.bytes()\n break\n case 5:\n obj.peerRecordEnvelope = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n}\n\nexport namespace Address {\n let _codec: Codec

    \n\n export const codec = (): Codec
    => {\n if (_codec == null) {\n _codec = message
    ((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (obj.isCertified != null) {\n w.uint32(16)\n w.bool(obj.isCertified)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Address): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Address => {\n return decodeMessage(buf, Address.codec())\n }\n}\n\nexport interface Metadata {\n key: string\n value: Uint8Array\n}\n\nexport namespace Metadata {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || obj.key !== '') {\n w.uint32(10)\n w.string(obj.key)\n }\n\n if (opts.writeDefaults === true || (obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: '',\n value: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Metadata): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { PeerStoreAddressBook } from './address-book.js'\nimport { PeerStoreKeyBook } from './key-book.js'\nimport { PeerStoreMetadataBook } from './metadata-book.js'\nimport { PeerStoreProtoBook } from './proto-book.js'\nimport { PersistentStore, Store } from './store.js'\nimport type { PeerStore, AddressBook, KeyBook, MetadataBook, ProtoBook, PeerStoreEvents, PeerStoreInit, Peer, TagOptions } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport errCode from 'err-code'\nimport { Tag, Tags } from './pb/tags.js'\nimport type { Datastore } from 'interface-datastore'\n\nconst log = logger('libp2p:peer-store')\n\nexport interface PersistentPeerStoreComponents {\n peerId: PeerId\n datastore: Datastore\n}\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore extends EventEmitter implements PeerStore {\n public addressBook: AddressBook\n public keyBook: KeyBook\n public metadataBook: MetadataBook\n public protoBook: ProtoBook\n\n private readonly components: PersistentPeerStoreComponents\n private readonly store: Store\n\n constructor (components: PersistentPeerStoreComponents, init: PeerStoreInit = {}) {\n super()\n\n this.components = components\n this.store = new PersistentStore(components)\n this.addressBook = new PeerStoreAddressBook(this.dispatchEvent.bind(this), this.store, init.addressFilter)\n this.keyBook = new PeerStoreKeyBook(this.dispatchEvent.bind(this), this.store)\n this.metadataBook = new PeerStoreMetadataBook(this.dispatchEvent.bind(this), this.store)\n this.protoBook = new PeerStoreProtoBook(this.dispatchEvent.bind(this), this.store)\n }\n\n async forEach (fn: (peer: Peer) => void) {\n log.trace('getPeers await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getPeers got read lock')\n\n try {\n for await (const peer of this.store.all()) {\n if (peer.id.equals(this.components.peerId)) {\n // Skip self peer if present\n continue\n }\n\n fn(peer)\n }\n } finally {\n log.trace('getPeers release read lock')\n release()\n }\n }\n\n async all (): Promise {\n const output: Peer[] = []\n\n await this.forEach(peer => {\n output.push(peer)\n })\n\n return output\n }\n\n /**\n * Delete the information of the given peer in every book\n */\n async delete (peerId: PeerId) {\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n log.trace('delete release write lock')\n release()\n }\n }\n\n /**\n * Get the stored information of a given peer\n */\n async get (peerId: PeerId) {\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n log.trace('get release read lock')\n release()\n }\n }\n\n /**\n * Returns true if we have a record of the peer\n */\n async has (peerId: PeerId) {\n log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n log.trace('has release read lock')\n release()\n }\n }\n\n async tagPeer (peerId: PeerId, tag: string, options: TagOptions = {}) {\n const providedValue = options.value ?? 0\n const value = Math.round(providedValue)\n const ttl = options.ttl ?? undefined\n\n if (value !== providedValue || value < 0 || value > 100) {\n throw errCode(new Error('Tag value must be between 0-100'), 'ERR_TAG_VALUE_OUT_OF_BOUNDS')\n }\n\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n for (const t of tags) {\n if (t.name === tag) {\n throw errCode(new Error('Peer already tagged'), 'ERR_DUPLICATE_TAG')\n }\n }\n\n tags.push({\n name: tag,\n value,\n expiry: ttl == null ? undefined : BigInt(Date.now() + ttl)\n })\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async unTagPeer (peerId: PeerId, tag: string) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n tags = tags.filter(t => t.name !== tag)\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async getTags (peerId: PeerId) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n const now = BigInt(Date.now())\n const unexpiredTags = tags.filter(tag => tag.expiry == null || tag.expiry > now)\n\n if (unexpiredTags.length !== tags.length) {\n // remove any expired tags\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags: unexpiredTags }).subarray())\n }\n\n return unexpiredTags.map(t => ({\n name: t.name,\n value: t.value ?? 0\n }))\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Tags {\n tags: Tag[]\n}\n\nexport namespace Tags {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.tags != null) {\n for (const value of obj.tags) {\n w.uint32(10)\n Tag.codec().encode(value, w, {\n writeDefaults: true\n })\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n tags: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.tags.push(Tag.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tags): Uint8Array => {\n return encodeMessage(obj, Tags.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tags => {\n return decodeMessage(buf, Tags.codec())\n }\n}\n\nexport interface Tag {\n name: string\n value?: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || obj.name !== '') {\n w.uint32(10)\n w.string(obj.name)\n }\n\n if (obj.value != null) {\n w.uint32(16)\n w.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n w.uint32(24)\n w.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n name: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.name = reader.string()\n break\n case 2:\n obj.value = reader.uint32()\n break\n case 3:\n obj.expiry = reader.uint64()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tag): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tag => {\n return decodeMessage(buf, Tag.codec())\n }\n}\n", "import drain from 'it-drain'\nimport errCode from 'err-code'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTContentRouting implements ContentRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async provide (cid: CID) {\n await drain(this.dht.provide(cid))\n }\n\n async * findProviders (cid: CID, options: AbortOptions = {}) {\n for await (const event of this.dht.findProviders(cid, options)) {\n if (event.name === 'PROVIDER') {\n yield * event.providers\n }\n }\n }\n\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise {\n await drain(this.dht.put(key, value, options))\n }\n\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n for await (const event of this.dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n}\n", "import errCode from 'err-code'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport { isStartable, Startable } from '@libp2p/interfaces/startable'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { TransportManager, Upgrader } from '@libp2p/interface-transport'\nimport type { Datastore } from 'interface-datastore'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { ConnectionManager, Dialer } from '@libp2p/interface-connection-manager'\n\nexport interface Components {\n peerId: PeerId\n addressManager: AddressManager\n peerStore: PeerStore\n upgrader: Upgrader\n registrar: Registrar\n connectionManager: ConnectionManager\n transportManager: TransportManager\n connectionGater: ConnectionGater\n contentRouting: ContentRouting\n peerRouting: PeerRouting\n datastore: Datastore\n connectionProtector?: ConnectionProtector\n dialer: Dialer\n metrics?: Metrics\n dht?: DualDHT\n pubsub?: PubSub\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dht?: DualDHT\n pubsub?: PubSub\n dialer?: Dialer\n}\n\nexport class DefaultComponents implements Components, Startable {\n private _peerId?: PeerId\n private _addressManager?: AddressManager\n private _peerStore?: PeerStore\n private _upgrader?: Upgrader\n private _metrics?: Metrics\n private _registrar?: Registrar\n private _connectionManager?: ConnectionManager\n private _transportManager?: TransportManager\n private _connectionGater?: ConnectionGater\n private _contentRouting?: ContentRouting\n private _peerRouting?: PeerRouting\n private _datastore?: Datastore\n private _connectionProtector?: ConnectionProtector\n private _dht?: DualDHT\n private _pubsub?: PubSub\n private _dialer?: Dialer\n private _started = false\n\n constructor (init: ComponentsInit = {}) {\n this._peerId = init.peerId\n this._addressManager = init.addressManager\n this._peerStore = init.peerStore\n this._upgrader = init.upgrader\n this._metrics = init.metrics\n this._registrar = init.registrar\n this._connectionManager = init.connectionManager\n this._transportManager = init.transportManager\n this._connectionGater = init.connectionGater\n this._contentRouting = init.contentRouting\n this._peerRouting = init.peerRouting\n this._datastore = init.datastore\n this._connectionProtector = init.connectionProtector\n this._dht = init.dht\n this._pubsub = init.pubsub\n this._dialer = init.dialer\n }\n\n isStarted () {\n return this._started\n }\n\n async beforeStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStart != null) {\n await startable.beforeStart()\n }\n })\n )\n }\n\n async start () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.start()\n })\n )\n\n this._started = true\n }\n\n async afterStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStart != null) {\n await startable.afterStart()\n }\n })\n )\n }\n\n async beforeStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStop != null) {\n await startable.beforeStop()\n }\n })\n )\n }\n\n async stop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.stop()\n })\n )\n\n this._started = false\n }\n\n async afterStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStop != null) {\n await startable.afterStop()\n }\n })\n )\n }\n\n get peerId (): PeerId {\n if (this._peerId == null) {\n throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._peerId\n }\n\n set peerId (peerId: PeerId) {\n this._peerId = peerId\n }\n\n get addressManager (): AddressManager {\n if (this._addressManager == null) {\n throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._addressManager\n }\n\n set addressManager (addressManager: AddressManager) {\n this._addressManager = addressManager\n }\n\n get peerStore (): PeerStore {\n if (this._peerStore == null) {\n throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._peerStore\n }\n\n set peerStore (peerStore: PeerStore) {\n this._peerStore = peerStore\n }\n\n get upgrader (): Upgrader {\n if (this._upgrader == null) {\n throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._upgrader\n }\n\n set upgrader (upgrader: Upgrader) {\n this._upgrader = upgrader\n }\n\n get registrar (): Registrar {\n if (this._registrar == null) {\n throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._registrar\n }\n\n set registrar (registrar: Registrar) {\n this._registrar = registrar\n }\n\n get connectionManager (): ConnectionManager {\n if (this._connectionManager == null) {\n throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._connectionManager\n }\n\n set connectionManager (connectionManager: ConnectionManager) {\n this._connectionManager = connectionManager\n }\n\n get transportManager (): TransportManager {\n if (this._transportManager == null) {\n throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._transportManager\n }\n\n set transportManager (transportManager: TransportManager) {\n this._transportManager = transportManager\n }\n\n get connectionGater (): ConnectionGater {\n if (this._connectionGater == null) {\n throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._connectionGater\n }\n\n set connectionGater (connectionGater: ConnectionGater) {\n this._connectionGater = connectionGater\n }\n\n get contentRouting (): ContentRouting {\n if (this._contentRouting == null) {\n throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._contentRouting\n }\n\n set contentRouting (contentRouting: ContentRouting) {\n this._contentRouting = contentRouting\n }\n\n get peerRouting (): PeerRouting {\n if (this._peerRouting == null) {\n throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._peerRouting\n }\n\n set peerRouting (peerRouting: PeerRouting) {\n this._peerRouting = peerRouting\n }\n\n get datastore (): Datastore {\n if (this._datastore == null) {\n throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._datastore\n }\n\n set datastore (datastore: Datastore) {\n this._datastore = datastore\n }\n\n get connectionProtector (): ConnectionProtector | undefined {\n return this._connectionProtector\n }\n\n set connectionProtector (connectionProtector: ConnectionProtector | undefined) {\n this._connectionProtector = connectionProtector\n }\n\n get dialer (): Dialer {\n if (this._dialer == null) {\n throw errCode(new Error('dialer not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._dialer\n }\n\n set dialer (dialer: Dialer) {\n this._dialer = dialer\n }\n\n get metrics (): Metrics | undefined {\n return this._metrics\n }\n\n set metrics (metrics: Metrics | undefined) {\n this._metrics = metrics\n }\n\n get dht (): DualDHT | undefined {\n return this._dht\n }\n\n set dht (dht: DualDHT | undefined) {\n this._dht = dht\n }\n\n get pubsub (): PubSub | undefined {\n return this._pubsub\n }\n\n set pubsub (pubsub: PubSub | undefined) {\n this._pubsub = pubsub\n }\n}\n", "import debug from 'debug'\nimport Receptacle from 'receptacle'\nimport * as utils from './utils.js'\nimport type { DNSJSON } from './utils'\n\nconst log = Object.assign(debug('dns-over-http-resolver'), {\n error: debug('dns-over-http-resolver:error')\n})\n\nexport interface Request { (resource: string, signal: AbortSignal): Promise }\n\ninterface ResolverOptions {\n maxCache?: number\n request?: Request\n}\n\n/**\n * DNS over HTTP resolver.\n * Uses a list of servers to resolve DNS records with HTTP requests.\n */\nclass Resolver {\n private readonly _cache: Receptacle\n private readonly _TXTcache: Receptacle\n private _servers: string[]\n private readonly _request: Request\n private _abortControllers: AbortController[]\n\n /**\n * @class\n * @param {object} [options]\n * @param {number} [options.maxCache = 100] - maximum number of cached dns records\n * @param {Request} [options.request] - function to return DNSJSON\n */\n constructor (options: ResolverOptions = {}) {\n this._cache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._TXTcache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._servers = [\n 'https://cloudflare-dns.com/dns-query',\n 'https://dns.google/resolve'\n ]\n this._request = options.request ?? utils.request\n this._abortControllers = []\n }\n\n /**\n * Cancel all outstanding DNS queries made by this resolver. Any outstanding\n * requests will be aborted and promises rejected.\n */\n cancel () {\n this._abortControllers.forEach(controller => controller.abort())\n }\n\n /**\n * Get an array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n getServers () {\n return this._servers\n }\n\n /**\n * Get a shuffled array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n _getShuffledServers () {\n const newServers = [...this._servers]\n\n for (let i = newServers.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i)\n const temp = newServers[i]\n newServers[i] = newServers[j]\n newServers[j] = temp\n }\n\n return newServers\n }\n\n /**\n * Sets the IP address and port of servers to be used when performing DNS resolution.\n *\n * @param {string[]} servers - array of RFC 5952 formatted addresses.\n */\n setServers (servers: string[]) {\n this._servers = servers\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into the appropriate DNS record\n *\n * @param {string} hostname - host name to resolve\n * @param {string} [rrType = 'A'] - resource record type\n */\n async resolve (hostname: string, rrType = 'A') {\n switch (rrType) {\n case 'A':\n return await this.resolve4(hostname)\n case 'AAAA':\n return await this.resolve6(hostname)\n case 'TXT':\n return await this.resolveTxt(hostname)\n default:\n throw new Error(`${rrType} is not supported`)\n }\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv4 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve4 (hostname: string) {\n const recordType = 'A'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryA ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv6 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve6 (hostname: string) {\n const recordType = 'AAAA'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryAaaa ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into a Text record\n *\n * @param {string} hostname - host name to resolve\n */\n async resolveTxt (hostname: string) {\n const recordType = 'TXT'\n const cached = this._TXTcache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => [a.data.replace(/['\"]+/g, '')])\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._TXTcache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryTxt ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n clearCache () {\n this._cache.clear()\n this._TXTcache.clear()\n }\n}\n\nexport default Resolver\n", "const globalFetch = globalThis.fetch;\nconst globalHeaders = globalThis.Headers;\nconst globalRequest = globalThis.Request;\nconst globalResponse = globalThis.Response;\nexport {\n globalFetch as fetch\n};\nexport {\n globalHeaders as Headers\n};\nexport {\n globalRequest as Request\n};\nexport {\n globalResponse as Response\n};", "import { fetch as nativeFetch, Headers } from 'native-fetch'\n\n/**\n * Build fetch resource for request\n */\nexport function buildResource (serverResolver: string, hostname: string, recordType: string) {\n return `${serverResolver}?name=${hostname}&type=${recordType}`\n}\n\nexport interface DNSJSON {\n Question: Question[]\n Answer: Answer[]\n}\n\ninterface Question {\n name: string\n type: number\n}\n\ninterface Answer {\n name: string\n type: number\n data: string\n TTL: number\n}\n\n/**\n * Use fetch to find the record\n */\nexport async function request (resource: string, signal: AbortSignal) {\n const req = await nativeFetch(resource, {\n headers: new Headers({\n accept: 'application/dns-json'\n }),\n signal\n })\n const res = await req.json()\n\n return res as DNSJSON\n}\n\n/**\n * Creates cache key composed by recordType and hostname\n *\n * @param {string} hostname\n * @param {string} recordType\n */\nexport function getCacheKey (hostname: string, recordType: string) {\n return `${recordType}_${hostname}`\n}\n", "import dns from 'dns-over-http-resolver'\n\nexport default dns\n", "/**\n * @packageDocumentation\n *\n * Provides strategies for resolving multiaddrs.\n */\n\nimport { getProtocol } from '../protocols-table.js'\nimport Resolver from './dns.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\n\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\n/**\n * Resolver for dnsaddr addresses.\n *\n * @example\n *\n * ```typescript\n * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const addresses = await dnsaddrResolver(ma)\n *\n * console.info(addresses)\n * //[\n * // '/dnsaddr/am6.bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb',\n * // '/dnsaddr/ny5.bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa',\n * // '/dnsaddr/sg1.bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt',\n * // '/dnsaddr/sv15.bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN'\n * //]\n * ```\n */\nexport async function dnsaddrResolver (addr: Multiaddr, options: AbortOptions = {}): Promise {\n const resolver = new Resolver()\n\n if (options.signal != null) {\n options.signal.addEventListener('abort', () => {\n resolver.cancel()\n })\n }\n\n const peerId = addr.getPeerId()\n const [, hostname] = addr.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n if (hostname == null) {\n throw new Error('No hostname found in multiaddr')\n }\n\n const records = await resolver.resolveTxt(`_dnsaddr.${hostname}`)\n\n let addresses = records.flat().map((a) => a.split('=')[1])\n\n if (peerId != null) {\n addresses = addresses.filter((entry) => entry.includes(peerId))\n }\n\n return addresses\n}\n", "import mergeOptions from 'merge-options'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport * as Constants from './constants.js'\nimport { AGENT_VERSION } from './identify/consts.js'\nimport * as RelayConstants from './circuit/constants.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { FaultTolerance } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Libp2pInit } from './index.js'\nimport { codes, messages } from './errors.js'\nimport errCode from 'err-code'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'\n\nconst DefaultConfig: Partial = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n maxConnections: 300,\n minConnections: 50,\n autoDial: true,\n autoDialInterval: 10000,\n maxParallelDials: Constants.MAX_PARALLEL_DIALS,\n maxDialsPerPeer: Constants.MAX_PER_PEER_DIALS,\n dialTimeout: Constants.DIAL_TIMEOUT,\n inboundUpgradeTimeout: Constants.INBOUND_UPGRADE_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: publicAddressesFirst\n },\n connectionGater: {},\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n },\n peerRouting: {\n refreshManager: {\n enabled: true,\n interval: 6e5,\n bootDelay: 10e3\n }\n },\n nat: {\n enabled: true,\n ttl: 7200,\n keepAlive: true\n },\n relay: {\n enabled: true,\n advertise: {\n bootDelay: RelayConstants.ADVERTISE_BOOT_DELAY,\n enabled: false,\n ttl: RelayConstants.ADVERTISE_TTL\n },\n hop: {\n enabled: false,\n active: false,\n timeout: 30000\n },\n autoRelay: {\n enabled: false,\n maxListeners: 2\n }\n },\n identify: {\n protocolPrefix: 'ipfs',\n host: {\n agentVersion: AGENT_VERSION\n },\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 },\n ping: {\n protocolPrefix: 'ipfs',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n },\n fetch: {\n protocolPrefix: 'libp2p',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n }\n}\n\nexport function validateConfig (opts: RecursivePartial): Libp2pInit {\n const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {\n throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)\n }\n\n if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {\n throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)\n }\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)\n }\n\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (resultingOptions.identify.host.agentVersion === AGENT_VERSION) {\n if (isNode || isElectronMain) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.process.version}`\n } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`\n }\n }\n\n return resultingOptions\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerIdProto {\n id: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.id != null && obj.id.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.pubKey != null) {\n w.uint32(18)\n w.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n w.uint32(26)\n w.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerIdProto): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n", "import { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerIdProto } from './proto.js'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\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}\n\nexport async function createFromProtobuf (buf: Uint8Array): Promise {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return await createFromParts(\n id,\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }): Promise {\n return await createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array): Promise {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return await createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey)\n\n return await createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n", "import { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { Startable, isStartable } from '@libp2p/interfaces/startable'\nimport { isMultiaddr, Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { CompoundContentRouting } from './content-routing/index.js'\nimport { codes } from './errors.js'\nimport { DefaultAddressManager } from './address-manager/index.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { AutoDialler } from './connection-manager/auto-dialler.js'\nimport { Circuit } from './circuit/transport.js'\nimport { Relay } from './circuit/index.js'\nimport { KeyChain } from './keychain/index.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { DefaultUpgrader } from './upgrader.js'\nimport { DefaultRegistrar } from './registrar.js'\nimport { IdentifyService } from './identify/index.js'\nimport { FetchService } from './fetch/index.js'\nimport { PingService } from './ping/index.js'\nimport { NatManager } from './nat-manager.js'\nimport { PeerRecordUpdater } from './peer-record-updater.js'\nimport { DHTPeerRouting } from './dht/dht-peer-routing.js'\nimport { PersistentPeerStore } from '@libp2p/peer-store'\nimport { DHTContentRouting } from './dht/dht-content-routing.js'\nimport { DefaultComponents } from './components.js'\nimport type { Components } from './components.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions, Topology } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'\nimport { validateConfig } from './config.js'\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport errCode from 'err-code'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { DummyDHT } from './dht/dummy-dht.js'\nimport { DummyPubSub } from './pubsub/dummy-pubsub.js'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport { DefaultDialer } from './connection-manager/dialer/index.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Datastore } from 'interface-datastore'\n\nconst log = logger('libp2p')\n\nexport class Libp2pNode extends EventEmitter implements Libp2p {\n public peerId: PeerId\n public dht: DualDHT\n public pubsub: PubSub\n public identifyService: IdentifyService\n public fetchService: FetchService\n public pingService: PingService\n public components: Components\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public keychain: KeyChain\n public connectionManager: ConnectionManager\n public registrar: Registrar\n public metrics?: Metrics\n\n private started: boolean\n private readonly services: Startable[]\n\n constructor (init: Libp2pInit) {\n super()\n\n this.started = false\n this.peerId = init.peerId\n const components = this.components = new DefaultComponents({\n peerId: init.peerId,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: {\n denyDialPeer: async () => await Promise.resolve(false),\n denyDialMultiaddr: async () => await Promise.resolve(false),\n denyInboundConnection: async () => await Promise.resolve(false),\n denyOutboundConnection: async () => await Promise.resolve(false),\n denyInboundEncryptedConnection: async () => await Promise.resolve(false),\n denyOutboundEncryptedConnection: async () => await Promise.resolve(false),\n denyInboundUpgradedConnection: async () => await Promise.resolve(false),\n denyOutboundUpgradedConnection: async () => await Promise.resolve(false),\n filterMultiaddrForPeer: async () => await Promise.resolve(true),\n ...init.connectionGater\n }\n })\n components.peerStore = new PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n })\n\n this.services = [\n components\n ]\n\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.components.metrics = this.configureComponent(init.metrics(this.components))\n }\n\n this.peerStore = this.components.peerStore\n\n this.peerStore.addEventListener('peer', evt => {\n const { detail: peerData } = evt\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peerData }))\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.components.connectionProtector = init.connectionProtector(components)\n }\n\n // Set up the Upgrader\n this.components.upgrader = new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map(fn => this.configureComponent(fn(this.components))),\n muxers: (init.streamMuxers ?? []).map(fn => this.configureComponent(fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n })\n\n // Create the dialer\n this.components.dialer = new DefaultDialer(this.components, init.connectionManager)\n\n // Create the Connection Manager\n this.connectionManager = this.components.connectionManager = new DefaultConnectionManager(this.components, init.connectionManager)\n\n // forward connection manager events\n this.components.connectionManager.addEventListener('peer:disconnect', (event) => {\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: event.detail }))\n })\n this.components.connectionManager.addEventListener('peer:connect', (event) => {\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: event.detail }))\n })\n\n // Create the Registrar\n this.registrar = this.components.registrar = new DefaultRegistrar(this.components)\n\n // Setup the transport manager\n this.components.transportManager = new DefaultTransportManager(this.components, init.transportManager)\n\n // Addresses {listen, announce, noAnnounce}\n this.components.addressManager = new DefaultAddressManager(this.components, init.addresses)\n\n // update our peer record when addresses change\n this.configureComponent(new PeerRecordUpdater(this.components))\n\n this.configureComponent(new AutoDialler(this.components, {\n enabled: init.connectionManager.autoDial,\n minConnections: init.connectionManager.minConnections,\n autoDialInterval: init.connectionManager.autoDialInterval\n }))\n\n // Create keychain\n const keychainOpts = KeyChain.generateOptions()\n this.keychain = this.configureComponent(new KeyChain(this.components, {\n ...keychainOpts,\n ...init.keychain\n }))\n\n // Create the Nat Manager\n this.services.push(new NatManager(this.components, init.nat))\n\n init.transports.forEach((fn) => {\n this.components.transportManager.add(this.configureComponent(fn(this.components)))\n })\n\n // Add the identify service\n this.identifyService = new IdentifyService(this.components, {\n ...init.identify\n })\n this.configureComponent(this.identifyService)\n\n // dht provided components (peerRouting, contentRouting, dht)\n if (init.dht != null) {\n this.dht = this.components.dht = init.dht(this.components)\n } else {\n this.dht = new DummyDHT()\n }\n\n // Create pubsub if provided\n if (init.pubsub != null) {\n this.pubsub = this.components.pubsub = init.pubsub(this.components)\n } else {\n this.pubsub = new DummyPubSub()\n }\n\n // Attach remaining APIs\n // peer and content routing will automatically get modules from _modules and _dht\n\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map(fn => this.configureComponent(fn(this.components)))\n\n if (init.dht != null) {\n // add dht to routers\n peerRouters.push(this.configureComponent(new DHTPeerRouting(this.dht)))\n\n // use dht for peer discovery\n this.dht.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n\n this.peerRouting = this.components.peerRouting = this.configureComponent(new DefaultPeerRouting(this.components, {\n ...init.peerRouting,\n routers: peerRouters\n }))\n\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map(fn => this.configureComponent(fn(this.components)))\n\n if (init.dht != null) {\n // add dht to routers\n contentRouters.push(this.configureComponent(new DHTContentRouting(this.dht)))\n }\n\n this.contentRouting = this.components.contentRouting = this.configureComponent(new CompoundContentRouting(this.components, {\n routers: contentRouters\n }))\n\n if (init.relay.enabled) {\n this.components.transportManager.add(this.configureComponent(new Circuit(this.components, init.relay)))\n\n this.configureComponent(new Relay(this.components, {\n addressSorter: init.connectionManager.addressSorter,\n ...init.relay\n }))\n }\n\n this.fetchService = this.configureComponent(new FetchService(this.components, {\n ...init.fetch\n }))\n\n this.pingService = this.configureComponent(new PingService(this.components, {\n ...init.ping\n }))\n\n // Discovery modules\n for (const fn of init.peerDiscovery ?? []) {\n const service = this.configureComponent(fn(this.components))\n\n service.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n }\n\n private configureComponent (component: T): T {\n if (isStartable(component)) {\n this.services.push(component)\n }\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start () {\n if (this.started) {\n return\n }\n\n this.started = true\n\n log('libp2p is starting')\n\n try {\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStart != null) {\n await service.beforeStart()\n }\n })\n )\n\n // start any startables\n await Promise.all(\n this.services.map(service => service.start())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStart != null) {\n await service.afterStart()\n }\n })\n )\n\n log('libp2p has started')\n } catch (err: any) {\n log.error('An error occurred starting libp2p', err)\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop () {\n if (!this.started) {\n return\n }\n\n log('libp2p is stopping')\n\n this.started = false\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStop != null) {\n await service.beforeStop()\n }\n })\n )\n\n await Promise.all(\n this.services.map(service => service.stop())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStop != null) {\n await service.afterStop()\n }\n })\n )\n\n log('libp2p has stopped')\n }\n\n isStarted () {\n return this.started\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.connectionManager.getConnections(peerId)\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n return await this.components.connectionManager.openConnection(peer, options)\n }\n\n async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}) {\n if (protocols == null) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n const connection = await this.dial(peer, options)\n\n return await connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.addressManager.getAddresses()\n }\n\n getProtocols (): string[] {\n return this.components.registrar.getProtocols()\n }\n\n async hangUp (peer: PeerId | Multiaddr): Promise {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '')\n }\n\n await this.components.connectionManager.closeConnections(peer)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise {\n log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.pubKey != null) {\n return peerInfo.pubKey\n }\n\n if (this.dht == null) {\n throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ])\n\n // search the dht\n for await (const event of this.dht.get(peerKey, options)) {\n if (event.name === 'VALUE') {\n const key = unmarshalPublicKey(event.value)\n\n await this.peerStore.keyBook.set(peer, event.value)\n\n return key.bytes\n }\n }\n\n throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)\n }\n\n async fetch (peer: PeerId | Multiaddr, key: string, options: AbortOptions = {}): Promise {\n if (isMultiaddr(peer)) {\n const peerId = peerIdFromString(peer.getPeerId() ?? '')\n await this.components.peerStore.addressBook.add(peerId, [peer])\n peer = peerId\n }\n\n return await this.fetchService.fetch(peer, key, options)\n }\n\n async ping (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n if (isMultiaddr(peer)) {\n const peerId = peerIdFromString(peer.getPeerId() ?? '')\n await this.components.peerStore.addressBook.add(peerId, [peer])\n peer = peerId\n }\n\n return await this.pingService.ping(peer, options)\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.unhandle(protocol)\n })\n )\n }\n\n async register (protocol: string, topology: Topology): Promise {\n return await this.registrar.register(protocol, topology)\n }\n\n unregister (id: string) {\n this.registrar.unregister(id)\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events.\n * Known peers may be emitted.\n */\n onDiscoveryPeer (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n log.error(new Error(codes.ERR_DISCOVERED_SELF))\n return\n }\n\n if (peer.multiaddrs.length > 0) {\n void this.components.peerStore.addressBook.add(peer.id, peer.multiaddrs).catch(err => log.error(err))\n }\n\n if (peer.protocols.length > 0) {\n void this.components.peerStore.protoBook.set(peer.id, peer.protocols).catch(err => log.error(err))\n }\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peer }))\n }\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: Libp2pOptions): Promise {\n if (options.peerId == null) {\n const datastore = options.datastore as Datastore | undefined\n\n if (datastore != null) {\n try {\n // try load the peer id from the keychain\n // @ts-expect-error missing the peer id property\n const keyChain = new KeyChain({\n datastore\n }, {\n ...KeyChain.generateOptions(),\n ...(options.keychain ?? {})\n })\n\n options.peerId = await keyChain.exportPeerId('self')\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n }\n\n if (options.peerId == null) {\n // no peer id in the keychain, create a new peer id\n options.peerId = await createEd25519PeerId()\n }\n\n return new Libp2pNode(validateConfig(options))\n}\n", "import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { symbol } from '@libp2p/interface-peer-discovery'\n\nexport class DummyDHT extends EventEmitter implements DualDHT {\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/dummy-dht'\n }\n\n get wan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get lan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findProviders (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findPeer (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n getClosestPeers (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n provide (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n put (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async getMode (): Promise<'client' | 'server'> {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async setMode (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async refreshRoutingTable (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n}\n", "import { EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign, TopicValidatorFn } from '@libp2p/interface-pubsub'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\n\nexport class DummyPubSub extends EventEmitter implements PubSub {\n public topicValidators = new Map()\n\n isStarted (): boolean {\n return false\n }\n\n start (): void | Promise {\n\n }\n\n stop (): void | Promise {\n\n }\n\n get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n get multicodecs (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getPeers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getTopics (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n subscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n unsubscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getSubscribers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n async publish (): Promise {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { isMultiaddr, Multiaddr, Resolver, multiaddr, resolvers } from '@multiformats/multiaddr'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'events'\nimport { DialAction, DialRequest } from './dial-request.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { codes } from '../../errors.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PER_PEER_DIALS,\n MAX_ADDRS_TO_DIAL\n} from '../../constants.js'\nimport type { Connection, ConnectionGater } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { getPeerAddress } from '../../get-peer.js'\nimport type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { Dialer } from '@libp2p/interface-connection-manager'\nimport type { TransportManager } from '@libp2p/interface-transport'\n\nconst log = logger('libp2p:dialer')\n\nexport interface DialTarget {\n id: string\n addrs: Multiaddr[]\n}\n\nexport interface PendingDial {\n dialRequest: DialRequest\n controller: TimeoutController\n promise: Promise\n destroy: () => void\n}\n\nexport interface PendingDialTarget {\n resolve: (value: any) => void\n reject: (err: Error) => void\n}\n\nexport interface DialerInit {\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take\n */\n dialTimeout?: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n}\n\nexport interface DefaultDialerComponents {\n peerId: PeerId\n metrics?: Metrics\n peerStore: PeerStore\n transportManager: TransportManager\n connectionGater: ConnectionGater\n}\n\nexport class DefaultDialer implements Startable, Dialer {\n private readonly components: DefaultDialerComponents\n private readonly addressSorter: AddressSorter\n private readonly maxAddrsToDial: number\n private readonly timeout: number\n private readonly maxDialsPerPeer: number\n public tokens: number[]\n public pendingDials: Map\n public pendingDialTargets: Map\n private started: boolean\n\n constructor (components: DefaultDialerComponents, init: DialerInit = {}) {\n this.started = false\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxAddrsToDial = init.maxAddrsToDial ?? MAX_ADDRS_TO_DIAL\n this.timeout = init.dialTimeout ?? DIAL_TIMEOUT\n this.maxDialsPerPeer = init.maxDialsPerPeer ?? MAX_PER_PEER_DIALS\n this.tokens = [...new Array(init.maxParallelDials ?? MAX_PARALLEL_DIALS)].map((_, index) => index)\n this.components = components\n this.pendingDials = trackedMap({\n name: 'libp2p_dialler_pending_dials',\n metrics: components.metrics\n })\n this.pendingDialTargets = trackedMap({\n name: 'libp2p_dialler_pending_dial_targets',\n metrics: components.metrics\n })\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n /**\n * Clears any pending dials\n */\n async stop () {\n this.started = false\n\n for (const dial of this.pendingDials.values()) {\n try {\n dial.controller.abort()\n } catch (err: any) {\n log.error(err)\n }\n }\n this.pendingDials.clear()\n\n for (const pendingTarget of this.pendingDialTargets.values()) {\n pendingTarget.abort()\n }\n this.pendingDialTargets.clear()\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async dial (peerIdOrMultiaddr: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { peerId, multiaddr } = getPeerAddress(peerIdOrMultiaddr)\n\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)\n }\n\n if (multiaddr != null) {\n log('storing multiaddrs %p', peerId, multiaddr)\n await this.components.peerStore.addressBook.add(peerId, [multiaddr])\n }\n\n if (await this.components.connectionGater.denyDialPeer(peerId)) {\n throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)\n }\n }\n\n log('creating dial target for %p', peerId)\n\n // resolving multiaddrs can involve dns lookups so allow them to be aborted\n const controller = new AbortController()\n const controllerId = randomId()\n this.pendingDialTargets.set(controllerId, controller)\n let signal = controller.signal\n\n // merge with the passed signal, if any\n if (options.signal != null) {\n signal = anySignal([signal, options.signal])\n }\n\n let dialTarget: DialTarget\n\n try {\n dialTarget = await this._createDialTarget({ peerId, multiaddr }, {\n ...options,\n signal\n })\n } finally {\n // done resolving the multiaddrs so remove the abort controller\n this.pendingDialTargets.delete(controllerId)\n }\n\n if (dialTarget.addrs.length === 0) {\n throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)\n }\n\n // try to join an in-flight dial for this peer if one is available\n const pendingDial = this.pendingDials.get(dialTarget.id) ?? this._createPendingDial(dialTarget, options)\n\n try {\n const connection = await pendingDial.promise\n log('dial succeeded to %s', dialTarget.id)\n return connection\n } catch (err: any) {\n log('dial failed to %s', dialTarget.id, err)\n // Error is a timeout\n if (pendingDial.controller.signal.aborted) {\n err.code = codes.ERR_TIMEOUT\n }\n log.error(err)\n throw err\n } finally {\n pendingDial.destroy()\n }\n }\n\n /**\n * Creates a DialTarget. The DialTarget is used to create and track\n * the DialRequest to a given peer.\n *\n * If a multiaddr is received it should be the only address attempted.\n *\n * Multiaddrs not supported by the available transports will be filtered out.\n */\n async _createDialTarget (peerIdOrMultiaddr: { peerId?: PeerId, multiaddr?: Multiaddr }, options: AbortOptions): Promise {\n let addrs: Multiaddr[] = []\n\n if (isMultiaddr(peerIdOrMultiaddr.multiaddr)) {\n addrs.push(peerIdOrMultiaddr.multiaddr)\n }\n\n // only load addresses if a peer id was passed, otherwise only dial the passed multiaddr\n if (!isMultiaddr(peerIdOrMultiaddr.multiaddr) && isPeerId(peerIdOrMultiaddr.peerId)) {\n addrs.push(...await this._loadAddresses(peerIdOrMultiaddr.peerId))\n }\n\n addrs = (await Promise.all(\n addrs.map(async (ma) => await this._resolve(ma, options))\n ))\n .flat()\n // Multiaddrs not supported by the available transports will be filtered out.\n .filter(ma => Boolean(this.components.transportManager.transportForMultiaddr(ma)))\n\n // deduplicate addresses\n addrs = [...new Set(addrs.map(ma => ma.toString()))].map(ma => multiaddr(ma))\n\n if (addrs.length > this.maxAddrsToDial) {\n throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)\n }\n\n const peerId = isPeerId(peerIdOrMultiaddr.peerId) ? peerIdOrMultiaddr.peerId : undefined\n\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`\n addrs = addrs.map(addr => {\n const addressPeerId = addr.getPeerId()\n\n if (addressPeerId == null || !peerId.equals(addressPeerId)) {\n return addr.encapsulate(peerIdMultiaddr)\n }\n\n return addr\n })\n }\n\n return {\n id: peerId == null ? randomId() : peerId.toString(),\n addrs\n }\n }\n\n /**\n * Loads a list of addresses from the peer store for the passed peer id\n */\n async _loadAddresses (peer: PeerId): Promise {\n const addresses = await this.components.peerStore.addressBook.get(peer)\n\n return (await Promise.all(\n addresses.map(async address => {\n const deny = await this.components.connectionGater.denyDialMultiaddr(peer, address.multiaddr)\n\n if (deny) {\n return false\n }\n\n return address\n })\n ))\n .filter(isTruthy)\n // Sort addresses so, for example, we try certified public address first\n .sort(this.addressSorter)\n .map(address => address.multiaddr)\n }\n\n /**\n * Creates a PendingDial that wraps the underlying DialRequest\n */\n _createPendingDial (dialTarget: DialTarget, options: AbortOptions = {}): PendingDial {\n /**\n * @param {Multiaddr} addr\n * @param {{ signal: { aborted: any; }; }} options\n */\n const dialAction: DialAction = async (addr, options = {}) => {\n if (options.signal?.aborted === true) {\n throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)\n }\n\n return await this.components.transportManager.dial(addr, options).catch(err => {\n log.error('dial to %s failed', addr, err)\n throw err\n })\n }\n\n const dialRequest = new DialRequest({\n addrs: dialTarget.addrs,\n dialAction,\n dialer: this\n })\n\n // Combine the timeout signal and options.signal, if provided\n const timeoutController = new TimeoutController(this.timeout)\n\n const signals = [timeoutController.signal]\n ;(options.signal != null) && signals.push(options.signal)\n const signal = anySignal(signals)\n\n // this signal will potentially be used while dialing lots of\n // peers so prevent MaxListenersExceededWarning appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, signal)\n } catch {}\n\n const pendingDial = {\n dialRequest,\n controller: timeoutController,\n promise: dialRequest.run({ ...options, signal }),\n destroy: () => {\n timeoutController.clear()\n this.pendingDials.delete(dialTarget.id)\n }\n }\n this.pendingDials.set(dialTarget.id, pendingDial)\n\n return pendingDial\n }\n\n getTokens (num: number) {\n const total = Math.min(num, this.maxDialsPerPeer, this.tokens.length)\n const tokens = this.tokens.splice(0, total)\n log('%d tokens request, returning %d, %d remaining', num, total, this.tokens.length)\n return tokens\n }\n\n releaseToken (token: number) {\n // Guard against duplicate releases\n if (this.tokens.includes(token)) {\n return\n }\n\n log('token %d released', token)\n this.tokens.push(token)\n }\n\n /**\n * Resolve multiaddr recursively\n */\n async _resolve (ma: Multiaddr, options: AbortOptions): Promise {\n // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place\n // Now only supporting resolve for dnsaddr\n const resolvableProto = ma.protoNames().includes('dnsaddr')\n\n // Multiaddr is not resolvable? End recursion!\n if (!resolvableProto) {\n return [ma]\n }\n\n const resolvedMultiaddrs = await this._resolveRecord(ma, options)\n const recursiveMultiaddrs = await Promise.all(resolvedMultiaddrs.map(async (nm) => {\n return await this._resolve(nm, options)\n }))\n\n const addrs = recursiveMultiaddrs.flat()\n return addrs.reduce((array, newM) => {\n if (array.find(m => m.equals(newM)) == null) {\n array.push(newM)\n }\n return array\n }, ([]))\n }\n\n /**\n * Resolve a given multiaddr. If this fails, an empty array will be returned\n */\n async _resolveRecord (ma: Multiaddr, options: AbortOptions): Promise {\n try {\n ma = multiaddr(ma.toString()) // Use current multiaddr module\n const multiaddrs = await ma.resolve(options)\n return multiaddrs\n } catch (err) {\n log.error(`multiaddr ${ma.toString()} could not be resolved`, err)\n return []\n }\n }\n}\n\n/**\n * Type safe version of `list.filter(Boolean)`\n */\nfunction isTruthy (e: T | false | null | undefined): e is T {\n return Boolean(e)\n}\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n", "import errCode from 'err-code'\nimport { anySignal } from 'any-signal'\nimport FIFO from 'p-fifo'\nimport { setMaxListeners } from 'events'\nimport { codes } from '../../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Dialer } from '@libp2p/interface-connection-manager'\n\nconst log = logger('libp2p:dialer:dial-request')\n\nexport interface DialAction {\n (m: Multiaddr, options: AbortOptions): Promise\n}\n\nexport interface DialRequestOptions {\n addrs: Multiaddr[]\n dialAction: DialAction\n dialer: Dialer\n}\n\nexport class DialRequest {\n private readonly addrs: Multiaddr[]\n private readonly dialer: Dialer\n private readonly dialAction: DialAction\n\n /**\n * Manages running the `dialAction` on multiple provided `addrs` in parallel\n * up to a maximum determined by the number of tokens returned\n * from `dialer.getTokens`. Once a DialRequest is created, it can be\n * started using `DialRequest.run(options)`. Once a single dial has succeeded,\n * all other dials in the request will be cancelled.\n */\n constructor (options: DialRequestOptions) {\n const {\n addrs,\n dialAction,\n dialer\n } = options\n\n this.addrs = addrs\n this.dialer = dialer\n this.dialAction = dialAction\n }\n\n async run (options: AbortOptions = {}): Promise {\n const tokens = this.dialer.getTokens(this.addrs.length)\n\n // If no tokens are available, throw\n if (tokens.length < 1) {\n throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)\n }\n\n const tokenHolder = new FIFO()\n\n for (const token of tokens) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n }\n\n const dialAbortControllers: Array<(AbortController | undefined)> = this.addrs.map(() => {\n const controller = new AbortController()\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n return controller\n })\n\n if (options.signal != null) {\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, options.signal)\n } catch {}\n }\n\n let completedDials = 0\n let done = false\n\n try {\n return await Promise.any(this.addrs.map(async (addr, i) => {\n const token = await tokenHolder.shift() // get token\n // End attempt once another attempt succeeded\n if (done) {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)\n }\n\n const controller = dialAbortControllers[i]\n if (controller == null) {\n throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)\n }\n let conn\n try {\n const signal = controller.signal\n conn = await this.dialAction(addr, { ...options, signal: (options.signal != null) ? anySignal([signal, options.signal]) : signal })\n // Remove the successful AbortController so it is not aborted\n dialAbortControllers[i] = undefined\n } finally {\n completedDials++\n // If we have more or equal dials remaining than tokens, recycle the token, otherwise release it\n if (this.addrs.length - completedDials >= tokens.length) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n } else {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n }\n }\n\n if (conn == null) {\n // Notify Promise.any that attempt was not successful\n // to prevent from returning undefined despite there\n // were successful dial attempts\n throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)\n } else {\n // This dial succeeded, don't attempt anything else\n done = true\n }\n\n return conn\n }))\n } finally {\n // success/failure happened, abort everything else\n dialAbortControllers.forEach(c => {\n if (c !== undefined) {\n c.abort()\n }\n })\n tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer\n }\n }\n}\n", "/**\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 */\n\nimport { createLibp2pNode } from './libp2p.js'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport type { TransportManagerInit } from './transport-manager.js'\nimport type { IdentifyServiceInit } from './identify/index.js'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { Datastore } from 'interface-datastore'\nimport type { PeerStoreInit } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { RelayConfig } from './circuit/index.js'\nimport type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { Transport } from '@libp2p/interface-transport'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PingServiceInit } from './ping/index.js'\nimport type { FetchServiceInit } from './fetch/index.js'\nimport type { Components } from './components.js'\nimport type { Libp2p } from '@libp2p/interface-libp2p'\nimport type { KeyChainInit } from './keychain/index.js'\nimport type { NatManagerInit } from './nat-manager.js'\nimport type { AddressManagerInit } from './address-manager/index.js'\nimport type { PeerRoutingInit } from './peer-routing.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\n\n/**\n * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).\n */\nexport interface Libp2pInit {\n /**\n * peerId instance (it will be created if not provided)\n */\n peerId: PeerId\n\n /**\n * Addresses for transport listening and to advertise to the network\n */\n addresses: AddressManagerInit\n\n /**\n * libp2p Connection Manager configuration\n */\n connectionManager: ConnectionManagerInit\n\n /**\n * A connection gater can deny new connections based on user criteria\n */\n connectionGater: Partial\n\n /**\n * libp2p transport manager configuration\n */\n transportManager: TransportManagerInit\n\n /**\n * An optional datastore to persist peer information, DHT records, etc.\n *\n * An in-memory datastore will be used if one is not provided.\n */\n datastore: Datastore\n\n /**\n * libp2p PeerStore configuration\n */\n peerStore: PeerStoreInit\n\n /**\n * libp2p Peer routing service configuration\n */\n peerRouting: PeerRoutingInit\n\n /**\n * keychain configuration\n */\n keychain: KeyChainInit\n\n /**\n * The NAT manager controls uPNP hole punching\n */\n nat: NatManagerInit\n\n /**\n * If configured as a relay this node will relay certain\n * types of traffic for other peers\n */\n relay: RelayConfig\n\n /**\n * libp2p identify protocol options\n */\n identify: IdentifyServiceInit\n\n /**\n * libp2p ping protocol options\n */\n ping: PingServiceInit\n\n /**\n * libp2p fetch protocol options\n */\n fetch: FetchServiceInit\n\n /**\n * An array that must include at least 1 compliant transport\n */\n transports: Array<(components: Components) => Transport>\n streamMuxers?: Array<(components: Components) => StreamMuxerFactory>\n connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>\n peerDiscovery?: Array<(components: Components) => PeerDiscovery>\n peerRouters?: Array<(components: Components) => PeerRouting>\n contentRouters?: Array<(components: Components) => ContentRouting>\n\n /**\n * Pass a DHT implementation to enable DHT operations\n */\n dht?: (components: Components) => DualDHT\n\n /**\n * A Metrics implementation can be supplied to collect metrics on this node\n */\n metrics?: (components: Components) => Metrics\n\n /**\n * If a PubSub implmentation is supplied, PubSub operations will become available\n */\n pubsub?: (components: Components) => PubSub\n\n /**\n * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys\n */\n connectionProtector?: (components: Components) => ConnectionProtector\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits, so that you can be notified of relevant network events.\n */\nexport interface Libp2pEvents {\n /**\n * @example\n *\n * ```js\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent\n}\n\nexport type { Libp2p }\n\nexport type Libp2pOptions = RecursivePartial & { start?: boolean }\n\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 * ```js\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 *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [mplex()],\n * connectionEncryption: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p (options: Libp2pOptions): Promise {\n const node = await createLibp2pNode(options)\n\n if (options.start !== false) {\n await node.start()\n }\n\n return node\n}\n", "// @ts-expect-error no types\nimport KBuck from 'k-bucket'\nimport * as utils from '../utils.js'\nimport Queue from 'p-queue'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { logger } from '@libp2p/logger'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Logger } from '@libp2p/logger'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport type { Metric, Metrics } from '@libp2p/interface-metrics'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nexport const KAD_CLOSE_TAG_NAME = 'kad-close'\nexport const KAD_CLOSE_TAG_VALUE = 50\nexport const KBUCKET_SIZE = 20\nexport const PING_TIMEOUT = 10000\nexport const PING_CONCURRENCY = 10\n\nexport interface KBucketPeer {\n id: Uint8Array\n peer: PeerId\n}\n\nexport interface KBucket {\n id: Uint8Array\n contacts: KBucketPeer[]\n dontSplit: boolean\n left: KBucket\n right: KBucket\n}\n\ninterface KBucketTreeEvents {\n 'ping': (oldContacts: KBucketPeer[], newContact: KBucketPeer) => void\n 'added': (contact: KBucketPeer) => void\n 'removed': (contact: KBucketPeer) => void\n}\n\nexport interface KBucketTree {\n root: KBucket\n localNodeId: Uint8Array\n\n on: (\n event: U, listener: KBucketTreeEvents[U]\n ) => this\n\n closest: (key: Uint8Array, count: number) => KBucketPeer[]\n closestPeer: (key: Uint8Array) => KBucketPeer\n remove: (key: Uint8Array) => void\n add: (peer: KBucketPeer) => void\n get: (key: Uint8Array) => Uint8Array\n count: () => number\n toIterable: () => Iterable\n}\n\nexport interface RoutingTableInit {\n lan: boolean\n protocol: string\n kBucketSize?: number\n pingTimeout?: number\n pingConcurrency?: number\n tagName?: string\n tagValue?: number\n}\n\nexport interface RoutingTableComponents {\n peerId: PeerId\n peerStore: PeerStore\n connectionManager: ConnectionManager\n metrics?: Metrics\n}\n\n/**\n * A wrapper around `k-bucket`, to provide easy store and\n * retrieval for peers.\n */\nexport class RoutingTable implements Startable {\n public kBucketSize: number\n public kb?: KBucketTree\n public pingQueue: Queue\n\n private readonly log: Logger\n private readonly components: RoutingTableComponents\n private readonly lan: boolean\n private readonly pingTimeout: number\n private readonly pingConcurrency: number\n private running: boolean\n private readonly protocol: string\n private readonly tagName: string\n private readonly tagValue: number\n private metrics?: {\n routingTableSize: Metric\n pingQueueSize: Metric\n pingRunning: Metric\n }\n\n constructor (components: RoutingTableComponents, init: RoutingTableInit) {\n const { kBucketSize, pingTimeout, lan, pingConcurrency, protocol, tagName, tagValue } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:routing-table`)\n this.kBucketSize = kBucketSize ?? KBUCKET_SIZE\n this.pingTimeout = pingTimeout ?? PING_TIMEOUT\n this.pingConcurrency = pingConcurrency ?? PING_CONCURRENCY\n this.lan = lan\n this.running = false\n this.protocol = protocol\n this.tagName = tagName ?? KAD_CLOSE_TAG_NAME\n this.tagValue = tagValue ?? KAD_CLOSE_TAG_VALUE\n\n const updatePingQueueSizeMetric = (): void => {\n this.metrics?.pingQueueSize.update(this.pingQueue.size)\n this.metrics?.pingRunning.update(this.pingQueue.pending)\n }\n\n this.pingQueue = new Queue({ concurrency: this.pingConcurrency })\n this.pingQueue.addListener('add', updatePingQueueSizeMetric)\n this.pingQueue.addListener('next', updatePingQueueSizeMetric)\n\n this._onPing = this._onPing.bind(this)\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n async start (): Promise {\n this.running = true\n\n if (this.components.metrics != null) {\n this.metrics = {\n routingTableSize: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_routing_table_size`),\n pingQueueSize: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_ping_queue_size`),\n pingRunning: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_ping_running`)\n }\n }\n\n const kBuck: KBucketTree = new KBuck({\n localNodeId: await utils.convertPeerId(this.components.peerId),\n numberOfNodesPerKBucket: this.kBucketSize,\n numberOfNodesToPing: 1\n })\n this.kb = kBuck\n\n // test whether to evict peers\n kBuck.on('ping', this._onPing)\n\n // tag kad-close peers\n this._tagPeers(kBuck)\n }\n\n async stop (): Promise {\n this.running = false\n this.pingQueue.clear()\n this.kb = undefined\n }\n\n /**\n * Keep track of our k-closest peers and tag them in the peer store as such\n * - this will lower the chances that connections to them get closed when\n * we reach connection limits\n */\n _tagPeers (kBuck: KBucketTree): void {\n let kClosest = new PeerSet()\n\n const updatePeerTags = utils.debounce(() => {\n const newClosest = new PeerSet(\n kBuck.closest(kBuck.localNodeId, KBUCKET_SIZE).map(contact => contact.peer)\n )\n const addedPeers = newClosest.difference(kClosest)\n const removedPeers = kClosest.difference(newClosest)\n\n Promise.resolve()\n .then(async () => {\n for (const peer of addedPeers) {\n await this.components.peerStore.tagPeer(peer, this.tagName, {\n value: this.tagValue\n })\n }\n\n for (const peer of removedPeers) {\n await this.components.peerStore.unTagPeer(peer, this.tagName)\n }\n })\n .catch(err => {\n this.log.error('Could not update peer tags', err)\n })\n\n kClosest = newClosest\n })\n\n kBuck.on('added', () => {\n updatePeerTags()\n })\n kBuck.on('removed', () => {\n updatePeerTags()\n })\n }\n\n /**\n * Called on the `ping` event from `k-bucket` when a bucket is full\n * and cannot split.\n *\n * `oldContacts.length` is defined by the `numberOfNodesToPing` param\n * passed to the `k-bucket` constructor.\n *\n * `oldContacts` will not be empty and is the list of contacts that\n * have not been contacted for the longest.\n */\n _onPing (oldContacts: KBucketPeer[], newContact: KBucketPeer): void {\n // add to a queue so multiple ping requests do not overlap and we don't\n // flood the network with ping requests if lots of newContact requests\n // are received\n this.pingQueue.add(async () => {\n if (!this.running) {\n return\n }\n\n let responded = 0\n\n try {\n await Promise.all(\n oldContacts.map(async oldContact => {\n let timeoutController\n\n try {\n timeoutController = new TimeoutController(this.pingTimeout)\n\n const options = {\n signal: timeoutController.signal\n }\n\n this.log('pinging old contact %p', oldContact.peer)\n const connection = await this.components.connectionManager.openConnection(oldContact.peer, options)\n const stream = await connection.newStream(this.protocol, options)\n stream.close()\n responded++\n } catch (err: any) {\n if (this.running && this.kb != null) {\n // only evict peers if we are still running, otherwise we evict when dialing is\n // cancelled due to shutdown in progress\n this.log.error('could not ping peer %p', oldContact.peer, err)\n this.log('evicting old contact after ping failed %p', oldContact)\n this.kb.remove(oldContact.id)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n this.metrics?.routingTableSize.update(this.size)\n }\n })\n )\n\n if (this.running && responded < oldContacts.length && this.kb != null) {\n this.log('adding new contact %p', newContact.peer)\n this.kb.add(newContact)\n }\n } catch (err: any) {\n this.log.error('could not process k-bucket ping event', err)\n }\n })\n .catch(err => {\n this.log.error('could not process k-bucket ping event', err)\n })\n }\n\n // -- Public Interface\n\n /**\n * Amount of currently stored peers\n */\n get size (): number {\n if (this.kb == null) {\n return 0\n }\n\n return this.kb.count()\n }\n\n /**\n * Find a specific peer by id\n */\n async find (peer: PeerId): Promise {\n const key = await utils.convertPeerId(peer)\n const closest = this.closestPeer(key)\n\n if (closest != null && peer.equals(closest)) {\n return closest\n }\n\n return undefined\n }\n\n /**\n * Retrieve the closest peers to the given key\n */\n closestPeer (key: Uint8Array): PeerId | undefined {\n const res = this.closestPeers(key, 1)\n\n if (res.length > 0) {\n return res[0]\n }\n\n return undefined\n }\n\n /**\n * Retrieve the `count`-closest peers to the given key\n */\n closestPeers (key: Uint8Array, count = this.kBucketSize): PeerId[] {\n if (this.kb == null) {\n return []\n }\n\n const closest = this.kb.closest(key, count)\n\n return closest.map(p => p.peer)\n }\n\n /**\n * Add or update the routing table with the given peer\n */\n async add (peer: PeerId): Promise {\n if (this.kb == null) {\n throw new Error('RoutingTable is not started')\n }\n\n const id = await utils.convertPeerId(peer)\n\n this.kb.add({ id, peer })\n\n this.log('added %p with kad id %b', peer, id)\n\n this.metrics?.routingTableSize.update(this.size)\n }\n\n /**\n * Remove a given peer from the table\n */\n async remove (peer: PeerId): Promise {\n if (this.kb == null) {\n throw new Error('RoutingTable is not started')\n }\n\n const id = await utils.convertPeerId(peer)\n\n this.kb.remove(id)\n\n this.metrics?.routingTableSize.update(this.size)\n }\n}\n", "import { Netmask } from 'netmask';\nimport ip_regex from 'ip-regex';\nimport { isIP } from '@chainsafe/is-ip';\nimport ipaddr from 'ipaddr.js';\nconst { isValid: is_valid, parse } = ipaddr;\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(ip_range => new Netmask(ip_range));\nfunction ipv4_check(ip_addr) {\n for (let r of NETMASK_RANGES) {\n if (r.contains(ip_addr))\n return true;\n }\n return false;\n}\nfunction ipv6_check(ip_addr) {\n return /^::$/.test(ip_addr) ||\n /^::1$/.test(ip_addr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ip_addr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ip_addr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ip_addr);\n}\nexport default (ip) => {\n if (is_valid(ip)) {\n const parsed = parse(ip);\n if (parsed.kind() === 'ipv4')\n return ipv4_check(parsed.toNormalizedString());\n else if (parsed.kind() === 'ipv6')\n return ipv6_check(ip);\n }\n else if (isIP(ip) && ip_regex.v6().test(ip))\n return ipv6_check(ip);\n return undefined;\n};\n", "'use strict'\n\nimport is_ip_private from './lib/index.js'\nexport default is_ip_private", "// MaxRecordAge specifies the maximum time that any node will hold onto a record\n// from the time its received. This does not apply to any other forms of validity that\n// the record may contain.\n// For example, a record may contain an ipns entry with an EOL saying its valid\n// until the year 2020 (a great time in the future). For that record to stick around\n// it must be rebroadcasted more frequently than once every 'MaxRecordAge'\n\nexport const second = 1000\nexport const minute = 60 * second\nexport const hour = 60 * minute\n\nexport const MAX_RECORD_AGE = 36 * hour\n\nexport const LAN_PREFIX = '/lan'\n\nexport const PROTOCOL_PREFIX = '/ipfs'\n\nexport const PROTOCOL_DHT = '/kad/1.0.0'\n\nexport const RECORD_KEY_PREFIX = '/dht/record'\n\nexport const PROVIDER_KEY_PREFIX = '/dht/provider'\n\nexport const PROVIDERS_LRU_CACHE_SIZE = 256\n\nexport const PROVIDERS_VALIDITY = 24 * hour\n\nexport const PROVIDERS_CLEANUP_INTERVAL = hour\n\nexport const READ_MESSAGE_TIMEOUT = 10 * second\n\n// The number of records that will be retrieved on a call to getMany()\nexport const GET_MANY_RECORD_COUNT = 16\n\n// K is the maximum number of requests to perform before returning failure\nexport const K = 20\n\n// Alpha is the concurrency for asynchronous requests\nexport const ALPHA = 3\n\n// How often we look for our closest DHT neighbours\nexport const QUERY_SELF_INTERVAL = Number(5 * minute)\n\n// How long to look for our closest DHT neighbours for\nexport const QUERY_SELF_TIMEOUT = Number(30 * second)\n\n// How often we try to find new peers\nexport const TABLE_REFRESH_INTERVAL = Number(5 * minute)\n\n// How how long to look for new peers for\nexport const TABLE_REFRESH_QUERY_TIMEOUT = Number(30 * second)\n\n// When a timeout is not specified, run a query for this long\nexport const DEFAULT_QUERY_TIMEOUT = Number(30 * second)\n", "import { sha256 } from 'multiformats/hashes/sha2'\nimport { Key } from 'interface-datastore/key'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport isPrivateIp from 'private-ip'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { RECORD_KEY_PREFIX } from './constants.js'\n\n// const IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nconst PK_PREFIX = uint8ArrayFromString('/pk/')\n\nexport function removePrivateAddresses (peer: PeerInfo): PeerInfo {\n return {\n ...peer,\n multiaddrs: peer.multiaddrs.filter(multiaddr => {\n const [[type, addr]] = multiaddr.stringTuples()\n\n // treat /dns, /dns4, and /dns6 addrs as public\n if (type === 53 || type === 54 || type === 55) {\n // localhost can be a dns address but it's private\n if (addr === 'localhost') {\n return false\n }\n\n return true\n }\n\n if (type !== 4 && type !== 6) {\n return false\n }\n\n if (addr == null) {\n return false\n }\n\n const isPrivate = isPrivateIp(addr)\n\n if (isPrivate == null) {\n // not an ip address\n return true\n }\n\n return !isPrivate\n })\n }\n}\n\nexport function removePublicAddresses (peer: PeerInfo): PeerInfo {\n return {\n ...peer,\n multiaddrs: peer.multiaddrs.filter(multiaddr => {\n const [[type, addr]] = multiaddr.stringTuples()\n\n if (addr === 'localhost') {\n return true\n }\n\n if (type !== 4 && type !== 6) {\n return false\n }\n\n if (addr == null) {\n return false\n }\n\n const isPrivate = isPrivateIp(addr)\n\n if (isPrivate == null) {\n // not an ip address\n return false\n }\n\n return isPrivate\n })\n }\n}\n\n/**\n * Creates a DHT ID by hashing a given Uint8Array\n */\nexport async function convertBuffer (buf: Uint8Array): Promise {\n const multihash = await sha256.digest(buf)\n\n return multihash.digest\n}\n\n/**\n * Creates a DHT ID by hashing a Peer ID\n */\nexport async function convertPeerId (peerId: PeerId): Promise {\n return await convertBuffer(peerId.toBytes())\n}\n\n/**\n * Convert a Uint8Array to their SHA2-256 hash\n */\nexport function bufferToKey (buf: Uint8Array): Key {\n return new Key('/' + uint8ArrayToString(buf, 'base32'), false)\n}\n\n/**\n * Convert a Uint8Array to their SHA2-256 hash\n */\nexport function bufferToRecordKey (buf: Uint8Array): Key {\n return new Key(`${RECORD_KEY_PREFIX}/${uint8ArrayToString(buf, 'base32')}`, false)\n}\n\n/**\n * Generate the key for a public key.\n */\nexport function keyForPublicKey (peer: PeerId): Uint8Array {\n return uint8ArrayConcat([\n PK_PREFIX,\n peer.toBytes()\n ])\n}\n\nexport function isPublicKeyKey (key: Uint8Array): boolean {\n return uint8ArrayToString(key.subarray(0, 4)) === '/pk/'\n}\n\nexport function isIPNSKey (key: Uint8Array): boolean {\n return uint8ArrayToString(key.subarray(0, 4)) === '/ipns/'\n}\n\nexport function fromPublicKeyKey (key: Uint8Array): PeerId {\n return peerIdFromBytes(key.subarray(4))\n}\n\n/**\n * Create a new put record, encodes and signs it if enabled\n */\nexport function createPutRecord (key: Uint8Array, value: Uint8Array): Uint8Array {\n const timeReceived = new Date()\n const rec = new Libp2pRecord(key, value, timeReceived)\n\n return rec.serialize()\n}\n\nexport function debounce (callback: () => void, wait: number = 100): () => void {\n let timeout: ReturnType\n\n return (): void => {\n clearTimeout(timeout)\n timeout = setTimeout(() => { callback() }, wait)\n }\n}\n", "\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\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 * ```JavaScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator<[PeerId, T]> {\n return this.entries()\n }\n\n clear (): void {\n this.map.clear()\n }\n\n delete (peer: PeerId): void {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T): void {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values (): IterableIterator {\n return this.map.values()\n }\n\n get size (): number {\n return this.map.size\n }\n}\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\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 * ```JavaScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\n/**\n * We can't use PeerIds as list entries because list 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 * ```JavaScript\n * import { peerList } from '@libp2p/peer-collections'\n *\n * const list = peerList()\n * list.push(peerId)\n * ```\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList | Iterable) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList): PeerList {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]): void {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]): number {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length (): number {\n return this.list.length\n }\n}\n", "import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns the xor distance between two arrays\n */\nexport function xor (a: Uint8Array, b: Uint8Array): Uint8Array {\n if (a.length !== b.length) {\n throw new Error('Inputs should have the same length')\n }\n\n const result = allocUnsafe(a.length)\n\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i]\n }\n\n return asUint8Array(result)\n}\n", "export default [\n 77591, 22417, 43971, 28421, 740, 29829, 71467, 228973, 196661, 78537, 27689, 36431, 44415, 14362, 19456, 106025,\n 96308, 2882, 49509, 21149, 87173, 131409, 75844, 23676, 121838, 30291, 17492, 2953, 7564, 110620, 129477, 127283,\n 53113, 72417, 165166, 109690, 21200, 102125, 24049, 71504, 90342, 25307, 72039, 26812, 26715, 32264, 133800, 71161,\n 88956, 171987, 51779, 24425, 16671, 30251, 186294, 247761, 14202, 2121, 8465, 35024, 4876, 85917, 169730, 3638,\n 256836, 96184, 943, 18678, 6583, 52907, 35807, 112254, 214097, 18796, 11595, 9243, 23554, 887, 268203, 382004,\n 24590, 111335, 11625, 16619, 29039, 102425, 69006, 97976, 92362, 32552, 63717, 41433, 128974, 137630, 59943, 10019,\n 13986, 35430, 33665, 108037, 43799, 43280, 38195, 29078, 58629, 18265, 14425, 46832, 235538, 40830, 77881, 110717,\n 58937, 3463, 325358, 51300, 47623, 117252, 19007, 10170, 20540, 91237, 294813, 4951, 79841, 56232, 36270, 128547,\n 69209, 66275, 100156, 32063, 73531, 34439, 80937, 28892, 44466, 88595, 216307, 32583, 49620, 16605, 82127, 45807,\n 21630, 78726, 20235, 40163, 111007, 96926, 5567, 72083, 21665, 58844, 39419, 179767, 48328, 42662, 51550, 5251,\n 37811, 49608, 81056, 50854, 55513, 20922, 18891, 197409, 164656, 32593, 71449, 220474, 58919, 85682, 67854, 13758,\n 35066, 3565, 61905, 214793, 119572, 141419, 21504, 10302, 27354, 67003, 46131, 32668, 15165, 64871, 34450, 17821,\n 2757, 11452, 34189, 5160, 12257, 85523, 560, 53385, 65887, 119549, 135620, 312353, 115979, 122356, 10867, 193231,\n 124537, 54783, 90675, 120791, 4715, 142253, 50943, 17271, 43358, 25331, 4917, 120566, 34580, 12878, 33786, 160528,\n 32523, 4869, 301307, 104817, 81491, 23276, 8832, 97911, 31265, 52065, 7998, 49622, 9715, 43998, 34091, 84587,\n 20664, 69041, 29419, 53205, 10838, 58288, 116145, 6185, 5154, 141795, 35924, 21307, 144738, 43730, 12085, 8279,\n 10002, 119, 133779, 199668, 72938, 31768, 39176, 67875, 38453, 9700, 44144, 4121, 116048, 41733, 12868, 82669,\n 92308, 128, 34262, 11332, 7712, 90764, 36141, 13553, 71312, 77470, 117314, 96549, 49135, 23602, 54468, 28605,\n 6327, 62308, 17171, 67531, 21319, 14105, 894, 107722, 46157, 8503, 51069, 100472, 45138, 15246, 14577, 35609,\n 191464, 1757, 13364, 161349, 32067, 91705, 81144, 52339, 5408, 91066, 21983, 14157, 100545, 4372, 26630, 129112,\n 1423, 29676, 213626, 4397, 88436, 99190, 6877, 49958, 26122, 114348, 60661, 29818, 293118, 50042, 179738, 16400,\n 163423, 89627, 31040, 43973, 36638, 45952, 5153, 1894, 109322, 1898, 134021, 12402, 112077, 68309, 190269, 69866,\n 31938, 107383, 11522, 105232, 11248, 14868, 39852, 71707, 186525, 16530, 38162, 106212, 11700, 5130, 16608, 26998,\n 59586, 108399, 230033, 43683, 48135, 82179, 2073, 5015, 196684, 189293, 16378, 23452, 8301, 35640, 11632, 214551,\n 29240, 57644, 33137, 91949, 55157, 52384, 117313, 5090, 17717, 89668, 49363, 82238, 241035, 66216, 29066, 184088,\n 97206, 62820, 26595, 4241, 135635, 173672, 8202, 459, 71355, 146294, 29587, 3008, 135385, 141203, 14803, 6634,\n 45094, 69362, 50925, 546, 51884, 62011, 83296, 234584, 44515, 56050, 89476, 87751, 19373, 12691, 149923, 19794,\n 13833, 35846, 87557, 58339, 2884, 19145, 25647, 12224, 11024, 77338, 64608, 122297, 53025, 7205, 36189, 36294,\n 170779, 21750, 7739, 173883, 75192, 35664, 224240, 113121, 30181, 26267, 27036, 117827, 92015, 106516, 55628, 203549,\n 67949, 60462, 60844, 35911, 20457, 1820, 920, 19773, 8738, 73173, 181993, 38521, 98254, 76257, 46008, 92796,\n 5384, 26868, 151566, 22124, 2411, 15919, 186872, 180021, 28099, 152961, 78811, 80237, 62352, 102653, 74259, 184890,\n 16792, 123702, 224945, 29940, 19512, 75283, 14059, 112691, 92811, 233329, 20411, 138569, 53341, 109802, 50600, 134528,\n 66747, 5529, 166531, 31578, 64732, 67189, 1596, 126357, 967, 167999, 206598, 109752, 119431, 207825, 78791, 91938,\n 10301, 27311, 24233, 252343, 28831, 32812, 66002, 112267, 90895, 8786, 8095, 16824, 22866, 21813, 60507, 174833,\n 19549, 130985, 117051, 52110, 6938, 81923, 123864, 38061, 919, 18680, 53534, 46739, 112893, 161529, 85429, 26761,\n 11900, 81121, 91968, 15390, 217947, 56524, 1713, 6654, 37089, 85630, 138866, 61850, 16491, 75577, 16884, 98296,\n 73523, 6140, 44645, 6062, 36366, 29844, 57946, 37932, 42472, 5266, 20834, 19309, 33753, 127182, 134259, 35810,\n 41805, 45878, 312001, 14881, 47757, 49251, 120050, 44252, 3708, 25856, 107864, 120347, 1228, 36550, 41682, 34496,\n 47025, 8393, 173365, 246526, 12894, 161607, 35670, 90785, 126572, 2095, 124731, 157033, 58694, 554, 12786, 9642,\n 4817, 16136, 47864, 174698, 66992, 4639, 69284, 10625, 40710, 27763, 51738, 30404, 264105, 137904, 109882, 52487,\n 42824, 57514, 2740, 10479, 146799, 107390, 16586, 88038, 174951, 9410, 16185, 44158, 5568, 40658, 46108, 12763,\n 97385, 26175, 108859, 664, 230732, 67470, 46663, 14395, 50750, 141320, 93140, 15361, 47997, 55784, 6791, 307840,\n 118569, 107326, 18056, 58281, 260415, 54691, 8790, 73332, 45633, 7511, 45674, 143373, 14031, 11799, 94491, 35646,\n 96544, 14560, 26049, 32983, 25791, 83814, 42094, 231370, 63955, 139212, 2359, 169908, 3108, 183486, 105867, 28197,\n 32941, 124968, 26402, 88267, 149768, 23053, 3078, 19091, 52924, 25383, 19209, 111548, 97361, 3959, 24880, 235061,\n 9099, 24921, 161254, 151405, 20508, 7159, 34381, 20133, 11434, 74036, 19974, 34769, 36585, 1076, 22454, 17354,\n 38727, 235160, 111547, 96454, 117448, 156940, 91330, 37299, 7310, 26915, 117060, 51369, 22620, 61861, 322264, 106850,\n 111694, 15091, 2624, 40345, 300446, 177064, 1707, 27389, 54792, 327783, 132669, 183543, 59003, 17744, 20603, 151134,\n 106923, 53084, 71803, 279424, 319816, 11579, 21946, 16728, 38274, 72711, 5085, 83391, 88646, 40159, 25027, 34680,\n 10752, 12988, 54126, 30365, 18338, 100445, 230674, 44874, 84974, 143877, 123253, 139372, 28082, 91477, 144002, 13096,\n 219729, 46016, 50029, 42377, 14601, 6660, 58244, 58978, 23918, 88206, 113611, 64452, 17541, 41032, 10942, 12021,\n 49189, 10978, 40175, 37156, 10947, 71709, 106894, 112538, 57007, 137486, 150608, 152719, 40615, 7746, 279716, 13101,\n 19524, 28708, 40578, 72320, 1096, 182051, 94527, 51275, 22833, 45164, 81917, 77519, 48508, 5421, 140302, 37845,\n 149830, 5587, 27579, 5357, 428725, 248187, 6326, 206760, 39814, 32585, 89923, 44341, 288753, 284443, 96368, 31201,\n 94189, 119504, 20359, 52073, 103216, 179, 27934, 32801, 96035, 34111, 34309, 101326, 18198, 20704, 210266, 37643,\n 27880, 141873, 106000, 19414, 56614, 167714, 66483, 107885, 86602, 4379, 20796, 75467, 4987, 5017, 118857, 26003,\n 34308, 114428, 29198, 6686, 29697, 73632, 3739, 69795, 16798, 41504, 7207, 30722, 21436, 36735, 28067, 28545,\n 3239, 11221, 36031, 41889, 100010, 19247, 317673, 29495, 174554, 6424, 129725, 53845, 94986, 7955, 59676, 2604,\n 191497, 19735, 102214, 62954, 23844, 11872, 179525, 261436, 34492, 428, 78404, 142035, 16747, 17246, 27578, 37021,\n 33672, 57944, 26056, 135760, 2369, 61674, 122066, 31327, 19374, 157065, 40553, 130982, 69619, 71290, 38855, 72100,\n 92903, 95940, 51422, 165999, 65713, 57873, 50726, 7288, 20272, 2081, 42326, 22624, 81120, 57914, 79352, 19447,\n 1684, 72302, 11774, 302559, 161481, 96396, 13692, 414988, 3721, 79066, 56627, 46883, 21150, 11747, 12184, 5856,\n 113458, 176117, 84416, 52079, 27933, 3354, 59765, 141359, 2212, 216309, 2555, 23458, 196722, 142463, 45701, 44548,\n 28798, 19418, 215, 29916, 9396, 10574, 114226, 84475, 13520, 18694, 34056, 4524, 90302, 62930, 13539, 19407,\n 77209, 7728, 38088, 9535, 2263, 23875, 183945, 17750, 26274, 67172, 10585, 28042, 22199, 7478, 51331, 66030,\n 26774, 192929, 31434, 25850, 50197, 52926, 178158, 4679, 181256, 70184, 229600, 9959, 105594, 72158, 73974, 2726,\n 35085, 78087, 23284, 35568, 51713, 155676, 5401, 27254, 11966, 17569, 223253, 71993, 103357, 111477, 55722, 30504,\n 26034, 46774, 35392, 36285, 214814, 41143, 163465, 1051, 16094, 81044, 6636, 76489, 179102, 20712, 39178, 35683,\n 125177, 54219, 30617, 52994, 25324, 50123, 2543, 87529, 58995, 10688, 125199, 12388, 60158, 125481, 131646, 7642,\n 133350, 65874, 3438, 97277, 101450, 10075, 56344, 116821, 50778, 60547, 98016, 106135, 13859, 14255, 16300, 77373,\n 173521, 8285, 45932, 37426, 4054, 114295, 55947, 7703, 39114, 52, 51119, 128135, 19714, 60715, 9554, 50492,\n 88180, 2823, 118271, 52993, 122625, 97919, 23859, 37895, 25040, 33614, 32102, 20431, 3577, 9275, 15686, 43031,\n 157741, 110358, 1884, 40291, 125391, 13736, 5008, 64881, 87336, 77381, 70711, 43032, 49155, 118587, 70494, 4318,\n 10168, 30126, 12580, 10524, 280104, 104001, 145413, 2862, 84140, 6603, 106005, 13566, 12780, 11251, 42830, 571,\n 179910, 82443, 13146, 469, 42714, 32591, 265217, 424024, 92553, 54721, 134100, 6007, 15242, 114681, 59030, 16718,\n 85465, 200214, 85982, 55174, 165013, 23493, 56964, 82529, 109150, 32706, 27568, 82442, 5350, 14976, 13165, 44890,\n 60021, 21343, 33978, 17264, 4655, 22328, 27819, 75730, 16567, 55483, 14510, 17926, 45827, 150609, 3704, 7385,\n 272531, 161543, 76904, 122163, 52405, 2039, 19165, 41623, 14423, 228354, 3369, 176360, 85491, 7122, 35789, 303724,\n 4465, 13628, 2233, 55311, 118771, 20713, 10006, 221519, 45115, 71021, 35650, 29775, 7337, 10864, 20665, 21142,\n 1746, 15080, 1624, 32449, 10905, 105743, 229797, 7701, 3940, 22997, 178467, 57208, 389057, 39683, 59403, 63344,\n 63125, 54847, 69691, 18336, 56448, 3362, 37202, 18282, 29648, 138224, 35867, 10495, 5911, 28814, 26653, 31514,\n 176702, 26550, 45621, 11734, 4525, 40543, 73944, 121080, 27858, 155561, 14887, 44670, 30742, 8796, 107455, 113472,\n 56369, 75581, 183777, 240095, 133699, 153299, 8768, 160464, 26058, 49078, 103971, 21875, 71486, 44888, 17156, 9678,\n 89541, 123019, 102337, 3972, 83930, 21245, 87852, 109660, 287918, 183019, 686, 10100, 39177, 283941, 11274, 24736,\n 26793, 26214, 25995, 77011, 141580, 4070, 23742, 46285, 46632, 30700, 26669, 19056, 35951, 115575, 174034, 56097,\n 35463, 87425, 24575, 44245, 38701, 82317, 85922, 281616, 100333, 147697, 61503, 7730, 84330, 8530, 59917, 61597,\n 17173, 9092, 32658, 90288, 193136, 39023, 20381, 56654, 31132, 7779, 1919, 1375, 117128, 30819, 11169, 40938,\n 23935, 115201, 101155, 151034, 4835, 11231, 74550, 89388, 59951, 91704, 107312, 167882, 115062, 12732, 72738, 88703,\n 464019, 158267, 57995, 60496, 737, 14371, 123867, 4174, 243339, 159946, 7568, 16025, 134556, 110916, 38103, 191,\n 80226, 88794, 29688, 27230, 10454, 76308, 57647, 77409, 113483, 66864, 14745, 19808, 12023, 46583, 84805, 16015,\n 17102, 2231, 20611, 3547, 95740, 250131, 34559, 108894, 8498, 15853, 159169, 148920, 20942, 2813, 93160, 45188,\n 210613, 45531, 52587, 149062, 39782, 28194, 57849, 60965, 84954, 89766, 84453, 100927, 16501, 27658, 165311, 103841,\n 54192, 207341, 19558, 20084, 319622, 5672, 205467, 98462, 61849, 36279, 13609, 147177, 24726, 165015, 209489, 59591,\n 31157, 6551, 117580, 75060, 141146, 277310, 21072, 22023, 106474, 63041, 137443, 122965, 68371, 5383, 42146, 98961,\n 113467, 30863, 23794, 4843, 99630, 30392, 82679, 13699, 241612, 33601, 93146, 24319, 18643, 32155, 95669, 40440,\n 15333, 34089, 67799, 142144, 58245, 38633, 114531, 117400, 77861, 188726, 5507, 2568, 8853, 10987, 107222, 2663,\n 2421, 11530, 13345, 30075, 41785, 118661, 104786, 17459, 12490, 16281, 71936, 193555, 17431, 5944, 71758, 26485,\n 77317, 20803, 367167, 158, 7362, 93430, 11735, 172445, 46002, 11532, 54482, 930, 62911, 2235, 23004, 179236,\n 4764, 101859, 208113, 22477, 55163, 95579, 14098, 67320, 162556, 90709, 156949, 3826, 57492, 4025, 34092, 87442,\n 104565, 6718, 186015, 28214, 14209, 10039, 107186, 233912, 58877, 81637, 55265, 39828, 6194, 145813, 50831, 105849,\n 4974, 88319, 122296, 10272, 197216, 95714, 51540, 72418, 23324, 91555, 8743, 140452, 250249, 51666, 34124, 7229,\n 38592, 129641, 78169, 174242, 22464, 149964, 51450, 14034, 10026, 95376, 26190, 120062, 14401, 8700, 265, 31386,\n 143573, 7203, 229889, 61567, 4227, 140981, 2466, 72052, 10787, 10062, 30958, 6099, 38471, 30103, 23202, 208101,\n 70847, 467, 58934, 32271, 32984, 36637, 24107, 30771, 17109, 73353, 13650, 2098, 157040, 67366, 66904, 106018,\n 265380, 107238, 18535, 44025, 32681, 144983, 62505, 91295, 56120, 3082, 77508, 10322, 63023, 36700, 81885, 224127,\n 16721, 45023, 239261, 111272, 13852, 7866, 149243, 204199, 32309, 22084, 42029, 38316, 126644, 104973, 14406, 43454,\n 67322, 61310, 15789, 40285, 24026, 181047, 6301, 70927, 23319, 115823, 27248, 66693, 115875, 278566, 63007, 146844,\n 56841, 59007, 87368, 180001, 22370, 42114, 80605, 12022, 10374, 308, 25079, 14689, 12618, 63368, 7936, 264973,\n 212291, 136713, 95999, 105801, 18965, 32075, 48700, 52230, 35119, 96912, 32992, 8586, 16606, 101333, 101812, 14969,\n 39930, 759, 193090, 27387, 42914, 12937, 5058, 62646, 64528, 38624, 25743, 37502, 3716, 4435, 30352, 178687,\n 26461, 132611, 42002, 138442, 35833, 59582, 16345, 8048, 60319, 49349, 309, 47800, 49739, 90482, 26405, 34470,\n 63786, 32479, 85028, 39866, 47846, 11649, 23934, 29466, 2816, 42864, 31828, 7410, 74885, 49632, 47629, 111801,\n 90749, 19536, 18767, 105764, 59606, 21223, 10746, 76298, 22220, 39408, 7190, 79654, 64856, 11602, 82156, 272765,\n 17079, 70089, 245473, 51813, 184407, 384678, 1576, 122249, 5064, 27481, 6188, 25790, 74361, 27541, 318284, 45430,\n 31488, 620, 93579, 45723, 192118, 22670, 51913, 4162, 70244, 35966, 26397, 16199, 50899, 209613, 121702, 287507,\n 2993, 36101, 132229, 67345, 33062, 76295, 118628, 78705, 52316, 34375, 107083, 107454, 44863, 127561, 33964, 3073,\n 154010, 190914, 55967, 39074, 6272, 31047, 5550, 41123, 26154, 98638, 47110, 19998, 148091, 50229, 31329, 59900,\n 195442, 19106, 61347, 73497, 70015, 682, 45850, 25776, 38022, 148951, 6288, 37411, 232526, 109277, 27286, 32342,\n 9262, 5220, 16651, 23175, 46740, 129438, 78614, 121925, 66914, 88710, 127952, 5563, 21500, 34521, 10739, 14863,\n 191006, 62956, 17359, 16749, 67027, 56284, 69134, 43301, 35039, 58883, 54466, 60823, 404451, 75743, 59856, 86979,\n 7923, 34273, 83785, 32142, 7693, 268986, 197428, 282681, 17049, 22346, 22990, 92245, 107180, 3357, 37104, 96724,\n 49153, 7683, 31197, 43267, 82231, 164276, 23696, 20848, 188364, 22309, 24821, 158707, 1018, 22514, 70922, 27792,\n 45589, 59709, 10765, 736, 35218, 63479, 51987, 24275, 63588, 55361, 92929, 81964, 4658, 20122, 12330, 44058,\n 13065, 311456, 72224, 8337, 211229, 38979, 22590, 138478, 52757, 32595, 133600, 8838, 31549, 94412, 43391, 90056,\n 1585, 94802, 127271, 6223, 31889, 137038, 132910, 2165, 57616, 230152, 6080, 10748, 36737, 74579, 134062, 50525,\n 180532, 119270, 34556, 76155, 82394, 52595, 29258, 31435, 87820, 67996, 26943, 183878, 38007, 2410, 13526, 180297,\n 69856, 3503, 187396, 167700, 7838, 16701, 9199, 56267, 3661, 37407, 65994, 23767, 5708, 62508, 221700, 67088,\n 86978, 46776, 84434, 32088, 5612, 9149, 88244, 21685, 95151, 46750, 189612, 2979, 506311, 2594, 3628, 40074,\n 105039, 78243, 28523, 6651, 38058, 71999, 30992, 12764, 68261, 108991, 6165, 26450, 61961, 13400, 22426, 7490,\n 60890, 109623, 2070, 12958, 50355, 67979, 257096, 7213, 42578, 52121, 35716, 65461, 7516, 124758, 39268, 302,\n 64712, 14977, 1467, 219452, 2840, 34229, 11121, 21602, 19270, 63574, 8024, 1532, 17331, 79839, 78885, 52029,\n 180767, 57957, 6069, 91265, 61380, 55767, 8927, 32881, 287603, 22149, 35029, 68876, 6428, 199567, 46926, 13412,\n 104132, 21434, 366616, 45060, 110046, 81924, 128910, 45886, 52821, 130416, 29416, 77342, 21762, 67329, 121432, 79924,\n 11724, 38625, 81006, 102033, 28338, 13326, 3250, 82056, 82526, 38212, 21112, 12382, 111495, 3263, 7414, 86274,\n 93490, 40844, 30224, 45212, 24019, 48411, 71367, 24941, 76729, 57776, 3769, 38114, 202019, 197745, 31953, 237533,\n 33270, 201580, 255648, 100798, 44741, 32241, 98468, 106931, 10085, 15090, 170358, 33154, 66787, 18819, 69760, 25061,\n 234005, 82660, 6295, 131975, 16874, 9076, 4094, 25005, 17740, 40908, 19533, 220019, 44330, 99792, 50040, 19619,\n 13950, 55228, 24423, 31253, 95308, 103177, 184795, 28590, 82285, 5059, 3210, 75525, 49894, 70007, 56178, 10580,\n 36051, 139681, 21617, 98736, 3555, 106306, 164189, 37352, 63915, 47824, 24883, 145530, 61904, 28444, 11483, 19837,\n 145446, 30420, 112972, 85939, 11835, 191233, 2262, 20705, 58630, 1753, 148334, 1197, 144714, 6887, 11223, 107667,\n 60879, 77914, 4151, 57417, 81594, 96681, 169430, 1784, 20444, 95138, 254041, 27038, 596, 7117, 72808, 13759,\n 3353, 126776, 21074, 55322, 27081, 36942, 39547, 139830, 179275, 4453, 713, 8722, 71399, 19204, 25785, 22794,\n 23923, 104114, 11291, 25458, 102309, 88396, 75288, 230440, 206396, 104551, 58447, 130857, 37247, 94734, 31548, 176529,\n 226077, 65159, 20104, 10096, 66881, 94191, 237909, 27109, 37404, 1520, 27421, 25220, 113003, 23423, 24884, 50585,\n 6286, 231877, 150800, 11789, 3226, 90004, 60642, 5053, 202400, 61442, 132531, 175329, 57138, 30116, 103847, 9973,\n 75367, 16452, 32360, 59119, 21246, 10191, 164804, 23305, 61051, 37348, 154530, 13214, 5468, 50403, 66754, 130976,\n 50559, 80515, 14436, 155492, 84017, 5472, 43107, 41240, 2890, 90431, 70188, 382, 76234, 48040, 50211, 281038,\n 237007, 32115, 142178, 1536, 22761, 96429, 1811, 31243, 1679, 49143, 55209, 17402, 235054, 61494, 7462, 77030,\n 34925, 87609, 78002, 9499, 9027, 73289, 201078, 101379, 63544, 27666, 5469, 10642, 30029, 49816, 132979, 95620,\n 58086, 351930, 116300, 2110, 2043, 30845, 6154, 11279, 16727, 4122, 2277, 27281, 4971, 3650, 39060, 61970,\n 65951, 39674, 75686, 38151, 11370, 130809, 177895, 32665, 63725, 122267, 7857, 39618, 118483, 44792, 157755, 178624,\n 136994, 24260, 41308, 22471, 12404, 21707, 12486, 30473, 52781, 50246, 20247, 39065, 909, 56825, 103158, 128603,\n 31542, 1089, 41935, 32744, 12428, 37963, 84420, 33134, 72921, 208449, 42622, 168151, 127335, 147107, 46699, 38216,\n 12591, 94342, 85814, 31423, 24944, 2605, 87542, 67473, 192551, 4496, 56321, 91819, 17630, 6300, 256183, 114569,\n 202090, 33209, 35289, 34897, 24967, 40520, 43470, 5344, 10199, 34810, 14283, 10381, 10017, 62923, 49924, 23233,\n 64539, 13051, 35686, 19698, 11570, 135555, 120868, 44924, 87065, 52318, 52335, 47586, 140906, 245885, 109834, 78668,\n 9065, 46990, 25258, 72022, 61243, 40838, 4545, 146387, 10537, 11557, 17470, 36930, 68104, 46711, 24264, 79401,\n 81043, 18225, 120488, 24746, 84338, 81652, 28266, 13776, 21878, 46973, 1047, 230465, 73357, 95777, 24973, 210160,\n 62210, 58404, 110633, 169651, 6937, 41870, 9909, 26822, 191062, 76553, 27519, 96256, 239070, 2478, 205678, 67955,\n 58532, 20601, 50120, 19148, 78501, 195724, 110740, 8249, 109665, 27446, 30568, 57631, 31425, 49752, 32820, 65504,\n 50079, 3663, 102256, 219898, 23849, 211315, 14645, 4359, 91767, 9528, 12449, 49366, 7941, 49763, 107848, 8930,\n 27086, 50686, 9744, 10447, 81935, 39513, 46514, 1670, 29229, 6172, 22312, 137280, 97759, 9806, 14445, 22976,\n 56458, 73391, 34983, 93760, 174219, 52573, 33149, 59747, 2429, 136277, 75123, 165263, 91040, 7446, 57632, 48633,\n 97140, 246081, 84766, 151684, 79918, 93268, 120346, 54059, 54875, 77858, 32996, 103590, 45276, 11968, 19600, 25849,\n 17159, 132907, 42828, 16817, 4913, 99462, 103303, 27395, 5737, 74184, 20749, 21160, 14377, 77062, 131403, 158735,\n 10999, 27799, 77785, 9320, 34366, 51593, 61070, 33746, 47048, 29268, 36675, 30262, 53297, 9832, 82000, 20188,\n 122292, 39917, 7331, 18160, 68301, 185935, 134830, 15031, 4935, 10004, 165845, 185534, 46923, 30109, 44134, 122631,\n 18874, 22903, 112790, 26561, 18549, 348902, 82871, 140345, 255565, 135390, 63556, 103747, 145055, 179600, 145662, 296111,\n 61661, 211987, 23952, 52342, 126343, 48450, 32919, 44277, 82185, 9591, 62139, 205363, 376969, 394874, 108461, 18040,\n 120885, 14798, 39863, 16571, 16794, 58271, 81025, 55206, 14640, 118656, 6361, 44092, 85970, 6262, 153863, 108244,\n 180200, 72264, 79947, 38044, 10050, 5735, 61221, 80712, 5471, 115689, 11391, 11661, 184257, 20010, 60116, 30320,\n 19327, 134598, 45455, 27542, 18004, 125092, 452272, 1549, 91523, 46567, 180063, 156026, 2608, 11174, 58848, 37788,\n 65907, 80194, 30490, 5786, 40775, 119519, 106241, 11323, 156297, 8425, 61495, 2617, 29675, 2425, 59886, 112582,\n 49142, 59618, 4863, 50597, 86710, 50650, 168632, 27693, 85641, 83643, 18993, 25768, 84284, 28090, 93592, 36627,\n 312804, 43381, 9887, 9402, 100931, 97165, 3311, 173330, 66805, 28935, 4963, 184460, 3201, 78102, 19126, 21607,\n 37496, 24938, 22615, 16153, 32862, 134792, 153318, 61120, 6067, 2812, 12826, 12792, 23825, 37559, 64662, 202250,\n 102694, 155488, 85881, 149193, 46233, 65383, 15521, 106982, 11358, 176786, 25752, 39717, 34208, 24510, 32464, 77742,\n 39371, 72028, 138229, 60688, 71386, 102834, 132477, 2208, 11548, 63670, 271279, 28351, 30338, 38620, 32491, 99845,\n 143885, 152266, 13252, 2825, 178663, 108097, 1775, 78201, 14897, 113573, 163346, 62292, 171129, 22183, 96598, 38733,\n 64971, 166776, 117445, 9968, 146393, 44677, 74867, 20908, 97328, 12761, 25656, 26785, 9148, 112344, 26115, 99176,\n 110121, 22437, 49547, 6180, 79320, 5835, 31392, 43328, 33377, 75870, 119860, 69497, 80273, 7325, 155219, 43167,\n 111173, 28347, 20222, 3763, 71752, 55041, 47252, 14618, 28088, 15012, 97805, 194698, 54636, 2036, 41349, 6173,\n 96604, 61530, 51859, 43782, 13361, 24334, 22668, 24792, 7070, 23441, 16789, 3209, 36211, 208475, 26242, 32880,\n 122181, 182407, 21444, 31060, 88459, 29929, 77907, 12716, 10934, 97005, 20599, 31690, 8403, 58445, 30303, 22700,\n 10336, 86731, 103115, 337709, 72556, 46788, 112566, 47684, 67089, 53548, 36874, 56487, 41387, 125985, 26893, 40071,\n 106683, 73712, 18787, 40105, 72992, 67246, 137276, 50802, 36790, 70328, 138827, 22466, 39263, 183295, 29858, 50975,\n 9322, 57397, 10654, 24364, 30383, 55799, 41600, 23584, 127295, 296610, 129078, 143558, 244131, 86397, 36049, 1085,\n 80677, 3820, 108139, 5476, 34767, 24683, 7758, 13060, 7239, 131671, 250593, 59556, 103392, 29810, 4188, 252323,\n 39404, 116877, 7651, 43600, 40338, 13554, 157253, 39196, 25978, 144387, 61211, 234, 50104, 6129, 10449, 93777,\n 9240, 356378, 274148, 4439, 72970, 3724, 147770, 78680, 62570, 115877, 40027, 40547, 36817, 224392, 64609, 34795,\n 165027, 67440, 2477, 37206, 23431, 50754, 164797, 46018, 94995, 170982, 27051, 7957, 22767, 3674, 27900, 56419,\n 18930, 60701, 41302, 2692, 84749, 339721, 61996, 111094, 80221, 50129, 1045, 8153, 62945, 19202, 8250, 37208,\n 37418, 32560, 79477, 41106, 88569, 33963, 36693, 5892, 30570, 1581, 66471, 49647, 11922, 160717, 29442, 5643,\n 114865, 82962, 95982, 132098, 22633, 22838, 94726, 54556, 28566, 205039, 162340, 33216, 16849, 35847, 221339, 94851,\n 26533, 71469, 1805, 3804, 12935, 45483, 71020, 36310, 65381, 192960, 34240, 35165, 59773, 1248, 46954, 155332,\n 96864, 4246, 388800, 16129, 57133, 74592, 44807, 442014, 38203, 42574, 80818, 91592, 26377, 36424, 65760, 977,\n 77387, 22628, 147610, 28018, 30561, 98454, 6969, 119628, 63648, 18170, 36854, 26601, 64018, 22027, 37279, 51395,\n 152934, 21153, 9430, 58760, 194742, 5330, 55115, 34158, 28917, 174111, 13171, 122326, 1526, 43896, 66094, 25325,\n 4234, 148354, 11450, 275, 18999, 112191, 44365, 22723, 68409, 8733, 57746, 96565, 75007, 14196, 108844, 29475,\n 88599, 177563, 100792, 106156, 86323, 93726, 14248, 135341, 194131, 40126, 47099, 14779, 8272, 39597, 95983, 171398,\n 65882, 28052, 10393, 47213, 40689, 22120, 72212, 106829, 34964, 109146, 753, 648, 21660, 30047, 17527, 181025,\n 5619, 145357, 4085, 216883, 9359, 186951, 24779, 53931, 24545, 36197, 223296, 62628, 168101, 4243, 107313, 30321,\n 26642, 13049, 51059, 31027, 107912, 807, 73550, 26551, 84369, 122422, 165872, 49754, 74213, 234264, 33151, 52014,\n 33100, 87183, 22365, 52500, 40013, 23302, 5652, 72723, 21404, 26107, 48434, 587, 94049, 168493, 96418, 32871,\n 70860, 31709, 25128, 443, 71597, 166253, 15670, 70994, 26341, 133675, 28280, 75491, 54756, 47955, 56028, 26182,\n 11952, 113272, 472197, 64640, 110753, 17919, 337, 50642, 22576, 142, 87371, 53391, 93210, 126694, 15285, 19642,\n 85667, 14148, 1506, 42092, 52962, 33243, 11970, 20734, 135843, 57044, 58880, 13002, 219134, 22876, 64754, 232519,\n 4257, 43120, 321573, 24799, 64526, 124728, 52579, 81472, 70831, 276848, 17403, 74359, 23021, 182101, 74597, 23744,\n 148267, 12055, 7976, 5349, 11772, 67540, 167347, 65318, 18720, 127832, 108238, 22828, 90233, 9987, 259080, 118185,\n 73209, 79270, 13775, 90100, 137742, 90799, 70569, 15699, 19961, 9087, 67475, 57872, 39731, 8810, 134897, 131868,\n 146849, 19898, 3334, 2281, 167061, 91073, 60356, 467742, 74712, 188, 53179, 137679, 92769, 29241, 9537, 132595,\n 80119, 1041, 88962, 5976, 40171, 44911, 102859, 139059, 104558, 98987, 47761, 19272, 71472, 113864, 175377, 73338,\n 10857, 23402, 23758, 1591, 139864, 5644, 4076, 118760, 16427, 134198, 18853, 20291, 100849, 37423, 22038, 36677,\n 19071, 195521, 57445, 11069, 31869, 55718, 66882, 148490, 44, 41296, 75242, 49704, 166810, 9906, 20943, 122258,\n 49112, 105667, 15969, 10344, 6408, 187694, 21399, 72742, 58970, 14867, 14376, 81889, 41856, 23225, 15042, 56993,\n 16074, 131389, 74276, 72407, 53875, 383108, 53597, 37363, 68993, 44854, 122548, 430927, 198279, 38430, 80409, 12245,\n 2981, 628, 2818, 17760, 37437, 238229, 7968, 46892, 2200, 3730, 34190, 65983, 37959, 112291, 87850, 70827,\n 6522, 20750, 73913, 111621, 41652, 19587, 2780, 58668, 25916, 85259, 18200, 168962, 95781, 42445, 102050, 7776,\n 57662, 103313, 47742, 96358, 41964, 66174, 100396, 29069, 204735, 19679, 27978, 7479, 40264, 22534, 61183, 36081,\n 107436, 58223, 14680, 23002, 101311, 24716, 124108, 12908, 5646, 31750, 40380, 14215, 232799, 102772, 14122, 96775,\n 61398, 50917, 12096, 149880, 67833, 598749, 124194, 155871, 49216, 790, 14677, 65319, 56917, 7440, 145744, 95701,\n 12206, 49405, 129269, 76199, 45732, 9767, 11058, 9047, 210885, 11051, 7392, 26307, 2130, 8132, 147526, 20802,\n 232698, 115660, 50060, 59789, 57344, 107623, 80343, 112676, 23291, 9866, 160971, 34032, 118291, 15719, 59730, 164911,\n 28975, 2659, 58046, 78480, 21854, 66209, 53863, 109085, 116045, 29021, 46481, 107552, 22130, 18764, 70254, 31272,\n 11300, 52460, 43933, 84738, 20721, 53869, 190840, 79673, 105300, 7561, 321817, 66924, 13940, 33281, 101046, 183181,\n 32176, 71878, 5678, 62924, 79535, 56646, 40303, 19559, 27703, 93042, 73368, 42187, 3670, 37376, 46440, 7023,\n 36816, 109628, 20680, 5940, 276440, 275233, 170848, 112093, 136996, 14984, 20226, 111441, 77693, 112960, 48577, 39370,\n 55707, 50314, 123404, 26570, 54281, 61372, 123391, 4857, 35928, 246740, 132507, 106646, 44241, 7196, 92258, 9825,\n 37688, 51197, 303141, 5590, 15476, 132986, 10955, 85782, 34486, 26696, 7991, 28813, 18858, 39546, 11703, 11365,\n 38185, 5716, 93555, 11925, 40121, 60002, 6985, 10976, 171384, 3887, 43394, 13337, 56346, 6381, 252336, 39573,\n 75042, 53711, 1028, 31781, 44295, 95925, 131713, 7214, 68125, 43571, 70954, 213234, 1628, 8760, 13391, 65485,\n 17320, 56038, 1710, 25248, 60803, 57399, 19839, 3870, 326, 281556, 50945, 72400, 21460, 316244, 75619, 56246,\n 98775, 481, 13513, 55765, 50427, 7388, 123519, 32929, 57908, 27124, 61316, 101097, 57467, 30228, 48792, 10788,\n 20402, 37318, 50526, 155730, 34456, 158065, 145305, 17832, 43733, 64052, 4506, 35072, 205355, 177028, 184004, 187081,\n 68616, 35938, 83703, 10367, 36892, 93186, 260137, 51934, 89970, 4985, 23445, 26755, 21558, 7948, 78741, 23376,\n 124405, 85594, 68596, 57536, 49351, 12619, 56593, 132668, 99924, 109728, 71844, 71935, 196018, 65464, 17617, 14987,\n 89701, 143773, 33997, 8687, 22701, 33258, 2914, 4436, 72108, 85610, 9671, 49067, 2327, 82988, 1361, 1672,\n 44033, 35777, 30269, 24057, 10605, 82236, 616, 15793, 13919, 47249, 112086, 116698, 9484, 80207, 90574, 33304,\n 68624, 93127, 56101, 42210, 160929, 4827, 38995, 38095, 4701, 125119, 5027, 33680, 9236, 231236, 14135, 87837,\n 23318, 70261, 78893, 30151, 81482, 14332, 1084, 74256, 27532, 46644, 79185, 3148, 62615, 6981, 55672, 31668,\n 36825, 1849, 14536, 37446, 14738, 23779, 43058, 162749, 72199, 1168, 21346, 5592, 85932, 85302, 9668, 18351,\n 57135, 150360, 2080, 228015, 77953, 34670, 119302, 151751, 31009, 106725, 84265, 45214, 59289, 74178, 113071, 263206,\n 111009, 4021, 44449, 188119, 192629, 123592, 392506, 292847, 114487, 12831, 205858, 9852, 20780, 79648, 75767, 357014,\n 97721, 18166, 21005, 67950, 33226, 204009, 16536, 2987, 11335, 66717, 144910, 47950, 17262, 55060, 15063, 2934,\n 51038, 26775, 178497, 66008, 3427, 49433, 128592, 20036, 157553, 63861, 3089, 23015, 51210, 28696, 35933, 49942,\n 71135, 231518, 99620, 17248, 21835, 176536, 20676, 16944, 38700, 165831, 233253, 295625, 36723, 13023, 52745, 10907,\n 19423, 67972, 125868, 95473, 82875, 1183, 108455, 52685, 33417, 64095, 21433, 52438, 33191, 127809, 44505, 211823,\n 7810, 2752, 95548, 162031, 7185, 91196, 47563, 61721, 33359, 17897, 23682, 42806, 178101, 22874, 49707, 199897,\n 75419, 82456, 8618, 11171, 79712, 116847, 18783, 44190, 46564, 5346, 59046, 95032, 7893, 14916, 3214, 26800,\n 24172, 121453, 34362, 10250, 17408, 18888, 4840, 68696, 22831, 13162, 36005, 32512, 14800, 62357, 41723, 45046,\n 27247, 37486, 5372, 2564, 34261, 298500, 66509, 133920, 89138, 31305, 117697, 19097, 108304, 81386, 84106, 23802,\n 46411, 63304, 946, 51417, 41777, 41041, 19501, 115864, 60743, 294354, 37955, 94165, 18116, 1156, 17937, 20645,\n 57114, 90804, 58042, 48643, 92288, 9861, 2557, 88546, 61333, 101008, 12853, 5148, 87856, 4152, 144503, 73841,\n 18718, 9789, 147565, 10846, 42085, 12789, 30223, 8993, 56352, 67203, 2448, 28215, 6052, 23540, 126319, 75933,\n 36689, 80235, 23231, 23561, 21383, 38800, 77548, 102798, 21234, 31468, 158608, 46188, 63960, 191679, 8051, 67014,\n 11185, 170078, 42186, 28827, 34777, 41930, 212079, 12421, 34750, 24111, 110344, 73918, 45171, 70826, 141949, 40063,\n 23979, 24254, 37309, 26724, 27179, 24718, 83648, 54938, 14591, 17425, 29525, 102675, 48975, 48654, 12316, 8929,\n 60640, 41709, 50168, 63264, 89812, 50716, 48632, 38755, 138583, 160123, 55579, 71829, 24230, 233277, 46322, 39650,\n 166388, 34718, 24108, 98252, 7031, 106695, 62498, 18258, 35062, 217827, 78731, 34824, 33354, 19520, 60852, 2432,\n 60224, 8587, 2836, 62955, 702, 20227, 42285, 40560, 95592, 62486, 11094, 53035, 143291, 18842, 46177, 77994,\n 1770, 9657, 107422, 172915, 32655, 128716, 25886, 25164, 156740, 119928, 165875, 85817, 11007, 89110, 33956, 12652,\n 65156, 180266, 8494, 36889, 19958, 20955, 96, 1264, 118288, 135769, 44754, 86671, 5632, 19026, 168220, 289120,\n 33569, 93821, 66144, 70635, 7687, 5642, 2714, 55445, 56636, 71545, 184182, 93133, 7332, 37389, 12643, 52315,\n 22729, 11014, 158742, 17050, 152889, 50178, 34601, 41945, 52136, 9948, 26914, 63548, 95721, 115951, 40759, 8960,\n 158258, 38938, 49232, 48325, 42234, 81523, 253019, 66128, 40978, 20048, 238048, 38760, 62928, 122560, 118532, 43687,\n 137472, 163689, 26680, 9878, 17448, 51035, 16211, 60834, 36749, 29178, 14241, 59868, 150086, 2305, 26477, 42422,\n 34342, 165341, 83279, 33894, 14257, 29928, 12743, 13957, 125571, 89134, 66712, 10952, 16507, 147839, 30146, 7249,\n 16565, 45399, 39874, 114565, 215780, 31990, 230881, 171477, 102, 196546, 44538, 10880, 84948, 281705, 86651, 10617,\n 31395, 2342, 453658, 43569, 60561, 132901, 21845, 17727, 58556, 258242, 22262, 58728, 4008, 77997, 11806, 37431,\n 30599, 81375, 109137, 185787, 114085, 217292, 97453, 169085, 30593, 60212, 11544, 102056, 65580, 2384, 91655, 4855,\n 95725, 7295, 157994, 16228, 20669, 53276, 141590, 105246, 17334, 25440, 76067, 17967, 39321, 38911, 11362, 28559,\n 63807, 21627, 26468, 85816, 40120, 1025, 15234, 58319, 69516, 66512, 124548, 75845, 78873, 22137, 46681, 51242,\n 85683, 32909, 76747, 35555, 43396, 101465, 1765, 73094, 1077, 2962, 39028, 66777, 57831, 42048, 15828, 13962,\n 36041, 63657, 52412, 5242, 58846, 2141, 5506, 219012, 134451, 3936, 182230, 17558, 17153, 152237, 22621, 49377,\n 170216, 35257, 68233, 65374, 6510, 11126, 212151, 7184, 2480, 22517, 3437, 33073, 30156, 16557, 3768, 55067,\n 86829, 91000, 12350, 148650, 66017, 79424, 70885, 49066, 28250, 21369, 51213, 34533, 11510, 3258, 18176, 18465,\n 84413, 6315, 36411, 163765, 4346, 356, 107618, 598, 13727, 285026, 162695, 8749, 14583, 7132, 63521, 184253,\n 32378, 25991, 5604, 30961, 53675, 4874, 84693, 5086, 34811, 26978, 56564, 7904, 33519, 51221, 113942, 69253,\n 6664, 125563, 22055, 220680, 102008, 742, 51930, 19494, 176108, 44424, 35123, 13025, 75685, 11759, 74335, 22250,\n 181453, 131147, 16984, 132115, 154311, 11991, 76452, 52609, 85351, 196, 30969, 9198, 74919, 2529, 56838, 71779,\n 29187, 116304, 3504, 62330, 41190, 86153, 28393, 254926, 104228, 105189, 13264, 84359, 3574, 12415, 8534, 57147,\n 10175, 188174, 59504, 60932, 66318, 16407, 107921, 17638, 99103, 49278, 28403, 39786, 145865, 8462, 3558, 43406,\n 142271, 29139, 21989, 36552, 93955, 72365, 7176, 13556, 106185, 37957, 321774, 17782, 129017, 51154, 27938, 24952,\n 1935, 39366, 2791, 33489, 41582, 56078, 24558, 9311, 5449, 218786, 27808, 190429, 68013, 36020, 86003, 29735,\n 3404, 87348, 119357, 115714, 2324, 86796, 81973, 40992, 43376, 93621, 28784, 16808, 36367, 2517, 2909, 191926,\n 24978, 55303, 53308, 205724, 60068, 3098, 21375, 64784, 23949, 26579, 63121, 12319, 80145, 39967, 97861, 6757,\n 70143, 67642, 37082, 34698, 69140, 122883, 46151, 62187, 80934, 429, 19437, 135071, 137885, 222647, 13331, 154065,\n 327, 61778, 74257, 40116, 37493, 14855, 85079, 237641, 42342, 102164, 199965, 71204, 4662, 29368, 5042, 113914,\n 122214, 8955, 13149, 102503, 43173, 5659, 163787, 69003, 307084, 63392, 171080, 21390, 81918, 86666, 36622, 24126,\n 28887, 5736, 28054, 207170, 163428, 79891, 346467, 95363, 38980, 111806, 80828, 9200, 19288, 294896, 114468, 87405,\n 111715, 141705, 7015, 72754, 68463, 48738, 243147, 33397, 101210, 37051, 98801, 82847, 20397, 4940, 185559, 18716,\n 54718, 83491, 11725, 40803, 1128, 12128, 23060, 5174, 7745, 67007, 46701, 1571, 27807, 180186, 256996, 18975,\n 16837, 7877, 212758, 250379, 15440, 87954, 57755, 24719, 124057, 83461, 258, 50864, 8874, 29038, 71289, 31627,\n 15429, 9005, 4061, 113851, 107716, 82819, 13651, 79656, 117851, 17539, 111446, 12938, 39724, 190787, 4352, 15402,\n 21070, 62708, 8539, 23777, 73853, 13552, 38810, 86117, 16285, 56400, 1718, 75342, 142863, 29033, 378, 110113,\n 180321, 32586, 23606, 26393, 160984, 207987, 23783, 8406, 16904, 24596, 47274, 11693, 46539, 60524, 78595, 48423,\n 31718, 20170, 9009, 146268, 15183, 191060, 172765, 1349, 138436, 37365, 10970, 40509, 225817, 20021, 70394, 152138,\n 21541, 66559, 66544, 89352, 2725, 17258, 91345, 7313, 3815, 115868, 8660, 40362, 4071, 103524, 39388, 118275,\n 21950, 6549, 38226, 32754, 209574, 29201, 43495, 18028, 20296, 40597, 18370, 47520, 202450, 24134, 2219, 8195,\n 69545, 38041, 136934, 46374, 19041, 159811, 84865, 58620, 846, 98749, 13569, 30714, 97246, 32186, 4479, 27355,\n 92973, 35214, 151491, 75963, 37631, 1561, 27200, 238083, 23182, 60756, 12291, 25766, 39355, 102333, 87362, 65741,\n 59906, 19538, 201575, 48772, 102938, 24438, 292580, 39964, 66366, 9004, 61379, 50548, 37622, 38732, 28379, 68180,\n 76622, 17488, 69849, 5963, 7219, 48143, 43413, 55358, 540, 58691, 29506, 19245, 52193, 48621, 5518, 13048,\n 118625, 44755, 191081, 42061, 89197, 2259, 60665, 66994, 71210, 51232, 3585, 142096, 55024, 7892, 8345, 58653,\n 463307, 65658, 64319, 137941, 136323, 53499, 12746, 43492, 6978, 95163, 29925, 60175, 5128, 7352, 41463, 184756,\n 121146, 20473, 18426, 4598, 5309, 54580, 14277, 121151, 10691, 56711, 43880, 63409, 76682, 11830, 172218, 264898,\n 32632, 66536, 81062, 31649, 25788, 92774, 60222, 11100, 63159, 9432, 224657, 25240, 53613, 152, 138620, 163829,\n 2397, 85345, 12501, 37507, 64932, 38575, 43522, 65789, 80198, 78796, 35226, 3851, 108891, 73311, 3060, 28391,\n 93671, 39663, 46142, 30982, 66041, 37281, 68157, 26553, 71872, 81142, 211527, 39747, 118119, 22695, 2859, 11066,\n 20232, 168911, 7933, 197005, 17066, 111071, 44434, 133994, 120798, 12766, 227798, 45756, 132852, 29917, 36076, 55352,\n 65281, 129800, 41958, 18944, 84678, 18580, 168093, 132621, 39997, 54092, 27740, 32354, 3770, 114118, 103242, 43918,\n 15899, 18574, 145944, 3190, 123469, 219903, 24169, 100571, 62403, 16776, 92779, 14535, 17168, 16475, 14304, 37231,\n 1712, 28218, 242754, 61688, 28980, 1318, 51359, 222657, 99200, 67989, 31772, 23932, 35351, 201251, 49041, 27306,\n 19128, 40135, 3986, 77333, 19649, 120683, 151927, 21081, 7076, 78375, 77501, 101599, 8011, 89585, 96715, 58179,\n 5378, 102138, 106793, 26051, 217276, 4197, 16297, 27014, 46721, 13322, 22806, 5278, 29629, 70632, 9647, 71519,\n 58818, 40603, 128530, 8903, 36770, 56900, 31483, 26935, 43845, 34265, 34920, 87658, 6114, 84767, 64250, 47318,\n 50720, 19264, 162514, 33357, 13117, 6705, 46696, 75032, 71054, 87004, 42035, 69138, 11903, 99854, 102328, 19611,\n 34525, 69312, 6431, 49842, 101600, 133178, 108751, 41829, 89939, 225664, 48916, 99556, 9195, 130387, 5960, 36857,\n 116724, 53518, 94002, 39077, 53996, 6945, 22261, 64291, 8314, 152785, 57588, 16522, 9091, 5048, 87671, 35441,\n 39509, 1945, 12423, 158923, 178413, 37549, 14095, 1475, 73188, 62878, 4819, 24012, 68534, 42606, 4010, 120809,\n 57497, 59564, 101758, 103718, 32701, 80116, 12345, 95834, 46918, 21468, 53213, 15665, 31200, 3867, 5140, 96013,\n 250744, 21016, 10069, 13968, 35449, 180829, 27683, 39704, 59956, 22893, 3115, 26293, 32785, 75934, 62445, 141162,\n 62720, 2018, 83638, 19949, 114012, 95006, 3330, 99829, 130935, 309272, 9565, 55874, 121727, 37017, 23586, 319858,\n 40970, 27602, 8625, 112329, 61060, 100088, 118525, 25922, 16232, 1907, 60671, 51583, 44553, 80993, 5262, 94679,\n 8676, 940, 20736, 11823, 3020, 16476, 12340, 152600, 97416, 3703, 25744, 66826, 16245, 16876, 46446, 84798,\n 74227, 176020, 45192, 61955, 75496, 23946, 23626, 40372, 26036, 6149, 11822, 30582, 16541, 41914, 82385, 232823,\n 40921, 80773, 14930, 3631, 7517, 39619, 4348, 36180, 126106, 138939, 62611, 1477, 113512, 47321, 25052, 14546,\n 118881, 29060, 23589, 128322, 36795, 18401, 137921, 104699, 267929, 36194, 172791, 18113, 4766, 188215, 30083, 332586,\n 94089, 5805, 77909, 22194, 68234, 154976, 43220, 40660, 70001, 184893, 138095, 11128, 103010, 22663, 5108, 212615,\n 8485, 5565, 49222, 54614, 26530, 42639, 16319, 55062, 152662, 105595, 21114, 22216, 10294, 68158, 10436, 86950,\n 7206, 62115, 3977, 3657, 59874, 456, 118617, 18156, 106663, 112229, 80992, 17442, 8217, 55551, 5133, 34344,\n 251927, 51153, 39364, 201321, 7816, 66803, 23057, 156724, 145664, 14276, 95705, 979, 2796, 6875, 13429, 212525,\n 50602, 26276, 28284, 3424, 19465, 52397, 46963, 31420, 51399, 206476, 92317, 48851, 637, 100820, 83349, 10317,\n 60227, 21972, 6908, 282439, 32857, 224767, 95629, 83882, 42106, 87338, 69757, 29840, 68709, 37665, 45244, 114577,\n 49188, 175943, 54009, 186746, 106158, 70168, 3358, 234002, 50555, 9221, 129338, 9562, 20118, 32923, 78479, 118280,\n 65752, 4977, 10474, 102174, 60947, 129006, 10570, 83451, 8598, 8078, 159367, 123785, 80438, 16742, 5905, 5281,\n 181513, 42402, 6977, 163136, 93179, 42191, 14968, 50421, 112401, 105440, 33456, 57347, 121611, 4221, 94954, 36517,\n 24046, 27796, 6255, 33394, 72990, 135408, 116627, 1233, 57874, 25654, 95419, 68156, 401399, 313338, 55208, 45573,\n 93124, 119251, 47200, 38196, 11909, 130667, 45391, 73904, 64964, 167846, 4137, 115606, 52036, 62214, 7969, 160925,\n 7187, 1132, 134835, 40309, 73195, 64494, 80472, 444841, 61111, 26500, 45323, 40743, 53625, 52797, 22659, 15631,\n 29739, 36706, 28841, 39147, 102836, 26794, 10536, 14845, 87305, 45874, 12241, 127587, 83833, 57183, 79722, 30844,\n 41304, 84655, 20825, 92500, 3722, 25655, 27811, 10157, 81634, 31362, 34088, 92487, 70123, 22190, 185100, 72658,\n 139035, 192523, 88241, 2078, 230490, 44528, 85638, 100198, 22088, 29982, 291233, 241062, 13865, 4445, 137791, 37835,\n 107218, 31726, 19718, 38234, 72528, 23046, 19177, 66695, 5109, 17251, 28077, 5617, 21554, 47839, 72425, 133825,\n 1486, 73065, 181275, 141508, 21768, 62971, 63082, 2512, 34200, 9904, 120309, 6392, 91243, 68416, 268253, 41199,\n 116757, 138551, 185526, 41246, 28986, 4093, 19057, 17295, 4148, 245766, 122360, 35356, 112075, 20301, 75441, 10998,\n 7977, 19769, 62922, 937, 63547, 100196, 26427, 157820, 20983, 236696, 22935, 8140, 90315, 156004, 47204, 140973,\n 7726, 45097, 52725, 22636, 23436, 257282, 105247, 522, 88389, 216031, 202204, 46812, 211666, 19693, 68828, 81691,\n 45925, 11256, 30292, 372, 5236, 167826, 88328, 232776, 151611, 5360, 82104, 18841, 80393, 25465, 18285, 20320,\n 72377, 31730, 33160, 45803, 38715, 27705, 37379, 24163, 18360, 103586, 4015, 32305, 269494, 91252, 20080, 36567,\n 54650, 7797, 57073, 12650, 31164, 42209, 6375, 261663, 105528, 81661, 106002, 2800, 5375, 17247, 43151, 4442,\n 15727, 194619, 100855, 144898, 62320, 78465, 39929, 16454, 1967, 28311, 61363, 17219, 9395, 8745, 121445, 76939,\n 80385, 162380, 22009, 54191, 44248, 16299, 122830, 48151, 74429, 78291, 64755, 14238, 44966, 2511, 17712, 67954,\n 93583, 829, 105899, 49935, 84750, 11591, 33185, 85447, 42717, 27409, 208542, 28965, 62052, 52525, 5597, 25694,\n 65594, 16343, 63224, 276188, 12475, 9331, 127507, 38522, 57287, 24128, 133161, 79723, 105548, 133695, 48917, 27558,\n 43278, 46520, 13778, 141954, 110785, 83366, 17715, 46317, 105763, 66298, 147013, 41086, 94180, 16478, 220447, 44611,\n 730, 19722, 78975, 117889, 125643, 26254, 16574, 18480, 65006, 15806, 38549, 246418, 46052, 36056, 8440, 34984,\n 30170, 3163, 59800, 4458, 115442, 4283, 41970, 33507, 104078, 1653, 22, 121158, 276486, 3655, 6338, 24048,\n 133421, 23641, 2161, 24422, 36006, 8086, 10675, 181474, 12307, 29514, 59143, 14729, 52509, 87128, 122470, 19446,\n 80852, 33314, 24573, 119864, 14237, 9652, 57779, 6612, 51851, 15284, 98871, 90581, 124466, 156831, 21190, 22015,\n 71380, 161906, 87247, 69201, 18392, 17908, 108470, 72962, 40719, 14338, 17911, 95260, 43339, 20610, 78916, 20710,\n 72451, 11315, 31448, 17263, 58853, 178878, 48111, 116002, 45497, 80506, 82605, 85880, 36300, 121755, 25215, 36118,\n 301929, 88728, 405223, 276136, 553, 34704, 212438, 49970, 78329, 922, 20711, 25036, 257130, 38295, 145369, 18128,\n 15385, 30829, 55656, 48345, 8012, 3561, 28004, 122041, 192900, 58338, 112508, 41085, 29976, 87040, 47117, 23905,\n 4336, 92061, 138880, 97407, 42083, 172121, 6256, 25192, 172671, 5, 93568, 1420, 12677, 31605, 56743, 40620,\n 6015, 78415, 231077, 31298, 80026, 13902, 19048, 24924, 170586, 32955, 176119, 87859, 36731, 6773, 27711, 24658,\n 26475, 115216, 133207, 93250, 95820, 88522, 8317, 5714, 124047, 55219, 86860, 19677, 23961, 22928, 162209, 8904,\n 225992, 359835, 56084, 96201, 29392, 96558, 86071, 93643, 55114, 13347, 8183, 95129, 82012, 2017, 123336, 34219,\n 115554, 157159, 47747, 101684, 41008, 18735, 193781, 104151, 226906, 7552, 179874, 124113, 31159, 21162, 44010, 14771,\n 51268, 166128, 31382, 73124, 77438, 92830, 205709, 12113, 1292, 38937, 13114, 1334, 2118, 15597, 69581, 14449,\n 21934, 76618, 48728, 67038, 14967, 51495, 24243, 87736, 147249, 26720, 11119, 46063, 43749, 5843, 44147, 152629,\n 133428, 65703, 14269, 45604, 57982, 28672, 55616, 45957, 8438, 95433, 37698, 220862, 132034, 39456, 61870, 4161,\n 26501, 73560, 56418, 9845, 4654, 20916, 10456, 88920, 119358, 9015, 65931, 96507, 48029, 38534, 21676, 109081,\n 43078, 34943, 25089, 6131, 28766, 23665, 5477, 10255, 16695, 67, 45778, 42443, 42770, 29534, 23733, 100513,\n 62617, 42630, 48746, 14191, 43753, 50295, 26007, 8792, 57243, 43119, 54725, 164253, 58250, 112304, 131796, 25165,\n 4651, 3188, 24831, 47748, 3705, 19540, 13211, 102095, 5593, 18699, 23666, 32005, 117571, 33541, 60584, 74573,\n 86311, 99443, 25172, 27222, 168938, 7143, 11853, 53560, 18834, 19960, 86522, 28217, 53266, 117700, 72989, 34323,\n 18721, 66450, 34346, 74056, 47217, 202002, 46269, 9429, 68582, 75458, 37823, 82843, 96652, 32549, 145144, 27958,\n 19820, 158086, 31955, 201406, 135379, 31207, 192545, 12950, 51704, 9094, 248263, 76147, 64028, 110009, 79407, 89345,\n 99284, 223492, 47966, 26848, 15359, 201137, 2861, 110507, 71231, 72297, 31851, 118777, 71039, 151051, 240855, 16333,\n 50766, 14727, 7939, 4149, 80908, 418780, 88378, 59276, 1327, 7284, 38576, 79814, 65820, 42199, 84860, 49574,\n 62596, 12396, 70598, 40117, 8648, 7994, 16836, 7630, 14047, 359699, 106878, 525, 29037, 28064, 13380, 11675,\n 50669, 74216, 103539, 180314, 27449, 56299, 172344, 19274, 7301, 246099, 32043, 19422, 36506, 129317, 6806, 30140,\n 4614, 46639, 66926, 932, 86600, 6322, 27847, 233103, 10541, 39025, 34887, 3517, 12972, 26220, 2031, 66561,\n 115015, 48658, 47596, 12714, 33845, 3893, 16165, 35237, 89983, 14769, 11962, 147224, 47018, 29977, 27979, 5552,\n 82338, 86023, 131368, 1218, 24853, 237840, 132193, 15455, 40873, 3668, 65351, 53388, 15229, 59889, 272245, 47934,\n 11858, 34347, 18038, 90853, 86981, 300602, 19343, 114181, 29362, 84921, 6095, 106059, 79472, 38015, 1206, 48741,\n 6208, 80000, 21916, 17423, 6002, 108083, 24479, 34931, 56661, 9511, 26995, 100694, 163853, 35997, 81254, 58321,\n 18919, 171890, 86877, 91341, 74503, 70477, 53412, 7027, 59281, 39892, 131302, 5864, 15947, 61301, 67466, 162369,\n 47956, 27874, 35624, 282324, 21270, 111847, 102548, 41482, 30955, 116737, 28264, 8592, 55458, 22301, 75090, 29821,\n 30697, 51709, 3041, 19208, 8038, 24634, 30467, 87509, 126428, 19389, 18814, 152686, 20701, 83474, 45832, 80891,\n 105808, 11378, 153223, 120770, 98186, 150633, 49838, 9141, 12755, 30962, 5260, 74490, 21256, 31678, 65062, 33326,\n 289838, 187831, 20595, 89768, 2805, 58535, 10844, 70085, 12090, 2451, 138068, 98544, 24461, 4511, 6754, 41684,\n 28203, 3383, 65355, 82833, 30161, 83924, 234361, 128424, 28921, 222594, 33975, 125491, 34069, 11508, 67464, 144226,\n 41850, 98703, 34371, 7901, 21254, 38398, 65651, 23549, 53883, 213340, 123269, 12028, 71764, 177701, 28758, 2623,\n 68395, 11549, 15232, 68603, 9660, 63116, 36079, 57093, 31198, 20475, 48467, 89984, 35619, 186847, 107469, 31389,\n 43631, 73867, 41949, 68841, 114250, 1605, 30564, 63403, 17588, 27680, 99533, 12641, 70325, 50428, 73426, 78379,\n 11855, 91651, 72081, 91720, 60198, 15743, 12065, 83398, 140046, 6761, 46598, 45900, 5068, 886, 62448, 148968,\n 37347, 19405, 9680, 15819, 43496, 63370, 75667, 163700, 37639, 3633, 22774, 34341, 183131, 134335, 37200, 23915,\n 7054, 14194, 12970, 26438, 13350, 285521, 25594, 8219, 104410, 91039, 168804, 138480, 149734, 15907, 33818, 61132,\n 60082, 4622, 110187, 56736, 13551, 73571, 3945, 73463, 65498, 17758, 263266, 17593, 2710, 27585, 54469, 38200,\n 45367, 63754, 28881, 3473, 12791, 98287, 31895, 65787, 4463, 94536, 24951, 36332, 59901, 28803, 52130, 86403,\n 7668, 181822, 74831, 18977, 9850, 177206, 145485, 109798, 7292, 31421, 26280, 77211, 58511, 12507, 127004, 11113,\n 147, 8729, 56208, 43066, 79926, 129937, 31345, 83947, 39915, 46146, 98763, 42566, 1337, 13192, 18323, 105163,\n 80570, 117753, 16555, 72883, 11077, 159438, 40764, 70933, 83329, 26066, 12276, 72059, 21655, 173836, 126713, 69454,\n 153482, 91585, 70644, 102558, 110483, 6764, 127864, 190133, 3961, 101798, 20945, 71138, 82402, 90884, 69669, 44753,\n 923, 16939, 59700, 164258, 25969, 27082, 31399, 43846, 6306, 246093, 51342, 6153, 151581, 202801, 182731, 56475,\n 162188, 89426, 141356, 14355, 121815, 27536, 28023, 65257, 77523, 106668, 127314, 24947, 12790, 38796, 169698, 23555,\n 10725, 44573, 183083, 42088, 62716, 43265, 105958, 32050, 44067, 50118, 1668, 3874, 6243, 318411, 16599, 1691,\n 94999, 52378, 28671, 216728, 123258, 2059, 34969, 69225, 5913, 136280, 171443, 141515, 91662, 22175, 135282, 80020,\n 92270, 1663, 4808, 4482, 3495, 34691, 5226, 109830, 108512, 17342, 107488, 11606, 123190, 100247, 29666, 146527,\n 113014, 15794, 30894, 13224, 39585, 243192, 22351, 9903, 7836, 47699, 11078, 25468, 122291, 48821, 26780, 122679,\n 75521, 81450, 630, 4895, 92900, 55074, 74293, 17441, 3563, 111657, 103102, 51613, 12318, 52370, 36191, 68245,\n 34269, 40445, 41354, 122901, 168604, 182500, 62012, 42557, 11259, 24428, 115113, 86345, 12362, 3909, 78430, 86852,\n 134602, 20459, 47853, 93879, 22577, 7659, 3688, 38555, 13349, 17381, 56715, 91639, 12493, 10895, 92438, 3142,\n 37057, 28928, 2004, 36427, 32268, 34222, 209974, 10432, 67436, 41989, 173518, 107930, 27079, 62729, 30908, 55558,\n 5828, 45031, 14902, 53546, 8204, 144263, 60255, 14520, 88212, 86582, 109589, 69356, 8064, 47449, 8505, 66558,\n 16886, 4844, 52817, 111260, 215129, 12941, 91118, 650, 20770, 6273, 73089, 40618, 62790, 2873, 35002, 14023,\n 97208, 19386, 102646, 36993, 143736, 135457, 35385, 113601, 17893, 32627, 84439, 100619, 56016, 6581, 57264, 172160,\n 45452, 111710, 203627, 70131, 24100, 322787, 1996, 35665, 70078, 22358, 90922, 83658, 4097, 63200, 58499, 14542,\n 99153, 52159, 6615, 12414, 63415, 31986, 16823, 1579, 65405, 137809, 8841, 16898, 48082, 259, 33014, 42375,\n 12260, 179850, 73667, 91389, 98882, 29532, 17311, 326251, 41092, 5928, 20742, 44964, 48019, 43505, 9317, 49265,\n 6643, 192712, 48424, 163487, 19861, 20113, 70848, 31928, 105333, 23685, 78563, 14638, 54755, 7158, 24142, 44018,\n 20774, 125255, 20331, 24280, 10163, 1285, 2336, 39851, 4299, 117269, 46714, 63816, 87779, 159624, 11731, 9971,\n 990, 137317, 108831, 50994, 74554, 162680, 23640, 131597, 146962, 170620, 34829, 91205, 21184, 1913, 63616, 18427,\n 93136, 156592, 17519, 67565, 115882, 138220, 78622, 88535, 18115, 2711, 33554, 109492, 54298, 971, 24914, 25863,\n 36363, 45715, 27099, 194995, 14299, 178181, 111488, 72395, 322385, 157719, 130787, 11897, 81843, 83999, 11369, 49280,\n 118604, 40922, 61332, 110343, 53407, 75639, 40582, 300440, 54722, 25637, 13694, 48248, 48278, 194521, 56203, 52779,\n 48783, 72627, 10953, 376, 16733, 280238, 26351, 230789, 15132, 25168, 137270, 3588, 63704, 73376, 94031, 74284,\n 19443, 159557, 9697, 39901, 13351, 119050, 15406, 146455, 3460, 29556, 75195, 37673, 102524, 92329, 47289, 98413,\n 15311, 100684, 56345, 7116, 95480, 11590, 7200, 167, 23610, 58426, 17730, 136656, 27944, 53151, 2701, 8824,\n 103124, 3017, 90744, 113588, 53216, 79736, 65940, 26931, 498, 29568, 80540, 143543, 21292, 1740, 59268, 16561,\n 180816, 42323, 50174, 40890, 52866, 10703, 57169, 4700, 17191, 4424, 93511, 49698, 166650, 26972, 48631, 165169,\n 82879, 69326, 202970, 4007, 2376, 231325, 139592, 22119, 62851, 37504, 68816, 58345, 67398, 186643, 43331, 277416,\n 53749, 15746, 23102, 17432, 4793, 151138, 48822, 54265, 48203, 198688, 14305, 54287, 2291, 18018, 113378, 123260,\n 7180, 97549, 87027, 120085, 2920, 76080, 8190, 102005, 5641, 64580, 14955, 59802, 54028, 58884, 19367, 81779,\n 412567, 85957, 97053, 103637, 78871, 29364, 27637, 141728, 4767, 30686, 112738, 130146, 42745, 12730, 105040, 14844,\n 232, 210944, 36581, 152317, 135543, 29744, 3129, 55647, 58149, 46319, 27265, 17499, 28005, 59948, 7170, 34138,\n 5702, 293047, 110892, 408, 91760, 218674, 18469, 46095, 81403, 14389, 4610, 35672, 73060, 11006, 74848, 104820,\n 118143, 190357, 20043, 105358, 141735, 5115, 27093, 45924, 123073, 52599, 29433, 9616, 238350, 78610, 24851, 58858,\n 26769, 31969, 24613, 18294, 4982, 32735, 39639, 143563, 112073, 202205, 12567, 4873, 88601, 44897, 81503, 101648,\n 81362, 34662, 85277, 17574, 48173, 21435, 221188, 40215, 39576, 80786, 26544, 64668, 81841, 10731, 37733, 247986,\n 149188, 127703, 495, 18382, 54388, 72446, 43071, 30974, 198723, 89608, 41360, 190, 33045, 8386, 31658, 19992,\n 237838, 119015, 137622, 50890, 100913, 6460, 116233, 267230, 26621, 104129, 65114, 14190, 41542, 14888, 85962, 23342,\n 23041, 26453, 43725, 71809, 45186, 4770, 46452, 53894, 56616, 221286, 18973, 9038, 109299, 55365, 19366, 26863,\n 18808, 60909, 69353, 41738, 83463, 12100, 68561, 72860, 3980, 13796, 49340, 12332, 31311, 27418, 4255, 53430,\n 18976, 45523, 510, 14224, 30477, 26581, 4530, 3651, 101663, 139840, 22709, 150861, 31996, 63923, 120623, 262522,\n 3076, 10528, 2929, 14672, 130238, 18087, 9816, 121894, 100308, 25085, 55111, 14565, 18952, 53293, 2042, 369988,\n 23674, 61789, 133529, 28783, 108293, 35477, 47119, 36448, 71049, 40015, 33055, 78598, 198442, 1833, 159937, 40654,\n 77444, 189245, 113153, 8621, 18599, 38553, 35223, 166072, 2375, 11659, 21786, 89523, 6032, 12116, 63046, 159398,\n 18454, 3678, 32521, 47626, 11411, 103527, 38896, 42946, 15696, 26370, 10185, 8413, 37080, 165583, 4331, 63555,\n 14907, 72220, 50056, 6623, 62236, 36565, 49783, 10049, 17503, 100581, 55951, 146244, 24724, 9626, 17969, 25524,\n 109300, 173965, 99994, 101056, 46459, 43647, 53737, 277968, 8347, 123521, 74858, 33829, 44762, 77574, 877, 81377,\n 222525, 123532, 30602, 43881, 53145, 2973, 16284, 81940, 61281, 127044, 63620, 9875, 14756, 114829, 19032, 9202,\n 52759, 119141, 23928, 120551, 19607, 3599, 33401, 76821, 73233, 117430, 39968, 36539, 7071, 5446, 121735, 194059,\n 15206, 45283, 6706, 15603, 65615, 1207, 165723, 92275, 34773, 104447, 8396, 32353, 205240, 164323, 13600, 60555,\n 79205, 25532, 22907, 33410, 57480, 107111, 69630, 32137, 47832, 70913, 33161, 20321, 2371, 117348, 10714, 86246,\n 1625, 11763, 17900, 268, 78457, 99175, 97940, 101092, 86660, 32221, 14041, 128504, 125080, 53744, 124263, 31017,\n 13897, 403, 31859, 21964, 5633, 111630, 5547, 77329, 17961, 18241, 84995, 25984, 12983, 67491, 62168, 47262,\n 5241, 297, 51191, 7351, 8967, 147212, 82060, 16821, 782, 11033, 82431, 62957, 5026, 43459, 77963, 203477,\n 53528, 6247, 191852, 87774, 74164, 215654, 13467, 1522, 219964, 28589, 244104, 16242, 117821, 67725, 72570, 156792,\n 17186, 15979, 26990, 44128, 193014, 35276, 57125, 16212, 166451, 68017, 6905, 77608, 16364, 53777, 75921, 76426,\n 37975, 26203, 269296, 64099, 84122, 12077, 38533, 830, 4407, 20139, 963, 43028, 38902, 42911, 37503, 83343,\n 85045, 16979, 1165, 60835, 137387, 58380, 86990, 110066, 134540, 56331, 193845, 81238, 17922, 163093, 38744, 110641,\n 12502, 56404, 34862, 26865, 125964, 12965, 111648, 25547, 7771, 27196, 136980, 9555, 29551, 107158, 57885, 18831,\n 37705, 35505, 101742, 13970, 102109, 62548, 124657, 23328, 11124, 89592, 146376, 248050, 6241, 22033, 18337, 80685,\n 29898, 11908, 216623, 67721, 106162, 146610, 21377, 15085, 91552, 42041, 62560, 122532, 125336, 102365, 121537, 142559,\n 29693, 223919, 11515, 110495, 18776, 22494, 5895, 185059, 103592, 229351, 51220, 100102, 37027, 257855, 29359, 54123,\n 36066, 106493, 12244, 79258, 32002, 432, 56205, 94836, 90182, 6726, 14762, 29391, 48938, 26864, 38083, 60364,\n 3310, 60192, 14766, 205567, 57504, 110760, 22649, 24666, 46333, 21517, 3430, 13135, 28873, 27052, 158809, 11597,\n 20529, 6695, 23138, 22960, 37137, 45574, 6545, 305877, 43423, 26153, 24769, 59844, 14501, 10430, 134352, 56169,\n 13213, 103432, 49523, 35181, 13435, 12408, 129475, 64620, 230854, 77390, 51990, 15653, 83248, 33466, 44571, 117828,\n 51481, 2187, 10559, 68019, 18021, 54895, 48247, 18354, 33737, 4554, 108595, 37288, 39767, 116707, 9175, 3726,\n 108877, 21616, 83684, 49862, 1938, 8543, 276466, 20134, 108498, 48770, 102254, 31914, 131520, 185291, 100559, 51890,\n 209, 19526, 76471, 50544, 71814, 99351, 8172, 198526, 28816, 20419, 9109, 98389, 136777, 76479, 75596, 30635,\n 165417, 48216, 120220, 25955, 211071, 39314, 24308, 32164, 2559, 146280, 43403, 9233, 17947, 90585, 1786, 86920,\n 125662, 2457, 64741, 32152, 32918, 122882, 78538, 44001, 31723, 56426, 23375, 103172, 88177, 145697, 52506, 49319,\n 68016, 31664, 41488, 18486, 110400, 7030, 28241, 986, 109199, 19900, 42147, 56864, 65287, 49183, 7858, 24000,\n 30453, 840, 16673, 25907, 68916, 89927, 6309, 158335, 36407, 199737, 130464, 13137, 59603, 201778, 195292, 21015,\n 42466, 179062, 172561, 89492, 11075, 180407, 31868, 72493, 20998, 60217, 9865, 19530, 39274, 130266, 54539, 21623,\n 12535, 13505, 40641, 73375, 4087, 85633, 2153, 3117, 70680, 55788, 92096, 47509, 98493, 37490, 271936, 151475,\n 3032, 16171, 96642, 34106, 78425, 125761, 19591, 3366, 19316, 54508, 24183, 50786, 194248, 91528, 33253, 34622,\n 108355, 41741, 705, 3814, 3883, 108929, 13203, 67831, 10142, 59754, 68208, 29128, 84820, 56880, 38794, 24972,\n 48571, 40821, 40476, 18137, 164254, 24064, 236309, 79181, 11282, 395, 39169, 2013, 51587, 28551, 9645, 701,\n 109513, 115899, 113566, 12762, 62045, 58322, 103726, 41343, 40866, 244102, 143816, 2490, 70346, 40973, 52618, 15412,\n 30720, 104315, 38917, 42027, 93676, 17513, 107418, 20706, 123890, 13399, 97727, 24044, 87962, 65606, 44250, 98044,\n 65276, 74790, 101473, 19350, 91570, 1326, 87790, 172042, 7577, 100813, 86896, 85891, 41512, 108130, 27794, 14875,\n 71431, 12835, 156250, 58135, 3759, 22476, 42176, 115873, 34686, 56523, 73643, 108505, 51491, 20838, 12721, 32863,\n 45700, 29496, 13700, 34294, 55360, 29206, 155942, 123812, 7706, 163234, 203, 132720, 49358, 144431, 8130, 175788,\n 35818, 3270, 76832, 25710, 54095, 97274, 28779, 94621, 74396, 19092, 128242, 58067, 20885, 14670, 93255, 15107,\n 63291, 23654, 126900, 129421, 59294, 262659, 9798, 3251, 67344, 28600, 44629, 50672, 29072, 26999, 31526, 23183,\n 49175, 165843, 175455, 17282, 175411, 32022, 45989, 30298, 90690, 78118, 83156, 23749, 35636, 31317, 7069, 80381,\n 94561, 133756, 14960, 97404, 6138, 41065, 78041, 32843, 16601, 34123, 9559, 146529, 123377, 96395, 54441, 42012,\n 84257, 123541, 10745, 22139, 106459, 11720, 150883, 172651, 154996, 110538, 4728, 53447, 25704, 2009, 71152, 119354,\n 21166, 66604, 1429, 216162, 8637, 122250, 63520, 27180, 29172, 36124, 276428, 107787, 77184, 4680, 14952, 104903,\n 24418, 14793, 51561, 52931, 8371, 26342, 48526, 7118, 92066, 67280, 40653, 8847, 34597, 105438, 14198, 50163,\n 61188, 146286, 50315, 41205, 170829, 161496, 585, 197359, 95056, 1687, 365794, 91349, 48507, 5804, 49263, 5146,\n 104902, 96365, 117343, 132222, 46084, 96919, 16875, 8073, 262381, 79982, 52663, 13928, 16056, 153908, 15145, 109256,\n 132308, 18763, 24904, 167644, 13618, 40750, 18686, 147124, 114709, 150038, 52849, 2938, 12568, 48617, 8778, 5459,\n 44202, 44591, 74914, 17183, 248689, 13878, 7822, 80060, 23116, 194037, 18487, 2067, 7798, 43077, 33678, 244028,\n 31320, 74273, 2794, 19466, 8218, 36280, 183997, 48124, 19416, 29656, 19280, 98734, 7715, 18311, 30701, 133602,\n 150307, 126956, 7378, 2933, 79903, 13178, 12593, 86571, 26604, 92446, 13574, 44205, 65699, 427599, 21118, 8245,\n 14407, 27877, 47936, 33542, 7916, 26460, 117762, 21596, 37818, 2249, 127359, 209394, 60044, 47677, 308089, 36791,\n 154971, 31417, 6998, 150042, 174360, 12255, 43009, 29335, 48739, 3912, 101398, 53340, 2580, 146939, 151295, 45360,\n 125275, 15273, 45383, 27456, 48761, 23314, 8750, 60801, 85823, 104759, 27894, 123685, 66968, 39480, 26917, 55290,\n 83305, 2696, 98390, 57569, 145853, 340733, 4919, 20024, 52268, 30884, 7413, 203685, 70989, 112855, 4129, 50536,\n 349518, 68205, 332641, 159581, 135361, 236026, 37563, 176404, 64899, 6578, 122033, 63871, 1850, 85234, 82089, 66124,\n 74145, 121098, 107351, 12687, 36881, 117334, 13136, 14698, 85933, 93866, 18047, 32620, 310, 15094, 46000, 88451,\n 23632, 36645, 27940, 87618, 80520, 58892, 20976, 27702, 140090, 96075, 67841, 103292, 238964, 87778, 107338, 17019,\n 83427, 67522, 7302, 8261, 47570, 116787, 8730, 80484, 61772, 174422, 56005, 131193, 52875, 14588, 28471, 59817,\n 9586, 15720, 158155, 51307, 109734, 15196, 11025, 59331, 3884, 52626, 102602, 84797, 25158, 27314, 4437, 20488,\n 76214, 189248, 35023, 114952, 157376, 2827, 62439, 102878, 129749, 36405, 10329, 109339, 108633, 36662, 1254, 13267,\n 5470, 87105, 58004, 15397, 10434, 159667, 21864, 52022, 179464, 3013, 32147, 31496, 116832, 18494, 105502, 129227,\n 107267, 50033, 13481, 9954, 24267, 22141, 16257, 116154, 36185, 950, 115685, 11305, 176708, 2048, 178671, 112573,\n 287867, 162328, 497663, 95170, 50979, 193861, 50987, 30368, 136257, 31830, 46549, 15119, 169876, 23788, 17462, 249887,\n 57377, 1949, 35448, 14791, 43769, 210091, 3783, 34612, 282103, 88380, 245190, 5457, 20491, 98908, 11402, 86899,\n 117916, 16028, 162584, 60644, 320177, 156096, 31065, 55876, 22000, 77655, 9992, 23397, 13757, 317623, 63978, 215255,\n 2443, 17648, 93231, 27388, 104529, 93807, 55505, 140477, 12046, 112040, 70887, 40152, 94365, 112353, 25063, 114679,\n 266061, 71248, 119555, 15589, 2244, 617, 14129, 211431, 70110, 100652, 7777, 4383, 85911, 89221, 21010, 120615,\n 58357, 86405, 37554, 41647, 18, 15143, 69662, 60491, 14714, 186134, 148344, 42347, 5410, 168175, 44535, 42449,\n 343894, 129417, 99682, 20659, 27272, 140483, 63455, 222159, 17536, 13722, 42637, 62324, 11976, 114691, 148109, 2283,\n 32057, 182393, 4295, 147364, 33705, 2075, 44303, 30274, 28331, 63740, 69740, 29148, 10346, 44862, 33716, 73937,\n 153333, 12930, 38784, 247159, 2515, 41053, 20256, 83368, 256189, 54639, 115240, 5096, 24661, 175419, 153552, 26516,\n 141, 138176, 63885, 34115, 47222, 55709, 2765, 28479, 38875, 236608, 12229, 22921, 77291, 54426, 45388, 2860,\n 57787, 114579, 295139, 105782, 17826, 71066, 19119, 54364, 69385, 16568, 12323, 28057, 33346, 34919, 124763, 155533,\n 101386, 31644, 8627, 49001, 303600, 29868, 63213, 9103, 77280, 71333, 9696, 138789, 37059, 24823, 5057, 21352,\n 32368, 114208, 56803, 19424, 10445, 58514, 8661, 209508, 26187, 171838, 10460, 63454, 14016, 122504, 41328, 21329,\n 46618, 32493, 38225, 7855, 31763, 7945, 29876, 8734, 6438, 24205, 97490, 139977, 130740, 47323, 33195, 85390,\n 57194, 13813, 60600, 21313, 96251, 7699, 27584, 170521, 139271, 1363, 4402, 336738, 129223, 84983, 69150, 13147,\n 3590, 163929, 207225, 155260, 55916, 20288, 4503, 8398, 98490, 11773, 27512, 37113, 84976, 86558, 28365, 11756,\n 116005, 182148, 13733, 115313, 47644, 67208, 85069, 9347, 14995, 226141, 14704, 101835, 41159, 35314, 13113, 63526,\n 214039, 29978, 50446, 83339, 17440, 129441, 72522, 118641, 97816, 24907, 73844, 15717, 118884, 167255, 96509, 162793,\n 30847, 36849, 51297, 78974, 77793, 10427, 1873, 2972, 9999, 35074, 28190, 64297, 146836, 46298, 60038, 163007,\n 108919, 61219, 2403, 75022, 127339, 4233, 110389, 69022, 9833, 128097, 88016, 79390, 222936, 22570, 94657, 28462,\n 56956, 38803, 81536, 30474, 152794, 19566, 16481, 147408, 74574, 81895, 20731, 1918, 1366, 76367, 187321, 54494,\n 24366, 21690, 61696, 33283, 107477, 77499, 31112, 414383, 74362, 18463, 218441, 120929, 59848, 258629, 201924, 69269,\n 454, 19989, 13054, 59894, 3623, 58908, 20681, 35723, 78523, 102680, 38988, 184112, 108087, 50944, 132704, 52966,\n 21699, 18860, 96349, 201411, 82697, 85395, 95658, 5093, 6427, 177894, 44191, 32755, 26961, 155739, 6249, 31310,\n 81030, 26574, 84311, 120155, 86730, 113535, 7424, 48888, 13516, 45747, 98098, 20077, 183995, 81945, 43210, 26704,\n 40420, 75831, 45648, 11180, 6855, 57927, 65528, 124096, 34851, 2598, 156633, 107572, 127352, 38169, 123845, 60142,\n 62722, 105584, 232364, 23211, 68120, 1601, 22169, 89299, 747, 258039, 80572, 7258, 152249, 11862, 101204, 8834,\n 121434, 33761, 19175, 133142, 46343, 40178, 48723, 3589, 41977, 30210, 38868, 62257, 10087, 82658, 87827, 90646,\n 16415, 47552, 351723, 28298, 72225, 91146, 272760, 1701, 11295, 1652, 109651, 300747, 51863, 198800, 29446, 11794,\n 32345, 37538, 22356, 33102, 37590, 113544, 37970, 11478, 179743, 25454, 103417, 59905, 221970, 105196, 145604, 7817,\n 164809, 102360, 16974, 75840, 255333, 56902, 6659, 1954, 645, 59400, 67769, 7689, 18675, 5215, 13793, 20536,\n 27852, 3387, 29523, 259718, 16860, 94625, 43143, 29245, 15848, 233581, 22685, 63631, 78557, 22836, 133302, 84513,\n 1348, 51826, 47129, 98836, 58284, 1830, 1749, 94642, 10933, 6145, 12506, 10975, 13879, 103781, 144434, 10268,\n 28409, 32346, 52968, 121567, 107374, 77268, 23686, 35097, 10501, 155275, 15303, 47136, 21102, 168741, 55332, 90385,\n 15996, 84817, 681, 137803, 25054, 142275, 6163, 38175, 8056, 124296, 240642, 65621, 4934, 178205, 16101, 62803,\n 60964, 18230, 100622, 76465, 44689, 14545, 9543, 47514, 16852, 93380, 28048, 12047, 107106, 37575, 101485, 77047,\n 57326, 34819, 96137, 76916, 6469, 46264, 115983, 75768, 87668, 69942, 13027, 165, 8373, 114231, 26434, 52844,\n 42799, 182044, 23580, 146254, 38081, 43236, 33883, 146220, 382894, 14606, 46035, 36481, 166621, 35417, 95382, 2957,\n 59384, 60428, 36358, 66343, 75378, 22267, 22950, 83528, 17577, 56474, 25285, 4619, 179691, 75355, 95836, 53295,\n 34588, 171410, 4487, 14679, 84208, 44015, 18562, 109133, 54101, 11531, 86052, 174479, 303157, 28095, 9953, 35642,\n 14564, 39802, 16145, 77606, 117406, 53038, 121117, 53624, 22062, 1212, 7632, 127157, 237292, 189087, 10478, 127345,\n 102515, 181997, 86752, 87623, 10966, 121602, 68783, 68681, 83042, 114380, 138349, 191305, 67176, 50085, 39016, 1427,\n 42384, 1412, 67118, 122616, 72389, 25260, 2237, 13576, 137346, 19938, 20304, 2191, 68759, 5373, 61364, 238507,\n 75814, 23931, 69565, 38993, 131741, 38364, 12528, 87762, 5679, 129853, 5310, 186831, 32653, 90338, 260176, 389531,\n 108118, 26843, 43985, 50175, 30563, 25106, 56965, 18130, 140428, 4542, 165503, 117991, 24219, 229605, 1819, 129663,\n 1240, 3797, 76093, 18398, 71339, 51919, 93043, 27175, 47060, 216257, 6483, 35051, 1217, 16512, 80798, 129064,\n 13225, 69339, 8548, 237079, 72298, 2575, 34280, 51379, 117910, 55671, 53345, 247552, 29486, 39328, 140821, 34681,\n 57045, 60177, 5004, 90269, 78522, 2479, 322607, 48474, 61296, 13057, 31558, 4678, 59271, 6699, 27044, 31988,\n 35944, 12503, 83480, 4389, 136508, 3781, 114121, 70279, 4488, 155829, 42214, 2898, 68191, 75695, 305850, 45041,\n 74344, 106509, 30087, 17429, 93292, 12477, 290, 23080, 114802, 35714, 18751, 26554, 105424, 17775, 2144, 2412,\n 100610, 65192, 113975, 52975, 180272, 135050, 129815, 76238, 106483, 21440, 63186, 4260, 46189, 9711, 28249, 4169,\n 23429, 23390, 8324, 141585, 63809, 67668, 38457, 38063, 39226, 59972, 1189, 203916, 62368, 14403, 16949, 61767,\n 85801, 1739, 40147, 35049, 76757, 33124, 62102, 15780, 103593, 103009, 53484, 22952, 67973, 114645, 6566, 5245,\n 50462, 7601, 8288, 3513, 194571, 80276, 1908, 54592, 5124, 58571, 2513, 6800, 273997, 193904, 1119, 17991,\n 117245, 2508, 129156, 82366, 26278, 71465, 63341, 56943, 39662, 106116, 94966, 156875, 9736, 2204, 122308, 94418,\n 27134, 1280, 24539, 49022, 45314, 3764, 50904, 46424, 30699, 28087, 293839, 9400, 33646, 40165, 822, 147499,\n 50263, 116179, 29085, 11863, 31314, 5578, 17797, 5104, 12454, 1604, 15342, 219206, 10232, 67800, 94261, 25872,\n 13565, 90339, 78971, 75377, 26649, 41184, 47695, 11514, 35369, 20767, 14227, 41953, 309396, 148270, 147938, 33074,\n 14453, 27499, 109019, 39018, 25738, 240196, 158931, 52820, 8612, 95853, 21524, 137010, 84901, 70869, 70021, 116794,\n 48404, 38771, 6732, 1070, 70990, 187297, 49140, 5238, 576, 3564, 253975, 16027, 16483, 2811, 37775, 19034,\n 25259, 4053, 2000, 70083, 95774, 19713, 33431, 92703, 91314, 42381, 288770, 48194, 95985, 3991, 77418, 13406,\n 241328, 245086, 56533, 35275, 62725, 9246, 51924, 70181, 95331, 16163, 31410, 79016, 39312, 120878, 119371, 275987,\n 80124, 27712, 9186, 220, 23598, 146167, 85209, 68238, 282190, 57048, 31273, 30555, 80913, 17594, 75779, 59160,\n 135002, 101219, 189377, 29225, 96735, 60126, 62522, 104000, 27620, 86814, 17240, 147533, 11001, 5425, 43682, 410,\n 49460, 87270, 69480, 46315, 59448, 1816, 76201, 9431, 11788, 87960, 29063, 65539, 47347, 11678, 33846, 7008,\n 196704, 9895, 6753, 8633, 120892, 59970, 572824, 115934, 6646, 202559, 892, 48351, 37611, 251282, 57823, 67263,\n 57750, 26527, 34485, 90747, 7685, 88370, 6144, 64182, 1709, 41969, 21458, 62327, 181657, 49247, 225330, 122600,\n 114574, 107124, 85361, 111833, 63243, 71420, 15655, 191178, 72430, 18063, 51425, 54002, 12364, 53225, 86557, 18193,\n 97580, 41232, 138398, 67821, 128724, 8944, 233212, 101353, 52099, 42127, 14006, 120107, 32789, 32132, 3498, 18123,\n 33758, 56058, 5779, 128760, 59888, 98869, 18445, 84702, 51911, 13234, 218379, 20093, 39031, 8074, 70195, 20708,\n 23462, 24355, 131384, 60189, 26390, 10403, 41060, 7140, 10781, 49410, 42261, 87202, 82566, 41663, 43105, 60276,\n 2768, 5733, 74176, 28329, 2297, 145430, 131632, 83615, 122915, 105441, 655, 224102, 5284, 136426, 67763, 16294,\n 188511, 32538, 61049, 27893, 3394, 13951, 159099, 28542, 17930, 145360, 9492, 190122, 32285, 78855, 26440, 13570,\n 58648, 73908, 4239, 124561, 2444, 74172, 53131, 11468, 10794, 73566, 11623, 35343, 64710, 30481, 4163, 10328,\n 38309, 29901, 10538, 154377, 76132, 92405, 24839, 11679, 3465, 13449, 11637, 7824, 2337, 57754, 1260, 14458,\n 41118, 19878, 38661, 13416, 159180, 37074, 163164, 54137, 28627, 52134, 184900, 8520, 40385, 29546, 30502, 22386,\n 66527, 107458, 6850, 24022, 47983, 30603, 35083, 8934, 304066, 39500, 9, 28261, 33026, 77251, 9374, 44833,\n 116312, 34990, 29236, 63563, 125639, 135405, 165398, 159055, 55690, 88141, 69643, 236964, 31983, 25572, 20436, 36746,\n 60896, 31850, 16179, 11828, 5888, 3043, 66368, 9750, 31167, 7915, 53111, 36430, 1333, 64344, 93659, 20061,\n 60596, 180191, 51630, 6792, 30244, 43509, 101058, 22409, 420, 44210, 109783, 43223, 27030, 72477, 72831, 32679,\n 29235, 7675, 47556, 12258, 39907, 149412, 84926, 118247, 24692, 71717, 105038, 86009, 45941, 41189, 89453, 29856,\n 52543, 30627, 226798, 67303, 59230, 67415, 34408, 1367, 99685, 16867, 128419, 52147, 4111, 125381, 117881, 16173,\n 44093, 102224, 31575, 23234, 24870, 83790, 127407, 239098, 3200, 994, 1255, 100903, 242275, 117266, 55116, 38205,\n 16140, 29662, 11307, 40414, 208793, 123355, 56470, 4862, 75600, 30119, 58218, 70828, 24075, 26974, 7802, 192353,\n 4851, 5475, 78720, 66596, 3409, 28573, 64396, 30381, 30690, 59859, 88256, 5406, 99945, 103064, 34463, 37727,\n 24238, 86643, 60088, 4057, 23741, 5967, 162904, 38240, 28356, 93858, 25510, 122879, 6897, 3278, 7057, 11971,\n 4400, 35461, 211413, 21395, 59615, 39471, 87233, 55795, 128426, 3051, 22470, 41950, 14705, 3974, 180108, 80476,\n 78442, 204996, 91987, 15634, 67610, 139015, 142373, 35611, 51134, 10387, 4353, 153456, 57749, 181039, 14183, 68447,\n 151532, 21107, 36452, 20551, 3186, 46247, 46383, 129666, 88736, 140662, 146243, 2066, 8360, 7978, 64818, 106963,\n 17896, 47801, 10723, 114821, 223295, 74192, 3293, 3393, 16987, 74064, 11277, 91622, 4270, 29828, 27951, 387869,\n 103235, 1374, 61988, 120083, 477, 145892, 128378, 11779, 211263, 61354, 18221, 17869, 46530, 83061, 108538, 157981,\n 90608, 67199, 95080, 49064, 195814, 12302, 66307, 10348, 231346, 160732, 112859, 63633, 146558, 21271, 31037, 198802,\n 47622, 12862, 95710, 3910, 77850, 73961, 85585, 34752, 61000, 4082, 24595, 103679, 71107, 8208, 79568, 150019,\n 16615, 24961, 139857, 32664, 197366, 4559, 54735, 32696, 4126, 162019, 75698, 13916, 70108, 159638, 19834, 9349,\n 24675, 175560, 49643, 18206, 52459, 27992, 10809, 88865, 401975, 133172, 29000, 34558, 30915, 3658, 25834, 42430,\n 36562, 125265, 18182, 10155, 40149, 97082, 208980, 19575, 60853, 90529, 66545, 9600, 789, 46420, 2317, 88593,\n 55595, 98980, 115302, 5742, 169155, 1073, 177901, 3472, 11189, 63711, 78643, 65472, 50459, 127979, 93, 42202,\n 67053, 21720, 157650, 11145, 141378, 42033, 22824, 85705, 79114, 35584, 15974, 1510, 54172, 28562, 12451, 104226,\n 19190, 97151, 73024, 20948, 5151, 81741, 21499, 29006, 84183, 198074, 54003, 45120, 170125, 26240, 35177, 28389,\n 64863, 79974, 60778, 176915, 232183, 45342, 2038, 80253, 41564, 40703, 32689, 5430, 100689, 5366, 23007, 134279,\n 14266, 26712, 73993, 24934, 64242, 52113, 102887, 61801, 46415, 201049, 54251, 62133, 122757, 164883, 30815, 139966,\n 2319, 30842, 766, 13362, 10287, 134518, 86111, 81665, 82440, 28333, 43019, 18963, 8804, 161944, 23439, 102144,\n 101145, 80029, 39052, 248708, 30350, 117340, 11878, 128467, 974, 138625, 63961, 5237, 74778, 61834, 67040, 43814,\n 13690, 65947, 33809, 232476, 115258, 181745, 28824, 94013, 9510, 10246, 93722, 81976, 7217, 114383, 3493, 16014,\n 69045, 72692, 12145, 80981, 9507, 6692, 1620, 60820, 330444, 35474, 33962, 4797, 7053, 295463, 46445, 27026,\n 12491, 77988, 49524, 35675, 90947, 29114, 166705, 101385, 133782, 32704, 6186, 84595, 176031, 185623, 45966, 151302,\n 63069, 1699, 107491, 947, 15458, 74452, 196212, 6046, 10498, 12163, 10239, 35191, 243951, 9277, 9090, 29539,\n 54460, 22820, 26514, 112549, 60372, 51753, 48756, 21812, 70861, 260326, 41, 44222, 10441, 16961, 48148, 138771,\n 216194, 5914, 52153, 53400, 212036, 56519, 26245, 10117, 45888, 15294, 138019, 90913, 26368, 43842, 42111, 23348,\n 6082, 194845, 161089, 156206, 51546, 11647, 30759, 302912, 262094, 8635, 78876, 26535, 35283, 54183, 31183, 85484,\n 147873, 12989, 5197, 6356, 72894, 65347, 20150, 27370, 73787, 1493, 45918, 12366, 190217, 20724, 13858, 10981,\n 67449, 81213, 7553, 14115, 72242, 271517, 11842, 48310, 88743, 143726, 22177, 3290, 243231, 58452, 62937, 12592,\n 1654, 40066, 33477, 13751, 9921, 128442, 15868, 7106, 75236, 83773, 10775, 36938, 10482, 170465, 17368, 17469,\n 161508, 32752, 98340, 800, 19824, 264456, 3901, 87319, 2867, 26782, 9630, 113102, 185815, 24197, 44584, 86366,\n 40224, 3636, 140916, 31731, 267731, 9567, 53678, 72984, 29389, 27963, 17106, 50282, 284911, 60170, 8322, 12608,\n 23374, 89652, 5268, 39044, 229766, 8869, 151350, 31436, 177342, 12269, 183212, 120418, 116270, 2843, 78888, 69192,\n 7865, 184099, 1086, 129897, 18383, 70508, 20242, 18508, 229924, 124569, 35749, 50589, 55626, 9884, 83115, 40971,\n 30671, 18135, 14452, 38861, 17844, 201826, 5549, 26413, 17189, 13561, 38539, 10679, 143331, 3314, 36785, 171194,\n 49685, 187713, 67506, 4618, 104039, 17060, 195080, 50648, 33159, 19238, 67559, 134840, 28599, 157523, 17130, 38064,\n 117398, 94355, 31918, 13575, 34538, 40326, 13997, 3494, 348283, 62481, 26862, 3603, 104426, 244363, 153709, 112487,\n 304612, 199674, 41239, 35545, 54869, 293005, 28223, 26277, 26899, 4533, 18518, 15492, 38587, 80488, 70485, 160395,\n 263, 60162, 11382, 222152, 4696, 250751, 51921, 182609, 10707, 48463, 46243, 1227, 49111, 111564, 46502, 33342,\n 56846, 68541, 63559, 858, 139927, 16654, 229375, 76759, 26478, 33205, 95828, 23399, 92945, 2637, 35630, 28470,\n 143992, 50214, 14174, 21456, 166191, 65665, 1711, 21594, 78019, 97599, 111701, 36, 147151, 110246, 189022, 43021,\n 30397, 40757, 131935, 42065, 73335, 48039, 26596, 28984, 15102, 2361, 7421, 202167, 69744, 43766, 52826, 3642,\n 83304, 33873, 75140, 63169, 192389, 36551, 92748, 13039, 123959, 233220, 21738, 84447, 77230, 20228, 187852, 19095,\n 25799, 92136, 108774, 29237, 53947, 2299, 118106, 2687, 8830, 42331, 202924, 33667, 2023, 73763, 30704, 19363,\n 19779, 16737, 35629, 48081, 24068, 101013, 162338, 291912, 13749, 24745, 328289, 167679, 70086, 48299, 23306, 16732,\n 17801, 43322, 54589, 3586, 63653, 43624, 53474, 925, 109177, 251316, 43805, 13082, 19511, 86565, 142182, 92461,\n 17117, 101033, 103319, 64589, 4022, 4351, 235897, 5352, 82705, 107142, 46391, 156084, 5860, 61365, 10558, 13045,\n 7717, 18357, 33922, 12590, 33065, 6928, 46993, 783, 46937, 67846, 8952, 26295, 6107, 119656, 18799, 17458,\n 50747, 4229, 179559, 112727, 118080, 20683, 41464, 125468, 51560, 49749, 44231, 7359, 35339, 62988, 136487, 67015,\n 5208, 29150, 24956, 105186, 48858, 6143, 18097, 6972, 16404, 73489, 58742, 97196, 36357, 164616, 5834, 32267,\n 13746, 147733, 15113, 132091, 34127, 106298, 39729, 106426, 22294, 9780, 15602, 36213, 71502, 42808, 66802, 599,\n 60755, 5851, 39120, 67363, 108623, 126368, 72770, 91263, 32486, 30596, 151717, 7951, 52002, 43103, 11768, 68942,\n 40901, 39344, 24037, 127500, 116890, 48403, 16926, 86750, 17745, 48648, 159545, 34460, 58419, 5634, 114317, 67865,\n 31462, 23352, 24010, 98185, 125708, 69686, 68337, 13610, 26271, 70691, 2980, 4768, 27225, 102402, 75453, 28106,\n 8104, 6931, 1176, 6274, 6475, 112635, 22498, 6176, 238686, 26832, 28893, 90319, 14441, 15682, 15087, 39517,\n 45270, 109134, 104440, 45965, 47645, 81772, 7876, 52683, 87720, 12898, 4505, 185665, 2769, 113401, 15664, 57592,\n 105229, 137381, 97059, 119268, 6876, 43309, 33886, 128363, 35476, 144249, 67013, 143587, 83367, 25703, 91436, 59347,\n 53236, 2289, 16519, 19844, 46309, 58558, 99834, 23313, 218816, 231303, 36388, 51333, 183535, 109792, 139277, 54306,\n 90139, 18235, 8275, 32710, 37677, 82464, 86025, 92204, 88842, 117723, 37570, 128723, 234242, 76350, 73795, 34896,\n 148247, 58424, 11105, 11744, 45746, 63372, 17118, 49772, 199520, 81902, 38004, 22911, 33752, 3125, 1995, 53792,\n 4689, 26909, 108150, 146062, 69674, 41811, 161444, 84855, 8999, 28561, 16731, 93937, 3189, 21967, 24890, 22943,\n 1356, 145300, 51569, 28802, 517, 118679, 31703, 40607, 48098, 108854, 25003, 10233, 73969, 177495, 5248, 24516,\n 215347, 146192, 48712, 60626, 69188, 40735, 5866, 586, 101541, 6509, 47590, 52129, 5969, 222045, 110933, 25733,\n 24223, 65339, 62812, 2414, 155418, 35819, 16022, 78423, 43138, 20995, 128255, 240673, 46745, 236093, 72176, 57085,\n 97841, 61248, 107, 36068, 193177, 105427, 55726, 215229, 20446, 47228, 100420, 87091, 14429, 121708, 23605, 21157,\n 187721, 21880, 2997, 203976, 99166, 95068, 25877, 7724, 98925, 83401, 4829, 13182, 18229, 13718, 239662, 38653,\n 116505, 153497, 30589, 89029, 38962, 181302, 43853, 78872, 180301, 4786, 248240, 7401, 106136, 112590, 77745, 19731,\n 60880, 77789, 125748, 135487, 5975, 48627, 34084, 12419, 215770, 47557, 254582, 10364, 106495, 21856, 67539, 88981,\n 38805, 21428, 48732, 42316, 12149, 16078, 52808, 25327, 51322, 33850, 51147, 12253, 122354, 46077, 56483, 254553,\n 115417, 81834, 150991, 94662, 86668, 7381, 12841, 100650, 18218, 15741, 22372, 68294, 50705, 15535, 84660, 61887,\n 22553, 72299, 31361, 24824, 17743, 46820, 64288, 31582, 77006, 111674, 116384, 30760, 80920, 86149, 77192, 51979,\n 79691, 60342, 122805, 103800, 240873, 160744, 233114, 78962, 54920, 8608, 3484, 316104, 72548, 24337, 5088, 230040,\n 21926, 10172, 36838, 26, 86221, 83458, 102176, 12062, 17571, 41929, 41170, 28428, 68239, 41750, 103930, 2634,\n 18313, 53019, 34825, 97837, 63115, 24606, 73157, 152474, 14715, 91439, 37033, 109806, 140259, 30668, 174760, 380,\n 135597, 95673, 136073, 65073, 134249, 13829, 17279, 122305, 4420, 46444, 10237, 64848, 203623, 70728, 10349, 182885,\n 65075, 24519, 25783, 40318, 34139, 22222, 63394, 55266, 102764, 41422, 20126, 65100, 90408, 53640, 35128, 48932,\n 11192, 38935, 96839, 34782, 39492, 19396, 41332, 6250, 5511, 19492, 51304, 25936, 104466, 54099, 73771, 86115,\n 5080, 7669, 30891, 111700, 13931, 25276, 72289, 135447, 14820, 258641, 25265, 31005, 281179, 75286, 393, 95359,\n 14623, 13584, 6680, 101227, 80173, 44933, 76666, 54542, 13244, 39348, 458, 25379, 109451, 134348, 81143, 6959,\n 65554, 12027, 51311, 8716, 57589, 140731, 28467, 23316, 17272, 30458, 25980, 55229, 77197, 83798, 28302, 114784,\n 7428, 34548, 26241, 14712, 39336, 103304, 18928, 54080, 12870, 334, 87722, 15208, 16895, 142098, 114262, 39820,\n 83913, 57817, 28682, 7721, 14900, 108672, 11250, 62246, 42849, 415188, 1724, 26555, 24549, 25505, 26443, 107450,\n 145899, 61035, 43528, 6901, 60726, 65906, 267741, 21338, 147590, 42079, 18924, 73017, 135236, 15393, 5206, 4026,\n 84185, 1531, 5988, 113890, 82647, 303391, 7386, 69844, 71611, 189865, 76523, 31877, 13315, 19314, 198575, 32821,\n 1928, 67641, 25913, 104475, 103489, 3297, 70391, 18406, 15446, 113347, 19295, 93790, 27856, 1792, 167471, 116449,\n 8541, 4408, 41757, 63233, 25765, 86680, 64501, 27034, 24816, 34975, 6079, 4486, 49693, 36229, 16917, 21581,\n 62426, 27862, 11612, 54284, 35702, 194034, 355, 24277, 48262, 87411, 70504, 310164, 118018, 12516, 47559, 43502,\n 57433, 107139, 9290, 66533, 80863, 14634, 34312, 91725, 28606, 21342, 67241, 72355, 43244, 375789, 37402, 174015,\n 105070, 8342, 44167, 67494, 1890, 16365, 11723, 271002, 1865, 47918, 8350, 45564, 27742, 25110, 125803, 8553,\n 49504, 81925, 62211, 4534, 15491, 19011, 80373, 206920, 667, 102405, 128623, 245524, 5553, 113309, 192739, 65766,\n 19567, 22832, 261958, 29679, 21293, 71134, 20962, 105123, 24721, 860, 21752, 33448, 18372, 157167, 94822, 35770,\n 173224, 232737, 75729, 28937, 46828, 28062, 25453, 5207, 140366, 36665, 30652, 6169, 67920, 150458, 92040, 23186,\n 184604, 92330, 20891, 176492, 49427, 27828, 38305, 42495, 143982, 49560, 25503, 90043, 29747, 65328, 47830, 12932,\n 11068, 77721, 9003, 25213, 94205, 140426, 46090, 89945, 138173, 192691, 33329, 112232, 129905, 35709, 27514, 1841,\n 19957, 31411, 127476, 53572, 17497, 173549, 55063, 175135, 19841, 69314, 5192, 237921, 117660, 150697, 4060, 273045,\n 50414, 98940, 65348, 153665, 164423, 58804, 156695, 48994, 213928, 86036, 28608, 8355, 39574, 34540, 16927, 135680,\n 18374, 151587, 10830, 53805, 16878, 16623, 4282, 48030, 8537, 14986, 46102, 13062, 72897, 72, 33050, 108227,\n 39451, 45935, 651, 113320, 40535, 95176, 57450, 48843, 5003, 19019, 10407, 211163, 3848, 1068, 4988, 32091,\n 30095, 41692, 15099, 43602, 107434, 50744, 7627, 171349, 16313, 150832, 352665, 207750, 33937, 38256, 51091, 156000,\n 87889, 90663, 84175, 24908, 114900, 50365, 31494, 83829, 5398, 169342, 47521, 54818, 18935, 8356, 43094, 41212,\n 174536, 10082, 92550, 6678, 60614, 23355, 69721, 14796, 34149, 128830, 58187, 3179, 208, 40325, 28399, 225029,\n 401412, 51150, 31580, 207268, 6657, 10993, 69818, 64282, 289845, 23308, 12961, 38447, 6681, 52944, 31855, 2572,\n 47646, 120728, 179148, 37240, 45196, 218274, 4816, 3695, 21961, 50084, 35209, 18073, 51452, 27004, 6100, 33941,\n 1377, 84831, 171214, 85, 141510, 9078, 99227, 32610, 6417, 11718, 49868, 65579, 87902, 73018, 49062, 46280,\n 61742, 21512, 40862, 107733, 15941, 29168, 157765, 144919, 14487, 5767, 158014, 140070, 7241, 573, 71584, 16921,\n 223566, 40331, 179473, 35081, 47926, 140885, 41508, 52104, 59180, 42310, 32811, 29048, 123517, 102413, 80208, 10104,\n 14746, 12649, 153641, 126022, 37965, 113017, 4171, 83, 142592, 2809, 6362, 50416, 71323, 116894, 260776, 16204,\n 1524, 5760, 30351, 12658, 20703, 54403, 36083, 45408, 74772, 4946, 14485, 50759, 111222, 10890, 2195, 167147,\n 92962, 130534, 16283, 177256, 35016, 15472, 210156, 151187, 73922, 117691, 43250, 52051, 37392, 24811, 24358, 30830,\n 5775, 818, 21969, 1476, 127322, 151783, 58392, 31021, 106913, 65215, 89407, 90802, 28531, 11690, 20234, 95249,\n 44602, 37256, 18707, 11928, 5161, 4410, 26571, 51903, 49768, 22008, 25252, 65780, 209499, 68769, 203726, 13249,\n 137363, 48845, 86823, 6658, 5674, 31881, 1083, 1823, 108676, 34518, 166752, 13791, 14287, 91576, 91429, 8665,\n 11529, 26401, 16191, 91972, 30964, 5254, 28486, 54697, 79613, 66520, 18447, 22870, 45203, 194466, 22822, 51703,\n 12278, 76716, 44595, 73455, 33546, 12235, 144843, 36154, 51247, 11116, 33040, 3180, 225753, 60864, 1972, 28469,\n 12891, 28879, 10338, 144157, 56294, 353058, 38302, 41447, 87532, 110616, 27065, 168438, 6557, 1213, 50804, 144643,\n 24817, 2390, 136531, 38174, 247513, 16190, 4059, 122791, 131994, 137430, 39506, 57650, 16305, 5188, 54309, 106128,\n 20628, 88071, 67394, 395446, 250285, 66176, 91254, 1399, 114196, 43915, 60230, 44853, 27206, 106353, 43013, 18733,\n 345105, 226453, 51202, 16607, 57106, 117175, 35492, 10476, 89598, 127439, 15187, 39624, 13688, 61570, 10615, 31111,\n 59370, 6238, 175252, 32143, 224492, 41388, 95408, 34384, 148238, 78307, 38959, 9340, 160091, 61443, 15737, 11216,\n 41244, 170, 38299, 102443, 113097, 26382, 14027, 33707, 3957, 76300, 66160, 19431, 18900, 6952, 1717, 108656,\n 82206, 188021, 257335, 27295, 43999, 41210, 31777, 46956, 57457, 12657, 11489, 15697, 48060, 204748, 53583, 82422,\n 284790, 30503, 137341, 8120, 19615, 220311, 15991, 10217, 63424, 9808, 67431, 70976, 98221, 4491, 15177, 28535,\n 144789, 751, 13230, 2394, 1504, 33977, 132104, 30316, 22230, 931, 97193, 185240, 24826, 22687, 174322, 15307,\n 22988, 1390, 188745, 180325, 29580, 59068, 74903, 18994, 29195, 79, 15436, 7622, 38462, 11566, 138710, 44828,\n 45774, 37768, 99236, 68137, 84083, 19282, 22698, 17134, 74807, 126662, 173497, 46248, 16938, 119735, 3212, 28292,\n 213652, 49013, 9975, 32180, 45660, 86250, 4801, 68788, 95490, 77482, 113751, 11994, 44624, 94452, 46839, 128497,\n 100316, 5798, 58588, 73184, 202987, 65417, 37790, 88524, 1606, 43156, 97964, 105717, 34947, 11203, 100060, 37742,\n 130074, 93653, 107799, 94311, 196106, 41347, 8035, 10780, 16390, 27883, 118236, 167395, 1979, 25006, 19375, 31628,\n 18916, 144723, 78502, 114047, 103107, 86492, 107686, 5844, 20934, 206963, 23556, 22591, 16562, 146333, 20167, 10471,\n 117434, 33085, 2863, 9740, 36669, 41849, 37271, 22790, 18209, 28979, 8231, 12952, 54408, 21731, 25130, 45208,\n 55748, 138120, 75826, 414, 29593, 9925, 292865, 25999, 683, 123149, 7036, 92159, 86055, 61827, 103680, 23176,\n 54918, 58466, 57578, 13305, 5709, 86479, 16697, 31064, 17660, 200919, 10770, 49793, 33423, 32370, 52047, 16488,\n 62555, 6459, 8426, 83493, 7763, 59725, 82812, 18628, 67760, 79405, 68557, 9612, 7673, 28102, 56517, 69620,\n 171797, 32458, 29541, 15870, 81109, 32080, 207644, 71495, 21202, 11039, 91036, 61230, 2810, 130800, 32260, 4613,\n 60590, 37112, 75214, 33979, 126402, 155062, 30642, 63875, 12810, 194463, 82799, 47664, 16725, 36685, 43367, 61099,\n 449, 172150, 102867, 21691, 301838, 36745, 7130, 18671, 57316, 34852, 38034, 54182, 35578, 65900, 99486, 19771,\n 3456, 2658, 16914, 99866, 28390, 28109, 8262, 21147, 34353, 20006, 4228, 137085, 1675, 203023, 283196, 198286,\n 214375, 163329, 290603, 152574, 40471, 83506, 30068, 14730, 23177, 131539, 34759, 27668, 32178, 71896, 104799, 116305,\n 85430, 119262, 42860, 25160, 8911, 23428, 49437, 105322, 6519, 16203, 6349, 74711, 1230, 38045, 8540, 75165,\n 44736, 25909, 51026, 317034, 4984, 32281, 91312, 27060, 44431, 17817, 45363, 155937, 239085, 35697, 59784, 91993,\n 29531, 126740, 213757, 76560, 167776, 285273, 24262, 8237, 65030, 41160, 74437, 48804, 118916, 13159, 37842, 1031,\n 75349, 1478, 11655, 108777, 23435, 277425, 101734, 67469, 70231, 124711, 43532, 28514, 65526, 54956, 1000, 21882,\n 17728, 25302, 40952, 52214, 149632, 1999, 2111, 3259, 63362, 89961, 220561, 39777, 26335, 9063, 10572, 12416,\n 34551, 34623, 38604, 24723, 5947, 15588, 69927, 66252, 119177, 69173, 46629, 28714, 70715, 212408, 20521, 406913,\n 74380, 11716, 50659, 50862, 37009, 88460, 130101, 7210, 53853, 538, 65120, 151950, 55806, 163748, 52837, 13153,\n 21100, 16674, 64536, 6091, 138201, 44837, 58547, 3723, 163, 2177, 32288, 85454, 34033, 8497, 14282, 25742,\n 10535, 10741, 79559, 117493, 243787, 49337, 100718, 79495, 40139, 42956, 7551, 55433, 15421, 31509, 23034, 45081,\n 547, 61176, 53434, 328001, 8470, 36263, 30145, 4519, 74173, 53935, 11845, 73774, 60211, 78025, 3, 4102,\n 73782, 109293, 315332, 48412, 26683, 13714, 6865, 20128, 18490, 104141, 325, 39470, 171970, 115860, 15707, 7268,\n 73301, 74336, 31370, 2368, 111827, 107757, 136231, 142844, 97138, 96638, 84053, 38691, 23801, 1588, 10573, 122098,\n 77039, 240, 186135, 146101, 11996, 18143, 112963, 46171, 155836, 348769, 47795, 121213, 116266, 132515, 3344, 144804,\n 31286, 99187, 255838, 129694, 35894, 48779, 55235, 148582, 71967, 65282, 15174, 13920, 47080, 6147, 108242, 157593,\n 125025, 7136, 1286, 28957, 127956, 28402, 98813, 20805, 7532, 109417, 40610, 5041, 32958, 15142, 18408, 108596,\n 33543, 50517, 27748, 80114, 233434, 91447, 487, 37094, 100048, 30541, 43477, 10639, 89862, 155868, 37667, 8726,\n 60684, 237903, 73408, 99589, 12190, 38739, 97348, 3914, 13594, 2680, 149016, 13907, 30171, 28343, 23530, 115225,\n 61104, 35821, 147679, 14337, 4297, 244282, 24085, 326976, 56428, 7851, 21303, 131620, 71446, 83253, 68692, 111870,\n 5224, 15813, 38197, 49026, 45057, 13660, 3306, 76345, 40671, 27905, 91072, 996, 68527, 62085, 91351, 122634,\n 55109, 168209, 2024, 27560, 112707, 17352, 8306, 167115, 169921, 166958, 5031, 46020, 11844, 67284, 19130, 76185,\n 6920, 32849, 5450, 14610, 22451, 21002, 17392, 31872, 66682, 84796, 13709, 40210, 59898, 12029, 8719, 53564,\n 21462, 91884, 21647, 88379, 194428, 12754, 37797, 132826, 160016, 22567, 54383, 53186, 77611, 31107, 8339, 4694,\n 19185, 90355, 23597, 17222, 140675, 28442, 23668, 55977, 9128, 61555, 28774, 155229, 17658, 9390, 24379, 69357,\n 15752, 127381, 239631, 62460, 93181, 55913, 45133, 140155, 18676, 25249, 33164, 29581, 82837, 67223, 22362, 29975,\n 7317, 52813, 1943, 29613, 20012, 207130, 49617, 49651, 5636, 15334, 36313, 29226, 28084, 95247, 72072, 19000,\n 224932, 15811, 114, 32127, 38097, 37508, 88507, 37225, 27359, 91626, 12193, 69279, 20608, 11055, 88156, 92808,\n 2152, 57259, 55275, 72789, 24475, 104414, 1708, 9882, 3818, 48661, 66897, 1631, 34806, 227930, 85815, 87753,\n 18321, 250664, 72733, 25107, 206797, 50891, 8082, 196411, 92596, 96764, 152823, 65514, 22819, 387277, 62176, 51225,\n 40329, 15563, 189, 3659, 73670, 64357, 51793, 275136, 33482, 86653, 74615, 67058, 11318, 125720, 15388, 22388,\n 8267, 1730, 102663, 170910, 40784, 7144, 85373, 13040, 7088, 94309, 583, 44224, 140424, 77439, 18496, 164026,\n 36578, 4722, 9151, 5824, 63365, 26510, 35199, 40500, 79277, 32495, 44614, 35233, 9566, 203293, 152144, 7097,\n 2330, 183480, 98629, 13423, 330887, 44130, 68600, 30939, 97829, 31012, 345465, 56747, 94879, 4939, 160027, 149761,\n 99423, 46099, 32251, 15332, 8761, 96094, 128555, 5763, 235318, 222223, 55729, 30241, 55420, 201746, 3987, 81382,\n 8259, 49325, 23287, 7719, 24633, 251100, 92311, 18591, 110533, 64759, 170260, 393860, 7175, 21144, 132887, 3593,\n 75346, 101277, 91109, 16387, 259187, 11627, 57459, 173829, 44694, 55780, 49797, 89192, 120443, 62622, 3904, 14814,\n 23887, 1027, 112258, 64955, 99800, 11132, 66353, 36202, 48624, 18158, 88481, 96882, 43059, 11040, 2455, 7077,\n 21651, 181159, 99126, 100434, 61388, 68186, 19161, 110468, 120052, 8819, 55324, 41494, 7014, 37689, 3618, 87729,\n 92615, 207943, 9823, 128657, 12587, 15857, 6379, 67628, 51216, 71775, 157617, 63244, 1503, 3864, 218754, 110864,\n 5769, 21492, 7243, 1192, 87921, 85529, 31512, 18537, 42698, 35350, 73510, 84474, 34301, 8991, 21013, 35034,\n 566, 38832, 19838, 35586, 37216, 39413, 55006, 12178, 59742, 856, 84563, 6900, 25632, 17437, 49786, 30723,\n 13847, 70845, 4044, 7843, 23944, 235976, 55530, 48942, 6518, 20939, 73769, 192653, 52936, 95207, 23895, 132542,\n 142982, 22632, 87452, 48042, 54018, 178468, 10728, 26230, 23559, 363, 81269, 142012, 5718, 346258, 31456, 84333,\n 246476, 51018, 66692, 101804, 120570, 39962, 30373, 70593, 2864, 60541, 19425, 54209, 104092, 7201, 31545, 48018,\n 25865, 15442, 46257, 40443, 8328, 6451, 111782, 47527, 97754, 33046, 470, 245116, 31095, 39, 91934, 87208,\n 73470, 36708, 36521, 12801, 70624, 36272, 8892, 79768, 12427, 55454, 103756, 5908, 52390, 62962, 22720, 141138,\n 94634, 41689, 128402, 126390, 6628, 106394, 35527, 134394, 82727, 254651, 194502, 148064, 89549, 3202, 28359, 957,\n 21954, 27906, 49840, 142747, 8307, 24206, 48978, 1186, 71728, 133038, 71474, 91306, 6333, 110959, 74600, 70387,\n 18983, 62609, 56057, 22970, 1147, 135850, 1321, 28834, 3578, 59715, 102227, 32827, 81415, 99952, 55636, 257598,\n 390, 22702, 35701, 85872, 402916, 39216, 189795, 14929, 19467, 10112, 144422, 61514, 5279, 63421, 134686, 41436,\n 8424, 51925, 10598, 132295, 124416, 4604, 194739, 210929, 57866, 31829, 51626, 50007, 9976, 91878, 61906, 56168,\n 81906, 60918, 61859, 40017, 23059, 16887, 40927, 62064, 12785, 32893, 32913, 21782, 93965, 20169, 44387, 79084,\n 38463, 11457, 93950, 27127, 157050, 2697, 337088, 5116, 54128, 48255, 33279, 8821, 27352, 25515, 124022, 65710,\n 28906, 38557, 33390, 1722, 104435, 72215, 38551, 12094, 30978, 25113, 6671, 37355, 175109, 42862, 98024, 65406,\n 221276, 59624, 118012, 64637, 78760, 86697, 21426, 1639, 40350, 12584, 67193, 84144, 31396, 7863, 143011, 69629,\n 63112, 9454, 28666, 65798, 46372, 134721, 6314, 51402, 30837, 151922, 2847, 38676, 38008, 92823, 136245, 17540,\n 5504, 109295, 205242, 37606, 5211, 214892, 1586, 20670, 208711, 137743, 19328, 40652, 16995, 20023, 14657, 154919,\n 34422, 12996, 13918, 38221, 47690, 16398, 2959, 37680, 89122, 6721, 198469, 91876, 172043, 83898, 101992, 26084,\n 94570, 3635, 76958, 22853, 76497, 38266, 176590, 168403, 44464, 142840, 79180, 184594, 1984, 41806, 83147, 11985,\n 6546, 366068, 59732, 24533, 271505, 8736, 39084, 222992, 93429, 28962, 58985, 86665, 8432, 30028, 14548, 32439,\n 54424, 165029, 55175, 27458, 69046, 121277, 46168, 33732, 20661, 24581, 135574, 123110, 37556, 79260, 72611, 16957,\n 12939, 46162, 58238, 44907, 72936, 253758, 41324, 32518, 96480, 11949, 124438, 65280, 43256, 34107, 53533, 43531,\n 37037, 28366, 45970, 32741, 173438, 6121, 194202, 62969, 26355, 30314, 58370, 28455, 1848, 50519, 82830, 90393,\n 21761, 295490, 10936, 256940, 133568, 44050, 20269, 4089, 27457, 21610, 219460, 36743, 14821, 101388, 52005, 13124,\n 30979, 140816, 167362, 26054, 18458, 60789, 34917, 40447, 26606, 33422, 9066, 3452, 83614, 5761, 20263, 137238,\n 25038, 91310, 101, 52322, 74548, 42572, 38084, 214054, 186568, 31802, 17665, 30620, 141936, 37730, 14420, 4265,\n 187218, 49640, 188208, 51441, 55388, 96452, 66659, 40869, 42039, 60967, 221027, 19234, 178581, 29105, 96050, 9165,\n 196118, 157335, 3738, 40354, 117436, 2965, 34136, 59659, 15570, 50843, 230035, 31444, 71260, 43886, 18316, 5387,\n 38500, 168508, 17406, 32174, 8828, 103373, 143806, 90367, 3560, 18719, 122310, 16508, 26719, 2541, 105429, 6645,\n 37998, 73190, 10591, 235916, 49737, 87112, 233941, 53188, 32193, 79154, 4544, 52905, 126477, 7580, 63501, 57314,\n 3216, 31337, 6541, 103083, 60846, 49, 9756, 15481, 1355, 43840, 14319, 13743, 27486, 10222, 73114, 230718,\n 418644, 16706, 6674, 279748, 23058, 45273, 295831, 86306, 2743, 5535, 88773, 21829, 35253, 120938, 31153, 3169,\n 16839, 42847, 8751, 80974, 33942, 36867, 35514, 16485, 26474, 77775, 56877, 5391, 48346, 3882, 108713, 31403,\n 27804, 55248, 26235, 43821, 136104, 40118, 175507, 28034, 203908, 18732, 1788, 34030, 106427, 36958, 54359, 7251,\n 44936, 15356, 69139, 455, 157915, 22173, 140291, 50348, 43275, 82066, 49621, 54952, 15216, 36226, 96695, 66855,\n 6936, 1987, 8227, 196087, 4631, 68827, 99004, 47541, 110265, 17953, 147605, 110242, 58520, 31312, 38724, 329975,\n 642, 3155, 34497, 75937, 6207, 73843, 6120, 17249, 51429, 117746, 3218, 910, 68961, 319671, 14938, 29555,\n 34700, 1649, 66673, 72268, 9655, 76800, 153087, 6941, 210168, 27130, 35398, 1780, 73242, 3135, 56689, 19556,\n 165307, 8765, 35967, 121458, 13333, 70453, 17350, 117253, 22265, 13340, 44265, 39869, 441, 3742, 135025, 23581,\n 33309, 16543, 17731, 13291, 157637, 283005, 21408, 101360, 63887, 52312, 83873, 5338, 233779, 23759, 186949, 34531,\n 177320, 38069, 156465, 91004, 19353, 59852, 68160, 14891, 1338, 1072, 29823, 1950, 28901, 81407, 313445, 73038,\n 84807, 162348, 240257, 37162, 138934, 16111, 58013, 41253, 102951, 16457, 96056, 19541, 56402, 67217, 41638, 94381,\n 89674, 29481, 37456, 80815, 151579, 13937, 13683, 132537, 19699, 134545, 67020, 29816, 222341, 141235, 427578, 48868,\n 129557, 233342, 23077, 87871, 16213, 18728, 16184, 9469, 37913, 19680, 2798, 171356, 178328, 13216, 50049, 72690,\n 71904, 124644, 55455, 7504, 29052, 41036, 266546, 19899, 30391, 188755, 8659, 59469, 16, 104298, 112943, 53865,\n 76203, 138226, 68857, 139953, 14125, 107625, 119795, 173133, 4398, 50273, 48808, 54390, 16466, 122086, 31835, 67035,\n 50971, 48859, 7508, 46427, 66477, 73021, 84615, 39985, 83076, 46779, 201569, 53336, 36443, 60865, 168164, 143810,\n 51393, 25548, 169307, 32896, 24485, 38424, 21837, 29087, 275813, 51674, 6714, 64883, 46169, 187369, 55186, 76192,\n 12852, 12018, 62134, 31067, 118303, 16542, 12125, 10579, 4928, 26291, 43854, 7091, 10946, 253716, 109062, 39283,\n 17261, 113012, 258512, 47764, 125126, 32646, 55892, 80279, 201623, 149872, 3192, 385, 1208, 48750, 5376, 58738,\n 22335, 5427, 82416, 47811, 32435, 143086, 38930, 94128, 59975, 156037, 37977, 38224, 62485, 7698, 50405, 71027,\n 16462, 21559, 136153, 34131, 107506, 162069, 63703, 3101, 215029, 40407, 4178, 3774, 9187, 80019, 17880, 97926,\n 67579, 2600, 18405, 8351, 47924, 86638, 70820, 92206, 86453, 29610, 42241, 119200, 3198, 15466, 67813, 57863,\n 35454, 4779, 99518, 4649, 104641, 144269, 33730, 38073, 65864, 6838, 109456, 193298, 154007, 5623, 45741, 30846,\n 182578, 25573, 157224, 1543, 58575, 138703, 146140, 44971, 49356, 18275, 59064, 20300, 13122, 11848, 24453, 11973,\n 9797, 86843, 2919, 25530, 49210, 1130, 161220, 76788, 75373, 85604, 34926, 36014, 17777, 17255, 51533, 11676,\n 92226, 51845, 119859, 21525, 5936, 18507, 28050, 1140, 31418, 14857, 34207, 47859, 10750, 36382, 32079, 106909,\n 59426, 87757, 38393, 110042, 15965, 97104, 33757, 35344, 97993, 53979, 33651, 45407, 41884, 82515, 173089, 7177,\n 58371, 35365, 47543, 51927, 35587, 10670, 23544, 29306, 84233, 39976, 76076, 62097, 9007, 8668, 28119, 78281,\n 120790, 19835, 143020, 54968, 18670, 64959, 20649, 34469, 42570, 33001, 136570, 87796, 120044, 1106, 58700, 63951,\n 127623, 12805, 83057, 40212, 31773, 49850, 7361, 54336, 347524, 101314, 23751, 19569, 48791, 29174, 49369, 20467,\n 7465, 75842, 38281, 623, 112457, 60210, 28849, 51003, 94720, 6426, 90047, 85560, 43761, 3579, 85105, 34607,\n 90410, 118528, 7224, 42907, 111163, 18168, 6960, 161135, 191298, 5247, 100584, 127552, 171568, 20121, 91173, 12636,\n 54615, 20199, 63730, 98105, 2396, 40387, 14438, 125012, 4765, 33235, 12865, 45299, 37728, 82098, 77872, 114037,\n 59253, 19675, 24838, 398016, 102561, 11446, 17069, 57508, 178277, 65836, 99941, 26114, 2585, 271882, 136866, 50126,\n 11027, 155648, 118367, 14585, 8910, 123015, 335383, 40434, 41016, 53021, 14439, 87098, 176860, 201543, 121888, 2358,\n 9286, 5739, 22666, 54270, 37884, 169381, 33984, 93859, 16124, 89364, 72207, 51639, 76366, 99029, 65812, 2198,\n 12147, 174891, 194289, 6986, 30252, 88822, 21284, 11445, 288337, 160821, 33034, 100869, 43852, 25761, 52882, 1144,\n 103809, 1924, 84458, 86079, 43411, 13542, 139276, 18141, 34978, 41298, 7276, 26481, 173800, 33210, 17951, 142652,\n 33616, 33677, 2210, 19941, 98568, 2486, 192414, 80136, 12058, 235883, 50963, 249638, 29572, 27221, 47034, 6124,\n 72107, 63346, 97620, 158513, 299699, 40388, 23235, 37176, 224244, 198386, 121323, 67992, 23827, 63170, 17838, 106622,\n 158590, 26807, 5345, 23489, 91891, 55474, 74834, 37981, 13058, 5977, 72552, 34706, 26828, 145172, 19904, 21367,\n 34043, 960, 77092, 91381, 4733, 47446, 7680, 41697, 5170, 16960, 14741, 46101, 13656, 473, 51842, 37433,\n 11103, 11551, 121951, 13191, 97536, 165932, 50397, 51628, 129028, 9069, 44885, 6590, 59195, 47045, 32940, 225472,\n 90345, 21833, 13303, 29407, 96615, 141951, 5198, 6028, 18395, 7181, 3861, 14966, 156358, 167182, 36529, 55253,\n 25942, 173153, 30959, 27261, 50691, 150176, 162201, 38467, 48462, 80602, 42163, 118482, 168, 108756, 26011, 17166,\n 54149, 456538, 22512, 91374, 13816, 90358, 131615, 18132, 226707, 1824, 28139, 26860, 42253, 93877, 77351, 65575,\n 8980, 80574, 22020, 27948, 40422, 91324, 76376, 13528, 39281, 91685, 82215, 122541, 144066, 1983, 193851, 17283,\n 26320, 2739, 194978, 4790, 26845, 42627, 61300, 65815, 174612, 55133, 4200, 191130, 79771, 158321, 52280, 166796,\n 221620, 62461, 11278, 4067, 88152, 83409, 31717, 121367, 13522, 47325, 37945, 10406, 174348, 249321, 154101, 64912,\n 29938, 51775, 17220, 15776, 166138, 78890, 84425, 54121, 42861, 16368, 24572, 291647, 10197, 32073, 22651, 11677,\n 97509, 26952, 35787, 18424, 41910, 71614, 94977, 72318, 41594, 70024, 275419, 37702, 60199, 7335, 39107, 61315,\n 18271, 18394, 33768, 87884, 104277, 123724, 7277, 56288, 71981, 189803, 49320, 3352, 6798, 14240, 8954, 69220,\n 94433, 57372, 28620, 68863, 193727, 85575, 42309, 41667, 67689, 42081, 22543, 44824, 12719, 28540, 114236, 101553,\n 27638, 27296, 4300, 5353, 4663, 19379, 94098, 3758, 95888, 95144, 80344, 87320, 28447, 259518, 12718, 71391,\n 152731, 37063, 24132, 31911, 104896, 15672, 103782, 1521, 4945, 72541, 23717, 122632, 15619, 87175, 206120, 29428,\n 189780, 61416, 28350, 44457, 972, 1175, 47233, 198738, 95789, 41907, 21953, 97034, 59341, 22864, 53713, 16873,\n 32971, 20693, 20954, 31336, 21477, 16169, 38370, 16412, 9019, 3841, 24599, 21938, 17085, 6484, 81198, 76413,\n 5849, 72514, 12320, 65247, 276175, 37234, 59796, 52642, 16312, 57349, 198507, 94148, 46134, 18958, 125552, 1747,\n 18725, 151873, 14901, 5490, 68287, 29470, 3689, 64794, 40814, 26018, 25692, 54450, 2703, 88278, 124886, 173087,\n 174000, 24159, 179477, 24276, 46004, 201876, 209202, 445, 52876, 31948, 30206, 157610, 39180, 18439, 44124, 50469,\n 5774, 96278, 222758, 200216, 50290, 45486, 20435, 46986, 46276, 140133, 142326, 15569, 13363, 47522, 92583, 2182,\n 7135, 16853, 22998, 30272, 4952, 63263, 35623, 39096, 53789, 44864, 20053, 110392, 124213, 4630, 16087, 28221,\n 127787, 25839, 77481, 44693, 13464, 113146, 6983, 27069, 55717, 50102, 4760, 7107, 26186, 66507, 59145, 36032,\n 104182, 71328, 29425, 64317, 50781, 47465, 94298, 69706, 74899, 22754, 120756, 25108, 93077, 56834, 73286, 39928,\n 16218, 41699, 176763, 7555, 70819, 50083, 26895, 23315, 26014, 16773, 123079, 41712, 5719, 31516, 90427, 158540,\n 85051, 183128, 40864, 27505, 55392, 9058, 45224, 96857, 30901, 136622, 96557, 56304, 120061, 11501, 151448, 5773,\n 89743, 7769, 86069, 2935, 18471, 41628, 10114, 33660, 110170, 49479, 26745, 92846, 33221, 26731, 18795, 87076,\n 8550, 2100, 29972, 120289, 3077, 72490, 33784, 2630, 208722, 50861, 63483, 79029, 6419, 39467, 14302, 45286,\n 64207, 9686, 67513, 44170, 1050, 77246, 59266, 17055, 53801, 7150, 11111, 42432, 4278, 94579, 362117, 36175,\n 42902, 41933, 39002, 98489, 22913, 74161, 84773, 57036, 17556, 162288, 74485, 178760, 93867, 73635, 128860, 50362,\n 261, 67455, 80001, 46080, 35662, 4368, 25247, 19230, 74393, 22588, 1822, 27682, 235324, 13798, 85998, 13194,\n 235067, 23514, 71669, 147632, 23191, 134748, 214683, 105101, 1518, 25489, 247114, 7380, 54842, 26922, 3971, 26361,\n 20844, 68642, 170517, 77339, 123255, 8963, 77818, 150998, 48466, 36806, 2732, 23261, 11741, 236162, 18243, 126216,\n 28690, 50546, 16385, 92760, 197383, 246558, 201295, 88255, 67588, 71687, 176076, 172653, 169058, 33906, 63747, 24835,\n 157621, 43338, 30050, 46152, 132741, 2770, 51371, 94835, 6614, 15112, 11749, 56936, 1250, 19027, 399017, 58036,\n 100215, 23388, 55815, 308768, 124152, 94803, 9521, 64186, 8971, 28, 30427, 62163, 7616, 103838, 35079, 29203,\n 131235, 7743, 17389, 10882, 37420, 61460, 228512, 85363, 41581, 131077, 62822, 119647, 10130, 54445, 26925, 19968,\n 29016, 24446, 74028, 24176, 61448, 67185, 9254, 8563, 119129, 9771, 99184, 37716, 39514, 10532, 221512, 258753,\n 218630, 55980, 23394, 32141, 61924, 66749, 32411, 3741, 36475, 26678, 77010, 44946, 91203, 128749, 116953, 20476,\n 49625, 53116, 13735, 102335, 29376, 51946, 83407, 67892, 59212, 34685, 21083, 1546, 112982, 32972, 74397, 1078,\n 190545, 16082, 86140, 58591, 89611, 101531, 10061, 105104, 76319, 20035, 17551, 52611, 169061, 190842, 100780, 23907,\n 90413, 115619, 9675, 34710, 193435, 49443, 129734, 11183, 258877, 16318, 136182, 126808, 44635, 27304, 192375, 2599,\n 125648, 47051, 12091, 23814, 721, 58800, 40137, 66726, 97930, 60877, 74487, 7942, 54326, 9841, 41428, 13762,\n 8211, 85383, 6950, 99177, 79806, 201786, 296464, 124087, 13144, 29741, 41721, 47634, 55088, 254286, 106408, 17041,\n 99064, 12942, 64086, 45233, 14005, 2612, 55827, 255, 7984, 13980, 38574, 12776, 46654, 73499, 249951, 2101,\n 26676, 25996, 132326, 116415, 119062, 50449, 31033, 23038, 11589, 179252, 20007, 14860, 129270, 21143, 17796, 144715,\n 60106, 70758, 69842, 34674, 282133, 44014, 16774, 57268, 38528, 24053, 46373, 201667, 28327, 471023, 51889, 102667,\n 21193, 114909, 84132, 69317, 96723, 67969, 16134, 68145, 15058, 28765, 32035, 2524, 101089, 98664, 25045, 76571,\n 14957, 86040, 118506, 262428, 154764, 81573, 39681, 283900, 73287, 127825, 544, 80448, 52347, 38512, 175971, 15180,\n 45467, 33086, 46552, 48894, 81107, 43213, 36672, 54025, 76703, 8053, 7608, 13299, 56619, 20752, 238099, 54164,\n 105133, 1444, 32942, 953, 37564, 8000, 66316, 119463, 106817, 404, 13667, 149108, 128597, 31267, 10269, 49836,\n 106150, 1484, 52330, 76965, 160486, 171648, 38456, 31263, 22424, 37738, 66245, 67467, 143369, 60471, 75610, 20895,\n 115528, 86070, 60854, 40796, 49347, 18989, 15030, 11371, 37578, 15779, 79867, 10187, 86462, 46402, 155626, 93200,\n 40229, 7090, 57547, 108053, 99598, 11088, 47505, 41218, 206017, 2173, 20988, 30219, 22919, 80563, 57566, 42369,\n 93141, 41675, 2407, 182519, 120495, 27154, 16702, 29456, 14349, 7958, 16688, 117177, 140375, 42467, 261919, 74916,\n 153569, 10836, 34742, 49526, 7621, 105997, 12212, 2270, 392377, 7755, 17959, 25086, 232152, 138791, 33847, 13860,\n 35316, 5811, 1344, 71259, 50452, 207539, 92635, 50359, 5821, 33674, 30255, 2086, 2587, 96264, 17543, 42,\n 6029, 9580, 43007, 139248, 82831, 12917, 29607, 25786, 51467, 42137, 85161, 100698, 31561, 88989, 121990, 278500,\n 3602, 109344, 37982, 15279, 116442, 28936, 30880, 87894, 58079, 128661, 126731, 67392, 28051, 146885, 4861, 16216,\n 97344, 42827, 147561, 153948, 22684, 21335, 47685, 1853, 43349, 15185, 59642, 10229, 25520, 187921, 108972, 5579,\n 98037, 24945, 6697, 19193, 63734, 137934, 75056, 89740, 19767, 224268, 56138, 63643, 151661, 39313, 70618, 84031,\n 89723, 84074, 13703, 85626, 35460, 8867, 64845, 3439, 57906, 99776, 63968, 49270, 81130, 34356, 16210, 23547,\n 36446, 34090, 140028, 72439, 2221, 22163, 57058, 363492, 113754, 18913, 95451, 48663, 54464, 54037, 176097, 68425,\n 3023, 34906, 29482, 117389, 341780, 80431, 58330, 16753, 92616, 60907, 94846, 147486, 4498, 48646, 7773, 46801,\n 7778, 18946, 464978, 47558, 33223, 177444, 7328, 15626, 63337, 94700, 11743, 9351, 255024, 39098, 16447, 42647,\n 96230, 39769, 58840, 10068, 63439, 35800, 65843, 58823, 413844, 9156, 51258, 7434, 61791, 85018, 6872, 3692,\n 28096, 7121, 33024, 6009, 75532, 31997, 192535, 9661, 3304, 9547, 14753, 31987, 25314, 55689, 15896, 20430,\n 39472, 31340, 99744, 25398, 115569, 54883, 28719, 205423, 23071, 57855, 64638, 149867, 25671, 82403, 37616, 20668,\n 39989, 77996, 74948, 140555, 175248, 64810, 36515, 46595, 4958, 248773, 24045, 28728, 136673, 168704, 20804, 114833,\n 100325, 27135, 21205, 96151, 153134, 45992, 7093, 13992, 76047, 1980, 19432, 145001, 75159, 87462, 17710, 1013,\n 45556, 34297, 144882, 20648, 26061, 11319, 129567, 108555, 18872, 464580, 33386, 22717, 65948, 167189, 5603, 135042,\n 79542, 8801, 202632, 18114, 91882, 5973, 5239, 67315, 4431, 60916, 47819, 71693, 32597, 32606, 18183, 45072,\n 80329, 76385, 24749, 51305, 40314, 156514, 14693, 130345, 13168, 66214, 18029, 12858, 34801, 27628, 14544, 10823,\n 40522, 40185, 33739, 148694, 23548, 9923, 61012, 28859, 17933, 19442, 34364, 99849, 164107, 141167, 30629, 21054,\n 6744, 36491, 8096, 42474, 41706, 155060, 30650, 10600, 163442, 1143, 96655, 61390, 52359, 7559, 51568, 64256,\n 203854, 4467, 22453, 14504, 436398, 7878, 6980, 8293, 63610, 293747, 16167, 35763, 19627, 147603, 15419, 18032,\n 110744, 51346, 33681, 54571, 40472, 48615, 39073, 21604, 13754, 173027, 92560, 11083, 47299, 63062, 11813, 52007,\n 29883, 9734, 139722, 15953, 1550, 20651, 13616, 49306, 16113, 90089, 92326, 7584, 30712, 72424, 164858, 6831,\n 152871, 55746, 197721, 34167, 196442, 6022, 112107, 55215, 7538, 123381, 4920, 43539, 77165, 8939, 50392, 34192,\n 20225, 79762, 22505, 58667, 40770, 29788, 97180, 82835, 4568, 8579, 13273, 363569, 35898, 49983, 436, 36598,\n 3237, 131691, 62418, 35591, 8101, 4073, 379438, 65218, 76072, 33887, 2968, 27573, 212619, 288680, 68278, 72851,\n 150504, 217896, 6913, 121339, 22017, 35340, 51072, 43616, 75043, 31437, 10833, 81487, 4364, 22968, 41454, 106687,\n 85446, 19863, 109625, 149241, 524, 141850, 214404, 54376, 657, 237023, 9401, 108137, 53800, 32474, 49712, 53334,\n 126876, 27337, 45552, 177696, 8269, 15036, 12097, 42240, 2328, 125374, 119295, 99715, 2500, 19624, 39441, 27220,\n 102691, 60957, 94543, 39101, 18566, 67362, 13975, 78230, 25017, 34017, 239007, 90027, 39351, 41681, 35354, 43822,\n 1043, 916, 58587, 141983, 94818, 38799, 75459, 41114, 67432, 16195, 36606, 59568, 22272, 126769, 31424, 68659,\n 12287, 134302, 257977, 5756, 207285, 95637, 47248, 117689, 19583, 77451, 22373, 12200, 54993, 117118, 34244, 29386,\n 34562, 53819, 71267, 64172, 77665, 49368, 7716, 59301, 25749, 45426, 194789, 17297, 2650, 1766, 32501, 45198,\n 20403, 20984, 6600, 14171, 94604, 19037, 5402, 29896, 9938, 59935, 109708, 88081, 145182, 44844, 39167, 352626,\n 164173, 35374, 45982, 6122, 154, 73419, 220487, 53834, 53601, 17992, 8609, 229321, 5610, 68098, 66815, 71012,\n 95069, 140968, 27396, 8957, 134489, 24656, 86659, 56598, 134852, 17316, 123838, 255436, 6613, 41610, 138033, 81452,\n 32023, 32396, 123687, 63398, 8693, 29712, 30407, 19296, 121188, 3551, 36099, 20032, 111948, 56624, 16547, 27453,\n 35916, 15378, 52039, 56849, 13489, 22214, 73177, 53097, 277349, 2157, 14029, 187886, 10260, 141743, 246460, 91880,\n 50869, 3788, 49486, 133566, 54950, 33120, 129337, 53768, 18333, 9525, 26902, 312251, 10297, 9020, 70759, 16647,\n 112432, 59260, 84609, 9818, 82766, 73569, 468, 46001, 75780, 55028, 52106, 11498, 43645, 108069, 17150, 17753,\n 29417, 16705, 31799, 9606, 289, 122254, 115975, 8620, 6133, 255357, 56908, 14456, 133464, 43554, 79224, 11247,\n 29630, 160, 12756, 25464, 65960, 350428, 62521, 321796, 100359, 67358, 35169, 46172, 113128, 48988, 88868, 31094,\n 33266, 6847, 60887, 98188, 49659, 69117, 92977, 220228, 13947, 80181, 35103, 62170, 97351, 13475, 2440, 199768,\n 19498, 36597, 46971, 25234, 67806, 62881, 84717, 73648, 181966, 10488, 94149, 21550, 26655, 63436, 48375, 14405,\n 165650, 9621, 24439, 28043, 42735, 4490, 29963, 56674, 45373, 1934, 262446, 50855, 67098, 26898, 5261, 52696,\n 40644, 33900, 9440, 180286, 87162, 22940, 19704, 26936, 69769, 10254, 101759, 27406, 12243, 48000, 73926, 113215,\n 54935, 5726, 192787, 4312, 106216, 9366, 11550, 52949, 23457, 212271, 277152, 133895, 108374, 6191, 96477, 29980,\n 218916, 58024, 54696, 40853, 91124, 65894, 91170, 65908, 252552, 6793, 29212, 15389, 44516, 122515, 52617, 35058,\n 9017, 103536, 39510, 49136, 19242, 130652, 662077, 74699, 47024, 31422, 8517, 73351, 24399, 13867, 128360, 4810,\n 4434, 61779, 111983, 61036, 17798, 110240, 59722, 102960, 39688, 10001, 23803, 23039, 176498, 56659, 44814, 134295,\n 17188, 77577, 74466, 226175, 102472, 154333, 63900, 111747, 18062, 41171, 79669, 32773, 408933, 42562, 28931, 30907,\n 107388, 43487, 2946, 240310, 23938, 24354, 319, 184983, 7927, 6488, 1422, 10790, 68809, 68209, 64775, 4361,\n 202, 17123, 59634, 51200, 44391, 18188, 17843, 2619, 74278, 3230, 9540, 47187, 21702, 36274, 56894, 43907,\n 16310, 34790, 16866, 6150, 5561, 13587, 107545, 108873, 126867, 86986, 28640, 33427, 19017, 5762, 80637, 17430,\n 46903, 2047, 131055, 25958, 13558, 5444, 47152, 13900, 44563, 122857, 45348, 70863, 39593, 54332, 38068, 33637,\n 318, 40310, 143467, 18502, 24520, 11377, 62013, 28942, 27246, 28269, 83545, 17999, 59015, 90707, 30065, 15161,\n 34720, 1263, 37008, 2012, 6060, 98575, 92933, 5721, 299, 199555, 24578, 29223, 2985, 743, 115825, 109523,\n 136657, 47454, 26378, 53586, 3733, 174945, 93340, 244456, 5693, 37386, 28782, 89767, 27545, 23573, 18798, 136425,\n 34320, 84778, 20041, 48453, 38215, 7477, 71958, 40621, 8773, 5874, 187927, 105965, 51100, 43533, 18083, 8443,\n 10180, 43597, 2003, 183999, 69689, 12216, 129696, 146188, 62389, 34044, 68410, 12765, 43273, 26949, 266807, 3345,\n 34477, 79197, 5688, 47539, 213110, 21634, 22257, 50092, 32222, 42346, 39530, 63668, 98, 134978, 74022, 5152,\n 59088, 174145, 37220, 9934, 9545, 118937, 5724, 87240, 19875, 15784, 40143, 23263, 87513, 181654, 285152, 37881,\n 263241, 4966, 43934, 10433, 186657, 6470, 74416, 225854, 25908, 142677, 246262, 32280, 6192, 75890, 45546, 143264,\n 135305, 29742, 47013, 77787, 11732, 126658, 8763, 37950, 21806, 57557, 113464, 89465, 108995, 164574, 23894, 22996,\n 23169, 15369, 23117, 17642, 130607, 40503, 36239, 280990, 44666, 9981, 40427, 147487, 26869, 168452, 32886, 32991,\n 46798, 240839, 15111, 70502, 65697, 88548, 44145, 28701, 48767, 31139, 206777, 35659, 181164, 166262, 14554, 171445,\n 31786, 66523, 76607, 17956, 6507, 31279, 90476, 116611, 167918, 6560, 1243, 115324, 80128, 41867, 55897, 187323,\n 37069, 32596, 189444, 145931, 13390, 105530, 65709, 26805, 6999, 55714, 41300, 22915, 68951, 22138, 21120, 22264,\n 10058, 19945, 33635, 56123, 99085, 10032, 5818, 6016, 46649, 57476, 35264, 94413, 112522, 262288, 93686, 83038,\n 14341, 23204, 28807, 66084, 77987, 6101, 126673, 7133, 38126, 5923, 122091, 170240, 97772, 46874, 215746, 43948,\n 41622, 3272, 55596, 8332, 146411, 251315, 13533, 8561, 81521, 115449, 48616, 175175, 2063, 186556, 3036, 134537,\n 75772, 29728, 82360, 22973, 186559, 86348, 89100, 38388, 82297, 45610, 2613, 87082, 9986, 177812, 57884, 23591,\n 47485, 42543, 33582, 44713, 74439, 257444, 252451, 31825, 35631, 38540, 33066, 5147, 13973, 4343, 51830, 70378,\n 22827, 26448, 95560, 36896, 241741, 48067, 203953, 298860, 61620, 20450, 3220, 67272, 6586, 107662, 100160, 108684,\n 6929, 57226, 4762, 7457, 1320, 40404, 77204, 99309, 62750, 208653, 59977, 44000, 74315, 34332, 5819, 172217,\n 64904, 114077, 18147, 84012, 1791, 98456, 90930, 21446, 116669, 103938, 7422, 85140, 59713, 5768, 326211, 16239,\n 75411, 13229, 29398, 10758, 236107, 1539, 112472, 95979, 152154, 151294, 306, 21196, 38146, 10700, 6891, 84282,\n 109646, 56492, 40539, 6589, 119491, 51354, 30685, 140209, 136906, 29622, 73617, 49553, 70525, 51671, 166869, 139616,\n 74395, 37439, 49595, 45678, 11959, 33211, 86560, 52434, 9282, 62690, 112155, 130810, 5243, 108261, 99970, 265613,\n 72551, 80049, 6391, 33365, 90721, 66737, 69872, 87011, 1860, 9032, 112544, 60905, 37371, 89015, 140351, 19076,\n 850, 373531, 2802, 36725, 218795, 72062, 28990, 16550, 24614, 7815, 6187, 26336, 33373, 32162, 42791, 73555,\n 32062, 23386, 10244, 56392, 49442, 27076, 136262, 12412, 14883, 1134, 33675, 97153, 199281, 15608, 100152, 74072,\n 47942, 254301, 36451, 16026, 10687, 65067, 56708, 254030, 30290, 50490, 13864, 57941, 259331, 35588, 23485, 43486,\n 24869, 21620, 92971, 22072, 88645, 1048, 182050, 13343, 32452, 14825, 19509, 3325, 216938, 45740, 99716, 189082,\n 53740, 78245, 25609, 24311, 176777, 47340, 308354, 40669, 66085, 14102, 125339, 9225, 128709, 97207, 1271, 200933,\n 78439, 113451, 88975, 18324, 46521, 11819, 18570, 141756, 72512, 170020, 52754, 63550, 118515, 103073, 93330, 32736,\n 50499, 14722, 31600, 68452, 398867, 29316, 172786, 18417, 104924, 2606, 5670, 84818, 16288, 67106, 59580, 82929,\n 607401, 291, 85829, 359, 15897, 35830, 50696, 65630, 52672, 22115, 356968, 29895, 40837, 231192, 34024, 38957,\n 26722, 406, 23335, 124952, 72068, 68804, 13268, 147101, 164740, 276569, 162596, 66943, 11569, 26654, 66358, 4777,\n 23229, 102127, 5848, 978, 2921, 59666, 5371, 28212, 90108, 42938, 39320, 2499, 4271, 108792, 33510, 125072,\n 71653, 65239, 38250, 66357, 38577, 13964, 86251, 35708, 50755, 36010, 29448, 12209, 3844, 38222, 206337, 100876,\n 67827, 137088, 14167, 252225, 84163, 195270, 1306, 5703, 54198, 779, 46802, 22028, 51124, 86759, 70560, 113164,\n 35685, 162145, 45471, 34561, 422, 2611, 6464, 47486, 19223, 38246, 9191, 18331, 89942, 243642, 212364, 15893,\n 17518, 22617, 6409, 30046, 126182, 59716, 36560, 104428, 18846, 26592, 19458, 50793, 147333, 30826, 1388, 27647,\n 10922, 14495, 33545, 19269, 135828, 39727, 41601, 46931, 233379, 49169, 131130, 182112, 16276, 82381, 118209, 142445,\n 128310, 19672, 28740, 82907, 33436, 3118, 102206, 28723, 24819, 41937, 38854, 5157, 3881, 111491, 1142, 9776,\n 421673, 152241, 29309, 14961, 87854, 6054, 15424, 3796, 82656, 54996, 2108, 55367, 239450, 154525, 9643, 118103,\n 106041, 64601, 68549, 48707, 30266, 25772, 18740, 9462, 229669, 91798, 112152, 191327, 14493, 72828, 8175, 66636,\n 236474, 25817, 87351, 129027, 76653, 20422, 22983, 71240, 27846, 44661, 12399, 46158, 77704, 53101, 35032, 11072,\n 17300, 109294, 33638, 24408, 1895, 11241, 760, 17584, 82479, 125877, 63150, 141075, 34259, 23274, 81698, 15732,\n 43577, 48340, 91584, 14688, 16379, 24481, 150280, 96420, 262050, 48635, 43727, 61819, 56268, 72003, 88178, 17281,\n 79912, 13218, 122519, 125295, 166396, 11811, 2171, 118930, 67746, 17636, 178278, 174656, 95661, 173039, 83845, 79689,\n 17473, 98555, 127696, 203415, 54730, 22925, 232239, 9309, 12136, 175026, 20740, 180188, 10747, 39816, 314017, 266131,\n 10040, 175732, 112550, 220651, 31974, 37393, 888, 23008, 86799, 4303, 64905, 148467, 75337, 251, 3284, 370102,\n 50264, 9835, 5438, 23655, 4481, 29851, 329, 12855, 7162, 64931, 78141, 12804, 42372, 296771, 83547, 18624,\n 34874, 86271, 3360, 48665, 77735, 88767, 11463, 63527, 28889, 22258, 29140, 194315, 113924, 25499, 6406, 31334,\n 1845, 4802, 49184, 43455, 35469, 127594, 92970, 61038, 115005, 38840, 87761, 106838, 8811, 20572, 55637, 11162,\n 96721, 132425, 108925, 2948, 125457, 36356, 3502, 75270, 27622, 127192, 2561, 123095, 49394, 61155, 16897, 110064,\n 9699, 89448, 53356, 19628, 220310, 21622, 83036, 9885, 112214, 6087, 26713, 17901, 161912, 91492, 3440, 68594,\n 9266, 92238, 8087, 6866, 150194, 72175, 80701, 13459, 31836, 43243, 239700, 95846, 44749, 50647, 21945, 230538,\n 120612, 132371, 244604, 5193, 105637, 34661, 41341, 68775, 85393, 1874, 8771, 33718, 49672, 77403, 595452, 99507,\n 6490, 58895, 128742, 7704, 39239, 73217, 43816, 62824, 37804, 199976, 22361, 80005, 87514, 94832, 14089, 4574,\n 139975, 59142, 75523, 100268, 43906, 53442, 15152, 2547, 186002, 17011, 19513, 204282, 3343, 60568, 128318, 119250,\n 4298, 51871, 41336, 71759, 21921, 45074, 98169, 145889, 99427, 11350, 1237, 5520, 28799, 7803, 53702, 21026,\n 136352, 38293, 128690, 12158, 90132, 44600, 10184, 26957, 39459, 126025, 78904, 82999, 59373, 39301, 150198, 120529,\n 153042, 20177, 50089, 14764, 271571, 30530, 123161, 38975, 101562, 22941, 5648, 124654, 109243, 69817, 71675, 49162,\n 106884, 21241, 107795, 30258, 16572, 188262, 141456, 7688, 60718, 8271, 11044, 32440, 104608, 103419, 236109, 93156,\n 43293, 128929, 42107, 67180, 25201, 115254, 185488, 130954, 72813, 167547, 20537, 39969, 38432, 22582, 184022, 1139,\n 27199, 5655, 17767, 97412, 122606, 209377, 27070, 35871, 326617, 188954, 42680, 73512, 80911, 22629, 3011, 95021,\n 315242, 157737, 383, 41821, 41808, 19335, 27950, 15674, 25677, 110950, 35375, 76835, 59108, 57370, 35262, 16569,\n 160415, 37706, 78086, 32041, 49691, 137143, 9782, 172080, 50148, 77917, 6323, 10110, 69172, 17711, 21795, 59511,\n 76184, 135114, 31046, 132319, 59105, 157578, 20549, 80778, 57649, 158421, 65143, 4575, 72235, 21899, 10797, 92745,\n 34035, 106079, 80159, 4508, 78304, 25350, 75457, 46458, 32937, 25623, 47, 8531, 104751, 84953, 8138, 36508,\n 187199, 66310, 115274, 13253, 32461, 38536, 1916, 42007, 187160, 35055, 26325, 84394, 35963, 94216, 45590, 97782\n]\n", "/**\n * Consumes the passed iterator and returns the number of items it contained\n */\nexport default async function length (iterator: AsyncIterable | Iterable): Promise {\n let count = 0\n\n for await (const _ of iterator) { // eslint-disable-line no-unused-vars,@typescript-eslint/no-unused-vars\n count++\n }\n\n return count\n}\n", "import { xor as uint8ArrayXor } from 'uint8arrays/xor'\nimport GENERATED_PREFIXES from './generated-prefix-list.js'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { randomBytes } from '@libp2p/crypto'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { logger } from '@libp2p/logger'\nimport length from 'it-length'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { TABLE_REFRESH_INTERVAL, TABLE_REFRESH_QUERY_TIMEOUT } from '../constants.js'\nimport type { RoutingTable } from './index.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { PeerRouting } from '../peer-routing/index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\n/**\n * Cannot generate random KadIds longer than this + 1\n */\nconst MAX_COMMON_PREFIX_LENGTH = 15\n\nexport interface RoutingTableRefreshInit {\n peerRouting: PeerRouting\n routingTable: RoutingTable\n lan: boolean\n refreshInterval?: number\n refreshQueryTimeout?: number\n}\n\n/**\n * A wrapper around `k-bucket`, to provide easy store and\n * retrieval for peers.\n */\nexport class RoutingTableRefresh {\n private readonly log: Logger\n private readonly peerRouting: PeerRouting\n private readonly routingTable: RoutingTable\n private readonly refreshInterval: number\n private readonly refreshQueryTimeout: number\n private readonly commonPrefixLengthRefreshedAt: Date[]\n private refreshTimeoutId?: NodeJS.Timer\n\n constructor (init: RoutingTableRefreshInit) {\n const { peerRouting, routingTable, refreshInterval, refreshQueryTimeout, lan } = init\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:routing-table:refresh`)\n this.peerRouting = peerRouting\n this.routingTable = routingTable\n this.refreshInterval = refreshInterval ?? TABLE_REFRESH_INTERVAL\n this.refreshQueryTimeout = refreshQueryTimeout ?? TABLE_REFRESH_QUERY_TIMEOUT\n this.commonPrefixLengthRefreshedAt = []\n\n this.refreshTable = this.refreshTable.bind(this)\n }\n\n async start (): Promise {\n this.log(`refreshing routing table every ${this.refreshInterval}ms`)\n this.refreshTable(true)\n }\n\n async stop (): Promise {\n if (this.refreshTimeoutId != null) {\n clearTimeout(this.refreshTimeoutId)\n }\n }\n\n /**\n * To speed lookups, we seed the table with random PeerIds. This means\n * when we are asked to locate a peer on the network, we can find a KadId\n * that is close to the requested peer ID and query that, then network\n * peers will tell us who they know who is close to the fake ID\n */\n refreshTable (force: boolean = false): void {\n this.log('refreshing routing table')\n\n const prefixLength = this._maxCommonPrefix()\n const refreshCpls = this._getTrackedCommonPrefixLengthsForRefresh(prefixLength)\n\n this.log(`max common prefix length ${prefixLength}`)\n this.log(`tracked CPLs [ ${refreshCpls.map(date => date.toISOString()).join(', ')} ]`)\n\n /**\n * If we see a gap at a common prefix length in the Routing table, we ONLY refresh up until\n * the maximum cpl we have in the Routing Table OR (2 * (Cpl+ 1) with the gap), whichever\n * is smaller.\n *\n * This is to prevent refreshes for Cpls that have no peers in the network but happen to be\n * before a very high max Cpl for which we do have peers in the network.\n *\n * The number of 2 * (Cpl + 1) can be proved and a proof would have been written here if\n * the programmer had paid more attention in the Math classes at university.\n *\n * So, please be patient and a doc explaining it will be published soon.\n *\n * https://github.com/libp2p/go-libp2p-kad-dht/commit/2851c88acb0a3f86bcfe3cfd0f4604a03db801d8#diff-ad45f4ba97ffbc4083c2eb87a4420c1157057b233f048030d67c6b551855ccf6R219\n */\n Promise.all(\n refreshCpls.map(async (lastRefresh, index) => {\n try {\n await this._refreshCommonPrefixLength(index, lastRefresh, force)\n\n if (this._numPeersForCpl(prefixLength) === 0) {\n const lastCpl = Math.min(2 * (index + 1), refreshCpls.length - 1)\n\n for (let n = index + 1; n < lastCpl + 1; n++) {\n try {\n await this._refreshCommonPrefixLength(n, lastRefresh, force)\n } catch (err: any) {\n this.log.error(err)\n }\n }\n }\n } catch (err: any) {\n this.log.error(err)\n }\n })\n ).catch(err => {\n this.log.error(err)\n }).then(() => {\n this.refreshTimeoutId = setTimeout(this.refreshTable, this.refreshInterval)\n\n if (this.refreshTimeoutId.unref != null) {\n this.refreshTimeoutId.unref()\n }\n }).catch(err => {\n this.log.error(err)\n })\n }\n\n async _refreshCommonPrefixLength (cpl: number, lastRefresh: Date, force: boolean): Promise {\n if (!force && lastRefresh.getTime() > (Date.now() - this.refreshInterval)) {\n this.log('not running refresh for cpl %s as time since last refresh not above interval', cpl)\n return\n }\n\n // gen a key for the query to refresh the cpl\n const peerId = await this._generateRandomPeerId(cpl)\n\n this.log('starting refreshing cpl %s with key %p (routing table size was %s)', cpl, peerId, this.routingTable.size)\n\n const controller = new TimeoutController(this.refreshQueryTimeout)\n\n try {\n const peers = await length(this.peerRouting.getClosestPeers(peerId.toBytes(), { signal: controller.signal }))\n\n this.log(`found ${peers} peers that were close to imaginary peer %p`, peerId)\n this.log('finished refreshing cpl %s with key %p (routing table size is now %s)', cpl, peerId, this.routingTable.size)\n } finally {\n controller.clear()\n }\n }\n\n _getTrackedCommonPrefixLengthsForRefresh (maxCommonPrefix: number): Date[] {\n if (maxCommonPrefix > MAX_COMMON_PREFIX_LENGTH) {\n maxCommonPrefix = MAX_COMMON_PREFIX_LENGTH\n }\n\n const dates = []\n\n for (let i = 0; i <= maxCommonPrefix; i++) {\n // defaults to the zero value if we haven't refreshed it yet.\n dates[i] = this.commonPrefixLengthRefreshedAt[i] ?? new Date()\n }\n\n return dates\n }\n\n async _generateRandomPeerId (targetCommonPrefixLength: number): Promise {\n if (this.routingTable.kb == null) {\n throw new Error('Routing table not started')\n }\n\n const randomData = randomBytes(2)\n const randomUint16 = (randomData[1] << 8) + randomData[0]\n\n const key = await this._makePeerId(this.routingTable.kb.localNodeId, randomUint16, targetCommonPrefixLength)\n\n return peerIdFromBytes(key)\n }\n\n async _makePeerId (localKadId: Uint8Array, randomPrefix: number, targetCommonPrefixLength: number): Promise {\n if (targetCommonPrefixLength > MAX_COMMON_PREFIX_LENGTH) {\n throw new Error(`Cannot generate peer ID for common prefix length greater than ${MAX_COMMON_PREFIX_LENGTH}`)\n }\n\n const view = new DataView(localKadId.buffer, localKadId.byteOffset, localKadId.byteLength)\n const localPrefix = view.getUint16(0, false)\n\n // For host with ID `L`, an ID `K` belongs to a bucket with ID `B` ONLY IF CommonPrefixLen(L,K) is EXACTLY B.\n // Hence, to achieve a targetPrefix `T`, we must toggle the (T+1)th bit in L & then copy (T+1) bits from L\n // to our randomly generated prefix.\n const toggledLocalPrefix = localPrefix ^ (0x8000 >> targetCommonPrefixLength)\n\n // Combine the toggled local prefix and the random bits at the correct offset\n // such that ONLY the first `targetCommonPrefixLength` bits match the local ID.\n const mask = 65535 << (16 - (targetCommonPrefixLength + 1))\n const targetPrefix = (toggledLocalPrefix & mask) | (randomPrefix & ~mask)\n\n // Convert to a known peer ID.\n const keyPrefix = GENERATED_PREFIXES[targetPrefix]\n\n const keyBuffer = new ArrayBuffer(34)\n const keyView = new DataView(keyBuffer, 0, keyBuffer.byteLength)\n keyView.setUint8(0, sha256.code)\n keyView.setUint8(1, 32)\n keyView.setUint32(2, keyPrefix, false)\n\n return new Uint8Array(keyView.buffer, keyView.byteOffset, keyView.byteLength)\n }\n\n /**\n * returns the maximum common prefix length between any peer in the table\n * and the current peer\n */\n _maxCommonPrefix (): number {\n // xor our KadId with every KadId in the k-bucket tree,\n // return the longest id prefix that is the same\n let prefixLength = 0\n\n for (const length of this._prefixLengths()) {\n if (length > prefixLength) {\n prefixLength = length\n }\n }\n\n return prefixLength\n }\n\n /**\n * Returns the number of peers in the table with a given prefix length\n */\n _numPeersForCpl (prefixLength: number): number {\n let count = 0\n\n for (const length of this._prefixLengths()) {\n if (length === prefixLength) {\n count++\n }\n }\n\n return count\n }\n\n /**\n * Yields the common prefix length of every peer in the table\n */\n * _prefixLengths (): Generator {\n if (this.routingTable.kb == null) {\n return\n }\n\n for (const { id } of this.routingTable.kb.toIterable()) {\n const distance = uint8ArrayXor(this.routingTable.kb.localNodeId, id)\n let leadingZeros = 0\n\n for (const byte of distance) {\n if (byte === 0) {\n leadingZeros++\n } else {\n break\n }\n }\n\n yield leadingZeros\n }\n }\n}\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\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key?: Uint8Array\n value?: Uint8Array\n author?: Uint8Array\n signature?: Uint8Array\n timeReceived?: string\n}\n\nexport namespace Record {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.key != null) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if (obj.value != null) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if (obj.author != null) {\n w.uint32(26)\n w.bytes(obj.author)\n }\n\n if (obj.signature != null) {\n w.uint32(34)\n w.bytes(obj.signature)\n }\n\n if (obj.timeReceived != null) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.bytes()\n break\n case 2:\n obj.value = reader.bytes()\n break\n case 3:\n obj.author = reader.bytes()\n break\n case 4:\n obj.signature = reader.bytes()\n break\n case 5:\n obj.timeReceived = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Record.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Record => {\n return decodeMessage(buf, Record.codec())\n }\n}\n\nexport interface Message {\n type?: Message.MessageType\n clusterLevelRaw?: number\n key?: Uint8Array\n record?: Uint8Array\n closerPeers: Message.Peer[]\n providerPeers: Message.Peer[]\n}\n\nexport namespace Message {\n export enum MessageType {\n PUT_VALUE = 'PUT_VALUE',\n GET_VALUE = 'GET_VALUE',\n ADD_PROVIDER = 'ADD_PROVIDER',\n GET_PROVIDERS = 'GET_PROVIDERS',\n FIND_NODE = 'FIND_NODE',\n PING = 'PING'\n }\n\n enum __MessageTypeValues {\n PUT_VALUE = 0,\n GET_VALUE = 1,\n ADD_PROVIDER = 2,\n GET_PROVIDERS = 3,\n FIND_NODE = 4,\n PING = 5\n }\n\n export namespace MessageType {\n export const codec = (): Codec => {\n return enumeration(__MessageTypeValues)\n }\n }\n\n export enum ConnectionType {\n NOT_CONNECTED = 'NOT_CONNECTED',\n CONNECTED = 'CONNECTED',\n CAN_CONNECT = 'CAN_CONNECT',\n CANNOT_CONNECT = 'CANNOT_CONNECT'\n }\n\n enum __ConnectionTypeValues {\n NOT_CONNECTED = 0,\n CONNECTED = 1,\n CAN_CONNECT = 2,\n CANNOT_CONNECT = 3\n }\n\n export namespace ConnectionType {\n export const codec = (): Codec => {\n return enumeration(__ConnectionTypeValues)\n }\n }\n\n export interface Peer {\n id?: Uint8Array\n addrs: Uint8Array[]\n connection?: Message.ConnectionType\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.id != null) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (obj.connection != null) {\n w.uint32(24)\n Message.ConnectionType.codec().encode(obj.connection, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addrs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs.push(reader.bytes())\n break\n case 3:\n obj.connection = Message.ConnectionType.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.type != null) {\n w.uint32(8)\n Message.MessageType.codec().encode(obj.type, w)\n }\n\n if (obj.clusterLevelRaw != null) {\n w.uint32(80)\n w.int32(obj.clusterLevelRaw)\n }\n\n if (obj.key != null) {\n w.uint32(18)\n w.bytes(obj.key)\n }\n\n if (obj.record != null) {\n w.uint32(26)\n w.bytes(obj.record)\n }\n\n if (obj.closerPeers != null) {\n for (const value of obj.closerPeers) {\n w.uint32(66)\n Message.Peer.codec().encode(value, w)\n }\n }\n\n if (obj.providerPeers != null) {\n for (const value of obj.providerPeers) {\n w.uint32(74)\n Message.Peer.codec().encode(value, w)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n closerPeers: [],\n providerPeers: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = Message.MessageType.codec().decode(reader)\n break\n case 10:\n obj.clusterLevelRaw = reader.int32()\n break\n case 2:\n obj.key = reader.bytes()\n break\n case 3:\n obj.record = reader.bytes()\n break\n case 8:\n obj.closerPeers.push(Message.Peer.codec().decode(reader, reader.uint32()))\n break\n case 9:\n obj.providerPeers.push(Message.Peer.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Message.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Message => {\n return decodeMessage(buf, Message.codec())\n }\n}\n", "import { peerIdFromBytes } from '@libp2p/peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { Message as PBMessage } from './dht.js'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MESSAGE_TYPE = PBMessage.MessageType\nexport const CONNECTION_TYPE = PBMessage.ConnectionType\nexport const MESSAGE_TYPE_LOOKUP = Object.keys(MESSAGE_TYPE)\n\ninterface PBPeer {\n id: Uint8Array\n addrs: Uint8Array[]\n connection: PBMessage.ConnectionType\n}\n\n/**\n * Represents a single DHT control message.\n */\nexport class Message {\n public type: PBMessage.MessageType\n public key: Uint8Array\n private clusterLevelRaw: number\n public closerPeers: PeerInfo[]\n public providerPeers: PeerInfo[]\n public record?: Libp2pRecord\n\n constructor (type: PBMessage.MessageType, key: Uint8Array, level: number) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('Key must be a Uint8Array')\n }\n\n this.type = type\n this.key = key\n this.clusterLevelRaw = level\n this.closerPeers = []\n this.providerPeers = []\n this.record = undefined\n }\n\n /**\n * @type {number}\n */\n get clusterLevel (): number {\n const level = this.clusterLevelRaw - 1\n if (level < 0) {\n return 0\n }\n\n return level\n }\n\n set clusterLevel (level) {\n this.clusterLevelRaw = level\n }\n\n /**\n * Encode into protobuf\n */\n serialize (): Uint8Array {\n return PBMessage.encode({\n key: this.key,\n type: this.type,\n clusterLevelRaw: this.clusterLevelRaw,\n closerPeers: this.closerPeers.map(toPbPeer),\n providerPeers: this.providerPeers.map(toPbPeer),\n record: this.record == null ? undefined : this.record.serialize().subarray()\n })\n }\n\n /**\n * Decode from protobuf\n */\n static deserialize (raw: Uint8ArrayList | Uint8Array): Message {\n const dec = PBMessage.decode(raw)\n\n const msg = new Message(dec.type ?? PBMessage.MessageType.PUT_VALUE, dec.key ?? Uint8Array.from([]), dec.clusterLevelRaw ?? 0)\n msg.closerPeers = dec.closerPeers.map(fromPbPeer)\n msg.providerPeers = dec.providerPeers.map(fromPbPeer)\n\n if (dec.record?.length != null) {\n msg.record = Libp2pRecord.deserialize(dec.record)\n }\n\n return msg\n }\n}\n\nfunction toPbPeer (peer: PeerInfo): PBPeer {\n const output: PBPeer = {\n id: peer.id.toBytes(),\n addrs: (peer.multiaddrs ?? []).map((m) => m.bytes),\n connection: CONNECTION_TYPE.CONNECTED\n }\n\n return output\n}\n\nfunction fromPbPeer (peer: PBMessage.Peer): PeerInfo {\n if (peer.id == null) {\n throw new Error('Invalid peer in message')\n }\n\n return {\n id: peerIdFromBytes(peer.id),\n multiaddrs: (peer.addrs ?? []).map((a) => multiaddr(a)),\n protocols: []\n }\n}\n", "import { MESSAGE_TYPE_LOOKUP } from '../message/index.js'\nimport type { Message } from '../message/dht.js'\nimport type { SendingQueryEvent, PeerResponseEvent, DialingPeerEvent, AddingPeerEvent, ValueEvent, ProviderEvent, QueryErrorEvent, FinalPeerEvent } from '@libp2p/interface-dht'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Libp2pRecord } from '@libp2p/record'\n\nexport interface QueryEventFields {\n to: PeerId\n type: Message.MessageType\n}\n\nexport function sendingQueryEvent (fields: QueryEventFields): SendingQueryEvent {\n return {\n ...fields,\n name: 'SENDING_QUERY',\n type: 0,\n messageName: fields.type,\n messageType: MESSAGE_TYPE_LOOKUP.indexOf(fields.type.toString())\n }\n}\n\nexport interface PeerResponseEventField {\n from: PeerId\n messageType: Message.MessageType\n closer?: PeerInfo[]\n providers?: PeerInfo[]\n record?: Libp2pRecord\n}\n\nexport function peerResponseEvent (fields: PeerResponseEventField): PeerResponseEvent {\n return {\n ...fields,\n name: 'PEER_RESPONSE',\n type: 1,\n messageName: fields.messageType,\n closer: (fields.closer != null) ? fields.closer : [],\n providers: (fields.providers != null) ? fields.providers : []\n }\n}\n\nexport interface FinalPeerEventFields {\n from: PeerId\n peer: PeerInfo\n}\n\nexport function finalPeerEvent (fields: FinalPeerEventFields): FinalPeerEvent {\n return {\n ...fields,\n name: 'FINAL_PEER',\n type: 2\n }\n}\n\nexport interface ErrorEventFields {\n from: PeerId\n error: Error\n}\n\nexport function queryErrorEvent (fields: ErrorEventFields): QueryErrorEvent {\n return {\n ...fields,\n name: 'QUERY_ERROR',\n type: 3\n }\n}\n\nexport interface ProviderEventFields {\n from: PeerId\n providers: PeerInfo[]\n}\n\nexport function providerEvent (fields: ProviderEventFields): ProviderEvent {\n return {\n ...fields,\n name: 'PROVIDER',\n type: 4\n }\n}\n\nexport interface ValueEventFields {\n from: PeerId\n value: Uint8Array\n}\n\nexport function valueEvent (fields: ValueEventFields): ValueEvent {\n return {\n ...fields,\n name: 'VALUE',\n type: 5\n }\n}\n\nexport interface PeerEventFields {\n peer: PeerId\n}\n\nexport function addingPeerEvent (fields: PeerEventFields): AddingPeerEvent {\n return {\n ...fields,\n name: 'ADDING_PEER',\n type: 6\n }\n}\n\nexport interface DialingPeerEventFields {\n peer: PeerId\n}\n\nexport function dialingPeerEvent (fields: DialingPeerEventFields): DialingPeerEvent {\n return {\n ...fields,\n name: 'DIALING_PEER',\n type: 7\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { pipe } from 'it-pipe'\nimport * as lp from 'it-length-prefixed'\nimport drain from 'it-drain'\nimport first from 'it-first'\nimport { Message } from './message/index.js'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport {\n dialingPeerEvent,\n sendingQueryEvent,\n peerResponseEvent,\n queryErrorEvent\n} from './query/events.js'\nimport { logger } from '@libp2p/logger'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Logger } from '@libp2p/logger'\nimport type { Duplex } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { abortableDuplex } from 'abortable-iterator'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { KadDHTComponents } from './index.js'\nimport type { QueryEvent } from '@libp2p/interface-dht'\n\nexport interface NetworkInit {\n protocol: string\n lan: boolean\n}\n\ninterface NetworkEvents {\n 'peer': CustomEvent\n}\n\n/**\n * Handle network operations for the dht\n */\nexport class Network extends EventEmitter implements Startable {\n private readonly log: Logger\n private readonly protocol: string\n private running: boolean\n private readonly components: KadDHTComponents\n\n /**\n * Create a new network\n */\n constructor (components: KadDHTComponents, init: NetworkInit) {\n super()\n\n const { protocol, lan } = init\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:network`)\n this.running = false\n this.protocol = protocol\n }\n\n /**\n * Start the network\n */\n async start (): Promise {\n if (this.running) {\n return\n }\n\n this.running = true\n }\n\n /**\n * Stop all network activity\n */\n async stop (): Promise {\n this.running = false\n }\n\n /**\n * Is the network online?\n */\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * Send a request and record RTT for latency measurements\n */\n async * sendRequest (to: PeerId, msg: Message, options: AbortOptions = {}): AsyncGenerator {\n if (!this.running) {\n return\n }\n\n this.log('sending %s to %p', msg.type, to)\n yield dialingPeerEvent({ peer: to })\n yield sendingQueryEvent({ to, type: msg.type })\n\n let stream: Stream | undefined\n\n try {\n const connection = await this.components.connectionManager.openConnection(to, options)\n const stream = await connection.newStream(this.protocol, options)\n\n const response = await this._writeReadMessage(stream, msg.serialize(), options)\n\n yield peerResponseEvent({\n from: to,\n messageType: response.type,\n closer: response.closerPeers,\n providers: response.providerPeers,\n record: response.record\n })\n } catch (err: any) {\n yield queryErrorEvent({ from: to, error: err })\n } finally {\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Sends a message without expecting an answer\n */\n async * sendMessage (to: PeerId, msg: Message, options: AbortOptions = {}): AsyncGenerator {\n if (!this.running) {\n return\n }\n\n this.log('sending %s to %p', msg.type, to)\n yield dialingPeerEvent({ peer: to })\n yield sendingQueryEvent({ to, type: msg.type })\n\n let stream: Stream | undefined\n\n try {\n const connection = await this.components.connectionManager.openConnection(to, options)\n const stream = await connection.newStream(this.protocol, options)\n\n await this._writeMessage(stream, msg.serialize(), options)\n\n yield peerResponseEvent({ from: to, messageType: msg.type })\n } catch (err: any) {\n yield queryErrorEvent({ from: to, error: err })\n } finally {\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Write a message to the given stream\n */\n async _writeMessage (stream: Duplex, msg: Uint8Array | Uint8ArrayList, options: AbortOptions): Promise {\n if (options.signal != null) {\n stream = abortableDuplex(stream, options.signal)\n }\n\n await pipe(\n [msg],\n lp.encode(),\n stream,\n drain\n )\n }\n\n /**\n * Write a message and read its response.\n * If no response is received after the specified timeout\n * this will error out.\n */\n async _writeReadMessage (stream: Duplex, msg: Uint8Array | Uint8ArrayList, options: AbortOptions): Promise {\n if (options.signal != null) {\n stream = abortableDuplex(stream, options.signal)\n }\n\n const res = await pipe(\n [msg],\n lp.encode(),\n stream,\n lp.decode(),\n async source => {\n const buf = await first(source)\n\n if (buf != null) {\n return buf\n }\n\n throw new CodeError('No message received', 'ERR_NO_MESSAGE_RECEIVED')\n }\n )\n\n const message = Message.deserialize(res)\n\n // tell any listeners about new peers we've seen\n message.closerPeers.forEach(peerData => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerData\n }))\n })\n message.providerPeers.forEach(peerData => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerData\n }))\n })\n\n return message\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Libp2pRecord } from './index.js'\nimport type { Validators } from '@libp2p/interface-dht'\n\n/**\n * Checks a record and ensures it is still valid.\n * It runs the needed validators.\n * If verification fails the returned Promise will reject with the error.\n */\nexport async function verifyRecord (validators: Validators, record: Libp2pRecord): Promise {\n const key = record.key\n const keyString = uint8ArrayToString(key)\n const parts = keyString.split('/')\n\n if (parts.length < 3) {\n // No validator available\n return\n }\n\n const validator = validators[parts[1].toString()]\n\n if (validator == null) {\n const errMsg = 'Invalid record keytype'\n\n throw new CodeError(errMsg, 'ERR_INVALID_RECORD_KEY_TYPE')\n }\n\n await validator(key, record.value)\n}\n\n/**\n * Validator for public key records.\n * Verifies that the passed in record value is the PublicKey\n * that matches the passed in key.\n * If validation fails the returned Promise will reject with the error.\n *\n * @param {Uint8Array} key - A valid key is of the form `'/pk/'`\n * @param {Uint8Array} publicKey - The public key to validate against (protobuf encoded).\n */\nconst validatePublicKeyRecord = async (key: Uint8Array, publicKey: Uint8Array): Promise => {\n if (!(key instanceof Uint8Array)) {\n throw new CodeError('\"key\" must be a Uint8Array', 'ERR_INVALID_RECORD_KEY_NOT_BUFFER')\n }\n\n if (key.byteLength < 5) {\n throw new CodeError('invalid public key record', 'ERR_INVALID_RECORD_KEY_TOO_SHORT')\n }\n\n const prefix = uint8ArrayToString(key.subarray(0, 4))\n\n if (prefix !== '/pk/') {\n throw new CodeError('key was not prefixed with /pk/', 'ERR_INVALID_RECORD_KEY_BAD_PREFIX')\n }\n\n const keyhash = key.slice(4)\n\n const publicKeyHash = await sha256.digest(publicKey)\n\n if (!uint8ArrayEquals(keyhash, publicKeyHash.bytes)) {\n throw new CodeError('public key does not match passed in key', 'ERR_INVALID_RECORD_HASH_MISMATCH')\n }\n}\n\nexport const validators: Validators = {\n pk: validatePublicKeyRecord\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Selectors } from '@libp2p/interface-dht'\n\n/**\n * Select the best record out of the given records\n */\nexport function bestRecord (selectors: Selectors, k: Uint8Array, records: Uint8Array[]): number {\n if (records.length === 0) {\n const errMsg = 'No records given'\n\n throw new CodeError(errMsg, 'ERR_NO_RECORDS_RECEIVED')\n }\n\n const kStr = uint8ArrayToString(k)\n const parts = kStr.split('/')\n\n if (parts.length < 3) {\n const errMsg = 'Record key does not have a selector function'\n\n throw new CodeError(errMsg, 'ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY')\n }\n\n const selector = selectors[parts[1].toString()]\n\n if (selector == null) {\n const errMsg = `Unrecognized key prefix: ${parts[1]}`\n\n throw new CodeError(errMsg, 'ERR_UNRECOGNIZED_KEY_PREFIX')\n }\n\n if (records.length === 1) {\n return 0\n }\n\n return selector(k, records)\n}\n\n/**\n * Best record selector, for public key records.\n * Simply returns the first record, as all valid public key\n * records are equal\n */\nfunction publickKey (k: Uint8Array, records: Uint8Array[]): number {\n return 0\n}\n\nexport const selectors: Selectors = {\n pk: publickKey\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { verifyRecord } from '@libp2p/record/validators'\nimport { bestRecord } from '@libp2p/record/selectors'\nimport parallel from 'it-parallel'\nimport map from 'it-map'\nimport {\n valueEvent,\n queryErrorEvent\n} from '../query/events.js'\nimport { Message, MESSAGE_TYPE } from '../message/index.js'\nimport { pipe } from 'it-pipe'\nimport {\n ALPHA\n} from '../constants.js'\nimport { createPutRecord, convertBuffer, bufferToRecordKey } from '../utils.js'\nimport { logger } from '@libp2p/logger'\nimport type { Validators, Selectors, ValueEvent, QueryOptions, QueryEvent } from '@libp2p/interface-dht'\nimport type { PeerRouting } from '../peer-routing/index.js'\nimport type { QueryManager } from '../query/manager.js'\nimport type { RoutingTable } from '../routing-table/index.js'\nimport type { Network } from '../network.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { QueryFunc } from '../query/types.js'\nimport type { KadDHTComponents } from '../index.js'\n\nexport interface ContentFetchingInit {\n validators: Validators\n selectors: Selectors\n peerRouting: PeerRouting\n queryManager: QueryManager\n routingTable: RoutingTable\n network: Network\n lan: boolean\n}\n\nexport class ContentFetching {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly validators: Validators\n private readonly selectors: Selectors\n private readonly peerRouting: PeerRouting\n private readonly queryManager: QueryManager\n private readonly routingTable: RoutingTable\n private readonly network: Network\n\n constructor (components: KadDHTComponents, init: ContentFetchingInit) {\n const { validators, selectors, peerRouting, queryManager, routingTable, network, lan } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:content-fetching`)\n this.validators = validators\n this.selectors = selectors\n this.peerRouting = peerRouting\n this.queryManager = queryManager\n this.routingTable = routingTable\n this.network = network\n }\n\n async putLocal (key: Uint8Array, rec: Uint8Array): Promise {\n const dsKey = bufferToRecordKey(key)\n await this.components.datastore.put(dsKey, rec)\n }\n\n /**\n * Attempt to retrieve the value for the given key from\n * the local datastore\n */\n async getLocal (key: Uint8Array): Promise {\n this.log('getLocal %b', key)\n\n const dsKey = bufferToRecordKey(key)\n\n this.log('fetching record for key %k', dsKey)\n\n const raw = await this.components.datastore.get(dsKey)\n this.log('found %k in local datastore', dsKey)\n\n const rec = Libp2pRecord.deserialize(raw)\n\n await verifyRecord(this.validators, rec)\n\n return rec\n }\n\n /**\n * Send the best record found to any peers that have an out of date record\n */\n async * sendCorrectionRecord (key: Uint8Array, vals: ValueEvent[], best: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n this.log('sendCorrection for %b', key)\n const fixupRec = createPutRecord(key, best)\n\n for (const { value, from } of vals) {\n // no need to do anything\n if (uint8ArrayEquals(value, best)) {\n this.log('record was ok')\n continue\n }\n\n // correct ourself\n if (this.components.peerId.equals(from)) {\n try {\n const dsKey = bufferToRecordKey(key)\n this.log(`Storing corrected record for key ${dsKey.toString()}`)\n await this.components.datastore.put(dsKey, fixupRec.subarray())\n } catch (err: any) {\n this.log.error('Failed error correcting self', err)\n }\n\n continue\n }\n\n // send correction\n let sentCorrection = false\n const request = new Message(MESSAGE_TYPE.PUT_VALUE, key, 0)\n request.record = Libp2pRecord.deserialize(fixupRec)\n\n for await (const event of this.network.sendRequest(from, request, options)) {\n if (event.name === 'PEER_RESPONSE' && (event.record != null) && uint8ArrayEquals(event.record.value, Libp2pRecord.deserialize(fixupRec).value)) {\n sentCorrection = true\n }\n\n yield event\n }\n\n if (!sentCorrection) {\n yield queryErrorEvent({ from, error: new CodeError('value not put correctly', 'ERR_PUT_VALUE_INVALID') })\n }\n\n this.log.error('Failed error correcting entry')\n }\n }\n\n /**\n * Store the given key/value pair in the DHT\n */\n async * put (key: Uint8Array, value: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n this.log('put key %b value %b', key, value)\n\n // create record in the dht format\n const record = createPutRecord(key, value)\n\n // store the record locally\n const dsKey = bufferToRecordKey(key)\n this.log(`storing record for key ${dsKey.toString()}`)\n await this.components.datastore.put(dsKey, record.subarray())\n\n // put record to the closest peers\n yield * pipe(\n this.peerRouting.getClosestPeers(key, { signal: options.signal }),\n (source) => map(source, (event) => {\n return async () => {\n if (event.name !== 'FINAL_PEER') {\n return [event]\n }\n\n const events = []\n\n const msg = new Message(MESSAGE_TYPE.PUT_VALUE, key, 0)\n msg.record = Libp2pRecord.deserialize(record)\n\n this.log('send put to %p', event.peer.id)\n for await (const putEvent of this.network.sendRequest(event.peer.id, msg, options)) {\n events.push(putEvent)\n\n if (putEvent.name !== 'PEER_RESPONSE') {\n continue\n }\n\n if (!(putEvent.record != null && uint8ArrayEquals(putEvent.record.value, Libp2pRecord.deserialize(record).value))) {\n events.push(queryErrorEvent({ from: event.peer.id, error: new CodeError('value not put correctly', 'ERR_PUT_VALUE_INVALID') }))\n }\n }\n\n return events\n }\n }),\n (source) => parallel(source, {\n ordered: false,\n concurrency: ALPHA\n }),\n async function * (source) {\n for await (const events of source) {\n yield * events\n }\n }\n )\n }\n\n /**\n * Get the value to the given key\n */\n async * get (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n this.log('get %b', key)\n\n const vals: ValueEvent[] = []\n\n for await (const event of this.getMany(key, options)) {\n if (event.name === 'VALUE') {\n vals.push(event)\n }\n\n yield event\n }\n\n if (vals.length === 0) {\n return\n }\n\n const records = vals.map((v) => v.value)\n let i = 0\n\n try {\n i = bestRecord(this.selectors, key, records)\n } catch (err: any) {\n // Assume the first record if no selector available\n if (err.code !== 'ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY') {\n throw err\n }\n }\n\n const best = records[i]\n this.log('GetValue %b %b', key, best)\n\n if (best == null) {\n throw new CodeError('best value was not found', 'ERR_NOT_FOUND')\n }\n\n yield * this.sendCorrectionRecord(key, vals, best, options)\n\n yield vals[i]\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n this.log('getMany values for %b', key)\n\n try {\n const localRec = await this.getLocal(key)\n\n yield valueEvent({\n value: localRec.value,\n from: this.components.peerId\n })\n } catch (err: any) {\n this.log('error getting local value for %b', key, err)\n }\n\n const id = await convertBuffer(key)\n const rtp = this.routingTable.closestPeers(id)\n\n this.log('found %d peers in routing table', rtp.length)\n\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n const getValueQuery: QueryFunc = async function * ({ peer, signal }) {\n for await (const event of self.peerRouting.getValueOrPeers(peer, key, { signal })) {\n yield event\n\n if (event.name === 'PEER_RESPONSE' && (event.record != null)) {\n yield valueEvent({ from: peer, value: event.record.value })\n }\n }\n }\n\n // we have peers, lets send the actual query to them\n yield * this.queryManager.run(key, rtp, getValueQuery, options)\n }\n}\n", "import { Message, MESSAGE_TYPE } from '../message/index.js'\nimport parallel from 'it-parallel'\nimport map from 'it-map'\nimport { convertBuffer } from '../utils.js'\nimport { ALPHA } from '../constants.js'\nimport { pipe } from 'it-pipe'\nimport {\n queryErrorEvent,\n peerResponseEvent,\n providerEvent\n} from '../query/events.js'\nimport { logger } from '@libp2p/logger'\nimport type { PeerResponseEvent, ProviderEvent, QueryEvent, QueryOptions } from '@libp2p/interface-dht'\nimport type { PeerRouting } from '../peer-routing/index.js'\nimport type { QueryManager } from '../query/manager.js'\nimport type { RoutingTable } from '../routing-table/index.js'\nimport type { Network } from '../network.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { Providers } from '../providers.js'\nimport type { QueryFunc } from '../query/types.js'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { KadDHTComponents } from '../index.js'\n\nexport interface ContentRoutingInit {\n network: Network\n peerRouting: PeerRouting\n queryManager: QueryManager\n routingTable: RoutingTable\n providers: Providers\n lan: boolean\n}\n\nexport class ContentRouting {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly network: Network\n private readonly peerRouting: PeerRouting\n private readonly queryManager: QueryManager\n private readonly routingTable: RoutingTable\n private readonly providers: Providers\n\n constructor (components: KadDHTComponents, init: ContentRoutingInit) {\n const { network, peerRouting, queryManager, routingTable, providers, lan } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:content-routing`)\n this.network = network\n this.peerRouting = peerRouting\n this.queryManager = queryManager\n this.routingTable = routingTable\n this.providers = providers\n }\n\n /**\n * Announce to the network that we can provide the value for a given key and\n * are contactable on the given multiaddrs\n */\n async * provide (key: CID, multiaddrs: Multiaddr[], options: AbortOptions = {}): AsyncGenerator {\n this.log('provide %s', key)\n\n // Add peer as provider\n await this.providers.addProvider(key, this.components.peerId)\n\n const msg = new Message(MESSAGE_TYPE.ADD_PROVIDER, key.multihash.bytes, 0)\n msg.providerPeers = [{\n id: this.components.peerId,\n multiaddrs,\n protocols: []\n }]\n\n let sent = 0\n\n const maybeNotifyPeer = (event: QueryEvent) => {\n return async () => {\n if (event.name !== 'FINAL_PEER') {\n return [event]\n }\n\n const events = []\n\n this.log('putProvider %s to %p', key, event.peer.id)\n\n try {\n this.log('sending provider record for %s to %p', key, event.peer.id)\n\n for await (const sendEvent of this.network.sendMessage(event.peer.id, msg, options)) {\n if (sendEvent.name === 'PEER_RESPONSE') {\n this.log('sent provider record for %s to %p', key, event.peer.id)\n sent++\n }\n\n events.push(sendEvent)\n }\n } catch (err: any) {\n this.log.error('error sending provide record to peer %p', event.peer.id, err)\n events.push(queryErrorEvent({ from: event.peer.id, error: err }))\n }\n\n return events\n }\n }\n\n // Notify closest peers\n yield * pipe(\n this.peerRouting.getClosestPeers(key.multihash.bytes, options),\n (source) => map(source, (event) => maybeNotifyPeer(event)),\n (source) => parallel(source, {\n ordered: false,\n concurrency: ALPHA\n }),\n async function * (source) {\n for await (const events of source) {\n yield * events\n }\n }\n )\n\n this.log('sent provider records to %d peers', sent)\n }\n\n /**\n * Search the dht for up to `K` providers of the given CID.\n */\n async * findProviders (key: CID, options: QueryOptions): AsyncGenerator {\n const toFind = this.routingTable.kBucketSize\n const target = key.multihash.bytes\n const id = await convertBuffer(target)\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n this.log('findProviders %c', key)\n\n const provs = await this.providers.getProviders(key)\n\n // yield values if we have some, also slice because maybe we got lucky and already have too many?\n if (provs.length > 0) {\n const providers: PeerInfo[] = []\n\n for (const peerId of provs.slice(0, toFind)) {\n providers.push({\n id: peerId,\n multiaddrs: ((await this.components.peerStore.addressBook.get(peerId)) ?? []).map(address => address.multiaddr),\n protocols: []\n })\n }\n\n yield peerResponseEvent({ from: this.components.peerId, messageType: MESSAGE_TYPE.GET_PROVIDERS, providers })\n yield providerEvent({ from: this.components.peerId, providers })\n }\n\n // All done\n if (provs.length >= toFind) {\n return\n }\n\n /**\n * The query function to use on this particular disjoint path\n */\n const findProvidersQuery: QueryFunc = async function * ({ peer, signal }) {\n const request = new Message(MESSAGE_TYPE.GET_PROVIDERS, target, 0)\n\n yield * self.network.sendRequest(peer, request, { signal })\n }\n\n const providers = new Set(provs.map(p => p.toString()))\n\n for await (const event of this.queryManager.run(target, this.routingTable.closestPeers(id), findProvidersQuery, options)) {\n yield event\n\n if (event.name === 'PEER_RESPONSE') {\n this.log('Found %d provider entries for %c and %d closer peers', event.providers.length, key, event.closer.length)\n\n const newProviders = []\n\n for (const peer of event.providers) {\n if (providers.has(peer.id.toString())) {\n continue\n }\n\n providers.add(peer.id.toString())\n newProviders.push(peer)\n }\n\n if (newProviders.length > 0) {\n yield providerEvent({ from: event.from, providers: newProviders })\n }\n\n if (providers.size === toFind) {\n return\n }\n }\n }\n }\n}\n", "/**\n * Can be used with Array.sort to sort and array with Uint8Array entries\n */\nexport function compare (a: Uint8Array, b: Uint8Array): number {\n if (globalThis.Buffer != null) {\n return globalThis.Buffer.compare(a, b)\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] < b[i]) {\n return -1\n }\n\n if (a[i] > b[i]) {\n return 1\n }\n }\n\n if (a.byteLength > b.byteLength) {\n return 1\n }\n\n if (a.byteLength < b.byteLength) {\n return -1\n }\n\n return 0\n}\n", "import * as utils from '../utils.js'\nimport { compare as uint8ArrayCompare } from 'uint8arrays/compare'\nimport { xor as uint8ArrayXor } from 'uint8arrays/xor'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\ninterface PeerDistance {\n peerId: PeerId\n distance: Uint8Array\n}\n\n/**\n * Maintains a list of peerIds sorted by distance from a DHT key.\n */\nexport class PeerDistanceList {\n /**\n * The DHT key from which distance is calculated\n */\n private readonly originDhtKey: Uint8Array\n\n /**\n * The maximum size of the list\n */\n private readonly capacity: number\n\n private peerDistances: PeerDistance[]\n\n constructor (originDhtKey: Uint8Array, capacity: number) {\n this.originDhtKey = originDhtKey\n this.capacity = capacity\n this.peerDistances = []\n }\n\n /**\n * The length of the list\n */\n get length (): number {\n return this.peerDistances.length\n }\n\n /**\n * The peerIds in the list, in order of distance from the origin key\n */\n get peers (): PeerId[] {\n return this.peerDistances.map(pd => pd.peerId)\n }\n\n /**\n * Add a peerId to the list.\n */\n async add (peerId: PeerId): Promise {\n if (this.peerDistances.find(pd => pd.peerId.equals(peerId)) != null) {\n return\n }\n\n const dhtKey = await utils.convertPeerId(peerId)\n const el = {\n peerId,\n distance: uint8ArrayXor(this.originDhtKey, dhtKey)\n }\n\n this.peerDistances.push(el)\n this.peerDistances.sort((a, b) => uint8ArrayCompare(a.distance, b.distance))\n this.peerDistances = this.peerDistances.slice(0, this.capacity)\n }\n\n /**\n * Indicates whether any of the peerIds passed as a parameter are closer\n * to the origin key than the furthest peerId in the PeerDistanceList.\n */\n async anyCloser (peerIds: PeerId[]): Promise {\n if (peerIds.length === 0) {\n return false\n }\n\n if (this.length === 0) {\n return true\n }\n\n const dhtKeys = await Promise.all(peerIds.map(utils.convertPeerId))\n const furthestDistance = this.peerDistances[this.peerDistances.length - 1].distance\n\n for (const dhtKey of dhtKeys) {\n const keyDistance = uint8ArrayXor(this.originDhtKey, dhtKey)\n\n if (uint8ArrayCompare(keyDistance, furthestDistance) < 0) {\n return true\n }\n }\n\n return false\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { verifyRecord } from '@libp2p/record/validators'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { Message, MESSAGE_TYPE } from '../message/index.js'\nimport * as utils from '../utils.js'\nimport {\n queryErrorEvent,\n finalPeerEvent,\n valueEvent\n} from '../query/events.js'\nimport { PeerDistanceList } from '../peer-list/peer-distance-list.js'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { logger } from '@libp2p/logger'\nimport { keys } from '@libp2p/crypto'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { DHTRecord, DialingPeerEvent, FinalPeerEvent, QueryEvent, QueryOptions, Validators } from '@libp2p/interface-dht'\nimport type { RoutingTable } from '../routing-table/index.js'\nimport type { QueryManager } from '../query/manager.js'\nimport type { Network } from '../network.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { QueryFunc } from '../query/types.js'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { KadDHTComponents } from '../index.js'\n\nexport interface PeerRoutingInit {\n routingTable: RoutingTable\n network: Network\n validators: Validators\n queryManager: QueryManager\n lan: boolean\n}\n\nexport class PeerRouting {\n private readonly components: KadDHTComponents\n private readonly log: Logger\n private readonly routingTable: RoutingTable\n private readonly network: Network\n private readonly validators: Validators\n private readonly queryManager: QueryManager\n\n constructor (components: KadDHTComponents, init: PeerRoutingInit) {\n const { routingTable, network, validators, queryManager, lan } = init\n\n this.components = components\n this.routingTable = routingTable\n this.network = network\n this.validators = validators\n this.queryManager = queryManager\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:peer-routing`)\n }\n\n /**\n * Look if we are connected to a peer with the given id.\n * Returns its id and addresses, if found, otherwise `undefined`.\n */\n async findPeerLocal (peer: PeerId): Promise {\n let peerData\n const p = await this.routingTable.find(peer)\n\n if (p != null) {\n this.log('findPeerLocal found %p in routing table', peer)\n\n try {\n peerData = await this.components.peerStore.get(p)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n if (peerData == null) {\n try {\n peerData = await this.components.peerStore.get(peer)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n if (peerData != null) {\n this.log('findPeerLocal found %p in peer store', peer)\n\n return {\n id: peerData.id,\n multiaddrs: peerData.addresses.map((address) => address.multiaddr),\n protocols: []\n }\n }\n\n return undefined\n }\n\n /**\n * Get a value via rpc call for the given parameters\n */\n async * _getValueSingle (peer: PeerId, key: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n const msg = new Message(MESSAGE_TYPE.GET_VALUE, key, 0)\n yield * this.network.sendRequest(peer, msg, options)\n }\n\n /**\n * Get the public key directly from a node\n */\n async * getPublicKeyFromNode (peer: PeerId, options: AbortOptions = {}): AsyncGenerator {\n const pkKey = utils.keyForPublicKey(peer)\n\n for await (const event of this._getValueSingle(peer, pkKey, options)) {\n yield event\n\n if (event.name === 'PEER_RESPONSE' && event.record != null) {\n const recPeer = await peerIdFromKeys(keys.marshalPublicKey({ bytes: event.record.value }))\n\n // compare hashes of the pub key\n if (!recPeer.equals(peer)) {\n throw new CodeError('public key does not match id', 'ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID')\n }\n\n if (recPeer.publicKey == null) {\n throw new CodeError('public key missing', 'ERR_PUBLIC_KEY_MISSING')\n }\n\n yield valueEvent({ from: peer, value: recPeer.publicKey })\n }\n }\n\n throw new CodeError(`Node not responding with its public key: ${peer.toString()}`, 'ERR_INVALID_RECORD')\n }\n\n /**\n * Search for a peer with the given ID\n */\n async * findPeer (id: PeerId, options: QueryOptions = {}): AsyncGenerator {\n this.log('findPeer %p', id)\n\n // Try to find locally\n const pi = await this.findPeerLocal(id)\n\n // already got it\n if (pi != null) {\n this.log('found local')\n yield finalPeerEvent({\n from: this.components.peerId,\n peer: pi\n })\n return\n }\n\n const key = await utils.convertPeerId(id)\n const peers = this.routingTable.closestPeers(key)\n\n // sanity check\n const match = peers.find((p) => p.equals(id))\n\n if (match != null) {\n try {\n const peer = await this.components.peerStore.get(id)\n\n this.log('found in peerStore')\n yield finalPeerEvent({\n from: this.components.peerId,\n peer: {\n id: peer.id,\n multiaddrs: peer.addresses.map((address) => address.multiaddr),\n protocols: []\n }\n })\n\n return\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n const findPeerQuery: QueryFunc = async function * ({ peer, signal }) {\n const request = new Message(MESSAGE_TYPE.FIND_NODE, id.toBytes(), 0)\n\n for await (const event of self.network.sendRequest(peer, request, { signal })) {\n yield event\n\n if (event.name === 'PEER_RESPONSE') {\n const match = event.closer.find((p) => p.id.equals(id))\n\n // found the peer\n if (match != null) {\n yield finalPeerEvent({ from: event.from, peer: match })\n }\n }\n }\n }\n\n let foundPeer = false\n\n for await (const event of this.queryManager.run(id.toBytes(), peers, findPeerQuery, options)) {\n if (event.name === 'FINAL_PEER') {\n foundPeer = true\n }\n\n yield event\n }\n\n if (!foundPeer) {\n yield queryErrorEvent({ from: this.components.peerId, error: new CodeError('Not found', 'ERR_NOT_FOUND') })\n }\n }\n\n /**\n * Kademlia 'node lookup' operation on a key, which could be a the\n * bytes from a multihash or a peer ID\n */\n async * getClosestPeers (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n this.log('getClosestPeers to %b', key)\n const id = await utils.convertBuffer(key)\n const tablePeers = this.routingTable.closestPeers(id)\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n const peers = new PeerDistanceList(id, this.routingTable.kBucketSize)\n await Promise.all(tablePeers.map(async peer => { await peers.add(peer) }))\n\n const getCloserPeersQuery: QueryFunc = async function * ({ peer, signal }) {\n self.log('closerPeersSingle %s from %p', uint8ArrayToString(key, 'base32'), peer)\n const request = new Message(MESSAGE_TYPE.FIND_NODE, key, 0)\n\n yield * self.network.sendRequest(peer, request, { signal })\n }\n\n for await (const event of this.queryManager.run(key, tablePeers, getCloserPeersQuery, options)) {\n yield event\n\n if (event.name === 'PEER_RESPONSE') {\n await Promise.all(event.closer.map(async peerData => { await peers.add(peerData.id) }))\n }\n }\n\n this.log('found %d peers close to %b', peers.length, key)\n\n for (const peer of peers.peers) {\n yield finalPeerEvent({\n from: this.components.peerId,\n peer: {\n id: peer,\n multiaddrs: (await (this.components.peerStore.addressBook.get(peer)) ?? []).map(addr => addr.multiaddr),\n protocols: []\n }\n })\n }\n }\n\n /**\n * Query a particular peer for the value for the given key.\n * It will either return the value or a list of closer peers.\n *\n * Note: The peerStore is updated with new addresses found for the given peer.\n */\n async * getValueOrPeers (peer: PeerId, key: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n for await (const event of this._getValueSingle(peer, key, options)) {\n if (event.name === 'PEER_RESPONSE') {\n if (event.record != null) {\n // We have a record\n try {\n await this._verifyRecordOnline(event.record)\n } catch (err: any) {\n const errMsg = 'invalid record received, discarded'\n this.log(errMsg)\n\n yield queryErrorEvent({ from: event.from, error: new CodeError(errMsg, 'ERR_INVALID_RECORD') })\n continue\n }\n }\n }\n\n yield event\n }\n }\n\n /**\n * Verify a record, fetching missing public keys from the network.\n * Throws an error if the record is invalid.\n */\n async _verifyRecordOnline (record: DHTRecord): Promise {\n if (record.timeReceived == null) {\n throw new CodeError('invalid record received', 'ERR_INVALID_RECORD')\n }\n\n await verifyRecord(this.validators, new Libp2pRecord(record.key, record.value, record.timeReceived))\n }\n\n /**\n * Get the nearest peers to the given query, but if closer\n * than self\n */\n async getCloserPeersOffline (key: Uint8Array, closerThan: PeerId): Promise {\n const id = await utils.convertBuffer(key)\n const ids = this.routingTable.closestPeers(id)\n const output: PeerInfo[] = []\n\n for (const peerId of ids) {\n if (peerId.equals(closerThan)) {\n continue\n }\n\n try {\n const addresses = await this.components.peerStore.addressBook.get(peerId)\n const protocols = await this.components.peerStore.protoBook.get(peerId)\n\n output.push({\n id: peerId,\n multiaddrs: addresses.map((address) => address.multiaddr),\n protocols\n })\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n if (output.length > 0) {\n this.log('getCloserPeersOffline found %d peer(s) closer to %b than %p', output.length, key, closerThan)\n } else {\n this.log('getCloserPeersOffline could not find peer closer to %b than %p', key, closerThan)\n }\n\n return output\n }\n}\n", "import cache from 'hashlru'\nimport varint from 'varint'\nimport { Key } from 'interface-datastore/key'\nimport Queue from 'p-queue'\nimport {\n PROVIDERS_CLEANUP_INTERVAL,\n PROVIDERS_VALIDITY,\n PROVIDERS_LRU_CACHE_SIZE,\n PROVIDER_KEY_PREFIX\n} from './constants.js'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Datastore } from 'interface-datastore'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:kad-dht:providers')\n\nexport interface ProvidersInit {\n cacheSize?: number\n /**\n * How often invalid records are cleaned. (in seconds)\n */\n cleanupInterval?: number\n /**\n * How long is a provider valid for. (in seconds)\n */\n provideValidity?: number\n}\n\nexport interface ProvidersComponents {\n datastore: Datastore\n}\n\n/**\n * This class manages known providers.\n * A provider is a peer that we know to have the content for a given CID.\n *\n * Every `cleanupInterval` providers are checked if they\n * are still valid, i.e. younger than the `provideValidity`.\n * If they are not, they are deleted.\n *\n * To ensure the list survives restarts of the daemon,\n * providers are stored in the datastore, but to ensure\n * access is fast there is an LRU cache in front of that.\n */\nexport class Providers implements Startable {\n private readonly components: ProvidersComponents\n private readonly cache: ReturnType\n private readonly cleanupInterval: number\n private readonly provideValidity: number\n private readonly syncQueue: Queue\n private started: boolean\n private cleaner?: NodeJS.Timer\n\n constructor (components: ProvidersComponents, init: ProvidersInit = {}) {\n const { cacheSize, cleanupInterval, provideValidity } = init\n\n this.components = components\n this.cleanupInterval = cleanupInterval ?? PROVIDERS_CLEANUP_INTERVAL\n this.provideValidity = provideValidity ?? PROVIDERS_VALIDITY\n this.cache = cache(cacheSize ?? PROVIDERS_LRU_CACHE_SIZE)\n this.syncQueue = new Queue({ concurrency: 1 })\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * Start the provider cleanup service\n */\n async start (): Promise {\n if (this.started) {\n return\n }\n\n this.started = true\n\n this.cleaner = setInterval(\n () => {\n this._cleanup().catch(err => {\n log.error(err)\n })\n },\n this.cleanupInterval\n )\n }\n\n /**\n * Release any resources.\n */\n async stop (): Promise {\n this.started = false\n\n if (this.cleaner != null) {\n clearInterval(this.cleaner)\n this.cleaner = undefined\n }\n }\n\n /**\n * Check all providers if they are still valid, and if not delete them\n */\n async _cleanup (): Promise {\n await this.syncQueue.add(async () => {\n const start = Date.now()\n\n let count = 0\n let deleteCount = 0\n const deleted = new Map>()\n const batch = this.components.datastore.batch()\n\n // Get all provider entries from the datastore\n const query = this.components.datastore.query({ prefix: PROVIDER_KEY_PREFIX })\n\n for await (const entry of query) {\n try {\n // Add a delete to the batch for each expired entry\n const { cid, peerId } = parseProviderKey(entry.key)\n const time = readTime(entry.value).getTime()\n const now = Date.now()\n const delta = now - time\n const expired = delta > this.provideValidity\n\n log('comparing: %d - %d = %d > %d %s', now, time, delta, this.provideValidity, expired ? '(expired)' : '')\n\n if (expired) {\n deleteCount++\n batch.delete(entry.key)\n const peers = deleted.get(cid) ?? new Set()\n peers.add(peerId)\n deleted.set(cid, peers)\n }\n count++\n } catch (err: any) {\n log.error(err.message)\n }\n }\n\n // Commit the deletes to the datastore\n if (deleted.size > 0) {\n log('deleting %d / %d entries', deleteCount, count)\n await batch.commit()\n } else {\n log('nothing to delete')\n }\n\n // Clear expired entries from the cache\n for (const [cid, peers] of deleted) {\n const key = makeProviderKey(cid)\n const provs = this.cache.get(key)\n\n if (provs != null) {\n for (const peerId of peers) {\n provs.delete(peerId)\n }\n\n if (provs.size === 0) {\n this.cache.remove(key)\n } else {\n this.cache.set(key, provs)\n }\n }\n }\n\n log('Cleanup successful (%dms)', Date.now() - start)\n })\n }\n\n /**\n * Get the currently known provider peer ids for a given CID\n */\n async _getProvidersMap (cid: CID): Promise> {\n const cacheKey = makeProviderKey(cid)\n let provs: Map = this.cache.get(cacheKey)\n\n if (provs == null) {\n provs = await loadProviders(this.components.datastore, cid)\n this.cache.set(cacheKey, provs)\n }\n\n return provs\n }\n\n /**\n * Add a new provider for the given CID\n */\n async addProvider (cid: CID, provider: PeerId): Promise {\n await this.syncQueue.add(async () => {\n log('%p provides %s', provider, cid)\n const provs = await this._getProvidersMap(cid)\n\n log('loaded %s provs', provs.size)\n const now = new Date()\n provs.set(provider.toString(), now)\n\n const dsKey = makeProviderKey(cid)\n this.cache.set(dsKey, provs)\n\n await writeProviderEntry(this.components.datastore, cid, provider, now)\n })\n }\n\n /**\n * Get a list of providers for the given CID\n */\n async getProviders (cid: CID): Promise {\n return await this.syncQueue.add(async () => {\n log('get providers for %s', cid)\n const provs = await this._getProvidersMap(cid)\n\n return [...provs.keys()].map(peerIdStr => {\n return peerIdFromString(peerIdStr)\n })\n }, {\n // no timeout is specified for this queue so it will not\n // throw, but this is required to get the right return\n // type since p-queue@7.3.4\n throwOnTimeout: true\n })\n }\n}\n\n/**\n * Encode the given key its matching datastore key\n */\nfunction makeProviderKey (cid: CID | string): string {\n const cidStr = typeof cid === 'string' ? cid : uint8ArrayToString(cid.multihash.bytes, 'base32')\n\n return `${PROVIDER_KEY_PREFIX}/${cidStr}`\n}\n\n/**\n * Write a provider into the given store\n */\nasync function writeProviderEntry (store: Datastore, cid: CID, peer: PeerId, time: Date): Promise {\n const dsKey = [\n makeProviderKey(cid),\n '/',\n peer.toString()\n ].join('')\n\n const key = new Key(dsKey)\n const buffer = Uint8Array.from(varint.encode(time.getTime()))\n\n await store.put(key, buffer)\n}\n\n/**\n * Parse the CID and provider peer id from the key\n */\nfunction parseProviderKey (key: Key): { cid: string, peerId: string } {\n const parts = key.toString().split('/')\n\n if (parts.length !== 5) {\n throw new Error(`incorrectly formatted provider entry key in datastore: ${key.toString()}`)\n }\n\n return {\n cid: parts[3],\n peerId: parts[4]\n }\n}\n\n/**\n * Load providers for the given CID from the store\n */\nasync function loadProviders (store: Datastore, cid: CID): Promise> {\n const providers = new Map()\n const query = store.query({ prefix: makeProviderKey(cid) })\n\n for await (const entry of query) {\n const { peerId } = parseProviderKey(entry.key)\n providers.set(peerId, readTime(entry.value))\n }\n\n return providers\n}\n\nfunction readTime (buf: Uint8Array): Date {\n return new Date(varint.decode(buf))\n}\n", "import { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport {\n ALPHA, K, DEFAULT_QUERY_TIMEOUT\n} from '../constants.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { queryPath } from './query-path.js'\nimport merge from 'it-merge'\nimport { setMaxListeners } from 'events'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { QueryFunc } from './types.js'\nimport type { QueryEvent, QueryOptions } from '@libp2p/interface-dht'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport type { Metric, Metrics } from '@libp2p/interface-metrics'\n\nexport interface CleanUpEvents {\n 'cleanup': CustomEvent\n}\n\nexport interface QueryManagerInit {\n lan?: boolean\n disjointPaths?: number\n alpha?: number\n}\n\nexport interface QueryManagerComponents {\n peerId: PeerId\n metrics?: Metrics\n}\n\n/**\n * Keeps track of all running queries\n */\nexport class QueryManager implements Startable {\n private readonly components: QueryManagerComponents\n private readonly lan: boolean\n public disjointPaths: number\n private readonly alpha: number\n private readonly controllers: Set\n private running: boolean\n private queries: number\n private metrics?: {\n runningQueries: Metric\n queryTime: Metric\n }\n\n constructor (components: QueryManagerComponents, init: QueryManagerInit) {\n const { lan = false, disjointPaths = K, alpha = ALPHA } = init\n\n this.components = components\n this.disjointPaths = disjointPaths ?? K\n this.controllers = new Set()\n this.running = false\n this.alpha = alpha ?? ALPHA\n this.lan = lan\n this.queries = 0\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * Starts the query manager\n */\n async start (): Promise {\n this.running = true\n\n if (this.components.metrics != null && this.metrics == null) {\n this.metrics = {\n runningQueries: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_running_queries`),\n queryTime: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_query_time_seconds`)\n }\n }\n }\n\n /**\n * Stops all queries\n */\n async stop (): Promise {\n this.running = false\n\n for (const controller of this.controllers) {\n controller.abort()\n }\n\n this.controllers.clear()\n }\n\n async * run (key: Uint8Array, peers: PeerId[], queryFunc: QueryFunc, options: QueryOptions = {}): AsyncGenerator {\n if (!this.running) {\n throw new Error('QueryManager not started')\n }\n\n const stopQueryTimer = this.metrics?.queryTime.timer()\n let timeoutController\n\n if (options.signal == null) {\n // don't let queries run forever\n timeoutController = new TimeoutController(DEFAULT_QUERY_TIMEOUT)\n options.signal = timeoutController.signal\n\n // this signal will get listened to for network requests, etc\n // so make sure we don't make a lot of noise in the logs\n try {\n if (setMaxListeners != null) {\n setMaxListeners(Infinity, timeoutController.signal)\n }\n } catch {} // fails on node < 15.4\n }\n\n // allow us to stop queries on shut down\n const abortController = new AbortController()\n this.controllers.add(abortController)\n const signals = [abortController.signal]\n\n if (options.signal != null) {\n signals.push(options.signal)\n }\n\n const signal = anySignal(signals)\n\n // this signal will get listened to for every invocation of queryFunc\n // so make sure we don't make a lot of noise in the logs\n try {\n if (setMaxListeners != null) {\n setMaxListeners(Infinity, signal)\n }\n } catch {} // fails on node < 15.4\n\n const log = logger(`libp2p:kad-dht:${this.lan ? 'lan' : 'wan'}:query:` + uint8ArrayToString(key, 'base58btc'))\n\n // query a subset of peers up to `kBucketSize / 2` in length\n const peersToQuery = peers.slice(0, Math.min(this.disjointPaths, peers.length))\n const startTime = Date.now()\n const cleanUp = new EventEmitter()\n\n try {\n log('query:start')\n this.queries++\n this.metrics?.runningQueries.update(this.queries)\n\n if (peers.length === 0) {\n log.error('Running query with no peers')\n return\n }\n\n // make sure we don't get trapped in a loop\n const peersSeen = new PeerSet()\n\n // Create query paths from the starting peers\n const paths = peersToQuery.map((peer, index) => {\n return queryPath({\n key,\n startingPeer: peer,\n ourPeerId: this.components.peerId,\n signal,\n query: queryFunc,\n pathIndex: index,\n numPaths: peersToQuery.length,\n alpha: this.alpha,\n cleanUp,\n queryFuncTimeout: options.queryFuncTimeout,\n log,\n peersSeen\n })\n })\n\n // Execute the query along each disjoint path and yield their results as they become available\n for await (const event of merge(...paths)) {\n yield event\n\n if (event.name === 'QUERY_ERROR') {\n log('error', event.error)\n }\n }\n } catch (err: any) {\n if (!this.running && err.code === 'ERR_QUERY_ABORTED') {\n // ignore query aborted errors that were thrown during query manager shutdown\n } else {\n throw err\n }\n } finally {\n this.controllers.delete(abortController)\n\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n this.queries--\n this.metrics?.runningQueries.update(this.queries)\n\n if (stopQueryTimer != null) {\n stopQueryTimer()\n }\n\n cleanUp.dispatchEvent(new CustomEvent('cleanup'))\n log('query:done in %dms', Date.now() - startTime)\n }\n }\n}\n", "import Queue from 'p-queue'\nimport { xor } from 'uint8arrays/xor'\nimport { toString } from 'uint8arrays/to-string'\nimport defer from 'p-defer'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { convertPeerId, convertBuffer } from '../utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport { queryErrorEvent } from './events.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { CleanUpEvents } from './manager.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { QueryFunc } from '../query/types.js'\nimport type { QueryEvent } from '@libp2p/interface-dht'\nimport type { PeerSet } from '@libp2p/peer-collections'\n\nconst MAX_XOR = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')\n\nexport interface QueryPathOptions {\n /**\n * What are we trying to find\n */\n key: Uint8Array\n\n /**\n * Where we start our query\n */\n startingPeer: PeerId\n\n /**\n * Who we are\n */\n ourPeerId: PeerId\n\n /**\n * When to stop querying\n */\n signal: AbortSignal\n\n /**\n * The query function to run with each peer\n */\n query: QueryFunc\n\n /**\n * How many concurrent node/value lookups to run\n */\n alpha: number\n\n /**\n * How many concurrent node/value lookups to run\n */\n pathIndex: number\n\n /**\n * How many concurrent node/value lookups to run\n */\n numPaths: number\n\n /**\n * will emit a 'cleanup' event if the caller exits the for..await of early\n */\n cleanUp: EventEmitter\n\n /**\n * A timeout for queryFunc in ms\n */\n queryFuncTimeout?: number\n\n /**\n * Query log\n */\n log: Logger\n\n /**\n * Set of peers seen by this and other paths\n */\n peersSeen: PeerSet\n}\n\n/**\n * Walks a path through the DHT, calling the passed query function for\n * every peer encountered that we have not seen before\n */\nexport async function * queryPath (options: QueryPathOptions): AsyncGenerator {\n const { key, startingPeer, ourPeerId, signal, query, alpha, pathIndex, numPaths, cleanUp, queryFuncTimeout, log, peersSeen } = options\n // Only ALPHA node/value lookups are allowed at any given time for each process\n // https://github.com/libp2p/specs/tree/master/kad-dht#alpha-concurrency-parameter-%CE%B1\n const queue = new Queue({\n concurrency: alpha\n })\n\n // perform lookups on kadId, not the actual value\n const kadId = await convertBuffer(key)\n\n /**\n * Adds the passed peer to the query queue if it's not us and no\n * other path has passed through this peer\n */\n function queryPeer (peer: PeerId, peerKadId: Uint8Array): void {\n if (peer == null) {\n return\n }\n\n peersSeen.add(peer)\n\n const peerXor = BigInt('0x' + toString(xor(peerKadId, kadId), 'base16'))\n\n queue.add(async () => {\n let timeout\n const signals = [signal]\n\n if (queryFuncTimeout != null) {\n timeout = new TimeoutController(queryFuncTimeout)\n signals.push(timeout.signal)\n }\n\n const compoundSignal = anySignal(signals)\n\n try {\n for await (const event of query({\n key,\n peer,\n signal: compoundSignal,\n pathIndex,\n numPaths\n })) {\n if (compoundSignal.aborted) {\n return\n }\n\n // if there are closer peers and the query has not completed, continue the query\n if (event.name === 'PEER_RESPONSE') {\n for (const closerPeer of event.closer) {\n if (peersSeen.has(closerPeer.id)) { // eslint-disable-line max-depth\n log('already seen %p in query', closerPeer.id)\n continue\n }\n\n if (ourPeerId.equals(closerPeer.id)) { // eslint-disable-line max-depth\n log('not querying ourselves')\n continue\n }\n\n const closerPeerKadId = await convertPeerId(closerPeer.id)\n const closerPeerXor = BigInt('0x' + toString(xor(closerPeerKadId, kadId), 'base16'))\n\n // only continue query if closer peer is actually closer\n if (closerPeerXor > peerXor) { // eslint-disable-line max-depth\n log('skipping %p as they are not closer to %b than %p', closerPeer.id, key, peer)\n continue\n }\n\n log('querying closer peer %p', closerPeer.id)\n queryPeer(closerPeer.id, closerPeerKadId)\n }\n }\n\n // TODO: we have upgraded to p-queue@7, this should no longer be necessary\n queue.emit('completed', event)\n }\n\n timeout?.clear()\n } catch (err: any) {\n if (signal.aborted) {\n // TODO: we have upgraded to p-queue@7, this should no longer be necessary\n queue.emit('error', err)\n } else {\n // TODO: we have upgraded to p-queue@7, this should no longer be necessary\n queue.emit('completed', queryErrorEvent({\n from: peer,\n error: err\n }))\n }\n } finally {\n timeout?.clear()\n }\n }, {\n // use xor value as the queue priority - closer peers should execute first\n // subtract it from MAX_XOR because higher priority values execute sooner\n\n // @ts-expect-error this is supposed to be a Number but it's ok to use BigInts\n // as long as all priorities are BigInts since we won't mix BigInts and Number\n // values in arithmetic operations\n priority: MAX_XOR - peerXor\n }).catch(err => {\n log.error(err)\n })\n }\n\n // begin the query with the starting peer\n queryPeer(startingPeer, await convertPeerId(startingPeer))\n\n // yield results as they come in\n yield * toGenerator(queue, signal, cleanUp, log)\n}\n\nasync function * toGenerator (queue: Queue, signal: AbortSignal, cleanUp: EventEmitter, log: Logger): AsyncGenerator {\n let deferred = defer()\n let running = true\n const results: QueryEvent[] = []\n\n const cleanup = (): void => {\n if (!running) {\n return\n }\n\n log('clean up queue, results %d, queue size %d, pending tasks %d', results.length, queue.size, queue.pending)\n\n running = false\n queue.clear()\n results.splice(0, results.length)\n }\n\n queue.on('completed', result => {\n results.push(result)\n deferred.resolve()\n })\n queue.on('error', err => {\n log('queue error', err)\n cleanup()\n deferred.reject(err)\n })\n queue.on('idle', () => {\n log('queue idle')\n running = false\n deferred.resolve()\n })\n\n // clear the queue and throw if the query is aborted\n signal.addEventListener('abort', () => {\n log('abort queue')\n const wasRunning = running\n cleanup()\n\n if (wasRunning) {\n deferred.reject(new CodeError('Query aborted', 'ERR_QUERY_ABORTED'))\n }\n })\n\n // the user broke out of the loop early, ensure we resolve the deferred result\n // promise and clear the queue of any remaining jobs\n cleanUp.addEventListener('cleanup', () => {\n cleanup()\n deferred.resolve()\n })\n\n while (running) { // eslint-disable-line no-unmodified-loop-condition\n await deferred.promise\n deferred = defer()\n\n // yield all available results\n while (results.length > 0) {\n const result = results.shift()\n\n if (result != null) {\n yield result\n }\n }\n }\n\n // yield any remaining results\n yield * results\n}\n", "import { pushable } from 'it-pushable'\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nexport default async function * merge (...sources: Array | Iterable>): AsyncGenerator {\n const output = pushable({\n objectMode: true\n })\n\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n output.push(item)\n }\n })\n )\n\n output.end()\n } catch (err: any) {\n output.end(err)\n }\n })\n\n yield * output\n}\n", "import { CID } from 'multiformats/cid'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { logger } from '@libp2p/logger'\nimport type { Providers } from '../../providers'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { Message } from '../../message/index.js'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:add-provider')\n\nexport interface AddProviderHandlerInit {\n providers: Providers\n}\n\nexport class AddProviderHandler implements DHTMessageHandler {\n private readonly providers: Providers\n\n constructor (init: AddProviderHandlerInit) {\n const { providers } = init\n this.providers = providers\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n log('start')\n\n if (msg.key == null || msg.key.length === 0) {\n throw new CodeError('Missing key', 'ERR_MISSING_KEY')\n }\n\n let cid: CID\n try {\n // this is actually just the multihash, not the whole CID\n cid = CID.decode(msg.key)\n } catch (err: any) {\n throw new CodeError('Invalid CID', 'ERR_INVALID_CID')\n }\n\n if (msg.providerPeers == null || msg.providerPeers.length === 0) {\n log.error('no providers found in message')\n }\n\n await Promise.all(\n msg.providerPeers.map(async (pi) => {\n // Ignore providers not from the originator\n if (!pi.id.equals(peerId)) {\n log('invalid provider peer %p from %p', pi.id, peerId)\n return\n }\n\n if (pi.multiaddrs.length < 1) {\n log('no valid addresses for provider %p. Ignore', peerId)\n return\n }\n\n log('received provider %p for %s (addrs %s)', peerId, cid, pi.multiaddrs.map((m) => m.toString()))\n\n await this.providers.addProvider(cid, pi.id)\n })\n )\n\n return undefined\n }\n}\n", "import { Message } from '../../message/index.js'\nimport { logger } from '@libp2p/logger'\nimport {\n removePrivateAddresses,\n removePublicAddresses\n} from '../../utils.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays'\nimport { protocols } from '@multiformats/multiaddr'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { PeerRouting } from '../../peer-routing/index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:find-node')\n\nexport interface FindNodeHandlerInit {\n peerRouting: PeerRouting\n lan: boolean\n}\n\nexport interface FindNodeHandlerComponents {\n peerId: PeerId\n addressManager: AddressManager\n}\n\nexport class FindNodeHandler implements DHTMessageHandler {\n private readonly peerRouting: PeerRouting\n private readonly lan: boolean\n private readonly components: FindNodeHandlerComponents\n\n constructor (components: FindNodeHandlerComponents, init: FindNodeHandlerInit) {\n const { peerRouting, lan } = init\n\n this.components = components\n this.peerRouting = peerRouting\n this.lan = Boolean(lan)\n }\n\n /**\n * Process `FindNode` DHT messages\n */\n async handle (peerId: PeerId, msg: Message): Promise {\n log('incoming request from %p for peers closer to %b', peerId, msg.key)\n\n let closer: PeerInfo[] = []\n\n if (uint8ArrayEquals(this.components.peerId.toBytes(), msg.key)) {\n closer = [{\n id: this.components.peerId,\n multiaddrs: this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code)),\n protocols: []\n }]\n } else {\n closer = await this.peerRouting.getCloserPeersOffline(msg.key, peerId)\n }\n\n closer = closer\n .map(this.lan ? removePublicAddresses : removePrivateAddresses)\n .filter(({ multiaddrs }) => multiaddrs.length)\n\n const response = new Message(msg.type, new Uint8Array(0), msg.clusterLevel)\n\n if (closer.length > 0) {\n response.closerPeers = closer\n } else {\n log('could not find any peers closer to %b than %p', msg.key, peerId)\n }\n\n return response\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { Message } from '../../message/index.js'\nimport {\n removePrivateAddresses,\n removePublicAddresses\n} from '../../utils.js'\nimport { logger } from '@libp2p/logger'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { Providers } from '../../providers.js'\nimport type { PeerRouting } from '../../peer-routing/index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:get-providers')\n\nexport interface GetProvidersHandlerInit {\n peerRouting: PeerRouting\n providers: Providers\n lan: boolean\n}\n\nexport interface GetProvidersHandlerComponents {\n peerStore: PeerStore\n}\n\nexport class GetProvidersHandler implements DHTMessageHandler {\n private readonly components: GetProvidersHandlerComponents\n private readonly peerRouting: PeerRouting\n private readonly providers: Providers\n private readonly lan: boolean\n\n constructor (components: GetProvidersHandlerComponents, init: GetProvidersHandlerInit) {\n const { peerRouting, providers, lan } = init\n\n this.components = components\n this.peerRouting = peerRouting\n this.providers = providers\n this.lan = Boolean(lan)\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n let cid\n try {\n cid = CID.decode(msg.key)\n } catch (err: any) {\n throw new CodeError('Invalid CID', 'ERR_INVALID_CID')\n }\n\n log('%p asking for providers for %s', peerId, cid)\n\n const [peers, closer] = await Promise.all([\n this.providers.getProviders(cid),\n this.peerRouting.getCloserPeersOffline(msg.key, peerId)\n ])\n\n const providerPeers = await this._getPeers(peers)\n const closerPeers = await this._getPeers(closer.map(({ id }) => id))\n const response = new Message(msg.type, msg.key, msg.clusterLevel)\n\n if (providerPeers.length > 0) {\n response.providerPeers = providerPeers\n }\n\n if (closerPeers.length > 0) {\n response.closerPeers = closerPeers\n }\n\n log('got %s providers %s closerPeers', providerPeers.length, closerPeers.length)\n return response\n }\n\n async _getAddresses (peerId: PeerId): Promise {\n const addrs = await this.components.peerStore.addressBook.get(peerId)\n\n return addrs.map(address => address.multiaddr)\n }\n\n async _getPeers (peerIds: PeerId[]): Promise {\n const output: PeerInfo[] = []\n const addrFilter = this.lan ? removePublicAddresses : removePrivateAddresses\n\n for (const peerId of peerIds) {\n const peer = addrFilter({\n id: peerId,\n multiaddrs: await this._getAddresses(peerId),\n protocols: []\n })\n\n if (peer.multiaddrs.length > 0) {\n output.push(peer)\n }\n }\n\n return output\n }\n}\n", "import { Libp2pRecord } from '@libp2p/record'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { Message, MESSAGE_TYPE } from '../../message/index.js'\nimport {\n MAX_RECORD_AGE\n} from '../../constants.js'\nimport { bufferToRecordKey, isPublicKeyKey, fromPublicKeyKey } from '../../utils.js'\nimport { logger } from '@libp2p/logger'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '../../peer-routing/index.js'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Datastore } from 'interface-datastore'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:get-value')\n\nexport interface GetValueHandlerInit {\n peerRouting: PeerRouting\n}\n\nexport interface GetValueHandlerComponents {\n peerStore: PeerStore\n datastore: Datastore\n}\n\nexport class GetValueHandler implements DHTMessageHandler {\n private readonly components: GetValueHandlerComponents\n private readonly peerRouting: PeerRouting\n\n constructor (components: GetValueHandlerComponents, init: GetValueHandlerInit) {\n const { peerRouting } = init\n\n this.components = components\n this.peerRouting = peerRouting\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n const key = msg.key\n\n log('%p asked for key %b', peerId, key)\n\n if (key == null || key.length === 0) {\n throw new CodeError('Invalid key', 'ERR_INVALID_KEY')\n }\n\n const response = new Message(MESSAGE_TYPE.GET_VALUE, key, msg.clusterLevel)\n\n if (isPublicKeyKey(key)) {\n log('is public key')\n const idFromKey = fromPublicKeyKey(key)\n let pubKey: Uint8Array | undefined\n\n try {\n const key = await this.components.peerStore.keyBook.get(idFromKey)\n\n if (key == null) {\n throw new CodeError('No public key found in key book', 'ERR_NOT_FOUND')\n }\n\n pubKey = key\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n if (pubKey != null) {\n log('returning found public key')\n response.record = new Libp2pRecord(key, pubKey, new Date())\n return response\n }\n }\n\n const [record, closer] = await Promise.all([\n this._checkLocalDatastore(key),\n this.peerRouting.getCloserPeersOffline(msg.key, peerId)\n ])\n\n if (record != null) {\n log('had record for %b in local datastore', key)\n response.record = record\n }\n\n if (closer.length > 0) {\n log('had %s closer peers in routing table', closer.length)\n response.closerPeers = closer\n }\n\n return response\n }\n\n /**\n * Try to fetch a given record by from the local datastore.\n * Returns the record if it is still valid, meaning\n * - it was either authored by this node, or\n * - it was received less than `MAX_RECORD_AGE` ago.\n */\n async _checkLocalDatastore (key: Uint8Array): Promise {\n log('checkLocalDatastore looking for %b', key)\n const dsKey = bufferToRecordKey(key)\n\n // Fetch value from ds\n let rawRecord\n try {\n rawRecord = await this.components.datastore.get(dsKey)\n } catch (err: any) {\n if (err.code === 'ERR_NOT_FOUND') {\n return undefined\n }\n throw err\n }\n\n // Create record from the returned bytes\n const record = Libp2pRecord.deserialize(rawRecord)\n\n if (record == null) {\n throw new CodeError('Invalid record', 'ERR_INVALID_RECORD')\n }\n\n // Check validity: compare time received with max record age\n if (record.timeReceived == null ||\n Date.now() - record.timeReceived.getTime() > MAX_RECORD_AGE) {\n // If record is bad delete it and return\n await this.components.datastore.delete(dsKey)\n return undefined\n }\n\n // Record is valid\n return record\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport type { Message } from '../../message/index.js'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:ping')\n\nexport class PingHandler implements DHTMessageHandler {\n async handle (peerId: PeerId, msg: Message): Promise {\n log('ping from %p', peerId)\n return msg\n }\n}\n", "import { bufferToRecordKey } from '../../utils.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { verifyRecord } from '@libp2p/record/validators'\nimport { Logger, logger } from '@libp2p/logger'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { Validators } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Message } from '../../message/index.js'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface PutValueHandlerInit {\n validators: Validators\n}\n\nexport interface PutValueHandlerComponents {\n datastore: Datastore\n}\n\nexport class PutValueHandler implements DHTMessageHandler {\n private readonly log: Logger\n private readonly components: PutValueHandlerComponents\n private readonly validators: Validators\n\n constructor (components: PutValueHandlerComponents, init: PutValueHandlerInit) {\n const { validators } = init\n\n this.components = components\n this.log = logger('libp2p:kad-dht:rpc:handlers:put-value')\n this.validators = validators\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n const key = msg.key\n this.log('%p asked us to store value for key %b', peerId, key)\n\n const record = msg.record\n\n if (record == null) {\n const errMsg = `Empty record from: ${peerId.toString()}`\n\n this.log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_EMPTY_RECORD')\n }\n\n try {\n await verifyRecord(this.validators, record)\n\n record.timeReceived = new Date()\n const recordKey = bufferToRecordKey(record.key)\n await this.components.datastore.put(recordKey, record.serialize().subarray())\n this.log('put record for %b into datastore under key %k', key, recordKey)\n } catch (err: any) {\n this.log('did not put record for key %b into datastore %o', key, err)\n }\n\n return msg\n }\n}\n", "import { pipe } from 'it-pipe'\nimport * as lp from 'it-length-prefixed'\nimport { Logger, logger } from '@libp2p/logger'\nimport type { RoutingTable } from '../routing-table'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Message, MESSAGE_TYPE } from '../message/index.js'\nimport { AddProviderHandler } from './handlers/add-provider.js'\nimport { FindNodeHandler, FindNodeHandlerComponents } from './handlers/find-node.js'\nimport { GetProvidersHandler, GetProvidersHandlerComponents } from './handlers/get-providers.js'\nimport { GetValueHandler, GetValueHandlerComponents } from './handlers/get-value.js'\nimport { PingHandler } from './handlers/ping.js'\nimport { PutValueHandler, PutValueHandlerComponents } from './handlers/put-value.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Providers } from '../providers'\nimport type { PeerRouting } from '../peer-routing'\nimport type { Validators } from '@libp2p/interface-dht'\n\nexport interface DHTMessageHandler {\n handle: (peerId: PeerId, msg: Message) => Promise\n}\n\nexport interface RPCInit {\n routingTable: RoutingTable\n providers: Providers\n peerRouting: PeerRouting\n validators: Validators\n lan: boolean\n}\n\nexport interface RPCComponents extends GetValueHandlerComponents, PutValueHandlerComponents, FindNodeHandlerComponents, GetProvidersHandlerComponents {\n\n}\n\nexport class RPC {\n private readonly handlers: Record\n private readonly routingTable: RoutingTable\n private readonly log: Logger\n\n constructor (components: RPCComponents, init: RPCInit) {\n const { providers, peerRouting, validators, lan } = init\n\n this.log = logger('libp2p:kad-dht:rpc')\n this.routingTable = init.routingTable\n this.handlers = {\n [MESSAGE_TYPE.GET_VALUE]: new GetValueHandler(components, { peerRouting }),\n [MESSAGE_TYPE.PUT_VALUE]: new PutValueHandler(components, { validators }),\n [MESSAGE_TYPE.FIND_NODE]: new FindNodeHandler(components, { peerRouting, lan }),\n [MESSAGE_TYPE.ADD_PROVIDER]: new AddProviderHandler({ providers }),\n [MESSAGE_TYPE.GET_PROVIDERS]: new GetProvidersHandler(components, { peerRouting, providers, lan }),\n [MESSAGE_TYPE.PING]: new PingHandler()\n }\n }\n\n /**\n * Process incoming DHT messages\n */\n async handleMessage (peerId: PeerId, msg: Message): Promise {\n try {\n await this.routingTable.add(peerId)\n } catch (err: any) {\n this.log.error('Failed to update the kbucket store', err)\n }\n\n // get handler & execute it\n const handler = this.handlers[msg.type]\n\n if (handler == null) {\n this.log.error(`no handler found for message type: ${msg.type}`)\n return\n }\n\n return await handler.handle(peerId, msg)\n }\n\n /**\n * Handle incoming streams on the dht protocol\n */\n onIncomingStream (data: IncomingStreamData): void {\n Promise.resolve().then(async () => {\n const { stream, connection } = data\n const peerId = connection.remotePeer\n\n try {\n await this.routingTable.add(peerId)\n } catch (err: any) {\n this.log.error(err)\n }\n\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n for await (const msg of source) {\n // handle the message\n const desMessage = Message.deserialize(msg)\n self.log('incoming %s from %p', desMessage.type, peerId)\n const res = await self.handleMessage(peerId, desMessage)\n\n // Not all handlers will return a response\n if (res != null) {\n yield res.serialize()\n }\n }\n },\n lp.encode(),\n stream\n )\n })\n .catch(err => {\n this.log.error(err)\n })\n }\n}\n", "import { createTopology } from '@libp2p/topology'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { Logger } from '@libp2p/logger'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { KadDHTComponents } from '.'\n\nexport interface TopologyListenerInit {\n protocol: string\n lan: boolean\n}\n\nexport interface TopologyListenerEvents {\n 'peer': CustomEvent\n}\n\n/**\n * Receives notifications of new peers joining the network that support the DHT protocol\n */\nexport class TopologyListener extends EventEmitter implements Startable {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly protocol: string\n private running: boolean\n private registrarId?: string\n\n constructor (components: KadDHTComponents, init: TopologyListenerInit) {\n super()\n\n const { protocol, lan } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:topology-listener:${lan ? 'lan' : 'wan'}`)\n this.running = false\n this.protocol = protocol\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * Start the network\n */\n async start (): Promise {\n if (this.running) {\n return\n }\n\n this.running = true\n\n // register protocol with topology\n const topology = createTopology({\n onConnect: (peerId) => {\n this.log('observed peer %p with protocol %s', peerId, this.protocol)\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerId\n }))\n }\n })\n this.registrarId = await this.components.registrar.register(this.protocol, topology)\n }\n\n /**\n * Stop all network activity\n */\n async stop (): Promise {\n this.running = false\n\n // unregister protocol and handlers\n if (this.registrarId != null) {\n this.components.registrar.unregister(this.registrarId)\n this.registrarId = undefined\n }\n }\n}\n", "import { setMaxListeners } from 'events'\nimport take from 'it-take'\nimport length from 'it-length'\nimport { QUERY_SELF_INTERVAL, QUERY_SELF_TIMEOUT, K } from './constants.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport { logger, Logger } from '@libp2p/logger'\nimport type { PeerRouting } from './peer-routing/index.js'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { pipe } from 'it-pipe'\nimport type { KadDHTComponents } from './index.js'\n\nexport interface QuerySelfInit {\n lan: boolean\n peerRouting: PeerRouting\n count?: number\n interval?: number\n queryTimeout?: number\n}\n\n/**\n * Receives notifications of new peers joining the network that support the DHT protocol\n */\nexport class QuerySelf implements Startable {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly peerRouting: PeerRouting\n private readonly count: number\n private readonly interval: number\n private readonly queryTimeout: number\n private running: boolean\n private timeoutId?: NodeJS.Timer\n private controller?: AbortController\n\n constructor (components: KadDHTComponents, init: QuerySelfInit) {\n const { peerRouting, lan, count, interval, queryTimeout } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:query-self`)\n this.running = false\n this.peerRouting = peerRouting\n this.count = count ?? K\n this.interval = interval ?? QUERY_SELF_INTERVAL\n this.queryTimeout = queryTimeout ?? QUERY_SELF_TIMEOUT\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n async start (): Promise {\n if (this.running) {\n return\n }\n\n this.running = true\n this._querySelf()\n }\n\n async stop (): Promise {\n this.running = false\n\n if (this.timeoutId != null) {\n clearTimeout(this.timeoutId)\n }\n\n if (this.controller != null) {\n this.controller.abort()\n }\n }\n\n _querySelf (): void {\n Promise.resolve().then(async () => {\n const timeoutController = new TimeoutController(this.queryTimeout)\n\n try {\n this.controller = new AbortController()\n const signal = anySignal([this.controller.signal, timeoutController.signal])\n // this controller will get used for lots of dial attempts so make sure we don't cause warnings to be logged\n try {\n if (setMaxListeners != null) {\n setMaxListeners(Infinity, signal)\n }\n } catch {} // fails on node < 15.4\n const found = await pipe(\n this.peerRouting.getClosestPeers(this.components.peerId.toBytes(), {\n signal\n }),\n (source) => take(source, this.count),\n async (source) => await length(source)\n )\n\n this.log('query ran successfully - found %d peers', found)\n } catch (err: any) {\n this.log('query error', err)\n } finally {\n this.timeoutId = setTimeout(this._querySelf.bind(this), this.interval)\n timeoutController.clear()\n }\n }).catch(err => {\n this.log('query error', err)\n })\n }\n}\n", "\n/**\n * Stop iteration after n items have been received\n */\nexport default async function * take (source: AsyncIterable | Iterable, limit: number): AsyncGenerator {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n}\n", "import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\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 * ```js\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 peerDiscovery = Symbol.for('@libp2p/peer-discovery')\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n", "import { RoutingTable } from './routing-table/index.js'\nimport { RoutingTableRefresh } from './routing-table/refresh.js'\nimport { Network } from './network.js'\nimport { ContentFetching } from './content-fetching/index.js'\nimport { ContentRouting } from './content-routing/index.js'\nimport { PeerRouting } from './peer-routing/index.js'\nimport { Providers } from './providers.js'\nimport { QueryManager } from './query/manager.js'\nimport { RPC } from './rpc/index.js'\nimport { TopologyListener } from './topology-listener.js'\nimport { QuerySelf } from './query-self.js'\nimport {\n removePrivateAddresses,\n removePublicAddresses\n} from './utils.js'\nimport { Logger, logger } from '@libp2p/logger'\nimport type { QueryOptions, Validators, Selectors, DHT, QueryEvent } from '@libp2p/interface-dht'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport type { KadDHTComponents, KadDHTInit } from './index.js'\nimport { validators as recordValidators } from '@libp2p/record/validators'\nimport { selectors as recordSelectors } from '@libp2p/record/selectors'\nimport { symbol } from '@libp2p/interface-peer-discovery'\nimport { PROTOCOL_DHT, PROTOCOL_PREFIX, LAN_PREFIX } from './constants.js'\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\nexport interface SingleKadDHTInit extends KadDHTInit {\n /**\n * Whether to start up in lan or wan mode\n */\n lan?: boolean\n}\n\n/**\n * A DHT implementation modelled after Kademlia with S/Kademlia modifications.\n * Original implementation in go: https://github.com/libp2p/go-libp2p-kad-dht.\n */\nexport class KadDHT extends EventEmitter implements DHT {\n public protocol: string\n public routingTable: RoutingTable\n public providers: Providers\n public network: Network\n public peerRouting: PeerRouting\n\n public readonly components: KadDHTComponents\n private readonly log: Logger\n private running: boolean\n private readonly kBucketSize: number\n private clientMode: boolean\n private readonly lan: boolean\n private readonly validators: Validators\n private readonly selectors: Selectors\n private readonly queryManager: QueryManager\n private readonly contentFetching: ContentFetching\n private readonly contentRouting: ContentRouting\n private readonly routingTableRefresh: RoutingTableRefresh\n private readonly rpc: RPC\n private readonly topologyListener: TopologyListener\n private readonly querySelf: QuerySelf\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n\n /**\n * Create a new KadDHT\n */\n constructor (components: KadDHTComponents, init: SingleKadDHTInit) {\n super()\n\n const {\n kBucketSize,\n clientMode,\n validators,\n selectors,\n querySelfInterval,\n lan,\n protocolPrefix,\n pingTimeout,\n pingConcurrency,\n maxInboundStreams,\n maxOutboundStreams,\n providers: providersInit\n } = init\n\n this.running = false\n this.components = components\n this.lan = Boolean(lan)\n this.log = logger(`libp2p:kad-dht:${lan === true ? 'lan' : 'wan'}`)\n this.protocol = `${protocolPrefix ?? PROTOCOL_PREFIX}${lan === true ? LAN_PREFIX : ''}${PROTOCOL_DHT}`\n this.kBucketSize = kBucketSize ?? 20\n this.clientMode = clientMode ?? true\n this.maxInboundStreams = maxInboundStreams ?? DEFAULT_MAX_INBOUND_STREAMS\n this.maxOutboundStreams = maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS\n this.routingTable = new RoutingTable(components, {\n kBucketSize,\n lan: this.lan,\n pingTimeout,\n pingConcurrency,\n protocol: this.protocol\n })\n\n this.providers = new Providers(components, providersInit ?? {})\n\n this.validators = {\n ...recordValidators,\n ...validators\n }\n this.selectors = {\n ...recordSelectors,\n ...selectors\n }\n this.network = new Network(components, {\n protocol: this.protocol,\n lan: this.lan\n })\n this.queryManager = new QueryManager(components, {\n // Number of disjoint query paths to use - This is set to `kBucketSize/2` per the S/Kademlia paper\n disjointPaths: Math.ceil(this.kBucketSize / 2),\n lan\n })\n\n // DHT components\n this.peerRouting = new PeerRouting(components, {\n routingTable: this.routingTable,\n network: this.network,\n validators: this.validators,\n queryManager: this.queryManager,\n lan: this.lan\n })\n this.contentFetching = new ContentFetching(components, {\n validators: this.validators,\n selectors: this.selectors,\n peerRouting: this.peerRouting,\n queryManager: this.queryManager,\n routingTable: this.routingTable,\n network: this.network,\n lan: this.lan\n })\n this.contentRouting = new ContentRouting(components, {\n network: this.network,\n peerRouting: this.peerRouting,\n queryManager: this.queryManager,\n routingTable: this.routingTable,\n providers: this.providers,\n lan: this.lan\n })\n this.routingTableRefresh = new RoutingTableRefresh({\n peerRouting: this.peerRouting,\n routingTable: this.routingTable,\n lan: this.lan\n })\n this.rpc = new RPC(components, {\n routingTable: this.routingTable,\n providers: this.providers,\n peerRouting: this.peerRouting,\n validators: this.validators,\n lan: this.lan\n })\n this.topologyListener = new TopologyListener(components, {\n protocol: this.protocol,\n lan: this.lan\n })\n this.querySelf = new QuerySelf(components, {\n peerRouting: this.peerRouting,\n interval: querySelfInterval,\n lan: this.lan\n })\n\n // handle peers being discovered during processing of DHT messages\n this.network.addEventListener('peer', (evt) => {\n const peerData = evt.detail\n\n this.onPeerConnect(peerData).catch(err => {\n this.log.error('could not add %p to routing table', peerData.id, err)\n })\n\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerData\n }))\n })\n\n // handle peers being discovered via other peer discovery mechanisms\n this.topologyListener.addEventListener('peer', (evt) => {\n const peerId = evt.detail\n\n Promise.resolve().then(async () => {\n const multiaddrs = await this.components.peerStore.addressBook.get(peerId)\n\n const peerData = {\n id: peerId,\n multiaddrs: multiaddrs.map(addr => addr.multiaddr),\n protocols: []\n }\n\n await this.onPeerConnect(peerData)\n }).catch(err => {\n this.log.error('could not add %p to routing table', peerId, err)\n })\n })\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] (): '@libp2p/kad-dht' {\n return '@libp2p/kad-dht'\n }\n\n async onPeerConnect (peerData: PeerInfo): Promise {\n this.log('peer %p connected with protocols %s', peerData.id, peerData.protocols)\n\n if (this.lan) {\n peerData = removePublicAddresses(peerData)\n } else {\n peerData = removePrivateAddresses(peerData)\n }\n\n if (peerData.multiaddrs.length === 0) {\n this.log('ignoring %p as they do not have any %s addresses in %s', peerData.id, this.lan ? 'private' : 'public', peerData.multiaddrs.map(addr => addr.toString()))\n return\n }\n\n try {\n await this.routingTable.add(peerData.id)\n } catch (err: any) {\n this.log.error('could not add %p to routing table', peerData.id, err)\n }\n }\n\n /**\n * Is this DHT running.\n */\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async getMode (): Promise<'client' | 'server'> {\n return this.clientMode ? 'client' : 'server'\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async setMode (mode: 'client' | 'server'): Promise {\n await this.components.registrar.unhandle(this.protocol)\n\n if (mode === 'client') {\n this.log('enabling client mode')\n this.clientMode = true\n } else {\n this.log('enabling server mode')\n this.clientMode = false\n await this.components.registrar.handle(this.protocol, this.rpc.onIncomingStream.bind(this.rpc), {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams\n })\n }\n }\n\n /**\n * Start listening to incoming connections.\n */\n async start (): Promise {\n this.running = true\n\n // Only respond to queries when not in client mode\n await this.setMode(this.clientMode ? 'client' : 'server')\n\n await Promise.all([\n this.providers.start(),\n this.queryManager.start(),\n this.network.start(),\n this.routingTable.start(),\n this.topologyListener.start(),\n this.querySelf.start()\n ])\n\n await this.routingTableRefresh.start()\n }\n\n /**\n * Stop accepting incoming connections and sending outgoing\n * messages.\n */\n async stop (): Promise {\n this.running = false\n\n await Promise.all([\n this.providers.stop(),\n this.queryManager.stop(),\n this.network.stop(),\n this.routingTable.stop(),\n this.routingTableRefresh.stop(),\n this.topologyListener.stop(),\n this.querySelf.stop()\n ])\n }\n\n /**\n * Store the given key/value pair in the DHT\n */\n async * put (key: Uint8Array, value: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentFetching.put(key, value, options)\n }\n\n /**\n * Get the value that corresponds to the passed key\n */\n async * get (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentFetching.get(key, options)\n }\n\n // ----------- Content Routing\n\n /**\n * Announce to the network that we can provide given key's value\n */\n async * provide (key: CID, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentRouting.provide(key, this.components.addressManager.getAddresses(), options)\n }\n\n /**\n * Search the dht for providers of the given CID\n */\n async * findProviders (key: CID, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentRouting.findProviders(key, options)\n }\n\n // ----------- Peer Routing -----------\n\n /**\n * Search for a peer with the given ID\n */\n async * findPeer (id: PeerId, options: QueryOptions = {}): AsyncGenerator {\n yield * this.peerRouting.findPeer(id, options)\n }\n\n /**\n * Kademlia 'node lookup' operation\n */\n async * getClosestPeers (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * this.peerRouting.getClosestPeers(key, options)\n }\n\n async refreshRoutingTable (): Promise {\n this.routingTableRefresh.refreshTable(true)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport merge from 'it-merge'\nimport { queryErrorEvent } from './query/events.js'\nimport type { KadDHT } from './kad-dht.js'\nimport type { DualDHT, QueryEvent, QueryOptions } from '@libp2p/interface-dht'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport type { CID } from 'multiformats'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport { symbol } from '@libp2p/interface-peer-discovery'\nimport type { KadDHTComponents } from './index.js'\n\nconst log = logger('libp2p:kad-dht')\n\n/**\n * A DHT implementation modelled after Kademlia with S/Kademlia modifications.\n * Original implementation in go: https://github.com/libp2p/go-libp2p-kad-dht.\n */\nexport class DualKadDHT extends EventEmitter implements DualDHT {\n public readonly wan: KadDHT\n public readonly lan: KadDHT\n public readonly components: KadDHTComponents\n\n constructor (components: KadDHTComponents, wan: KadDHT, lan: KadDHT) {\n super()\n\n this.components = components\n this.wan = wan\n this.lan = lan\n\n // handle peers being discovered during processing of DHT messages\n this.wan.addEventListener('peer', (evt) => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: evt.detail\n }))\n })\n this.lan.addEventListener('peer', (evt) => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: evt.detail\n }))\n })\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] (): '@libp2p/dual-kad-dht' {\n return '@libp2p/dual-kad-dht'\n }\n\n /**\n * Is this DHT running.\n */\n isStarted (): boolean {\n return this.wan.isStarted() && this.lan.isStarted()\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async getMode (): Promise<'client' | 'server'> {\n return await this.wan.getMode()\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async setMode (mode: 'client' | 'server'): Promise {\n await this.wan.setMode(mode)\n }\n\n /**\n * Start listening to incoming connections.\n */\n async start (): Promise {\n await Promise.all([\n this.lan.start(),\n this.wan.start()\n ])\n }\n\n /**\n * Stop accepting incoming connections and sending outgoing\n * messages.\n */\n async stop (): Promise {\n await Promise.all([\n this.lan.stop(),\n this.wan.stop()\n ])\n }\n\n /**\n * Store the given key/value pair in the DHT\n */\n async * put (key: Uint8Array, value: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n for await (const event of merge(\n this.lan.put(key, value, options),\n this.wan.put(key, value, options)\n )) {\n yield event\n }\n }\n\n /**\n * Get the value that corresponds to the passed key\n */\n async * get (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n let queriedPeers = false\n let foundValue = false\n\n for await (const event of merge(\n this.lan.get(key, options),\n this.wan.get(key, options)\n )) {\n yield event\n\n if (event.name === 'DIALING_PEER') {\n queriedPeers = true\n }\n\n if (event.name === 'VALUE') {\n queriedPeers = true\n\n if (event.value != null) {\n foundValue = true\n }\n }\n\n if (event.name === 'SENDING_QUERY') {\n queriedPeers = true\n }\n }\n\n if (!queriedPeers) {\n throw new CodeError('No peers found in routing table!', 'ERR_NO_PEERS_IN_ROUTING_TABLE')\n }\n\n if (!foundValue) {\n yield queryErrorEvent({\n from: this.components.peerId,\n error: new CodeError('Not found', 'ERR_NOT_FOUND')\n })\n }\n }\n\n // ----------- Content Routing\n\n /**\n * Announce to the network that we can provide given key's value\n */\n async * provide (key: CID, options: AbortOptions = {}): AsyncGenerator {\n let sent = 0\n let success = 0\n const errors = []\n\n const dhts = [this.lan]\n\n // only run provide on the wan if we are in server mode\n if ((await this.wan.getMode()) === 'server') {\n dhts.push(this.wan)\n }\n\n for await (const event of merge(...dhts.map(dht => dht.provide(key, options)))) {\n yield event\n\n if (event.name === 'SENDING_QUERY') {\n sent++\n }\n\n if (event.name === 'QUERY_ERROR') {\n errors.push(event.error)\n }\n\n if (event.name === 'PEER_RESPONSE' && event.messageName === 'ADD_PROVIDER') {\n log('sent provider record for %s to %p', key, event.from)\n success++\n }\n }\n\n if (success === 0) {\n if (errors.length > 0) {\n // if all sends failed, throw an error to inform the caller\n throw new CodeError(`Failed to provide to ${errors.length} of ${sent} peers`, 'ERR_PROVIDES_FAILED', { errors })\n }\n\n throw new CodeError('Failed to provide - no peers found', 'ERR_PROVIDES_FAILED')\n }\n }\n\n /**\n * Search the dht for up to `K` providers of the given CID\n */\n async * findProviders (key: CID, options: QueryOptions = {}): AsyncGenerator {\n yield * merge(\n this.lan.findProviders(key, options),\n this.wan.findProviders(key, options)\n )\n }\n\n // ----------- Peer Routing -----------\n\n /**\n * Search for a peer with the given ID\n */\n async * findPeer (id: PeerId, options: QueryOptions = {}): AsyncGenerator {\n let queriedPeers = false\n\n for await (const event of merge(\n this.lan.findPeer(id, options),\n this.wan.findPeer(id, options)\n )) {\n yield event\n\n if (event.name === 'SENDING_QUERY' || event.name === 'FINAL_PEER') {\n queriedPeers = true\n }\n }\n\n if (!queriedPeers) {\n throw new CodeError('Peer lookup failed', 'ERR_LOOKUP_FAILED')\n }\n }\n\n /**\n * Kademlia 'node lookup' operation\n */\n async * getClosestPeers (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * merge(\n this.lan.getClosestPeers(key, options),\n this.wan.getClosestPeers(key, options)\n )\n }\n\n async refreshRoutingTable (): Promise {\n await Promise.all([\n this.lan.refreshRoutingTable(),\n this.wan.refreshRoutingTable()\n ])\n }\n}\n", "import { KadDHT as SingleKadDHT } from './kad-dht.js'\nimport { DualKadDHT } from './dual-kad-dht.js'\nimport type { ProvidersInit } from './providers.js'\nimport type { Selectors, Validators } from '@libp2p/interface-dht'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface KadDHTInit {\n /**\n * How many peers to store in each kBucket (default 20)\n */\n kBucketSize?: number\n\n /**\n * Whether to start up as a DHT client or server\n */\n clientMode?: boolean\n\n /**\n * Record selectors\n */\n selectors?: Selectors\n\n /**\n * Record validators\n */\n validators?: Validators\n\n /**\n * How often to query our own PeerId in order to ensure we have a\n * good view on the KAD address space local to our PeerId\n */\n querySelfInterval?: number\n\n /**\n * A custom protocol prefix to use (default: '/ipfs')\n */\n protocolPrefix?: string\n\n /**\n * How long to wait in ms when pinging DHT peers to decide if they\n * should be evicted from the routing table or not (default 10000)\n */\n pingTimeout?: number\n\n /**\n * How many peers to ping in parallel when deciding if they should\n * be evicted from the routing table or not (default 10)\n */\n pingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the DHT protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the DHT protocol per-connection\n */\n maxOutboundStreams?: number\n\n /**\n * Initialization options for the Providers component\n */\n providers?: ProvidersInit\n}\n\nexport interface KadDHTComponents {\n peerId: PeerId\n registrar: Registrar\n addressManager: AddressManager\n peerStore: PeerStore\n metrics?: Metrics\n connectionManager: ConnectionManager\n datastore: Datastore\n}\n\nclass KadDHT extends DualKadDHT {\n constructor (components: KadDHTComponents, init?: KadDHTInit) {\n super(components, new SingleKadDHT(components, {\n protocolPrefix: '/ipfs',\n ...init,\n lan: false\n }),\n new SingleKadDHT(components, {\n protocolPrefix: '/ipfs',\n ...init,\n clientMode: false,\n lan: true\n }))\n }\n}\n\nexport function kadDHT (init?: KadDHTInit): (components: KadDHTComponents) => DualKadDHT {\n return (components: KadDHTComponents) => new KadDHT(components, init)\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { P2P } from '@multiformats/mafmt'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { symbol } from '@libp2p/interface-peer-discovery'\nimport type { Startable } from '@libp2p/interfaces/dist/src/startable'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:bootstrap')\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\nexport interface BootstrapInit {\n /**\n * The list of peer addresses in multi-address format\n */\n list: string[]\n\n /**\n * How long to wait before discovering bootstrap nodes\n */\n timeout?: number\n\n /**\n * Tag a bootstrap peer with this name before \"discovering\" it (default: 'bootstrap')\n */\n tagName?: string\n\n /**\n * The bootstrap peer tag will have this value (default: 50)\n */\n tagValue?: number\n\n /**\n * Cause the bootstrap peer tag to be removed after this number of ms (default: 2 minutes)\n */\n tagTTL?: number\n}\n\nexport interface BootstrapComponents {\n peerStore: PeerStore\n}\n\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends EventEmitter implements PeerDiscovery, Startable {\n static tag = 'bootstrap'\n\n private timer?: ReturnType\n private readonly list: PeerInfo[]\n private readonly timeout: number\n private readonly components: BootstrapComponents\n private readonly _init: BootstrapInit\n\n constructor (components: BootstrapComponents, options: BootstrapInit = { 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\n this.components = components\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT\n this.list = []\n\n for (const candidate of options.list) {\n if (!P2P.matches(candidate)) {\n log.error('Invalid multiaddr')\n continue\n }\n\n const ma = multiaddr(candidate)\n const peerIdStr = ma.getPeerId()\n\n if (peerIdStr == null) {\n log.error('Invalid bootstrap multiaddr without peer id')\n continue\n }\n\n const peerData: PeerInfo = {\n id: peerIdFromString(peerIdStr),\n multiaddrs: [ma],\n protocols: []\n }\n\n this.list.push(peerData)\n }\n\n this._init = options\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] (): '@libp2p/bootstrap' {\n return '@libp2p/bootstrap'\n }\n\n isStarted (): boolean {\n return Boolean(this.timer)\n }\n\n /**\n * Start emitting events\n */\n start (): void {\n if (this.isStarted()) {\n return\n }\n\n log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout)\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n log.error(err)\n })\n }, this.timeout)\n }\n\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers (): Promise {\n if (this.timer == null) {\n return\n }\n\n for (const peerData of this.list) {\n await this.components.peerStore.tagPeer(peerData.id, 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 // check we are still running\n if (this.timer == null) {\n return\n }\n\n this.dispatchEvent(new CustomEvent('peer', { detail: peerData }))\n }\n }\n\n /**\n * Stop emitting events\n */\n stop (): void {\n if (this.timer != null) {\n clearTimeout(this.timer)\n }\n\n this.timer = undefined\n }\n}\n\nexport function bootstrap (init: BootstrapInit): (components: BootstrapComponents) => PeerDiscovery {\n return (components: BootstrapComponents) => new Bootstrap(components, init)\n}\n", "/* eslint-env browser */\n\nexport default WebSocket\n", "\nimport { EventIterator } from 'event-iterator'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { WebSocket, ErrorEvent, MessageEvent } from 'ws'\n\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: any): obj is ArrayBuffer {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number')\n}\n\nexport interface ConnectedSource extends AsyncIterable {\n connected: () => Promise\n}\n\nexport default (socket: WebSocket): ConnectedSource => {\n socket.binaryType = 'arraybuffer'\n\n const connected = async () => await new Promise((resolve, reject) => {\n if (isConnected) {\n return resolve()\n }\n if (connError != null) {\n return reject(connError)\n }\n\n const cleanUp = (cont: () => void) => {\n socket.removeEventListener('open', onOpen)\n socket.removeEventListener('error', onError)\n cont()\n }\n\n const onOpen = () => cleanUp(resolve)\n const onError = (event: ErrorEvent) => {\n cleanUp(() => reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)))\n }\n\n socket.addEventListener('open', onOpen)\n socket.addEventListener('error', onError)\n })\n\n const source = (async function * () {\n const messages = new EventIterator(\n ({ push, stop, fail }) => {\n const onMessage = (event: MessageEvent) => {\n let data: Uint8Array | null = null\n\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data)\n }\n\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data)\n }\n\n if (event.data instanceof Uint8Array) {\n data = event.data\n }\n\n if (data == null) {\n return\n }\n\n push(data)\n }\n const onError = (event: ErrorEvent) => fail(event.error ?? new Error('Socket error'))\n\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('close', stop)\n\n return () => {\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('close', stop)\n }\n },\n { highWaterMark: Infinity }\n )\n\n await connected()\n\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk\n }\n }())\n\n let isConnected = socket.readyState === 1\n let connError: Error | null\n\n socket.addEventListener('open', () => {\n isConnected = true\n connError = null\n })\n\n socket.addEventListener('close', () => {\n isConnected = false\n connError = null\n })\n\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)\n }\n })\n\n return Object.assign(source, {\n connected\n })\n}\n", "import type { ErrorEvent, WebSocket } from 'ws'\n\nexport default (socket: WebSocket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed')\n }\n\n // if open, return\n if (socket.readyState === 1) {\n return\n }\n\n return new Promise((resolve, reject) => {\n function cleanup () {\n socket.removeEventListener('open', handleOpen)\n socket.removeEventListener('error', handleErr)\n }\n\n function handleOpen () {\n cleanup()\n resolve()\n }\n\n function handleErr (event: ErrorEvent) {\n cleanup()\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`))\n }\n\n socket.addEventListener('open', handleOpen)\n socket.addEventListener('error', handleErr)\n })\n}\n", "import ready from './ready.js'\nimport type { WebSocket } from 'ws'\nimport type { Sink } from 'it-stream-types'\n\nexport interface SinkOptions {\n closeOnEnd?: boolean\n}\n\nexport default (socket: WebSocket, options: SinkOptions) => {\n options = options ?? {}\n options.closeOnEnd = options.closeOnEnd !== false\n\n const sink: Sink> = async source => {\n for await (const data of source) {\n try {\n await ready(socket)\n } catch (err: any) {\n if (err.message === 'socket closed') break\n throw err\n }\n\n socket.send(data)\n }\n\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n return await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve()\n } else {\n const err = Object.assign(new Error('ws error'), { event })\n reject(err)\n }\n })\n\n setTimeout(() => socket.close())\n })\n }\n }\n\n return sink\n}\n", "import source from './source.js'\nimport sink from './sink.js'\nimport type WebSocket from './web-socket.js'\nimport type { SinkOptions } from './sink.js'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface DuplexWebSocket extends Duplex> {\n connected: () => Promise\n localAddress?: string\n localPort?: number\n remoteAddress: string\n remotePort: number\n close: () => Promise\n destroy: () => void\n socket: WebSocket\n}\n\nexport interface DuplexWebSocketOptions extends SinkOptions {\n remoteAddress?: string\n remotePort?: number\n}\n\nexport default (socket: WebSocket, options?: DuplexWebSocketOptions): DuplexWebSocket => {\n options = options ?? {}\n\n const connectedSource = source(socket)\n let remoteAddress: string | undefined = options.remoteAddress\n let remotePort: number | undefined = options.remotePort\n\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 } catch {}\n }\n\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port')\n }\n\n const duplex: DuplexWebSocket = {\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 } else {\n socket.close()\n }\n },\n remoteAddress,\n remotePort,\n socket\n }\n\n return duplex\n}\n", "import { relative } from 'iso-url'\n\nconst map = { http: 'ws', https: 'wss' }\nconst def = 'ws'\n\nexport default (url: string, location: string | Partial) => relative(url, location, map, def)\n", "// load websocket library if we are not in the browser\nimport WebSocket from './web-socket.js'\nimport duplex from './duplex.js'\nimport wsurl from './ws-url.js'\nimport type { ClientOptions } from 'ws'\nimport type { DuplexWebSocket } from './duplex.js'\nimport type { SinkOptions } from './sink.js'\n\nexport interface WebSocketOptions extends SinkOptions {\n websocket?: ClientOptions\n}\n\nexport function connect (addr: string, opts?: WebSocketOptions): DuplexWebSocket {\n const location = typeof window === 'undefined' ? '' : window.location\n opts = opts ?? {}\n\n const url = wsurl(addr, location.toString())\n const socket = new WebSocket(url, opts.websocket)\n\n return duplex(socket, opts)\n}\n", "import type { Listener } from '@libp2p/interface-transport'\n\nexport function createListener (): Listener {\n throw new Error('WebSocket Servers can not be created in the browser!')\n}\n", "import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport pTimeout from 'p-timeout'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\n\nconst log = logger('libp2p:websockets:socket')\n\nexport interface SocketToConnOptions extends AbortOptions {\n localAddr?: Multiaddr\n}\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn (stream: DuplexWebSocket, remoteAddr: Multiaddr, options?: SocketToConnOptions): MultiaddrConnection {\n options = options ?? {}\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if ((options?.signal) != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await stream.sink(source)\n } catch (err: any) {\n if (err.type !== 'aborted') {\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(stream.source, options.signal) : stream.source,\n\n remoteAddr,\n\n timeline: { open: Date.now() },\n\n async close () {\n const start = Date.now()\n\n try {\n await pTimeout(stream.close(), {\n milliseconds: CLOSE_TIMEOUT\n })\n } catch (err) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n\n stream.destroy()\n } finally {\n maConn.timeline.close = Date.now()\n }\n }\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\n return maConn\n}\n", "import * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport {\n CODE_CIRCUIT,\n CODE_P2P,\n CODE_TCP,\n CODE_WS,\n CODE_WSS\n} from './constants.js'\n\nexport function all (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function wss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function dnsWss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n\nexport function dnsWsOrWss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))\n }\n\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n", "import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface UpgraderOptions {\n skipEncryption?: boolean\n skipProtection?: boolean\n muxerFactory?: StreamMuxerFactory\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n", "import { connect, WebSocketOptions } from 'it-ws/client'\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport pDefer from 'p-defer'\nimport { logger } from '@libp2p/logger'\nimport { isBrowser, isWebWorker } from 'wherearewe'\nimport { createListener } from './listener.js'\nimport { socketToMaConn } from './socket-to-conn.js'\nimport * as filters from './filters.js'\nimport { Transport, MultiaddrFilter, symbol, CreateListenerOptions, DialOptions, Listener } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\nimport type { ClientOptions } from 'ws'\nimport type { Server } from 'http'\n\nconst log = logger('libp2p:websockets')\n\nexport interface WebSocketsInit extends AbortOptions, WebSocketOptions {\n filter?: MultiaddrFilter\n websocket?: ClientOptions\n server?: Server\n}\n\nclass WebSockets implements Transport {\n private readonly init?: WebSocketsInit\n\n constructor (init?: WebSocketsInit) {\n this.init = init\n }\n\n get [Symbol.toStringTag] (): string {\n return '@libp2p/websockets'\n }\n\n get [symbol] (): true {\n return true\n }\n\n async dial (ma: Multiaddr, options: DialOptions): Promise {\n log('dialing %s', ma)\n options = options ?? {}\n\n const socket = await this._connect(ma, options)\n const maConn = socketToMaConn(socket, ma)\n log('new outbound connection %s', maConn.remoteAddr)\n\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: AbortOptions): Promise {\n if (options?.signal?.aborted === true) {\n throw new AbortError()\n }\n const cOpts = ma.toOptions()\n log('dialing %s:%s', cOpts.host, cOpts.port)\n\n const errorPromise = pDefer()\n const errfn = (err: any): void => {\n log.error('connection error:', err)\n\n errorPromise.reject(err)\n }\n\n const rawSocket = connect(toUri(ma), this.init)\n\n if (rawSocket.socket.on != null) {\n rawSocket.socket.on('error', errfn)\n } else {\n rawSocket.socket.onerror = errfn\n }\n\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise])\n\n log('connected %s', ma)\n return rawSocket\n }\n\n // Allow abort via signal during connect\n let onAbort\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError())\n rawSocket.close().catch(err => {\n log.error('error closing raw socket', err)\n })\n }\n\n // Already aborted?\n if (options?.signal?.aborted === true) {\n onAbort(); return\n }\n\n options?.signal?.addEventListener('abort', onAbort)\n })\n\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()])\n } finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n log('connected %s', ma)\n return rawSocket\n }\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: CreateListenerOptions): Listener {\n return createListener({ ...this.init, ...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: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs)\n }\n\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.wss(multiaddrs)\n }\n\n return filters.all(multiaddrs)\n }\n}\n\nexport function webSockets (init: WebSocketsInit = {}): (components?: any) => Transport {\n return () => {\n return new WebSockets(init)\n }\n}\n", "import type { Source } from 'it-stream-types'\nimport varint from 'varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from './alloc-unsafe.js'\nimport { Message, MessageTypes } from './message-types.js'\nimport batchedBytes from 'it-batched-bytes'\n\nconst POOL_SIZE = 10 * 1024\n\nclass Encoder {\n private _pool: Uint8Array\n private _poolOffset: number\n\n constructor () {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n }\n\n /**\n * Encodes the given message and adds it to the passed list\n */\n write (msg: Message, list: Uint8ArrayList): void {\n const pool = this._pool\n let offset = this._poolOffset\n\n varint.encode(msg.id << 3 | msg.type, pool, offset)\n offset += varint.encode.bytes ?? 0\n\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 } else {\n varint.encode(0, pool, offset)\n }\n\n offset += varint.encode.bytes ?? 0\n\n const header = pool.subarray(this._poolOffset, offset)\n\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n } else {\n this._poolOffset = offset\n }\n\n list.append(header)\n\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}\n\nconst encoder = new Encoder()\n\n/**\n * Encode and yield one or more messages\n */\nexport async function * encode (source: Source, minSendBytes: number = 0): AsyncGenerator {\n if (minSendBytes == null || minSendBytes === 0) {\n // just send the messages\n for await (const messages of source) {\n const list = new Uint8ArrayList()\n\n for (const msg of messages) {\n encoder.write(msg, list)\n }\n\n yield list.subarray()\n }\n\n return\n }\n\n // batch messages up for sending\n yield * batchedBytes(source, {\n size: minSendBytes,\n serialize: (obj, list) => {\n for (const m of obj) {\n encoder.write(m, list)\n }\n }\n })\n}\n", "export function allocUnsafe (size: number): Uint8Array {\n return new Uint8Array(size)\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\ntype INITIATOR_NAME = 'NEW_STREAM' | 'MESSAGE' | 'CLOSE' | 'RESET'\ntype RECEIVER_NAME = 'MESSAGE' | 'CLOSE' | 'RESET'\ntype NAME = 'NEW_STREAM' | 'MESSAGE_INITIATOR' | 'CLOSE_INITIATOR' | 'RESET_INITIATOR' | 'MESSAGE_RECEIVER' | 'CLOSE_RECEIVER' | 'RESET_RECEIVER'\ntype CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport enum MessageTypes {\n NEW_STREAM = 0,\n MESSAGE_RECEIVER = 1,\n MESSAGE_INITIATOR = 2,\n CLOSE_RECEIVER = 3,\n CLOSE_INITIATOR = 4,\n RESET_RECEIVER = 5,\n RESET_INITIATOR = 6\n}\n\nexport const MessageTypeNames: Record = 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})\n\nexport const InitiatorMessageTypes: Record = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n})\n\nexport const ReceiverMessageTypes: Record = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n})\n\nexport interface NewStreamMessage {\n id: number\n type: MessageTypes.NEW_STREAM\n data: Uint8ArrayList\n}\n\nexport interface MessageReceiverMessage {\n id: number\n type: MessageTypes.MESSAGE_RECEIVER\n data: Uint8ArrayList\n}\n\nexport interface MessageInitiatorMessage {\n id: number\n type: MessageTypes.MESSAGE_INITIATOR\n data: Uint8ArrayList\n}\n\nexport interface CloseReceiverMessage {\n id: number\n type: MessageTypes.CLOSE_RECEIVER\n}\n\nexport interface CloseInitiatorMessage {\n id: number\n type: MessageTypes.CLOSE_INITIATOR\n}\n\nexport interface ResetReceiverMessage {\n id: number\n type: MessageTypes.RESET_RECEIVER\n}\n\nexport interface ResetInitiatorMessage {\n id: number\n type: MessageTypes.RESET_INITIATOR\n}\n\nexport type Message = NewStreamMessage | MessageReceiverMessage | MessageInitiatorMessage | CloseReceiverMessage | CloseInitiatorMessage | ResetReceiverMessage | ResetInitiatorMessage\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport defer from 'p-defer'\nimport type { Source } from 'it-stream-types'\n\nconst DEFAULT_BATCH_SIZE = 1024 * 1024\nconst DEFAULT_SERIALIZE = (buf: Uint8Array | Uint8ArrayList, list: Uint8ArrayList): void => { list.append(buf) }\n\nexport interface BatchedBytesOptions {\n /**\n * The minimum number of bytes that should be in a batch (default: 1MB)\n */\n size?: number\n\n /**\n * If this amount of time passes, yield all the bytes in the batch even\n * if they are below `size` (default: 0 - e.g. on every tick)\n */\n yieldAfter?: number\n}\n\nexport interface BatchedOptions {\n /**\n * The minimum number of bytes that should be in a batch (default: 1MB)\n */\n size?: number\n\n /**\n * If this amount of time passes, yield all the bytes in the batch even\n * if they are below `size` (default: 0 - e.g. on every tick)\n */\n yieldAfter?: number\n\n /**\n * If passed, this function should serialize the object and append the\n * result to the passed list\n */\n serialize: (object: T, list: Uint8ArrayList) => void\n}\n\n/**\n * Takes a stream of Uint8Arrays and/or Uint8ArrayLists and store them in\n * an internal buffer. Either once the buffer reaches the requested size\n * or the next event loop tick occurs, yield any bytes from the buffer.\n */\nfunction batchedBytes (source: Source, options?: BatchedBytesOptions): Source\nfunction batchedBytes (source: Source, options: BatchedOptions): Source\nasync function * batchedBytes (source: Source, options: any = {}): any {\n let buffer = new Uint8ArrayList()\n let ended = false\n let deferred = defer()\n\n let size = Number(options.size ?? DEFAULT_BATCH_SIZE)\n\n if (isNaN(size) || size === 0 || size < 0) {\n size = DEFAULT_BATCH_SIZE\n }\n\n const yieldAfter = options.yieldAfter ?? 0\n const serialize = options.serialize ?? DEFAULT_SERIALIZE\n\n void Promise.resolve().then(async () => {\n try {\n let timeout\n\n for await (const buf of source) {\n serialize(buf, buffer)\n\n if (buffer.byteLength >= size) {\n clearTimeout(timeout)\n deferred.resolve()\n continue\n }\n\n timeout = setTimeout(() => { // eslint-disable-line no-loop-func\n deferred.resolve()\n }, yieldAfter)\n }\n\n clearTimeout(timeout)\n deferred.resolve()\n } catch (err) {\n deferred.reject(err)\n } finally {\n ended = true\n }\n })\n\n while (!ended) { // eslint-disable-line no-unmodified-loop-condition\n await deferred.promise\n deferred = defer()\n if (buffer.byteLength > 0) {\n const b = buffer\n buffer = new Uint8ArrayList()\n yield b.subarray()\n }\n }\n}\n\nexport default batchedBytes\n", "import { MessageTypeNames, MessageTypes } from './message-types.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Message } from './message-types.js'\n\nexport const MAX_MSG_SIZE = 1 << 20 // 1MB\nexport const MAX_MSG_QUEUE_SIZE = 4 << 20 // 4MB\n\ninterface MessageHeader {\n id: number\n type: keyof typeof MessageTypeNames\n offset: number\n length: number\n}\n\nexport class Decoder {\n private readonly _buffer: Uint8ArrayList\n private _headerInfo: MessageHeader | null\n private readonly _maxMessageSize: number\n private readonly _maxUnprocessedMessageQueueSize: number\n\n constructor (maxMessageSize: number = MAX_MSG_SIZE, maxUnprocessedMessageQueueSize: number = MAX_MSG_QUEUE_SIZE) {\n this._buffer = new Uint8ArrayList()\n this._headerInfo = null\n this._maxMessageSize = maxMessageSize\n this._maxUnprocessedMessageQueueSize = maxUnprocessedMessageQueueSize\n }\n\n write (chunk: Uint8Array): Message[] {\n if (chunk == null || chunk.length === 0) {\n return []\n }\n\n this._buffer.append(chunk)\n\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\n const msgs: Message[] = []\n\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer)\n } catch (err: any) {\n if (err.code === 'ERR_MSG_TOO_BIG') {\n throw err\n }\n\n break // We haven't received enough data yet\n }\n }\n\n const { id, type, length, offset } = this._headerInfo\n const bufferedDataLength = this._buffer.length - offset\n\n if (bufferedDataLength < length) {\n break // not enough data yet\n }\n\n const msg: any = {\n id,\n type\n }\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\n msgs.push(msg)\n\n this._buffer.consume(offset + length)\n this._headerInfo = null\n }\n\n return msgs\n }\n\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader (data: Uint8ArrayList): MessageHeader {\n const {\n value: h,\n offset\n } = readVarInt(data)\n const {\n value: length,\n offset: end\n } = readVarInt(data, offset)\n\n const type = h & 7\n\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\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\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length }\n }\n}\n\nconst MSB = 0x80\nconst REST = 0x7F\n\nexport interface ReadVarIntResult {\n value: number\n offset: number\n}\n\nfunction readVarInt (buf: Uint8ArrayList, offset: number = 0): ReadVarIntResult {\n let res = 0\n let shift = 0\n let counter = offset\n let b: number\n const l = buf.length\n\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\n offset = counter - offset\n\n return {\n value: res,\n offset\n }\n}\n", "import { abortableSource } from 'abortable-iterator'\nimport { pushable } from 'it-pushable'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { MAX_MSG_SIZE } from './decode.js'\nimport { anySignal } from 'any-signal'\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { logger } from '@libp2p/logger'\nimport type { Message } from './message-types.js'\nimport type { StreamTimeline } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { MplexStream } from './mplex.js'\n\nconst log = logger('libp2p:mplex:stream')\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET'\nconst ERR_STREAM_ABORT = 'ERR_STREAM_ABORT'\nconst ERR_SINK_ENDED = 'ERR_SINK_ENDED'\nconst ERR_DOUBLE_SINK = 'ERR_DOUBLE_SINK'\n\nexport interface Options {\n id: number\n send: (msg: Message) => void\n name?: string\n onEnd?: (err?: Error) => void\n type?: 'initiator' | 'receiver'\n maxMsgSize?: number\n}\n\nexport function createStream (options: Options): MplexStream {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options\n\n const abortController = new AbortController()\n const resetController = new AbortController()\n const closeController = new AbortController()\n const Types = type === 'initiator' ? InitiatorMessageTypes : ReceiverMessageTypes\n const externalId = type === 'initiator' ? (`i${id}`) : `r${id}`\n const streamName = `${name == null ? id : name}`\n\n let sourceEnded = false\n let sinkEnded = false\n let sinkSunk = false\n let endErr: Error | undefined\n\n const timeline: StreamTimeline = {\n open: Date.now()\n }\n\n const onSourceEnd = (err?: Error): void => {\n if (sourceEnded) {\n return\n }\n\n sourceEnded = true\n log.trace('%s stream %s source end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sinkEnded) {\n stream.stat.timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const onSinkEnd = (err?: Error): void => {\n if (sinkEnded) {\n return\n }\n\n sinkEnded = true\n log.trace('%s stream %s sink end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sourceEnded) {\n timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const streamSource = pushable({\n onEnd: onSourceEnd\n })\n\n const stream: MplexStream = {\n // Close for both Reading and Writing\n close: () => {\n log.trace('%s stream %s close', type, streamName)\n\n stream.closeRead()\n stream.closeWrite()\n },\n\n // Close for reading\n closeRead: () => {\n log.trace('%s stream %s closeRead', type, streamName)\n\n if (sourceEnded) {\n return\n }\n\n streamSource.end()\n },\n\n // Close for writing\n closeWrite: () => {\n log.trace('%s stream %s closeWrite', type, streamName)\n\n if (sinkEnded) {\n return\n }\n\n closeController.abort()\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n // Close for reading and writing (local error)\n abort: (err: Error) => {\n log.trace('%s stream %s abort', type, streamName, err)\n // End the source with the passed error\n streamSource.end(err)\n abortController.abort()\n onSinkEnd(err)\n },\n\n // Close immediately for reading and writing (remote error)\n reset: () => {\n const err = new CodeError('stream reset', ERR_STREAM_RESET)\n resetController.abort()\n streamSource.end(err)\n onSinkEnd(err)\n },\n\n sink: async (source: Source) => {\n if (sinkSunk) {\n throw new CodeError('sink already called on stream', ERR_DOUBLE_SINK)\n }\n\n sinkSunk = true\n\n if (sinkEnded) {\n throw new CodeError('stream closed for writing', ERR_SINK_ENDED)\n }\n\n const signal = anySignal([\n abortController.signal,\n resetController.signal,\n closeController.signal\n ])\n\n try {\n source = abortableSource(source, signal)\n\n if (type === 'initiator') { // If initiator, open a new stream\n send({ id, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(streamName)) })\n }\n\n for await (let data of source) {\n while (data.length > 0) {\n if (data.length <= maxMsgSize) {\n send({ id, type: Types.MESSAGE, data: data instanceof Uint8Array ? new Uint8ArrayList(data) : data })\n break\n }\n data = data instanceof Uint8Array ? new Uint8ArrayList(data) : data\n send({ id, type: Types.MESSAGE, data: data.sublist(0, maxMsgSize) })\n data.consume(maxMsgSize)\n }\n }\n } catch (err: any) {\n if (err.type === 'aborted' && err.message === 'The operation was aborted') {\n if (closeController.signal.aborted) {\n return\n }\n\n if (resetController.signal.aborted) {\n err.message = 'stream reset'\n err.code = ERR_STREAM_RESET\n }\n\n if (abortController.signal.aborted) {\n err.message = 'stream aborted'\n err.code = ERR_STREAM_ABORT\n }\n }\n\n // Send no more data if this stream was remotely reset\n if (err.code === ERR_STREAM_RESET) {\n log.trace('%s stream %s reset', type, name)\n } else {\n log.trace('%s stream %s error', type, name, err)\n try {\n send({ id, type: Types.RESET })\n } catch (err) {\n log.trace('%s stream %s error sending reset', type, name, err)\n }\n }\n\n streamSource.end(err)\n onSinkEnd(err)\n return\n } finally {\n signal.clear()\n }\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n source: streamSource,\n\n sourcePush: (data: Uint8ArrayList) => {\n streamSource.push(data)\n },\n\n sourceReadableLength () {\n return streamSource.readableLength\n },\n\n stat: {\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n timeline\n },\n\n metadata: {},\n\n id: externalId\n }\n\n return stream\n}\n", "import { pushableV } from 'it-pushable'\nimport { abortableSource } from 'abortable-iterator'\nimport { encode } from './encode.js'\nimport { Decoder } from './decode.js'\nimport { MessageTypes, MessageTypeNames, Message } from './message-types.js'\nimport { createStream } from './stream.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { logger } from '@libp2p/logger'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { RateLimiterMemory } from 'rate-limiter-flexible'\nimport type { Sink } from 'it-stream-types'\nimport type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { MplexInit } from './index.js'\nimport { anySignal } from 'any-signal'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:mplex')\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\n\nfunction printMessage (msg: Message): any {\n const output: any = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n }\n\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray())\n }\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\n return output\n}\n\nexport interface MplexStream extends Stream {\n sourceReadableLength: () => number\n sourcePush: (data: Uint8ArrayList) => void\n}\n\ninterface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {}\n\nexport class MplexStreamMuxer implements StreamMuxer {\n public protocol = '/mplex/6.7.0'\n\n public sink: Sink\n public source: AsyncIterable\n\n private _streamId: number\n private readonly _streams: { initiators: Map, receivers: Map }\n private readonly _init: MplexStreamMuxerInit\n private readonly _source: { push: (val: Message) => void, end: (err?: Error) => void }\n private readonly closeController: AbortController\n private readonly rateLimiter: RateLimiterMemory\n\n constructor (init?: MplexStreamMuxerInit) {\n init = init ?? {}\n\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\n /**\n * An iterable sink\n */\n this.sink = this._createSink()\n\n /**\n * An iterable source\n */\n const source = this._createSource()\n this._source = source\n this.source = source\n\n /**\n * Close controller\n */\n this.closeController = new AbortController()\n\n this.rateLimiter = new RateLimiterMemory({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n })\n }\n\n /**\n * Returns a Map of streams and their ids\n */\n get streams (): Stream[] {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams: Stream[] = []\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream)\n }\n\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream)\n }\n return streams\n }\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?: string): Stream {\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 /**\n * Close or abort all tracked streams and stop the muxer\n */\n close (err?: Error | undefined): void {\n if (this.closeController.signal.aborted) return\n\n if (err != null) {\n this.streams.forEach(s => { s.abort(err) })\n } else {\n this.streams.forEach(s => { s.close() })\n }\n this.closeController.abort()\n }\n\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream (options: { id: number, name: string }): MplexStream {\n const { id, name } = options\n const registry = this._streams.receivers\n return this._newStream({ id, name, type: 'receiver', registry })\n }\n\n _newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map }): MplexStream {\n const { id, name, type, registry } = options\n\n log('new %s stream %s', type, id)\n\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\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`)\n }\n\n const send = (msg: Message): void => {\n if (log.enabled) {\n log.trace('%s stream %s send', type, id, printMessage(msg))\n }\n\n this._source.push(msg)\n }\n\n const onEnd = (): void => {\n log('%s stream with id %s and protocol %s ended', type, id, stream.stat.protocol)\n registry.delete(id)\n\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream)\n }\n }\n\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize })\n registry.set(id, stream)\n return stream\n }\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 (): Sink {\n const sink: Sink = async source => {\n const signal = anySignal([this.closeController.signal, this._init.signal])\n\n try {\n source = abortableSource(source, signal)\n\n const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize)\n\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg)\n }\n }\n\n this._source.end()\n } catch (err: any) {\n log('error in sink', err)\n this._source.end(err) // End the source with an error\n } finally {\n signal.clear()\n }\n }\n\n return sink\n }\n\n /**\n * Creates a source that restricts outgoing message sizes\n * and varint encodes them\n */\n _createSource (): any {\n const onEnd = (err?: Error): void => {\n this.close(err)\n }\n const source = pushableV({\n objectMode: true,\n onEnd\n })\n\n return Object.assign(encode(source, this._init.minSendBytes), {\n push: source.push,\n end: source.end,\n return: source.return\n })\n }\n\n async _handleIncoming (message: Message): Promise {\n const { id, type } = message\n\n if (log.enabled) {\n log.trace('incoming message', printMessage(message))\n }\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 log('too many inbound streams open')\n\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\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 } catch {\n 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._source.end(new Error('Too many open streams'))\n return\n }\n\n return\n }\n\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) })\n\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream)\n }\n\n return\n }\n\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers\n const stream = list.get(id)\n\n if (stream == null) {\n log('missing stream %s for message type %s', id, MessageTypeNames[type])\n\n return\n }\n\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE\n\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\n // Inform the stream consumer they are not fast enough\n const error = new CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL')\n stream.abort(error)\n\n return\n }\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 // We should expect no more data from the remote, stop reading\n stream.closeRead()\n break\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // Stop reading and writing to the stream immediately\n stream.reset()\n break\n default:\n log('unknown message type %s', type)\n }\n }\n}\n", "import type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport { MplexStreamMuxer } from './mplex.js'\n\nexport interface MplexInit {\n /**\n * The maximum size of message that can be sent in one go in bytes.\n * Messages larger than this will be split into multiple smaller\n * messages. If we receive a message larger than this an error will\n * be thrown and the connection closed. (default: 1MB)\n */\n maxMsgSize?: number\n\n /**\n * Constrains the size of the unprocessed message queue buffer.\n * Before messages are deserialized, the raw bytes are buffered to ensure\n * we have the complete message to deserialized. If the queue gets longer\n * than this value an error will be thrown and the connection closed.\n * (default: 4MB)\n */\n maxUnprocessedMessageQueueSize?: number\n\n /**\n * Each byte array written into a multiplexed stream is converted to one or\n * more messages which are sent as byte arrays to the remote node. Sending\n * lots of small messages can be expensive - use this setting to batch up\n * the serialized bytes of all messages sent during the current tick up to\n * this limit to send in one go similar to Nagle's algorithm. N.b. you\n * should benchmark your application carefully when using this setting as it\n * may cause the opposite of the desired effect. Omit this setting to send\n * all messages as they become available. (default: undefined)\n */\n minSendBytes?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. A request to open more than this will have a stream\n * reset message sent immediately as a response for the newly opened\n * stream id (default: 1024)\n */\n maxInboundStreams?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw (default: 1024)\n */\n maxOutboundStreams?: number\n\n /**\n * Incoming stream messages are buffered until processed by the stream\n * handler. If the buffer reaches this size in bytes the stream will\n * be reset (default: 4MB)\n */\n maxStreamBufferSize?: number\n\n /**\n * When `maxInboundStreams` is hit, if the remote continues try to open\n * more than this many new multiplexed streams per second the connection\n * will be closed (default: 5)\n */\n disconnectThreshold?: number\n}\n\nclass Mplex implements StreamMuxerFactory {\n public protocol = '/mplex/6.7.0'\n private readonly _init: MplexInit\n\n constructor (init: MplexInit = {}) {\n this._init = init\n }\n\n createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {\n return new MplexStreamMuxer({\n ...init,\n ...this._init\n })\n }\n}\n\nexport function mplex (init: MplexInit = {}): () => StreamMuxerFactory {\n return () => new Mplex(init)\n}\n", "export function isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n", "import * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { isAsyncIterable } from './utils.js'\nimport type { LengthEncoderFunction } from './index.js'\nimport type { Source } from 'it-stream-types'\n\ninterface EncoderOptions {\n lengthEncoder?: LengthEncoderFunction\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = varint.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n varint.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (source: Iterable, options?: EncoderOptions): Generator\nexport function encode (source: Source, options?: EncoderOptions): AsyncGenerator\nexport function encode (source: Source, options?: EncoderOptions): Generator | AsyncGenerator {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n function * maybeYield (chunk: Uint8Array | Uint8ArrayList): Generator {\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\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\n return (function * () {\n for (const chunk of source) {\n yield * maybeYield(chunk)\n }\n })()\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n", "/**\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/**\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/**\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/**\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", "/* eslint max-depth: [\"error\", 6] */\n\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError, UnexpectedEOFError } from './errors.js'\nimport { isAsyncIterable } from './utils.js'\nimport type { LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source } from 'it-stream-types'\n\nexport interface ReadState {\n dataLength: number\n}\n\nexport interface DecoderOptions {\n lengthDecoder?: LengthDecoderFunction\n onData?(data: Uint8ArrayList): void\n onLength?(length: number): void\n maxLengthLength?: number\n maxDataLength?: number\n}\n\nexport interface ReadResult {\n mode: string\n chunk?: Uint8ArrayList\n buffer: Uint8ArrayList\n state?: ReadState\n data?: Uint8ArrayList\n}\n\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\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = varint.decode(buf)\n defaultDecoder.bytes = varint.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (source: Iterable, options?: DecoderOptions): Generator\nexport function decode (source: Source, options?: DecoderOptions): AsyncGenerator\nexport function decode (source: Source, options?: DecoderOptions): Generator | AsyncGenerator {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n function * maybeYield (): Generator {\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\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length')\n }\n\n if (dataLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new InvalidDataLengthLengthError('Message length length too long')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n }\n\n return (function * () {\n for (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n}\n\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number): void => { byteLength = l }\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n })\n}\n", "/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive Protobuf encoded messages over\n * streams.\n *\n * @example\n *\n * ```typescript\n * import { pbStream } from 'it-pb-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 * stream.writePB({\n * foo: 'bar'\n * }, MessageType)\n * const res = await stream.readPB(MessageType)\n * ```\n */\n\nimport * as lp from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { pushable } from 'it-pushable'\nimport { unsigned } from 'uint8-varint'\nimport errCode from 'err-code'\n\n/**\n * A protobuf decoder - takes a byte array and returns an object\n */\nexport interface Decoder {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\n/**\n * A protobuf encoder - takes an object and returns a byte array\n */\nexport interface Encoder {\n (data: T): Uint8Array\n}\n\n/**\n * A message reader/writer that only uses one type of message\n */\nexport interface MessageStream = Duplex> {\n /**\n * Read a message from the stream\n */\n read: () => Promise\n\n /**\n * Write a message to the stream\n */\n write: (d: T) => void\n\n /**\n * Unwrap the underlying protobuf stream\n */\n unwrap: () => ProtobufStream\n}\n\n/**\n * Convenience methods for working with protobuf streams\n */\nexport interface ProtobufStream = Duplex> {\n /**\n * Read a set number of bytes from the stream\n */\n read: (bytes?: number) => Promise\n\n /**\n * Read the next length-prefixed number of bytes from the stream\n */\n readLP: () => Promise\n\n /**\n * Read the next length-prefixed byte array from the stream and decode it as the passed protobuf format\n */\n readPB: (proto: { decode: Decoder }) => Promise\n\n /**\n * Write the passed bytes to the stream\n */\n write: (input: Uint8Array | Uint8ArrayList) => void\n\n /**\n * Write the passed bytes to the stream prefixed by their length\n */\n writeLP: (input: Uint8Array | Uint8ArrayList) => void\n\n /**\n * Encode the passed object as a protobuf message and write it's length-prefixed bytes tot he stream\n */\n writePB: (data: T, proto: { encode: Encoder }) => void\n\n /**\n * Returns an object with read/write methods for operating on one specific type of protobuf message\n */\n pb: (proto: { encode: Encoder, decode: Decoder }) => MessageStream\n\n /**\n * Returns the underlying stream\n */\n unwrap: () => Stream\n}\n\nexport interface Opts {\n // encoding opts\n poolSize: number\n minPoolSize: number\n lengthEncoder: lp.LengthEncoderFunction\n\n // decoding opts\n lengthDecoder: lp.LengthDecoderFunction\n maxLengthLength: number\n maxDataLength: number\n}\n\nconst defaultLengthDecoder: lp.LengthDecoderFunction = (buf) => {\n return unsigned.decode(buf)\n}\ndefaultLengthDecoder.bytes = 0\n\nexport function pbStream > (duplex: Stream, opts?: Partial): ProtobufStream\nexport function pbStream > (duplex: Duplex, opts?: Partial): ProtobufStream\nexport function pbStream (duplex: any, opts: Partial = {}): ProtobufStream {\n const write = pushable()\n\n duplex.sink(write).catch((err: Error) => {\n write.end(err)\n })\n\n duplex.sink = async (source: any) => {\n for await (const buf of source) {\n write.push(buf)\n }\n }\n\n let source = duplex.source\n\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]()\n } else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]()\n }\n\n const readBuffer = new Uint8ArrayList()\n\n const W: ProtobufStream = {\n read: async (bytes) => {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await source.next()\n\n if (done === true) {\n return new Uint8ArrayList()\n }\n\n return value\n }\n\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await source.next()\n\n if (done === true) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF')\n }\n\n readBuffer.append(value)\n }\n\n const buf = readBuffer.sublist(0, bytes)\n readBuffer.consume(bytes)\n\n return buf\n },\n readLP: async () => {\n let dataLength: number = -1\n const lengthBuffer = new Uint8ArrayList()\n const decodeLength = opts?.lengthDecoder ?? defaultLengthDecoder\n\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await W.read(1))\n\n try {\n dataLength = decodeLength(lengthBuffer)\n } catch (err) {\n if (err instanceof RangeError) {\n continue\n }\n\n throw err\n }\n\n if (dataLength > -1) {\n break\n }\n\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG')\n }\n }\n\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG')\n }\n\n return await W.read(dataLength)\n },\n readPB: async (proto) => {\n // readLP, decode\n const value = await W.readLP()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n // Is this a buffer?\n const buf = value instanceof Uint8Array ? value : value.subarray()\n\n return proto.decode(buf)\n },\n write: (data) => {\n // just write\n if (data instanceof Uint8Array) {\n write.push(data)\n } else {\n write.push(data.subarray())\n }\n },\n writeLP: (data) => {\n // encode, write\n W.write(lp.encode.single(data, opts))\n },\n writePB: (data, proto) => {\n // encode, writeLP\n W.writeLP(proto.encode(data))\n },\n pb: (proto) => {\n return {\n read: async () => await W.readPB(proto),\n write: (d) => { W.writePB(d, proto) },\n unwrap: () => W\n }\n },\n unwrap: () => {\n const originalStream = duplex.source\n duplex.source = (async function * () {\n yield * readBuffer\n yield * originalStream\n }())\n\n return duplex\n }\n }\n\n return W\n}\n", "import defer from 'p-defer'\nimport type { Source, Duplex } from 'it-stream-types'\n\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair (): Duplex, Source, Promise> {\n const deferred = defer>()\n let piped = false\n\n return {\n sink: async source => {\n if (piped) {\n throw new Error('already piped')\n }\n\n piped = true\n deferred.resolve(source)\n },\n source: (async function * () {\n const source = await deferred.promise\n\n yield * source\n }())\n }\n}\n", "import { pair } from './index.js'\nimport type { Duplex, Source } from 'it-stream-types'\n\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair (): [Duplex, Source, Promise>, Duplex, Source, Promise>] {\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", "export const NOISE_MSG_MAX_LENGTH_BYTES = 65535\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16\n\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS)\n", "import { HKDF } from '@stablelib/hkdf'\nimport * as x25519 from '@stablelib/x25519'\nimport { SHA256, hash } from '@stablelib/sha256'\nimport { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305'\nimport type { bytes32, bytes } from '../@types/basic.js'\nimport type { Hkdf } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { ICryptoInterface } from '../crypto.js'\n\nexport const stablelib: ICryptoInterface = {\n hashSHA256 (data: Uint8Array): Uint8Array {\n return hash(data)\n },\n\n getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {\n const hkdf = new HKDF(SHA256, ikm, ck)\n const okmU8Array = hkdf.expand(96)\n const okm = okmU8Array\n\n const k1 = okm.subarray(0, 32)\n const k2 = okm.subarray(32, 64)\n const k3 = okm.subarray(64, 96)\n\n return [k1, k2, k3]\n },\n\n generateX25519KeyPair (): KeyPair {\n const keypair = x25519.generateKeyPair()\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {\n const keypair = x25519.generateKeyPairFromSeed(seed)\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array {\n return x25519.sharedKey(privateKey, publicKey)\n },\n\n chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.seal(nonce, plaintext, ad)\n },\n\n chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32, dst?: Uint8Array): bytes | null {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.open(nonce, ciphertext, ad, dst)\n }\n}\n", "import { TAG_LENGTH } from '@stablelib/chacha20poly1305'\nimport type { Transform } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { IHandshake } from '../@types/handshake-interface.js'\nimport type { MetricsRegistry } from '../metrics.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'\nimport { uint16BEEncode } from '../encoder.js'\n\n// Returns generator that encrypts payload from the user\nexport function encryptStream (handshake: IHandshake, metrics?: MetricsRegistry): Transform {\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\n const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)\n metrics?.encryptedPackets.increment()\n\n yield uint16BEEncode(data.byteLength)\n yield data\n }\n }\n }\n}\n\n// Decrypt received payload to the user\nexport function decryptStream (handshake: IHandshake, metrics?: MetricsRegistry): Transform {\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\n if (end - TAG_LENGTH < i) {\n throw new Error('Invalid chunk')\n }\n const encrypted = chunk.subarray(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 - TAG_LENGTH)\n const { plaintext: decrypted, valid } = handshake.decrypt(encrypted, handshake.session, dst)\n if (!valid) {\n metrics?.decryptErrors.increment()\n throw new Error('Failed to validate decrypted chunk')\n }\n metrics?.decryptedPackets.increment()\n yield decrypted\n }\n }\n }\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { bytes } from './@types/basic.js'\nimport type { MessageBuffer } from './@types/handshake.js'\nimport type { LengthDecoderFunction } from 'it-length-prefixed'\n\nconst allocUnsafe = (len: number): Uint8Array => {\n if (globalThis.Buffer) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n\nexport const uint16BEEncode = (value: number): Uint8Array => {\n const target = allocUnsafe(2)\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)\n return target\n}\nuint16BEEncode.bytes = 2\n\nexport const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {\n if (data.length < 2) throw RangeError('Could not decode int16BE')\n\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)\n }\n\n return data.getUint16(0)\n}\nuint16BEDecode.bytes = 2\n\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\n\nexport function encode0 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)\n}\n\nexport function encode1 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)\n}\n\nexport function encode2 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)\n}\n\nexport function decode0 (input: bytes): MessageBuffer {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: new Uint8Array(0)\n }\n}\n\nexport function decode1 (input: bytes): MessageBuffer {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n }\n}\n\nexport function decode2 (input: bytes): MessageBuffer {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')\n }\n\n return {\n ne: new Uint8Array(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n }\n}\n", "\nexport class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.code = UnexpectedPeerError.code\n }\n\n static get code (): string {\n return 'ERR_UNEXPECTED_PEER'\n }\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.code = InvalidCryptoExchangeError.code\n }\n\n static get code (): string {\n return 'ERR_INVALID_CRYPTO_EXCHANGE'\n }\n}\n\nexport class InvalidCryptoTransmissionError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto transmission') {\n super(message)\n this.code = InvalidCryptoTransmissionError.code\n }\n\n static get code (): string {\n return 'ERR_INVALID_CRYPTO_TRANSMISSION'\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface NoiseExtensions {\n webtransportCerthashes: Uint8Array[]\n}\n\nexport namespace NoiseExtensions {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.webtransportCerthashes != null) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n webtransportCerthashes: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.webtransportCerthashes.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, NoiseExtensions.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseExtensions => {\n return decodeMessage(buf, NoiseExtensions.codec())\n }\n}\n\nexport interface NoiseHandshakePayload {\n identityKey: Uint8Array\n identitySig: Uint8Array\n extensions?: NoiseExtensions\n}\n\nexport namespace NoiseHandshakePayload {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.identityKey ?? new Uint8Array(0))\n }\n\n if (opts.writeDefaults === true || (obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.identitySig ?? new Uint8Array(0))\n }\n\n if (obj.extensions != null) {\n w.uint32(34)\n NoiseExtensions.codec().encode(obj.extensions, w, {\n writeDefaults: false\n })\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n identityKey: new Uint8Array(0),\n identitySig: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identityKey = reader.bytes()\n break\n case 2:\n obj.identitySig = reader.bytes()\n break\n case 4:\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, NoiseHandshakePayload.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseHandshakePayload => {\n return decodeMessage(buf, NoiseHandshakePayload.codec())\n }\n}\n", "import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { bytes } from './@types/basic.js'\nimport { NoiseExtensions, NoiseHandshakePayload } from './proto/payload.js'\n\nexport async function getPayload (\n localPeer: PeerId,\n staticPublicKey: bytes,\n extensions?: NoiseExtensions\n): Promise {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey))\n\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId')\n }\n\n return createHandshakePayload(\n localPeer.publicKey,\n signedPayload,\n extensions\n )\n}\n\nexport function createHandshakePayload (\n libp2pPublicKey: Uint8Array,\n signedPayload: Uint8Array,\n extensions?: NoiseExtensions\n): bytes {\n return NoiseHandshakePayload.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n extensions: extensions ?? { webtransportCerthashes: [] }\n }).subarray()\n}\n\nexport async function signPayload (peerId: PeerId, payload: bytes): Promise {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId')\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return await privateKey.sign(payload)\n}\n\nexport async function getPeerIdFromPayload (payload: NoiseHandshakePayload): Promise {\n return await peerIdFromKeys(payload.identityKey)\n}\n\nexport function decodePayload (payload: bytes | Uint8Array): NoiseHandshakePayload {\n return NoiseHandshakePayload.decode(payload)\n}\n\nexport function getHandshakePayload (publicKey: bytes): bytes {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:')\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length)\n}\n\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload (\n noiseStaticKey: bytes,\n payload: NoiseHandshakePayload,\n remotePeer: PeerId\n): Promise {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey)\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(`Payload identity key ${payloadPeerId.toString()} does not match expected remote peer ${remotePeer.toString()}`)\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey)\n\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId')\n }\n\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message')\n }\n\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey)\n\n const valid = await publicKey.verify(generatedPayload, payload.identitySig)\n\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\")\n }\n\n return payloadPeerId\n}\n\nexport function isValidPublicKey (pk: bytes): boolean {\n if (!(pk instanceof Uint8Array)) {\n return false\n }\n\n if (pk.length !== 32) {\n return false\n }\n\n return true\n}\n", "import { Logger, logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { DUMP_SESSION_KEYS } from './constants.js'\n\nconst log = logger('libp2p:noise')\n\nexport { log as logger }\n\nlet keyLogger: Logger\nif (DUMP_SESSION_KEYS) {\n keyLogger = log\n} else {\n keyLogger = Object.assign(() => { /* do nothing */ }, {\n enabled: false,\n trace: () => {},\n error: () => {}\n })\n}\n\nexport function logLocalStaticKeys (s: KeyPair): void {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)\n}\n\nexport function logLocalEphemeralKeys (e: KeyPair | undefined): void {\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)\n } else {\n keyLogger('Missing local ephemeral keys.')\n }\n}\n\nexport function logRemoteStaticKey (rs: Uint8Array): void {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs, 'hex')}`)\n}\n\nexport function logRemoteEphemeralKey (re: Uint8Array): void {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re, 'hex')}`)\n}\n\nexport function logCipherState (session: NoiseSession): void {\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)\n } else {\n keyLogger('Missing cipher state.')\n }\n}\n", "import type { bytes, uint64 } from './@types/basic'\n\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\n\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'\n\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n private n: uint64\n private readonly bytes: bytes\n private readonly view: DataView\n\n constructor (n = MIN_NONCE) {\n this.n = n\n this.bytes = new Uint8Array(12)\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)\n this.view.setUint32(4, n, true)\n }\n\n increment (): void {\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\n getBytes (): bytes {\n return this.bytes\n }\n\n getUint64 (): uint64 {\n return this.n\n }\n\n assertValue (): void {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE)\n }\n }\n}\n", "import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays'\nimport type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, MessageBuffer, SymmetricState } from '../@types/handshake.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport { logger } from '../logger.js'\nimport { Nonce } from '../nonce.js'\n\nexport interface DecryptedResult {\n plaintext: bytes\n valid: boolean\n}\n\nexport interface SplitState {\n cs1: CipherState\n cs2: CipherState\n}\n\nexport abstract class AbstractHandshake {\n public crypto: ICryptoInterface\n\n constructor (crypto: ICryptoInterface) {\n this.crypto = crypto\n }\n\n public encryptWithAd (cs: CipherState, ad: Uint8Array, plaintext: Uint8Array): bytes {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext)\n cs.n.increment()\n\n return e\n }\n\n public decryptWithAd (cs: CipherState, ad: Uint8Array, ciphertext: Uint8Array, dst?: Uint8Array): DecryptedResult {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext, dst)\n if (valid) cs.n.increment()\n\n return { plaintext, valid }\n }\n\n // Cipher state related\n protected hasKey (cs: CipherState): boolean {\n return !this.isEmptyKey(cs.k)\n }\n\n protected createEmptyKey (): bytes32 {\n return new Uint8Array(32)\n }\n\n protected isEmptyKey (k: bytes32): boolean {\n const emptyKey = this.createEmptyKey()\n return uint8ArrayEquals(emptyKey, k)\n }\n\n protected encrypt (k: bytes32, n: Nonce, ad: Uint8Array, plaintext: Uint8Array): bytes {\n n.assertValue()\n\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k)\n }\n\n protected encryptAndHash (ss: SymmetricState, plaintext: bytes): bytes {\n let ciphertext\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext)\n } else {\n ciphertext = plaintext\n }\n\n this.mixHash(ss, ciphertext)\n return ciphertext\n }\n\n protected decrypt (k: bytes32, n: Nonce, ad: bytes, ciphertext: bytes, dst?: Uint8Array): DecryptedResult {\n n.assertValue()\n\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k, dst)\n\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n }\n } else {\n return {\n plaintext: new Uint8Array(0),\n valid: false\n }\n }\n }\n\n protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): DecryptedResult {\n let plaintext: bytes; let valid = true\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext))\n } else {\n plaintext = ciphertext\n }\n\n this.mixHash(ss, ciphertext)\n return { plaintext, valid }\n }\n\n protected dh (privateKey: bytes32, publicKey: bytes32): bytes32 {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey)\n\n if (derivedU8.length === 32) {\n return derivedU8\n }\n\n return derivedU8.subarray(0, 32)\n } catch (e) {\n const err = e as Error\n logger.error(err)\n return new Uint8Array(32)\n }\n }\n\n protected mixHash (ss: SymmetricState, data: bytes): void {\n ss.h = this.getHash(ss.h, data)\n }\n\n protected getHash (a: Uint8Array, b: Uint8Array): bytes32 {\n const u = this.crypto.hashSHA256(uint8ArrayConcat([a, b], a.length + b.length))\n return u\n }\n\n protected mixKey (ss: SymmetricState, ikm: bytes32): void {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm)\n ss.cs = this.initializeKey(tempK)\n ss.ck = ck\n }\n\n protected initializeKey (k: bytes32): CipherState {\n return { k, n: new Nonce() }\n }\n\n // Symmetric state related\n\n protected initializeSymmetric (protocolName: string): SymmetricState {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8')\n const h = this.hashProtocolName(protocolNameBytes)\n\n const ck = h\n const key = this.createEmptyKey()\n const cs: CipherState = this.initializeKey(key)\n\n return { cs, ck, h }\n }\n\n protected hashProtocolName (protocolName: Uint8Array): bytes32 {\n if (protocolName.length <= 32) {\n const h = new Uint8Array(32)\n h.set(protocolName)\n return h\n } else {\n return this.getHash(protocolName, new Uint8Array(0))\n }\n }\n\n protected split (ss: SymmetricState): SplitState {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, new Uint8Array(0))\n const cs1 = this.initializeKey(tempk1)\n const cs2 = this.initializeKey(tempk2)\n\n return { cs1, cs2 }\n }\n\n protected writeMessageRegular (cs: CipherState, payload: bytes): MessageBuffer {\n const ciphertext = this.encryptWithAd(cs, new Uint8Array(0), payload)\n const ne = this.createEmptyKey()\n const ns = new Uint8Array(0)\n\n return { ne, ns, ciphertext }\n }\n\n protected readMessageRegular (cs: CipherState, message: MessageBuffer): DecryptedResult {\n return this.decryptWithAd(cs, new Uint8Array(0), message.ciphertext)\n }\n}\n", "import type { bytes32, bytes } from '../@types/basic.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport { AbstractHandshake, DecryptedResult } from './abstract-handshake.js'\n\nexport class XX extends AbstractHandshake {\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer {\n const ns = new Uint8Array(0)\n\n if (e !== undefined) {\n hs.e = e\n } else {\n hs.e = this.crypto.generateX25519KeyPair()\n }\n\n const ne = hs.e.publicKey\n\n this.mixHash(hs.ss, ne)\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageC (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes } {\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ne = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, messageBuffer, cs1, cs2 }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): DecryptedResult {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n return this.decryptAndHash(hs.ss, message.ciphertext)\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): DecryptedResult {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageC (hs: HandshakeState, message: MessageBuffer): { h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState } {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 }\n }\n\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair): NoiseSession {\n const psk = this.createEmptyKey()\n const rs = new Uint8Array(32) // no static key yet\n let hs\n\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes, ephemeral?: KeyPair): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral)\n } else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message)\n } else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message)\n messageBuffer = resultingBuffer\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): DecryptedResult {\n let plaintext: bytes = new Uint8Array(0)\n let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n } else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message))\n } else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message)\n plaintext = resultingPlaintext\n valid = resultingValid\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from '@libp2p/interface-connection-encrypter/errors'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js'\nimport { XX } from './handshakes/xx.js'\nimport {\n logger,\n logLocalStaticKeys,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logRemoteStaticKey,\n logCipherState\n} from './logger.js'\nimport {\n decodePayload,\n getPeerIdFromPayload,\n verifySignedPayload\n} from './utils.js'\nimport type { NoiseExtensions } from './proto/payload.js'\n\nexport class XXHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteExtensions: NoiseExtensions = { webtransportCerthashes: [] }\n\n protected payload: bytes\n protected connection: ProtobufStream\n protected xx: XX\n protected staticKeypair: KeyPair\n\n private readonly prologue: bytes32\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remotePeer?: PeerId,\n handshake?: XX\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.xx = handshake ?? new XX(crypto)\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair)\n }\n\n // stage 0\n public async propose (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n if (this.isInitiator) {\n logger.trace('Stage 0 - Initiator starting to send first message.')\n const messageBuffer = this.xx.sendMessage(this.session, new Uint8Array(0))\n this.connection.writeLP(encode0(messageBuffer))\n logger.trace('Stage 0 - Initiator finished sending first message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger.trace('Stage 0 - Responder waiting to receive first message...')\n const receivedMessageBuffer = decode0((await this.connection.readLP()).subarray())\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail')\n }\n logger.trace('Stage 0 - Responder received first message.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n logger.trace('Stage 1 - Initiator waiting to receive first message from responder...')\n const receivedMessageBuffer = decode1((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail')\n }\n logger.trace('Stage 1 - Initiator received the message.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger.trace(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteNoiseExtension(decodedPayload.extensions)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n logger.trace('All good with the signature!')\n } else {\n logger.trace('Stage 1 - Responder sending out first message with signed payload and static key.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger.trace('Stage 1 - Responder sent the second handshake message with signed payload.')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n }\n\n // stage 2\n public async finish (): Promise {\n if (this.isInitiator) {\n logger.trace('Stage 2 - Initiator sending third handshake message.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode2(messageBuffer))\n logger.trace('Stage 2 - Initiator sent message with signed payload.')\n } else {\n logger.trace('Stage 2 - Responder waiting for third handshake message...')\n const receivedMessageBuffer = decode2((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail')\n }\n logger.trace('Stage 2 - Responder received the message, finished handshake.')\n\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteNoiseExtension(decodedPayload.extensions)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n }\n logCipherState(this.session)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n\n return this.xx.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession, dst?: Uint8Array): { plaintext: bytes, valid: boolean } {\n const cs = this.getCS(session, false)\n\n return this.xx.decryptWithAd(cs, new Uint8Array(0), ciphertext, dst)\n }\n\n public getRemoteStaticKey (): bytes {\n return this.session.hs.rs\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n protected setRemoteNoiseExtension (e: NoiseExtensions | null | undefined): void {\n if (e) {\n this.remoteExtensions = e\n }\n }\n}\n", "import type { Counter, Metrics } from '@libp2p/interface-metrics'\n\nexport type MetricsRegistry = Record\n\nexport function registerMetrics (metrics: Metrics): MetricsRegistry {\n return {\n xxHandshakeSuccesses: metrics.registerCounter(\n 'libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n\n xxHandshakeErrors: metrics.registerCounter(\n 'libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n\n encryptedPackets: metrics.registerCounter(\n 'libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n\n decryptedPackets: metrics.registerCounter(\n 'libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n\n decryptErrors: metrics.registerCounter(\n 'libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport { pbStream, ProtobufStream } from 'it-pb-stream'\nimport { duplexPair } from 'it-pair/duplex'\nimport { pipe } from 'it-pipe'\nimport { decode } from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { bytes } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { INoiseConnection, KeyPair } from './@types/libp2p.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { stablelib } from './crypto/stablelib.js'\nimport { decryptStream, encryptStream } from './crypto/streaming.js'\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport { getPayload } from './utils.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { MetricsRegistry, registerMetrics } from './metrics.js'\n\ninterface HandshakeParams {\n connection: ProtobufStream\n isInitiator: boolean\n localPeer: PeerId\n remotePeer?: PeerId\n}\n\nexport interface NoiseInit {\n /**\n * x25519 private key, reuse for faster handshakes\n */\n staticNoiseKey?: bytes\n extensions?: NoiseExtensions\n crypto?: ICryptoInterface\n prologueBytes?: Uint8Array\n metrics?: Metrics\n}\n\nexport class Noise implements INoiseConnection {\n public protocol = '/noise'\n public crypto: ICryptoInterface\n\n private readonly prologue: Uint8Array\n private readonly staticKeys: KeyPair\n private readonly extensions?: NoiseExtensions\n private readonly metrics?: MetricsRegistry\n\n constructor (init: NoiseInit = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes, metrics } = init\n\n this.crypto = crypto ?? stablelib\n this.extensions = extensions\n this.metrics = metrics ? registerMetrics(metrics) : undefined\n\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey)\n } else {\n this.staticKeys = this.crypto.generateX25519KeyPair()\n }\n this.prologue = prologueBytes ?? new Uint8Array(0)\n }\n\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {Duplex} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise}\n */\n public async secureOutbound (localPeer: PeerId, connection: Duplex, remotePeer?: PeerId): Promise> {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteExtensions: handshake.remoteExtensions,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {Duplex} connection - streaming iterable duplex that will be encryption.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise}\n */\n public async secureInbound (localPeer: PeerId, connection: Duplex, remotePeer?: PeerId): Promise> {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remotePeer: handshake.remotePeer,\n remoteExtensions: handshake.remoteExtensions\n }\n }\n\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n private async performHandshake (params: HandshakeParams): Promise {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.extensions)\n\n // run XX handshake\n return await this.performXXHandshake(params, payload)\n }\n\n private async performXXHandshake (\n params: HandshakeParams,\n payload: bytes\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake = new XXHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n remotePeer\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n this.metrics?.xxHandshakeSuccesses.increment()\n } catch (e: unknown) {\n this.metrics?.xxHandshakeErrors.increment()\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`\n throw e\n }\n }\n\n return handshake\n }\n\n private async createSecureConnection (\n connection: ProtobufStream,\n handshake: IHandshake\n ): Promise> {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair()\n const network = connection.unwrap()\n\n await pipe(\n secure, // write to wrapper\n encryptStream(handshake, this.metrics), // encrypt data + prefix with message length\n network, // send to the remote peer\n decode({ lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake, this.metrics), // decrypt the incoming data\n secure // pipe to the wrapper\n )\n\n return user\n }\n}\n", "import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport { Noise } from './noise.js'\nimport type { NoiseInit } from './noise.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nexport * from './crypto.js'\nexport * from './crypto/stablelib.js'\n\nexport function noise (init: NoiseInit = {}): () => ConnectionEncrypter {\n return () => new Noise(init)\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerIdProto {\n id?: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.id != null) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.pubKey != null) {\n w.uint32(18)\n w.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n w.uint32(26)\n w.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n", "import { 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'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\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}\n\nexport async function createFromProtobuf (buf: Uint8Array): Promise {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return createFromParts(\n id ?? new Uint8Array(0),\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }): Promise {\n return createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array): Promise {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey)\n\n return createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n", "import { logger } from '@libp2p/logger'\nimport { createRepo } from 'ipfs-core-config/repo'\nimport getDefaultConfig from 'ipfs-core-config/config'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport mergeOpts from 'merge-options'\nimport { profiles as configProfiles } from './config/profiles.js'\nimport { NotEnabledError, NotInitializedError } from '../errors.js'\nimport { createLibp2p } from './libp2p.js'\nimport { ERR_REPO_NOT_INITIALIZED } from 'ipfs-repo/errors'\nimport { createEd25519PeerId, createRSAPeerId } from '@libp2p/peer-id-factory'\nimport errCode from 'err-code'\nimport { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport { Key } from 'interface-datastore/key'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:components:peer:storage')\n\n/**\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('../types').Options} IPFSOptions\n * @typedef {import('../types').InitOptions} InitOptions\n * @typedef {import('../types').Print} Print\n * @typedef {import('ipfs-core-types/src/config').Config} IPFSConfig\n * @typedef {import('@libp2p/crypto/keys').KeyTypes} KeyType\n * @typedef {import('@libp2p/interface-keychain').KeyChain} Keychain\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\nexport class Storage {\n /**\n * @private\n * @param {PeerId} peerId\n * @param {Keychain} keychain\n * @param {IPFSRepo} repo\n * @param {Print} print\n * @param {boolean} isNew\n */\n constructor (peerId, keychain, repo, print, isNew) {\n this.print = print\n this.peerId = peerId\n this.keychain = keychain\n this.repo = repo\n this.print = print\n this.isNew = isNew\n }\n\n /**\n * @param {Print} print\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {IPFSOptions} options\n */\n static async start (print, codecs, options) {\n const { repoAutoMigrate, repo: inputRepo, onMigrationProgress } = options\n\n const repo = (typeof inputRepo === 'string' || inputRepo == null)\n ? createRepo(print, codecs, {\n path: inputRepo,\n autoMigrate: repoAutoMigrate,\n onMigrationProgress: onMigrationProgress\n })\n : inputRepo\n\n const { peerId, keychain, isNew } = await loadRepo(print, repo, options)\n\n // TODO: throw error?\n // @ts-expect-error On start, keychain will always be available\n return new Storage(peerId, keychain, repo, print, isNew)\n }\n}\n\n/**\n * @param {Print} print\n * @param {IPFSRepo} repo\n * @param {IPFSOptions} options\n */\nconst loadRepo = async (print, repo, options) => {\n if (!repo.closed) {\n return { ...await configureRepo(repo, options), isNew: false }\n }\n\n try {\n await repo.open()\n\n return { ...await configureRepo(repo, options), isNew: false }\n } catch (/** @type {any} */ err) {\n if (err.code !== ERR_REPO_NOT_INITIALIZED) {\n throw err\n }\n\n if (options.init && options.init.allowNew === false) {\n throw new NotEnabledError('Initialization of new repos disabled by config, pass `config.init.isNew: true` to enable it')\n }\n\n return { ...await initRepo(print, repo, options), isNew: true }\n }\n}\n\n/**\n * @param {Print} print\n * @param {IPFSRepo} repo\n * @param {IPFSOptions} options\n * @returns {Promise<{peerId: PeerId, keychain?: Keychain}>}\n */\nconst initRepo = async (print, repo, options) => {\n const initOptions = options.init || {}\n\n // 1. Verify that repo does not exist yet (if it does and we could not open it we give up)\n const exists = await repo.exists()\n log('repo exists?', exists)\n\n if (exists === true) {\n throw new Error('repo already exists')\n }\n\n // 2. Restore `peerId` from a given `.privateKey` or init new using provided options.\n const peerId = initOptions.privateKey\n ? await decodePeerId(initOptions.privateKey)\n : await initPeerId(print, initOptions)\n\n const identity = peerIdToIdentity(peerId)\n\n log('peer identity: %s', identity.PeerID)\n\n // 3. Init new repo with provided `.config` and restored / initialized `peerId`\n const config = {\n ...mergeOptions(applyProfiles(getDefaultConfig(), initOptions.profiles), options.config),\n Identity: identity\n }\n await repo.init(config)\n\n // 4. Open initialized repo.\n await repo.open()\n\n log('repo opened')\n\n /** @type {import('./libp2p').KeychainConfig} */\n const keychainConfig = {\n pass: options.pass\n }\n\n try {\n keychainConfig.dek = await repo.config.get('Keychain.DEK')\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n // Create libp2p for Keychain creation\n const libp2p = await createLibp2p({\n options: undefined,\n multiaddrs: undefined,\n peerId,\n repo,\n config,\n keychainConfig\n })\n\n if (!(await repo.datastore.has(new Key('/info/self')))) {\n await libp2p.keychain.importPeer('self', peerId)\n }\n\n await repo.config.set('Keychain', {\n // @ts-expect-error private field\n DEK: libp2p.keychain.init.dek\n })\n\n return { peerId, keychain: libp2p.keychain }\n}\n\n/**\n * Takes `peerId` either represented as a string serialized string or\n * an instance and returns a `PeerId` instance.\n *\n * @param {PeerId|string} peerId\n * @returns {Promise}\n */\nconst decodePeerId = async (peerId) => {\n log('using user-supplied private-key')\n if (isPeerId(peerId)) {\n return peerId\n }\n\n const rawPrivateKey = uint8ArrayFromString(peerId, 'base64pad')\n const key = await unmarshalPrivateKey(rawPrivateKey)\n return await peerIdFromKeys(key.public.bytes, key.bytes)\n}\n\n/**\n * Initializes new PeerId by generating an underlying keypair.\n *\n * @param {Print} print\n * @param {object} options\n * @param {KeyType} [options.algorithm='Ed25519']\n * @param {number} [options.bits=2048]\n * @returns {Promise}\n */\nconst initPeerId = (print, { algorithm = 'Ed25519', bits = 2048 }) => {\n // Generate peer identity keypair + transform to desired format + add to config.\n print('generating %s keypair...', algorithm)\n\n if (algorithm === 'Ed25519') {\n return createEd25519PeerId()\n }\n\n if (algorithm === 'RSA') {\n return createRSAPeerId({ bits })\n }\n\n throw errCode(new Error('Unknown PeerId algorithm'), 'ERR_UNKNOWN_PEER_ID_ALGORITHM')\n}\n\n/**\n * @param {PeerId} peerId\n */\nconst peerIdToIdentity = (peerId) => {\n if (peerId.privateKey == null) {\n throw errCode(new Error('Private key missing'), 'ERR_MISSING_PRIVATE_KEY')\n }\n\n return {\n PeerID: peerId.toString(),\n /** @type {string} */\n PrivKey: uint8ArrayToString(peerId.privateKey, 'base64pad')\n }\n}\n\n/**\n * Applies passed `profiles` and a `config` to an open repo.\n *\n * @param {IPFSRepo} repo\n * @param {IPFSOptions} options\n * @returns {Promise<{peerId: PeerId, keychain?: Keychain}>}\n */\nconst configureRepo = async (repo, options) => {\n const config = options.config\n const profiles = (options.init && options.init.profiles) || []\n const pass = options.pass\n const original = await repo.config.getAll()\n const changed = mergeConfigs(applyProfiles(original, profiles), config)\n\n if (original !== changed) {\n await repo.config.replace(changed)\n }\n\n if (!changed.Identity || !changed.Identity.PrivKey) {\n throw new NotInitializedError('No private key was found in the config, please intialize the repo')\n }\n\n const buf = uint8ArrayFromString(changed.Identity.PrivKey, 'base64pad')\n const key = await unmarshalPrivateKey(buf)\n const peerId = await peerIdFromKeys(key.public.bytes, key.bytes)\n const libp2p = await createLibp2p({\n options: undefined,\n multiaddrs: undefined,\n peerId,\n repo,\n config: changed,\n keychainConfig: {\n pass,\n ...changed.Keychain\n }\n })\n\n return { peerId, keychain: libp2p.keychain }\n}\n\n/**\n * @param {IPFSConfig} config\n * @param {Partial} [changes]\n */\nconst mergeConfigs = (config, changes) =>\n changes ? mergeOptions(config, changes) : config\n\n/**\n * Apply profiles (e.g. ['server', 'lowpower']) to config\n *\n * @param {IPFSConfig} config\n * @param {string[]} [profiles]\n */\nconst applyProfiles = (config, profiles) => {\n return (profiles || []).reduce((config, name) => {\n const profile = configProfiles[name]\n if (!profile) {\n throw new Error(`Could not find profile with name '${name}'`)\n }\n log('applying profile %s', name)\n return profile.transform(config)\n }, config)\n}\n", "import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { base58btc } from 'multiformats/bases/base58'\n// @ts-ignore\nimport vd from 'varint-decoder'\nimport ve from '../utils/varint-encoder.js'\nimport { isMapEqual } from '../utils/index.js'\nimport { Message } from './message.js'\nimport { BitswapMessageEntry as Entry } from './entry.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n/**\n * @typedef {import('../types').MultihashHasherLoader} MultihashHasherLoader\n */\n\nexport class BitswapMessage {\n /**\n * @param {boolean} full\n */\n constructor (full) {\n this.full = full\n /** @type {Map} */\n this.wantlist = new Map()\n\n /** @type {Map} */\n this.blocks = new Map()\n\n /** @type {Map} */\n this.blockPresences = new Map()\n this.pendingBytes = 0\n }\n\n get empty () {\n return this.blocks.size === 0 &&\n this.wantlist.size === 0 &&\n this.blockPresences.size === 0\n }\n\n /**\n *\n * @param {CID} cid\n * @param {number} priority\n * @param {import('./message').Message.Wantlist.WantType | null} [wantType]\n * @param {boolean} [cancel]\n * @param {boolean} [sendDontHave]\n * @returns {void}\n */\n addEntry (cid, priority, wantType, cancel, sendDontHave) {\n if (wantType == null) {\n wantType = BitswapMessage.WantType.Block\n }\n\n const cidStr = cid.toString(base58btc)\n const entry = this.wantlist.get(cidStr)\n if (entry) {\n // Only change priority if want is of the same type\n if (entry.wantType === wantType) {\n entry.priority = priority\n }\n // Only change from \"dont cancel\" to \"do cancel\"\n if (cancel) {\n entry.cancel = Boolean(cancel)\n }\n // Only change from \"dont send\" to \"do send\" DONT_HAVE\n if (sendDontHave) {\n entry.sendDontHave = Boolean(sendDontHave)\n }\n // want-block overrides existing want-have\n if (wantType === BitswapMessage.WantType.Block && entry.wantType === BitswapMessage.WantType.Have) {\n entry.wantType = wantType\n }\n } else {\n this.wantlist.set(cidStr, new Entry(cid, priority, wantType, cancel, sendDontHave))\n }\n }\n\n /**\n * @param {CID} cid\n * @param {Uint8Array} block\n * @returns {void}\n */\n addBlock (cid, block) {\n const cidStr = cid.toString(base58btc)\n this.blocks.set(cidStr, block)\n }\n\n /**\n * @param {CID} cid\n */\n addHave (cid) {\n const cidStr = cid.toString(base58btc)\n if (!this.blockPresences.has(cidStr)) {\n this.blockPresences.set(cidStr, BitswapMessage.BlockPresenceType.Have)\n }\n }\n\n /**\n * @param {CID} cid\n */\n addDontHave (cid) {\n const cidStr = cid.toString(base58btc)\n if (!this.blockPresences.has(cidStr)) {\n this.blockPresences.set(cidStr, BitswapMessage.BlockPresenceType.DontHave)\n }\n }\n\n /**\n * @param {CID} cid\n */\n cancel (cid) {\n const cidStr = cid.toString(base58btc)\n this.wantlist.delete(cidStr)\n this.addEntry(cid, 0, BitswapMessage.WantType.Block, true, false)\n }\n\n /**\n * @param {number} size\n */\n setPendingBytes (size) {\n this.pendingBytes = size\n }\n\n /**\n * Serializes to Bitswap Message protobuf of\n * version 1.0.0\n *\n * @returns {Uint8Array}\n */\n serializeToBitswap100 () {\n const msg = {\n wantlist: {\n entries: Array.from(this.wantlist.values()).map((entry) => {\n return {\n block: entry.cid.bytes, // cid\n priority: Number(entry.priority),\n cancel: Boolean(entry.cancel)\n }\n }),\n full: this.full ? true : undefined\n },\n blocks: Array.from(this.blocks.values())\n }\n\n return Message.encode(msg).finish()\n }\n\n /**\n * Serializes to Bitswap Message protobuf of\n * version 1.1.0\n *\n * @returns {Uint8Array}\n */\n serializeToBitswap110 () {\n const msg = {\n wantlist: {\n entries: Array.from(this.wantlist.values()).map((entry) => {\n return {\n block: entry.cid.bytes, // cid\n priority: Number(entry.priority),\n wantType: entry.wantType,\n cancel: Boolean(entry.cancel),\n sendDontHave: Boolean(entry.sendDontHave)\n }\n }),\n full: this.full ? true : undefined\n },\n /** @type {import('./message').Message.BlockPresence[]} */\n blockPresences: [],\n\n /** @type {{ prefix: Uint8Array, data: Uint8Array }[]} */\n payload: [],\n pendingBytes: this.pendingBytes\n }\n\n for (const [cidStr, data] of this.blocks.entries()) {\n const cid = CID.parse(cidStr)\n const version = cid.version\n const codec = cid.code\n const multihash = cid.multihash.code\n const digestLength = cid.multihash.digest.length\n const prefix = ve([\n version, codec, multihash, digestLength\n ])\n\n msg.payload.push(\n new Message.Block({\n prefix,\n data\n })\n )\n }\n\n for (const [cidStr, bpType] of this.blockPresences) {\n msg.blockPresences.push(new Message.BlockPresence({\n cid: CID.parse(cidStr).bytes,\n type: bpType\n }))\n }\n\n if (this.pendingBytes > 0) {\n msg.pendingBytes = this.pendingBytes\n }\n\n return Message.encode(msg).finish()\n }\n\n /**\n * @param {BitswapMessage} other\n * @returns {boolean}\n */\n equals (other) {\n if (this.full !== other.full ||\n this.pendingBytes !== other.pendingBytes ||\n !isMapEqual(this.wantlist, other.wantlist) ||\n !isMapEqual(this.blocks, other.blocks) ||\n // @TODO - Is this a bug ?\n // @ts-expect-error - isMap equals map values to be objects not numbers\n !isMapEqual(this.blockPresences, other.blockPresences)\n ) {\n return false\n }\n\n return true\n }\n\n get [Symbol.toStringTag] () {\n const list = Array.from(this.wantlist.keys())\n const blocks = Array.from(this.blocks.keys())\n return `BitswapMessage `\n }\n}\n\n/**\n * @param {Uint8Array} raw\n * @param {MultihashHasherLoader} [hashLoader]\n */\nBitswapMessage.deserialize = async (raw, hashLoader) => {\n const decoded = Message.decode(raw)\n\n const isFull = (decoded.wantlist && decoded.wantlist.full) || false\n const msg = new BitswapMessage(isFull)\n\n if (decoded.wantlist && decoded.wantlist.entries) {\n decoded.wantlist.entries.forEach((entry) => {\n if (!entry.block) {\n return\n }\n // note: entry.block is the CID here\n const cid = CID.decode(entry.block)\n msg.addEntry(cid, entry.priority || 0, entry.wantType, Boolean(entry.cancel), Boolean(entry.sendDontHave))\n })\n }\n\n if (decoded.blockPresences) {\n decoded.blockPresences.forEach((blockPresence) => {\n if (!blockPresence.cid) {\n return\n }\n\n const cid = CID.decode(blockPresence.cid)\n\n if (blockPresence.type === BitswapMessage.BlockPresenceType.Have) {\n msg.addHave(cid)\n } else {\n msg.addDontHave(cid)\n }\n })\n }\n\n // Bitswap 1.0.0\n // decoded.blocks are just the byte arrays\n if (decoded.blocks.length > 0) {\n await Promise.all(decoded.blocks.map(async (b) => {\n const hash = await sha256.digest(b)\n const cid = CID.createV0(hash)\n msg.addBlock(cid, b)\n }))\n return msg\n }\n\n // Bitswap 1.1.0\n if (decoded.payload.length > 0) {\n await Promise.all(decoded.payload.map(async (p) => {\n if (!p.prefix || !p.data) {\n return\n }\n const values = vd(p.prefix)\n const cidVersion = values[0]\n const multicodec = values[1]\n const hashAlg = values[2]\n const hasher = hashAlg === sha256.code ? sha256 : hashLoader && await hashLoader.getHasher(hashAlg)\n\n if (!hasher) {\n throw new CodeError('Unknown hash algorithm', 'ERR_UNKNOWN_HASH_ALG')\n }\n\n // const hashLen = values[3] // We haven't need to use this so far\n const hash = await hasher.digest(p.data)\n const cid = CID.create(cidVersion, multicodec, hash)\n msg.addBlock(cid, p.data)\n }))\n msg.setPendingBytes(decoded.pendingBytes)\n return msg\n }\n\n return msg\n}\n\n/**\n * @param {CID} cid\n */\nBitswapMessage.blockPresenceSize = (cid) => {\n // It's ok if this is not exactly right: it's used to estimate the size of\n // the HAVE / DONT_HAVE on the wire, but when doing that calculation we leave\n // plenty of padding under the maximum message size.\n // (It's more important for this to be fast).\n return cid.bytes.length + 1\n}\n\nBitswapMessage.Entry = Entry\nBitswapMessage.WantType = {\n Block: Message.Wantlist.WantType.Block,\n Have: Message.Wantlist.WantType.Have\n}\nBitswapMessage.BlockPresenceType = {\n Have: Message.BlockPresenceType.Have,\n DontHave: Message.BlockPresenceType.DontHave\n}\n", "import * as varint from 'varint'\n\n/**\n * @param {Array} buf\n * @returns {Uint8Array}\n */\nfunction varintEncoder (buf) {\n let out = new Uint8Array(buf.reduce((acc, curr) => {\n // @ts-expect-error types are wrong\n return acc + varint.default.encodingLength(curr)\n }, 0))\n let offset = 0\n\n for (const num of buf) {\n out = varint.encode(num, out, offset)\n\n // @ts-expect-error types are wrong\n offset += varint.default.encodingLength(num)\n }\n\n return out\n}\n\nexport default varintEncoder\n", "\nimport { base58btc } from 'multiformats/bases/base58'\n\nexport class WantListEntry {\n /**\n * @param {import('multiformats').CID} cid\n * @param {number} priority\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n */\n constructor (cid, priority, wantType) {\n // Keep track of how many requests we have for this key\n this._refCounter = 1\n\n this.cid = cid\n this.priority = priority || 1\n this.wantType = wantType\n }\n\n inc () {\n this._refCounter += 1\n }\n\n dec () {\n this._refCounter = Math.max(0, this._refCounter - 1)\n }\n\n hasRefs () {\n return this._refCounter > 0\n }\n\n // So that console.log prints a nice description of this object\n get [Symbol.toStringTag] () {\n const cidStr = this.cid.toString(base58btc)\n return `WantlistEntry `\n }\n\n /**\n * @param {any} other\n */\n equals (other) {\n return (this._refCounter === other._refCounter) &&\n this.cid.equals(other.cid) &&\n this.priority === other.priority &&\n this.wantType === other.wantType\n }\n}\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"ipfs-bitswap\"] || ($protobuf.roots[\"ipfs-bitswap\"] = {});\n\nexport const Message = $root.Message = (() => {\n\n /**\n * Properties of a Message.\n * @exports IMessage\n * @interface IMessage\n * @property {Message.IWantlist|null} [wantlist] Message wantlist\n * @property {Array.|null} [blocks] Message blocks\n * @property {Array.|null} [payload] Message payload\n * @property {Array.|null} [blockPresences] Message blockPresences\n * @property {number|null} [pendingBytes] Message pendingBytes\n */\n\n /**\n * Constructs a new Message.\n * @exports Message\n * @classdesc Represents a Message.\n * @implements IMessage\n * @constructor\n * @param {IMessage=} [p] Properties to set\n */\n function Message(p) {\n this.blocks = [];\n this.payload = [];\n this.blockPresences = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Message wantlist.\n * @member {Message.IWantlist|null|undefined} wantlist\n * @memberof Message\n * @instance\n */\n Message.prototype.wantlist = null;\n\n /**\n * Message blocks.\n * @member {Array.} blocks\n * @memberof Message\n * @instance\n */\n Message.prototype.blocks = $util.emptyArray;\n\n /**\n * Message payload.\n * @member {Array.} payload\n * @memberof Message\n * @instance\n */\n Message.prototype.payload = $util.emptyArray;\n\n /**\n * Message blockPresences.\n * @member {Array.} blockPresences\n * @memberof Message\n * @instance\n */\n Message.prototype.blockPresences = $util.emptyArray;\n\n /**\n * Message pendingBytes.\n * @member {number} pendingBytes\n * @memberof Message\n * @instance\n */\n Message.prototype.pendingBytes = 0;\n\n /**\n * Encodes the specified Message message. Does not implicitly {@link Message.verify|verify} messages.\n * @function encode\n * @memberof Message\n * @static\n * @param {IMessage} m Message message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Message.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.wantlist != null && Object.hasOwnProperty.call(m, \"wantlist\"))\n $root.Message.Wantlist.encode(m.wantlist, w.uint32(10).fork()).ldelim();\n if (m.blocks != null && m.blocks.length) {\n for (var i = 0; i < m.blocks.length; ++i)\n w.uint32(18).bytes(m.blocks[i]);\n }\n if (m.payload != null && m.payload.length) {\n for (var i = 0; i < m.payload.length; ++i)\n $root.Message.Block.encode(m.payload[i], w.uint32(26).fork()).ldelim();\n }\n if (m.blockPresences != null && m.blockPresences.length) {\n for (var i = 0; i < m.blockPresences.length; ++i)\n $root.Message.BlockPresence.encode(m.blockPresences[i], w.uint32(34).fork()).ldelim();\n }\n if (m.pendingBytes != null && Object.hasOwnProperty.call(m, \"pendingBytes\"))\n w.uint32(40).int32(m.pendingBytes);\n return w;\n };\n\n /**\n * Decodes a Message message from the specified reader or buffer.\n * @function decode\n * @memberof Message\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message} Message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Message.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.wantlist = $root.Message.Wantlist.decode(r, r.uint32());\n break;\n }\n case 2: {\n if (!(m.blocks && m.blocks.length))\n m.blocks = [];\n m.blocks.push(r.bytes());\n break;\n }\n case 3: {\n if (!(m.payload && m.payload.length))\n m.payload = [];\n m.payload.push($root.Message.Block.decode(r, r.uint32()));\n break;\n }\n case 4: {\n if (!(m.blockPresences && m.blockPresences.length))\n m.blockPresences = [];\n m.blockPresences.push($root.Message.BlockPresence.decode(r, r.uint32()));\n break;\n }\n case 5: {\n m.pendingBytes = r.int32();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Message message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message\n * @static\n * @param {Object.} d Plain object\n * @returns {Message} Message\n */\n Message.fromObject = function fromObject(d) {\n if (d instanceof $root.Message)\n return d;\n var m = new $root.Message();\n if (d.wantlist != null) {\n if (typeof d.wantlist !== \"object\")\n throw TypeError(\".Message.wantlist: object expected\");\n m.wantlist = $root.Message.Wantlist.fromObject(d.wantlist);\n }\n if (d.blocks) {\n if (!Array.isArray(d.blocks))\n throw TypeError(\".Message.blocks: array expected\");\n m.blocks = [];\n for (var i = 0; i < d.blocks.length; ++i) {\n if (typeof d.blocks[i] === \"string\")\n $util.base64.decode(d.blocks[i], m.blocks[i] = $util.newBuffer($util.base64.length(d.blocks[i])), 0);\n else if (d.blocks[i].length >= 0)\n m.blocks[i] = d.blocks[i];\n }\n }\n if (d.payload) {\n if (!Array.isArray(d.payload))\n throw TypeError(\".Message.payload: array expected\");\n m.payload = [];\n for (var i = 0; i < d.payload.length; ++i) {\n if (typeof d.payload[i] !== \"object\")\n throw TypeError(\".Message.payload: object expected\");\n m.payload[i] = $root.Message.Block.fromObject(d.payload[i]);\n }\n }\n if (d.blockPresences) {\n if (!Array.isArray(d.blockPresences))\n throw TypeError(\".Message.blockPresences: array expected\");\n m.blockPresences = [];\n for (var i = 0; i < d.blockPresences.length; ++i) {\n if (typeof d.blockPresences[i] !== \"object\")\n throw TypeError(\".Message.blockPresences: object expected\");\n m.blockPresences[i] = $root.Message.BlockPresence.fromObject(d.blockPresences[i]);\n }\n }\n if (d.pendingBytes != null) {\n m.pendingBytes = d.pendingBytes | 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Message message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message\n * @static\n * @param {Message} m Message\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Message.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.blocks = [];\n d.payload = [];\n d.blockPresences = [];\n }\n if (o.defaults) {\n d.wantlist = null;\n d.pendingBytes = 0;\n }\n if (m.wantlist != null && m.hasOwnProperty(\"wantlist\")) {\n d.wantlist = $root.Message.Wantlist.toObject(m.wantlist, o);\n }\n if (m.blocks && m.blocks.length) {\n d.blocks = [];\n for (var j = 0; j < m.blocks.length; ++j) {\n d.blocks[j] = o.bytes === String ? $util.base64.encode(m.blocks[j], 0, m.blocks[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.blocks[j]) : m.blocks[j];\n }\n }\n if (m.payload && m.payload.length) {\n d.payload = [];\n for (var j = 0; j < m.payload.length; ++j) {\n d.payload[j] = $root.Message.Block.toObject(m.payload[j], o);\n }\n }\n if (m.blockPresences && m.blockPresences.length) {\n d.blockPresences = [];\n for (var j = 0; j < m.blockPresences.length; ++j) {\n d.blockPresences[j] = $root.Message.BlockPresence.toObject(m.blockPresences[j], o);\n }\n }\n if (m.pendingBytes != null && m.hasOwnProperty(\"pendingBytes\")) {\n d.pendingBytes = m.pendingBytes;\n }\n return d;\n };\n\n /**\n * Converts this Message to JSON.\n * @function toJSON\n * @memberof Message\n * @instance\n * @returns {Object.} JSON object\n */\n Message.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Message\n * @function getTypeUrl\n * @memberof Message\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Message.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message\";\n };\n\n Message.Wantlist = (function() {\n\n /**\n * Properties of a Wantlist.\n * @memberof Message\n * @interface IWantlist\n * @property {Array.|null} [entries] Wantlist entries\n * @property {boolean|null} [full] Wantlist full\n */\n\n /**\n * Constructs a new Wantlist.\n * @memberof Message\n * @classdesc Represents a Wantlist.\n * @implements IWantlist\n * @constructor\n * @param {Message.IWantlist=} [p] Properties to set\n */\n function Wantlist(p) {\n this.entries = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Wantlist entries.\n * @member {Array.} entries\n * @memberof Message.Wantlist\n * @instance\n */\n Wantlist.prototype.entries = $util.emptyArray;\n\n /**\n * Wantlist full.\n * @member {boolean} full\n * @memberof Message.Wantlist\n * @instance\n */\n Wantlist.prototype.full = false;\n\n /**\n * Encodes the specified Wantlist message. Does not implicitly {@link Message.Wantlist.verify|verify} messages.\n * @function encode\n * @memberof Message.Wantlist\n * @static\n * @param {Message.IWantlist} m Wantlist message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Wantlist.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.entries != null && m.entries.length) {\n for (var i = 0; i < m.entries.length; ++i)\n $root.Message.Wantlist.Entry.encode(m.entries[i], w.uint32(10).fork()).ldelim();\n }\n if (m.full != null && Object.hasOwnProperty.call(m, \"full\"))\n w.uint32(16).bool(m.full);\n return w;\n };\n\n /**\n * Decodes a Wantlist message from the specified reader or buffer.\n * @function decode\n * @memberof Message.Wantlist\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.Wantlist} Wantlist\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Wantlist.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.Wantlist();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n if (!(m.entries && m.entries.length))\n m.entries = [];\n m.entries.push($root.Message.Wantlist.Entry.decode(r, r.uint32()));\n break;\n }\n case 2: {\n m.full = r.bool();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Wantlist message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.Wantlist\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.Wantlist} Wantlist\n */\n Wantlist.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.Wantlist)\n return d;\n var m = new $root.Message.Wantlist();\n if (d.entries) {\n if (!Array.isArray(d.entries))\n throw TypeError(\".Message.Wantlist.entries: array expected\");\n m.entries = [];\n for (var i = 0; i < d.entries.length; ++i) {\n if (typeof d.entries[i] !== \"object\")\n throw TypeError(\".Message.Wantlist.entries: object expected\");\n m.entries[i] = $root.Message.Wantlist.Entry.fromObject(d.entries[i]);\n }\n }\n if (d.full != null) {\n m.full = Boolean(d.full);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Wantlist message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.Wantlist\n * @static\n * @param {Message.Wantlist} m Wantlist\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Wantlist.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.entries = [];\n }\n if (o.defaults) {\n d.full = false;\n }\n if (m.entries && m.entries.length) {\n d.entries = [];\n for (var j = 0; j < m.entries.length; ++j) {\n d.entries[j] = $root.Message.Wantlist.Entry.toObject(m.entries[j], o);\n }\n }\n if (m.full != null && m.hasOwnProperty(\"full\")) {\n d.full = m.full;\n }\n return d;\n };\n\n /**\n * Converts this Wantlist to JSON.\n * @function toJSON\n * @memberof Message.Wantlist\n * @instance\n * @returns {Object.} JSON object\n */\n Wantlist.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Wantlist\n * @function getTypeUrl\n * @memberof Message.Wantlist\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Wantlist.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.Wantlist\";\n };\n\n /**\n * WantType enum.\n * @name Message.Wantlist.WantType\n * @enum {number}\n * @property {number} Block=0 Block value\n * @property {number} Have=1 Have value\n */\n Wantlist.WantType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Block\"] = 0;\n values[valuesById[1] = \"Have\"] = 1;\n return values;\n })();\n\n Wantlist.Entry = (function() {\n\n /**\n * Properties of an Entry.\n * @memberof Message.Wantlist\n * @interface IEntry\n * @property {Uint8Array|null} [block] Entry block\n * @property {number|null} [priority] Entry priority\n * @property {boolean|null} [cancel] Entry cancel\n * @property {Message.Wantlist.WantType|null} [wantType] Entry wantType\n * @property {boolean|null} [sendDontHave] Entry sendDontHave\n */\n\n /**\n * Constructs a new Entry.\n * @memberof Message.Wantlist\n * @classdesc Represents an Entry.\n * @implements IEntry\n * @constructor\n * @param {Message.Wantlist.IEntry=} [p] Properties to set\n */\n function Entry(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Entry block.\n * @member {Uint8Array} block\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.block = $util.newBuffer([]);\n\n /**\n * Entry priority.\n * @member {number} priority\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.priority = 0;\n\n /**\n * Entry cancel.\n * @member {boolean} cancel\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.cancel = false;\n\n /**\n * Entry wantType.\n * @member {Message.Wantlist.WantType} wantType\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.wantType = 0;\n\n /**\n * Entry sendDontHave.\n * @member {boolean} sendDontHave\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.sendDontHave = false;\n\n /**\n * Encodes the specified Entry message. Does not implicitly {@link Message.Wantlist.Entry.verify|verify} messages.\n * @function encode\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {Message.Wantlist.IEntry} m Entry message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Entry.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.block != null && Object.hasOwnProperty.call(m, \"block\"))\n w.uint32(10).bytes(m.block);\n if (m.priority != null && Object.hasOwnProperty.call(m, \"priority\"))\n w.uint32(16).int32(m.priority);\n if (m.cancel != null && Object.hasOwnProperty.call(m, \"cancel\"))\n w.uint32(24).bool(m.cancel);\n if (m.wantType != null && Object.hasOwnProperty.call(m, \"wantType\"))\n w.uint32(32).int32(m.wantType);\n if (m.sendDontHave != null && Object.hasOwnProperty.call(m, \"sendDontHave\"))\n w.uint32(40).bool(m.sendDontHave);\n return w;\n };\n\n /**\n * Decodes an Entry message from the specified reader or buffer.\n * @function decode\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.Wantlist.Entry} Entry\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Entry.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.Wantlist.Entry();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.block = r.bytes();\n break;\n }\n case 2: {\n m.priority = r.int32();\n break;\n }\n case 3: {\n m.cancel = r.bool();\n break;\n }\n case 4: {\n m.wantType = r.int32();\n break;\n }\n case 5: {\n m.sendDontHave = r.bool();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Entry message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.Wantlist.Entry} Entry\n */\n Entry.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.Wantlist.Entry)\n return d;\n var m = new $root.Message.Wantlist.Entry();\n if (d.block != null) {\n if (typeof d.block === \"string\")\n $util.base64.decode(d.block, m.block = $util.newBuffer($util.base64.length(d.block)), 0);\n else if (d.block.length >= 0)\n m.block = d.block;\n }\n if (d.priority != null) {\n m.priority = d.priority | 0;\n }\n if (d.cancel != null) {\n m.cancel = Boolean(d.cancel);\n }\n switch (d.wantType) {\n case \"Block\":\n case 0:\n m.wantType = 0;\n break;\n case \"Have\":\n case 1:\n m.wantType = 1;\n break;\n }\n if (d.sendDontHave != null) {\n m.sendDontHave = Boolean(d.sendDontHave);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Entry message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {Message.Wantlist.Entry} m Entry\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Entry.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.block = \"\";\n else {\n d.block = [];\n if (o.bytes !== Array)\n d.block = $util.newBuffer(d.block);\n }\n d.priority = 0;\n d.cancel = false;\n d.wantType = o.enums === String ? \"Block\" : 0;\n d.sendDontHave = false;\n }\n if (m.block != null && m.hasOwnProperty(\"block\")) {\n d.block = o.bytes === String ? $util.base64.encode(m.block, 0, m.block.length) : o.bytes === Array ? Array.prototype.slice.call(m.block) : m.block;\n }\n if (m.priority != null && m.hasOwnProperty(\"priority\")) {\n d.priority = m.priority;\n }\n if (m.cancel != null && m.hasOwnProperty(\"cancel\")) {\n d.cancel = m.cancel;\n }\n if (m.wantType != null && m.hasOwnProperty(\"wantType\")) {\n d.wantType = o.enums === String ? $root.Message.Wantlist.WantType[m.wantType] : m.wantType;\n }\n if (m.sendDontHave != null && m.hasOwnProperty(\"sendDontHave\")) {\n d.sendDontHave = m.sendDontHave;\n }\n return d;\n };\n\n /**\n * Converts this Entry to JSON.\n * @function toJSON\n * @memberof Message.Wantlist.Entry\n * @instance\n * @returns {Object.} JSON object\n */\n Entry.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Entry\n * @function getTypeUrl\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Entry.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.Wantlist.Entry\";\n };\n\n return Entry;\n })();\n\n return Wantlist;\n })();\n\n Message.Block = (function() {\n\n /**\n * Properties of a Block.\n * @memberof Message\n * @interface IBlock\n * @property {Uint8Array|null} [prefix] Block prefix\n * @property {Uint8Array|null} [data] Block data\n */\n\n /**\n * Constructs a new Block.\n * @memberof Message\n * @classdesc Represents a Block.\n * @implements IBlock\n * @constructor\n * @param {Message.IBlock=} [p] Properties to set\n */\n function Block(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Block prefix.\n * @member {Uint8Array} prefix\n * @memberof Message.Block\n * @instance\n */\n Block.prototype.prefix = $util.newBuffer([]);\n\n /**\n * Block data.\n * @member {Uint8Array} data\n * @memberof Message.Block\n * @instance\n */\n Block.prototype.data = $util.newBuffer([]);\n\n /**\n * Encodes the specified Block message. Does not implicitly {@link Message.Block.verify|verify} messages.\n * @function encode\n * @memberof Message.Block\n * @static\n * @param {Message.IBlock} m Block message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Block.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.prefix != null && Object.hasOwnProperty.call(m, \"prefix\"))\n w.uint32(10).bytes(m.prefix);\n if (m.data != null && Object.hasOwnProperty.call(m, \"data\"))\n w.uint32(18).bytes(m.data);\n return w;\n };\n\n /**\n * Decodes a Block message from the specified reader or buffer.\n * @function decode\n * @memberof Message.Block\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.Block} Block\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Block.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.Block();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.prefix = r.bytes();\n break;\n }\n case 2: {\n m.data = r.bytes();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Block message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.Block\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.Block} Block\n */\n Block.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.Block)\n return d;\n var m = new $root.Message.Block();\n if (d.prefix != null) {\n if (typeof d.prefix === \"string\")\n $util.base64.decode(d.prefix, m.prefix = $util.newBuffer($util.base64.length(d.prefix)), 0);\n else if (d.prefix.length >= 0)\n m.prefix = d.prefix;\n }\n if (d.data != null) {\n if (typeof d.data === \"string\")\n $util.base64.decode(d.data, m.data = $util.newBuffer($util.base64.length(d.data)), 0);\n else if (d.data.length >= 0)\n m.data = d.data;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Block message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.Block\n * @static\n * @param {Message.Block} m Block\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Block.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.prefix = \"\";\n else {\n d.prefix = [];\n if (o.bytes !== Array)\n d.prefix = $util.newBuffer(d.prefix);\n }\n if (o.bytes === String)\n d.data = \"\";\n else {\n d.data = [];\n if (o.bytes !== Array)\n d.data = $util.newBuffer(d.data);\n }\n }\n if (m.prefix != null && m.hasOwnProperty(\"prefix\")) {\n d.prefix = o.bytes === String ? $util.base64.encode(m.prefix, 0, m.prefix.length) : o.bytes === Array ? Array.prototype.slice.call(m.prefix) : m.prefix;\n }\n if (m.data != null && m.hasOwnProperty(\"data\")) {\n d.data = o.bytes === String ? $util.base64.encode(m.data, 0, m.data.length) : o.bytes === Array ? Array.prototype.slice.call(m.data) : m.data;\n }\n return d;\n };\n\n /**\n * Converts this Block to JSON.\n * @function toJSON\n * @memberof Message.Block\n * @instance\n * @returns {Object.} JSON object\n */\n Block.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Block\n * @function getTypeUrl\n * @memberof Message.Block\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Block.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.Block\";\n };\n\n return Block;\n })();\n\n /**\n * BlockPresenceType enum.\n * @name Message.BlockPresenceType\n * @enum {number}\n * @property {number} Have=0 Have value\n * @property {number} DontHave=1 DontHave value\n */\n Message.BlockPresenceType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Have\"] = 0;\n values[valuesById[1] = \"DontHave\"] = 1;\n return values;\n })();\n\n Message.BlockPresence = (function() {\n\n /**\n * Properties of a BlockPresence.\n * @memberof Message\n * @interface IBlockPresence\n * @property {Uint8Array|null} [cid] BlockPresence cid\n * @property {Message.BlockPresenceType|null} [type] BlockPresence type\n */\n\n /**\n * Constructs a new BlockPresence.\n * @memberof Message\n * @classdesc Represents a BlockPresence.\n * @implements IBlockPresence\n * @constructor\n * @param {Message.IBlockPresence=} [p] Properties to set\n */\n function BlockPresence(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * BlockPresence cid.\n * @member {Uint8Array} cid\n * @memberof Message.BlockPresence\n * @instance\n */\n BlockPresence.prototype.cid = $util.newBuffer([]);\n\n /**\n * BlockPresence type.\n * @member {Message.BlockPresenceType} type\n * @memberof Message.BlockPresence\n * @instance\n */\n BlockPresence.prototype.type = 0;\n\n /**\n * Encodes the specified BlockPresence message. Does not implicitly {@link Message.BlockPresence.verify|verify} messages.\n * @function encode\n * @memberof Message.BlockPresence\n * @static\n * @param {Message.IBlockPresence} m BlockPresence message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n BlockPresence.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.cid != null && Object.hasOwnProperty.call(m, \"cid\"))\n w.uint32(10).bytes(m.cid);\n if (m.type != null && Object.hasOwnProperty.call(m, \"type\"))\n w.uint32(16).int32(m.type);\n return w;\n };\n\n /**\n * Decodes a BlockPresence message from the specified reader or buffer.\n * @function decode\n * @memberof Message.BlockPresence\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.BlockPresence} BlockPresence\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n BlockPresence.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.BlockPresence();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.cid = r.bytes();\n break;\n }\n case 2: {\n m.type = r.int32();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a BlockPresence message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.BlockPresence\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.BlockPresence} BlockPresence\n */\n BlockPresence.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.BlockPresence)\n return d;\n var m = new $root.Message.BlockPresence();\n if (d.cid != null) {\n if (typeof d.cid === \"string\")\n $util.base64.decode(d.cid, m.cid = $util.newBuffer($util.base64.length(d.cid)), 0);\n else if (d.cid.length >= 0)\n m.cid = d.cid;\n }\n switch (d.type) {\n case \"Have\":\n case 0:\n m.type = 0;\n break;\n case \"DontHave\":\n case 1:\n m.type = 1;\n break;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a BlockPresence message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.BlockPresence\n * @static\n * @param {Message.BlockPresence} m BlockPresence\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n BlockPresence.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.cid = \"\";\n else {\n d.cid = [];\n if (o.bytes !== Array)\n d.cid = $util.newBuffer(d.cid);\n }\n d.type = o.enums === String ? \"Have\" : 0;\n }\n if (m.cid != null && m.hasOwnProperty(\"cid\")) {\n d.cid = o.bytes === String ? $util.base64.encode(m.cid, 0, m.cid.length) : o.bytes === Array ? Array.prototype.slice.call(m.cid) : m.cid;\n }\n if (m.type != null && m.hasOwnProperty(\"type\")) {\n d.type = o.enums === String ? $root.Message.BlockPresenceType[m.type] : m.type;\n }\n return d;\n };\n\n /**\n * Converts this BlockPresence to JSON.\n * @function toJSON\n * @memberof Message.BlockPresence\n * @instance\n * @returns {Object.} JSON object\n */\n BlockPresence.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for BlockPresence\n * @function getTypeUrl\n * @memberof Message.BlockPresence\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n BlockPresence.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.BlockPresence\";\n };\n\n return BlockPresence;\n })();\n\n return Message;\n})();\n\nexport { $root as default };\n", "\nimport { WantListEntry as Entry } from './entry.js'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { Message } from '../message/message.js'\nimport { trackedMap } from '@libp2p/tracked-map'\n\nconst WantType = {\n Block: Message.Wantlist.WantType.Block,\n Have: Message.Wantlist.WantType.Have\n}\n\n/**\n * @template T\n * @param {(v:T) => number} fn\n * @param {T[]} list\n * @returns {T[]}\n */\nconst sortBy = (fn, list) => {\n return Array.prototype.slice.call(list, 0).sort((a, b) => {\n const aa = fn(a)\n const bb = fn(b)\n return aa < bb ? -1 : aa > bb ? 1 : 0\n })\n}\n\n/**\n * @typedef {import('multiformats').CID} CID\n */\n\nexport class Wantlist {\n /**\n * @param {import('../stats').Stats} [stats]\n * @param {import('@libp2p/interface-libp2p').Libp2p} [libp2p]\n */\n constructor (stats, libp2p) {\n /** @type {Map} */\n this.set = libp2p\n ? trackedMap({\n name: 'ipfs_bitswap_wantlist',\n metrics: libp2p.metrics\n })\n : new Map()\n this._stats = stats\n }\n\n get length () {\n return this.set.size\n }\n\n /**\n * @param {CID} cid\n * @param {number} priority\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n */\n add (cid, priority, wantType) {\n const cidStr = cid.toString(base58btc)\n const entry = this.set.get(cidStr)\n\n if (entry) {\n entry.inc()\n entry.priority = priority\n\n // We can only overwrite want-have with want-block\n if (entry.wantType === WantType.Have && wantType === WantType.Block) {\n entry.wantType = wantType\n }\n } else {\n this.set.set(cidStr, new Entry(cid, priority, wantType))\n if (this._stats) {\n this._stats.push(null, 'wantListSize', 1)\n }\n }\n }\n\n /**\n * @param {CID} cid\n */\n remove (cid) {\n const cidStr = cid.toString(base58btc)\n const entry = this.set.get(cidStr)\n\n if (!entry) {\n return\n }\n\n entry.dec()\n\n // only delete when no refs are held\n if (entry.hasRefs()) {\n return\n }\n\n this.set.delete(cidStr)\n if (this._stats) {\n this._stats.push(null, 'wantListSize', -1)\n }\n }\n\n /**\n * @param {string} cidStr\n */\n removeForce (cidStr) {\n if (this.set.has(cidStr)) {\n this.set.delete(cidStr)\n }\n }\n\n /**\n * @param {(entry:Entry, key:string) => void} fn\n */\n forEach (fn) {\n return this.set.forEach(fn)\n }\n\n entries () {\n return this.set.entries()\n }\n\n sortedEntries () {\n // TODO: Figure out if this is an actual bug.\n // @ts-expect-error - Property 'key' does not exist on type 'WantListEntry'\n return new Map(sortBy(o => o[1].key, Array.from(this.set.entries())))\n }\n\n /**\n * @param {CID} cid\n */\n contains (cid) {\n const cidStr = cid.toString(base58btc)\n return this.set.has(cidStr)\n }\n\n /**\n * @param {CID} cid\n */\n get (cid) {\n const cidStr = cid.toString(base58btc)\n return this.set.get(cidStr)\n }\n}\n\nWantlist.Entry = Entry\n", "\nimport { Wantlist } from '../wantlist/index.js'\nimport { base58btc } from 'multiformats/bases/base58'\n\nconst WantlistEntry = Wantlist.Entry\n\nexport class BitswapMessageEntry {\n /**\n * @param {import('multiformats').CID} cid\n * @param {number} priority\n * @param {import('./message').Message.Wantlist.WantType} wantType\n * @param {boolean} [cancel]\n * @param {boolean} [sendDontHave]\n */\n constructor (cid, priority, wantType, cancel, sendDontHave) {\n this.entry = new WantlistEntry(cid, priority, wantType)\n this.cancel = Boolean(cancel)\n this.sendDontHave = Boolean(sendDontHave)\n }\n\n get cid () {\n return this.entry.cid\n }\n\n set cid (cid) {\n this.entry.cid = cid\n }\n\n get priority () {\n return this.entry.priority\n }\n\n set priority (val) {\n this.entry.priority = val\n }\n\n get wantType () {\n return this.entry.wantType\n }\n\n set wantType (val) {\n this.entry.wantType = val\n }\n\n get [Symbol.toStringTag] () {\n const cidStr = this.cid.toString(base58btc)\n return `BitswapMessageEntry ${cidStr} `\n }\n\n /**\n * @param {this} other\n */\n equals (other) {\n return (this.cancel === other.cancel) &&\n (this.sendDontHave === other.sendDontHave) &&\n (this.wantType === other.wantType) &&\n this.entry.equals(other.entry)\n }\n}\n", "import { logger as createLogger } from '@libp2p/logger'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { BitswapMessageEntry } from '../message/entry.js'\n\n/**\n * Creates a logger for the given subsystem\n *\n * @param {import('@libp2p/interface-peer-id').PeerId} [id]\n * @param {string} [subsystem]\n */\nexport const logger = (id, subsystem) => {\n const name = ['bitswap']\n if (subsystem) {\n name.push(subsystem)\n }\n if (id) {\n name.push(`${id.toString().slice(0, 8)}`)\n }\n\n return createLogger(name.join(':'))\n}\n\n/**\n * @template X, T\n * @param {(x:X, t:T) => boolean} pred\n * @param {X} x\n * @param {T[]} list\n * @returns {boolean}\n */\nexport const includesWith = (pred, x, list) => {\n let idx = 0\n const len = list.length\n while (idx < len) {\n if (pred(x, list[idx])) {\n return true\n }\n idx += 1\n }\n return false\n}\n\n/**\n * @template T\n * @param {(x:T, t:T) => boolean} pred\n * @param {T[]} list\n * @returns {T[]}\n */\nexport const uniqWith = (pred, list) => {\n let idx = 0\n const len = list.length\n const result = []\n let item\n\n while (idx < len) {\n item = list[idx]\n if (!includesWith(pred, item, result)) {\n result[result.length] = item\n }\n idx += 1\n }\n return result\n}\n\n/**\n * @template {string|number|symbol} K\n * @template V\n * @param {(v:V) => K} pred\n * @param {V[]} list\n * @returns {Record}\n */\nexport const groupBy = (pred, list) => {\n return list.reduce((acc, v) => {\n const k = pred(v)\n\n if (acc[k]) {\n acc[k].push(v)\n } else {\n acc[k] = [v]\n }\n return acc\n }, /** @type {Record} */({}))\n}\n\n/**\n * @template T, E\n * @param {(a:T, b:E) => boolean} pred\n * @param {T[]} list\n * @param {E[]} values\n * @returns {T[]}\n */\nexport const pullAllWith = (pred, list, values) => {\n return list.filter(i => {\n return !includesWith(pred, i, values)\n })\n}\n\n/**\n * @template T\n * @param {(v:T) => number} fn\n * @param {T[]} list\n * @returns {T[]}\n */\nexport const sortBy = (fn, list) => {\n return Array.prototype.slice.call(list, 0).sort((a, b) => {\n const aa = fn(a)\n const bb = fn(b)\n return aa < bb ? -1 : aa > bb ? 1 : 0\n })\n}\n\n/**\n * Is equal for Maps of BitswapMessageEntry or Uint8Arrays\n *\n * @param {Map} a\n * @param {Map} b\n */\nexport const isMapEqual = (a, b) => {\n if (a.size !== b.size) {\n return false\n }\n\n for (const [key, valueA] of a) {\n const valueB = b.get(key)\n\n if (valueB === undefined) {\n return false\n }\n\n // TODO: revisit this\n\n // Support Blocks\n if (valueA instanceof Uint8Array && valueB instanceof Uint8Array && !uint8ArrayEquals(valueA, valueB)) {\n return false\n }\n\n // Support BitswapMessageEntry\n if (valueA instanceof BitswapMessageEntry && valueB instanceof BitswapMessageEntry && !valueA.equals(valueB)) {\n return false\n }\n }\n\n return true\n}\n", "const SECOND = 1000\n\nexport const maxProvidersPerRequest = 3\nexport const providerRequestTimeout = 10 * SECOND\nexport const hasBlockTimeout = 15 * SECOND\nexport const provideTimeout = 15 * SECOND\nexport const kMaxPriority = Math.pow(2, 31) - 1\nexport const maxListeners = 1000\nexport const wantlistSendDebounceMs = 1\n", "var functionDebounce = debounce;\n\nfunction debounce(fn, wait, callFirst) {\n var timeout = null;\n var debouncedFn = null;\n\n var clear = function() {\n if (timeout) {\n clearTimeout(timeout);\n\n debouncedFn = null;\n timeout = null;\n }\n };\n\n var flush = function() {\n var call = debouncedFn;\n clear();\n\n if (call) {\n call();\n }\n };\n\n var debounceWrapper = function() {\n if (!wait) {\n return fn.apply(this, arguments);\n }\n\n var context = this;\n var args = arguments;\n var callNow = callFirst && !timeout;\n clear();\n\n debouncedFn = function() {\n fn.apply(context, args);\n };\n\n timeout = setTimeout(function() {\n timeout = null;\n\n if (!callNow) {\n var call = debouncedFn;\n debouncedFn = null;\n\n return call();\n }\n }, wait);\n\n if (callNow) {\n return debouncedFn();\n }\n };\n\n debounceWrapper.cancel = clear;\n debounceWrapper.flush = flush;\n\n return debounceWrapper;\n}\n\nexport {functionDebounce as default};\n", "\n// @ts-ignore\nimport debounce from 'just-debounce-it'\nimport { BitswapMessage as Message } from '../message/index.js'\nimport { logger } from '../utils/index.js'\nimport { wantlistSendDebounceMs } from '../constants.js'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('../network').Network} Network\n */\n\nexport class MsgQueue {\n /**\n * @param {PeerId} selfPeerId\n * @param {PeerId} otherPeerId\n * @param {Network} network\n */\n constructor (selfPeerId, otherPeerId, network) {\n this.peerId = otherPeerId\n this.network = network\n this.refcnt = 1\n\n /**\n * @private\n * @type {{cid:CID, priority:number, cancel?:boolean}[]}\n */\n this._entries = []\n /** @private */\n this._log = logger(selfPeerId, 'msgqueue')\n this.sendEntries = debounce(this._sendEntries.bind(this), wantlistSendDebounceMs)\n }\n\n /**\n * @param {Message} msg\n */\n addMessage (msg) {\n if (msg.empty) {\n return\n }\n\n this.send(msg)\n }\n\n /**\n * @param {{cid:CID, priority:number}[]} entries\n */\n addEntries (entries) {\n this._entries = this._entries.concat(entries)\n this.sendEntries()\n }\n\n /**\n * @private\n */\n _sendEntries () {\n if (!this._entries.length) {\n return\n }\n\n const msg = new Message(false)\n this._entries.forEach((entry) => {\n if (entry.cancel) {\n msg.cancel(entry.cid)\n } else {\n msg.addEntry(entry.cid, entry.priority)\n }\n })\n this._entries = []\n this.addMessage(msg)\n }\n\n /**\n * @param {Message} msg\n */\n async send (msg) {\n try {\n await this.network.connectTo(this.peerId)\n } catch (/** @type {any} */ err) {\n this._log.error('cant connect to peer %s: %s', this.peerId.toString(), err.message)\n return\n }\n\n this._log('sending message to peer %s', this.peerId.toString())\n\n // Note: Don't wait for sendMessage() to complete\n this.network.sendMessage(this.peerId, msg).catch((err) => {\n this._log.error('send error: %s', err.message)\n })\n }\n}\n", "\nimport { BitswapMessage as Message } from '../message/index.js'\nimport { Wantlist } from '../wantlist/index.js'\nimport * as CONSTANTS from '../constants.js'\nimport { MsgQueue } from './msg-queue.js'\nimport { logger } from '../utils/index.js'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { trackedMap } from '@libp2p/tracked-map'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats').CID} CID\n */\n\nexport class WantManager {\n /**\n * @param {PeerId} peerId\n * @param {import('../network').Network} network\n * @param {import('../stats').Stats} stats\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n */\n constructor (peerId, network, stats, libp2p) {\n /** @type {Map} */\n this.peers = trackedMap({\n name: 'ipfs_bitswap_want_manager_peers',\n metrics: libp2p.metrics\n })\n this.wantlist = new Wantlist(stats, libp2p)\n\n this.network = network\n this._stats = stats\n\n this._peerId = peerId\n this._log = logger(peerId, 'want')\n }\n\n /**\n * @private\n * @param {CID[]} cids\n * @param {boolean} cancel\n * @param {boolean} [force]\n */\n _addEntries (cids, cancel, force) {\n const entries = cids.map((cid, i) => {\n return new Message.Entry(cid, CONSTANTS.kMaxPriority - i, Message.WantType.Block, cancel)\n })\n\n entries.forEach((e) => {\n // add changes to our wantlist\n if (e.cancel) {\n if (force) {\n this.wantlist.removeForce(e.cid.toString(base58btc))\n } else {\n this.wantlist.remove(e.cid)\n }\n } else {\n this._log('adding to wl')\n // TODO: Figure out the wantType\n // @ts-expect-error - requires wantType\n this.wantlist.add(e.cid, e.priority)\n }\n })\n\n // broadcast changes\n for (const p of this.peers.values()) {\n p.addEntries(entries)\n }\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _startPeerHandler (peerId) {\n let mq = this.peers.get(peerId.toString())\n\n if (mq) {\n mq.refcnt++\n return\n }\n\n mq = new MsgQueue(this._peerId, peerId, this.network)\n\n // new peer, give them the full wantlist\n const fullwantlist = new Message(true)\n\n for (const entry of this.wantlist.entries()) {\n fullwantlist.addEntry(entry[1].cid, entry[1].priority)\n }\n\n mq.addMessage(fullwantlist)\n\n this.peers.set(peerId.toString(), mq)\n return mq\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _stopPeerHandler (peerId) {\n const mq = this.peers.get(peerId.toString())\n\n if (!mq) {\n return\n }\n\n mq.refcnt--\n if (mq.refcnt > 0) {\n return\n }\n\n this.peers.delete(peerId.toString())\n }\n\n /**\n * add all the cids to the wantlist\n *\n * @param {CID[]} cids\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n wantBlocks (cids, options = {}) {\n this._addEntries(cids, false)\n\n if (options && options.signal) {\n options.signal.addEventListener('abort', () => {\n this.cancelWants(cids)\n })\n }\n }\n\n /**\n * Remove blocks of all the given keys without respecting refcounts\n *\n * @param {CID[]} cids\n */\n unwantBlocks (cids) {\n this._log('unwant blocks: %s', cids.length)\n this._addEntries(cids, true, true)\n }\n\n /**\n * Cancel wanting all of the given keys\n *\n * @param {CID[]} cids\n */\n cancelWants (cids) {\n this._log('cancel wants: %s', cids.length)\n this._addEntries(cids, true)\n }\n\n /**\n * Returns a list of all currently connected peers\n */\n connectedPeers () {\n return Array.from(this.peers.keys())\n }\n\n /**\n * @param {PeerId} peerId\n */\n connected (peerId) {\n this._startPeerHandler(peerId)\n }\n\n /**\n * @param {PeerId} peerId\n */\n disconnected (peerId) {\n this._stopPeerHandler(peerId)\n }\n\n start () {\n }\n\n stop () {\n this.peers.forEach((mq) => this.disconnected(mq.peerId))\n }\n}\n", "import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = () => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] () {\n return symbol.toString()\n }\n\n get [symbol] () {\n return true\n }\n\n async setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId) {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n", "import * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport { createTopology } from '@libp2p/topology'\nimport { BitswapMessage as Message } from './message/index.js'\nimport * as CONSTANTS from './constants.js'\nimport { logger } from './utils/index.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableSource } from 'abortable-iterator'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n * @typedef {import('@libp2p/interface-connection').Connection} Connection\n * @typedef {import('@libp2p/interface-connection').Stream} Stream\n * @typedef {import('./types').MultihashHasherLoader} MultihashHasherLoader\n *\n * @typedef {object} Provider\n * @property {PeerId} id\n * @property {Multiaddr[]} multiaddrs\n *\n * @typedef {import('it-stream-types').Duplex} Duplex\n */\n\nconst BITSWAP100 = '/ipfs/bitswap/1.0.0'\nconst BITSWAP110 = '/ipfs/bitswap/1.1.0'\nconst BITSWAP120 = '/ipfs/bitswap/1.2.0'\n\nconst DEFAULT_MAX_INBOUND_STREAMS = 32\nconst DEFAULT_MAX_OUTBOUND_STREAMS = 128\nconst DEFAULT_INCOMING_STREAM_TIMEOUT = 30000\n\nexport class Network {\n /**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {import('./bitswap').Bitswap} bitswap\n * @param {import('./stats').Stats} stats\n * @param {object} [options]\n * @param {boolean} [options.b100Only]\n * @param {MultihashHasherLoader} [options.hashLoader]\n * @param {number} [options.maxInboundStreams=32]\n * @param {number} [options.maxOutboundStreams=32]\n * @param {number} [options.incomingStreamTimeout=30000]\n */\n constructor (libp2p, bitswap, stats, options = {}) {\n this._log = logger(libp2p.peerId, 'network')\n this._libp2p = libp2p\n this._bitswap = bitswap\n this._protocols = [BITSWAP100]\n\n if (!options.b100Only) {\n // Latest bitswap first\n this._protocols.unshift(BITSWAP110)\n this._protocols.unshift(BITSWAP120)\n }\n\n this._stats = stats\n this._running = false\n\n // bind event listeners\n this._onPeerConnect = this._onPeerConnect.bind(this)\n this._onPeerDisconnect = this._onPeerDisconnect.bind(this)\n this._onConnection = this._onConnection.bind(this)\n this._hashLoader = options.hashLoader\n this._maxInboundStreams = options.maxInboundStreams ?? DEFAULT_MAX_INBOUND_STREAMS\n this._maxOutboundStreams = options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS\n this._incomingStreamTimeout = options.incomingStreamTimeout ?? DEFAULT_INCOMING_STREAM_TIMEOUT\n }\n\n async start () {\n this._running = true\n await this._libp2p.handle(this._protocols, this._onConnection, {\n maxInboundStreams: this._maxInboundStreams,\n maxOutboundStreams: this._maxOutboundStreams\n })\n\n // register protocol with topology\n const topology = createTopology({\n onConnect: this._onPeerConnect,\n onDisconnect: this._onPeerDisconnect\n })\n\n /** @type {string[]} */\n this._registrarIds = []\n\n for (const protocol of this._protocols) {\n this._registrarIds.push(await this._libp2p.register(protocol, topology))\n }\n\n // All existing connections are like new ones for us\n this._libp2p.getConnections().forEach(conn => {\n this._onPeerConnect(conn.remotePeer)\n })\n }\n\n async stop () {\n this._running = false\n\n // Unhandle both, libp2p doesn't care if it's not already handled\n await this._libp2p.unhandle(this._protocols)\n\n // unregister protocol and handlers\n if (this._registrarIds != null) {\n for (const id of this._registrarIds) {\n this._libp2p.unregister(id)\n }\n\n this._registrarIds = []\n }\n }\n\n /**\n * Handles both types of incoming bitswap messages\n *\n * @private\n * @param {object} connection\n * @param {Stream} connection.stream - A duplex iterable stream\n * @param {Connection} connection.connection - A libp2p Connection\n */\n _onConnection ({ stream, connection }) {\n if (!this._running) {\n return\n }\n\n const controller = new TimeoutController(this._incomingStreamTimeout)\n\n Promise.resolve().then(async () => {\n this._log('incoming new bitswap %s connection from %p', stream.stat.protocol, connection.remotePeer)\n\n await pipe(\n abortableSource(stream.source, controller.signal),\n lp.decode(),\n async (source) => {\n for await (const data of source) {\n try {\n const message = await Message.deserialize(data.subarray(), this._hashLoader)\n await this._bitswap._receiveMessage(connection.remotePeer, message)\n } catch (/** @type {any} */ err) {\n this._bitswap._receiveError(err)\n break\n }\n\n // we have received some data so reset the timeout controller\n controller.reset()\n }\n }\n )\n })\n .catch(err => {\n this._log(err)\n stream.abort(err)\n })\n .finally(() => {\n controller.clear()\n stream.close()\n })\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _onPeerConnect (peerId) {\n this._bitswap._onPeerConnected(peerId)\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _onPeerDisconnect (peerId) {\n this._bitswap._onPeerDisconnected(peerId)\n }\n\n /**\n * Find providers given a `cid`.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n * @returns {AsyncIterable}\n */\n findProviders (cid, options = {}) {\n return this._libp2p.contentRouting.findProviders(cid, options)\n }\n\n /**\n * Find the providers of a given `cid` and connect to them.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async findAndConnect (cid, options) {\n const connectAttempts = []\n let found = 0\n\n for await (const provider of this.findProviders(cid, options)) {\n this._log(`connecting to provider ${provider.id}`)\n connectAttempts.push(\n this.connectTo(provider.id, options)\n .catch(err => {\n // Prevent unhandled promise rejection\n this._log.error(err)\n })\n )\n\n found++\n\n if (found === CONSTANTS.maxProvidersPerRequest) {\n break\n }\n }\n\n await Promise.all(connectAttempts)\n }\n\n /**\n * Tell the network we can provide content for the passed CID\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async provide (cid, options) {\n await this._libp2p.contentRouting.provide(cid, options)\n }\n\n /**\n * Connect to the given peer\n * Send the given msg (instance of Message) to the given peer\n *\n * @param {PeerId} peer\n * @param {Message} msg\n */\n async sendMessage (peer, msg) {\n if (!this._running) throw new Error('network isn\\'t running')\n\n const stringId = peer.toString()\n this._log('sendMessage to %s', stringId, msg)\n\n const connection = await this._libp2p.dial(peer)\n const stream = await connection.newStream([BITSWAP120, BITSWAP110, BITSWAP100])\n\n await writeMessage(stream, msg, this._log)\n\n this._updateSentStats(peer, msg.blocks)\n }\n\n /**\n * Connects to another peer\n *\n * @param {PeerId|Multiaddr} peer\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n * @returns {Promise}\n */\n async connectTo (peer, options) { // eslint-disable-line require-await\n if (!this._running) {\n throw new Error('network isn\\'t running')\n }\n\n return this._libp2p.dial(peer, options)\n }\n\n /**\n * @private\n * @param {PeerId} peer\n * @param {Map} blocks\n */\n _updateSentStats (peer, blocks) {\n const peerId = peer.toString()\n\n if (this._stats) {\n for (const block of blocks.values()) {\n this._stats.push(peerId, 'dataSent', block.length)\n }\n\n this._stats.push(peerId, 'blocksSent', blocks.size)\n }\n }\n}\n\n/**\n *\n * @param {Stream} stream\n * @param {Message} msg\n * @param {*} log\n */\nasync function writeMessage (stream, msg, log) {\n try {\n /** @type {Uint8Array} */\n let serialized\n switch (stream.stat.protocol) {\n case BITSWAP100:\n serialized = msg.serializeToBitswap100()\n break\n case BITSWAP110:\n case BITSWAP120:\n serialized = msg.serializeToBitswap110()\n break\n default:\n throw new Error('Unknown protocol: ' + stream.stat.protocol)\n }\n\n await pipe(\n [serialized],\n lp.encode(),\n stream\n )\n } catch (err) {\n log(err)\n } finally {\n stream.close()\n }\n}\n", "import { Wantlist } from '../wantlist/index.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n */\n\nexport class Ledger {\n /**\n * @param {import('@libp2p/interface-peer-id').PeerId} peerId\n */\n constructor (peerId) {\n this.partner = peerId\n this.wantlist = new Wantlist()\n\n this.exchangeCount = 0\n this.sentToPeer = new Map()\n\n this.accounting = {\n bytesSent: 0,\n bytesRecv: 0\n }\n }\n\n /**\n * @param {number} n\n */\n sentBytes (n) {\n this.exchangeCount++\n this.lastExchange = (new Date()).getTime()\n this.accounting.bytesSent += n\n }\n\n /**\n * @param {number} n\n */\n receivedBytes (n) {\n this.exchangeCount++\n this.lastExchange = (new Date()).getTime()\n this.accounting.bytesRecv += n\n }\n\n /**\n *\n * @param {CID} cid\n * @param {number} priority\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n * @returns {void}\n */\n wants (cid, priority, wantType) {\n this.wantlist.add(cid, priority, wantType)\n }\n\n /**\n * @param {CID} cid\n * @returns {void}\n */\n\n cancelWant (cid) {\n this.wantlist.remove(cid)\n }\n\n /**\n * @param {CID} cid\n */\n wantlistContains (cid) {\n return this.wantlist.get(cid)\n }\n\n /**\n * @returns {number}\n */\n debtRatio () {\n return (this.accounting.bytesSent / (this.accounting.bytesRecv + 1)) // +1 is to prevent division by zero\n }\n}\n", "/**\n * @template Key, Value\n * SortedMap is a Map whose iterator order can be defined by the user\n * @extends {Map}\n */\nexport class SortedMap extends Map {\n /**\n * @param {Array<[Key, Value]>} [entries]\n * @param {(a:[Key, Value], b:[Key, Value]) => number} [cmp] - compares [k1, v1] to [k2, v2]\n */\n constructor (entries, cmp) {\n super()\n this._cmp = cmp || this._defaultSort\n /** @type {Key[]} */\n this._keys = []\n for (const [k, v] of entries || []) {\n this.set(k, v)\n }\n }\n\n /**\n * Call update to update the position of the key when it should change.\n * For example if the compare function sorts by the priority field, and the\n * priority changes, call update.\n * Call indexOf() to get the index _before_ the change happens.\n *\n * @param {number} i - the index of entry whose position should be updated.\n */\n update (i) {\n if (i < 0 || i >= this._keys.length) {\n return\n }\n\n const k = this._keys[i]\n this._keys.splice(i, 1)\n const newIdx = this._find(k)\n this._keys.splice(newIdx, 0, k)\n }\n\n /**\n * @param {Key} k\n * @param {Value} v\n */\n set (k, v) {\n // If the key is already in the map, remove it from the ordering and\n // re-insert it below\n if (this.has(k)) {\n const i = this.indexOf(k)\n this._keys.splice(i, 1)\n }\n\n // Update / insert the k/v into the map\n super.set(k, v)\n\n // Find the correct position of the newly inserted k/v in the order\n const i = this._find(k)\n this._keys.splice(i, 0, k)\n\n return this\n }\n\n clear () {\n super.clear()\n this._keys = []\n }\n\n /**\n * @param {Key} k\n */\n delete (k) {\n if (!this.has(k)) {\n return false\n }\n\n const i = this.indexOf(k)\n this._keys.splice(i, 1)\n return super.delete(k)\n }\n\n /**\n * @param {Key} k\n */\n indexOf (k) {\n if (!this.has(k)) {\n return -1\n }\n\n const i = this._find(k)\n if (this._keys[i] === k) {\n return i\n }\n\n // There may be more than one key with the same ordering\n // eg { k1: , k2: }\n // so scan outwards until the key matches\n for (let j = 1; j < this._keys.length; j++) {\n if (this._keys[i + j] === k) return i + j\n if (this._keys[i - j] === k) return i - j\n }\n\n return -1 // should never happen for existing key\n }\n\n /**\n * @private\n * @param {Key} k\n * @returns {number}\n */\n\n _find (k) {\n let lower = 0\n let upper = this._keys.length\n while (lower < upper) {\n const pivot = (lower + upper) >>> 1 // lower + (upper - lower) / 2\n const cmp = this._kCmp(this._keys[pivot], k)\n // console.log(` _find ${lower}:${upper}[${pivot}] ${cmp}`)\n if (cmp < 0) { // pivot < k\n lower = pivot + 1\n } else if (cmp > 0) { // pivot > k\n upper = pivot\n } else { // pivot == k\n return pivot\n }\n }\n return lower\n }\n\n * keys () {\n for (const k of this._keys) {\n yield k\n }\n\n return undefined\n }\n\n /**\n * @returns {IterableIterator}\n */\n * values () {\n for (const k of this._keys) {\n // @ts-ignore - return of `this.get(k)` is `Value|undefined` which is\n // incompatible with `Value`. Typechecker can't that this contains values\n // for all the `_keys`. ts(2322)\n yield this.get(k)\n }\n\n return undefined\n }\n\n /**\n * @returns {IterableIterator<[Key, Value]>}\n */\n * entries () {\n for (const k of this._keys) {\n // @ts-ignore - return of `this.get(k)` is `Value|undefined` which is\n // incompatible with `Value`. Typechecker can't that this contains values\n // for all the `_keys`. ts(2322)\n yield [k, this.get(k)]\n }\n\n return undefined\n }\n\n * [Symbol.iterator] () {\n yield * this.entries()\n }\n\n /**\n * @template This\n * @param {(entry:[Key, Value]) => void} cb\n * @param {This} [thisArg]\n */\n // @ts-expect-error - Callback in Map forEach is (V, K, Map) => void\n forEach (cb, thisArg) {\n if (!cb) {\n return\n }\n\n for (const k of this._keys) {\n cb.apply(thisArg, [[k, /** @type {Value} */(this.get(k))]])\n }\n }\n\n /**\n * @private\n * @param {[Key, Value]} a\n * @param {[Key, Value]} b\n * @returns {0|1|-1}\n */\n _defaultSort (a, b) {\n if (a[0] < b[0]) return -1\n if (b[0] < a[0]) return 1\n return 0\n }\n\n /**\n * @private\n * @param {Key} a\n * @param {Key} b\n */\n _kCmp (a, b) {\n return this._cmp(\n // @ts-ignore - get may return undefined\n [a, this.get(a)],\n // @ts-ignore - get may return undefined\n [b, this.get(b)]\n )\n }\n}\n", "import { SortedMap } from '../utils/sorted-map.js'\n\n/**\n * @typedef {object} PopTaskResult\n * @property {PeerId} [peerId]\n * @property {Task[]} tasks\n * @property {number} pendingSize\n *\n * @typedef {object} PendingTask\n * @property {number} created\n * @property {Task} task\n *\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('./types').Task} Task\n * @typedef {import('./types').TaskMerger} TaskMerger\n */\n\n/**\n * The task merger that is used by default.\n * Assumes that new tasks do not add any information over existing tasks,\n * and doesn't try to merge.\n *\n * @type {TaskMerger}\n */\nconst DefaultTaskMerger = {\n hasNewInfo () {\n return false\n },\n\n merge () {}\n}\n\n/**\n * Queue of requests to be processed by the engine.\n * The requests from each peer are added to the peer's queue, sorted by\n * priority.\n * Tasks are popped in priority order from the best peer - see popTasks()\n * for more details.\n */\nexport class RequestQueue {\n /**\n * @param {TaskMerger} [taskMerger]\n */\n constructor (taskMerger = DefaultTaskMerger) {\n this._taskMerger = taskMerger\n /** @type {SortedMap} */\n this._byPeer = new SortedMap([], PeerTasks.compare)\n }\n\n /**\n * Push tasks onto the queue for the given peer\n *\n * @param {PeerId} peerId\n * @param {Task[]} tasks\n * @returns {void}\n */\n pushTasks (peerId, tasks) {\n let peerTasks = this._byPeer.get(peerId.toString())\n\n if (!peerTasks) {\n peerTasks = new PeerTasks(peerId, this._taskMerger)\n }\n\n peerTasks.pushTasks(tasks)\n this._byPeer.set(peerId.toString(), peerTasks)\n }\n\n /**\n * Choose the peer with the least active work (or if all have the same active\n * work, the most pending tasks) and pop off the highest priority tasks until\n * the total size is at least targetMinBytes.\n * This puts the popped tasks into the \"active\" state, meaning they are\n * actively being processed (and cannot be modified).\n *\n * @param {number} targetMinBytes - the minimum total size of tasks to pop\n * @returns {PopTaskResult}\n */\n popTasks (targetMinBytes) {\n // Get the queue of tasks for the best peer and pop off tasks up to\n // targetMinBytes\n const peerTasks = this._head()\n if (peerTasks === undefined) {\n return { tasks: [], pendingSize: 0 }\n }\n\n const { tasks, pendingSize } = peerTasks.popTasks(targetMinBytes)\n if (tasks.length === 0) {\n return { tasks, pendingSize }\n }\n\n const peerId = peerTasks.peerId\n if (peerTasks.isIdle()) {\n // If there are no more tasks for the peer, free up its memory\n this._byPeer.delete(peerId.toString())\n } else {\n // If there are still tasks remaining, update the sort order of peerTasks\n // (because it depends on the number of pending tasks)\n this._byPeer.update(0)\n }\n\n return {\n peerId, tasks, pendingSize\n }\n }\n\n /**\n * @private\n * @returns {PeerTasks|undefined}\n */\n _head () {\n // Shortcut\n if (this._byPeer.size === 0) {\n return undefined\n }\n\n // eslint-disable-next-line no-unreachable-loop\n for (const [, v] of this._byPeer) {\n return v\n }\n\n return undefined\n }\n\n /**\n * Remove the task with the given topic for the given peer.\n *\n * @param {string} topic\n * @param {PeerId} peerId\n * @returns {void}\n */\n remove (topic, peerId) {\n const peerTasks = this._byPeer.get(peerId.toString())\n peerTasks && peerTasks.remove(topic)\n }\n\n /**\n * Called when the tasks for the given peer complete.\n *\n * @param {PeerId} peerId\n * @param {Task[]} tasks\n * @returns {void}\n */\n tasksDone (peerId, tasks) {\n const peerTasks = this._byPeer.get(peerId.toString())\n if (!peerTasks) {\n return\n }\n\n const i = this._byPeer.indexOf(peerId.toString())\n for (const task of tasks) {\n peerTasks.taskDone(task)\n }\n\n // Marking the tasks as done takes them out of the \"active\" state, and the\n // sort order depends on the size of the active tasks, so we need to update\n // the order.\n this._byPeer.update(i)\n }\n}\n\n/**\n * Queue of tasks for a particular peer, sorted by priority.\n */\nclass PeerTasks {\n /**\n * @param {PeerId} peerId\n * @param {TaskMerger} taskMerger\n */\n constructor (peerId, taskMerger) {\n this.peerId = peerId\n this._taskMerger = taskMerger\n this._activeTotalSize = 0\n this._pending = new PendingTasks()\n this._active = new Set()\n }\n\n /**\n * Push tasks onto the queue.\n *\n * @param {Task[]} tasks\n * @returns {void}\n */\n pushTasks (tasks) {\n for (const t of tasks) {\n this._pushTask(t)\n }\n }\n\n /**\n * @private\n * @param {Task} task\n * @returns {void}\n */\n\n _pushTask (task) {\n // If the new task doesn't add any more information over what we\n // already have in the active queue, then we can skip the new task\n if (!this._taskHasMoreInfoThanActiveTasks(task)) {\n return\n }\n\n // If there is already a non-active (pending) task with this topic\n const existingTask = this._pending.get(task.topic)\n if (existingTask) {\n // If the new task has a higher priority than the old task,\n if (task.priority > existingTask.priority) {\n // Update the priority and the task's position in the queue\n this._pending.updatePriority(task.topic, task.priority)\n }\n\n // Merge the information from the new task into the existing task\n this._taskMerger.merge(task, existingTask)\n\n // A task with the topic exists, so we don't need to add\n // the new task to the queue\n return\n }\n\n // Push the new task onto the queue\n this._pending.add(task)\n }\n\n /**\n * Indicates whether the new task adds any more information over tasks that are\n * already in the active task queue\n *\n * @private\n * @param {Task} task\n * @returns {boolean}\n */\n _taskHasMoreInfoThanActiveTasks (task) {\n const tasksWithTopic = []\n for (const activeTask of this._active) {\n if (activeTask.topic === task.topic) {\n tasksWithTopic.push(activeTask)\n }\n }\n\n // No tasks with that topic, so the new task adds information\n if (tasksWithTopic.length === 0) {\n return true\n }\n\n return this._taskMerger.hasNewInfo(task, tasksWithTopic)\n }\n\n /**\n * Pop tasks off the queue such that the total size is at least targetMinBytes\n *\n * @param {number} targetMinBytes\n * @returns {PopTaskResult}\n */\n popTasks (targetMinBytes) {\n let size = 0\n const tasks = []\n\n // Keep popping tasks until we get up to targetMinBytes (or one item over\n // targetMinBytes)\n const pendingTasks = this._pending.tasks()\n for (let i = 0; i < pendingTasks.length && size < targetMinBytes; i++) {\n const task = pendingTasks[i]\n tasks.push(task)\n size += task.size\n\n // Move tasks from pending to active\n this._pending.delete(task.topic)\n this._activeTotalSize += task.size\n this._active.add(task)\n }\n\n return {\n tasks, pendingSize: this._pending.totalSize\n }\n }\n\n /**\n * Called when a task completes.\n * Note: must be the same reference as returned from popTasks.\n *\n * @param {Task} task\n * @returns {void}\n */\n taskDone (task) {\n if (this._active.has(task)) {\n this._activeTotalSize -= task.size\n this._active.delete(task)\n }\n }\n\n /**\n * Remove pending tasks with the given topic\n *\n * @param {string} topic\n * @returns {void}\n */\n remove (topic) {\n this._pending.delete(topic)\n }\n\n /**\n * No work to be done, this PeerTasks object can be freed.\n *\n * @returns {boolean}\n */\n isIdle () {\n return this._pending.length === 0 && this._active.size === 0\n }\n\n /**\n * Compare PeerTasks\n *\n * @template Key\n * @param {[Key, PeerTasks]} a\n * @param {[Key, PeerTasks]} b\n * @returns {number}\n */\n static compare (a, b) {\n // Move peers with no pending tasks to the back of the queue\n if (a[1]._pending.length === 0) {\n return 1\n }\n if (b[1]._pending.length === 0) {\n return -1\n }\n\n // If the amount of active work is the same\n if (a[1]._activeTotalSize === b[1]._activeTotalSize) {\n // Choose the peer with the most pending work\n return b[1]._pending.length - a[1]._pending.length\n }\n\n // Choose the peer with the least amount of active work (\"keep peers busy\")\n return a[1]._activeTotalSize - b[1]._activeTotalSize\n }\n}\n\n/**\n * Queue of pending tasks for a particular peer, sorted by priority.\n */\nclass PendingTasks {\n constructor () {\n /** @type {SortedMap} */\n this._tasks = new SortedMap([], this._compare)\n }\n\n get length () {\n return this._tasks.size\n }\n\n /**\n * Sum of the size of all pending tasks\n *\n * @type {number}\n **/\n get totalSize () {\n return [...this._tasks.values()].reduce((a, t) => a + t.task.size, 0)\n }\n\n /**\n * @param {string} topic\n * @returns {Task|void}\n */\n get (topic) {\n return (this._tasks.get(topic) || {}).task\n }\n\n /**\n * @param {Task} task\n */\n add (task) {\n this._tasks.set(task.topic, {\n created: Date.now(),\n task\n })\n }\n\n /**\n * @param {string} topic\n * @returns {void}\n */\n delete (topic) {\n this._tasks.delete(topic)\n }\n\n // All pending tasks, in priority order\n tasks () {\n return [...this._tasks.values()].map(i => i.task)\n }\n\n /**\n * Update the priority of the task with the given topic, and update the order\n *\n * @param {string} topic\n * @param {number} priority\n * @returns {void}\n **/\n updatePriority (topic, priority) {\n const obj = this._tasks.get(topic)\n if (!obj) {\n return\n }\n\n const i = this._tasks.indexOf(topic)\n obj.task.priority = priority\n this._tasks.update(i)\n }\n\n /**\n * Sort by priority desc then FIFO\n *\n * @param {[string, PendingTask]} a\n * @param {[string, PendingTask]} b\n * @returns {number}\n * @private\n */\n _compare (a, b) {\n if (a[1].task.priority === b[1].task.priority) {\n // FIFO\n return a[1].created - b[1].created\n }\n // Priority high -> low\n return b[1].task.priority - a[1].task.priority\n }\n}\n", "/**\n * @typedef {import('./types').Task} Task\n * @typedef {import('./types').TaskMerger} TaskMergerAPI\n */\n\n/** @type {TaskMergerAPI} */\nexport const TaskMerger = {\n /**\n * Indicates whether the given task has newer information than the active\n * tasks with the same topic.\n *\n * @param {Task} task\n * @param {Task[]} tasksWithTopic\n * @returns {boolean}\n */\n hasNewInfo (task, tasksWithTopic) {\n let haveBlock = false\n let isWantBlock = false\n for (const existing of tasksWithTopic) {\n if (existing.data.haveBlock) {\n haveBlock = true\n }\n\n if (existing.data.isWantBlock) {\n isWantBlock = true\n }\n }\n\n // If there is no active want-block and the new task is a want-block,\n // the new task is better\n if (!isWantBlock && task.data.isWantBlock) {\n return true\n }\n\n // If we didn't have the block, and the new task indicates that we now\n // do have the block, then we must also have size information for the\n // block, so the new task has new information.\n if (!haveBlock && task.data.haveBlock) {\n return true\n }\n\n return false\n },\n\n /**\n * Merge the information from the given task into the existing task (with the\n * same topic)\n *\n * @param {Task} newTask\n * @param {Task} existingTask\n */\n merge (newTask, existingTask) {\n // The merge function ignores the topic and priority as these don't change.\n //\n // We may receive new information about a want before the want has been\n // popped from the queue in the following scenarios:\n //\n // - Replace want type:\n // 1. Client sends want-have CID1\n // 2. Client sends want-block CID1\n // In this case we should replace want-have with want-block, including\n // updating the task size to be the block size.\n //\n // - Replace DONT_HAVE with want:\n // 1. Client sends want-have CID1 or want-block CID1\n // 2. Local node doesn't have block for CID1\n // 3. Local node receives block for CID1 from peer\n // In this case we should replace DONT_HAVE with the want, including\n // updating the task size and block size.\n const taskData = newTask.data\n const existingData = existingTask.data\n\n // If we didn't have block size information (because we didn't have the\n // block) and we receive the block from a peer, update the task with the\n // new block size\n if (!existingData.haveBlock && taskData.haveBlock) {\n existingData.haveBlock = taskData.haveBlock\n existingData.blockSize = taskData.blockSize\n }\n\n // If replacing a want-have with a want-block\n if (!existingData.isWantBlock && taskData.isWantBlock) {\n // Change the type from want-have to want-block\n existingData.isWantBlock = true\n // If the want-have was a DONT_HAVE, or the want-block has a size\n if (!existingData.haveBlock || taskData.haveBlock) {\n // Update the entry size\n existingData.haveBlock = taskData.haveBlock\n existingTask.size = newTask.size\n }\n }\n\n // If the task is a want-block, make sure the entry size is equal\n // to the block size (because we will send the whole block)\n if (existingData.isWantBlock && existingData.haveBlock) {\n existingTask.size = existingData.blockSize\n }\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { BitswapMessage as Message } from '../message/index.js'\nimport { Wantlist } from '../wantlist/index.js'\nimport { Ledger } from './ledger.js'\nimport { RequestQueue } from './req-queue.js'\nimport { TaskMerger } from './task-merger.js'\nimport { logger } from '../utils/index.js'\nimport { trackedMap } from '@libp2p/tracked-map'\n\n/**\n * @typedef {import('../message/entry').BitswapMessageEntry} BitswapMessageEntry\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\nconst WantType = Message.WantType\n\n// The ideal size of the batched payload. We try to pop this much data off the\n// request queue, but\n// - if there isn't any more data in the queue we send whatever we have\n// - if there are several small items in the queue (eg HAVE response) followed\n// by one big item (eg a block) that would exceed this target size, we\n// include the big item in the message\nconst TARGET_MESSAGE_SIZE = 16 * 1024\n\n// If the client sends a want-have, and the engine has the corresponding block,\n// we check the size of the block and if it's small enough we send the block\n// itself, rather than sending a HAVE.\n// This constant defines the maximum size up to which we replace a HAVE with\n// a block.\nconst MAX_SIZE_REPLACE_HAS_WITH_BLOCK = 1024\n\nexport class DecisionEngine {\n /**\n * @param {PeerId} peerId\n * @param {import('interface-blockstore').Blockstore} blockstore\n * @param {import('../network').Network} network\n * @param {import('../stats').Stats} stats\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {object} [opts]\n * @param {number} [opts.targetMessageSize]\n * @param {number} [opts.maxSizeReplaceHasWithBlock]\n */\n constructor (peerId, blockstore, network, stats, libp2p, opts = {}) {\n this._log = logger(peerId, 'engine')\n this.blockstore = blockstore\n this.network = network\n this._stats = stats\n this._opts = this._processOpts(opts)\n\n // A list of of ledgers by their partner id\n /** @type {Map} */\n this.ledgerMap = trackedMap({\n name: 'ipfs_bitswap_ledger_map',\n metrics: libp2p.metrics\n })\n this._running = false\n\n // Queue of want-have / want-block per peer\n this._requestQueue = new RequestQueue(TaskMerger)\n }\n\n /**\n * @template {object} Opts\n * @param {Opts} opts\n * @returns {Opts & {maxSizeReplaceHasWithBlock:number, targetMessageSize:number}}\n * @private\n */\n _processOpts (opts) {\n return {\n maxSizeReplaceHasWithBlock: MAX_SIZE_REPLACE_HAS_WITH_BLOCK,\n targetMessageSize: TARGET_MESSAGE_SIZE,\n ...opts\n }\n }\n\n _scheduleProcessTasks () {\n setTimeout(() => {\n this._processTasks()\n })\n }\n\n /**\n * Pull tasks off the request queue and send a message to the corresponding\n * peer\n */\n async _processTasks () {\n if (!this._running) {\n return\n }\n\n const { peerId, tasks, pendingSize } = this._requestQueue.popTasks(this._opts.targetMessageSize)\n\n if (tasks.length === 0) {\n return\n }\n\n // Create a new message\n const msg = new Message(false)\n\n // Amount of data in the request queue still waiting to be popped\n msg.setPendingBytes(pendingSize)\n\n // Split out want-blocks, want-haves and DONT_HAVEs\n const blockCids = []\n const blockTasks = new Map()\n for (const task of tasks) {\n const cid = CID.parse(task.topic)\n if (task.data.haveBlock) {\n if (task.data.isWantBlock) {\n blockCids.push(cid)\n blockTasks.set(task.topic, task.data)\n } else {\n // Add HAVES to the message\n msg.addHave(cid)\n }\n } else {\n // Add DONT_HAVEs to the message\n msg.addDontHave(cid)\n }\n }\n\n const blocks = await this._getBlocks(blockCids)\n for (const [topic, taskData] of blockTasks) {\n const cid = CID.parse(topic)\n const blk = blocks.get(topic)\n // If the block was found (it has not been removed)\n if (blk) {\n // Add the block to the message\n msg.addBlock(cid, blk)\n } else {\n // The block was not found. If the client requested DONT_HAVE,\n // add DONT_HAVE to the message.\n if (taskData.sendDontHave) {\n msg.addDontHave(cid)\n }\n }\n }\n\n // If there's nothing in the message, bail out\n if (msg.empty) {\n peerId && this._requestQueue.tasksDone(peerId, tasks)\n\n // Trigger the next round of task processing\n this._scheduleProcessTasks()\n\n return\n }\n\n try {\n // Send the message\n peerId && await this.network.sendMessage(peerId, msg)\n\n // Peform sent message accounting\n for (const [cidStr, block] of blocks.entries()) {\n peerId && this.messageSent(peerId, CID.parse(cidStr), block)\n }\n } catch (err) {\n this._log.error(err)\n }\n\n // Free the tasks up from the request queue\n peerId && this._requestQueue.tasksDone(peerId, tasks)\n\n // Trigger the next round of task processing\n this._scheduleProcessTasks()\n }\n\n /**\n * @param {PeerId} peerId\n * @returns {Map}\n */\n wantlistForPeer (peerId) {\n const peerIdStr = peerId.toString()\n const ledger = this.ledgerMap.get(peerIdStr)\n return ledger ? ledger.wantlist.sortedEntries() : new Map()\n }\n\n /**\n * @param {PeerId} peerId\n */\n ledgerForPeer (peerId) {\n const peerIdStr = peerId.toString()\n\n const ledger = this.ledgerMap.get(peerIdStr)\n\n if (!ledger) {\n return null\n }\n\n return {\n peer: ledger.partner,\n value: ledger.debtRatio(),\n sent: ledger.accounting.bytesSent,\n recv: ledger.accounting.bytesRecv,\n exchanged: ledger.exchangeCount\n }\n }\n\n /**\n * @returns {PeerId[]}\n */\n peers () {\n return Array.from(this.ledgerMap.values()).map((l) => l.partner)\n }\n\n /**\n * Receive blocks either from an incoming message from the network, or from\n * blocks being added by the client on the localhost (eg IPFS add)\n *\n * @param {{ cid: CID, data: Uint8Array }[]} blocks\n */\n receivedBlocks (blocks) {\n if (!blocks.length) {\n return\n }\n\n // For each connected peer, check if it wants the block we received\n for (const ledger of this.ledgerMap.values()) {\n for (const block of blocks) {\n // Filter out blocks that we don't want\n const want = ledger.wantlistContains(block.cid)\n\n if (!want) {\n continue\n }\n\n // If the block is small enough, just send the block, even if the\n // client asked for a HAVE\n const blockSize = block.data.length\n const isWantBlock = this._sendAsBlock(want.wantType, blockSize)\n\n let entrySize = blockSize\n if (!isWantBlock) {\n entrySize = Message.blockPresenceSize(want.cid)\n }\n\n this._requestQueue.pushTasks(ledger.partner, [{\n topic: want.cid.toString(base58btc),\n priority: want.priority,\n size: entrySize,\n data: {\n blockSize,\n isWantBlock,\n haveBlock: true,\n sendDontHave: false\n }\n }])\n }\n }\n\n this._scheduleProcessTasks()\n }\n\n /**\n * Handle incoming messages\n *\n * @param {PeerId} peerId\n * @param {Message} msg\n * @returns {Promise}\n */\n async messageReceived (peerId, msg) {\n const ledger = this._findOrCreate(peerId)\n\n if (msg.empty) {\n return\n }\n\n // If the message has a full wantlist, clear the current wantlist\n if (msg.full) {\n ledger.wantlist = new Wantlist()\n }\n\n // Record the amount of block data received\n this._updateBlockAccounting(msg.blocks, ledger)\n\n if (msg.wantlist.size === 0) {\n this._scheduleProcessTasks()\n return\n }\n\n // Clear cancelled wants and add new wants to the ledger\n /** @type {CID[]} */\n const cancels = []\n /** @type {BitswapMessageEntry[]} */\n const wants = []\n msg.wantlist.forEach((entry) => {\n if (entry.cancel) {\n ledger.cancelWant(entry.cid)\n cancels.push(entry.cid)\n } else {\n ledger.wants(entry.cid, entry.priority, entry.wantType)\n wants.push(entry)\n }\n })\n\n this._cancelWants(peerId, cancels)\n await this._addWants(peerId, wants)\n\n this._scheduleProcessTasks()\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @param {CID[]} cids\n * @returns {void}\n */\n _cancelWants (peerId, cids) {\n for (const c of cids) {\n this._requestQueue.remove(c.toString(base58btc), peerId)\n }\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @param {BitswapMessageEntry[]} wants\n * @returns {Promise}\n */\n async _addWants (peerId, wants) {\n // Get the size of each wanted block\n const blockSizes = await this._getBlockSizes(wants.map(w => w.cid))\n\n const tasks = []\n for (const want of wants) {\n const id = want.cid.toString(base58btc)\n const blockSize = blockSizes.get(id)\n\n // If the block was not found\n if (blockSize == null) {\n // Only add the task to the queue if the requester wants a DONT_HAVE\n if (want.sendDontHave) {\n tasks.push({\n topic: id,\n priority: want.priority,\n size: Message.blockPresenceSize(want.cid),\n data: {\n isWantBlock: want.wantType === WantType.Block,\n blockSize: 0,\n haveBlock: false,\n sendDontHave: want.sendDontHave\n }\n })\n }\n } else {\n // The block was found, add it to the queue\n\n // If the block is small enough, just send the block, even if the\n // client asked for a HAVE\n const isWantBlock = this._sendAsBlock(want.wantType, blockSize)\n\n // entrySize is the amount of space the entry takes up in the\n // message we send to the recipient. If we're sending a block, the\n // entrySize is the size of the block. Otherwise it's the size of\n // a block presence entry.\n let entrySize = blockSize\n if (!isWantBlock) {\n entrySize = Message.blockPresenceSize(want.cid)\n }\n\n tasks.push({\n topic: id,\n priority: want.priority,\n size: entrySize,\n data: {\n isWantBlock,\n blockSize,\n haveBlock: true,\n sendDontHave: want.sendDontHave\n }\n })\n }\n\n this._requestQueue.pushTasks(peerId, tasks)\n }\n }\n\n /**\n * @private\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n * @param {number} blockSize\n */\n _sendAsBlock (wantType, blockSize) {\n return wantType === WantType.Block ||\n blockSize <= this._opts.maxSizeReplaceHasWithBlock\n }\n\n /**\n * @private\n * @param {CID[]} cids\n * @returns {Promise>}\n */\n async _getBlockSizes (cids) {\n const blocks = await this._getBlocks(cids)\n return new Map([...blocks].map(([k, v]) => [k, v.length]))\n }\n\n /**\n * @private\n * @param {CID[]} cids\n * @returns {Promise>}\n */\n async _getBlocks (cids) {\n const res = new Map()\n await Promise.all(cids.map(async (cid) => {\n try {\n const block = await this.blockstore.get(cid)\n res.set(cid.toString(base58btc), block)\n } catch (/** @type {any} */ e) {\n if (e.code !== 'ERR_NOT_FOUND') {\n this._log.error('failed to query blockstore for %s: %s', cid, e)\n }\n }\n }))\n return res\n }\n\n /**\n * @private\n * @param {Map} blocksMap\n * @param {Ledger} ledger\n */\n _updateBlockAccounting (blocksMap, ledger) {\n for (const block of blocksMap.values()) {\n this._log('got block (%s bytes)', block.length)\n ledger.receivedBytes(block.length)\n }\n }\n\n /**\n * Clear up all accounting things after message was sent\n *\n * @param {PeerId} peerId\n * @param {CID} cid\n * @param {Uint8Array} block\n */\n messageSent (peerId, cid, block) {\n const ledger = this._findOrCreate(peerId)\n ledger.sentBytes(block.length)\n ledger.wantlist.remove(cid)\n }\n\n /**\n * @param {PeerId} peerId\n * @returns {number}\n */\n numBytesSentTo (peerId) {\n return this._findOrCreate(peerId).accounting.bytesSent\n }\n\n /**\n * @param {PeerId} peerId\n * @returns {number}\n */\n\n numBytesReceivedFrom (peerId) {\n return this._findOrCreate(peerId).accounting.bytesRecv\n }\n\n /**\n *\n * @param {PeerId} peerId\n */\n peerDisconnected (peerId) {\n this.ledgerMap.delete(peerId.toString())\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @returns {Ledger}\n */\n _findOrCreate (peerId) {\n const peerIdStr = peerId.toString()\n const ledger = this.ledgerMap.get(peerIdStr)\n if (ledger) {\n return ledger\n }\n\n const l = new Ledger(peerId)\n\n this.ledgerMap.set(peerIdStr, l)\n if (this._stats) {\n this._stats.push(peerIdStr, 'peerCount', 1)\n }\n\n return l\n }\n\n start () {\n this._running = true\n }\n\n stop () {\n this._running = false\n }\n}\n", "import { EventEmitter } from 'events'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as CONSTANTS from './constants.js'\nimport { logger } from './utils/index.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\n/**\n * @param {CID} cid\n */\nconst unwantEvent = (cid) => `unwant:${uint8ArrayToString(cid.multihash.bytes, 'base64')}`\n\n/**\n * @param {CID} cid\n */\nconst blockEvent = (cid) => `block:${uint8ArrayToString(cid.multihash.bytes, 'base64')}`\n\nexport class Notifications extends EventEmitter {\n /**\n * Internal module used to track events about incoming blocks,\n * wants and unwants.\n *\n * @param {PeerId} peerId\n */\n constructor (peerId) {\n super()\n\n this.setMaxListeners(CONSTANTS.maxListeners)\n\n this._log = logger(peerId, 'notif')\n }\n\n /**\n * Signal the system that we received `block`.\n *\n * @param {CID} cid\n * @param {Uint8Array} block\n * @returns {void}\n */\n hasBlock (cid, block) {\n const event = blockEvent(cid)\n this._log(event)\n this.emit(event, block)\n }\n\n /**\n * Signal the system that we are waiting to receive the\n * block associated with the given `cid`.\n * Returns a Promise that resolves to the block when it is received,\n * or undefined when the block is unwanted.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n * @returns {Promise}\n */\n wantBlock (cid, options = {}) {\n if (!cid) {\n throw new Error('Not a valid cid')\n }\n\n const blockEvt = blockEvent(cid)\n const unwantEvt = unwantEvent(cid)\n\n this._log(`wantBlock:${cid}`)\n\n return new Promise((resolve, reject) => {\n const onUnwant = () => {\n this.removeListener(blockEvt, onBlock)\n\n reject(new Error(`Block for ${cid} unwanted`))\n }\n\n /**\n * @param {Uint8Array} data\n */\n const onBlock = (data) => {\n this.removeListener(unwantEvt, onUnwant)\n\n resolve(data)\n }\n\n this.once(unwantEvt, onUnwant)\n this.once(blockEvt, onBlock)\n\n if (options && options.signal) {\n options.signal.addEventListener('abort', () => {\n this.removeListener(blockEvt, onBlock)\n this.removeListener(unwantEvt, onUnwant)\n\n reject(new Error(`Want for ${cid} aborted`))\n })\n }\n })\n }\n\n /**\n * Signal that the block is not wanted anymore.\n *\n * @param {CID} cid - the CID of the block that is not wanted anymore.\n * @returns {void}\n */\n unwantBlock (cid) {\n const event = unwantEvent(cid)\n this._log(event)\n this.emit(event)\n }\n}\n", "import { EventEmitter } from 'events'\nimport { Stat } from './stat.js'\nimport { trackedMap } from '@libp2p/tracked-map'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\n/**\n * @typedef {[number, number, number]} AverageIntervals\n */\nconst defaultOptions = {\n enabled: false,\n computeThrottleTimeout: 1000,\n computeThrottleMaxQueueSize: 1000,\n movingAverageIntervals: /** @type {AverageIntervals} */ ([\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ])\n}\n\nexport class Stats extends EventEmitter {\n /**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {string[]} [initialCounters]\n * @param {object} _options\n * @param {boolean} _options.enabled\n * @param {number} _options.computeThrottleTimeout\n * @param {number} _options.computeThrottleMaxQueueSize\n */\n constructor (libp2p, initialCounters = [], _options = defaultOptions) {\n super()\n\n const options = Object.assign({}, defaultOptions, _options)\n\n if (typeof options.computeThrottleTimeout !== 'number') {\n throw new Error('need computeThrottleTimeout')\n }\n\n if (typeof options.computeThrottleMaxQueueSize !== 'number') {\n throw new Error('need computeThrottleMaxQueueSize')\n }\n\n this._initialCounters = initialCounters\n this._options = options\n this._enabled = this._options.enabled\n\n this._global = new Stat(initialCounters, options)\n this._global.on('update', (stats) => this.emit('update', stats))\n\n /** @type {Map} */\n this._peers = trackedMap({\n name: 'ipfs_bitswap_stats_peers',\n metrics: libp2p.metrics\n })\n }\n\n enable () {\n this._enabled = true\n this._options.enabled = true\n this._global.enable()\n }\n\n disable () {\n this._enabled = false\n this._options.enabled = false\n this._global.disable()\n }\n\n stop () {\n this._enabled = false\n this._global.stop()\n for (const peerStat of this._peers) {\n peerStat[1].stop()\n }\n }\n\n get snapshot () {\n return this._global.snapshot\n }\n\n get movingAverages () {\n return this._global.movingAverages\n }\n\n /**\n * @param {PeerId|string} peerId\n * @returns {Stat|undefined}\n */\n forPeer (peerId) {\n const peerIdStr = (typeof peerId !== 'string' && peerId.toString)\n ? peerId.toString()\n : `${peerId}`\n\n return this._peers.get(peerIdStr)\n }\n\n /**\n *\n * @param {string|null} peer\n * @param {string} counter\n * @param {number} inc\n */\n push (peer, counter, inc) {\n if (this._enabled) {\n this._global.push(counter, inc)\n\n if (peer) {\n let peerStats = this._peers.get(peer)\n if (!peerStats) {\n peerStats = new Stat(this._initialCounters, this._options)\n this._peers.set(peer, peerStats)\n }\n\n peerStats.push(counter, inc)\n }\n }\n }\n\n /**\n * @param {PeerId} peer\n */\n disconnected (peer) {\n const peerId = peer.toString()\n const peerStats = this._peers.get(peerId)\n if (peerStats) {\n peerStats.stop()\n this._peers.delete(peerId)\n }\n }\n}\n", "import { EventEmitter } from 'events'\nimport MovingAverage from '@vascosantos/moving-average'\n\n/**\n * @typedef {import('@vascosantos/moving-average').IMovingAverage} IMovingAverage\n * @typedef {[string, number, number]} Op\n */\n\nexport class Stat extends EventEmitter {\n /**\n *\n * @param {string[]} initialCounters\n * @param {object} options\n * @param {boolean} options.enabled\n * @param {number} options.computeThrottleTimeout\n * @param {number} options.computeThrottleMaxQueueSize\n * @param {import('.').AverageIntervals} options.movingAverageIntervals\n */\n constructor (initialCounters, options) {\n super()\n\n this._options = options\n /** @type {Op[]} */\n this._queue = []\n /** @type {Record} */\n this._stats = {}\n\n this._frequencyLastTime = Date.now()\n /** @type {Record} */\n this._frequencyAccumulators = {}\n\n /** @type {Record>} */\n this._movingAverages = {}\n\n this._update = this._update.bind(this)\n\n initialCounters.forEach((key) => {\n this._stats[key] = BigInt(0)\n this._movingAverages[key] = {}\n this._options.movingAverageIntervals.forEach((interval) => {\n const ma = this._movingAverages[key][interval] = MovingAverage(interval)\n ma.push(this._frequencyLastTime, 0)\n })\n })\n\n this._enabled = this._options.enabled\n }\n\n enable () {\n this._enabled = true\n }\n\n disable () {\n this._disabled = true\n }\n\n stop () {\n if (this._timeout) {\n clearTimeout(this._timeout)\n }\n }\n\n get snapshot () {\n return Object.assign({}, this._stats)\n }\n\n get movingAverages () {\n return Object.assign({}, this._movingAverages)\n }\n\n /**\n * @param {string} counter\n * @param {number} inc\n */\n push (counter, inc) {\n if (this._enabled) {\n this._queue.push([counter, inc, Date.now()])\n this._resetComputeTimeout()\n }\n }\n\n /**\n * @private\n */\n _resetComputeTimeout () {\n if (this._timeout) {\n clearTimeout(this._timeout)\n }\n this._timeout = setTimeout(this._update, this._nextTimeout())\n }\n\n /**\n * @private\n * @returns {number}\n */\n _nextTimeout () {\n // calculate the need for an update, depending on the queue length\n const urgency = this._queue.length / this._options.computeThrottleMaxQueueSize\n return Math.max(this._options.computeThrottleTimeout * (1 - urgency), 0)\n }\n\n /**\n * @private\n */\n _update () {\n this._timeout = null\n\n if (this._queue.length) {\n let last\n while (this._queue.length) {\n const op = last = this._queue.shift()\n op && this._applyOp(op)\n }\n\n last && this._updateFrequency(last[2]) // contains timestamp of last op\n\n this.emit('update', this._stats)\n }\n }\n\n /**\n * @private\n * @param {number} latestTime\n */\n _updateFrequency (latestTime) {\n const timeDiff = latestTime - this._frequencyLastTime\n\n if (timeDiff) {\n Object.keys(this._stats).forEach((key) => {\n this._updateFrequencyFor(key, timeDiff, latestTime)\n })\n }\n\n this._frequencyLastTime = latestTime\n }\n\n /**\n * @private\n * @param {string} key\n * @param {number} timeDiffMS\n * @param {number} latestTime\n * @returns {void}\n */\n _updateFrequencyFor (key, timeDiffMS, latestTime) {\n const count = this._frequencyAccumulators[key] || 0\n this._frequencyAccumulators[key] = 0\n const hz = (count / timeDiffMS) * 1000\n\n let movingAverages = this._movingAverages[key]\n if (!movingAverages) {\n movingAverages = this._movingAverages[key] = {}\n }\n this._options.movingAverageIntervals.forEach((movingAverageInterval) => {\n let movingAverage = movingAverages[movingAverageInterval]\n if (!movingAverage) {\n movingAverage = movingAverages[movingAverageInterval] = MovingAverage(movingAverageInterval)\n }\n movingAverage.push(latestTime, hz)\n })\n }\n\n /**\n * @private\n * @param {Op} op\n */\n _applyOp (op) {\n const key = op[0]\n const inc = op[1]\n\n if (typeof inc !== 'number') {\n throw new Error(`invalid increment number: ${inc}`)\n }\n\n if (!Object.prototype.hasOwnProperty.call(this._stats, key)) {\n this._stats[key] = BigInt(0)\n }\n\n this._stats[key] = BigInt(this._stats[key]) + BigInt(inc)\n\n if (!this._frequencyAccumulators[key]) {\n this._frequencyAccumulators[key] = 0\n }\n this._frequencyAccumulators[key] += inc\n }\n}\n", "import { WantManager } from './want-manager/index.js'\nimport { Network } from './network.js'\nimport { DecisionEngine } from './decision-engine/index.js'\nimport { Notifications } from './notifications.js'\nimport { logger } from './utils/index.js'\nimport { Stats } from './stats/index.js'\nimport { anySignal } from 'any-signal'\nimport { BaseBlockstore } from 'blockstore-core/base'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./types').IPFSBitswap} IPFSBitswap\n * @typedef {import('./types').MultihashHasherLoader} MultihashHasherLoader\n * @typedef {import('./message').BitswapMessage} BitswapMessage\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Options} Options\n */\n\nconst defaultOptions = {\n statsEnabled: false,\n statsComputeThrottleTimeout: 1000,\n statsComputeThrottleMaxQueueSize: 1000\n}\nconst statsKeys = [\n 'blocksReceived',\n 'dataReceived',\n 'dupBlksReceived',\n 'dupDataReceived',\n 'blocksSent',\n 'dataSent',\n 'providesBufferLength',\n 'wantListLength',\n 'peerCount'\n]\n\n/**\n * JavaScript implementation of the Bitswap 'data exchange' protocol\n * used by IPFS.\n *\n * @implements {IPFSBitswap}\n */\nexport class Bitswap extends BaseBlockstore {\n /**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {Blockstore} blockstore\n * @param {object} [options]\n * @param {boolean} [options.statsEnabled=false]\n * @param {number} [options.statsComputeThrottleTimeout=1000]\n * @param {number} [options.statsComputeThrottleMaxQueueSize=1000]\n * @param {number} [options.maxInboundStreams=32]\n * @param {number} [options.maxOutboundStreams=32]\n * @param {number} [options.incomingStreamTimeout=30000]\n * @param {MultihashHasherLoader} [options.hashLoader]\n */\n constructor (libp2p, blockstore, options = {}) {\n super()\n\n this._libp2p = libp2p\n this._log = logger(this.peerId)\n\n this._options = Object.assign({}, defaultOptions, options)\n\n // stats\n this._stats = new Stats(libp2p, statsKeys, {\n enabled: this._options.statsEnabled,\n computeThrottleTimeout: this._options.statsComputeThrottleTimeout,\n computeThrottleMaxQueueSize: this._options.statsComputeThrottleMaxQueueSize\n })\n\n // the network delivers messages\n this.network = new Network(libp2p, this, this._stats, {\n hashLoader: options.hashLoader,\n maxInboundStreams: options.maxInboundStreams,\n maxOutboundStreams: options.maxOutboundStreams,\n incomingStreamTimeout: options.incomingStreamTimeout\n })\n\n // local database\n this.blockstore = blockstore\n\n this.engine = new DecisionEngine(this.peerId, blockstore, this.network, this._stats, libp2p)\n\n // handle message sending\n this.wm = new WantManager(this.peerId, this.network, this._stats, libp2p)\n\n this.notifications = new Notifications(this.peerId)\n\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * @type {PeerId}\n */\n get peerId () {\n return this._libp2p.peerId\n }\n\n /**\n * handle messages received through the network\n *\n * @param {PeerId} peerId\n * @param {BitswapMessage} incoming\n */\n async _receiveMessage (peerId, incoming) {\n try {\n // Note: this allows the engine to respond to any wants in the message.\n // Processing of the blocks in the message happens below, after the\n // blocks have been added to the blockstore.\n await this.engine.messageReceived(peerId, incoming)\n } catch (err) {\n // Log instead of throwing an error so as to process as much as\n // possible of the message. Currently `messageReceived` does not\n // throw any errors, but this could change in the future.\n this._log('failed to receive message', incoming)\n }\n\n if (incoming.blocks.size === 0) {\n return\n }\n\n /** @type { { cid: CID, wasWanted: boolean, data: Uint8Array }[] } */\n const received = []\n\n for (const [cidStr, data] of incoming.blocks.entries()) {\n const cid = CID.parse(cidStr)\n\n received.push({\n wasWanted: this.wm.wantlist.contains(cid),\n cid,\n data\n })\n }\n\n // quickly send out cancels, reduces chances of duplicate block receives\n this.wm.cancelWants(\n received\n .filter(({ wasWanted }) => wasWanted)\n .map(({ cid }) => cid)\n )\n\n await Promise.all(\n received.map(\n ({ cid, wasWanted, data }) => this._handleReceivedBlock(peerId, cid, data, wasWanted)\n )\n )\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @param {CID} cid\n * @param {Uint8Array} data\n * @param {boolean} wasWanted\n */\n async _handleReceivedBlock (peerId, cid, data, wasWanted) {\n this._log('received block')\n\n const has = await this.blockstore.has(cid)\n\n this._updateReceiveCounters(peerId.toString(), cid, data, has)\n\n if (!wasWanted) {\n return\n }\n\n await this.put(cid, data)\n }\n\n /**\n * @private\n * @param {string} peerIdStr\n * @param {CID} cid\n * @param {Uint8Array} data\n * @param {boolean} exists\n */\n _updateReceiveCounters (peerIdStr, cid, data, exists) {\n this._stats.push(peerIdStr, 'blocksReceived', 1)\n this._stats.push(peerIdStr, 'dataReceived', data.length)\n\n if (exists) {\n this._stats.push(peerIdStr, 'dupBlksReceived', 1)\n this._stats.push(peerIdStr, 'dupDataReceived', data.length)\n }\n }\n\n /**\n * handle errors on the receiving channel\n *\n * @param {Error} err\n */\n _receiveError (err) {\n this._log.error('ReceiveError: %s', err.message)\n }\n\n /**\n * handle new peers\n *\n * @param {PeerId} peerId\n */\n _onPeerConnected (peerId) {\n this.wm.connected(peerId)\n }\n\n /**\n * handle peers being disconnected\n *\n * @param {PeerId} peerId\n */\n _onPeerDisconnected (peerId) {\n this.wm.disconnected(peerId)\n this.engine.peerDisconnected(peerId)\n this._stats.disconnected(peerId)\n }\n\n enableStats () {\n this._stats.enable()\n }\n\n disableStats () {\n this._stats.disable()\n }\n\n /**\n * Return the current wantlist for a given `peerId`\n *\n * @param {PeerId} peerId\n * @param {any} [_options]\n */\n wantlistForPeer (peerId, _options) {\n return this.engine.wantlistForPeer(peerId)\n }\n\n /**\n * Return ledger information for a given `peerId`\n *\n * @param {PeerId} peerId\n */\n ledgerForPeer (peerId) {\n return this.engine.ledgerForPeer(peerId)\n }\n\n /**\n * Fetch a given block by cid. If the block is in the local\n * blockstore it is returned, otherwise the block is added to the wantlist and returned once another node sends it to us.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async get (cid, options = {}) {\n /**\n * @param {CID} cid\n * @param {object} options\n * @param {AbortSignal} options.signal\n */\n const fetchFromNetwork = (cid, options) => {\n // add it to the want list - n.b. later we will abort the AbortSignal\n // so no need to remove the blocks from the wantlist after we have it\n this.wm.wantBlocks([cid], options)\n\n return this.notifications.wantBlock(cid, options)\n }\n\n let promptedNetwork = false\n\n /**\n *\n * @param {CID} cid\n * @param {object} options\n * @param {AbortSignal} options.signal\n */\n const loadOrFetchFromNetwork = async (cid, options) => {\n try {\n // have to await here as we want to handle ERR_NOT_FOUND\n const block = await this.blockstore.get(cid, options)\n\n return block\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n\n if (!promptedNetwork) {\n promptedNetwork = true\n\n this.network.findAndConnect(cid, options)\n .catch((err) => this._log.error(err))\n }\n\n // we don't have the block locally so fetch it from the network\n return fetchFromNetwork(cid, options)\n }\n }\n\n // depending on implementation it's possible for blocks to come in while\n // we do the async operations to get them from the blockstore leading to\n // a race condition, so register for incoming block notifications as well\n // as trying to get it from the datastore\n const controller = new AbortController()\n const signal = options.signal\n ? anySignal([options.signal, controller.signal])\n : controller.signal\n\n try {\n const block = await Promise.race([\n this.notifications.wantBlock(cid, {\n signal\n }),\n loadOrFetchFromNetwork(cid, {\n signal\n })\n ])\n\n return block\n } finally {\n // since we have the block we can now remove our listener\n controller.abort()\n }\n }\n\n /**\n * Fetch a a list of blocks by cid. If the blocks are in the local\n * blockstore they are returned, otherwise the blocks are added to the wantlist and returned once another node sends them to us.\n *\n * @param {AsyncIterable|Iterable} cids\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async * getMany (cids, options = {}) {\n for await (const cid of cids) {\n yield this.get(cid, options)\n }\n }\n\n /**\n * Removes the given CIDs from the wantlist independent of any ref counts.\n *\n * This will cause all outstanding promises for a given block to reject.\n *\n * If you want to cancel the want for a block without doing that, pass an\n * AbortSignal in to `.get` or `.getMany` and abort it.\n *\n * @param {CID[]|CID} cids\n */\n unwant (cids) {\n const cidsArray = Array.isArray(cids) ? cids : [cids]\n\n this.wm.unwantBlocks(cidsArray)\n cidsArray.forEach((cid) => this.notifications.unwantBlock(cid))\n }\n\n /**\n * Removes the given keys from the want list. This may cause pending promises\n * for blocks to never resolve. If you wish these promises to abort instead\n * call `unwant(cids)` instead.\n *\n * @param {CID[]|CID} cids\n */\n cancelWants (cids) {\n this.wm.cancelWants(Array.isArray(cids) ? cids : [cids])\n }\n\n /**\n * Put the given block to the underlying blockstore and\n * send it to nodes that have it in their wantlist.\n *\n * @param {CID} cid\n * @param {Uint8Array} block\n * @param {any} [_options]\n */\n async put (cid, block, _options) {\n await this.blockstore.put(cid, block)\n this._sendHaveBlockNotifications(cid, block)\n }\n\n /**\n * Put the given blocks to the underlying blockstore and\n * send it to nodes that have it them their wantlist.\n *\n * @param {Iterable | AsyncIterable} source\n * @param {Options} [options]\n */\n async * putMany (source, options) {\n for await (const { key, value } of this.blockstore.putMany(source, options)) {\n this._sendHaveBlockNotifications(key, value)\n\n yield { key, value }\n }\n }\n\n /**\n * Sends notifications about the arrival of a block\n *\n * @private\n * @param {CID} cid\n * @param {Uint8Array} data\n */\n _sendHaveBlockNotifications (cid, data) {\n this.notifications.hasBlock(cid, data)\n this.engine.receivedBlocks([{ cid, data }])\n // Note: Don't wait for provide to finish before returning\n this.network.provide(cid).catch((err) => {\n this._log.error('Failed to provide: %s', err.message)\n })\n }\n\n /**\n * Get the current list of wants\n */\n getWantlist () {\n return this.wm.wantlist.entries()\n }\n\n /**\n * Get the current list of partners\n */\n peers () {\n return this.engine.peers()\n }\n\n /**\n * Get stats about the bitswap node\n */\n stat () {\n return this._stats\n }\n\n /**\n * Start the bitswap node\n */\n async start () {\n this.wm.start()\n await this.network.start()\n this.engine.start()\n this.started = true\n }\n\n /**\n * Stop the bitswap node\n */\n async stop () {\n this._stats.stop()\n this.wm.stop()\n await this.network.stop()\n this.engine.stop()\n this.started = false\n }\n\n unwrap () {\n return this.blockstore\n }\n\n /**\n * @param {CID} cid\n * @returns {Promise}\n */\n has (cid) {\n return this.blockstore.has(cid)\n }\n}\n", "import { Bitswap } from './bitswap.js'\n\n/**\n * @typedef {import('./types').IPFSBitswap} IPFSBitswap\n * @typedef {import('./types').MultihashHasherLoader} MultihashHasherLoader\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('./message')} BitswapMessage\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Options} Options\n */\n\n/**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {Blockstore} blockstore\n * @param {object} [options]\n * @param {boolean} [options.statsEnabled=false]\n * @param {number} [options.statsComputeThrottleTimeout=1000]\n * @param {number} [options.statsComputeThrottleMaxQueueSize=1000]\n * @param {number} [options.maxInboundStreams=32]\n * @param {number} [options.maxOutboundStreams=128]\n * @param {number} [options.incomingStreamTimeout=30000]\n * @param {MultihashHasherLoader} [options.hashLoader]\n * @returns {IPFSBitswap}\n */\nexport const createBitswap = (libp2p, blockstore, options = {}) => {\n return new Bitswap(libp2p, blockstore, options)\n}\n", "import { createBitswap } from 'ipfs-bitswap'\nimport { createLibp2p } from './libp2p.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { BlockStorage } from '../block-storage.js'\n\n/**\n * @typedef {object} Online\n * @property {libp2p} libp2p\n * @property {Bitswap} bitswap\n *\n * @typedef {object} Options\n * @property {PeerId} options.peerId\n * @property {Repo} options.repo\n * @property {Print} options.print\n * @property {IPFSOptions} options.options\n * @property {import('ipfs-core-utils/multihashes').Multihashes} options.hashers\n *\n * @typedef {import('ipfs-core-types/src/config').Config} IPFSConfig\n * @typedef {import('../types').Options} IPFSOptions\n * @typedef {import('ipfs-repo').IPFSRepo} Repo\n * @typedef {import('../types').Print} Print\n * @typedef {import('libp2p').Libp2p} libp2p\n * @typedef {import('ipfs-bitswap').IPFSBitswap} Bitswap\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\nexport class Network {\n /**\n * @param {PeerId} peerId\n * @param {libp2p} libp2p\n * @param {Bitswap} bitswap\n * @param {Repo} repo\n * @param {BlockStorage} blockstore\n */\n constructor (peerId, libp2p, bitswap, repo, blockstore) {\n this.peerId = peerId\n this.libp2p = libp2p\n this.bitswap = bitswap\n this.repo = repo\n this.blockstore = blockstore\n }\n\n /**\n * @param {Options} options\n */\n static async start ({ peerId, repo, print, hashers, options }) {\n // Need to ensure that repo is open as it could have been closed between\n // `init` and `start`.\n if (repo.closed) {\n await repo.open()\n }\n\n /** @type {IPFSConfig} */\n const config = await repo.config.getAll()\n\n const libp2p = await createLibp2p({\n options,\n repo,\n peerId,\n multiaddrs: readAddrs(peerId, config),\n config,\n keychainConfig: undefined\n })\n\n await libp2p.start()\n\n for (const ma of libp2p.getMultiaddrs()) {\n print(`Swarm listening on ${ma.toString()}`)\n }\n\n const bitswap = createBitswap(libp2p, repo.blocks, {\n statsEnabled: true,\n hashLoader: hashers,\n maxInboundStreams: 1024,\n maxOutboundStreams: 1024\n })\n await bitswap.start()\n\n const blockstore = new BlockStorage(repo.blocks, bitswap)\n repo.blocks = blockstore\n // @ts-expect-error private field\n repo.pins.blockstore = blockstore\n\n return new Network(peerId, libp2p, bitswap, repo, blockstore)\n }\n\n /**\n * @param {Network} network\n */\n static async stop (network) {\n network.repo.blocks = network.blockstore.unwrap()\n // @ts-expect-error private field\n network.repo.pins.blockstore = network.blockstore.unwrap()\n\n await network.bitswap.stop()\n await network.libp2p.stop()\n }\n}\n\n/**\n * @param {PeerId} peerId\n * @param {IPFSConfig} config\n */\nconst readAddrs = (peerId, config) => {\n const peerIdStr = peerId.toString()\n /** @type {Multiaddr[]} */\n const addrs = []\n const swarm = (config.Addresses && config.Addresses.Swarm) || []\n for (const addr of swarm) {\n let ma = multiaddr(addr)\n\n // Temporary error for users migrating using websocket-star multiaddrs for listenning on libp2p\n // websocket-star support was removed from ipfs and libp2p\n if (ma.protoCodes().includes(WEBSOCKET_STAR_PROTO_CODE)) {\n throw errCode(new Error('websocket-star swarm addresses are not supported. See https://github.com/ipfs/js-ipfs/issues/2779'), 'ERR_WEBSOCKET_STAR_SWARM_ADDR_NOT_SUPPORTED')\n }\n\n // multiaddrs that go via a signalling server or other intermediary (e.g. stardust,\n // webrtc-star) can have the intermediary's peer ID in the address, so append our\n // peer ID to the end of it\n const maId = ma.getPeerId()\n if (maId && maId !== peerIdStr) {\n ma = ma.encapsulate(`/p2p/${peerIdStr}`)\n }\n\n addrs.push(ma)\n }\n\n return addrs\n}\n\nconst WEBSOCKET_STAR_PROTO_CODE = 479\n", "import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n", "import * as ErrorsImport from './errors.js'\n\nexport { BaseBlockstore } from './base.js'\nexport { MemoryBlockstore } from './memory.js'\n\nexport const Errors = {\n ...ErrorsImport\n}\n", "import { BaseBlockstore } from 'blockstore-core'\nimport merge from 'it-merge'\nimport { pushable } from 'it-pushable'\nimport filter from 'it-filter'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Query} Query\n * @typedef {import('interface-blockstore').KeyQuery} KeyQuery\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-bitswap').IPFSBitswap} Bitswap\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('ipfs-core-types/src/block').RmOptions} RmOptions\n */\n\n/**\n * BlockStorage is a hybrid block datastore. It stores data in a local\n * datastore and may retrieve data from a remote Exchange.\n * It uses an internal `datastore.Datastore` instance to store values.\n *\n * @implements {Blockstore}\n */\nexport class BlockStorage extends BaseBlockstore {\n /**\n * Create a new BlockStorage\n *\n * @param {Blockstore} blockstore\n * @param {Bitswap} bitswap\n */\n constructor (blockstore, bitswap) {\n super()\n\n this.child = blockstore\n this.bitswap = bitswap\n }\n\n open () {\n return this.child.open()\n }\n\n close () {\n return this.child.close()\n }\n\n unwrap () {\n return this.child\n }\n\n /**\n * Put a block to the underlying datastore\n *\n * @param {CID} cid\n * @param {Uint8Array} block\n * @param {AbortOptions} [options]\n */\n async put (cid, block, options = {}) {\n if (await this.has(cid)) {\n return\n }\n\n if (this.bitswap.isStarted()) {\n await this.bitswap.put(cid, block, options)\n } else {\n await this.child.put(cid, block, options)\n }\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n *\n * @param {AsyncIterable<{ key: CID, value: Uint8Array }> | Iterable<{ key: CID, value: Uint8Array }>} blocks\n * @param {AbortOptions} [options]\n */\n async * putMany (blocks, options = {}) {\n const missingBlocks = filter(blocks, async ({ key }) => { return !(await this.has(key)) })\n\n if (this.bitswap.isStarted()) {\n yield * this.bitswap.putMany(missingBlocks, options)\n } else {\n yield * this.child.putMany(missingBlocks, options)\n }\n }\n\n /**\n * Get a block by cid\n *\n * @param {CID} cid\n * @param {AbortOptions} [options]\n */\n async get (cid, options = {}) {\n if (!(await this.has(cid)) && this.bitswap.isStarted()) {\n return this.bitswap.get(cid, options)\n } else {\n return this.child.get(cid, options)\n }\n }\n\n /**\n * Get multiple blocks back from an array of cids\n *\n * @param {AsyncIterable | Iterable} cids\n * @param {AbortOptions} [options]\n */\n async * getMany (cids, options = {}) {\n const getFromBitswap = pushable({ objectMode: true })\n const getFromChild = pushable({ objectMode: true })\n\n Promise.resolve().then(async () => {\n for await (const cid of cids) {\n if (!(await this.has(cid)) && this.bitswap.isStarted()) {\n getFromBitswap.push(cid)\n } else {\n getFromChild.push(cid)\n }\n }\n\n getFromBitswap.end()\n getFromChild.end()\n })\n\n yield * merge(\n this.bitswap.getMany(getFromBitswap, options),\n this.child.getMany(getFromChild, options)\n )\n }\n\n /**\n * Delete a block from the blockstore\n *\n * @param {CID} cid\n * @param {RmOptions} [options]\n */\n async delete (cid, options) {\n await this.child.delete(cid, options)\n }\n\n /**\n * Delete multiple blocks from the blockstore\n *\n * @param {AsyncIterable | Iterable} cids\n * @param {RmOptions} [options]\n */\n async * deleteMany (cids, options) {\n yield * this.child.deleteMany(cids, options)\n }\n\n /**\n * @param {CID} cid\n * @param {AbortOptions} options\n */\n async has (cid, options = {}) {\n return this.child.has(cid, options)\n }\n\n /**\n * @param {Query} q\n * @param {AbortOptions} options\n */\n async * query (q, options = {}) {\n yield * this.child.query(q, options)\n }\n\n /**\n * @param {KeyQuery} q\n * @param {AbortOptions} options\n */\n async * queryKeys (q, options = {}) {\n yield * this.child.queryKeys(q, options)\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('ipfs-core-types/src/swarm').AddrsResult} AddrsResult\n */\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createAddrs ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"addrs\"]}\n */\n async function addrs (options = {}) { // eslint-disable-line require-await\n /** @type {AddrsResult[]} */\n const peers = []\n const { libp2p } = await network.use(options)\n\n await libp2p.peerStore.forEach(peer => {\n peers.push({\n id: peer.id,\n addrs: peer.addresses.map((mi) => mi.multiaddr)\n })\n })\n\n return peers\n }\n\n return withTimeoutOption(addrs)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createConnect ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"connect\"]}\n */\n async function connect (multiaddrOrPeerId, options = {}) {\n const { libp2p } = await network.use(options)\n await libp2p.dial(multiaddrOrPeerId, options)\n }\n\n return withTimeoutOption(connect)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createDisconnect ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"disconnect\"]}\n */\n async function disconnect (addr, options = {}) {\n const { libp2p } = await network.use(options)\n await libp2p.hangUp(addr)\n }\n\n return withTimeoutOption(disconnect)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createLocalAddrs ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"localAddrs\"]}\n */\n async function localAddrs (options = {}) {\n const { libp2p } = await network.use(options)\n return libp2p.getMultiaddrs()\n }\n\n return withTimeoutOption(localAddrs)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('ipfs-core-types/src/swarm').PeersResult} PeersResult\n */\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createPeers ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"peers\"]}\n */\n async function peers (options = {}) {\n const { libp2p } = await network.use(options)\n\n if (options.verbose) {\n const peers = []\n for (const connection of libp2p.getConnections()) {\n /** @type {PeersResult} */\n const peer = {\n addr: connection.remoteAddr,\n peer: connection.remotePeer\n }\n\n if (options.verbose || options.direction) {\n peer.direction = connection.stat.direction\n }\n\n if (options.verbose) {\n peer.muxer = connection.stat.multiplexer\n peer.latency = 'n/a'\n peer.streams = [] // TODO: get this from libp2p\n }\n\n peers.push(peer)\n }\n\n return peers\n }\n\n /** @type {Map} */\n const peers = new Map()\n\n for (const connection of libp2p.getConnections()) {\n /** @type {import('ipfs-core-types/src/swarm').PeersResult} */\n const peer = {\n addr: connection.remoteAddr,\n peer: connection.remotePeer\n }\n\n peers.set(connection.remotePeer.toString(), peer)\n }\n\n return Array.from(peers.values())\n }\n\n return withTimeoutOption(peers)\n}\n", "import { createAddrs } from './addrs.js'\nimport { createConnect } from './connect.js'\nimport { createDisconnect } from './disconnect.js'\nimport { createLocalAddrs } from './local-addrs.js'\nimport { createPeers } from './peers.js'\n\nexport class SwarmAPI {\n /**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\n constructor ({ network }) {\n this.addrs = createAddrs({ network })\n this.connect = createConnect({ network })\n this.disconnect = createDisconnect({ network })\n this.localAddrs = createLocalAddrs({ network })\n this.peers = createPeers({ network })\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {Pong|PingFailure|StatusUpdate} Packet\n * Note that not all ping response objects are \"pongs\".\n * A \"pong\" message can be identified by a truthy success property and an empty\n * text property. Other ping responses are failures or status updates.\n *\n * @typedef {object} Pong\n * @property {true} success\n * @property {number} time\n * @property {''} text\n *\n * @typedef {object} PingFailure\n * @property {false} success\n * @property {number} time\n * @property {string} text\n *\n * @typedef {object} StatusUpdate\n * @property {true} success\n * @property {0} time\n * @property {string} text\n *\n * @typedef {PingSettings & AbortOptions} PingOptions\n *\n * @typedef {object} PingSettings\n * @property {number} [count=10] - The number of ping messages to send\n *\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/** @type {{success:true, time:0, text: ''}} */\nconst basePacket = { success: true, time: 0, text: '' }\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n */\nexport function createPing ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"ping\"]}\n */\n async function * ping (peerId, options = {}) {\n const { libp2p } = await network.use()\n options.count = options.count || 10\n\n const storedPeer = await libp2p.peerStore.get(peerId)\n let id = storedPeer && storedPeer.id\n\n if (!id) {\n yield { ...basePacket, text: `Looking up peer ${peerId}` }\n const remotePeer = await libp2p.peerRouting.findPeer(peerId)\n\n id = remotePeer && remotePeer.id\n }\n\n if (!id) {\n throw new Error('Peer was not found')\n }\n\n yield { ...basePacket, text: `PING ${id.toString()}` }\n\n let packetCount = 0\n let totalTime = 0\n\n for (let i = 0; i < options.count; i++) {\n try {\n const time = await libp2p.ping(id)\n totalTime += time\n packetCount++\n yield { ...basePacket, time }\n } catch (/** @type {any} */ err) {\n yield { ...basePacket, success: false, text: err.toString() }\n }\n }\n\n if (packetCount) {\n const average = totalTime / packetCount\n yield { ...basePacket, text: `Average latency: ${average}ms` }\n }\n }\n\n return withTimeoutOption(ping)\n}\n", "import errCode from 'err-code'\nimport { NotEnabledError } from '../errors.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base36 } from 'multiformats/bases/base36'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('@libp2p/interface-dht').QueryEvent} QueryEvent\n * @typedef {import('./network').Network} Network\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\nconst IPNS_PREFIX = '/ipns/'\n\n/**\n * @param {string} str\n */\nfunction toDHTKey (str) {\n if (str.startsWith(IPNS_PREFIX)) {\n str = str.substring(IPNS_PREFIX.length)\n }\n\n /** @type {Uint8Array|undefined} */\n let buf\n\n if (str[0] === '1' || str[0] === 'Q') {\n // ed25519 key or hash of rsa key\n str = `z${str}`\n }\n\n if (str[0] === 'z') {\n buf = base58btc.decode(str)\n }\n\n if (str[0] === 'k') {\n // base36 encoded string\n buf = base36.decode(str)\n }\n\n if (!buf) {\n throw new Error('Could not parse string')\n }\n\n if (buf[0] !== 0x01 && buf[1] !== 0x72) {\n // prefix key with CIDv1 and libp2p-key codec\n buf = uint8ArrayConcat([\n [0x01, 0x72],\n buf\n ])\n }\n\n if (buf.length !== 40) {\n throw new Error('Incorrect length ' + buf.length)\n }\n\n return uint8ArrayConcat([\n uint8ArrayFromString(IPNS_PREFIX),\n buf.subarray(2)\n ])\n}\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {PeerId} config.peerId\n */\nexport function createDht ({ network, repo, peerId }) {\n const { get, put, findProvs, findPeer, provide, query } = {\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"get\"]}\n */\n async * get (key, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n\n const dhtKey = key instanceof Uint8Array ? key : toDHTKey(key)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.get(dhtKey, options)\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"put\"]}\n */\n async * put (key, value, options) {\n const { libp2p } = await use(network, peerId, options)\n\n const dhtKey = key instanceof Uint8Array ? key : toDHTKey(key)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.put(dhtKey, value, options)\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"findProvs\"]}\n */\n async * findProvs (cid, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.findProviders(cid, {\n signal: options.signal\n })\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"findPeer\"]}\n */\n async * findPeer (peerIdToFind, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.findPeer(peerIdToFind, {\n signal: options.signal\n })\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"provide\"]}\n */\n async * provide (cid, options = { recursive: false }) {\n const { libp2p } = await use(network, peerId, options)\n\n // ensure blocks are actually local\n const hasBlock = await repo.blocks.has(cid)\n\n if (!hasBlock) {\n throw errCode(new Error('block(s) not found locally, cannot provide'), 'ERR_BLOCK_NOT_FOUND')\n }\n\n if (options.recursive) {\n // TODO: Implement recursive providing\n throw errCode(new Error('not implemented yet'), 'ERR_NOT_IMPLEMENTED_YET')\n }\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.provide(cid)\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"query\"]}\n */\n async * query (peerIdToQuery, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n let bytes\n const asCid = CID.asCID(peerIdToQuery)\n\n if (asCid != null) {\n bytes = asCid.multihash.bytes\n } else {\n bytes = peerIdFromString(peerIdToQuery.toString()).toBytes()\n }\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.getClosestPeers(bytes, options)\n }\n }\n\n return {\n get: withTimeoutOption(get),\n put: withTimeoutOption(put),\n findProvs: withTimeoutOption(findProvs),\n findPeer: withTimeoutOption(findPeer),\n provide: withTimeoutOption(provide),\n query: withTimeoutOption(query)\n }\n}\n\n/**\n * @param {import('../types').NetworkService} network\n * @param {PeerId} peerId\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n * @returns {Promise}\n */\nconst use = async (network, peerId, options) => {\n const net = await network.use(options)\n if (net.libp2p.dht != null) {\n return net\n } else {\n const fn = async function * () {\n yield {\n from: peerId,\n name: 'QUERY_ERROR',\n type: 3,\n error: new NotEnabledError('dht not enabled')\n }\n }\n\n return {\n libp2p: {\n dht: {\n // @ts-expect-error incomplete implementation\n get: fn,\n // @ts-expect-error incomplete implementation\n put: fn,\n // @ts-expect-error incomplete implementation\n findProviders: fn,\n // @ts-expect-error incomplete implementation\n findPeer: fn,\n // @ts-expect-error incomplete implementation\n provide: fn,\n // @ts-expect-error incomplete implementation\n getClosestPeers: fn\n }\n }\n }\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport errCode from 'err-code'\nimport { NotEnabledError } from '../errors.js'\nimport get from 'dlv'\n\n/**\n * @typedef {import('@libp2p/interface-pubsub').Message} Message\n * @typedef {import('@libp2p/interfaces/events').EventHandler>} EventHandler\n * @typedef {import('@libp2p/interfaces/events').EventHandler} MessageEventHandler\n */\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('ipfs-core-types/src/config').Config} [config.config]\n */\nexport function createPubsub ({ network, config }) {\n const isEnabled = get(config || {}, 'Pubsub.Enabled', true)\n\n /** @type {Record} */\n const handlers = {}\n /** @type {EventHandler | undefined} */\n let onMessage\n\n return {\n subscribe: isEnabled ? withTimeoutOption(subscribe) : notEnabled,\n unsubscribe: isEnabled ? withTimeoutOption(unsubscribe) : notEnabled,\n publish: isEnabled ? withTimeoutOption(publish) : notEnabled,\n ls: isEnabled ? withTimeoutOption(ls) : notEnabled,\n peers: isEnabled ? withTimeoutOption(peers) : notEnabled\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"subscribe\"]}\n */\n async function subscribe (topic, handler, options = {}) {\n const { libp2p } = await network.use(options)\n\n libp2p.pubsub.subscribe(topic)\n\n // listen for 'message' events if we aren't already\n if (onMessage == null) {\n onMessage = (evt) => {\n const msg = evt.detail\n\n if (handlers[msg.topic]) {\n handlers[msg.topic].forEach(handler => {\n if (typeof handler === 'function') {\n handler(msg)\n return\n }\n\n if (handler != null && handler.handleEvent != null) {\n handler.handleEvent(msg)\n }\n })\n }\n }\n\n libp2p.pubsub.addEventListener('message', onMessage)\n }\n\n // store handler for future invocation\n if (handler != null) {\n if (handlers[topic] == null) {\n handlers[topic] = []\n }\n\n handlers[topic].push(handler)\n }\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"unsubscribe\"]}\n */\n async function unsubscribe (topic, handler, options = {}) {\n const { libp2p } = await network.use(options)\n\n // remove handler from local map\n if (handler != null && handlers[topic] != null) {\n handlers[topic] = handlers[topic].filter(h => h !== handler)\n\n if (handlers[topic].length === 0) {\n delete handlers[topic]\n }\n }\n\n // remove all handlers\n if (typeof handler !== 'function') {\n delete handlers[topic]\n }\n\n // no more handlers for this topic, unsubscribe\n if (handlers[topic] == null) {\n libp2p.pubsub.unsubscribe(topic)\n }\n\n // no more pubsub handlers, remove message listener\n if (Object.keys(handlers).length === 0) {\n libp2p.pubsub.removeEventListener('message', onMessage)\n onMessage = undefined\n }\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"publish\"]}\n */\n async function publish (topic, data, options = {}) {\n const { libp2p } = await network.use(options)\n if (!data) {\n throw errCode(new Error('argument \"data\" is required'), 'ERR_ARG_REQUIRED')\n }\n\n await libp2p.pubsub.publish(topic, data)\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"ls\"]}\n */\n async function ls (options = {}) {\n const { libp2p } = await network.use(options)\n\n return libp2p.pubsub.getTopics()\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"peers\"]}\n */\n async function peers (topic, options = {}) {\n const { libp2p } = await network.use(options)\n\n return libp2p.pubsub.getSubscribers(topic)\n }\n}\n\nconst notEnabled = async () => { // eslint-disable-line require-await\n throw new NotEnabledError('pubsub not enabled')\n}\n", "import { create as createImport } from './components/index.js'\nimport globSourceImport from 'ipfs-utils/src/files/glob-source.js'\nimport urlSourceImport from 'ipfs-utils/src/files/url-source.js'\n\n/**\n * @typedef {import('ipfs-core-types').IPFS} IPFS\n * @typedef {import('./types').Options} Options\n * @typedef {import('./types').Libp2pFactoryFn} Libp2pFactoryFn\n * @typedef {import('./types').Libp2pFactoryFnArgs} Libp2pFactoryFnArgs\n * @typedef {import('./types').InitOptions} InitOptions\n * @typedef {import('./types').RelayOptions} RelayOptions\n * @typedef {import('./types').PreloadOptions} PreloadOptions\n * @typedef {import('./types').ExperimentalOptions} ExperimentalOptions\n * @typedef {import('./types').Preload} Preload\n * @typedef {import('./types').MfsPreload} MfsPreload\n * @typedef {import('./types').LoadBaseFn} LoadBaseFn\n * @typedef {import('./types').LoadCodecFn} LoadCodecFn\n * @typedef {import('./types').LoadHasherFn} LoadHasherFn\n * @typedef {import('./types').IPLDOptions} IPLDOptions\n */\n\nexport const create = createImport\nexport const globSource = globSourceImport\nexport const urlSource = urlSourceImport\n", "import { CID as CoreCID } from \"multiformats/cid\";\n\nexport const CID = (() => {\n return {\n toString: function (cid: CoreCID): string {\n return cid.toV1().toString();\n },\n fromString: function (cid: string): CoreCID {\n return CoreCID.parse(cid);\n },\n };\n})();\n", "import { create } from \"ipfs-core\";\nimport { CID } from \"../Entities/CID\";\nimport type { IPFS } from \"ipfs-core-types\";\n\nexport const ipfs = (() => {\n let ipfs: IPFS;\n\n return {\n init: async () => {\n if (!ipfs) {\n ipfs = await create({\n repo: String(Math.random() + Date.now()),\n });\n }\n },\n store: async function (filename: string, content): Promise {\n await this.init();\n\n const fileToAdd = {\n path: filename,\n content,\n };\n\n const file = await ipfs.add(fileToAdd);\n const { cid } = file;\n\n return CID.toString(cid);\n },\n retrieve: async function (cid) {\n await this.init();\n const decoder = new TextDecoder();\n let content = \"\";\n\n for await (const chunk of ipfs.cat(cid)) {\n content += decoder.decode(chunk, {\n stream: true,\n });\n }\n return content;\n },\n };\n})();\n", "import {\n saveNote,\n getNote,\n resetNoteManager,\n getNotes,\n deleteNote,\n} from \"../noteManager/noteManager\";\nimport select from \"../../../utils/dom\";\nimport storage from \"../../../utils/localstorage\";\nimport { isUserLoggedIn } from \"../../../utils/isUserLoggedIn\";\nimport {\n goAuthenticate,\n setGistToSyncWith,\n syncNotesWithGitHub,\n} from \"../../../utils/github/actions\";\nimport commander from \"./commander\";\nimport {\n saveFileAs,\n saveDataToFile,\n} from \"../../../utils/fileSystem/fileSystem\";\nimport { url } from \"../../../utils/urlManager\";\nimport { mailTo } from \"../../../utils/mail\";\nimport markDownViewer from \"../markdown/markDownViewer\";\nimport prettifyJSON from \"../../../utils/prettifyJSON\";\nimport notify from \"../../molecules/notify\";\nimport { copyToClipboard } from \"../../../utils/copyToClipboard\";\nimport { sleep } from \"../../../utils/sleep\";\nimport { updateGist, publishGist } from \"../../../utils/github/api\";\nimport { icon } from \"../../atoms/icon/icon\";\nimport ListSVG from \"../../../../assets/svg/list.svg\";\nimport TrashSVG from \"../../../../assets/svg/trash.svg\";\nimport CheckmarkCircleSVG from \"../../../../assets/svg/checkmark-circle.svg\";\nimport CloudSyncSVG from \"../../../../assets/svg/cloud-sync.svg\";\nimport LighterSVG from \"../../../../assets/svg/lighter.svg\";\nimport EnterDownSVG from \"../../../../assets/svg/enter-down.svg\";\nimport DownloadSVG from \"../../../../assets/svg/download.svg\";\nimport EnvelopeSVG from \"../../../../assets/svg/envelope.svg\";\nimport BugSVG from \"../../../../assets/svg/bug.svg\";\nimport PictureSVG from \"../../../../assets/svg/picture.svg\";\nimport PrinterSVG from \"../../../../assets/svg/printer.svg\";\nimport PageBreakSVG from \"../../../../assets/svg/page-break.svg\";\nimport FrameExpandSVG from \"../../../../assets/svg/frame-expand.svg\";\nimport ArrowRightCircleSVG from \"../../../../assets/svg/arrow-right-circle.svg\";\nimport MagicWandSVG from \"../../../../assets/svg/magic-wand.svg\";\nimport RocketSVG from \"../../../../assets/svg/rocket.svg\";\nimport EarthSVG from \"../../../../assets/svg/earth.svg\";\nimport SpellCheckSVG from \"../../../../assets/svg/spell-check.svg\";\nimport PencilSVG from \"../../../../assets/svg/pencil.svg\";\nimport ShareSVG from \"../../../../assets/svg/exit-up.svg\";\nimport LeafSVG from \"../../../../assets/svg/leaf.svg\";\nimport { share } from \"../../../utils/webShare\";\nimport { ipfs } from \"../../../repositories/ipfs\";\nimport { setSavedState } from \"../../../ui/functions/savedState\";\n\nconst getSyncTitle = () => {\n const gistId = storage.get(\"gistId\");\n const authToken = storage.get(\"authToken\");\n if (!authToken) {\n return \"Sync: Authorize your GitHub account for synchronisation\";\n }\n if (!gistId) {\n return \"Sync: Pick your Gist to sync with\";\n }\n return \"Sync: Notes with my GitHub Gist\";\n};\n\nconst shareNoteCommand = {\n title: \"Share note\",\n icon: icon(ShareSVG, \"share note\"),\n sortTitle: \"Share\",\n call: share,\n};\n\nconst sharePublicLinkCommand = {\n title: \"Share public link\",\n key: null,\n icon: icon(ShareSVG, \"share public link\"),\n sortTitle: \"Share public link\",\n call: async () => {\n commander.hide();\n await saveNote(select(\".terminal\").getValue());\n const note = getNote();\n const response = await publishGist({\n note,\n });\n const rawLink = response.history[0].url;\n const gitResponse = await fetch(rawLink).then((response) =>\n response.json()\n );\n const { files } = gitResponse;\n const fileContents = Object.values(files);\n const [gistFile] = fileContents;\n const { raw_url: rawUrl } = gistFile;\n const linkToShare = `${url.baseUrl}?raw=${rawUrl}`;\n const successMessage = \"MiroPad public link copied to clipboard \uD83D\uDCCB!\";\n copyToClipboard(linkToShare, successMessage);\n },\n};\n\nexport const commands = () => {\n return [\n {\n title: \"New note\",\n icon: icon(PencilSVG, \"new note\"),\n sortTitle: \"New\",\n key: \"n\",\n call: resetNoteManager,\n },\n {\n title: \"Save\",\n key: \"s\",\n icon: icon(CheckmarkCircleSVG, \"save\"),\n sortTitle: \"Save\",\n call: async () => {\n commander.hide();\n await saveNote(select(\".terminal\").getValue());\n const note = getNote();\n const { disableSync = false } = note;\n if (!disableSync) {\n updateGist([note]);\n }\n setSavedState();\n },\n },\n ...(navigator.share ? [shareNoteCommand] : []),\n {\n title: \"Toggle MarkDown Viewer\",\n icon: icon(PageBreakSVG, \"toggle markdown viewer\", \"rotate90\"),\n sortTitle: \"Split\",\n key: \"m\",\n call: () => {\n markDownViewer.toggle();\n commander.hide();\n },\n },\n {\n title: \"Full MarkDown view\",\n icon: icon(FrameExpandSVG, \"full view\"),\n sortTitle: \"Full view\",\n key: \"shift m\",\n call: () => {\n markDownViewer.toggle(\"full\");\n commander.hide();\n },\n },\n {\n title: \"Save to IPFS\",\n key: \"i\",\n icon: icon(EarthSVG, \"save\"),\n sortTitle: \"save->ipfs\",\n call: async () => {\n commander.hide();\n await saveNote(select(\".terminal\").getValue());\n const note = getNote();\n const { disableSync = false } = note;\n if (!disableSync) {\n updateGist([note]);\n }\n\n if (note) {\n const cid = await ipfs.store(note.title, note.text);\n copyToClipboard(`${url.baseUrl}#?cid=${cid}`);\n }\n },\n },\n ...(isUserLoggedIn() ? [sharePublicLinkCommand] : []),\n {\n title: \"Zen mode\",\n icon: icon(LeafSVG, \"zen mode\"),\n sortTitle: \"Zen mode\",\n key: \"shift z\",\n call: () => {\n const isZen = Boolean(url.getSearchParam(\"zen\"));\n if (isZen) {\n url.deleteParam(\"zen\");\n } else {\n url.set(undefined, {\n zen: true,\n });\n }\n commander.hide();\n },\n },\n {\n title: \"List saved notes\",\n icon: icon(ListSVG, \"list notes\"),\n sortTitle: \"Notes\",\n key: \"p\",\n call: () => commander.toggle(commander.getModes().notes),\n },\n {\n title: \"Delete note\",\n key: \"shift d\",\n icon: icon(TrashSVG, \"delete note\"),\n sortTitle: \"Delete\",\n call: deleteNote,\n },\n {\n title: getSyncTitle(),\n icon: icon(CloudSyncSVG, \"sync with github\"),\n key: null,\n call: async () => {\n const token = storage.get(\"authToken\");\n if (!token) {\n return await goAuthenticate();\n }\n const gistId = storage.get(\"gistId\");\n if (!gistId) {\n return await setGistToSyncWith(token);\n }\n commander.hide();\n await syncNotesWithGitHub();\n },\n },\n {\n title: \"Sync: Reset Gist settings\",\n icon: icon(LighterSVG, \"reset github settings\"),\n key: null,\n call: async () => {\n localStorage.removeItem(\"authToken\");\n localStorage.removeItem(\"gistId\");\n localStorage.removeItem(\"lastLocalUpdate\");\n localStorage.removeItem(\"lastSync\");\n notify.info(\"Gist setting have been reset!\");\n commander.hide();\n },\n },\n {\n title: \"Toggle sidebar\",\n experimental: true,\n key: \"shift l\",\n call: () => {\n select(\"aside\").toggle();\n },\n },\n {\n title: \"Save to File System...\",\n experimental: true,\n icon: icon(EnterDownSVG, \"save file\"),\n key: \"shift s\",\n call: async () => {\n const { text, title } = getNote();\n\n saveFileAs(text, title);\n commander.hide();\n },\n },\n {\n title: \"Email note to...\",\n experimental: true,\n icon: icon(EnvelopeSVG, \"email\"),\n key: \"e\",\n call: () => {\n const note = document.querySelector(\".terminal\").value;\n mailTo(note);\n commander.hide();\n },\n },\n {\n title: \"Toggle experimental features\",\n experimental: false,\n icon: icon(BugSVG, \"lab\"),\n key: null,\n call: () => {\n const previousStatus = Boolean(storage.get(\"__experimental__\"));\n\n if (previousStatus) {\n storage.remove(\"__experimental__\");\n } else {\n storage.set(\"__experimental__\", true);\n }\n notify.showNotification(\n `Experimental features turned ${previousStatus ? \"off\" : \"on\"}`\n );\n commander.hide();\n },\n },\n {\n title: \"Toggle Autocompletion\",\n experimental: false,\n icon: icon(ArrowRightCircleSVG, \"autocompletion\"),\n key: null,\n call: () => {\n const previousStatus = Boolean(storage.get(\"__autocomplete__\"));\n\n if (previousStatus) {\n storage.remove(\"__autocomplete__\");\n } else {\n storage.set(\"__autocomplete__\", true);\n }\n notify.showNotification(\n `Autocomplete feature turned ${previousStatus ? \"off\" : \"on\"}`\n );\n commander.hide();\n select(\".terminal\").focus();\n },\n },\n {\n title: \"Add a cover picture\",\n experimental: true,\n icon: icon(PictureSVG, \"cover picture\"),\n key: null,\n call: async () => {\n const bgImage = prompt(\"Paste the image URL in here...\");\n commander.hide();\n await sleep(200); // need to wait after prompt for some reason before copy\n copyToClipboard(\n `
    `,\n \"\uD83D\uDC4CCopied! Paste the code on the MiroPad editor\"\n );\n select(\".terminal\").focus();\n notify.info(\n \"Paste the cover picture wherever you prefer on the MirPad editor\"\n );\n },\n },\n {\n title: \"Print MarkDown output\",\n experimental: true,\n icon: icon(PrinterSVG, \"print\"),\n key: null,\n call: () => {\n select(\".preview\").show();\n markDownViewer.init();\n window.print();\n commander.hide();\n },\n },\n {\n key: \"j\",\n title: \"Prettify JSON document\",\n icon: icon(MagicWandSVG, \"prettify json\"),\n call: () => {\n prettifyJSON(\".terminal\");\n commander.hide();\n },\n },\n {\n title: \"Toggle command palette\",\n icon: icon(RocketSVG, \"toggle command palette\"),\n key: [\"shift p\", \"k\"],\n call: () => commander.toggle(commander.getModes().commands),\n },\n {\n title: \"Find and Replace...\",\n experimental: true,\n icon: icon(SpellCheckSVG, \"find and replace\"),\n key: \"shift f\",\n call: () => {\n const selectedValue = select(\".terminal\")\n .getValue()\n .slice(\n select(\".terminal\").el.selectionStart,\n select(\".terminal\").el.selectionEnd\n );\n const valueToFind = prompt(\"What do you wanna find?\", selectedValue);\n if (!valueToFind) {\n return notify.info(\"Value not found\");\n }\n const positionOfFirstChar = select(\".terminal\")\n .getValue()\n .indexOf(valueToFind);\n\n select(\".terminal\").el.setSelectionRange(\n positionOfFirstChar,\n positionOfFirstChar + valueToFind.length\n );\n const replacementValue = prompt(`Replace ${valueToFind} with...`);\n if (replacementValue) {\n select(\".terminal\").el.setRangeText(replacementValue);\n }\n },\n },\n {\n title: \"Download all notes!\",\n icon: icon(DownloadSVG, \"Download all notes on your local file system\"),\n call: () => {\n const notes = getNotes({\n includeDeleted: true,\n });\n saveDataToFile(notes);\n commander.hide();\n },\n },\n {\n title: \"Permanently delete ALL notes \u2757\",\n icon: icon(TrashSVG, \"delete note\"),\n call: () => {\n const confirmation = confirm(\n \"Are you sure you want do delete ALL your notes?\"\n );\n if (confirmation) {\n const notes = getNotes({\n includeDeleted: true,\n });\n notes.forEach((note) => {\n storage.remove(note.id);\n });\n resetNoteManager();\n }\n commander.hide();\n },\n },\n ];\n};\n", "const keyListener = {\n events: [],\n on(key, fn) {\n if (Array.isArray(key)) {\n key.forEach((k) => {\n const finalKey = k.key || k;\n const functionToCall = k.call || fn;\n this.on(finalKey, functionToCall);\n });\n\n return this;\n }\n\n if (key && typeof key === \"string\" && fn && typeof fn === \"function\") {\n this.events = [\n ...this.events,\n {\n key: key.includes(\"shift\") ? key.replace(\"shift\", \"\").trim() : key,\n shift: key.includes(\"shift\"),\n fn() {\n fn();\n },\n },\n ];\n }\n return this;\n },\n listen() {\n document.addEventListener(\"keydown\", (e) => {\n this.handleEvent(e);\n });\n return this;\n },\n handleEvent(e) {\n this.events.map((event) => {\n if (\n event.key === e.key &&\n (e.ctrlKey === true || e.metaKey === true) &&\n e.shiftKey === event.shift\n ) {\n e.preventDefault();\n event.fn();\n }\n return true;\n });\n },\n};\n\nexport default keyListener;\n", "import { isElement } from \"../../../utils/dom\";\nexport const link = (textOrNode, url) => {\n const a = document.createElement(\"a\");\n a.href = url;\n a.appendChild(\n isElement(textOrNode) ? textOrNode : document.createTextNode(textOrNode)\n );\n return a;\n};\n", "const isSameYear = (aDate, bDate = new Date()) => {\n const yearA = new Date(aDate).getFullYear();\n const yearB = new Date(bDate).getFullYear();\n\n return yearA === yearB;\n};\n\nconst isSameMonth = (aDate, bDate = new Date()) => {\n const monthA = new Date(aDate).getMonth();\n const monthB = new Date(bDate).getMonth();\n\n return monthA === monthB;\n};\n\nconst isSameDateOfMonth = (aDate, bDate = new Date()) => {\n const dateA = new Date(aDate).getDate();\n const dateB = new Date(bDate).getDate();\n\n return dateA === dateB;\n};\n\nconst isSameDate = (aDate, bDate = new Date()) => {\n return (\n isSameYear(aDate, bDate) &&\n isSameMonth(aDate, bDate) &&\n isSameDateOfMonth(aDate, bDate)\n );\n};\n\nconst monthNames = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nconst shortMonthNames = monthNames.map((name) => name.slice(0, 3));\n\nconst isYesterday = (date = new Date()) => {\n const theDate = new Date(date);\n const yesterDate = new Date().getDate() - 1;\n return (\n isSameMonth(theDate) &&\n isSameYear(theDate) &&\n theDate.getDate() === yesterDate\n );\n};\n\nexport const relativeDate = (dateCreated) => {\n const date = new Date(dateCreated);\n const month = !isYesterday(dateCreated)\n ? shortMonthNames[date.getMonth()]\n : \"\";\n const year = isSameYear(date) ? \"\" : date.getFullYear();\n const day = isYesterday(date) ? \"Yesterday\" : date.getDate();\n\n return `${isSameDate(date) ? \"\" : `${day} ${month} ${year}`} ${\n isSameDate(date) ? date.toLocaleTimeString() : \"\"\n }`;\n};\n", "export const isArraySorted = (arr) => {\n const someArray = arr.reduce((currentValue, item) => {\n if (currentValue.length === 0) {\n return [item];\n }\n const max = Math.max(...currentValue);\n return [...currentValue, ...(item >= max ? [item] : [])];\n }, []);\n return someArray.length === arr.length;\n};\n", "import { isArraySorted } from \"../../../utils/isArraySorted\";\n\nexport const smartFilter = (phrase, filter) => {\n const wordParts = phrase.split(\" \").map((w) => w.toLowerCase());\n const filterParts = filter.split(\" \").map((f) => f.toLowerCase());\n const indexes = filterParts.map((f) => {\n const foundIndexes = wordParts.map((w, i) => {\n return w.includes(f) ? i : -1;\n });\n const firstIndexFound = foundIndexes.reduce((currentValue, fi) => {\n return fi > -1 ? fi : currentValue;\n }, -1);\n return firstIndexFound;\n });\n\n if (indexes.includes(-1)) {\n return false;\n }\n return isArraySorted(indexes);\n};\n", "import storage from \"./utils/localstorage\";\n\nexport const requestNotificationPermission = async () => {\n if (!storage.get(\"__notification-permission__\")) {\n const permission = await window.Notification.requestPermission();\n storage.set(\"__notification-permission__\", permission);\n }\n};\n\nexport const registerServiceWorker = async () => {\n if (\"serviceWorker\" in navigator) {\n navigator.serviceWorker.register(\n `${window.location.pathname}service-worker.js?v=${VERSION}`\n );\n }\n};\n", "/* eslint-disable indent */\nimport {\n getNote,\n getNotes,\n getDateCreatedFromTitle,\n} from \"../noteManager/noteManager\";\nimport { commands } from \"./commands\";\nimport keyListener from \"../../../utils/keyListener\";\nimport select from \"../../../utils/dom\";\nimport { url } from \"../../../utils/urlManager\";\nimport { command } from \"../../molecules/commands/command\";\nimport { link } from \"../../atoms/link/link\";\nimport { div } from \"../../atoms/div/div\";\nimport { relativeDate } from \"../../../utils/dates\";\nimport { smartFilter } from \"./smartFilter\";\nimport { button } from \"../../atoms/button/button\";\nimport { requestNotificationPermission } from \"../../../registerServiceWorker\";\nimport storage from \"../../../utils/localstorage\";\n\nconst getShortcut = (key) => {\n if (Array.isArray(key)) {\n return key.map((k) => getShortcut(k)).join(\", \");\n }\n\n return key ? `\u2318+${key.toUpperCase()}` : \"\";\n};\n\nconst commander = (() => {\n const commanderModes = {\n off: \"off\",\n notes: \"notes\",\n revisions: \"revisions\",\n commands: \"commands\",\n gists: \"gists\",\n };\n let state = {\n input: \"\",\n mode: commanderModes.off,\n options: {\n selected: 0,\n length: 0,\n },\n };\n return {\n getState: function () {\n return state;\n },\n getModes: function () {\n return commanderModes;\n },\n setState: function (newState) {\n state = {\n ...state,\n ...newState,\n };\n return state;\n },\n show: function (what = commanderModes.commands) {\n select(\"#commander\").show();\n select(\"#commander input\").focus();\n switch (what) {\n case commanderModes.commands:\n this.generateCommands();\n select(\"#commander input\").setValue(\"> \");\n this.setState({\n mode: commanderModes.commands,\n });\n break;\n case commanderModes.notes:\n this.generateNotes();\n select(\"#commander input\").setValue(\"\");\n this.setState({\n mode: commanderModes.notes,\n });\n break;\n case commanderModes.revisions:\n this.generateRevisions();\n select(\"#commander input\").setValue(\"\");\n this.setState({\n mode: commanderModes.revisions,\n });\n break;\n default:\n // do nothing;\n break;\n }\n return this;\n },\n hide: function () {\n select(\"#commander\").hide();\n state.mode = commanderModes.off;\n return this;\n },\n toggle: function (mode) {\n requestNotificationPermission();\n if (state.mode === commanderModes.off || state.mode !== mode) {\n this.show(mode);\n } else {\n this.hide();\n }\n return this;\n },\n commands: function () {\n return commands();\n },\n selectOption: function (e, direction) {\n const currentlySelected = state.options.selected;\n const lastOption = state.options.length - 1;\n const isLastOption = currentlySelected === lastOption;\n const isFirstOption = currentlySelected === 0;\n const isDown = direction === \"down\";\n\n const indexToSelect = isDown\n ? isLastOption\n ? 0\n : currentlySelected + 1\n : isFirstOption\n ? lastOption\n : currentlySelected - 1;\n\n state.options = {\n ...state.options,\n selected: indexToSelect,\n };\n },\n initCommander: function () {\n // initialize mobile-dock\n commands()\n .slice(0, 5)\n .map((command) => {\n select(\".mobile-dock\").append(\n button(\n [command.icon, document.createTextNode(command.sortTitle)],\n command.call,\n command.title.toLowerCase().replace(/\\s/g, \"-\")\n )\n );\n });\n\n select(\"#commander button\").listen(\"click\", () => {\n this.hide();\n });\n\n select(\"#commander input\")\n .listen(\"keydown\", (e) => {\n // arrow down 40\n if (e.keyCode === 40) {\n if (state.mode === commanderModes.revisions) {\n select(\"#commands li.selected\").click();\n }\n this.selectOption(e, \"down\");\n }\n // arrow up 38\n if (e.keyCode === 38) {\n if (state.mode === commanderModes.revisions) {\n select(\"#commands li.selected\").click();\n }\n this.selectOption(e, \"up\");\n }\n })\n .listen(\"keyup\", (e) => {\n // enter\n if (e.keyCode === 13) {\n if (state.mode === commanderModes.commands) {\n select(\"#commands li.selected div\").click();\n } else {\n select(\"#commands li.selected a\").click();\n }\n }\n // escape\n if (e.keyCode === 27) {\n select(\".terminal\").focus();\n }\n if (state.input !== e.target.value) {\n state.options.selected = 0;\n }\n state.input = e.target.value;\n this.generateOptions(e.target.value);\n });\n return this;\n },\n init: function () {\n this.initCommander();\n keyListener.listen().on(this.commands());\n select(\".menu\").listen(\"click\", () => this.toggle());\n select(\"#revisions\").listen(\"click\", () => this.generateRevisions());\n return this;\n },\n generateRevisions: function () {\n this.show();\n state.mode = commanderModes.revisions;\n const { revisions } = getNote();\n const indexToSelect = state.options.selected;\n const revisionsOptions = Object.keys(revisions)\n .sort((a, b) => {\n const { dateCreated: aDateCreated } = revisions[a];\n const { dateCreated: bDateCreated } = revisions[b];\n return bDateCreated - aDateCreated;\n })\n .map((id, i) => ({\n title: div({ content: `...${id.slice(-10)}` }),\n secondary: `${relativeDate(revisions[id].dateCreated)}`,\n onclick: () => {\n url.set(undefined, {\n v: id,\n });\n state.options.selected = i;\n this.generateRevisions();\n },\n }))\n .map((r, i) => command(r, i === indexToSelect));\n\n select(\"#commands\").html(revisionsOptions);\n\n state.options = {\n ...state.options,\n length: revisionsOptions.length,\n };\n return this;\n },\n generateOptions: function (value) {\n switch (state.mode) {\n case commanderModes.commands:\n case commanderModes.notes:\n if (value.slice(0, 1) === \">\") {\n state.mode = commanderModes.commands;\n this.generateCommands(value.slice(1).trim());\n select(\"#commander input\").placeholder(\"Search for commands...\");\n } else {\n state.mode = commanderModes.notes;\n this.generateNotes(value);\n }\n return;\n case commanderModes.revisions:\n return this.generateRevisions();\n case commanderModes.off:\n break;\n default:\n break;\n }\n },\n generateNotes: function (value = \"\") {\n const indexToSelect = state.options.selected;\n const notes = getNotes()\n .filter(({ title }) => {\n return smartFilter(title, value);\n })\n .filter(({ id, deleted }) => !deleted && id !== url.getPageId())\n .sort((a, b) => {\n const aDateCreated = getDateCreatedFromTitle(a.title);\n const bDateCreated = getDateCreatedFromTitle(b.title);\n return bDateCreated - aDateCreated;\n })\n .map(({ id, title, cid }, i) => {\n const dateCreated = getDateCreatedFromTitle(title);\n const linkParams = cid ? `?cid=${cid}` : \"\";\n const href = `${window.location.origin}${window.location.pathname}#${id}${linkParams}`;\n\n const noteLink = link(\n div({ content: title, highlight: value }),\n href\n );\n\n const noteCommand = command(\n {\n title: noteLink,\n secondary: relativeDate(dateCreated),\n onclick: () => {\n this.hide();\n select(\".terminal\").focus();\n },\n },\n i === indexToSelect\n );\n return noteCommand;\n });\n select(\"#commands\").html(notes);\n select(\"#commander input\").placeholder(\n `Search from ${notes.length} saved notes...`\n );\n state.options = {\n ...state.options,\n length: notes.length,\n };\n return this;\n },\n generateCommands: async function (value = \"\") {\n const indexToSelect = state.options.selected;\n const commandComponents = this.commands()\n .filter(({ title }) => smartFilter(title, value))\n .filter(({ experimental = false }) => {\n return storage.get(\"__experimental__\") ? true : !experimental;\n })\n .map(({ title, key, call, icon }, i) => {\n const commandComponent = command(\n {\n title: div({ content: title, highlight: value }),\n icon: icon,\n secondary: getShortcut(key),\n onclick: call,\n },\n i === indexToSelect\n );\n return commandComponent;\n });\n select(\"#commands\").html(commandComponents);\n state.options = {\n ...state.options,\n length: commandComponents.length,\n };\n return this;\n },\n };\n})();\n\nexport default commander;\n", "import { nanoid } from \"nanoid\";\nimport getCaretCoordinates from \"textarea-caret\";\nimport TrashSVG from \"../../../assets/svg/trash.svg\";\nimport { configuration } from \"../../../configuration\";\nimport { trieDictionary } from \"../../main\";\nimport { setSavedState } from \"../../ui/functions/savedState\";\nimport select from \"../../utils/dom\";\nimport storage from \"../../utils/localstorage\";\nimport { handleErrorResponse } from \"../../utils/mail\";\nimport { autoCompleteCheckboxes } from \"../../utils/text/autoCompleteCheckboxes\";\nimport { div } from \"../atoms/div/div\";\nimport { icon } from \"../atoms/icon/icon\";\nimport { command } from \"../molecules/commands/command\";\nimport notify from \"../molecules/notify\";\nimport commander from \"./commander/commander\";\nimport markDownViewer from \"./markdown/markDownViewer\";\nimport { getNote, getTitle } from \"./noteManager/noteManager\";\n\nconst isLastCharacterInTheWord = (text, characterIndex) =>\n text[characterIndex] === undefined || text[characterIndex].trim() === \"\";\n\nconst placeSuggestion = (textEl) => {\n const coords = getCaretCoordinates(textEl, textEl.selectionEnd);\n const { top, left } = coords;\n\n // This does the trick! `main` is getting the same\n // height as the textarea so the suggestion will be placed\n // right!\n // TODO: change that on terminal size change!\n const actualTerminalHeight = select(\".terminal\").el.scrollHeight;\n const main = select(\"main\").el;\n main.style.height = `${actualTerminalHeight}px`;\n\n select(\".suggestion\").el.style.top = `${top}px`;\n select(\".suggestion\").el.style.left = `${left}px`;\n};\n\nconst getCurrentlyTypingWord = (text, cursorIndexPosition) => {\n let word = \"\";\n let currentIndex = cursorIndexPosition - 1;\n do {\n const character = text[currentIndex] || \"\";\n currentIndex = character.trim() === \"\" ? -1 : currentIndex - 1;\n word = character.trim() !== \"\" ? `${character}${word}` : word;\n } while (currentIndex >= 0);\n return word;\n};\n\nconst getPredictions = (word) => {\n const sanitizedWord = word.replace(/[\\r\\n\\t]+/g, \"\").toLowerCase();\n\n return trieDictionary.getMatchingWords(sanitizedWord);\n};\n\nexport const terminal = (() => {\n const initState = {\n matches: [],\n currentWord: null,\n prediction: null,\n options: {\n selected: 0,\n length: 0,\n },\n };\n let state = initState;\n return {\n el: select(\".terminal\"),\n setState: function (newState) {\n state = {\n ...state,\n ...newState,\n };\n return state;\n },\n resetState: function () {\n terminal.setState(initState);\n },\n selectOption: function (e, direction) {\n const currentlySelected = state.options.selected;\n const lastOption = state.options.length - 1;\n const isLastOption = currentlySelected === lastOption;\n const isFirstOption = currentlySelected === 0;\n const isDown = direction === \"down\";\n\n const indexToSelect = isDown\n ? isLastOption\n ? 0\n : currentlySelected + 1\n : // eslint-disable-next-line prettier/prettier\n isFirstOption ? lastOption : currentlySelected - 1;\n\n state.options = {\n ...state.options,\n selected: indexToSelect,\n };\n\n terminal.setState({\n prediction: state.matches[state.options.selected],\n });\n terminal.renderInlineSuggestion();\n terminal.renderOptions();\n },\n acceptCompletion: (word) => {\n const complete = (word, currentWord) => {\n const completion = word.replace(currentWord.toLowerCase(), \"\");\n if (completion) {\n select(\".terminal\").insertAtCaret(`${completion} `);\n } else {\n select(\".terminal\").insertAtCaret(\" \");\n }\n select(\".suggestion\").hide();\n terminal.resetState();\n };\n\n const { prediction, currentWord } = state;\n\n if (word) {\n return complete(word, currentWord);\n }\n\n if (prediction) {\n complete(prediction, currentWord);\n // +1 to the score of the word autocompleted\n trieDictionary.insert(prediction);\n }\n },\n renderInlineSuggestion: () => {\n const { prediction, currentWord } = state;\n\n const inlineSuggestion = div({\n content: `${prediction.slice(currentWord.length)}`,\n });\n inlineSuggestion.setAttribute(\"id\", \"inlineSuggestion\");\n select(\".suggestion\").show().html(inlineSuggestion);\n },\n renderOptions: () => {\n const optionsUl = select(\".suggestion .options\");\n if (optionsUl && optionsUl.el) optionsUl.el.remove();\n\n const selectedIndex = state.options.selected;\n const options = state.matches.map((word, i) =>\n command(\n {\n title: div({ content: word }),\n secondary: icon(TrashSVG, \"delete word\"),\n onSecondaryClick: () => {\n storage.removeFromDictionary(word);\n terminal.setState({\n matches: state.matches.filter((m) => m !== word),\n });\n terminal.renderOptions();\n },\n onclick: () => {\n terminal.acceptCompletion(word);\n },\n },\n i === selectedIndex\n )\n );\n const optionList = document.createElement(\"ul\");\n optionList.classList.add(\"options\");\n optionList.classList.add(\"frost\");\n options.forEach((el) => optionList.append(el));\n\n select(\".suggestion\").el.append(optionList);\n },\n onFocus: () => {\n commander.hide();\n select(\".note-info\").hide();\n },\n onInput: (e) => {\n const isAutocompleteEnabled = !!storage.get(\"__autocomplete__\");\n if (!isAutocompleteEnabled) return;\n\n const cursorIndexPosition = e.target.selectionEnd;\n const fullText = terminal.el.getValue();\n\n const charTyped = fullText[cursorIndexPosition - 1];\n if (e.inputType === \"deleteContentBackward\" || charTyped === \" \") {\n terminal.setState({\n prediction: initState.prediction,\n currentWord: initState.currentWord,\n });\n return select(\".suggestion\").hide();\n }\n\n const shouldDisplaySuggestion =\n e.inputType === \"insertText\" &&\n isLastCharacterInTheWord(fullText, cursorIndexPosition);\n\n if (shouldDisplaySuggestion) {\n placeSuggestion(e.target);\n const word = getCurrentlyTypingWord(fullText, cursorIndexPosition);\n const matches = getPredictions(word);\n\n const [firstMatch] = matches;\n const prediction = firstMatch || \"\";\n\n terminal.setState({\n prediction,\n currentWord: word,\n matches: matches.slice(0, 10),\n options: {\n selected: 0,\n length: matches.length,\n },\n });\n if (state.currentWord.length > 1 && state.prediction) {\n terminal.renderInlineSuggestion();\n terminal.renderOptions();\n } else {\n select(\".suggestion\").hide();\n }\n }\n },\n onArrowDown: (e) => {\n if (state.matches.length > 0) {\n e.preventDefault();\n terminal.selectOption(e, \"down\");\n }\n },\n onArrowUp: (e) => {\n if (state.matches.length > 0) {\n e.preventDefault();\n terminal.selectOption(e, \"up\");\n }\n },\n setValue: () => {\n // terminal.el.value = \"mpampis\";\n },\n onEnter: (e) => {\n if (state.matches.length > 0) {\n e.preventDefault();\n terminal.acceptCompletion();\n }\n\n // auto-magically handle checkboxes\n autoCompleteCheckboxes(e);\n },\n onEscape: () => {\n terminal.resetState();\n select(\".suggestion\").hide();\n },\n onTab: (e) => {\n e.preventDefault();\n terminal.acceptCompletion();\n },\n onKeyDown: (e) => {\n // enter\n if (e.keyCode === 13) {\n terminal.onEnter(e);\n }\n // arrow down\n if (e.keyCode === 40) {\n terminal.onArrowDown(e);\n }\n\n // arrow up\n if (e.keyCode === 38) {\n terminal.onArrowUp(e);\n }\n\n if (e.keyCode === 9) {\n terminal.onTab(e);\n }\n\n if (e.keyCode === 32) {\n terminal.setState({\n prediction: \"\",\n });\n }\n\n // escape\n if (e.keyCode === 27) {\n terminal.onEscape(e);\n }\n },\n onKeyUp: (e) => {\n const currentlySavedNote = getNote();\n const title = getTitle(e.target.value);\n select(\".title h3\").html(title);\n\n const { text = \"\" } = currentlySavedNote || {};\n const isNoteSaved = currentlySavedNote && terminal.el.getValue() === text;\n setSavedState(isNoteSaved);\n },\n onPaste: async () => {\n const clipboardItems = await navigator.clipboard.read();\n for (const clipboardItem of clipboardItems) {\n const imageTypes = clipboardItem.types?.filter((type) =>\n type.startsWith(\"image/\")\n );\n for (const imageType of imageTypes) {\n const blob = await clipboardItem.getType(imageType);\n const token = storage.get(\"MIROPAD_SECRET_TOKEN\");\n if (token) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [image, fileExtension] = imageType.split(\"/\");\n const fileName = `${nanoid()}.${fileExtension}`;\n\n select(\"#logo\").addClass(\"loading\");\n try {\n const { url } = await fetch(\n `${configuration.file_service.api}?fileName=${fileName}`,\n {\n method: \"POST\",\n headers: {\n \"x-secret-token\": token,\n accept: \"application/json\",\n \"content-type\": \"application/octet-stream\",\n },\n body: blob,\n }\n )\n .then(handleErrorResponse)\n .then((response) => response.json());\n select(\".terminal\").insertAtCaret(`![image](${url})`);\n } catch (error) {\n notify.error(`Uploading file failed \uD83D\uDCA5! Error$ ${error.message}`);\n }\n select(\"#logo\").removeClass(\"loading\");\n } else {\n const imageURI = URL.createObjectURL(blob);\n select(\".terminal\").insertAtCaret(`![image](${imageURI})`);\n }\n markDownViewer.update();\n }\n }\n },\n init: function () {\n this.el\n .listen(\"focus\", this.onFocus)\n .listen(\"input\", this.onInput)\n .listen(\"keydown\", this.onKeyDown)\n .listen(\"keyup\", this.onKeyUp)\n .listen(\"paste\", this.onPaste);\n },\n };\n})();\n", "export const findCurrentLine = (text: string, caretIndex: number): string => {\n const lines = text.split(\"\\n\");\n type MyAcc = {\n text: string;\n isFound: boolean;\n };\n const line = lines.reduce(\n (acc: MyAcc, line) => {\n const { isFound } = acc;\n if (isFound) return acc;\n const recon = `${acc.text}${line}\\n`;\n const currentLength = recon.length;\n\n if (caretIndex >= currentLength) {\n return {\n text: recon,\n isFound: false,\n };\n }\n\n return {\n text: line,\n isFound: true,\n };\n },\n {\n text: \"\",\n isFound: false,\n }\n );\n\n return line.text;\n};\n", "import select from \"../dom\";\nimport { findCurrentLine } from \"./index\";\n\nexport const autoCompleteCheckboxes = (e) => {\n const currentLine = findCurrentLine(e.target.value, e.target.selectionEnd);\n\n const completers = {\n \"* [\": \"\\n* [] \",\n \"* \": \"\\n* \",\n \" * [\": \"\\n * [] \",\n \" * \": \"\\n * \",\n };\n\n for (const [startsWith, compleano] of Object.entries(completers)) {\n if (currentLine.startsWith(startsWith)) {\n e.preventDefault();\n select(\".terminal\").insertAtCaret(compleano);\n break;\n }\n }\n};\n", "import storage from \"./utils/localstorage\";\n\nexport const isSyncEnabled = () => {\n const { authToken, gistId } = storage.get([\"authToken\", \"gistId\"]);\n return !!(authToken && gistId);\n};\n", "const groupByFrequency = (entries: []) => {\n return Object.entries(entries).reduce((acc, [word, frequency]) => {\n const cc = acc[frequency] || [];\n return {\n ...acc,\n [frequency]: [word, ...cc],\n };\n }, {});\n};\n\ntype Node = {\n char: string | null;\n children: {\n [key: string]: Node;\n };\n frequency: number;\n hasChildren: () => boolean;\n isWord: () => boolean;\n contains: (char: string) => boolean;\n getWords: (\n char: string,\n dictionary?: {\n [key: string]: string;\n }\n ) => {\n [key: string]: string;\n };\n increaseFrequency: () => void;\n insert: (word: string) => void;\n insertNode: (char: string, isLast?: boolean) => Node;\n};\n\nconst Node = (): Node => ({\n char: null,\n children: {},\n frequency: 0,\n hasChildren: function () {\n return Object.keys(this.children).length > 0;\n },\n isWord: function () {\n return this.frequency > 0;\n },\n contains: function (char: string) {\n return Object.keys(this.children).includes(char);\n },\n getWords: function (prefix, dictionary = {}) {\n const nodeInstance = this as Node;\n if (nodeInstance.isWord()) {\n dictionary = {\n ...dictionary,\n [prefix]: this.frequency,\n };\n }\n\n if (nodeInstance.hasChildren()) {\n for (const node of Object.values(nodeInstance.children)) {\n dictionary = node.getWords(`${prefix}${node.char}`, dictionary);\n }\n }\n\n return dictionary;\n },\n increaseFrequency: function () {\n this.frequency = this.frequency + 1;\n },\n insert: function (word) {\n const [firstChar, ...rest] = word;\n if (firstChar) {\n const isLast = rest.length === 0;\n if (this.contains(firstChar)) {\n const node = this.children[firstChar];\n node.char = firstChar;\n if (isLast) node.increaseFrequency();\n\n return node.insert(rest);\n } else {\n const node = this.insertNode(firstChar, isLast);\n return node.insert(rest);\n }\n }\n },\n insertNode: function (char, isLast = false) {\n const newNode = Node();\n if (isLast) newNode.increaseFrequency();\n newNode.char = char;\n this.children = {\n ...this.children,\n [char]: newNode,\n };\n return newNode;\n },\n});\n\nexport const Trie = () => {\n const rootNode = Node();\n\n return {\n insert: function (word: string | Array = []) {\n const words = Array.isArray(word) ? word : [word];\n words.forEach((word) => rootNode.insert(word));\n return this;\n },\n search: function (prefix = \"\") {\n let node = rootNode;\n prefix.split(\"\").forEach((character) => {\n if (node) node = node.children[character];\n });\n\n return node ? node.getWords(prefix) : {};\n },\n // get sorted matching words\n // first by frequency\n // and then alphabetically\n getMatchingWords: function (prefix = \"\") {\n const frequencyGroups = groupByFrequency(this.search(prefix));\n return Object.keys(frequencyGroups)\n .sort((a, b) => parseInt(b, 10) - parseInt(a, 10))\n .flatMap((key) => frequencyGroups[key].sort());\n },\n };\n};\n", "import notify from \"../components/molecules/notify\";\n\nconst errorHandler = (error) => {\n const { message = \"Unexpected error occurred!\" } = error;\n notify.error(message);\n};\n\nexport default errorHandler;\n", "import select from \"../utils/dom\";\nimport { ipfs } from \"../repositories/ipfs\";\nimport { setSavedState } from \"../ui/functions/savedState\";\n\nexport const retrieveNoteFromIPFS = async (cid: string) => {\n select(\".anchor\").show();\n\n select(\"#logo\").addClass(\"loading\");\n const remoteNote = await ipfs.retrieve(cid);\n select(\"#logo\").removeClass(\"loading\");\n\n setSavedState(false);\n select(\".terminal\").setValue(remoteNote);\n};\n", "import \"github-markdown-css\";\nimport \"../../css/print.css\";\nimport \"../../css/styles.css\";\nimport { retrieveNoteFromIPFS } from \"../Functions/retrieveNoteFromIPFS\";\nimport notify from \"../components/molecules/notify\";\nimport {\n search,\n setNoteFromHash,\n} from \"../components/organisms/noteManager/noteManager\";\nimport select from \"../utils/dom\";\nimport { url } from \"../utils/urlManager\";\nimport { getGist } from \"../utils/github/api\";\n\nconst setNoteFromRawUrl = async (rawUrl) => {\n if (rawUrl) {\n const response = await fetch(rawUrl).then((response) => {\n if (response.ok) return response.text();\n throw new Error(\n `Remote note could not be retrieved! code: ${response.status}`\n );\n });\n select(\".terminal\").setValue(response);\n }\n};\n\nconst setNoteFromGist = async (gistId) => {\n if (gistId) {\n try {\n const gist = await getGist(gistId);\n const { files } = gist;\n const fileContents = Object.values(files);\n const [gistFile] = fileContents;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const { content } = gistFile;\n select(\".terminal\").setValue(content);\n } catch (error) {\n notify.error(\"MiroPad note not found! \uD83E\uDD37\u200D\u2642\uFE0F\");\n }\n }\n};\n\nexport const actOnURLStateChange = async (e = {}) => {\n try {\n const { oldURL, newURL } = e;\n const oldPageId = url.getPageId(oldURL);\n const newPageId = url.getPageId(newURL);\n const hasPageIdChanged = oldPageId !== newPageId;\n const { v: oldV } = url.getParamsObject(oldURL);\n const { v: newV } = url.getParamsObject(newURL);\n const hasPageVersionChanged = oldV !== newV;\n const shouldChangeNote = [hasPageIdChanged, hasPageVersionChanged].some(\n (r) => r\n );\n if (shouldChangeNote) setNoteFromHash();\n\n const { gistId, raw } = url.getParamsObject(newURL);\n await setNoteFromGist(gistId);\n await setNoteFromRawUrl(raw);\n } catch (e) {\n notify.error(e.message);\n }\n\n const isANewNote = !url.getPageId();\n select(\"#note-info-button\").show(!isANewNote);\n select(\"#new-note\").disable(isANewNote);\n\n if (url.getSearchParam(\"md\") === \"full\") {\n select(\".terminal\").hide();\n } else {\n select(\".terminal\").show();\n }\n\n if (url.getSearchParam(\"zen\") === \"true\") {\n select(\".header\").hide();\n } else {\n select(\".header\").show();\n }\n\n if (url.getSearchParam(\"cid\")) {\n await retrieveNoteFromIPFS(url.getSearchParam(\"cid\"));\n } else {\n select(\".anchor\").hide();\n }\n\n select(\".note-info\").hide();\n\n const q = url.getSearchParam(\"q\");\n const queryResult = search(q);\n if (queryResult) select(\".terminal\").setValue(queryResult.text);\n};\n", "export const isDevelopmentMode = () => {\n // eslint-disable-next-line no-undef\n const env = process.env.NODE_ENV;\n return env === \"development\";\n};\n\nexport const enableDevelopment = () => {\n if (isDevelopmentMode()) {\n new EventSource(\"/esbuild\").addEventListener(\"change\", () =>\n location.reload()\n );\n }\n};\n", "import select from \"../../../utils/dom\";\n\n// This is a feature where you can easily tick on/off\n// checkboxes \u2705 on the Markdown preview.\n// It does NOT persist the state on the data layer,\n// but lives temporarily on the browser's state\n// Useful feature when you are going to the Super market \uD83D\uDE04\n\n// Technically I cloud re-enable the checkboxes that ShowdownJS generates,\n// which are by default disabled, but couldn't figure that out. \u00AF\\_(\u30C4)_/\u00AF\n\nexport const autoMagicallyCheckBoxes = () => {\n select(\".task-list-item\").listenAll(\"click\", (el) => {\n el.firstChild.checked = !el.firstChild.checked;\n });\n};\n", "import \"github-markdown-css\";\nimport \"../css/print.css\";\nimport \"../css/styles.css\";\nimport welcomeUser from \"./components/molecules/welcome\";\nimport commander from \"./components/organisms/commander/commander\";\nimport markDownViewer from \"./components/organisms/markdown/markDownViewer\";\nimport {\n deleteNote,\n disableSyncOnCurrentNote,\n getNote,\n setNoteFromHash,\n} from \"./components/organisms/noteManager/noteManager\";\nimport { terminal } from \"./components/organisms/terminal\";\nimport { isSyncEnabled } from \"./isSyncEnabled\";\nimport { registerServiceWorker } from \"./registerServiceWorker\";\nimport { Trie } from \"./utils/Trie/Trie\";\nimport { copyToClipboard } from \"./utils/copyToClipboard\";\nimport { relativeDate } from \"./utils/dates\";\nimport select from \"./utils/dom\";\nimport errorHandler from \"./utils/errorHandler\";\nimport {\n setAuthTokenFromCallback,\n syncNotesWithGitHub,\n} from \"./utils/github/actions\";\nimport storage from \"./utils/localstorage\";\nimport { resetPageTitle } from \"./utils/pageTitle\";\nimport { url } from \"./utils/urlManager\";\nimport { actOnURLStateChange } from \"./listeners/urlChange\";\nimport { enableDevelopment } from \"./utils/enableDevelopmentTasks\";\nimport { autoMagicallyCheckBoxes } from \"./ui/markdown/preview/autoMagicallyCheckBoxes\";\n\n// Initialize a Trie tree to be used for the predictions\nexport const trieDictionary = Trie();\n\nconst initInfoPanel = () => {\n select(\"#note-info-close\").listen(\"click\", () => {\n select(\".note-info\").hide();\n });\n select(\"#note-info-button\").listen(\"click\", () => {\n const note = getNote();\n select(\".note-info\").show();\n\n select(\".note-info .details\").innerHTML(\n `

    \n \n ${note.title}\n

    \n

    \n \n ${relativeDate(note.dateCreated)}\n

    \n

    \n \n ${note.numberOfRevisions}\n

    \n `\n );\n\n const isSyncOn = isSyncEnabled();\n if (isSyncOn && note) {\n const syncEl = (() => {\n const { disableSync } = note;\n const p = document.createElement(\"P\");\n p.innerHTML = `\n \n \n `;\n return p;\n })();\n select(\".note-info .details\").append(syncEl);\n select(\"#sync\").listen(\"click\", (e) => {\n disableSyncOnCurrentNote(!e.target.checked);\n });\n }\n const deleteButton = (() => {\n const p = document.createElement(\"P\");\n p.innerHTML = `\n \n \n \n \n \n \n \n Delete\n \n `;\n return p;\n })();\n select(\".note-info .details\").append(deleteButton);\n select(\"#delete-note\").listen(\"click\", () => {\n deleteNote();\n });\n });\n};\n\nconst main = async () => {\n // Insert all the saved data from dictionary to the Trie tree\n const words = storage.getDictionary();\n trieDictionary.insert(words);\n\n window.addEventListener(\"error\", errorHandler);\n welcomeUser();\n commander.init();\n\n initInfoPanel();\n\n terminal.init();\n resetPageTitle();\n setNoteFromHash(url.getPageId());\n select(\".logo\").listen(\"click\", () => {\n commander.toggle(commander.getModes().notes);\n });\n select(\"#permalink\").listen(\"click\", async () => {\n await copyToClipboard(url.get());\n });\n\n markDownViewer.init();\n\n window.addEventListener(\"hashchange\", actOnURLStateChange);\n actOnURLStateChange();\n\n registerServiceWorker();\n\n autoMagicallyCheckBoxes();\n\n await syncNotesWithGitHub();\n await setAuthTokenFromCallback();\n\n enableDevelopment();\n};\n\nexport default main;\n", "import main from \"./js/main\";\n\n(() => {\n main();\n})();\n"], - "mappings": "u9CAIA,SAASA,EAAgBC,EAAQ,CAC/B,aAEA,IAAIC,EAAiB,CACnB,wBAAyB,CACvB,aAAc,GACd,SAAU,wDACV,KAAM,SACR,EACA,WAAY,CACV,aAAc,GACd,SAAU,kCACV,KAAM,SACR,EACA,eAAgB,CACd,aAAc,GACd,SAAU,4JACV,KAAM,QACR,EACA,kBAAmB,CACjB,aAAc,GACd,SAAU,uKACV,KAAM,SACR,EACA,qBAAsB,CACpB,aAAc,GACd,SAAU,oIACV,KAAM,SACR,EACA,YAAa,CACX,aAAc,GACd,SAAU,0JACV,KAAM,SACR,EACA,iBAAkB,CAChB,aAAc,GACd,SAAU,gCACV,KAAM,SACR,EACA,mBAAoB,CAClB,aAAc,GACd,SAAU,sCACV,KAAM,SACR,EACA,mBAAoB,CAClB,aAAc,GACd,SAAU,iCACV,KAAM,SACR,EACA,mCAAoC,CAClC,aAAc,GACd,SAAU,sEACV,KAAM,SACR,EACA,0BAA2B,CACzB,aAAc,GACd,SAAU,mDACV,KAAM,SACR,EACA,wBAAyB,CACvB,aAAc,GACd,SAAU,+CACV,KAAM,SACR,EACA,cAAe,CACb,aAAc,GACd,SAAU,oCACV,KAAM,SACR,EACA,OAAQ,CACN,aAAc,GACd,SAAU,6BACV,KAAM,SACR,EACA,eAAgB,CACd,aAAc,GACd,SAAU,6BACV,KAAM,SACR,EACA,aAAc,CACZ,aAAc,GACd,SAAU,6CACV,KAAM,SACR,EACA,UAAW,CACT,aAAc,GACd,SAAU,mCACV,KAAM,SACR,EACA,kBAAmB,CACjB,aAAc,GACd,SAAU,kEACV,KAAM,SACR,EACA,oBAAqB,CACnB,aAAc,GACd,SAAU,kDACV,KAAM,SACR,EACA,qCAAsC,CACpC,aAAc,GACd,SAAU,oEACV,KAAM,SACR,EACA,iBAAkB,CAChB,aAAc,GACd,SAAU,gDACV,KAAM,SACR,EACA,8BAA+B,CAC7B,aAAc,GACd,SAAU,6EACV,KAAM,SACR,EACA,WAAY,CACV,aAAc,GACd,SAAU,2BACV,KAAM,SACR,EACA,eAAgB,CACd,aAAc,yBACd,SAAU,yFACV,KAAM,QACR,EACA,aAAc,CACZ,aAAc,GACd,SAAU,0IACV,KAAM,SACR,EACA,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BC,GAAI,UAAU,CAAC,EAC/BrB,EAAO,OAAO,EAAE,OAAO,QAAS,IAAM,CACpCiB,GAAU,OAAOA,GAAU,SAAS,EAAE,KAAK,CAC7C,CAAC,EACDjB,EAAO,YAAY,EAAE,OAAO,QAAS,SAAY,CAC/C,MAAMsB,GAAgBD,GAAI,IAAI,CAAC,CACjC,CAAC,EAEDE,GAAe,KAAK,EAEpB,OAAO,iBAAiB,aAAcC,EAAmB,EACzDA,GAAoB,EAEpBC,IAAsB,EAEtBC,IAAwB,EAExB,MAAMC,GAAoB,EAC1B,MAAMC,GAAyB,EAE/BC,IAAkB,CACpB,EAEOC,IAAQlB,IC9IbmB,IAAK", - "names": ["getDefaultOpts", "simple", "defaultOptions", "ret", "opt", "allOptionsOn", "options", "showdown", "parsers", "extensions", "globalOptions", "setFlavor", "flavor", "key", "value", "name", "preset", "option", "func", "ext", "validExtension", "validate", "extension", "errMsg", "i", "baseMsg", "type", "ln", "validateExtension", "a", "getType", "obj", "callback", "prop", "s", "escapeCharactersCallback", "wholeMatch", "m1", "charCodeToEscape", "text", "charsToEscape", "afterBackslash", "regexString", "regex", "txt", "rgxFindMatchPos", "str", "left", "right", "flags", "f", "g", "x", "l", "pos", "t", "m", "start", "end", "matchPos", "results", "replacement", "repStr", "finalStr", "lng", "bits", "fromIndex", "indexOf", "index", "mail", "encode", "ch", "r", "targetLength", "padString", "msg", "converterOptions", "langExtensions", "outputModifiers", "listeners", "setConvFlavor", "metadata", "_constructor", "gOpt", "_parseExtension", "legacyExtensionLoading", "validExt", "listen", "valid", "rTrimInputText", "rsp", "rgx", "evtName", "globals", "ei", "nText", "src", "HTMLParser", "doc", "substitutePreCodeTags", "clean", "nodes", "mdDoc", "node", "n", "child", "pres", "presPH", "content", "language", "classes", "c", "matches", "extensionName", "ii", "raw", "format", "writeAnchorTag", "linkText", "linkId", "url", "m5", "m6", "title", "result", "wm", "st", "escape", "mentions", "username", "lnk", "target", "simpleURLRegex", "simpleURLRegex2", "delimUrlRegex", "simpleMailRegex", "delimMailRegex", "replaceLink", "leadingMagicChars", "link", "m2", "m3", "trailingPunctuation", "trailingMagicChars", "lnkTxt", "append", "lmc", "tmc", "replaceMail", "b", "href", "bq", "pre", "pattern", "codeblock", "nextChar", "doctype", "doctypeParsed", "charset", "lang", "meta", "leadingText", "numSpaces", "emojiRgx", "emojiCode", "tags", "comments", "delim", "repFunc", "match", "blockText", "blockTags", "inside", "opTagPos", "rgx1", "patLeft", "patRight", "subTexts", "newSubText1", "hashHTMLSpan", "html", "repText", "limit", "num", "headerLevelStart", "setextRegexH1", "setextRegexH2", "spanGamut", "hID", "headerId", "hLevel", "hashBlock", "matchFound", "atxStyle", "hText", "span", "header", "prefix", "inlineRegExp", "crazyRegExp", "base64RegExp", "referenceRegExp", "refShortcutRegExp", "writeImageTagBase64", "altText", "width", "height", "writeImageTag", "gUrls", "gTitles", "gDims", "parseInside", "lead", "processListItems", "listStr", "trimTrailing", "isParagraphed", "m4", "taskbtn", "checked", "item", "bulletStyle", "otp", "wm2", "styleStartNumber", "list", "listType", "res", "parseConsecutiveLists", "olRgx", "ulRgx", "counterRxg", "parseCL", "style", "parseMetadataContents", "wholematch", "grafs", "grafsOut", "grafsOutIt", "codeFlag", "re", "base64Regex", "replaceFunc", "blankLines", "tableRgx", "singeColTblRgx", "parseStyles", "sLine", "parseHeaders", "id", "parseCells", "cell", "subText", "buildTable", "headers", "cells", "tb", "tblLgn", "parseTable", "rawTable", "tableLines", "rawHeaders", "rawStyles", "rawCells", "styles", "row", "charCodeToReplace", "children", "childrenLength", "innerTxt", "headerLevel", "headerMark", "listItems", "listItemsLenght", "listNum", "bullet", "listItemTxt", "childrenLenght", "spansOnly", "tagName", "tableArray", "headings", "rows", "headContent", "allign", "cols", "cellContent", "cellSpacesCount", "strLen", "root", "module", "require_is_plain_obj", "__commonJSMin", "exports", "module", "value", "prototype", "require_merge_options", "__commonJSMin", "exports", "module", "isOptionObject", "hasOwnProperty", "propertyIsEnumerable", "defineProperty", "object", "name", "value", "globalThis", "defaultMergeOptions", "getEnumerableOwnPropertyKeys", "keys", "key", "symbols", "symbol", "clone", "cloneArray", "cloneOptionObject", "array", "result", "mergeKeys", "merged", "source", "config", "merge", "concatArrays", "resultIndex", "indices", "k", "options", "option", "require_is_electron", "__commonJSMin", "exports", "module", "isElectron", "require_env", "__commonJSMin", "exports", "module", "isElectron", "IS_ENV_WITH_DOM", "IS_ELECTRON", "IS_BROWSER", "IS_ELECTRON_MAIN", "IS_ELECTRON_RENDERER", "IS_NODE", "__require", "IS_WEBWORKER", "IS_TEST", "IS_REACT_NATIVE", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "require_err_code", "__commonJSMin", "exports", "module", "assign", "obj", "props", "key", "createError", "err", "code", "ErrClass", "require_aspromise", "__commonJSMin", "exports", "module", "asPromise", "fn", "ctx", "params", "offset", "index", "pending", "resolve", "reject", "err", "require_base64", "__commonJSMin", "exports", "base64", "string", "p", "b64", "s64", "i", "buffer", "start", "end", "parts", "chunk", "j", "t", "b", "invalidEncoding", "offset", "require_eventemitter", "__commonJSMin", "exports", "module", "EventEmitter", "evt", "fn", "ctx", "listeners", "args", "require_float", "__commonJSMin", "exports", "module", "factory", "f32", "f8b", "le", "writeFloat_f32_cpy", "val", "buf", "pos", "writeFloat_f32_rev", "readFloat_f32_cpy", "readFloat_f32_rev", "writeFloat_ieee754", "writeUint", "sign", "exponent", "mantissa", "writeUintLE", "writeUintBE", "readFloat_ieee754", "readUint", "uint", "readUintLE", "readUintBE", "f64", "writeDouble_f64_cpy", "writeDouble_f64_rev", "readDouble_f64_cpy", "readDouble_f64_rev", "writeDouble_ieee754", "off0", "off1", "readDouble_ieee754", "lo", "hi", "require_inquire", "__commonJSMin", "e", "require_utf8", "__commonJSMin", "exports", "utf8", "string", "len", "c", "buffer", "start", "end", "parts", "chunk", "i", "t", "offset", "c1", "c2", "require_pool", "__commonJSMin", "exports", "module", "pool", "alloc", "slice", "size", "SIZE", "MAX", "slab", "offset", "buf", "require_longbits", "__commonJSMin", "exports", "module", "LongBits", "util", "lo", "hi", "zero", "zeroHash", "value", "sign", "unsigned", "charCodeAt", "hash", "mask", "part0", "part1", "part2", "require_minimal", "__commonJSMin", "exports", "util", "value", "obj", "prop", "Buffer", "sizeOrArray", "hash", "unsigned", "bits", "merge", "dst", "src", "ifNotSet", "keys", "str", "newError", "name", "CustomError", "message", "properties", "fieldNames", "fieldMap", "i", "encoding", "size", "require_writer", "__commonJSMin", "exports", "module", "Writer", "util", "BufferWriter", "LongBits", "base64", "utf8", "Op", "fn", "len", "val", "noop", "State", "writer", "create", "size", "writeByte", "buf", "pos", "writeVarint32", "VarintOp", "value", "writeVarint64", "bits", "writeFixed32", "writeBytes", "head", "tail", "BufferWriter_", "require_writer_buffer", "__commonJSMin", "exports", "module", "BufferWriter", "Writer", "util", "val", "buf", "pos", "value", "len", "writeStringBuffer", "require_reader", "__commonJSMin", "exports", "module", "Reader", "util", "BufferReader", "LongBits", "utf8", "indexOutOfRange", "reader", "writeLength", "buffer", "create_array", "create", "value", "readLongVarint", "bits", "i", "readFixed32_end", "buf", "end", "readFixed64", "length", "start", "bytes", "wireType", "BufferReader_", "fn", "require_reader_buffer", "__commonJSMin", "exports", "module", "BufferReader", "Reader", "util", "buffer", "len", "require_service", "__commonJSMin", "exports", "module", "Service", "util", "rpcImpl", "requestDelimited", "responseDelimited", "rpcCall", "method", "requestCtor", "responseCtor", "request", "callback", "self", "err", "response", "endedByRPC", "require_rpc", "__commonJSMin", "exports", "rpc", "require_roots", "__commonJSMin", "exports", "module", "require_index_minimal", "__commonJSMin", "exports", "protobuf", "configure", "require_minimal", "__commonJSMin", "exports", "module", "require_time_browser", "__commonJSMin", "exports", "module", "require_retimer", "__commonJSMin", "exports", "module", "getTime", "Retimer", "callback", "timeout", "args", "that", "now", "retimer", "i", "require_timeout_abort_controller", "__commonJSMin", "exports", "module", "AbortController", "retimer", "TimeoutController", "ms", "require_url_browser", "__commonJSMin", "exports", "module", "isReactNative", "getDefaultBase", "URL", "defaultBase", "URLWithLegacySupport", "url", "base", "hash", "host", "hostname", "href", "password", "pathname", "port", "protocol", "search", "username", "o", "format", "obj", "userPass", "auth", "path", "require_relative", "__commonJSMin", "exports", "module", "URLWithLegacySupport", "format", "url", "location", "protocolMap", "defaultProtocol", "protocol", "urlParsed", "base", "require_iso_url", "__commonJSMin", "exports", "module", "URLWithLegacySupport", "format", "URLSearchParams", "defaultBase", "relative", "require_any_signal", "__commonJSMin", "exports", "module", "anySignal", "signals", "controller", "onAbort", "signal", "require_hashlru", "__commonJSMin", "exports", "module", "max", "size", "cache", "_cache", "update", "key", "value", "v", "require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "i", "length", "j", "require_error", "__commonJSMin", "exports", "TimeoutError", "message", "AbortError", "HTTPError", "response", "require_browser", "__commonJSMin", "exports", "module", "getGlobal", "globalObject", "require_src", "__commonJSMin", "exports", "module", "require_fetch_browser", "__commonJSMin", "exports", "module", "require_fetch_browser", "__commonJSMin", "exports", "module", "TimeoutError", "AbortError", "Response", "Request", "Headers", "fetch", "fetchWithProgress", "url", "options", "request", "timeout", "headers", "name", "value", "resolve", "reject", "handleEvent", "event", "ResponseWithURL", "parseHeaders", "fetchWithStreaming", "fetchWith", "input", "line", "index", "body", "require_browser_readablestream_to_it", "__commonJSMin", "exports", "module", "browserReadableStreamToIt", "stream", "options", "reader", "result", "require_it_all", "__commonJSMin", "exports", "module", "all", "source", "arr", "entry", "require_http", "__commonJSMin", "exports", "module", "fetch", "Request", "Headers", "TimeoutError", "HTTPError", "merge", "URL", "URLSearchParams", "anySignal", "browserReableStreamToIt", "isBrowser", "isWebWorker", "all", "timeout", "promise", "ms", "abortController", "start", "timedOut", "resolve", "reject", "timeoutID", "after", "next", "res", "defaults", "HTTP", "options", "resource", "opts", "headers", "url", "searchParams", "transformSearchParams", "json", "signal", "response", "fromStream", "chunk", "ndjson", "source", "decoder", "buf", "lines", "i", "l", "isAsyncIterable", "isNodeReadableStream", "iter", "value", "isWebReadableStream", "reader", "done", "require_timestamp_min", "__commonJSMin", "exports", "module", "Timestamp", "d", "l", "s", "T", "e", "f", "c", "g", "h", "u", "m", "n", "t", "o", "r", "p", "y", "M", "C", "D", "a", "i", "v", "w", "require_forge", "__commonJSMin", "exports", "module", "require_baseN", "__commonJSMin", "exports", "module", "api", "_reverseAlphabets", "input", "alphabet", "maxline", "output", "_encodeWithByteBuffer", "base", "first", "digits", "j", "carry", "regex", "table", "i", "bytes", "value", "k", "require_util", "__commonJSMin", "exports", "module", "forge", "baseN", "util", "callback", "handler", "event", "msg", "copy", "callbacks", "now", "attr", "div", "oldSetImmediate", "x", "_checkBitsParam", "n", "ByteStringBuffer", "b", "arr", "i", "_MAX_CONSTRUCTED_STRING_LENGTH", "d", "bytes", "str", "buffer", "rval", "max", "count", "c", "len", "DataBuffer", "options", "isArrayBuffer", "isArrayBufferView", "amount", "growSize", "src", "dst", "encoding", "view", "input", "s", "s1", "s2", "s3", "t", "hex", "_base64", "_base64Idx", "_base58", "maxline", "line", "output", "chr1", "chr2", "chr3", "enc1", "enc2", "enc3", "enc4", "offset", "out", "j", "k", "api", "raw", "start", "flg", "_setStorageObject", "id", "obj", "error", "_getStorageObject", "_setItem", "key", "data", "_getItem", "_removeItem", "empty", "prop", "_clearItems", "_callStorageFunction", "func", "args", "location", "type", "done", "exception", "idx", "ex", "format", "re", "match", "part", "argi", "parts", "last", "code", "number", "decimals", "dec_point", "thousands_sep", "size", "ip", "num", "blanks", "e", "zeros", "zeroGroups", "zeroMaxGroup", "group", "blobUrl", "st", "et", "sample", "samples", "numWorkers", "avg", "map", "err", "results", "reduce", "workers", "worker", "overlaps", "r1", "overlap", "r2", "require_oids", "__commonJSMin", "exports", "module", "forge", "oids", "_IN", "id", "name", "_I_", "require_asn1", "__commonJSMin", "exports", "module", "forge", "asn1", "tagClass", "type", "constructed", "value", "options", "tmp", "i", "obj", "copy", "obj1", "obj2", "equal", "b", "b2", "length", "longForm", "_checkBufferLength", "bytes", "remaining", "n", "error", "_getValueLength", "longFormBytes", "byteCount", "_fromDer", "depth", "start", "b1", "bitStringContents", "savedRead", "savedRemaining", "unused", "subOptions", "composed", "used", "tc", "asn1Options", "useBitStringContents", "len", "lenBytes", "oid", "values", "last", "valueBytes", "utc", "date", "year", "MM", "DD", "hh", "mm", "ss", "end", "hhoffset", "mmoffset", "offset", "gentime", "YYYY", "fff", "isUTC", "c", "rval", "format", "x", "v", "capture", "errors", "j", "_nonLatinRegex", "level", "indentation", "indent", "subvalues", "sub", "e", "require_cipher", "__commonJSMin", "exports", "module", "forge", "algorithm", "key", "api", "name", "BlockCipher", "options", "opts", "input", "pad", "output", "require_cipherModes", "__commonJSMin", "exports", "module", "forge", "modes", "options", "input", "output", "finish", "i", "padding", "len", "count", "transformIV", "inputLength", "partialBytes", "inc32", "iv", "additionalData", "ivLength", "from64To32", "overflow", "rval", "lengths", "tag", "x", "y", "z_i", "v_i", "x_i", "out", "lsb", "z", "idx", "ah", "h", "bits", "multiplier", "perInt", "size", "m", "tmp", "shft", "mid", "half", "j", "m_i", "m_j", "c", "blockSize", "ints", "blocks", "block", "num", "require_aes", "__commonJSMin", "exports", "module", "forge", "key", "iv", "output", "mode", "cipher", "_createCipher", "name", "init", "initialize", "self", "inBlock", "outBlock", "_updateBlock", "options", "tmp", "i", "len", "encryptOp", "_expandKey", "decrypt", "registerAlgorithm", "factory", "Nb", "sbox", "isbox", "rcon", "mix", "imix", "xtime", "e", "ei", "e2", "e4", "e8", "sx", "sx2", "me", "ime", "n", "w", "temp", "iNk", "Nk", "Nr1", "end", "m0", "m1", "m2", "m3", "wnew", "wi", "input", "Nr", "sub", "a", "b", "c", "a2", "b2", "c2", "round", "algorithm", "start", "require_des", "__commonJSMin", "exports", "module", "forge", "key", "iv", "output", "mode", "cipher", "_createCipher", "name", "self", "inBlock", "outBlock", "_updateBlock", "options", "_createKeys", "registerAlgorithm", "factory", "spfunction1", "spfunction2", "spfunction3", "spfunction4", "spfunction5", "spfunction6", "spfunction7", "spfunction8", "pc2bytes0", "pc2bytes1", "pc2bytes2", "pc2bytes3", "pc2bytes4", "pc2bytes5", "pc2bytes6", "pc2bytes7", "pc2bytes8", "pc2bytes9", "pc2bytes10", "pc2bytes11", "pc2bytes12", "pc2bytes13", "iterations", "keys", "shifts", "n", "tmp", "j", "left", "right", "i", "lefttmp", "righttmp", "input", "decrypt", "looping", "endloop", "loopinc", "right1", "right2", "algorithm", "start", "require_md", "__commonJSMin", "exports", "module", "forge", "require_hmac", "__commonJSMin", "exports", "module", "forge", "hmac", "_key", "_md", "_ipadding", "_opadding", "ctx", "md", "key", "tmp", "i", "keylen", "bytes", "inner", "require_pbkdf2", "__commonJSMin", "exports", "module", "forge", "pkcs5", "crypto", "p", "s", "c", "dkLen", "md", "callback", "err", "key", "hLen", "len", "r", "prf", "dk", "xor", "u_c", "u_c1", "i", "j", "outer", "inner", "require_pem", "__commonJSMin", "exports", "module", "forge", "pem", "msg", "options", "rval", "header", "foldHeader", "str", "rMessage", "rHeader", "rCRLF", "match", "type", "lines", "li", "line", "nl", "next", "values", "vi", "ltrim", "insertSpace", "$1", "length", "candidate", "insert", "require_sha256", "__commonJSMin", "exports", "module", "forge", "sha256", "_initialized", "_init", "_state", "_input", "_w", "md", "int32s", "i", "msg", "encoding", "len", "_update", "finalBlock", "remaining", "overflow", "_padding", "next", "carry", "bits", "s2", "rval", "_k", "s", "w", "bytes", "t1", "t2", "s0", "s1", "ch", "maj", "a", "b", "c", "e", "f", "g", "h", "require_prng", "__commonJSMin", "exports", "module", "forge", "_crypto", "prng", "plugin", "ctx", "md", "pools", "count", "callback", "cipher", "increment", "formatKey", "formatSeed", "b", "generate", "err", "_reseed", "bytes", "_reseedSync", "_seed", "needed", "_2powK", "k", "seedBytes", "defaultSeedFile", "getRandomValues", "globalScope", "arr", "entropy", "i", "e", "hi", "lo", "next", "seed", "n", "x", "worker", "listener", "data", "require_random", "__commonJSMin", "exports", "module", "forge", "jQuery", "prng_aes", "_prng_aes_output", "_prng_aes_buffer", "key", "tmp", "seed", "spawnPrng", "ctx", "count", "callback", "_ctx", "getRandomValues", "globalScope", "_crypto", "arr", "_navBytes", "e", "require_rc2", "__commonJSMin", "exports", "module", "forge", "piTable", "s", "rol", "word", "bits", "ror", "key", "effKeyBits", "L", "T", "T1", "T8", "TM", "i", "createCipher", "encrypt", "_finish", "_input", "_output", "_iv", "mixRound", "mashRound", "j", "K", "R", "runPlan", "plan", "val", "ptr", "ctr", "cipher", "iv", "output", "input", "pad", "rval", "padding", "len", "count", "require_jsbn", "__commonJSMin", "exports", "module", "forge", "dbits", "canary", "j_lm", "BigInteger", "a", "b", "c", "nbi", "am1", "i", "x", "w", "j", "n", "v", "am2", "xl", "xh", "l", "h", "m", "am3", "BI_FP", "BI_RM", "BI_RC", "rr", "vv", "int2char", "intAt", "s", "bnpCopyTo", "bnpFromInt", "nbv", "r", "bnpFromString", "k", "mi", "sh", "bnpClamp", "bnToString", "km", "d", "p", "bnNegate", "bnAbs", "bnCompareTo", "nbits", "bnBitLength", "bnpDLShiftTo", "bnpDRShiftTo", "bnpLShiftTo", "bs", "cbs", "bm", "ds", "bnpRShiftTo", "bnpSubTo", "bnpMultiplyTo", "y", "bnpSquareTo", "bnpDivRemTo", "q", "pm", "pt", "ts", "ms", "nsh", "ys", "y0", "yt", "d1", "d2", "e", "t", "qd", "bnMod", "Classic", "cConvert", "cRevert", "cReduce", "cMulTo", "cSqrTo", "bnpInvDigit", "Montgomery", "montConvert", "montRevert", "montReduce", "u0", "montSqrTo", "montMulTo", "bnpIsEven", "bnpExp", "z", "r2", "g", "bnModPowInt", "bnClone", "bnIntValue", "bnByteValue", "bnShortValue", "bnpChunkSize", "bnSigNum", "bnpToRadix", "cs", "bnpFromRadix", "bnpFromNumber", "op_or", "bnToByteArray", "bnEquals", "bnMin", "bnMax", "bnpBitwiseTo", "op", "f", "op_and", "bnAnd", "bnOr", "op_xor", "bnXor", "op_andnot", "bnAndNot", "bnNot", "bnShiftLeft", "bnShiftRight", "lbit", "bnGetLowestSetBit", "cbit", "bnBitCount", "bnTestBit", "bnpChangeBit", "bnSetBit", "bnClearBit", "bnFlipBit", "bnpAddTo", "bnAdd", "bnSubtract", "bnMultiply", "bnDivide", "bnRemainder", "bnDivideAndRemainder", "bnpDMultiply", "bnpDAddOffset", "NullExp", "nNop", "nMulTo", "nSqrTo", "bnPow", "bnpMultiplyLowerTo", "bnpMultiplyUpperTo", "Barrett", "barrettConvert", "barrettRevert", "barrettReduce", "barrettSqrTo", "barrettMulTo", "bnModPow", "k1", "g2", "is1", "bnGCD", "bnpModInt", "bnModInverse", "ac", "u", "lowprimes", "lplim", "bnIsProbablePrime", "bnpMillerRabin", "n1", "prng", "bnGetPrng", "require_sha1", "__commonJSMin", "exports", "module", "forge", "sha1", "_initialized", "_init", "_state", "_input", "_w", "md", "int32s", "i", "msg", "encoding", "len", "_update", "finalBlock", "remaining", "overflow", "_padding", "next", "carry", "bits", "s2", "rval", "s", "w", "bytes", "t", "a", "b", "c", "d", "e", "f", "require_pkcs1", "__commonJSMin", "exports", "module", "forge", "pkcs1", "key", "message", "options", "label", "seed", "md", "mgf1Md", "keyLength", "maxLength", "error", "lHash", "PS", "PS_length", "i", "DB", "dbMask", "rsa_mgf1", "maskedDB", "seedMask", "maskedSeed", "em", "y", "db", "lHashPrime", "in_ps", "index", "j", "code", "is_0", "error_mask", "maskLength", "hash", "t", "count", "c", "require_prime", "__commonJSMin", "exports", "module", "forge", "prime", "BigInteger", "GCD_30_DELTA", "THIRTY", "op_or", "x", "y", "bits", "options", "callback", "algorithm", "prng", "rng", "b", "i", "primeincFindPrime", "primeincFindPrimeWithWorkers", "primeincFindPrimeWithoutWorkers", "num", "generateRandom", "deltaIdx", "mrTests", "getMillerRabinTests", "maxBlockTime", "_primeinc", "start", "numWorkers", "workLoad", "range", "workerScript", "err", "cores", "generate", "workers", "running", "workerMessage", "found", "e", "data", "hex", "bits1", "require_rsa", "__commonJSMin", "exports", "module", "forge", "BigInteger", "_crypto", "asn1", "util", "pki", "GCD_30_DELTA", "privateKeyValidator", "rsaPrivateKeyValidator", "rsaPublicKeyValidator", "publicKeyValidator", "digestInfoValidator", "emsaPkcs1v15encode", "md", "oid", "error", "oidBytes", "digestInfo", "digestAlgorithm", "digest", "_modPow", "x", "key", "pub", "r", "xp", "xq", "y", "m", "bt", "eb", "k", "_encodePkcs1_v1_5", "yhex", "ed", "zeros", "ml", "xhex", "_decodePkcs1_v1_5", "bits", "options", "prng", "rng", "b", "i", "algorithm", "rval", "state", "n", "THIRTY", "deltaIdx", "op_or", "t1", "t2", "total", "bits1", "_getMillerRabinTests", "d", "callback", "_detectNodeCrypto", "err", "priv", "_detectSubtleCrypto", "_intToUint8Array", "pair", "pkcs8", "privateKey", "_detectSubtleMsCrypto", "genOp", "e", "exportOp", "keypair", "_generateKeyPair", "data", "scheme", "schemeOptions", "signature", "obj", "capture", "errors", "p", "q", "dP", "dQ", "qInv", "rsaKey", "_bnToBytes", "padNum", "padByte", "numZeros", "padBytes", "em", "first", "zero", "opts", "generate", "getPrime", "num", "finish", "tmp", "hex", "bytes", "fn", "buffer", "require_pbe", "__commonJSMin", "exports", "module", "forge", "BigInteger", "asn1", "pki", "oids", "encryptedPrivateKeyValidator", "PBES2AlgorithmsValidator", "pkcs12PbeParamsValidator", "obj", "password", "options", "salt", "count", "countBytes", "dkLen", "encryptionAlgorithm", "encryptedData", "ivLen", "encOid", "cipherFn", "error", "prfAlgorithm", "md", "prfAlgorithmToMessageDigest", "dk", "iv", "cipher", "params", "createPbkdf2Params", "saltBytes", "rval", "capture", "errors", "oid", "encrypted", "epki", "maxline", "msg", "pem", "rsaKey", "algorithm", "key", "id", "iter", "n", "j", "l", "u", "v", "result", "passBuf", "p", "s", "D", "Slen", "S", "Plen", "P", "I", "c", "i", "buf", "round", "B", "k", "Inew", "chunk", "x", "prfOidToMessageDigest", "dIvLen", "digests", "hash", "length", "bytes", "prfOid", "factory", "require_sha512", "__commonJSMin", "exports", "module", "forge", "sha512", "sha384", "algorithm", "_initialized", "_init", "_states", "_state", "_h", "_input", "_w", "wi", "digestLength", "md", "int32s", "i", "msg", "encoding", "len", "_update", "finalBlock", "remaining", "overflow", "_padding", "next", "carry", "bits", "h", "rval", "hlen", "_k", "s", "w", "bytes", "t1_hi", "t1_lo", "t2_hi", "t2_lo", "s0_hi", "s0_lo", "s1_hi", "s1_lo", "ch_hi", "ch_lo", "maj_hi", "maj_lo", "a_hi", "a_lo", "b_hi", "b_lo", "c_hi", "c_lo", "d_hi", "d_lo", "e_hi", "e_lo", "f_hi", "f_lo", "g_hi", "g_lo", "h_hi", "h_lo", "hi", "lo", "w2", "w7", "w15", "w16", "require_longbits", "__commonJSMin", "exports", "module", "LongBits", "util", "lo", "hi", "zero", "zeroHash", "value", "sign", "unsigned", "charCodeAt", "hash", "mask", "part0", "part1", "part2", "require_minimal", "__commonJSMin", "exports", "util", "value", "obj", "prop", "Buffer", "sizeOrArray", "hash", "unsigned", "bits", "merge", "dst", "src", "ifNotSet", "keys", "str", "newError", "name", "CustomError", "message", "properties", "fieldNames", "fieldMap", "i", "encoding", "size", "require_reader", "__commonJSMin", "exports", "module", "Reader", "util", "BufferReader", "LongBits", "utf8", "indexOutOfRange", "reader", "writeLength", "buffer", "create_array", "create", "value", "readLongVarint", "bits", "i", "readFixed32_end", "buf", "end", "readFixed64", "length", "start", "nativeBuffer", "bytes", "wireType", "BufferReader_", "fn", "require_reader_buffer", "__commonJSMin", "exports", "module", "BufferReader", "Reader", "util", "buffer", "len", "require_writer", "__commonJSMin", "exports", "module", "Writer", "util", "BufferWriter", "LongBits", "base64", "utf8", "Op", "fn", "len", "val", "noop", "State", "writer", "create", "size", "writeByte", "buf", "pos", "writeVarint32", "VarintOp", "value", "writeVarint64", "bits", "writeFixed32", "writeBytes", "head", "tail", "BufferWriter_", "require_writer_buffer", "__commonJSMin", "exports", "module", "BufferWriter", "Writer", "util", "val", "buf", "pos", "value", "len", "writeStringBuffer", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "obj", "key", "def", "p", "undef", "split", "length", "require_is_domain_name", "__commonJSMin", "exports", "module", "domainNameRegex", "domainName", "rootDot", "lastChar", "require_encode", "__commonJSMin", "exports", "module", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "require_decode", "__commonJSMin", "exports", "module", "read", "MSB", "REST", "buf", "offset", "res", "shift", "counter", "b", "l", "require_length", "__commonJSMin", "exports", "module", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "value", "require_varint", "__commonJSMin", "exports", "module", "require_murmurHash3js", "__commonJSMin", "exports", "module", "root", "undefined", "library", "_validBytes", "bytes", "i", "_x86Multiply", "m", "n", "_x86Rotl", "_x86Fmix", "h", "_x64Add", "o", "_x64Multiply", "_x64Rotl", "_x64LeftShift", "_x64Xor", "_x64Fmix", "seed", "remainder", "blocks", "h1", "k1", "c1", "c2", "h2", "h3", "h4", "k2", "k3", "k4", "c3", "c4", "require_murmurhash3js_revisited", "__commonJSMin", "exports", "module", "require_rabin", "__commonJSMin", "exports", "module", "Rabin", "asModule", "bits", "min", "max", "windowSize", "polynomial", "buf", "__retain", "__release", "__allocArray", "__getInt32Array", "Int32Array_ID", "Uint8Array_ID", "lengths", "lengthsPtr", "pointer", "out", "processed", "end", "require_loader", "__commonJSMin", "exports", "BIGINT", "THIS", "CHUNKSIZE", "getStringImpl", "buffer", "ptr", "U32", "U16", "length", "offset", "parts", "last", "size", "preInstantiate", "imports", "baseModule", "getString", "memory", "env", "mesg", "file", "line", "colm", "n", "postInstantiate", "instance", "rawExports", "table", "alloc", "retain", "rttiBase", "getInfo", "id", "count", "getBase", "getValueAlign", "info", "getKeyAlign", "__allocString", "str", "i", "p", "__getString", "getView", "alignLog2", "signed", "float", "__allocArray", "values", "align", "buf", "arr", "view", "__getArrayView", "__getArray", "input", "len", "out", "__getArrayBuffer", "getTypedArray", "Type", "getTypedArrayView", "bufPtr", "__instanceof", "baseId", "demangle", "isResponse", "o", "instantiate", "source", "instantiateStreaming", "instantiateSync", "module", "setArgumentsLength", "internalName", "elem", "curr", "part", "name", "hash", "className", "classElem", "ctor", "args", "thisValue", "getter", "setter", "value", "require_rabin_wasm", "__commonJSMin", "exports", "module", "instantiate", "loadWebAssembly", "imp", "wasm", "require_src", "__commonJSMin", "exports", "module", "Rabin", "getRabin", "create", "avg", "min", "max", "windowSize", "polynomial", "compiled", "require_sparse_array", "__commonJSMin", "exports", "module", "index", "value", "pos", "needsSort", "last", "iterator", "i", "mapped", "reducer", "initialValue", "acc", "finder", "found", "noCreate", "bytePos", "byte", "bitPos", "previousPopCount", "popCountReduce", "mask", "bytePopCount", "popCount", "targetLength", "data", "elem", "randomIndex", "sortInternal", "bytes", "pendingBitsForResultingByte", "pendingBitsForNewByte", "resultingByte", "newByte", "pending", "usingBits", "masked", "valueOnly", "count", "_v", "v", "a", "b", "require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "i", "length", "j", "require_index_browser", "__commonJSMin", "exports", "module", "require_fnv1a", "__commonJSMin", "exports", "module", "hash", "s", "h", "l", "i", "require_bytes", "__commonJSMin", "exports", "module", "bytes", "format", "parse", "formatThousandsRegExp", "formatDecimalsRegExp", "map", "parseRegExp", "value", "options", "mag", "thousandsSeparator", "unitSeparator", "decimalPlaces", "fixedDecimals", "unit", "val", "str", "s", "i", "results", "floatValue", "require_level_supports", "__commonJSMin", "exports", "manifests", "manifest", "acc", "m", "require_module_error", "__commonJSMin", "exports", "module", "message", "options", "require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_ieee754", "__commonJSMin", "exports", "buffer", "offset", "isLE", "mLen", "nBytes", "e", "m", "eLen", "eMax", "eBias", "nBits", "i", "d", "s", "value", "rt", "require_buffer", "__commonJSMin", "exports", "base64", "ieee754", "customInspectSymbol", "Buffer", "SlowBuffer", "K_MAX_LENGTH", "typedArraySupport", "arr", "proto", "createBuffer", "length", "buf", "arg", "encodingOrOffset", "allocUnsafe", "from", "value", "fromString", "fromArrayView", "isInstance", "fromArrayBuffer", "valueOf", "b", "fromObject", "assertSize", "size", "alloc", "fill", "encoding", "checked", "string", "byteLength", "actual", "fromArrayLike", "array", "i", "arrayView", "copy", "byteOffset", "obj", "len", "numberIsNaN", "a", "x", "y", "list", "buffer", "pos", "mustMatch", "loweredCase", "utf8ToBytes", "base64ToBytes", "slowToString", "start", "end", "hexSlice", "utf8Slice", "asciiSlice", "latin1Slice", "base64Slice", "utf16leSlice", "swap", "n", "m", "str", "max", "target", "thisStart", "thisEnd", "thisCopy", "targetCopy", "bidirectionalIndexOf", "val", "dir", "arrayIndexOf", "indexSize", "arrLength", "valLength", "read", "foundIndex", "found", "j", "hexWrite", "offset", "remaining", "strLen", "parsed", "utf8Write", "blitBuffer", "asciiWrite", "asciiToBytes", "base64Write", "ucs2Write", "utf16leToBytes", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "ret", "out", "hexSliceLookupTable", "bytes", "newBuf", "checkOffset", "ext", "noAssert", "mul", "defineBigIntMethod", "validateNumber", "first", "last", "boundsError", "lo", "hi", "checkInt", "min", "maxBytes", "wrtBigUInt64LE", "checkIntBI", "wrtBigUInt64BE", "limit", "sub", "checkIEEE754", "writeFloat", "littleEndian", "writeDouble", "targetStart", "code", "errors", "E", "sym", "getMessage", "Base", "name", "range", "input", "msg", "received", "addNumericalSeparator", "checkBounds", "type", "INVALID_BASE64_RE", "base64clean", "units", "leadSurrogate", "byteArray", "c", "src", "dst", "alphabet", "table", "i16", "fn", "BufferBigIntNotDefined", "require_text_endec", "__commonJSMin", "exports", "module", "lazy", "require_encoding", "__commonJSMin", "exports", "ModuleError", "formats", "Encoding", "options", "require_formats", "__commonJSMin", "exports", "Buffer", "Encoding", "textEndec", "BufferFormat", "options", "ViewFormat", "data", "view", "UTF8Format", "textEncoder", "textDecoder", "require_encodings", "__commonJSMin", "exports", "Buffer", "textEncoder", "textDecoder", "BufferFormat", "ViewFormat", "UTF8Format", "identity", "v", "data", "buffer", "require_level_transcoder", "__commonJSMin", "exports", "ModuleError", "encodings", "Encoding", "BufferFormat", "ViewFormat", "UTF8Format", "kFormats", "kEncodings", "validFormats", "Transcoder", "formats", "f", "k", "err", "encoding", "resolved", "lookup", "from", "name", "format", "options", "maybeType", "anonymousCount", "detectFormat", "aliases", "require_events", "__commonJSMin", "exports", "module", "R", "ReflectApply", "target", "receiver", "args", "ReflectOwnKeys", "ProcessEmitWarning", "warning", "NumberIsNaN", "value", "EventEmitter", "once", "defaultMaxListeners", "checkListener", "listener", "arg", "n", "_getMaxListeners", "that", "type", "i", "doError", "events", "er", "err", "handler", "len", "listeners", "arrayClone", "_addListener", "prepend", "m", "existing", "w", "onceWrapper", "_onceWrap", "state", "wrapped", "list", "position", "originalListener", "spliceOne", "keys", "key", "_listeners", "unwrap", "evlistener", "unwrapListeners", "emitter", "listenerCount", "arr", "copy", "index", "ret", "name", "resolve", "reject", "errorListener", "resolver", "eventTargetAgnosticAddListener", "addErrorHandlerIfEventEmitter", "flags", "wrapListener", "require_next_tick_browser", "__commonJSMin", "exports", "module", "fn", "require_catering", "__commonJSMin", "exports", "nextTick", "callback", "symbol", "promise", "resolve", "reject", "err", "res", "require_common", "__commonJSMin", "exports", "options", "callback", "def", "require_abstract_iterator", "__commonJSMin", "exports", "fromCallback", "ModuleError", "getOptions", "getCallback", "kPromise", "kCallback", "kWorking", "kHandleOne", "kHandleMany", "kAutoClose", "kFinishWork", "kReturnMany", "kClosing", "kHandleClose", "kClosed", "kCloseCallbacks", "kKeyEncoding", "kValueEncoding", "kAbortOnClose", "kLegacy", "kKeys", "kValues", "kLimit", "kCount", "emptyOptions", "noop", "warnedEnd", "CommonIterator", "db", "options", "legacy", "hint", "callback", "promise", "resolve", "reject", "err", "key", "value", "size", "acc", "onnext", "count", "nextv", "onnextv", "items", "cb", "target", "keyEncoding", "keyFormat", "mapped", "callbacks", "item", "AbstractIterator", "IteratorDecodeError", "entries", "entry", "AbstractKeyIterator", "keys", "AbstractValueIterator", "values", "subject", "cause", "k", "require_default_kv_iterator", "__commonJSMin", "exports", "AbstractKeyIterator", "AbstractValueIterator", "kIterator", "kCallback", "kHandleOne", "kHandleMany", "DefaultKeyIterator", "db", "options", "DefaultValueIterator", "Iterator", "keys", "mapEntry", "entry", "callback", "err", "key", "value", "size", "entries", "target", "require_deferred_iterator", "__commonJSMin", "exports", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "ModuleError", "kNut", "kUndefer", "kFactory", "DeferredIterator", "db", "options", "DeferredKeyIterator", "DeferredValueIterator", "Iterator", "callback", "size", "target", "require_abstract_chained_batch", "__commonJSMin", "exports", "fromCallback", "ModuleError", "getCallback", "getOptions", "kPromise", "kStatus", "kOperations", "kFinishClose", "kCloseCallbacks", "AbstractChainedBatch", "db", "hint", "key", "value", "options", "err", "original", "keyEncoding", "valueEncoding", "keyFormat", "mappedKey", "mappedValue", "callback", "callbacks", "cb", "require_default_chained_batch", "__commonJSMin", "exports", "AbstractChainedBatch", "ModuleError", "kEncoded", "DefaultChainedBatch", "db", "key", "value", "options", "callback", "require_range_options", "__commonJSMin", "exports", "module", "ModuleError", "hasOwnProperty", "rangeOptions", "options", "keyEncoding", "result", "k", "require_queue_microtask", "__commonJSMin", "exports", "module", "promise", "cb", "err", "require_next_tick_browser", "__commonJSMin", "exports", "module", "queueMicrotask", "fn", "args", "require_abstract_sublevel_iterator", "__commonJSMin", "exports", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "kUnfix", "kIterator", "kHandleOne", "kHandleMany", "kCallback", "AbstractSublevelIterator", "db", "options", "iterator", "unfix", "err", "key", "value", "callback", "entries", "entry", "AbstractSublevelKeyIterator", "keys", "AbstractSublevelValueIterator", "Iterator", "size", "target", "require_abstract_sublevel", "__commonJSMin", "exports", "module", "ModuleError", "Buffer", "AbstractSublevelIterator", "AbstractSublevelKeyIterator", "AbstractSublevelValueIterator", "kPrefix", "kUpperBound", "kPrefixRange", "kParent", "kUnfix", "textEncoder", "defaults", "AbstractLevel", "AbstractSublevel", "options", "db", "name", "separator", "manifest", "forward", "trim", "reserved", "parent", "x", "mergeManifests", "prefix", "upperBound", "MultiFormat", "Unfixer", "key", "keyFormat", "view", "result", "buffer", "range", "callback", "value", "keys", "operations", "iterator", "unfix", "supportsEncoding", "encoding", "prefixLength", "str", "char", "start", "end", "require_abstract_level", "__commonJSMin", "exports", "supports", "Transcoder", "EventEmitter", "fromCallback", "ModuleError", "AbstractIterator", "DefaultKeyIterator", "DefaultValueIterator", "DeferredIterator", "DeferredKeyIterator", "DeferredValueIterator", "DefaultChainedBatch", "getCallback", "getOptions", "rangeOptions", "kPromise", "kLanded", "kResources", "kCloseResources", "kOperations", "kUndefer", "kDeferOpen", "kOptions", "kStatus", "kDefaultOptions", "kTranscoder", "kKeyEncoding", "kValueEncoding", "noop", "AbstractLevel", "manifest", "options", "keyEncoding", "valueEncoding", "passive", "forward", "formats", "encoding", "callback", "maybeOpened", "err", "maybeClosed", "cancel", "pending", "sync", "next", "resource", "key", "maybeError", "keyFormat", "valueFormat", "value", "keys", "mappedKeys", "i", "values", "mappedKey", "mappedValue", "operations", "mapped", "ke", "ve", "op", "db", "valueErr", "name", "AbstractSublevel", "original", "fn", "k", "require_abstract_level", "__commonJSMin", "exports", "require_run_parallel_limit", "__commonJSMin", "exports", "module", "runParallelLimit", "queueMicrotask", "tasks", "limit", "cb", "results", "len", "pending", "keys", "isErrored", "isSync", "next", "done", "err", "end", "each", "i", "result", "key", "task", "require_key_range", "__commonJSMin", "exports", "module", "options", "lower", "upper", "lowerExclusive", "upperExclusive", "require_deserialize", "__commonJSMin", "exports", "module", "textEncoder", "data", "require_iterator", "__commonJSMin", "exports", "AbstractIterator", "createKeyRange", "deserialize", "kCache", "kFinished", "kOptions", "kCurrentOptions", "kPosition", "kLocation", "kFirst", "emptyOptions", "Iterator", "db", "location", "options", "size", "callback", "keyRange", "transaction", "store", "entries", "method", "ev", "cursor", "key", "value", "maybeCommit", "keys", "values", "complete", "length", "i", "err", "cache", "target", "require_clear", "__commonJSMin", "exports", "module", "db", "location", "keyRange", "options", "callback", "transaction", "store", "count", "method", "direction", "ev", "cursor", "require_browser_level", "__commonJSMin", "exports", "AbstractLevel", "ModuleError", "parallel", "fromCallback", "Iterator", "deserialize", "clear", "createKeyRange", "DEFAULT_PREFIX", "kIDB", "kNamePrefix", "kLocation", "kVersion", "kStore", "kOnComplete", "kPromise", "BrowserLevel", "location", "options", "_", "prefix", "version", "forward", "callback", "req", "ev", "db", "mode", "request", "transaction", "key", "store", "err", "value", "keys", "tasks", "next", "operations", "index", "error", "loop", "op", "keyRange", "require_browser", "__commonJSMin", "exports", "require_longbits", "__commonJSMin", "exports", "module", "LongBits", "util", "lo", "hi", "zero", "zeroHash", "value", "sign", "unsigned", "charCodeAt", "hash", "mask", "part0", "part1", "part2", "require_minimal", "__commonJSMin", "exports", "util", "value", "obj", "prop", "Buffer", "sizeOrArray", "hash", "unsigned", "bits", "merge", "dst", "src", "ifNotSet", "keys", "str", "newError", "name", "CustomError", "message", "properties", "fieldNames", "fieldMap", "i", "encoding", "size", "require_writer", "__commonJSMin", "exports", "module", "Writer", "util", "BufferWriter", "LongBits", "base64", "utf8", "Op", "fn", "len", "val", "noop", "State", "writer", "create", "size", "writeByte", "buf", "pos", "writeVarint32", "VarintOp", "value", "writeVarint64", "bits", "writeFixed32", "writeBytes", "head", "tail", "BufferWriter_", "require_writer_buffer", "__commonJSMin", "exports", "module", "BufferWriter", "Writer", "util", "val", "buf", "pos", "value", "len", "writeStringBuffer", "require_reader", "__commonJSMin", "exports", "module", "Reader", "util", "BufferReader", "LongBits", "utf8", "indexOutOfRange", "reader", "writeLength", "buffer", "create_array", "create", "value", "readLongVarint", "bits", "i", "readFixed32_end", "buf", "end", "readFixed64", "length", "start", "bytes", "wireType", "BufferReader_", "fn", "require_reader_buffer", "__commonJSMin", "exports", "module", "BufferReader", "Reader", "util", "buffer", "len", "require_service", "__commonJSMin", "exports", "module", "Service", "util", "rpcImpl", "requestDelimited", "responseDelimited", "rpcCall", "method", "requestCtor", "responseCtor", "request", "callback", "self", "err", "response", "endedByRPC", "require_rpc", "__commonJSMin", "exports", "rpc", "require_roots", "__commonJSMin", "exports", "module", "require_index_minimal", "__commonJSMin", "exports", "protobuf", "configure", "require_minimal", "__commonJSMin", "exports", "module", "require_rpc", "__commonJSMin", "exports", "module", "global", "factory", "__require", "$protobuf", "$Reader", "$Writer", "$util", "$root", "RPC", "p", "ks", "i", "$oneOfFields", "m", "w", "r", "l", "c", "t", "d", "o", "j", "SubOpts", "Message", "ControlMessage", "ControlIHave", "ControlIWant", "ControlGraft", "ControlPrune", "PeerInfo", "require_denque", "__commonJSMin", "exports", "module", "Denque", "array", "options", "index", "i", "len", "item", "head", "tail", "size", "k", "count", "removed", "del_count", "temp", "arg_len", "arguments_index", "leng", "fullCopy", "newArray", "list", "require_source", "__commonJSMin", "exports", "module", "readable", "reader", "done", "value", "require_url_source", "__commonJSMin", "exports", "module", "HTTP", "urlSource", "url", "options", "readURLContent", "require_random_browser", "__commonJSMin", "exports", "module", "randomBytes", "size", "bytes", "generated", "require_delay", "__commonJSMin", "exports", "module", "randomInteger", "minimum", "maximum", "createAbortError", "error", "createDelay", "defaultClear", "set", "willResolve", "ms", "value", "signal", "timeoutId", "settle", "rejectFn", "clear", "signalListener", "cleanup", "delayPromise", "resolve", "reject", "createWithTimers", "clearAndSet", "delay", "options", "require_src", "__commonJSMin", "exports", "module", "intervals", "_generateId", "_runPeriodically", "task", "interval", "id", "err", "resolve", "_timeout", "setDelayedInterval", "delay", "clearDelayedInterval", "require_RateLimiterAbstract", "__commonJSMin", "exports", "module", "opts", "value", "options", "key", "rlKey", "require_BlockedKeys", "__commonJSMin", "exports", "module", "now", "key", "sec", "ms", "expire", "require_BlockedKeys", "__commonJSMin", "exports", "module", "BlockedKeys", "require_RateLimiterRes", "__commonJSMin", "exports", "module", "remainingPoints", "msBeforeNext", "consumedPoints", "isFirstInDuration", "ms", "p", "value", "require_RateLimiterStoreAbstract", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "BlockedKeys", "RateLimiterRes", "opts", "value", "resolve", "reject", "rlKey", "changedPoints", "storeResult", "options", "res", "blockPromise", "err", "delay", "funcName", "key", "data", "secDuration", "msDuration", "points", "pointsToConsume", "inMemoryBlockMsBeforeExpire", "initPoints", "forceExpire", "require_RateLimiterRedis", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "incrTtlLuaScript", "RateLimiterRedis", "opts", "rlKey", "changedPoints", "result", "consumed", "resTtlMs", "res", "points", "msDuration", "forceExpire", "resolve", "reject", "secDuration", "multi", "err", "incrCallback", "require_RateLimiterMongo", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "getDriverVersion", "client", "_client", "version", "_v", "v", "RateLimiterMongo", "opts", "conn", "value", "obj", "collection", "rlKey", "changedPoints", "result", "res", "doc", "key", "points", "msDuration", "forceExpire", "options", "docAttrs", "where", "upsertData", "upsertOptions", "resolve", "reject", "errUpsert", "replaceWhere", "replaceTo", "errReplace", "err", "require_RateLimiterMySQL", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMySQL", "opts", "cb", "err", "expire", "resolve", "conn", "reject", "errConn", "errDb", "value", "rlKey", "changedPoints", "result", "res", "row", "key", "points", "msDuration", "forceExpire", "errBegin", "dateNow", "newExpire", "q", "values", "errUpsert", "errSelect", "require_RateLimiterPostgres", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterPostgres", "opts", "cb", "err", "expire", "resolve", "q", "conn", "reject", "value", "constructorName", "rlKey", "changedPoints", "result", "res", "row", "queryObj", "key", "points", "msDuration", "forceExpire", "newExpire", "expireQ", "require_Record", "__commonJSMin", "exports", "module", "value", "expiresAt", "timeoutId", "require_MemoryStorage", "__commonJSMin", "exports", "module", "Record", "RateLimiterRes", "key", "value", "durationSec", "msBeforeExpires", "durationMs", "require_RateLimiterMemory", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "MemoryStorage", "RateLimiterRes", "RateLimiterMemory", "opts", "key", "pointsToConsume", "options", "resolve", "reject", "rlKey", "secDuration", "res", "delay", "points", "msDuration", "initPoints", "require_RateLimiterCluster", "__commonJSMin", "exports", "module", "cluster", "crypto", "RateLimiterAbstract", "RateLimiterMemory", "RateLimiterRes", "channel", "masterInstance", "masterSendToWorker", "worker", "msg", "type", "res", "data", "workerWaitInit", "payload", "workerSendToMaster", "func", "promiseId", "key", "arg", "opts", "masterProcessMsg", "promise", "rejRes", "workerProcessMsg", "getOpts", "savePromise", "resolve", "reject", "hrtime", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "pm2", "err", "pm2Bus", "packet", "sendErr", "msgData", "pm2Message", "RateLimiterClusterWorker", "value", "pointsToConsume", "options", "points", "secDuration", "require_RateLimiterMemcache", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMemcache", "opts", "rlKey", "changedPoints", "result", "res", "points", "msDuration", "forceExpire", "options", "resolve", "reject", "nowMs", "secDuration", "err", "consumedPoints", "errAddKey", "createdNew", "nextOptions", "resUpsert", "errUpsert", "errGetExpire", "resGetExpireMs", "expireMs", "errDelExpire", "require_RLWrapperBlackAndWhite", "__commonJSMin", "exports", "module", "RateLimiterRes", "opts", "value", "func", "key", "pointsToConsume", "res", "secDuration", "points", "require_RateLimiterUnion", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "limiters", "limiter", "key", "points", "resolve", "reject", "promises", "rej", "res", "resObj", "rejected", "item", "i", "require_RateLimiterQueueError", "__commonJSMin", "exports", "module", "message", "extra", "require_RateLimiterQueue", "__commonJSMin", "exports", "module", "RateLimiterQueueError", "MAX_QUEUE_SIZE", "KEY_DEFAULT", "limiterFlexible", "opts", "RateLimiterQueueInternal", "key", "tokens", "rlRes", "_this", "resolve", "reject", "res", "rej", "item", "require_BurstyRateLimiter", "__commonJSMin", "exports", "module", "RateLimiterRes", "rateLimiter", "burstLimiter", "rlRes", "blRes", "key", "pointsToConsume", "options", "rlRej", "blRej", "require_rate_limiter_flexible", "__commonJSMin", "exports", "module", "RateLimiterRedis", "RateLimiterMongo", "RateLimiterMySQL", "RateLimiterPostgres", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "RateLimiterCluster", "RateLimiterMemory", "RateLimiterMemcache", "RLWrapperBlackAndWhite", "RateLimiterUnion", "RateLimiterQueue", "BurstyRateLimiter", "RateLimiterRes", "require_netmask", "__commonJSMin", "exports", "Netmask", "atob", "chr", "chr0", "chrA", "chra", "ip2long", "long2ip", "long", "a", "b", "c", "d", "ip", "i", "j", "n", "ref", "s", "base", "dmax", "start", "net", "mask", "error", "error1", "count", "fn", "index", "lastLong", "require_ipaddr", "__commonJSMin", "exports", "module", "root", "ipv4Part", "ipv4Regexes", "octalRegex", "hexRegex", "zoneIndex", "ipv6Part", "ipv6Regexes", "expandIPv6", "string", "parts", "colonCount", "lastColon", "zoneId", "replacement", "replacementCount", "ref", "results", "i", "matchCIDR", "first", "second", "partSize", "cidrBits", "part", "shift", "parseIntAuto", "padPart", "length", "ipaddr", "IPv4", "octets", "octet", "other", "cidrRange", "cidr", "stop", "zerotable", "zeros", "ipInterfaceOctets", "subnetMaskOctets", "match", "maskLength", "parsed", "value", "prefix", "j", "filledOctetCount", "IPv6", "bytes", "addr", "suffix", "high", "low", "regex", "bestMatchIndex", "bestMatchLength", "e", "address", "rangeList", "defaultName", "rangeName", "rangeSubnets", "subnet", "require_truncate", "__commonJSMin", "exports", "module", "isHighSurrogate", "codePoint", "isLowSurrogate", "getLength", "string", "byteLength", "charLength", "curByteLength", "segment", "i", "require_browser", "__commonJSMin", "exports", "module", "isHighSurrogate", "codePoint", "isLowSurrogate", "string", "charLength", "byteLength", "prevCodePoint", "i", "require_browser", "__commonJSMin", "exports", "module", "truncate", "getLength", "require_sanitize_filename", "__commonJSMin", "exports", "module", "truncate", "illegalRe", "controlRe", "reservedRe", "windowsReservedRe", "windowsTrailingRe", "sanitize", "input", "replacement", "sanitized", "options", "output", "require_pkcs7asn1", "__commonJSMin", "exports", "module", "forge", "asn1", "p7v", "contentInfoValidator", "encryptedContentInfoValidator", "signerValidator", "require_mgf1", "__commonJSMin", "exports", "module", "forge", "mgf1", "md", "mgf", "seed", "maskLen", "t", "len", "i", "c", "require_mgf", "__commonJSMin", "exports", "module", "forge", "require_pss", "__commonJSMin", "exports", "module", "forge", "pss", "options", "hash", "mgf", "hLen", "salt_", "sLen", "prng", "pssobj", "md", "modBits", "i", "emBits", "emLen", "mHash", "salt", "m_", "h", "ps", "db", "maskLen", "dbMask", "maskedDB", "mask", "em", "checkLen", "h_", "require_x509", "__commonJSMin", "exports", "module", "forge", "asn1", "pki", "oids", "_shortNames", "publicKeyValidator", "x509CertificateValidator", "rsassaPssParameterValidator", "certificationRequestInfoValidator", "certificationRequestValidator", "rdn", "md", "rval", "set", "attr", "obj", "si", "i", "attributes", "seq", "type", "values", "vi", "ei", "_getAttribute", "options", "_readSignatureParameters", "oid", "fillDefaults", "params", "capture", "errors", "error", "_createSignatureDigest", "_verifySignature", "cert", "scheme", "hash", "mgf", "pem", "computeHash", "strict", "msg", "maxline", "key", "bytes", "digest", "hex", "csr", "sn", "_fillMissingFields", "attrs", "uniqueId", "exts", "_fillMissingExtensionFields", "ext", "algorithmOid", "child", "issuer", "subject", "tbsCertificate", "parent", "s", "iattr", "sattr", "n", "ski", "serial", "validity", "imd", "ibytes", "smd", "sbytes", "extseq", "ev", "b2", "b3", "value", "gn", "altName", "cri", "_dnToAsn1", "valueTagClass", "e", "unused", "keyIdentifier", "authorityCertIssuer", "serialNumber", "subSeq", "fullNameGeneralNames", "_signatureParametersToAsn1", "parts", "_CRIAttributesToAsn1", "valueConstructed", "jan_1_1950", "jan_1_2050", "_dateToAsn1", "date", "notBefore", "notAfter", "tbs", "dn", "certs", "caStore", "getBySubject", "ensureSubjectHasHash", "tmp", "match", "der1", "der2", "certList", "result", "chain", "validityCheckDate", "first", "depth", "selfSigned", "parents", "verified", "se", "bcExt", "keyUsageExt", "pathLen", "vfd", "ret", "require_pkcs7", "__commonJSMin", "exports", "module", "forge", "asn1", "p7", "pem", "msg", "error", "obj", "maxline", "pemObj", "capture", "errors", "contentType", "_fromAsn1", "certs", "i", "crls", "signedData", "signer", "issuer", "serialNumber", "cert", "key", "digestAlgorithm", "authenticatedAttributes", "messageDigest", "attr", "options", "content", "mds", "addDigestAlgorithmIds", "addSignerInfos", "crl", "oid", "bytes", "signingTime", "attrsAsn1", "ai", "_attributeToAsn1", "_signersToAsn1", "_decryptContent", "_recipientsFromAsn1", "_recipientsToAsn1", "_encryptedContentToAsn1", "sAttr", "r", "rAttr", "match", "j", "recipient", "privKey", "cipher", "keyLen", "ivLen", "ciphFn", "ciph", "_recipientFromAsn1", "_recipientToAsn1", "infos", "ret", "recipients", "_signerToAsn1", "rval", "signers", "value", "jan_1_1950", "jan_1_2050", "date", "timestamp", "ec", "validator", "require_receptacle", "__commonJSMin", "exports", "module", "Receptacle", "toMS", "cache", "counter", "getUID", "options", "item", "ttl", "i", "key", "record", "value", "oldRecord", "ms", "items", "require_fixed_size", "__commonJSMin", "exports", "module", "hwm", "data", "last", "require_fast_fifo", "__commonJSMin", "exports", "module", "FixedFIFO", "hwm", "val", "prev", "next", "require_p_defer", "__commonJSMin", "exports", "module", "pDefer", "deferred", "resolve", "reject", "require_p_fifo", "__commonJSMin", "exports", "module", "Fifo", "defer", "chunk", "promise", "resolve", "nextConsumer", "nextChunk", "require_safe_buffer", "__commonJSMin", "exports", "module", "buffer", "Buffer", "copyProps", "src", "dst", "key", "SafeBuffer", "arg", "encodingOrOffset", "length", "size", "fill", "encoding", "buf", "require_browser", "__commonJSMin", "exports", "module", "MAX_BYTES", "MAX_UINT32", "oldBrowser", "Buffer", "crypto", "randomBytes", "size", "cb", "bytes", "generated", "require_k_bucket", "__commonJSMin", "exports", "module", "randomBytes", "EventEmitter", "arrayEquals", "array1", "array2", "i", "length", "createNode", "ensureInt8", "name", "val", "KBucket", "options", "incumbent", "candidate", "firstId", "secondId", "distance", "min", "max", "contact", "bitIndex", "node", "index", "id", "n", "contacts", "nodes", "detNode", "a", "b", "count", "bytesDescribedByBitIndex", "bitIndexWithinByte", "otherNode", "result", "selection", "require_ipaddr", "__commonJSMin", "exports", "module", "root", "ipv4Part", "ipv4Regexes", "octalRegex", "hexRegex", "zoneIndex", "ipv6Part", "ipv6Regexes", "expandIPv6", "string", "parts", "colonCount", "lastColon", "zoneId", "replacement", "replacementCount", "ref", "results", "i", "matchCIDR", "first", "second", "partSize", "cidrBits", "part", "shift", "parseIntAuto", "padPart", "length", "ipaddr", "IPv4", "octets", "octet", "other", "cidrRange", "cidr", "stop", "zerotable", "zeros", "ipInterfaceOctets", "subnetMaskOctets", "match", "maskLength", "parsed", "value", "prefix", "j", "filledOctetCount", "IPv6", "bytes", "addr", "suffix", "high", "low", "regex", "bestMatchIndex", "bestMatchLength", "e", "address", "rangeList", "defaultName", "rangeName", "rangeSubnets", "subnet", "require_event_iterator", "__commonJSMin", "exports", "EventQueue", "value", "resolution", "placeholder", "error", "rejection", "result", "resolve", "reject", "EventIterator", "listen", "highWaterMark", "lowWaterMark", "queue", "event", "fn", "require_dom", "__commonJSMin", "exports", "event_iterator_1", "subscribe", "event", "options", "evOptions", "push", "require_RateLimiterAbstract", "__commonJSMin", "exports", "module", "opts", "value", "options", "key", "rlKey", "require_BlockedKeys", "__commonJSMin", "exports", "module", "now", "key", "sec", "ms", "expire", "require_BlockedKeys", "__commonJSMin", "exports", "module", "BlockedKeys", "require_RateLimiterRes", "__commonJSMin", "exports", "module", "remainingPoints", "msBeforeNext", "consumedPoints", "isFirstInDuration", "ms", "p", "value", "require_RateLimiterStoreAbstract", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "BlockedKeys", "RateLimiterRes", "opts", "value", "resolve", "reject", "rlKey", "changedPoints", "storeResult", "options", "res", "blockPromise", "err", "delay", "funcName", "key", "data", "secDuration", "msDuration", "points", "pointsToConsume", "inMemoryBlockMsBeforeExpire", "initPoints", "forceExpire", "require_RateLimiterRedis", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "incrTtlLuaScript", "RateLimiterRedis", "opts", "rlKey", "changedPoints", "result", "consumed", "resTtlMs", "res", "points", "msDuration", "forceExpire", "resolve", "reject", "secDuration", "multi", "err", "incrCallback", "require_RateLimiterMongo", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "getDriverVersion", "client", "_client", "version", "_v", "v", "RateLimiterMongo", "opts", "conn", "value", "obj", "collection", "rlKey", "changedPoints", "result", "res", "doc", "key", "points", "msDuration", "forceExpire", "options", "docAttrs", "where", "upsertData", "upsertOptions", "resolve", "reject", "errUpsert", "replaceWhere", "replaceTo", "errReplace", "err", "require_RateLimiterMySQL", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMySQL", "opts", "cb", "err", "expire", "resolve", "conn", "reject", "errConn", "errDb", "value", "rlKey", "changedPoints", "result", "res", "row", "key", "points", "msDuration", "forceExpire", "errBegin", "dateNow", "newExpire", "q", "values", "errUpsert", "errSelect", "require_RateLimiterPostgres", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterPostgres", "opts", "cb", "err", "expire", "resolve", "q", "conn", "reject", "value", "constructorName", "rlKey", "changedPoints", "result", "res", "row", "queryObj", "key", "points", "msDuration", "forceExpire", "newExpire", "expireQ", "require_Record", "__commonJSMin", "exports", "module", "value", "expiresAt", "timeoutId", "require_MemoryStorage", "__commonJSMin", "exports", "module", "Record", "RateLimiterRes", "key", "value", "durationSec", "msBeforeExpires", "durationMs", "require_RateLimiterMemory", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "MemoryStorage", "RateLimiterRes", "RateLimiterMemory", "opts", "key", "pointsToConsume", "options", "resolve", "reject", "rlKey", "secDuration", "res", "delay", "points", "msDuration", "initPoints", "require_RateLimiterCluster", "__commonJSMin", "exports", "module", "cluster", "crypto", "RateLimiterAbstract", "RateLimiterMemory", "RateLimiterRes", "channel", "masterInstance", "masterSendToWorker", "worker", "msg", "type", "res", "data", "workerWaitInit", "payload", "workerSendToMaster", "func", "promiseId", "key", "arg", "opts", "masterProcessMsg", "promise", "rejRes", "workerProcessMsg", "getOpts", "savePromise", "resolve", "reject", "hrtime", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "pm2", "err", "pm2Bus", "packet", "sendErr", "msgData", "pm2Message", "RateLimiterClusterWorker", "value", "pointsToConsume", "options", "points", "secDuration", "require_RateLimiterMemcache", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMemcache", "opts", "rlKey", "changedPoints", "result", "res", "points", "msDuration", "forceExpire", "options", "resolve", "reject", "nowMs", "secDuration", "err", "consumedPoints", "errAddKey", "createdNew", "nextOptions", "resUpsert", "errUpsert", "errGetExpire", "resGetExpireMs", "expireMs", "errDelExpire", "require_RLWrapperBlackAndWhite", "__commonJSMin", "exports", "module", "RateLimiterRes", "opts", "value", "func", "key", "pointsToConsume", "res", "secDuration", "points", "require_RateLimiterUnion", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "limiters", "limiter", "key", "points", "resolve", "reject", "promises", "rej", "res", "resObj", "rejected", "item", "i", "require_RateLimiterQueueError", "__commonJSMin", "exports", "module", "message", "extra", "require_RateLimiterQueue", "__commonJSMin", "exports", "module", "RateLimiterQueueError", "MAX_QUEUE_SIZE", "KEY_DEFAULT", "limiterFlexible", "opts", "RateLimiterQueueInternal", "key", "tokens", "rlRes", "_this", "resolve", "reject", "res", "rej", "item", "require_BurstyRateLimiter", "__commonJSMin", "exports", "module", "RateLimiterRes", "rateLimiter", "burstLimiter", "rlRes", "blRes", "key", "pointsToConsume", "options", "rlRej", "blRej", "require_rate_limiter_flexible", "__commonJSMin", "exports", "module", "RateLimiterRedis", "RateLimiterMongo", "RateLimiterMySQL", "RateLimiterPostgres", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "RateLimiterCluster", "RateLimiterMemory", "RateLimiterMemcache", "RLWrapperBlackAndWhite", "RateLimiterUnion", "RateLimiterQueue", "BurstyRateLimiter", "RateLimiterRes", "isSerializableHash", "h", "exports", "select", "subject", "resultIfOne", "resultIfZero", "exports", "lessOrEqual", "a", "b", "compare", "result", "i", "equal", "wipe", "array", "i", "exports", "hash_1", "constant_time_1", "wipe_1", "HMAC", "hash", "key", "pad", "data", "out", "savedState", "exports", "hmac", "h", "digest", "hmac_1", "wipe_1", "HKDF", "hash", "key", "salt", "info", "okm", "ctr", "length", "out", "i", "exports", "QUOTA", "BrowserRandomSource", "browserCrypto", "length", "out", "i", "exports", "wipe_1", "NodeRandomSource", "__require", "nodeCrypto", "length", "buffer", "out", "exports", "browser_1", "node_1", "SystemRandomSource", "length", "exports", "imulShim", "a", "b", "ah", "al", "bh", "bl", "exports", "add", "sub", "rotl", "x", "n", "rotr", "isIntegerShim", "int_1", "readInt16BE", "array", "offset", "exports", "readUint16BE", "readInt16LE", "readUint16LE", "writeUint16BE", "value", "out", "writeUint16LE", "readInt32BE", "readUint32BE", "readInt32LE", "readUint32LE", "writeUint32BE", "writeUint32LE", "readInt64BE", "hi", "lo", "readUint64BE", "readInt64LE", "readUint64LE", "writeUint64BE", "writeUint64LE", "readUintBE", "bitLength", "result", "mul", "i", "readUintLE", "writeUintBE", "div", "writeUintLE", "readFloat32BE", "view", "readFloat32LE", "readFloat64BE", "readFloat64LE", "writeFloat32BE", "writeFloat32LE", "writeFloat64BE", "writeFloat64LE", "system_1", "binary_1", "wipe_1", "exports", "randomBytes", "length", "prng", "randomUint32", "buf", "result", "ALPHANUMERIC", "randomString", "charset", "out", "charsLen", "maxByte", "i", "randomByte", "randomStringForEntropy", "bits", "random_1", "wipe_1", "exports", "gf", "init", "r", "i", "_9", "_121665", "car25519", "o", "c", "v", "sel25519", "p", "q", "b", "t", "pack25519", "n", "m", "j", "unpack25519", "add", "a", "sub", "mul", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10", "t11", "t12", "t13", "t14", "t15", "t16", "t17", "t18", "t19", "t20", "t21", "t22", "t23", "t24", "t25", "t26", "t27", "t28", "t29", "t30", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10", "b11", "b12", "b13", "b14", "b15", "square", "inv25519", "inp", "scalarMult", "z", "x", "d", "e", "f", "x32", "x16", "scalarMultBase", "generateKeyPairFromSeed", "seed", "secretKey", "generateKeyPair", "prng", "result", "sharedKey", "mySecretKey", "theirPublicKey", "rejectZero", "zeros", "binary_1", "wipe_1", "exports", "SHA256", "data", "dataLength", "dataPos", "hashBlocks", "out", "bytesHashed", "left", "bitLenHi", "bitLenLo", "padLength", "i", "savedState", "K", "w", "v", "p", "pos", "len", "a", "b", "c", "d", "e", "f", "g", "j", "u", "t1", "t2", "hash", "h", "digest", "binary_1", "wipe_1", "ROUNDS", "core", "out", "input", "key", "j0", "j1", "j2", "j3", "j4", "j5", "j6", "j7", "j8", "j9", "j10", "j11", "j12", "j13", "j14", "j15", "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "i", "streamXOR", "nonce", "src", "dst", "nonceInplaceCounterLength", "nc", "counterLength", "block", "j", "incrementCounter", "exports", "stream", "counter", "pos", "len", "carry", "constant_time_1", "wipe_1", "exports", "Poly1305", "key", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "m", "mpos", "bytes", "hibit", "h0", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "c", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "mac", "macpos", "g", "mask", "f", "i", "want", "oneTimeAuth", "data", "h", "digest", "equal", "a", "b", "chacha_1", "poly1305_1", "wipe_1", "binary_1", "constant_time_1", "exports", "ZEROS", "ChaCha20Poly1305", "key", "nonce", "plaintext", "associatedData", "dst", "counter", "authKey", "resultLength", "result", "sealed", "calculatedTag", "tagOut", "ciphertext", "h", "length", "tag", "i", "require_encode", "__commonJSMin", "exports", "module", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "require_decode", "__commonJSMin", "exports", "module", "read", "MSB", "REST", "buf", "offset", "res", "shift", "counter", "b", "l", "require_length", "__commonJSMin", "exports", "module", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "value", "require_varint", "__commonJSMin", "exports", "module", "require_src", "__commonJSMin", "exports", "module", "varint", "buf", "result", "num", "require_moving_average", "__commonJSMin", "exports", "module", "exp", "timespan", "ma", "v", "d", "f", "previousTime", "ret", "alpha", "t", "pt", "time", "value", "a", "diff", "incr", "require_textarea_caret", "__commonJSMin", "exports", "module", "properties", "isBrowser", "isFirefox", "getCaretCoordinates", "element", "position", "options", "debug", "el", "div", "style", "computed", "isInput", "prop", "span", "coordinates", "isArray", "what", "select", "selector", "what", "text", "value", "event", "htmlString", "content", "el", "isArray", "e", "newContent", "isElement", "li", "className", "classes", "cls", "shouldShow", "fn", "shouldDisable", "obj", "dom_default", "notificationTypes", "notification", "dom_default", "cleanNotificationClasses", "notificationFactory", "acc", "notificationType", "message", "Notification", "autohideDuration", "type", "notify", "notify_default", "welcomeUser", "lastVisit", "notify_default", "welcome_default", "storage", "key", "what", "attr", "current", "isArray", "acc", "k", "savedTxt", "word", "newDictionary", "w", "cleanText", "words", "distinctWords", "notify_default", "localstorage_default", "configuration", "getGist", "id", "token", "localstorage_default", "response", "getAuthenticatedUsersGists", "deleteFileOnGist", "fileName", "gistId", "responseAsJson", "notify_default", "updateGist", "notes", "getNotes", "noteToFiles", "acc", "text", "deleted", "createNewGist", "note", "getAuthToken", "code", "state", "configuration", "publishGist", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "base58_exports", "__export", "base58btc", "base58flickr", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "json_exports", "__export", "code", "decode", "encode", "name", "textEncoder", "textDecoder", "node", "data", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "hashBrowser", "val", "bytes", "encode", "hash", "sha256", "CID", "code", "hashBrowser_default", "isJSON", "str", "isJSON_default", "_getBasePageTitle", "setPageTitle", "what", "baseTitle", "dom_default", "resetPageTitle", "url", "currentParams", "params", "parametersObject", "key", "param", "searchParams", "p", "pathname", "hash", "pageId", "allParams", "newParams", "setSavedState", "saved", "dom_default", "encodeTitle", "title", "encodedTitle", "getDateCreatedFromTitle", "titleID", "getTitleId", "note", "getNote", "dateCreated", "markNoteForDeletion", "id", "url", "revision", "doc", "localstorage_default", "newerNote", "acc", "noteToReturn", "disableSyncOnCurrentNote", "value", "notify_default", "setNoteFromHash", "hash", "version", "dom_default", "setPageTitle", "resetNoteManager", "resetPageTitle", "setSavedState", "getTitle", "updateNote", "what", "existingNote", "saveNote", "text", "hashOfIncomingNote", "hashBrowser_default", "hashOfCurrentNote", "currentNote", "cid", "e", "getNotes", "includeDeleted", "body", "isJSON_default", "noteId", "deleted", "search", "q", "deleteNote", "deleteFileOnGist", "commander_default", "isUserLoggedIn", "localstorage_default", "command", "title", "secondary", "onclick", "onSecondaryClick", "icon", "selected", "li", "iconClone", "liContent", "isElement", "span", "secondaryElement", "commands", "commandsToGen", "selectedIndex", "props", "i", "command", "wordParts", "word", "match", "parts", "indexInWord", "acc", "part", "i", "p", "syllable", "start", "end", "mark", "word", "markEl", "div", "content", "highlight", "words", "wordsToHighlight", "matches", "wordToHighlight", "m", "match", "wordElements", "wordParts", "syllable", "w", "goAuthenticate", "notify_default", "commander_default", "configuration", "setGistToSyncWith", "token", "gists", "getAuthenticatedUsersGists", "gistOptions", "a", "b", "description", "updated_at", "id", "div", "localstorage_default", "syncNotesWithGitHub", "gistOptionComponents", "commands", "createNewGist", "error", "dom_default", "gistId", "files", "getGist", "content", "updateNote", "setAuthTokenFromCallback", "code", "url", "state", "getAuthToken", "getNewFileHandle", "title", "options", "writeFile", "fileHandle", "contents", "writable", "saveFileAs", "msg", "notify_default", "saveDataToFile", "a", "data", "fileName", "json", "blob", "url", "import_showdown", "converter", "showdown", "convertMarkDownToHtml", "md", "handleErrorResponse", "response", "wrapTemplate", "body", "configuration", "sendMail", "email", "subject", "notify_default", "localstorage_default", "getUserMailingPreferences", "savedMail", "mailSameAgainQuestion", "whoMailing", "wannaSaveDat", "mailTo", "what", "title", "getTitle", "htmlBody", "convertMarkDownToHtml", "copyToClipboard", "what", "message", "notify_default", "error", "button", "els", "fn", "id", "elements", "isArray", "element", "e", "markDownViewer", "dom_default", "url", "convertMarkDownToHtml", "el", "copyBtn", "button", "e", "codeToCopy", "copyToClipboard", "mode", "markDownViewer_default", "prettifyJSON", "selector", "el", "isJSON_default", "prettifiedJSON", "notify_default", "prettifyJSON_default", "sleep", "ms", "resolve", "icon", "svgIcon", "altText", "className", "image", "share", "note", "getNote", "currentUrl", "url", "error", "notify_default", "import_index", "merge_options_default", "mergeOptions", "import_env", "import_debug", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "debug", "v", "base58btc", "base32", "base64", "createDisabledLogger", "namespace", "logger", "name", "trace", "r", "n", "import_err_code", "import_err_code", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Data", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "c2", "d", "o", "n", "j", "valuesById", "values", "UnixTime", "Metadata", "PBData", "Data", "types", "dirTypes", "DEFAULT_FILE_MODE", "DEFAULT_DIRECTORY_MODE", "parseMode", "mode", "parseMtime", "input", "mtime", "ms", "secs", "errcode", "UnixFS", "marshaled", "message", "decoded", "data", "options", "type", "blockSizes", "hashType", "fanout", "parsedMode", "size", "index", "sum", "parsed", "pbData", "src_exports", "__export", "code", "createLink", "createNode", "decode", "encode", "name", "prepare", "validate", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "bytes_exports", "__export", "coerce", "empty", "equals", "fromHex", "fromString", "isBinary", "toHex", "toString", "d", "hex", "byte", "hexes", "b", "aa", "bb", "ii", "o", "str", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "__publicField", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "__publicField", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "_a", "CID", "version", "code", "multihash", "bytes", "__publicField", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "textDecoder", "decodeVarint", "bytes", "offset", "v", "shift", "b", "decodeBytes", "byteLen", "postOffset", "decodeKey", "index", "wire", "decodeLink", "link", "l", "wireType", "fieldNum", "byts", "decodeNode", "links", "linksBeforeData", "data", "node", "textEncoder", "maxInt32", "maxUInt32", "encodeLink", "link", "bytes", "i", "encodeVarint", "nameBytes", "encodeNode", "node", "size", "sizeNode", "index", "sizeLink", "n", "l", "sov", "offset", "v", "base", "x", "len64", "len8tab", "pbNodeProperties", "pbLinkProperties", "textEncoder", "linkComparator", "a", "b", "abuf", "bbuf", "x", "y", "i", "len", "hasOnlyProperties", "node", "properties", "p", "asLink", "link", "Hash", "CID", "pbl", "cid", "e", "prepare", "pbn", "validate", "createNode", "data", "links", "createLink", "name", "size", "toByteView", "buf", "name", "code", "encode", "node", "validate", "pbn", "l", "link", "encodeNode", "decode", "bytes", "buf", "toByteView", "decodeNode", "CID", "src_exports", "__export", "code", "decode", "decodeOptions", "encode", "encodeOptions", "name", "toByteView", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "str", "out", "p", "c", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "length", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "i", "key", "Type", "tagged", "decodeFirst", "decoded", "decode", "remainder", "CID_CBOR_TAG", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "bytes", "Token", "Type", "undefinedEncoder", "numberEncoder", "num", "_encodeOptions", "encodeOptions", "cidDecoder", "_decodeOptions", "decodeOptions", "name", "code", "encode", "node", "decode", "data", "src_exports", "__export", "code", "decode", "encode", "format", "name", "parse", "JSONEncoder", "buf", "recurs", "Type", "token", "is", "isa", "i", "_buf", "_token", "encodeErrPrefix", "byts", "fromString", "asU8A", "dp", "mapSorter", "e1", "e2", "keyToken1", "keyToken2", "defaultEncodeOptions", "encode", "data", "options", "encodeCustom", "Tokenizer", "data", "options", "c", "str", "decodeErrPrefix", "i", "startPos", "negative", "float", "swallow", "chars", "ch", "Token", "Type", "numStr", "num", "l", "readu4", "u4", "readUtf8Char", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "ch1", "decodeCodePointsArray", "token", "decode", "from", "name", "code", "encode", "Hasher", "__publicField", "input", "result", "create", "digest", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "cidString", "Token", "Type", "bytesEncoder", "bytes", "bytesString", "base64", "taBytesEncoder", "abBytesEncoder", "ab", "undefinedEncoder", "numberEncoder", "num", "encodeOptions", "DagJsonTokenizer", "Tokenizer", "data", "options", "token", "keyToken", "valueToken", "innerKeyToken", "innerValueToken", "i", "decodeOptions", "name", "code", "encode", "node", "decode", "format", "utf8Decoder", "utf8Decoder", "parse", "data", "decode", "utf8Encoder", "lib_exports", "__export", "code", "decode", "encode", "name", "toGeneral", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "bytes_exports", "__export", "coerce", "empty", "equals", "fromHex", "fromString", "isBinary", "toHex", "toString", "d", "hex", "byte", "hexes", "b", "aa", "bb", "ii", "o", "str", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "toBase64url", "b", "base64url", "fromBase64url", "s", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "fromSplit", "split", "protectedHeader", "payload", "signature", "CID", "fromBase64url", "encodeSignature", "encoded", "encode", "jws", "decodeSignature", "sign", "toBase64url", "decode", "decoded", "fromSplit", "split", "protectedHeader", "encrypted_key", "iv", "ciphertext", "tag", "jwe", "encodeRecipient", "recipient", "encRec", "fromBase64url", "encode", "encJwe", "decodeRecipient", "encoded", "toBase64url", "decode", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "string", "units", "codePoint", "length", "leadSurrogate", "bytes", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "length", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "i", "key", "Type", "tagged", "decode", "decoded", "CID_CBOR_TAG", "cidEncoder", "obj", "cid", "CID", "bytes", "Token", "Type", "undefinedEncoder", "numberEncoder", "num", "encodeOptions", "cidDecoder", "decodeOptions", "code", "encode", "node", "encodeOptions", "decode", "data", "decodeOptions", "name", "code", "isDagJWS", "jose", "isEncodedJWS", "isEncodedJWE", "isDagJWE", "toGeneral", "split", "fromSplit", "encode", "obj", "encodedJose", "decode", "data", "encoded", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "base2_exports", "__export", "base2", "base2", "rfc4648", "base8_exports", "__export", "base8", "base8", "rfc4648", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "raw_exports", "__export", "code", "decode", "encode", "name", "name", "code", "encode", "node", "coerce", "decode", "data", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "codecs", "raw_exports", "json_exports", "NotInitializedError", "message", "AlreadyInitializingError", "AlreadyInitializedError", "NotStartedError", "AlreadyStartingError", "AlreadyStartedError", "NotEnabledError", "asUint8Array", "buf", "base10_exports", "__export", "base10", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "allocUnsafe", "size", "_a", "asUint8Array", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "asUint8Array", "import_timeout_abort_controller", "equals", "a", "b", "i", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "sha2_browser_exports", "__export", "sha256", "sha512", "sha", "name", "data", "sha256", "from", "sha512", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "alloc", "size", "allocUnsafe", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "toString", "array", "encoding", "base", "bases_default", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "MSB", "REST", "encodingLength", "value", "encodeUint8Array", "buf", "offset", "encodeUint8ArrayList", "decodeUint8Array", "b", "res", "decodeUint8ArrayList", "encode", "allocUnsafe", "decode", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "Parser", "__publicField", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "parseIP", "maxIPv6Octet", "ipv4Prefix", "fromString", "string", "encoding", "base", "bases_default", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "isIP", "parseIP", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "ip4Protocol", "getProtocol", "ip6Protocol", "ipcidrProtocol", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "toString", "convertToBytes", "str", "ip2bytes", "str2bytes", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "fromString", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ip2bytes", "ipString", "isIP", "toBytes", "bytes2ip", "ipBuff", "toString", "port2bytes", "port", "buf", "bytes2port", "str2bytes", "str", "fromString", "size", "encode", "concat", "bytes2str", "decode", "encodingLength", "mh2bytes", "hash", "mh", "base58btc", "CID", "mb2bytes", "mbstr", "mb", "bytes2mb", "bytes2mh", "address", "onion2bytes", "addr", "base32", "portBuf", "onion32bytes", "bytes2onion", "addrBytes", "portBytes", "stringToMultiaddrParts", "str", "cleanPath", "tuples", "stringTuples", "path", "parts", "p", "part", "proto", "getProtocol", "ParseError", "convertToBytes", "bytes", "convertToString", "stringTuplesToString", "tuplesToBytes", "bytesToMultiaddrParts", "code", "decode", "n", "encodingLength", "size", "sizeForAddr", "addr", "toString", "stringAddr", "tup", "concat", "buf", "encode", "cleanPath", "str", "a", "ParseError", "inspect", "symbol", "DNS_CODES", "getProtocol", "NoAvailableResolverError", "message", "_string", "_tuples", "_stringTuples", "_path", "_a", "_Multiaddr", "addr", "__publicField", "__privateAdd", "parts", "bytesToMultiaddrParts", "stringToMultiaddrParts", "isMultiaddr", "__privateSet", "__privateGet", "family", "transport", "host", "port", "zone", "tcp", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "value", "addrString", "s", "tuples", "i", "tuplesToBytes", "name", "names", "tuple", "peerIdStr", "toString", "base58btc", "CID", "equals", "options", "resolvableProto", "p", "resolver", "resolvers", "str", "multiaddr", "protos", "Multiaddr", "resolvers", "isMultiaddr", "value", "symbol", "multiaddr", "addr", "Multiaddr", "DNS4", "base", "DNS6", "DNSADDR", "DNS", "or", "IP", "TCP", "and", "UDP", "UTP", "QUIC", "QUICV1", "_WebSockets", "WebSockets", "_WebSocketsSecure", "WebSocketsSecure", "HTTP", "HTTPS", "_WebRTCDirect", "WebRTCDirect", "_WebTransport", "WebTransport", "P2PWebRTCStar", "WebSocketStar", "P2PWebRTCDirect", "Reliable", "Stardust", "_P2P", "_Circuit", "CircuitRecursive", "Circuit", "P2P", "WebRTC", "or", "and", "Circuit", "base", "Reliable", "makeMatchesFunction", "partialMatch", "matches", "a", "ma", "multiaddr", "out", "args", "arg", "res", "n", "name", "pnames", "protos", "import_iso_url", "pathPattern", "defaultProtocolMatch", "defaultHashMath", "subdomainGatewayPattern", "fqdnWithTld", "isCID", "hash", "isString", "CID", "isIpfs", "input", "pattern", "protocolMatch", "defaultProtocolMatch", "hashMatch", "defaultHashMath", "formatted", "convertToString", "match", "hash", "subdomainGatewayPattern", "isCID", "isIpns", "ipnsId", "hostname", "fqdnWithTld", "isString", "toString", "path", "isIpfs", "pathPattern", "isIpns", "ipfsPath", "path", "isIpfs", "pathPattern", "ipnsPath", "isIpns", "nanoid", "size", "id", "byte", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "base2_exports", "__export", "base2", "base2", "rfc4648", "base8_exports", "__export", "base8", "base8", "rfc4648", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "code", "textEncoder", "textDecoder", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "asUint8Array", "buf", "alloc", "size", "_a", "asUint8Array", "allocUnsafe", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "toString", "array", "encoding", "base", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "asUint8Array", "pathSepS", "pathSepB", "pathSep", "Key", "s", "clean", "fromString", "encoding", "toString", "list", "nanoid", "other", "bytes", "key", "list1", "list2", "c1", "c2", "ns", "namespaceType", "namespaceValue", "p", "keys", "flatten", "parts", "arr", "import_err_code", "import_timeout_abort_controller", "import_any_signal", "durationRE", "parse", "str", "format", "result", "isNegative", "_", "n", "units", "unitRatio", "parse_duration_default", "TimeoutError", "message", "withTimeoutOption", "fn", "optionsArgIndex", "args", "options", "timeout", "parse_duration_default", "controller", "fnRes", "timeoutPromise", "_resolve", "reject", "TimeoutError", "start", "maybeThrowTimeoutError", "it", "value", "done", "err", "res", "import_err_code", "IPFS_PREFIX", "toCidAndPath", "string", "CID", "err", "errCode", "cid", "parts", "path", "ERR_BAD_PATH", "OFFLINE_ERROR", "MFS_ROOT_KEY", "Key", "MFS_MAX_CHUNK_SIZE", "normalizePath", "pathStr", "CID", "str", "path", "errCode", "ERR_BAD_PATH", "normalizeCidPath", "resolvePath", "repo", "codecs", "ipfsPath", "options", "cid", "toCidAndPath", "lastCid", "lastRemainderPath", "value", "remainderPath", "resolve", "err", "mapFile", "file", "output", "withTimeout", "withTimeoutOption", "promise", "_options", "load", "codec", "block", "parts", "key", "code", "link", "l", "Service", "start", "stop", "service", "options", "state", "activate", "promise", "result", "error", "AlreadyStartingError", "AlreadyStartedError", "deactivate", "withTimeout", "NotStartedError", "status", "createStart", "network", "preload", "peerId", "keychain", "repo", "ipns", "mfsPreload", "print", "hashers", "options", "libp2p", "Service", "createStop", "network", "preload", "ipns", "repo", "mfsPreload", "Service", "import_hashlru", "TLRU", "maxSize", "hashlru", "key", "value", "ttl", "import_index", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "milliseconds", "fallback", "options", "timer", "cancelablePromise", "resolve", "reject", "error", "timeoutError", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "__classPrivateFieldGet", "receiver", "state", "kind", "f", "_PriorityQueue_queue", "PriorityQueue", "run", "options", "element", "index", "lowerBound", "a", "b", "item", "priority_queue_default", "__classPrivateFieldSet", "receiver", "state", "value", "kind", "f", "__classPrivateFieldGet", "_PQueue_instances", "_PQueue_carryoverConcurrencyCount", "_PQueue_isIntervalIgnored", "_PQueue_intervalCount", "_PQueue_intervalCap", "_PQueue_interval", "_PQueue_intervalEnd", "_PQueue_intervalId", "_PQueue_timeoutId", "_PQueue_queue", "_PQueue_queueClass", "_PQueue_pending", "_PQueue_concurrency", "_PQueue_isPaused", "_PQueue_throwOnTimeout", "_PQueue_doesIntervalAllowAnother_get", "_PQueue_doesConcurrentAllowAnother_get", "_PQueue_next", "_PQueue_onResumeInterval", "_PQueue_isIntervalPaused_get", "_PQueue_tryToStartAnother", "_PQueue_initializeIntervalIfNeeded", "_PQueue_onInterval", "_PQueue_processQueue", "_PQueue_throwOnAbort", "_PQueue_onEvent", "AbortError", "PQueue", "EventEmitter", "options", "_a", "_b", "_c", "_d", "priority_queue_default", "newConcurrency", "function_", "resolve", "reject", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "limit", "now", "delay", "canInitializeInterval", "job", "signal", "_resolve", "event", "filter", "listener", "dist_default", "import_http", "cache", "TLRU", "ttl", "Queue", "dist_default", "httpQueue", "ipfsPath", "response", "resolveDnslink", "fqdn", "opts", "searchParams", "query", "res", "HTTP", "json", "fqdnFixups", "domain", "createDns", "withTimeoutOption", "options", "resolveDnslink", "createIsOnline", "network", "net", "symbol", "isPeerId", "other", "_AbortError", "message", "__publicField", "AbortError", "CodeError", "code", "props", "equals", "a", "b", "i", "inspect", "baseDecoder", "bases", "codec", "acc", "curr", "LIBP2P_KEY_CODE", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "_a", "PeerIdImpl", "init", "__publicField", "base58btc", "CID", "id", "equals", "peerIdFromString", "symbol", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "peerIdFromString", "str", "decoder", "baseDecoder", "multihash", "decode", "base58btc", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "RSAPeerIdImpl", "peerIdFromBytes", "buf", "identity", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "sha256", "peerIdFromCID", "CID", "cid", "LIBP2P_KEY_CODE", "peerIdFromKeys", "publicKey", "privateKey", "create", "createResolve", "repo", "codecs", "bases", "name", "resolve", "path", "opts", "ipnsPath", "resolvedPath", "schema", "hash", "rest", "base", "bytes", "parseBytes", "str", "cid", "CID", "results", "value", "remainderPath", "result", "withTimeoutOption", "peerIdFromString", "last", "source", "res", "entry", "createAdd", "addAll", "path", "options", "iter", "cid", "CID", "last", "import_err_code", "isIterable", "thing", "isAsyncIterable", "isCID", "CID", "normaliseInput", "input", "errCode", "cid", "toPin", "iterator", "first", "path", "obj", "pin", "PinTypes", "createAddAll", "repo", "codecs", "addAll", "source", "options", "pinAdd", "path", "recursive", "metadata", "normaliseInput", "cid", "resolvePath", "reason", "PinTypes", "release", "withTimeoutOption", "import_err_code", "toPin", "type", "cid", "metadata", "output", "createLs", "repo", "codecs", "ls", "options", "PinTypes", "errCode", "matched", "path", "normaliseInput", "resolvePath", "reason", "pinned", "parent", "withTimeoutOption", "createRm", "rmAll", "rm", "path", "options", "cid", "last", "createRmAll", "repo", "codecs", "rmAll", "source", "_options", "release", "path", "recursive", "normaliseInput", "cid", "resolvePath", "pinned", "reason", "PinTypes", "withTimeoutOption", "PinAPI", "codecs", "repo", "addAll", "createAddAll", "createAdd", "rmAll", "createRmAll", "createRm", "createLs", "cid", "options", "query", "name", "credentials", "import_err_code", "errors_exports", "__export", "abortedError", "dbDeleteFailedError", "dbOpenFailedError", "dbWriteFailedError", "notFoundError", "import_err_code", "err", "errCode", "import_err_code", "toString", "array", "encoding", "base", "bases_default", "import_timestamp_nano", "keys_exports", "__export", "ephemeral_keys_default", "generateKeyPair", "generateKeyPairFromSeed", "importKey", "keyStretcher", "marshalPrivateKey", "marshalPublicKey", "supportedKeys", "unmarshalPrivateKey", "unmarshalPublicKey", "import_asn1", "import_pbe", "import_forge", "ed25519_class_exports", "__export", "Ed25519PrivateKey", "Ed25519PublicKey", "generateKeyPair", "generateKeyPairFromSeed", "unmarshalEd25519PrivateKey", "unmarshalEd25519PublicKey", "nodeCrypto", "_0n", "_1n", "_2n", "_8n", "CU_O", "CURVE", "POW_2_256", "SQRT_M1", "SQRT_D", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "ExtendedPoint", "x", "y", "z", "t", "p", "Point", "_1n", "mod", "points", "toInv", "invertBatch", "other", "assertExtPoint", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "a", "CURVE", "A", "B", "C", "_2n", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "_0n", "W", "windows", "base", "window", "i", "n", "affinePoint", "precomputes", "pointPrecomputes", "f", "windowSize", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "constTimeNegate", "scalar", "normalizeScalar", "P0", "d", "invZ", "is0", "_8n", "invert", "ax", "ay", "zz", "legacyRist", "condition", "item", "neg", "assertRstPoint", "RistrettoPoint", "ep", "r0", "r", "Ns", "c", "Ns_D_is_sq", "s", "uvRatio", "s_", "edIsNegative", "Nt", "s2", "W0", "W1", "W2", "W3", "hex", "ensureBytes", "r1", "bytes255ToNumberLE", "R1", "r2", "R2", "emsg", "equalBytes", "numberTo32BytesLE", "u1", "u2", "u1_2", "u2_2", "v", "isValid", "I", "invertSqrt", "Dx", "Dy", "u2sq", "invsqrt", "D1", "D2", "zInv", "_x", "_y", "bytesToHex", "b", "one", "two", "strict", "P", "normed", "bytesToNumberLE", "y2", "u", "isXOdd", "privateKey", "getExtendedPublicKey", "bytes", "Signature", "u8", "concatBytes", "arrays", "a", "length", "arr", "result", "i", "pad", "hexes", "v", "bytesToHex", "uint8a", "hex", "hexToBytes", "array", "j", "hexByte", "byte", "numberTo32BytesBE", "num", "numberTo32BytesLE", "edIsNegative", "mod", "_1n", "bytesToNumberLE", "MAX_255B", "bytes255ToNumberLE", "bytes", "b", "CURVE", "res", "_0n", "invert", "number", "modulo", "x", "y", "u", "q", "r", "m", "n", "invertBatch", "nums", "p", "tmp", "lastMultiplied", "acc", "inverted", "pow2", "power", "P", "pow_2_252_3", "_5n", "_10n", "_20n", "_40n", "_80n", "b2", "b4", "_2n", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "uvRatio", "v3", "v7", "pow", "vx2", "root1", "root2", "SQRT_M1", "useRoot1", "useRoot2", "noRoot", "invertSqrt", "modlLE", "hash", "equalBytes", "b1", "ensureBytes", "expectedLength", "normalizeScalar", "max", "strict", "adjustBytes25519", "checkPrivateKey", "key", "numberTo32BytesBE", "normalizeScalar", "POW_2_256", "ensureBytes", "getKeyFromHash", "hashed", "head", "adjustBytes25519", "prefix", "scalar", "modlLE", "point", "Point", "pointBytes", "_sha512Sync", "getExtendedPublicKey", "key", "getKeyFromHash", "utils", "checkPrivateKey", "getPublicKey", "privateKey", "getExtendedPublicKey", "sign", "message", "privateKey", "ensureBytes", "prefix", "scalar", "pointBytes", "getExtendedPublicKey", "r", "modlLE", "utils", "R", "Point", "k", "s", "mod", "CURVE", "Signature", "prepareVerification", "sig", "message", "publicKey", "ensureBytes", "Point", "r", "s", "Signature", "SB", "ExtendedPoint", "finishVerification", "hashed", "k", "modlLE", "kA", "CURVE", "verify", "msg", "pub", "utils", "Point", "crypto", "nodeCrypto", "utils", "bytesToHex", "hexToBytes", "concatBytes", "getExtendedPublicKey", "mod", "invert", "hash", "ensureBytes", "bytesToNumberLE", "CURVE", "_1n", "bytesLength", "randomBytes", "messages", "message", "buffer", "windowSize", "point", "Point", "cached", "_2n", "_sha512Sync", "val", "PUBLIC_KEY_BYTE_LENGTH", "PRIVATE_KEY_BYTE_LENGTH", "KEYS_BYTE_LENGTH", "generateKey", "privateKeyRaw", "utils", "publicKey", "getPublicKey", "concatKeys", "generateKeyFromSeed", "seed", "KEYS_BYTE_LENGTH", "hashAndSign", "privateKey", "msg", "sign", "hashAndVerify", "sig", "verify", "PRIVATE_KEY_BYTE_LENGTH", "i", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "webcrypto_default", "win", "nativeCrypto", "derivedEmptyPasswordKey", "create", "opts", "algorithm", "keyLength", "nonceLength", "digest", "saltLength", "iterations", "crypto", "webcrypto_default", "encrypt", "data", "password", "salt", "nonce", "aesGcm", "fromString", "cryptoKey", "deriveParams", "runtimeDerivedEmptyPassword", "rawKey", "ciphertext", "concat", "decrypt", "plaintext", "exporter", "privateKey", "password", "encryptedKey", "create", "base64", "keys_exports", "__export", "KeyType", "PrivateKey", "PublicKey", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "lo", "hi", "__publicField", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "__publicField", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "pool", "size", "SIZE", "MAX", "slab", "offset", "allocUnsafe", "buf", "Op", "fn", "len", "val", "__publicField", "noop", "State", "writer", "bufferPool", "pool", "alloc", "size", "allocUnsafe", "Uint8ArrayWriter", "value", "VarintOp", "writeVarint64", "LongBits", "bits", "encodeUint8Array", "encodingLength", "writeByte", "writeFixed32", "writeFloatLE", "writeDoubleLE", "writeBytes", "length", "write", "head", "tail", "buf", "pos", "writeVarint32", "writeBytesBuffer", "writeStringBuffer", "fromString", "createWriter", "encodeMessage", "message", "codec", "w", "createWriter", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "Ed25519PublicKey", "key", "__publicField", "ensureKey", "PUBLIC_KEY_BYTE_LENGTH", "data", "sig", "hashAndVerify", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Ed25519PrivateKey", "publicKey", "PRIVATE_KEY_BYTE_LENGTH", "message", "hashAndSign", "PrivateKey", "encoding", "identity", "base58btc", "password", "format", "exporter", "CodeError", "unmarshalEd25519PrivateKey", "privateKeyBytes", "publicKeyBytes", "unmarshalEd25519PublicKey", "generateKeyPair", "privateKey", "generateKey", "generateKeyPairFromSeed", "seed", "generateKeyFromSeed", "length", "import_util", "import_jsbn", "import_forge", "bigIntegerToUintBase64url", "num", "len", "buf", "concat", "toString", "base64urlToBigInteger", "str", "base64urlToBuffer", "forge", "fromString", "bits", "curveTypes", "names", "generateEphmeralKeyPair", "curve", "CodeError", "pair", "webcrypto_default", "genSharedKey", "theirPub", "forcePrivate", "privateKey", "unmarshalPrivateKey", "key", "unmarshalPublicKey", "buffer", "publicKey", "marshalPublicKey", "curveLengths", "jwk", "byteLen", "concat", "base64urlToBuffer", "equals", "toString", "ephemeral_keys_default", "generateEphmeralKeyPair", "importer", "privateKey", "password", "encryptedKey", "base64", "create", "lengths_default", "hashTypes", "sign", "key", "data", "buf", "webcrypto_default", "create", "hashType", "secret", "hash", "lengths_default", "cipherMap", "keyStretcher", "cipherType", "hash", "secret", "cipher", "allowed", "CodeError", "cipherKeySize", "ivSize", "hmacKeySize", "seed", "fromString", "resultLength", "m", "create", "a", "result", "j", "b", "concat", "todo", "half", "resultBuffer", "r1", "r2", "createKey", "res", "rsa_class_exports", "__export", "RsaPrivateKey", "RsaPublicKey", "fromJwk", "generateKeyPair", "unmarshalRsaPrivateKey", "unmarshalRsaPublicKey", "import_forge", "import_sha512", "nodeCrypto", "_0n", "_1n", "_2n", "_3n", "_8n", "CURVE", "divNearest", "a", "b", "endo", "k", "n", "a1", "b1", "a2", "b2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "fieldLen", "groupLen", "hashLen", "compressedLen", "uncompressedLen", "weierstrass", "x", "a", "b", "CURVE", "x2", "mod", "x3", "USE_ENDOMORPHISM", "_0n", "ShaError", "message", "assertJacPoint", "other", "JacobianPoint", "y", "z", "p", "Point", "_1n", "points", "toInv", "invertBatch", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "Z1Z1", "Z2Z2", "U1", "U2", "S1", "S2", "A", "B", "C", "x1b", "D", "_2n", "E", "_3n", "F", "X3", "Y3", "_8n", "Z3", "H", "r", "HH", "HHH", "V", "scalar", "P0", "normalizeScalar", "d", "k1neg", "k1", "k2neg", "k2", "endo", "k1p", "k2p", "W", "windows", "base", "window", "i", "n", "affinePoint", "precomputes", "pointPrecomputes", "f", "windowSize", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "constTimeNegate", "point", "fake", "f1p", "f2p", "invZ", "is0", "invert", "iz1", "iz2", "iz3", "ax", "ay", "zz", "condition", "item", "neg", "bytes", "isShort", "bytesToNumber", "isValidFieldElement", "y2", "sqrtMod", "isYOdd", "fieldLen", "hex", "ensureBytes", "len", "header", "compressedLen", "uncompressedLen", "privateKey", "normalizePrivateKey", "msgHash", "signature", "recovery", "s", "normalizeSignature", "h", "truncateHash", "radj", "rinv", "u1", "u2", "prefix", "R", "numTo32bStr", "Q", "isCompressed", "hexToBytes", "msg", "left", "right", "P", "aP", "bQ", "sum", "sliceDER", "parseDERInt", "data", "bytesToHex", "res", "parseDERSignature", "sBytes", "rBytesLeft", "Signature", "arr", "name", "str", "hexToNumber", "isWithinCurveOrder", "HALF", "sHex", "numberToHexUnpadded", "rHex", "sHexL", "rHexL", "sLen", "rLen", "concatBytes", "arrays", "length", "result", "pad", "hexes", "v", "uint8a", "POW_2_256", "num", "numTo32b", "array", "j", "hexByte", "byte", "pow2", "power", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "rt", "number", "modulo", "u", "q", "m", "nums", "scratch", "lastMultiplied", "acc", "inverted", "bits2int_2", "delta", "groupLen", "hash", "truncateOnly", "_sha256Sync", "_hmacSha256Sync", "HmacDrbg", "hashLen", "qByteLen", "values", "utils", "seed", "out", "sl", "kmdToSig", "kBytes", "lowS", "k", "kinv", "sig", "key", "normalizePublicKey", "publicKey", "getPublicKey", "bits2int", "bytes", "slice", "fieldLen", "bytesToNumber", "bits2octets", "z1", "z2", "mod", "CURVE", "int2octets", "_0n", "num", "numTo32b", "initSigArgs", "msgHash", "privateKey", "extraEntropy", "h1", "ensureBytes", "d", "normalizePrivateKey", "seedArgs", "utils", "e", "seed", "concatBytes", "m", "finalizeSig", "recSig", "opts", "sig", "recovery", "der", "recovered", "hashed", "sign", "privKey", "drbg", "HmacDrbg", "hashLen", "groupLen", "kmdToSig", "vopts", "verify", "signature", "msgHash", "publicKey", "opts", "sig", "normalizeSignature", "ensureBytes", "r", "h", "truncateHash", "P", "normalizePublicKey", "n", "CURVE", "sinv", "invert", "u1", "mod", "u2", "R", "Point", "Point", "crypto", "nodeCrypto", "TAGGED_HASH_PREFIXES", "utils", "bytesToHex", "hexToBytes", "concatBytes", "mod", "invert", "privateKey", "normalizePrivateKey", "numTo32b", "hash", "ensureBytes", "minLen", "groupLen", "num", "bytesToNumber", "CURVE", "_1n", "bytesLength", "crypto", "randomBytes", "windowSize", "point", "Point", "cached", "_3n", "messages", "buffer", "createHash", "m", "key", "ckey", "message", "createHmac", "tag", "tagP", "tagH", "c", "_sha256Sync", "ShaError", "JacobianPoint", "val", "_hmacSha256Sync", "randomBytes", "length", "CodeError", "utils", "import_rsa", "import_forge", "convert", "key", "types", "base64urlToBigInteger", "jwk2priv", "forge", "jwk2pub", "rsa_utils_exports", "__export", "jwkToPkcs1", "jwkToPkix", "pkcs1ToJwk", "pkixToJwk", "import_asn1", "import_rsa", "import_forge", "pkcs1ToJwk", "bytes", "asn1", "forge", "toString", "privateKey", "bigIntegerToUintBase64url", "jwkToPkcs1", "jwk", "CodeError", "base64urlToBigInteger", "fromString", "pkixToJwk", "publicKey", "jwkToPkix", "generateKey", "bits", "pair", "webcrypto_default", "keys", "exportKey", "unmarshalPrivateKey", "key", "derivePublicFromPrivate", "hashAndSign", "key", "msg", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "exportKey", "pair", "CodeError", "derivePublicFromPrivate", "jwKey", "convertKey", "pub", "handle", "fkey", "jwk2pub", "jwk2priv", "fmsg", "toString", "fomsg", "fromString", "encrypt", "decrypt", "RsaPublicKey", "key", "__publicField", "data", "sig", "hashAndVerify", "rsa_utils_exports", "PublicKey", "KeyType", "bytes", "encrypt", "equals", "sha256", "RsaPrivateKey", "publicKey", "randomBytes", "message", "hashAndSign", "CodeError", "decrypt", "PrivateKey", "hash", "toString", "password", "format", "buffer", "forge", "asn1", "privateKey", "options", "exporter", "unmarshalRsaPrivateKey", "jwk", "keys", "unmarshalPrivateKey", "unmarshalRsaPublicKey", "fromJwk", "generateKeyPair", "bits", "generateKey", "secp256k1_class_exports", "__export", "Secp256k1PrivateKey", "Secp256k1PublicKey", "generateKeyPair", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKey", "utils", "hashAndSign", "key", "msg", "digest", "sha256", "sign", "err", "CodeError", "hashAndVerify", "sig", "verify", "compressPublicKey", "Point", "validatePrivateKey", "key", "getPublicKey", "err", "CodeError", "validatePublicKey", "Point", "computePublicKey", "privateKey", "Secp256k1PublicKey", "key", "__publicField", "validatePublicKey", "data", "sig", "hashAndVerify", "compressPublicKey", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Secp256k1PrivateKey", "publicKey", "computePublicKey", "validatePrivateKey", "message", "hashAndSign", "PrivateKey", "hash", "toString", "password", "format", "exporter", "CodeError", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKeyPair", "privateKeyBytes", "generateKey", "supportedKeys", "rsa_class_exports", "ed25519_class_exports", "secp256k1_class_exports", "unsupportedKey", "type", "supported", "CodeError", "typeToKey", "generateKeyPair", "bits", "generateKeyPairFromSeed", "seed", "unmarshalPublicKey", "buf", "decoded", "PublicKey", "data", "KeyType", "marshalPublicKey", "key", "unmarshalPrivateKey", "PrivateKey", "marshalPrivateKey", "importKey", "encryptedKey", "password", "importer", "forge", "der", "fromString", "import_err_code", "import_err_code", "ERR_IPNS_EXPIRED_RECORD", "ERR_UNRECOGNIZED_VALIDITY", "ERR_SIGNATURE_CREATION", "ERR_SIGNATURE_VERIFICATION", "ERR_UNRECOGNIZED_FORMAT", "ERR_UNDEFINED_PARAMETER", "ERR_INVALID_RECORD_DATA", "ERR_INVALID_EMBEDDED_KEY", "ERR_MISSING_PRIVATE_KEY", "import_reader", "import_reader_buffer", "import_writer", "import_writer_buffer", "import_minimal", "configure", "util", "ReaderClass", "ReaderBufferClass", "WriterClass", "WriterBufferClass", "methods", "patchReader", "obj", "method", "original", "reader", "buf", "patchWriter", "val", "writer", "decodeMessage", "buf", "codec", "r", "reader", "encodeMessage", "message", "codec", "w", "writer", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "IpnsEntry", "ValidityType", "__ValidityTypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "string", "units", "codePoint", "length", "leadSurrogate", "bytes", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "length", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "i", "key", "Type", "tagged", "decode", "decoded", "log", "logger", "IPNS_PREFIX", "fromString", "parseRFC3339", "time", "rfc3339Matcher", "m", "year", "month", "date", "hour", "minute", "second", "millisecond", "extractPublicKey", "peerId", "entry", "error", "log", "errCode", "ERR_UNDEFINED_PARAMETER", "pubKey", "unmarshalPublicKey", "err", "peerIdFromKeys", "ERR_INVALID_EMBEDDED_KEY", "ipnsEntryDataForV1Sig", "value", "validityType", "validity", "validityTypeBuffer", "fromString", "concat", "ipnsEntryDataForV2Sig", "data", "entryData", "marshal", "obj", "IpnsEntry", "unmarshal", "buf", "message", "peerIdToRoutingKey", "IPNS_PREFIX", "peerIdFromRoutingKey", "key", "peerIdFromBytes", "createCborData", "sequence", "ttl", "ValidityType", "ERR_UNRECOGNIZED_VALIDITY", "encode", "parseCborData", "decode", "log", "logger", "ID_MULTIHASH_CODE", "identity", "namespace", "namespaceLength", "create", "peerId", "value", "seq", "lifetime", "expirationDate", "NanoDate", "validityType", "IpnsEntry", "ms", "ns", "lifetimeNs", "_create", "_create", "peerId", "value", "seq", "validityType", "expirationDate", "ttl", "isoValidity", "fromString", "errCode", "ERR_MISSING_PRIVATE_KEY", "privateKey", "unmarshalPrivateKey", "signatureV1", "signLegacyV1", "data", "createCborData", "sigData", "ipnsEntryDataForV2Sig", "signatureV2", "entry", "digest", "decode", "ID_MULTIHASH_CODE", "equals", "log", "rawStdEncoding", "key", "base32upper", "getLocalKey", "Key", "validity", "dataForSignature", "ipnsEntryDataForV1Sig", "error", "ERR_SIGNATURE_CREATION", "log", "logger", "ERR_NOT_FOUND", "notFoundError", "defaultRecordLifetime", "IpnsPublisher", "routing", "datastore", "peerId", "value", "lifetime", "options", "record", "isPeerId", "errMsg", "errcode", "routingKey", "peerIdToRoutingKey", "key", "entry", "res", "toString", "err", "checkRouting", "dsVal", "getLocalKey", "data", "unmarshal", "getPublishedOptions", "seqNumber", "equals", "entryData", "create", "marshal", "import_err_code", "import_timeout_abort_controller", "log", "logger", "minute", "hour", "defaultBroadcastInterval", "defaultRecordLifetime", "IpnsRepublisher", "publisher", "datastore", "peerId", "keychain", "options", "errcode", "republishHandle", "period", "err", "pass", "firstRun", "timeoutController", "errMsg", "keys", "key", "pem", "privKey", "importKey", "peerIdKey", "peerIdFromKeys", "value", "isPeerId", "dsVal", "getLocalKey", "unmarshal", "import_err_code", "import_err_code", "log", "logger", "validate", "publicKey", "entry", "value", "validityType", "validity", "dataForSignature", "signature", "ipnsEntryDataForV2Sig", "validateCborDataMatchesPbData", "errCode", "ERR_SIGNATURE_VERIFICATION", "isValid", "IpnsEntry", "validityDate", "parseRFC3339", "toString", "ERR_UNRECOGNIZED_FORMAT", "ERR_IPNS_EXPIRED_RECORD", "ERR_UNRECOGNIZED_VALIDITY", "ERR_INVALID_RECORD_DATA", "data", "parseCborData", "equals", "ipnsValidator", "key", "marshalledData", "peerId", "peerIdFromRoutingKey", "receivedEntry", "unmarshal", "pubKey", "extractPublicKey", "log", "logger", "ERR_NOT_FOUND", "notFoundError", "defaultMaximumRecursiveDepth", "IpnsResolver", "routing", "name", "options", "errcode", "recursive", "nameSegments", "key", "depth", "res", "errMsg", "peerId", "peerIdFromString", "routingKey", "peerIdToRoutingKey", "record", "err", "ipnsValidator", "concat", "fromString", "ipnsEntry", "unmarshal", "toString", "import_hashlru", "TLRU", "maxSize", "hashlru", "key", "value", "ttl", "log", "logger", "defaultRecordTtl", "IPNS", "routing", "datastore", "peerId", "keychain", "options", "IpnsPublisher", "IpnsRepublisher", "IpnsResolver", "TLRU", "value", "lifetime", "toString", "id", "ttEol", "ttl", "err", "name", "errcode", "result", "all", "source", "arr", "entry", "sortAll", "iterable", "sorter", "all", "drain", "source", "_", "filter", "source", "fn", "entry", "take", "source", "limit", "items", "entry", "BaseDatastore", "key", "val", "options", "source", "value", "puts", "dels", "drain", "q", "it", "filter", "e", "f", "sortAll", "take", "import_debug", "debug", "v", "base58btc", "base32", "base64", "logger", "name", "FixedFIFO", "hwm", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "pushable", "options", "_pushable", "buffer", "next", "_pushable", "getNext", "options", "onEnd", "buffer", "FIFO", "pushable", "onNext", "ended", "waitNext", "resolve", "reject", "next", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "log", "logger", "TieredDatastore", "BaseDatastore", "stores", "store", "err", "dbOpenFailedError", "key", "value", "options", "dbWriteFailedError", "res", "notFoundError", "s", "dbDeleteFailedError", "source", "error", "pushables", "pushable", "drain", "pair", "p", "batches", "b", "batch", "q", "import_dlv", "ipnsSelector", "key", "data", "entries", "buf", "index", "IpnsEntry", "a", "b", "aSeq", "bSeq", "aValidty", "bValidty", "entryAValidityDate", "parseRFC3339", "toString", "entryBValidityDate", "SHARDING_FN", "README_FN", "MemoryDatastore", "BaseDatastore", "key", "val", "notFoundError", "value", "Key", "map", "source", "func", "val", "merge", "sources", "output", "pushable", "source", "item", "err", "rawPipe", "fns", "res", "isIterable", "obj", "isDuplex", "duplexPipelineFn", "duplex", "source", "p", "stream", "pushable", "err", "merge", "pipe", "first", "rest", "i", "shardKey", "Key", "SHARDING_FN", "shardReadmeKey", "README_FN", "CodeError", "message", "code", "props", "namespace", "encodeBase32", "buf", "toString", "keyToTopic", "key", "fromString", "b64url", "topicToKey", "topic", "CodeError", "equals", "a", "b", "i", "log", "logger", "PubSubDatastore", "BaseDatastore", "pubsub", "datastore", "peerId", "validator", "selector", "subscriptionKeyFn", "CodeError", "key", "val", "options", "errMsg", "stringifiedTopic", "keyToTopic", "subscriptions", "routingKey", "Key", "encodeBase32", "dsVal", "err", "evt", "msg", "data", "from", "topic", "topicToKey", "res", "isBetter", "value", "records", "dsKey", "currentRecord", "equals", "import_err_code", "log", "logger", "IpnsPubsubDatastore", "pubsub", "localDatastore", "peerId", "PubSubDatastore", "ipnsValidator", "ipnsSelector", "key", "value", "options", "err", "res", "e", "ns", "namespaceLength", "toString", "namespace", "stringifiedTopic", "base58btc", "id", "subscriber", "errcode", "peerIdToRoutingKey", "peerIdFromString", "sub", "name", "bufTopic", "fromString", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "toRFC3339", "time", "year", "month", "day", "hour", "minute", "seconds", "milliseconds", "nanoseconds", "parseRFC3339", "rfc3339Matcher", "m", "date", "second", "millisecond", "Libp2pRecord", "key", "value", "timeReceived", "__publicField", "Record", "toRFC3339", "raw", "rec", "obj", "recvtime", "parseRFC3339", "import_err_code", "log", "logger", "OfflineDatastore", "datastore", "key", "value", "options", "errcode", "routingKey", "err", "record", "Libp2pRecord", "res", "Key", "toString", "drain", "source", "_", "log", "logger", "DHTDatastore", "dht", "key", "value", "options", "drain", "err", "event", "notFoundError", "createRouting", "libp2p", "repo", "peerId", "options", "ipnsStores", "pubsubDs", "get", "IpnsPubsubDatastore", "DHTDatastore", "offlineDatastore", "OfflineDatastore", "TieredDatastore", "log", "logger", "IPNSAPI", "options", "ipns", "NotInitializedError", "repo", "peerId", "keychain", "AlreadyInitializedError", "routing", "OfflineDatastore", "IPNS", "libp2p", "createRouting", "value", "lifetime", "name", "import_err_code", "resolvePath", "ipns", "repo", "codecs", "name", "options", "ipnsPath", "cid", "path", "toCidAndPath", "drain", "resolve", "log", "logger", "createPublish", "ipns", "repo", "codecs", "peerId", "isOnline", "keychain", "lookupKey", "keyName", "privateKey", "unmarshalPrivateKey", "pem", "importKey", "err", "errcode", "peerIdFromKeys", "publish", "value", "options", "resolve", "lifetime", "key", "OFFLINE_ERROR", "normalizePath", "pubLifetime", "parse_duration_default", "results", "resolvePath", "bytes", "fromString", "result", "toString", "withTimeoutOption", "import_err_code", "import_is_domain_name", "mergeOptions", "merge_options_default", "log", "logger", "appendRemainder", "result", "remainder", "createResolve", "dns", "ipns", "isOnline", "offline", "resolve", "name", "options", "errcode", "OFFLINE_ERROR", "ipnsName", "namespace", "hash", "id", "peerIdFromString", "digest", "decode", "CID", "base36", "cid", "err", "isDomain", "value", "toString", "withTimeoutOption", "import_err_code", "getPubsubRouting", "ipns", "options", "errcode", "IpnsPubsubDatastore", "pubsub", "s", "createCancel", "ipns", "options", "experimental", "cancel", "name", "getPubsubRouting", "withTimeoutOption", "createState", "ipns", "options", "experimental", "state", "_options", "getPubsubRouting", "withTimeoutOption", "createSubs", "ipns", "options", "experimental", "subs", "getPubsubRouting", "withTimeoutOption", "PubSubAPI", "ipns", "options", "createCancel", "createState", "createSubs", "NameAPI", "dns", "ipns", "repo", "codecs", "peerId", "isOnline", "keychain", "options", "createPublish", "createResolve", "PubSubAPI", "import_timeout_abort_controller", "import_any_signal", "ERR_NOT_FOUND", "notFoundError", "Format", "createRefs", "repo", "codecs", "resolve", "preload", "refs", "ipfsPath", "options", "signals", "paths", "p", "getFullPath", "path", "refsStream", "err", "cid", "toCidAndPath", "resPath", "maxDepth", "unique", "obj", "objectStream", "formatLink", "srcCid", "dstCid", "linkName", "format", "out", "rootCid", "uniqueOnly", "seen", "traverseLevel", "parent", "depth", "nextLevelDepth", "link", "getLinks", "block", "value", "isDagPb", "code", "base", "name", "links", "match", "index", "source", "key", "element", "elementPath", "CID", "createLocal", "repo", "refsLocal", "options", "cid", "withTimeoutOption", "createWantlist", "network", "wantlist", "options", "bitswap", "list", "e", "withTimeoutOption", "createWantlistForPeer", "network", "wantlistForPeer", "peerId", "options", "bitswap", "list", "e", "withTimeoutOption", "createUnwant", "network", "unwant", "cids", "options", "bitswap", "withTimeoutOption", "createStat", "network", "stat", "options", "bitswap", "snapshot", "e", "withTimeoutOption", "BitswapAPI", "network", "createWantlist", "createWantlistForPeer", "createUnwant", "createStat", "DNS4", "base", "DNS6", "DNSADDR", "DNS", "or", "IP", "TCP", "and", "UDP", "UTP", "QUIC", "WebSockets", "WebSocketsSecure", "HTTP", "HTTPS", "_WebRTC", "WebRTC", "WebRTCStar", "WebSocketStar", "WebRTCDirect", "Reliable", "Stardust", "_P2P", "_Circuit", "CircuitRecursive", "Circuit", "P2P", "IPFS", "makeMatchesFunction", "partialMatch", "matches", "a", "ma", "multiaddr", "out", "args", "arg", "res", "n", "name", "pnames", "protos", "isValidMultiaddr", "ma", "IPFS", "createAdd", "repo", "add", "multiaddr", "options", "isValidMultiaddr", "config", "boostrappers", "a", "b", "withTimeoutOption", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "import_varint", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "toString", "convertToBytes", "str", "ip2bytes", "str2bytes", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "fromString", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ipString", "isIP", "toBytes", "ipBuff", "port", "size", "varint", "concat", "hash", "mh", "decode", "base58btc", "CID", "mbstr", "mb", "address", "addr", "base32", "portBuf", "addrBytes", "portBytes", "import_varint", "stringToStringTuples", "str", "tuples", "parts", "p", "part", "proto", "getProtocol", "ParseError", "cleanPath", "stringTuplesToString", "tup", "protoFromTuple", "stringTuplesToTuples", "convertToBytes", "tuplesToStringTuples", "convertToString", "tuplesToBytes", "fromBytes", "concat", "buf", "varint", "sizeForAddr", "addr", "bytesToTuples", "i", "code", "n", "size", "toString", "bytesToString", "a", "b", "stringToBytes", "fromString", "err", "validateBytes", "cleanPath", "str", "a", "ParseError", "protoFromTuple", "tup", "getProtocol", "import_varint", "import_err_code", "inspect", "DNS_CODES", "getProtocol", "resolvers", "symbol", "isMultiaddr", "value", "symbol", "DefaultMultiaddr", "addr", "_DefaultMultiaddr_string", "_DefaultMultiaddr_tuples", "_DefaultMultiaddr_stringTuples", "_a", "fromBytes", "fromString", "__classPrivateFieldGet", "__classPrivateFieldSet", "bytesToString", "family", "transport", "host", "port", "zone", "tcp", "getProtocol", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "DNS_CODES", "codes", "buf", "i", "varint", "n", "p", "size", "sizeForAddr", "proto", "bytesToTuples", "tuplesToStringTuples", "addrString", "s", "tuples", "tuplesToBytes", "tuple", "names", "peerIdStr", "toString", "base58btc", "CID", "path", "equals", "options", "resolvableProto", "resolver", "resolvers", "errCode", "a", "protos", "inspect", "multiaddr", "createClear", "repo", "clear", "options", "config", "removed", "ma", "multiaddr", "withTimeoutOption", "createList", "repo", "list", "options", "ma", "multiaddr", "withTimeoutOption", "config_browser_default", "createReset", "repo", "reset", "options", "config", "config_browser_default", "ma", "multiaddr", "withTimeoutOption", "createRm", "repo", "rm", "multiaddr", "options", "isValidMultiaddr", "config", "ma", "withTimeoutOption", "BootstrapAPI", "repo", "createAdd", "createList", "createRm", "createClear", "createReset", "createGet", "preload", "repo", "get", "cid", "options", "withTimeoutOption", "createPut", "codecs", "hashers", "repo", "preload", "put", "block", "options", "release", "cidVersion", "codecName", "hash", "codec", "cid", "CID", "withTimeoutOption", "import_err_code", "pDefer", "deferred", "resolve", "reject", "CustomEvent", "parallel", "source", "options", "concurrency", "ordered", "emitter", "ops", "slotAvailable", "pDefer", "resultAvailable", "sourceFinished", "sourceErr", "opErred", "task", "op", "result", "err", "valuesAvailable", "_a", "yieldOrderedValues", "yieldUnOrderedValues", "i", "map", "source", "func", "val", "filter", "source", "fn", "entry", "cleanCid", "cid", "CID", "BLOCK_RM_CONCURRENCY", "createRm", "repo", "rm", "cids", "options", "release", "pipe", "source", "map", "cid", "cleanCid", "result", "errCode", "err", "parallel", "filter", "withTimeoutOption", "createStat", "repo", "preload", "stat", "cid", "options", "cleanCid", "block", "withTimeoutOption", "BlockAPI", "codecs", "hashers", "preload", "repo", "createGet", "createPut", "createRm", "createStat", "import_err_code", "browserReadableStreamToIt", "stream", "options", "reader", "result", "blobToIt", "blob", "browserReadableStreamToIt", "peekableIterator", "iterable", "iterator", "symbol", "queue", "value", "all", "source", "arr", "entry", "isBytes", "obj", "isBlob", "isFileObject", "isReadableStream", "value", "toAsyncIterable", "thing", "normaliseContent", "input", "isBytes", "toBytes", "isBlob", "blobToIt", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "all", "map", "errCode", "chunk", "fromString", "import_err_code", "normaliseCandidateSingle", "input", "normaliseContent", "errCode", "toFileObject", "isBytes", "isBlob", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "isFileObject", "path", "mode", "mtime", "content", "file", "parseMode", "parseMtime", "normaliseInput", "input", "normaliseCandidateSingle", "normaliseContent", "createAdd", "addAll", "add", "entry", "options", "result", "last", "normaliseInput", "batch", "source", "size", "things", "thing", "parallelBatch", "source", "size", "tasks", "batch", "things", "p", "value", "err", "result", "import_murmurhash3js_revisited", "fromNumberTo32BitBuf", "number", "bytes", "i", "murmur332", "from", "input", "mur", "murmur3128", "bytes_exports", "murmur364", "hamtHashFn", "buf", "murmur3128", "defaultOptions", "sha256", "options_default", "options", "merge_options_default", "persist", "buffer", "blockstore", "options", "src_exports", "sha256", "multihash", "cid", "CID", "persist_default", "dirBuilder", "item", "blockstore", "options", "unixfs", "UnixFS", "buffer", "encode", "prepare", "cid", "persist_default", "path", "dir_default", "import_err_code", "flat", "source", "reduce", "all", "flat_default", "balanced", "source", "reduce", "options", "reduceToParents", "roots", "chunked", "batch", "balanced_default", "trickleStream", "source", "reduce", "options", "root", "Root", "iteration", "maxDepth", "subTree", "layer", "batch", "SubTree", "trickle_default", "layerRepeat", "distantRelative", "parent", "nextNode", "node", "children", "child", "depth", "bufferImporter", "file", "block", "options", "buffer", "unixfs", "opts", "src_exports", "raw_exports", "UnixFS", "encode", "persist_default", "buffer_importer_default", "dagBuilders", "flat_default", "balanced_default", "trickle_default", "buildFileBatch", "file", "blockstore", "options", "count", "previous", "bufferImporter", "buffer_importer_default", "entry", "parallelBatch", "reduce", "reducer", "leaves", "leaf", "buffer", "UnixFS", "encode", "prepare", "persist_default", "src_exports", "f", "links", "code", "node", "acc", "curr", "fileBuilder", "block", "dagBuilder", "errCode", "file_default", "import_err_code", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "_a", "Uint8ArrayList", "data", "__publicField", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "import_rabin_wasm", "import_err_code", "rabinChunker", "source", "options", "min", "max", "avg", "errcode", "sizepow", "chunk", "rabin", "rabin_default", "r", "buffers", "Uint8ArrayList", "sizes", "i", "size", "buf", "fixedSizeChunker", "source", "options", "list", "Uint8ArrayList", "currentLength", "emitted", "maxChunkSize", "buffer", "newBl", "fixed_size_default", "import_err_code", "validateChunks", "source", "content", "errCode", "fromString", "validate_chunks_default", "isIterable", "thing", "isAsyncIterable", "contentAsAsyncIterable", "content", "errCode", "dagBuilder", "source", "blockstore", "options", "entry", "path", "chunker", "rabin_default", "fixed_size_default", "chunkValidator", "validate_chunks_default", "file", "file_default", "dir", "dir_default", "dag_builder_default", "Dir", "props", "options", "name", "value", "blockstore", "dir_default", "DirFlat", "dir_default", "props", "options", "name", "value", "keys", "i", "key", "block", "children", "links", "child", "entry", "unixfs", "UnixFS", "node", "buffer", "encode", "prepare", "cid", "persist_default", "size", "acc", "curr", "dir_flat_default", "import_sparse_array", "Bucket", "options", "parent", "posAtParent", "__publicField", "SparseArray", "key", "value", "place", "child", "acc", "children", "map", "reduce", "index", "asyncMap", "asyncReduce", "asyncTransformBucket", "mapNode", "reduceNodes", "result", "hashValue", "fromString", "bucket", "newPlace", "pos", "object", "onlyChild", "exists", "hash", "o", "node", "_", "nodes", "output", "mappedChildren", "START_MASKS", "STOP_MASKS", "ConsumableBuffer", "value", "__publicField", "bits", "pendingBits", "result", "byte", "availableBits", "taking", "byteBitsToInt", "start", "length", "mask", "maskFor", "wrapHash", "hashFn", "hashing", "value", "InfiniteHash", "__publicField", "bits", "pendingBits", "result", "hash", "available", "took", "availableForUntake", "concat", "hashValue", "buffer", "ConsumableBuffer", "createHAMT", "options", "bucketOptions", "wrapHash", "Bucket", "DirSharded", "dir_default", "props", "options", "createHAMT", "name", "value", "key", "blockstore", "entry", "flush", "dir_sharded_default", "bucket", "shardRoot", "children", "links", "childrenSize", "i", "child", "labelPrefix", "Bucket", "shard", "subShard", "dir", "flushedDir", "label", "size", "data", "UnixFS", "node", "buffer", "encode", "prepare", "cid", "persist_default", "flatToShard", "child", "dir", "threshold", "options", "newDir", "dir_flat_default", "convertToShard", "parent", "oldDir", "dir_sharded_default", "key", "flat_to_shard_default", "toPathComponents", "path", "to_path_components_default", "addToTree", "elem", "tree", "options", "pathElems", "to_path_components_default", "lastIndex", "parent", "currentPath", "i", "pathElem", "last", "flat_to_shard_default", "dir", "dir_default", "dir_flat_default", "flushAndYield", "blockstore", "treeBuilder", "source", "block", "entry", "unwrapped", "tree_builder_default", "importer", "source", "blockstore", "options", "opts", "options_default", "dagBuilder", "dag_builder_default", "treeBuilder", "tree_builder_default", "candidates", "entry", "parallelBatch", "import_err_code", "normaliseCandidateMultiple", "input", "normaliseContent", "isBytes", "isBlob", "errCode", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "map", "toFileObject", "isFileObject", "path", "mode", "mtime", "content", "file", "parseMode", "parseMtime", "normaliseInput", "input", "normaliseCandidateMultiple", "normaliseContent", "parseChunkerString", "chunker", "sizeStr", "size", "parseRabinString", "options", "parts", "parseChunkSize", "str", "name", "mergeOptions", "merge_options_default", "createAddAll", "repo", "preload", "hashers", "options", "isShardingEnabled", "addAll", "source", "opts", "parseChunkerString", "totals", "prog", "bytes", "path", "hasher", "iterator", "pipe", "normaliseInput", "importer", "transformFile", "preloadFile", "pinFile", "releaseLock", "added", "withTimeoutOption", "file", "cid", "maybePreloadFile", "maybePinFile", "isRootDir", "import_err_code", "import_err_code", "textDecoder", "decodeVarint", "bytes", "offset", "v", "shift", "b", "decodeBytes", "byteLen", "postOffset", "decodeKey", "index", "wire", "decodeLink", "link", "l", "wireType", "fieldNum", "byts", "decodeNode", "links", "linksBeforeData", "data", "node", "textEncoder", "maxInt32", "maxUInt32", "encodeLink", "link", "bytes", "i", "encodeVarint", "nameBytes", "encodeNode", "node", "size", "sizeNode", "index", "sizeLink", "n", "l", "sov", "offset", "v", "base", "x", "len64", "len8tab", "pbNodeProperties", "pbLinkProperties", "textEncoder", "linkComparator", "a", "b", "abuf", "bbuf", "x", "y", "i", "len", "hasOnlyProperties", "node", "properties", "p", "validate", "node", "hasOnlyProperties", "pbNodeProperties", "i", "link", "pbLinkProperties", "linkComparator", "code", "encode", "node", "validate", "pbn", "l", "link", "encodeNode", "decode", "bytes", "decodeNode", "CID", "import_err_code", "import_sparse_array", "Bucket", "options", "parent", "posAtParent", "SparseArray", "key", "value", "place", "child", "acc", "children", "map", "reduce", "index", "asyncMap", "asyncReduce", "asyncTransformBucket", "mapNode", "reduceNodes", "result", "hashValue", "fromString", "bucket", "newPlace", "pos", "object", "onlyChild", "exists", "hash", "o", "node", "_", "nodes", "output", "mappedChildren", "START_MASKS", "STOP_MASKS", "ConsumableBuffer", "value", "bits", "pendingBits", "result", "byte", "availableBits", "taking", "byteBitsToInt", "start", "length", "mask", "maskFor", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "wrapHash", "hashFn", "hashing", "value", "InfiniteHash", "bits", "pendingBits", "result", "hash", "available", "took", "availableForUntake", "concat", "hashValue", "buffer", "ConsumableBuffer", "createHAMT", "options", "bucketOptions", "wrapHash", "Bucket", "import_murmurhash3js_revisited", "fromNumberTo32BitBuf", "number", "bytes", "i", "murmur332", "from", "input", "mur", "murmur3128", "bytes_exports", "murmur364", "hashFn", "buf", "murmur3128", "addLinksToHamtBucket", "links", "bucket", "rootBucket", "link", "pos", "Bucket", "toPrefix", "position", "toBucketPath", "path", "findShardCid", "node", "name", "blockstore", "context", "options", "createHAMT", "prefix", "bucketPath", "entryPrefix", "entryName", "block", "decode", "find_cid_in_shard_default", "extractDataFromBlock", "block", "blockStart", "requestedStart", "requestedEnd", "blockLength", "blockEnd", "extract_data_from_block_default", "import_err_code", "validateOffsetAndLength", "size", "offset", "length", "errCode", "validate_offset_and_length_default", "import_err_code", "pDefer", "deferred", "resolve", "reject", "CustomEvent", "parallel", "source", "options", "concurrency", "ordered", "emitter", "ops", "slotAvailable", "pDefer", "resultAvailable", "sourceFinished", "sourceErr", "opErred", "task", "op", "result", "err", "valuesAvailable", "_a", "yieldOrderedValues", "yieldUnOrderedValues", "i", "import_eventemitter3", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "__classPrivateFieldGet", "receiver", "state", "kind", "f", "_PriorityQueue_queue", "PriorityQueue", "run", "options", "element", "index", "lowerBound", "a", "b", "item", "__classPrivateFieldSet", "receiver", "state", "value", "kind", "f", "__classPrivateFieldGet", "_PQueue_instances", "_PQueue_carryoverConcurrencyCount", "_PQueue_isIntervalIgnored", "_PQueue_intervalCount", "_PQueue_intervalCap", "_PQueue_interval", "_PQueue_intervalEnd", "_PQueue_intervalId", "_PQueue_timeoutId", "_PQueue_queue", "_PQueue_queueClass", "_PQueue_pending", "_PQueue_concurrency", "_PQueue_isPaused", "_PQueue_throwOnTimeout", "_PQueue_doesIntervalAllowAnother_get", "_PQueue_doesConcurrentAllowAnother_get", "_PQueue_next", "_PQueue_onResumeInterval", "_PQueue_isIntervalPaused_get", "_PQueue_tryToStartAnother", "_PQueue_initializeIntervalIfNeeded", "_PQueue_onInterval", "_PQueue_processQueue", "_PQueue_throwOnAbort", "_PQueue_onEvent", "AbortError", "PQueue", "EventEmitter", "options", "_a", "_b", "_c", "_d", "PriorityQueue", "newConcurrency", "function_", "resolve", "reject", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "limit", "now", "delay", "canInitializeInterval", "job", "signal", "_resolve", "event", "filter", "listener", "walkDAG", "blockstore", "node", "queue", "streamPosition", "start", "end", "walkQueue", "options", "extract_data_from_block_default", "errCode", "file", "UnixFS", "err", "data", "buf", "childOps", "i", "childLink", "childStart", "childEnd", "pipe", "source", "map", "op", "block", "parallel", "link", "blockStart", "child", "code", "decode", "fileContent", "cid", "unixfs", "path", "resolve", "depth", "yieldFileContent", "fileSize", "offset", "length", "validate_offset_and_length_default", "PQueue", "pushable", "error", "read", "file_default", "directoryContent", "cid", "node", "unixfs", "path", "resolve", "depth", "blockstore", "yieldDirectoryContent", "options", "offset", "length", "links", "link", "result", "directory_default", "hamtShardedDirectoryContent", "cid", "node", "unixfs", "path", "resolve", "depth", "blockstore", "yieldHamtDirectoryContent", "options", "listDirectory", "links", "link", "name", "block", "decode", "file", "hamt_sharded_directory_default", "findLinkCid", "node", "name", "link", "contentExporters", "file_default", "directory_default", "hamt_sharded_directory_default", "cid", "unixfs", "path", "resolve", "depth", "blockstore", "unixFsResolver", "toResolve", "options", "block", "decode", "next", "errCode", "UnixFS", "err", "linkCid", "find_cid_in_shard_default", "nextName", "nextPath", "unixfs_v1_default", "import_err_code", "rawContent", "node", "contentGenerator", "options", "offset", "length", "validate_offset_and_length_default", "extract_data_from_block_default", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "errCode", "block", "raw_default", "import_err_code", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "options", "block", "object", "decode", "subObject", "subPath", "prop", "subObjectCid", "CID", "errCode", "dag_cbor_default", "import_err_code", "rawContent", "node", "contentGenerator", "options", "offset", "length", "validate_offset_and_length_default", "extract_data_from_block_default", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "errCode", "buf", "decode", "identity_default", "resolvers", "code", "unixfs_v1_default", "raw_default", "dag_cbor_default", "identity", "identity_default", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "options", "resolver", "errCode", "resolvers_default", "last", "source", "res", "entry", "toPathComponents", "path", "cidAndRest", "CID", "cid", "output", "errCode", "walkPath", "blockstore", "options", "toResolve", "name", "entryPath", "startingDepth", "result", "resolvers_default", "exporter", "last", "recursive", "node", "child", "recurse", "file", "createCat", "repo", "preload", "cat", "ipfsPath", "options", "normalizeCidPath", "pathComponents", "CID", "file", "exporter", "withTimeoutOption", "import_err_code", "ZERO_OFFSET", "USTAR_MAGIC", "fromString", "GNU_MAGIC", "GNU_VER", "import_iso_constants", "isAsyncIterable", "thing", "toBuffer", "source", "buffer", "buf", "concat", "bufs", "length", "src_default", "ZEROS", "SEVENS", "ZERO_OFFSET", "USTAR_MAGIC", "fromString", "USTAR_VER", "MASK", "MAGIC_OFFSET", "VERSION_OFFSET", "toTypeflag", "flag", "cksum", "block", "sum", "i", "j", "encodeOct", "val", "n", "str", "addLength", "len", "digits", "encodePax", "opts", "result", "pax", "key", "encode", "buf", "name", "prefix", "S_IFMT", "S_IFBLK", "S_IFCHR", "S_IFDIR", "S_IFIFO", "S_IFLNK", "isoConstants", "DMODE", "FMODE", "END_OF_TAR", "modeToType", "mode", "getPadding", "size", "encode", "header", "encoded", "encodePax", "paxHeader", "newHeader", "Uint8ArrayList", "pack", "source", "partialHeader", "body", "fromString", "isUint8ArrayList", "toString", "src_default", "written", "chunk", "zero$1", "buf", "len", "STORED_BLOCK", "STATIC_TREES", "DYN_TREES", "MIN_MATCH$1", "MAX_MATCH$1", "LENGTH_CODES$1", "LITERALS$1", "L_CODES$1", "D_CODES$1", "BL_CODES$1", "HEAP_SIZE$1", "MAX_BITS$1", "Buf_size", "MAX_BL_BITS", "END_BLOCK", "REP_3_6", "REPZ_3_10", "REPZ_11_138", "extra_lbits", "extra_dbits", "extra_blbits", "bl_order", "DIST_CODE_LEN", "static_ltree", "static_dtree", "_dist_code", "_length_code", "base_length", "base_dist", "StaticTreeDesc", "static_tree", "extra_bits", "extra_base", "elems", "max_length", "static_l_desc", "static_d_desc", "static_bl_desc", "TreeDesc", "dyn_tree", "stat_desc", "d_code", "dist", "put_short", "s", "w", "send_bits", "value", "length", "send_code", "c", "tree", "bi_reverse", "code", "res", "bi_flush", "gen_bitlen", "desc", "max_code", "stree", "has_stree", "extra", "base", "h", "n", "m", "bits", "xbits", "f", "overflow", "gen_codes", "bl_count", "next_code", "tr_static_init", "init_block", "bi_windup", "smaller", "depth", "_n2", "_m2", "pqdownheap", "k", "v", "j", "compress_block", "ltree", "dtree", "lc", "sx", "build_tree", "node", "scan_tree", "prevlen", "curlen", "nextlen", "count", "max_count", "min_count", "send_tree", "build_bl_tree", "max_blindex", "send_all_trees", "lcodes", "dcodes", "blcodes", "rank", "detect_data_type", "block_mask", "static_init_done", "_tr_init$1", "_tr_stored_block$1", "stored_len", "last", "_tr_align$1", "_tr_flush_block$1", "opt_lenb", "static_lenb", "_tr_tally$1", "_tr_init_1", "_tr_stored_block_1", "_tr_flush_block_1", "_tr_tally_1", "_tr_align_1", "trees", "adler32", "adler", "pos", "s1", "s2", "adler32_1", "makeTable", "table", "crcTable", "crc32", "crc", "t", "end", "i", "crc32_1", "messages", "constants$2", "_tr_init", "_tr_stored_block", "_tr_flush_block", "_tr_tally", "_tr_align", "Z_NO_FLUSH$2", "Z_PARTIAL_FLUSH", "Z_FULL_FLUSH$1", "Z_FINISH$3", "Z_BLOCK$1", "Z_OK$3", "Z_STREAM_END$3", "Z_STREAM_ERROR$2", "Z_DATA_ERROR$2", "Z_BUF_ERROR$1", "Z_DEFAULT_COMPRESSION$1", "Z_FILTERED", "Z_HUFFMAN_ONLY", "Z_RLE", "Z_FIXED", "Z_DEFAULT_STRATEGY$1", "Z_UNKNOWN", "Z_DEFLATED$2", "MAX_MEM_LEVEL", "MAX_WBITS$1", "DEF_MEM_LEVEL", "LENGTH_CODES", "LITERALS", "L_CODES", "D_CODES", "BL_CODES", "HEAP_SIZE", "MAX_BITS", "MIN_MATCH", "MAX_MATCH", "MIN_LOOKAHEAD", "PRESET_DICT", "INIT_STATE", "GZIP_STATE", "EXTRA_STATE", "NAME_STATE", "COMMENT_STATE", "HCRC_STATE", "BUSY_STATE", "FINISH_STATE", "BS_NEED_MORE", "BS_BLOCK_DONE", "BS_FINISH_STARTED", "BS_FINISH_DONE", "OS_CODE", "err", "strm", "errorCode", "zero", "slide_hash", "p", "wsize", "HASH_ZLIB", "prev", "data", "HASH", "flush_pending", "flush_block_only", "put_byte", "b", "putShortMSB", "read_buf", "start", "size", "longest_match", "cur_match", "chain_length", "scan", "match", "best_len", "nice_match", "limit", "_win", "wmask", "strend", "scan_end1", "scan_end", "fill_window", "_w_size", "more", "str", "deflate_stored", "flush", "min_block", "left", "have", "used", "deflate_fast", "hash_head", "bflush", "deflate_slow", "max_insert", "deflate_rle", "deflate_huff", "Config", "good_length", "max_lazy", "nice_length", "max_chain", "func", "configuration_table", "lm_init", "DeflateState", "deflateStateCheck", "deflateResetKeep", "deflateReset", "ret", "deflateSetHeader", "head", "deflateInit2", "level", "method", "windowBits", "memLevel", "strategy", "wrap", "deflateInit", "deflate$2", "old_flush", "header", "level_flags", "beg", "copy", "gzhead_extra", "val", "bstate", "deflateEnd", "status", "deflateSetDictionary", "dictionary", "dictLength", "tmpDict", "avail", "next", "input", "deflateInit_1", "deflateInit2_1", "deflateReset_1", "deflateResetKeep_1", "deflateSetHeader_1", "deflate_2$1", "deflateEnd_1", "deflateSetDictionary_1", "deflateInfo", "deflate_1$2", "_has", "obj", "key", "assign", "sources", "source", "flattenChunks", "chunks", "l", "result", "chunk", "common", "STR_APPLY_UIA_OK", "_utf8len", "q", "string2buf", "c2", "m_pos", "str_len", "buf_len", "buf2binstring", "buf2string", "max", "out", "utf16buf", "c_len", "utf8border", "strings", "ZStream", "zstream", "toString$1", "Z_NO_FLUSH$1", "Z_SYNC_FLUSH", "Z_FULL_FLUSH", "Z_FINISH$2", "Z_OK$2", "Z_STREAM_END$2", "Z_DEFAULT_COMPRESSION", "Z_DEFAULT_STRATEGY", "Z_DEFLATED$1", "Deflate$1", "options", "opt", "dict", "flush_mode", "chunkSize", "_flush_mode", "deflate$1", "deflator", "deflateRaw$1", "gzip$1", "Deflate_1$1", "deflate_2", "deflateRaw_1$1", "gzip_1$1", "constants$1", "deflate_1$1", "BAD$1", "TYPE$1", "inffast", "_in", "_out", "dmax", "whave", "wnext", "s_window", "hold", "lcode", "dcode", "lmask", "dmask", "here", "op", "from", "from_source", "output", "state", "top", "dolen", "dodist", "MAXBITS", "ENOUGH_LENS$1", "ENOUGH_DISTS$1", "CODES$1", "LENS$1", "DISTS$1", "lbase", "lext", "dbase", "dext", "inflate_table", "type", "lens", "lens_index", "codes", "table_index", "work", "opts", "sym", "min", "root", "curr", "drop", "huff", "incr", "fill", "low", "mask", "offs", "here_bits", "here_op", "here_val", "inftrees", "CODES", "LENS", "DISTS", "Z_FINISH$1", "Z_BLOCK", "Z_TREES", "Z_OK$1", "Z_STREAM_END$1", "Z_NEED_DICT$1", "Z_STREAM_ERROR$1", "Z_DATA_ERROR$1", "Z_MEM_ERROR$1", "Z_BUF_ERROR", "Z_DEFLATED", "HEAD", "FLAGS", "TIME", "OS", "EXLEN", "EXTRA", "NAME", "COMMENT", "HCRC", "DICTID", "DICT", "TYPE", "TYPEDO", "STORED", "COPY_", "COPY", "TABLE", "LENLENS", "CODELENS", "LEN_", "LEN", "LENEXT", "DIST", "DISTEXT", "MATCH", "LIT", "CHECK", "LENGTH", "DONE", "BAD", "MEM", "SYNC", "ENOUGH_LENS", "ENOUGH_DISTS", "MAX_WBITS", "DEF_WBITS", "zswap32", "InflateState", "inflateStateCheck", "inflateResetKeep", "inflateReset", "inflateReset2", "inflateInit2", "inflateInit", "virgin", "lenfix", "distfix", "fixedtables", "updatewindow", "src", "inflate$2", "put", "last_bits", "last_op", "last_val", "hbuf", "order", "inf_leave", "inflateEnd", "inflateGetHeader", "inflateSetDictionary", "dictid", "inflateReset_1", "inflateReset2_1", "inflateResetKeep_1", "inflateInit_1", "inflateInit2_1", "inflate_2$1", "inflateEnd_1", "inflateGetHeader_1", "inflateSetDictionary_1", "inflateInfo", "inflate_1$2", "GZheader", "gzheader", "toString", "Z_NO_FLUSH", "Z_FINISH", "Z_OK", "Z_STREAM_END", "Z_NEED_DICT", "Z_STREAM_ERROR", "Z_DATA_ERROR", "Z_MEM_ERROR", "Inflate$1", "last_avail_out", "next_out_utf8", "tail", "utf8str", "inflate$1", "inflator", "inflateRaw$1", "Inflate_1$1", "inflate_2", "inflateRaw_1$1", "ungzip$1", "constants", "inflate_1$1", "Deflate", "deflate", "deflateRaw", "gzip", "Inflate", "inflate", "inflateRaw", "ungzip", "Deflate_1", "deflate_1", "deflateRaw_1", "gzip_1", "Inflate_1", "inflate_1", "inflateRaw_1", "ungzip_1", "constants_1", "pako", "toBuffer", "stream", "buffer", "buf", "concat", "DEFAULT_COMPRESSION_LEVEL", "createGet", "repo", "preload", "get", "ipfsPath", "options", "errCode", "pathComponents", "normalizeCidPath", "err", "CID", "ipfsPathOrCid", "file", "exporter", "args", "pack", "source", "buf", "toBuffer", "pako", "pipe", "recursive", "entry", "output", "withTimeoutOption", "import_err_code", "createLs", "repo", "preload", "ls", "ipfsPath", "options", "legacyPath", "normalizeCidPath", "pathComponents", "CID", "ipfsPathOrCid", "file", "exporter", "mapFile", "child", "errCode", "withTimeoutOption", "RootAPI", "preload", "repo", "hashers", "options", "addAll", "createAddAll", "createAdd", "createCat", "createGet", "createLs", "ipfsCore", "commit", "interfaceIpfsCore", "createVersion", "repo", "version", "_options", "repoVersion", "ipfsCore", "commit", "interfaceIpfsCore", "withTimeoutOption", "import_err_code", "log", "logger", "createId", "peerId", "network", "id", "options", "net", "NotStartedError", "errCode", "toString", "ipfsCore", "libp2p", "peerIdToId", "peer", "findPeer", "agentVersion", "protocolVersion", "idStr", "publicKeyStr", "ma", "str", "multiaddr", "withTimeoutOption", "findPeerOnDht", "publicKey", "err", "addr", "event", "objectSafeSet", "set", "obj", "propsArg", "value", "props", "lastProp", "prototypeCheck", "thisProp", "prop", "profiles", "config", "objectSafeSet", "defaultConfig", "config_browser_default", "Swarm", "ConnMgr", "log", "logger", "createConfig", "repo", "withTimeoutOption", "getAll", "get", "set", "replace", "applyProfile", "listProfiles", "options", "key", "value", "profileName", "dryRun", "profile", "profiles", "oldCfg", "newCfg", "err", "_options", "name", "readonly", "enumerable", "configurable", "linksWithin", "path", "value", "index", "element", "elementPath", "cid", "CID", "links", "source", "base", "key", "treeWithin", "tree", "get", "node", "part", "Block", "bytes", "createUnsafe", "bytes", "cid", "maybeValue", "codec", "value", "Block", "import_varint", "CIDV0_BYTES", "V2_HEADER_LENGTH", "decodeVarint", "bytes", "seeker", "i", "varint", "decodeV2Header", "dv", "offset", "getMultihashLength", "codeLength", "length", "lengthLength", "Kinds", "obj", "Types", "i", "v", "ret", "j", "entries", "requiredCount", "key", "value", "Reprs", "CarV1HeaderOrV2Pragma", "readHeader", "reader", "strictVersion", "length", "decodeVarint", "header", "block", "decode", "CarV1HeaderOrV2Pragma", "v2Header", "decodeV2Header", "V2_HEADER_LENGTH", "v1Header", "readCid", "first", "CIDV0_BYTES", "bytes", "multihash", "CID", "version", "codec", "getMultihashLength", "readBlockHead", "start", "cid", "blockLength", "readBlock", "readBlockIndex", "offset", "index", "createDecoder", "headerPromise", "v1length", "limitReader", "bytesReader", "pos", "seek", "out", "chunkReader", "readChunk", "have", "currentChunk", "read", "bufa", "chunk", "p", "c", "off", "b", "asyncIterableReader", "asyncIterable", "iterator", "next", "byteLimit", "bytesRead", "import_varint", "CAR_V1_VERSION", "createHeader", "roots", "headerBytes", "encode", "varintBytes", "varint", "header", "createEncoder", "writer", "bytes", "block", "cid", "noop", "create", "chunkQueue", "drainer", "drainerResolver", "ended", "outWait", "outWaitResolver", "makeDrainer", "resolve", "writer", "chunk", "iterator", "CarWriter", "roots", "encoder", "block", "cid", "CID", "toRoots", "iterator", "encodeWriter", "writer", "out", "CarWriterOut", "bytes", "reader", "bytesReader", "readHeader", "newHeader", "createHeader", "iw", "create", "createEncoder", "_roots", "root", "_root", "walk", "cid", "load", "seen", "b58Cid", "base58btc", "block", "log", "logger", "NO_LINKS_CODECS", "code", "createExport", "repo", "preload", "codecs", "dagExport", "root", "options", "cid", "CID", "writer", "out", "CarWriter", "err", "load", "makeLoader", "walk", "e", "chunk", "withTimeoutOption", "codec", "bytes", "createUnsafe", "first", "source", "entry", "import_err_code", "createGet", "codecs", "repo", "preload", "withTimeoutOption", "cid", "options", "result", "first", "resolve", "last", "errCode", "codec", "block", "CarIteratorBase", "version", "roots", "iterable", "CarBlockIterator", "bytes", "iterator", "fromBytes", "asyncIterable", "fromIterable", "CarCIDIterator", "next", "decodeIterator", "bytesReader", "asyncIterableReader", "reader", "decoder", "createDecoder", "log", "logger", "createImport", "repo", "dagImport", "sources", "options", "release", "abortOptions", "peekable", "peekableIterator", "value", "done", "cars", "car", "roots", "importCar", "cid", "pinErrorMsg", "err", "withTimeoutOption", "source", "reader", "CarBlockIterator", "drain", "map", "key", "createPut", "repo", "codecs", "hashers", "preload", "put", "dagNode", "options", "release", "storeCodec", "inputCodec", "cidVersion", "hasher", "buf", "hash", "cid", "CID", "withTimeoutOption", "createResolve", "repo", "codecs", "preload", "dagResolve", "ipfsPath", "options", "cid", "toCidAndPath", "resolvePath", "withTimeoutOption", "DagAPI", "repo", "codecs", "hashers", "preload", "createExport", "createGet", "createImport", "createResolve", "createPut", "extractSNI", "ma", "sniProtoCode", "getProtocol", "proto", "value", "hasTLS", "_", "interpretNext", "headProtoCode", "headProtoVal", "restMa", "interpreter", "interpreters", "restVal", "tailProto", "maHasTLS", "sni", "protocol", "baseVal", "multiaddrToUri", "input", "opts", "parts", "multiaddr", "head", "uri", "arrayShuffle", "array", "index", "newIndex", "import_http", "log", "logger", "Queue", "dist_default", "httpQueue", "preload", "url", "options", "reader", "HTTP", "done", "import_hashlru", "log", "logger", "createPreloader", "options", "stopped", "requests", "apiUris", "str", "multiaddrToUri", "cache", "hashlru", "api", "cid", "path", "fallbackApiUris", "arrayShuffle", "success", "now", "uri", "controller", "preload", "err", "r", "log", "logger", "createMfsPreloader", "preload", "files", "options", "noop", "rootCid", "timeoutId", "preloadMfs", "stats", "nextRootCid", "err", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "_queue", "PriorityQueue", "__privateAdd", "run", "options", "element", "__privateGet", "index", "lowerBound", "a", "b", "item", "_carryoverConcurrencyCount", "_isIntervalIgnored", "_intervalCount", "_intervalCap", "_interval", "_intervalEnd", "_intervalId", "_timeoutId", "_queue", "_queueClass", "_pending", "_concurrency", "_isPaused", "_throwOnTimeout", "_doesIntervalAllowAnother", "doesIntervalAllowAnother_get", "_doesConcurrentAllowAnother", "doesConcurrentAllowAnother_get", "_next", "next_fn", "_onResumeInterval", "onResumeInterval_fn", "_isIntervalPaused", "isIntervalPaused_get", "_tryToStartAnother", "tryToStartAnother_fn", "_initializeIntervalIfNeeded", "initializeIntervalIfNeeded_fn", "_onInterval", "onInterval_fn", "_processQueue", "processQueue_fn", "_throwOnAbort", "throwOnAbort_fn", "_onEvent", "onEvent_fn", "PQueue", "EventEmitter", "options", "_a", "_b", "__privateAdd", "__publicField", "PriorityQueue", "__privateSet", "__privateGet", "newConcurrency", "__privateMethod", "function_", "resolve", "reject", "__privateWrapper", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "limit", "now", "delay", "canInitializeInterval", "job", "signal", "_resolve", "event", "filter", "listener", "events", "observable", "worker", "event", "type", "fn", "listener", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "nanoid", "size", "handleWorkerLockRequest", "emitter", "masterEvent", "requestType", "releaseType", "grantType", "worker", "event", "requestEvent", "resolve", "releaseEventListener", "releaseEvent", "makeWorkerLockRequest", "name", "id", "nanoid", "listener", "responseEvent", "defaultOptions", "browser_default", "options", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "mutexes", "implementation", "createReleaseable", "queue", "options", "res", "p", "resolve", "pTimeout", "createMutex", "name", "masterQueue", "PQueue", "readQueue", "localReadQueue", "readPromise", "defaultOptions", "createMortice", "opts", "browser_default", "event", "release", "lock", "createLock", "repoOwner", "mutex", "createMortice", "func", "args", "releaseLock", "import_err_code", "log", "logger", "loadMfsRoot", "context", "options", "errCode", "cid", "buf", "MFS_ROOT_KEY", "CID", "err", "encode", "UnixFS", "hash", "sha256", "toPathComponents", "path", "import_err_code", "IPFS_PREFIX", "toMfsPath", "context", "path", "options", "root", "loadMfsRoot", "output", "ipfsPath", "CID", "errCode", "pathComponents", "toPathComponents", "mfsDirectory", "mfsPath", "cidPath", "res", "exporter", "err", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createStat", "context", "mfsStat", "path", "options", "type", "cid", "mfsPath", "toMfsPath", "exportPath", "file", "exporter", "err", "errCode", "statters", "withTimeoutOption", "stat", "encode", "acc", "curr", "import_err_code", "log", "logger", "toTrail", "context", "path", "output", "fsEntry", "walkPath", "persist", "buffer", "blockstore", "options", "src_exports", "sha256", "multihash", "cid", "CID", "hamtHashCode", "murmur3128", "hamtBucketBits", "hamtHashFn", "buf", "Dir", "props", "options", "name", "value", "blockstore", "DirSharded", "createHAMT", "hamtHashFn", "hamtBucketBits", "key", "flush", "bucket", "shardRoot", "children", "links", "childrenSize", "i", "child", "labelPrefix", "Bucket", "shard", "subShard", "dir", "flushedDir", "entry", "label", "size", "data", "node", "UnixFS", "hamtHashCode", "buffer", "encode", "prepare", "cid", "persist", "log", "logger", "updateHamtDirectory", "context", "links", "bucket", "options", "data", "node", "UnixFS", "dir", "hamtHashCode", "hasher", "parent", "a", "b", "buf", "encode", "hash", "cid", "CID", "code", "sum", "link", "recreateHamtLevel", "rootBucket", "parentBucket", "positionAtParent", "Bucket", "addLinksToHamtBucket", "recreateInitialHamtLevel", "createHAMT", "hamtHashFn", "hamtBucketBits", "linkName", "pos", "subBucket", "block", "decode", "toPrefix", "position", "generatePath", "fileName", "rootNode", "path", "currentBucket", "i", "segment", "nextSegment", "createShard", "contents", "shard", "DirSharded", "res", "last", "import_err_code", "log", "logger", "addLink", "context", "options", "parent", "parentCid", "CID", "errCode", "code", "block", "decode", "meta", "UnixFS", "addToShardedDirectory", "convertToShardedDirectory", "addToDirectory", "result", "createShard", "link", "parentLinks", "node", "data", "ms", "secs", "prepare", "hasher", "buf", "encode", "hash", "cid", "shard", "path", "addFileToShardedDirectory", "last", "newLink", "updateHamtDirectory", "file", "rootBucket", "recreateInitialHamtLevel", "DirSharded", "position", "toBucketPath", "index", "segment", "subShard", "recreateHamtLevel", "toPrefix", "nextSegment", "addLinksToHamtBucket", "bucket", "positionInBucket", "log", "logger", "defaultOptions", "updateTree", "context", "trail", "options", "index", "child", "block", "node", "decode", "cid", "name", "result", "addLink", "import_err_code", "log", "logger", "updateMfsRoot", "context", "cid", "options", "errCode", "MFS_ROOT_KEY", "import_err_code", "createNode", "context", "type", "options", "metadata", "UnixFS", "hasher", "node", "buf", "encode", "hash", "cid", "CID", "code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createMkdir", "context", "mfsMkdir", "path", "options", "opts", "errCode", "pathComponents", "toPathComponents", "root", "loadMfsRoot", "parent", "trail", "emptyDir", "createNode", "i", "subPathComponents", "subPath", "exporter", "err", "addEmptyDir", "newRootCid", "updateTree", "updateMfsRoot", "withTimeoutOption", "childName", "result", "addLink", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createCp", "context", "mfsCp", "from", "to", "opts", "options", "sources", "path", "toMfsPath", "destination", "errCode", "missing", "source", "destinationIsDirectory", "isDirectory", "createMkdir", "parentFolder", "createStat", "err", "destinationPath", "trail", "toTrail", "destinationName", "copyToFile", "copyToDirectory", "withTimeoutOption", "destinationTrail", "parent", "addSourceToParent", "newRootCid", "updateTree", "updateMfsRoot", "i", "childName", "sourceBlock", "node", "cid", "size", "addLink", "import_err_code", "import_err_code", "log", "logger", "removeLink", "context", "options", "parent", "parentCid", "CID", "errCode", "block", "decode", "UnixFS", "removeFromShardedDirectory", "removeFromDirectory", "link", "parentBlock", "encode", "hash", "code", "rootBucket", "path", "generatePath", "node", "updateShard", "updateHamtDirectory", "positions", "name", "last", "bucket", "prefix", "links", "nodeLink", "result", "cid", "size", "newName", "updateShardParent", "oldName", "parentLinks", "mergeOptions", "merge_options_default", "defaultOptions", "createRm", "context", "mfsRm", "paths", "opts", "options", "sources", "path", "toMfsPath", "errCode", "source", "removePath", "withTimeoutOption", "mfsPath", "trail", "toTrail", "child", "parent", "cid", "removeLink", "newRootCid", "updateTree", "updateMfsRoot", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "calculateModification", "mode", "originalMode", "isDirectory", "modification", "calculateUGO", "references", "ugo", "calculateSpecial", "parseSymbolicMode", "input", "match", "operator", "calculateMode", "metadata", "strMode", "curr", "acc", "createChmod", "context", "mfsChmod", "path", "options", "opts", "cid", "mfsDirectory", "name", "toMfsPath", "code", "errCode", "root", "pipe", "entry", "recursive", "node", "prepare", "source", "importer", "block", "buf", "encode", "persist", "unixfs", "UnixFS", "nodes", "last", "createRm", "createCp", "decode", "updatedBlock", "hashAlg", "hash", "updatedCid", "CID", "trail", "toTrail", "parent", "parentCid", "parentBlock", "parentNode", "result", "addLink", "newRootCid", "updateTree", "updateMfsRoot", "withTimeoutOption", "mergeOptions", "merge_options_default", "defaultOptions", "createFlush", "context", "mfsFlush", "path", "options", "cid", "createStat", "withTimeoutOption", "mergeOptions", "merge_options_default", "defaultOptions", "createMv", "context", "mfsMv", "from", "to", "options", "opts", "createCp", "createRm", "withTimeoutOption", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createTouch", "context", "mfsTouch", "path", "options", "settings", "cid", "mfsDirectory", "name", "exists", "toMfsPath", "hashAlg", "hasher", "updatedBlock", "updatedCid", "cidVersion", "code", "errCode", "block", "node", "decode", "metadata", "UnixFS", "encode", "hash", "CID", "trail", "toTrail", "parent", "parentCid", "parentBlock", "parentNode", "result", "addLink", "newRootCid", "updateTree", "updateMfsRoot", "withTimeoutOption", "import_err_code", "mergeOptions", "merge_options_default", "defaultOptions", "createRead", "context", "mfsRead", "path", "options", "mfsPath", "toMfsPath", "result", "exporter", "errCode", "buf", "withTimeoutOption", "import_err_code", "log", "logger", "toAsyncIterator", "content", "errCode", "fromString", "browserReadableStreamToIt", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "bytes", "path", "createWrite", "context", "mfsWrite", "content", "opts", "options", "source", "destination", "parent", "createLock", "toAsyncIterator", "toMfsPath", "errCode", "updateOrImport", "withTimeoutOption", "child", "write", "pathComponents", "toPathComponents", "fileName", "parentExists", "createStat", "err", "createMkdir", "updatedPath", "trail", "toTrail", "parentBlock", "parentNode", "decode", "result", "addLink", "newRootCid", "updateTree", "updateMfsRoot", "sources", "extra", "asyncZeroes", "limitAsyncStreamBytes", "countBytesStreamed", "catAsyncIterators", "bytesWritten", "fileSize", "mode", "parseMode", "mtime", "parseMtime", "hasher", "last", "importer", "stream", "limit", "emitted", "buf", "count", "chunkSize", "MFS_MAX_CHUNK_SIZE", "_asyncZeroes", "i", "notify", "wrote", "toOutput", "fsEntry", "output", "createLs", "context", "mfsLs", "path", "options", "mfsPath", "toMfsPath", "exporter", "map", "withTimeoutOption", "readOperations", "createStat", "writeOperations", "createChmod", "createCp", "createFlush", "createMkdir", "createMv", "createRm", "createTouch", "unwrappedOperations", "createWrite", "createRead", "createLs", "wrap", "options", "mfs", "operations", "lock", "key", "defaultOptions", "createMfs", "repoOwner", "createLock", "readLock", "operation", "writeLock", "createFiles", "repo", "preload", "hashers", "constructorOptions", "methods", "withPreload", "fn", "args", "paths", "arg", "ipfsPath", "isCID", "path", "file", "createExport", "keychain", "withTimeoutOption", "name", "password", "DEFAULT_KEY_TYPE", "DEFAULT_KEY_SIZE", "createGen", "keychain", "withTimeoutOption", "name", "options", "createImport", "keychain", "withTimeoutOption", "name", "pem", "password", "createInfo", "keychain", "withTimeoutOption", "name", "createList", "keychain", "withTimeoutOption", "createRename", "keychain", "withTimeoutOption", "oldName", "newName", "key", "createRm", "keychain", "withTimeoutOption", "name", "KeyAPI", "keychain", "createGen", "createList", "createRm", "createRename", "createExport", "createImport", "createInfo", "createGet", "repo", "preload", "get", "cid", "options", "block", "decode", "withTimeoutOption", "createData", "repo", "preload", "get", "createGet", "data", "multihash", "options", "withTimeoutOption", "findLinks", "node", "links", "key", "val", "CID", "cid", "createLinks", "repo", "codecs", "options", "codec", "block", "code", "withTimeoutOption", "createNew", "repo", "preload", "_new", "options", "data", "UnixFS", "buf", "encode", "hash", "sha256", "cid", "CID", "withTimeoutOption", "createPut", "repo", "preload", "put", "obj", "options", "release", "buf", "encode", "hash", "sha256", "cid", "CID", "code", "withTimeoutOption", "createStat", "repo", "preload", "get", "createGet", "stat", "cid", "options", "node", "blockSize", "encode", "linkLength", "a", "l", "withTimeoutOption", "createAddLink", "repo", "preload", "get", "createGet", "put", "createPut", "addLink", "cid", "link", "options", "node", "withTimeoutOption", "createAppendData", "repo", "preload", "get", "createGet", "put", "createPut", "appendData", "cid", "data", "options", "node", "newData", "concat", "withTimeoutOption", "createRmLink", "repo", "preload", "get", "createGet", "put", "createPut", "rmLink", "cid", "link", "options", "node", "name", "withTimeoutOption", "createSetData", "repo", "preload", "get", "createGet", "put", "createPut", "setData", "cid", "data", "options", "node", "withTimeoutOption", "ObjectPatchAPI", "repo", "preload", "createAddLink", "createAppendData", "createRmLink", "createSetData", "ObjectAPI", "repo", "codecs", "preload", "createData", "createGet", "createLinks", "createNew", "createPut", "createStat", "ObjectPatchAPI", "log", "logger", "createGc", "repo", "hashers", "gc", "options", "start", "mfsRootCid", "loadMfsRoot", "withTimeoutOption", "createStat", "repo", "stat", "options", "stats", "withTimeoutOption", "createVersion", "repo", "version", "options", "err", "m", "withTimeoutOption", "RepoAPI", "repo", "hashers", "createGc", "createStat", "createVersion", "addr", "import_err_code", "getBandwidthStats", "libp2p", "opts", "createBw", "network", "withTimeoutOption", "options", "interval", "ms", "parse_duration_default", "err", "errCode", "timeoutId", "resolve", "StatsAPI", "repo", "network", "createStat", "createBw", "objectSafeGet", "get", "obj", "propsArg", "defaultValue", "props", "prop", "import_debug", "import_err_code", "import_debug", "length", "iterator", "count", "_", "log", "debug", "unwrap", "blockstore", "keyToMultihash", "key", "buf", "base32", "multihash", "CID", "multihashStr", "Key", "keyToCid", "digest", "decode", "code", "process", "backends", "onProgress", "keyFunction", "unwrapped", "blockCount", "length", "counter", "block", "newKey", "migration", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "ipfs", "pin", "Set", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "import_fnv1a", "import_varint", "PIN_DS_KEY", "Key", "DEFAULT_FANOUT", "MAX_ITEMS", "EMPTY_KEY", "CID", "PinTypes", "cidToKey", "cid", "base32", "compare", "a", "b", "i", "PinSet", "ipfs", "readHeader", "rootNode", "rootData", "hdrLength", "varint", "vBytes", "hdrSlice", "header", "hash", "seed", "key", "buffer", "encodedKey", "fromString", "data", "concat", "fnv1a", "toString", "walkItems", "blockstore", "node", "pbh", "idx", "link", "linkHash", "EMPTY_KEY", "buf", "decode", "loadSet", "name", "l", "storeItems", "items", "storePins", "pins", "depth", "pbHeader", "DEFAULT_FANOUT", "headerBuf", "fanoutLinks", "i", "MAX_ITEMS", "nodes", "item", "a", "b", "compare", "rootLinks", "bins", "pin", "n", "bin", "child", "storeChild", "binIdx", "encode", "digest", "sha256", "cid", "CID", "size", "acc", "curr", "storeSet", "type", "cids", "pinsToDatastore", "blockstore", "datastore", "pinstore", "onProgress", "PIN_DS_KEY", "mh", "cid", "CID", "pinRootBuf", "pinRoot", "decode", "counter", "pinCount", "length", "loadSet", "PinTypes", "pin", "code", "cidToKey", "encode", "pinsToDAG", "recursivePins", "directPins", "key", "value", "base32", "storeSet", "buf", "digest", "sha256", "process", "backends", "fn", "migration", "CONFIG_KEY", "Key", "VERSION_KEY", "findLevelJs", "store", "db", "hasWithFallback", "key", "has", "result", "levelJs", "resolve", "reject", "req", "getWithFallback", "get", "notFoundError", "wrapStore", "originalGet", "originalHas", "wrapBackends", "backends", "keysToBinary", "name", "store", "onProgress", "db", "findLevelJs", "withEach", "key", "value", "fromString", "keysToStrings", "toString", "unwrap", "process", "backends", "fn", "datastores", "backend", "migrated", "progress", "message", "migration", "batch", "operations", "next", "transaction", "index", "error", "loop", "op", "req", "err", "resolve", "reject", "it", "id", "data", "handleNext", "handleEnd", "err2", "MFS_ROOT_KEY", "Key", "storeMfsRootInDatastore", "backends", "onProgress", "root", "storeMfsRootInRoot", "migration", "import_minimal", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Protocols", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "j", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Addresses", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "j", "Address", "$oneOfFields", "CertifiedRecord", "n", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Peer", "p", "ks", "$oneOfFields", "m", "w", "i", "r", "l", "c", "t", "d", "o", "j", "Address", "Metadata", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Envelope", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "PeerRecord", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "n", "j", "AddressInfo", "Parser", "__publicField", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "parseIP", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "isIP", "parseIP", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "import_varint", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "toString", "convertToBytes", "str", "ip2bytes", "str2bytes", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "fromString", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ipString", "isIP", "toBytes", "ipBuff", "port", "size", "varint", "concat", "hash", "mh", "decode", "base58btc", "CID", "mbstr", "mb", "address", "addr", "base32", "portBuf", "addrBytes", "portBytes", "import_varint", "stringToStringTuples", "str", "tuples", "parts", "p", "part", "proto", "getProtocol", "ParseError", "cleanPath", "stringTuplesToString", "tup", "protoFromTuple", "stringTuplesToTuples", "convertToBytes", "tuplesToStringTuples", "convertToString", "tuplesToBytes", "fromBytes", "concat", "buf", "varint", "sizeForAddr", "addr", "bytesToTuples", "i", "code", "n", "size", "toString", "bytesToString", "a", "b", "stringToBytes", "fromString", "err", "validateBytes", "cleanPath", "str", "a", "ParseError", "protoFromTuple", "tup", "getProtocol", "import_varint", "import_err_code", "inspect", "DNS_CODES", "getProtocol", "resolvers", "symbol", "fromNodeAddress", "addr", "transport", "ip", "host", "parts", "DefaultMultiaddr", "isName", "isMultiaddr", "proto", "value", "_DefaultMultiaddr_string", "_DefaultMultiaddr_tuples", "_DefaultMultiaddr_stringTuples", "_a", "fromBytes", "fromString", "__classPrivateFieldGet", "__classPrivateFieldSet", "bytesToString", "family", "port", "zone", "tcp", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "codes", "buf", "i", "varint", "n", "p", "size", "sizeForAddr", "bytesToTuples", "tuplesToStringTuples", "addrString", "s", "tuples", "tuplesToBytes", "tuple", "names", "peerIdStr", "toString", "base58btc", "CID", "path", "equals", "options", "resolvableProto", "resolver", "errCode", "a", "protos", "multiaddr", "$protobuf", "storePeerUnderSingleDatastoreKey", "backends", "onProgress", "peers", "keys", "key", "value", "keyStr", "prefix", "type", "peerId", "metadataKey", "protos", "Protocols", "addrs", "Addresses", "a", "b", "multiaddr", "peer", "data", "Peer", "Key", "storePeerUnderMultipleDatastoreKeys", "peerRecordEnvelope", "certifiedRecord", "envelope", "Envelope", "record", "PeerRecord", "migration", "emptyMigration", "migrations_default", "migration", "import_debug", "errors_exports", "__export", "InvalidValueError", "MissingRepoOptionsError", "NonReversibleMigrationError", "NotInitializedRepoError", "RequiredParameterError", "message", "log", "debug", "isRepoInitialized", "backends", "MissingRepoOptionsError", "root", "versionCheck", "VERSION_KEY", "configCheck", "CONFIG_KEY", "e", "getVersion", "backends", "isRepoInitialized", "NotInitializedRepoError", "store", "toString", "VERSION_KEY", "setVersion", "version", "MissingRepoOptionsError", "fromString", "import_debug", "log", "debug", "getLatestMigrationVersion", "migrations", "migrations_default", "migrate", "path", "backends", "repoOptions", "toVersion", "options", "ignoreLock", "onProgress", "isDryRun", "errors", "wrapBackends", "currentVersion", "getVersion", "verifyAvailableMigrations", "lock", "migration", "progressCallback", "percent", "message", "e", "lastSuccessfullyMigratedVersion", "setVersion", "revert", "reversedMigrationArray", "lastSuccessfullyRevertedVersion", "fromVersion", "checkReversibility", "migrationCounter", "errors", "errors_exports", "import_bytes", "import_debug", "LockExistsError", "message", "NotFoundError", "InvalidRepoVersionError", "ERR_REPO_NOT_INITIALIZED", "ERR_REPO_ALREADY_OPEN", "ERR_REPO_ALREADY_CLOSED", "hasWithFallback", "key", "has", "store", "result", "levelJs", "findLevelJs", "resolve", "reject", "req", "getWithFallback", "get", "NotFoundError", "db", "log", "debug", "versionKey", "Key", "version", "store", "hasWithFallback", "buf", "getWithFallback", "toString", "fromString", "expected", "import_err_code", "Queue", "PQueue", "configKey", "Key", "config", "store", "setQueue", "configStore", "options", "encodedValue", "getWithFallback", "toString", "key", "NotFoundError", "value", "objectSafeGet", "errCode", "_maybeDoSet", "hasWithFallback", "m", "signal", "objectSafeSet", "_saveAll", "buf", "fromString", "isPlainObject", "value", "prototype", "sortKeys", "object", "options", "isPlainObject", "deep", "compare", "seenInput", "seenOutput", "deepSortArray", "array", "seenIndex", "result", "item", "_sortKeys", "keys", "key", "value", "newValue", "specKey", "Key", "spec", "store", "buf", "toString", "fromString", "sortKeys", "apiFile", "Key", "apiAddr", "store", "value", "fromString", "import_err_code", "createIdStore", "store", "query", "options", "cid", "extracted", "extractContents", "cids", "buf", "isIdentity", "pairs", "output", "pushable", "drain", "key", "value", "err", "filter", "batch", "k", "CID", "errCode", "identity", "import_debug", "log", "debug", "lockFile", "LOCKS", "lock", "dir", "file", "LockExistsError", "locked", "MemoryLock", "default_options_default", "MemoryLock", "default_datastore_default", "import_err_code", "import_debug", "first", "source", "entry", "readonly", "enumerable", "configurable", "linksWithin", "path", "value", "index", "element", "elementPath", "cid", "CID", "links", "source", "base", "key", "treeWithin", "tree", "get", "node", "part", "Block", "bytes", "createUnsafe", "bytes", "cid", "maybeValue", "codec", "value", "Block", "import_err_code", "cidToKey", "c", "cid", "CID", "errCode", "encoded", "base32", "Key", "keyToMultihash", "key", "decode", "base32", "import_debug", "log", "debug", "walkDag", "cid", "blockstore", "loadCodec", "options", "bytes", "codec", "block", "createUnsafe", "childCid", "err", "QuickLRU", "options", "cache", "key", "item", "value", "maxAge", "expiry", "deleted", "newSize", "items", "removeCount", "i", "oldCacheSize", "callbackFunction", "thisArgument", "CID_CACHE_MAX_SIZE", "invalidPinTypeErr", "type", "errMsg", "errCode", "PinManager", "pinstore", "blockstore", "loadCodec", "debug", "cid", "options", "pin", "code", "cidToKey", "encode", "entry", "decode", "version", "codec", "multihash", "keyToMultihash", "CID", "childCid", "walkDag", "types", "PinTypes", "all", "direct", "recursive", "indirect", "result", "first", "self", "findChild", "key", "source", "parentCid", "seen", "QuickLRU", "bytes", "block", "createUnsafe", "import_err_code", "createPinnedBlockstore", "pins", "store", "query", "options", "cid", "cids", "buf", "pairs", "ensureNotPinned", "map", "pinned", "reason", "PinTypes", "errCode", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "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", "emitter", "masterEvent", "requestType", "releaseType", "grantType", "worker", "event", "requestEvent", "resolve", "releaseEventListener", "releaseEvent", "makeWorkerLockRequest", "name", "id", "nanoid", "listener", "responseEvent", "defaultOptions", "browser_default", "options", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "mutexes", "implementation", "createReleaseable", "queue", "options", "res", "p", "resolve", "pTimeout", "createMutex", "name", "masterQueue", "PQueue", "readQueue", "localReadQueue", "readPromise", "defaultOptions", "createMortice", "opts", "browser_default", "event", "release", "import_debug", "batch", "source", "size", "things", "thing", "parallelBatch", "source", "size", "tasks", "batch", "things", "p", "value", "err", "result", "log", "debug", "ERR_NOT_FOUND", "notFoundError", "BLOCK_RM_CONCURRENCY", "MFS_ROOT_KEY", "Key", "gc", "gcLock", "pins", "blockstore", "root", "loadCodec", "start", "release", "markedSet", "createMarkedSet", "blockKeys", "deleteUnmarkedBlocks", "mfsSource", "mh", "err", "rootCid", "CID", "walkDag", "pinsSource", "merge", "map", "cid", "output", "base32", "blocksCount", "removedBlocksCount", "pipe", "parallelBatch", "b32", "msg", "source", "filter", "log", "debug", "noLimit", "AUTO_MIGRATE_CONFIG_KEY", "Repo", "path", "loadCodec", "backends", "options", "merge_options_default", "default_options_default", "blockstore", "pinstore", "PinManager", "pinnedBlockstore", "createPinnedBlockstore", "createIdStore", "version", "config", "spec", "apiAddr", "createMortice", "gc", "buildConfig", "buildDatastoreSpec", "errCode", "ERR_REPO_ALREADY_OPEN", "InvalidRepoVersionError", "err", "err2", "lockfile", "ERR_REPO_NOT_INITIALIZED", "ERR_REPO_ALREADY_CLOSED", "store", "storageMax", "blocks", "datastore", "keys", "getSize", "size", "autoMigrateConfig", "e", "NotFoundError", "toVersion", "revert", "migrate", "max", "bytes", "count", "key", "value", "sum", "block", "createRepo", "_config", "default_datastore_default", "objectSafeGet", "mounting", "sort", "source", "sorter", "all", "import_level", "LevelDatastore", "BaseDatastore", "path", "opts", "err", "errors_exports", "key", "value", "data", "ops", "q", "it", "f", "filter", "sort", "offset", "limit", "i", "take", "map", "iteratorOpts", "prefix", "iterator", "levelIteratorToIterator", "oldLevelIteratorToIterator", "li", "Key", "resolve", "reject", "import_err_code", "sortAll", "iterable", "sorter", "all", "BaseBlockstore", "key", "val", "options", "source", "value", "puts", "dels", "drain", "q", "it", "filter", "e", "f", "take", "cid", "cidToKey", "cid", "c", "CID", "errcode", "Key", "base32", "keyToCid", "key", "code", "decode", "convertPrefix", "prefix", "firstChar", "decoder", "input", "base32pad", "base58btc", "bytes", "i", "err", "str", "convertQuery", "query", "filter", "pair", "order", "a", "b", "convertKeyQuery", "BlockstoreDatastoreAdapter", "BaseBlockstore", "datastore", "options", "value", "cids", "blocks", "output", "pushable", "store", "drain", "block", "out", "createRepo", "print", "codecs", "options", "repoPath", "codeOrName", "LevelDatastore", "BlockstoreDatastoreAdapter", "MemoryLock", "import_dlv", "import_err_code", "accessor", "buf", "index", "value", "TWO_32", "LongBits", "hi", "lo", "unsigned", "mask", "buf", "offset", "access", "accessor", "value", "negative", "sign", "bits", "i", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "unsigned", "value", "buf", "offset", "allocUnsafe", "LongBits", "codes", "Envelope", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "_RecordEnvelope", "init", "__publicField", "peerId", "payloadType", "payload", "signature", "Envelope", "other", "equals", "domain", "signData", "formatSignaturePayload", "unmarshalPublicKey", "RecordEnvelope", "data", "envelopeData", "peerIdFromKeys", "record", "unmarshalPrivateKey", "envelope", "CodeError", "codes", "domainUint8Array", "fromString", "domainLength", "unsigned", "payloadTypeLength", "payloadLength", "Uint8ArrayList", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "PeerRecord", "AddressInfo", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "value", "topologySymbol", "noop", "_a", "TopologyImpl", "init", "__publicField", "topologySymbol", "registrar", "peerId", "createTopology", "_listeners", "EventEmitter", "__privateAdd", "type", "listeners", "__privateGet", "listener", "options", "list", "callback", "event", "result", "once", "detail", "CustomEvent", "CustomEventPolyfill", "message", "data", "__publicField", "MessageCache", "gossip", "historyCapacity", "msgIdToStrFn", "messageId", "msg", "validated", "msgIdStr", "msgId", "fromPeerIdStr", "entry", "_a", "p", "count", "topics", "msgIdsByTopic", "i", "msgIds", "message", "originatingPeers", "cacheEntry", "import_rpc", "RPC", "cjs", "FloodsubID", "GossipsubIDv10", "GossipsubIDv11", "ERR_TOPIC_VALIDATOR_REJECT", "ERR_TOPIC_VALIDATOR_IGNORE", "shuffle", "arr", "randInt", "i", "j", "tmp", "messageIdToString", "msgId", "toString", "StrictSign", "StrictNoSign", "TopicValidatorResult", "SignaturePolicy", "PublishConfigType", "RejectReason", "ValidateError", "MessageStatus", "rejectReasonFromAcceptance", "acceptance", "TopicValidatorResult", "getPublishConfigFromPeerId", "signaturePolicy", "peerId", "StrictSign", "privateKey", "unmarshalPrivateKey", "PublishConfigType", "StrictNoSign", "ERR_INVALID_PEER_SCORE_PARAMS", "defaultPeerScoreParams", "defaultTopicScoreParams", "createPeerScoreParams", "p", "topics", "topic", "topicScoreParams", "createTopicScoreParams", "validatePeerScoreParams", "params", "validateTopicScoreParams", "e", "CodeError", "ERR_INVALID_PEER_SCORE_PARAMS", "defaultPeerScoreThresholds", "createPeerScoreThresholds", "p", "computeScore", "peer", "pstats", "params", "peerIPs", "score", "topic", "tstats", "topicParams", "topicScore", "p1", "p2", "deficit", "p3", "p3b", "p4", "p5", "ip", "peersInIP", "numPeersInIP", "surplus", "p6", "excess", "p7", "import_denque", "DeliveryRecordStatus", "MessageDeliveries", "Denque", "msgIdStr", "drec", "entry", "now", "head", "removeItemsFromSet", "superSet", "ineed", "cond", "subset", "id", "removeFirstNItemsFromSet", "MapDef", "getDefault", "key", "value", "log", "logger", "PeerScore", "params", "metrics", "opts", "MapDef", "MessageDeliveries", "validatePeerScoreParams", "computeScore", "peer", "stats", "now", "decayToZero", "pstats", "id", "topic", "tstats", "tparams", "_a", "_b", "_c", "cacheEntry", "score", "cacheUntil", "penalty", "penaltyLabel", "ip", "peersWithIP", "threshold", "deficit", "msgIdStr", "from", "drec", "DeliveryRecordStatus", "p", "reason", "RejectReason", "cap", "validatedTime", "deliveryDelayMs", "isLateDelivery", "ipsToRemove", "ipToRemove", "peerSet", "topicStats", "IWantTracer", "gossipsubIWantFollowupMs", "msgIdToStrFn", "metrics", "from", "msgIds", "ix", "msgId", "msgIdStr", "expireByPeer", "now", "_a", "result", "brokenPromises", "expire", "p", "isDuplicate", "reason", "RejectReason", "maxMs", "count", "k", "v", "requestMs", "SimpleTimeCache", "opts", "key", "value", "now", "k", "v", "MessageSource", "InclusionReason", "ChurnReason", "ScorePenalty", "IHaveIgnoreReason", "ScoreThreshold", "getMetrics", "register", "topicStrToLabel", "opts", "topicStr", "reason", "count", "topic", "hit", "acceptance", "penalty", "ihave", "idonthave", "iwantByTopic", "iwantDonthave", "iwant", "tosendCount", "tosendGroupCount", "dataLen", "status", "error", "RejectReason", "deliveryDelayMs", "isLateDelivery", "rpc", "rpcBytes", "_a", "_b", "_c", "_d", "graft", "prune", "scores", "scoreThresholds", "graylist", "publish", "gossip", "mesh", "score", "sw", "wsTopic", "scoreByPeer", "peersPerTopicLabel", "peers", "topicLabel", "peersInMesh", "p", "meshScores", "peer", "import_aes", "import_forge", "import_pbkdf2", "import_util", "SignPrefix", "fromString", "buildRawMessage", "publishConfig", "topic", "originalData", "transformedData", "PublishConfigType", "rpcMsg", "randomBytes", "bytes", "concat", "RPC", "msg", "toString", "validateToRawMessage", "signaturePolicy", "StrictNoSign", "ValidateError", "StrictSign", "fromPeerId", "peerIdFromBytes", "publicKey", "unmarshalPublicKey", "equals", "rpcMsgPreSign", "marshalPublicKey", "msgId", "key", "seqno", "seqnoBytes", "fromString", "msgIdFnStrictSign", "msg", "msgId", "msgIdFnStrictNoSign", "sha256", "computeScoreWeights", "peer", "pstats", "params", "peerIPs", "topicStrToLabel", "score", "byTopic", "topic", "tstats", "topicLabel", "topicParams", "topicScores", "p1w", "p2w", "p3w", "p3bw", "p4w", "p1", "p2", "deficit", "p3", "p3b", "p4", "capF", "ws", "p5w", "p6w", "p7w", "p5", "ip", "peersInIP", "numPeersInIP", "surplus", "p6", "p7", "computeAllPeersScoreWeights", "peerIdStrs", "peerStats", "sw", "peerIdStr", "swPeer", "swPeerTopic", "swTopic", "FixedFIFO", "hwm", "__publicField", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "AbortError", "message", "code", "__publicField", "pushable", "options", "_pushable", "buffer", "next", "pushableV", "values", "getNext", "onEnd", "FIFO", "onNext", "ended", "drain", "pDefer", "waitNext", "resolve", "reject", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "signal", "cancel", "listener", "opts", "AbortError", "message", "code", "getIterator", "obj", "abortableSource", "source", "signal", "options", "opts", "iterator", "getIterator", "abortable", "nextAbortHandler", "abortHandler", "result", "abortMessage", "abortCode", "AbortError", "abort", "resolve", "reject", "err", "isKnownAborter", "p", "abortableSink", "sink", "abortableDuplex", "duplex", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "unsigned", "value", "buf", "offset", "allocUnsafe", "LongBits", "allocUnsafe", "len", "_a", "defaultEncoder", "length", "lengthLength", "unsigned", "lengthBuf", "allocUnsafe", "encode", "options", "encodeLength", "source", "chunk", "Uint8ArrayList", "import_err_code", "MAX_LENGTH_LENGTH", "MAX_DATA_LENGTH", "ReadMode", "defaultDecoder", "buf", "length", "unsigned", "decode", "options", "source", "buffer", "Uint8ArrayList", "mode", "dataLength", "lengthDecoder", "maxLengthLength", "maxDataLength", "errCode", "dataLengthLength", "err", "data", "reader", "byteLength", "varByteSource", "done", "value", "l", "OutboundStream", "rawStream", "errCallback", "opts", "pushable", "pipe", "abortableSource", "encode", "data", "InboundStream", "decode", "import_minimal", "defaultDecodeRpcLimits", "decodeRpc", "bytes", "opts", "r", "protobuf", "l", "c", "m", "t", "decodeSubOpts", "decodeMessage", "decodeControlMessage", "decodeControlIHave", "decodeControlIWant", "decodeControlGraft", "decodeControlPrune", "decodePeerInfo", "Protocol", "multiaddrToIPStr", "multiaddr", "tuple", "convertToString", "GossipStatusCode", "GossipSub", "EventEmitter", "components", "options", "GossipsubIDv11", "GossipsubIDv10", "pushable", "_a", "timer", "err", "msToNextHeartbeat", "opts", "createPeerScoreParams", "createPeerScoreThresholds", "defaultDecodeRpcLimits", "StrictSign", "FloodsubID", "logger", "p", "SimpleTimeCache", "msgIdFnStrictSign", "StrictNoSign", "msgIdFnStrictNoSign", "messageIdToString", "MessageCache", "maxMeshMessageDeliveriesWindowMs", "topicParam", "metrics", "getMetrics", "protocol", "IWantTracer", "PeerScore", "str", "peerIdFromString", "getPublishConfigFromPeerId", "pipe", "source", "peerId", "connection", "e", "registrar", "multicodec", "topology", "createTopology", "registrarTopologyIds", "heartbeatTimeout", "id", "outboundStream", "inboundStream", "stream", "OutboundStream", "priorInboundStream", "InboundStream", "direction", "addr", "currentIP", "multiaddrToIPStr", "_b", "peers", "topicStr", "ChurnReason", "topic", "peersInTopic", "_c", "data", "rpcBytes", "rpc", "decodeRpc", "from", "subscriptions", "messages", "ihave", "iwant", "graft", "prune", "subOpt", "subscribe", "CustomEvent", "message", "handleReceivedMessagePromise", "topicSet", "rpcMsg", "validationResult", "MessageStatus", "msgIdStr", "propagationSource", "fastMsgIdStr", "msgIdCached", "validateToRawMessage", "RejectReason", "msg", "ValidateError", "msgId", "messageId", "topicValidator", "acceptance", "errCode", "ERR_TOPIC_VALIDATOR_IGNORE", "TopicValidatorResult", "ERR_TOPIC_VALIDATOR_REJECT", "rejectReasonFromAcceptance", "toPeer", "topics", "controlMsg", "sent", "iwantMessageIds", "now", "entry", "score", "IHaveIgnoreReason", "peerhave", "iasked", "topicID", "messageIDs", "idonthave", "iask", "iwantList", "shuffle", "iwantByTopic", "iwantDonthave", "doPX", "peersInMesh", "expire", "ScorePenalty", "floodCutoff", "InclusionReason", "backoff", "interval", "count", "toconnect", "pi", "peerIdFromBytes", "envelope", "RecordEnvelope", "eid", "wasSubscribed", "toAdd", "fanoutPeers", "fanoutCount", "peer", "meshPeers", "excludePeers", "tosend", "tosendCount", "newFanoutPeers", "rawMsg", "transformedData", "buildRawMessage", "ignoreDuplicatePublishError", "willSendToSelf", "allowPublishToZeroPeers", "_d", "cacheEntry", "originatingPeers", "rejectReason", "ctrl", "RPC", "outRpc", "tograft", "toprune", "noPX", "pruning", "peersToGossipByTopic", "gossipIDsByTopic", "peersToGossip", "candidateToGossip", "target", "factor", "peerMessageIDs", "control", "controlIHaveMsgs", "gossip", "xid", "px", "D", "Dlo", "Dhi", "Dscore", "Dout", "fanoutTTL", "scores", "getScore", "s", "candidateMeshPeers", "shuffledPeers", "peerStreams", "prunePeer", "reason", "graftPeer", "ineed", "removeFirstNItemsFromSet", "peersArray", "a", "b", "outbound", "rotate", "i", "j", "removeItemsFromSet", "peersList", "medianIndex", "medianScore", "newMeshPeers", "lastpb", "topicPeers", "candidateFanoutPeers", "filter", "backoffSize", "scoreByPeer", "peerIdStr", "sw", "computeAllPeersScoreWeights", "gossipsub", "init", "routers", "gossipsub", "import_debug", "debug", "v", "base58btc", "base32", "base64", "createDisabledLogger", "namespace", "logger", "logger", "name", "trace", "createDisabledLogger", "debug", "r", "n", "symbol", "inspect", "baseDecoder", "bases", "codec", "acc", "curr", "LIBP2P_KEY_CODE", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "_a", "PeerIdImpl", "init", "__publicField", "base58btc", "CID", "id", "equals", "peerIdFromString", "symbol", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "peerIdFromString", "str", "decoder", "baseDecoder", "multihash", "decode", "base58btc", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "RSAPeerIdImpl", "peerIdFromBytes", "buf", "identity", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "sha256", "peerIdFromCID", "CID", "cid", "LIBP2P_KEY_CODE", "anySignal", "signals", "controller", "onAbort", "signal", "clear", "log", "logger", "DEFAULT_TIMEOUT", "CONCURRENT_HTTP_REQUESTS", "EventTypes", "MessageType", "DelegatedPeerRouting", "client", "__publicField", "dist_default", "protocol", "host", "port", "id", "options", "signal", "anySignal", "onStart", "pDefer", "onFinish", "event", "CodeError", "err", "key", "cidOrPeerId", "cid", "CID", "peerIdFromBytes", "closer", "delegatedPeerRouting", "import_err_code", "isAsyncIterable", "thing", "drain", "source", "_", "src_default", "log", "logger", "DEFAULT_TIMEOUT", "CONCURRENT_HTTP_REQUESTS", "CONCURRENT_HTTP_REFS_REQUESTS", "EventTypes", "MessageType", "DelegatedContentRouting", "client", "__publicField", "dist_default", "protocol", "host", "port", "key", "options", "signal", "anySignal", "onStart", "pDefer", "onFinish", "event", "prov", "err", "src_default", "value", "errCode", "delegatedContentRouting", "LOAD_BASE", "name", "Multibases", "options", "base", "nameOrPrefix", "LOAD_CODEC", "codeOrName", "Multicodecs", "options", "codec", "code", "table", "LOAD_HASHER", "codeOrName", "Multihashes", "options", "hasher", "code", "table", "import_env", "import_http", "toUrlString", "url", "multiaddrToUri", "multiaddr", "agent_browser_default", "log", "logger", "merge", "merge_options_default", "DEFAULT_PROTOCOL", "DEFAULT_HOST", "DEFAULT_PORT", "normalizeOptions", "options", "url", "opts", "agent", "isMultiaddr", "toUrlString", "protocol", "host", "port", "Agent", "agent_browser_default", "errorHandler", "response", "msg", "data", "err", "error", "HTTP", "KEBAB_REGEX", "kebabCase", "str", "match", "parseTimeout", "value", "parse_duration_default", "Client", "search", "out", "key", "fetch", "resource", "HTTPError", "configure", "fn", "options", "Client", "modeToString", "mode", "import_err_code", "parseMtime", "input", "mtime", "ms", "secs", "errCode", "toUrlSearchParams", "arg", "searchParams", "hashAlg", "mtime", "mode", "options", "parseMtime", "modeToString", "urlSearchParams", "createWantlist", "configure", "api", "wantlist", "options", "toUrlSearchParams", "k", "CID", "createWantlistForPeer", "configure", "api", "wantlistForPeer", "peerId", "options", "toUrlSearchParams", "k", "CID", "createStat", "configure", "api", "stat", "options", "res", "toUrlSearchParams", "toCoreInterface", "k", "CID", "str", "peerIdFromString", "createUnwant", "configure", "api", "unwant", "cid", "options", "toUrlSearchParams", "createBitswap", "config", "createWantlist", "createWantlistForPeer", "createUnwant", "createStat", "createGet", "configure", "api", "get", "cid", "options", "res", "toUrlSearchParams", "import_err_code", "normaliseContent", "input", "isBytes", "isBlob", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "itToBlob", "all", "errCode", "stream", "parts", "chunk", "normaliseInput", "input", "normaliseCandidateMultiple", "normaliseContent", "modeToString", "mode", "multipartRequest", "source", "abortController", "headers", "parts", "formData", "index", "total", "content", "path", "mode", "mtime", "normaliseInput", "fileSuffix", "type", "fieldName", "qs", "modeToString", "secs", "nsecs", "end", "import_any_signal", "filter", "signals", "abortSignal", "createPut", "configure", "api", "put", "data", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "multipartRequest", "err", "CID", "createRm", "configure", "api", "rm", "cid", "options", "res", "toUrlSearchParams", "removed", "toCoreInterface", "out", "CID", "createStat", "configure", "api", "stat", "cid", "options", "data", "toUrlSearchParams", "CID", "createBlock", "config", "createGet", "createPut", "createRm", "createStat", "createAdd", "configure", "api", "add", "addr", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createClear", "configure", "api", "clear", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createList", "configure", "api", "list", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createReset", "configure", "api", "reset", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createRm", "configure", "api", "rm", "addr", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createBootstrap", "config", "createAdd", "createClear", "createList", "createReset", "createRm", "createApply", "configure", "api", "apply", "profile", "options", "data", "toUrlSearchParams", "objectToCamel", "obj", "caps", "output", "camelObj", "k", "createList", "configure", "api", "list", "options", "toUrlSearchParams", "profile", "objectToCamel", "createProfiles", "config", "createApply", "createList", "createGet", "configure", "api", "key", "options", "toUrlSearchParams", "createGetAll", "configure", "api", "options", "toUrlSearchParams", "createReplace", "configure", "api", "config", "options", "controller", "signal", "abortSignal", "toUrlSearchParams", "multipartRequest", "fromString", "createSet", "configure", "api", "key", "value", "options", "params", "encodeParam", "toUrlSearchParams", "createConfig", "config", "createGetAll", "createGet", "createSet", "createReplace", "createProfiles", "createExport", "configure", "api", "dagExport", "root", "options", "toUrlSearchParams", "import_err_code", "resolve", "cid", "path", "codecs", "getBlock", "options", "load", "codec", "block", "parts", "value", "lastCid", "key", "errCode", "CID", "import_err_code", "createGet", "codecs", "options", "configure", "api", "opts", "getBlock", "cid", "result", "first", "resolve", "last", "errCode", "codec", "block", "createImport", "configure", "api", "dagImport", "source", "options", "controller", "signal", "abortSignal", "headers", "body", "multipartRequest", "res", "toUrlSearchParams", "Root", "Cid", "PinErrorMsg", "CID", "createPut", "codecs", "options", "configure", "api", "dagNode", "settings", "serialized", "controller", "signal", "abortSignal", "data", "toUrlSearchParams", "multipartRequest", "CID", "createResolve", "configure", "api", "ipfsPath", "options", "data", "toUrlSearchParams", "CID", "createDag", "codecs", "config", "createExport", "createGet", "createImport", "createPut", "createResolve", "mapEvent", "event", "peerIdFromString", "ID", "Addrs", "addr", "multiaddr", "peer", "fromString", "peers", "createFindPeer", "configure", "api", "findPeer", "peerId", "options", "res", "toUrlSearchParams", "event", "mapEvent", "createFindProvs", "configure", "api", "findProvs", "cid", "options", "res", "toUrlSearchParams", "event", "mapEvent", "createGet", "configure", "api", "get", "key", "options", "res", "toUrlSearchParams", "toString", "event", "mapEvent", "createProvide", "configure", "api", "provide", "cids", "options", "cidArr", "res", "toUrlSearchParams", "cid", "event", "mapEvent", "createPut", "configure", "api", "put", "key", "value", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "toString", "multipartRequest", "event", "mapEvent", "createQuery", "configure", "api", "query", "peerId", "options", "res", "toUrlSearchParams", "event", "mapEvent", "createDht", "config", "createFindPeer", "createFindProvs", "createGet", "createProvide", "createPut", "createQuery", "createCmds", "configure", "api", "cmds", "options", "toUrlSearchParams", "createNet", "configure", "api", "net", "options", "toUrlSearchParams", "createSys", "configure", "api", "sys", "options", "toUrlSearchParams", "createDiag", "config", "createCmds", "createNet", "createSys", "createChmod", "configure", "api", "chmod", "path", "mode", "options", "toUrlSearchParams", "createCp", "configure", "api", "cp", "sources", "destination", "options", "sourceArr", "toUrlSearchParams", "src", "CID", "createFlush", "configure", "api", "flush", "path", "options", "data", "toUrlSearchParams", "CID", "objectToCamelWithMetadata", "entry", "file", "objectToCamel", "createLs", "configure", "api", "ls", "path", "options", "res", "toUrlSearchParams", "CID", "result", "entry", "toCoreInterface", "objectToCamelWithMetadata", "createMkdir", "configure", "api", "mkdir", "path", "options", "toUrlSearchParams", "createMv", "configure", "api", "mv", "sources", "destination", "options", "toUrlSearchParams", "import_source", "createRead", "configure", "api", "read", "path", "options", "res", "toUrlSearchParams", "toIterable", "import_http", "createRm", "configure", "api", "rm", "path", "options", "res", "toUrlSearchParams", "body", "error", "HTTP", "createStat", "configure", "api", "stat", "path", "options", "data", "toUrlSearchParams", "toCoreInterface", "objectToCamelWithMetadata", "entry", "CID", "createTouch", "configure", "api", "touch", "path", "options", "toUrlSearchParams", "createWrite", "configure", "api", "write", "path", "input", "options", "controller", "signal", "abortSignal", "toUrlSearchParams", "multipartRequest", "modeToString", "parseMtime", "createFiles", "config", "createChmod", "createCp", "createFlush", "createLs", "createMkdir", "createMv", "createRead", "createRm", "createStat", "createTouch", "createWrite", "import_err_code", "createExport", "configure", "api", "name", "password", "options", "errCode", "createGen", "configure", "api", "gen", "name", "options", "opts", "data", "toUrlSearchParams", "objectToCamel", "createImport", "configure", "api", "importKey", "name", "pem", "password", "options", "data", "toUrlSearchParams", "objectToCamel", "import_err_code", "createInfo", "configure", "api", "name", "options", "errCode", "createList", "configure", "api", "list", "options", "toUrlSearchParams", "k", "objectToCamel", "createRename", "configure", "api", "rename", "oldName", "newName", "options", "res", "toUrlSearchParams", "objectToCamel", "createRm", "configure", "api", "rm", "name", "options", "data", "toUrlSearchParams", "objectToCamel", "createKey", "config", "createExport", "createGen", "createImport", "createInfo", "createList", "createRename", "createRm", "createLevel", "configure", "api", "level", "subsystem", "options", "res", "toUrlSearchParams", "objectToCamel", "createLs", "configure", "api", "ls", "options", "toUrlSearchParams", "createTail", "configure", "api", "tail", "options", "toUrlSearchParams", "createLog", "config", "createLevel", "createLs", "createTail", "createPublish", "configure", "api", "publish", "path", "options", "res", "toUrlSearchParams", "objectToCamel", "createResolve", "configure", "api", "resolve", "path", "options", "res", "toUrlSearchParams", "result", "createCancel", "configure", "api", "cancel", "name", "options", "res", "toUrlSearchParams", "objectToCamel", "createState", "configure", "api", "state", "options", "res", "toUrlSearchParams", "objectToCamel", "createSubs", "configure", "api", "subs", "options", "toUrlSearchParams", "createPubsub", "config", "createCancel", "createState", "createSubs", "createName", "config", "createPublish", "createResolve", "createPubsub", "createData", "configure", "api", "data", "cid", "options", "toUrlSearchParams", "CID", "createGet", "configure", "api", "get", "cid", "options", "data", "toUrlSearchParams", "CID", "fromString", "link", "createLinks", "configure", "api", "links", "cid", "options", "toUrlSearchParams", "CID", "l", "createNew", "configure", "api", "newObject", "options", "res", "toUrlSearchParams", "Hash", "CID", "createPut", "codecs", "options", "configure", "api", "dagPut", "put", "obj", "createStat", "configure", "api", "stat", "cid", "options", "output", "toUrlSearchParams", "CID", "createAddLink", "configure", "api", "addLink", "cid", "dLink", "options", "res", "toUrlSearchParams", "Hash", "CID", "createAppendData", "configure", "api", "appendData", "cid", "data", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "multipartRequest", "Hash", "CID", "createRmLink", "configure", "api", "rmLink", "cid", "dLink", "options", "res", "toUrlSearchParams", "Hash", "CID", "createSetData", "configure", "api", "setData", "cid", "data", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "multipartRequest", "Hash", "CID", "createPatch", "config", "createAddLink", "createAppendData", "createRmLink", "createSetData", "createObject", "codecs", "config", "createData", "createGet", "createLinks", "createNew", "createPut", "createStat", "createPatch", "createAddAll", "configure", "api", "addAll", "source", "options", "path", "recursive", "metadata", "normaliseInput", "res", "toUrlSearchParams", "pin", "cid", "CID", "createAdd", "config", "all", "createAddAll", "configure", "add", "path", "options", "last", "toPin", "type", "cid", "metadata", "pin", "CID", "createLs", "configure", "api", "ls", "options", "paths", "res", "toUrlSearchParams", "path", "createRmAll", "configure", "api", "rmAll", "source", "options", "path", "recursive", "normaliseInput", "searchParams", "res", "toUrlSearchParams", "pin", "cid", "CID", "createRm", "config", "all", "createRmAll", "configure", "rm", "path", "options", "last", "decodePin", "name", "status", "cid", "CID", "encodeService", "service", "encodeCID", "encodeQuery", "all", "query", "toUrlSearchParams", "value", "encodeAddParams", "background", "origins", "params", "origin", "createAdd", "client", "add", "cid", "timeout", "signal", "headers", "query", "response", "encodeAddParams", "decodePin", "createLs", "client", "ls", "timeout", "signal", "headers", "query", "response", "encodeQuery", "pin", "decodePin", "createRm", "client", "rm", "timeout", "signal", "headers", "query", "encodeQuery", "createRmAll", "client", "rmAll", "timeout", "signal", "headers", "query", "encodeQuery", "encodeEndpoint", "url", "href", "decodeRemoteService", "json", "decodeStat", "Pinning", "Pinned", "Queued", "Failed", "createAdd", "client", "add", "name", "options", "endpoint", "key", "headers", "timeout", "signal", "toUrlSearchParams", "encodeEndpoint", "createLs", "client", "ls", "options", "stat", "headers", "timeout", "signal", "response", "toUrlSearchParams", "RemoteServices", "decodeRemoteService", "createRm", "client", "rm", "name", "options", "toUrlSearchParams", "createService", "config", "client", "Client", "createAdd", "createLs", "createRm", "createRemote", "config", "client", "Client", "createAdd", "createLs", "createRm", "createRmAll", "createService", "createPin", "config", "createAddAll", "createAdd", "createLs", "createRmAll", "createRm", "createRemote", "rpcArrayToTextArray", "strings", "rpcToText", "mb", "toString", "rpcToBytes", "base64url", "rpcToBigInt", "textToUrlSafeRpc", "text", "fromString", "createLs", "configure", "api", "ls", "options", "Strings", "toUrlSearchParams", "rpcArrayToTextArray", "createPeers", "configure", "api", "peers", "topic", "options", "res", "toUrlSearchParams", "textToUrlSafeRpc", "Strings", "createPublish", "configure", "api", "publish", "topic", "data", "options", "searchParams", "toUrlSearchParams", "textToUrlSafeRpc", "controller", "signal", "abortSignal", "multipartRequest", "log", "logger", "createSubscribe", "options", "subsTracker", "configure", "api", "subscribe", "topic", "handler", "done", "fail", "result", "resolve", "reject", "ffWorkaround", "toUrlSearchParams", "textToUrlSafeRpc", "err", "response", "readMessages", "message", "onMessage", "onEnd", "onError", "msg", "peerIdFromString", "rpcToBytes", "rpcToBigInt", "rpcToText", "isAbortError", "error", "createUnsubscribe", "options", "subsTracker", "unsubscribe", "topic", "handler", "SubscriptionTracker", "topic", "handler", "signal", "topicSubs", "controller", "subs", "unsubs", "s", "createPubsub", "config", "subscriptionTracker", "SubscriptionTracker", "createLs", "createPeers", "createPublish", "createSubscribe", "createUnsubscribe", "createLocal", "configure", "api", "refsLocal", "options", "objectToCamel", "toUrlSearchParams", "createRefs", "configure", "api", "opts", "args", "options", "argsArr", "toUrlSearchParams", "arg", "CID", "objectToCamel", "createLocal", "createGc", "configure", "api", "gc", "options", "toUrlSearchParams", "res", "CID", "createStat", "configure", "api", "stat", "options", "data", "toUrlSearchParams", "createVersion", "configure", "api", "version", "options", "toUrlSearchParams", "createRepo", "config", "createGc", "createStat", "createVersion", "createBw", "configure", "api", "bw", "options", "toUrlSearchParams", "stats", "createStats", "config", "createStat", "createBw", "createAddrs", "configure", "api", "addrs", "options", "res", "toUrlSearchParams", "Addrs", "id", "peerIdFromString", "a", "multiaddr", "createConnect", "configure", "api", "connect", "addr", "options", "res", "toUrlSearchParams", "Strings", "createDisconnect", "configure", "api", "disconnect", "addr", "options", "res", "toUrlSearchParams", "Strings", "createLocalAddrs", "configure", "api", "localAddrs", "options", "res", "toUrlSearchParams", "Strings", "a", "multiaddr", "createPeers", "configure", "api", "peers", "options", "res", "toUrlSearchParams", "Peers", "peer", "multiaddr", "peerIdFromString", "createSwarm", "config", "createAddrs", "createConnect", "createDisconnect", "createLocalAddrs", "createPeers", "createAddAll", "configure", "api", "addAll", "source", "options", "controller", "signal", "abortSignal", "headers", "body", "total", "parts", "multipartRequest", "progressFn", "onUploadProgress", "createProgressHandler", "res", "toUrlSearchParams", "file", "objectToCamel", "toCoreInterface", "progress", "createOnUploadProgress", "size", "index", "count", "loaded", "position", "start", "end", "name", "hash", "mode", "mtime", "mtimeNsecs", "output", "CID", "createAdd", "options", "all", "createAddAll", "configure", "add", "input", "last", "normaliseInput", "createCat", "configure", "api", "cat", "path", "options", "toUrlSearchParams", "createCommands", "configure", "api", "options", "toUrlSearchParams", "createDns", "configure", "api", "domain", "options", "toUrlSearchParams", "createGetEndpointConfig", "configure", "api", "url", "createGet", "configure", "api", "get", "path", "options", "opts", "CID", "toUrlSearchParams", "createId", "configure", "api", "id", "options", "data", "toUrlSearchParams", "output", "objectToCamel", "peerIdFromString", "ma", "multiaddr", "createIsOnline", "options", "id", "createId", "isOnline", "res", "createLs", "configure", "api", "opts", "ls", "path", "options", "pathStr", "CID", "mapLink", "link", "hash", "ipfsPath", "createStat", "entry", "typeOf", "res", "toUrlSearchParams", "result", "links", "createMount", "configure", "api", "mount", "options", "res", "toUrlSearchParams", "objectToCamel", "createPing", "configure", "api", "ping", "peerId", "options", "toUrlSearchParams", "objectToCamel", "createResolve", "configure", "api", "resolve", "path", "options", "res", "toUrlSearchParams", "Path", "import_err_code", "createStart", "configure", "api", "options", "errCode", "createStop", "configure", "api", "stop", "options", "toUrlSearchParams", "createVersion", "configure", "api", "version", "options", "res", "toUrlSearchParams", "objectToCamel", "import_url_source", "create", "options", "id", "identity", "multibaseCodecs", "bases", "base", "multibases", "Multibases", "blockCodecs", "codecs", "src_exports", "lib_exports", "codec", "multicodecs", "Multicodecs", "multihashHashers", "hashes", "hasher", "multihashes", "Multihashes", "createAdd", "createAddAll", "createBitswap", "createBlock", "createBootstrap", "createCat", "createCommands", "createConfig", "createDag", "createDht", "createDiag", "createDns", "createFiles", "createGet", "createGetEndpointConfig", "createId", "createIsOnline", "createKey", "createLog", "createLs", "createMount", "createName", "createObject", "createPin", "createPing", "createPubsub", "createRefs", "createRepo", "createResolve", "createStart", "createStats", "createStop", "createSwarm", "createVersion", "import_err_code", "AbortError", "message", "code", "getIterator", "obj", "abortableSource", "source", "signal", "options", "opts", "iterator", "getIterator", "abortable", "nextAbortHandler", "abortHandler", "result", "abortMessage", "abortCode", "AbortError", "abort", "resolve", "reject", "err", "isKnownAborter", "p", "abortableSink", "sink", "abortableDuplex", "duplex", "DNS4", "base", "DNS6", "DNSADDR", "DNS", "or", "IP", "TCP", "and", "UDP", "UTP", "QUIC", "WebSockets", "WebSocketsSecure", "HTTP", "HTTPS", "WebRTCStar", "WebSocketStar", "WebRTCDirect", "Reliable", "Stardust", "_P2P", "_Circuit", "CircuitRecursive", "Circuit", "P2P", "makeMatchesFunction", "partialMatch", "matches", "a", "ma", "multiaddr", "out", "and", "args", "arg", "or", "res", "base", "n", "name", "pnames", "protos", "import_err_code", "PACKET_TYPES", "PACKET_TYPES_REVERSE", "key", "ERROR_PACKET", "withNativeBlob", "withNativeArrayBuffer", "isView", "obj", "encodePacket", "type", "data", "supportsBinary", "callback", "encodeBlobAsBase64", "PACKET_TYPES", "fileReader", "content", "encodePacket_browser_default", "chars", "lookup", "i", "decode", "base64", "bufferLength", "len", "i", "p", "encoded1", "encoded2", "encoded3", "encoded4", "arraybuffer", "bytes", "lookup", "withNativeArrayBuffer", "decodePacket", "encodedPacket", "binaryType", "mapBinary", "type", "decodeBase64Packet", "PACKET_TYPES_REVERSE", "ERROR_PACKET", "data", "decoded", "decode", "decodePacket_browser_default", "SEPARATOR", "encodePayload", "packets", "callback", "length", "encodedPackets", "count", "packet", "i", "encodePacket_browser_default", "encodedPacket", "decodePayload", "encodedPayload", "binaryType", "decodedPacket", "decodePacket_browser_default", "protocol", "Emitter", "obj", "mixin", "key", "event", "fn", "on", "callbacks", "cb", "args", "i", "len", "globalThisShim", "pick", "obj", "attr", "acc", "k", "NATIVE_SET_TIMEOUT", "globalThisShim", "NATIVE_CLEAR_TIMEOUT", "installTimerFunctions", "opts", "BASE64_OVERHEAD", "byteLength", "utf8Length", "str", "c", "length", "i", "l", "TransportError", "reason", "description", "context", "Transport", "Emitter", "opts", "installTimerFunctions", "packets", "data", "packet", "decodePacket_browser_default", "details", "onPause", "alphabet", "length", "map", "seed", "i", "prev", "encode", "num", "encoded", "yeast", "now", "encode", "prev", "seed", "i", "length", "map", "alphabet", "encode", "obj", "str", "i", "decode", "qs", "qry", "pairs", "l", "pair", "value", "hasCORS", "XHR", "opts", "xdomain", "hasCORS", "globalThisShim", "empty", "hasXHR2", "XHR", "Polling", "Transport", "opts", "isSSL", "port", "forceBase64", "onPause", "pause", "total", "data", "callback", "packet", "decodePayload", "close", "packets", "encodePayload", "query", "schema", "yeast", "encodedQuery", "encode", "ipv6", "Request", "fn", "req", "xhrStatus", "context", "Emitter", "uri", "installTimerFunctions", "pick", "xhr", "i", "e", "err", "fromError", "unloadHandler", "terminationEvent", "globalThisShim", "nextTick", "cb", "setTimeoutFn", "WebSocket", "globalThisShim", "usingBrowserWebSocket", "defaultBinaryType", "isReactNative", "WS", "Transport", "opts", "uri", "protocols", "pick", "usingBrowserWebSocket", "WebSocket", "err", "defaultBinaryType", "closeEvent", "ev", "packets", "i", "packet", "lastPacket", "encodePacket_browser_default", "data", "nextTick", "query", "schema", "port", "yeast", "encodedQuery", "encode", "ipv6", "transports", "WS", "Polling", "re", "parts", "parse", "str", "src", "b", "e", "m", "uri", "i", "pathNames", "queryKey", "obj", "path", "regx", "names", "query", "data", "$0", "$1", "$2", "Socket", "Emitter", "uri", "opts", "parse", "installTimerFunctions", "decode", "name", "query", "protocol", "transports", "transport", "reason", "failed", "onTransportOpen", "msg", "cleanup", "err", "freezeTransport", "onerror", "error", "onTransportClose", "onclose", "onupgrade", "to", "i", "l", "packet", "data", "packets", "payloadSize", "byteLength", "options", "fn", "type", "close", "cleanupAndClose", "waitForUpgrade", "description", "upgrades", "filteredUpgrades", "j", "protocol", "Socket", "url", "uri", "path", "loc", "obj", "parse", "host", "esm_exports", "__export", "Decoder", "Encoder", "PacketType", "protocol", "withNativeArrayBuffer", "isView", "obj", "toString", "withNativeBlob", "withNativeFile", "isBinary", "hasBinary", "toJSON", "i", "l", "key", "deconstructPacket", "packet", "buffers", "packetData", "pack", "_deconstructPacket", "data", "isBinary", "placeholder", "newData", "i", "key", "reconstructPacket", "_reconstructPacket", "protocol", "PacketType", "Encoder", "replacer", "obj", "hasBinary", "str", "deconstruction", "deconstructPacket", "pack", "buffers", "Decoder", "Emitter", "reviver", "packet", "isBinaryEvent", "BinaryReconstructor", "isBinary", "i", "p", "start", "buf", "next", "c", "payload", "type", "binData", "reconstructPacket", "on", "obj", "ev", "fn", "RESERVED_EVENTS", "Socket", "Emitter", "io", "nsp", "opts", "on", "args", "ev", "packet", "PacketType", "id", "ack", "isTransportWritable", "_a", "timeout", "timer", "i", "withErr", "resolve", "reject", "arg1", "arg2", "err", "responseArgs", "force", "data", "reason", "description", "listeners", "listener", "self", "sent", "pid", "subDestroy", "compress", "Backoff", "opts", "ms", "rand", "deviation", "min", "max", "jitter", "Manager", "Emitter", "uri", "opts", "_a", "installTimerFunctions", "Backoff", "_parser", "esm_exports", "v", "fn", "Socket", "socket", "self", "openSubDestroy", "on", "errorSub", "err", "timeout", "timer", "data", "e", "packet", "nextTick", "nsp", "nsps", "encodedPackets", "i", "subDestroy", "reason", "description", "delay", "attempt", "cache", "lookup", "uri", "opts", "parsed", "url", "source", "id", "path", "sameNamespace", "newConnection", "io", "Manager", "Socket", "EventEmitter", "_EventEmitter_listeners", "type", "listeners", "__classPrivateFieldGet", "listener", "options", "list", "callback", "event", "result", "once", "detail", "CustomEvent", "CustomEventPolyfill", "message", "data", "import_err_code", "import_random", "import_err_code", "MAX_BUFFERED_AMOUNT", "CHANNEL_CLOSING_TIMEOUT", "WebRTCDataChannel", "channel", "opts", "pDefer", "event", "_a", "_b", "_c", "_d", "_e", "err", "errCode", "isClosing", "data", "import_delay", "DEFAULT_PEER_CONNECTION_CONFIG", "getBrowserRTC", "errCode", "wrtc", "WebRTCPeer", "EventEmitter", "opts", "toString", "randombytes", "logger", "pDefer", "pushable", "source", "buf", "event", "dataChannel", "err", "WebRTCDataChannel", "CustomEvent", "_a", "delay", "import_err_code", "WebRTCHandshake", "EventEmitter", "options", "err", "signal", "iceCandidate", "errCode", "log", "logger", "WebRTCReceiver", "WebRTCPeer", "opts", "WebRTCReceiverHandshake", "event", "CustomEvent", "signal", "err", "WebRTCHandshake", "options", "candidate", "answer", "import_random", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "rejectHandler", "error", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "import_delay", "log", "logger", "ICECOMPLETE_TIMEOUT", "WebRTCInitiator", "WebRTCPeer", "opts", "toString", "randombytes", "WebRTCInitiatorHandshake", "event", "CustomEvent", "signal", "err", "WebRTCHandshake", "options", "offer", "pEvent", "delay", "log", "logger", "toMultiaddrConnection", "socket", "options", "sink", "source", "maConn", "abortableSource", "err", "start", "timeout", "host", "port", "cleanUrlSIO", "ma", "maStrSplit", "tcpProto", "wsProto", "tcpPort", "isName", "cleanMultiaddr", "maStr", "legacy", "multiaddr", "tuppleIPFS", "tupple", "log", "logger", "sioOptions", "SigServer", "EventEmitter", "signallingUrl", "signallingAddr", "upgrader", "handler", "channelOptions", "lookup", "previouslyConnected", "err", "CustomEvent", "maStr", "intentId", "srcMultiaddr", "dstMultiaddr", "channel", "WebRTCReceiver", "onError", "evt", "signal", "maConn", "toMultiaddrConnection", "conn", "untrackConn", "c", "offer", "pendingSignals", "handshake", "WebRTCListener", "peerId", "transport", "options", "ma", "errCode", "defer", "pDefer", "cleanUrlSIO", "server", "createListener", "import_random", "symbol", "isPeerId", "other", "inspect", "baseDecoder", "bases", "codec", "acc", "curr", "LIBP2P_KEY_CODE", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "PeerIdImpl", "init", "symbol", "base58btc", "CID", "id", "_a", "equals", "peerIdFromString", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "peerIdFromPeerId", "other", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "CodeError", "peerIdFromString", "str", "decoder", "baseDecoder", "multihash", "decode", "base58btc", "peerIdFromBytes", "buf", "identity", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "sha256", "peerIdFromCID", "CID", "cid", "LIBP2P_KEY_CODE", "peerIdFromKeys", "publicKey", "privateKey", "create", "symbol", "FaultTolerance", "symbol", "webrtcSupport", "log", "logger", "noop", "WebRTCStarDiscovery", "EventEmitter", "symbol", "event", "WebRTCStar", "init", "ma", "options", "rawConn", "maConn", "toMultiaddrConnection", "conn", "_a", "AbortError", "channelOptions", "cOpts", "intentId", "toString", "randomBytes", "resolve", "reject", "sio", "cleanUrlSIO", "errcode", "connected", "channel", "WebRTCInitiator", "onError", "evt", "err", "msg", "done", "onReady", "onAbort", "signal", "offer", "createListener", "multiaddrs", "maStr", "cleanMultiaddr", "multiaddr", "peerIdStr", "peerId", "peerIdFromString", "CustomEvent", "webRTCStar", "init", "transport", "WebRTCStar", "components", "libp2pConfig", "webRtcStar", "webRTCStar", "isStartable", "obj", "import_err_code", "messages", "codes", "import_err_code", "storeAddresses", "source", "peerStore", "map", "peer", "uniquePeers", "seen", "filter", "requirePeers", "min", "errCode", "import_timeout_abort_controller", "import_set_delayed_interval", "import_events", "log", "logger", "DefaultPeerRouting", "components", "init", "_a", "_b", "drain", "err", "id", "options", "errCode", "codes", "output", "pipe", "merge", "router", "source", "filter", "storeAddresses", "first", "messages", "key", "uniquePeers", "requirePeers", "import_err_code", "CompoundContentRouting", "components", "init", "key", "options", "errCode", "codes", "pipe", "merge", "router", "source", "storeAddresses", "uniquePeers", "requirePeers", "value", "messages", "dht", "drain", "event", "nVals", "gotValues", "defaultAddressFilter", "addrs", "DefaultAddressManager", "EventEmitter", "components", "init", "listen", "announce", "ma", "a", "multiaddr", "addr", "remotePeer", "peerIdFromString", "addrString", "CustomEvent", "addrSet", "str", "_a", "import_err_code", "log", "logger", "VisibilityChangeEmitter", "EventEmitter", "hidden", "visibilityChange", "visible", "CustomEvent", "log", "logger", "LatencyMonitor", "EventEmitter", "init", "_a", "_b", "latencyCheckIntervalMs", "dataEmitIntervalMs", "asyncTestFn", "latencyRandomPercentage", "startTime", "hrtime", "isBrowser", "VisibilityChangeEmitter", "evt", "pageInFocus", "summary", "CustomEvent", "latency", "randomness", "localData", "cb", "deltaMS", "import_events", "OPEN", "CLOSING", "CLOSED", "mapIterable", "iter", "map", "iterator", "next", "val", "PeerMap", "map", "key", "value", "peer", "mapIterable", "val", "peerIdFromString", "fn", "PeerSet", "set", "key", "peer", "mapIterable", "val", "peerId", "peerIdFromString", "predicate", "str", "id", "other", "output", "PeerList", "list", "value", "mapIterable", "val", "peerIdFromString", "output", "predicate", "str", "index", "peerId", "peerIds", "len", "i", "import_timeout_abort_controller", "KEEP_ALIVE", "import_rate_limiter_flexible", "import_err_code", "getPeerAddress", "peer", "isPeerId", "isMultiaddr", "peerId", "peerIdFromString", "errCode", "codes", "log", "logger", "defaultOptions", "STARTUP_RECONNECT_TIMEOUT", "DefaultConnectionManager", "EventEmitter", "components", "init", "_a", "merge_options_default", "errCode", "codes", "LatencyMonitor", "ma", "multiaddr", "_b", "_c", "_d", "_e", "metric", "conns", "conn", "stream", "key", "allStreams", "streams", "protocol", "count", "counts", "a", "b", "index", "keepAlivePeers", "peer", "tag", "KEEP_ALIVE", "err", "tasks", "connectionList", "connection", "evt", "peerId", "peerIdStr", "storedConns", "numConnections", "toPrune", "CustomEvent", "storedConn", "c", "peerIdOrMultiaddr", "options", "getPeerAddress", "existingConnections", "timeoutController", "peerConnections", "trackedConnection", "connections", "isPeerId", "id", "OPEN", "summary", "name", "value", "limit", "peerValues", "PeerMap", "remotePeer", "tags", "acc", "curr", "sortedConnections", "peerAValue", "peerBValue", "connectionALifespan", "connectionBLifespan", "toClose", "maConn", "host", "import_retimer", "log", "logger", "defaultOptions", "AutoDialler", "components", "init", "merge_options_default", "err", "minConnections", "retimer", "allPeers", "peers", "pipe", "source", "filter", "peer", "sort", "a", "b", "all", "import_err_code", "import_reader", "import_reader_buffer", "import_writer", "import_writer_buffer", "import_minimal", "configure", "util", "ReaderClass", "ReaderBufferClass", "WriterClass", "WriterBufferClass", "methods", "patchReader", "obj", "method", "original", "reader", "buf", "patchWriter", "val", "writer", "decodeMessage", "buf", "codec", "r", "reader", "encodeMessage", "message", "codec", "w", "writer", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "CircuitRelay", "Status", "__StatusValues", "enumeration", "Type", "__TypeValues", "Peer", "_codec", "message", "obj", "w", "opts", "value", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "log", "logger", "streamToMaConnection", "props", "options", "stream", "remoteAddr", "sink", "source", "mapSource", "list", "maConn", "abortableSource", "close", "err", "RELAY_CODEC", "createListener", "options", "listeningAddrs", "listen", "addr", "addrString", "a", "ma", "multiaddr", "relayPeerStr", "relayPeerId", "peerIdFromString", "relayConn", "relayedAddr", "listener", "CustomEvent", "getAddrs", "addrs", "EventEmitter", "evt", "connection", "import_err_code", "writeResponse", "streamHandler", "status", "CircuitRelay", "validateAddrs", "msg", "_a", "_b", "addr", "multiaddr", "err", "reader", "source", "bytes", "bl", "Uint8ArrayList", "chunk", "data", "handshake", "stream", "writer", "pushable", "source", "reader", "sourcePromise", "pDefer", "sinkErr", "sinkPromise", "err", "res", "log", "logger", "StreamHandler", "options", "stream", "maxLength", "handshake", "decode", "msg", "value", "CircuitRelay", "encode", "err", "log", "logger", "handleStop", "options", "connection", "request", "streamHandler", "validateAddrs", "err", "CircuitRelay", "stop", "signal", "stream", "RELAY_CODEC", "StreamHandler", "response", "log", "logger", "handleHop", "hopRequest", "connection", "request", "streamHandler", "circuit", "connectionManager", "CircuitRelay", "validateAddrs", "err", "destinationPeer", "peerIdFromBytes", "destinationConnections", "stopRequest", "destinationStream", "result", "stop", "sourceStream", "pipe", "hop", "options", "signal", "stream", "RELAY_CODEC", "StreamHandler", "response", "errCode", "codes", "canHop", "handleCanHop", "import_timeout_abort_controller", "import_events", "log", "logger", "Circuit", "components", "init", "RELAY_CODEC", "data", "err", "symbol", "_a", "_b", "_c", "connection", "stream", "controller", "source", "abortableDuplex", "streamHandler", "StreamHandler", "request", "CircuitRelay", "virtualConnection", "handleCanHop", "handleHop", "handleStop", "remoteAddr", "multiaddr", "localAddr", "maConn", "streamToMaConnection", "type", "conn", "ma", "options", "addrs", "relayAddr", "destinationAddr", "relayId", "destinationId", "errMsg", "errCode", "codes", "relayPeer", "peerIdFromString", "destinationPeer", "disconnectOnFailure", "relayConnection", "hop", "addr", "createListener", "multiaddrs", "import_set_delayed_interval", "namespaceToCid", "namespace", "bytes", "hash", "sha256", "CID", "HOP_METADATA_KEY", "HOP_METADATA_VALUE", "RELAY_RENDEZVOUS_NS", "import_netmask", "word", "boundry", "options", "v4", "v6segment", "v6", "v46Exact", "v4exact", "v6exact", "ipRegex", "ip_regex_default", "import_ipaddr", "is_valid", "parse", "ipaddr", "PRIVATE_IP_RANGES", "NETMASK_RANGES", "ip_range", "ipv4_check", "ip_addr", "r", "ipv6_check", "lib_default", "ip", "parsed", "isIP", "ip_regex_default", "private_ip_default", "lib_default", "isPrivate", "ma", "address", "private_ip_default", "publicAddressesFirst", "a", "b", "isAPrivate", "isPrivate", "isBPrivate", "log", "logger", "noop", "AutoRelay", "components", "init", "publicAddressesFirst", "evt", "err", "peerId", "protocols", "id", "protocol", "RELAY_CODEC", "connections", "connection", "canHop", "HOP_METADATA_KEY", "fromString", "HOP_METADATA_VALUE", "remoteAddrs", "pipe", "source", "sort", "all", "addr", "multiaddr", "peersToIgnore", "knownHopsToDial", "peers", "metadata", "idStr", "supportsHop", "toString", "cid", "namespaceToCid", "RELAY_RENDEZVOUS_NS", "provider", "log", "logger", "Relay", "components", "init", "_a", "AutoRelay", "cid", "namespaceToCid", "RELAY_RENDEZVOUS_NS", "err", "codes", "import_sanitize_filename", "import_pkcs7", "import_pbe", "import_forge", "import_x509", "import_forge", "pki", "forge", "certificateForKey", "key", "privateKey", "publicKey", "cert", "attrs", "findAsync", "array", "asyncCompare", "promises", "index", "result", "import_err_code", "log", "logger", "privates", "CMS", "keychain", "dek", "errCode", "codes", "name", "plain", "key", "pem", "cached", "privateKey", "forge", "certificate", "certificateForKey", "p7", "der", "fromString", "cmsData", "cms", "buf", "toString", "obj", "err", "recipients", "r", "a", "findAsync", "recipient", "missingKeys", "import_err_code", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "import_asn1", "import_pbe", "import_forge", "webcrypto_default", "win", "nativeCrypto", "import_util", "import_jsbn", "import_forge", "bigIntegerToUintBase64url", "num", "len", "buf", "concat", "toString", "base64urlToBigInteger", "str", "base64urlToBuffer", "forge", "fromString", "bits", "curveTypes", "names", "create", "opts", "algorithm", "keyLength", "nonceLength", "digest", "saltLength", "iterations", "crypto", "webcrypto_default", "encrypt", "data", "password", "salt", "nonce", "aesGcm", "fromString", "deriveParams", "rawKey", "cryptoKey", "ciphertext", "concat", "decrypt", "plaintext", "importer", "privateKey", "password", "encryptedKey", "base64", "create", "rsa_class_exports", "__export", "RsaPrivateKey", "RsaPublicKey", "fromJwk", "generateKeyPair", "unmarshalRsaPrivateKey", "unmarshalRsaPublicKey", "import_sha512", "import_forge", "randomBytes", "length", "CodeError", "utils", "rsa_utils_exports", "__export", "jwkToPkcs1", "jwkToPkix", "pkcs1ToJwk", "pkixToJwk", "import_asn1", "import_rsa", "import_forge", "pkcs1ToJwk", "bytes", "asn1", "forge", "toString", "privateKey", "bigIntegerToUintBase64url", "jwkToPkcs1", "jwk", "CodeError", "base64urlToBigInteger", "fromString", "pkixToJwk", "publicKey", "jwkToPkix", "import_rsa", "import_forge", "convert", "key", "types", "base64urlToBigInteger", "jwk2priv", "forge", "jwk2pub", "generateKey", "bits", "pair", "webcrypto_default", "keys", "exportKey", "unmarshalPrivateKey", "key", "derivePublicFromPrivate", "hashAndSign", "key", "msg", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "exportKey", "pair", "CodeError", "derivePublicFromPrivate", "jwKey", "convertKey", "pub", "handle", "fkey", "jwk2pub", "jwk2priv", "fmsg", "toString", "fomsg", "fromString", "encrypt", "decrypt", "exporter", "privateKey", "password", "encryptedKey", "create", "base64", "RsaPublicKey", "key", "data", "sig", "hashAndVerify", "rsa_utils_exports", "PublicKey", "KeyType", "bytes", "encrypt", "equals", "sha256", "RsaPrivateKey", "publicKey", "randomBytes", "message", "hashAndSign", "CodeError", "decrypt", "PrivateKey", "hash", "toString", "password", "format", "buffer", "forge", "asn1", "privateKey", "options", "exporter", "unmarshalRsaPrivateKey", "jwk", "keys", "unmarshalPrivateKey", "unmarshalRsaPublicKey", "fromJwk", "generateKeyPair", "bits", "generateKey", "ed25519_class_exports", "__export", "Ed25519PrivateKey", "Ed25519PublicKey", "generateKeyPair", "generateKeyPairFromSeed", "unmarshalEd25519PrivateKey", "unmarshalEd25519PublicKey", "PUBLIC_KEY_BYTE_LENGTH", "PRIVATE_KEY_BYTE_LENGTH", "KEYS_BYTE_LENGTH", "generateKey", "privateKeyRaw", "utils", "publicKey", "getPublicKey", "concatKeys", "generateKeyFromSeed", "seed", "KEYS_BYTE_LENGTH", "hashAndSign", "privateKey", "msg", "sign", "hashAndVerify", "sig", "verify", "PRIVATE_KEY_BYTE_LENGTH", "i", "Ed25519PublicKey", "key", "ensureKey", "PUBLIC_KEY_BYTE_LENGTH", "data", "sig", "hashAndVerify", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Ed25519PrivateKey", "publicKey", "PRIVATE_KEY_BYTE_LENGTH", "message", "hashAndSign", "PrivateKey", "encoding", "identity", "base58btc", "password", "format", "exporter", "CodeError", "unmarshalEd25519PrivateKey", "privateKeyBytes", "publicKeyBytes", "unmarshalEd25519PublicKey", "generateKeyPair", "privateKey", "generateKey", "generateKeyPairFromSeed", "seed", "generateKeyFromSeed", "length", "secp256k1_class_exports", "__export", "Secp256k1PrivateKey", "Secp256k1PublicKey", "generateKeyPair", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKey", "utils", "hashAndSign", "key", "msg", "digest", "sha256", "sign", "err", "CodeError", "hashAndVerify", "sig", "verify", "compressPublicKey", "Point", "validatePrivateKey", "key", "getPublicKey", "err", "CodeError", "validatePublicKey", "Point", "computePublicKey", "privateKey", "Secp256k1PublicKey", "key", "validatePublicKey", "data", "sig", "hashAndVerify", "compressPublicKey", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Secp256k1PrivateKey", "publicKey", "computePublicKey", "validatePrivateKey", "message", "hashAndSign", "PrivateKey", "hash", "toString", "password", "format", "exporter", "CodeError", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKeyPair", "privateKeyBytes", "generateKey", "supportedKeys", "rsa_class_exports", "ed25519_class_exports", "secp256k1_class_exports", "unsupportedKey", "type", "supported", "CodeError", "typeToKey", "generateKeyPair", "bits", "unmarshalPublicKey", "buf", "decoded", "PublicKey", "data", "KeyType", "supportedKeys", "unsupportedKey", "marshalPublicKey", "key", "type", "typeToKey", "unmarshalPrivateKey", "PrivateKey", "marshalPrivateKey", "importKey", "encryptedKey", "password", "importer", "forge", "CodeError", "der", "fromString", "import_aes", "import_forge", "import_pbkdf2", "import_util", "hashName", "pbkdf2", "password", "salt", "iterations", "keySize", "hash", "types", "CodeError", "hasher", "dek", "forgePbkdf2", "forgeUtil", "log", "logger", "keyPrefix", "infoPrefix", "privates", "NIST", "defaultOptions", "validateKeyName", "name", "sanitize", "randomDelay", "delay", "resolve", "DsName", "Key", "DsInfoName", "KeyChain", "components", "init", "_a", "_b", "_c", "_d", "_e", "_f", "_g", "_h", "_i", "_j", "merge_options_default", "dek", "pbkdf2", "dsname", "cached", "errCode", "codes", "CMS", "options", "saltLength", "toString", "randomBytes", "type", "size", "keyInfo", "keypair", "generateKeyPair", "kid", "pem", "batch", "fromString", "err", "query", "info", "value", "id", "k", "res", "oldName", "newName", "oldDsname", "newDsname", "oldInfoName", "newInfoName", "password", "importKey", "privateKey", "peerIdFromKeys", "peer", "unmarshalPrivateKey", "oldPass", "newPass", "oldDek", "newDek", "keys", "key", "keyAsPEM", "pReflect", "promise", "error", "Node", "value", "__publicField", "_head", "_tail", "_size", "Queue", "__privateAdd", "node", "__privateGet", "__privateSet", "__privateWrapper", "current", "pLimit", "concurrency", "queue", "Queue", "activeCount", "next", "run", "fn", "resolve", "args", "result", "enqueue", "generator", "pSettle", "array", "options", "concurrency", "limit", "pLimit", "element", "pReflect", "import_err_code", "TrackedMap", "init", "name", "metrics", "key", "value", "deleted", "trackedMap", "config", "map", "log", "logger", "DefaultTransportManager", "EventEmitter", "components", "init", "trackedMap", "FaultTolerance", "transport", "tag", "errCode", "codes", "addrs", "tasks", "key", "listeners", "listener", "ma", "options", "err", "couldNotListen", "supportedAddrs", "addr", "CustomEvent", "pSettle", "r", "message", "import_err_code", "PROTOCOL_ID", "import_err_code", "import_err_code", "log", "logger", "NewLine", "fromString", "encode", "buffer", "list", "Uint8ArrayList", "write", "writer", "options", "encoded", "writeAll", "buffers", "buf", "read", "reader", "byteLength", "varByteSource", "input", "abortableSource", "pipe", "decode", "l", "source", "first", "errCode", "readString", "toString", "log", "logger", "select", "stream", "protocols", "options", "reader", "writer", "rest", "shakeStream", "handshake", "protocol", "PROTOCOL_ID", "p1", "fromString", "p2", "writeAll", "response", "readString", "write", "errCode", "log", "logger", "handle", "stream", "protocols", "options", "writer", "reader", "rest", "shakeStream", "handshake", "protocol", "readString", "PROTOCOL_ID", "write", "fromString", "Uint8ArrayList", "p", "encode", "import_err_code", "symbol", "log", "logger", "ConnectionImpl", "init", "remoteAddr", "remotePeer", "newStream", "close", "getStreams", "stat", "OPEN", "symbol", "protocols", "options", "CLOSING", "errCode", "CLOSED", "stream", "id", "s", "err", "createConnection", "import_err_code", "topologySymbol", "isTopology", "other", "log", "logger", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "DefaultRegistrar", "components", "protocol", "handler", "errCode", "codes", "topologies", "opts", "options", "merge_options_default", "protocols", "protocolList", "topology", "isTopology", "id", "evt", "connection", "peerProtocols", "err", "peerId", "oldProtocols", "removed", "added", "import_timeout_abort_controller", "import_events", "log", "logger", "findIncomingStreamLimit", "protocol", "registrar", "options", "err", "codes", "DEFAULT_MAX_INBOUND_STREAMS", "findOutgoingStreamLimit", "DEFAULT_MAX_OUTBOUND_STREAMS", "countStreams", "direction", "connection", "streamCount", "stream", "DefaultUpgrader", "EventEmitter", "components", "init", "encrypter", "muxer", "maConn", "opts", "_a", "_b", "errCode", "encryptedConn", "remotePeer", "upgradedConn", "muxerFactory", "cryptoProtocol", "timeoutController", "abortableStream", "abortableDuplex", "protectedConn", "protector", "idStr", "remotePeerId", "peerIdFromString", "multiplexed", "newStream", "muxedStream", "protocols", "handle", "incomingLimit", "controller", "select", "outgoingLimit", "_timeline", "args", "CustomEvent", "errConnectionNotMultiplexed", "createConnection", "handler", "muxers", "import_err_code", "Identify", "_codec", "message", "obj", "w", "opts", "value", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "import_err_code", "codes", "Envelope", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "RecordEnvelope", "init", "peerId", "payloadType", "payload", "signature", "Envelope", "other", "equals", "domain", "signData", "formatSignaturePayload", "unmarshalPublicKey", "data", "envelopeData", "peerIdFromKeys", "record", "unmarshalPrivateKey", "envelope", "errCode", "codes", "domainUint8Array", "fromString", "domainLength", "unsigned", "payloadTypeLength", "payloadLength", "Uint8ArrayList", "arrayEquals", "a", "b", "sort", "item", "index", "PeerRecord", "AddressInfo", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "value", "ENVELOPE_DOMAIN_PEER_RECORD", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "PeerRecord", "init", "peerId", "multiaddrs", "seqNumber", "m", "other", "arrayEquals", "buf", "peerRecord", "peerIdFromBytes", "a", "multiaddr", "ENVELOPE_DOMAIN_PEER_RECORD", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "version", "name", "AGENT_VERSION", "version", "IDENTIFY_PROTOCOL_VERSION", "MULTICODEC_IDENTIFY_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PROTOCOL_VERSION", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION", "import_timeout_abort_controller", "import_events", "log", "logger", "MAX_IDENTIFY_MESSAGE_SIZE", "IdentifyService", "components", "init", "MULTICODEC_IDENTIFY_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PROTOCOL_VERSION", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION", "IDENTIFY_PROTOCOL_VERSION", "evt", "connection", "peerId", "err", "fromString", "data", "connections", "signedPeerRecord", "listenAddrs", "ma", "protocols", "pushes", "_a", "stream", "timeoutController", "abortableDuplex", "pipe", "Identify", "encode", "conn", "options", "signal", "source", "decode", "first", "errCode", "codes", "message", "publicKey", "observedAddr", "agentVersion", "protocolVersion", "id", "peerIdFromKeys", "cleanObservedAddr", "envelope", "RecordEnvelope", "PeerRecord", "addr", "multiaddr", "peerData", "multiaddrs", "getProtocol", "peerRecord", "msgWithLenPrefix", "import_err_code", "FetchRequest", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "FetchResponse", "StatusCode", "__StatusCodeValues", "enumeration", "PROTOCOL_VERSION", "PROTOCOL_NAME", "import_timeout_abort_controller", "import_events", "log", "logger", "FetchService", "components", "init", "PROTOCOL_NAME", "PROTOCOL_VERSION", "data", "err", "peer", "key", "options", "_a", "connection", "timeoutController", "signal", "stream", "source", "abortableDuplex", "pipe", "FetchRequest", "encode", "decode", "buf", "first", "errCode", "codes", "response", "FetchResponse", "errmsg", "toString", "self", "request", "lookup", "fromString", "prefix", "import_err_code", "PROTOCOL_VERSION", "PROTOCOL_NAME", "import_timeout_abort_controller", "import_events", "log", "logger", "PingService", "components", "init", "PROTOCOL_NAME", "PROTOCOL_VERSION", "data", "stream", "pipe", "err", "peer", "options", "_a", "start", "randomBytes", "connection", "timeoutController", "signal", "source", "abortableDuplex", "result", "first", "end", "equals", "errCode", "codes", "upnpNat", "import_is_electron", "isEnvWithDom", "isElectron", "detectElectron", "isBrowser", "isElectronMain", "isElectronRenderer", "isNode", "isWebWorker", "isTest", "isReactNative", "import_err_code", "isLoopbackAddr", "ip", "isLoopback", "ma", "address", "isLoopbackAddr", "log", "logger", "DEFAULT_TTL", "highPort", "min", "max", "NatManager", "components", "init", "name", "version", "errCode", "codes", "isBrowser", "err", "addrs", "addr", "family", "host", "port", "transport", "isLoopback", "client", "publicIp", "isPrivate", "private_ip_default", "publicPort", "fromNodeAddress", "upnpNat", "log", "logger", "PeerRecordUpdater", "components", "peerRecord", "PeerRecord", "ma", "getProtocol", "envelope", "RecordEnvelope", "err", "import_err_code", "DHTPeerRouting", "dht", "peerId", "options", "event", "errCode", "messages", "codes", "key", "import_err_code", "codes", "forEach", "source", "fn", "thing", "log", "logger", "EVENT_NAME", "allowAll", "PeerStoreAddressBook", "dispatchEvent", "store", "addressFilter", "envelope", "release", "peerId", "peer", "updatedPeer", "peerRecord", "PeerRecord", "multiaddrs", "storedEnvelope", "RecordEnvelope", "storedRecord", "addresses", "filterMultiaddrs", "CustomEvent", "multiaddr", "err", "codes", "raw", "peerIdFromPeerId", "errcode", "hasPeer", "addr", "isCertified", "pipe", "source", "forEach", "isMultiaddr", "filter", "map", "all", "import_err_code", "log", "logger", "EVENT_NAME", "PeerStoreKeyBook", "dispatchEvent", "store", "peerId", "publicKey", "peerIdFromPeerId", "errcode", "codes", "release", "updatedKey", "peer", "equals", "err", "CustomEvent", "import_err_code", "log", "logger", "EVENT_NAME", "PeerStoreMetadataBook", "dispatchEvent", "store", "peerId", "peerIdFromPeerId", "release", "err", "codes", "key", "metadata", "errcode", "peer", "CustomEvent", "value", "updatedPeer", "existingValue", "equals", "import_err_code", "log", "logger", "EVENT_NAME", "PeerStoreProtoBook", "dispatchEvent", "store", "peerId", "release", "err", "codes", "protocols", "peerIdFromPeerId", "errcode", "peer", "updatedPeer", "CustomEvent", "protocolSet", "protocol", "import_err_code", "Peer", "_codec", "message", "obj", "w", "opts", "value", "Address", "Metadata", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "log", "logger", "NAMESPACE_COMMON", "PersistentStore", "components", "createMortice", "peerId", "errcode", "codes", "b32key", "Key", "buf", "peer", "Peer", "metadata", "meta", "ma", "isCertified", "multiaddr", "equals", "addressSet", "addresses", "address", "a", "b", "key", "value", "data", "err", "_a", "_b", "addr", "addrString", "addrStr", "base32Str", "base32", "peerIdFromBytes", "import_err_code", "Tags", "_codec", "message", "obj", "w", "opts", "value", "Tag", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "log", "logger", "PersistentPeerStore", "EventEmitter", "components", "init", "PersistentStore", "PeerStoreAddressBook", "PeerStoreKeyBook", "PeerStoreMetadataBook", "PeerStoreProtoBook", "fn", "release", "peer", "output", "peerId", "tag", "options", "providedValue", "value", "ttl", "errCode", "buf", "tags", "Tags", "t", "now", "unexpiredTags", "import_err_code", "DHTContentRouting", "dht", "cid", "drain", "options", "event", "key", "value", "errCode", "import_err_code", "DefaultComponents", "init", "obj", "isStartable", "startable", "errCode", "peerId", "addressManager", "peerStore", "upgrader", "registrar", "connectionManager", "transportManager", "connectionGater", "contentRouting", "peerRouting", "datastore", "connectionProtector", "dialer", "metrics", "dht", "pubsub", "import_debug", "import_receptacle", "globalFetch", "globalHeaders", "globalRequest", "globalResponse", "buildResource", "serverResolver", "hostname", "recordType", "request", "resource", "signal", "globalFetch", "globalHeaders", "getCacheKey", "log", "debug", "Resolver", "options", "Receptacle", "request", "controller", "newServers", "i", "j", "temp", "servers", "hostname", "rrType", "recordType", "cached", "getCacheKey", "aborted", "server", "response", "buildResource", "data", "a", "ttl", "c", "src_default", "dns_browser_default", "src_default", "dnsaddrCode", "getProtocol", "dnsaddrResolver", "addr", "options", "resolver", "dns_browser_default", "peerId", "hostname", "proto", "addresses", "entry", "import_err_code", "DefaultConfig", "multiaddrs", "dnsaddrResolver", "publicAddressesFirst", "FaultTolerance", "AGENT_VERSION", "validateConfig", "opts", "_a", "_b", "resultingOptions", "merge_options_default", "errCode", "messages", "codes", "isNode", "isElectronMain", "isBrowser", "isWebWorker", "isElectronRenderer", "isReactNative", "PeerIdProto", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "createEd25519PeerId", "key", "generateKeyPair", "id", "createFromPrivKey", "createFromPrivKey", "privateKey", "peerIdFromKeys", "marshalPublicKey", "marshalPrivateKey", "import_err_code", "import_err_code", "DummyDHT", "EventEmitter", "symbol", "errCode", "messages", "codes", "import_err_code", "DummyPubSub", "EventEmitter", "errCode", "messages", "codes", "import_err_code", "import_timeout_abort_controller", "import_any_signal", "import_events", "import_err_code", "import_any_signal", "import_p_fifo", "import_events", "log", "logger", "DialRequest", "options", "addrs", "dialAction", "dialer", "_a", "tokens", "errCode", "codes", "tokenHolder", "FIFO", "token", "err", "dialAbortControllers", "controller", "completedDials", "done", "addr", "i", "conn", "signal", "log", "logger", "DefaultDialer", "components", "init", "publicAddressesFirst", "_", "index", "trackedMap", "key", "value", "resolvers", "dial", "err", "pendingTarget", "peerIdOrMultiaddr", "options", "peerId", "multiaddr", "getPeerAddress", "errCode", "codes", "controller", "controllerId", "randomId", "signal", "dialTarget", "pendingDial", "connection", "addrs", "isMultiaddr", "isPeerId", "ma", "peerIdMultiaddr", "addr", "addressPeerId", "peer", "addresses", "address", "isTruthy", "_a", "dialAction", "dialRequest", "DialRequest", "timeoutController", "signals", "num", "total", "tokens", "token", "resolvedMultiaddrs", "nm", "array", "newM", "m", "e", "log", "logger", "Libp2pNode", "EventEmitter", "init", "components", "DefaultComponents", "MemoryDatastore", "PersistentPeerStore", "evt", "peerData", "CustomEvent", "DefaultUpgrader", "fn", "DefaultDialer", "DefaultConnectionManager", "event", "DefaultRegistrar", "DefaultTransportManager", "DefaultAddressManager", "PeerRecordUpdater", "AutoDialler", "keychainOpts", "KeyChain", "NatManager", "IdentifyService", "DummyDHT", "DummyPubSub", "peerRouters", "DHTPeerRouting", "DefaultPeerRouting", "contentRouters", "DHTContentRouting", "CompoundContentRouting", "Circuit", "Relay", "FetchService", "PingService", "component", "isStartable", "service", "err", "peerId", "peerSet", "PeerSet", "conn", "peer", "options", "protocols", "errCode", "codes", "isMultiaddr", "peerIdFromString", "peerInfo", "peerKey", "concat", "fromString", "key", "unmarshalPublicKey", "handler", "protocol", "topology", "id", "createLibp2pNode", "datastore", "keyChain", "createEd25519PeerId", "validateConfig", "createLibp2p", "options", "node", "createLibp2pNode", "import_k_bucket", "import_netmask", "import_ipaddr", "is_valid", "parse", "ipaddr", "PRIVATE_IP_RANGES", "NETMASK_RANGES", "ip_range", "ipv4_check", "ip_addr", "r", "ipv6_check", "lib_default", "ip", "parsed", "isIP", "ip_regex_default", "private_ip_default", "lib_default", "LAN_PREFIX", "PROTOCOL_PREFIX", "PROTOCOL_DHT", "RECORD_KEY_PREFIX", "PROVIDER_KEY_PREFIX", "PK_PREFIX", "fromString", "removePrivateAddresses", "peer", "multiaddr", "type", "addr", "isPrivate", "private_ip_default", "removePublicAddresses", "convertBuffer", "buf", "sha256", "convertPeerId", "peerId", "bufferToRecordKey", "buf", "Key", "RECORD_KEY_PREFIX", "toString", "keyForPublicKey", "peer", "concat", "PK_PREFIX", "isPublicKeyKey", "key", "fromPublicKeyKey", "key", "peerIdFromBytes", "createPutRecord", "value", "timeReceived", "Libp2pRecord", "debounce", "callback", "wait", "timeout", "import_timeout_abort_controller", "mapIterable", "iter", "map", "iterator", "next", "val", "PeerMap", "map", "__publicField", "key", "value", "peer", "mapIterable", "val", "peerIdFromString", "fn", "PeerSet", "set", "__publicField", "key", "peer", "mapIterable", "val", "peerId", "peerIdFromString", "predicate", "str", "id", "other", "output", "PeerList", "list", "__publicField", "value", "mapIterable", "val", "peerIdFromString", "output", "predicate", "str", "index", "peerId", "peerIds", "len", "i", "KAD_CLOSE_TAG_NAME", "KAD_CLOSE_TAG_VALUE", "KBUCKET_SIZE", "PING_TIMEOUT", "PING_CONCURRENCY", "RoutingTable", "components", "init", "kBucketSize", "pingTimeout", "lan", "pingConcurrency", "protocol", "tagName", "tagValue", "logger", "updatePingQueueSizeMetric", "_a", "_b", "dist_default", "kBuck", "KBuck", "convertPeerId", "kClosest", "PeerSet", "updatePeerTags", "debounce", "newClosest", "contact", "addedPeers", "removedPeers", "peer", "err", "oldContacts", "newContact", "responded", "oldContact", "timeoutController", "options", "key", "closest", "res", "count", "p", "id", "xor", "a", "b", "result", "allocUnsafe", "i", "asUint8Array", "generated_prefix_list_browser_default", "length", "iterator", "count", "_", "import_timeout_abort_controller", "MAX_COMMON_PREFIX_LENGTH", "RoutingTableRefresh", "init", "peerRouting", "routingTable", "refreshInterval", "refreshQueryTimeout", "lan", "logger", "force", "prefixLength", "refreshCpls", "date", "lastRefresh", "index", "lastCpl", "n", "err", "cpl", "peerId", "controller", "peers", "length", "maxCommonPrefix", "dates", "i", "targetCommonPrefixLength", "randomData", "randomBytes", "randomUint16", "key", "peerIdFromBytes", "localKadId", "randomPrefix", "toggledLocalPrefix", "mask", "targetPrefix", "keyPrefix", "generated_prefix_list_browser_default", "keyBuffer", "keyView", "sha256", "count", "id", "distance", "xor", "leadingZeros", "byte", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "Message", "MessageType", "__MessageTypeValues", "enumeration", "ConnectionType", "__ConnectionTypeValues", "Peer", "value", "MESSAGE_TYPE", "Message", "CONNECTION_TYPE", "MESSAGE_TYPE_LOOKUP", "type", "key", "level", "toPbPeer", "raw", "_a", "dec", "msg", "fromPbPeer", "Libp2pRecord", "peer", "m", "peerIdFromBytes", "a", "multiaddr", "sendingQueryEvent", "fields", "MESSAGE_TYPE_LOOKUP", "peerResponseEvent", "finalPeerEvent", "queryErrorEvent", "providerEvent", "valueEvent", "dialingPeerEvent", "fields", "Network", "EventEmitter", "components", "init", "protocol", "lan", "logger", "to", "msg", "options", "dialingPeerEvent", "sendingQueryEvent", "stream", "response", "peerResponseEvent", "err", "queryErrorEvent", "abortableDuplex", "pipe", "encode", "drain", "res", "decode", "source", "buf", "first", "CodeError", "message", "Message", "peerData", "CustomEvent", "verifyRecord", "validators", "record", "key", "parts", "toString", "validator", "errMsg", "CodeError", "validatePublicKeyRecord", "publicKey", "keyhash", "publicKeyHash", "sha256", "equals", "bestRecord", "selectors", "k", "records", "errMsg", "CodeError", "parts", "toString", "selector", "publickKey", "ContentFetching", "components", "init", "validators", "selectors", "peerRouting", "queryManager", "routingTable", "network", "lan", "logger", "key", "rec", "dsKey", "bufferToRecordKey", "raw", "Libp2pRecord", "verifyRecord", "vals", "best", "options", "fixupRec", "createPutRecord", "value", "from", "equals", "err", "sentCorrection", "request", "Message", "MESSAGE_TYPE", "event", "queryErrorEvent", "CodeError", "record", "pipe", "source", "map", "events", "msg", "putEvent", "parallel", "records", "v", "i", "bestRecord", "localRec", "valueEvent", "id", "convertBuffer", "rtp", "self", "getValueQuery", "peer", "signal", "ContentRouting", "components", "init", "network", "peerRouting", "queryManager", "routingTable", "providers", "lan", "logger", "key", "multiaddrs", "options", "msg", "Message", "MESSAGE_TYPE", "sent", "maybeNotifyPeer", "event", "events", "sendEvent", "err", "queryErrorEvent", "pipe", "source", "map", "parallel", "toFind", "target", "id", "convertBuffer", "self", "provs", "peerId", "address", "peerResponseEvent", "providerEvent", "findProvidersQuery", "peer", "signal", "request", "p", "newProviders", "compare", "a", "b", "i", "PeerDistanceList", "originDhtKey", "capacity", "pd", "peerId", "dhtKey", "convertPeerId", "el", "xor", "a", "b", "compare", "peerIds", "dhtKeys", "furthestDistance", "keyDistance", "PeerRouting", "components", "init", "routingTable", "network", "validators", "queryManager", "lan", "logger", "peer", "peerData", "p", "err", "address", "key", "options", "msg", "Message", "MESSAGE_TYPE", "pkKey", "keyForPublicKey", "event", "recPeer", "peerIdFromKeys", "keys_exports", "CodeError", "valueEvent", "id", "pi", "finalPeerEvent", "convertPeerId", "peers", "self", "findPeerQuery", "signal", "request", "match", "foundPeer", "queryErrorEvent", "convertBuffer", "tablePeers", "PeerDistanceList", "getCloserPeersQuery", "toString", "addr", "errMsg", "record", "verifyRecord", "Libp2pRecord", "closerThan", "ids", "output", "peerId", "addresses", "protocols", "import_hashlru", "import_varint", "log", "logger", "Providers", "components", "init", "cacheSize", "cleanupInterval", "provideValidity", "cache", "dist_default", "err", "start", "count", "deleteCount", "deleted", "batch", "query", "PROVIDER_KEY_PREFIX", "entry", "cid", "peerId", "parseProviderKey", "time", "readTime", "now", "delta", "expired", "peers", "key", "makeProviderKey", "provs", "cacheKey", "loadProviders", "provider", "dsKey", "writeProviderEntry", "peerIdStr", "peerIdFromString", "cidStr", "toString", "store", "peer", "Key", "buffer", "varint", "parts", "providers", "buf", "import_timeout_abort_controller", "import_any_signal", "import_timeout_abort_controller", "import_any_signal", "MAX_XOR", "queryPath", "options", "key", "startingPeer", "ourPeerId", "signal", "query", "alpha", "pathIndex", "numPaths", "cleanUp", "queryFuncTimeout", "log", "peersSeen", "queue", "dist_default", "kadId", "convertBuffer", "queryPeer", "peer", "peerKadId", "peerXor", "toString", "xor", "timeout", "signals", "compoundSignal", "event", "closerPeer", "closerPeerKadId", "convertPeerId", "err", "queryErrorEvent", "toGenerator", "deferred", "pDefer", "running", "results", "cleanup", "result", "wasRunning", "CodeError", "merge", "sources", "output", "pushable", "source", "item", "err", "import_events", "QueryManager", "components", "init", "lan", "disjointPaths", "alpha", "controller", "key", "peers", "queryFunc", "options", "_a", "_b", "_c", "stopQueryTimer", "timeoutController", "abortController", "signals", "signal", "log", "logger", "toString", "peersToQuery", "startTime", "cleanUp", "EventEmitter", "peersSeen", "PeerSet", "paths", "peer", "index", "queryPath", "event", "merge", "err", "CustomEvent", "log", "logger", "AddProviderHandler", "init", "providers", "peerId", "msg", "CodeError", "cid", "CID", "pi", "m", "log", "logger", "FindNodeHandler", "components", "init", "peerRouting", "lan", "peerId", "msg", "closer", "equals", "ma", "getProtocol", "removePublicAddresses", "removePrivateAddresses", "multiaddrs", "response", "Message", "log", "logger", "GetProvidersHandler", "components", "init", "peerRouting", "providers", "lan", "peerId", "msg", "cid", "CID", "CodeError", "peers", "closer", "providerPeers", "closerPeers", "id", "response", "Message", "address", "peerIds", "output", "addrFilter", "removePublicAddresses", "removePrivateAddresses", "peer", "log", "logger", "GetValueHandler", "components", "init", "peerRouting", "peerId", "msg", "key", "CodeError", "response", "Message", "MESSAGE_TYPE", "isPublicKeyKey", "idFromKey", "fromPublicKeyKey", "pubKey", "err", "Libp2pRecord", "record", "closer", "dsKey", "bufferToRecordKey", "rawRecord", "log", "logger", "PingHandler", "peerId", "msg", "PutValueHandler", "components", "init", "validators", "logger", "peerId", "msg", "key", "record", "errMsg", "CodeError", "verifyRecord", "recordKey", "bufferToRecordKey", "err", "RPC", "components", "init", "providers", "peerRouting", "validators", "lan", "logger", "MESSAGE_TYPE", "GetValueHandler", "PutValueHandler", "FindNodeHandler", "AddProviderHandler", "GetProvidersHandler", "PingHandler", "peerId", "msg", "err", "handler", "data", "stream", "connection", "self", "pipe", "decode", "source", "desMessage", "Message", "res", "encode", "TopologyListener", "EventEmitter", "components", "init", "protocol", "lan", "logger", "topology", "createTopology", "peerId", "CustomEvent", "import_events", "take", "source", "limit", "items", "entry", "import_timeout_abort_controller", "import_any_signal", "QuerySelf", "components", "init", "peerRouting", "lan", "count", "interval", "queryTimeout", "logger", "timeoutController", "signal", "found", "pipe", "source", "take", "length", "err", "peerDiscovery", "symbol", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "KadDHT", "EventEmitter", "components", "init", "kBucketSize", "clientMode", "validators", "selectors", "querySelfInterval", "lan", "protocolPrefix", "pingTimeout", "pingConcurrency", "maxInboundStreams", "maxOutboundStreams", "providersInit", "logger", "PROTOCOL_PREFIX", "LAN_PREFIX", "PROTOCOL_DHT", "RoutingTable", "Providers", "Network", "QueryManager", "PeerRouting", "ContentFetching", "ContentRouting", "RoutingTableRefresh", "RPC", "TopologyListener", "QuerySelf", "evt", "peerData", "err", "CustomEvent", "peerId", "multiaddrs", "addr", "symbol", "removePublicAddresses", "removePrivateAddresses", "mode", "key", "value", "options", "id", "log", "logger", "DualKadDHT", "EventEmitter", "components", "wan", "lan", "evt", "CustomEvent", "symbol", "mode", "key", "value", "options", "event", "merge", "queriedPeers", "foundValue", "CodeError", "queryErrorEvent", "sent", "success", "errors", "dhts", "dht", "id", "KadDHT", "DualKadDHT", "components", "init", "kadDHT", "log", "logger", "DEFAULT_BOOTSTRAP_TAG_NAME", "DEFAULT_BOOTSTRAP_TAG_VALUE", "DEFAULT_BOOTSTRAP_TAG_TTL", "DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT", "Bootstrap", "EventEmitter", "components", "options", "candidate", "P2P", "ma", "multiaddr", "peerIdStr", "peerData", "peerIdFromString", "symbol", "err", "CustomEvent", "bootstrap", "init", "web_socket_browser_default", "import_event_iterator", "isArrayBuffer", "obj", "_a", "source_default", "socket", "connected", "resolve", "reject", "isConnected", "connError", "cleanUp", "cont", "onOpen", "onError", "event", "source", "messages", "push", "stop", "fail", "onMessage", "data", "fromString", "chunk", "ready_default", "socket", "resolve", "reject", "cleanup", "handleOpen", "handleErr", "event", "sink_default", "socket", "options", "source", "data", "ready_default", "err", "resolve", "reject", "event", "duplex_default", "socket", "options", "connectedSource", "source_default", "remoteAddress", "remotePort", "url", "sink_default", "resolve", "import_iso_url", "map", "def", "ws_url_default", "url", "location", "connect", "addr", "opts", "location", "url", "ws_url_default", "socket", "web_socket_browser_default", "duplex_default", "createListener", "log", "logger", "socketToMaConn", "stream", "remoteAddr", "options", "maConn", "source", "abortableSource", "err", "start", "pTimeout", "host", "port", "all", "multiaddrs", "ma", "testMa", "WebSockets", "WebSocketsSecure", "wss", "symbol", "FaultTolerance", "log", "logger", "WebSockets", "init", "symbol", "ma", "options", "socket", "maConn", "socketToMaConn", "conn", "_a", "_b", "AbortError", "cOpts", "errorPromise", "pDefer", "errfn", "err", "rawSocket", "connect", "multiaddrToUri", "onAbort", "abort", "resolve", "reject", "createListener", "multiaddrs", "isBrowser", "isWebWorker", "wss", "all", "webSockets", "import_varint", "allocUnsafe", "size", "MessageTypes", "MessageTypeNames", "InitiatorMessageTypes", "ReceiverMessageTypes", "DEFAULT_BATCH_SIZE", "DEFAULT_SERIALIZE", "buf", "list", "batchedBytes", "source", "options", "buffer", "Uint8ArrayList", "ended", "deferred", "pDefer", "size", "yieldAfter", "serialize", "timeout", "err", "b", "src_default", "POOL_SIZE", "Encoder", "allocUnsafe", "msg", "list", "pool", "offset", "varint", "MessageTypes", "header", "encoder", "encode", "source", "minSendBytes", "messages", "Uint8ArrayList", "src_default", "obj", "m", "MAX_MSG_SIZE", "MAX_MSG_QUEUE_SIZE", "Decoder", "maxMessageSize", "maxUnprocessedMessageQueueSize", "Uint8ArrayList", "chunk", "msgs", "err", "id", "type", "length", "offset", "msg", "MessageTypes", "data", "h", "readVarInt", "end", "MessageTypeNames", "MSB", "REST", "buf", "res", "shift", "counter", "b", "l", "log", "logger", "ERR_STREAM_RESET", "ERR_STREAM_ABORT", "ERR_SINK_ENDED", "ERR_DOUBLE_SINK", "createStream", "options", "id", "name", "send", "onEnd", "type", "maxMsgSize", "MAX_MSG_SIZE", "abortController", "resetController", "closeController", "Types", "InitiatorMessageTypes", "ReceiverMessageTypes", "externalId", "streamName", "sourceEnded", "sinkEnded", "sinkSunk", "endErr", "timeline", "onSourceEnd", "err", "stream", "onSinkEnd", "streamSource", "pushable", "CodeError", "source", "signal", "anySignal", "abortableSource", "Uint8ArrayList", "fromString", "data", "import_rate_limiter_flexible", "log", "logger", "MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION", "MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION", "MAX_STREAM_BUFFER_SIZE", "DISCONNECT_THRESHOLD", "printMessage", "msg", "output", "MessageTypeNames", "MessageTypes", "toString", "MplexStreamMuxer", "init", "source", "streams", "stream", "name", "id", "registry", "err", "s", "options", "type", "CodeError", "createStream", "signal", "anySignal", "abortableSource", "decoder", "Decoder", "chunk", "pushableV", "encode", "message", "maxBufferSize", "error", "Mplex", "init", "MplexStreamMuxer", "mplex", "isAsyncIterable", "thing", "defaultEncoder", "length", "lengthLength", "encodingLength", "lengthBuf", "allocUnsafe", "encode", "source", "options", "encodeLength", "maybeYield", "chunk", "isAsyncIterable", "Uint8ArrayList", "InvalidMessageLengthError", "__publicField", "InvalidDataLengthError", "InvalidDataLengthLengthError", "UnexpectedEOFError", "MAX_LENGTH_LENGTH", "MAX_DATA_LENGTH", "ReadMode", "defaultDecoder", "buf", "length", "decode", "encodingLength", "source", "options", "buffer", "Uint8ArrayList", "mode", "dataLength", "lengthDecoder", "maxLengthLength", "maxDataLength", "maybeYield", "InvalidMessageLengthError", "InvalidDataLengthError", "dataLengthLength", "err", "InvalidDataLengthLengthError", "data", "isAsyncIterable", "UnexpectedEOFError", "reader", "byteLength", "varByteSource", "done", "value", "l", "import_err_code", "defaultLengthDecoder", "buf", "unsigned", "pbStream", "duplex", "opts", "write", "pushable", "err", "source", "readBuffer", "Uint8ArrayList", "W", "bytes", "done", "value", "errCode", "dataLength", "lengthBuffer", "decodeLength", "proto", "data", "encode", "d", "originalStream", "pair", "deferred", "pDefer", "piped", "source", "duplexPair", "a", "pair", "b", "_a", "_b", "DUMP_SESSION_KEYS", "import_hkdf", "x25519", "import_sha256", "import_chacha20poly1305", "stablelib", "data", "ck", "ikm", "okm", "k1", "k2", "k3", "keypair", "seed", "privateKey", "publicKey", "plaintext", "nonce", "ad", "k", "ciphertext", "dst", "import_chacha20poly1305", "allocUnsafe", "len", "uint16BEEncode", "value", "target", "uint16BEDecode", "data", "encode0", "message", "concat", "encode1", "encode2", "decode0", "input", "decode1", "decode2", "encryptStream", "handshake", "metrics", "source", "chunk", "end", "data", "uint16BEEncode", "decryptStream", "encrypted", "dst", "decrypted", "valid", "UnexpectedPeerError", "message", "InvalidCryptoExchangeError", "NoiseExtensions", "_codec", "message", "obj", "w", "opts", "value", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "NoiseHandshakePayload", "getPayload", "localPeer", "staticPublicKey", "extensions", "signedPayload", "signPayload", "getHandshakePayload", "createHandshakePayload", "libp2pPublicKey", "NoiseHandshakePayload", "peerId", "payload", "unmarshalPrivateKey", "getPeerIdFromPayload", "peerIdFromKeys", "decodePayload", "publicKey", "prefix", "fromString", "concat", "verifySignedPayload", "noiseStaticKey", "remotePeer", "payloadPeerId", "generatedPayload", "unmarshalPublicKey", "isValidPublicKey", "pk", "log", "logger", "keyLogger", "DUMP_SESSION_KEYS", "log", "logLocalStaticKeys", "s", "toString", "logLocalEphemeralKeys", "e", "logRemoteStaticKey", "rs", "logRemoteEphemeralKey", "re", "logCipherState", "session", "ERR_MAX_NONCE", "Nonce", "n", "AbstractHandshake", "crypto", "cs", "ad", "plaintext", "e", "ciphertext", "dst", "valid", "k", "emptyKey", "equals", "n", "ss", "encryptedMessage", "privateKey", "publicKey", "derivedU8", "err", "log", "data", "a", "b", "concat", "ikm", "ck", "tempK", "Nonce", "protocolName", "protocolNameBytes", "fromString", "h", "key", "tempk1", "tempk2", "cs1", "cs2", "payload", "ne", "ns", "message", "XX", "AbstractHandshake", "prologue", "s", "rs", "psk", "name", "ss", "re", "hs", "payload", "e", "ns", "ne", "ciphertext", "spk", "messageBuffer", "cs1", "cs2", "message", "isValidPublicKey", "valid1", "plaintext", "valid2", "initiator", "session", "ephemeral", "h", "resultingBuffer", "valid", "resultingPlaintext", "resultingValid", "XXHandshake", "isInitiator", "payload", "prologue", "crypto", "staticKeypair", "connection", "remotePeer", "handshake", "XX", "logLocalStaticKeys", "log", "messageBuffer", "encode0", "logLocalEphemeralKeys", "receivedMessageBuffer", "decode0", "valid", "InvalidCryptoExchangeError", "logRemoteEphemeralKey", "decode1", "plaintext", "logRemoteStaticKey", "decodedPayload", "decodePayload", "getPeerIdFromPayload", "verifySignedPayload", "e", "err", "UnexpectedPeerError", "encode1", "encode2", "decode2", "logCipherState", "session", "cs", "ciphertext", "dst", "encryption", "registerMetrics", "metrics", "Noise", "init", "staticNoiseKey", "extensions", "crypto", "prologueBytes", "metrics", "stablelib", "registerMetrics", "localPeer", "connection", "remotePeer", "wrappedConnection", "pbStream", "uint16BEEncode", "uint16BEDecode", "handshake", "params", "payload", "getPayload", "_a", "_b", "isInitiator", "XXHandshake", "e", "secure", "user", "duplexPair", "network", "pipe", "encryptStream", "decode", "decryptStream", "noise", "init", "Noise", "mergeOptions", "merge_options_default", "createLibp2p", "options", "peerId", "multiaddrs", "repo", "keychainConfig", "config", "datastore", "libp2pOptions", "getLibp2pOptions", "_a", "_b", "_c", "_d", "getPubsubRouter", "router", "get", "availableRouters", "routers", "errCode", "libp2pDefaults", "ma", "ipfsCore", "mplex", "noise", "kadDHT", "ipnsValidator", "ipnsSelector", "boostrapNodes", "bootstrap", "constructorOptions", "libp2pFinalConfig", "libp2pConfig", "delegateHosts", "delegateString", "delegateAddr", "multiaddr", "delegateApiOptions", "delegateHttpClient", "create", "delegatedContentRouting", "delegatedPeerRouting", "d", "t", "webSockets", "PeerIdProto", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "createEd25519PeerId", "key", "generateKeyPair", "id", "createFromPrivKey", "createRSAPeerId", "opts", "key", "generateKeyPair", "id", "createFromPrivKey", "createFromPrivKey", "privateKey", "peerIdFromKeys", "marshalPublicKey", "marshalPrivateKey", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "Storage", "peerId", "keychain", "repo", "print", "isNew", "codecs", "options", "repoAutoMigrate", "inputRepo", "onMigrationProgress", "createRepo", "loadRepo", "configureRepo", "err", "ERR_REPO_NOT_INITIALIZED", "NotEnabledError", "initRepo", "initOptions", "exists", "decodePeerId", "initPeerId", "identity", "peerIdToIdentity", "config", "applyProfiles", "config_browser_default", "keychainConfig", "libp2p", "createLibp2p", "Key", "isPeerId", "rawPrivateKey", "fromString", "key", "unmarshalPrivateKey", "peerIdFromKeys", "algorithm", "bits", "createEd25519PeerId", "createRSAPeerId", "errCode", "toString", "profiles", "pass", "original", "changed", "mergeConfigs", "NotInitializedError", "buf", "changes", "name", "profile", "import_varint_decoder", "varint", "varintEncoder", "buf", "out", "acc", "curr", "offset", "num", "varint_encoder_default", "WantListEntry", "cid", "priority", "wantType", "base58btc", "other", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Message", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "j", "typeUrlPrefix", "Wantlist", "valuesById", "values", "Entry", "Block", "BlockPresence", "WantType", "Message", "sortBy", "fn", "list", "a", "b", "aa", "bb", "Wantlist", "stats", "libp2p", "trackedMap", "cid", "priority", "wantType", "cidStr", "base58btc", "entry", "WantListEntry", "o", "WantlistEntry", "Wantlist", "BitswapMessageEntry", "cid", "priority", "wantType", "cancel", "sendDontHave", "val", "base58btc", "other", "logger", "id", "subsystem", "name", "isMapEqual", "a", "b", "key", "valueA", "valueB", "equals", "BitswapMessageEntry", "BitswapMessage", "full", "cid", "priority", "wantType", "cancel", "sendDontHave", "cidStr", "base58btc", "entry", "BitswapMessageEntry", "block", "size", "msg", "Message", "data", "CID", "version", "codec", "multihash", "digestLength", "prefix", "varint_encoder_default", "bpType", "other", "isMapEqual", "list", "blocks", "raw", "hashLoader", "decoded", "isFull", "blockPresence", "b", "hash", "sha256", "p", "values", "vd", "cidVersion", "multicodec", "hashAlg", "hasher", "CodeError", "kMaxPriority", "maxListeners", "wantlistSendDebounceMs", "functionDebounce", "debounce", "fn", "wait", "callFirst", "timeout", "debouncedFn", "clear", "flush", "call", "debounceWrapper", "context", "args", "callNow", "MsgQueue", "selfPeerId", "otherPeerId", "network", "logger", "functionDebounce", "wantlistSendDebounceMs", "msg", "entries", "BitswapMessage", "entry", "err", "WantManager", "peerId", "network", "stats", "libp2p", "trackedMap", "Wantlist", "logger", "cids", "cancel", "force", "entries", "cid", "i", "BitswapMessage", "kMaxPriority", "e", "base58btc", "p", "mq", "MsgQueue", "fullwantlist", "entry", "options", "noop", "TopologyImpl", "init", "topologySymbol", "registrar", "peerId", "createTopology", "import_timeout_abort_controller", "BITSWAP100", "BITSWAP110", "BITSWAP120", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "DEFAULT_INCOMING_STREAM_TIMEOUT", "Network", "libp2p", "bitswap", "stats", "options", "logger", "topology", "createTopology", "protocol", "conn", "id", "stream", "connection", "controller", "pipe", "abortableSource", "decode", "source", "data", "message", "BitswapMessage", "err", "peerId", "cid", "connectAttempts", "found", "provider", "peer", "msg", "stringId", "writeMessage", "blocks", "block", "log", "serialized", "encode", "Ledger", "peerId", "Wantlist", "n", "cid", "priority", "wantType", "SortedMap", "entries", "cmp", "k", "v", "i", "newIdx", "j", "lower", "upper", "pivot", "cb", "thisArg", "a", "b", "DefaultTaskMerger", "RequestQueue", "taskMerger", "SortedMap", "PeerTasks", "peerId", "tasks", "peerTasks", "targetMinBytes", "pendingSize", "v", "topic", "task", "PendingTasks", "existingTask", "tasksWithTopic", "activeTask", "size", "pendingTasks", "i", "a", "b", "priority", "obj", "TaskMerger", "task", "tasksWithTopic", "haveBlock", "isWantBlock", "existing", "newTask", "existingTask", "taskData", "existingData", "WantType", "BitswapMessage", "TARGET_MESSAGE_SIZE", "MAX_SIZE_REPLACE_HAS_WITH_BLOCK", "DecisionEngine", "peerId", "blockstore", "network", "stats", "libp2p", "opts", "logger", "trackedMap", "RequestQueue", "TaskMerger", "tasks", "pendingSize", "msg", "blockCids", "blockTasks", "task", "cid", "CID", "blocks", "topic", "taskData", "blk", "cidStr", "block", "err", "peerIdStr", "ledger", "l", "want", "blockSize", "isWantBlock", "entrySize", "base58btc", "Wantlist", "cancels", "wants", "entry", "cids", "c", "blockSizes", "w", "id", "wantType", "k", "v", "res", "e", "blocksMap", "Ledger", "import_events", "unwantEvent", "cid", "toString", "blockEvent", "Notifications", "peerId", "maxListeners", "logger", "block", "event", "options", "blockEvt", "unwantEvt", "resolve", "reject", "onUnwant", "onBlock", "data", "import_events", "import_events", "import_moving_average", "Stat", "initialCounters", "options", "key", "interval", "MovingAverage", "counter", "inc", "urgency", "last", "op", "latestTime", "timeDiff", "timeDiffMS", "count", "hz", "movingAverages", "movingAverageInterval", "movingAverage", "defaultOptions", "Stats", "libp2p", "initialCounters", "_options", "options", "Stat", "stats", "trackedMap", "peerStat", "peerId", "peerIdStr", "peer", "counter", "inc", "peerStats", "import_any_signal", "defaultOptions", "statsKeys", "Bitswap", "BaseBlockstore", "libp2p", "blockstore", "options", "logger", "Stats", "Network", "DecisionEngine", "WantManager", "Notifications", "peerId", "incoming", "received", "cidStr", "data", "cid", "CID", "wasWanted", "has", "peerIdStr", "exists", "err", "_options", "fetchFromNetwork", "promptedNetwork", "loadOrFetchFromNetwork", "controller", "signal", "cids", "cidsArray", "block", "source", "key", "value", "createBitswap", "libp2p", "blockstore", "options", "Bitswap", "import_err_code", "errors_exports", "__export", "abortedError", "notFoundError", "import_err_code", "err", "errCode", "Errors", "errors_exports", "BlockStorage", "BaseBlockstore", "blockstore", "bitswap", "cid", "block", "options", "blocks", "missingBlocks", "filter", "key", "cids", "getFromBitswap", "pushable", "getFromChild", "merge", "q", "Network", "peerId", "libp2p", "bitswap", "repo", "blockstore", "print", "hashers", "options", "config", "createLibp2p", "readAddrs", "ma", "createBitswap", "BlockStorage", "network", "peerIdStr", "addrs", "swarm", "addr", "multiaddr", "WEBSOCKET_STAR_PROTO_CODE", "errCode", "maId", "createAddrs", "network", "addrs", "options", "peers", "libp2p", "peer", "mi", "withTimeoutOption", "createConnect", "network", "connect", "multiaddrOrPeerId", "options", "libp2p", "withTimeoutOption", "createDisconnect", "network", "disconnect", "addr", "options", "libp2p", "withTimeoutOption", "createLocalAddrs", "network", "localAddrs", "options", "libp2p", "withTimeoutOption", "createPeers", "network", "peers", "options", "libp2p", "connection", "peer", "withTimeoutOption", "SwarmAPI", "network", "createAddrs", "createConnect", "createDisconnect", "createLocalAddrs", "createPeers", "basePacket", "createPing", "network", "ping", "peerId", "options", "libp2p", "storedPeer", "id", "remotePeer", "packetCount", "totalTime", "i", "time", "err", "average", "withTimeoutOption", "import_err_code", "IPNS_PREFIX", "toDHTKey", "str", "buf", "base58btc", "base36", "concat", "fromString", "createDht", "network", "repo", "peerId", "get", "put", "findProvs", "findPeer", "provide", "query", "key", "options", "libp2p", "use", "dhtKey", "errCode", "value", "cid", "peerIdToFind", "peerIdToQuery", "bytes", "asCid", "CID", "peerIdFromString", "withTimeoutOption", "net", "fn", "NotEnabledError", "import_err_code", "import_dlv", "createPubsub", "network", "config", "isEnabled", "get", "handlers", "onMessage", "withTimeoutOption", "subscribe", "notEnabled", "unsubscribe", "publish", "ls", "peers", "topic", "handler", "options", "libp2p", "evt", "msg", "h", "data", "errCode", "NotEnabledError", "mergeOptions", "merge_options_default", "log", "logger", "IPNS_INIT_KEYSPACE_TIMEOUT", "IPFS", "print", "storage", "codecs", "options", "peerId", "repo", "keychain", "network", "Service", "Network", "preload", "createPreloader", "dns", "createDns", "isOnline", "createIsOnline", "ipns", "IPNSAPI", "multihashHashers", "hashes", "hasher", "Multihashes", "multibaseCodecs", "bases", "base", "Multibases", "pin", "PinAPI", "block", "BlockAPI", "name", "NameAPI", "resolve", "createResolve", "dag", "DagAPI", "refs", "createRefs", "createLocal", "add", "addAll", "cat", "get", "ls", "RootAPI", "files", "createFiles", "mfsPreload", "createMfsPreloader", "createStart", "createStop", "createDht", "createPubsub", "createId", "createVersion", "BitswapAPI", "BootstrapAPI", "createConfig", "createPing", "KeyAPI", "ObjectAPI", "RepoAPI", "StatsAPI", "SwarmAPI", "net", "notImplemented", "errCode", "notImplementedIter", "AlreadyInitializedError", "addEmptyDir", "ipfs", "buf", "encode", "UnixFS", "cid", "getDefaultOptions", "create", "initOptions", "id", "identity", "blockCodecs", "src_exports", "lib_exports", "codec", "multicodecs", "Multicodecs", "Storage", "config", "timeoutController", "fromString", "import_url_source", "create", "CID", "cid", "ipfs", "create", "filename", "content", "fileToAdd", "file", "cid", "CID", "decoder", "chunk", "getSyncTitle", "gistId", "localstorage_default", "shareNoteCommand", "icon", "exit_up_default", "share", "sharePublicLinkCommand", "commander_default", "saveNote", "dom_default", "note", "getNote", "rawLink", "publishGist", "gitResponse", "response", "files", "fileContents", "gistFile", "rawUrl", "linkToShare", "url", "copyToClipboard", "commands", "pencil_default", "resetNoteManager", "checkmark_circle_default", "disableSync", "updateGist", "setSavedState", "page_break_default", "markDownViewer_default", "frame_expand_default", "earth_default", "cid", "ipfs", "isUserLoggedIn", "leaf_default", "list_default", "trash_default", "deleteNote", "cloud_sync_default", "token", "goAuthenticate", "setGistToSyncWith", "syncNotesWithGitHub", "lighter_default", "notify_default", "enter_down_default", "text", "title", "saveFileAs", "envelope_default", "mailTo", "bug_default", "previousStatus", "arrow_right_circle_default", "picture_default", "bgImage", "sleep", "printer_default", "magic_wand_default", "prettifyJSON_default", "rocket_default", "spell_check_default", "selectedValue", "valueToFind", "positionOfFirstChar", "replacementValue", "download_default", "notes", "getNotes", "saveDataToFile", "keyListener", "key", "fn", "k", "finalKey", "functionToCall", "e", "event", "keyListener_default", "link", "textOrNode", "url", "a", "isElement", "isSameYear", "aDate", "bDate", "yearA", "yearB", "isSameMonth", "monthA", "monthB", "isSameDateOfMonth", "dateA", "dateB", "isSameDate", "monthNames", "shortMonthNames", "name", "isYesterday", "date", "theDate", "yesterDate", "relativeDate", "dateCreated", "month", "year", "day", "isArraySorted", "arr", "currentValue", "item", "max", "smartFilter", "phrase", "filter", "wordParts", "w", "indexes", "f", "i", "currentValue", "fi", "isArraySorted", "requestNotificationPermission", "localstorage_default", "permission", "registerServiceWorker", "getShortcut", "key", "k", "commander", "commanderModes", "state", "newState", "what", "dom_default", "mode", "requestNotificationPermission", "commands", "e", "direction", "currentlySelected", "lastOption", "indexToSelect", "command", "button", "keyListener_default", "revisions", "getNote", "revisionsOptions", "a", "b", "aDateCreated", "bDateCreated", "id", "i", "div", "relativeDate", "url", "r", "value", "notes", "getNotes", "title", "smartFilter", "deleted", "getDateCreatedFromTitle", "cid", "dateCreated", "linkParams", "href", "noteLink", "link", "commandComponents", "experimental", "localstorage_default", "call", "icon", "commander_default", "import_textarea_caret", "findCurrentLine", "text", "caretIndex", "acc", "line", "isFound", "recon", "currentLength", "autoCompleteCheckboxes", "e", "currentLine", "findCurrentLine", "completers", "startsWith", "compleano", "dom_default", "isLastCharacterInTheWord", "text", "characterIndex", "placeSuggestion", "textEl", "coords", "getCaretCoordinates", "top", "left", "actualTerminalHeight", "dom_default", "main", "getCurrentlyTypingWord", "cursorIndexPosition", "word", "currentIndex", "character", "getPredictions", "sanitizedWord", "trieDictionary", "terminal", "initState", "state", "newState", "e", "direction", "currentlySelected", "lastOption", "indexToSelect", "complete", "currentWord", "completion", "prediction", "inlineSuggestion", "div", "optionsUl", "selectedIndex", "options", "i", "command", "icon", "trash_default", "localstorage_default", "m", "optionList", "el", "commander_default", "fullText", "charTyped", "matches", "firstMatch", "autoCompleteCheckboxes", "currentlySavedNote", "getNote", "title", "getTitle", "isNoteSaved", "setSavedState", "_a", "clipboardItems", "clipboardItem", "imageTypes", "type", "imageType", "blob", "token", "image", "fileExtension", "fileName", "nanoid", "url", "configuration", "handleErrorResponse", "response", "error", "notify_default", "imageURI", "markDownViewer_default", "isSyncEnabled", "authToken", "gistId", "localstorage_default", "groupByFrequency", "entries", "acc", "word", "frequency", "cc", "Node", "char", "prefix", "dictionary", "nodeInstance", "node", "firstChar", "rest", "isLast", "newNode", "Trie", "rootNode", "character", "frequencyGroups", "a", "b", "key", "errorHandler", "error", "message", "notify_default", "errorHandler_default", "retrieveNoteFromIPFS", "cid", "dom_default", "remoteNote", "ipfs", "setSavedState", "setNoteFromRawUrl", "rawUrl", "response", "dom_default", "setNoteFromGist", "gistId", "gist", "getGist", "files", "fileContents", "gistFile", "content", "notify_default", "actOnURLStateChange", "e", "oldURL", "newURL", "oldPageId", "url", "newPageId", "hasPageIdChanged", "oldV", "newV", "r", "setNoteFromHash", "raw", "isANewNote", "retrieveNoteFromIPFS", "q", "queryResult", "search", "isDevelopmentMode", "enableDevelopment", "autoMagicallyCheckBoxes", "dom_default", "el", "trieDictionary", "Trie", "initInfoPanel", "dom_default", "note", "getNote", "relativeDate", "isSyncEnabled", "syncEl", "disableSync", "p", "e", "disableSyncOnCurrentNote", "deleteButton", "deleteNote", "main", "words", "localstorage_default", "errorHandler_default", "welcome_default", "commander_default", "terminal", "resetPageTitle", "setNoteFromHash", "url", "copyToClipboard", "markDownViewer_default", "actOnURLStateChange", "registerServiceWorker", "autoMagicallyCheckBoxes", "syncNotesWithGitHub", "setAuthTokenFromCallback", "enableDevelopment", "main_default", "main_default"] + "sourcesContent": ["/**\n * Created by Tivie on 13-07-2015.\n */\n\nfunction getDefaultOpts (simple) {\n 'use strict';\n\n var defaultOptions = {\n omitExtraWLInCodeBlocks: {\n defaultValue: false,\n describe: 'Omit the default extra whiteline added to code blocks',\n type: 'boolean'\n },\n noHeaderId: {\n defaultValue: false,\n describe: 'Turn on/off generated header id',\n type: 'boolean'\n },\n prefixHeaderId: {\n defaultValue: false,\n describe: 'Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic \\'section-\\' prefix',\n type: 'string'\n },\n rawPrefixHeaderId: {\n defaultValue: false,\n describe: 'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the \" char is used in the prefix)',\n type: 'boolean'\n },\n ghCompatibleHeaderId: {\n defaultValue: false,\n describe: 'Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)',\n type: 'boolean'\n },\n rawHeaderId: {\n defaultValue: false,\n describe: 'Remove only spaces, \\' and \" from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids',\n type: 'boolean'\n },\n headerLevelStart: {\n defaultValue: false,\n describe: 'The header blocks level start',\n type: 'integer'\n },\n parseImgDimensions: {\n defaultValue: false,\n describe: 'Turn on/off image dimension parsing',\n type: 'boolean'\n },\n simplifiedAutoLink: {\n defaultValue: false,\n describe: 'Turn on/off GFM autolink style',\n type: 'boolean'\n },\n excludeTrailingPunctuationFromURLs: {\n defaultValue: false,\n describe: 'Excludes trailing punctuation from links generated with autoLinking',\n type: 'boolean'\n },\n literalMidWordUnderscores: {\n defaultValue: false,\n describe: 'Parse midword underscores as literal underscores',\n type: 'boolean'\n },\n literalMidWordAsterisks: {\n defaultValue: false,\n describe: 'Parse midword asterisks as literal asterisks',\n type: 'boolean'\n },\n strikethrough: {\n defaultValue: false,\n describe: 'Turn on/off strikethrough support',\n type: 'boolean'\n },\n tables: {\n defaultValue: false,\n describe: 'Turn on/off tables support',\n type: 'boolean'\n },\n tablesHeaderId: {\n defaultValue: false,\n describe: 'Add an id to table headers',\n type: 'boolean'\n },\n ghCodeBlocks: {\n defaultValue: true,\n describe: 'Turn on/off GFM fenced code blocks support',\n type: 'boolean'\n },\n tasklists: {\n defaultValue: false,\n describe: 'Turn on/off GFM tasklist support',\n type: 'boolean'\n },\n smoothLivePreview: {\n defaultValue: false,\n describe: 'Prevents weird effects in live previews due to incomplete input',\n type: 'boolean'\n },\n smartIndentationFix: {\n defaultValue: false,\n describe: 'Tries to smartly fix indentation in es6 strings',\n type: 'boolean'\n },\n disableForced4SpacesIndentedSublists: {\n defaultValue: false,\n describe: 'Disables the requirement of indenting nested sublists by 4 spaces',\n type: 'boolean'\n },\n simpleLineBreaks: {\n defaultValue: false,\n describe: 'Parses simple line breaks as
    (GFM Style)',\n type: 'boolean'\n },\n requireSpaceBeforeHeadingText: {\n defaultValue: false,\n describe: 'Makes adding a space between `#` and the header text mandatory (GFM Style)',\n type: 'boolean'\n },\n ghMentions: {\n defaultValue: false,\n describe: 'Enables github @mentions',\n type: 'boolean'\n },\n ghMentionsLink: {\n defaultValue: 'https://github.com/{u}',\n describe: 'Changes the link generated by @mentions. Only applies if ghMentions option is enabled.',\n type: 'string'\n },\n encodeEmails: {\n defaultValue: true,\n describe: 'Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities',\n type: 'boolean'\n },\n openLinksInNewWindow: {\n defaultValue: false,\n describe: 'Open all links in new windows',\n type: 'boolean'\n },\n backslashEscapesHTMLTags: {\n defaultValue: false,\n describe: 'Support for HTML Tag escaping. ex: \\
    foo\\
    ',\n type: 'boolean'\n },\n emoji: {\n defaultValue: false,\n describe: 'Enable emoji support. Ex: `this is a :smile: emoji`',\n type: 'boolean'\n },\n underline: {\n defaultValue: false,\n describe: 'Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `` and ``',\n type: 'boolean'\n },\n ellipsis: {\n defaultValue: true,\n describe: 'Replaces three dots with the ellipsis unicode character',\n type: 'boolean'\n },\n completeHTMLDocument: {\n defaultValue: false,\n describe: 'Outputs a complete html document, including ``, `` and `` tags',\n type: 'boolean'\n },\n metadata: {\n defaultValue: false,\n describe: 'Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).',\n type: 'boolean'\n },\n splitAdjacentBlockquotes: {\n defaultValue: false,\n describe: 'Split adjacent blockquote blocks',\n type: 'boolean'\n }\n };\n if (simple === false) {\n return JSON.parse(JSON.stringify(defaultOptions));\n }\n var ret = {};\n for (var opt in defaultOptions) {\n if (defaultOptions.hasOwnProperty(opt)) {\n ret[opt] = defaultOptions[opt].defaultValue;\n }\n }\n return ret;\n}\n\nfunction allOptionsOn () {\n 'use strict';\n var options = getDefaultOpts(true),\n ret = {};\n for (var opt in options) {\n if (options.hasOwnProperty(opt)) {\n ret[opt] = true;\n }\n }\n return ret;\n}\n", "/**\n * Created by Tivie on 06-01-2015.\n */\n\n// Private properties\nvar showdown = {},\n parsers = {},\n extensions = {},\n globalOptions = getDefaultOpts(true),\n setFlavor = 'vanilla',\n flavor = {\n github: {\n omitExtraWLInCodeBlocks: true,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true,\n literalMidWordUnderscores: true,\n strikethrough: true,\n tables: true,\n tablesHeaderId: true,\n ghCodeBlocks: true,\n tasklists: true,\n disableForced4SpacesIndentedSublists: true,\n simpleLineBreaks: true,\n requireSpaceBeforeHeadingText: true,\n ghCompatibleHeaderId: true,\n ghMentions: true,\n backslashEscapesHTMLTags: true,\n emoji: true,\n splitAdjacentBlockquotes: true\n },\n original: {\n noHeaderId: true,\n ghCodeBlocks: false\n },\n ghost: {\n omitExtraWLInCodeBlocks: true,\n parseImgDimensions: true,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true,\n literalMidWordUnderscores: true,\n strikethrough: true,\n tables: true,\n tablesHeaderId: true,\n ghCodeBlocks: true,\n tasklists: true,\n smoothLivePreview: true,\n simpleLineBreaks: true,\n requireSpaceBeforeHeadingText: true,\n ghMentions: false,\n encodeEmails: true\n },\n vanilla: getDefaultOpts(true),\n allOn: allOptionsOn()\n };\n\n/**\n * helper namespace\n * @type {{}}\n */\nshowdown.helper = {};\n\n/**\n * TODO LEGACY SUPPORT CODE\n * @type {{}}\n */\nshowdown.extensions = {};\n\n/**\n * Set a global option\n * @static\n * @param {string} key\n * @param {*} value\n * @returns {showdown}\n */\nshowdown.setOption = function (key, value) {\n 'use strict';\n globalOptions[key] = value;\n return this;\n};\n\n/**\n * Get a global option\n * @static\n * @param {string} key\n * @returns {*}\n */\nshowdown.getOption = function (key) {\n 'use strict';\n return globalOptions[key];\n};\n\n/**\n * Get the global options\n * @static\n * @returns {{}}\n */\nshowdown.getOptions = function () {\n 'use strict';\n return globalOptions;\n};\n\n/**\n * Reset global options to the default values\n * @static\n */\nshowdown.resetOptions = function () {\n 'use strict';\n globalOptions = getDefaultOpts(true);\n};\n\n/**\n * Set the flavor showdown should use as default\n * @param {string} name\n */\nshowdown.setFlavor = function (name) {\n 'use strict';\n if (!flavor.hasOwnProperty(name)) {\n throw Error(name + ' flavor was not found');\n }\n showdown.resetOptions();\n var preset = flavor[name];\n setFlavor = name;\n for (var option in preset) {\n if (preset.hasOwnProperty(option)) {\n globalOptions[option] = preset[option];\n }\n }\n};\n\n/**\n * Get the currently set flavor\n * @returns {string}\n */\nshowdown.getFlavor = function () {\n 'use strict';\n return setFlavor;\n};\n\n/**\n * Get the options of a specified flavor. Returns undefined if the flavor was not found\n * @param {string} name Name of the flavor\n * @returns {{}|undefined}\n */\nshowdown.getFlavorOptions = function (name) {\n 'use strict';\n if (flavor.hasOwnProperty(name)) {\n return flavor[name];\n }\n};\n\n/**\n * Get the default options\n * @static\n * @param {boolean} [simple=true]\n * @returns {{}}\n */\nshowdown.getDefaultOptions = function (simple) {\n 'use strict';\n return getDefaultOpts(simple);\n};\n\n/**\n * Get or set a subParser\n *\n * subParser(name) - Get a registered subParser\n * subParser(name, func) - Register a subParser\n * @static\n * @param {string} name\n * @param {function} [func]\n * @returns {*}\n */\nshowdown.subParser = function (name, func) {\n 'use strict';\n if (showdown.helper.isString(name)) {\n if (typeof func !== 'undefined') {\n parsers[name] = func;\n } else {\n if (parsers.hasOwnProperty(name)) {\n return parsers[name];\n } else {\n throw Error('SubParser named ' + name + ' not registered!');\n }\n }\n }\n};\n\n/**\n * Gets or registers an extension\n * @static\n * @param {string} name\n * @param {object|object[]|function=} ext\n * @returns {*}\n */\nshowdown.extension = function (name, ext) {\n 'use strict';\n\n if (!showdown.helper.isString(name)) {\n throw Error('Extension \\'name\\' must be a string');\n }\n\n name = showdown.helper.stdExtName(name);\n\n // Getter\n if (showdown.helper.isUndefined(ext)) {\n if (!extensions.hasOwnProperty(name)) {\n throw Error('Extension named ' + name + ' is not registered!');\n }\n return extensions[name];\n\n // Setter\n } else {\n // Expand extension if it's wrapped in a function\n if (typeof ext === 'function') {\n ext = ext();\n }\n\n // Ensure extension is an array\n if (!showdown.helper.isArray(ext)) {\n ext = [ext];\n }\n\n var validExtension = validate(ext, name);\n\n if (validExtension.valid) {\n extensions[name] = ext;\n } else {\n throw Error(validExtension.error);\n }\n }\n};\n\n/**\n * Gets all extensions registered\n * @returns {{}}\n */\nshowdown.getAllExtensions = function () {\n 'use strict';\n return extensions;\n};\n\n/**\n * Remove an extension\n * @param {string} name\n */\nshowdown.removeExtension = function (name) {\n 'use strict';\n delete extensions[name];\n};\n\n/**\n * Removes all extensions\n */\nshowdown.resetExtensions = function () {\n 'use strict';\n extensions = {};\n};\n\n/**\n * Validate extension\n * @param {array} extension\n * @param {string} name\n * @returns {{valid: boolean, error: string}}\n */\nfunction validate (extension, name) {\n 'use strict';\n\n var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',\n ret = {\n valid: true,\n error: ''\n };\n\n if (!showdown.helper.isArray(extension)) {\n extension = [extension];\n }\n\n for (var i = 0; i < extension.length; ++i) {\n var baseMsg = errMsg + ' sub-extension ' + i + ': ',\n ext = extension[i];\n if (typeof ext !== 'object') {\n ret.valid = false;\n ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';\n return ret;\n }\n\n if (!showdown.helper.isString(ext.type)) {\n ret.valid = false;\n ret.error = baseMsg + 'property \"type\" must be a string, but ' + typeof ext.type + ' given';\n return ret;\n }\n\n var type = ext.type = ext.type.toLowerCase();\n\n // normalize extension type\n if (type === 'language') {\n type = ext.type = 'lang';\n }\n\n if (type === 'html') {\n type = ext.type = 'output';\n }\n\n if (type !== 'lang' && type !== 'output' && type !== 'listener') {\n ret.valid = false;\n ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: \"lang/language\", \"output/html\" or \"listener\"';\n return ret;\n }\n\n if (type === 'listener') {\n if (showdown.helper.isUndefined(ext.listeners)) {\n ret.valid = false;\n ret.error = baseMsg + '. Extensions of type \"listener\" must have a property called \"listeners\"';\n return ret;\n }\n } else {\n if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {\n ret.valid = false;\n ret.error = baseMsg + type + ' extensions must define either a \"regex\" property or a \"filter\" method';\n return ret;\n }\n }\n\n if (ext.listeners) {\n if (typeof ext.listeners !== 'object') {\n ret.valid = false;\n ret.error = baseMsg + '\"listeners\" property must be an object but ' + typeof ext.listeners + ' given';\n return ret;\n }\n for (var ln in ext.listeners) {\n if (ext.listeners.hasOwnProperty(ln)) {\n if (typeof ext.listeners[ln] !== 'function') {\n ret.valid = false;\n ret.error = baseMsg + '\"listeners\" property must be an hash of [event name]: [callback]. listeners.' + ln +\n ' must be a function but ' + typeof ext.listeners[ln] + ' given';\n return ret;\n }\n }\n }\n }\n\n if (ext.filter) {\n if (typeof ext.filter !== 'function') {\n ret.valid = false;\n ret.error = baseMsg + '\"filter\" must be a function, but ' + typeof ext.filter + ' given';\n return ret;\n }\n } else if (ext.regex) {\n if (showdown.helper.isString(ext.regex)) {\n ext.regex = new RegExp(ext.regex, 'g');\n }\n if (!(ext.regex instanceof RegExp)) {\n ret.valid = false;\n ret.error = baseMsg + '\"regex\" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';\n return ret;\n }\n if (showdown.helper.isUndefined(ext.replace)) {\n ret.valid = false;\n ret.error = baseMsg + '\"regex\" extensions must implement a replace string or function';\n return ret;\n }\n }\n }\n return ret;\n}\n\n/**\n * Validate extension\n * @param {object} ext\n * @returns {boolean}\n */\nshowdown.validateExtension = function (ext) {\n 'use strict';\n\n var validateExtension = validate(ext, null);\n if (!validateExtension.valid) {\n console.warn(validateExtension.error);\n return false;\n }\n return true;\n};\n", "/**\n * showdownjs helper functions\n */\n\nif (!showdown.hasOwnProperty('helper')) {\n showdown.helper = {};\n}\n\n/**\n * Check if var is string\n * @static\n * @param {string} a\n * @returns {boolean}\n */\nshowdown.helper.isString = function (a) {\n 'use strict';\n return (typeof a === 'string' || a instanceof String);\n};\n\n/**\n * Check if var is a function\n * @static\n * @param {*} a\n * @returns {boolean}\n */\nshowdown.helper.isFunction = function (a) {\n 'use strict';\n var getType = {};\n return a && getType.toString.call(a) === '[object Function]';\n};\n\n/**\n * isArray helper function\n * @static\n * @param {*} a\n * @returns {boolean}\n */\nshowdown.helper.isArray = function (a) {\n 'use strict';\n return Array.isArray(a);\n};\n\n/**\n * Check if value is undefined\n * @static\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n */\nshowdown.helper.isUndefined = function (value) {\n 'use strict';\n return typeof value === 'undefined';\n};\n\n/**\n * ForEach helper function\n * Iterates over Arrays and Objects (own properties only)\n * @static\n * @param {*} obj\n * @param {function} callback Accepts 3 params: 1. value, 2. key, 3. the original array/object\n */\nshowdown.helper.forEach = function (obj, callback) {\n 'use strict';\n // check if obj is defined\n if (showdown.helper.isUndefined(obj)) {\n throw new Error('obj param is required');\n }\n\n if (showdown.helper.isUndefined(callback)) {\n throw new Error('callback param is required');\n }\n\n if (!showdown.helper.isFunction(callback)) {\n throw new Error('callback param must be a function/closure');\n }\n\n if (typeof obj.forEach === 'function') {\n obj.forEach(callback);\n } else if (showdown.helper.isArray(obj)) {\n for (var i = 0; i < obj.length; i++) {\n callback(obj[i], i, obj);\n }\n } else if (typeof (obj) === 'object') {\n for (var prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n callback(obj[prop], prop, obj);\n }\n }\n } else {\n throw new Error('obj does not seem to be an array or an iterable object');\n }\n};\n\n/**\n * Standardidize extension name\n * @static\n * @param {string} s extension name\n * @returns {string}\n */\nshowdown.helper.stdExtName = function (s) {\n 'use strict';\n return s.replace(/[_?*+\\/\\\\.^-]/g, '').replace(/\\s/g, '').toLowerCase();\n};\n\nfunction escapeCharactersCallback (wholeMatch, m1) {\n 'use strict';\n var charCodeToEscape = m1.charCodeAt(0);\n return '¨E' + charCodeToEscape + 'E';\n}\n\n/**\n * Callback used to escape characters when passing through String.replace\n * @static\n * @param {string} wholeMatch\n * @param {string} m1\n * @returns {string}\n */\nshowdown.helper.escapeCharactersCallback = escapeCharactersCallback;\n\n/**\n * Escape characters in a string\n * @static\n * @param {string} text\n * @param {string} charsToEscape\n * @param {boolean} afterBackslash\n * @returns {XML|string|void|*}\n */\nshowdown.helper.escapeCharacters = function (text, charsToEscape, afterBackslash) {\n 'use strict';\n // First we have to escape the escape characters so that\n // we can build a character class out of them\n var regexString = '([' + charsToEscape.replace(/([\\[\\]\\\\])/g, '\\\\$1') + '])';\n\n if (afterBackslash) {\n regexString = '\\\\\\\\' + regexString;\n }\n\n var regex = new RegExp(regexString, 'g');\n text = text.replace(regex, escapeCharactersCallback);\n\n return text;\n};\n\n/**\n * Unescape HTML entities\n * @param txt\n * @returns {string}\n */\nshowdown.helper.unescapeHTMLEntities = function (txt) {\n 'use strict';\n\n return txt\n .replace(/"/g, '\"')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/&/g, '&');\n};\n\nvar rgxFindMatchPos = function (str, left, right, flags) {\n 'use strict';\n var f = flags || '',\n g = f.indexOf('g') > -1,\n x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),\n l = new RegExp(left, f.replace(/g/g, '')),\n pos = [],\n t, s, m, start, end;\n\n do {\n t = 0;\n while ((m = x.exec(str))) {\n if (l.test(m[0])) {\n if (!(t++)) {\n s = x.lastIndex;\n start = s - m[0].length;\n }\n } else if (t) {\n if (!--t) {\n end = m.index + m[0].length;\n var obj = {\n left: {start: start, end: s},\n match: {start: s, end: m.index},\n right: {start: m.index, end: end},\n wholeMatch: {start: start, end: end}\n };\n pos.push(obj);\n if (!g) {\n return pos;\n }\n }\n }\n }\n } while (t && (x.lastIndex = s));\n\n return pos;\n};\n\n/**\n * matchRecursiveRegExp\n *\n * (c) 2007 Steven Levithan \n * MIT License\n *\n * Accepts a string to search, a left and right format delimiter\n * as regex patterns, and optional regex flags. Returns an array\n * of matches, allowing nested instances of left/right delimiters.\n * Use the \"g\" flag to return all matches, otherwise only the\n * first is returned. Be careful to ensure that the left and\n * right format delimiters produce mutually exclusive matches.\n * Backreferences are not supported within the right delimiter\n * due to how it is internally combined with the left delimiter.\n * When matching strings whose format delimiters are unbalanced\n * to the left or right, the output is intentionally as a\n * conventional regex library with recursion support would\n * produce, e.g. \"<\" and \">\" both produce [\"x\"] when using\n * \"<\" and \">\" as the delimiters (both strings contain a single,\n * balanced instance of \"\").\n *\n * examples:\n * matchRecursiveRegExp(\"test\", \"\\\\(\", \"\\\\)\")\n * returns: []\n * matchRecursiveRegExp(\">>t<>\", \"<\", \">\", \"g\")\n * returns: [\"t<>\", \"\"]\n * matchRecursiveRegExp(\"
    test
    \", \"]*>\", \"\", \"gi\")\n * returns: [\"test\"]\n */\nshowdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {\n 'use strict';\n\n var matchPos = rgxFindMatchPos (str, left, right, flags),\n results = [];\n\n for (var i = 0; i < matchPos.length; ++i) {\n results.push([\n str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),\n str.slice(matchPos[i].match.start, matchPos[i].match.end),\n str.slice(matchPos[i].left.start, matchPos[i].left.end),\n str.slice(matchPos[i].right.start, matchPos[i].right.end)\n ]);\n }\n return results;\n};\n\n/**\n *\n * @param {string} str\n * @param {string|function} replacement\n * @param {string} left\n * @param {string} right\n * @param {string} flags\n * @returns {string}\n */\nshowdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {\n 'use strict';\n\n if (!showdown.helper.isFunction(replacement)) {\n var repStr = replacement;\n replacement = function () {\n return repStr;\n };\n }\n\n var matchPos = rgxFindMatchPos(str, left, right, flags),\n finalStr = str,\n lng = matchPos.length;\n\n if (lng > 0) {\n var bits = [];\n if (matchPos[0].wholeMatch.start !== 0) {\n bits.push(str.slice(0, matchPos[0].wholeMatch.start));\n }\n for (var i = 0; i < lng; ++i) {\n bits.push(\n replacement(\n str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),\n str.slice(matchPos[i].match.start, matchPos[i].match.end),\n str.slice(matchPos[i].left.start, matchPos[i].left.end),\n str.slice(matchPos[i].right.start, matchPos[i].right.end)\n )\n );\n if (i < lng - 1) {\n bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));\n }\n }\n if (matchPos[lng - 1].wholeMatch.end < str.length) {\n bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));\n }\n finalStr = bits.join('');\n }\n return finalStr;\n};\n\n/**\n * Returns the index within the passed String object of the first occurrence of the specified regex,\n * starting the search at fromIndex. Returns -1 if the value is not found.\n *\n * @param {string} str string to search\n * @param {RegExp} regex Regular expression to search\n * @param {int} [fromIndex = 0] Index to start the search\n * @returns {Number}\n * @throws InvalidArgumentError\n */\nshowdown.helper.regexIndexOf = function (str, regex, fromIndex) {\n 'use strict';\n if (!showdown.helper.isString(str)) {\n throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';\n }\n if (regex instanceof RegExp === false) {\n throw 'InvalidArgumentError: second parameter of showdown.helper.regexIndexOf function must be an instance of RegExp';\n }\n var indexOf = str.substring(fromIndex || 0).search(regex);\n return (indexOf >= 0) ? (indexOf + (fromIndex || 0)) : indexOf;\n};\n\n/**\n * Splits the passed string object at the defined index, and returns an array composed of the two substrings\n * @param {string} str string to split\n * @param {int} index index to split string at\n * @returns {[string,string]}\n * @throws InvalidArgumentError\n */\nshowdown.helper.splitAtIndex = function (str, index) {\n 'use strict';\n if (!showdown.helper.isString(str)) {\n throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';\n }\n return [str.substring(0, index), str.substring(index)];\n};\n\n/**\n * Obfuscate an e-mail address through the use of Character Entities,\n * transforming ASCII characters into their equivalent decimal or hex entities.\n *\n * Since it has a random component, subsequent calls to this function produce different results\n *\n * @param {string} mail\n * @returns {string}\n */\nshowdown.helper.encodeEmailAddress = function (mail) {\n 'use strict';\n var encode = [\n function (ch) {\n return '&#' + ch.charCodeAt(0) + ';';\n },\n function (ch) {\n return '&#x' + ch.charCodeAt(0).toString(16) + ';';\n },\n function (ch) {\n return ch;\n }\n ];\n\n mail = mail.replace(/./g, function (ch) {\n if (ch === '@') {\n // this *must* be encoded. I insist.\n ch = encode[Math.floor(Math.random() * 2)](ch);\n } else {\n var r = Math.random();\n // roughly 10% raw, 45% hex, 45% dec\n ch = (\n r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)\n );\n }\n return ch;\n });\n\n return mail;\n};\n\n/**\n *\n * @param str\n * @param targetLength\n * @param padString\n * @returns {string}\n */\nshowdown.helper.padEnd = function padEnd (str, targetLength, padString) {\n 'use strict';\n /*jshint bitwise: false*/\n // eslint-disable-next-line space-infix-ops\n targetLength = targetLength>>0; //floor if number or convert non-number to 0;\n /*jshint bitwise: true*/\n padString = String(padString || ' ');\n if (str.length > targetLength) {\n return String(str);\n } else {\n targetLength = targetLength - str.length;\n if (targetLength > padString.length) {\n padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed\n }\n return String(str) + padString.slice(0,targetLength);\n }\n};\n\n/**\n * POLYFILLS\n */\n// use this instead of builtin is undefined for IE8 compatibility\nif (typeof (console) === 'undefined') {\n console = {\n warn: function (msg) {\n 'use strict';\n alert(msg);\n },\n log: function (msg) {\n 'use strict';\n alert(msg);\n },\n error: function (msg) {\n 'use strict';\n throw msg;\n }\n };\n}\n\n/**\n * Common regexes.\n * We declare some common regexes to improve performance\n */\nshowdown.helper.regexes = {\n asteriskDashAndColon: /([*_:~])/g\n};\n\n/**\n * EMOJIS LIST\n */\nshowdown.helper.emojis = {\n '+1':'\\ud83d\\udc4d',\n '-1':'\\ud83d\\udc4e',\n '100':'\\ud83d\\udcaf',\n '1234':'\\ud83d\\udd22',\n '1st_place_medal':'\\ud83e\\udd47',\n '2nd_place_medal':'\\ud83e\\udd48',\n '3rd_place_medal':'\\ud83e\\udd49',\n '8ball':'\\ud83c\\udfb1',\n 'a':'\\ud83c\\udd70\\ufe0f',\n 'ab':'\\ud83c\\udd8e',\n 'abc':'\\ud83d\\udd24',\n 'abcd':'\\ud83d\\udd21',\n 'accept':'\\ud83c\\ude51',\n 'aerial_tramway':'\\ud83d\\udea1',\n 'airplane':'\\u2708\\ufe0f',\n 'alarm_clock':'\\u23f0',\n 'alembic':'\\u2697\\ufe0f',\n 'alien':'\\ud83d\\udc7d',\n 'ambulance':'\\ud83d\\ude91',\n 'amphora':'\\ud83c\\udffa',\n 'anchor':'\\u2693\\ufe0f',\n 'angel':'\\ud83d\\udc7c',\n 'anger':'\\ud83d\\udca2',\n 'angry':'\\ud83d\\ude20',\n 'anguished':'\\ud83d\\ude27',\n 'ant':'\\ud83d\\udc1c',\n 'apple':'\\ud83c\\udf4e',\n 'aquarius':'\\u2652\\ufe0f',\n 'aries':'\\u2648\\ufe0f',\n 'arrow_backward':'\\u25c0\\ufe0f',\n 'arrow_double_down':'\\u23ec',\n 'arrow_double_up':'\\u23eb',\n 'arrow_down':'\\u2b07\\ufe0f',\n 'arrow_down_small':'\\ud83d\\udd3d',\n 'arrow_forward':'\\u25b6\\ufe0f',\n 'arrow_heading_down':'\\u2935\\ufe0f',\n 'arrow_heading_up':'\\u2934\\ufe0f',\n 'arrow_left':'\\u2b05\\ufe0f',\n 'arrow_lower_left':'\\u2199\\ufe0f',\n 'arrow_lower_right':'\\u2198\\ufe0f',\n 'arrow_right':'\\u27a1\\ufe0f',\n 'arrow_right_hook':'\\u21aa\\ufe0f',\n 'arrow_up':'\\u2b06\\ufe0f',\n 'arrow_up_down':'\\u2195\\ufe0f',\n 'arrow_up_small':'\\ud83d\\udd3c',\n 'arrow_upper_left':'\\u2196\\ufe0f',\n 'arrow_upper_right':'\\u2197\\ufe0f',\n 'arrows_clockwise':'\\ud83d\\udd03',\n 'arrows_counterclockwise':'\\ud83d\\udd04',\n 'art':'\\ud83c\\udfa8',\n 'articulated_lorry':'\\ud83d\\ude9b',\n 'artificial_satellite':'\\ud83d\\udef0',\n 'astonished':'\\ud83d\\ude32',\n 'athletic_shoe':'\\ud83d\\udc5f',\n 'atm':'\\ud83c\\udfe7',\n 'atom_symbol':'\\u269b\\ufe0f',\n 'avocado':'\\ud83e\\udd51',\n 'b':'\\ud83c\\udd71\\ufe0f',\n 'baby':'\\ud83d\\udc76',\n 'baby_bottle':'\\ud83c\\udf7c',\n 'baby_chick':'\\ud83d\\udc24',\n 'baby_symbol':'\\ud83d\\udebc',\n 'back':'\\ud83d\\udd19',\n 'bacon':'\\ud83e\\udd53',\n 'badminton':'\\ud83c\\udff8',\n 'baggage_claim':'\\ud83d\\udec4',\n 'baguette_bread':'\\ud83e\\udd56',\n 'balance_scale':'\\u2696\\ufe0f',\n 'balloon':'\\ud83c\\udf88',\n 'ballot_box':'\\ud83d\\uddf3',\n 'ballot_box_with_check':'\\u2611\\ufe0f',\n 'bamboo':'\\ud83c\\udf8d',\n 'banana':'\\ud83c\\udf4c',\n 'bangbang':'\\u203c\\ufe0f',\n 'bank':'\\ud83c\\udfe6',\n 'bar_chart':'\\ud83d\\udcca',\n 'barber':'\\ud83d\\udc88',\n 'baseball':'\\u26be\\ufe0f',\n 'basketball':'\\ud83c\\udfc0',\n 'basketball_man':'\\u26f9\\ufe0f',\n 'basketball_woman':'\\u26f9\\ufe0f‍\\u2640\\ufe0f',\n 'bat':'\\ud83e\\udd87',\n 'bath':'\\ud83d\\udec0',\n 'bathtub':'\\ud83d\\udec1',\n 'battery':'\\ud83d\\udd0b',\n 'beach_umbrella':'\\ud83c\\udfd6',\n 'bear':'\\ud83d\\udc3b',\n 'bed':'\\ud83d\\udecf',\n 'bee':'\\ud83d\\udc1d',\n 'beer':'\\ud83c\\udf7a',\n 'beers':'\\ud83c\\udf7b',\n 'beetle':'\\ud83d\\udc1e',\n 'beginner':'\\ud83d\\udd30',\n 'bell':'\\ud83d\\udd14',\n 'bellhop_bell':'\\ud83d\\udece',\n 'bento':'\\ud83c\\udf71',\n 'biking_man':'\\ud83d\\udeb4',\n 'bike':'\\ud83d\\udeb2',\n 'biking_woman':'\\ud83d\\udeb4‍\\u2640\\ufe0f',\n 'bikini':'\\ud83d\\udc59',\n 'biohazard':'\\u2623\\ufe0f',\n 'bird':'\\ud83d\\udc26',\n 'birthday':'\\ud83c\\udf82',\n 'black_circle':'\\u26ab\\ufe0f',\n 'black_flag':'\\ud83c\\udff4',\n 'black_heart':'\\ud83d\\udda4',\n 'black_joker':'\\ud83c\\udccf',\n 'black_large_square':'\\u2b1b\\ufe0f',\n 'black_medium_small_square':'\\u25fe\\ufe0f',\n 'black_medium_square':'\\u25fc\\ufe0f',\n 'black_nib':'\\u2712\\ufe0f',\n 'black_small_square':'\\u25aa\\ufe0f',\n 'black_square_button':'\\ud83d\\udd32',\n 'blonde_man':'\\ud83d\\udc71',\n 'blonde_woman':'\\ud83d\\udc71‍\\u2640\\ufe0f',\n 'blossom':'\\ud83c\\udf3c',\n 'blowfish':'\\ud83d\\udc21',\n 'blue_book':'\\ud83d\\udcd8',\n 'blue_car':'\\ud83d\\ude99',\n 'blue_heart':'\\ud83d\\udc99',\n 'blush':'\\ud83d\\ude0a',\n 'boar':'\\ud83d\\udc17',\n 'boat':'\\u26f5\\ufe0f',\n 'bomb':'\\ud83d\\udca3',\n 'book':'\\ud83d\\udcd6',\n 'bookmark':'\\ud83d\\udd16',\n 'bookmark_tabs':'\\ud83d\\udcd1',\n 'books':'\\ud83d\\udcda',\n 'boom':'\\ud83d\\udca5',\n 'boot':'\\ud83d\\udc62',\n 'bouquet':'\\ud83d\\udc90',\n 'bowing_man':'\\ud83d\\ude47',\n 'bow_and_arrow':'\\ud83c\\udff9',\n 'bowing_woman':'\\ud83d\\ude47‍\\u2640\\ufe0f',\n 'bowling':'\\ud83c\\udfb3',\n 'boxing_glove':'\\ud83e\\udd4a',\n 'boy':'\\ud83d\\udc66',\n 'bread':'\\ud83c\\udf5e',\n 'bride_with_veil':'\\ud83d\\udc70',\n 'bridge_at_night':'\\ud83c\\udf09',\n 'briefcase':'\\ud83d\\udcbc',\n 'broken_heart':'\\ud83d\\udc94',\n 'bug':'\\ud83d\\udc1b',\n 'building_construction':'\\ud83c\\udfd7',\n 'bulb':'\\ud83d\\udca1',\n 'bullettrain_front':'\\ud83d\\ude85',\n 'bullettrain_side':'\\ud83d\\ude84',\n 'burrito':'\\ud83c\\udf2f',\n 'bus':'\\ud83d\\ude8c',\n 'business_suit_levitating':'\\ud83d\\udd74',\n 'busstop':'\\ud83d\\ude8f',\n 'bust_in_silhouette':'\\ud83d\\udc64',\n 'busts_in_silhouette':'\\ud83d\\udc65',\n 'butterfly':'\\ud83e\\udd8b',\n 'cactus':'\\ud83c\\udf35',\n 'cake':'\\ud83c\\udf70',\n 'calendar':'\\ud83d\\udcc6',\n 'call_me_hand':'\\ud83e\\udd19',\n 'calling':'\\ud83d\\udcf2',\n 'camel':'\\ud83d\\udc2b',\n 'camera':'\\ud83d\\udcf7',\n 'camera_flash':'\\ud83d\\udcf8',\n 'camping':'\\ud83c\\udfd5',\n 'cancer':'\\u264b\\ufe0f',\n 'candle':'\\ud83d\\udd6f',\n 'candy':'\\ud83c\\udf6c',\n 'canoe':'\\ud83d\\udef6',\n 'capital_abcd':'\\ud83d\\udd20',\n 'capricorn':'\\u2651\\ufe0f',\n 'car':'\\ud83d\\ude97',\n 'card_file_box':'\\ud83d\\uddc3',\n 'card_index':'\\ud83d\\udcc7',\n 'card_index_dividers':'\\ud83d\\uddc2',\n 'carousel_horse':'\\ud83c\\udfa0',\n 'carrot':'\\ud83e\\udd55',\n 'cat':'\\ud83d\\udc31',\n 'cat2':'\\ud83d\\udc08',\n 'cd':'\\ud83d\\udcbf',\n 'chains':'\\u26d3',\n 'champagne':'\\ud83c\\udf7e',\n 'chart':'\\ud83d\\udcb9',\n 'chart_with_downwards_trend':'\\ud83d\\udcc9',\n 'chart_with_upwards_trend':'\\ud83d\\udcc8',\n 'checkered_flag':'\\ud83c\\udfc1',\n 'cheese':'\\ud83e\\uddc0',\n 'cherries':'\\ud83c\\udf52',\n 'cherry_blossom':'\\ud83c\\udf38',\n 'chestnut':'\\ud83c\\udf30',\n 'chicken':'\\ud83d\\udc14',\n 'children_crossing':'\\ud83d\\udeb8',\n 'chipmunk':'\\ud83d\\udc3f',\n 'chocolate_bar':'\\ud83c\\udf6b',\n 'christmas_tree':'\\ud83c\\udf84',\n 'church':'\\u26ea\\ufe0f',\n 'cinema':'\\ud83c\\udfa6',\n 'circus_tent':'\\ud83c\\udfaa',\n 'city_sunrise':'\\ud83c\\udf07',\n 'city_sunset':'\\ud83c\\udf06',\n 'cityscape':'\\ud83c\\udfd9',\n 'cl':'\\ud83c\\udd91',\n 'clamp':'\\ud83d\\udddc',\n 'clap':'\\ud83d\\udc4f',\n 'clapper':'\\ud83c\\udfac',\n 'classical_building':'\\ud83c\\udfdb',\n 'clinking_glasses':'\\ud83e\\udd42',\n 'clipboard':'\\ud83d\\udccb',\n 'clock1':'\\ud83d\\udd50',\n 'clock10':'\\ud83d\\udd59',\n 'clock1030':'\\ud83d\\udd65',\n 'clock11':'\\ud83d\\udd5a',\n 'clock1130':'\\ud83d\\udd66',\n 'clock12':'\\ud83d\\udd5b',\n 'clock1230':'\\ud83d\\udd67',\n 'clock130':'\\ud83d\\udd5c',\n 'clock2':'\\ud83d\\udd51',\n 'clock230':'\\ud83d\\udd5d',\n 'clock3':'\\ud83d\\udd52',\n 'clock330':'\\ud83d\\udd5e',\n 'clock4':'\\ud83d\\udd53',\n 'clock430':'\\ud83d\\udd5f',\n 'clock5':'\\ud83d\\udd54',\n 'clock530':'\\ud83d\\udd60',\n 'clock6':'\\ud83d\\udd55',\n 'clock630':'\\ud83d\\udd61',\n 'clock7':'\\ud83d\\udd56',\n 'clock730':'\\ud83d\\udd62',\n 'clock8':'\\ud83d\\udd57',\n 'clock830':'\\ud83d\\udd63',\n 'clock9':'\\ud83d\\udd58',\n 'clock930':'\\ud83d\\udd64',\n 'closed_book':'\\ud83d\\udcd5',\n 'closed_lock_with_key':'\\ud83d\\udd10',\n 'closed_umbrella':'\\ud83c\\udf02',\n 'cloud':'\\u2601\\ufe0f',\n 'cloud_with_lightning':'\\ud83c\\udf29',\n 'cloud_with_lightning_and_rain':'\\u26c8',\n 'cloud_with_rain':'\\ud83c\\udf27',\n 'cloud_with_snow':'\\ud83c\\udf28',\n 'clown_face':'\\ud83e\\udd21',\n 'clubs':'\\u2663\\ufe0f',\n 'cocktail':'\\ud83c\\udf78',\n 'coffee':'\\u2615\\ufe0f',\n 'coffin':'\\u26b0\\ufe0f',\n 'cold_sweat':'\\ud83d\\ude30',\n 'comet':'\\u2604\\ufe0f',\n 'computer':'\\ud83d\\udcbb',\n 'computer_mouse':'\\ud83d\\uddb1',\n 'confetti_ball':'\\ud83c\\udf8a',\n 'confounded':'\\ud83d\\ude16',\n 'confused':'\\ud83d\\ude15',\n 'congratulations':'\\u3297\\ufe0f',\n 'construction':'\\ud83d\\udea7',\n 'construction_worker_man':'\\ud83d\\udc77',\n 'construction_worker_woman':'\\ud83d\\udc77‍\\u2640\\ufe0f',\n 'control_knobs':'\\ud83c\\udf9b',\n 'convenience_store':'\\ud83c\\udfea',\n 'cookie':'\\ud83c\\udf6a',\n 'cool':'\\ud83c\\udd92',\n 'policeman':'\\ud83d\\udc6e',\n 'copyright':'\\u00a9\\ufe0f',\n 'corn':'\\ud83c\\udf3d',\n 'couch_and_lamp':'\\ud83d\\udecb',\n 'couple':'\\ud83d\\udc6b',\n 'couple_with_heart_woman_man':'\\ud83d\\udc91',\n 'couple_with_heart_man_man':'\\ud83d\\udc68‍\\u2764\\ufe0f‍\\ud83d\\udc68',\n 'couple_with_heart_woman_woman':'\\ud83d\\udc69‍\\u2764\\ufe0f‍\\ud83d\\udc69',\n 'couplekiss_man_man':'\\ud83d\\udc68‍\\u2764\\ufe0f‍\\ud83d\\udc8b‍\\ud83d\\udc68',\n 'couplekiss_man_woman':'\\ud83d\\udc8f',\n 'couplekiss_woman_woman':'\\ud83d\\udc69‍\\u2764\\ufe0f‍\\ud83d\\udc8b‍\\ud83d\\udc69',\n 'cow':'\\ud83d\\udc2e',\n 'cow2':'\\ud83d\\udc04',\n 'cowboy_hat_face':'\\ud83e\\udd20',\n 'crab':'\\ud83e\\udd80',\n 'crayon':'\\ud83d\\udd8d',\n 'credit_card':'\\ud83d\\udcb3',\n 'crescent_moon':'\\ud83c\\udf19',\n 'cricket':'\\ud83c\\udfcf',\n 'crocodile':'\\ud83d\\udc0a',\n 'croissant':'\\ud83e\\udd50',\n 'crossed_fingers':'\\ud83e\\udd1e',\n 'crossed_flags':'\\ud83c\\udf8c',\n 'crossed_swords':'\\u2694\\ufe0f',\n 'crown':'\\ud83d\\udc51',\n 'cry':'\\ud83d\\ude22',\n 'crying_cat_face':'\\ud83d\\ude3f',\n 'crystal_ball':'\\ud83d\\udd2e',\n 'cucumber':'\\ud83e\\udd52',\n 'cupid':'\\ud83d\\udc98',\n 'curly_loop':'\\u27b0',\n 'currency_exchange':'\\ud83d\\udcb1',\n 'curry':'\\ud83c\\udf5b',\n 'custard':'\\ud83c\\udf6e',\n 'customs':'\\ud83d\\udec3',\n 'cyclone':'\\ud83c\\udf00',\n 'dagger':'\\ud83d\\udde1',\n 'dancer':'\\ud83d\\udc83',\n 'dancing_women':'\\ud83d\\udc6f',\n 'dancing_men':'\\ud83d\\udc6f‍\\u2642\\ufe0f',\n 'dango':'\\ud83c\\udf61',\n 'dark_sunglasses':'\\ud83d\\udd76',\n 'dart':'\\ud83c\\udfaf',\n 'dash':'\\ud83d\\udca8',\n 'date':'\\ud83d\\udcc5',\n 'deciduous_tree':'\\ud83c\\udf33',\n 'deer':'\\ud83e\\udd8c',\n 'department_store':'\\ud83c\\udfec',\n 'derelict_house':'\\ud83c\\udfda',\n 'desert':'\\ud83c\\udfdc',\n 'desert_island':'\\ud83c\\udfdd',\n 'desktop_computer':'\\ud83d\\udda5',\n 'male_detective':'\\ud83d\\udd75\\ufe0f',\n 'diamond_shape_with_a_dot_inside':'\\ud83d\\udca0',\n 'diamonds':'\\u2666\\ufe0f',\n 'disappointed':'\\ud83d\\ude1e',\n 'disappointed_relieved':'\\ud83d\\ude25',\n 'dizzy':'\\ud83d\\udcab',\n 'dizzy_face':'\\ud83d\\ude35',\n 'do_not_litter':'\\ud83d\\udeaf',\n 'dog':'\\ud83d\\udc36',\n 'dog2':'\\ud83d\\udc15',\n 'dollar':'\\ud83d\\udcb5',\n 'dolls':'\\ud83c\\udf8e',\n 'dolphin':'\\ud83d\\udc2c',\n 'door':'\\ud83d\\udeaa',\n 'doughnut':'\\ud83c\\udf69',\n 'dove':'\\ud83d\\udd4a',\n 'dragon':'\\ud83d\\udc09',\n 'dragon_face':'\\ud83d\\udc32',\n 'dress':'\\ud83d\\udc57',\n 'dromedary_camel':'\\ud83d\\udc2a',\n 'drooling_face':'\\ud83e\\udd24',\n 'droplet':'\\ud83d\\udca7',\n 'drum':'\\ud83e\\udd41',\n 'duck':'\\ud83e\\udd86',\n 'dvd':'\\ud83d\\udcc0',\n 'e-mail':'\\ud83d\\udce7',\n 'eagle':'\\ud83e\\udd85',\n 'ear':'\\ud83d\\udc42',\n 'ear_of_rice':'\\ud83c\\udf3e',\n 'earth_africa':'\\ud83c\\udf0d',\n 'earth_americas':'\\ud83c\\udf0e',\n 'earth_asia':'\\ud83c\\udf0f',\n 'egg':'\\ud83e\\udd5a',\n 'eggplant':'\\ud83c\\udf46',\n 'eight_pointed_black_star':'\\u2734\\ufe0f',\n 'eight_spoked_asterisk':'\\u2733\\ufe0f',\n 'electric_plug':'\\ud83d\\udd0c',\n 'elephant':'\\ud83d\\udc18',\n 'email':'\\u2709\\ufe0f',\n 'end':'\\ud83d\\udd1a',\n 'envelope_with_arrow':'\\ud83d\\udce9',\n 'euro':'\\ud83d\\udcb6',\n 'european_castle':'\\ud83c\\udff0',\n 'european_post_office':'\\ud83c\\udfe4',\n 'evergreen_tree':'\\ud83c\\udf32',\n 'exclamation':'\\u2757\\ufe0f',\n 'expressionless':'\\ud83d\\ude11',\n 'eye':'\\ud83d\\udc41',\n 'eye_speech_bubble':'\\ud83d\\udc41‍\\ud83d\\udde8',\n 'eyeglasses':'\\ud83d\\udc53',\n 'eyes':'\\ud83d\\udc40',\n 'face_with_head_bandage':'\\ud83e\\udd15',\n 'face_with_thermometer':'\\ud83e\\udd12',\n 'fist_oncoming':'\\ud83d\\udc4a',\n 'factory':'\\ud83c\\udfed',\n 'fallen_leaf':'\\ud83c\\udf42',\n 'family_man_woman_boy':'\\ud83d\\udc6a',\n 'family_man_boy':'\\ud83d\\udc68‍\\ud83d\\udc66',\n 'family_man_boy_boy':'\\ud83d\\udc68‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_man_girl':'\\ud83d\\udc68‍\\ud83d\\udc67',\n 'family_man_girl_boy':'\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_man_girl_girl':'\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_man_man_boy':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc66',\n 'family_man_man_boy_boy':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_man_man_girl':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc67',\n 'family_man_man_girl_boy':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_man_man_girl_girl':'\\ud83d\\udc68‍\\ud83d\\udc68‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_man_woman_boy_boy':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_man_woman_girl':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc67',\n 'family_man_woman_girl_boy':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_man_woman_girl_girl':'\\ud83d\\udc68‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_woman_boy':'\\ud83d\\udc69‍\\ud83d\\udc66',\n 'family_woman_boy_boy':'\\ud83d\\udc69‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_woman_girl':'\\ud83d\\udc69‍\\ud83d\\udc67',\n 'family_woman_girl_boy':'\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_woman_girl_girl':'\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'family_woman_woman_boy':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc66',\n 'family_woman_woman_boy_boy':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc66‍\\ud83d\\udc66',\n 'family_woman_woman_girl':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc67',\n 'family_woman_woman_girl_boy':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc66',\n 'family_woman_woman_girl_girl':'\\ud83d\\udc69‍\\ud83d\\udc69‍\\ud83d\\udc67‍\\ud83d\\udc67',\n 'fast_forward':'\\u23e9',\n 'fax':'\\ud83d\\udce0',\n 'fearful':'\\ud83d\\ude28',\n 'feet':'\\ud83d\\udc3e',\n 'female_detective':'\\ud83d\\udd75\\ufe0f‍\\u2640\\ufe0f',\n 'ferris_wheel':'\\ud83c\\udfa1',\n 'ferry':'\\u26f4',\n 'field_hockey':'\\ud83c\\udfd1',\n 'file_cabinet':'\\ud83d\\uddc4',\n 'file_folder':'\\ud83d\\udcc1',\n 'film_projector':'\\ud83d\\udcfd',\n 'film_strip':'\\ud83c\\udf9e',\n 'fire':'\\ud83d\\udd25',\n 'fire_engine':'\\ud83d\\ude92',\n 'fireworks':'\\ud83c\\udf86',\n 'first_quarter_moon':'\\ud83c\\udf13',\n 'first_quarter_moon_with_face':'\\ud83c\\udf1b',\n 'fish':'\\ud83d\\udc1f',\n 'fish_cake':'\\ud83c\\udf65',\n 'fishing_pole_and_fish':'\\ud83c\\udfa3',\n 'fist_raised':'\\u270a',\n 'fist_left':'\\ud83e\\udd1b',\n 'fist_right':'\\ud83e\\udd1c',\n 'flags':'\\ud83c\\udf8f',\n 'flashlight':'\\ud83d\\udd26',\n 'fleur_de_lis':'\\u269c\\ufe0f',\n 'flight_arrival':'\\ud83d\\udeec',\n 'flight_departure':'\\ud83d\\udeeb',\n 'floppy_disk':'\\ud83d\\udcbe',\n 'flower_playing_cards':'\\ud83c\\udfb4',\n 'flushed':'\\ud83d\\ude33',\n 'fog':'\\ud83c\\udf2b',\n 'foggy':'\\ud83c\\udf01',\n 'football':'\\ud83c\\udfc8',\n 'footprints':'\\ud83d\\udc63',\n 'fork_and_knife':'\\ud83c\\udf74',\n 'fountain':'\\u26f2\\ufe0f',\n 'fountain_pen':'\\ud83d\\udd8b',\n 'four_leaf_clover':'\\ud83c\\udf40',\n 'fox_face':'\\ud83e\\udd8a',\n 'framed_picture':'\\ud83d\\uddbc',\n 'free':'\\ud83c\\udd93',\n 'fried_egg':'\\ud83c\\udf73',\n 'fried_shrimp':'\\ud83c\\udf64',\n 'fries':'\\ud83c\\udf5f',\n 'frog':'\\ud83d\\udc38',\n 'frowning':'\\ud83d\\ude26',\n 'frowning_face':'\\u2639\\ufe0f',\n 'frowning_man':'\\ud83d\\ude4d‍\\u2642\\ufe0f',\n 'frowning_woman':'\\ud83d\\ude4d',\n 'middle_finger':'\\ud83d\\udd95',\n 'fuelpump':'\\u26fd\\ufe0f',\n 'full_moon':'\\ud83c\\udf15',\n 'full_moon_with_face':'\\ud83c\\udf1d',\n 'funeral_urn':'\\u26b1\\ufe0f',\n 'game_die':'\\ud83c\\udfb2',\n 'gear':'\\u2699\\ufe0f',\n 'gem':'\\ud83d\\udc8e',\n 'gemini':'\\u264a\\ufe0f',\n 'ghost':'\\ud83d\\udc7b',\n 'gift':'\\ud83c\\udf81',\n 'gift_heart':'\\ud83d\\udc9d',\n 'girl':'\\ud83d\\udc67',\n 'globe_with_meridians':'\\ud83c\\udf10',\n 'goal_net':'\\ud83e\\udd45',\n 'goat':'\\ud83d\\udc10',\n 'golf':'\\u26f3\\ufe0f',\n 'golfing_man':'\\ud83c\\udfcc\\ufe0f',\n 'golfing_woman':'\\ud83c\\udfcc\\ufe0f‍\\u2640\\ufe0f',\n 'gorilla':'\\ud83e\\udd8d',\n 'grapes':'\\ud83c\\udf47',\n 'green_apple':'\\ud83c\\udf4f',\n 'green_book':'\\ud83d\\udcd7',\n 'green_heart':'\\ud83d\\udc9a',\n 'green_salad':'\\ud83e\\udd57',\n 'grey_exclamation':'\\u2755',\n 'grey_question':'\\u2754',\n 'grimacing':'\\ud83d\\ude2c',\n 'grin':'\\ud83d\\ude01',\n 'grinning':'\\ud83d\\ude00',\n 'guardsman':'\\ud83d\\udc82',\n 'guardswoman':'\\ud83d\\udc82‍\\u2640\\ufe0f',\n 'guitar':'\\ud83c\\udfb8',\n 'gun':'\\ud83d\\udd2b',\n 'haircut_woman':'\\ud83d\\udc87',\n 'haircut_man':'\\ud83d\\udc87‍\\u2642\\ufe0f',\n 'hamburger':'\\ud83c\\udf54',\n 'hammer':'\\ud83d\\udd28',\n 'hammer_and_pick':'\\u2692',\n 'hammer_and_wrench':'\\ud83d\\udee0',\n 'hamster':'\\ud83d\\udc39',\n 'hand':'\\u270b',\n 'handbag':'\\ud83d\\udc5c',\n 'handshake':'\\ud83e\\udd1d',\n 'hankey':'\\ud83d\\udca9',\n 'hatched_chick':'\\ud83d\\udc25',\n 'hatching_chick':'\\ud83d\\udc23',\n 'headphones':'\\ud83c\\udfa7',\n 'hear_no_evil':'\\ud83d\\ude49',\n 'heart':'\\u2764\\ufe0f',\n 'heart_decoration':'\\ud83d\\udc9f',\n 'heart_eyes':'\\ud83d\\ude0d',\n 'heart_eyes_cat':'\\ud83d\\ude3b',\n 'heartbeat':'\\ud83d\\udc93',\n 'heartpulse':'\\ud83d\\udc97',\n 'hearts':'\\u2665\\ufe0f',\n 'heavy_check_mark':'\\u2714\\ufe0f',\n 'heavy_division_sign':'\\u2797',\n 'heavy_dollar_sign':'\\ud83d\\udcb2',\n 'heavy_heart_exclamation':'\\u2763\\ufe0f',\n 'heavy_minus_sign':'\\u2796',\n 'heavy_multiplication_x':'\\u2716\\ufe0f',\n 'heavy_plus_sign':'\\u2795',\n 'helicopter':'\\ud83d\\ude81',\n 'herb':'\\ud83c\\udf3f',\n 'hibiscus':'\\ud83c\\udf3a',\n 'high_brightness':'\\ud83d\\udd06',\n 'high_heel':'\\ud83d\\udc60',\n 'hocho':'\\ud83d\\udd2a',\n 'hole':'\\ud83d\\udd73',\n 'honey_pot':'\\ud83c\\udf6f',\n 'horse':'\\ud83d\\udc34',\n 'horse_racing':'\\ud83c\\udfc7',\n 'hospital':'\\ud83c\\udfe5',\n 'hot_pepper':'\\ud83c\\udf36',\n 'hotdog':'\\ud83c\\udf2d',\n 'hotel':'\\ud83c\\udfe8',\n 'hotsprings':'\\u2668\\ufe0f',\n 'hourglass':'\\u231b\\ufe0f',\n 'hourglass_flowing_sand':'\\u23f3',\n 'house':'\\ud83c\\udfe0',\n 'house_with_garden':'\\ud83c\\udfe1',\n 'houses':'\\ud83c\\udfd8',\n 'hugs':'\\ud83e\\udd17',\n 'hushed':'\\ud83d\\ude2f',\n 'ice_cream':'\\ud83c\\udf68',\n 'ice_hockey':'\\ud83c\\udfd2',\n 'ice_skate':'\\u26f8',\n 'icecream':'\\ud83c\\udf66',\n 'id':'\\ud83c\\udd94',\n 'ideograph_advantage':'\\ud83c\\ude50',\n 'imp':'\\ud83d\\udc7f',\n 'inbox_tray':'\\ud83d\\udce5',\n 'incoming_envelope':'\\ud83d\\udce8',\n 'tipping_hand_woman':'\\ud83d\\udc81',\n 'information_source':'\\u2139\\ufe0f',\n 'innocent':'\\ud83d\\ude07',\n 'interrobang':'\\u2049\\ufe0f',\n 'iphone':'\\ud83d\\udcf1',\n 'izakaya_lantern':'\\ud83c\\udfee',\n 'jack_o_lantern':'\\ud83c\\udf83',\n 'japan':'\\ud83d\\uddfe',\n 'japanese_castle':'\\ud83c\\udfef',\n 'japanese_goblin':'\\ud83d\\udc7a',\n 'japanese_ogre':'\\ud83d\\udc79',\n 'jeans':'\\ud83d\\udc56',\n 'joy':'\\ud83d\\ude02',\n 'joy_cat':'\\ud83d\\ude39',\n 'joystick':'\\ud83d\\udd79',\n 'kaaba':'\\ud83d\\udd4b',\n 'key':'\\ud83d\\udd11',\n 'keyboard':'\\u2328\\ufe0f',\n 'keycap_ten':'\\ud83d\\udd1f',\n 'kick_scooter':'\\ud83d\\udef4',\n 'kimono':'\\ud83d\\udc58',\n 'kiss':'\\ud83d\\udc8b',\n 'kissing':'\\ud83d\\ude17',\n 'kissing_cat':'\\ud83d\\ude3d',\n 'kissing_closed_eyes':'\\ud83d\\ude1a',\n 'kissing_heart':'\\ud83d\\ude18',\n 'kissing_smiling_eyes':'\\ud83d\\ude19',\n 'kiwi_fruit':'\\ud83e\\udd5d',\n 'koala':'\\ud83d\\udc28',\n 'koko':'\\ud83c\\ude01',\n 'label':'\\ud83c\\udff7',\n 'large_blue_circle':'\\ud83d\\udd35',\n 'large_blue_diamond':'\\ud83d\\udd37',\n 'large_orange_diamond':'\\ud83d\\udd36',\n 'last_quarter_moon':'\\ud83c\\udf17',\n 'last_quarter_moon_with_face':'\\ud83c\\udf1c',\n 'latin_cross':'\\u271d\\ufe0f',\n 'laughing':'\\ud83d\\ude06',\n 'leaves':'\\ud83c\\udf43',\n 'ledger':'\\ud83d\\udcd2',\n 'left_luggage':'\\ud83d\\udec5',\n 'left_right_arrow':'\\u2194\\ufe0f',\n 'leftwards_arrow_with_hook':'\\u21a9\\ufe0f',\n 'lemon':'\\ud83c\\udf4b',\n 'leo':'\\u264c\\ufe0f',\n 'leopard':'\\ud83d\\udc06',\n 'level_slider':'\\ud83c\\udf9a',\n 'libra':'\\u264e\\ufe0f',\n 'light_rail':'\\ud83d\\ude88',\n 'link':'\\ud83d\\udd17',\n 'lion':'\\ud83e\\udd81',\n 'lips':'\\ud83d\\udc44',\n 'lipstick':'\\ud83d\\udc84',\n 'lizard':'\\ud83e\\udd8e',\n 'lock':'\\ud83d\\udd12',\n 'lock_with_ink_pen':'\\ud83d\\udd0f',\n 'lollipop':'\\ud83c\\udf6d',\n 'loop':'\\u27bf',\n 'loud_sound':'\\ud83d\\udd0a',\n 'loudspeaker':'\\ud83d\\udce2',\n 'love_hotel':'\\ud83c\\udfe9',\n 'love_letter':'\\ud83d\\udc8c',\n 'low_brightness':'\\ud83d\\udd05',\n 'lying_face':'\\ud83e\\udd25',\n 'm':'\\u24c2\\ufe0f',\n 'mag':'\\ud83d\\udd0d',\n 'mag_right':'\\ud83d\\udd0e',\n 'mahjong':'\\ud83c\\udc04\\ufe0f',\n 'mailbox':'\\ud83d\\udceb',\n 'mailbox_closed':'\\ud83d\\udcea',\n 'mailbox_with_mail':'\\ud83d\\udcec',\n 'mailbox_with_no_mail':'\\ud83d\\udced',\n 'man':'\\ud83d\\udc68',\n 'man_artist':'\\ud83d\\udc68‍\\ud83c\\udfa8',\n 'man_astronaut':'\\ud83d\\udc68‍\\ud83d\\ude80',\n 'man_cartwheeling':'\\ud83e\\udd38‍\\u2642\\ufe0f',\n 'man_cook':'\\ud83d\\udc68‍\\ud83c\\udf73',\n 'man_dancing':'\\ud83d\\udd7a',\n 'man_facepalming':'\\ud83e\\udd26‍\\u2642\\ufe0f',\n 'man_factory_worker':'\\ud83d\\udc68‍\\ud83c\\udfed',\n 'man_farmer':'\\ud83d\\udc68‍\\ud83c\\udf3e',\n 'man_firefighter':'\\ud83d\\udc68‍\\ud83d\\ude92',\n 'man_health_worker':'\\ud83d\\udc68‍\\u2695\\ufe0f',\n 'man_in_tuxedo':'\\ud83e\\udd35',\n 'man_judge':'\\ud83d\\udc68‍\\u2696\\ufe0f',\n 'man_juggling':'\\ud83e\\udd39‍\\u2642\\ufe0f',\n 'man_mechanic':'\\ud83d\\udc68‍\\ud83d\\udd27',\n 'man_office_worker':'\\ud83d\\udc68‍\\ud83d\\udcbc',\n 'man_pilot':'\\ud83d\\udc68‍\\u2708\\ufe0f',\n 'man_playing_handball':'\\ud83e\\udd3e‍\\u2642\\ufe0f',\n 'man_playing_water_polo':'\\ud83e\\udd3d‍\\u2642\\ufe0f',\n 'man_scientist':'\\ud83d\\udc68‍\\ud83d\\udd2c',\n 'man_shrugging':'\\ud83e\\udd37‍\\u2642\\ufe0f',\n 'man_singer':'\\ud83d\\udc68‍\\ud83c\\udfa4',\n 'man_student':'\\ud83d\\udc68‍\\ud83c\\udf93',\n 'man_teacher':'\\ud83d\\udc68‍\\ud83c\\udfeb',\n 'man_technologist':'\\ud83d\\udc68‍\\ud83d\\udcbb',\n 'man_with_gua_pi_mao':'\\ud83d\\udc72',\n 'man_with_turban':'\\ud83d\\udc73',\n 'tangerine':'\\ud83c\\udf4a',\n 'mans_shoe':'\\ud83d\\udc5e',\n 'mantelpiece_clock':'\\ud83d\\udd70',\n 'maple_leaf':'\\ud83c\\udf41',\n 'martial_arts_uniform':'\\ud83e\\udd4b',\n 'mask':'\\ud83d\\ude37',\n 'massage_woman':'\\ud83d\\udc86',\n 'massage_man':'\\ud83d\\udc86‍\\u2642\\ufe0f',\n 'meat_on_bone':'\\ud83c\\udf56',\n 'medal_military':'\\ud83c\\udf96',\n 'medal_sports':'\\ud83c\\udfc5',\n 'mega':'\\ud83d\\udce3',\n 'melon':'\\ud83c\\udf48',\n 'memo':'\\ud83d\\udcdd',\n 'men_wrestling':'\\ud83e\\udd3c‍\\u2642\\ufe0f',\n 'menorah':'\\ud83d\\udd4e',\n 'mens':'\\ud83d\\udeb9',\n 'metal':'\\ud83e\\udd18',\n 'metro':'\\ud83d\\ude87',\n 'microphone':'\\ud83c\\udfa4',\n 'microscope':'\\ud83d\\udd2c',\n 'milk_glass':'\\ud83e\\udd5b',\n 'milky_way':'\\ud83c\\udf0c',\n 'minibus':'\\ud83d\\ude90',\n 'minidisc':'\\ud83d\\udcbd',\n 'mobile_phone_off':'\\ud83d\\udcf4',\n 'money_mouth_face':'\\ud83e\\udd11',\n 'money_with_wings':'\\ud83d\\udcb8',\n 'moneybag':'\\ud83d\\udcb0',\n 'monkey':'\\ud83d\\udc12',\n 'monkey_face':'\\ud83d\\udc35',\n 'monorail':'\\ud83d\\ude9d',\n 'moon':'\\ud83c\\udf14',\n 'mortar_board':'\\ud83c\\udf93',\n 'mosque':'\\ud83d\\udd4c',\n 'motor_boat':'\\ud83d\\udee5',\n 'motor_scooter':'\\ud83d\\udef5',\n 'motorcycle':'\\ud83c\\udfcd',\n 'motorway':'\\ud83d\\udee3',\n 'mount_fuji':'\\ud83d\\uddfb',\n 'mountain':'\\u26f0',\n 'mountain_biking_man':'\\ud83d\\udeb5',\n 'mountain_biking_woman':'\\ud83d\\udeb5‍\\u2640\\ufe0f',\n 'mountain_cableway':'\\ud83d\\udea0',\n 'mountain_railway':'\\ud83d\\ude9e',\n 'mountain_snow':'\\ud83c\\udfd4',\n 'mouse':'\\ud83d\\udc2d',\n 'mouse2':'\\ud83d\\udc01',\n 'movie_camera':'\\ud83c\\udfa5',\n 'moyai':'\\ud83d\\uddff',\n 'mrs_claus':'\\ud83e\\udd36',\n 'muscle':'\\ud83d\\udcaa',\n 'mushroom':'\\ud83c\\udf44',\n 'musical_keyboard':'\\ud83c\\udfb9',\n 'musical_note':'\\ud83c\\udfb5',\n 'musical_score':'\\ud83c\\udfbc',\n 'mute':'\\ud83d\\udd07',\n 'nail_care':'\\ud83d\\udc85',\n 'name_badge':'\\ud83d\\udcdb',\n 'national_park':'\\ud83c\\udfde',\n 'nauseated_face':'\\ud83e\\udd22',\n 'necktie':'\\ud83d\\udc54',\n 'negative_squared_cross_mark':'\\u274e',\n 'nerd_face':'\\ud83e\\udd13',\n 'neutral_face':'\\ud83d\\ude10',\n 'new':'\\ud83c\\udd95',\n 'new_moon':'\\ud83c\\udf11',\n 'new_moon_with_face':'\\ud83c\\udf1a',\n 'newspaper':'\\ud83d\\udcf0',\n 'newspaper_roll':'\\ud83d\\uddde',\n 'next_track_button':'\\u23ed',\n 'ng':'\\ud83c\\udd96',\n 'no_good_man':'\\ud83d\\ude45‍\\u2642\\ufe0f',\n 'no_good_woman':'\\ud83d\\ude45',\n 'night_with_stars':'\\ud83c\\udf03',\n 'no_bell':'\\ud83d\\udd15',\n 'no_bicycles':'\\ud83d\\udeb3',\n 'no_entry':'\\u26d4\\ufe0f',\n 'no_entry_sign':'\\ud83d\\udeab',\n 'no_mobile_phones':'\\ud83d\\udcf5',\n 'no_mouth':'\\ud83d\\ude36',\n 'no_pedestrians':'\\ud83d\\udeb7',\n 'no_smoking':'\\ud83d\\udead',\n 'non-potable_water':'\\ud83d\\udeb1',\n 'nose':'\\ud83d\\udc43',\n 'notebook':'\\ud83d\\udcd3',\n 'notebook_with_decorative_cover':'\\ud83d\\udcd4',\n 'notes':'\\ud83c\\udfb6',\n 'nut_and_bolt':'\\ud83d\\udd29',\n 'o':'\\u2b55\\ufe0f',\n 'o2':'\\ud83c\\udd7e\\ufe0f',\n 'ocean':'\\ud83c\\udf0a',\n 'octopus':'\\ud83d\\udc19',\n 'oden':'\\ud83c\\udf62',\n 'office':'\\ud83c\\udfe2',\n 'oil_drum':'\\ud83d\\udee2',\n 'ok':'\\ud83c\\udd97',\n 'ok_hand':'\\ud83d\\udc4c',\n 'ok_man':'\\ud83d\\ude46‍\\u2642\\ufe0f',\n 'ok_woman':'\\ud83d\\ude46',\n 'old_key':'\\ud83d\\udddd',\n 'older_man':'\\ud83d\\udc74',\n 'older_woman':'\\ud83d\\udc75',\n 'om':'\\ud83d\\udd49',\n 'on':'\\ud83d\\udd1b',\n 'oncoming_automobile':'\\ud83d\\ude98',\n 'oncoming_bus':'\\ud83d\\ude8d',\n 'oncoming_police_car':'\\ud83d\\ude94',\n 'oncoming_taxi':'\\ud83d\\ude96',\n 'open_file_folder':'\\ud83d\\udcc2',\n 'open_hands':'\\ud83d\\udc50',\n 'open_mouth':'\\ud83d\\ude2e',\n 'open_umbrella':'\\u2602\\ufe0f',\n 'ophiuchus':'\\u26ce',\n 'orange_book':'\\ud83d\\udcd9',\n 'orthodox_cross':'\\u2626\\ufe0f',\n 'outbox_tray':'\\ud83d\\udce4',\n 'owl':'\\ud83e\\udd89',\n 'ox':'\\ud83d\\udc02',\n 'package':'\\ud83d\\udce6',\n 'page_facing_up':'\\ud83d\\udcc4',\n 'page_with_curl':'\\ud83d\\udcc3',\n 'pager':'\\ud83d\\udcdf',\n 'paintbrush':'\\ud83d\\udd8c',\n 'palm_tree':'\\ud83c\\udf34',\n 'pancakes':'\\ud83e\\udd5e',\n 'panda_face':'\\ud83d\\udc3c',\n 'paperclip':'\\ud83d\\udcce',\n 'paperclips':'\\ud83d\\udd87',\n 'parasol_on_ground':'\\u26f1',\n 'parking':'\\ud83c\\udd7f\\ufe0f',\n 'part_alternation_mark':'\\u303d\\ufe0f',\n 'partly_sunny':'\\u26c5\\ufe0f',\n 'passenger_ship':'\\ud83d\\udef3',\n 'passport_control':'\\ud83d\\udec2',\n 'pause_button':'\\u23f8',\n 'peace_symbol':'\\u262e\\ufe0f',\n 'peach':'\\ud83c\\udf51',\n 'peanuts':'\\ud83e\\udd5c',\n 'pear':'\\ud83c\\udf50',\n 'pen':'\\ud83d\\udd8a',\n 'pencil2':'\\u270f\\ufe0f',\n 'penguin':'\\ud83d\\udc27',\n 'pensive':'\\ud83d\\ude14',\n 'performing_arts':'\\ud83c\\udfad',\n 'persevere':'\\ud83d\\ude23',\n 'person_fencing':'\\ud83e\\udd3a',\n 'pouting_woman':'\\ud83d\\ude4e',\n 'phone':'\\u260e\\ufe0f',\n 'pick':'\\u26cf',\n 'pig':'\\ud83d\\udc37',\n 'pig2':'\\ud83d\\udc16',\n 'pig_nose':'\\ud83d\\udc3d',\n 'pill':'\\ud83d\\udc8a',\n 'pineapple':'\\ud83c\\udf4d',\n 'ping_pong':'\\ud83c\\udfd3',\n 'pisces':'\\u2653\\ufe0f',\n 'pizza':'\\ud83c\\udf55',\n 'place_of_worship':'\\ud83d\\uded0',\n 'plate_with_cutlery':'\\ud83c\\udf7d',\n 'play_or_pause_button':'\\u23ef',\n 'point_down':'\\ud83d\\udc47',\n 'point_left':'\\ud83d\\udc48',\n 'point_right':'\\ud83d\\udc49',\n 'point_up':'\\u261d\\ufe0f',\n 'point_up_2':'\\ud83d\\udc46',\n 'police_car':'\\ud83d\\ude93',\n 'policewoman':'\\ud83d\\udc6e‍\\u2640\\ufe0f',\n 'poodle':'\\ud83d\\udc29',\n 'popcorn':'\\ud83c\\udf7f',\n 'post_office':'\\ud83c\\udfe3',\n 'postal_horn':'\\ud83d\\udcef',\n 'postbox':'\\ud83d\\udcee',\n 'potable_water':'\\ud83d\\udeb0',\n 'potato':'\\ud83e\\udd54',\n 'pouch':'\\ud83d\\udc5d',\n 'poultry_leg':'\\ud83c\\udf57',\n 'pound':'\\ud83d\\udcb7',\n 'rage':'\\ud83d\\ude21',\n 'pouting_cat':'\\ud83d\\ude3e',\n 'pouting_man':'\\ud83d\\ude4e‍\\u2642\\ufe0f',\n 'pray':'\\ud83d\\ude4f',\n 'prayer_beads':'\\ud83d\\udcff',\n 'pregnant_woman':'\\ud83e\\udd30',\n 'previous_track_button':'\\u23ee',\n 'prince':'\\ud83e\\udd34',\n 'princess':'\\ud83d\\udc78',\n 'printer':'\\ud83d\\udda8',\n 'purple_heart':'\\ud83d\\udc9c',\n 'purse':'\\ud83d\\udc5b',\n 'pushpin':'\\ud83d\\udccc',\n 'put_litter_in_its_place':'\\ud83d\\udeae',\n 'question':'\\u2753',\n 'rabbit':'\\ud83d\\udc30',\n 'rabbit2':'\\ud83d\\udc07',\n 'racehorse':'\\ud83d\\udc0e',\n 'racing_car':'\\ud83c\\udfce',\n 'radio':'\\ud83d\\udcfb',\n 'radio_button':'\\ud83d\\udd18',\n 'radioactive':'\\u2622\\ufe0f',\n 'railway_car':'\\ud83d\\ude83',\n 'railway_track':'\\ud83d\\udee4',\n 'rainbow':'\\ud83c\\udf08',\n 'rainbow_flag':'\\ud83c\\udff3\\ufe0f‍\\ud83c\\udf08',\n 'raised_back_of_hand':'\\ud83e\\udd1a',\n 'raised_hand_with_fingers_splayed':'\\ud83d\\udd90',\n 'raised_hands':'\\ud83d\\ude4c',\n 'raising_hand_woman':'\\ud83d\\ude4b',\n 'raising_hand_man':'\\ud83d\\ude4b‍\\u2642\\ufe0f',\n 'ram':'\\ud83d\\udc0f',\n 'ramen':'\\ud83c\\udf5c',\n 'rat':'\\ud83d\\udc00',\n 'record_button':'\\u23fa',\n 'recycle':'\\u267b\\ufe0f',\n 'red_circle':'\\ud83d\\udd34',\n 'registered':'\\u00ae\\ufe0f',\n 'relaxed':'\\u263a\\ufe0f',\n 'relieved':'\\ud83d\\ude0c',\n 'reminder_ribbon':'\\ud83c\\udf97',\n 'repeat':'\\ud83d\\udd01',\n 'repeat_one':'\\ud83d\\udd02',\n 'rescue_worker_helmet':'\\u26d1',\n 'restroom':'\\ud83d\\udebb',\n 'revolving_hearts':'\\ud83d\\udc9e',\n 'rewind':'\\u23ea',\n 'rhinoceros':'\\ud83e\\udd8f',\n 'ribbon':'\\ud83c\\udf80',\n 'rice':'\\ud83c\\udf5a',\n 'rice_ball':'\\ud83c\\udf59',\n 'rice_cracker':'\\ud83c\\udf58',\n 'rice_scene':'\\ud83c\\udf91',\n 'right_anger_bubble':'\\ud83d\\uddef',\n 'ring':'\\ud83d\\udc8d',\n 'robot':'\\ud83e\\udd16',\n 'rocket':'\\ud83d\\ude80',\n 'rofl':'\\ud83e\\udd23',\n 'roll_eyes':'\\ud83d\\ude44',\n 'roller_coaster':'\\ud83c\\udfa2',\n 'rooster':'\\ud83d\\udc13',\n 'rose':'\\ud83c\\udf39',\n 'rosette':'\\ud83c\\udff5',\n 'rotating_light':'\\ud83d\\udea8',\n 'round_pushpin':'\\ud83d\\udccd',\n 'rowing_man':'\\ud83d\\udea3',\n 'rowing_woman':'\\ud83d\\udea3‍\\u2640\\ufe0f',\n 'rugby_football':'\\ud83c\\udfc9',\n 'running_man':'\\ud83c\\udfc3',\n 'running_shirt_with_sash':'\\ud83c\\udfbd',\n 'running_woman':'\\ud83c\\udfc3‍\\u2640\\ufe0f',\n 'sa':'\\ud83c\\ude02\\ufe0f',\n 'sagittarius':'\\u2650\\ufe0f',\n 'sake':'\\ud83c\\udf76',\n 'sandal':'\\ud83d\\udc61',\n 'santa':'\\ud83c\\udf85',\n 'satellite':'\\ud83d\\udce1',\n 'saxophone':'\\ud83c\\udfb7',\n 'school':'\\ud83c\\udfeb',\n 'school_satchel':'\\ud83c\\udf92',\n 'scissors':'\\u2702\\ufe0f',\n 'scorpion':'\\ud83e\\udd82',\n 'scorpius':'\\u264f\\ufe0f',\n 'scream':'\\ud83d\\ude31',\n 'scream_cat':'\\ud83d\\ude40',\n 'scroll':'\\ud83d\\udcdc',\n 'seat':'\\ud83d\\udcba',\n 'secret':'\\u3299\\ufe0f',\n 'see_no_evil':'\\ud83d\\ude48',\n 'seedling':'\\ud83c\\udf31',\n 'selfie':'\\ud83e\\udd33',\n 'shallow_pan_of_food':'\\ud83e\\udd58',\n 'shamrock':'\\u2618\\ufe0f',\n 'shark':'\\ud83e\\udd88',\n 'shaved_ice':'\\ud83c\\udf67',\n 'sheep':'\\ud83d\\udc11',\n 'shell':'\\ud83d\\udc1a',\n 'shield':'\\ud83d\\udee1',\n 'shinto_shrine':'\\u26e9',\n 'ship':'\\ud83d\\udea2',\n 'shirt':'\\ud83d\\udc55',\n 'shopping':'\\ud83d\\udecd',\n 'shopping_cart':'\\ud83d\\uded2',\n 'shower':'\\ud83d\\udebf',\n 'shrimp':'\\ud83e\\udd90',\n 'signal_strength':'\\ud83d\\udcf6',\n 'six_pointed_star':'\\ud83d\\udd2f',\n 'ski':'\\ud83c\\udfbf',\n 'skier':'\\u26f7',\n 'skull':'\\ud83d\\udc80',\n 'skull_and_crossbones':'\\u2620\\ufe0f',\n 'sleeping':'\\ud83d\\ude34',\n 'sleeping_bed':'\\ud83d\\udecc',\n 'sleepy':'\\ud83d\\ude2a',\n 'slightly_frowning_face':'\\ud83d\\ude41',\n 'slightly_smiling_face':'\\ud83d\\ude42',\n 'slot_machine':'\\ud83c\\udfb0',\n 'small_airplane':'\\ud83d\\udee9',\n 'small_blue_diamond':'\\ud83d\\udd39',\n 'small_orange_diamond':'\\ud83d\\udd38',\n 'small_red_triangle':'\\ud83d\\udd3a',\n 'small_red_triangle_down':'\\ud83d\\udd3b',\n 'smile':'\\ud83d\\ude04',\n 'smile_cat':'\\ud83d\\ude38',\n 'smiley':'\\ud83d\\ude03',\n 'smiley_cat':'\\ud83d\\ude3a',\n 'smiling_imp':'\\ud83d\\ude08',\n 'smirk':'\\ud83d\\ude0f',\n 'smirk_cat':'\\ud83d\\ude3c',\n 'smoking':'\\ud83d\\udeac',\n 'snail':'\\ud83d\\udc0c',\n 'snake':'\\ud83d\\udc0d',\n 'sneezing_face':'\\ud83e\\udd27',\n 'snowboarder':'\\ud83c\\udfc2',\n 'snowflake':'\\u2744\\ufe0f',\n 'snowman':'\\u26c4\\ufe0f',\n 'snowman_with_snow':'\\u2603\\ufe0f',\n 'sob':'\\ud83d\\ude2d',\n 'soccer':'\\u26bd\\ufe0f',\n 'soon':'\\ud83d\\udd1c',\n 'sos':'\\ud83c\\udd98',\n 'sound':'\\ud83d\\udd09',\n 'space_invader':'\\ud83d\\udc7e',\n 'spades':'\\u2660\\ufe0f',\n 'spaghetti':'\\ud83c\\udf5d',\n 'sparkle':'\\u2747\\ufe0f',\n 'sparkler':'\\ud83c\\udf87',\n 'sparkles':'\\u2728',\n 'sparkling_heart':'\\ud83d\\udc96',\n 'speak_no_evil':'\\ud83d\\ude4a',\n 'speaker':'\\ud83d\\udd08',\n 'speaking_head':'\\ud83d\\udde3',\n 'speech_balloon':'\\ud83d\\udcac',\n 'speedboat':'\\ud83d\\udea4',\n 'spider':'\\ud83d\\udd77',\n 'spider_web':'\\ud83d\\udd78',\n 'spiral_calendar':'\\ud83d\\uddd3',\n 'spiral_notepad':'\\ud83d\\uddd2',\n 'spoon':'\\ud83e\\udd44',\n 'squid':'\\ud83e\\udd91',\n 'stadium':'\\ud83c\\udfdf',\n 'star':'\\u2b50\\ufe0f',\n 'star2':'\\ud83c\\udf1f',\n 'star_and_crescent':'\\u262a\\ufe0f',\n 'star_of_david':'\\u2721\\ufe0f',\n 'stars':'\\ud83c\\udf20',\n 'station':'\\ud83d\\ude89',\n 'statue_of_liberty':'\\ud83d\\uddfd',\n 'steam_locomotive':'\\ud83d\\ude82',\n 'stew':'\\ud83c\\udf72',\n 'stop_button':'\\u23f9',\n 'stop_sign':'\\ud83d\\uded1',\n 'stopwatch':'\\u23f1',\n 'straight_ruler':'\\ud83d\\udccf',\n 'strawberry':'\\ud83c\\udf53',\n 'stuck_out_tongue':'\\ud83d\\ude1b',\n 'stuck_out_tongue_closed_eyes':'\\ud83d\\ude1d',\n 'stuck_out_tongue_winking_eye':'\\ud83d\\ude1c',\n 'studio_microphone':'\\ud83c\\udf99',\n 'stuffed_flatbread':'\\ud83e\\udd59',\n 'sun_behind_large_cloud':'\\ud83c\\udf25',\n 'sun_behind_rain_cloud':'\\ud83c\\udf26',\n 'sun_behind_small_cloud':'\\ud83c\\udf24',\n 'sun_with_face':'\\ud83c\\udf1e',\n 'sunflower':'\\ud83c\\udf3b',\n 'sunglasses':'\\ud83d\\ude0e',\n 'sunny':'\\u2600\\ufe0f',\n 'sunrise':'\\ud83c\\udf05',\n 'sunrise_over_mountains':'\\ud83c\\udf04',\n 'surfing_man':'\\ud83c\\udfc4',\n 'surfing_woman':'\\ud83c\\udfc4‍\\u2640\\ufe0f',\n 'sushi':'\\ud83c\\udf63',\n 'suspension_railway':'\\ud83d\\ude9f',\n 'sweat':'\\ud83d\\ude13',\n 'sweat_drops':'\\ud83d\\udca6',\n 'sweat_smile':'\\ud83d\\ude05',\n 'sweet_potato':'\\ud83c\\udf60',\n 'swimming_man':'\\ud83c\\udfca',\n 'swimming_woman':'\\ud83c\\udfca‍\\u2640\\ufe0f',\n 'symbols':'\\ud83d\\udd23',\n 'synagogue':'\\ud83d\\udd4d',\n 'syringe':'\\ud83d\\udc89',\n 'taco':'\\ud83c\\udf2e',\n 'tada':'\\ud83c\\udf89',\n 'tanabata_tree':'\\ud83c\\udf8b',\n 'taurus':'\\u2649\\ufe0f',\n 'taxi':'\\ud83d\\ude95',\n 'tea':'\\ud83c\\udf75',\n 'telephone_receiver':'\\ud83d\\udcde',\n 'telescope':'\\ud83d\\udd2d',\n 'tennis':'\\ud83c\\udfbe',\n 'tent':'\\u26fa\\ufe0f',\n 'thermometer':'\\ud83c\\udf21',\n 'thinking':'\\ud83e\\udd14',\n 'thought_balloon':'\\ud83d\\udcad',\n 'ticket':'\\ud83c\\udfab',\n 'tickets':'\\ud83c\\udf9f',\n 'tiger':'\\ud83d\\udc2f',\n 'tiger2':'\\ud83d\\udc05',\n 'timer_clock':'\\u23f2',\n 'tipping_hand_man':'\\ud83d\\udc81‍\\u2642\\ufe0f',\n 'tired_face':'\\ud83d\\ude2b',\n 'tm':'\\u2122\\ufe0f',\n 'toilet':'\\ud83d\\udebd',\n 'tokyo_tower':'\\ud83d\\uddfc',\n 'tomato':'\\ud83c\\udf45',\n 'tongue':'\\ud83d\\udc45',\n 'top':'\\ud83d\\udd1d',\n 'tophat':'\\ud83c\\udfa9',\n 'tornado':'\\ud83c\\udf2a',\n 'trackball':'\\ud83d\\uddb2',\n 'tractor':'\\ud83d\\ude9c',\n 'traffic_light':'\\ud83d\\udea5',\n 'train':'\\ud83d\\ude8b',\n 'train2':'\\ud83d\\ude86',\n 'tram':'\\ud83d\\ude8a',\n 'triangular_flag_on_post':'\\ud83d\\udea9',\n 'triangular_ruler':'\\ud83d\\udcd0',\n 'trident':'\\ud83d\\udd31',\n 'triumph':'\\ud83d\\ude24',\n 'trolleybus':'\\ud83d\\ude8e',\n 'trophy':'\\ud83c\\udfc6',\n 'tropical_drink':'\\ud83c\\udf79',\n 'tropical_fish':'\\ud83d\\udc20',\n 'truck':'\\ud83d\\ude9a',\n 'trumpet':'\\ud83c\\udfba',\n 'tulip':'\\ud83c\\udf37',\n 'tumbler_glass':'\\ud83e\\udd43',\n 'turkey':'\\ud83e\\udd83',\n 'turtle':'\\ud83d\\udc22',\n 'tv':'\\ud83d\\udcfa',\n 'twisted_rightwards_arrows':'\\ud83d\\udd00',\n 'two_hearts':'\\ud83d\\udc95',\n 'two_men_holding_hands':'\\ud83d\\udc6c',\n 'two_women_holding_hands':'\\ud83d\\udc6d',\n 'u5272':'\\ud83c\\ude39',\n 'u5408':'\\ud83c\\ude34',\n 'u55b6':'\\ud83c\\ude3a',\n 'u6307':'\\ud83c\\ude2f\\ufe0f',\n 'u6708':'\\ud83c\\ude37\\ufe0f',\n 'u6709':'\\ud83c\\ude36',\n 'u6e80':'\\ud83c\\ude35',\n 'u7121':'\\ud83c\\ude1a\\ufe0f',\n 'u7533':'\\ud83c\\ude38',\n 'u7981':'\\ud83c\\ude32',\n 'u7a7a':'\\ud83c\\ude33',\n 'umbrella':'\\u2614\\ufe0f',\n 'unamused':'\\ud83d\\ude12',\n 'underage':'\\ud83d\\udd1e',\n 'unicorn':'\\ud83e\\udd84',\n 'unlock':'\\ud83d\\udd13',\n 'up':'\\ud83c\\udd99',\n 'upside_down_face':'\\ud83d\\ude43',\n 'v':'\\u270c\\ufe0f',\n 'vertical_traffic_light':'\\ud83d\\udea6',\n 'vhs':'\\ud83d\\udcfc',\n 'vibration_mode':'\\ud83d\\udcf3',\n 'video_camera':'\\ud83d\\udcf9',\n 'video_game':'\\ud83c\\udfae',\n 'violin':'\\ud83c\\udfbb',\n 'virgo':'\\u264d\\ufe0f',\n 'volcano':'\\ud83c\\udf0b',\n 'volleyball':'\\ud83c\\udfd0',\n 'vs':'\\ud83c\\udd9a',\n 'vulcan_salute':'\\ud83d\\udd96',\n 'walking_man':'\\ud83d\\udeb6',\n 'walking_woman':'\\ud83d\\udeb6‍\\u2640\\ufe0f',\n 'waning_crescent_moon':'\\ud83c\\udf18',\n 'waning_gibbous_moon':'\\ud83c\\udf16',\n 'warning':'\\u26a0\\ufe0f',\n 'wastebasket':'\\ud83d\\uddd1',\n 'watch':'\\u231a\\ufe0f',\n 'water_buffalo':'\\ud83d\\udc03',\n 'watermelon':'\\ud83c\\udf49',\n 'wave':'\\ud83d\\udc4b',\n 'wavy_dash':'\\u3030\\ufe0f',\n 'waxing_crescent_moon':'\\ud83c\\udf12',\n 'wc':'\\ud83d\\udebe',\n 'weary':'\\ud83d\\ude29',\n 'wedding':'\\ud83d\\udc92',\n 'weight_lifting_man':'\\ud83c\\udfcb\\ufe0f',\n 'weight_lifting_woman':'\\ud83c\\udfcb\\ufe0f‍\\u2640\\ufe0f',\n 'whale':'\\ud83d\\udc33',\n 'whale2':'\\ud83d\\udc0b',\n 'wheel_of_dharma':'\\u2638\\ufe0f',\n 'wheelchair':'\\u267f\\ufe0f',\n 'white_check_mark':'\\u2705',\n 'white_circle':'\\u26aa\\ufe0f',\n 'white_flag':'\\ud83c\\udff3\\ufe0f',\n 'white_flower':'\\ud83d\\udcae',\n 'white_large_square':'\\u2b1c\\ufe0f',\n 'white_medium_small_square':'\\u25fd\\ufe0f',\n 'white_medium_square':'\\u25fb\\ufe0f',\n 'white_small_square':'\\u25ab\\ufe0f',\n 'white_square_button':'\\ud83d\\udd33',\n 'wilted_flower':'\\ud83e\\udd40',\n 'wind_chime':'\\ud83c\\udf90',\n 'wind_face':'\\ud83c\\udf2c',\n 'wine_glass':'\\ud83c\\udf77',\n 'wink':'\\ud83d\\ude09',\n 'wolf':'\\ud83d\\udc3a',\n 'woman':'\\ud83d\\udc69',\n 'woman_artist':'\\ud83d\\udc69‍\\ud83c\\udfa8',\n 'woman_astronaut':'\\ud83d\\udc69‍\\ud83d\\ude80',\n 'woman_cartwheeling':'\\ud83e\\udd38‍\\u2640\\ufe0f',\n 'woman_cook':'\\ud83d\\udc69‍\\ud83c\\udf73',\n 'woman_facepalming':'\\ud83e\\udd26‍\\u2640\\ufe0f',\n 'woman_factory_worker':'\\ud83d\\udc69‍\\ud83c\\udfed',\n 'woman_farmer':'\\ud83d\\udc69‍\\ud83c\\udf3e',\n 'woman_firefighter':'\\ud83d\\udc69‍\\ud83d\\ude92',\n 'woman_health_worker':'\\ud83d\\udc69‍\\u2695\\ufe0f',\n 'woman_judge':'\\ud83d\\udc69‍\\u2696\\ufe0f',\n 'woman_juggling':'\\ud83e\\udd39‍\\u2640\\ufe0f',\n 'woman_mechanic':'\\ud83d\\udc69‍\\ud83d\\udd27',\n 'woman_office_worker':'\\ud83d\\udc69‍\\ud83d\\udcbc',\n 'woman_pilot':'\\ud83d\\udc69‍\\u2708\\ufe0f',\n 'woman_playing_handball':'\\ud83e\\udd3e‍\\u2640\\ufe0f',\n 'woman_playing_water_polo':'\\ud83e\\udd3d‍\\u2640\\ufe0f',\n 'woman_scientist':'\\ud83d\\udc69‍\\ud83d\\udd2c',\n 'woman_shrugging':'\\ud83e\\udd37‍\\u2640\\ufe0f',\n 'woman_singer':'\\ud83d\\udc69‍\\ud83c\\udfa4',\n 'woman_student':'\\ud83d\\udc69‍\\ud83c\\udf93',\n 'woman_teacher':'\\ud83d\\udc69‍\\ud83c\\udfeb',\n 'woman_technologist':'\\ud83d\\udc69‍\\ud83d\\udcbb',\n 'woman_with_turban':'\\ud83d\\udc73‍\\u2640\\ufe0f',\n 'womans_clothes':'\\ud83d\\udc5a',\n 'womans_hat':'\\ud83d\\udc52',\n 'women_wrestling':'\\ud83e\\udd3c‍\\u2640\\ufe0f',\n 'womens':'\\ud83d\\udeba',\n 'world_map':'\\ud83d\\uddfa',\n 'worried':'\\ud83d\\ude1f',\n 'wrench':'\\ud83d\\udd27',\n 'writing_hand':'\\u270d\\ufe0f',\n 'x':'\\u274c',\n 'yellow_heart':'\\ud83d\\udc9b',\n 'yen':'\\ud83d\\udcb4',\n 'yin_yang':'\\u262f\\ufe0f',\n 'yum':'\\ud83d\\ude0b',\n 'zap':'\\u26a1\\ufe0f',\n 'zipper_mouth_face':'\\ud83e\\udd10',\n 'zzz':'\\ud83d\\udca4',\n\n /* special emojis :P */\n 'octocat': '\":octocat:\"',\n 'showdown': 'S'\n};\n", "/**\n * Created by Estevao on 31-05-2015.\n */\n\n/**\n * Showdown Converter class\n * @class\n * @param {object} [converterOptions]\n * @returns {Converter}\n */\nshowdown.Converter = function (converterOptions) {\n 'use strict';\n\n var\n /**\n * Options used by this converter\n * @private\n * @type {{}}\n */\n options = {},\n\n /**\n * Language extensions used by this converter\n * @private\n * @type {Array}\n */\n langExtensions = [],\n\n /**\n * Output modifiers extensions used by this converter\n * @private\n * @type {Array}\n */\n outputModifiers = [],\n\n /**\n * Event listeners\n * @private\n * @type {{}}\n */\n listeners = {},\n\n /**\n * The flavor set in this converter\n */\n setConvFlavor = setFlavor,\n\n /**\n * Metadata of the document\n * @type {{parsed: {}, raw: string, format: string}}\n */\n metadata = {\n parsed: {},\n raw: '',\n format: ''\n };\n\n _constructor();\n\n /**\n * Converter constructor\n * @private\n */\n function _constructor () {\n converterOptions = converterOptions || {};\n\n for (var gOpt in globalOptions) {\n if (globalOptions.hasOwnProperty(gOpt)) {\n options[gOpt] = globalOptions[gOpt];\n }\n }\n\n // Merge options\n if (typeof converterOptions === 'object') {\n for (var opt in converterOptions) {\n if (converterOptions.hasOwnProperty(opt)) {\n options[opt] = converterOptions[opt];\n }\n }\n } else {\n throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +\n ' was passed instead.');\n }\n\n if (options.extensions) {\n showdown.helper.forEach(options.extensions, _parseExtension);\n }\n }\n\n /**\n * Parse extension\n * @param {*} ext\n * @param {string} [name='']\n * @private\n */\n function _parseExtension (ext, name) {\n\n name = name || null;\n // If it's a string, the extension was previously loaded\n if (showdown.helper.isString(ext)) {\n ext = showdown.helper.stdExtName(ext);\n name = ext;\n\n // LEGACY_SUPPORT CODE\n if (showdown.extensions[ext]) {\n console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +\n 'Please inform the developer that the extension should be updated!');\n legacyExtensionLoading(showdown.extensions[ext], ext);\n return;\n // END LEGACY SUPPORT CODE\n\n } else if (!showdown.helper.isUndefined(extensions[ext])) {\n ext = extensions[ext];\n\n } else {\n throw Error('Extension \"' + ext + '\" could not be loaded. It was either not found or is not a valid extension.');\n }\n }\n\n if (typeof ext === 'function') {\n ext = ext();\n }\n\n if (!showdown.helper.isArray(ext)) {\n ext = [ext];\n }\n\n var validExt = validate(ext, name);\n if (!validExt.valid) {\n throw Error(validExt.error);\n }\n\n for (var i = 0; i < ext.length; ++i) {\n switch (ext[i].type) {\n\n case 'lang':\n langExtensions.push(ext[i]);\n break;\n\n case 'output':\n outputModifiers.push(ext[i]);\n break;\n }\n if (ext[i].hasOwnProperty('listeners')) {\n for (var ln in ext[i].listeners) {\n if (ext[i].listeners.hasOwnProperty(ln)) {\n listen(ln, ext[i].listeners[ln]);\n }\n }\n }\n }\n\n }\n\n /**\n * LEGACY_SUPPORT\n * @param {*} ext\n * @param {string} name\n */\n function legacyExtensionLoading (ext, name) {\n if (typeof ext === 'function') {\n ext = ext(new showdown.Converter());\n }\n if (!showdown.helper.isArray(ext)) {\n ext = [ext];\n }\n var valid = validate(ext, name);\n\n if (!valid.valid) {\n throw Error(valid.error);\n }\n\n for (var i = 0; i < ext.length; ++i) {\n switch (ext[i].type) {\n case 'lang':\n langExtensions.push(ext[i]);\n break;\n case 'output':\n outputModifiers.push(ext[i]);\n break;\n default:// should never reach here\n throw Error('Extension loader error: Type unrecognized!!!');\n }\n }\n }\n\n /**\n * Listen to an event\n * @param {string} name\n * @param {function} callback\n */\n function listen (name, callback) {\n if (!showdown.helper.isString(name)) {\n throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');\n }\n\n if (typeof callback !== 'function') {\n throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');\n }\n\n if (!listeners.hasOwnProperty(name)) {\n listeners[name] = [];\n }\n listeners[name].push(callback);\n }\n\n function rTrimInputText (text) {\n var rsp = text.match(/^\\s*/)[0].length,\n rgx = new RegExp('^\\\\s{0,' + rsp + '}', 'gm');\n return text.replace(rgx, '');\n }\n\n /**\n * Dispatch an event\n * @private\n * @param {string} evtName Event name\n * @param {string} text Text\n * @param {{}} options Converter Options\n * @param {{}} globals\n * @returns {string}\n */\n this._dispatch = function dispatch (evtName, text, options, globals) {\n if (listeners.hasOwnProperty(evtName)) {\n for (var ei = 0; ei < listeners[evtName].length; ++ei) {\n var nText = listeners[evtName][ei](evtName, text, this, options, globals);\n if (nText && typeof nText !== 'undefined') {\n text = nText;\n }\n }\n }\n return text;\n };\n\n /**\n * Listen to an event\n * @param {string} name\n * @param {function} callback\n * @returns {showdown.Converter}\n */\n this.listen = function (name, callback) {\n listen(name, callback);\n return this;\n };\n\n /**\n * Converts a markdown string into HTML\n * @param {string} text\n * @returns {*}\n */\n this.makeHtml = function (text) {\n //check if text is not falsy\n if (!text) {\n return text;\n }\n\n var globals = {\n gHtmlBlocks: [],\n gHtmlMdBlocks: [],\n gHtmlSpans: [],\n gUrls: {},\n gTitles: {},\n gDimensions: {},\n gListLevel: 0,\n hashLinkCounts: {},\n langExtensions: langExtensions,\n outputModifiers: outputModifiers,\n converter: this,\n ghCodeBlocks: [],\n metadata: {\n parsed: {},\n raw: '',\n format: ''\n }\n };\n\n // This lets us use ¨ trema as an escape char to avoid md5 hashes\n // The choice of character is arbitrary; anything that isn't\n // magic in Markdown will work.\n text = text.replace(/¨/g, '¨T');\n\n // Replace $ with ¨D\n // RegExp interprets $ as a special character\n // when it's in a replacement string\n text = text.replace(/\\$/g, '¨D');\n\n // Standardize line endings\n text = text.replace(/\\r\\n/g, '\\n'); // DOS to Unix\n text = text.replace(/\\r/g, '\\n'); // Mac to Unix\n\n // Stardardize line spaces\n text = text.replace(/\\u00A0/g, ' ');\n\n if (options.smartIndentationFix) {\n text = rTrimInputText(text);\n }\n\n // Make sure text begins and ends with a couple of newlines:\n text = '\\n\\n' + text + '\\n\\n';\n\n // detab\n text = showdown.subParser('detab')(text, options, globals);\n\n /**\n * Strip any lines consisting only of spaces and tabs.\n * This makes subsequent regexs easier to write, because we can\n * match consecutive blank lines with /\\n+/ instead of something\n * contorted like /[ \\t]*\\n+/\n */\n text = text.replace(/^[ \\t]+$/mg, '');\n\n //run languageExtensions\n showdown.helper.forEach(langExtensions, function (ext) {\n text = showdown.subParser('runExtension')(ext, text, options, globals);\n });\n\n // run the sub parsers\n text = showdown.subParser('metadata')(text, options, globals);\n text = showdown.subParser('hashPreCodeTags')(text, options, globals);\n text = showdown.subParser('githubCodeBlocks')(text, options, globals);\n text = showdown.subParser('hashHTMLBlocks')(text, options, globals);\n text = showdown.subParser('hashCodeTags')(text, options, globals);\n text = showdown.subParser('stripLinkDefinitions')(text, options, globals);\n text = showdown.subParser('blockGamut')(text, options, globals);\n text = showdown.subParser('unhashHTMLSpans')(text, options, globals);\n text = showdown.subParser('unescapeSpecialChars')(text, options, globals);\n\n // attacklab: Restore dollar signs\n text = text.replace(/¨D/g, '$$');\n\n // attacklab: Restore tremas\n text = text.replace(/¨T/g, '¨');\n\n // render a complete html document instead of a partial if the option is enabled\n text = showdown.subParser('completeHTMLDocument')(text, options, globals);\n\n // Run output modifiers\n showdown.helper.forEach(outputModifiers, function (ext) {\n text = showdown.subParser('runExtension')(ext, text, options, globals);\n });\n\n // update metadata\n metadata = globals.metadata;\n return text;\n };\n\n /**\n * Converts an HTML string into a markdown string\n * @param src\n * @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used.\n * @returns {string}\n */\n this.makeMarkdown = this.makeMd = function (src, HTMLParser) {\n\n // replace \\r\\n with \\n\n src = src.replace(/\\r\\n/g, '\\n');\n src = src.replace(/\\r/g, '\\n'); // old macs\n\n // due to an edge case, we need to find this: > <\n // to prevent removing of non silent white spaces\n // ex: this is sparta\n src = src.replace(/>[ \\t]+¨NBSP;<');\n\n if (!HTMLParser) {\n if (window && window.document) {\n HTMLParser = window.document;\n } else {\n throw new Error('HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM');\n }\n }\n\n var doc = HTMLParser.createElement('div');\n doc.innerHTML = src;\n\n var globals = {\n preList: substitutePreCodeTags(doc)\n };\n\n // remove all newlines and collapse spaces\n clean(doc);\n\n // some stuff, like accidental reference links must now be escaped\n // TODO\n // doc.innerHTML = doc.innerHTML.replace(/\\[[\\S\\t ]]/);\n\n var nodes = doc.childNodes,\n mdDoc = '';\n\n for (var i = 0; i < nodes.length; i++) {\n mdDoc += showdown.subParser('makeMarkdown.node')(nodes[i], globals);\n }\n\n function clean (node) {\n for (var n = 0; n < node.childNodes.length; ++n) {\n var child = node.childNodes[n];\n if (child.nodeType === 3) {\n if (!/\\S/.test(child.nodeValue) && !/^[ ]+$/.test(child.nodeValue)) {\n node.removeChild(child);\n --n;\n } else {\n child.nodeValue = child.nodeValue.split('\\n').join(' ');\n child.nodeValue = child.nodeValue.replace(/(\\s)+/g, '$1');\n }\n } else if (child.nodeType === 1) {\n clean(child);\n }\n }\n }\n\n // find all pre tags and replace contents with placeholder\n // we need this so that we can remove all indentation from html\n // to ease up parsing\n function substitutePreCodeTags (doc) {\n\n var pres = doc.querySelectorAll('pre'),\n presPH = [];\n\n for (var i = 0; i < pres.length; ++i) {\n\n if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {\n var content = pres[i].firstChild.innerHTML.trim(),\n language = pres[i].firstChild.getAttribute('data-language') || '';\n\n // if data-language attribute is not defined, then we look for class language-*\n if (language === '') {\n var classes = pres[i].firstChild.className.split(' ');\n for (var c = 0; c < classes.length; ++c) {\n var matches = classes[c].match(/^language-(.+)$/);\n if (matches !== null) {\n language = matches[1];\n break;\n }\n }\n }\n\n // unescape html entities in content\n content = showdown.helper.unescapeHTMLEntities(content);\n\n presPH.push(content);\n pres[i].outerHTML = '';\n } else {\n presPH.push(pres[i].innerHTML);\n pres[i].innerHTML = '';\n pres[i].setAttribute('prenum', i.toString());\n }\n }\n return presPH;\n }\n\n return mdDoc;\n };\n\n /**\n * Set an option of this Converter instance\n * @param {string} key\n * @param {*} value\n */\n this.setOption = function (key, value) {\n options[key] = value;\n };\n\n /**\n * Get the option of this Converter instance\n * @param {string} key\n * @returns {*}\n */\n this.getOption = function (key) {\n return options[key];\n };\n\n /**\n * Get the options of this Converter instance\n * @returns {{}}\n */\n this.getOptions = function () {\n return options;\n };\n\n /**\n * Add extension to THIS converter\n * @param {{}} extension\n * @param {string} [name=null]\n */\n this.addExtension = function (extension, name) {\n name = name || null;\n _parseExtension(extension, name);\n };\n\n /**\n * Use a global registered extension with THIS converter\n * @param {string} extensionName Name of the previously registered extension\n */\n this.useExtension = function (extensionName) {\n _parseExtension(extensionName);\n };\n\n /**\n * Set the flavor THIS converter should use\n * @param {string} name\n */\n this.setFlavor = function (name) {\n if (!flavor.hasOwnProperty(name)) {\n throw Error(name + ' flavor was not found');\n }\n var preset = flavor[name];\n setConvFlavor = name;\n for (var option in preset) {\n if (preset.hasOwnProperty(option)) {\n options[option] = preset[option];\n }\n }\n };\n\n /**\n * Get the currently set flavor of this converter\n * @returns {string}\n */\n this.getFlavor = function () {\n return setConvFlavor;\n };\n\n /**\n * Remove an extension from THIS converter.\n * Note: This is a costly operation. It's better to initialize a new converter\n * and specify the extensions you wish to use\n * @param {Array} extension\n */\n this.removeExtension = function (extension) {\n if (!showdown.helper.isArray(extension)) {\n extension = [extension];\n }\n for (var a = 0; a < extension.length; ++a) {\n var ext = extension[a];\n for (var i = 0; i < langExtensions.length; ++i) {\n if (langExtensions[i] === ext) {\n langExtensions.splice(i, 1);\n }\n }\n for (var ii = 0; ii < outputModifiers.length; ++ii) {\n if (outputModifiers[ii] === ext) {\n outputModifiers.splice(ii, 1);\n }\n }\n }\n };\n\n /**\n * Get all extension of THIS converter\n * @returns {{language: Array, output: Array}}\n */\n this.getAllExtensions = function () {\n return {\n language: langExtensions,\n output: outputModifiers\n };\n };\n\n /**\n * Get the metadata of the previously parsed document\n * @param raw\n * @returns {string|{}}\n */\n this.getMetadata = function (raw) {\n if (raw) {\n return metadata.raw;\n } else {\n return metadata.parsed;\n }\n };\n\n /**\n * Get the metadata format of the previously parsed document\n * @returns {string}\n */\n this.getMetadataFormat = function () {\n return metadata.format;\n };\n\n /**\n * Private: set a single key, value metadata pair\n * @param {string} key\n * @param {string} value\n */\n this._setMetadataPair = function (key, value) {\n metadata.parsed[key] = value;\n };\n\n /**\n * Private: set metadata format\n * @param {string} format\n */\n this._setMetadataFormat = function (format) {\n metadata.format = format;\n };\n\n /**\n * Private: set metadata raw text\n * @param {string} raw\n */\n this._setMetadataRaw = function (raw) {\n metadata.raw = raw;\n };\n};\n", "/**\n * Turn Markdown link shortcuts into XHTML
    tags.\n */\nshowdown.subParser('anchors', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('anchors.before', text, options, globals);\n\n var writeAnchorTag = function (wholeMatch, linkText, linkId, url, m5, m6, title) {\n if (showdown.helper.isUndefined(title)) {\n title = '';\n }\n linkId = linkId.toLowerCase();\n\n // Special case for explicit empty url\n if (wholeMatch.search(/\\(? ?(['\"].*['\"])?\\)$/m) > -1) {\n url = '';\n } else if (!url) {\n if (!linkId) {\n // lower-case and turn embedded newlines into spaces\n linkId = linkText.toLowerCase().replace(/ ?\\n/g, ' ');\n }\n url = '#' + linkId;\n\n if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {\n url = globals.gUrls[linkId];\n if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {\n title = globals.gTitles[linkId];\n }\n } else {\n return wholeMatch;\n }\n }\n\n //url = showdown.helper.escapeCharacters(url, '*_', false); // replaced line to improve performance\n url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n\n var result = '';\n\n return result;\n };\n\n // First, handle reference-style links: [link text] [id]\n text = text.replace(/\\[((?:\\[[^\\]]*]|[^\\[\\]])*)] ?(?:\\n *)?\\[(.*?)]()()()()/g, writeAnchorTag);\n\n // Next, inline-style links: [link text](url \"optional title\")\n // cases with crazy urls like ./image/cat1).png\n text = text.replace(/\\[((?:\\[[^\\]]*]|[^\\[\\]])*)]()[ \\t]*\\([ \\t]?<([^>]*)>(?:[ \\t]*(([\"'])([^\"]*?)\\5))?[ \\t]?\\)/g,\n writeAnchorTag);\n\n // normal cases\n text = text.replace(/\\[((?:\\[[^\\]]*]|[^\\[\\]])*)]()[ \\t]*\\([ \\t]??(?:[ \\t]*(([\"'])([^\"]*?)\\5))?[ \\t]?\\)/g,\n writeAnchorTag);\n\n // handle reference-style shortcuts: [link text]\n // These must come last in case you've also got [link test][1]\n // or [link test](/foo)\n text = text.replace(/\\[([^\\[\\]]+)]()()()()()/g, writeAnchorTag);\n\n // Lastly handle GithubMentions if option is enabled\n if (options.ghMentions) {\n text = text.replace(/(^|\\s)(\\\\)?(@([a-z\\d]+(?:[a-z\\d.-]+?[a-z\\d]+)*))/gmi, function (wm, st, escape, mentions, username) {\n if (escape === '\\\\') {\n return st + mentions;\n }\n\n //check if options.ghMentionsLink is a string\n if (!showdown.helper.isString(options.ghMentionsLink)) {\n throw new Error('ghMentionsLink option must be a string');\n }\n var lnk = options.ghMentionsLink.replace(/\\{u}/g, username),\n target = '';\n if (options.openLinksInNewWindow) {\n target = ' rel=\"noopener noreferrer\" target=\"¨E95Eblank\"';\n }\n return st + '' + mentions + '';\n });\n }\n\n text = globals.converter._dispatch('anchors.after', text, options, globals);\n return text;\n});\n", "// url allowed chars [a-z\\d_.~:/?#[]@!$&'()*+,;=-]\n\nvar simpleURLRegex = /([*~_]+|\\b)(((https?|ftp|dict):\\/\\/|www\\.)[^'\">\\s]+?\\.[^'\">\\s]+?)()(\\1)?(?=\\s|$)(?![\"<>])/gi,\n simpleURLRegex2 = /([*~_]+|\\b)(((https?|ftp|dict):\\/\\/|www\\.)[^'\">\\s]+\\.[^'\">\\s]+?)([.!?,()\\[\\]])?(\\1)?(?=\\s|$)(?![\"<>])/gi,\n delimUrlRegex = /()<(((https?|ftp|dict):\\/\\/|www\\.)[^'\">\\s]+)()>()/gi,\n simpleMailRegex = /(^|\\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)(?=$|\\s)/gmi,\n delimMailRegex = /<()(?:mailto:)?([-.\\w]+@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)>/gi,\n\n replaceLink = function (options) {\n 'use strict';\n return function (wm, leadingMagicChars, link, m2, m3, trailingPunctuation, trailingMagicChars) {\n link = link.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n var lnkTxt = link,\n append = '',\n target = '',\n lmc = leadingMagicChars || '',\n tmc = trailingMagicChars || '';\n if (/^www\\./i.test(link)) {\n link = link.replace(/^www\\./i, 'http://www.');\n }\n if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {\n append = trailingPunctuation;\n }\n if (options.openLinksInNewWindow) {\n target = ' rel=\"noopener noreferrer\" target=\"¨E95Eblank\"';\n }\n return lmc + '' + lnkTxt + '' + append + tmc;\n };\n },\n\n replaceMail = function (options, globals) {\n 'use strict';\n return function (wholeMatch, b, mail) {\n var href = 'mailto:';\n b = b || '';\n mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);\n if (options.encodeEmails) {\n href = showdown.helper.encodeEmailAddress(href + mail);\n mail = showdown.helper.encodeEmailAddress(mail);\n } else {\n href = href + mail;\n }\n return b + '' + mail + '';\n };\n };\n\nshowdown.subParser('autoLinks', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('autoLinks.before', text, options, globals);\n\n text = text.replace(delimUrlRegex, replaceLink(options));\n text = text.replace(delimMailRegex, replaceMail(options, globals));\n\n text = globals.converter._dispatch('autoLinks.after', text, options, globals);\n\n return text;\n});\n\nshowdown.subParser('simplifiedAutoLinks', function (text, options, globals) {\n 'use strict';\n\n if (!options.simplifiedAutoLink) {\n return text;\n }\n\n text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);\n\n if (options.excludeTrailingPunctuationFromURLs) {\n text = text.replace(simpleURLRegex2, replaceLink(options));\n } else {\n text = text.replace(simpleURLRegex, replaceLink(options));\n }\n text = text.replace(simpleMailRegex, replaceMail(options, globals));\n\n text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);\n\n return text;\n});\n", "/**\n * These are all the transformations that form block-level\n * tags like paragraphs, headers, and list items.\n */\nshowdown.subParser('blockGamut', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('blockGamut.before', text, options, globals);\n\n // we parse blockquotes first so that we can have headings and hrs\n // inside blockquotes\n text = showdown.subParser('blockQuotes')(text, options, globals);\n text = showdown.subParser('headers')(text, options, globals);\n\n // Do Horizontal Rules:\n text = showdown.subParser('horizontalRule')(text, options, globals);\n\n text = showdown.subParser('lists')(text, options, globals);\n text = showdown.subParser('codeBlocks')(text, options, globals);\n text = showdown.subParser('tables')(text, options, globals);\n\n // We already ran _HashHTMLBlocks() before, in Markdown(), but that\n // was to escape raw HTML in the original Markdown source. This time,\n // we're escaping the markup we've just created, so that we don't wrap\n //

    tags around block-level tags.\n text = showdown.subParser('hashHTMLBlocks')(text, options, globals);\n text = showdown.subParser('paragraphs')(text, options, globals);\n\n text = globals.converter._dispatch('blockGamut.after', text, options, globals);\n\n return text;\n});\n", "showdown.subParser('blockQuotes', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('blockQuotes.before', text, options, globals);\n\n // add a couple extra lines after the text and endtext mark\n text = text + '\\n\\n';\n\n var rgx = /(^ {0,3}>[ \\t]?.+\\n(.+\\n)*\\n*)+/gm;\n\n if (options.splitAdjacentBlockquotes) {\n rgx = /^ {0,3}>[\\s\\S]*?(?:\\n\\n)/gm;\n }\n\n text = text.replace(rgx, function (bq) {\n // attacklab: hack around Konqueror 3.5.4 bug:\n // \"----------bug\".replace(/^-/g,\"\") == \"bug\"\n bq = bq.replace(/^[ \\t]*>[ \\t]?/gm, ''); // trim one level of quoting\n\n // attacklab: clean up hack\n bq = bq.replace(/¨0/g, '');\n\n bq = bq.replace(/^[ \\t]+$/gm, ''); // trim whitespace-only lines\n bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);\n bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse\n\n bq = bq.replace(/(^|\\n)/g, '$1 ');\n // These leading spaces screw with

     content, so we need to fix that:\n    bq = bq.replace(/(\\s*
    [^\\r]+?<\\/pre>)/gm, function (wholeMatch, m1) {\n      var pre = m1;\n      // attacklab: hack around Konqueror 3.5.4 bug:\n      pre = pre.replace(/^  /mg, '¨0');\n      pre = pre.replace(/¨0/g, '');\n      return pre;\n    });\n\n    return showdown.subParser('hashBlock')('
    \\n' + bq + '\\n
    ', options, globals);\n });\n\n text = globals.converter._dispatch('blockQuotes.after', text, options, globals);\n return text;\n});\n", "/**\n * Process Markdown `
    ` blocks.\n */\nshowdown.subParser('codeBlocks', function (text, options, globals) {\n  'use strict';\n\n  text = globals.converter._dispatch('codeBlocks.before', text, options, globals);\n\n  // sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug\n  text += '¨0';\n\n  var pattern = /(?:\\n\\n|^)((?:(?:[ ]{4}|\\t).*\\n+)+)(\\n*[ ]{0,3}[^ \\t\\n]|(?=¨0))/g;\n  text = text.replace(pattern, function (wholeMatch, m1, m2) {\n    var codeblock = m1,\n        nextChar = m2,\n        end = '\\n';\n\n    codeblock = showdown.subParser('outdent')(codeblock, options, globals);\n    codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);\n    codeblock = showdown.subParser('detab')(codeblock, options, globals);\n    codeblock = codeblock.replace(/^\\n+/g, ''); // trim leading newlines\n    codeblock = codeblock.replace(/\\n+$/g, ''); // trim trailing newlines\n\n    if (options.omitExtraWLInCodeBlocks) {\n      end = '';\n    }\n\n    codeblock = '
    ' + codeblock + end + '
    ';\n\n return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;\n });\n\n // strip sentinel\n text = text.replace(/¨0/, '');\n\n text = globals.converter._dispatch('codeBlocks.after', text, options, globals);\n return text;\n});\n", "/**\n *\n * * Backtick quotes are used for spans.\n *\n * * You can use multiple backticks as the delimiters if you want to\n * include literal backticks in the code span. So, this input:\n *\n * Just type ``foo `bar` baz`` at the prompt.\n *\n * Will translate to:\n *\n *

    Just type foo `bar` baz at the prompt.

    \n *\n * There's no arbitrary limit to the number of backticks you\n * can use as delimters. If you need three consecutive backticks\n * in your code, use four for delimiters, etc.\n *\n * * You can use spaces to get literal backticks at the edges:\n *\n * ... type `` `bar` `` ...\n *\n * Turns to:\n *\n * ... type `bar` ...\n */\nshowdown.subParser('codeSpans', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('codeSpans.before', text, options, globals);\n\n if (typeof (text) === 'undefined') {\n text = '';\n }\n text = text.replace(/(^|[^\\\\])(`+)([^\\r]*?[^`])\\2(?!`)/gm,\n function (wholeMatch, m1, m2, m3) {\n var c = m3;\n c = c.replace(/^([ \\t]*)/g, '');\t// leading whitespace\n c = c.replace(/[ \\t]*$/g, '');\t// trailing whitespace\n c = showdown.subParser('encodeCode')(c, options, globals);\n c = m1 + '' + c + '';\n c = showdown.subParser('hashHTMLSpans')(c, options, globals);\n return c;\n }\n );\n\n text = globals.converter._dispatch('codeSpans.after', text, options, globals);\n return text;\n});\n", "/**\n * Create a full HTML document from the processed markdown\n */\nshowdown.subParser('completeHTMLDocument', function (text, options, globals) {\n 'use strict';\n\n if (!options.completeHTMLDocument) {\n return text;\n }\n\n text = globals.converter._dispatch('completeHTMLDocument.before', text, options, globals);\n\n var doctype = 'html',\n doctypeParsed = '\\n',\n title = '',\n charset = '\\n',\n lang = '',\n metadata = '';\n\n if (typeof globals.metadata.parsed.doctype !== 'undefined') {\n doctypeParsed = '\\n';\n doctype = globals.metadata.parsed.doctype.toString().toLowerCase();\n if (doctype === 'html' || doctype === 'html5') {\n charset = '';\n }\n }\n\n for (var meta in globals.metadata.parsed) {\n if (globals.metadata.parsed.hasOwnProperty(meta)) {\n switch (meta.toLowerCase()) {\n case 'doctype':\n break;\n\n case 'title':\n title = '' + globals.metadata.parsed.title + '\\n';\n break;\n\n case 'charset':\n if (doctype === 'html' || doctype === 'html5') {\n charset = '\\n';\n } else {\n charset = '\\n';\n }\n break;\n\n case 'language':\n case 'lang':\n lang = ' lang=\"' + globals.metadata.parsed[meta] + '\"';\n metadata += '\\n';\n break;\n\n default:\n metadata += '\\n';\n }\n }\n }\n\n text = doctypeParsed + '\\n\\n' + title + charset + metadata + '\\n\\n' + text.trim() + '\\n\\n';\n\n text = globals.converter._dispatch('completeHTMLDocument.after', text, options, globals);\n return text;\n});\n", "/**\n * Convert all tabs to spaces\n */\nshowdown.subParser('detab', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('detab.before', text, options, globals);\n\n // expand first n-1 tabs\n text = text.replace(/\\t(?=\\t)/g, ' '); // g_tab_width\n\n // replace the nth with two sentinels\n text = text.replace(/\\t/g, '¨A¨B');\n\n // use the sentinel to anchor our regex so it doesn't explode\n text = text.replace(/¨B(.+?)¨A/g, function (wholeMatch, m1) {\n var leadingText = m1,\n numSpaces = 4 - leadingText.length % 4; // g_tab_width\n\n // there *must* be a better way to do this:\n for (var i = 0; i < numSpaces; i++) {\n leadingText += ' ';\n }\n\n return leadingText;\n });\n\n // clean up sentinels\n text = text.replace(/¨A/g, ' '); // g_tab_width\n text = text.replace(/¨B/g, '');\n\n text = globals.converter._dispatch('detab.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('ellipsis', function (text, options, globals) {\n 'use strict';\n\n if (!options.ellipsis) {\n return text;\n }\n\n text = globals.converter._dispatch('ellipsis.before', text, options, globals);\n\n text = text.replace(/\\.\\.\\./g, '…');\n\n text = globals.converter._dispatch('ellipsis.after', text, options, globals);\n\n return text;\n});\n", "/**\n * Turn emoji codes into emojis\n *\n * List of supported emojis: https://github.com/showdownjs/showdown/wiki/Emojis\n */\nshowdown.subParser('emoji', function (text, options, globals) {\n 'use strict';\n\n if (!options.emoji) {\n return text;\n }\n\n text = globals.converter._dispatch('emoji.before', text, options, globals);\n\n var emojiRgx = /:([\\S]+?):/g;\n\n text = text.replace(emojiRgx, function (wm, emojiCode) {\n if (showdown.helper.emojis.hasOwnProperty(emojiCode)) {\n return showdown.helper.emojis[emojiCode];\n }\n return wm;\n });\n\n text = globals.converter._dispatch('emoji.after', text, options, globals);\n\n return text;\n});\n", "/**\n * Smart processing for ampersands and angle brackets that need to be encoded.\n */\nshowdown.subParser('encodeAmpsAndAngles', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('encodeAmpsAndAngles.before', text, options, globals);\n\n // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:\n // http://bumppo.net/projects/amputator/\n text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)/g, '&');\n\n // Encode naked <'s\n text = text.replace(/<(?![a-z\\/?$!])/gi, '<');\n\n // Encode <\n text = text.replace(/\n text = text.replace(/>/g, '>');\n\n text = globals.converter._dispatch('encodeAmpsAndAngles.after', text, options, globals);\n return text;\n});\n", "/**\n * Returns the string, with after processing the following backslash escape sequences.\n *\n * attacklab: The polite way to do this is with the new escapeCharacters() function:\n *\n * text = escapeCharacters(text,\"\\\\\",true);\n * text = escapeCharacters(text,\"`*_{}[]()>#+-.!\",true);\n *\n * ...but we're sidestepping its use of the (slow) RegExp constructor\n * as an optimization for Firefox. This function gets called a LOT.\n */\nshowdown.subParser('encodeBackslashEscapes', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('encodeBackslashEscapes.before', text, options, globals);\n\n text = text.replace(/\\\\(\\\\)/g, showdown.helper.escapeCharactersCallback);\n text = text.replace(/\\\\([`*_{}\\[\\]()>#+.!~=|:-])/g, showdown.helper.escapeCharactersCallback);\n\n text = globals.converter._dispatch('encodeBackslashEscapes.after', text, options, globals);\n return text;\n});\n", "/**\n * Encode/escape certain characters inside Markdown code runs.\n * The point is that in code, these characters are literals,\n * and lose their special Markdown meanings.\n */\nshowdown.subParser('encodeCode', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('encodeCode.before', text, options, globals);\n\n // Encode all ampersands; HTML entities are not\n // entities within a Markdown code span.\n text = text\n .replace(/&/g, '&')\n // Do the angle bracket song and dance:\n .replace(//g, '>')\n // Now, escape characters that are magic in Markdown:\n .replace(/([*_{}\\[\\]\\\\=~-])/g, showdown.helper.escapeCharactersCallback);\n\n text = globals.converter._dispatch('encodeCode.after', text, options, globals);\n return text;\n});\n", "/**\n * Within tags -- meaning between < and > -- encode [\\ ` * _ ~ =] so they\n * don't conflict with their use in Markdown for code, italics and strong.\n */\nshowdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.before', text, options, globals);\n\n // Build a regex to find HTML tags.\n var tags = /<\\/?[a-z\\d_:-]+(?:[\\s]+[\\s\\S]+?)?>/gi,\n comments = /-]|-[^>])(?:[^-]|-[^-])*)--)>/gi;\n\n text = text.replace(tags, function (wholeMatch) {\n return wholeMatch\n .replace(/(.)<\\/?code>(?=.)/g, '$1`')\n .replace(/([\\\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);\n });\n\n text = text.replace(comments, function (wholeMatch) {\n return wholeMatch\n .replace(/([\\\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);\n });\n\n text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.after', text, options, globals);\n return text;\n});\n", "/**\n * Handle github codeblocks prior to running HashHTML so that\n * HTML contained within the codeblock gets escaped properly\n * Example:\n * ```ruby\n * def hello_world(x)\n * puts \"Hello, #{x}\"\n * end\n * ```\n */\nshowdown.subParser('githubCodeBlocks', function (text, options, globals) {\n 'use strict';\n\n // early exit if option is not enabled\n if (!options.ghCodeBlocks) {\n return text;\n }\n\n text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);\n\n text += '¨0';\n\n text = text.replace(/(?:^|\\n)(?: {0,3})(```+|~~~+)(?: *)([^\\s`~]*)\\n([\\s\\S]*?)\\n(?: {0,3})\\1/g, function (wholeMatch, delim, language, codeblock) {\n var end = (options.omitExtraWLInCodeBlocks) ? '' : '\\n';\n\n // First parse the github code block\n codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);\n codeblock = showdown.subParser('detab')(codeblock, options, globals);\n codeblock = codeblock.replace(/^\\n+/g, ''); // trim leading newlines\n codeblock = codeblock.replace(/\\n+$/g, ''); // trim trailing whitespace\n\n codeblock = '
    ' + codeblock + end + '
    ';\n\n codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);\n\n // Since GHCodeblocks can be false positives, we need to\n // store the primitive text and the parsed text in a global var,\n // and then return a token\n return '\\n\\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\\n\\n';\n });\n\n // attacklab: strip sentinel\n text = text.replace(/¨0/, '');\n\n return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);\n});\n", "showdown.subParser('hashBlock', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashBlock.before', text, options, globals);\n text = text.replace(/(^\\n+|\\n+$)/g, '');\n text = '\\n\\n¨K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\\n\\n';\n text = globals.converter._dispatch('hashBlock.after', text, options, globals);\n return text;\n});\n", "/**\n * Hash and escape elements that should not be parsed as markdown\n */\nshowdown.subParser('hashCodeTags', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashCodeTags.before', text, options, globals);\n\n var repFunc = function (wholeMatch, match, left, right) {\n var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;\n return '¨C' + (globals.gHtmlSpans.push(codeblock) - 1) + 'C';\n };\n\n // Hash naked \n text = showdown.helper.replaceRecursiveRegExp(text, repFunc, ']*>', '', 'gim');\n\n text = globals.converter._dispatch('hashCodeTags.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('hashElement', function (text, options, globals) {\n 'use strict';\n\n return function (wholeMatch, m1) {\n var blockText = m1;\n\n // Undo double lines\n blockText = blockText.replace(/\\n\\n/g, '\\n');\n blockText = blockText.replace(/^\\n/, '');\n\n // strip trailing blank lines\n blockText = blockText.replace(/\\n+$/g, '');\n\n // Replace the element text with a marker (\"¨KxK\" where x is its key)\n blockText = '\\n\\n¨K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\\n\\n';\n\n return blockText;\n };\n});\n", "showdown.subParser('hashHTMLBlocks', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashHTMLBlocks.before', text, options, globals);\n\n var blockTags = [\n 'pre',\n 'div',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'blockquote',\n 'table',\n 'dl',\n 'ol',\n 'ul',\n 'script',\n 'noscript',\n 'form',\n 'fieldset',\n 'iframe',\n 'math',\n 'style',\n 'section',\n 'header',\n 'footer',\n 'nav',\n 'article',\n 'aside',\n 'address',\n 'audio',\n 'canvas',\n 'figure',\n 'hgroup',\n 'output',\n 'video',\n 'p'\n ],\n repFunc = function (wholeMatch, match, left, right) {\n var txt = wholeMatch;\n // check if this html element is marked as markdown\n // if so, it's contents should be parsed as markdown\n if (left.search(/\\bmarkdown\\b/) !== -1) {\n txt = left + globals.converter.makeHtml(match) + right;\n }\n return '\\n\\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\\n\\n';\n };\n\n if (options.backslashEscapesHTMLTags) {\n // encode backslash escaped HTML tags\n text = text.replace(/\\\\<(\\/?[^>]+?)>/g, function (wm, inside) {\n return '<' + inside + '>';\n });\n }\n\n // hash HTML Blocks\n for (var i = 0; i < blockTags.length; ++i) {\n\n var opTagPos,\n rgx1 = new RegExp('^ {0,3}(<' + blockTags[i] + '\\\\b[^>]*>)', 'im'),\n patLeft = '<' + blockTags[i] + '\\\\b[^>]*>',\n patRight = '';\n // 1. Look for the first position of the first opening HTML tag in the text\n while ((opTagPos = showdown.helper.regexIndexOf(text, rgx1)) !== -1) {\n\n // if the HTML tag is \\ escaped, we need to escape it and break\n\n\n //2. Split the text in that position\n var subTexts = showdown.helper.splitAtIndex(text, opTagPos),\n //3. Match recursively\n newSubText1 = showdown.helper.replaceRecursiveRegExp(subTexts[1], repFunc, patLeft, patRight, 'im');\n\n // prevent an infinite loop\n if (newSubText1 === subTexts[1]) {\n break;\n }\n text = subTexts[0].concat(newSubText1);\n }\n }\n // HR SPECIAL CASE\n text = text.replace(/(\\n {0,3}(<(hr)\\b([^<>])*?\\/?>)[ \\t]*(?=\\n{2,}))/g,\n showdown.subParser('hashElement')(text, options, globals));\n\n // Special case for standalone HTML comments\n text = showdown.helper.replaceRecursiveRegExp(text, function (txt) {\n return '\\n\\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\\n\\n';\n }, '^ {0,3}', 'gm');\n\n // PHP and ASP-style processor instructions ( and <%...%>)\n text = text.replace(/(?:\\n\\n)( {0,3}(?:<([?%])[^\\r]*?\\2>)[ \\t]*(?=\\n{2,}))/g,\n showdown.subParser('hashElement')(text, options, globals));\n\n text = globals.converter._dispatch('hashHTMLBlocks.after', text, options, globals);\n return text;\n});\n", "/**\n * Hash span elements that should not be parsed as markdown\n */\nshowdown.subParser('hashHTMLSpans', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('hashHTMLSpans.before', text, options, globals);\n\n function hashHTMLSpan (html) {\n return '¨C' + (globals.gHtmlSpans.push(html) - 1) + 'C';\n }\n\n // Hash Self Closing tags\n text = text.replace(/<[^>]+?\\/>/gi, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n // Hash tags without properties\n text = text.replace(/<([^>]+?)>[\\s\\S]*?<\\/\\1>/g, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n // Hash tags with properties\n text = text.replace(/<([^>]+?)\\s[^>]+?>[\\s\\S]*?<\\/\\1>/g, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n // Hash self closing tags without />\n text = text.replace(/<[^>]+?>/gi, function (wm) {\n return hashHTMLSpan(wm);\n });\n\n /*showdown.helper.matchRecursiveRegExp(text, ']*>', '', 'gi');*/\n\n text = globals.converter._dispatch('hashHTMLSpans.after', text, options, globals);\n return text;\n});\n\n/**\n * Unhash HTML spans\n */\nshowdown.subParser('unhashHTMLSpans', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('unhashHTMLSpans.before', text, options, globals);\n\n for (var i = 0; i < globals.gHtmlSpans.length; ++i) {\n var repText = globals.gHtmlSpans[i],\n // limiter to prevent infinite loop (assume 10 as limit for recurse)\n limit = 0;\n\n while (/¨C(\\d+)C/.test(repText)) {\n var num = RegExp.$1;\n repText = repText.replace('¨C' + num + 'C', globals.gHtmlSpans[num]);\n if (limit === 10) {\n console.error('maximum nesting of 10 spans reached!!!');\n break;\n }\n ++limit;\n }\n text = text.replace('¨C' + i + 'C', repText);\n }\n\n text = globals.converter._dispatch('unhashHTMLSpans.after', text, options, globals);\n return text;\n});\n", "/**\n * Hash and escape
     elements that should not be parsed as markdown\n */\nshowdown.subParser('hashPreCodeTags', function (text, options, globals) {\n  'use strict';\n  text = globals.converter._dispatch('hashPreCodeTags.before', text, options, globals);\n\n  var repFunc = function (wholeMatch, match, left, right) {\n    // encode html entities\n    var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;\n    return '\\n\\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\\n\\n';\n  };\n\n  // Hash 
    \n  text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}]*>\\\\s*]*>', '^ {0,3}\\\\s*
    ', 'gim');\n\n text = globals.converter._dispatch('hashPreCodeTags.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('headers', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('headers.before', text, options, globals);\n\n var headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),\n\n // Set text-style headers:\n //\tHeader 1\n //\t========\n //\n //\tHeader 2\n //\t--------\n //\n setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \\t]*\\n={2,}[ \\t]*\\n+/gm : /^(.+)[ \\t]*\\n=+[ \\t]*\\n+/gm,\n setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \\t]*\\n-{2,}[ \\t]*\\n+/gm : /^(.+)[ \\t]*\\n-+[ \\t]*\\n+/gm;\n\n text = text.replace(setextRegexH1, function (wholeMatch, m1) {\n\n var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),\n hID = (options.noHeaderId) ? '' : ' id=\"' + headerId(m1) + '\"',\n hLevel = headerLevelStart,\n hashBlock = '' + spanGamut + '';\n return showdown.subParser('hashBlock')(hashBlock, options, globals);\n });\n\n text = text.replace(setextRegexH2, function (matchFound, m1) {\n var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),\n hID = (options.noHeaderId) ? '' : ' id=\"' + headerId(m1) + '\"',\n hLevel = headerLevelStart + 1,\n hashBlock = '' + spanGamut + '';\n return showdown.subParser('hashBlock')(hashBlock, options, globals);\n });\n\n // atx-style headers:\n // # Header 1\n // ## Header 2\n // ## Header 2 with closing hashes ##\n // ...\n // ###### Header 6\n //\n var atxStyle = (options.requireSpaceBeforeHeadingText) ? /^(#{1,6})[ \\t]+(.+?)[ \\t]*#*\\n+/gm : /^(#{1,6})[ \\t]*(.+?)[ \\t]*#*\\n+/gm;\n\n text = text.replace(atxStyle, function (wholeMatch, m1, m2) {\n var hText = m2;\n if (options.customizedHeaderId) {\n hText = m2.replace(/\\s?\\{([^{]+?)}\\s*$/, '');\n }\n\n var span = showdown.subParser('spanGamut')(hText, options, globals),\n hID = (options.noHeaderId) ? '' : ' id=\"' + headerId(m2) + '\"',\n hLevel = headerLevelStart - 1 + m1.length,\n header = '' + span + '';\n\n return showdown.subParser('hashBlock')(header, options, globals);\n });\n\n function headerId (m) {\n var title,\n prefix;\n\n // It is separate from other options to allow combining prefix and customized\n if (options.customizedHeaderId) {\n var match = m.match(/\\{([^{]+?)}\\s*$/);\n if (match && match[1]) {\n m = match[1];\n }\n }\n\n title = m;\n\n // Prefix id to prevent causing inadvertent pre-existing style matches.\n if (showdown.helper.isString(options.prefixHeaderId)) {\n prefix = options.prefixHeaderId;\n } else if (options.prefixHeaderId === true) {\n prefix = 'section-';\n } else {\n prefix = '';\n }\n\n if (!options.rawPrefixHeaderId) {\n title = prefix + title;\n }\n\n if (options.ghCompatibleHeaderId) {\n title = title\n .replace(/ /g, '-')\n // replace previously escaped chars (&, ¨ and $)\n .replace(/&/g, '')\n .replace(/¨T/g, '')\n .replace(/¨D/g, '')\n // replace rest of the chars (&~$ are repeated as they might have been escaped)\n // borrowed from github's redcarpet (some they should produce similar results)\n .replace(/[&+$,\\/:;=?@\"#{}|^¨~\\[\\]`\\\\*)(%.!'<>]/g, '')\n .toLowerCase();\n } else if (options.rawHeaderId) {\n title = title\n .replace(/ /g, '-')\n // replace previously escaped chars (&, ¨ and $)\n .replace(/&/g, '&')\n .replace(/¨T/g, '¨')\n .replace(/¨D/g, '$')\n // replace \" and '\n .replace(/[\"']/g, '-')\n .toLowerCase();\n } else {\n title = title\n .replace(/[^\\w]/g, '')\n .toLowerCase();\n }\n\n if (options.rawPrefixHeaderId) {\n title = prefix + title;\n }\n\n if (globals.hashLinkCounts[title]) {\n title = title + '-' + (globals.hashLinkCounts[title]++);\n } else {\n globals.hashLinkCounts[title] = 1;\n }\n return title;\n }\n\n text = globals.converter._dispatch('headers.after', text, options, globals);\n return text;\n});\n", "/**\n * Turn Markdown link shortcuts into XHTML tags.\n */\nshowdown.subParser('horizontalRule', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('horizontalRule.before', text, options, globals);\n\n var key = showdown.subParser('hashBlock')('
    ', options, globals);\n text = text.replace(/^ {0,2}( ?-){3,}[ \\t]*$/gm, key);\n text = text.replace(/^ {0,2}( ?\\*){3,}[ \\t]*$/gm, key);\n text = text.replace(/^ {0,2}( ?_){3,}[ \\t]*$/gm, key);\n\n text = globals.converter._dispatch('horizontalRule.after', text, options, globals);\n return text;\n});\n", "/**\n * Turn Markdown image shortcuts into tags.\n */\nshowdown.subParser('images', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('images.before', text, options, globals);\n\n var inlineRegExp = /!\\[([^\\]]*?)][ \\t]*()\\([ \\t]??(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*(?:([\"'])([^\"]*?)\\6)?[ \\t]?\\)/g,\n crazyRegExp = /!\\[([^\\]]*?)][ \\t]*()\\([ \\t]?<([^>]*)>(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*(?:(?:([\"'])([^\"]*?)\\6))?[ \\t]?\\)/g,\n base64RegExp = /!\\[([^\\]]*?)][ \\t]*()\\([ \\t]??(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*(?:([\"'])([^\"]*?)\\6)?[ \\t]?\\)/g,\n referenceRegExp = /!\\[([^\\]]*?)] ?(?:\\n *)?\\[([\\s\\S]*?)]()()()()()/g,\n refShortcutRegExp = /!\\[([^\\[\\]]+)]()()()()()/g;\n\n function writeImageTagBase64 (wholeMatch, altText, linkId, url, width, height, m5, title) {\n url = url.replace(/\\s/g, '');\n return writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title);\n }\n\n function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {\n\n var gUrls = globals.gUrls,\n gTitles = globals.gTitles,\n gDims = globals.gDimensions;\n\n linkId = linkId.toLowerCase();\n\n if (!title) {\n title = '';\n }\n // Special case for explicit empty url\n if (wholeMatch.search(/\\(? ?(['\"].*['\"])?\\)$/m) > -1) {\n url = '';\n\n } else if (url === '' || url === null) {\n if (linkId === '' || linkId === null) {\n // lower-case and turn embedded newlines into spaces\n linkId = altText.toLowerCase().replace(/ ?\\n/g, ' ');\n }\n url = '#' + linkId;\n\n if (!showdown.helper.isUndefined(gUrls[linkId])) {\n url = gUrls[linkId];\n if (!showdown.helper.isUndefined(gTitles[linkId])) {\n title = gTitles[linkId];\n }\n if (!showdown.helper.isUndefined(gDims[linkId])) {\n width = gDims[linkId].width;\n height = gDims[linkId].height;\n }\n } else {\n return wholeMatch;\n }\n }\n\n altText = altText\n .replace(/\"/g, '"')\n //altText = showdown.helper.escapeCharacters(altText, '*_', false);\n .replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n //url = showdown.helper.escapeCharacters(url, '*_', false);\n url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);\n var result = '\"'x \"optional title\")\n\n // base64 encoded images\n text = text.replace(base64RegExp, writeImageTagBase64);\n\n // cases with crazy urls like ./image/cat1).png\n text = text.replace(crazyRegExp, writeImageTag);\n\n // normal cases\n text = text.replace(inlineRegExp, writeImageTag);\n\n // handle reference-style shortcuts: ![img text]\n text = text.replace(refShortcutRegExp, writeImageTag);\n\n text = globals.converter._dispatch('images.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('italicsAndBold', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);\n\n // it's faster to have 3 separate regexes for each case than have just one\n // because of backtracing, in some cases, it could lead to an exponential effect\n // called \"catastrophic backtrace\". Ominous!\n\n function parseInside (txt, left, right) {\n /*\n if (options.simplifiedAutoLink) {\n txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);\n }\n */\n return left + txt + right;\n }\n\n // Parse underscores\n if (options.literalMidWordUnderscores) {\n text = text.replace(/\\b___(\\S[\\s\\S]*?)___\\b/g, function (wm, txt) {\n return parseInside (txt, '', '');\n });\n text = text.replace(/\\b__(\\S[\\s\\S]*?)__\\b/g, function (wm, txt) {\n return parseInside (txt, '', '');\n });\n text = text.replace(/\\b_(\\S[\\s\\S]*?)_\\b/g, function (wm, txt) {\n return parseInside (txt, '', '');\n });\n } else {\n text = text.replace(/___(\\S[\\s\\S]*?)___/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/__(\\S[\\s\\S]*?)__/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/_([^\\s_][\\s\\S]*?)_/g, function (wm, m) {\n // !/^_[^_]/.test(m) - test if it doesn't start with __ (since it seems redundant, we removed it)\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n }\n\n // Now parse asterisks\n if (options.literalMidWordAsterisks) {\n text = text.replace(/([^*]|^)\\B\\*\\*\\*(\\S[\\s\\S]*?)\\*\\*\\*\\B(?!\\*)/g, function (wm, lead, txt) {\n return parseInside (txt, lead + '', '');\n });\n text = text.replace(/([^*]|^)\\B\\*\\*(\\S[\\s\\S]*?)\\*\\*\\B(?!\\*)/g, function (wm, lead, txt) {\n return parseInside (txt, lead + '', '');\n });\n text = text.replace(/([^*]|^)\\B\\*(\\S[\\s\\S]*?)\\*\\B(?!\\*)/g, function (wm, lead, txt) {\n return parseInside (txt, lead + '', '');\n });\n } else {\n text = text.replace(/\\*\\*\\*(\\S[\\s\\S]*?)\\*\\*\\*/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/\\*\\*(\\S[\\s\\S]*?)\\*\\*/g, function (wm, m) {\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n text = text.replace(/\\*([^\\s*][\\s\\S]*?)\\*/g, function (wm, m) {\n // !/^\\*[^*]/.test(m) - test if it doesn't start with ** (since it seems redundant, we removed it)\n return (/\\S$/.test(m)) ? parseInside (m, '', '') : wm;\n });\n }\n\n\n text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);\n return text;\n});\n", "/**\n * Form HTML ordered (numbered) and unordered (bulleted) lists.\n */\nshowdown.subParser('lists', function (text, options, globals) {\n 'use strict';\n\n /**\n * Process the contents of a single ordered or unordered list, splitting it\n * into individual list items.\n * @param {string} listStr\n * @param {boolean} trimTrailing\n * @returns {string}\n */\n function processListItems (listStr, trimTrailing) {\n // The $g_list_level global keeps track of when we're inside a list.\n // Each time we enter a list, we increment it; when we leave a list,\n // we decrement. If it's zero, we're not in a list anymore.\n //\n // We do this because when we're not inside a list, we want to treat\n // something like this:\n //\n // I recommend upgrading to version\n // 8. Oops, now this line is treated\n // as a sub-list.\n //\n // As a single paragraph, despite the fact that the second line starts\n // with a digit-period-space sequence.\n //\n // Whereas when we're inside a list (or sub-list), that line will be\n // treated as the start of a sub-list. What a kludge, huh? This is\n // an aspect of Markdown's syntax that's hard to parse perfectly\n // without resorting to mind-reading. Perhaps the solution is to\n // change the syntax rules such that sub-lists must start with a\n // starting cardinal number; e.g. \"1.\" or \"a.\".\n globals.gListLevel++;\n\n // trim trailing blank lines:\n listStr = listStr.replace(/\\n{2,}$/, '\\n');\n\n // attacklab: add sentinel to emulate \\z\n listStr += '¨0';\n\n var rgx = /(\\n)?(^ {0,3})([*+-]|\\d+[.])[ \\t]+((\\[(x|X| )?])?[ \\t]*[^\\r]+?(\\n{1,2}))(?=\\n*(¨0| {0,3}([*+-]|\\d+[.])[ \\t]+))/gm,\n isParagraphed = (/\\n[ \\t]*\\n(?!¨0)/.test(listStr));\n\n // Since version 1.5, nesting sublists requires 4 spaces (or 1 tab) indentation,\n // which is a syntax breaking change\n // activating this option reverts to old behavior\n if (options.disableForced4SpacesIndentedSublists) {\n rgx = /(\\n)?(^ {0,3})([*+-]|\\d+[.])[ \\t]+((\\[(x|X| )?])?[ \\t]*[^\\r]+?(\\n{1,2}))(?=\\n*(¨0|\\2([*+-]|\\d+[.])[ \\t]+))/gm;\n }\n\n listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {\n checked = (checked && checked.trim() !== '');\n\n var item = showdown.subParser('outdent')(m4, options, globals),\n bulletStyle = '';\n\n // Support for github tasklists\n if (taskbtn && options.tasklists) {\n bulletStyle = ' class=\"task-list-item\" style=\"list-style-type: none;\"';\n item = item.replace(/^[ \\t]*\\[(x|X| )?]/m, function () {\n var otp = '
  • a
  • \n // instead of:\n //
    • - - a
    \n // So, to prevent it, we will put a marker (¨A)in the beginning of the line\n // Kind of hackish/monkey patching, but seems more effective than overcomplicating the list parser\n item = item.replace(/^([-*+]|\\d\\.)[ \\t]+[\\S\\n ]*/g, function (wm2) {\n return '¨A' + wm2;\n });\n\n // m1 - Leading line or\n // Has a double return (multi paragraph) or\n // Has sublist\n if (m1 || (item.search(/\\n{2,}/) > -1)) {\n item = showdown.subParser('githubCodeBlocks')(item, options, globals);\n item = showdown.subParser('blockGamut')(item, options, globals);\n } else {\n // Recursion for sub-lists:\n item = showdown.subParser('lists')(item, options, globals);\n item = item.replace(/\\n$/, ''); // chomp(item)\n item = showdown.subParser('hashHTMLBlocks')(item, options, globals);\n\n // Colapse double linebreaks\n item = item.replace(/\\n\\n+/g, '\\n\\n');\n if (isParagraphed) {\n item = showdown.subParser('paragraphs')(item, options, globals);\n } else {\n item = showdown.subParser('spanGamut')(item, options, globals);\n }\n }\n\n // now we need to remove the marker (¨A)\n item = item.replace('¨A', '');\n // we can finally wrap the line in list item tags\n item = '' + item + '\\n';\n\n return item;\n });\n\n // attacklab: strip sentinel\n listStr = listStr.replace(/¨0/g, '');\n\n globals.gListLevel--;\n\n if (trimTrailing) {\n listStr = listStr.replace(/\\s+$/, '');\n }\n\n return listStr;\n }\n\n function styleStartNumber (list, listType) {\n // check if ol and starts by a number different than 1\n if (listType === 'ol') {\n var res = list.match(/^ *(\\d+)\\./);\n if (res && res[1] !== '1') {\n return ' start=\"' + res[1] + '\"';\n }\n }\n return '';\n }\n\n /**\n * Check and parse consecutive lists (better fix for issue #142)\n * @param {string} list\n * @param {string} listType\n * @param {boolean} trimTrailing\n * @returns {string}\n */\n function parseConsecutiveLists (list, listType, trimTrailing) {\n // check if we caught 2 or more consecutive lists by mistake\n // we use the counterRgx, meaning if listType is UL we look for OL and vice versa\n var olRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?\\d+\\.[ \\t]/gm : /^ {0,3}\\d+\\.[ \\t]/gm,\n ulRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?[*+-][ \\t]/gm : /^ {0,3}[*+-][ \\t]/gm,\n counterRxg = (listType === 'ul') ? olRgx : ulRgx,\n result = '';\n\n if (list.search(counterRxg) !== -1) {\n (function parseCL (txt) {\n var pos = txt.search(counterRxg),\n style = styleStartNumber(list, listType);\n if (pos !== -1) {\n // slice\n result += '\\n\\n<' + listType + style + '>\\n' + processListItems(txt.slice(0, pos), !!trimTrailing) + '\\n';\n\n // invert counterType and listType\n listType = (listType === 'ul') ? 'ol' : 'ul';\n counterRxg = (listType === 'ul') ? olRgx : ulRgx;\n\n //recurse\n parseCL(txt.slice(pos));\n } else {\n result += '\\n\\n<' + listType + style + '>\\n' + processListItems(txt, !!trimTrailing) + '\\n';\n }\n })(list);\n } else {\n var style = styleStartNumber(list, listType);\n result = '\\n\\n<' + listType + style + '>\\n' + processListItems(list, !!trimTrailing) + '\\n';\n }\n\n return result;\n }\n\n /** Start of list parsing **/\n text = globals.converter._dispatch('lists.before', text, options, globals);\n // add sentinel to hack around khtml/safari bug:\n // http://bugs.webkit.org/show_bug.cgi?id=11231\n text += '¨0';\n\n if (globals.gListLevel) {\n text = text.replace(/^(( {0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(¨0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm,\n function (wholeMatch, list, m2) {\n var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';\n return parseConsecutiveLists(list, listType, true);\n }\n );\n } else {\n text = text.replace(/(\\n\\n|^\\n?)(( {0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(¨0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm,\n function (wholeMatch, m1, list, m3) {\n var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';\n return parseConsecutiveLists(list, listType, false);\n }\n );\n }\n\n // strip sentinel\n text = text.replace(/¨0/, '');\n text = globals.converter._dispatch('lists.after', text, options, globals);\n return text;\n});\n", "/**\n * Parse metadata at the top of the document\n */\nshowdown.subParser('metadata', function (text, options, globals) {\n 'use strict';\n\n if (!options.metadata) {\n return text;\n }\n\n text = globals.converter._dispatch('metadata.before', text, options, globals);\n\n function parseMetadataContents (content) {\n // raw is raw so it's not changed in any way\n globals.metadata.raw = content;\n\n // escape chars forbidden in html attributes\n // double quotes\n content = content\n // ampersand first\n .replace(/&/g, '&')\n // double quotes\n .replace(/\"/g, '"');\n\n content = content.replace(/\\n {4}/g, ' ');\n content.replace(/^([\\S ]+): +([\\s\\S]+?)$/gm, function (wm, key, value) {\n globals.metadata.parsed[key] = value;\n return '';\n });\n }\n\n text = text.replace(/^\\s*«««+(\\S*?)\\n([\\s\\S]+?)\\n»»»+\\n/, function (wholematch, format, content) {\n parseMetadataContents(content);\n return '¨M';\n });\n\n text = text.replace(/^\\s*---+(\\S*?)\\n([\\s\\S]+?)\\n---+\\n/, function (wholematch, format, content) {\n if (format) {\n globals.metadata.format = format;\n }\n parseMetadataContents(content);\n return '¨M';\n });\n\n text = text.replace(/¨M/g, '');\n\n text = globals.converter._dispatch('metadata.after', text, options, globals);\n return text;\n});\n", "/**\n * Remove one level of line-leading tabs or spaces\n */\nshowdown.subParser('outdent', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('outdent.before', text, options, globals);\n\n // attacklab: hack around Konqueror 3.5.4 bug:\n // \"----------bug\".replace(/^-/g,\"\") == \"bug\"\n text = text.replace(/^(\\t|[ ]{1,4})/gm, '¨0'); // attacklab: g_tab_width\n\n // attacklab: clean up hack\n text = text.replace(/¨0/g, '');\n\n text = globals.converter._dispatch('outdent.after', text, options, globals);\n return text;\n});\n", "/**\n *\n */\nshowdown.subParser('paragraphs', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('paragraphs.before', text, options, globals);\n // Strip leading and trailing lines:\n text = text.replace(/^\\n+/g, '');\n text = text.replace(/\\n+$/g, '');\n\n var grafs = text.split(/\\n{2,}/g),\n grafsOut = [],\n end = grafs.length; // Wrap

    tags\n\n for (var i = 0; i < end; i++) {\n var str = grafs[i];\n // if this is an HTML marker, copy it\n if (str.search(/¨(K|G)(\\d+)\\1/g) >= 0) {\n grafsOut.push(str);\n\n // test for presence of characters to prevent empty lines being parsed\n // as paragraphs (resulting in undesired extra empty paragraphs)\n } else if (str.search(/\\S/) >= 0) {\n str = showdown.subParser('spanGamut')(str, options, globals);\n str = str.replace(/^([ \\t]*)/g, '

    ');\n str += '

    ';\n grafsOut.push(str);\n }\n }\n\n /** Unhashify HTML blocks */\n end = grafsOut.length;\n for (i = 0; i < end; i++) {\n var blockText = '',\n grafsOutIt = grafsOut[i],\n codeFlag = false;\n // if this is a marker for an html block...\n // use RegExp.test instead of string.search because of QML bug\n while (/¨(K|G)(\\d+)\\1/.test(grafsOutIt)) {\n var delim = RegExp.$1,\n num = RegExp.$2;\n\n if (delim === 'K') {\n blockText = globals.gHtmlBlocks[num];\n } else {\n // we need to check if ghBlock is a false positive\n if (codeFlag) {\n // use encoded version of all text\n blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text, options, globals);\n } else {\n blockText = globals.ghCodeBlocks[num].codeblock;\n }\n }\n blockText = blockText.replace(/\\$/g, '$$$$'); // Escape any dollar signs\n\n grafsOutIt = grafsOutIt.replace(/(\\n\\n)?¨(K|G)\\d+\\2(\\n\\n)?/, blockText);\n // Check if grafsOutIt is a pre->code\n if (/^]*>\\s*]*>/.test(grafsOutIt)) {\n codeFlag = true;\n }\n }\n grafsOut[i] = grafsOutIt;\n }\n text = grafsOut.join('\\n');\n // Strip leading and trailing lines:\n text = text.replace(/^\\n+/g, '');\n text = text.replace(/\\n+$/g, '');\n return globals.converter._dispatch('paragraphs.after', text, options, globals);\n});\n", "/**\n * Run extension\n */\nshowdown.subParser('runExtension', function (ext, text, options, globals) {\n 'use strict';\n\n if (ext.filter) {\n text = ext.filter(text, globals.converter, options);\n\n } else if (ext.regex) {\n // TODO remove this when old extension loading mechanism is deprecated\n var re = ext.regex;\n if (!(re instanceof RegExp)) {\n re = new RegExp(re, 'g');\n }\n text = text.replace(re, ext.replace);\n }\n\n return text;\n});\n", "/**\n * These are all the transformations that occur *within* block-level\n * tags like paragraphs, headers, and list items.\n */\nshowdown.subParser('spanGamut', function (text, options, globals) {\n 'use strict';\n\n text = globals.converter._dispatch('spanGamut.before', text, options, globals);\n text = showdown.subParser('codeSpans')(text, options, globals);\n text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);\n text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);\n\n // Process anchor and image tags. Images must come first,\n // because ![foo][f] looks like an anchor.\n text = showdown.subParser('images')(text, options, globals);\n text = showdown.subParser('anchors')(text, options, globals);\n\n // Make links out of things like ``\n // Must come after anchors, because you can use < and >\n // delimiters in inline links like [this]().\n text = showdown.subParser('autoLinks')(text, options, globals);\n text = showdown.subParser('simplifiedAutoLinks')(text, options, globals);\n text = showdown.subParser('emoji')(text, options, globals);\n text = showdown.subParser('underline')(text, options, globals);\n text = showdown.subParser('italicsAndBold')(text, options, globals);\n text = showdown.subParser('strikethrough')(text, options, globals);\n text = showdown.subParser('ellipsis')(text, options, globals);\n\n // we need to hash HTML tags inside spans\n text = showdown.subParser('hashHTMLSpans')(text, options, globals);\n\n // now we encode amps and angles\n text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);\n\n // Do hard breaks\n if (options.simpleLineBreaks) {\n // GFM style hard breaks\n // only add line breaks if the text does not contain a block (special case for lists)\n if (!/\\n\\n¨K/.test(text)) {\n text = text.replace(/\\n+/g, '
    \\n');\n }\n } else {\n // Vanilla hard breaks\n text = text.replace(/ +\\n/g, '
    \\n');\n }\n\n text = globals.converter._dispatch('spanGamut.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('strikethrough', function (text, options, globals) {\n 'use strict';\n\n function parseInside (txt) {\n if (options.simplifiedAutoLink) {\n txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);\n }\n return '' + txt + '';\n }\n\n if (options.strikethrough) {\n text = globals.converter._dispatch('strikethrough.before', text, options, globals);\n text = text.replace(/(?:~){2}([\\s\\S]+?)(?:~){2}/g, function (wm, txt) { return parseInside(txt); });\n text = globals.converter._dispatch('strikethrough.after', text, options, globals);\n }\n\n return text;\n});\n", "/**\n * Strips link definitions from text, stores the URLs and titles in\n * hash references.\n * Link defs are in the form: ^[id]: url \"optional title\"\n */\nshowdown.subParser('stripLinkDefinitions', function (text, options, globals) {\n 'use strict';\n\n var regex = /^ {0,3}\\[([^\\]]+)]:[ \\t]*\\n?[ \\t]*\\s]+)>?(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*\\n?[ \\t]*(?:(\\n*)[\"|'(](.+?)[\"|')][ \\t]*)?(?:\\n+|(?=¨0))/gm,\n base64Regex = /^ {0,3}\\[([^\\]]+)]:[ \\t]*\\n?[ \\t]*?(?: =([*\\d]+[A-Za-z%]{0,4})x([*\\d]+[A-Za-z%]{0,4}))?[ \\t]*\\n?[ \\t]*(?:(\\n*)[\"|'(](.+?)[\"|')][ \\t]*)?(?:\\n\\n|(?=¨0)|(?=\\n\\[))/gm;\n\n // attacklab: sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug\n text += '¨0';\n\n var replaceFunc = function (wholeMatch, linkId, url, width, height, blankLines, title) {\n\n // if there aren't two instances of linkId it must not be a reference link so back out\n linkId = linkId.toLowerCase();\n if (text.toLowerCase().split(linkId).length - 1 < 2) {\n return wholeMatch;\n }\n if (url.match(/^data:.+?\\/.+?;base64,/)) {\n // remove newlines\n globals.gUrls[linkId] = url.replace(/\\s/g, '');\n } else {\n globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url, options, globals); // Link IDs are case-insensitive\n }\n\n if (blankLines) {\n // Oops, found blank lines, so it's not a title.\n // Put back the parenthetical statement we stole.\n return blankLines + title;\n\n } else {\n if (title) {\n globals.gTitles[linkId] = title.replace(/\"|'/g, '"');\n }\n if (options.parseImgDimensions && width && height) {\n globals.gDimensions[linkId] = {\n width: width,\n height: height\n };\n }\n }\n // Completely remove the definition from the text\n return '';\n };\n\n // first we try to find base64 link references\n text = text.replace(base64Regex, replaceFunc);\n\n text = text.replace(regex, replaceFunc);\n\n // attacklab: strip sentinel\n text = text.replace(/¨0/, '');\n\n return text;\n});\n", "showdown.subParser('tables', function (text, options, globals) {\n 'use strict';\n\n if (!options.tables) {\n return text;\n }\n\n var tableRgx = /^ {0,3}\\|?.+\\|.+\\n {0,3}\\|?[ \\t]*:?[ \\t]*(?:[-=]){2,}[ \\t]*:?[ \\t]*\\|[ \\t]*:?[ \\t]*(?:[-=]){2,}[\\s\\S]+?(?:\\n\\n|¨0)/gm,\n //singeColTblRgx = /^ {0,3}\\|.+\\|\\n {0,3}\\|[ \\t]*:?[ \\t]*(?:[-=]){2,}[ \\t]*:?[ \\t]*\\|[ \\t]*\\n(?: {0,3}\\|.+\\|\\n)+(?:\\n\\n|¨0)/gm;\n singeColTblRgx = /^ {0,3}\\|.+\\|[ \\t]*\\n {0,3}\\|[ \\t]*:?[ \\t]*(?:[-=]){2,}[ \\t]*:?[ \\t]*\\|[ \\t]*\\n( {0,3}\\|.+\\|[ \\t]*\\n)*(?:\\n|¨0)/gm;\n\n function parseStyles (sLine) {\n if (/^:[ \\t]*--*$/.test(sLine)) {\n return ' style=\"text-align:left;\"';\n } else if (/^--*[ \\t]*:[ \\t]*$/.test(sLine)) {\n return ' style=\"text-align:right;\"';\n } else if (/^:[ \\t]*--*[ \\t]*:$/.test(sLine)) {\n return ' style=\"text-align:center;\"';\n } else {\n return '';\n }\n }\n\n function parseHeaders (header, style) {\n var id = '';\n header = header.trim();\n // support both tablesHeaderId and tableHeaderId due to error in documentation so we don't break backwards compatibility\n if (options.tablesHeaderId || options.tableHeaderId) {\n id = ' id=\"' + header.replace(/ /g, '_').toLowerCase() + '\"';\n }\n header = showdown.subParser('spanGamut')(header, options, globals);\n\n return '' + header + '\\n';\n }\n\n function parseCells (cell, style) {\n var subText = showdown.subParser('spanGamut')(cell, options, globals);\n return '' + subText + '\\n';\n }\n\n function buildTable (headers, cells) {\n var tb = '\\n\\n\\n',\n tblLgn = headers.length;\n\n for (var i = 0; i < tblLgn; ++i) {\n tb += headers[i];\n }\n tb += '\\n\\n\\n';\n\n for (i = 0; i < cells.length; ++i) {\n tb += '\\n';\n for (var ii = 0; ii < tblLgn; ++ii) {\n tb += cells[i][ii];\n }\n tb += '\\n';\n }\n tb += '\\n
    \\n';\n return tb;\n }\n\n function parseTable (rawTable) {\n var i, tableLines = rawTable.split('\\n');\n\n for (i = 0; i < tableLines.length; ++i) {\n // strip wrong first and last column if wrapped tables are used\n if (/^ {0,3}\\|/.test(tableLines[i])) {\n tableLines[i] = tableLines[i].replace(/^ {0,3}\\|/, '');\n }\n if (/\\|[ \\t]*$/.test(tableLines[i])) {\n tableLines[i] = tableLines[i].replace(/\\|[ \\t]*$/, '');\n }\n // parse code spans first, but we only support one line code spans\n tableLines[i] = showdown.subParser('codeSpans')(tableLines[i], options, globals);\n }\n\n var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),\n rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),\n rawCells = [],\n headers = [],\n styles = [],\n cells = [];\n\n tableLines.shift();\n tableLines.shift();\n\n for (i = 0; i < tableLines.length; ++i) {\n if (tableLines[i].trim() === '') {\n continue;\n }\n rawCells.push(\n tableLines[i]\n .split('|')\n .map(function (s) {\n return s.trim();\n })\n );\n }\n\n if (rawHeaders.length < rawStyles.length) {\n return rawTable;\n }\n\n for (i = 0; i < rawStyles.length; ++i) {\n styles.push(parseStyles(rawStyles[i]));\n }\n\n for (i = 0; i < rawHeaders.length; ++i) {\n if (showdown.helper.isUndefined(styles[i])) {\n styles[i] = '';\n }\n headers.push(parseHeaders(rawHeaders[i], styles[i]));\n }\n\n for (i = 0; i < rawCells.length; ++i) {\n var row = [];\n for (var ii = 0; ii < headers.length; ++ii) {\n if (showdown.helper.isUndefined(rawCells[i][ii])) {\n\n }\n row.push(parseCells(rawCells[i][ii], styles[ii]));\n }\n cells.push(row);\n }\n\n return buildTable(headers, cells);\n }\n\n text = globals.converter._dispatch('tables.before', text, options, globals);\n\n // find escaped pipe characters\n text = text.replace(/\\\\(\\|)/g, showdown.helper.escapeCharactersCallback);\n\n // parse multi column tables\n text = text.replace(tableRgx, parseTable);\n\n // parse one column tables\n text = text.replace(singeColTblRgx, parseTable);\n\n text = globals.converter._dispatch('tables.after', text, options, globals);\n\n return text;\n});\n", "showdown.subParser('underline', function (text, options, globals) {\n 'use strict';\n\n if (!options.underline) {\n return text;\n }\n\n text = globals.converter._dispatch('underline.before', text, options, globals);\n\n if (options.literalMidWordUnderscores) {\n text = text.replace(/\\b___(\\S[\\s\\S]*?)___\\b/g, function (wm, txt) {\n return '' + txt + '';\n });\n text = text.replace(/\\b__(\\S[\\s\\S]*?)__\\b/g, function (wm, txt) {\n return '' + txt + '';\n });\n } else {\n text = text.replace(/___(\\S[\\s\\S]*?)___/g, function (wm, m) {\n return (/\\S$/.test(m)) ? '' + m + '' : wm;\n });\n text = text.replace(/__(\\S[\\s\\S]*?)__/g, function (wm, m) {\n return (/\\S$/.test(m)) ? '' + m + '' : wm;\n });\n }\n\n // escape remaining underscores to prevent them being parsed by italic and bold\n text = text.replace(/(_)/g, showdown.helper.escapeCharactersCallback);\n\n text = globals.converter._dispatch('underline.after', text, options, globals);\n\n return text;\n});\n", "/**\n * Swap back in all the special characters we've hidden.\n */\nshowdown.subParser('unescapeSpecialChars', function (text, options, globals) {\n 'use strict';\n text = globals.converter._dispatch('unescapeSpecialChars.before', text, options, globals);\n\n text = text.replace(/¨E(\\d+)E/g, function (wholeMatch, m1) {\n var charCodeToReplace = parseInt(m1);\n return String.fromCharCode(charCodeToReplace);\n });\n\n text = globals.converter._dispatch('unescapeSpecialChars.after', text, options, globals);\n return text;\n});\n", "showdown.subParser('makeMarkdown.blockquote', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n var children = node.childNodes,\n childrenLength = children.length;\n\n for (var i = 0; i < childrenLength; ++i) {\n var innerTxt = showdown.subParser('makeMarkdown.node')(children[i], globals);\n\n if (innerTxt === '') {\n continue;\n }\n txt += innerTxt;\n }\n }\n // cleanup\n txt = txt.trim();\n txt = '> ' + txt.split('\\n').join('\\n> ');\n return txt;\n});\n", "showdown.subParser('makeMarkdown.codeBlock', function (node, globals) {\n 'use strict';\n\n var lang = node.getAttribute('language'),\n num = node.getAttribute('precodenum');\n return '```' + lang + '\\n' + globals.preList[num] + '\\n```';\n});\n", "showdown.subParser('makeMarkdown.codeSpan', function (node) {\n 'use strict';\n\n return '`' + node.innerHTML + '`';\n});\n", "showdown.subParser('makeMarkdown.emphasis', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n txt += '*';\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '*';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.header', function (node, globals, headerLevel) {\n 'use strict';\n\n var headerMark = new Array(headerLevel + 1).join('#'),\n txt = '';\n\n if (node.hasChildNodes()) {\n txt = headerMark + ' ';\n var children = node.childNodes,\n childrenLength = children.length;\n\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.hr', function () {\n 'use strict';\n\n return '---';\n});\n", "showdown.subParser('makeMarkdown.image', function (node) {\n 'use strict';\n\n var txt = '';\n if (node.hasAttribute('src')) {\n txt += '![' + node.getAttribute('alt') + '](';\n txt += '<' + node.getAttribute('src') + '>';\n if (node.hasAttribute('width') && node.hasAttribute('height')) {\n txt += ' =' + node.getAttribute('width') + 'x' + node.getAttribute('height');\n }\n\n if (node.hasAttribute('title')) {\n txt += ' \"' + node.getAttribute('title') + '\"';\n }\n txt += ')';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.links', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes() && node.hasAttribute('href')) {\n var children = node.childNodes,\n childrenLength = children.length;\n txt = '[';\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '](';\n txt += '<' + node.getAttribute('href') + '>';\n if (node.hasAttribute('title')) {\n txt += ' \"' + node.getAttribute('title') + '\"';\n }\n txt += ')';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.list', function (node, globals, type) {\n 'use strict';\n\n var txt = '';\n if (!node.hasChildNodes()) {\n return '';\n }\n var listItems = node.childNodes,\n listItemsLenght = listItems.length,\n listNum = node.getAttribute('start') || 1;\n\n for (var i = 0; i < listItemsLenght; ++i) {\n if (typeof listItems[i].tagName === 'undefined' || listItems[i].tagName.toLowerCase() !== 'li') {\n continue;\n }\n\n // define the bullet to use in list\n var bullet = '';\n if (type === 'ol') {\n bullet = listNum.toString() + '. ';\n } else {\n bullet = '- ';\n }\n\n // parse list item\n txt += bullet + showdown.subParser('makeMarkdown.listItem')(listItems[i], globals);\n ++listNum;\n }\n\n // add comment at the end to prevent consecutive lists to be parsed as one\n txt += '\\n\\n';\n return txt.trim();\n});\n", "showdown.subParser('makeMarkdown.listItem', function (node, globals) {\n 'use strict';\n\n var listItemTxt = '';\n\n var children = node.childNodes,\n childrenLenght = children.length;\n\n for (var i = 0; i < childrenLenght; ++i) {\n listItemTxt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n // if it's only one liner, we need to add a newline at the end\n if (!/\\n$/.test(listItemTxt)) {\n listItemTxt += '\\n';\n } else {\n // it's multiparagraph, so we need to indent\n listItemTxt = listItemTxt\n .split('\\n')\n .join('\\n ')\n .replace(/^ {4}$/gm, '')\n .replace(/\\n\\n+/g, '\\n\\n');\n }\n\n return listItemTxt;\n});\n", "\n\nshowdown.subParser('makeMarkdown.node', function (node, globals, spansOnly) {\n 'use strict';\n\n spansOnly = spansOnly || false;\n\n var txt = '';\n\n // edge case of text without wrapper paragraph\n if (node.nodeType === 3) {\n return showdown.subParser('makeMarkdown.txt')(node, globals);\n }\n\n // HTML comment\n if (node.nodeType === 8) {\n return '\\n\\n';\n }\n\n // process only node elements\n if (node.nodeType !== 1) {\n return '';\n }\n\n var tagName = node.tagName.toLowerCase();\n\n switch (tagName) {\n\n //\n // BLOCKS\n //\n case 'h1':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 1) + '\\n\\n'; }\n break;\n case 'h2':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 2) + '\\n\\n'; }\n break;\n case 'h3':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 3) + '\\n\\n'; }\n break;\n case 'h4':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 4) + '\\n\\n'; }\n break;\n case 'h5':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 5) + '\\n\\n'; }\n break;\n case 'h6':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 6) + '\\n\\n'; }\n break;\n\n case 'p':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.paragraph')(node, globals) + '\\n\\n'; }\n break;\n\n case 'blockquote':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.blockquote')(node, globals) + '\\n\\n'; }\n break;\n\n case 'hr':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.hr')(node, globals) + '\\n\\n'; }\n break;\n\n case 'ol':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ol') + '\\n\\n'; }\n break;\n\n case 'ul':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ul') + '\\n\\n'; }\n break;\n\n case 'precode':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.codeBlock')(node, globals) + '\\n\\n'; }\n break;\n\n case 'pre':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.pre')(node, globals) + '\\n\\n'; }\n break;\n\n case 'table':\n if (!spansOnly) { txt = showdown.subParser('makeMarkdown.table')(node, globals) + '\\n\\n'; }\n break;\n\n //\n // SPANS\n //\n case 'code':\n txt = showdown.subParser('makeMarkdown.codeSpan')(node, globals);\n break;\n\n case 'em':\n case 'i':\n txt = showdown.subParser('makeMarkdown.emphasis')(node, globals);\n break;\n\n case 'strong':\n case 'b':\n txt = showdown.subParser('makeMarkdown.strong')(node, globals);\n break;\n\n case 'del':\n txt = showdown.subParser('makeMarkdown.strikethrough')(node, globals);\n break;\n\n case 'a':\n txt = showdown.subParser('makeMarkdown.links')(node, globals);\n break;\n\n case 'img':\n txt = showdown.subParser('makeMarkdown.image')(node, globals);\n break;\n\n default:\n txt = node.outerHTML + '\\n\\n';\n }\n\n // common normalization\n // TODO eventually\n\n return txt;\n});\n", "showdown.subParser('makeMarkdown.paragraph', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n }\n\n // some text normalization\n txt = txt.trim();\n\n return txt;\n});\n", "showdown.subParser('makeMarkdown.pre', function (node, globals) {\n 'use strict';\n\n var num = node.getAttribute('prenum');\n return '
    ' + globals.preList[num] + '
    ';\n});\n", "showdown.subParser('makeMarkdown.strikethrough', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n txt += '~~';\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '~~';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.strong', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (node.hasChildNodes()) {\n txt += '**';\n var children = node.childNodes,\n childrenLength = children.length;\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals);\n }\n txt += '**';\n }\n return txt;\n});\n", "showdown.subParser('makeMarkdown.table', function (node, globals) {\n 'use strict';\n\n var txt = '',\n tableArray = [[], []],\n headings = node.querySelectorAll('thead>tr>th'),\n rows = node.querySelectorAll('tbody>tr'),\n i, ii;\n for (i = 0; i < headings.length; ++i) {\n var headContent = showdown.subParser('makeMarkdown.tableCell')(headings[i], globals),\n allign = '---';\n\n if (headings[i].hasAttribute('style')) {\n var style = headings[i].getAttribute('style').toLowerCase().replace(/\\s/g, '');\n switch (style) {\n case 'text-align:left;':\n allign = ':---';\n break;\n case 'text-align:right;':\n allign = '---:';\n break;\n case 'text-align:center;':\n allign = ':---:';\n break;\n }\n }\n tableArray[0][i] = headContent.trim();\n tableArray[1][i] = allign;\n }\n\n for (i = 0; i < rows.length; ++i) {\n var r = tableArray.push([]) - 1,\n cols = rows[i].getElementsByTagName('td');\n\n for (ii = 0; ii < headings.length; ++ii) {\n var cellContent = ' ';\n if (typeof cols[ii] !== 'undefined') {\n cellContent = showdown.subParser('makeMarkdown.tableCell')(cols[ii], globals);\n }\n tableArray[r].push(cellContent);\n }\n }\n\n var cellSpacesCount = 3;\n for (i = 0; i < tableArray.length; ++i) {\n for (ii = 0; ii < tableArray[i].length; ++ii) {\n var strLen = tableArray[i][ii].length;\n if (strLen > cellSpacesCount) {\n cellSpacesCount = strLen;\n }\n }\n }\n\n for (i = 0; i < tableArray.length; ++i) {\n for (ii = 0; ii < tableArray[i].length; ++ii) {\n if (i === 1) {\n if (tableArray[i][ii].slice(-1) === ':') {\n tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii].slice(-1), cellSpacesCount - 1, '-') + ':';\n } else {\n tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount, '-');\n }\n } else {\n tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount);\n }\n }\n txt += '| ' + tableArray[i].join(' | ') + ' |\\n';\n }\n\n return txt.trim();\n});\n", "showdown.subParser('makeMarkdown.tableCell', function (node, globals) {\n 'use strict';\n\n var txt = '';\n if (!node.hasChildNodes()) {\n return '';\n }\n var children = node.childNodes,\n childrenLength = children.length;\n\n for (var i = 0; i < childrenLength; ++i) {\n txt += showdown.subParser('makeMarkdown.node')(children[i], globals, true);\n }\n return txt.trim();\n});\n", "showdown.subParser('makeMarkdown.txt', function (node) {\n 'use strict';\n\n var txt = node.nodeValue;\n\n // multiple spaces are collapsed\n txt = txt.replace(/ +/g, ' ');\n\n // replace the custom ¨NBSP; with a space\n txt = txt.replace(/¨NBSP;/g, ' ');\n\n // \", <, > and & should replace escaped html entities\n txt = showdown.helper.unescapeHTMLEntities(txt);\n\n // escape markdown magic characters\n // emphasis, strong and strikethrough - can appear everywhere\n // we also escape pipe (|) because of tables\n // and escape ` because of code blocks and spans\n txt = txt.replace(/([*_~|`])/g, '\\\\$1');\n\n // escape > because of blockquotes\n txt = txt.replace(/^(\\s*)>/g, '\\\\$1>');\n\n // hash character, only troublesome at the beginning of a line because of headers\n txt = txt.replace(/^#/gm, '\\\\#');\n\n // horizontal rules\n txt = txt.replace(/^(\\s*)([-=]{3,})(\\s*)$/, '$1\\\\$2$3');\n\n // dot, because of ordered lists, only troublesome at the beginning of a line when preceded by an integer\n txt = txt.replace(/^( {0,3}\\d+)\\./gm, '$1\\\\.');\n\n // +, * and -, at the beginning of a line becomes a list, so we need to escape them also (asterisk was already escaped)\n txt = txt.replace(/^( {0,3})([+-])/gm, '$1\\\\$2');\n\n // images and links, ] followed by ( is problematic, so we escape it\n txt = txt.replace(/]([\\s]*)\\(/g, '\\\\]$1\\\\(');\n\n // reference URIs must also be escaped\n txt = txt.replace(/^ {0,3}\\[([\\S \\t]*?)]:/gm, '\\\\[$1]:');\n\n return txt;\n});\n", "var root = this;\n\n// AMD Loader\nif (typeof define === 'function' && define.amd) {\n define(function () {\n 'use strict';\n return showdown;\n });\n\n// CommonJS/nodeJS Loader\n} else if (typeof module !== 'undefined' && module.exports) {\n module.exports = showdown;\n\n// Regular Browser loader\n} else {\n root.showdown = showdown;\n}\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", "'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", "// 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'\nconst isElectron = require('is-electron')\n\nconst IS_ENV_WITH_DOM = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\n// @ts-ignore\nconst IS_ELECTRON = isElectron()\nconst IS_BROWSER = IS_ENV_WITH_DOM && !IS_ELECTRON\nconst IS_ELECTRON_MAIN = IS_ELECTRON && !IS_ENV_WITH_DOM\nconst IS_ELECTRON_RENDERER = IS_ELECTRON && IS_ENV_WITH_DOM\nconst IS_NODE = typeof require === 'function' && typeof process !== 'undefined' && typeof process.release !== 'undefined' && process.release.name === 'node' && !IS_ELECTRON\n// @ts-ignore - we either ignore worker scope or dom scope\nconst IS_WEBWORKER = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\nconst IS_TEST = typeof process !== 'undefined' && typeof process.env !== 'undefined' && process.env.NODE_ENV === 'test'\nconst IS_REACT_NATIVE = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n\nmodule.exports = {\n isTest: IS_TEST,\n isElectron: IS_ELECTRON,\n isElectronMain: IS_ELECTRON_MAIN,\n isElectronRenderer: IS_ELECTRON_RENDERER,\n isNode: IS_NODE,\n /**\n * Detects browser main thread **NOT** web worker or service worker\n */\n isBrowser: IS_BROWSER,\n isWebWorker: IS_WEBWORKER,\n isEnvWithDom: IS_ENV_WITH_DOM,\n isReactNative: IS_REACT_NATIVE\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", "\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", "/* 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", "'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\";\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 = 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\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 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", "\"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\";\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 = 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", "\"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 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new this.buf.constructor(0)\n : 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 = 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\";\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 = {};\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\";\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", "// minimal library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index-minimal\");\n", "'use strict'\n\nmodule.exports = function getTime () {\n return Date.now()\n}\n", "'use strict'\n\nconst getTime = require('./time')\n\nclass Retimer {\n constructor (callback, timeout, args) {\n const that = this\n\n this._started = getTime()\n this._rescheduled = 0\n this._scheduled = timeout\n this._args = args\n this._triggered = false\n\n this._timerWrapper = () => {\n if (that._rescheduled > 0) {\n that._scheduled = that._rescheduled - (getTime() - that._started)\n that._schedule(that._scheduled)\n } else {\n that._triggered = true\n callback.apply(null, that._args)\n }\n }\n\n this._timer = setTimeout(this._timerWrapper, timeout)\n }\n\n reschedule (timeout) {\n if (!timeout) {\n timeout = this._scheduled\n }\n const now = getTime()\n if ((now + timeout) - (this._started + this._scheduled) < 0) {\n clearTimeout(this._timer)\n this._schedule(timeout)\n } else if (!this._triggered) {\n this._started = now\n this._rescheduled = timeout\n } else {\n this._schedule(timeout)\n }\n }\n\n _schedule (timeout) {\n this._triggered = false\n this._started = getTime()\n this._rescheduled = 0\n this._scheduled = timeout\n this._timer = setTimeout(this._timerWrapper, timeout)\n }\n\n clear () {\n clearTimeout(this._timer)\n }\n}\n\nfunction retimer () {\n if (typeof arguments[0] !== 'function') {\n throw new Error('callback needed')\n }\n\n if (typeof arguments[1] !== 'number') {\n throw new Error('timeout needed')\n }\n\n let args\n\n if (arguments.length > 0) {\n args = new Array(arguments.length - 2)\n\n /* eslint-disable no-var */\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 2]\n }\n }\n\n return new Retimer(arguments[0], arguments[1], args)\n}\n\nmodule.exports = retimer\n", "'use strict'\n\nconst { AbortController } = globalThis\n\n// @ts-expect-error no types\nconst retimer = require('retimer')\n\nclass TimeoutController extends AbortController {\n /**\n * @constructor\n * @param {number} ms milliseconds\n */\n constructor (ms) {\n super()\n this._ms = ms\n this._timer = retimer(() => this.abort(), ms)\n // Patch for safari not supported extending built in classes\n Object.setPrototypeOf(this, TimeoutController.prototype)\n }\n\n /**\n * Aborts the controller and clears the timer\n */\n abort () {\n this._timer.clear()\n return super.abort()\n }\n\n /**\n * Clears the timer\n */\n clear () {\n this._timer.clear()\n }\n\n /**\n * Resets the timer\n */\n reset () {\n this._timer.clear()\n this._timer = retimer(() => this.abort(), this._ms)\n }\n}\n\nmodule.exports = {\n TimeoutController\n}\n", "'use strict'\n\nconst isReactNative =\n typeof navigator !== 'undefined' &&\n navigator.product === 'ReactNative'\n\nfunction getDefaultBase () {\n if (isReactNative) {\n return 'http://localhost'\n }\n // in some environments i.e. cloudflare workers location is not available\n if (!self.location) {\n return ''\n }\n\n return self.location.protocol + '//' + self.location.host\n}\n\nconst URL = self.URL\nconst defaultBase = getDefaultBase()\n\nclass URLWithLegacySupport {\n constructor (url = '', base = defaultBase) {\n this.super = new URL(url, base)\n this.path = this.pathname + this.search\n this.auth =\n this.username && this.password\n ? this.username + ':' + this.password\n : null\n\n this.query =\n this.search && this.search.startsWith('?')\n ? this.search.slice(1)\n : null\n }\n\n get hash () {\n return this.super.hash\n }\n\n get host () {\n return this.super.host\n }\n\n get hostname () {\n return this.super.hostname\n }\n\n get href () {\n return this.super.href\n }\n\n get origin () {\n return this.super.origin\n }\n\n get password () {\n return this.super.password\n }\n\n get pathname () {\n return this.super.pathname\n }\n\n get port () {\n return this.super.port\n }\n\n get protocol () {\n return this.super.protocol\n }\n\n get search () {\n return this.super.search\n }\n\n get searchParams () {\n return this.super.searchParams\n }\n\n get username () {\n return this.super.username\n }\n\n set hash (hash) {\n this.super.hash = hash\n }\n\n set host (host) {\n this.super.host = host\n }\n\n set hostname (hostname) {\n this.super.hostname = hostname\n }\n\n set href (href) {\n this.super.href = href\n }\n\n set password (password) {\n this.super.password = password\n }\n\n set pathname (pathname) {\n this.super.pathname = pathname\n }\n\n set port (port) {\n this.super.port = port\n }\n\n set protocol (protocol) {\n this.super.protocol = protocol\n }\n\n set search (search) {\n this.super.search = search\n }\n\n set username (username) {\n this.super.username = username\n }\n\n /**\n * @param {any} o\n */\n static createObjectURL (o) {\n return URL.createObjectURL(o)\n }\n\n /**\n * @param {string} o\n */\n static revokeObjectURL (o) {\n URL.revokeObjectURL(o)\n }\n\n toJSON () {\n return this.super.toJSON()\n }\n\n toString () {\n return this.super.toString()\n }\n\n format () {\n return this.toString()\n }\n}\n\n/**\n * @param {string | import('url').UrlObject} obj\n */\nfunction format (obj) {\n if (typeof obj === 'string') {\n const url = new URL(obj)\n\n return url.toString()\n }\n\n if (!(obj instanceof URL)) {\n const userPass =\n // @ts-ignore its not supported in node but we normalise\n obj.username && obj.password\n // @ts-ignore its not supported in node but we normalise\n ? `${obj.username}:${obj.password}@`\n : ''\n const auth = obj.auth ? obj.auth + '@' : ''\n const port = obj.port ? ':' + obj.port : ''\n const protocol = obj.protocol ? obj.protocol + '//' : ''\n const host = obj.host || ''\n const hostname = obj.hostname || ''\n const search = obj.search || (obj.query ? '?' + obj.query : '')\n const hash = obj.hash || ''\n const pathname = obj.pathname || ''\n // @ts-ignore - path is not supported in node but we normalise\n const path = obj.path || pathname + search\n\n return `${protocol}${userPass || auth}${\n host || hostname + port\n }${path}${hash}`\n }\n}\n\nmodule.exports = {\n URLWithLegacySupport,\n URLSearchParams: self.URLSearchParams,\n defaultBase,\n format\n}\n", "'use strict'\n\nconst { URLWithLegacySupport, format } = require('./url')\n\n/**\n * @param {string | undefined} url\n * @param {any} [location]\n * @param {any} [protocolMap]\n * @param {any} [defaultProtocol]\n */\nmodule.exports = (url, location = {}, protocolMap = {}, defaultProtocol) => {\n let protocol = location.protocol\n ? location.protocol.replace(':', '')\n : 'http'\n\n // Check protocol map\n protocol = (protocolMap[protocol] || defaultProtocol || protocol) + ':'\n let urlParsed\n\n try {\n urlParsed = new URLWithLegacySupport(url)\n } catch (err) {\n urlParsed = {}\n }\n\n const base = Object.assign({}, location, {\n protocol: protocol || urlParsed.protocol,\n host: location.host || urlParsed.host\n })\n\n return new URLWithLegacySupport(url, format(base)).toString()\n}\n", "'use strict'\n\nconst {\n URLWithLegacySupport,\n format,\n URLSearchParams,\n defaultBase\n} = require('./src/url')\nconst relative = require('./src/relative')\n\nmodule.exports = {\n URL: URLWithLegacySupport,\n URLSearchParams,\n format,\n relative,\n defaultBase\n}\n", "/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n * @param {Array} signals\n * @returns {AbortSignal}\n */\nfunction anySignal (signals) {\n const controller = new globalThis.AbortController()\n\n function onAbort () {\n controller.abort()\n\n for (const signal of signals) {\n if (!signal || !signal.removeEventListener) continue\n signal.removeEventListener('abort', onAbort)\n }\n }\n\n for (const signal of signals) {\n if (!signal || !signal.addEventListener) continue\n if (signal.aborted) {\n onAbort()\n break\n }\n signal.addEventListener('abort', onAbort)\n }\n\n return controller.signal\n}\n\nmodule.exports = anySignal\nmodule.exports.anySignal = anySignal\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", "'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", "'use strict'\n\nclass TimeoutError extends Error {\n constructor (message = 'Request timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\nexports.TimeoutError = TimeoutError\n\nclass AbortError extends Error {\n constructor (message = 'The operation was aborted.') {\n super(message)\n this.name = 'AbortError'\n }\n}\nexports.AbortError = AbortError\n\nclass HTTPError extends Error {\n /**\n * @param {Response} response\n */\n constructor (response) {\n super(response.statusText)\n this.name = 'HTTPError'\n this.response = response\n }\n}\nexports.HTTPError = HTTPError\n", "\"use strict\";\n\n// ref: https://github.com/tc39/proposal-global\nvar getGlobal = function () {\n\t// the only reliable means to get the global object is\n\t// `Function('return this')()`\n\t// However, this causes CSP violations in Chrome apps.\n\tif (typeof self !== 'undefined') { return self; }\n\tif (typeof window !== 'undefined') { return window; }\n\tif (typeof global !== 'undefined') { return global; }\n\tthrow new Error('unable to locate global object');\n}\n\nvar globalObject = getGlobal();\n\nmodule.exports = exports = globalObject.fetch;\n\n// Needed for TypeScript and Webpack.\nif (globalObject.fetch) {\n\texports.default = globalObject.fetch.bind(globalObject);\n}\n\nexports.Headers = globalObject.Headers;\nexports.Request = globalObject.Request;\nexports.Response = globalObject.Response;\n", "'use strict'\n\nif (globalThis.fetch && globalThis.Headers && globalThis.Request && globalThis.Response) {\n module.exports = {\n default: globalThis.fetch,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response\n }\n} else {\n module.exports = {\n default: require('node-fetch').default,\n Headers: require('node-fetch').Headers,\n Request: require('node-fetch').Request,\n Response: require('node-fetch').Response\n }\n}\n", "'use strict'\n\n/**\n * @typedef {globalThis.Headers} Headers\n * @typedef {globalThis.Request} Request\n * @typedef {globalThis.Response} Response\n */\n\n// use window.fetch if it is available, fall back to node-fetch if not\nmodule.exports = require('native-fetch')\n", "'use strict'\n\nconst { TimeoutError, AbortError } = require('./error')\n// @ts-expect-error\nconst { Response, Request, Headers, default: fetch } = require('../fetch')\n\n/**\n * @typedef {import('../types').FetchOptions} FetchOptions\n * @typedef {import('../types').ProgressFn} ProgressFn\n */\n\n/**\n * Fetch with progress\n *\n * @param {string | Request} url\n * @param {FetchOptions} [options]\n * @returns {Promise}\n */\nconst fetchWithProgress = (url, options = {}) => {\n const request = new XMLHttpRequest()\n request.open(options.method || 'GET', url.toString(), true)\n\n const { timeout, headers } = options\n\n if (timeout && timeout > 0 && timeout < Infinity) {\n request.timeout = timeout\n }\n\n if (options.overrideMimeType != null) {\n request.overrideMimeType(options.overrideMimeType)\n }\n\n if (headers) {\n for (const [name, value] of new Headers(headers)) {\n request.setRequestHeader(name, value)\n }\n }\n\n if (options.signal) {\n options.signal.onabort = () => request.abort()\n }\n\n if (options.onUploadProgress) {\n request.upload.onprogress = options.onUploadProgress\n }\n\n // Note: Need to use `arraybuffer` here instead of `blob` because `Blob`\n // instances coming from JSDOM are not compatible with `Response` from\n // node-fetch (which is the setup we get when testing with jest because\n // it uses JSDOM which does not provide a global fetch\n // https://github.com/jsdom/jsdom/issues/1724)\n request.responseType = 'arraybuffer'\n\n return new Promise((resolve, reject) => {\n /**\n * @param {Event} event\n */\n const handleEvent = (event) => {\n switch (event.type) {\n case 'error': {\n resolve(Response.error())\n break\n }\n case 'load': {\n resolve(\n new ResponseWithURL(request.responseURL, request.response, {\n status: request.status,\n statusText: request.statusText,\n headers: parseHeaders(request.getAllResponseHeaders())\n })\n )\n break\n }\n case 'timeout': {\n reject(new TimeoutError())\n break\n }\n case 'abort': {\n reject(new AbortError())\n break\n }\n default: {\n break\n }\n }\n }\n request.onerror = handleEvent\n request.onload = handleEvent\n request.ontimeout = handleEvent\n request.onabort = handleEvent\n\n // @ts-expect-error options.body can be a node readable stream, which isn't compatible with XHR, but this\n // file is a browser override so you won't get a node readable stream so ignore the error\n request.send(options.body)\n })\n}\n\nconst fetchWithStreaming = fetch\n\n/**\n * @param {string | Request} url\n * @param {FetchOptions} options\n */\nconst fetchWith = (url, options = {}) =>\n (options.onUploadProgress != null)\n ? fetchWithProgress(url, options)\n : fetchWithStreaming(url, options)\n\n/**\n * Parse Headers from a XMLHttpRequest\n *\n * @param {string} input\n * @returns {Headers}\n */\nconst parseHeaders = (input) => {\n const headers = new Headers()\n for (const line of input.trim().split(/[\\r\\n]+/)) {\n const index = line.indexOf(': ')\n if (index > 0) {\n headers.set(line.slice(0, index), line.slice(index + 1))\n }\n }\n\n return headers\n}\n\nclass ResponseWithURL extends Response {\n /**\n * @param {string} url\n * @param {BodyInit} body\n * @param {ResponseInit} options\n */\n constructor (url, body, options) {\n super(body, options)\n Object.defineProperty(this, 'url', { value: url })\n }\n}\n\nmodule.exports = {\n fetch: fetchWith,\n Request,\n Headers\n}\n", "'use strict'\n\n/**\n * Turns a browser readable stream into an async iterable. Async iteration over\n * returned iterable will lock give stream, preventing any other consumer from\n * acquiring a reader. The lock will be released if iteration loop is broken. To\n * prevent stream cancelling optional `{ preventCancel: true }` could be passed\n * as a second argument.\n * @template T\n * @param {ReadableStream} stream\n * @param {Object} [options]\n * @param {boolean} [options.preventCancel=boolean]\n * @returns {AsyncIterable}\n */\nasync function * browserReadableStreamToIt (stream, options = {}) {\n const reader = stream.getReader()\n\n try {\n while (true) {\n const result = await reader.read()\n\n if (result.done) {\n return\n }\n\n yield result.value\n }\n } finally {\n if (options.preventCancel !== true) {\n reader.cancel()\n }\n\n reader.releaseLock()\n }\n}\n\nmodule.exports = browserReadableStreamToIt\n", "'use strict'\n\n/**\n * Collects all values from an (async) iterable into an array and returns it.\n *\n * @template T\n * @param {AsyncIterable|Iterable} source\n */\nconst all = async (source) => {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n\nmodule.exports = all\n", "/* eslint-disable no-undef */\n'use strict'\n\nconst { fetch, Request, Headers } = require('./http/fetch')\nconst { TimeoutError, HTTPError } = require('./http/error')\nconst merge = require('merge-options').bind({ ignoreUndefined: true })\nconst { URL, URLSearchParams } = require('iso-url')\nconst anySignal = require('any-signal')\nconst browserReableStreamToIt = require('browser-readablestream-to-it')\nconst { isBrowser, isWebWorker } = require('./env')\nconst all = require('it-all')\n\n/**\n * @typedef {import('stream').Readable} NodeReadableStream\n * @typedef {import('./types').HTTPOptions} HTTPOptions\n * @typedef {import('./types').ExtendedResponse} ExtendedResponse\n */\n\n/**\n * @template TResponse\n * @param {Promise} promise\n * @param {number | undefined} ms\n * @param {AbortController} abortController\n * @returns {Promise}\n */\nconst timeout = (promise, ms, abortController) => {\n if (ms === undefined) {\n return promise\n }\n\n const start = Date.now()\n\n const timedOut = () => {\n const time = Date.now() - start\n\n return time >= ms\n }\n\n return new Promise((resolve, reject) => {\n const timeoutID = setTimeout(() => {\n if (timedOut()) {\n reject(new TimeoutError())\n abortController.abort()\n }\n }, ms)\n\n /**\n * @param {(value: any) => void } next\n */\n const after = (next) => {\n /**\n * @param {any} res\n */\n const fn = (res) => {\n clearTimeout(timeoutID)\n\n if (timedOut()) {\n reject(new TimeoutError())\n return\n }\n\n next(res)\n }\n return fn\n }\n\n promise\n .then(after(resolve), after(reject))\n })\n}\n\nconst defaults = {\n throwHttpErrors: true,\n credentials: 'same-origin'\n}\n\nclass HTTP {\n /**\n *\n * @param {HTTPOptions} options\n */\n constructor (options = {}) {\n /** @type {HTTPOptions} */\n this.opts = merge(defaults, options)\n }\n\n /**\n * Fetch\n *\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n * @returns {Promise}\n */\n async fetch (resource, options = {}) {\n /** @type {HTTPOptions} */\n const opts = merge(this.opts, options)\n // @ts-expect-error\n const headers = new Headers(opts.headers)\n\n // validate resource type\n // @ts-expect-error\n if (typeof resource !== 'string' && !(resource instanceof URL || resource instanceof Request)) {\n throw new TypeError('`resource` must be a string, URL, or Request')\n }\n\n const url = new URL(resource.toString(), opts.base)\n\n const {\n searchParams,\n transformSearchParams,\n json\n } = opts\n\n if (searchParams) {\n if (typeof transformSearchParams === 'function') {\n // @ts-ignore\n url.search = transformSearchParams(new URLSearchParams(opts.searchParams))\n } else {\n // @ts-ignore\n url.search = new URLSearchParams(opts.searchParams)\n }\n }\n\n if (json) {\n opts.body = JSON.stringify(opts.json)\n headers.set('content-type', 'application/json')\n }\n\n const abortController = new AbortController()\n // @ts-ignore\n const signal = anySignal([abortController.signal, opts.signal])\n\n if (globalThis.ReadableStream != null && opts.body instanceof globalThis.ReadableStream && (isBrowser || isWebWorker)) {\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1387483\n opts.body = new Blob(await all(browserReableStreamToIt(opts.body)))\n }\n\n /** @type {ExtendedResponse} */\n // @ts-expect-error additional fields are assigned below\n const response = await timeout(\n fetch(\n url.toString(),\n {\n ...opts,\n signal,\n // @ts-expect-error non-browser fetch implementations may take extra options\n timeout: undefined,\n headers,\n\n // https://fetch.spec.whatwg.org/#dom-requestinit-duplex\n // https://github.com/whatwg/fetch/issues/1254\n duplex: 'half'\n }\n ),\n opts.timeout,\n abortController\n )\n\n if (!response.ok && opts.throwHttpErrors) {\n if (opts.handleError) {\n await opts.handleError(response)\n }\n throw new HTTPError(response)\n }\n\n response.iterator = async function * () {\n yield * fromStream(response.body)\n }\n\n response.ndjson = async function * () {\n for await (const chunk of ndjson(response.iterator())) {\n if (options.transform) {\n yield options.transform(chunk)\n } else {\n yield chunk\n }\n }\n }\n\n return response\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n post (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'POST' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n get (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'GET' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n put (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'PUT' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n delete (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'DELETE' })\n }\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n options (resource, options = {}) {\n return this.fetch(resource, { ...options, method: 'OPTIONS' })\n }\n}\n\n/**\n * Parses NDJSON chunks from an iterator\n *\n * @param {AsyncIterable} source\n * @returns {AsyncIterable}\n */\nconst ndjson = async function * (source) {\n const decoder = new TextDecoder()\n let buf = ''\n\n for await (const chunk of source) {\n buf += decoder.decode(chunk, { stream: true })\n const lines = buf.split(/\\r?\\n/)\n\n for (let i = 0; i < lines.length - 1; i++) {\n const l = lines[i].trim()\n if (l.length > 0) {\n yield JSON.parse(l)\n }\n }\n buf = lines[lines.length - 1]\n }\n buf += decoder.decode()\n buf = buf.trim()\n if (buf.length !== 0) {\n yield JSON.parse(buf)\n }\n}\n\n/**\n * Stream to AsyncIterable\n *\n * @template TChunk\n * @param {ReadableStream | NodeReadableStream | null} source\n * @returns {AsyncIterable}\n */\nconst fromStream = (source) => {\n if (isAsyncIterable(source)) {\n return source\n }\n\n // Workaround for https://github.com/node-fetch/node-fetch/issues/766\n if (isNodeReadableStream(source)) {\n const iter = source[Symbol.asyncIterator]()\n return {\n [Symbol.asyncIterator] () {\n return {\n next: iter.next.bind(iter),\n return (value) {\n source.destroy()\n if (typeof iter.return === 'function') {\n return iter.return()\n }\n return Promise.resolve({ done: true, value })\n }\n }\n }\n }\n }\n\n if (isWebReadableStream(source)) {\n const reader = source.getReader()\n return (async function * () {\n try {\n while (true) {\n // Read from the stream\n const { done, value } = await reader.read()\n // Exit if we're done\n if (done) return\n // Else yield the chunk\n if (value) {\n yield value\n }\n }\n } finally {\n reader.releaseLock()\n }\n })()\n }\n\n throw new TypeError('Body can\\'t be converted to AsyncIterable')\n}\n\n/**\n * Check if it's an AsyncIterable\n *\n * @template {unknown} TChunk\n * @template {any} Other\n * @param {Other|AsyncIterable} value\n * @returns {value is AsyncIterable}\n */\nconst isAsyncIterable = (value) => {\n return typeof value === 'object' &&\n value !== null &&\n typeof /** @type {any} */(value)[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Check for web readable stream\n *\n * @template {unknown} TChunk\n * @template {any} Other\n * @param {Other|ReadableStream} value\n * @returns {value is ReadableStream}\n */\nconst isWebReadableStream = (value) => {\n return value && typeof /** @type {any} */(value).getReader === 'function'\n}\n\n/**\n * @param {any} value\n * @returns {value is NodeReadableStream}\n */\nconst isNodeReadableStream = (value) =>\n Object.prototype.hasOwnProperty.call(value, 'readable') &&\n Object.prototype.hasOwnProperty.call(value, 'writable')\n\nHTTP.HTTPError = HTTPError\nHTTP.TimeoutError = TimeoutError\nHTTP.streamToAsyncIterator = fromStream\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.post = (resource, options) => new HTTP(options).post(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.get = (resource, options) => new HTTP(options).get(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.put = (resource, options) => new HTTP(options).put(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.delete = (resource, options) => new HTTP(options).delete(resource, options)\n\n/**\n * @param {string | Request} resource\n * @param {HTTPOptions} [options]\n */\nHTTP.options = (resource, options) => new HTTP(options).options(resource, options)\n\nmodule.exports = HTTP\n", "var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n 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 * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\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 global;\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 * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n// Deprecated equivalent of sha1WithRSAEncryption\n_IN('1.3.14.3.2.29', 'sha1WithRSASignature');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('2.16.840.1.101.3.4.2.4', 'sha224');\n_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');\n_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');\n_IN('1.2.840.113549.2.2', 'md2');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.4', 'surname');\n_IN('2.5.4.5', 'serialNumber');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.12', 'title');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('2.5.4.42', 'givenName');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n", "/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @throws Will throw an error for various malformed input conditions.\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n remaining -= length;\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n try {\n rval += forge.util.decodeUtf8(obj.value);\n } catch(e) {\n if(e.message === 'URI malformed') {\n rval +=\n '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';\n } else {\n throw e;\n }\n }\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n", "/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n", "/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n", "/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n", "/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n", "/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n", "/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\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 = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\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 * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n // accept \"NEW CERTIFICATE REQUEST\" as \"CERTIFICATE REQUEST\"\n // https://datatracker.ietf.org/doc/html/rfc7468#section-7\n var type = match[1];\n if(type === 'NEW CERTIFICATE REQUEST') {\n type = 'CERTIFICATE REQUEST';\n }\n\n var msg = {\n type: type,\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n", "/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _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 // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\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 = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\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 * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n", "/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0x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25, 0x55, 0x97, 0x31,\n 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n", "// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a 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\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n", "/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n", "/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\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 FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n", "/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n", "/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n // captured only to check existence for md2 and md5\n capture: 'parameters',\n optional: true,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme, options) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // see PKCS1-v1-5DigestAlgorithms in RFC 8017\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha224 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512 ||\n oid === forge.oids['sha512-224'] ||\n oid === forge.oids['sha512-256'])) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n // special check for md2 and md5 that NULL parameters exist\n if(oid === forge.oids.md2 || oid === forge.oids.md5) {\n if(!('parameters' in capture)) {\n throw new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value. ' +\n 'Missing algorithm identifer NULL parameters.');\n }\n }\n\n // compare the given digest to the decrypted one\n return digest === capture.digest;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n", "/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n", "/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _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\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\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 = 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 = 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 * 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 * 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", "/* 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 = 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", "export default function dlv(obj, key, def, p, undef) {\n\tkey = key.split ? key.split('.') : key;\n\tfor (p = 0; p < key.length; p++) {\n\t\tobj = obj ? obj[key[p]] : undef;\n\t}\n\treturn obj === undef ? def : obj;\n}\n", "'use strict'\n\n// Adapted from RFC 2181 (See section 11)\n//\n// The RFC defines a Domain Name to be at most 255 chars including seperators\n// between labels.\n// Subdomains are labels plus a seperator. A label is a string starting and\n// ending with an alphanum, with dashes allowed in the middle. It is between 1 and 63 chars.\n//\n// We make some assumptions below that go beyond the RFC. We assume the TLD\n// to be at least 2 chars. The regex also allows domains longer than 255 chars,\n// but allows at most 127 subdomains, as assuming a lower-bound of one char per\n// subdomain will yield 252, and adding a TLD of 2 chars sums to 254.\n/*\n(?: // Group 1: This is for subdomain, which is composed of a label and a seperator (length = [1, 63] + 1)\n [a-z0-9]\n (?:\n [a-z0-9\\-]{0,61} // Limited to 61 chars as we have at least two chars if we reach this group (61 + 2 = 63 which is the limit)\n [a-z0-9]\n )?\n \\. // Label seperator\n){0,126} // If we assume the lower-bound of 1 char labels, we can at most have 126 groups before approaching the total limit of 255 chars\n(?: // Group 2: Assume that the TLD is at least 2 chars (for sanity)\n [a-z0-9]\n [a-z0-9\\-]{0,61}\n [a-z0-9]\n)\n\\.? // Some consider a trailing dot to be considered valid as it signifies the root of the domain tree\n */\nvar domainNameRegex = /^(?:[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9])?\\.){0,126}(?:[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9]))\\.?$/i\n\n/**\n * Test whether a string is a valid domain name, optionally checking for a root dot as well\n * @param {String} domainName\n * @param {Boolean} rootDot Check for a root dot eg. 'example.com.'. Defaults to false\n * @return {Boolean}\n */\nmodule.exports = function isDomainName (domainName, rootDot) {\n if (rootDot == null) rootDot = false\n\n if (domainName.length < 2) return false\n if (domainName.length > 255) return false\n\n var lastChar = domainName[domainName.length - 1]\n if (rootDot) {\n if (lastChar !== '.') return false\n } else {\n if (lastChar === '.') return false\n }\n\n return domainNameRegex.test(domainName)\n}\n", "module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {\n encode.bytes = 0\n throw new RangeError('Could not encode varint')\n }\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\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 \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n", "module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\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)\n\nmodule.exports = function (value) {\n return (\n 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 )\n}\n", "module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\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", "module.exports = require('./lib/murmurHash3js');\n", "/**\n * Rabin fingerprinting\n *\n * @class Rabin\n */\nclass Rabin {\n /**\n * Creates an instance of Rabin.\n * @param { import(\"./../dist/rabin-wasm\") } asModule\n * @param {number} [bits=12]\n * @param {number} [min=8 * 1024]\n * @param {number} [max=32 * 1024]\n * @param {number} polynomial\n * @memberof Rabin\n */\n constructor(asModule, bits = 12, min = 8 * 1024, max = 32 * 1024, windowSize = 64, polynomial) {\n this.bits = bits\n this.min = min\n this.max = max\n this.asModule = asModule\n this.rabin = new asModule.Rabin(bits, min, max, windowSize, polynomial)\n this.polynomial = polynomial\n }\n\n /**\n * Fingerprints the buffer\n *\n * @param {Uint8Array} buf\n * @returns {Array}\n * @memberof Rabin\n */\n fingerprint(buf) {\n const {\n __retain,\n __release,\n __allocArray,\n __getInt32Array,\n Int32Array_ID,\n Uint8Array_ID\n } = this.asModule\n\n const lengths = new Int32Array(Math.ceil(buf.length/this.min))\n const lengthsPtr = __retain(__allocArray(Int32Array_ID, lengths))\n const pointer = __retain(__allocArray(Uint8Array_ID, buf))\n\n const out = this.rabin.fingerprint(pointer, lengthsPtr)\n const processed = __getInt32Array(out)\n\n __release(pointer)\n __release(lengthsPtr)\n\n const end = processed.indexOf(0);\n return end >= 0 ? processed.subarray(0, end) : processed;\n }\n}\n\nmodule.exports = Rabin", "\"use strict\";\n\n// Runtime header offsets\nconst ID_OFFSET = -8;\nconst SIZE_OFFSET = -4;\n\n// Runtime ids\nconst ARRAYBUFFER_ID = 0;\nconst STRING_ID = 1;\nconst ARRAYBUFFERVIEW_ID = 2;\n\n// Runtime type information\nconst ARRAYBUFFERVIEW = 1 << 0;\nconst ARRAY = 1 << 1;\nconst SET = 1 << 2;\nconst MAP = 1 << 3;\nconst VAL_ALIGN_OFFSET = 5;\nconst VAL_ALIGN = 1 << VAL_ALIGN_OFFSET;\nconst VAL_SIGNED = 1 << 10;\nconst VAL_FLOAT = 1 << 11;\nconst VAL_NULLABLE = 1 << 12;\nconst VAL_MANAGED = 1 << 13;\nconst KEY_ALIGN_OFFSET = 14;\nconst KEY_ALIGN = 1 << KEY_ALIGN_OFFSET;\nconst KEY_SIGNED = 1 << 19;\nconst KEY_FLOAT = 1 << 20;\nconst KEY_NULLABLE = 1 << 21;\nconst KEY_MANAGED = 1 << 22;\n\n// Array(BufferView) layout\nconst ARRAYBUFFERVIEW_BUFFER_OFFSET = 0;\nconst ARRAYBUFFERVIEW_DATASTART_OFFSET = 4;\nconst ARRAYBUFFERVIEW_DATALENGTH_OFFSET = 8;\nconst ARRAYBUFFERVIEW_SIZE = 12;\nconst ARRAY_LENGTH_OFFSET = 12;\nconst ARRAY_SIZE = 16;\n\nconst BIGINT = typeof BigUint64Array !== \"undefined\";\nconst THIS = Symbol();\nconst CHUNKSIZE = 1024;\n\n/** Gets a string from an U32 and an U16 view on a memory. */\nfunction getStringImpl(buffer, ptr) {\n const U32 = new Uint32Array(buffer);\n const U16 = new Uint16Array(buffer);\n var length = U32[(ptr + SIZE_OFFSET) >>> 2] >>> 1;\n var offset = ptr >>> 1;\n if (length <= CHUNKSIZE) return String.fromCharCode.apply(String, U16.subarray(offset, offset + length));\n const parts = [];\n do {\n const last = U16[offset + CHUNKSIZE - 1];\n const size = last >= 0xD800 && last < 0xDC00 ? CHUNKSIZE - 1 : CHUNKSIZE;\n parts.push(String.fromCharCode.apply(String, U16.subarray(offset, offset += size)));\n length -= size;\n } while (length > CHUNKSIZE);\n return parts.join(\"\") + String.fromCharCode.apply(String, U16.subarray(offset, offset + length));\n}\n\n/** Prepares the base module prior to instantiation. */\nfunction preInstantiate(imports) {\n const baseModule = {};\n\n function getString(memory, ptr) {\n if (!memory) return \"\";\n return getStringImpl(memory.buffer, ptr);\n }\n\n // add common imports used by stdlib for convenience\n const env = (imports.env = imports.env || {});\n env.abort = env.abort || function abort(mesg, file, line, colm) {\n const memory = baseModule.memory || env.memory; // prefer exported, otherwise try imported\n throw Error(\"abort: \" + getString(memory, mesg) + \" at \" + getString(memory, file) + \":\" + line + \":\" + colm);\n }\n env.trace = env.trace || function trace(mesg, n) {\n const memory = baseModule.memory || env.memory;\n console.log(\"trace: \" + getString(memory, mesg) + (n ? \" \" : \"\") + Array.prototype.slice.call(arguments, 2, 2 + n).join(\", \"));\n }\n imports.Math = imports.Math || Math;\n imports.Date = imports.Date || Date;\n\n return baseModule;\n}\n\n/** Prepares the final module once instantiation is complete. */\nfunction postInstantiate(baseModule, instance) {\n const rawExports = instance.exports;\n const memory = rawExports.memory;\n const table = rawExports.table;\n const alloc = rawExports[\"__alloc\"];\n const retain = rawExports[\"__retain\"];\n const rttiBase = rawExports[\"__rtti_base\"] || ~0; // oob if not present\n\n /** Gets the runtime type info for the given id. */\n function getInfo(id) {\n const U32 = new Uint32Array(memory.buffer);\n const count = U32[rttiBase >>> 2];\n if ((id >>>= 0) >= count) throw Error(\"invalid id: \" + id);\n return U32[(rttiBase + 4 >>> 2) + id * 2];\n }\n\n /** Gets the runtime base id for the given id. */\n function getBase(id) {\n const U32 = new Uint32Array(memory.buffer);\n const count = U32[rttiBase >>> 2];\n if ((id >>>= 0) >= count) throw Error(\"invalid id: \" + id);\n return U32[(rttiBase + 4 >>> 2) + id * 2 + 1];\n }\n\n /** Gets the runtime alignment of a collection's values. */\n function getValueAlign(info) {\n return 31 - Math.clz32((info >>> VAL_ALIGN_OFFSET) & 31); // -1 if none\n }\n\n /** Gets the runtime alignment of a collection's keys. */\n function getKeyAlign(info) {\n return 31 - Math.clz32((info >>> KEY_ALIGN_OFFSET) & 31); // -1 if none\n }\n\n /** Allocates a new string in the module's memory and returns its retained pointer. */\n function __allocString(str) {\n const length = str.length;\n const ptr = alloc(length << 1, STRING_ID);\n const U16 = new Uint16Array(memory.buffer);\n for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i);\n return ptr;\n }\n\n baseModule.__allocString = __allocString;\n\n /** Reads a string from the module's memory by its pointer. */\n function __getString(ptr) {\n const buffer = memory.buffer;\n const id = new Uint32Array(buffer)[ptr + ID_OFFSET >>> 2];\n if (id !== STRING_ID) throw Error(\"not a string: \" + ptr);\n return getStringImpl(buffer, ptr);\n }\n\n baseModule.__getString = __getString;\n\n /** Gets the view matching the specified alignment, signedness and floatness. */\n function getView(alignLog2, signed, float) {\n const buffer = memory.buffer;\n if (float) {\n switch (alignLog2) {\n case 2: return new Float32Array(buffer);\n case 3: return new Float64Array(buffer);\n }\n } else {\n switch (alignLog2) {\n case 0: return new (signed ? Int8Array : Uint8Array)(buffer);\n case 1: return new (signed ? Int16Array : Uint16Array)(buffer);\n case 2: return new (signed ? Int32Array : Uint32Array)(buffer);\n case 3: return new (signed ? BigInt64Array : BigUint64Array)(buffer);\n }\n }\n throw Error(\"unsupported align: \" + alignLog2);\n }\n\n /** Allocates a new array in the module's memory and returns its retained pointer. */\n function __allocArray(id, values) {\n const info = getInfo(id);\n if (!(info & (ARRAYBUFFERVIEW | ARRAY))) throw Error(\"not an array: \" + id + \" @ \" + info);\n const align = getValueAlign(info);\n const length = values.length;\n const buf = alloc(length << align, ARRAYBUFFER_ID);\n const arr = alloc(info & ARRAY ? ARRAY_SIZE : ARRAYBUFFERVIEW_SIZE, id);\n const U32 = new Uint32Array(memory.buffer);\n U32[arr + ARRAYBUFFERVIEW_BUFFER_OFFSET >>> 2] = retain(buf);\n U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2] = buf;\n U32[arr + ARRAYBUFFERVIEW_DATALENGTH_OFFSET >>> 2] = length << align;\n if (info & ARRAY) U32[arr + ARRAY_LENGTH_OFFSET >>> 2] = length;\n const view = getView(align, info & VAL_SIGNED, info & VAL_FLOAT);\n if (info & VAL_MANAGED) {\n for (let i = 0; i < length; ++i) view[(buf >>> align) + i] = retain(values[i]);\n } else {\n view.set(values, buf >>> align);\n }\n return arr;\n }\n\n baseModule.__allocArray = __allocArray;\n\n /** Gets a live view on an array's values in the module's memory. Infers the array type from RTTI. */\n function __getArrayView(arr) {\n const U32 = new Uint32Array(memory.buffer);\n const id = U32[arr + ID_OFFSET >>> 2];\n const info = getInfo(id);\n if (!(info & ARRAYBUFFERVIEW)) throw Error(\"not an array: \" + id);\n const align = getValueAlign(info);\n var buf = U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2];\n const length = info & ARRAY\n ? U32[arr + ARRAY_LENGTH_OFFSET >>> 2]\n : U32[buf + SIZE_OFFSET >>> 2] >>> align;\n return getView(align, info & VAL_SIGNED, info & VAL_FLOAT)\n .subarray(buf >>>= align, buf + length);\n }\n\n baseModule.__getArrayView = __getArrayView;\n\n /** Copies an array's values from the module's memory. Infers the array type from RTTI. */\n function __getArray(arr) {\n const input = __getArrayView(arr);\n const len = input.length;\n const out = new Array(len);\n for (let i = 0; i < len; i++) out[i] = input[i];\n return out;\n }\n\n baseModule.__getArray = __getArray;\n\n /** Copies an ArrayBuffer's value from the module's memory. */\n function __getArrayBuffer(ptr) {\n const buffer = memory.buffer;\n const length = new Uint32Array(buffer)[ptr + SIZE_OFFSET >>> 2];\n return buffer.slice(ptr, ptr + length);\n }\n\n baseModule.__getArrayBuffer = __getArrayBuffer;\n\n /** Copies a typed array's values from the module's memory. */\n function getTypedArray(Type, alignLog2, ptr) {\n return new Type(getTypedArrayView(Type, alignLog2, ptr));\n }\n\n /** Gets a live view on a typed array's values in the module's memory. */\n function getTypedArrayView(Type, alignLog2, ptr) {\n const buffer = memory.buffer;\n const U32 = new Uint32Array(buffer);\n const bufPtr = U32[ptr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2];\n return new Type(buffer, bufPtr, U32[bufPtr + SIZE_OFFSET >>> 2] >>> alignLog2);\n }\n\n baseModule.__getInt8Array = getTypedArray.bind(null, Int8Array, 0);\n baseModule.__getInt8ArrayView = getTypedArrayView.bind(null, Int8Array, 0);\n baseModule.__getUint8Array = getTypedArray.bind(null, Uint8Array, 0);\n baseModule.__getUint8ArrayView = getTypedArrayView.bind(null, Uint8Array, 0);\n baseModule.__getUint8ClampedArray = getTypedArray.bind(null, Uint8ClampedArray, 0);\n baseModule.__getUint8ClampedArrayView = getTypedArrayView.bind(null, Uint8ClampedArray, 0);\n baseModule.__getInt16Array = getTypedArray.bind(null, Int16Array, 1);\n baseModule.__getInt16ArrayView = getTypedArrayView.bind(null, Int16Array, 1);\n baseModule.__getUint16Array = getTypedArray.bind(null, Uint16Array, 1);\n baseModule.__getUint16ArrayView = getTypedArrayView.bind(null, Uint16Array, 1);\n baseModule.__getInt32Array = getTypedArray.bind(null, Int32Array, 2);\n baseModule.__getInt32ArrayView = getTypedArrayView.bind(null, Int32Array, 2);\n baseModule.__getUint32Array = getTypedArray.bind(null, Uint32Array, 2);\n baseModule.__getUint32ArrayView = getTypedArrayView.bind(null, Uint32Array, 2);\n if (BIGINT) {\n baseModule.__getInt64Array = getTypedArray.bind(null, BigInt64Array, 3);\n baseModule.__getInt64ArrayView = getTypedArrayView.bind(null, BigInt64Array, 3);\n baseModule.__getUint64Array = getTypedArray.bind(null, BigUint64Array, 3);\n baseModule.__getUint64ArrayView = getTypedArrayView.bind(null, BigUint64Array, 3);\n }\n baseModule.__getFloat32Array = getTypedArray.bind(null, Float32Array, 2);\n baseModule.__getFloat32ArrayView = getTypedArrayView.bind(null, Float32Array, 2);\n baseModule.__getFloat64Array = getTypedArray.bind(null, Float64Array, 3);\n baseModule.__getFloat64ArrayView = getTypedArrayView.bind(null, Float64Array, 3);\n\n /** Tests whether an object is an instance of the class represented by the specified base id. */\n function __instanceof(ptr, baseId) {\n const U32 = new Uint32Array(memory.buffer);\n var id = U32[(ptr + ID_OFFSET) >>> 2];\n if (id <= U32[rttiBase >>> 2]) {\n do if (id == baseId) return true;\n while (id = getBase(id));\n }\n return false;\n }\n\n baseModule.__instanceof = __instanceof;\n\n // Pull basic exports to baseModule so code in preInstantiate can use them\n baseModule.memory = baseModule.memory || memory;\n baseModule.table = baseModule.table || table;\n\n // Demangle exports and provide the usual utility on the prototype\n return demangle(rawExports, baseModule);\n}\n\nfunction isResponse(o) {\n return typeof Response !== \"undefined\" && o instanceof Response;\n}\n\n/** Asynchronously instantiates an AssemblyScript module from anything that can be instantiated. */\nasync function instantiate(source, imports) {\n if (isResponse(source = await source)) return instantiateStreaming(source, imports);\n return postInstantiate(\n preInstantiate(imports || (imports = {})),\n await WebAssembly.instantiate(\n source instanceof WebAssembly.Module\n ? source\n : await WebAssembly.compile(source),\n imports\n )\n );\n}\n\nexports.instantiate = instantiate;\n\n/** Synchronously instantiates an AssemblyScript module from a WebAssembly.Module or binary buffer. */\nfunction instantiateSync(source, imports) {\n return postInstantiate(\n preInstantiate(imports || (imports = {})),\n new WebAssembly.Instance(\n source instanceof WebAssembly.Module\n ? source\n : new WebAssembly.Module(source),\n imports\n )\n )\n}\n\nexports.instantiateSync = instantiateSync;\n\n/** Asynchronously instantiates an AssemblyScript module from a response, i.e. as obtained by `fetch`. */\nasync function instantiateStreaming(source, imports) {\n if (!WebAssembly.instantiateStreaming) {\n return instantiate(\n isResponse(source = await source)\n ? source.arrayBuffer()\n : source,\n imports\n );\n }\n return postInstantiate(\n preInstantiate(imports || (imports = {})),\n (await WebAssembly.instantiateStreaming(source, imports)).instance\n );\n}\n\nexports.instantiateStreaming = instantiateStreaming;\n\n/** Demangles an AssemblyScript module's exports to a friendly object structure. */\nfunction demangle(exports, baseModule) {\n var module = baseModule ? Object.create(baseModule) : {};\n var setArgumentsLength = exports[\"__argumentsLength\"]\n ? function(length) { exports[\"__argumentsLength\"].value = length; }\n : exports[\"__setArgumentsLength\"] || exports[\"__setargc\"] || function() {};\n for (let internalName in exports) {\n if (!Object.prototype.hasOwnProperty.call(exports, internalName)) continue;\n const elem = exports[internalName];\n let parts = internalName.split(\".\");\n let curr = module;\n while (parts.length > 1) {\n let part = parts.shift();\n if (!Object.prototype.hasOwnProperty.call(curr, part)) curr[part] = {};\n curr = curr[part];\n }\n let name = parts[0];\n let hash = name.indexOf(\"#\");\n if (hash >= 0) {\n let className = name.substring(0, hash);\n let classElem = curr[className];\n if (typeof classElem === \"undefined\" || !classElem.prototype) {\n let ctor = function(...args) {\n return ctor.wrap(ctor.prototype.constructor(0, ...args));\n };\n ctor.prototype = {\n valueOf: function valueOf() {\n return this[THIS];\n }\n };\n ctor.wrap = function(thisValue) {\n return Object.create(ctor.prototype, { [THIS]: { value: thisValue, writable: false } });\n };\n if (classElem) Object.getOwnPropertyNames(classElem).forEach(name =>\n Object.defineProperty(ctor, name, Object.getOwnPropertyDescriptor(classElem, name))\n );\n curr[className] = ctor;\n }\n name = name.substring(hash + 1);\n curr = curr[className].prototype;\n if (/^(get|set):/.test(name)) {\n if (!Object.prototype.hasOwnProperty.call(curr, name = name.substring(4))) {\n let getter = exports[internalName.replace(\"set:\", \"get:\")];\n let setter = exports[internalName.replace(\"get:\", \"set:\")];\n Object.defineProperty(curr, name, {\n get: function() { return getter(this[THIS]); },\n set: function(value) { setter(this[THIS], value); },\n enumerable: true\n });\n }\n } else {\n if (name === 'constructor') {\n (curr[name] = (...args) => {\n setArgumentsLength(args.length);\n return elem(...args);\n }).original = elem;\n } else { // instance method\n (curr[name] = function(...args) { // !\n setArgumentsLength(args.length);\n return elem(this[THIS], ...args);\n }).original = elem;\n }\n }\n } else {\n if (/^(get|set):/.test(name)) {\n if (!Object.prototype.hasOwnProperty.call(curr, name = name.substring(4))) {\n Object.defineProperty(curr, name, {\n get: exports[internalName.replace(\"set:\", \"get:\")],\n set: exports[internalName.replace(\"get:\", \"set:\")],\n enumerable: true\n });\n }\n } else if (typeof elem === \"function\" && elem !== setArgumentsLength) {\n (curr[name] = (...args) => {\n setArgumentsLength(args.length);\n return elem(...args);\n }).original = elem;\n } else {\n curr[name] = elem;\n }\n }\n }\n return module;\n}\n\nexports.demangle = demangle;\n", "\nconst { instantiate } = require(\"@assemblyscript/loader\");\n\nloadWebAssembly.supported = typeof WebAssembly !== 'undefined'\n\nfunction loadWebAssembly (imp = {}) {\n if (!loadWebAssembly.supported) return null\n \n var wasm = new Uint8Array([0,97,115,109,1,0,0,0,1,78,14,96,2,127,126,0,96,1,127,1,126,96,2,127,127,0,96,1,127,1,127,96,1,127,0,96,2,127,127,1,127,96,3,127,127,127,1,127,96,0,0,96,3,127,127,127,0,96,0,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,1,127,96,1,126,1,127,96,2,126,126,1,126,2,13,1,3,101,110,118,5,97,98,111,114,116,0,10,3,54,53,2,2,8,9,3,5,2,8,6,5,3,4,2,6,9,12,13,2,5,11,3,2,3,2,3,2,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,6,7,7,4,4,5,3,1,0,1,6,47,9,127,1,65,0,11,127,1,65,0,11,127,0,65,3,11,127,0,65,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,240,2,11,127,0,65,6,11,7,240,5,41,6,109,101,109,111,114,121,2,0,7,95,95,97,108,108,111,99,0,10,8,95,95,114,101,116,97,105,110,0,11,9,95,95,114,101,108,101,97,115,101,0,12,9,95,95,99,111,108,108,101,99,116,0,51,11,95,95,114,116,116,105,95,98,97,115,101,3,7,13,73,110,116,51,50,65,114,114,97,121,95,73,68,3,2,13,85,105,110,116,56,65,114,114,97,121,95,73,68,3,3,6,100,101,103,114,101,101,0,16,3,109,111,100,0,17,5,82,97,98,105,110,3,8,16,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,0,21,16,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,0,22,21,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,23,21,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,24,14,82,97,98,105,110,35,103,101,116,58,119,112,111,115,0,25,14,82,97,98,105,110,35,115,101,116,58,119,112,111,115,0,26,15,82,97,98,105,110,35,103,101,116,58,99,111,117,110,116,0,27,15,82,97,98,105,110,35,115,101,116,58,99,111,117,110,116,0,28,13,82,97,98,105,110,35,103,101,116,58,112,111,115,0,29,13,82,97,98,105,110,35,115,101,116,58,112,111,115,0,30,15,82,97,98,105,110,35,103,101,116,58,115,116,97,114,116,0,31,15,82,97,98,105,110,35,115,101,116,58,115,116,97,114,116,0,32,16,82,97,98,105,110,35,103,101,116,58,100,105,103,101,115,116,0,33,16,82,97,98,105,110,35,115,101,116,58,100,105,103,101,115,116,0,34,21,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,35,21,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,36,22,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,37,22,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,38,31,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,39,31,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,40,20,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,0,41,20,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,0,42,17,82,97,98,105,110,35,103,101,116,58,109,105,110,115,105,122,101,0,43,17,82,97,98,105,110,35,115,101,116,58,109,105,110,115,105,122,101,0,44,17,82,97,98,105,110,35,103,101,116,58,109,97,120,115,105,122,101,0,45,17,82,97,98,105,110,35,115,101,116,58,109,97,120,115,105,122,101,0,46,14,82,97,98,105,110,35,103,101,116,58,109,97,115,107,0,47,14,82,97,98,105,110,35,115,101,116,58,109,97,115,107,0,48,17,82,97,98,105,110,35,99,111,110,115,116,114,117,99,116,111,114,0,20,17,82,97,98,105,110,35,102,105,110,103,101,114,112,114,105,110,116,0,49,8,1,50,10,165,31,53,199,1,1,4,127,32,1,40,2,0,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,3,65,4,107,118,65,16,115,33,4,32,3,65,7,107,11,33,3,32,1,40,2,20,33,2,32,1,40,2,16,34,5,4,64,32,5,32,2,54,2,20,11,32,2,4,64,32,2,32,5,54,2,16,11,32,1,32,0,32,4,32,3,65,4,116,106,65,2,116,106,40,2,96,70,4,64,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,2,54,2,96,32,2,69,4,64,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,65,127,115,113,34,1,54,2,4,32,1,69,4,64,32,0,32,0,40,2,0,65,1,32,3,116,65,127,115,113,54,2,0,11,11,11,11,226,2,1,6,127,32,1,40,2,0,33,3,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,5,65,1,113,4,64,32,3,65,124,113,65,16,106,32,5,65,124,113,106,34,2,65,240,255,255,255,3,73,4,64,32,0,32,4,16,1,32,1,32,2,32,3,65,3,113,114,34,3,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,5,11,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,2,40,2,0,34,6,65,124,113,65,16,106,32,3,65,124,113,106,34,7,65,240,255,255,255,3,73,4,64,32,0,32,2,16,1,32,2,32,7,32,6,65,3,113,114,34,3,54,2,0,32,2,33,1,11,11,32,4,32,5,65,2,114,54,2,0,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,33,4,65,0,5,32,2,65,31,32,2,103,107,34,2,65,4,107,118,65,16,115,33,4,32,2,65,7,107,11,34,3,65,4,116,32,4,106,65,2,116,106,40,2,96,33,2,32,1,65,0,54,2,16,32,1,32,2,54,2,20,32,2,4,64,32,2,32,1,54,2,16,11,32,0,32,4,32,3,65,4,116,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,3,116,114,54,2,0,32,0,32,3,65,2,116,106,32,0,32,3,65,2,116,106,40,2,4,65,1,32,4,116,114,54,2,4,11,119,1,1,127,32,2,2,127,32,0,40,2,160,12,34,2,4,64,32,2,32,1,65,16,107,70,4,64,32,2,40,2,0,33,3,32,1,65,16,107,33,1,11,11,32,1,11,107,34,2,65,48,73,4,64,15,11,32,1,32,3,65,2,113,32,2,65,32,107,65,1,114,114,54,2,0,32,1,65,0,54,2,16,32,1,65,0,54,2,20,32,1,32,2,106,65,16,107,34,2,65,2,54,2,0,32,0,32,2,54,2,160,12,32,0,32,1,16,2,11,155,1,1,3,127,35,0,34,0,69,4,64,65,1,63,0,34,0,74,4,127,65,1,32,0,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,176,3,34,0,65,0,54,2,0,65,208,15,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,176,3,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,176,3,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,176,3,65,224,15,63,0,65,16,116,16,3,65,176,3,36,0,11,32,0,11,45,0,32,0,65,240,255,255,255,3,79,4,64,65,32,65,224,0,65,201,3,65,29,16,0,0,11,32,0,65,15,106,65,112,113,34,0,65,16,32,0,65,16,75,27,11,169,1,1,1,127,32,0,32,1,65,128,2,73,4,127,32,1,65,4,118,33,1,65,0,5,32,1,65,248,255,255,255,1,73,4,64,32,1,65,1,65,27,32,1,103,107,116,106,65,1,107,33,1,11,32,1,65,31,32,1,103,107,34,2,65,4,107,118,65,16,115,33,1,32,2,65,7,107,11,34,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,111,1,1,127,63,0,34,2,32,1,65,248,255,255,255,1,73,4,127,32,1,65,1,65,27,32,1,103,107,116,65,1,107,106,5,32,1,11,65,16,32,0,40,2,160,12,32,2,65,16,116,65,16,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,32,0,32,2,65,16,116,63,0,65,16,116,16,3,11,113,1,2,127,32,1,40,2,0,34,3,65,124,113,32,2,107,34,4,65,32,79,4,64,32,1,32,2,32,3,65,2,113,114,54,2,0,32,2,32,1,65,16,106,106,34,1,32,4,65,16,107,65,1,114,54,2,0,32,0,32,1,16,2,5,32,1,32,3,65,126,113,54,2,0,32,1,65,16,106,32,1,40,2,0,65,124,113,106,32,1,65,16,106,32,1,40,2,0,65,124,113,106,40,2,0,65,125,113,54,2,0,11,11,91,1,2,127,32,0,32,1,16,5,34,4,16,6,34,3,69,4,64,65,1,36,1,65,0,36,1,32,0,32,4,16,6,34,3,69,4,64,32,0,32,4,16,7,32,0,32,4,16,6,33,3,11,11,32,3,65,0,54,2,4,32,3,32,2,54,2,8,32,3,32,1,54,2,12,32,0,32,3,16,1,32,0,32,3,32,4,16,8,32,3,11,13,0,16,4,32,0,32,1,16,9,65,16,106,11,33,1,1,127,32,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,18,0,32,0,65,172,3,75,4,64,32,0,65,16,107,16,52,11,11,140,3,1,1,127,2,64,32,1,69,13,0,32,0,65,0,58,0,0,32,0,32,1,106,65,1,107,65,0,58,0,0,32,1,65,2,77,13,0,32,0,65,1,106,65,0,58,0,0,32,0,65,2,106,65,0,58,0,0,32,0,32,1,106,34,2,65,2,107,65,0,58,0,0,32,2,65,3,107,65,0,58,0,0,32,1,65,6,77,13,0,32,0,65,3,106,65,0,58,0,0,32,0,32,1,106,65,4,107,65,0,58,0,0,32,1,65,8,77,13,0,32,1,65,0,32,0,107,65,3,113,34,1,107,33,2,32,0,32,1,106,34,0,65,0,54,2,0,32,0,32,2,65,124,113,34,1,106,65,4,107,65,0,54,2,0,32,1,65,8,77,13,0,32,0,65,4,106,65,0,54,2,0,32,0,65,8,106,65,0,54,2,0,32,0,32,1,106,34,2,65,12,107,65,0,54,2,0,32,2,65,8,107,65,0,54,2,0,32,1,65,24,77,13,0,32,0,65,12,106,65,0,54,2,0,32,0,65,16,106,65,0,54,2,0,32,0,65,20,106,65,0,54,2,0,32,0,65,24,106,65,0,54,2,0,32,0,32,1,106,34,2,65,28,107,65,0,54,2,0,32,2,65,24,107,65,0,54,2,0,32,2,65,20,107,65,0,54,2,0,32,2,65,16,107,65,0,54,2,0,32,0,32,0,65,4,113,65,24,106,34,2,106,33,0,32,1,32,2,107,33,1,3,64,32,1,65,32,79,4,64,32,0,66,0,55,3,0,32,0,65,8,106,66,0,55,3,0,32,0,65,16,106,66,0,55,3,0,32,0,65,24,106,66,0,55,3,0,32,1,65,32,107,33,1,32,0,65,32,106,33,0,12,1,11,11,11,11,178,1,1,3,127,32,1,65,240,255,255,255,3,32,2,118,75,4,64,65,144,1,65,192,1,65,23,65,56,16,0,0,11,32,1,32,2,116,34,3,65,0,16,10,34,2,32,3,16,13,32,0,69,4,64,65,12,65,2,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,2,34,1,32,0,40,2,0,34,4,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,32,4,16,12,11,32,0,32,1,54,2,0,32,0,32,2,54,2,4,32,0,32,3,54,2,8,32,0,11,46,1,2,127,65,12,65,5,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,65,128,2,65,3,16,14,11,9,0,65,63,32,0,121,167,107,11,49,1,2,127,65,63,32,1,121,167,107,33,2,3,64,65,63,32,0,121,167,107,32,2,107,34,3,65,0,78,4,64,32,0,32,1,32,3,172,134,133,33,0,12,1,11,11,32,0,11,40,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,163,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,65,0,58,0,0,11,38,0,32,1,32,0,40,2,8,79,4,64,65,128,2,65,192,2,65,152,1,65,44,16,0,0,11,32,1,32,0,40,2,4,106,45,0,0,11,254,5,2,1,127,4,126,32,0,69,4,64,65,232,0,65,6,16,10,34,0,65,172,3,75,4,64,32,0,65,16,107,34,5,32,5,40,2,4,65,1,106,54,2,4,11,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,24,32,0,66,0,55,3,32,32,0,66,0,55,3,40,32,0,66,0,55,3,48,32,0,66,0,55,3,56,32,0,66,0,55,3,64,32,0,66,0,55,3,72,32,0,66,0,55,3,80,32,0,66,0,55,3,88,32,0,66,0,55,3,96,32,0,32,2,173,55,3,80,32,0,32,3,173,55,3,88,65,12,65,4,16,10,34,2,65,172,3,75,4,64,32,2,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,32,4,65,0,16,14,33,2,32,0,40,2,0,16,12,32,0,32,2,54,2,0,32,0,32,4,54,2,4,32,0,66,1,32,1,173,134,66,1,125,55,3,96,32,0,66,243,130,183,218,216,230,232,30,55,3,72,35,4,69,4,64,65,0,33,2,3,64,32,2,65,128,2,72,4,64,32,2,65,255,1,113,173,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,65,0,33,4,3,64,32,4,32,0,40,2,4,65,1,107,72,4,64,32,6,66,8,134,33,6,32,0,41,3,72,34,7,33,8,65,63,32,7,121,167,107,33,1,3,64,65,63,32,6,121,167,107,32,1,107,34,3,65,0,78,4,64,32,6,32,8,32,3,172,134,133,33,6,12,1,11,11,32,4,65,1,106,33,4,12,1,11,11,35,6,40,2,4,32,2,65,3,116,106,32,6,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,63,32,0,41,3,72,121,167,107,172,33,7,65,0,33,2,3,64,32,2,65,128,2,72,4,64,35,5,33,1,32,2,172,32,7,134,34,8,33,6,65,63,32,0,41,3,72,34,9,121,167,107,33,3,3,64,65,63,32,6,121,167,107,32,3,107,34,4,65,0,78,4,64,32,6,32,9,32,4,172,134,133,33,6,12,1,11,11,32,1,40,2,4,32,2,65,3,116,106,32,6,32,8,132,55,3,0,32,2,65,1,106,33,2,12,1,11,11,65,1,36,4,11,32,0,66,0,55,3,24,32,0,66,0,55,3,32,65,0,33,2,3,64,32,2,32,0,40,2,4,72,4,64,32,0,40,2,0,32,2,16,18,32,2,65,1,106,33,2,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,6,66,45,136,167,65,3,116,106,41,3,0,32,6,66,8,134,66,1,132,133,55,3,40,32,0,11,38,1,1,127,32,0,40,2,0,34,0,65,172,3,75,4,64,32,0,65,16,107,34,1,32,1,40,2,4,65,1,106,54,2,4,11,32,0,11,55,1,2,127,32,1,32,0,40,2,0,34,2,71,4,64,32,1,65,172,3,75,4,64,32,1,65,16,107,34,3,32,3,40,2,4,65,1,106,54,2,4,11,32,2,16,12,11,32,0,32,1,54,2,0,11,7,0,32,0,40,2,4,11,9,0,32,0,32,1,54,2,4,11,7,0,32,0,40,2,8,11,9,0,32,0,32,1,54,2,8,11,7,0,32,0,41,3,16,11,9,0,32,0,32,1,55,3,16,11,7,0,32,0,41,3,24,11,9,0,32,0,32,1,55,3,24,11,7,0,32,0,41,3,32,11,9,0,32,0,32,1,55,3,32,11,7,0,32,0,41,3,40,11,9,0,32,0,32,1,55,3,40,11,7,0,32,0,41,3,48,11,9,0,32,0,32,1,55,3,48,11,7,0,32,0,41,3,56,11,9,0,32,0,32,1,55,3,56,11,7,0,32,0,41,3,64,11,9,0,32,0,32,1,55,3,64,11,7,0,32,0,41,3,72,11,9,0,32,0,32,1,55,3,72,11,7,0,32,0,41,3,80,11,9,0,32,0,32,1,55,3,80,11,7,0,32,0,41,3,88,11,9,0,32,0,32,1,55,3,88,11,7,0,32,0,41,3,96,11,9,0,32,0,32,1,55,3,96,11,172,4,2,5,127,1,126,32,2,65,172,3,75,4,64,32,2,65,16,107,34,4,32,4,40,2,4,65,1,106,54,2,4,11,32,2,33,4,65,0,33,2,32,1,40,2,8,33,5,32,1,40,2,4,33,6,3,64,2,127,65,0,33,3,3,64,32,3,32,5,72,4,64,32,3,32,6,106,45,0,0,33,1,32,0,40,2,0,32,0,40,2,8,16,19,33,7,32,0,40,2,8,32,0,40,2,0,40,2,4,106,32,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,7,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,1,173,32,8,66,8,134,132,133,55,3,40,32,0,32,0,41,3,16,66,1,124,55,3,16,32,0,32,0,41,3,24,66,1,124,55,3,24,32,0,41,3,16,32,0,41,3,80,90,4,127,32,0,41,3,40,32,0,41,3,96,131,80,5,65,0,11,4,127,65,1,5,32,0,41,3,16,32,0,41,3,88,90,11,4,64,32,0,32,0,41,3,32,55,3,48,32,0,32,0,41,3,16,55,3,56,32,0,32,0,41,3,40,55,3,64,65,0,33,1,3,64,32,1,32,0,40,2,4,72,4,64,32,0,40,2,0,32,1,16,18,32,1,65,1,106,33,1,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,19,33,1,32,0,40,2,8,32,0,40,2,0,40,2,4,106,65,1,58,0,0,32,0,32,0,41,3,40,35,6,40,2,4,32,1,65,3,116,106,41,3,0,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,35,5,40,2,4,32,0,41,3,40,34,8,66,45,136,167,65,3,116,106,41,3,0,32,8,66,8,134,66,1,132,133,55,3,40,32,3,65,1,106,12,3,11,32,3,65,1,106,33,3,12,1,11,11,65,127,11,34,1,65,0,78,4,64,32,5,32,1,107,33,5,32,1,32,6,106,33,6,32,2,34,1,65,1,106,33,2,32,4,40,2,4,32,1,65,2,116,106,32,0,41,3,56,62,2,0,12,1,11,11,32,4,11,10,0,16,15,36,5,16,15,36,6,11,3,0,1,11,73,1,2,127,32,0,40,2,4,34,1,65,255,255,255,255,0,113,34,2,65,1,70,4,64,32,0,65,16,106,16,53,32,0,32,0,40,2,0,65,1,114,54,2,0,35,0,32,0,16,2,5,32,0,32,2,65,1,107,32,1,65,128,128,128,128,127,113,114,54,2,4,11,11,58,0,2,64,2,64,2,64,32,0,65,8,107,40,2,0,14,7,0,0,1,1,1,1,1,2,11,15,11,32,0,40,2,0,34,0,4,64,32,0,65,172,3,79,4,64,32,0,65,16,107,16,52,11,11,15,11,0,11,11,137,3,7,0,65,16,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,208,0,11,45,30,0,0,0,1,0,0,0,1,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,128,1,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,176,1,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,240,1,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,176,2,11,51,36,0,0,0,1,0,0,0,1,0,0,0,36,0,0,0,126,0,108,0,105,0,98,0,47,0,116,0,121,0,112,0,101,0,100,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,240,2,11,53,7,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,145,4,0,0,2,0,0,0,49,0,0,0,2,0,0,0,17,1,0,0,2,0,0,0,16,0,34,16,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,16,46,47,114,97,98,105,110,46,119,97,115,109,46,109,97,112])\n // make it work async because browsers throw when a wasm module is bigger than 4kb and load sync\n return instantiate(new Response(new Blob([wasm], {type: 'application/wasm'})), imp)\n}\nmodule.exports = loadWebAssembly\n", "const Rabin = require('./rabin')\nconst getRabin = require('../dist/rabin-wasm.node.js')\n\nconst create = async (avg, min, max, windowSize, polynomial) => {\n const compiled = await getRabin()\n return new Rabin(compiled, avg, min, max, windowSize, polynomial)\n}\n\nmodule.exports = {\n Rabin,\n create\n}\n", "'use strict'\n\n// JS treats subjects of bitwise operators as SIGNED 32 bit numbers,\n// which means the maximum amount of bits we can store inside each byte\n// is 7..\nconst BITS_PER_BYTE = 7\n\nmodule.exports = class SparseArray {\n constructor () {\n this._bitArrays = []\n this._data = []\n this._length = 0\n this._changedLength = false\n this._changedData = false\n }\n\n set (index, value) {\n let pos = this._internalPositionFor(index, false)\n if (value === undefined) {\n // unsetting\n if (pos !== -1) {\n // remove item from bit array and array itself\n this._unsetInternalPos(pos)\n this._unsetBit(index)\n this._changedLength = true\n this._changedData = true\n }\n } else {\n let needsSort = false\n if (pos === -1) {\n pos = this._data.length\n this._setBit(index)\n this._changedData = true\n } else {\n needsSort = true\n }\n this._setInternalPos(pos, index, value, needsSort)\n this._changedLength = true\n }\n }\n\n unset (index) {\n this.set(index, undefined)\n }\n\n get (index) {\n this._sortData()\n const pos = this._internalPositionFor(index, true)\n if (pos === -1) {\n return undefined\n }\n return this._data[pos][1]\n }\n\n push (value) {\n this.set(this.length, value)\n return this.length\n }\n\n get length () {\n this._sortData()\n if (this._changedLength) {\n const last = this._data[this._data.length - 1]\n this._length = last ? last[0] + 1 : 0\n this._changedLength = false\n }\n return this._length\n }\n\n forEach (iterator) {\n let i = 0\n while(i < this.length) {\n iterator(this.get(i), i, this)\n i++\n }\n }\n\n map (iterator) {\n let i = 0\n let mapped = new Array(this.length)\n while(i < this.length) {\n mapped[i] = iterator(this.get(i), i, this)\n i++\n }\n return mapped\n }\n\n reduce (reducer, initialValue) {\n let i = 0\n let acc = initialValue\n while(i < this.length) {\n const value = this.get(i)\n acc = reducer(acc, value, i)\n i++\n }\n return acc\n }\n\n find (finder) {\n let i = 0, found, last\n while ((i < this.length) && !found) {\n last = this.get(i)\n found = finder(last)\n i++\n }\n return found ? last : undefined\n }\n\n _internalPositionFor (index, noCreate) {\n const bytePos = this._bytePosFor(index, noCreate)\n if (bytePos >= this._bitArrays.length) {\n return -1\n }\n const byte = this._bitArrays[bytePos]\n const bitPos = index - bytePos * BITS_PER_BYTE\n const exists = (byte & (1 << bitPos)) > 0\n if (!exists) {\n return -1\n }\n const previousPopCount = this._bitArrays.slice(0, bytePos).reduce(popCountReduce, 0)\n\n const mask = ~(0xffffffff << (bitPos + 1))\n const bytePopCount = popCount(byte & mask)\n const arrayPos = previousPopCount + bytePopCount - 1\n return arrayPos\n }\n\n _bytePosFor (index, noCreate) {\n const bytePos = Math.floor(index / BITS_PER_BYTE)\n const targetLength = bytePos + 1\n while (!noCreate && this._bitArrays.length < targetLength) {\n this._bitArrays.push(0)\n }\n return bytePos\n }\n\n _setBit (index) {\n const bytePos = this._bytePosFor(index, false)\n this._bitArrays[bytePos] |= (1 << (index - (bytePos * BITS_PER_BYTE)))\n }\n\n _unsetBit(index) {\n const bytePos = this._bytePosFor(index, false)\n this._bitArrays[bytePos] &= ~(1 << (index - (bytePos * BITS_PER_BYTE)))\n }\n\n _setInternalPos(pos, index, value, needsSort) {\n const data =this._data\n const elem = [index, value]\n if (needsSort) {\n this._sortData()\n data[pos] = elem\n } else {\n // new element. just shove it into the array\n // but be nice about where we shove it\n // in order to make sorting it later easier\n if (data.length) {\n if (data[data.length - 1][0] >= index) {\n data.push(elem)\n } else if (data[0][0] <= index) {\n data.unshift(elem)\n } else {\n const randomIndex = Math.round(data.length / 2)\n this._data = data.slice(0, randomIndex).concat(elem).concat(data.slice(randomIndex))\n }\n } else {\n this._data.push(elem)\n }\n this._changedData = true\n this._changedLength = true\n }\n }\n\n _unsetInternalPos (pos) {\n this._data.splice(pos, 1)\n }\n\n _sortData () {\n if (this._changedData) {\n this._data.sort(sortInternal)\n }\n\n this._changedData = false\n }\n\n bitField () {\n const bytes = []\n let pendingBitsForResultingByte = 8\n let pendingBitsForNewByte = 0\n let resultingByte = 0\n let newByte\n const pending = this._bitArrays.slice()\n while (pending.length || pendingBitsForNewByte) {\n if (pendingBitsForNewByte === 0) {\n newByte = pending.shift()\n pendingBitsForNewByte = 7\n }\n\n const usingBits = Math.min(pendingBitsForNewByte, pendingBitsForResultingByte)\n const mask = ~(0b11111111 << usingBits)\n const masked = newByte & mask\n resultingByte |= masked << (8 - pendingBitsForResultingByte)\n newByte = newByte >>> usingBits\n pendingBitsForNewByte -= usingBits\n pendingBitsForResultingByte -= usingBits\n\n if (!pendingBitsForResultingByte || (!pendingBitsForNewByte && !pending.length)) {\n bytes.push(resultingByte)\n resultingByte = 0\n pendingBitsForResultingByte = 8\n }\n }\n\n // remove trailing zeroes\n for(var i = bytes.length - 1; i > 0; i--) {\n const value = bytes[i]\n if (value === 0) {\n bytes.pop()\n } else {\n break\n }\n }\n\n return bytes\n }\n\n compactArray () {\n this._sortData()\n return this._data.map(valueOnly)\n }\n}\n\nfunction popCountReduce (count, byte) {\n return count + popCount(byte)\n}\n\nfunction popCount(_v) {\n let v = _v\n v = v - ((v >> 1) & 0x55555555) // reuse input as temporary\n v = (v & 0x33333333) + ((v >> 2) & 0x33333333) // temp\n return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24\n}\n\nfunction sortInternal (a, b) {\n return a[0] - b[0]\n}\n\nfunction valueOnly (elem) {\n return elem[1]\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", "\n'use strict';\n\nmodule.exports = {\n 'RTLD_LAZY': 1,\n 'RTLD_NOW': 2,\n 'RTLD_GLOBAL': 8,\n 'RTLD_LOCAL': 4,\n 'E2BIG': 7,\n 'EACCES': 13,\n 'EADDRINUSE': 48,\n 'EADDRNOTAVAIL': 49,\n 'EAFNOSUPPORT': 47,\n 'EAGAIN': 35,\n 'EALREADY': 37,\n 'EBADF': 9,\n 'EBADMSG': 94,\n 'EBUSY': 16,\n 'ECANCELED': 89,\n 'ECHILD': 10,\n 'ECONNABORTED': 53,\n 'ECONNREFUSED': 61,\n 'ECONNRESET': 54,\n 'EDEADLK': 11,\n 'EDESTADDRREQ': 39,\n 'EDOM': 33,\n 'EDQUOT': 69,\n 'EEXIST': 17,\n 'EFAULT': 14,\n 'EFBIG': 27,\n 'EHOSTUNREACH': 65,\n 'EIDRM': 90,\n 'EILSEQ': 92,\n 'EINPROGRESS': 36,\n 'EINTR': 4,\n 'EINVAL': 22,\n 'EIO': 5,\n 'EISCONN': 56,\n 'EISDIR': 21,\n 'ELOOP': 62,\n 'EMFILE': 24,\n 'EMLINK': 31,\n 'EMSGSIZE': 40,\n 'EMULTIHOP': 95,\n 'ENAMETOOLONG': 63,\n 'ENETDOWN': 50,\n 'ENETRESET': 52,\n 'ENETUNREACH': 51,\n 'ENFILE': 23,\n 'ENOBUFS': 55,\n 'ENODATA': 96,\n 'ENODEV': 19,\n 'ENOENT': 2,\n 'ENOEXEC': 8,\n 'ENOLCK': 77,\n 'ENOLINK': 97,\n 'ENOMEM': 12,\n 'ENOMSG': 91,\n 'ENOPROTOOPT': 42,\n 'ENOSPC': 28,\n 'ENOSR': 98,\n 'ENOSTR': 99,\n 'ENOSYS': 78,\n 'ENOTCONN': 57,\n 'ENOTDIR': 20,\n 'ENOTEMPTY': 66,\n 'ENOTSOCK': 38,\n 'ENOTSUP': 45,\n 'ENOTTY': 25,\n 'ENXIO': 6,\n 'EOPNOTSUPP': 102,\n 'EOVERFLOW': 84,\n 'EPERM': 1,\n 'EPIPE': 32,\n 'EPROTO': 100,\n 'EPROTONOSUPPORT': 43,\n 'EPROTOTYPE': 41,\n 'ERANGE': 34,\n 'EROFS': 30,\n 'ESPIPE': 29,\n 'ESRCH': 3,\n 'ESTALE': 70,\n 'ETIME': 101,\n 'ETIMEDOUT': 60,\n 'ETXTBSY': 26,\n 'EWOULDBLOCK': 35,\n 'EXDEV': 18,\n 'PRIORITY_LOW': 19,\n 'PRIORITY_BELOW_NORMAL': 10,\n 'PRIORITY_NORMAL': 0,\n 'PRIORITY_ABOVE_NORMAL': -7,\n 'PRIORITY_HIGH': -14,\n 'PRIORITY_HIGHEST': -20,\n 'SIGHUP': 1,\n 'SIGINT': 2,\n 'SIGQUIT': 3,\n 'SIGILL': 4,\n 'SIGTRAP': 5,\n 'SIGABRT': 6,\n 'SIGIOT': 6,\n 'SIGBUS': 10,\n 'SIGFPE': 8,\n 'SIGKILL': 9,\n 'SIGUSR1': 30,\n 'SIGSEGV': 11,\n 'SIGUSR2': 31,\n 'SIGPIPE': 13,\n 'SIGALRM': 14,\n 'SIGTERM': 15,\n 'SIGCHLD': 20,\n 'SIGCONT': 19,\n 'SIGSTOP': 17,\n 'SIGTSTP': 18,\n 'SIGTTIN': 21,\n 'SIGTTOU': 22,\n 'SIGURG': 16,\n 'SIGXCPU': 24,\n 'SIGXFSZ': 25,\n 'SIGVTALRM': 26,\n 'SIGPROF': 27,\n 'SIGWINCH': 28,\n 'SIGIO': 23,\n 'SIGINFO': 29,\n 'SIGSYS': 12,\n 'UV_FS_SYMLINK_DIR': 1,\n 'UV_FS_SYMLINK_JUNCTION': 2,\n 'O_RDONLY': 0,\n 'O_WRONLY': 1,\n 'O_RDWR': 2,\n 'UV_DIRENT_UNKNOWN': 0,\n 'UV_DIRENT_FILE': 1,\n 'UV_DIRENT_DIR': 2,\n 'UV_DIRENT_LINK': 3,\n 'UV_DIRENT_FIFO': 4,\n 'UV_DIRENT_SOCKET': 5,\n 'UV_DIRENT_CHAR': 6,\n 'UV_DIRENT_BLOCK': 7,\n 'S_IFMT': 61440,\n 'S_IFREG': 32768,\n 'S_IFDIR': 16384,\n 'S_IFCHR': 8192,\n 'S_IFBLK': 24576,\n 'S_IFIFO': 4096,\n 'S_IFLNK': 40960,\n 'S_IFSOCK': 49152,\n 'O_CREAT': 512,\n 'O_EXCL': 2048,\n 'UV_FS_O_FILEMAP': 0,\n 'O_NOCTTY': 131072,\n 'O_TRUNC': 1024,\n 'O_APPEND': 8,\n 'O_DIRECTORY': 1048576,\n 'O_NOFOLLOW': 256,\n 'O_SYNC': 128,\n 'O_DSYNC': 4194304,\n 'O_SYMLINK': 2097152,\n 'O_NONBLOCK': 4,\n 'S_IRWXU': 448,\n 'S_IRUSR': 256,\n 'S_IWUSR': 128,\n 'S_IXUSR': 64,\n 'S_IRWXG': 56,\n 'S_IRGRP': 32,\n 'S_IWGRP': 16,\n 'S_IXGRP': 8,\n 'S_IRWXO': 7,\n 'S_IROTH': 4,\n 'S_IWOTH': 2,\n 'S_IXOTH': 1,\n 'F_OK': 0,\n 'R_OK': 4,\n 'W_OK': 2,\n 'X_OK': 1,\n 'UV_FS_COPYFILE_EXCL': 1,\n 'COPYFILE_EXCL': 1,\n 'UV_FS_COPYFILE_FICLONE': 2,\n 'COPYFILE_FICLONE': 2,\n 'UV_FS_COPYFILE_FICLONE_FORCE': 4,\n 'COPYFILE_FICLONE_FORCE': 4,\n 'OPENSSL_VERSION_NUMBER': 805306480,\n 'SSL_OP_ALL': 2147485776,\n 'SSL_OP_ALLOW_NO_DHE_KEX': 1024,\n 'SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION': 262144,\n 'SSL_OP_CIPHER_SERVER_PREFERENCE': 4194304,\n 'SSL_OP_CISCO_ANYCONNECT': 32768,\n 'SSL_OP_COOKIE_EXCHANGE': 8192,\n 'SSL_OP_CRYPTOPRO_TLSEXT_BUG': 2147483648,\n 'SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS': 2048,\n 'SSL_OP_EPHEMERAL_RSA': 0,\n 'SSL_OP_LEGACY_SERVER_CONNECT': 4,\n 'SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER': 0,\n 'SSL_OP_MICROSOFT_SESS_ID_BUG': 0,\n 'SSL_OP_MSIE_SSLV2_RSA_PADDING': 0,\n 'SSL_OP_NETSCAPE_CA_DN_BUG': 0,\n 'SSL_OP_NETSCAPE_CHALLENGE_BUG': 0,\n 'SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG': 0,\n 'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG': 0,\n 'SSL_OP_NO_COMPRESSION': 131072,\n 'SSL_OP_NO_ENCRYPT_THEN_MAC': 524288,\n 'SSL_OP_NO_QUERY_MTU': 4096,\n 'SSL_OP_NO_RENEGOTIATION': 1073741824,\n 'SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION': 65536,\n 'SSL_OP_NO_SSLv2': 0,\n 'SSL_OP_NO_SSLv3': 33554432,\n 'SSL_OP_NO_TICKET': 16384,\n 'SSL_OP_NO_TLSv1': 67108864,\n 'SSL_OP_NO_TLSv1_1': 268435456,\n 'SSL_OP_NO_TLSv1_2': 134217728,\n 'SSL_OP_NO_TLSv1_3': 536870912,\n 'SSL_OP_PKCS1_CHECK_1': 0,\n 'SSL_OP_PKCS1_CHECK_2': 0,\n 'SSL_OP_PRIORITIZE_CHACHA': 2097152,\n 'SSL_OP_SINGLE_DH_USE': 0,\n 'SSL_OP_SINGLE_ECDH_USE': 0,\n 'SSL_OP_SSLEAY_080_CLIENT_DH_BUG': 0,\n 'SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG': 0,\n 'SSL_OP_TLS_BLOCK_PADDING_BUG': 0,\n 'SSL_OP_TLS_D5_BUG': 0,\n 'SSL_OP_TLS_ROLLBACK_BUG': 8388608,\n 'ENGINE_METHOD_RSA': 1,\n 'ENGINE_METHOD_DSA': 2,\n 'ENGINE_METHOD_DH': 4,\n 'ENGINE_METHOD_RAND': 8,\n 'ENGINE_METHOD_EC': 2048,\n 'ENGINE_METHOD_CIPHERS': 64,\n 'ENGINE_METHOD_DIGESTS': 128,\n 'ENGINE_METHOD_PKEY_METHS': 512,\n 'ENGINE_METHOD_PKEY_ASN1_METHS': 1024,\n 'ENGINE_METHOD_ALL': 65535,\n 'ENGINE_METHOD_NONE': 0,\n 'DH_CHECK_P_NOT_SAFE_PRIME': 2,\n 'DH_CHECK_P_NOT_PRIME': 1,\n 'DH_UNABLE_TO_CHECK_GENERATOR': 4,\n 'DH_NOT_SUITABLE_GENERATOR': 8,\n 'ALPN_ENABLED': 1,\n 'RSA_PKCS1_PADDING': 1,\n 'RSA_NO_PADDING': 3,\n 'RSA_PKCS1_OAEP_PADDING': 4,\n 'RSA_X931_PADDING': 5,\n 'RSA_PKCS1_PSS_PADDING': 6,\n 'RSA_PSS_SALTLEN_DIGEST': -1,\n 'RSA_PSS_SALTLEN_MAX_SIGN': -2,\n 'RSA_PSS_SALTLEN_AUTO': -2,\n 'defaultCoreCipherList': 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA',\n 'TLS1_VERSION': 769,\n 'TLS1_1_VERSION': 770,\n 'TLS1_2_VERSION': 771,\n 'TLS1_3_VERSION': 772,\n 'POINT_CONVERSION_COMPRESSED': 2,\n 'POINT_CONVERSION_UNCOMPRESSED': 4,\n 'POINT_CONVERSION_HYBRID': 6,\n 'defaultCipherList': 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA'\n};\n\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * FNV-1a hash generation init value.\n * It's exposed, because this allows user to override it.\n * More info: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV_hash_parameters\n *\n * @type {number}\n */\nhash.BASE = 0x811c9dc5;\n/**\n * Generates 32 bit FNV-1a hash from the given string.\n * As explained here: http://isthe.com/chongo/tech/comp/fnv/\n *\n * @param s {string} String to generate hash from.\n * @param [h] {number} FNV-1a hash generation init value.\n * @returns {number} The result integer hash.\n */\nfunction hash(s, h = hash.BASE) {\n const l = s.length;\n for (let i = 0; i < l; i++) {\n h ^= s.charCodeAt(i);\n h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);\n }\n return h >>> 0;\n}\nexports.default = hash;\nmodule.exports = hash;\n", "/*!\n * bytes\n * Copyright(c) 2012-2014 TJ Holowaychuk\n * Copyright(c) 2015 Jed Watson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = bytes;\nmodule.exports.format = format;\nmodule.exports.parse = parse;\n\n/**\n * Module variables.\n * @private\n */\n\nvar formatThousandsRegExp = /\\B(?=(\\d{3})+(?!\\d))/g;\n\nvar formatDecimalsRegExp = /(?:\\.0*|(\\.[^0]+)0+)$/;\n\nvar map = {\n b: 1,\n kb: 1 << 10,\n mb: 1 << 20,\n gb: 1 << 30,\n tb: Math.pow(1024, 4),\n pb: Math.pow(1024, 5),\n};\n\nvar parseRegExp = /^((-|\\+)?(\\d+(?:\\.\\d+)?)) *(kb|mb|gb|tb|pb)$/i;\n\n/**\n * Convert the given value in bytes into a string or parse to string to an integer in bytes.\n *\n * @param {string|number} value\n * @param {{\n * case: [string],\n * decimalPlaces: [number]\n * fixedDecimals: [boolean]\n * thousandsSeparator: [string]\n * unitSeparator: [string]\n * }} [options] bytes options.\n *\n * @returns {string|number|null}\n */\n\nfunction bytes(value, options) {\n if (typeof value === 'string') {\n return parse(value);\n }\n\n if (typeof value === 'number') {\n return format(value, options);\n }\n\n return null;\n}\n\n/**\n * Format the given value in bytes into a string.\n *\n * If the value is negative, it is kept as such. If it is a float,\n * it is rounded.\n *\n * @param {number} value\n * @param {object} [options]\n * @param {number} [options.decimalPlaces=2]\n * @param {number} [options.fixedDecimals=false]\n * @param {string} [options.thousandsSeparator=]\n * @param {string} [options.unit=]\n * @param {string} [options.unitSeparator=]\n *\n * @returns {string|null}\n * @public\n */\n\nfunction format(value, options) {\n if (!Number.isFinite(value)) {\n return null;\n }\n\n var mag = Math.abs(value);\n var thousandsSeparator = (options && options.thousandsSeparator) || '';\n var unitSeparator = (options && options.unitSeparator) || '';\n var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;\n var fixedDecimals = Boolean(options && options.fixedDecimals);\n var unit = (options && options.unit) || '';\n\n if (!unit || !map[unit.toLowerCase()]) {\n if (mag >= map.pb) {\n unit = 'PB';\n } else if (mag >= map.tb) {\n unit = 'TB';\n } else if (mag >= map.gb) {\n unit = 'GB';\n } else if (mag >= map.mb) {\n unit = 'MB';\n } else if (mag >= map.kb) {\n unit = 'KB';\n } else {\n unit = 'B';\n }\n }\n\n var val = value / map[unit.toLowerCase()];\n var str = val.toFixed(decimalPlaces);\n\n if (!fixedDecimals) {\n str = str.replace(formatDecimalsRegExp, '$1');\n }\n\n if (thousandsSeparator) {\n str = str.split('.').map(function (s, i) {\n return i === 0\n ? s.replace(formatThousandsRegExp, thousandsSeparator)\n : s\n }).join('.');\n }\n\n return str + unitSeparator + unit;\n}\n\n/**\n * Parse the string value into an integer in bytes.\n *\n * If no unit is given, it is assumed the value is in bytes.\n *\n * @param {number|string} val\n *\n * @returns {number|null}\n * @public\n */\n\nfunction parse(val) {\n if (typeof val === 'number' && !isNaN(val)) {\n return val;\n }\n\n if (typeof val !== 'string') {\n return null;\n }\n\n // Test if the string passed is valid\n var results = parseRegExp.exec(val);\n var floatValue;\n var unit = 'b';\n\n if (!results) {\n // Nothing could be extracted from the given string\n floatValue = parseInt(val, 10);\n unit = 'b'\n } else {\n // Retrieve the value and the unit\n floatValue = parseFloat(results[1]);\n unit = results[4].toLowerCase();\n }\n\n if (isNaN(floatValue)) {\n return null;\n }\n\n return Math.floor(map[unit] * floatValue);\n}\n", "'use strict'\n\nexports.supports = function supports (...manifests) {\n const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {})\n\n return Object.assign(manifest, {\n snapshots: manifest.snapshots || false,\n permanence: manifest.permanence || false,\n seek: manifest.seek || false,\n clear: manifest.clear || false,\n getMany: manifest.getMany || false,\n keyIterator: manifest.keyIterator || false,\n valueIterator: manifest.valueIterator || false,\n iteratorNextv: manifest.iteratorNextv || false,\n iteratorAll: manifest.iteratorAll || false,\n status: manifest.status || false,\n createIfMissing: manifest.createIfMissing || false,\n errorIfExists: manifest.errorIfExists || false,\n deferredOpen: manifest.deferredOpen || false,\n promises: manifest.promises || false,\n streams: manifest.streams || false,\n encodings: Object.assign({}, manifest.encodings),\n events: Object.assign({}, manifest.events),\n additionalMethods: Object.assign({}, manifest.additionalMethods)\n })\n}\n", "'use strict'\n\nmodule.exports = class ModuleError extends Error {\n /**\n * @param {string} message Error message\n * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]\n */\n constructor (message, options) {\n super(message || '')\n\n if (typeof options === 'object' && options !== null) {\n if (options.code) this.code = String(options.code)\n if (options.expected) this.expected = true\n if (options.transient) this.transient = true\n if (options.cause) this.cause = options.cause\n }\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n}\n", "'use strict'\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", "/*! 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 * 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'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\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", "'use strict'\n\n/** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */\nlet lazy = null\n\n/**\n * Get semi-global instances of TextEncoder and TextDecoder.\n * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}\n */\nmodule.exports = function () {\n if (lazy === null) {\n lazy = {\n textEncoder: new TextEncoder(),\n textDecoder: new TextDecoder()\n }\n }\n\n return lazy\n}\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst formats = new Set(['buffer', 'view', 'utf8'])\n\n/**\n * @template TIn, TFormat, TOut\n * @abstract\n */\nclass Encoding {\n /**\n * @param {IEncoding} options\n */\n constructor (options) {\n /** @type {(data: TIn) => TFormat} */\n this.encode = options.encode || this.encode\n\n /** @type {(data: TFormat) => TOut} */\n this.decode = options.decode || this.decode\n\n /** @type {string} */\n this.name = options.name || this.name\n\n /** @type {string} */\n this.format = options.format || this.format\n\n if (typeof this.encode !== 'function') {\n throw new TypeError(\"The 'encode' property must be a function\")\n }\n\n if (typeof this.decode !== 'function') {\n throw new TypeError(\"The 'decode' property must be a function\")\n }\n\n this.encode = this.encode.bind(this)\n this.decode = this.decode.bind(this)\n\n if (typeof this.name !== 'string' || this.name === '') {\n throw new TypeError(\"The 'name' property must be a string\")\n }\n\n if (typeof this.format !== 'string' || !formats.has(this.format)) {\n throw new TypeError(\"The 'format' property must be one of 'buffer', 'view', 'utf8'\")\n }\n\n if (options.createViewTranscoder) {\n this.createViewTranscoder = options.createViewTranscoder\n }\n\n if (options.createBufferTranscoder) {\n this.createBufferTranscoder = options.createBufferTranscoder\n }\n\n if (options.createUTF8Transcoder) {\n this.createUTF8Transcoder = options.createUTF8Transcoder\n }\n }\n\n get commonName () {\n return /** @type {string} */ (this.name.split('+')[0])\n }\n\n /** @return {BufferFormat} */\n createBufferTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {ViewFormat} */\n createViewTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'view'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {UTF8Format} */\n createUTF8Transcoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n}\n\nexports.Encoding = Encoding\n\n/**\n * @typedef {import('./encoding').IEncoding} IEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @typedef {import('./formats').BufferFormat} BufferFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').ViewFormat} ViewFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').UTF8Format} UTF8Format\n * @template TIn, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || {}\nconst { Encoding } = require('./encoding')\nconst textEndec = require('./text-endec')\n\n/**\n * @template TIn, TOut\n * @extends {Encoding}\n */\nclass BufferFormat extends Encoding {\n /**\n * @param {Omit, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'buffer' })\n }\n\n /** @override */\n createViewTranscoder () {\n return new ViewFormat({\n encode: this.encode, // Buffer is a view (UInt8Array)\n decode: (data) => this.decode(\n Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n ),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createBufferTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding}\n * @template TIn, TOut\n */\nclass ViewFormat extends Encoding {\n /**\n * @param {Omit, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'view' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => {\n const view = this.encode(data)\n return Buffer.from(view.buffer, view.byteOffset, view.byteLength)\n },\n decode: this.decode, // Buffer is a view (UInt8Array)\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding}\n * @template TIn, TOut\n */\nclass UTF8Format extends Encoding {\n /**\n * @param {Omit, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'utf8' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => Buffer.from(this.encode(data), 'utf8'),\n decode: (data) => this.decode(data.toString('utf8')),\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n const { textEncoder, textDecoder } = textEndec()\n\n return new ViewFormat({\n encode: (data) => textEncoder.encode(this.encode(data)),\n decode: (data) => this.decode(textDecoder.decode(data)),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createUTF8Transcoder () {\n return this\n }\n}\n\nexports.BufferFormat = BufferFormat\nexports.ViewFormat = ViewFormat\nexports.UTF8Format = UTF8Format\n\n/**\n * @typedef {import('./encoding').IEncoding} IEncoding\n * @template TIn, TFormat, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || { Buffer: { isBuffer: () => false } }\nconst { textEncoder, textDecoder } = require('./text-endec')()\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./formats')\n\n/** @type {(v: T) => v} */\nconst identity = (v) => v\n\n/**\n * @type {typeof import('./encodings').utf8}\n */\nexports.utf8 = new UTF8Format({\n encode: function (data) {\n // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder\n return Buffer.isBuffer(data)\n ? data.toString('utf8')\n : ArrayBuffer.isView(data)\n ? textDecoder.decode(data)\n : String(data)\n },\n decode: identity,\n name: 'utf8',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: function (data) {\n return textDecoder.decode(data)\n },\n name: `${this.name}+view`\n })\n },\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return data.toString('utf8')\n },\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').json}\n */\nexports.json = new UTF8Format({\n encode: JSON.stringify,\n decode: JSON.parse,\n name: 'json'\n})\n\n/**\n * @type {typeof import('./encodings').buffer}\n */\nexports.buffer = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: 'buffer',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n },\n name: `${this.name}+view`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').view}\n */\nexports.view = new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: identity,\n name: 'view',\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').hex}\n */\nexports.hex = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')\n },\n decode: function (buffer) {\n return buffer.toString('hex')\n },\n name: 'hex'\n})\n\n/**\n * @type {typeof import('./encodings').base64}\n */\nexports.base64 = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')\n },\n decode: function (buffer) {\n return buffer.toString('base64')\n },\n name: 'base64'\n})\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst encodings = require('./lib/encodings')\nconst { Encoding } = require('./lib/encoding')\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./lib/formats')\n\nconst kFormats = Symbol('formats')\nconst kEncodings = Symbol('encodings')\nconst validFormats = new Set(['buffer', 'view', 'utf8'])\n\n/** @template T */\nclass Transcoder {\n /**\n * @param {Array<'buffer'|'view'|'utf8'>} formats\n */\n constructor (formats) {\n if (!Array.isArray(formats)) {\n throw new TypeError(\"The first argument 'formats' must be an array\")\n } else if (!formats.every(f => validFormats.has(f))) {\n // Note: we only only support aliases in key- and valueEncoding options (where we already did)\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n\n /** @type {Map, Encoding>} */\n this[kEncodings] = new Map()\n this[kFormats] = new Set(formats)\n\n // Register encodings (done early in order to populate encodings())\n for (const k in encodings) {\n try {\n this.encoding(k)\n } catch (err) {\n /* istanbul ignore if: assertion */\n if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err\n }\n }\n }\n\n /**\n * @returns {Array>}\n */\n encodings () {\n return Array.from(new Set(this[kEncodings].values()))\n }\n\n /**\n * @param {string|MixedEncoding} encoding\n * @returns {Encoding}\n */\n encoding (encoding) {\n let resolved = this[kEncodings].get(encoding)\n\n if (resolved === undefined) {\n if (typeof encoding === 'string' && encoding !== '') {\n resolved = lookup[encoding]\n\n if (!resolved) {\n throw new ModuleError(`Encoding '${encoding}' is not found`, {\n code: 'LEVEL_ENCODING_NOT_FOUND'\n })\n }\n } else if (typeof encoding !== 'object' || encoding === null) {\n throw new TypeError(\"First argument 'encoding' must be a string or object\")\n } else {\n resolved = from(encoding)\n }\n\n const { name, format } = resolved\n\n if (!this[kFormats].has(format)) {\n if (this[kFormats].has('view')) {\n resolved = resolved.createViewTranscoder()\n } else if (this[kFormats].has('buffer')) {\n resolved = resolved.createBufferTranscoder()\n } else if (this[kFormats].has('utf8')) {\n resolved = resolved.createUTF8Transcoder()\n } else {\n throw new ModuleError(`Encoding '${name}' cannot be transcoded`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n }\n\n for (const k of [encoding, name, resolved.name, resolved.commonName]) {\n this[kEncodings].set(k, resolved)\n }\n }\n\n return resolved\n }\n}\n\nexports.Transcoder = Transcoder\n\n/**\n * @param {MixedEncoding} options\n * @returns {Encoding}\n */\nfunction from (options) {\n if (options instanceof Encoding) {\n return options\n }\n\n // Loosely typed for ecosystem compatibility\n const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined\n const name = options.name || maybeType || `anonymous-${anonymousCount++}`\n\n switch (detectFormat(options)) {\n case 'view': return new ViewFormat({ ...options, name })\n case 'utf8': return new UTF8Format({ ...options, name })\n case 'buffer': return new BufferFormat({ ...options, name })\n default: {\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n }\n}\n\n/**\n * If format is not provided, fallback to detecting `level-codec`\n * or `multiformats` encodings, else assume a format of buffer.\n * @param {MixedEncoding} options\n * @returns {string}\n */\nfunction detectFormat (options) {\n if ('format' in options && options.format !== undefined) {\n return options.format\n } else if ('buffer' in options && typeof options.buffer === 'boolean') {\n return options.buffer ? 'buffer' : 'utf8' // level-codec\n } else if ('code' in options && Number.isInteger(options.code)) {\n return 'view' // multiformats\n } else {\n return 'buffer'\n }\n}\n\n/**\n * @typedef {import('./lib/encoding').MixedEncoding} MixedEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @type {Object.>}\n */\nconst aliases = {\n binary: encodings.buffer,\n 'utf-8': encodings.utf8\n}\n\n/**\n * @type {Object.>}\n */\nconst lookup = {\n ...encodings,\n ...aliases\n}\n\nlet anonymousCount = 0\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'use strict';\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", "module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)\n", "'use strict'\n\nvar nextTick = require('./next-tick')\n\nexports.fromCallback = function (callback, symbol) {\n if (callback === undefined) {\n var promise = new Promise(function (resolve, reject) {\n callback = function (err, res) {\n if (err) reject(err)\n else resolve(res)\n }\n })\n\n callback[symbol !== undefined ? symbol : 'promise'] = promise\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n return callback\n}\n\nexports.fromPromise = function (promise, callback) {\n if (callback === undefined) return promise\n\n promise\n .then(function (res) { nextTick(() => callback(null, res)) })\n .catch(function (err) { nextTick(() => callback(err)) })\n}\n", "'use strict'\n\nexports.getCallback = function (options, callback) {\n return typeof options === 'function' ? options : callback\n}\n\nexports.getOptions = function (options, def) {\n if (typeof options === 'object' && options !== null) {\n return options\n }\n\n if (def !== undefined) {\n return def\n }\n\n return {}\n}\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getOptions, getCallback } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kCallback = Symbol('callback')\nconst kWorking = Symbol('working')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kAutoClose = Symbol('autoClose')\nconst kFinishWork = Symbol('finishWork')\nconst kReturnMany = Symbol('returnMany')\nconst kClosing = Symbol('closing')\nconst kHandleClose = Symbol('handleClose')\nconst kClosed = Symbol('closed')\nconst kCloseCallbacks = Symbol('closeCallbacks')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst kAbortOnClose = Symbol('abortOnClose')\nconst kLegacy = Symbol('legacy')\nconst kKeys = Symbol('keys')\nconst kValues = Symbol('values')\nconst kLimit = Symbol('limit')\nconst kCount = Symbol('count')\n\nconst emptyOptions = Object.freeze({})\nconst noop = () => {}\nlet warnedEnd = false\n\n// This class is an internal utility for common functionality between AbstractIterator,\n// AbstractKeyIterator and AbstractValueIterator. It's not exported.\nclass CommonIterator {\n constructor (db, options, legacy) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('The second argument must be an options object')\n }\n\n this[kClosed] = false\n this[kCloseCallbacks] = []\n this[kWorking] = false\n this[kClosing] = false\n this[kAutoClose] = false\n this[kCallback] = null\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kHandleClose] = this[kHandleClose].bind(this)\n this[kKeyEncoding] = options[kKeyEncoding]\n this[kValueEncoding] = options[kValueEncoding]\n this[kLegacy] = legacy\n this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity\n this[kCount] = 0\n\n // Undocumented option to abort pending work on close(). Used by the\n // many-level module as a temporary solution to a blocked close().\n // TODO (next major): consider making this the default behavior. Native\n // implementations should have their own logic to safely close iterators.\n this[kAbortOnClose] = !!options.abortOnClose\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get count () {\n return this[kCount]\n }\n\n get limit () {\n return this[kLimit]\n }\n\n next (callback) {\n let promise\n\n if (callback === undefined) {\n promise = new Promise((resolve, reject) => {\n callback = (err, key, value) => {\n if (err) reject(err)\n else if (!this[kLegacy]) resolve(key)\n else if (key === undefined && value === undefined) resolve()\n else resolve([key, value])\n }\n })\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call next() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne], null)\n else this._next(this[kHandleOne])\n }\n\n return promise\n }\n\n _next (callback) {\n this.nextTick(callback)\n }\n\n nextv (size, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (!Number.isInteger(size)) {\n this.nextTick(callback, new TypeError(\"The first argument 'size' must be an integer\"))\n return callback[kPromise]\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call nextv() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n if (size < 1) size = 1\n if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount])\n\n this[kWorking] = true\n this[kCallback] = callback\n\n if (size <= 0) this.nextTick(this[kHandleMany], null, [])\n else this._nextv(size, options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _nextv (size, options, callback) {\n const acc = []\n const onnext = (err, key, value) => {\n if (err) {\n return callback(err)\n } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {\n return callback(null, acc)\n }\n\n acc.push(this[kLegacy] ? [key, value] : key)\n\n if (acc.length === size) {\n callback(null, acc)\n } else {\n this._next(onnext)\n }\n }\n\n this._next(onnext)\n }\n\n all (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call all() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n this[kAutoClose] = true\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany], null, [])\n else this._all(options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _all (options, callback) {\n // Must count here because we're directly calling _nextv()\n let count = this[kCount]\n const acc = []\n\n const nextv = () => {\n // Not configurable, because implementations should optimize _all().\n const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3\n\n if (size <= 0) {\n this.nextTick(callback, null, acc)\n } else {\n this._nextv(size, emptyOptions, onnextv)\n }\n }\n\n const onnextv = (err, items) => {\n if (err) {\n callback(err)\n } else if (items.length === 0) {\n callback(null, acc)\n } else {\n acc.push.apply(acc, items)\n count += items.length\n nextv()\n }\n }\n\n nextv()\n }\n\n [kFinishWork] () {\n const cb = this[kCallback]\n\n // Callback will be null if work was aborted on close\n if (this[kAbortOnClose] && cb === null) return noop\n\n this[kWorking] = false\n this[kCallback] = null\n\n if (this[kClosing]) this._close(this[kHandleClose])\n\n return cb\n }\n\n [kReturnMany] (cb, err, items) {\n if (this[kAutoClose]) {\n this.close(cb.bind(null, err, items))\n } else {\n cb(err, items)\n }\n }\n\n seek (target, options) {\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n // Don't throw here, to be kind to implementations that wrap\n // another db and don't necessarily control when the db is closed\n } else if (this[kWorking]) {\n throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n })\n } else {\n const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding])\n const keyFormat = keyEncoding.format\n\n if (options.keyEncoding !== keyFormat) {\n options = { ...options, keyEncoding: keyFormat }\n }\n\n const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat)\n this._seek(mapped, options)\n }\n }\n\n _seek (target, options) {\n throw new ModuleError('Iterator does not support seek()', {\n code: 'LEVEL_NOT_SUPPORTED'\n })\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kClosed]) {\n this.nextTick(callback)\n } else if (this[kClosing]) {\n this[kCloseCallbacks].push(callback)\n } else {\n this[kClosing] = true\n this[kCloseCallbacks].push(callback)\n\n if (!this[kWorking]) {\n this._close(this[kHandleClose])\n } else if (this[kAbortOnClose]) {\n // Don't wait for work to finish. Subsequently ignore the result.\n const cb = this[kFinishWork]()\n\n cb(new ModuleError('Aborted on iterator close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kHandleClose] () {\n this[kClosed] = true\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n\n async * [Symbol.asyncIterator] () {\n try {\n let item\n\n while ((item = (await this.next())) !== undefined) {\n yield item\n }\n } finally {\n if (!this[kClosed]) await this.close()\n }\n }\n}\n\n// For backwards compatibility this class is not (yet) called AbstractEntryIterator.\nclass AbstractIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, true)\n this[kKeys] = options.keys !== false\n this[kValues] = options.values !== false\n }\n\n [kHandleOne] (err, key, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n value = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('entry', err))\n }\n\n if (!(key === undefined && value === undefined)) {\n this[kCount]++\n }\n\n cb(null, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (const entry of entries) {\n const key = entry[0]\n const value = entry[1]\n\n entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('entries', err))\n }\n\n this[kCount] += entries.length\n this[kReturnMany](cb, null, entries)\n }\n\n end (callback) {\n if (!warnedEnd && typeof console !== 'undefined') {\n warnedEnd = true\n console.warn(new ModuleError(\n 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',\n { code: 'LEVEL_LEGACY' }\n ))\n }\n\n return this.close(callback)\n }\n}\n\nclass AbstractKeyIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, key) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('key', err))\n }\n\n if (key !== undefined) this[kCount]++\n cb(null, key)\n }\n\n [kHandleMany] (err, keys) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n keys[i] = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('keys', err))\n }\n\n this[kCount] += keys.length\n this[kReturnMany](cb, null, keys)\n }\n}\n\nclass AbstractValueIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n value = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('value', err))\n }\n\n if (value !== undefined) this[kCount]++\n cb(null, value)\n }\n\n [kHandleMany] (err, values) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n values[i] = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('values', err))\n }\n\n this[kCount] += values.length\n this[kReturnMany](cb, null, values)\n }\n}\n\n// Internal utility, not typed or exported\nclass IteratorDecodeError extends ModuleError {\n constructor (subject, cause) {\n super(`Iterator could not decode ${subject}`, {\n code: 'LEVEL_DECODE_ERROR',\n cause\n })\n }\n}\n\n// To help migrating to abstract-level\nfor (const k of ['_ended property', '_nexting property', '_end method']) {\n Object.defineProperty(AbstractIterator.prototype, k.split(' ')[0], {\n get () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },\n set () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }\n })\n}\n\n// Exposed so that AbstractLevel can set these options\nAbstractIterator.keyEncoding = kKeyEncoding\nAbstractIterator.valueEncoding = kValueEncoding\n\nexports.AbstractIterator = AbstractIterator\nexports.AbstractKeyIterator = AbstractKeyIterator\nexports.AbstractValueIterator = AbstractValueIterator\n", "'use strict'\n\nconst { AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kIterator = Symbol('iterator')\nconst kCallback = Symbol('callback')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\n\nclass DefaultKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: true, values: false })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nclass DefaultValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: false, values: true })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nfor (const Iterator of [DefaultKeyIterator, DefaultValueIterator]) {\n const keys = Iterator === DefaultKeyIterator\n const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1]\n\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype[kHandleOne] = function (err, key, value) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, keys ? key : value)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n\n Iterator.prototype[kHandleMany] = function (err, entries) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, entries.map(mapEntry))\n }\n\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\n// Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator\nexports.DefaultKeyIterator = DefaultKeyIterator\nexports.DefaultValueIterator = DefaultValueIterator\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\nconst ModuleError = require('module-error')\n\nconst kNut = Symbol('nut')\nconst kUndefer = Symbol('undefer')\nconst kFactory = Symbol('factory')\n\nclass DeferredIterator extends AbstractIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.iterator(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.keys(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.values(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nfor (const Iterator of [DeferredIterator, DeferredKeyIterator, DeferredValueIterator]) {\n Iterator.prototype[kUndefer] = function () {\n if (this.db.status === 'open') {\n this[kNut] = this[kFactory]()\n }\n }\n\n Iterator.prototype._next = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].next(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._next(callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n if (this[kNut] !== null) {\n this[kNut].nextv(size, options, callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._nextv(size, options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._all = function (options, callback) {\n if (this[kNut] !== null) {\n this[kNut].all(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._all(options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._seek = function (target, options) {\n if (this[kNut] !== null) {\n // TODO: explain why we need _seek() rather than seek() here\n this[kNut]._seek(target, options)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._seek(target, options))\n }\n }\n\n Iterator.prototype._close = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].close(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._close(callback))\n } else {\n this.nextTick(callback)\n }\n }\n}\n\nexports.DeferredIterator = DeferredIterator\nexports.DeferredKeyIterator = DeferredKeyIterator\nexports.DeferredValueIterator = DeferredValueIterator\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getCallback, getOptions } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kStatus = Symbol('status')\nconst kOperations = Symbol('operations')\nconst kFinishClose = Symbol('finishClose')\nconst kCloseCallbacks = Symbol('closeCallbacks')\n\nclass AbstractChainedBatch {\n constructor (db) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n this[kOperations] = []\n this[kCloseCallbacks] = []\n this[kStatus] = 'open'\n this[kFinishClose] = this[kFinishClose].bind(this)\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get length () {\n return this[kOperations].length\n }\n\n put (key, value, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call put() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key) || this.db._checkValue(value)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const valueEncoding = db.valueEncoding(options && options.valueEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options)\n this[kOperations].push({ ...original, type: 'put', key, value })\n\n return this\n }\n\n _put (key, value, options) {}\n\n del (key, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call del() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options)\n this[kOperations].push({ ...original, type: 'del', key })\n\n return this\n }\n\n _del (key, options) {}\n\n clear () {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call clear() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n this._clear()\n this[kOperations] = []\n\n return this\n }\n\n _clear () {}\n\n write (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options)\n\n if (this[kStatus] !== 'open') {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n } else if (this.length === 0) {\n this.close(callback)\n } else {\n this[kStatus] = 'writing'\n this._write(options, (err) => {\n this[kStatus] = 'closing'\n this[kCloseCallbacks].push(() => callback(err))\n\n // Emit after setting 'closing' status, because event may trigger a\n // db close which in turn triggers (idempotently) closing this batch.\n if (!err) this.db.emit('batch', this[kOperations])\n\n this._close(this[kFinishClose])\n })\n }\n\n return callback[kPromise]\n }\n\n _write (options, callback) {}\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kStatus] === 'closing') {\n this[kCloseCallbacks].push(callback)\n } else if (this[kStatus] === 'closed') {\n this.nextTick(callback)\n } else {\n this[kCloseCallbacks].push(callback)\n\n if (this[kStatus] !== 'writing') {\n this[kStatus] = 'closing'\n this._close(this[kFinishClose])\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kFinishClose] () {\n this[kStatus] = 'closed'\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n}\n\nexports.AbstractChainedBatch = AbstractChainedBatch\n", "'use strict'\n\nconst { AbstractChainedBatch } = require('../abstract-chained-batch')\nconst ModuleError = require('module-error')\nconst kEncoded = Symbol('encoded')\n\n// Functional default for chained batch, with support of deferred open\nclass DefaultChainedBatch extends AbstractChainedBatch {\n constructor (db) {\n super(db)\n this[kEncoded] = []\n }\n\n _put (key, value, options) {\n this[kEncoded].push({ ...options, type: 'put', key, value })\n }\n\n _del (key, options) {\n this[kEncoded].push({ ...options, type: 'del', key })\n }\n\n _clear () {\n this[kEncoded] = []\n }\n\n // Assumes this[kEncoded] cannot change after write()\n _write (options, callback) {\n if (this.db.status === 'opening') {\n this.db.defer(() => this._write(options, callback))\n } else if (this.db.status === 'open') {\n if (this[kEncoded].length === 0) this.nextTick(callback)\n else this.db._batch(this[kEncoded], options, callback)\n } else {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n }\n }\n}\n\nexports.DefaultChainedBatch = DefaultChainedBatch\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst rangeOptions = new Set(['lt', 'lte', 'gt', 'gte'])\n\nmodule.exports = function (options, keyEncoding) {\n const result = {}\n\n for (const k in options) {\n if (!hasOwnProperty.call(options, k)) continue\n if (k === 'keyEncoding' || k === 'valueEncoding') continue\n\n if (k === 'start' || k === 'end') {\n throw new ModuleError(`The legacy range option '${k}' has been removed`, {\n code: 'LEVEL_LEGACY'\n })\n } else if (k === 'encoding') {\n // To help migrating to abstract-level\n throw new ModuleError(\"The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead\", {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (rangeOptions.has(k)) {\n // Note that we don't reject nullish and empty options here. While\n // those types are invalid as keys, they are valid as range options.\n result[k] = keyEncoding.encode(options[k])\n } else {\n result[k] = options[k]\n }\n }\n\n result.reverse = !!result.reverse\n result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1\n\n return result\n}\n", "/*! queue-microtask. MIT License. Feross Aboukhadijeh */\nlet promise\n\nmodule.exports = typeof queueMicrotask === 'function'\n ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)\n // reuse resolved promise, and allocate it lazily\n : cb => (promise || (promise = Promise.resolve()))\n .then(cb)\n .catch(err => setTimeout(() => { throw err }, 0))\n", "'use strict'\n\nconst queueMicrotask = require('queue-microtask')\n\nmodule.exports = function (fn, ...args) {\n if (args.length === 0) {\n queueMicrotask(fn)\n } else {\n queueMicrotask(() => fn(...args))\n }\n}\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kUnfix = Symbol('unfix')\nconst kIterator = Symbol('iterator')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kCallback = Symbol('callback')\n\n// TODO: unfix natively if db supports it\nclass AbstractSublevelIterator extends AbstractIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key, value) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (const entry of entries) {\n const key = entry[0]\n if (key !== undefined) entry[0] = this[kUnfix](key)\n }\n\n callback(err, entries)\n }\n}\n\nclass AbstractSublevelKeyIterator extends AbstractKeyIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key)\n }\n\n [kHandleMany] (err, keys) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n if (key !== undefined) keys[i] = this[kUnfix](key)\n }\n\n callback(err, keys)\n }\n}\n\nclass AbstractSublevelValueIterator extends AbstractValueIterator {\n constructor (db, options, iterator) {\n super(db, options)\n this[kIterator] = iterator\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n}\n\nfor (const Iterator of [AbstractSublevelValueIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kIterator].next(callback)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kIterator].nextv(size, options, callback)\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kIterator].all(options, callback)\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\nexports.AbstractSublevelIterator = AbstractSublevelIterator\nexports.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator\nexports.AbstractSublevelValueIterator = AbstractSublevelValueIterator\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst { Buffer } = require('buffer') || {}\nconst {\n AbstractSublevelIterator,\n AbstractSublevelKeyIterator,\n AbstractSublevelValueIterator\n} = require('./abstract-sublevel-iterator')\n\nconst kPrefix = Symbol('prefix')\nconst kUpperBound = Symbol('upperBound')\nconst kPrefixRange = Symbol('prefixRange')\nconst kParent = Symbol('parent')\nconst kUnfix = Symbol('unfix')\n\nconst textEncoder = new TextEncoder()\nconst defaults = { separator: '!' }\n\n// Wrapped to avoid circular dependency\nmodule.exports = function ({ AbstractLevel }) {\n class AbstractSublevel extends AbstractLevel {\n static defaults (options) {\n // To help migrating from subleveldown to abstract-level\n if (typeof options === 'string') {\n throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {\n code: 'LEVEL_LEGACY'\n })\n } else if (options && options.open) {\n throw new ModuleError('The subleveldown open option has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (options == null) {\n return defaults\n } else if (!options.separator) {\n return { ...options, separator: '!' }\n } else {\n return options\n }\n }\n\n // TODO: add autoClose option, which if true, does parent.attachResource(this)\n constructor (db, name, options) {\n // Don't forward AbstractSublevel options to AbstractLevel\n const { separator, manifest, ...forward } = AbstractSublevel.defaults(options)\n name = trim(name, separator)\n\n // Reserve one character between separator and name to give us an upper bound\n const reserved = separator.charCodeAt(0) + 1\n const parent = db[kParent] || db\n\n // Keys should sort like ['!a!', '!a!!a!', '!a\"', '!aa!', '!b!'].\n // Use ASCII for consistent length between string, Buffer and Uint8Array\n if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {\n throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {\n code: 'LEVEL_INVALID_PREFIX'\n })\n }\n\n super(mergeManifests(parent, manifest), forward)\n\n const prefix = (db.prefix || '') + separator + name + separator\n const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved)\n\n this[kParent] = parent\n this[kPrefix] = new MultiFormat(prefix)\n this[kUpperBound] = new MultiFormat(upperBound)\n this[kUnfix] = new Unfixer()\n\n this.nextTick = parent.nextTick\n }\n\n prefixKey (key, keyFormat) {\n if (keyFormat === 'utf8') {\n return this[kPrefix].utf8 + key\n } else if (key.byteLength === 0) {\n // Fast path for empty key (no copy)\n return this[kPrefix][keyFormat]\n } else if (keyFormat === 'view') {\n const view = this[kPrefix].view\n const result = new Uint8Array(view.byteLength + key.byteLength)\n\n result.set(view, 0)\n result.set(key, view.byteLength)\n\n return result\n } else {\n const buffer = this[kPrefix].buffer\n return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)\n }\n }\n\n // Not exposed for now.\n [kPrefixRange] (range, keyFormat) {\n if (range.gte !== undefined) {\n range.gte = this.prefixKey(range.gte, keyFormat)\n } else if (range.gt !== undefined) {\n range.gt = this.prefixKey(range.gt, keyFormat)\n } else {\n range.gte = this[kPrefix][keyFormat]\n }\n\n if (range.lte !== undefined) {\n range.lte = this.prefixKey(range.lte, keyFormat)\n } else if (range.lt !== undefined) {\n range.lt = this.prefixKey(range.lt, keyFormat)\n } else {\n range.lte = this[kUpperBound][keyFormat]\n }\n }\n\n get prefix () {\n return this[kPrefix].utf8\n }\n\n get db () {\n return this[kParent]\n }\n\n _open (options, callback) {\n // The parent db must open itself or be (re)opened by the user because\n // a sublevel should not initiate state changes on the rest of the db.\n this[kParent].open({ passive: true }, callback)\n }\n\n _put (key, value, options, callback) {\n this[kParent].put(key, value, options, callback)\n }\n\n _get (key, options, callback) {\n this[kParent].get(key, options, callback)\n }\n\n _getMany (keys, options, callback) {\n this[kParent].getMany(keys, options, callback)\n }\n\n _del (key, options, callback) {\n this[kParent].del(key, options, callback)\n }\n\n _batch (operations, options, callback) {\n this[kParent].batch(operations, options, callback)\n }\n\n _clear (options, callback) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n this[kParent].clear(options, callback)\n }\n\n _iterator (options) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].iterator(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelIterator(this, options, iterator, unfix)\n }\n\n _keys (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].keys(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelKeyIterator(this, options, iterator, unfix)\n }\n\n _values (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].values(options)\n return new AbstractSublevelValueIterator(this, options, iterator)\n }\n }\n\n return { AbstractSublevel }\n}\n\nconst mergeManifests = function (parent, manifest) {\n return {\n // Inherit manifest of parent db\n ...parent.supports,\n\n // Disable unsupported features\n createIfMissing: false,\n errorIfExists: false,\n\n // Unset additional events because we're not forwarding them\n events: {},\n\n // Unset additional methods (like approximateSize) which we can't support here unless\n // the AbstractSublevel class is overridden by an implementation of `abstract-level`.\n additionalMethods: {},\n\n // Inherit manifest of custom AbstractSublevel subclass. Such a class is not\n // allowed to override encodings.\n ...manifest,\n\n encodings: {\n utf8: supportsEncoding(parent, 'utf8'),\n buffer: supportsEncoding(parent, 'buffer'),\n view: supportsEncoding(parent, 'view')\n }\n }\n}\n\nconst supportsEncoding = function (parent, encoding) {\n // Prefer a non-transcoded encoding for optimal performance\n return parent.supports.encodings[encoding]\n ? parent.keyEncoding(encoding).name === encoding\n : false\n}\n\nclass MultiFormat {\n constructor (key) {\n this.utf8 = key\n this.view = textEncoder.encode(key)\n this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {}\n }\n}\n\nclass Unfixer {\n constructor () {\n this.cache = new Map()\n }\n\n get (prefixLength, keyFormat) {\n let unfix = this.cache.get(keyFormat)\n\n if (unfix === undefined) {\n if (keyFormat === 'view') {\n unfix = function (prefixLength, key) {\n // Avoid Uint8Array#slice() because it copies\n return key.subarray(prefixLength)\n }.bind(null, prefixLength)\n } else {\n unfix = function (prefixLength, key) {\n // Avoid Buffer#subarray() because it's slow\n return key.slice(prefixLength)\n }.bind(null, prefixLength)\n }\n\n this.cache.set(keyFormat, unfix)\n }\n\n return unfix\n }\n}\n\nconst trim = function (str, char) {\n let start = 0\n let end = str.length\n\n while (start < end && str[start] === char) start++\n while (end > start && str[end - 1] === char) end--\n\n return str.slice(start, end)\n}\n", "'use strict'\n\nconst { supports } = require('level-supports')\nconst { Transcoder } = require('level-transcoder')\nconst { EventEmitter } = require('events')\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { AbstractIterator } = require('./abstract-iterator')\nconst { DefaultKeyIterator, DefaultValueIterator } = require('./lib/default-kv-iterator')\nconst { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = require('./lib/deferred-iterator')\nconst { DefaultChainedBatch } = require('./lib/default-chained-batch')\nconst { getCallback, getOptions } = require('./lib/common')\nconst rangeOptions = require('./lib/range-options')\n\nconst kPromise = Symbol('promise')\nconst kLanded = Symbol('landed')\nconst kResources = Symbol('resources')\nconst kCloseResources = Symbol('closeResources')\nconst kOperations = Symbol('operations')\nconst kUndefer = Symbol('undefer')\nconst kDeferOpen = Symbol('deferOpen')\nconst kOptions = Symbol('options')\nconst kStatus = Symbol('status')\nconst kDefaultOptions = Symbol('defaultOptions')\nconst kTranscoder = Symbol('transcoder')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst noop = () => {}\n\nclass AbstractLevel extends EventEmitter {\n constructor (manifest, options) {\n super()\n\n if (typeof manifest !== 'object' || manifest === null) {\n throw new TypeError(\"The first argument 'manifest' must be an object\")\n }\n\n options = getOptions(options)\n const { keyEncoding, valueEncoding, passive, ...forward } = options\n\n this[kResources] = new Set()\n this[kOperations] = []\n this[kDeferOpen] = true\n this[kOptions] = forward\n this[kStatus] = 'opening'\n\n this.supports = supports(manifest, {\n status: true,\n promises: true,\n clear: true,\n getMany: true,\n deferredOpen: true,\n\n // TODO (next major): add seek\n snapshots: manifest.snapshots !== false,\n permanence: manifest.permanence !== false,\n\n // TODO: remove from level-supports because it's always supported\n keyIterator: true,\n valueIterator: true,\n iteratorNextv: true,\n iteratorAll: true,\n\n encodings: manifest.encodings || {},\n events: Object.assign({}, manifest.events, {\n opening: true,\n open: true,\n closing: true,\n closed: true,\n put: true,\n del: true,\n batch: true,\n clear: true\n })\n })\n\n this[kTranscoder] = new Transcoder(formats(this))\n this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8')\n this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8')\n\n // Add custom and transcoder encodings to manifest\n for (const encoding of this[kTranscoder].encodings()) {\n if (!this.supports.encodings[encoding.commonName]) {\n this.supports.encodings[encoding.commonName] = true\n }\n }\n\n this[kDefaultOptions] = {\n empty: Object.freeze({}),\n entry: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName,\n valueEncoding: this[kValueEncoding].commonName\n }),\n key: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName\n })\n }\n\n // Let subclass finish its constructor\n this.nextTick(() => {\n if (this[kDeferOpen]) {\n this.open({ passive: false }, noop)\n }\n })\n }\n\n get status () {\n return this[kStatus]\n }\n\n keyEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])\n }\n\n valueEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])\n }\n\n open (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n\n options = { ...this[kOptions], ...getOptions(options) }\n\n options.createIfMissing = options.createIfMissing !== false\n options.errorIfExists = !!options.errorIfExists\n\n const maybeOpened = (err) => {\n if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened)\n } else if (this[kStatus] !== 'open') {\n callback(new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (options.passive) {\n if (this[kStatus] === 'opening') {\n this.once(kLanded, maybeOpened)\n } else {\n this.nextTick(maybeOpened)\n }\n } else if (this[kStatus] === 'closed' || this[kDeferOpen]) {\n this[kDeferOpen] = false\n this[kStatus] = 'opening'\n this.emit('opening')\n\n this._open(options, (err) => {\n if (err) {\n this[kStatus] = 'closed'\n\n // Resources must be safe to close in any db state\n this[kCloseResources](() => {\n this.emit(kLanded)\n maybeOpened(err)\n })\n\n this[kUndefer]()\n return\n }\n\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'open') this.emit('open')\n\n // TODO (next major): remove this alias\n if (this[kStatus] === 'open') this.emit('ready')\n\n maybeOpened()\n })\n } else if (this[kStatus] === 'open') {\n this.nextTick(maybeOpened)\n } else {\n this.once(kLanded, () => this.open(options, callback))\n }\n\n return callback[kPromise]\n }\n\n _open (options, callback) {\n this.nextTick(callback)\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n const maybeClosed = (err) => {\n if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? maybeClosed(err) : maybeClosed)\n } else if (this[kStatus] !== 'closed') {\n callback(new ModuleError('Database is not closed', {\n code: 'LEVEL_DATABASE_NOT_CLOSED',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (this[kStatus] === 'open') {\n this[kStatus] = 'closing'\n this.emit('closing')\n\n const cancel = (err) => {\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n maybeClosed(err)\n }\n\n this[kCloseResources](() => {\n this._close((err) => {\n if (err) return cancel(err)\n\n this[kStatus] = 'closed'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'closed') this.emit('closed')\n\n maybeClosed()\n })\n })\n } else if (this[kStatus] === 'closed') {\n this.nextTick(maybeClosed)\n } else {\n this.once(kLanded, () => this.close(callback))\n }\n\n return callback[kPromise]\n }\n\n [kCloseResources] (callback) {\n if (this[kResources].size === 0) {\n return this.nextTick(callback)\n }\n\n let pending = this[kResources].size\n let sync = true\n\n const next = () => {\n if (--pending === 0) {\n // We don't have tests for generic resources, so dezalgo\n if (sync) this.nextTick(callback)\n else callback()\n }\n }\n\n // In parallel so that all resources know they are closed\n for (const resource of this[kResources]) {\n resource.close(next)\n }\n\n sync = false\n this[kResources].clear()\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n get (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.get(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options to the underlying store\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {\n if (err) {\n // Normalize not found error for backwards compatibility with abstract-leveldown and level(up)\n if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {\n if (!err.code) err.code = 'LEVEL_NOT_FOUND' // Preferred way going forward\n if (!err.notFound) err.notFound = true // Same as level-errors\n if (!err.status) err.status = 404 // Same as level-errors\n }\n\n return callback(err)\n }\n\n try {\n value = valueEncoding.decode(value)\n } catch (err) {\n return callback(new ModuleError('Could not decode value', {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, value)\n })\n\n return callback[kPromise]\n }\n\n _get (key, options, callback) {\n this.nextTick(callback, new Error('NotFound'))\n }\n\n getMany (keys, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.getMany(keys, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(keys)) {\n this.nextTick(callback, new TypeError(\"The first argument 'keys' must be an array\"))\n return callback[kPromise]\n }\n\n if (keys.length === 0) {\n this.nextTick(callback, null, [])\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKeys = new Array(keys.length)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat)\n }\n\n this._getMany(mappedKeys, options, (err, values) => {\n if (err) return callback(err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n if (values[i] !== undefined) {\n values[i] = valueEncoding.decode(values[i])\n }\n }\n } catch (err) {\n return callback(new ModuleError(`Could not decode one or more of ${values.length} value(s)`, {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, values)\n })\n\n return callback[kPromise]\n }\n\n _getMany (keys, options, callback) {\n this.nextTick(callback, null, new Array(keys.length).fill(undefined))\n }\n\n put (key, value, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.put(key, value, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key) || this._checkValue(value)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options, (err) => {\n if (err) return callback(err)\n this.emit('put', key, value)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _put (key, value, options, callback) {\n this.nextTick(callback)\n }\n\n del (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].key)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.del(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat })\n }\n\n this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {\n if (err) return callback(err)\n this.emit('del', key)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _del (key, options, callback) {\n this.nextTick(callback)\n }\n\n batch (operations, options, callback) {\n if (!arguments.length) {\n if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n return this._chainedBatch()\n }\n\n if (typeof operations === 'function') callback = operations\n else callback = getCallback(options, callback)\n\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.batch(operations, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(operations)) {\n this.nextTick(callback, new TypeError(\"The first argument 'operations' must be an array\"))\n return callback[kPromise]\n }\n\n if (operations.length === 0) {\n this.nextTick(callback)\n return callback[kPromise]\n }\n\n const mapped = new Array(operations.length)\n const { keyEncoding: ke, valueEncoding: ve, ...forward } = options\n\n for (let i = 0; i < operations.length; i++) {\n if (typeof operations[i] !== 'object' || operations[i] === null) {\n this.nextTick(callback, new TypeError('A batch operation must be an object'))\n return callback[kPromise]\n }\n\n const op = Object.assign({}, operations[i])\n\n if (op.type !== 'put' && op.type !== 'del') {\n this.nextTick(callback, new TypeError(\"A batch operation must have a type property that is 'put' or 'del'\"))\n return callback[kPromise]\n }\n\n const err = this._checkKey(op.key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const db = op.sublevel != null ? op.sublevel : this\n const keyEncoding = db.keyEncoding(op.keyEncoding || ke)\n const keyFormat = keyEncoding.format\n\n op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat)\n op.keyEncoding = keyFormat\n\n if (op.type === 'put') {\n const valueErr = this._checkValue(op.value)\n\n if (valueErr) {\n this.nextTick(callback, valueErr)\n return callback[kPromise]\n }\n\n const valueEncoding = db.valueEncoding(op.valueEncoding || ve)\n\n op.value = valueEncoding.encode(op.value)\n op.valueEncoding = valueEncoding.format\n }\n\n // Prevent double prefixing\n if (db !== this) {\n op.sublevel = null\n }\n\n mapped[i] = op\n }\n\n this._batch(mapped, forward, (err) => {\n if (err) return callback(err)\n this.emit('batch', operations)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _batch (operations, options, callback) {\n this.nextTick(callback)\n }\n\n sublevel (name, options) {\n return this._sublevel(name, AbstractSublevel.defaults(options))\n }\n\n _sublevel (name, options) {\n return new AbstractSublevel(this, name, options)\n }\n\n prefixKey (key, keyFormat) {\n return key\n }\n\n clear (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.clear(options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const original = options\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keyEncoding = keyEncoding.format\n\n if (options.limit === 0) {\n this.nextTick(callback)\n } else {\n this._clear(options, (err) => {\n if (err) return callback(err)\n this.emit('clear', original)\n callback()\n })\n }\n\n return callback[kPromise]\n }\n\n _clear (options, callback) {\n this.nextTick(callback)\n }\n\n iterator (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keys = options.keys !== false\n options.values = options.values !== false\n\n // We need the original encoding options in AbstractIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._iterator(options)\n }\n\n _iterator (options) {\n return new AbstractIterator(this, options)\n }\n\n keys (options) {\n // Also include valueEncoding (though unused) because we may fallback to _iterator()\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractKeyIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredKeyIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._keys(options)\n }\n\n _keys (options) {\n return new DefaultKeyIterator(this, options)\n }\n\n values (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractValueIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredValueIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._values(options)\n }\n\n _values (options) {\n return new DefaultValueIterator(this, options)\n }\n\n defer (fn) {\n if (typeof fn !== 'function') {\n throw new TypeError('The first argument must be a function')\n }\n\n this[kOperations].push(fn)\n }\n\n [kUndefer] () {\n if (this[kOperations].length === 0) {\n return\n }\n\n const operations = this[kOperations]\n this[kOperations] = []\n\n for (const op of operations) {\n op()\n }\n }\n\n // TODO: docs and types\n attachResource (resource) {\n if (typeof resource !== 'object' || resource === null ||\n typeof resource.close !== 'function') {\n throw new TypeError('The first argument must be a resource object')\n }\n\n this[kResources].add(resource)\n }\n\n // TODO: docs and types\n detachResource (resource) {\n this[kResources].delete(resource)\n }\n\n _chainedBatch () {\n return new DefaultChainedBatch(this)\n }\n\n _checkKey (key) {\n if (key === null || key === undefined) {\n return new ModuleError('Key cannot be null or undefined', {\n code: 'LEVEL_INVALID_KEY'\n })\n }\n }\n\n _checkValue (value) {\n if (value === null || value === undefined) {\n return new ModuleError('Value cannot be null or undefined', {\n code: 'LEVEL_INVALID_VALUE'\n })\n }\n }\n}\n\n// Expose browser-compatible nextTick for dependents\n// TODO: after we drop node 10, also use queueMicrotask in node\nAbstractLevel.prototype.nextTick = require('./lib/next-tick')\n\nconst { AbstractSublevel } = require('./lib/abstract-sublevel')({ AbstractLevel })\n\nexports.AbstractLevel = AbstractLevel\nexports.AbstractSublevel = AbstractSublevel\n\nconst maybeError = function (db, callback) {\n if (db[kStatus] !== 'open') {\n db.nextTick(callback, new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n }))\n return true\n }\n\n return false\n}\n\nconst formats = function (db) {\n return Object.keys(db.supports.encodings)\n .filter(k => !!db.supports.encodings[k])\n}\n", "'use strict'\n\nexports.AbstractLevel = require('./abstract-level').AbstractLevel\nexports.AbstractSublevel = require('./abstract-level').AbstractSublevel\nexports.AbstractIterator = require('./abstract-iterator').AbstractIterator\nexports.AbstractKeyIterator = require('./abstract-iterator').AbstractKeyIterator\nexports.AbstractValueIterator = require('./abstract-iterator').AbstractValueIterator\nexports.AbstractChainedBatch = require('./abstract-chained-batch').AbstractChainedBatch\n", "/*! run-parallel-limit. MIT License. Feross Aboukhadijeh */\nmodule.exports = runParallelLimit\n\nconst queueMicrotask = require('queue-microtask')\n\nfunction runParallelLimit (tasks, limit, cb) {\n if (typeof limit !== 'number') throw new Error('second argument must be a Number')\n let results, len, pending, keys, isErrored\n let isSync = true\n let next\n\n if (Array.isArray(tasks)) {\n results = []\n pending = len = tasks.length\n } else {\n keys = Object.keys(tasks)\n results = {}\n pending = len = keys.length\n }\n\n function done (err) {\n function end () {\n if (cb) cb(err, results)\n cb = null\n }\n if (isSync) queueMicrotask(end)\n else end()\n }\n\n function each (i, err, result) {\n results[i] = result\n if (err) isErrored = true\n if (--pending === 0 || err) {\n done(err)\n } else if (!isErrored && next < len) {\n let key\n if (keys) {\n key = keys[next]\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n } else {\n key = next\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n }\n }\n }\n\n next = limit\n if (!pending) {\n // empty\n done(null)\n } else if (keys) {\n // object\n keys.some(function (key, i) {\n tasks[key](function (err, result) { each(key, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n } else {\n // array\n tasks.some(function (task, i) {\n task(function (err, result) { each(i, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n }\n\n isSync = false\n}\n", "/* global IDBKeyRange */\n\n'use strict'\n\nmodule.exports = function createKeyRange (options) {\n const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined\n const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined\n const lowerExclusive = options.gte === undefined\n const upperExclusive = options.lte === undefined\n\n if (lower !== undefined && upper !== undefined) {\n return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)\n } else if (lower !== undefined) {\n return IDBKeyRange.lowerBound(lower, lowerExclusive)\n } else if (upper !== undefined) {\n return IDBKeyRange.upperBound(upper, upperExclusive)\n } else {\n return null\n }\n}\n", "'use strict'\n\nconst textEncoder = new TextEncoder()\n\nmodule.exports = function (data) {\n if (data instanceof Uint8Array) {\n return data\n } else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data)\n } else {\n // Non-binary data stored with an old version (level-js < 5.0.0)\n return textEncoder.encode(data)\n }\n}\n", "'use strict'\n\nconst { AbstractIterator } = require('abstract-level')\nconst createKeyRange = require('./util/key-range')\nconst deserialize = require('./util/deserialize')\n\nconst kCache = Symbol('cache')\nconst kFinished = Symbol('finished')\nconst kOptions = Symbol('options')\nconst kCurrentOptions = Symbol('currentOptions')\nconst kPosition = Symbol('position')\nconst kLocation = Symbol('location')\nconst kFirst = Symbol('first')\nconst emptyOptions = {}\n\nclass Iterator extends AbstractIterator {\n constructor (db, location, options) {\n super(db, options)\n\n this[kCache] = []\n this[kFinished] = this.limit === 0\n this[kOptions] = options\n this[kCurrentOptions] = { ...options }\n this[kPosition] = undefined\n this[kLocation] = location\n this[kFirst] = true\n }\n\n // Note: if called by _all() then size can be Infinity. This is an internal\n // detail; by design AbstractIterator.nextv() does not support Infinity.\n _nextv (size, options, callback) {\n this[kFirst] = false\n\n if (this[kFinished]) {\n return this.nextTick(callback, null, [])\n } else if (this[kCache].length > 0) {\n // TODO: mixing next and nextv is not covered by test suite\n size = Math.min(size, this[kCache].length)\n return this.nextTick(callback, null, this[kCache].splice(0, size))\n }\n\n // Adjust range by what we already visited\n if (this[kPosition] !== undefined) {\n if (this[kOptions].reverse) {\n this[kCurrentOptions].lt = this[kPosition]\n this[kCurrentOptions].lte = undefined\n } else {\n this[kCurrentOptions].gt = this[kPosition]\n this[kCurrentOptions].gte = undefined\n }\n }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kCurrentOptions])\n } catch (_) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just return 0 results.\n this[kFinished] = true\n return this.nextTick(callback, null, [])\n }\n\n const transaction = this.db.db.transaction([this[kLocation]], 'readonly')\n const store = transaction.objectStore(this[kLocation])\n const entries = []\n\n if (!this[kOptions].reverse) {\n let keys\n let values\n\n const complete = () => {\n // Wait for both requests to complete\n if (keys === undefined || values === undefined) return\n\n const length = Math.max(keys.length, values.length)\n\n if (length === 0 || size === Infinity) {\n this[kFinished] = true\n } else {\n this[kPosition] = keys[length - 1]\n }\n\n // Resize\n entries.length = length\n\n // Merge keys and values\n for (let i = 0; i < length; i++) {\n const key = keys[i]\n const value = values[i]\n\n entries[i] = [\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ]\n }\n\n maybeCommit(transaction)\n }\n\n // If keys were not requested and size is Infinity, we don't have to keep\n // track of position and can thus skip getting keys.\n if (this[kOptions].keys || size < Infinity) {\n store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n keys = ev.target.result\n complete()\n }\n } else {\n keys = []\n this.nextTick(complete)\n }\n\n if (this[kOptions].values) {\n store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n values = ev.target.result\n complete()\n }\n } else {\n values = []\n this.nextTick(complete)\n }\n } else {\n // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time\n // TODO: test if all target browsers support openKeyCursor\n const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n\n store[method](keyRange, 'prev').onsuccess = (ev) => {\n const cursor = ev.target.result\n\n if (cursor) {\n const { key, value } = cursor\n this[kPosition] = key\n\n entries.push([\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ])\n\n if (entries.length < size) {\n cursor.continue()\n } else {\n maybeCommit(transaction)\n }\n } else {\n this[kFinished] = true\n }\n }\n }\n\n // If an error occurs (on the request), the transaction will abort.\n transaction.onabort = () => {\n callback(transaction.error || new Error('aborted by user'))\n callback = null\n }\n\n transaction.oncomplete = () => {\n callback(null, entries)\n callback = null\n }\n }\n\n _next (callback) {\n if (this[kCache].length > 0) {\n const [key, value] = this[kCache].shift()\n this.nextTick(callback, null, key, value)\n } else if (this[kFinished]) {\n this.nextTick(callback)\n } else {\n let size = Math.min(100, this.limit - this.count)\n\n if (this[kFirst]) {\n // It's common to only want one entry initially or after a seek()\n this[kFirst] = false\n size = 1\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n this[kCache] = entries\n this._next(callback)\n })\n }\n }\n\n _all (options, callback) {\n this[kFirst] = false\n\n // TODO: mixing next and all is not covered by test suite\n const cache = this[kCache].splice(0, this[kCache].length)\n const size = this.limit - this.count - cache.length\n\n if (size <= 0) {\n return this.nextTick(callback, null, cache)\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n if (cache.length > 0) entries = cache.concat(entries)\n callback(null, entries)\n })\n }\n\n _seek (target, options) {\n this[kFirst] = true\n this[kCache] = []\n this[kFinished] = false\n this[kPosition] = undefined\n\n // TODO: not covered by test suite\n this[kCurrentOptions] = { ...this[kOptions] }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kOptions])\n } catch (_) {\n this[kFinished] = true\n return\n }\n\n if (keyRange !== null && !keyRange.includes(target)) {\n this[kFinished] = true\n } else if (this[kOptions].reverse) {\n this[kCurrentOptions].lte = target\n } else {\n this[kCurrentOptions].gte = target\n }\n }\n}\n\nexports.Iterator = Iterator\n\nfunction maybeCommit (transaction) {\n // Commit (meaning close) now instead of waiting for auto-commit\n if (typeof transaction.commit === 'function') {\n transaction.commit()\n }\n}\n", "'use strict'\n\nmodule.exports = function clear (db, location, keyRange, options, callback) {\n if (options.limit === 0) return db.nextTick(callback)\n\n const transaction = db.db.transaction([location], 'readwrite')\n const store = transaction.objectStore(location)\n let count = 0\n\n transaction.oncomplete = function () {\n callback()\n }\n\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n // A key cursor is faster (skips reading values) but not supported by IE\n // TODO: we no longer support IE. Test others\n const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n const direction = options.reverse ? 'prev' : 'next'\n\n store[method](keyRange, direction).onsuccess = function (ev) {\n const cursor = ev.target.result\n\n if (cursor) {\n // Wait for a request to complete before continuing, saving CPU.\n store.delete(cursor.key).onsuccess = function () {\n if (options.limit <= 0 || ++count < options.limit) {\n cursor.continue()\n }\n }\n }\n }\n}\n", "/* global indexedDB */\n\n'use strict'\n\nconst { AbstractLevel } = require('abstract-level')\nconst ModuleError = require('module-error')\nconst parallel = require('run-parallel-limit')\nconst { fromCallback } = require('catering')\nconst { Iterator } = require('./iterator')\nconst deserialize = require('./util/deserialize')\nconst clear = require('./util/clear')\nconst createKeyRange = require('./util/key-range')\n\n// Keep as-is for compatibility with existing level-js databases\nconst DEFAULT_PREFIX = 'level-js-'\n\nconst kIDB = Symbol('idb')\nconst kNamePrefix = Symbol('namePrefix')\nconst kLocation = Symbol('location')\nconst kVersion = Symbol('version')\nconst kStore = Symbol('store')\nconst kOnComplete = Symbol('onComplete')\nconst kPromise = Symbol('promise')\n\nclass BrowserLevel extends AbstractLevel {\n constructor (location, options, _) {\n // To help migrating to abstract-level\n if (typeof options === 'function' || typeof _ === 'function') {\n throw new ModuleError('The levelup-style callback argument has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n const { prefix, version, ...forward } = options || {}\n\n super({\n encodings: { view: true },\n snapshots: false,\n createIfMissing: false,\n errorIfExists: false,\n seek: true\n }, forward)\n\n if (typeof location !== 'string') {\n throw new Error('constructor requires a location string argument')\n }\n\n // TODO (next major): remove default prefix\n this[kLocation] = location\n this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix\n this[kVersion] = parseInt(version || 1, 10)\n this[kIDB] = null\n }\n\n get location () {\n return this[kLocation]\n }\n\n get namePrefix () {\n return this[kNamePrefix]\n }\n\n get version () {\n return this[kVersion]\n }\n\n // Exposed for backwards compat and unit tests\n get db () {\n return this[kIDB]\n }\n\n get type () {\n return 'browser-level'\n }\n\n _open (options, callback) {\n const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion])\n\n req.onerror = function () {\n callback(req.error || new Error('unknown error'))\n }\n\n req.onsuccess = () => {\n this[kIDB] = req.result\n callback()\n }\n\n req.onupgradeneeded = (ev) => {\n const db = ev.target.result\n\n if (!db.objectStoreNames.contains(this[kLocation])) {\n db.createObjectStore(this[kLocation])\n }\n }\n }\n\n [kStore] (mode) {\n const transaction = this[kIDB].transaction([this[kLocation]], mode)\n return transaction.objectStore(this[kLocation])\n }\n\n [kOnComplete] (request, callback) {\n const transaction = request.transaction\n\n // Take advantage of the fact that a non-canceled request error aborts\n // the transaction. I.e. no need to listen for \"request.onerror\".\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback(null, request.result)\n }\n }\n\n _get (key, options, callback) {\n const store = this[kStore]('readonly')\n let req\n\n try {\n req = store.get(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, function (err, value) {\n if (err) return callback(err)\n\n if (value === undefined) {\n return callback(new ModuleError('Entry not found', {\n code: 'LEVEL_NOT_FOUND'\n }))\n }\n\n callback(null, deserialize(value))\n })\n }\n\n _getMany (keys, options, callback) {\n const store = this[kStore]('readonly')\n const tasks = keys.map((key) => (next) => {\n let request\n\n try {\n request = store.get(key)\n } catch (err) {\n return next(err)\n }\n\n request.onsuccess = () => {\n const value = request.result\n next(null, value === undefined ? value : deserialize(value))\n }\n\n request.onerror = (ev) => {\n ev.stopPropagation()\n next(request.error)\n }\n })\n\n parallel(tasks, 16, callback)\n }\n\n _del (key, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n req = store.delete(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _put (key, value, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n // Will throw a DataError or DataCloneError if the environment\n // does not support serializing the key or value respectively.\n req = store.put(value, key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n // TODO: implement key and value iterators\n _iterator (options) {\n return new Iterator(this, this[kLocation], options)\n }\n\n _batch (operations, options, callback) {\n const store = this[kStore]('readwrite')\n const transaction = store.transaction\n let index = 0\n let error\n\n transaction.onabort = function () {\n callback(error || transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback()\n }\n\n // Wait for a request to complete before making the next, saving CPU.\n function loop () {\n const op = operations[index++]\n const key = op.key\n\n let req\n\n try {\n req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)\n } catch (err) {\n error = err\n transaction.abort()\n return\n }\n\n if (index < operations.length) {\n req.onsuccess = loop\n } else if (typeof transaction.commit === 'function') {\n // Commit now instead of waiting for auto-commit\n transaction.commit()\n }\n }\n\n loop()\n }\n\n _clear (options, callback) {\n let keyRange\n let req\n\n try {\n keyRange = createKeyRange(options)\n } catch (e) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just do nothing.\n return this.nextTick(callback)\n }\n\n if (options.limit >= 0) {\n // IDBObjectStore#delete(range) doesn't have such an option.\n // Fall back to cursor-based implementation.\n return clear(this, this[kLocation], keyRange, options, callback)\n }\n\n try {\n const store = this[kStore]('readwrite')\n req = keyRange ? store.delete(keyRange) : store.clear()\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _close (callback) {\n this[kIDB].close()\n this.nextTick(callback)\n }\n}\n\nBrowserLevel.destroy = function (location, prefix, callback) {\n if (typeof prefix === 'function') {\n callback = prefix\n prefix = DEFAULT_PREFIX\n }\n\n callback = fromCallback(callback, kPromise)\n const request = indexedDB.deleteDatabase(prefix + location)\n\n request.onsuccess = function () {\n callback()\n }\n\n request.onerror = function (err) {\n callback(err)\n }\n\n return callback[kPromise]\n}\n\nexports.BrowserLevel = BrowserLevel\n", "exports.Level = require('browser-level').BrowserLevel\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)).constructor = CustomError;\n\n Object.defineProperty(CustomError.prototype, \"name\", { get: function() { return name; } });\n\n CustomError.prototype.toString = function toString() {\n return this.name + \": \" + this.message;\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 = 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", "\"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 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new this.buf.constructor(0)\n : 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 = 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\";\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 = {};\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 accross 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\";\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", "// minimal library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index-minimal\");\n", "// @ts-nocheck\n/*eslint-disable*/\n(function(global, factory) { /* global define, require, module */\n\n /* AMD */ if (typeof define === 'function' && define.amd)\n define([\"protobufjs/minimal\"], factory);\n\n /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports)\n module.exports = factory(require(\"protobufjs/minimal\"));\n\n})(this, function($protobuf) {\n \"use strict\";\n\n // Common aliases\n var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n // Exported root namespace\n var $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\n $root.RPC = (function() {\n\n /**\n * Properties of a RPC.\n * @exports IRPC\n * @interface IRPC\n * @property {Array.|null} [subscriptions] RPC subscriptions\n * @property {Array.|null} [messages] RPC messages\n * @property {RPC.IControlMessage|null} [control] RPC control\n */\n\n /**\n * Constructs a new RPC.\n * @exports RPC\n * @classdesc Represents a RPC.\n * @implements IRPC\n * @constructor\n * @param {IRPC=} [p] Properties to set\n */\n function RPC(p) {\n this.subscriptions = [];\n this.messages = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * RPC subscriptions.\n * @member {Array.} subscriptions\n * @memberof RPC\n * @instance\n */\n RPC.prototype.subscriptions = $util.emptyArray;\n\n /**\n * RPC messages.\n * @member {Array.} messages\n * @memberof RPC\n * @instance\n */\n RPC.prototype.messages = $util.emptyArray;\n\n /**\n * RPC control.\n * @member {RPC.IControlMessage|null|undefined} control\n * @memberof RPC\n * @instance\n */\n RPC.prototype.control = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * RPC _control.\n * @member {\"control\"|undefined} _control\n * @memberof RPC\n * @instance\n */\n Object.defineProperty(RPC.prototype, \"_control\", {\n get: $util.oneOfGetter($oneOfFields = [\"control\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified RPC message. Does not implicitly {@link RPC.verify|verify} messages.\n * @function encode\n * @memberof RPC\n * @static\n * @param {IRPC} m RPC message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n RPC.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.subscriptions != null && m.subscriptions.length) {\n for (var i = 0; i < m.subscriptions.length; ++i)\n $root.RPC.SubOpts.encode(m.subscriptions[i], w.uint32(10).fork()).ldelim();\n }\n if (m.messages != null && m.messages.length) {\n for (var i = 0; i < m.messages.length; ++i)\n $root.RPC.Message.encode(m.messages[i], w.uint32(18).fork()).ldelim();\n }\n if (m.control != null && Object.hasOwnProperty.call(m, \"control\"))\n $root.RPC.ControlMessage.encode(m.control, w.uint32(26).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes a RPC message from the specified reader or buffer.\n * @function decode\n * @memberof RPC\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC} RPC\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n RPC.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.subscriptions && m.subscriptions.length))\n m.subscriptions = [];\n m.subscriptions.push($root.RPC.SubOpts.decode(r, r.uint32()));\n break;\n case 2:\n if (!(m.messages && m.messages.length))\n m.messages = [];\n m.messages.push($root.RPC.Message.decode(r, r.uint32()));\n break;\n case 3:\n m.control = $root.RPC.ControlMessage.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a RPC message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC} RPC\n */\n RPC.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC)\n return d;\n var m = new $root.RPC();\n if (d.subscriptions) {\n if (!Array.isArray(d.subscriptions))\n throw TypeError(\".RPC.subscriptions: array expected\");\n m.subscriptions = [];\n for (var i = 0; i < d.subscriptions.length; ++i) {\n if (typeof d.subscriptions[i] !== \"object\")\n throw TypeError(\".RPC.subscriptions: object expected\");\n m.subscriptions[i] = $root.RPC.SubOpts.fromObject(d.subscriptions[i]);\n }\n }\n if (d.messages) {\n if (!Array.isArray(d.messages))\n throw TypeError(\".RPC.messages: array expected\");\n m.messages = [];\n for (var i = 0; i < d.messages.length; ++i) {\n if (typeof d.messages[i] !== \"object\")\n throw TypeError(\".RPC.messages: object expected\");\n m.messages[i] = $root.RPC.Message.fromObject(d.messages[i]);\n }\n }\n if (d.control != null) {\n if (typeof d.control !== \"object\")\n throw TypeError(\".RPC.control: object expected\");\n m.control = $root.RPC.ControlMessage.fromObject(d.control);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a RPC message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC\n * @static\n * @param {RPC} m RPC\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n RPC.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.subscriptions = [];\n d.messages = [];\n }\n if (m.subscriptions && m.subscriptions.length) {\n d.subscriptions = [];\n for (var j = 0; j < m.subscriptions.length; ++j) {\n d.subscriptions[j] = $root.RPC.SubOpts.toObject(m.subscriptions[j], o);\n }\n }\n if (m.messages && m.messages.length) {\n d.messages = [];\n for (var j = 0; j < m.messages.length; ++j) {\n d.messages[j] = $root.RPC.Message.toObject(m.messages[j], o);\n }\n }\n if (m.control != null && m.hasOwnProperty(\"control\")) {\n d.control = $root.RPC.ControlMessage.toObject(m.control, o);\n if (o.oneofs)\n d._control = \"control\";\n }\n return d;\n };\n\n /**\n * Converts this RPC to JSON.\n * @function toJSON\n * @memberof RPC\n * @instance\n * @returns {Object.} JSON object\n */\n RPC.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n RPC.SubOpts = (function() {\n\n /**\n * Properties of a SubOpts.\n * @memberof RPC\n * @interface ISubOpts\n * @property {boolean|null} [subscribe] SubOpts subscribe\n * @property {string|null} [topic] SubOpts topic\n */\n\n /**\n * Constructs a new SubOpts.\n * @memberof RPC\n * @classdesc Represents a SubOpts.\n * @implements ISubOpts\n * @constructor\n * @param {RPC.ISubOpts=} [p] Properties to set\n */\n function SubOpts(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * SubOpts subscribe.\n * @member {boolean|null|undefined} subscribe\n * @memberof RPC.SubOpts\n * @instance\n */\n SubOpts.prototype.subscribe = null;\n\n /**\n * SubOpts topic.\n * @member {string|null|undefined} topic\n * @memberof RPC.SubOpts\n * @instance\n */\n SubOpts.prototype.topic = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * SubOpts _subscribe.\n * @member {\"subscribe\"|undefined} _subscribe\n * @memberof RPC.SubOpts\n * @instance\n */\n Object.defineProperty(SubOpts.prototype, \"_subscribe\", {\n get: $util.oneOfGetter($oneOfFields = [\"subscribe\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * SubOpts _topic.\n * @member {\"topic\"|undefined} _topic\n * @memberof RPC.SubOpts\n * @instance\n */\n Object.defineProperty(SubOpts.prototype, \"_topic\", {\n get: $util.oneOfGetter($oneOfFields = [\"topic\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified SubOpts message. Does not implicitly {@link RPC.SubOpts.verify|verify} messages.\n * @function encode\n * @memberof RPC.SubOpts\n * @static\n * @param {RPC.ISubOpts} m SubOpts message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n SubOpts.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.subscribe != null && Object.hasOwnProperty.call(m, \"subscribe\"))\n w.uint32(8).bool(m.subscribe);\n if (m.topic != null && Object.hasOwnProperty.call(m, \"topic\"))\n w.uint32(18).string(m.topic);\n return w;\n };\n\n /**\n * Decodes a SubOpts message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.SubOpts\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.SubOpts} SubOpts\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n SubOpts.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.SubOpts();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.subscribe = r.bool();\n break;\n case 2:\n m.topic = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a SubOpts message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.SubOpts\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.SubOpts} SubOpts\n */\n SubOpts.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.SubOpts)\n return d;\n var m = new $root.RPC.SubOpts();\n if (d.subscribe != null) {\n m.subscribe = Boolean(d.subscribe);\n }\n if (d.topic != null) {\n m.topic = String(d.topic);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a SubOpts message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.SubOpts\n * @static\n * @param {RPC.SubOpts} m SubOpts\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n SubOpts.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (m.subscribe != null && m.hasOwnProperty(\"subscribe\")) {\n d.subscribe = m.subscribe;\n if (o.oneofs)\n d._subscribe = \"subscribe\";\n }\n if (m.topic != null && m.hasOwnProperty(\"topic\")) {\n d.topic = m.topic;\n if (o.oneofs)\n d._topic = \"topic\";\n }\n return d;\n };\n\n /**\n * Converts this SubOpts to JSON.\n * @function toJSON\n * @memberof RPC.SubOpts\n * @instance\n * @returns {Object.} JSON object\n */\n SubOpts.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return SubOpts;\n })();\n\n RPC.Message = (function() {\n\n /**\n * Properties of a Message.\n * @memberof RPC\n * @interface IMessage\n * @property {Uint8Array|null} [from] Message from\n * @property {Uint8Array|null} [data] Message data\n * @property {Uint8Array|null} [seqno] Message seqno\n * @property {string} topic Message topic\n * @property {Uint8Array|null} [signature] Message signature\n * @property {Uint8Array|null} [key] Message key\n */\n\n /**\n * Constructs a new Message.\n * @memberof RPC\n * @classdesc Represents a Message.\n * @implements IMessage\n * @constructor\n * @param {RPC.IMessage=} [p] Properties to set\n */\n function Message(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Message from.\n * @member {Uint8Array|null|undefined} from\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.from = null;\n\n /**\n * Message data.\n * @member {Uint8Array|null|undefined} data\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.data = null;\n\n /**\n * Message seqno.\n * @member {Uint8Array|null|undefined} seqno\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.seqno = null;\n\n /**\n * Message topic.\n * @member {string} topic\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.topic = \"\";\n\n /**\n * Message signature.\n * @member {Uint8Array|null|undefined} signature\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.signature = null;\n\n /**\n * Message key.\n * @member {Uint8Array|null|undefined} key\n * @memberof RPC.Message\n * @instance\n */\n Message.prototype.key = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * Message _from.\n * @member {\"from\"|undefined} _from\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_from\", {\n get: $util.oneOfGetter($oneOfFields = [\"from\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _data.\n * @member {\"data\"|undefined} _data\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_data\", {\n get: $util.oneOfGetter($oneOfFields = [\"data\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _seqno.\n * @member {\"seqno\"|undefined} _seqno\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_seqno\", {\n get: $util.oneOfGetter($oneOfFields = [\"seqno\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _signature.\n * @member {\"signature\"|undefined} _signature\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_signature\", {\n get: $util.oneOfGetter($oneOfFields = [\"signature\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Message _key.\n * @member {\"key\"|undefined} _key\n * @memberof RPC.Message\n * @instance\n */\n Object.defineProperty(Message.prototype, \"_key\", {\n get: $util.oneOfGetter($oneOfFields = [\"key\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Message message. Does not implicitly {@link RPC.Message.verify|verify} messages.\n * @function encode\n * @memberof RPC.Message\n * @static\n * @param {RPC.IMessage} m Message message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Message.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.from != null && Object.hasOwnProperty.call(m, \"from\"))\n w.uint32(10).bytes(m.from);\n if (m.data != null && Object.hasOwnProperty.call(m, \"data\"))\n w.uint32(18).bytes(m.data);\n if (m.seqno != null && Object.hasOwnProperty.call(m, \"seqno\"))\n w.uint32(26).bytes(m.seqno);\n w.uint32(34).string(m.topic);\n if (m.signature != null && Object.hasOwnProperty.call(m, \"signature\"))\n w.uint32(42).bytes(m.signature);\n if (m.key != null && Object.hasOwnProperty.call(m, \"key\"))\n w.uint32(50).bytes(m.key);\n return w;\n };\n\n /**\n * Decodes a Message message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.Message\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.Message} Message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Message.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.Message();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.from = r.bytes();\n break;\n case 2:\n m.data = r.bytes();\n break;\n case 3:\n m.seqno = r.bytes();\n break;\n case 4:\n m.topic = r.string();\n break;\n case 5:\n m.signature = r.bytes();\n break;\n case 6:\n m.key = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"topic\"))\n throw $util.ProtocolError(\"missing required 'topic'\", { instance: m });\n return m;\n };\n\n /**\n * Creates a Message message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.Message\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.Message} Message\n */\n Message.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.Message)\n return d;\n var m = new $root.RPC.Message();\n if (d.from != null) {\n if (typeof d.from === \"string\")\n $util.base64.decode(d.from, m.from = $util.newBuffer($util.base64.length(d.from)), 0);\n else if (d.from.length)\n m.from = d.from;\n }\n if (d.data != null) {\n if (typeof d.data === \"string\")\n $util.base64.decode(d.data, m.data = $util.newBuffer($util.base64.length(d.data)), 0);\n else if (d.data.length)\n m.data = d.data;\n }\n if (d.seqno != null) {\n if (typeof d.seqno === \"string\")\n $util.base64.decode(d.seqno, m.seqno = $util.newBuffer($util.base64.length(d.seqno)), 0);\n else if (d.seqno.length)\n m.seqno = d.seqno;\n }\n if (d.topic != null) {\n m.topic = String(d.topic);\n }\n if (d.signature != null) {\n if (typeof d.signature === \"string\")\n $util.base64.decode(d.signature, m.signature = $util.newBuffer($util.base64.length(d.signature)), 0);\n else if (d.signature.length)\n m.signature = d.signature;\n }\n if (d.key != null) {\n if (typeof d.key === \"string\")\n $util.base64.decode(d.key, m.key = $util.newBuffer($util.base64.length(d.key)), 0);\n else if (d.key.length)\n m.key = d.key;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Message message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.Message\n * @static\n * @param {RPC.Message} m Message\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Message.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.topic = \"\";\n }\n if (m.from != null && m.hasOwnProperty(\"from\")) {\n d.from = o.bytes === String ? $util.base64.encode(m.from, 0, m.from.length) : o.bytes === Array ? Array.prototype.slice.call(m.from) : m.from;\n if (o.oneofs)\n d._from = \"from\";\n }\n if (m.data != null && m.hasOwnProperty(\"data\")) {\n d.data = o.bytes === String ? $util.base64.encode(m.data, 0, m.data.length) : o.bytes === Array ? Array.prototype.slice.call(m.data) : m.data;\n if (o.oneofs)\n d._data = \"data\";\n }\n if (m.seqno != null && m.hasOwnProperty(\"seqno\")) {\n d.seqno = o.bytes === String ? $util.base64.encode(m.seqno, 0, m.seqno.length) : o.bytes === Array ? Array.prototype.slice.call(m.seqno) : m.seqno;\n if (o.oneofs)\n d._seqno = \"seqno\";\n }\n if (m.topic != null && m.hasOwnProperty(\"topic\")) {\n d.topic = m.topic;\n }\n if (m.signature != null && m.hasOwnProperty(\"signature\")) {\n d.signature = o.bytes === String ? $util.base64.encode(m.signature, 0, m.signature.length) : o.bytes === Array ? Array.prototype.slice.call(m.signature) : m.signature;\n if (o.oneofs)\n d._signature = \"signature\";\n }\n if (m.key != null && m.hasOwnProperty(\"key\")) {\n d.key = o.bytes === String ? $util.base64.encode(m.key, 0, m.key.length) : o.bytes === Array ? Array.prototype.slice.call(m.key) : m.key;\n if (o.oneofs)\n d._key = \"key\";\n }\n return d;\n };\n\n /**\n * Converts this Message to JSON.\n * @function toJSON\n * @memberof RPC.Message\n * @instance\n * @returns {Object.} JSON object\n */\n Message.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Message;\n })();\n\n RPC.ControlMessage = (function() {\n\n /**\n * Properties of a ControlMessage.\n * @memberof RPC\n * @interface IControlMessage\n * @property {Array.|null} [ihave] ControlMessage ihave\n * @property {Array.|null} [iwant] ControlMessage iwant\n * @property {Array.|null} [graft] ControlMessage graft\n * @property {Array.|null} [prune] ControlMessage prune\n */\n\n /**\n * Constructs a new ControlMessage.\n * @memberof RPC\n * @classdesc Represents a ControlMessage.\n * @implements IControlMessage\n * @constructor\n * @param {RPC.IControlMessage=} [p] Properties to set\n */\n function ControlMessage(p) {\n this.ihave = [];\n this.iwant = [];\n this.graft = [];\n this.prune = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlMessage ihave.\n * @member {Array.} ihave\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.ihave = $util.emptyArray;\n\n /**\n * ControlMessage iwant.\n * @member {Array.} iwant\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.iwant = $util.emptyArray;\n\n /**\n * ControlMessage graft.\n * @member {Array.} graft\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.graft = $util.emptyArray;\n\n /**\n * ControlMessage prune.\n * @member {Array.} prune\n * @memberof RPC.ControlMessage\n * @instance\n */\n ControlMessage.prototype.prune = $util.emptyArray;\n\n /**\n * Encodes the specified ControlMessage message. Does not implicitly {@link RPC.ControlMessage.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlMessage\n * @static\n * @param {RPC.IControlMessage} m ControlMessage message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlMessage.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.ihave != null && m.ihave.length) {\n for (var i = 0; i < m.ihave.length; ++i)\n $root.RPC.ControlIHave.encode(m.ihave[i], w.uint32(10).fork()).ldelim();\n }\n if (m.iwant != null && m.iwant.length) {\n for (var i = 0; i < m.iwant.length; ++i)\n $root.RPC.ControlIWant.encode(m.iwant[i], w.uint32(18).fork()).ldelim();\n }\n if (m.graft != null && m.graft.length) {\n for (var i = 0; i < m.graft.length; ++i)\n $root.RPC.ControlGraft.encode(m.graft[i], w.uint32(26).fork()).ldelim();\n }\n if (m.prune != null && m.prune.length) {\n for (var i = 0; i < m.prune.length; ++i)\n $root.RPC.ControlPrune.encode(m.prune[i], w.uint32(34).fork()).ldelim();\n }\n return w;\n };\n\n /**\n * Decodes a ControlMessage message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlMessage\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlMessage} ControlMessage\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlMessage.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlMessage();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.ihave && m.ihave.length))\n m.ihave = [];\n m.ihave.push($root.RPC.ControlIHave.decode(r, r.uint32()));\n break;\n case 2:\n if (!(m.iwant && m.iwant.length))\n m.iwant = [];\n m.iwant.push($root.RPC.ControlIWant.decode(r, r.uint32()));\n break;\n case 3:\n if (!(m.graft && m.graft.length))\n m.graft = [];\n m.graft.push($root.RPC.ControlGraft.decode(r, r.uint32()));\n break;\n case 4:\n if (!(m.prune && m.prune.length))\n m.prune = [];\n m.prune.push($root.RPC.ControlPrune.decode(r, r.uint32()));\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlMessage message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlMessage\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlMessage} ControlMessage\n */\n ControlMessage.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlMessage)\n return d;\n var m = new $root.RPC.ControlMessage();\n if (d.ihave) {\n if (!Array.isArray(d.ihave))\n throw TypeError(\".RPC.ControlMessage.ihave: array expected\");\n m.ihave = [];\n for (var i = 0; i < d.ihave.length; ++i) {\n if (typeof d.ihave[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.ihave: object expected\");\n m.ihave[i] = $root.RPC.ControlIHave.fromObject(d.ihave[i]);\n }\n }\n if (d.iwant) {\n if (!Array.isArray(d.iwant))\n throw TypeError(\".RPC.ControlMessage.iwant: array expected\");\n m.iwant = [];\n for (var i = 0; i < d.iwant.length; ++i) {\n if (typeof d.iwant[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.iwant: object expected\");\n m.iwant[i] = $root.RPC.ControlIWant.fromObject(d.iwant[i]);\n }\n }\n if (d.graft) {\n if (!Array.isArray(d.graft))\n throw TypeError(\".RPC.ControlMessage.graft: array expected\");\n m.graft = [];\n for (var i = 0; i < d.graft.length; ++i) {\n if (typeof d.graft[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.graft: object expected\");\n m.graft[i] = $root.RPC.ControlGraft.fromObject(d.graft[i]);\n }\n }\n if (d.prune) {\n if (!Array.isArray(d.prune))\n throw TypeError(\".RPC.ControlMessage.prune: array expected\");\n m.prune = [];\n for (var i = 0; i < d.prune.length; ++i) {\n if (typeof d.prune[i] !== \"object\")\n throw TypeError(\".RPC.ControlMessage.prune: object expected\");\n m.prune[i] = $root.RPC.ControlPrune.fromObject(d.prune[i]);\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlMessage message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlMessage\n * @static\n * @param {RPC.ControlMessage} m ControlMessage\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlMessage.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.ihave = [];\n d.iwant = [];\n d.graft = [];\n d.prune = [];\n }\n if (m.ihave && m.ihave.length) {\n d.ihave = [];\n for (var j = 0; j < m.ihave.length; ++j) {\n d.ihave[j] = $root.RPC.ControlIHave.toObject(m.ihave[j], o);\n }\n }\n if (m.iwant && m.iwant.length) {\n d.iwant = [];\n for (var j = 0; j < m.iwant.length; ++j) {\n d.iwant[j] = $root.RPC.ControlIWant.toObject(m.iwant[j], o);\n }\n }\n if (m.graft && m.graft.length) {\n d.graft = [];\n for (var j = 0; j < m.graft.length; ++j) {\n d.graft[j] = $root.RPC.ControlGraft.toObject(m.graft[j], o);\n }\n }\n if (m.prune && m.prune.length) {\n d.prune = [];\n for (var j = 0; j < m.prune.length; ++j) {\n d.prune[j] = $root.RPC.ControlPrune.toObject(m.prune[j], o);\n }\n }\n return d;\n };\n\n /**\n * Converts this ControlMessage to JSON.\n * @function toJSON\n * @memberof RPC.ControlMessage\n * @instance\n * @returns {Object.} JSON object\n */\n ControlMessage.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlMessage;\n })();\n\n RPC.ControlIHave = (function() {\n\n /**\n * Properties of a ControlIHave.\n * @memberof RPC\n * @interface IControlIHave\n * @property {string|null} [topicID] ControlIHave topicID\n * @property {Array.|null} [messageIDs] ControlIHave messageIDs\n */\n\n /**\n * Constructs a new ControlIHave.\n * @memberof RPC\n * @classdesc Represents a ControlIHave.\n * @implements IControlIHave\n * @constructor\n * @param {RPC.IControlIHave=} [p] Properties to set\n */\n function ControlIHave(p) {\n this.messageIDs = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlIHave topicID.\n * @member {string|null|undefined} topicID\n * @memberof RPC.ControlIHave\n * @instance\n */\n ControlIHave.prototype.topicID = null;\n\n /**\n * ControlIHave messageIDs.\n * @member {Array.} messageIDs\n * @memberof RPC.ControlIHave\n * @instance\n */\n ControlIHave.prototype.messageIDs = $util.emptyArray;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * ControlIHave _topicID.\n * @member {\"topicID\"|undefined} _topicID\n * @memberof RPC.ControlIHave\n * @instance\n */\n Object.defineProperty(ControlIHave.prototype, \"_topicID\", {\n get: $util.oneOfGetter($oneOfFields = [\"topicID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified ControlIHave message. Does not implicitly {@link RPC.ControlIHave.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlIHave\n * @static\n * @param {RPC.IControlIHave} m ControlIHave message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlIHave.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.topicID != null && Object.hasOwnProperty.call(m, \"topicID\"))\n w.uint32(10).string(m.topicID);\n if (m.messageIDs != null && m.messageIDs.length) {\n for (var i = 0; i < m.messageIDs.length; ++i)\n w.uint32(18).bytes(m.messageIDs[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ControlIHave message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlIHave\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlIHave} ControlIHave\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlIHave.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlIHave();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string();\n break;\n case 2:\n if (!(m.messageIDs && m.messageIDs.length))\n m.messageIDs = [];\n m.messageIDs.push(r.bytes());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlIHave message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlIHave\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlIHave} ControlIHave\n */\n ControlIHave.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlIHave)\n return d;\n var m = new $root.RPC.ControlIHave();\n if (d.topicID != null) {\n m.topicID = String(d.topicID);\n }\n if (d.messageIDs) {\n if (!Array.isArray(d.messageIDs))\n throw TypeError(\".RPC.ControlIHave.messageIDs: array expected\");\n m.messageIDs = [];\n for (var i = 0; i < d.messageIDs.length; ++i) {\n if (typeof d.messageIDs[i] === \"string\")\n $util.base64.decode(d.messageIDs[i], m.messageIDs[i] = $util.newBuffer($util.base64.length(d.messageIDs[i])), 0);\n else if (d.messageIDs[i].length)\n m.messageIDs[i] = d.messageIDs[i];\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlIHave message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlIHave\n * @static\n * @param {RPC.ControlIHave} m ControlIHave\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlIHave.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.messageIDs = [];\n }\n if (m.topicID != null && m.hasOwnProperty(\"topicID\")) {\n d.topicID = m.topicID;\n if (o.oneofs)\n d._topicID = \"topicID\";\n }\n if (m.messageIDs && m.messageIDs.length) {\n d.messageIDs = [];\n for (var j = 0; j < m.messageIDs.length; ++j) {\n d.messageIDs[j] = o.bytes === String ? $util.base64.encode(m.messageIDs[j], 0, m.messageIDs[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.messageIDs[j]) : m.messageIDs[j];\n }\n }\n return d;\n };\n\n /**\n * Converts this ControlIHave to JSON.\n * @function toJSON\n * @memberof RPC.ControlIHave\n * @instance\n * @returns {Object.} JSON object\n */\n ControlIHave.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlIHave;\n })();\n\n RPC.ControlIWant = (function() {\n\n /**\n * Properties of a ControlIWant.\n * @memberof RPC\n * @interface IControlIWant\n * @property {Array.|null} [messageIDs] ControlIWant messageIDs\n */\n\n /**\n * Constructs a new ControlIWant.\n * @memberof RPC\n * @classdesc Represents a ControlIWant.\n * @implements IControlIWant\n * @constructor\n * @param {RPC.IControlIWant=} [p] Properties to set\n */\n function ControlIWant(p) {\n this.messageIDs = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlIWant messageIDs.\n * @member {Array.} messageIDs\n * @memberof RPC.ControlIWant\n * @instance\n */\n ControlIWant.prototype.messageIDs = $util.emptyArray;\n\n /**\n * Encodes the specified ControlIWant message. Does not implicitly {@link RPC.ControlIWant.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlIWant\n * @static\n * @param {RPC.IControlIWant} m ControlIWant message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlIWant.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.messageIDs != null && m.messageIDs.length) {\n for (var i = 0; i < m.messageIDs.length; ++i)\n w.uint32(10).bytes(m.messageIDs[i]);\n }\n return w;\n };\n\n /**\n * Decodes a ControlIWant message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlIWant\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlIWant} ControlIWant\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlIWant.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlIWant();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.messageIDs && m.messageIDs.length))\n m.messageIDs = [];\n m.messageIDs.push(r.bytes());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlIWant message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlIWant\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlIWant} ControlIWant\n */\n ControlIWant.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlIWant)\n return d;\n var m = new $root.RPC.ControlIWant();\n if (d.messageIDs) {\n if (!Array.isArray(d.messageIDs))\n throw TypeError(\".RPC.ControlIWant.messageIDs: array expected\");\n m.messageIDs = [];\n for (var i = 0; i < d.messageIDs.length; ++i) {\n if (typeof d.messageIDs[i] === \"string\")\n $util.base64.decode(d.messageIDs[i], m.messageIDs[i] = $util.newBuffer($util.base64.length(d.messageIDs[i])), 0);\n else if (d.messageIDs[i].length)\n m.messageIDs[i] = d.messageIDs[i];\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlIWant message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlIWant\n * @static\n * @param {RPC.ControlIWant} m ControlIWant\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlIWant.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.messageIDs = [];\n }\n if (m.messageIDs && m.messageIDs.length) {\n d.messageIDs = [];\n for (var j = 0; j < m.messageIDs.length; ++j) {\n d.messageIDs[j] = o.bytes === String ? $util.base64.encode(m.messageIDs[j], 0, m.messageIDs[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.messageIDs[j]) : m.messageIDs[j];\n }\n }\n return d;\n };\n\n /**\n * Converts this ControlIWant to JSON.\n * @function toJSON\n * @memberof RPC.ControlIWant\n * @instance\n * @returns {Object.} JSON object\n */\n ControlIWant.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlIWant;\n })();\n\n RPC.ControlGraft = (function() {\n\n /**\n * Properties of a ControlGraft.\n * @memberof RPC\n * @interface IControlGraft\n * @property {string|null} [topicID] ControlGraft topicID\n */\n\n /**\n * Constructs a new ControlGraft.\n * @memberof RPC\n * @classdesc Represents a ControlGraft.\n * @implements IControlGraft\n * @constructor\n * @param {RPC.IControlGraft=} [p] Properties to set\n */\n function ControlGraft(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlGraft topicID.\n * @member {string|null|undefined} topicID\n * @memberof RPC.ControlGraft\n * @instance\n */\n ControlGraft.prototype.topicID = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * ControlGraft _topicID.\n * @member {\"topicID\"|undefined} _topicID\n * @memberof RPC.ControlGraft\n * @instance\n */\n Object.defineProperty(ControlGraft.prototype, \"_topicID\", {\n get: $util.oneOfGetter($oneOfFields = [\"topicID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified ControlGraft message. Does not implicitly {@link RPC.ControlGraft.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlGraft\n * @static\n * @param {RPC.IControlGraft} m ControlGraft message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlGraft.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.topicID != null && Object.hasOwnProperty.call(m, \"topicID\"))\n w.uint32(10).string(m.topicID);\n return w;\n };\n\n /**\n * Decodes a ControlGraft message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlGraft\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlGraft} ControlGraft\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlGraft.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlGraft();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlGraft message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlGraft\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlGraft} ControlGraft\n */\n ControlGraft.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlGraft)\n return d;\n var m = new $root.RPC.ControlGraft();\n if (d.topicID != null) {\n m.topicID = String(d.topicID);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlGraft message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlGraft\n * @static\n * @param {RPC.ControlGraft} m ControlGraft\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlGraft.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (m.topicID != null && m.hasOwnProperty(\"topicID\")) {\n d.topicID = m.topicID;\n if (o.oneofs)\n d._topicID = \"topicID\";\n }\n return d;\n };\n\n /**\n * Converts this ControlGraft to JSON.\n * @function toJSON\n * @memberof RPC.ControlGraft\n * @instance\n * @returns {Object.} JSON object\n */\n ControlGraft.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlGraft;\n })();\n\n RPC.ControlPrune = (function() {\n\n /**\n * Properties of a ControlPrune.\n * @memberof RPC\n * @interface IControlPrune\n * @property {string|null} [topicID] ControlPrune topicID\n * @property {Array.|null} [peers] ControlPrune peers\n * @property {number|null} [backoff] ControlPrune backoff\n */\n\n /**\n * Constructs a new ControlPrune.\n * @memberof RPC\n * @classdesc Represents a ControlPrune.\n * @implements IControlPrune\n * @constructor\n * @param {RPC.IControlPrune=} [p] Properties to set\n */\n function ControlPrune(p) {\n this.peers = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * ControlPrune topicID.\n * @member {string|null|undefined} topicID\n * @memberof RPC.ControlPrune\n * @instance\n */\n ControlPrune.prototype.topicID = null;\n\n /**\n * ControlPrune peers.\n * @member {Array.} peers\n * @memberof RPC.ControlPrune\n * @instance\n */\n ControlPrune.prototype.peers = $util.emptyArray;\n\n /**\n * ControlPrune backoff.\n * @member {number|null|undefined} backoff\n * @memberof RPC.ControlPrune\n * @instance\n */\n ControlPrune.prototype.backoff = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * ControlPrune _topicID.\n * @member {\"topicID\"|undefined} _topicID\n * @memberof RPC.ControlPrune\n * @instance\n */\n Object.defineProperty(ControlPrune.prototype, \"_topicID\", {\n get: $util.oneOfGetter($oneOfFields = [\"topicID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * ControlPrune _backoff.\n * @member {\"backoff\"|undefined} _backoff\n * @memberof RPC.ControlPrune\n * @instance\n */\n Object.defineProperty(ControlPrune.prototype, \"_backoff\", {\n get: $util.oneOfGetter($oneOfFields = [\"backoff\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified ControlPrune message. Does not implicitly {@link RPC.ControlPrune.verify|verify} messages.\n * @function encode\n * @memberof RPC.ControlPrune\n * @static\n * @param {RPC.IControlPrune} m ControlPrune message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n ControlPrune.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.topicID != null && Object.hasOwnProperty.call(m, \"topicID\"))\n w.uint32(10).string(m.topicID);\n if (m.peers != null && m.peers.length) {\n for (var i = 0; i < m.peers.length; ++i)\n $root.RPC.PeerInfo.encode(m.peers[i], w.uint32(18).fork()).ldelim();\n }\n if (m.backoff != null && Object.hasOwnProperty.call(m, \"backoff\"))\n w.uint32(24).uint64(m.backoff);\n return w;\n };\n\n /**\n * Decodes a ControlPrune message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.ControlPrune\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.ControlPrune} ControlPrune\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n ControlPrune.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.ControlPrune();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string();\n break;\n case 2:\n if (!(m.peers && m.peers.length))\n m.peers = [];\n m.peers.push($root.RPC.PeerInfo.decode(r, r.uint32()));\n break;\n case 3:\n m.backoff = r.uint64();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a ControlPrune message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.ControlPrune\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.ControlPrune} ControlPrune\n */\n ControlPrune.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.ControlPrune)\n return d;\n var m = new $root.RPC.ControlPrune();\n if (d.topicID != null) {\n m.topicID = String(d.topicID);\n }\n if (d.peers) {\n if (!Array.isArray(d.peers))\n throw TypeError(\".RPC.ControlPrune.peers: array expected\");\n m.peers = [];\n for (var i = 0; i < d.peers.length; ++i) {\n if (typeof d.peers[i] !== \"object\")\n throw TypeError(\".RPC.ControlPrune.peers: object expected\");\n m.peers[i] = $root.RPC.PeerInfo.fromObject(d.peers[i]);\n }\n }\n if (d.backoff != null) {\n if ($util.Long)\n (m.backoff = $util.Long.fromValue(d.backoff)).unsigned = true;\n else if (typeof d.backoff === \"string\")\n m.backoff = parseInt(d.backoff, 10);\n else if (typeof d.backoff === \"number\")\n m.backoff = d.backoff;\n else if (typeof d.backoff === \"object\")\n m.backoff = new $util.LongBits(d.backoff.low >>> 0, d.backoff.high >>> 0).toNumber(true);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a ControlPrune message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.ControlPrune\n * @static\n * @param {RPC.ControlPrune} m ControlPrune\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n ControlPrune.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.peers = [];\n }\n if (m.topicID != null && m.hasOwnProperty(\"topicID\")) {\n d.topicID = m.topicID;\n if (o.oneofs)\n d._topicID = \"topicID\";\n }\n if (m.peers && m.peers.length) {\n d.peers = [];\n for (var j = 0; j < m.peers.length; ++j) {\n d.peers[j] = $root.RPC.PeerInfo.toObject(m.peers[j], o);\n }\n }\n if (m.backoff != null && m.hasOwnProperty(\"backoff\")) {\n if (typeof m.backoff === \"number\")\n d.backoff = o.longs === String ? String(m.backoff) : m.backoff;\n else\n d.backoff = o.longs === String ? $util.Long.prototype.toString.call(m.backoff) : o.longs === Number ? new $util.LongBits(m.backoff.low >>> 0, m.backoff.high >>> 0).toNumber(true) : m.backoff;\n if (o.oneofs)\n d._backoff = \"backoff\";\n }\n return d;\n };\n\n /**\n * Converts this ControlPrune to JSON.\n * @function toJSON\n * @memberof RPC.ControlPrune\n * @instance\n * @returns {Object.} JSON object\n */\n ControlPrune.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return ControlPrune;\n })();\n\n RPC.PeerInfo = (function() {\n\n /**\n * Properties of a PeerInfo.\n * @memberof RPC\n * @interface IPeerInfo\n * @property {Uint8Array|null} [peerID] PeerInfo peerID\n * @property {Uint8Array|null} [signedPeerRecord] PeerInfo signedPeerRecord\n */\n\n /**\n * Constructs a new PeerInfo.\n * @memberof RPC\n * @classdesc Represents a PeerInfo.\n * @implements IPeerInfo\n * @constructor\n * @param {RPC.IPeerInfo=} [p] Properties to set\n */\n function PeerInfo(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * PeerInfo peerID.\n * @member {Uint8Array|null|undefined} peerID\n * @memberof RPC.PeerInfo\n * @instance\n */\n PeerInfo.prototype.peerID = null;\n\n /**\n * PeerInfo signedPeerRecord.\n * @member {Uint8Array|null|undefined} signedPeerRecord\n * @memberof RPC.PeerInfo\n * @instance\n */\n PeerInfo.prototype.signedPeerRecord = null;\n\n // OneOf field names bound to virtual getters and setters\n var $oneOfFields;\n\n /**\n * PeerInfo _peerID.\n * @member {\"peerID\"|undefined} _peerID\n * @memberof RPC.PeerInfo\n * @instance\n */\n Object.defineProperty(PeerInfo.prototype, \"_peerID\", {\n get: $util.oneOfGetter($oneOfFields = [\"peerID\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * PeerInfo _signedPeerRecord.\n * @member {\"signedPeerRecord\"|undefined} _signedPeerRecord\n * @memberof RPC.PeerInfo\n * @instance\n */\n Object.defineProperty(PeerInfo.prototype, \"_signedPeerRecord\", {\n get: $util.oneOfGetter($oneOfFields = [\"signedPeerRecord\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified PeerInfo message. Does not implicitly {@link RPC.PeerInfo.verify|verify} messages.\n * @function encode\n * @memberof RPC.PeerInfo\n * @static\n * @param {RPC.IPeerInfo} m PeerInfo message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n PeerInfo.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.peerID != null && Object.hasOwnProperty.call(m, \"peerID\"))\n w.uint32(10).bytes(m.peerID);\n if (m.signedPeerRecord != null && Object.hasOwnProperty.call(m, \"signedPeerRecord\"))\n w.uint32(18).bytes(m.signedPeerRecord);\n return w;\n };\n\n /**\n * Decodes a PeerInfo message from the specified reader or buffer.\n * @function decode\n * @memberof RPC.PeerInfo\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {RPC.PeerInfo} PeerInfo\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n PeerInfo.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.RPC.PeerInfo();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.peerID = r.bytes();\n break;\n case 2:\n m.signedPeerRecord = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a PeerInfo message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof RPC.PeerInfo\n * @static\n * @param {Object.} d Plain object\n * @returns {RPC.PeerInfo} PeerInfo\n */\n PeerInfo.fromObject = function fromObject(d) {\n if (d instanceof $root.RPC.PeerInfo)\n return d;\n var m = new $root.RPC.PeerInfo();\n if (d.peerID != null) {\n if (typeof d.peerID === \"string\")\n $util.base64.decode(d.peerID, m.peerID = $util.newBuffer($util.base64.length(d.peerID)), 0);\n else if (d.peerID.length)\n m.peerID = d.peerID;\n }\n if (d.signedPeerRecord != null) {\n if (typeof d.signedPeerRecord === \"string\")\n $util.base64.decode(d.signedPeerRecord, m.signedPeerRecord = $util.newBuffer($util.base64.length(d.signedPeerRecord)), 0);\n else if (d.signedPeerRecord.length)\n m.signedPeerRecord = d.signedPeerRecord;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a PeerInfo message. Also converts values to other types if specified.\n * @function toObject\n * @memberof RPC.PeerInfo\n * @static\n * @param {RPC.PeerInfo} m PeerInfo\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n PeerInfo.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (m.peerID != null && m.hasOwnProperty(\"peerID\")) {\n d.peerID = o.bytes === String ? $util.base64.encode(m.peerID, 0, m.peerID.length) : o.bytes === Array ? Array.prototype.slice.call(m.peerID) : m.peerID;\n if (o.oneofs)\n d._peerID = \"peerID\";\n }\n if (m.signedPeerRecord != null && m.hasOwnProperty(\"signedPeerRecord\")) {\n d.signedPeerRecord = o.bytes === String ? $util.base64.encode(m.signedPeerRecord, 0, m.signedPeerRecord.length) : o.bytes === Array ? Array.prototype.slice.call(m.signedPeerRecord) : m.signedPeerRecord;\n if (o.oneofs)\n d._signedPeerRecord = \"signedPeerRecord\";\n }\n return d;\n };\n\n /**\n * Converts this PeerInfo to JSON.\n * @function toJSON\n * @memberof RPC.PeerInfo\n * @instance\n * @returns {Object.} JSON object\n */\n PeerInfo.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return PeerInfo;\n })();\n\n return RPC;\n })();\n\n return $root;\n});\n", "'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array, options) {\n var options = options || {};\n\n this._head = 0;\n this._tail = 0;\n this._capacity = options.capacity;\n this._capacityMask = 0x3;\n this._list = new Array(4);\n if (Array.isArray(array)) {\n this._fromArray(array);\n }\n}\n\n/**\n * -------------\n * PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var len = this.size();\n if (i >= len || i < -len) return undefined;\n if (i < 0) i += len;\n i = (this._head + i) & this._capacityMask;\n return this._list[i];\n};\n\n/**\n * Alias for peekAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n if (this._head === this._tail) return undefined;\n return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n get: function length() {\n return this.size();\n }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n if (this._head === this._tail) return 0;\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n if (item === undefined) return this.size();\n var len = this._list.length;\n this._head = (this._head - 1 + len) & this._capacityMask;\n this._list[this._head] = item;\n if (this._tail === this._head) this._growArray();\n if (this._capacity && this.size() > this._capacity) this.pop();\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n var head = this._head;\n if (head === this._tail) return undefined;\n var item = this._list[head];\n this._list[head] = undefined;\n this._head = (head + 1) & this._capacityMask;\n if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n if (item === undefined) return this.size();\n var tail = this._tail;\n this._list[tail] = item;\n this._tail = (tail + 1) & this._capacityMask;\n if (this._tail === this._head) {\n this._growArray();\n }\n if (this._capacity && this.size() > this._capacity) {\n this.shift();\n }\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n var tail = this._tail;\n if (tail === this._head) return undefined;\n var len = this._list.length;\n this._tail = (tail - 1 + len) & this._capacityMask;\n var item = this._list[this._tail];\n this._list[this._tail] = undefined;\n if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size) return void 0;\n if (i < 0) i += size;\n i = (this._head + i) & this._capacityMask;\n var item = this._list[i];\n var k;\n if (index < size / 2) {\n for (k = index; k > 0; k--) {\n this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._head = (this._head + 1 + len) & this._capacityMask;\n } else {\n for (k = size - 1 - index; k > 0; k--) {\n this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._tail = (this._tail - 1 + len) & this._capacityMask;\n }\n return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n var i = index;\n var removed;\n var del_count = count;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size || count < 1) return void 0;\n if (i < 0) i += size;\n if (count === 1 || !count) {\n removed = new Array(1);\n removed[0] = this.removeOne(i);\n return removed;\n }\n if (i === 0 && i + count >= size) {\n removed = this.toArray();\n this.clear();\n return removed;\n }\n if (i + count > size) count = size - i;\n var k;\n removed = new Array(count);\n for (k = 0; k < count; k++) {\n removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n }\n i = (this._head + i) & this._capacityMask;\n if (index + count === size) {\n this._tail = (this._tail - count + len) & this._capacityMask;\n for (k = count; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (index === 0) {\n this._head = (this._head + count + len) & this._capacityMask;\n for (k = count - 1; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (i < size / 2) {\n this._head = (this._head + index + count + len) & this._capacityMask;\n for (k = index; k > 0; k--) {\n this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n }\n i = (this._head - 1 + len) & this._capacityMask;\n while (del_count > 0) {\n this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n if (index < 0) this._tail = i;\n } else {\n this._tail = i;\n i = (i + count + len) & this._capacityMask;\n for (k = size - (count + index); k > 0; k--) {\n this.push(this._list[i++]);\n }\n i = this._tail;\n while (del_count > 0) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n }\n if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var size = this.size();\n if (i < 0) i += size;\n if (i > size) return void 0;\n if (arguments.length > 2) {\n var k;\n var temp;\n var removed;\n var arg_len = arguments.length;\n var len = this._list.length;\n var arguments_index = 2;\n if (!size || i < size / 2) {\n temp = new Array(i);\n for (k = 0; k < i; k++) {\n temp[k] = this._list[(this._head + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i > 0) {\n this._head = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._head = (this._head + i + len) & this._capacityMask;\n }\n while (arg_len > arguments_index) {\n this.unshift(arguments[--arg_len]);\n }\n for (k = i; k > 0; k--) {\n this.unshift(temp[k - 1]);\n }\n } else {\n temp = new Array(size - (i + count));\n var leng = temp.length;\n for (k = 0; k < leng; k++) {\n temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i != size) {\n this._tail = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._tail = (this._tail - leng + len) & this._capacityMask;\n }\n while (arguments_index < arg_len) {\n this.push(arguments[arguments_index++]);\n }\n for (k = 0; k < leng; k++) {\n this.push(temp[k]);\n }\n }\n return removed;\n } else {\n return this.remove(i, count);\n }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n this._head = 0;\n this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n return this._copyArray(false);\n};\n\n/**\n * -------------\n * INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n for (var i = 0; i < array.length; i++) this.push(array[i]);\n};\n\n/**\n *\n * @param fullCopy\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy) {\n var newArray = [];\n var list = this._list;\n var len = list.length;\n var i;\n if (fullCopy || this._head > this._tail) {\n for (i = this._head; i < len; i++) newArray.push(list[i]);\n for (i = 0; i < this._tail; i++) newArray.push(list[i]);\n } else {\n for (i = this._head; i < this._tail; i++) newArray.push(list[i]);\n }\n return newArray;\n};\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n if (this._head) {\n // copy existing data, head to end, then beginning to tail.\n this._list = this._copyArray(true);\n this._head = 0;\n }\n\n // head is at 0 and array is now full, safe to extend\n this._tail = this._list.length;\n\n this._list.length <<= 1;\n this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n this._list.length >>>= 1;\n this._capacityMask >>>= 1;\n};\n\n\nmodule.exports = Denque;\n", "module.exports = readable => {\n // Node.js stream\n if (readable[Symbol.asyncIterator]) return readable\n\n // Browser ReadableStream\n if (readable.getReader) {\n return (async function * () {\n const reader = readable.getReader()\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) return\n yield value\n }\n } finally {\n reader.releaseLock()\n }\n })()\n }\n\n throw new Error('unknown stream')\n}\n", "'use strict'\n\nconst HTTP = require('../http')\n\n/**\n *\n * @param {string} url\n * @param {import(\"../types\").HTTPOptions} [options]\n * @returns {{ path: string; content?: AsyncIterable }}\n */\nconst urlSource = (url, options) => {\n return {\n path: decodeURIComponent(new URL(url).pathname.split('/').pop() || ''),\n content: readURLContent(url, options)\n }\n}\n\n/**\n *\n * @param {string} url\n * @param {import(\"../types\").HTTPOptions} [options]\n * @returns {AsyncIterable}\n */\nasync function * readURLContent (url, options) {\n const http = new HTTP()\n const response = await http.get(url, options)\n\n yield * response.iterator()\n}\n\nmodule.exports = urlSource\n", "'use strict'\n\n// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nconst MAX_BYTES = 65536\n\n/**\n * @param {number} size\n */\nfunction randomBytes(size) {\n const bytes = new Uint8Array(size)\n let generated = 0\n\n if (size > 0) {\n // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) {\n while (generated < size) {\n if (generated + MAX_BYTES > size) {\n crypto.getRandomValues(\n bytes.subarray(generated, generated + (size - generated))\n )\n generated += size - generated\n } else {\n crypto.getRandomValues(\n bytes.subarray(generated, generated + MAX_BYTES)\n )\n generated += MAX_BYTES\n }\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n\n return bytes\n}\n\nmodule.exports = randomBytes\n", "'use strict';\n\n// 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 createDelay = ({clearTimeout: defaultClear, setTimeout: set, willResolve}) => (ms, {value, signal} = {}) => {\n\tif (signal && signal.aborted) {\n\t\treturn Promise.reject(createAbortError());\n\t}\n\n\tlet timeoutId;\n\tlet settle;\n\tlet rejectFn;\n\tconst clear = defaultClear || clearTimeout;\n\n\tconst signalListener = () => {\n\t\tclear(timeoutId);\n\t\trejectFn(createAbortError());\n\t};\n\n\tconst cleanup = () => {\n\t\tif (signal) {\n\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t}\n\t};\n\n\tconst delayPromise = new Promise((resolve, reject) => {\n\t\tsettle = () => {\n\t\t\tcleanup();\n\t\t\tif (willResolve) {\n\t\t\t\tresolve(value);\n\t\t\t} else {\n\t\t\t\treject(value);\n\t\t\t}\n\t\t};\n\n\t\trejectFn = reject;\n\t\ttimeoutId = (set || setTimeout)(settle, ms);\n\t});\n\n\tif (signal) {\n\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t}\n\n\tdelayPromise.clear = () => {\n\t\tclear(timeoutId);\n\t\ttimeoutId = null;\n\t\tsettle();\n\t};\n\n\treturn delayPromise;\n};\n\nconst createWithTimers = clearAndSet => {\n\tconst delay = createDelay({...clearAndSet, willResolve: true});\n\tdelay.reject = createDelay({...clearAndSet, willResolve: false});\n\tdelay.range = (minimum, maximum, options) => delay(randomInteger(minimum, maximum), options);\n\treturn delay;\n};\n\nconst delay = createWithTimers();\ndelay.createWithTimers = createWithTimers;\n\nmodule.exports = delay;\n// TODO: Remove this for the next major release\nmodule.exports.default = delay;\n", "'use strict'\n\nconst intervals = new Map()\n\nconst _generateId = () => `${Date.now()}:${Math.floor(Math.random() * 1000000)}`\n\n/**\n * Run a given task each {interval} ms\n *\n * @param {() => Promise} task\n * @param {number} interval\n * @param {string} id\n */\nasync function _runPeriodically (task, interval, id) {\n while (intervals.get(id)) {\n try {\n await task()\n } catch (err) {\n // Throw global context error if handler throws\n setTimeout(() => { throw err }, 1)\n break\n }\n\n if (!intervals.get(id)) {\n break\n }\n\n await new Promise(resolve => {\n const _timeout = setTimeout(resolve, interval)\n\n intervals.set(id, _timeout)\n })\n }\n}\n\n/**\n * Asynchronous setInterval that is properly delayed using promises and can be delayed on boot.\n *\n * @param {() => Promise} task\n * @param {number} interval\n * @param {number} [delay = interval]\n * @returns {string}\n */\nfunction setDelayedInterval (task, interval, delay) {\n delay = delay || interval\n\n const id = _generateId()\n const _timeout = setTimeout(() => {\n _runPeriodically(task, interval, id)\n }, delay)\n\n intervals.set(id, _timeout)\n\n return id\n}\n\n/**\n * Clear delayed interval.\n *\n * @param {string} id\n */\nfunction clearDelayedInterval (id) {\n const _timeout = intervals.get(id)\n\n if (_timeout) {\n clearTimeout(_timeout)\n intervals.delete(id)\n }\n}\n\nmodule.exports = {\n setDelayedInterval,\n clearDelayedInterval\n}\n", "module.exports = class RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * points: 4, // Number of points\n * duration: 1, // Per seconds\n * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds\n * execEvenly: false, // Execute allowed actions evenly over duration\n * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option\n * keyPrefix: 'rlflx',\n * }\n */\n constructor(opts = {}) {\n this.points = opts.points;\n this.duration = opts.duration;\n this.blockDuration = opts.blockDuration;\n this.execEvenly = opts.execEvenly;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs;\n this.keyPrefix = opts.keyPrefix;\n }\n\n get points() {\n return this._points;\n }\n\n set points(value) {\n this._points = value >= 0 ? value : 4;\n }\n\n get duration() {\n return this._duration;\n }\n\n set duration(value) {\n this._duration = typeof value === 'undefined' ? 1 : value;\n }\n\n get msDuration() {\n return this.duration * 1000;\n }\n\n get blockDuration() {\n return this._blockDuration;\n }\n\n set blockDuration(value) {\n this._blockDuration = typeof value === 'undefined' ? 0 : value;\n }\n\n get msBlockDuration() {\n return this.blockDuration * 1000;\n }\n\n get execEvenly() {\n return this._execEvenly;\n }\n\n set execEvenly(value) {\n this._execEvenly = typeof value === 'undefined' ? false : Boolean(value);\n }\n\n get execEvenlyMinDelayMs() {\n return this._execEvenlyMinDelayMs;\n }\n\n set execEvenlyMinDelayMs(value) {\n this._execEvenlyMinDelayMs = typeof value === 'undefined' ? Math.ceil(this.msDuration / this.points) : value;\n }\n\n get keyPrefix() {\n return this._keyPrefix;\n }\n\n set keyPrefix(value) {\n if (typeof value === 'undefined') {\n value = 'rlflx';\n }\n if (typeof value !== 'string') {\n throw new Error('keyPrefix must be string');\n }\n this._keyPrefix = value;\n }\n\n _getKeySecDuration(options = {}) {\n return options && options.customDuration >= 0\n ? options.customDuration\n : this.duration;\n }\n\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n\n consume() {\n throw new Error(\"You have to implement the method 'consume'!\");\n }\n\n penalty() {\n throw new Error(\"You have to implement the method 'penalty'!\");\n }\n\n reward() {\n throw new Error(\"You have to implement the method 'reward'!\");\n }\n\n get() {\n throw new Error(\"You have to implement the method 'get'!\");\n }\n\n set() {\n throw new Error(\"You have to implement the method 'set'!\");\n }\n\n block() {\n throw new Error(\"You have to implement the method 'block'!\");\n }\n\n delete() {\n throw new Error(\"You have to implement the method 'delete'!\");\n }\n};\n", "module.exports = class BlockedKeys {\n constructor() {\n this._keys = {}; // {'key': 1526279430331}\n this._addedKeysAmount = 0;\n }\n\n collectExpired() {\n const now = Date.now();\n\n Object.keys(this._keys).forEach((key) => {\n if (this._keys[key] <= now) {\n delete this._keys[key];\n }\n });\n\n this._addedKeysAmount = Object.keys(this._keys).length;\n }\n\n /**\n * Add new blocked key\n *\n * @param key String\n * @param sec Number\n */\n add(key, sec) {\n this.addMs(key, sec * 1000);\n }\n\n /**\n * Add new blocked key for ms\n *\n * @param key String\n * @param ms Number\n */\n addMs(key, ms) {\n this._keys[key] = Date.now() + ms;\n this._addedKeysAmount++;\n if (this._addedKeysAmount > 999) {\n this.collectExpired();\n }\n }\n\n /**\n * 0 means not blocked\n *\n * @param key\n * @returns {number}\n */\n msBeforeExpire(key) {\n const expire = this._keys[key];\n\n if (expire && expire >= Date.now()) {\n this.collectExpired();\n const now = Date.now();\n return expire >= now ? expire - now : 0;\n }\n\n return 0;\n }\n\n /**\n * If key is not given, delete all data in memory\n * \n * @param {string|undefined} key\n */\n delete(key) {\n if (key) {\n delete this._keys[key];\n } else {\n Object.keys(this._keys).forEach((key) => {\n delete this._keys[key];\n });\n }\n }\n};\n", "const BlockedKeys = require('./BlockedKeys');\n\nmodule.exports = BlockedKeys;\n", "module.exports = class RateLimiterRes {\n constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) {\n this.remainingPoints = typeof remainingPoints === 'undefined' ? 0 : remainingPoints; // Remaining points in current duration\n this.msBeforeNext = typeof msBeforeNext === 'undefined' ? 0 : msBeforeNext; // Milliseconds before next action\n this.consumedPoints = typeof consumedPoints === 'undefined' ? 0 : consumedPoints; // Consumed points in current duration\n this.isFirstInDuration = typeof isFirstInDuration === 'undefined' ? false : isFirstInDuration;\n }\n\n get msBeforeNext() {\n return this._msBeforeNext;\n }\n\n set msBeforeNext(ms) {\n this._msBeforeNext = ms;\n return this;\n }\n\n get remainingPoints() {\n return this._remainingPoints;\n }\n\n set remainingPoints(p) {\n this._remainingPoints = p;\n return this;\n }\n\n get consumedPoints() {\n return this._consumedPoints;\n }\n\n set consumedPoints(p) {\n this._consumedPoints = p;\n return this;\n }\n\n get isFirstInDuration() {\n return this._isFirstInDuration;\n }\n\n set isFirstInDuration(value) {\n this._isFirstInDuration = Boolean(value);\n }\n\n _getDecoratedProperties() {\n return {\n remainingPoints: this.remainingPoints,\n msBeforeNext: this.msBeforeNext,\n consumedPoints: this.consumedPoints,\n isFirstInDuration: this.isFirstInDuration,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this._getDecoratedProperties();\n }\n\n toString() {\n return JSON.stringify(this._getDecoratedProperties());\n }\n\n toJSON() {\n return this._getDecoratedProperties();\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst BlockedKeys = require('./component/BlockedKeys');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RateLimiterStoreAbstract extends RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * ... see other in RateLimiterAbstract\n *\n * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked\n * inMemoryBlockDuration: 10, // Block duration in seconds\n * insuranceLimiter: RateLimiterAbstract\n * }\n */\n constructor(opts = {}) {\n super(opts);\n\n this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed || opts.inmemoryBlockOnConsumed;\n this.inMemoryBlockDuration = opts.inMemoryBlockDuration || opts.inmemoryBlockDuration;\n this.insuranceLimiter = opts.insuranceLimiter;\n this._inMemoryBlockedKeys = new BlockedKeys();\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('storeClient is not set');\n }\n this._client = value;\n }\n\n /**\n * Have to be launched after consume\n * It blocks key and execute evenly depending on result from store\n *\n * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result\n *\n * @param resolve\n * @param reject\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @param {Object} options\n * @private\n */\n _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) {\n const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult);\n\n if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0)\n && res.consumedPoints >= this.inMemoryBlockOnConsumed\n ) {\n this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext);\n if (res.consumedPoints > this.points) {\n return reject(res);\n } else {\n return resolve(res)\n }\n } else if (res.consumedPoints > this.points) {\n let blockPromise = Promise.resolve();\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + changedPoints)) {\n res.msBeforeNext = this.msBlockDuration;\n blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options);\n }\n\n if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) {\n // Block key for this.inMemoryBlockDuration seconds\n this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration);\n res.msBeforeNext = this.msInMemoryBlockDuration;\n }\n\n blockPromise\n .then(() => {\n reject(res);\n })\n .catch((err) => {\n reject(err);\n });\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n }\n\n _handleError(err, funcName, resolve, reject, key, data = false, options = {}) {\n if (!(this.insuranceLimiter instanceof RateLimiterAbstract)) {\n reject(err);\n } else {\n this.insuranceLimiter[funcName](key, data, options)\n .then((res) => {\n resolve(res);\n })\n .catch((res) => {\n reject(res);\n });\n }\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {BlockedKeys}\n * @private\n */\n get _inmemoryBlockedKeys() {\n return this._inMemoryBlockedKeys\n }\n\n /**\n * @deprecated Use camelCase version\n * @param rlKey\n * @returns {number}\n */\n getInmemoryBlockMsBeforeExpire(rlKey) {\n return this.getInMemoryBlockMsBeforeExpire(rlKey)\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockOnConsumed() {\n return this.inMemoryBlockOnConsumed;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockOnConsumed(value) {\n this.inMemoryBlockOnConsumed = value;\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockDuration() {\n return this.inMemoryBlockDuration;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockDuration(value) {\n this.inMemoryBlockDuration = value\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number}\n */\n get msInmemoryBlockDuration() {\n return this.inMemoryBlockDuration * 1000;\n }\n\n getInMemoryBlockMsBeforeExpire(rlKey) {\n if (this.inMemoryBlockOnConsumed > 0) {\n return this._inMemoryBlockedKeys.msBeforeExpire(rlKey);\n }\n\n return 0;\n }\n\n get inMemoryBlockOnConsumed() {\n return this._inMemoryBlockOnConsumed;\n }\n\n set inMemoryBlockOnConsumed(value) {\n this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0;\n if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) {\n throw new Error('inMemoryBlockOnConsumed option must be greater or equal \"points\" option');\n }\n }\n\n get inMemoryBlockDuration() {\n return this._inMemoryBlockDuration;\n }\n\n set inMemoryBlockDuration(value) {\n this._inMemoryBlockDuration = value ? parseInt(value) : 0;\n if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) {\n throw new Error('inMemoryBlockOnConsumed option must be set up');\n }\n }\n\n get msInMemoryBlockDuration() {\n return this._inMemoryBlockDuration * 1000;\n }\n\n get insuranceLimiter() {\n return this._insuranceLimiter;\n }\n\n set insuranceLimiter(value) {\n if (typeof value !== 'undefined' && !(value instanceof RateLimiterAbstract)) {\n throw new Error('insuranceLimiter must be instance of RateLimiterAbstract');\n }\n this._insuranceLimiter = value;\n if (this._insuranceLimiter) {\n this._insuranceLimiter.blockDuration = this.blockDuration;\n this._insuranceLimiter.execEvenly = this.execEvenly;\n }\n }\n\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n block(key, secDuration, options = {}) {\n const msDuration = secDuration * 1000;\n return this._block(this.getKey(key), this.points + 1, msDuration, options);\n }\n\n /**\n * Set points by key for any duration\n *\n * @param key\n * @param points\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n set(key, points, secDuration, options = {}) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n return this._block(this.getKey(key), points, msDuration, options);\n }\n\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns Promise\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const rlKey = this.getKey(key);\n\n const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey);\n if (inMemoryBlockMsBeforeExpire > 0) {\n return reject(new RateLimiterRes(0, inMemoryBlockMsBeforeExpire));\n }\n\n this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n this._afterConsume(resolve, reject, rlKey, pointsToConsume, res);\n })\n .catch((err) => {\n this._handleError(err, 'consume', resolve, reject, key, pointsToConsume, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, points, res));\n })\n .catch((err) => {\n this._handleError(err, 'penalty', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, -points, res));\n })\n .catch((err) => {\n this._handleError(err, 'reward', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise|null\n */\n get(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._get(rlKey, options)\n .then((res) => {\n if (res === null || typeof res === 'undefined') {\n resolve(null);\n } else {\n resolve(this._getRateLimiterRes(rlKey, 0, res));\n }\n })\n .catch((err) => {\n this._handleError(err, 'get', resolve, reject, key, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise\n */\n delete(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._delete(rlKey, options)\n .then((res) => {\n this._inMemoryBlockedKeys.delete(rlKey);\n resolve(res);\n })\n .catch((err) => {\n this._handleError(err, 'delete', resolve, reject, key, options);\n });\n });\n }\n\n /**\n * Cleanup keys no-matter expired or not.\n */\n deleteInMemoryBlockedAll() {\n this._inMemoryBlockedKeys.delete();\n }\n\n /**\n * Get RateLimiterRes object filled depending on storeResult, which specific for exact store\n *\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @private\n */\n _getRateLimiterRes(rlKey, changedPoints, storeResult) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_getRateLimiterRes'!\");\n }\n\n /**\n * Block key for this.msBlockDuration milliseconds\n * Usually, it just prolongs lifetime of key\n *\n * @param rlKey\n * @param initPoints\n * @param msDuration\n * @param {Object} options\n *\n * @return Promise\n */\n _block(rlKey, initPoints, msDuration, options = {}) {\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, initPoints, msDuration, true, options)\n .then(() => {\n resolve(new RateLimiterRes(0, msDuration > 0 ? msDuration : -1, initPoints));\n })\n .catch((err) => {\n this._handleError(err, 'block', resolve, reject, this.parseKey(rlKey), msDuration / 1000, options);\n });\n });\n }\n\n /**\n * Have to be implemented in every limiter\n * Resolve with raw result from Store OR null if rlKey is not set\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _get(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_get'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with true OR false if rlKey doesn't exist\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _delete(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_delete'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}\n *\n * @param {string} rlKey\n * @param {number} points\n * @param {number} msDuration\n * @param {boolean} forceExpire\n * @param {Object} options\n * @abstract\n *\n * @return Promise\n */\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n throw new Error(\"You have to implement the method '_upsert'!\");\n }\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst incrTtlLuaScript = `redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') \\\nlocal consumed = redis.call('incrby', KEYS[1], ARGV[1]) \\\nlocal ttl = redis.call('pttl', KEYS[1]) \\\nif ttl == -1 then \\\n redis.call('expire', KEYS[1], ARGV[2]) \\\n ttl = 1000 * ARGV[2] \\\nend \\\nreturn {consumed, ttl} \\\n`;\n\nclass RateLimiterRedis extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * redis: RedisClient\n * rejectIfRedisNotReady: boolean = false - reject / invoke insuranceLimiter immediately when redis connection is not \"ready\"\n * }\n */\n constructor(opts) {\n super(opts);\n if (opts.redis) {\n this.client = opts.redis;\n } else {\n this.client = opts.storeClient;\n }\n\n this._rejectIfRedisNotReady = !!opts.rejectIfRedisNotReady;\n\n if (typeof this.client.defineCommand === 'function') {\n this.client.defineCommand(\"rlflxIncr\", {\n numberOfKeys: 1,\n lua: incrTtlLuaScript,\n });\n }\n }\n\n /**\n * Prevent actual redis call if redis connection is not ready\n * Because of different connection state checks for ioredis and node-redis, only this clients would be actually checked.\n * For any other clients all the requests would be passed directly to redis client\n * @return {boolean}\n * @private\n */\n _isRedisReady() {\n if (!this._rejectIfRedisNotReady) {\n return true;\n }\n // ioredis client\n if (this.client.status && this.client.status !== 'ready') {\n return false;\n }\n // node-redis client\n if (typeof this.client.isReady === 'function' && !this.client.isReady()) {\n return false;\n }\n return true;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n let [consumed, resTtlMs] = result;\n // Support ioredis results format\n if (Array.isArray(consumed)) {\n [, consumed] = consumed;\n [, resTtlMs] = resTtlMs;\n }\n\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(consumed);\n res.isFirstInDuration = res.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = resTtlMs;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n const secDuration = Math.floor(msDuration / 1000);\n const multi = this.client.multi();\n if (forceExpire) {\n if (secDuration > 0) {\n multi.set(rlKey, points, 'EX', secDuration);\n } else {\n multi.set(rlKey, points);\n }\n\n multi.pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n } else {\n if (secDuration > 0) {\n const incrCallback = function(err, result) {\n if (err) {\n return reject(err);\n }\n\n return resolve(result);\n };\n\n if (typeof this.client.rlflxIncr === 'function') {\n this.client.rlflxIncr(rlKey, points, secDuration, incrCallback);\n } else {\n this.client.eval(incrTtlLuaScript, 1, rlKey, points, secDuration, incrCallback);\n }\n } else {\n multi.incrby(rlKey, points)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n }\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n this.client\n .multi()\n .get(rlKey)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n reject(err);\n } else {\n const [points] = res;\n if (points === null) {\n return resolve(null)\n }\n\n resolve(res);\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res > 0);\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterRedis;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\n/**\n * Get MongoDB driver version as upsert options differ\n * @params {Object} Client instance\n * @returns {Object} Version Object containing major, feature & minor versions.\n */\nfunction getDriverVersion(client) {\n try {\n const _client = client.client ? client.client : client;\n\n const { version } = _client.topology.s.options.metadata.driver;\n const _v = version.split('.').map(v => parseInt(v));\n\n return {\n major: _v[0],\n feature: _v[1],\n patch: _v[2],\n };\n } catch (err) {\n return { major: 0, feature: 0, patch: 0 };\n }\n}\n\nclass RateLimiterMongo extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * indexKeyPrefix: {attr1: 1, attr2: 1}\n * ... see other in RateLimiterStoreAbstract\n *\n * mongo: MongoClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n this.indexKeyPrefix = opts.indexKeyPrefix;\n\n if (opts.mongo) {\n this.client = opts.mongo;\n } else {\n this.client = opts.storeClient;\n }\n if (typeof this.client.then === 'function') {\n // If Promise\n this.client\n .then((conn) => {\n this.client = conn;\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n });\n } else {\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n }\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? RateLimiterMongo.getDbName() : value;\n }\n\n static getDbName() {\n return 'node-rate-limiter-flexible';\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('mongo is not set');\n }\n this._client = value;\n }\n\n get indexKeyPrefix() {\n return this._indexKeyPrefix;\n }\n\n set indexKeyPrefix(obj) {\n this._indexKeyPrefix = obj || {};\n }\n\n _initCollection() {\n const db = typeof this.client.db === 'function'\n ? this.client.db(this.dbName)\n : this.client;\n\n const collection = db.collection(this.tableName);\n collection.createIndex({ expire: -1 }, { expireAfterSeconds: 0 });\n collection.createIndex(Object.assign({}, this.indexKeyPrefix, { key: 1 }), { unique: true });\n\n this._collection = collection;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n\n let doc;\n if (typeof result.value === 'undefined') {\n doc = result;\n } else {\n doc = result.value;\n }\n\n res.isFirstInDuration = doc.points === changedPoints;\n res.consumedPoints = doc.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = doc.expire !== null\n ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsert(key, points, msDuration, forceExpire = false, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n let where;\n let upsertData;\n if (forceExpire) {\n where = { key };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $set: {\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n };\n upsertData.$set = Object.assign(upsertData.$set, docAttrs);\n } else {\n where = {\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $setOnInsert: {\n key,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n $inc: { points },\n };\n upsertData.$setOnInsert = Object.assign(upsertData.$setOnInsert, docAttrs);\n }\n\n // Options for collection updates differ between driver versions\n const upsertOptions = {\n upsert: true,\n };\n if ((this._driverVersion.major >= 4) ||\n (this._driverVersion.major === 3 &&\n (this._driverVersion.feature >=7) || \n (this._driverVersion.feature >= 6 && \n this._driverVersion.patch >= 7 ))) \n {\n upsertOptions.returnDocument = 'after';\n } else {\n upsertOptions.returnOriginal = false;\n }\n\n /*\n * 1. Find actual limit and increment points\n * 2. If limit expired, but Mongo doesn't clean doc by TTL yet, try to replace limit doc completely\n * 3. If 2 or more Mongo threads try to insert the new limit doc, only the first succeed\n * 4. Try to upsert from step 1. Actual limit is created now, points are incremented without problems\n */\n return new Promise((resolve, reject) => {\n this._collection.findOneAndUpdate(\n where,\n upsertData,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errUpsert) => {\n if (errUpsert && errUpsert.code === 11000) { // E11000 duplicate key error collection\n const replaceWhere = Object.assign({ // try to replace OLD limit doc\n $or: [\n { expire: { $lte: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n }, docAttrs);\n\n const replaceTo = {\n $set: Object.assign({\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n }, docAttrs)\n };\n\n this._collection.findOneAndUpdate(\n replaceWhere,\n replaceTo,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errReplace) => {\n if (errReplace && errReplace.code === 11000) { // E11000 duplicate key error collection\n this._upsert(key, points, msDuration, forceExpire)\n .then(res => resolve(res))\n .catch(err => reject(err));\n } else {\n reject(errReplace);\n }\n });\n } else {\n reject(errUpsert);\n }\n });\n });\n }\n\n _get(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n const where = Object.assign({\n key: rlKey,\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n }, docAttrs);\n\n return this._collection.findOne(where);\n }\n\n _delete(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n const where = Object.assign({ key: rlKey }, docAttrs);\n\n return this._collection.deleteOne(where)\n .then(res => res.deletedCount > 0);\n }\n}\n\nmodule.exports = RateLimiterMongo;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMySQL extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: anySqlClient,\n * storeType: 'knex', // required only for Knex instance\n * dbName: 'string',\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createDbAndTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`DELETE FROM ??.?? WHERE expire < ?`, [this.dbName, this.tableName, expire], () => {\n this._releaseConnection(conn);\n resolve();\n });\n })\n .catch(() => {\n resolve();\n });\n });\n }\n\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return new Promise((resolve, reject) => {\n this.client.getConnection((errConn, conn) => {\n if (errConn) {\n return reject(errConn);\n }\n\n resolve(conn);\n });\n });\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return conn.release();\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createDbAndTable() {\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`CREATE DATABASE IF NOT EXISTS \\`${this.dbName}\\`;`, (errDb) => {\n if (errDb) {\n this._releaseConnection(conn);\n return reject(errDb);\n }\n conn.query(this._getCreateTableStmt(), (err) => {\n if (err) {\n this._releaseConnection(conn);\n return reject(err);\n }\n this._releaseConnection(conn);\n resolve();\n });\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS \\`${this.dbName}\\`.\\`${this.tableName}\\` (` +\n '`key` VARCHAR(255) CHARACTER SET utf8 NOT NULL,' +\n '`points` INT(9) NOT NULL default 0,' +\n '`expire` BIGINT UNSIGNED,' +\n 'PRIMARY KEY (`key`)' +\n ') ENGINE = INNODB;';\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n if (typeof value === 'undefined') {\n if (this.client.constructor.name === 'Connection') {\n value = 'connection';\n } else if (this.client.constructor.name === 'Pool') {\n value = 'pool';\n } else if (this.client.constructor.name === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n this._clientType = value.toLowerCase();\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? 'rtlmtrflx' : value;\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const [row] = result;\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsertTransaction(conn, key, points, msDuration, forceExpire) {\n return new Promise((resolve, reject) => {\n conn.query('BEGIN', (errBegin) => {\n if (errBegin) {\n conn.rollback();\n\n return reject(errBegin);\n }\n\n const dateNow = Date.now();\n const newExpire = msDuration > 0 ? dateNow + msDuration : null;\n\n let q;\n let values;\n if (forceExpire) {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = ?, \n expire = ?;`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n points,\n newExpire,\n ];\n } else {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = IF(expire <= ?, ?, points + (?)), \n expire = IF(expire <= ?, ?, expire);`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n dateNow, points, points,\n dateNow, newExpire,\n ];\n }\n\n conn.query(q, values, (errUpsert) => {\n if (errUpsert) {\n conn.rollback();\n\n return reject(errUpsert);\n }\n conn.query('SELECT points, expire FROM ??.?? WHERE `key` = ?;', [this.dbName, this.tableName, key], (errSelect, res) => {\n if (errSelect) {\n conn.rollback();\n\n return reject(errSelect);\n }\n\n conn.query('COMMIT', (err) => {\n if (err) {\n conn.rollback();\n\n return reject(err);\n }\n\n resolve(res);\n });\n });\n });\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n this._upsertTransaction(conn, key, points, msDuration, forceExpire)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)',\n [this.dbName, this.tableName, rlKey, Date.now()],\n (err, res) => {\n if (err) {\n reject(err);\n } else if (res.length === 0) {\n resolve(null);\n } else {\n resolve(res);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'DELETE FROM ??.?? WHERE `key` = ?',\n [this.dbName, this.tableName, rlKey],\n (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res.affectedRows > 0);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMySQL;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterPostgres extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: postgresClient,\n * storeType: 'knex', // required only for Knex instance\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n const q = {\n name: 'rlflx-clear-expired',\n text: `DELETE FROM ${this.tableName} WHERE expire < $1`,\n values: [expire],\n };\n this._query(q)\n .then(() => {\n resolve();\n })\n .catch(() => {\n // Deleting expired query is not critical\n resolve();\n });\n });\n }\n\n /**\n * Delete all rows expired 1 hour ago once per 5 minutes\n *\n * @private\n */\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return Promise.resolve(this.client);\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n case 'typeorm':\n return Promise.resolve(this.client.driver.master);\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return true;\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n case 'typeorm':\n return true;\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createTable() {\n return new Promise((resolve, reject) => {\n this._query({\n text: this._getCreateTableStmt(),\n })\n .then(() => {\n resolve();\n })\n .catch((err) => {\n if (err.code === '23505') {\n // Error: duplicate key value violates unique constraint \"pg_type_typname_nsp_index\"\n // Postgres doesn't handle concurrent table creation\n // It is supposed, that table is created by another worker\n resolve();\n } else {\n reject(err);\n }\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS ${this.tableName} ( \n key varchar(255) PRIMARY KEY,\n points integer NOT NULL DEFAULT 0,\n expire bigint\n );`;\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n const constructorName = this.client.constructor.name;\n\n if (typeof value === 'undefined') {\n if (constructorName === 'Client') {\n value = 'client';\n } else if (\n constructorName === 'Pool' ||\n constructorName === 'BoundPool'\n ) {\n value = 'pool';\n } else if (constructorName === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n\n this._clientType = value.toLowerCase();\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const row = result.rows[0];\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _query(q) {\n const prefix = this.tableName.toLowerCase();\n const queryObj = { name: `${prefix}:${q.name}`, text: q.text, values: q.values };\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(queryObj)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n const newExpire = msDuration > 0 ? Date.now() + msDuration : null;\n const expireQ = forceExpire\n ? ' $3 '\n : ` CASE\n WHEN ${this.tableName}.expire <= $4 THEN $3\n ELSE ${this.tableName}.expire\n END `;\n\n return this._query({\n name: forceExpire ? 'rlflx-upsert-force' : 'rlflx-upsert',\n text: `\n INSERT INTO ${this.tableName} VALUES ($1, $2, $3)\n ON CONFLICT(key) DO UPDATE SET\n points = CASE\n WHEN (${this.tableName}.expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2\n ELSE ${this.tableName}.points + ($2)\n END,\n expire = ${expireQ}\n RETURNING points, expire;`,\n values: [key, points, newExpire, Date.now()],\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._query({\n name: 'rlflx-get',\n text: `\n SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,\n values: [rlKey, Date.now()],\n })\n .then((res) => {\n if (res.rowCount === 0) {\n res = null;\n }\n resolve(res);\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return this._query({\n name: 'rlflx-delete',\n text: `DELETE FROM ${this.tableName} WHERE key = $1`,\n values: [rlKey],\n })\n .then(res => res.rowCount > 0);\n }\n}\n\nmodule.exports = RateLimiterPostgres;\n", "module.exports = class Record {\n /**\n *\n * @param value int\n * @param expiresAt Date|int\n * @param timeoutId\n */\n constructor(value, expiresAt, timeoutId = null) {\n this.value = value;\n this.expiresAt = expiresAt;\n this.timeoutId = timeoutId;\n }\n\n get value() {\n return this._value;\n }\n\n set value(value) {\n this._value = parseInt(value);\n }\n\n get expiresAt() {\n return this._expiresAt;\n }\n\n set expiresAt(value) {\n if (!(value instanceof Date) && Number.isInteger(value)) {\n value = new Date(value);\n }\n this._expiresAt = value;\n }\n\n get timeoutId() {\n return this._timeoutId;\n }\n\n set timeoutId(value) {\n this._timeoutId = value;\n }\n};\n", "const Record = require('./Record');\nconst RateLimiterRes = require('../../RateLimiterRes');\n\nmodule.exports = class MemoryStorage {\n constructor() {\n /**\n * @type {Object.}\n * @private\n */\n this._storage = {};\n }\n\n incrby(key, value, durationSec) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n if (msBeforeExpires !== 0) {\n // Change value\n this._storage[key].value = this._storage[key].value + value;\n\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n\n if (this._storage[key] && this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n\n this._storage[key] = new Record(\n value,\n durationMs > 0 ? new Date(Date.now() + durationMs) : null\n );\n if (durationMs > 0) {\n this._storage[key].timeoutId = setTimeout(() => {\n delete this._storage[key];\n }, durationMs);\n if (this._storage[key].timeoutId.unref) {\n this._storage[key].timeoutId.unref();\n }\n }\n\n return new RateLimiterRes(0, durationMs === 0 ? -1 : durationMs, this._storage[key].value, true);\n }\n\n /**\n *\n * @param key\n * @returns {*}\n */\n get(key) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n return null;\n }\n\n /**\n *\n * @param key\n * @returns {boolean}\n */\n delete(key) {\n if (this._storage[key]) {\n if (this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n delete this._storage[key];\n return true;\n }\n return false;\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst MemoryStorage = require('./component/MemoryStorage/MemoryStorage');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemory extends RateLimiterAbstract {\n constructor(opts = {}) {\n super(opts);\n\n this._memoryStorage = new MemoryStorage();\n }\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\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\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 reject(res);\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n });\n }\n\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\n\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\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\n this._memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, initPoints)\n );\n }\n\n set(key, points, secDuration) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n\n this._memoryStorage.set(this.getKey(key), points, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, points)\n );\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\n return Promise.resolve(res);\n }\n\n delete(key) {\n return Promise.resolve(this._memoryStorage.delete(this.getKey(key)));\n }\n}\n\nmodule.exports = RateLimiterMemory;\n\n", "/**\n * Implements rate limiting in cluster using built-in IPC\n *\n * Two classes are described here: master and worker\n * Master have to be create in the master process without any options.\n * Any number of rate limiters can be created in workers, but each rate limiter must be with unique keyPrefix\n *\n * Workflow:\n * 1. master rate limiter created in master process\n * 2. worker rate limiter sends 'init' message with necessary options during creating\n * 3. master receives options and adds new rate limiter by keyPrefix if it isn't created yet\n * 4. master sends 'init' back to worker's rate limiter\n * 5. worker can process requests immediately,\n * but they will be postponed by 'workerWaitInit' until master sends 'init' to worker\n * 6. every request to worker rate limiter creates a promise\n * 7. if master doesn't response for 'timeout', promise is rejected\n * 8. master sends 'resolve' or 'reject' command to worker\n * 9. worker resolves or rejects promise depending on message from master\n *\n */\n\nconst cluster = require('cluster');\nconst crypto = require('crypto');\nconst RateLimiterAbstract = require('./RateLimiterAbstract');\nconst RateLimiterMemory = require('./RateLimiterMemory');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst channel = 'rate_limiter_flexible';\nlet masterInstance = null;\n\nconst masterSendToWorker = function (worker, msg, type, res) {\n let data;\n if (res === null || res === true || res === false) {\n data = res;\n } else {\n data = {\n remainingPoints: res.remainingPoints,\n msBeforeNext: res.msBeforeNext,\n consumedPoints: res.consumedPoints,\n isFirstInDuration: res.isFirstInDuration,\n };\n }\n worker.send({\n channel,\n keyPrefix: msg.keyPrefix, // which rate limiter exactly\n promiseId: msg.promiseId,\n type,\n data,\n });\n};\n\nconst workerWaitInit = function (payload) {\n setTimeout(() => {\n if (this._initiated) {\n process.send(payload);\n // Promise will be removed by timeout if too long\n } else if (typeof this._promises[payload.promiseId] !== 'undefined') {\n workerWaitInit.call(this, payload);\n }\n }, 30);\n};\n\nconst workerSendToMaster = function (func, promiseId, key, arg, opts) {\n const payload = {\n channel,\n keyPrefix: this.keyPrefix,\n func,\n promiseId,\n data: {\n key,\n arg,\n opts,\n },\n };\n\n if (!this._initiated) {\n // Wait init before sending messages to master\n workerWaitInit.call(this, payload);\n } else {\n process.send(payload);\n }\n};\n\nconst masterProcessMsg = function (worker, msg) {\n if (!msg || msg.channel !== channel || typeof this._rateLimiters[msg.keyPrefix] === 'undefined') {\n return false;\n }\n\n let promise;\n\n switch (msg.func) {\n case 'consume':\n promise = this._rateLimiters[msg.keyPrefix].consume(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'penalty':\n promise = this._rateLimiters[msg.keyPrefix].penalty(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'reward':\n promise = this._rateLimiters[msg.keyPrefix].reward(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'block':\n promise = this._rateLimiters[msg.keyPrefix].block(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'get':\n promise = this._rateLimiters[msg.keyPrefix].get(msg.data.key, msg.data.opts);\n break;\n case 'delete':\n promise = this._rateLimiters[msg.keyPrefix].delete(msg.data.key, msg.data.opts);\n break;\n default:\n return false;\n }\n\n if (promise) {\n promise\n .then((res) => {\n masterSendToWorker(worker, msg, 'resolve', res);\n })\n .catch((rejRes) => {\n masterSendToWorker(worker, msg, 'reject', rejRes);\n });\n }\n};\n\nconst workerProcessMsg = function (msg) {\n if (!msg || msg.channel !== channel || msg.keyPrefix !== this.keyPrefix) {\n return false;\n }\n\n if (this._promises[msg.promiseId]) {\n clearTimeout(this._promises[msg.promiseId].timeoutId);\n let res;\n if (msg.data === null || msg.data === true || msg.data === false) {\n res = msg.data;\n } else {\n res = new RateLimiterRes(\n msg.data.remainingPoints,\n msg.data.msBeforeNext,\n msg.data.consumedPoints,\n msg.data.isFirstInDuration // eslint-disable-line comma-dangle\n );\n }\n\n switch (msg.type) {\n case 'resolve':\n this._promises[msg.promiseId].resolve(res);\n break;\n case 'reject':\n this._promises[msg.promiseId].reject(res);\n break;\n default:\n throw new Error(`RateLimiterCluster: no such message type '${msg.type}'`);\n }\n\n delete this._promises[msg.promiseId];\n }\n};\n/**\n * Prepare options to send to master\n * Master will create rate limiter depending on options\n *\n * @returns {{points: *, duration: *, blockDuration: *, execEvenly: *, execEvenlyMinDelayMs: *, keyPrefix: *}}\n */\nconst getOpts = function () {\n return {\n points: this.points,\n duration: this.duration,\n blockDuration: this.blockDuration,\n execEvenly: this.execEvenly,\n execEvenlyMinDelayMs: this.execEvenlyMinDelayMs,\n keyPrefix: this.keyPrefix,\n };\n};\n\nconst savePromise = function (resolve, reject) {\n const hrtime = process.hrtime();\n let promiseId = hrtime[0].toString() + hrtime[1].toString();\n\n if (typeof this._promises[promiseId] !== 'undefined') {\n promiseId += crypto.randomBytes(12).toString('base64');\n }\n\n this._promises[promiseId] = {\n resolve,\n reject,\n timeoutId: setTimeout(() => {\n delete this._promises[promiseId];\n reject(new Error('RateLimiterCluster timeout: no answer from master in time'));\n }, this.timeoutMs),\n };\n\n return promiseId;\n};\n\nclass RateLimiterClusterMaster {\n constructor() {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n cluster.setMaxListeners(0);\n\n cluster.on('message', (worker, msg) => {\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n worker.send({\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n });\n } else {\n masterProcessMsg.call(this, worker, msg);\n }\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterMasterPM2 {\n constructor(pm2) {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n pm2.launchBus((err, pm2Bus) => {\n pm2Bus.on('process:msg', (packet) => {\n const msg = packet.raw;\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n pm2.sendDataToProcessId(packet.process.pm_id, {\n data: {},\n topic: channel,\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n }, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n } else {\n const worker = {\n send: (msgData) => {\n const pm2Message = msgData;\n pm2Message.topic = channel;\n if (typeof pm2Message.data === 'undefined') {\n pm2Message.data = {};\n }\n pm2.sendDataToProcessId(packet.process.pm_id, pm2Message, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n },\n };\n masterProcessMsg.call(this, worker, msg);\n }\n });\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterWorker extends RateLimiterAbstract {\n get timeoutMs() {\n return this._timeoutMs;\n }\n\n set timeoutMs(value) {\n this._timeoutMs = typeof value === 'undefined' ? 5000 : Math.abs(parseInt(value));\n }\n\n constructor(opts = {}) {\n super(opts);\n\n process.setMaxListeners(0);\n\n this.timeoutMs = opts.timeoutMs;\n\n this._initiated = false;\n\n process.on('message', (msg) => {\n if (msg && msg.channel === channel && msg.type === 'init' && msg.keyPrefix === this.keyPrefix) {\n this._initiated = true;\n } else {\n workerProcessMsg.call(this, msg);\n }\n });\n\n // Create limiter on master with specific options\n process.send({\n channel,\n type: 'init',\n opts: getOpts.call(this),\n });\n\n this._promises = {};\n }\n\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'consume', promiseId, key, pointsToConsume, options);\n });\n }\n\n penalty(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'penalty', promiseId, key, points, options);\n });\n }\n\n reward(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'reward', promiseId, key, points, options);\n });\n }\n\n block(key, secDuration, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'block', promiseId, key, secDuration, options);\n });\n }\n\n get(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'get', promiseId, key, options);\n });\n }\n\n delete(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'delete', promiseId, key, options);\n });\n }\n}\n\nmodule.exports = {\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster: RateLimiterClusterWorker,\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemcache extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: memcacheClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.client = opts.storeClient;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(result.consumedPoints);\n res.isFirstInDuration = result.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = result.msBeforeNext;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n const secDuration = Math.floor(msDuration / 1000);\n\n if (forceExpire) {\n this.client.set(rlKey, points, secDuration, (err) => {\n if (!err) {\n this.client.set(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n } else {\n reject(err);\n }\n });\n } else {\n this.client.incr(rlKey, points, (err, consumedPoints) => {\n if (err || consumedPoints === false) {\n this.client.add(rlKey, points, secDuration, (errAddKey, createdNew) => {\n if (errAddKey || !createdNew) {\n // Try to upsert again in case of race condition\n if (typeof options.attemptNumber === 'undefined' || options.attemptNumber < 3) {\n const nextOptions = Object.assign({}, options);\n nextOptions.attemptNumber = nextOptions.attemptNumber ? (nextOptions.attemptNumber + 1) : 1;\n\n this._upsert(rlKey, points, msDuration, forceExpire, nextOptions)\n .then(resUpsert => resolve(resUpsert))\n .catch(errUpsert => reject(errUpsert));\n } else {\n reject(new Error('Can not add key'));\n }\n } else {\n this.client.add(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n }\n });\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n\n this.client.get(rlKey, (err, consumedPoints) => {\n if (!consumedPoints) {\n resolve(null);\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else if (res === false) {\n resolve(res);\n } else {\n this.client.del(`${rlKey}_expire`, (errDelExpire) => {\n if (errDelExpire) {\n reject(errDelExpire);\n } else {\n resolve(res);\n }\n });\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMemcache;\n", "const RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RLWrapperBlackAndWhite {\n constructor(opts = {}) {\n this.limiter = opts.limiter;\n this.blackList = opts.blackList;\n this.whiteList = opts.whiteList;\n this.isBlackListed = opts.isBlackListed;\n this.isWhiteListed = opts.isWhiteListed;\n this.runActionAnyway = opts.runActionAnyway;\n }\n\n get limiter() {\n return this._limiter;\n }\n\n set limiter(value) {\n if (typeof value === 'undefined') {\n throw new Error('limiter is not set');\n }\n\n this._limiter = value;\n }\n\n get runActionAnyway() {\n return this._runActionAnyway;\n }\n\n set runActionAnyway(value) {\n this._runActionAnyway = typeof value === 'undefined' ? false : value;\n }\n\n get blackList() {\n return this._blackList;\n }\n\n set blackList(value) {\n this._blackList = Array.isArray(value) ? value : [];\n }\n\n get isBlackListed() {\n return this._isBlackListed;\n }\n\n set isBlackListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isBlackListed must be function');\n }\n this._isBlackListed = func;\n }\n\n get whiteList() {\n return this._whiteList;\n }\n\n set whiteList(value) {\n this._whiteList = Array.isArray(value) ? value : [];\n }\n\n get isWhiteListed() {\n return this._isWhiteListed;\n }\n\n set isWhiteListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isWhiteListed must be function');\n }\n this._isWhiteListed = func;\n }\n\n isBlackListedSomewhere(key) {\n return this.blackList.indexOf(key) >= 0 || this.isBlackListed(key);\n }\n\n isWhiteListedSomewhere(key) {\n return this.whiteList.indexOf(key) >= 0 || this.isWhiteListed(key);\n }\n\n getBlackRes() {\n return new RateLimiterRes(0, Number.MAX_SAFE_INTEGER, 0, false);\n }\n\n getWhiteRes() {\n return new RateLimiterRes(Number.MAX_SAFE_INTEGER, 0, 0, false);\n }\n\n rejectBlack() {\n return Promise.reject(this.getBlackRes());\n }\n\n resolveBlack() {\n return Promise.resolve(this.getBlackRes());\n }\n\n resolveWhite() {\n return Promise.resolve(this.getWhiteRes());\n }\n\n consume(key, pointsToConsume = 1) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.rejectBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.consume(key, pointsToConsume);\n }\n\n if (this.runActionAnyway) {\n this.limiter.consume(key, pointsToConsume).catch(() => {});\n }\n return res;\n }\n\n block(key, secDuration) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.block(key, secDuration);\n }\n\n if (this.runActionAnyway) {\n this.limiter.block(key, secDuration).catch(() => {});\n }\n return res;\n }\n\n penalty(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.penalty(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.penalty(key, points).catch(() => {});\n }\n return res;\n }\n\n reward(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.reward(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.reward(key, points).catch(() => {});\n }\n return res;\n }\n\n get(key) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined' || this.runActionAnyway) {\n return this.limiter.get(key);\n }\n\n return res;\n }\n\n delete(key) {\n return this.limiter.delete(key);\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\n\nmodule.exports = class RateLimiterUnion {\n constructor(...limiters) {\n if (limiters.length < 1) {\n throw new Error('RateLimiterUnion: at least one limiter have to be passed');\n }\n limiters.forEach((limiter) => {\n if (!(limiter instanceof RateLimiterAbstract)) {\n throw new Error('RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract');\n }\n });\n\n this._limiters = limiters;\n }\n\n consume(key, points = 1) {\n return new Promise((resolve, reject) => {\n const promises = [];\n this._limiters.forEach((limiter) => {\n promises.push(limiter.consume(key, points).catch(rej => ({ rejected: true, rej })));\n });\n\n Promise.all(promises)\n .then((res) => {\n const resObj = {};\n let rejected = false;\n\n res.forEach((item) => {\n if (item.rejected === true) {\n rejected = true;\n }\n });\n\n for (let i = 0; i < res.length; i++) {\n if (rejected && res[i].rejected === true) {\n resObj[this._limiters[i].keyPrefix] = res[i].rej;\n } else if (!rejected) {\n resObj[this._limiters[i].keyPrefix] = res[i];\n }\n }\n\n if (rejected) {\n reject(resObj);\n } else {\n resolve(resObj);\n }\n });\n });\n }\n};\n", "module.exports = class RateLimiterQueueError extends Error {\n constructor(message, extra) {\n super();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = 'CustomError';\n this.message = message;\n if (extra) {\n this.extra = extra;\n }\n }\n};\n", "const RateLimiterQueueError = require('./component/RateLimiterQueueError')\nconst MAX_QUEUE_SIZE = 4294967295;\nconst KEY_DEFAULT = 'limiter';\n\nmodule.exports = class RateLimiterQueue {\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n }) {\n this._queueLimiters = {\n KEY_DEFAULT: new RateLimiterQueueInternal(limiterFlexible, opts)\n };\n this._limiterFlexible = limiterFlexible;\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining(key = KEY_DEFAULT) {\n if (this._queueLimiters[key]) {\n return this._queueLimiters[key].getTokensRemaining()\n } else {\n return Promise.resolve(this._limiterFlexible.points)\n }\n }\n\n removeTokens(tokens, key = KEY_DEFAULT) {\n if (!this._queueLimiters[key]) {\n this._queueLimiters[key] = new RateLimiterQueueInternal(\n this._limiterFlexible, {\n key,\n maxQueueSize: this._maxQueueSize,\n })\n }\n\n return this._queueLimiters[key].removeTokens(tokens)\n }\n};\n\nclass RateLimiterQueueInternal {\n\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n key: KEY_DEFAULT,\n }) {\n this._key = opts.key;\n this._waitTimeout = null;\n this._queue = [];\n this._limiterFlexible = limiterFlexible;\n\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining() {\n return this._limiterFlexible.get(this._key)\n .then((rlRes) => {\n return rlRes !== null ? rlRes.remainingPoints : this._limiterFlexible.points;\n })\n }\n\n removeTokens(tokens) {\n const _this = this;\n\n return new Promise((resolve, reject) => {\n if (tokens > _this._limiterFlexible.points) {\n reject(new RateLimiterQueueError(`Requested tokens ${tokens} exceeds maximum ${_this._limiterFlexible.points} tokens per interval`));\n return\n }\n\n if (_this._queue.length > 0) {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n } else {\n _this._limiterFlexible.consume(_this._key, tokens)\n .then((res) => {\n resolve(res.remainingPoints);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n reject(rej);\n } else {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n })\n }\n\n _queueRequest(resolve, reject, tokens) {\n const _this = this;\n if (_this._queue.length < _this._maxQueueSize) {\n _this._queue.push({resolve, reject, tokens});\n } else {\n reject(new RateLimiterQueueError(`Number of requests reached it's maximum ${_this._maxQueueSize}`))\n }\n }\n\n _processFIFO() {\n const _this = this;\n\n if (_this._waitTimeout !== null) {\n clearTimeout(_this._waitTimeout);\n _this._waitTimeout = null;\n }\n\n if (_this._queue.length === 0) {\n return;\n }\n\n const item = _this._queue.shift();\n _this._limiterFlexible.consume(_this._key, item.tokens)\n .then((res) => {\n item.resolve(res.remainingPoints);\n _this._processFIFO.call(_this);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n item.reject(rej);\n _this._processFIFO.call(_this);\n } else {\n _this._queue.unshift(item);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n}\n", "const RateLimiterRes = require(\"./RateLimiterRes\");\n\n/**\n * Bursty rate limiter exposes only msBeforeNext time and doesn't expose points from bursty limiter by default\n * @type {BurstyRateLimiter}\n */\nmodule.exports = class BurstyRateLimiter {\n constructor(rateLimiter, burstLimiter) {\n this._rateLimiter = rateLimiter;\n this._burstLimiter = burstLimiter\n }\n\n /**\n * Merge rate limiter response objects. Responses can be null\n *\n * @param {RateLimiterRes} [rlRes] Rate limiter response\n * @param {RateLimiterRes} [blRes] Bursty limiter response\n */\n _combineRes(rlRes, blRes) {\n return new RateLimiterRes(\n rlRes.remainingPoints,\n Math.min(rlRes.msBeforeNext, blRes.msBeforeNext),\n rlRes.consumedPoints,\n rlRes.isFirstInDuration\n )\n }\n\n /**\n * @param key\n * @param pointsToConsume\n * @param options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return this._rateLimiter.consume(key, pointsToConsume, options)\n .catch((rlRej) => {\n if (rlRej instanceof RateLimiterRes) {\n return this._burstLimiter.consume(key, pointsToConsume, options)\n .then((blRes) => {\n return Promise.resolve(this._combineRes(rlRej, blRes))\n })\n .catch((blRej) => {\n if (blRej instanceof RateLimiterRes) {\n return Promise.reject(this._combineRes(rlRej, blRej))\n } else {\n return Promise.reject(blRej)\n }\n }\n )\n } else {\n return Promise.reject(rlRej)\n }\n })\n }\n\n /**\n * It doesn't expose available points from burstLimiter\n *\n * @param key\n * @returns {Promise}\n */\n get(key) {\n return Promise.all([\n this._rateLimiter.get(key),\n this._burstLimiter.get(key),\n ]).then(([rlRes, blRes]) => {\n return this._combineRes(rlRes, blRes);\n });\n }\n\n get points() {\n return this._rateLimiter.points;\n }\n};\n", "const RateLimiterRedis = require('./lib/RateLimiterRedis');\nconst RateLimiterMongo = require('./lib/RateLimiterMongo');\nconst RateLimiterMySQL = require('./lib/RateLimiterMySQL');\nconst RateLimiterPostgres = require('./lib/RateLimiterPostgres');\nconst {RateLimiterClusterMaster, RateLimiterClusterMasterPM2, RateLimiterCluster} = require('./lib/RateLimiterCluster');\nconst RateLimiterMemory = require('./lib/RateLimiterMemory');\nconst RateLimiterMemcache = require('./lib/RateLimiterMemcache');\nconst RLWrapperBlackAndWhite = require('./lib/RLWrapperBlackAndWhite');\nconst RateLimiterUnion = require('./lib/RateLimiterUnion');\nconst RateLimiterQueue = require('./lib/RateLimiterQueue');\nconst BurstyRateLimiter = require('./lib/BurstyRateLimiter');\nconst RateLimiterRes = require('./lib/RateLimiterRes');\n\nmodule.exports = {\n RateLimiterRedis,\n RateLimiterMongo,\n RateLimiterMySQL,\n RateLimiterPostgres,\n RateLimiterMemory,\n RateLimiterMemcache,\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster,\n RLWrapperBlackAndWhite,\n RateLimiterUnion,\n RateLimiterQueue,\n BurstyRateLimiter,\n RateLimiterRes,\n};\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", "(function (root) {\n 'use strict';\n // A list of regular expressions that match arbitrary IPv4 addresses,\n // for which a number of weird notations exist.\n // Note that an address like 0010.0xa5.1.1 is considered legal.\n const ipv4Part = '(0?\\\\d+|0x[a-f0-9]+)';\n const ipv4Regexes = {\n fourOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n threeOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n twoOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n longValue: new RegExp(`^${ipv4Part}$`, 'i')\n };\n\n // Regular Expression for checking Octal numbers\n const octalRegex = new RegExp(`^0[0-7]+$`, 'i');\n const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');\n\n const zoneIndex = '%[0-9a-z]{1,}';\n\n // IPv6-matching regular expressions.\n // For IPv6, the task is simpler: it is enough to match the colon-delimited\n // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at\n // the end.\n const ipv6Part = '(?:[0-9a-f]+::?)+';\n const ipv6Regexes = {\n zoneIndex: new RegExp(zoneIndex, 'i'),\n 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),\n deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),\n transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?$`, 'i')\n };\n\n // Expand :: in an IPv6 address or address part consisting of `parts` groups.\n function expandIPv6 (string, parts) {\n // More than one '::' means invalid adddress\n if (string.indexOf('::') !== string.lastIndexOf('::')) {\n return null;\n }\n\n let colonCount = 0;\n let lastColon = -1;\n let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];\n let replacement, replacementCount;\n\n // Remove zone index and save it for later\n if (zoneId) {\n zoneId = zoneId.substring(1);\n string = string.replace(/%.+$/, '');\n }\n\n // How many parts do we already have?\n while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {\n colonCount++;\n }\n\n // 0::0 is two parts more than ::\n if (string.substr(0, 2) === '::') {\n colonCount--;\n }\n\n if (string.substr(-2, 2) === '::') {\n colonCount--;\n }\n\n // The following loop would hang if colonCount > parts\n if (colonCount > parts) {\n return null;\n }\n\n // replacement = ':' + '0:' * (parts - colonCount)\n replacementCount = parts - colonCount;\n replacement = ':';\n while (replacementCount--) {\n replacement += '0:';\n }\n\n // Insert the missing zeroes\n string = string.replace('::', replacement);\n\n // Trim any garbage which may be hanging around if :: was at the edge in\n // the source strin\n if (string[0] === ':') {\n string = string.slice(1);\n }\n\n if (string[string.length - 1] === ':') {\n string = string.slice(0, -1);\n }\n\n parts = (function () {\n const ref = string.split(':');\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n results.push(parseInt(ref[i], 16));\n }\n\n return results;\n })();\n\n return {\n parts: parts,\n zoneId: zoneId\n };\n }\n\n // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.\n function matchCIDR (first, second, partSize, cidrBits) {\n if (first.length !== second.length) {\n throw new Error('ipaddr: cannot match CIDR for objects with different lengths');\n }\n\n let part = 0;\n let shift;\n\n while (cidrBits > 0) {\n shift = partSize - cidrBits;\n if (shift < 0) {\n shift = 0;\n }\n\n if (first[part] >> shift !== second[part] >> shift) {\n return false;\n }\n\n cidrBits -= partSize;\n part += 1;\n }\n\n return true;\n }\n\n function parseIntAuto (string) {\n // Hexadedimal base 16 (0x#)\n if (hexRegex.test(string)) {\n return parseInt(string, 16);\n }\n // While octal representation is discouraged by ECMAScript 3\n // and forbidden by ECMAScript 5, we silently allow it to\n // work only if the rest of the string has numbers less than 8.\n if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {\n if (octalRegex.test(string)) {\n return parseInt(string, 8);\n }\n throw new Error(`ipaddr: cannot parse ${string} as octal`);\n }\n // Always include the base 10 radix!\n return parseInt(string, 10);\n }\n\n function padPart (part, length) {\n while (part.length < length) {\n part = `0${part}`;\n }\n\n return part;\n }\n\n const ipaddr = {};\n\n // An IPv4 address (RFC791).\n ipaddr.IPv4 = (function () {\n // Constructs a new IPv4 address from an array of four octets\n // in network order (MSB first)\n // Verifies the input.\n function IPv4 (octets) {\n if (octets.length !== 4) {\n throw new Error('ipaddr: ipv4 octet count should be 4');\n }\n\n let i, octet;\n\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n throw new Error('ipaddr: ipv4 octet should fit in 8 bits');\n }\n }\n\n this.octets = octets;\n }\n\n // Special IPv4 address ranges.\n // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses\n IPv4.prototype.SpecialRanges = {\n unspecified: [[new IPv4([0, 0, 0, 0]), 8]],\n broadcast: [[new IPv4([255, 255, 255, 255]), 32]],\n // RFC3171\n multicast: [[new IPv4([224, 0, 0, 0]), 4]],\n // RFC3927\n linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],\n // RFC5735\n loopback: [[new IPv4([127, 0, 0, 0]), 8]],\n // RFC6598\n carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],\n // RFC1918\n 'private': [\n [new IPv4([10, 0, 0, 0]), 8],\n [new IPv4([172, 16, 0, 0]), 12],\n [new IPv4([192, 168, 0, 0]), 16]\n ],\n // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700\n reserved: [\n [new IPv4([192, 0, 0, 0]), 24],\n [new IPv4([192, 0, 2, 0]), 24],\n [new IPv4([192, 88, 99, 0]), 24],\n [new IPv4([198, 51, 100, 0]), 24],\n [new IPv4([203, 0, 113, 0]), 24],\n [new IPv4([240, 0, 0, 0]), 4]\n ]\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv4.prototype.kind = function () {\n return 'ipv4';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv4.prototype.match = function (other, cidrRange) {\n let ref;\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv4') {\n throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');\n }\n\n return matchCIDR(this.octets, other.octets, 8, cidrRange);\n };\n\n // returns a number of leading ones in IPv4 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv4.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 8,\n 128: 7,\n 192: 6,\n 224: 5,\n 240: 4,\n 248: 3,\n 252: 2,\n 254: 1,\n 255: 0\n };\n let i, octet, zeros;\n\n for (i = 3; i >= 0; i -= 1) {\n octet = this.octets[i];\n if (octet in zerotable) {\n zeros = zerotable[octet];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 8) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 32 - cidr;\n };\n\n // Checks if the address corresponds to one of the special ranges.\n IPv4.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv4.prototype.toByteArray = function () {\n return this.octets.slice(0);\n };\n\n // Converts this IPv4 address to an IPv4-mapped IPv6 address.\n IPv4.prototype.toIPv4MappedAddress = function () {\n return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);\n };\n\n // Symmetrical method strictly for aligning with the IPv6 methods.\n IPv4.prototype.toNormalizedString = function () {\n return this.toString();\n };\n\n // Returns the address in convenient, decimal-dotted format.\n IPv4.prototype.toString = function () {\n return this.octets.join('.');\n };\n\n return IPv4;\n })();\n\n // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {\n\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 4) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Checks if a given string is formatted like IPv4 address.\n ipaddr.IPv4.isIPv4 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks if a given string is a valid IPv4 address.\n ipaddr.IPv4.isValid = function (string) {\n try {\n new this(this.parser(string));\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address.\n ipaddr.IPv4.isValidFourPartDecimal = function (string) {\n if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){3}$/)) {\n return true;\n } else {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 4) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Tries to parse and validate a string with IPv4 address.\n // Throws an error if it fails.\n ipaddr.IPv4.parse = function (string) {\n const parts = this.parser(string);\n\n if (parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv4 Address');\n }\n\n return new this(parts);\n };\n\n // Parses the string as an IPv4 Address with CIDR Notation.\n ipaddr.IPv4.parseCIDR = function (string) {\n let match;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n const maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 32) {\n const parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');\n };\n\n // Classful variants (like a.b, where a is an octet, and b is a 24-bit\n // value representing last three octets; this corresponds to a class C\n // address) are omitted due to classless nature of modern Internet.\n ipaddr.IPv4.parser = function (string) {\n let match, part, value;\n\n // parseInt recognizes all that octal & hexadecimal weirdness for us\n if ((match = string.match(ipv4Regexes.fourOctet))) {\n return (function () {\n const ref = match.slice(1, 6);\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n results.push(parseIntAuto(part));\n }\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.longValue))) {\n value = parseIntAuto(match[1]);\n if (value > 0xffffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n return ((function () {\n const results = [];\n let shift;\n\n for (shift = 0; shift <= 24; shift += 8) {\n results.push((value >> shift) & 0xff);\n }\n\n return results;\n })()).reverse();\n } else if ((match = string.match(ipv4Regexes.twoOctet))) {\n return (function () {\n const ref = match.slice(1, 4);\n const results = [];\n\n value = parseIntAuto(ref[1]);\n if (value > 0xffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push((value >> 16) & 0xff);\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.threeOctet))) {\n return (function () {\n const ref = match.slice(1, 5);\n const results = [];\n\n value = parseIntAuto(ref[2]);\n if (value > 0xffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push(parseIntAuto(ref[1]));\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else {\n return null;\n }\n };\n\n // A utility function to return subnet mask in IPv4 format given the prefix length\n ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 32) {\n throw new Error('ipaddr: invalid IPv4 prefix length');\n }\n\n const octets = [0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 4) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // An IPv6 address (RFC2460)\n ipaddr.IPv6 = (function () {\n // Constructs an IPv6 address from an array of eight 16 - bit parts\n // or sixteen 8 - bit parts in network order(MSB first).\n // Throws an error if the input is invalid.\n function IPv6 (parts, zoneId) {\n let i, part;\n\n if (parts.length === 16) {\n this.parts = [];\n for (i = 0; i <= 14; i += 2) {\n this.parts.push((parts[i] << 8) | parts[i + 1]);\n }\n } else if (parts.length === 8) {\n this.parts = parts;\n } else {\n throw new Error('ipaddr: ipv6 part count should be 8 or 16');\n }\n\n for (i = 0; i < this.parts.length; i++) {\n part = this.parts[i];\n if (!((0 <= part && part <= 0xffff))) {\n throw new Error('ipaddr: ipv6 part should fit in 16 bits');\n }\n }\n\n if (zoneId) {\n this.zoneId = zoneId;\n }\n }\n\n // Special IPv6 ranges\n IPv6.prototype.SpecialRanges = {\n // RFC4291, here and after\n unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],\n linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],\n multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],\n loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],\n uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],\n ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],\n // RFC6145\n rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],\n // RFC6052\n rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],\n // RFC3056\n '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],\n // RFC6052, RFC6146\n teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],\n // RFC4291\n reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]\n };\n\n // Checks if this address is an IPv4-mapped IPv6 address.\n IPv6.prototype.isIPv4MappedAddress = function () {\n return this.range() === 'ipv4Mapped';\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv6.prototype.kind = function () {\n return 'ipv6';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv6.prototype.match = function (other, cidrRange) {\n let ref;\n\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv6') {\n throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');\n }\n\n return matchCIDR(this.parts, other.parts, 16, cidrRange);\n };\n\n // returns a number of leading ones in IPv6 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv6.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 16,\n 32768: 15,\n 49152: 14,\n 57344: 13,\n 61440: 12,\n 63488: 11,\n 64512: 10,\n 65024: 9,\n 65280: 8,\n 65408: 7,\n 65472: 6,\n 65504: 5,\n 65520: 4,\n 65528: 3,\n 65532: 2,\n 65534: 1,\n 65535: 0\n };\n let part, zeros;\n\n for (let i = 7; i >= 0; i -= 1) {\n part = this.parts[i];\n if (part in zerotable) {\n zeros = zerotable[part];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 16) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 128 - cidr;\n };\n\n\n // Checks if the address corresponds to one of the special ranges.\n IPv6.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv6.prototype.toByteArray = function () {\n let part;\n const bytes = [];\n const ref = this.parts;\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n bytes.push(part >> 8);\n bytes.push(part & 0xff);\n }\n\n return bytes;\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:0db8:0008:0066:0000:0000:0000:0001\n IPv6.prototype.toFixedLengthString = function () {\n const addr = ((function () {\n const results = [];\n for (let i = 0; i < this.parts.length; i++) {\n results.push(padPart(this.parts[i].toString(16), 4));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.\n // Throws an error otherwise.\n IPv6.prototype.toIPv4Address = function () {\n if (!this.isIPv4MappedAddress()) {\n throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');\n }\n\n const ref = this.parts.slice(-2);\n const high = ref[0];\n const low = ref[1];\n\n return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:db8:8:66:0:0:0:1\n //\n // Deprecated: use toFixedLengthString() instead.\n IPv6.prototype.toNormalizedString = function () {\n const addr = ((function () {\n const results = [];\n\n for (let i = 0; i < this.parts.length; i++) {\n results.push(this.parts[i].toString(16));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)\n IPv6.prototype.toRFC5952String = function () {\n const regex = /((^|:)(0(:|$)){2,})/g;\n const string = this.toNormalizedString();\n let bestMatchIndex = 0;\n let bestMatchLength = -1;\n let match;\n\n while ((match = regex.exec(string))) {\n if (match[0].length > bestMatchLength) {\n bestMatchIndex = match.index;\n bestMatchLength = match[0].length;\n }\n }\n\n if (bestMatchLength < 0) {\n return string;\n }\n\n return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n //\n // Deprecated: use toRFC5952String() instead.\n IPv6.prototype.toString = function () {\n // Replace the first sequence of 1 or more '0' parts with '::'\n return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::');\n };\n\n return IPv6;\n\n })();\n\n // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 16) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Checks if a given string is formatted like IPv6 address.\n ipaddr.IPv6.isIPv6 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks to see if string is a valid IPv6 Address\n ipaddr.IPv6.isValid = function (string) {\n\n // Since IPv6.isValid is always called first, this shortcut\n // provides a substantial performance gain.\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n const addr = this.parser(string);\n new this(addr.parts, addr.zoneId);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 16) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Tries to parse and validate a string with IPv6 address.\n // Throws an error if it fails.\n ipaddr.IPv6.parse = function (string) {\n const addr = this.parser(string);\n\n if (addr.parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv6 Address');\n }\n\n return new this(addr.parts, addr.zoneId);\n };\n\n ipaddr.IPv6.parseCIDR = function (string) {\n let maskLength, match, parsed;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 128) {\n parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');\n };\n\n // Parse an IPv6 address.\n ipaddr.IPv6.parser = function (string) {\n let addr, i, match, octet, octets, zoneId;\n\n if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {\n return this.parser(`::ffff:${match[1]}`);\n }\n if (ipv6Regexes.native.test(string)) {\n return expandIPv6(string, 8);\n }\n if ((match = string.match(ipv6Regexes.transitional))) {\n zoneId = match[6] || '';\n addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);\n if (addr.parts) {\n octets = [\n parseInt(match[2]),\n parseInt(match[3]),\n parseInt(match[4]),\n parseInt(match[5])\n ];\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n return null;\n }\n }\n\n addr.parts.push(octets[0] << 8 | octets[1]);\n addr.parts.push(octets[2] << 8 | octets[3]);\n return {\n parts: addr.parts,\n zoneId: addr.zoneId\n };\n }\n }\n\n return null;\n };\n\n // A utility function to return subnet mask in IPv6 format given the prefix length\n ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 128) {\n throw new Error('ipaddr: invalid IPv6 prefix length');\n }\n\n const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 16) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // Try to parse an array in network order (MSB first) for IPv4 and IPv6\n ipaddr.fromByteArray = function (bytes) {\n const length = bytes.length;\n\n if (length === 4) {\n return new ipaddr.IPv4(bytes);\n } else if (length === 16) {\n return new ipaddr.IPv6(bytes);\n } else {\n throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');\n }\n };\n\n // Checks if the address is valid IP address\n ipaddr.isValid = function (string) {\n return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);\n };\n\n\n // Attempts to parse an IP Address, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parse = function (string) {\n if (ipaddr.IPv6.isValid(string)) {\n return ipaddr.IPv6.parse(string);\n } else if (ipaddr.IPv4.isValid(string)) {\n return ipaddr.IPv4.parse(string);\n } else {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');\n }\n };\n\n // Attempt to parse CIDR notation, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parseCIDR = function (string) {\n try {\n return ipaddr.IPv6.parseCIDR(string);\n } catch (e) {\n try {\n return ipaddr.IPv4.parseCIDR(string);\n } catch (e2) {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');\n }\n }\n };\n\n // Parse an address and return plain IPv4 address if it is an IPv4-mapped address\n ipaddr.process = function (string) {\n const addr = this.parse(string);\n\n if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {\n return addr.toIPv4Address();\n } else {\n return addr;\n }\n };\n\n // An utility function to ease named range matching. See examples below.\n // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors\n // on matching IPv4 addresses to IPv6 ranges or vice versa.\n ipaddr.subnetMatch = function (address, rangeList, defaultName) {\n let i, rangeName, rangeSubnets, subnet;\n\n if (defaultName === undefined || defaultName === null) {\n defaultName = 'unicast';\n }\n\n for (rangeName in rangeList) {\n if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {\n rangeSubnets = rangeList[rangeName];\n // ECMA5 Array.isArray isn't available everywhere\n if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {\n rangeSubnets = [rangeSubnets];\n }\n\n for (i = 0; i < rangeSubnets.length; i++) {\n subnet = rangeSubnets[i];\n if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {\n return rangeName;\n }\n }\n }\n }\n\n return defaultName;\n };\n\n // Export for both the CommonJS and browser-like environment\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = ipaddr;\n\n } else {\n root.ipaddr = ipaddr;\n }\n\n}(this));\n", "'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function truncate(getLength, string, byteLength) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var curByteLength = 0;\n var codePoint;\n var segment;\n\n for (var i = 0; i < charLength; i += 1) {\n codePoint = string.charCodeAt(i);\n segment = string[i];\n\n if (isHighSurrogate(codePoint) && isLowSurrogate(string.charCodeAt(i + 1))) {\n i += 1;\n segment += string[i];\n }\n\n curByteLength += getLength(segment);\n\n if (curByteLength === byteLength) {\n return string.slice(0, i + 1);\n }\n else if (curByteLength > byteLength) {\n return string.slice(0, i - segment.length + 1);\n }\n }\n\n return string;\n};\n\n", "'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function getByteLength(string) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var byteLength = 0;\n var codePoint = null;\n var prevCodePoint = null;\n for (var i = 0; i < charLength; i++) {\n codePoint = string.charCodeAt(i);\n // handle 4-byte non-BMP chars\n // low surrogate\n if (isLowSurrogate(codePoint)) {\n // when parsing previous hi-surrogate, 3 is added to byteLength\n if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) {\n byteLength += 1;\n }\n else {\n byteLength += 3;\n }\n }\n else if (codePoint <= 0x7f ) {\n byteLength += 1;\n }\n else if (codePoint >= 0x80 && codePoint <= 0x7ff) {\n byteLength += 2;\n }\n else if (codePoint >= 0x800 && codePoint <= 0xffff) {\n byteLength += 3;\n }\n prevCodePoint = codePoint;\n }\n\n return byteLength;\n};\n", "'use strict';\n\nvar truncate = require(\"./lib/truncate\");\nvar getLength = require(\"utf8-byte-length/browser\");\nmodule.exports = truncate.bind(null, getLength);\n", "/*jshint node:true*/\n'use strict';\n\n/**\n * Replaces characters in strings that are illegal/unsafe for filenames.\n * Unsafe characters are either removed or replaced by a substitute set\n * in the optional `options` object.\n *\n * Illegal Characters on Various Operating Systems\n * / ? < > \\ : * | \"\n * https://kb.acronis.com/content/39790\n *\n * Unicode Control codes\n * C0 0x00-0x1f & C1 (0x80-0x9f)\n * http://en.wikipedia.org/wiki/C0_and_C1_control_codes\n *\n * Reserved filenames on Unix-based systems (\".\", \"..\")\n * Reserved filenames in Windows (\"CON\", \"PRN\", \"AUX\", \"NUL\", \"COM1\",\n * \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\",\n * \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", and\n * \"LPT9\") case-insesitively and with or without filename extensions.\n *\n * Capped at 255 characters in length.\n * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs\n *\n * @param {String} input Original filename\n * @param {Object} options {replacement: String | Function }\n * @return {String} Sanitized filename\n */\n\nvar truncate = require(\"truncate-utf8-bytes\");\n\nvar illegalRe = /[\\/\\?<>\\\\:\\*\\|\"]/g;\nvar controlRe = /[\\x00-\\x1f\\x80-\\x9f]/g;\nvar reservedRe = /^\\.+$/;\nvar windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i;\nvar windowsTrailingRe = /[\\. ]+$/;\n\nfunction sanitize(input, replacement) {\n if (typeof input !== 'string') {\n throw new Error('Input must be string');\n }\n var sanitized = input\n .replace(illegalRe, replacement)\n .replace(controlRe, replacement)\n .replace(reservedRe, replacement)\n .replace(windowsReservedRe, replacement)\n .replace(windowsTrailingRe, replacement);\n return truncate(sanitized, 255);\n}\n\nmodule.exports = function (input, options) {\n var replacement = (options && options.replacement) || '';\n var output = sanitize(input, replacement);\n if (replacement === '') {\n return output;\n }\n return sanitize(output, '');\n};\n", "/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter',\n optional: true\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n", "/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n", "/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n", "/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n", "/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Create signature digest for OID.\n *\n * @param options\n * signatureOid: the OID specifying the signature algorithm.\n * type: a human readable type for error messages\n * @return a created md instance. throws if unknown oid.\n */\nvar _createSignatureDigest = function(options) {\n switch(oids[options.signatureOid]) {\n case 'sha1WithRSAEncryption':\n // deprecated alias\n case 'sha1WithRSASignature':\n return forge.md.sha1.create();\n case 'md5WithRSAEncryption':\n return forge.md.md5.create();\n case 'sha256WithRSAEncryption':\n return forge.md.sha256.create();\n case 'sha384WithRSAEncryption':\n return forge.md.sha384.create();\n case 'sha512WithRSAEncryption':\n return forge.md.sha512.create();\n case 'RSASSA-PSS':\n return forge.md.sha256.create();\n default:\n var error = new Error(\n 'Could not compute ' + options.type + ' digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = options.signatureOid;\n throw error;\n }\n};\n\n/**\n * Verify signature on certificate or CSR.\n *\n * @param options:\n * certificate the certificate or CSR to verify.\n * md the signature digest.\n * signature the signature\n * @return a created md instance. throws if unknown oid.\n */\nvar _verifySignature = function(options) {\n var cert = options.certificate;\n var scheme;\n\n switch(cert.signatureOid) {\n case oids.sha1WithRSAEncryption:\n // deprecated alias\n case oids.sha1WithRSASignature:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = cert.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[cert.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = cert.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[cert.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = cert.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(\n forge.md[hash].create(), mgf, cert.signatureParameters.saltLength\n );\n break;\n }\n\n // verify signature on cert using public key\n return cert.publicKey.verify(\n options.md.digest().getBytes(), options.signature, scheme\n );\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = subject.attributes;\n error.actualIssuer = issuer.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // create digest for OID signature types\n md = _createSignatureDigest({\n signatureOid: child.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: cert, md: md, signature: child.signature\n });\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // create digest for OID signature type\n cert.md = _createSignatureDigest({\n signatureOid: cert.signatureOid,\n type: 'certificate'\n });\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n var ibytes = asn1.toDer(capture.certIssuer);\n imd.update(ibytes.getBytes());\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n var sbytes = asn1.toDer(capture.certSubject);\n smd.update(sbytes.getBytes());\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // create digest for OID signature type\n csr.md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n md = _createSignatureDigest({\n signatureOid: csr.signatureOid,\n type: 'certification request'\n });\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n rval = _verifySignature({\n certificate: csr, md: md, signature: csr.signature\n });\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n", "/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter ? capture.encParameter.value : undefined,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n !ec.parameter ?\n undefined :\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n", "'use strict'\n\nmodule.exports = Receptacle\nvar toMS = require('ms')\nvar cache = Receptacle.prototype\nvar counter = new Date() % 1e9\n\nfunction getUID () { return (Math.random() * 1e9 >>> 0) + (counter++) }\n\n/**\n * Creates a cache with a maximum key size.\n *\n * @constructor\n * @param {Object} options\n * @param {Number} [options.max=Infinity] the maximum number of keys allowed in the cache (lru).\n * @param {Array} [options.items=[]] the default items in the cache.\n */\nfunction Receptacle (options) {\n options = options || {}\n this.id = options.id || getUID()\n this.max = options.max || Infinity\n this.items = options.items || []\n this._lookup = {}\n this.size = this.items.length\n this.lastModified = new Date(options.lastModified || new Date())\n\n // Setup initial timers and indexes for the cache.\n for (var item, ttl, i = this.items.length; i--;) {\n item = this.items[i]\n ttl = new Date(item.expires) - new Date()\n this._lookup[item.key] = item\n if (ttl > 0) this.expire(item.key, ttl)\n else if (ttl <= 0) this.delete(item.key)\n }\n}\n\n/**\n * Tests if a key is currently in the cache.\n * Does not check if slot is empty.\n *\n * @param {String} key - the key to retrieve from the cache.\n * @return {Boolean}\n */\ncache.has = function (key) {\n return key in this._lookup\n}\n\n/**\n * Retrieves a key from the cache and marks it as recently used.\n *\n * @param {String} key - the key to retrieve from the cache.\n * @return {*}\n */\ncache.get = function (key) {\n if (!this.has(key)) return null\n var record = this._lookup[key]\n // Update expiry for \"refresh\" keys\n if (record.refresh) this.expire(key, record.refresh)\n // Move to front of the line.\n this.items.splice(this.items.indexOf(record), 1)\n this.items.push(record)\n return record.value\n}\n\n/**\n * Retrieves user meta data for a cached item.\n *\n * @param {String} key - the key to retrieve meta data from the cache.\n * @return {*}\n */\ncache.meta = function (key) {\n if (!this.has(key)) return null\n var record = this._lookup[key]\n if (!('meta' in record)) return null\n return record.meta\n}\n\n/**\n * Puts a key into the cache with an optional expiry time.\n *\n * @param {String} key - the key for the value in the cache.\n * @param {*} value - the value to place at the key.\n * @param {Number} [options.ttl] - a time after which the key will be removed.\n * @return {Receptacle}\n */\ncache.set = function (key, value, options) {\n var oldRecord = this._lookup[key]\n var record = this._lookup[key] = { key: key, value: value }\n // Mark cache as modified.\n this.lastModified = new Date()\n\n if (oldRecord) {\n // Replace an old key.\n clearTimeout(oldRecord.timeout)\n this.items.splice(this.items.indexOf(oldRecord), 1, record)\n } else {\n // Remove least used item if needed.\n if (this.size >= this.max) this.delete(this.items[0].key)\n // Add a new key.\n this.items.push(record)\n this.size++\n }\n\n if (options) {\n // Setup key expiry.\n if ('ttl' in options) this.expire(key, options.ttl)\n // Store user options in the record.\n if ('meta' in options) record.meta = options.meta\n // Mark a auto refresh key.\n if (options.refresh) record.refresh = options.ttl\n }\n\n return this\n}\n\n/**\n * Deletes an item from the cache.\n *\n * @param {String} key - the key to remove.\n * @return {Receptacle}\n */\ncache.delete = function (key) {\n var record = this._lookup[key]\n if (!record) return false\n this.lastModified = new Date()\n this.items.splice(this.items.indexOf(record), 1)\n clearTimeout(record.timeout)\n delete this._lookup[key]\n this.size--\n return this\n}\n\n/**\n * Utility to register a key that will be removed after some time.\n *\n * @param {String} key - the key to remove.\n * @param {Number} [ms] - the timeout before removal.\n * @return {Receptacle}\n */\ncache.expire = function (key, ttl) {\n var ms = ttl || 0\n var record = this._lookup[key]\n if (!record) return this\n if (typeof ms === 'string') ms = toMS(ttl)\n if (typeof ms !== 'number') throw new TypeError('Expiration time must be a string or number.')\n clearTimeout(record.timeout)\n record.timeout = setTimeout(this.delete.bind(this, record.key), ms)\n record.expires = Number(new Date()) + ms\n return this\n}\n\n/**\n * Deletes all items from the cache.\n * @return {Receptacle}\n */\ncache.clear = function () {\n for (var i = this.items.length; i--;) this.delete(this.items[i].key)\n return this\n}\n\n/**\n * Fixes serialization issues in polyfilled environments.\n * Ensures non-cyclical serialized object.\n */\ncache.toJSON = function () {\n var items = new Array(this.items.length)\n var item\n for (var i = items.length; i--;) {\n item = this.items[i]\n items[i] = {\n key: item.key,\n meta: item.meta,\n value: item.value,\n expires: item.expires,\n refresh: item.refresh\n }\n }\n\n return {\n id: this.id,\n max: isFinite(this.max) ? this.max : undefined,\n lastModified: this.lastModified,\n items: items\n }\n}\n", "module.exports = class FixedFIFO {\n constructor (hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')\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\n push (data) {\n if (this.buffer[this.top] !== undefined) return false\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n return true\n }\n\n shift () {\n const last = this.buffer[this.btm]\n if (last === undefined) return undefined\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n peek () {\n return this.buffer[this.btm]\n }\n\n isEmpty () {\n return this.buffer[this.btm] === undefined\n }\n}\n", "const FixedFIFO = require('./fixed-size')\n\nmodule.exports = class FastFIFO {\n constructor (hwm) {\n this.hwm = hwm || 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n }\n\n push (val) {\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\n shift () {\n const val = this.tail.shift()\n if (val === undefined && this.tail.next) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n return this.tail.shift()\n }\n return val\n }\n\n peek () {\n return this.tail.peek()\n }\n\n isEmpty () {\n return this.head.isEmpty()\n }\n}\n", "'use strict';\n\nconst 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\nmodule.exports = pDefer;\n", "const Fifo = require('fast-fifo')\nconst defer = require('p-defer')\n\nmodule.exports = class PFifo {\n constructor () {\n this._buffer = new Fifo()\n this._waitingConsumers = new Fifo()\n }\n\n push (chunk) {\n const { promise, resolve } = defer()\n this._buffer.push({ chunk, resolve })\n this._consume()\n return promise\n }\n\n _consume () {\n while (!this._waitingConsumers.isEmpty() && !this._buffer.isEmpty()) {\n const nextConsumer = this._waitingConsumers.shift()\n const nextChunk = this._buffer.shift()\n nextConsumer.resolve(nextChunk.chunk)\n nextChunk.resolve()\n }\n }\n\n shift () {\n const { promise, resolve } = defer()\n this._waitingConsumers.push({ resolve })\n this._consume()\n return promise\n }\n\n isEmpty () {\n return this._buffer.isEmpty()\n }\n}\n", "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\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", "'use strict'\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 = require('safe-buffer').Buffer\nvar crypto = global.crypto || global.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", "/*\nindex.js - Kademlia DHT K-bucket implementation as a binary tree.\n\nThe MIT License (MIT)\n\nCopyright (c) 2013-2021 Tristan Slominski\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n'use strict'\n\nconst randomBytes = require('randombytes')\nconst { EventEmitter } = require('events')\n\n/**\n * @param {Uint8Array} array1\n * @param {Uint8Array} array2\n * @return {Boolean}\n */\nfunction arrayEquals (array1, array2) {\n if (array1 === array2) {\n return true\n }\n if (array1.length !== array2.length) {\n return false\n }\n for (let i = 0, length = array1.length; i < length; ++i) {\n if (array1[i] !== array2[i]) {\n return false\n }\n }\n return true\n}\n\nfunction createNode () {\n return { contacts: [], dontSplit: false, left: null, right: null }\n}\n\nfunction ensureInt8 (name, val) {\n if (!(val instanceof Uint8Array)) {\n throw new TypeError(name + ' is not a Uint8Array')\n }\n}\n\n/**\n * Implementation of a Kademlia DHT k-bucket used for storing\n * contact (peer node) information.\n *\n * @extends EventEmitter\n */\nclass KBucket extends EventEmitter {\n /**\n * `options`:\n * `distance`: _Function_\n * `function (firstId, secondId) { return distance }` An optional\n * `distance` function that gets two `id` Uint8Arrays\n * and return distance (as number) between them.\n * `arbiter`: _Function_ _(Default: vectorClock arbiter)_\n * `function (incumbent, candidate) { return contact; }` An optional\n * `arbiter` function that givent two `contact` objects with the same `id`\n * returns the desired object to be used for updating the k-bucket. For\n * more details, see [arbiter function](#arbiter-function).\n * `localNodeId`: _Uint8Array_ An optional Uint8Array representing the local node id.\n * If not provided, a local node id will be created via `randomBytes(20)`.\n * `metadata`: _Object_ _(Default: {})_ Optional satellite data to include\n * with the k-bucket. `metadata` property is guaranteed not be altered by,\n * it is provided as an explicit container for users of k-bucket to store\n * implementation-specific data.\n * `numberOfNodesPerKBucket`: _Integer_ _(Default: 20)_ The number of nodes\n * that a k-bucket can contain before being full or split.\n * `numberOfNodesToPing`: _Integer_ _(Default: 3)_ The number of nodes to\n * ping when a bucket that should not be split becomes full. KBucket will\n * emit a `ping` event that contains `numberOfNodesToPing` nodes that have\n * not been contacted the longest.\n *\n * @param {Object=} options optional\n */\n constructor (options = {}) {\n super()\n\n this.localNodeId = options.localNodeId || randomBytes(20)\n this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20\n this.numberOfNodesToPing = options.numberOfNodesToPing || 3\n this.distance = options.distance || KBucket.distance\n // use an arbiter from options or vectorClock arbiter by default\n this.arbiter = options.arbiter || KBucket.arbiter\n this.metadata = Object.assign({}, options.metadata)\n\n ensureInt8('option.localNodeId as parameter 1', this.localNodeId)\n\n this.root = createNode()\n }\n\n /**\n * Default arbiter function for contacts with the same id. Uses\n * contact.vectorClock to select which contact to update the k-bucket with.\n * Contact with larger vectorClock field will be selected. If vectorClock is\n * the same, candidat will be selected.\n *\n * @param {Object} incumbent Contact currently stored in the k-bucket.\n * @param {Object} candidate Contact being added to the k-bucket.\n * @return {Object} Contact to updated the k-bucket with.\n */\n static arbiter (incumbent, candidate) {\n return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate\n }\n\n /**\n * Default distance function. Finds the XOR\n * distance between firstId and secondId.\n *\n * @param {Uint8Array} firstId Uint8Array containing first id.\n * @param {Uint8Array} secondId Uint8Array containing second id.\n * @return {Number} Integer The XOR distance between firstId\n * and secondId.\n */\n static distance (firstId, secondId) {\n let distance = 0\n let i = 0\n const min = Math.min(firstId.length, secondId.length)\n const max = Math.max(firstId.length, secondId.length)\n for (; i < min; ++i) {\n distance = distance * 256 + (firstId[i] ^ secondId[i])\n }\n for (; i < max; ++i) distance = distance * 256 + 255\n return distance\n }\n\n /**\n * Adds a contact to the k-bucket.\n *\n * @param {Object} contact the contact object to add\n */\n add (contact) {\n ensureInt8('contact.id', (contact || {}).id)\n\n let bitIndex = 0\n let node = this.root\n\n while (node.contacts === null) {\n // this is not a leaf node but an inner node with 'low' and 'high'\n // branches; we will check the appropriate bit of the identifier and\n // delegate to the appropriate node for further processing\n node = this._determineNode(node, contact.id, bitIndex++)\n }\n\n // check if the contact already exists\n const index = this._indexOf(node, contact.id)\n if (index >= 0) {\n this._update(node, index, contact)\n return this\n }\n\n if (node.contacts.length < this.numberOfNodesPerKBucket) {\n node.contacts.push(contact)\n this.emit('added', contact)\n return this\n }\n\n // the bucket is full\n if (node.dontSplit) {\n // we are not allowed to split the bucket\n // we need to ping the first this.numberOfNodesToPing\n // in order to determine if they are alive\n // only if one of the pinged nodes does not respond, can the new contact\n // be added (this prevents DoS flodding with new invalid contacts)\n this.emit('ping', node.contacts.slice(0, this.numberOfNodesToPing), contact)\n return this\n }\n\n this._split(node, bitIndex)\n return this.add(contact)\n }\n\n /**\n * Get the n closest contacts to the provided node id. \"Closest\" here means:\n * closest according to the XOR metric of the contact node id.\n *\n * @param {Uint8Array} id Contact node id\n * @param {Number=} n Integer (Default: Infinity) The maximum number of\n * closest contacts to return\n * @return {Array} Array Maximum of n closest contacts to the node id\n */\n closest (id, n = Infinity) {\n ensureInt8('id', id)\n\n if ((!Number.isInteger(n) && n !== Infinity) || n <= 0) {\n throw new TypeError('n is not positive number')\n }\n\n let contacts = []\n\n for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n;) {\n const node = nodes.pop()\n if (node.contacts === null) {\n const detNode = this._determineNode(node, id, bitIndex++)\n nodes.push(node.left === detNode ? node.right : node.left)\n nodes.push(detNode)\n } else {\n contacts = contacts.concat(node.contacts)\n }\n }\n\n return contacts\n .map(a => [this.distance(a.id, id), a])\n .sort((a, b) => a[0] - b[0])\n .slice(0, n)\n .map(a => a[1])\n }\n\n /**\n * Counts the total number of contacts in the tree.\n *\n * @return {Number} The number of contacts held in the tree\n */\n count () {\n // return this.toArray().length\n let count = 0\n for (const nodes = [this.root]; nodes.length > 0;) {\n const node = nodes.pop()\n if (node.contacts === null) nodes.push(node.right, node.left)\n else count += node.contacts.length\n }\n return count\n }\n\n /**\n * Determines whether the id at the bitIndex is 0 or 1.\n * Return left leaf if `id` at `bitIndex` is 0, right leaf otherwise\n *\n * @param {Object} node internal object that has 2 leafs: left and right\n * @param {Uint8Array} id Id to compare localNodeId with.\n * @param {Number} bitIndex Integer (Default: 0) The bit index to which bit\n * to check in the id Uint8Array.\n * @return {Object} left leaf if id at bitIndex is 0, right leaf otherwise.\n */\n _determineNode (node, id, bitIndex) {\n // **NOTE** remember that id is a Uint8Array and has granularity of\n // bytes (8 bits), whereas the bitIndex is the _bit_ index (not byte)\n\n // id's that are too short are put in low bucket (1 byte = 8 bits)\n // (bitIndex >> 3) finds how many bytes the bitIndex describes\n // bitIndex % 8 checks if we have extra bits beyond byte multiples\n // if number of bytes is <= no. of bytes described by bitIndex and there\n // are extra bits to consider, this means id has less bits than what\n // bitIndex describes, id therefore is too short, and will be put in low\n // bucket\n const bytesDescribedByBitIndex = bitIndex >> 3\n const bitIndexWithinByte = bitIndex % 8\n if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0)) {\n return node.left\n }\n\n const byteUnderConsideration = id[bytesDescribedByBitIndex]\n\n // byteUnderConsideration is an integer from 0 to 255 represented by 8 bits\n // where 255 is 11111111 and 0 is 00000000\n // in order to find out whether the bit at bitIndexWithinByte is set\n // we construct (1 << (7 - bitIndexWithinByte)) which will consist\n // of all bits being 0, with only one bit set to 1\n // for example, if bitIndexWithinByte is 3, we will construct 00010000 by\n // (1 << (7 - 3)) -> (1 << 4) -> 16\n if (byteUnderConsideration & (1 << (7 - bitIndexWithinByte))) {\n return node.right\n }\n\n return node.left\n }\n\n /**\n * Get a contact by its exact ID.\n * If this is a leaf, loop through the bucket contents and return the correct\n * contact if we have it or null if not. If this is an inner node, determine\n * which branch of the tree to traverse and repeat.\n *\n * @param {Uint8Array} id The ID of the contact to fetch.\n * @return {Object|Null} The contact if available, otherwise null\n */\n get (id) {\n ensureInt8('id', id)\n\n let bitIndex = 0\n\n let node = this.root\n while (node.contacts === null) {\n node = this._determineNode(node, id, bitIndex++)\n }\n\n // index of uses contact id for matching\n const index = this._indexOf(node, id)\n return index >= 0 ? node.contacts[index] : null\n }\n\n /**\n * Returns the index of the contact with provided\n * id if it exists, returns -1 otherwise.\n *\n * @param {Object} node internal object that has 2 leafs: left and right\n * @param {Uint8Array} id Contact node id.\n * @return {Number} Integer Index of contact with provided id if it\n * exists, -1 otherwise.\n */\n _indexOf (node, id) {\n for (let i = 0; i < node.contacts.length; ++i) {\n if (arrayEquals(node.contacts[i].id, id)) return i\n }\n\n return -1\n }\n\n /**\n * Removes contact with the provided id.\n *\n * @param {Uint8Array} id The ID of the contact to remove.\n * @return {Object} The k-bucket itself.\n */\n remove (id) {\n ensureInt8('the id as parameter 1', id)\n\n let bitIndex = 0\n let node = this.root\n\n while (node.contacts === null) {\n node = this._determineNode(node, id, bitIndex++)\n }\n\n const index = this._indexOf(node, id)\n if (index >= 0) {\n const contact = node.contacts.splice(index, 1)[0]\n this.emit('removed', contact)\n }\n\n return this\n }\n\n /**\n * Splits the node, redistributes contacts to the new nodes, and marks the\n * node that was split as an inner node of the binary tree of nodes by\n * setting this.root.contacts = null\n *\n * @param {Object} node node for splitting\n * @param {Number} bitIndex the bitIndex to which byte to check in the\n * Uint8Array for navigating the binary tree\n */\n _split (node, bitIndex) {\n node.left = createNode()\n node.right = createNode()\n\n // redistribute existing contacts amongst the two newly created nodes\n for (const contact of node.contacts) {\n this._determineNode(node, contact.id, bitIndex).contacts.push(contact)\n }\n\n node.contacts = null // mark as inner tree node\n\n // don't split the \"far away\" node\n // we check where the local node would end up and mark the other one as\n // \"dontSplit\" (i.e. \"far away\")\n const detNode = this._determineNode(node, this.localNodeId, bitIndex)\n const otherNode = node.left === detNode ? node.right : node.left\n otherNode.dontSplit = true\n }\n\n /**\n * Returns all the contacts contained in the tree as an array.\n * If this is a leaf, return a copy of the bucket. If this is not a leaf,\n * return the union of the low and high branches (themselves also as arrays).\n *\n * @return {Array} All of the contacts in the tree, as an array\n */\n toArray () {\n let result = []\n for (const nodes = [this.root]; nodes.length > 0;) {\n const node = nodes.pop()\n if (node.contacts === null) nodes.push(node.right, node.left)\n else result = result.concat(node.contacts)\n }\n return result\n }\n\n /**\n * Similar to `toArray()` but instead of buffering everything up into an\n * array before returning it, yields contacts as they are encountered while\n * walking the tree.\n *\n * @return {Iterable} All of the contacts in the tree, as an iterable\n */\n * toIterable () {\n for (const nodes = [this.root]; nodes.length > 0;) {\n const node = nodes.pop()\n if (node.contacts === null) {\n nodes.push(node.right, node.left)\n } else {\n yield * node.contacts\n }\n }\n }\n\n /**\n * Updates the contact selected by the arbiter.\n * If the selection is our old contact and the candidate is some new contact\n * then the new contact is abandoned (not added).\n * If the selection is our old contact and the candidate is our old contact\n * then we are refreshing the contact and it is marked as most recently\n * contacted (by being moved to the right/end of the bucket array).\n * If the selection is our new contact, the old contact is removed and the new\n * contact is marked as most recently contacted.\n *\n * @param {Object} node internal object that has 2 leafs: left and right\n * @param {Number} index the index in the bucket where contact exists\n * (index has already been computed in a previous\n * calculation)\n * @param {Object} contact The contact object to update.\n */\n _update (node, index, contact) {\n // sanity check\n if (!arrayEquals(node.contacts[index].id, contact.id)) {\n throw new Error('wrong index for _update')\n }\n\n const incumbent = node.contacts[index]\n const selection = this.arbiter(incumbent, contact)\n // if the selection is our old contact and the candidate is some new\n // contact, then there is nothing to do\n if (selection === incumbent && incumbent !== contact) return\n\n node.contacts.splice(index, 1) // remove old contact\n node.contacts.push(selection) // add more recent contact version\n this.emit('updated', incumbent, selection)\n }\n}\n\nmodule.exports = KBucket\n", "(function (root) {\n 'use strict';\n // A list of regular expressions that match arbitrary IPv4 addresses,\n // for which a number of weird notations exist.\n // Note that an address like 0010.0xa5.1.1 is considered legal.\n const ipv4Part = '(0?\\\\d+|0x[a-f0-9]+)';\n const ipv4Regexes = {\n fourOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n threeOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n twoOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n longValue: new RegExp(`^${ipv4Part}$`, 'i')\n };\n\n // Regular Expression for checking Octal numbers\n const octalRegex = new RegExp(`^0[0-7]+$`, 'i');\n const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');\n\n const zoneIndex = '%[0-9a-z]{1,}';\n\n // IPv6-matching regular expressions.\n // For IPv6, the task is simpler: it is enough to match the colon-delimited\n // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at\n // the end.\n const ipv6Part = '(?:[0-9a-f]+::?)+';\n const ipv6Regexes = {\n zoneIndex: new RegExp(zoneIndex, 'i'),\n 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),\n deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),\n transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?$`, 'i')\n };\n\n // Expand :: in an IPv6 address or address part consisting of `parts` groups.\n function expandIPv6 (string, parts) {\n // More than one '::' means invalid adddress\n if (string.indexOf('::') !== string.lastIndexOf('::')) {\n return null;\n }\n\n let colonCount = 0;\n let lastColon = -1;\n let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];\n let replacement, replacementCount;\n\n // Remove zone index and save it for later\n if (zoneId) {\n zoneId = zoneId.substring(1);\n string = string.replace(/%.+$/, '');\n }\n\n // How many parts do we already have?\n while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {\n colonCount++;\n }\n\n // 0::0 is two parts more than ::\n if (string.substr(0, 2) === '::') {\n colonCount--;\n }\n\n if (string.substr(-2, 2) === '::') {\n colonCount--;\n }\n\n // The following loop would hang if colonCount > parts\n if (colonCount > parts) {\n return null;\n }\n\n // replacement = ':' + '0:' * (parts - colonCount)\n replacementCount = parts - colonCount;\n replacement = ':';\n while (replacementCount--) {\n replacement += '0:';\n }\n\n // Insert the missing zeroes\n string = string.replace('::', replacement);\n\n // Trim any garbage which may be hanging around if :: was at the edge in\n // the source strin\n if (string[0] === ':') {\n string = string.slice(1);\n }\n\n if (string[string.length - 1] === ':') {\n string = string.slice(0, -1);\n }\n\n parts = (function () {\n const ref = string.split(':');\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n results.push(parseInt(ref[i], 16));\n }\n\n return results;\n })();\n\n return {\n parts: parts,\n zoneId: zoneId\n };\n }\n\n // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.\n function matchCIDR (first, second, partSize, cidrBits) {\n if (first.length !== second.length) {\n throw new Error('ipaddr: cannot match CIDR for objects with different lengths');\n }\n\n let part = 0;\n let shift;\n\n while (cidrBits > 0) {\n shift = partSize - cidrBits;\n if (shift < 0) {\n shift = 0;\n }\n\n if (first[part] >> shift !== second[part] >> shift) {\n return false;\n }\n\n cidrBits -= partSize;\n part += 1;\n }\n\n return true;\n }\n\n function parseIntAuto (string) {\n // Hexadedimal base 16 (0x#)\n if (hexRegex.test(string)) {\n return parseInt(string, 16);\n }\n // While octal representation is discouraged by ECMAScript 3\n // and forbidden by ECMAScript 5, we silently allow it to\n // work only if the rest of the string has numbers less than 8.\n if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {\n if (octalRegex.test(string)) {\n return parseInt(string, 8);\n }\n throw new Error(`ipaddr: cannot parse ${string} as octal`);\n }\n // Always include the base 10 radix!\n return parseInt(string, 10);\n }\n\n function padPart (part, length) {\n while (part.length < length) {\n part = `0${part}`;\n }\n\n return part;\n }\n\n const ipaddr = {};\n\n // An IPv4 address (RFC791).\n ipaddr.IPv4 = (function () {\n // Constructs a new IPv4 address from an array of four octets\n // in network order (MSB first)\n // Verifies the input.\n function IPv4 (octets) {\n if (octets.length !== 4) {\n throw new Error('ipaddr: ipv4 octet count should be 4');\n }\n\n let i, octet;\n\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n throw new Error('ipaddr: ipv4 octet should fit in 8 bits');\n }\n }\n\n this.octets = octets;\n }\n\n // Special IPv4 address ranges.\n // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses\n IPv4.prototype.SpecialRanges = {\n unspecified: [[new IPv4([0, 0, 0, 0]), 8]],\n broadcast: [[new IPv4([255, 255, 255, 255]), 32]],\n // RFC3171\n multicast: [[new IPv4([224, 0, 0, 0]), 4]],\n // RFC3927\n linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],\n // RFC5735\n loopback: [[new IPv4([127, 0, 0, 0]), 8]],\n // RFC6598\n carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],\n // RFC1918\n 'private': [\n [new IPv4([10, 0, 0, 0]), 8],\n [new IPv4([172, 16, 0, 0]), 12],\n [new IPv4([192, 168, 0, 0]), 16]\n ],\n // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700\n reserved: [\n [new IPv4([192, 0, 0, 0]), 24],\n [new IPv4([192, 0, 2, 0]), 24],\n [new IPv4([192, 88, 99, 0]), 24],\n [new IPv4([198, 18, 0, 0]), 15],\n [new IPv4([198, 51, 100, 0]), 24],\n [new IPv4([203, 0, 113, 0]), 24],\n [new IPv4([240, 0, 0, 0]), 4]\n ],\n // RFC7534, RFC7535\n as112: [\n [new IPv4([192, 175, 48, 0]), 24],\n [new IPv4([192, 31, 196, 0]), 24],\n ],\n // RFC7450\n amt: [\n [new IPv4([192, 52, 193, 0]), 24],\n ],\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv4.prototype.kind = function () {\n return 'ipv4';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv4.prototype.match = function (other, cidrRange) {\n let ref;\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv4') {\n throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');\n }\n\n return matchCIDR(this.octets, other.octets, 8, cidrRange);\n };\n\n // returns a number of leading ones in IPv4 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv4.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 8,\n 128: 7,\n 192: 6,\n 224: 5,\n 240: 4,\n 248: 3,\n 252: 2,\n 254: 1,\n 255: 0\n };\n let i, octet, zeros;\n\n for (i = 3; i >= 0; i -= 1) {\n octet = this.octets[i];\n if (octet in zerotable) {\n zeros = zerotable[octet];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 8) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 32 - cidr;\n };\n\n // Checks if the address corresponds to one of the special ranges.\n IPv4.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv4.prototype.toByteArray = function () {\n return this.octets.slice(0);\n };\n\n // Converts this IPv4 address to an IPv4-mapped IPv6 address.\n IPv4.prototype.toIPv4MappedAddress = function () {\n return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);\n };\n\n // Symmetrical method strictly for aligning with the IPv6 methods.\n IPv4.prototype.toNormalizedString = function () {\n return this.toString();\n };\n\n // Returns the address in convenient, decimal-dotted format.\n IPv4.prototype.toString = function () {\n return this.octets.join('.');\n };\n\n return IPv4;\n })();\n\n // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {\n\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 4) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Checks if a given string is formatted like IPv4 address.\n ipaddr.IPv4.isIPv4 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks if a given string is a valid IPv4 address.\n ipaddr.IPv4.isValid = function (string) {\n try {\n new this(this.parser(string));\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv4 address in CIDR notation.\n ipaddr.IPv4.isValidCIDR = function (string) {\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address.\n ipaddr.IPv4.isValidFourPartDecimal = function (string) {\n if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){3}$/)) {\n return true;\n } else {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 4) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Tries to parse and validate a string with IPv4 address.\n // Throws an error if it fails.\n ipaddr.IPv4.parse = function (string) {\n const parts = this.parser(string);\n\n if (parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv4 Address');\n }\n\n return new this(parts);\n };\n\n // Parses the string as an IPv4 Address with CIDR Notation.\n ipaddr.IPv4.parseCIDR = function (string) {\n let match;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n const maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 32) {\n const parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');\n };\n\n // Classful variants (like a.b, where a is an octet, and b is a 24-bit\n // value representing last three octets; this corresponds to a class C\n // address) are omitted due to classless nature of modern Internet.\n ipaddr.IPv4.parser = function (string) {\n let match, part, value;\n\n // parseInt recognizes all that octal & hexadecimal weirdness for us\n if ((match = string.match(ipv4Regexes.fourOctet))) {\n return (function () {\n const ref = match.slice(1, 6);\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n results.push(parseIntAuto(part));\n }\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.longValue))) {\n value = parseIntAuto(match[1]);\n if (value > 0xffffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n return ((function () {\n const results = [];\n let shift;\n\n for (shift = 0; shift <= 24; shift += 8) {\n results.push((value >> shift) & 0xff);\n }\n\n return results;\n })()).reverse();\n } else if ((match = string.match(ipv4Regexes.twoOctet))) {\n return (function () {\n const ref = match.slice(1, 4);\n const results = [];\n\n value = parseIntAuto(ref[1]);\n if (value > 0xffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push((value >> 16) & 0xff);\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.threeOctet))) {\n return (function () {\n const ref = match.slice(1, 5);\n const results = [];\n\n value = parseIntAuto(ref[2]);\n if (value > 0xffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push(parseIntAuto(ref[1]));\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else {\n return null;\n }\n };\n\n // A utility function to return subnet mask in IPv4 format given the prefix length\n ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 32) {\n throw new Error('ipaddr: invalid IPv4 prefix length');\n }\n\n const octets = [0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 4) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // An IPv6 address (RFC2460)\n ipaddr.IPv6 = (function () {\n // Constructs an IPv6 address from an array of eight 16 - bit parts\n // or sixteen 8 - bit parts in network order(MSB first).\n // Throws an error if the input is invalid.\n function IPv6 (parts, zoneId) {\n let i, part;\n\n if (parts.length === 16) {\n this.parts = [];\n for (i = 0; i <= 14; i += 2) {\n this.parts.push((parts[i] << 8) | parts[i + 1]);\n }\n } else if (parts.length === 8) {\n this.parts = parts;\n } else {\n throw new Error('ipaddr: ipv6 part count should be 8 or 16');\n }\n\n for (i = 0; i < this.parts.length; i++) {\n part = this.parts[i];\n if (!((0 <= part && part <= 0xffff))) {\n throw new Error('ipaddr: ipv6 part should fit in 16 bits');\n }\n }\n\n if (zoneId) {\n this.zoneId = zoneId;\n }\n }\n\n // Special IPv6 ranges\n IPv6.prototype.SpecialRanges = {\n // RFC4291, here and after\n unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],\n linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],\n multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],\n loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],\n uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],\n ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],\n // RFC6666\n discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64],\n // RFC6145\n rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],\n // RFC6052\n rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],\n // RFC3056\n '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],\n // RFC6052, RFC6146\n teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],\n // RFC5180\n benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48],\n // RFC7450\n amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32],\n as112v6: [\n [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48],\n [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48],\n ],\n deprecated: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28],\n orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28],\n droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28],\n reserved: [\n // RFC3849\n [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23],\n // RFC2928\n [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32],\n ],\n };\n\n // Checks if this address is an IPv4-mapped IPv6 address.\n IPv6.prototype.isIPv4MappedAddress = function () {\n return this.range() === 'ipv4Mapped';\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv6.prototype.kind = function () {\n return 'ipv6';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv6.prototype.match = function (other, cidrRange) {\n let ref;\n\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv6') {\n throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');\n }\n\n return matchCIDR(this.parts, other.parts, 16, cidrRange);\n };\n\n // returns a number of leading ones in IPv6 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv6.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 16,\n 32768: 15,\n 49152: 14,\n 57344: 13,\n 61440: 12,\n 63488: 11,\n 64512: 10,\n 65024: 9,\n 65280: 8,\n 65408: 7,\n 65472: 6,\n 65504: 5,\n 65520: 4,\n 65528: 3,\n 65532: 2,\n 65534: 1,\n 65535: 0\n };\n let part, zeros;\n\n for (let i = 7; i >= 0; i -= 1) {\n part = this.parts[i];\n if (part in zerotable) {\n zeros = zerotable[part];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 16) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 128 - cidr;\n };\n\n\n // Checks if the address corresponds to one of the special ranges.\n IPv6.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv6.prototype.toByteArray = function () {\n let part;\n const bytes = [];\n const ref = this.parts;\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n bytes.push(part >> 8);\n bytes.push(part & 0xff);\n }\n\n return bytes;\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:0db8:0008:0066:0000:0000:0000:0001\n IPv6.prototype.toFixedLengthString = function () {\n const addr = ((function () {\n const results = [];\n for (let i = 0; i < this.parts.length; i++) {\n results.push(padPart(this.parts[i].toString(16), 4));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.\n // Throws an error otherwise.\n IPv6.prototype.toIPv4Address = function () {\n if (!this.isIPv4MappedAddress()) {\n throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');\n }\n\n const ref = this.parts.slice(-2);\n const high = ref[0];\n const low = ref[1];\n\n return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:db8:8:66:0:0:0:1\n //\n // Deprecated: use toFixedLengthString() instead.\n IPv6.prototype.toNormalizedString = function () {\n const addr = ((function () {\n const results = [];\n\n for (let i = 0; i < this.parts.length; i++) {\n results.push(this.parts[i].toString(16));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)\n IPv6.prototype.toRFC5952String = function () {\n const regex = /((^|:)(0(:|$)){2,})/g;\n const string = this.toNormalizedString();\n let bestMatchIndex = 0;\n let bestMatchLength = -1;\n let match;\n\n while ((match = regex.exec(string))) {\n if (match[0].length > bestMatchLength) {\n bestMatchIndex = match.index;\n bestMatchLength = match[0].length;\n }\n }\n\n if (bestMatchLength < 0) {\n return string;\n }\n\n return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // Calls toRFC5952String under the hood.\n IPv6.prototype.toString = function () {\n return this.toRFC5952String();\n };\n\n return IPv6;\n\n })();\n\n // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 16) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Checks if a given string is formatted like IPv6 address.\n ipaddr.IPv6.isIPv6 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks to see if string is a valid IPv6 Address\n ipaddr.IPv6.isValid = function (string) {\n\n // Since IPv6.isValid is always called first, this shortcut\n // provides a substantial performance gain.\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n const addr = this.parser(string);\n new this(addr.parts, addr.zoneId);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv6 address in CIDR notation.\n ipaddr.IPv6.isValidCIDR = function (string) {\n\n // See note in IPv6.isValid\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 16) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Tries to parse and validate a string with IPv6 address.\n // Throws an error if it fails.\n ipaddr.IPv6.parse = function (string) {\n const addr = this.parser(string);\n\n if (addr.parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv6 Address');\n }\n\n return new this(addr.parts, addr.zoneId);\n };\n\n ipaddr.IPv6.parseCIDR = function (string) {\n let maskLength, match, parsed;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 128) {\n parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');\n };\n\n // Parse an IPv6 address.\n ipaddr.IPv6.parser = function (string) {\n let addr, i, match, octet, octets, zoneId;\n\n if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {\n return this.parser(`::ffff:${match[1]}`);\n }\n if (ipv6Regexes.native.test(string)) {\n return expandIPv6(string, 8);\n }\n if ((match = string.match(ipv6Regexes.transitional))) {\n zoneId = match[6] || '';\n addr = match[1]\n if (!match[1].endsWith('::')) {\n addr = addr.slice(0, -1)\n }\n addr = expandIPv6(addr + zoneId, 6);\n if (addr.parts) {\n octets = [\n parseInt(match[2]),\n parseInt(match[3]),\n parseInt(match[4]),\n parseInt(match[5])\n ];\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n return null;\n }\n }\n\n addr.parts.push(octets[0] << 8 | octets[1]);\n addr.parts.push(octets[2] << 8 | octets[3]);\n return {\n parts: addr.parts,\n zoneId: addr.zoneId\n };\n }\n }\n\n return null;\n };\n\n // A utility function to return subnet mask in IPv6 format given the prefix length\n ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 128) {\n throw new Error('ipaddr: invalid IPv6 prefix length');\n }\n\n const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 16) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // Try to parse an array in network order (MSB first) for IPv4 and IPv6\n ipaddr.fromByteArray = function (bytes) {\n const length = bytes.length;\n\n if (length === 4) {\n return new ipaddr.IPv4(bytes);\n } else if (length === 16) {\n return new ipaddr.IPv6(bytes);\n } else {\n throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');\n }\n };\n\n // Checks if the address is valid IP address\n ipaddr.isValid = function (string) {\n return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);\n };\n\n // Checks if the address is valid IP address in CIDR notation\n ipaddr.isValidCIDR = function (string) {\n return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);\n };\n\n\n // Attempts to parse an IP Address, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parse = function (string) {\n if (ipaddr.IPv6.isValid(string)) {\n return ipaddr.IPv6.parse(string);\n } else if (ipaddr.IPv4.isValid(string)) {\n return ipaddr.IPv4.parse(string);\n } else {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');\n }\n };\n\n // Attempt to parse CIDR notation, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parseCIDR = function (string) {\n try {\n return ipaddr.IPv6.parseCIDR(string);\n } catch (e) {\n try {\n return ipaddr.IPv4.parseCIDR(string);\n } catch (e2) {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');\n }\n }\n };\n\n // Parse an address and return plain IPv4 address if it is an IPv4-mapped address\n ipaddr.process = function (string) {\n const addr = this.parse(string);\n\n if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {\n return addr.toIPv4Address();\n } else {\n return addr;\n }\n };\n\n // An utility function to ease named range matching. See examples below.\n // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors\n // on matching IPv4 addresses to IPv6 ranges or vice versa.\n ipaddr.subnetMatch = function (address, rangeList, defaultName) {\n let i, rangeName, rangeSubnets, subnet;\n\n if (defaultName === undefined || defaultName === null) {\n defaultName = 'unicast';\n }\n\n for (rangeName in rangeList) {\n if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {\n rangeSubnets = rangeList[rangeName];\n // ECMA5 Array.isArray isn't available everywhere\n if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {\n rangeSubnets = [rangeSubnets];\n }\n\n for (i = 0; i < rangeSubnets.length; i++) {\n subnet = rangeSubnets[i];\n if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {\n return rangeName;\n }\n }\n }\n }\n\n return defaultName;\n };\n\n // Export for both the CommonJS and browser-like environment\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = ipaddr;\n\n } else {\n root.ipaddr = ipaddr;\n }\n\n}(this));\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\";\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", "module.exports = class RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * points: 4, // Number of points\n * duration: 1, // Per seconds\n * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds\n * execEvenly: false, // Execute allowed actions evenly over duration\n * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option\n * keyPrefix: 'rlflx',\n * }\n */\n constructor(opts = {}) {\n this.points = opts.points;\n this.duration = opts.duration;\n this.blockDuration = opts.blockDuration;\n this.execEvenly = opts.execEvenly;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs;\n this.keyPrefix = opts.keyPrefix;\n }\n\n get points() {\n return this._points;\n }\n\n set points(value) {\n this._points = value >= 0 ? value : 4;\n }\n\n get duration() {\n return this._duration;\n }\n\n set duration(value) {\n this._duration = typeof value === 'undefined' ? 1 : value;\n }\n\n get msDuration() {\n return this.duration * 1000;\n }\n\n get blockDuration() {\n return this._blockDuration;\n }\n\n set blockDuration(value) {\n this._blockDuration = typeof value === 'undefined' ? 0 : value;\n }\n\n get msBlockDuration() {\n return this.blockDuration * 1000;\n }\n\n get execEvenly() {\n return this._execEvenly;\n }\n\n set execEvenly(value) {\n this._execEvenly = typeof value === 'undefined' ? false : Boolean(value);\n }\n\n get execEvenlyMinDelayMs() {\n return this._execEvenlyMinDelayMs;\n }\n\n set execEvenlyMinDelayMs(value) {\n this._execEvenlyMinDelayMs = typeof value === 'undefined' ? Math.ceil(this.msDuration / this.points) : value;\n }\n\n get keyPrefix() {\n return this._keyPrefix;\n }\n\n set keyPrefix(value) {\n if (typeof value === 'undefined') {\n value = 'rlflx';\n }\n if (typeof value !== 'string') {\n throw new Error('keyPrefix must be string');\n }\n this._keyPrefix = value;\n }\n\n _getKeySecDuration(options = {}) {\n return options && options.customDuration >= 0\n ? options.customDuration\n : this.duration;\n }\n\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n\n consume() {\n throw new Error(\"You have to implement the method 'consume'!\");\n }\n\n penalty() {\n throw new Error(\"You have to implement the method 'penalty'!\");\n }\n\n reward() {\n throw new Error(\"You have to implement the method 'reward'!\");\n }\n\n get() {\n throw new Error(\"You have to implement the method 'get'!\");\n }\n\n set() {\n throw new Error(\"You have to implement the method 'set'!\");\n }\n\n block() {\n throw new Error(\"You have to implement the method 'block'!\");\n }\n\n delete() {\n throw new Error(\"You have to implement the method 'delete'!\");\n }\n};\n", "module.exports = class BlockedKeys {\n constructor() {\n this._keys = {}; // {'key': 1526279430331}\n this._addedKeysAmount = 0;\n }\n\n collectExpired() {\n const now = Date.now();\n\n Object.keys(this._keys).forEach((key) => {\n if (this._keys[key] <= now) {\n delete this._keys[key];\n }\n });\n\n this._addedKeysAmount = Object.keys(this._keys).length;\n }\n\n /**\n * Add new blocked key\n *\n * @param key String\n * @param sec Number\n */\n add(key, sec) {\n this.addMs(key, sec * 1000);\n }\n\n /**\n * Add new blocked key for ms\n *\n * @param key String\n * @param ms Number\n */\n addMs(key, ms) {\n this._keys[key] = Date.now() + ms;\n this._addedKeysAmount++;\n if (this._addedKeysAmount > 999) {\n this.collectExpired();\n }\n }\n\n /**\n * 0 means not blocked\n *\n * @param key\n * @returns {number}\n */\n msBeforeExpire(key) {\n const expire = this._keys[key];\n\n if (expire && expire >= Date.now()) {\n this.collectExpired();\n const now = Date.now();\n return expire >= now ? expire - now : 0;\n }\n\n return 0;\n }\n\n /**\n * If key is not given, delete all data in memory\n * \n * @param {string|undefined} key\n */\n delete(key) {\n if (key) {\n delete this._keys[key];\n } else {\n Object.keys(this._keys).forEach((key) => {\n delete this._keys[key];\n });\n }\n }\n};\n", "const BlockedKeys = require('./BlockedKeys');\n\nmodule.exports = BlockedKeys;\n", "module.exports = class RateLimiterRes {\n constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) {\n this.remainingPoints = typeof remainingPoints === 'undefined' ? 0 : remainingPoints; // Remaining points in current duration\n this.msBeforeNext = typeof msBeforeNext === 'undefined' ? 0 : msBeforeNext; // Milliseconds before next action\n this.consumedPoints = typeof consumedPoints === 'undefined' ? 0 : consumedPoints; // Consumed points in current duration\n this.isFirstInDuration = typeof isFirstInDuration === 'undefined' ? false : isFirstInDuration;\n }\n\n get msBeforeNext() {\n return this._msBeforeNext;\n }\n\n set msBeforeNext(ms) {\n this._msBeforeNext = ms;\n return this;\n }\n\n get remainingPoints() {\n return this._remainingPoints;\n }\n\n set remainingPoints(p) {\n this._remainingPoints = p;\n return this;\n }\n\n get consumedPoints() {\n return this._consumedPoints;\n }\n\n set consumedPoints(p) {\n this._consumedPoints = p;\n return this;\n }\n\n get isFirstInDuration() {\n return this._isFirstInDuration;\n }\n\n set isFirstInDuration(value) {\n this._isFirstInDuration = Boolean(value);\n }\n\n _getDecoratedProperties() {\n return {\n remainingPoints: this.remainingPoints,\n msBeforeNext: this.msBeforeNext,\n consumedPoints: this.consumedPoints,\n isFirstInDuration: this.isFirstInDuration,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this._getDecoratedProperties();\n }\n\n toString() {\n return JSON.stringify(this._getDecoratedProperties());\n }\n\n toJSON() {\n return this._getDecoratedProperties();\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst BlockedKeys = require('./component/BlockedKeys');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RateLimiterStoreAbstract extends RateLimiterAbstract {\n /**\n *\n * @param opts Object Defaults {\n * ... see other in RateLimiterAbstract\n *\n * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked\n * inMemoryBlockDuration: 10, // Block duration in seconds\n * insuranceLimiter: RateLimiterAbstract\n * }\n */\n constructor(opts = {}) {\n super(opts);\n\n this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed || opts.inmemoryBlockOnConsumed;\n this.inMemoryBlockDuration = opts.inMemoryBlockDuration || opts.inmemoryBlockDuration;\n this.insuranceLimiter = opts.insuranceLimiter;\n this._inMemoryBlockedKeys = new BlockedKeys();\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('storeClient is not set');\n }\n this._client = value;\n }\n\n /**\n * Have to be launched after consume\n * It blocks key and execute evenly depending on result from store\n *\n * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result\n *\n * @param resolve\n * @param reject\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @param {Object} options\n * @private\n */\n _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) {\n const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult);\n\n if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0)\n && res.consumedPoints >= this.inMemoryBlockOnConsumed\n ) {\n this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext);\n if (res.consumedPoints > this.points) {\n return reject(res);\n } else {\n return resolve(res)\n }\n } else if (res.consumedPoints > this.points) {\n let blockPromise = Promise.resolve();\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + changedPoints)) {\n res.msBeforeNext = this.msBlockDuration;\n blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options);\n }\n\n if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) {\n // Block key for this.inMemoryBlockDuration seconds\n this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration);\n res.msBeforeNext = this.msInMemoryBlockDuration;\n }\n\n blockPromise\n .then(() => {\n reject(res);\n })\n .catch((err) => {\n reject(err);\n });\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n }\n\n _handleError(err, funcName, resolve, reject, key, data = false, options = {}) {\n if (!(this.insuranceLimiter instanceof RateLimiterAbstract)) {\n reject(err);\n } else {\n this.insuranceLimiter[funcName](key, data, options)\n .then((res) => {\n resolve(res);\n })\n .catch((res) => {\n reject(res);\n });\n }\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {BlockedKeys}\n * @private\n */\n get _inmemoryBlockedKeys() {\n return this._inMemoryBlockedKeys\n }\n\n /**\n * @deprecated Use camelCase version\n * @param rlKey\n * @returns {number}\n */\n getInmemoryBlockMsBeforeExpire(rlKey) {\n return this.getInMemoryBlockMsBeforeExpire(rlKey)\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockOnConsumed() {\n return this.inMemoryBlockOnConsumed;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockOnConsumed(value) {\n this.inMemoryBlockOnConsumed = value;\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number|number}\n */\n get inmemoryBlockDuration() {\n return this.inMemoryBlockDuration;\n }\n\n /**\n * @deprecated Use camelCase version\n * @param value\n */\n set inmemoryBlockDuration(value) {\n this.inMemoryBlockDuration = value\n }\n\n /**\n * @deprecated Use camelCase version\n * @returns {number}\n */\n get msInmemoryBlockDuration() {\n return this.inMemoryBlockDuration * 1000;\n }\n\n getInMemoryBlockMsBeforeExpire(rlKey) {\n if (this.inMemoryBlockOnConsumed > 0) {\n return this._inMemoryBlockedKeys.msBeforeExpire(rlKey);\n }\n\n return 0;\n }\n\n get inMemoryBlockOnConsumed() {\n return this._inMemoryBlockOnConsumed;\n }\n\n set inMemoryBlockOnConsumed(value) {\n this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0;\n if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) {\n throw new Error('inMemoryBlockOnConsumed option must be greater or equal \"points\" option');\n }\n }\n\n get inMemoryBlockDuration() {\n return this._inMemoryBlockDuration;\n }\n\n set inMemoryBlockDuration(value) {\n this._inMemoryBlockDuration = value ? parseInt(value) : 0;\n if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) {\n throw new Error('inMemoryBlockOnConsumed option must be set up');\n }\n }\n\n get msInMemoryBlockDuration() {\n return this._inMemoryBlockDuration * 1000;\n }\n\n get insuranceLimiter() {\n return this._insuranceLimiter;\n }\n\n set insuranceLimiter(value) {\n if (typeof value !== 'undefined' && !(value instanceof RateLimiterAbstract)) {\n throw new Error('insuranceLimiter must be instance of RateLimiterAbstract');\n }\n this._insuranceLimiter = value;\n if (this._insuranceLimiter) {\n this._insuranceLimiter.blockDuration = this.blockDuration;\n this._insuranceLimiter.execEvenly = this.execEvenly;\n }\n }\n\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n block(key, secDuration, options = {}) {\n const msDuration = secDuration * 1000;\n return this._block(this.getKey(key), this.points + 1, msDuration, options);\n }\n\n /**\n * Set points by key for any duration\n *\n * @param key\n * @param points\n * @param secDuration\n * @param {Object} options\n *\n * @return Promise\n */\n set(key, points, secDuration, options = {}) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n return this._block(this.getKey(key), points, msDuration, options);\n }\n\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns Promise\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const rlKey = this.getKey(key);\n\n const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey);\n if (inMemoryBlockMsBeforeExpire > 0) {\n return reject(new RateLimiterRes(0, inMemoryBlockMsBeforeExpire));\n }\n\n this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n this._afterConsume(resolve, reject, rlKey, pointsToConsume, res);\n })\n .catch((err) => {\n this._handleError(err, 'consume', resolve, reject, key, pointsToConsume, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, points, res));\n })\n .catch((err) => {\n this._handleError(err, 'penalty', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param points\n * @param {Object} options\n * @returns Promise\n */\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1000, false, options)\n .then((res) => {\n resolve(this._getRateLimiterRes(rlKey, -points, res));\n })\n .catch((err) => {\n this._handleError(err, 'reward', resolve, reject, key, points, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise|null\n */\n get(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._get(rlKey, options)\n .then((res) => {\n if (res === null || typeof res === 'undefined') {\n resolve(null);\n } else {\n resolve(this._getRateLimiterRes(rlKey, 0, res));\n }\n })\n .catch((err) => {\n this._handleError(err, 'get', resolve, reject, key, options);\n });\n });\n }\n\n /**\n *\n * @param key\n * @param {Object} options\n * @returns Promise\n */\n delete(key, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve, reject) => {\n this._delete(rlKey, options)\n .then((res) => {\n this._inMemoryBlockedKeys.delete(rlKey);\n resolve(res);\n })\n .catch((err) => {\n this._handleError(err, 'delete', resolve, reject, key, options);\n });\n });\n }\n\n /**\n * Cleanup keys no-matter expired or not.\n */\n deleteInMemoryBlockedAll() {\n this._inMemoryBlockedKeys.delete();\n }\n\n /**\n * Get RateLimiterRes object filled depending on storeResult, which specific for exact store\n *\n * @param rlKey\n * @param changedPoints\n * @param storeResult\n * @private\n */\n _getRateLimiterRes(rlKey, changedPoints, storeResult) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_getRateLimiterRes'!\");\n }\n\n /**\n * Block key for this.msBlockDuration milliseconds\n * Usually, it just prolongs lifetime of key\n *\n * @param rlKey\n * @param initPoints\n * @param msDuration\n * @param {Object} options\n *\n * @return Promise\n */\n _block(rlKey, initPoints, msDuration, options = {}) {\n return new Promise((resolve, reject) => {\n this._upsert(rlKey, initPoints, msDuration, true, options)\n .then(() => {\n resolve(new RateLimiterRes(0, msDuration > 0 ? msDuration : -1, initPoints));\n })\n .catch((err) => {\n this._handleError(err, 'block', resolve, reject, this.parseKey(rlKey), msDuration / 1000, options);\n });\n });\n }\n\n /**\n * Have to be implemented in every limiter\n * Resolve with raw result from Store OR null if rlKey is not set\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _get(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_get'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with true OR false if rlKey doesn't exist\n * or Reject with error\n *\n * @param rlKey\n * @param {Object} options\n * @private\n *\n * @return Promise\n */\n _delete(rlKey, options = {}) { // eslint-disable-line no-unused-vars\n throw new Error(\"You have to implement the method '_delete'!\");\n }\n\n /**\n * Have to be implemented\n * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}\n *\n * @param {string} rlKey\n * @param {number} points\n * @param {number} msDuration\n * @param {boolean} forceExpire\n * @param {Object} options\n * @abstract\n *\n * @return Promise\n */\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n throw new Error(\"You have to implement the method '_upsert'!\");\n }\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst incrTtlLuaScript = `redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') \\\nlocal consumed = redis.call('incrby', KEYS[1], ARGV[1]) \\\nlocal ttl = redis.call('pttl', KEYS[1]) \\\nif ttl == -1 then \\\n redis.call('expire', KEYS[1], ARGV[2]) \\\n ttl = 1000 * ARGV[2] \\\nend \\\nreturn {consumed, ttl} \\\n`;\n\nclass RateLimiterRedis extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * redis: RedisClient\n * rejectIfRedisNotReady: boolean = false - reject / invoke insuranceLimiter immediately when redis connection is not \"ready\"\n * }\n */\n constructor(opts) {\n super(opts);\n if (opts.redis) {\n this.client = opts.redis;\n } else {\n this.client = opts.storeClient;\n }\n\n this._rejectIfRedisNotReady = !!opts.rejectIfRedisNotReady;\n\n if (typeof this.client.defineCommand === 'function') {\n this.client.defineCommand(\"rlflxIncr\", {\n numberOfKeys: 1,\n lua: incrTtlLuaScript,\n });\n }\n }\n\n /**\n * Prevent actual redis call if redis connection is not ready\n * Because of different connection state checks for ioredis and node-redis, only this clients would be actually checked.\n * For any other clients all the requests would be passed directly to redis client\n * @return {boolean}\n * @private\n */\n _isRedisReady() {\n if (!this._rejectIfRedisNotReady) {\n return true;\n }\n // ioredis client\n if (this.client.status && this.client.status !== 'ready') {\n return false;\n }\n // node-redis client\n if (typeof this.client.isReady === 'function' && !this.client.isReady()) {\n return false;\n }\n return true;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n let [consumed, resTtlMs] = result;\n // Support ioredis results format\n if (Array.isArray(consumed)) {\n [, consumed] = consumed;\n [, resTtlMs] = resTtlMs;\n }\n\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(consumed);\n res.isFirstInDuration = res.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = resTtlMs;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n const secDuration = Math.floor(msDuration / 1000);\n const multi = this.client.multi();\n if (forceExpire) {\n if (secDuration > 0) {\n multi.set(rlKey, points, 'EX', secDuration);\n } else {\n multi.set(rlKey, points);\n }\n\n multi.pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n } else {\n if (secDuration > 0) {\n const incrCallback = function(err, result) {\n if (err) {\n return reject(err);\n }\n\n return resolve(result);\n };\n\n if (typeof this.client.rlflxIncr === 'function') {\n this.client.rlflxIncr(rlKey, points, secDuration, incrCallback);\n } else {\n this.client.eval(incrTtlLuaScript, 1, rlKey, points, secDuration, incrCallback);\n }\n } else {\n multi.incrby(rlKey, points)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n return reject(err);\n }\n\n return resolve(res);\n });\n }\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n if (!this._isRedisReady()) {\n return reject(new Error('Redis connection is not ready'));\n }\n\n this.client\n .multi()\n .get(rlKey)\n .pttl(rlKey)\n .exec((err, res) => {\n if (err) {\n reject(err);\n } else {\n const [points] = res;\n if (points === null) {\n return resolve(null)\n }\n\n resolve(res);\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res > 0);\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterRedis;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\n/**\n * Get MongoDB driver version as upsert options differ\n * @params {Object} Client instance\n * @returns {Object} Version Object containing major, feature & minor versions.\n */\nfunction getDriverVersion(client) {\n try {\n const _client = client.client ? client.client : client;\n\n const { version } = _client.topology.s.options.metadata.driver;\n const _v = version.split('.').map(v => parseInt(v));\n\n return {\n major: _v[0],\n feature: _v[1],\n patch: _v[2],\n };\n } catch (err) {\n return { major: 0, feature: 0, patch: 0 };\n }\n}\n\nclass RateLimiterMongo extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * indexKeyPrefix: {attr1: 1, attr2: 1}\n * ... see other in RateLimiterStoreAbstract\n *\n * mongo: MongoClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n this.indexKeyPrefix = opts.indexKeyPrefix;\n\n if (opts.mongo) {\n this.client = opts.mongo;\n } else {\n this.client = opts.storeClient;\n }\n if (typeof this.client.then === 'function') {\n // If Promise\n this.client\n .then((conn) => {\n this.client = conn;\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n });\n } else {\n this._initCollection();\n this._driverVersion = getDriverVersion(this.client);\n }\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? RateLimiterMongo.getDbName() : value;\n }\n\n static getDbName() {\n return 'node-rate-limiter-flexible';\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get client() {\n return this._client;\n }\n\n set client(value) {\n if (typeof value === 'undefined') {\n throw new Error('mongo is not set');\n }\n this._client = value;\n }\n\n get indexKeyPrefix() {\n return this._indexKeyPrefix;\n }\n\n set indexKeyPrefix(obj) {\n this._indexKeyPrefix = obj || {};\n }\n\n _initCollection() {\n const db = typeof this.client.db === 'function'\n ? this.client.db(this.dbName)\n : this.client;\n\n const collection = db.collection(this.tableName);\n collection.createIndex({ expire: -1 }, { expireAfterSeconds: 0 });\n collection.createIndex(Object.assign({}, this.indexKeyPrefix, { key: 1 }), { unique: true });\n\n this._collection = collection;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n\n let doc;\n if (typeof result.value === 'undefined') {\n doc = result;\n } else {\n doc = result.value;\n }\n\n res.isFirstInDuration = doc.points === changedPoints;\n res.consumedPoints = doc.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = doc.expire !== null\n ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsert(key, points, msDuration, forceExpire = false, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n let where;\n let upsertData;\n if (forceExpire) {\n where = { key };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $set: {\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n };\n upsertData.$set = Object.assign(upsertData.$set, docAttrs);\n } else {\n where = {\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n };\n where = Object.assign(where, docAttrs);\n upsertData = {\n $setOnInsert: {\n key,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n },\n $inc: { points },\n };\n upsertData.$setOnInsert = Object.assign(upsertData.$setOnInsert, docAttrs);\n }\n\n // Options for collection updates differ between driver versions\n const upsertOptions = {\n upsert: true,\n };\n if ((this._driverVersion.major >= 4) ||\n (this._driverVersion.major === 3 &&\n (this._driverVersion.feature >=7) || \n (this._driverVersion.feature >= 6 && \n this._driverVersion.patch >= 7 ))) \n {\n upsertOptions.returnDocument = 'after';\n } else {\n upsertOptions.returnOriginal = false;\n }\n\n /*\n * 1. Find actual limit and increment points\n * 2. If limit expired, but Mongo doesn't clean doc by TTL yet, try to replace limit doc completely\n * 3. If 2 or more Mongo threads try to insert the new limit doc, only the first succeed\n * 4. Try to upsert from step 1. Actual limit is created now, points are incremented without problems\n */\n return new Promise((resolve, reject) => {\n this._collection.findOneAndUpdate(\n where,\n upsertData,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errUpsert) => {\n if (errUpsert && errUpsert.code === 11000) { // E11000 duplicate key error collection\n const replaceWhere = Object.assign({ // try to replace OLD limit doc\n $or: [\n { expire: { $lte: new Date() } },\n { expire: { $eq: null } },\n ],\n key,\n }, docAttrs);\n\n const replaceTo = {\n $set: Object.assign({\n key,\n points,\n expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null,\n }, docAttrs)\n };\n\n this._collection.findOneAndUpdate(\n replaceWhere,\n replaceTo,\n upsertOptions\n ).then((res) => {\n resolve(res);\n }).catch((errReplace) => {\n if (errReplace && errReplace.code === 11000) { // E11000 duplicate key error collection\n this._upsert(key, points, msDuration, forceExpire)\n .then(res => resolve(res))\n .catch(err => reject(err));\n } else {\n reject(errReplace);\n }\n });\n } else {\n reject(errUpsert);\n }\n });\n });\n }\n\n _get(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n\n const where = Object.assign({\n key: rlKey,\n $or: [\n { expire: { $gt: new Date() } },\n { expire: { $eq: null } },\n ],\n }, docAttrs);\n\n return this._collection.findOne(where);\n }\n\n _delete(rlKey, options = {}) {\n if (!this._collection) {\n return Promise.reject(Error('Mongo connection is not established'));\n }\n\n const docAttrs = options.attrs || {};\n const where = Object.assign({ key: rlKey }, docAttrs);\n\n return this._collection.deleteOne(where)\n .then(res => res.deletedCount > 0);\n }\n}\n\nmodule.exports = RateLimiterMongo;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMySQL extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: anySqlClient,\n * storeType: 'knex', // required only for Knex instance\n * dbName: 'string',\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.dbName = opts.dbName;\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createDbAndTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`DELETE FROM ??.?? WHERE expire < ?`, [this.dbName, this.tableName, expire], () => {\n this._releaseConnection(conn);\n resolve();\n });\n })\n .catch(() => {\n resolve();\n });\n });\n }\n\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return new Promise((resolve, reject) => {\n this.client.getConnection((errConn, conn) => {\n if (errConn) {\n return reject(errConn);\n }\n\n resolve(conn);\n });\n });\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return conn.release();\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createDbAndTable() {\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(`CREATE DATABASE IF NOT EXISTS \\`${this.dbName}\\`;`, (errDb) => {\n if (errDb) {\n this._releaseConnection(conn);\n return reject(errDb);\n }\n conn.query(this._getCreateTableStmt(), (err) => {\n if (err) {\n this._releaseConnection(conn);\n return reject(err);\n }\n this._releaseConnection(conn);\n resolve();\n });\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS \\`${this.dbName}\\`.\\`${this.tableName}\\` (` +\n '`key` VARCHAR(255) CHARACTER SET utf8 NOT NULL,' +\n '`points` INT(9) NOT NULL default 0,' +\n '`expire` BIGINT UNSIGNED,' +\n 'PRIMARY KEY (`key`)' +\n ') ENGINE = INNODB;';\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n if (typeof value === 'undefined') {\n if (this.client.constructor.name === 'Connection') {\n value = 'connection';\n } else if (this.client.constructor.name === 'Pool') {\n value = 'pool';\n } else if (this.client.constructor.name === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n this._clientType = value.toLowerCase();\n }\n\n get dbName() {\n return this._dbName;\n }\n\n set dbName(value) {\n this._dbName = typeof value === 'undefined' ? 'rtlmtrflx' : value;\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const [row] = result;\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _upsertTransaction(conn, key, points, msDuration, forceExpire) {\n return new Promise((resolve, reject) => {\n conn.query('BEGIN', (errBegin) => {\n if (errBegin) {\n conn.rollback();\n\n return reject(errBegin);\n }\n\n const dateNow = Date.now();\n const newExpire = msDuration > 0 ? dateNow + msDuration : null;\n\n let q;\n let values;\n if (forceExpire) {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = ?, \n expire = ?;`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n points,\n newExpire,\n ];\n } else {\n q = `INSERT INTO ??.?? VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE \n points = IF(expire <= ?, ?, points + (?)), \n expire = IF(expire <= ?, ?, expire);`;\n values = [\n this.dbName, this.tableName, key, points, newExpire,\n dateNow, points, points,\n dateNow, newExpire,\n ];\n }\n\n conn.query(q, values, (errUpsert) => {\n if (errUpsert) {\n conn.rollback();\n\n return reject(errUpsert);\n }\n conn.query('SELECT points, expire FROM ??.?? WHERE `key` = ?;', [this.dbName, this.tableName, key], (errSelect, res) => {\n if (errSelect) {\n conn.rollback();\n\n return reject(errSelect);\n }\n\n conn.query('COMMIT', (err) => {\n if (err) {\n conn.rollback();\n\n return reject(err);\n }\n\n resolve(res);\n });\n });\n });\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n this._upsertTransaction(conn, key, points, msDuration, forceExpire)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)',\n [this.dbName, this.tableName, rlKey, Date.now()],\n (err, res) => {\n if (err) {\n reject(err);\n } else if (res.length === 0) {\n resolve(null);\n } else {\n resolve(res);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(\n 'DELETE FROM ??.?? WHERE `key` = ?',\n [this.dbName, this.tableName, rlKey],\n (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve(res.affectedRows > 0);\n }\n\n this._releaseConnection(conn);\n } // eslint-disable-line\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMySQL;\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterPostgres extends RateLimiterStoreAbstract {\n /**\n * @callback callback\n * @param {Object} err\n *\n * @param {Object} opts\n * @param {callback} cb\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: postgresClient,\n * storeType: 'knex', // required only for Knex instance\n * tableName: 'string',\n * }\n */\n constructor(opts, cb = null) {\n super(opts);\n\n this.client = opts.storeClient;\n this.clientType = opts.storeType;\n\n this.tableName = opts.tableName;\n\n this.clearExpiredByTimeout = opts.clearExpiredByTimeout;\n\n this.tableCreated = opts.tableCreated;\n if (!this.tableCreated) {\n this._createTable()\n .then(() => {\n this.tableCreated = true;\n if (this.clearExpiredByTimeout) {\n this._clearExpiredHourAgo();\n }\n if (typeof cb === 'function') {\n cb();\n }\n })\n .catch((err) => {\n if (typeof cb === 'function') {\n cb(err);\n } else {\n throw err;\n }\n });\n } else {\n if (typeof cb === 'function') {\n cb();\n }\n }\n }\n\n clearExpired(expire) {\n return new Promise((resolve) => {\n const q = {\n name: 'rlflx-clear-expired',\n text: `DELETE FROM ${this.tableName} WHERE expire < $1`,\n values: [expire],\n };\n this._query(q)\n .then(() => {\n resolve();\n })\n .catch(() => {\n // Deleting expired query is not critical\n resolve();\n });\n });\n }\n\n /**\n * Delete all rows expired 1 hour ago once per 5 minutes\n *\n * @private\n */\n _clearExpiredHourAgo() {\n if (this._clearExpiredTimeoutId) {\n clearTimeout(this._clearExpiredTimeoutId);\n }\n this._clearExpiredTimeoutId = setTimeout(() => {\n this.clearExpired(Date.now() - 3600000) // Never rejected\n .then(() => {\n this._clearExpiredHourAgo();\n });\n }, 300000);\n this._clearExpiredTimeoutId.unref();\n }\n\n /**\n *\n * @return Promise\n * @private\n */\n _getConnection() {\n switch (this.clientType) {\n case 'pool':\n return Promise.resolve(this.client);\n case 'sequelize':\n return this.client.connectionManager.getConnection();\n case 'knex':\n return this.client.client.acquireConnection();\n case 'typeorm':\n return Promise.resolve(this.client.driver.master);\n default:\n return Promise.resolve(this.client);\n }\n }\n\n _releaseConnection(conn) {\n switch (this.clientType) {\n case 'pool':\n return true;\n case 'sequelize':\n return this.client.connectionManager.releaseConnection(conn);\n case 'knex':\n return this.client.client.releaseConnection(conn);\n case 'typeorm':\n return true;\n default:\n return true;\n }\n }\n\n /**\n *\n * @returns {Promise}\n * @private\n */\n _createTable() {\n return new Promise((resolve, reject) => {\n this._query({\n text: this._getCreateTableStmt(),\n })\n .then(() => {\n resolve();\n })\n .catch((err) => {\n if (err.code === '23505') {\n // Error: duplicate key value violates unique constraint \"pg_type_typname_nsp_index\"\n // Postgres doesn't handle concurrent table creation\n // It is supposed, that table is created by another worker\n resolve();\n } else {\n reject(err);\n }\n });\n });\n }\n\n _getCreateTableStmt() {\n return `CREATE TABLE IF NOT EXISTS ${this.tableName} ( \n key varchar(255) PRIMARY KEY,\n points integer NOT NULL DEFAULT 0,\n expire bigint\n );`;\n }\n\n get clientType() {\n return this._clientType;\n }\n\n set clientType(value) {\n const constructorName = this.client.constructor.name;\n\n if (typeof value === 'undefined') {\n if (constructorName === 'Client') {\n value = 'client';\n } else if (\n constructorName === 'Pool' ||\n constructorName === 'BoundPool'\n ) {\n value = 'pool';\n } else if (constructorName === 'Sequelize') {\n value = 'sequelize';\n } else {\n throw new Error('storeType is not defined');\n }\n }\n\n this._clientType = value.toLowerCase();\n }\n\n get tableName() {\n return this._tableName;\n }\n\n set tableName(value) {\n this._tableName = typeof value === 'undefined' ? this.keyPrefix : value;\n }\n\n get tableCreated() {\n return this._tableCreated\n }\n\n set tableCreated(value) {\n this._tableCreated = typeof value === 'undefined' ? false : !!value;\n }\n\n get clearExpiredByTimeout() {\n return this._clearExpiredByTimeout;\n }\n\n set clearExpiredByTimeout(value) {\n this._clearExpiredByTimeout = typeof value === 'undefined' ? true : Boolean(value);\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n const row = result.rows[0];\n\n res.isFirstInDuration = changedPoints === row.points;\n res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;\n\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = row.expire\n ? Math.max(row.expire - Date.now(), 0)\n : -1;\n\n return res;\n }\n\n _query(q) {\n const prefix = this.tableName.toLowerCase();\n const queryObj = { name: `${prefix}:${q.name}`, text: q.text, values: q.values };\n return new Promise((resolve, reject) => {\n this._getConnection()\n .then((conn) => {\n conn.query(queryObj)\n .then((res) => {\n resolve(res);\n this._releaseConnection(conn);\n })\n .catch((err) => {\n reject(err);\n this._releaseConnection(conn);\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _upsert(key, points, msDuration, forceExpire = false) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n const newExpire = msDuration > 0 ? Date.now() + msDuration : null;\n const expireQ = forceExpire\n ? ' $3 '\n : ` CASE\n WHEN ${this.tableName}.expire <= $4 THEN $3\n ELSE ${this.tableName}.expire\n END `;\n\n return this._query({\n name: forceExpire ? 'rlflx-upsert-force' : 'rlflx-upsert',\n text: `\n INSERT INTO ${this.tableName} VALUES ($1, $2, $3)\n ON CONFLICT(key) DO UPDATE SET\n points = CASE\n WHEN (${this.tableName}.expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2\n ELSE ${this.tableName}.points + ($2)\n END,\n expire = ${expireQ}\n RETURNING points, expire;`,\n values: [key, points, newExpire, Date.now()],\n });\n }\n\n _get(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return new Promise((resolve, reject) => {\n this._query({\n name: 'rlflx-get',\n text: `\n SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,\n values: [rlKey, Date.now()],\n })\n .then((res) => {\n if (res.rowCount === 0) {\n res = null;\n }\n resolve(res);\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n _delete(rlKey) {\n if (!this.tableCreated) {\n return Promise.reject(Error('Table is not created yet'));\n }\n\n return this._query({\n name: 'rlflx-delete',\n text: `DELETE FROM ${this.tableName} WHERE key = $1`,\n values: [rlKey],\n })\n .then(res => res.rowCount > 0);\n }\n}\n\nmodule.exports = RateLimiterPostgres;\n", "module.exports = class Record {\n /**\n *\n * @param value int\n * @param expiresAt Date|int\n * @param timeoutId\n */\n constructor(value, expiresAt, timeoutId = null) {\n this.value = value;\n this.expiresAt = expiresAt;\n this.timeoutId = timeoutId;\n }\n\n get value() {\n return this._value;\n }\n\n set value(value) {\n this._value = parseInt(value);\n }\n\n get expiresAt() {\n return this._expiresAt;\n }\n\n set expiresAt(value) {\n if (!(value instanceof Date) && Number.isInteger(value)) {\n value = new Date(value);\n }\n this._expiresAt = value;\n }\n\n get timeoutId() {\n return this._timeoutId;\n }\n\n set timeoutId(value) {\n this._timeoutId = value;\n }\n};\n", "const Record = require('./Record');\nconst RateLimiterRes = require('../../RateLimiterRes');\n\nmodule.exports = class MemoryStorage {\n constructor() {\n /**\n * @type {Object.}\n * @private\n */\n this._storage = {};\n }\n\n incrby(key, value, durationSec) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n if (msBeforeExpires !== 0) {\n // Change value\n this._storage[key].value = this._storage[key].value + value;\n\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n\n if (this._storage[key] && this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n\n this._storage[key] = new Record(\n value,\n durationMs > 0 ? new Date(Date.now() + durationMs) : null\n );\n if (durationMs > 0) {\n this._storage[key].timeoutId = setTimeout(() => {\n delete this._storage[key];\n }, durationMs);\n if (this._storage[key].timeoutId.unref) {\n this._storage[key].timeoutId.unref();\n }\n }\n\n return new RateLimiterRes(0, durationMs === 0 ? -1 : durationMs, this._storage[key].value, true);\n }\n\n /**\n *\n * @param key\n * @returns {*}\n */\n get(key) {\n if (this._storage[key]) {\n const msBeforeExpires = this._storage[key].expiresAt\n ? this._storage[key].expiresAt.getTime() - new Date().getTime()\n : -1;\n return new RateLimiterRes(0, msBeforeExpires, this._storage[key].value, false);\n }\n return null;\n }\n\n /**\n *\n * @param key\n * @returns {boolean}\n */\n delete(key) {\n if (this._storage[key]) {\n if (this._storage[key].timeoutId) {\n clearTimeout(this._storage[key].timeoutId);\n }\n delete this._storage[key];\n return true;\n }\n return false;\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\nconst MemoryStorage = require('./component/MemoryStorage/MemoryStorage');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemory extends RateLimiterAbstract {\n constructor(opts = {}) {\n super(opts);\n\n this._memoryStorage = new MemoryStorage();\n }\n /**\n *\n * @param key\n * @param pointsToConsume\n * @param {Object} options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\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\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 reject(res);\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delay < this.execEvenlyMinDelayMs) {\n delay = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n\n setTimeout(resolve, delay, res);\n } else {\n resolve(res);\n }\n });\n }\n\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\n\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n return new Promise((resolve) => {\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 resolve(res);\n });\n }\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\n this._memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, initPoints)\n );\n }\n\n set(key, points, secDuration) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n\n this._memoryStorage.set(this.getKey(key), points, secDuration);\n return Promise.resolve(\n new RateLimiterRes(0, msDuration === 0 ? -1 : msDuration, points)\n );\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\n return Promise.resolve(res);\n }\n\n delete(key) {\n return Promise.resolve(this._memoryStorage.delete(this.getKey(key)));\n }\n}\n\nmodule.exports = RateLimiterMemory;\n\n", "/**\n * Implements rate limiting in cluster using built-in IPC\n *\n * Two classes are described here: master and worker\n * Master have to be create in the master process without any options.\n * Any number of rate limiters can be created in workers, but each rate limiter must be with unique keyPrefix\n *\n * Workflow:\n * 1. master rate limiter created in master process\n * 2. worker rate limiter sends 'init' message with necessary options during creating\n * 3. master receives options and adds new rate limiter by keyPrefix if it isn't created yet\n * 4. master sends 'init' back to worker's rate limiter\n * 5. worker can process requests immediately,\n * but they will be postponed by 'workerWaitInit' until master sends 'init' to worker\n * 6. every request to worker rate limiter creates a promise\n * 7. if master doesn't response for 'timeout', promise is rejected\n * 8. master sends 'resolve' or 'reject' command to worker\n * 9. worker resolves or rejects promise depending on message from master\n *\n */\n\nconst cluster = require('cluster');\nconst crypto = require('crypto');\nconst RateLimiterAbstract = require('./RateLimiterAbstract');\nconst RateLimiterMemory = require('./RateLimiterMemory');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nconst channel = 'rate_limiter_flexible';\nlet masterInstance = null;\n\nconst masterSendToWorker = function (worker, msg, type, res) {\n let data;\n if (res === null || res === true || res === false) {\n data = res;\n } else {\n data = {\n remainingPoints: res.remainingPoints,\n msBeforeNext: res.msBeforeNext,\n consumedPoints: res.consumedPoints,\n isFirstInDuration: res.isFirstInDuration,\n };\n }\n worker.send({\n channel,\n keyPrefix: msg.keyPrefix, // which rate limiter exactly\n promiseId: msg.promiseId,\n type,\n data,\n });\n};\n\nconst workerWaitInit = function (payload) {\n setTimeout(() => {\n if (this._initiated) {\n process.send(payload);\n // Promise will be removed by timeout if too long\n } else if (typeof this._promises[payload.promiseId] !== 'undefined') {\n workerWaitInit.call(this, payload);\n }\n }, 30);\n};\n\nconst workerSendToMaster = function (func, promiseId, key, arg, opts) {\n const payload = {\n channel,\n keyPrefix: this.keyPrefix,\n func,\n promiseId,\n data: {\n key,\n arg,\n opts,\n },\n };\n\n if (!this._initiated) {\n // Wait init before sending messages to master\n workerWaitInit.call(this, payload);\n } else {\n process.send(payload);\n }\n};\n\nconst masterProcessMsg = function (worker, msg) {\n if (!msg || msg.channel !== channel || typeof this._rateLimiters[msg.keyPrefix] === 'undefined') {\n return false;\n }\n\n let promise;\n\n switch (msg.func) {\n case 'consume':\n promise = this._rateLimiters[msg.keyPrefix].consume(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'penalty':\n promise = this._rateLimiters[msg.keyPrefix].penalty(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'reward':\n promise = this._rateLimiters[msg.keyPrefix].reward(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'block':\n promise = this._rateLimiters[msg.keyPrefix].block(msg.data.key, msg.data.arg, msg.data.opts);\n break;\n case 'get':\n promise = this._rateLimiters[msg.keyPrefix].get(msg.data.key, msg.data.opts);\n break;\n case 'delete':\n promise = this._rateLimiters[msg.keyPrefix].delete(msg.data.key, msg.data.opts);\n break;\n default:\n return false;\n }\n\n if (promise) {\n promise\n .then((res) => {\n masterSendToWorker(worker, msg, 'resolve', res);\n })\n .catch((rejRes) => {\n masterSendToWorker(worker, msg, 'reject', rejRes);\n });\n }\n};\n\nconst workerProcessMsg = function (msg) {\n if (!msg || msg.channel !== channel || msg.keyPrefix !== this.keyPrefix) {\n return false;\n }\n\n if (this._promises[msg.promiseId]) {\n clearTimeout(this._promises[msg.promiseId].timeoutId);\n let res;\n if (msg.data === null || msg.data === true || msg.data === false) {\n res = msg.data;\n } else {\n res = new RateLimiterRes(\n msg.data.remainingPoints,\n msg.data.msBeforeNext,\n msg.data.consumedPoints,\n msg.data.isFirstInDuration // eslint-disable-line comma-dangle\n );\n }\n\n switch (msg.type) {\n case 'resolve':\n this._promises[msg.promiseId].resolve(res);\n break;\n case 'reject':\n this._promises[msg.promiseId].reject(res);\n break;\n default:\n throw new Error(`RateLimiterCluster: no such message type '${msg.type}'`);\n }\n\n delete this._promises[msg.promiseId];\n }\n};\n/**\n * Prepare options to send to master\n * Master will create rate limiter depending on options\n *\n * @returns {{points: *, duration: *, blockDuration: *, execEvenly: *, execEvenlyMinDelayMs: *, keyPrefix: *}}\n */\nconst getOpts = function () {\n return {\n points: this.points,\n duration: this.duration,\n blockDuration: this.blockDuration,\n execEvenly: this.execEvenly,\n execEvenlyMinDelayMs: this.execEvenlyMinDelayMs,\n keyPrefix: this.keyPrefix,\n };\n};\n\nconst savePromise = function (resolve, reject) {\n const hrtime = process.hrtime();\n let promiseId = hrtime[0].toString() + hrtime[1].toString();\n\n if (typeof this._promises[promiseId] !== 'undefined') {\n promiseId += crypto.randomBytes(12).toString('base64');\n }\n\n this._promises[promiseId] = {\n resolve,\n reject,\n timeoutId: setTimeout(() => {\n delete this._promises[promiseId];\n reject(new Error('RateLimiterCluster timeout: no answer from master in time'));\n }, this.timeoutMs),\n };\n\n return promiseId;\n};\n\nclass RateLimiterClusterMaster {\n constructor() {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n cluster.setMaxListeners(0);\n\n cluster.on('message', (worker, msg) => {\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n worker.send({\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n });\n } else {\n masterProcessMsg.call(this, worker, msg);\n }\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterMasterPM2 {\n constructor(pm2) {\n if (masterInstance) {\n return masterInstance;\n }\n\n this._rateLimiters = {};\n\n pm2.launchBus((err, pm2Bus) => {\n pm2Bus.on('process:msg', (packet) => {\n const msg = packet.raw;\n if (msg && msg.channel === channel && msg.type === 'init') {\n // If init request, check or create rate limiter by key prefix and send 'init' back to worker\n if (typeof this._rateLimiters[msg.opts.keyPrefix] === 'undefined') {\n this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory(msg.opts);\n }\n\n pm2.sendDataToProcessId(packet.process.pm_id, {\n data: {},\n topic: channel,\n channel,\n type: 'init',\n keyPrefix: msg.opts.keyPrefix,\n }, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n } else {\n const worker = {\n send: (msgData) => {\n const pm2Message = msgData;\n pm2Message.topic = channel;\n if (typeof pm2Message.data === 'undefined') {\n pm2Message.data = {};\n }\n pm2.sendDataToProcessId(packet.process.pm_id, pm2Message, (sendErr, res) => {\n if (sendErr) {\n console.log(sendErr, res);\n }\n });\n },\n };\n masterProcessMsg.call(this, worker, msg);\n }\n });\n });\n\n masterInstance = this;\n }\n}\n\nclass RateLimiterClusterWorker extends RateLimiterAbstract {\n get timeoutMs() {\n return this._timeoutMs;\n }\n\n set timeoutMs(value) {\n this._timeoutMs = typeof value === 'undefined' ? 5000 : Math.abs(parseInt(value));\n }\n\n constructor(opts = {}) {\n super(opts);\n\n process.setMaxListeners(0);\n\n this.timeoutMs = opts.timeoutMs;\n\n this._initiated = false;\n\n process.on('message', (msg) => {\n if (msg && msg.channel === channel && msg.type === 'init' && msg.keyPrefix === this.keyPrefix) {\n this._initiated = true;\n } else {\n workerProcessMsg.call(this, msg);\n }\n });\n\n // Create limiter on master with specific options\n process.send({\n channel,\n type: 'init',\n opts: getOpts.call(this),\n });\n\n this._promises = {};\n }\n\n consume(key, pointsToConsume = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'consume', promiseId, key, pointsToConsume, options);\n });\n }\n\n penalty(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'penalty', promiseId, key, points, options);\n });\n }\n\n reward(key, points = 1, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'reward', promiseId, key, points, options);\n });\n }\n\n block(key, secDuration, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'block', promiseId, key, secDuration, options);\n });\n }\n\n get(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'get', promiseId, key, options);\n });\n }\n\n delete(key, options = {}) {\n return new Promise((resolve, reject) => {\n const promiseId = savePromise.call(this, resolve, reject);\n\n workerSendToMaster.call(this, 'delete', promiseId, key, options);\n });\n }\n}\n\nmodule.exports = {\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster: RateLimiterClusterWorker,\n};\n", "const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract');\nconst RateLimiterRes = require('./RateLimiterRes');\n\nclass RateLimiterMemcache extends RateLimiterStoreAbstract {\n /**\n *\n * @param {Object} opts\n * Defaults {\n * ... see other in RateLimiterStoreAbstract\n *\n * storeClient: memcacheClient\n * }\n */\n constructor(opts) {\n super(opts);\n\n this.client = opts.storeClient;\n }\n\n _getRateLimiterRes(rlKey, changedPoints, result) {\n const res = new RateLimiterRes();\n res.consumedPoints = parseInt(result.consumedPoints);\n res.isFirstInDuration = result.consumedPoints === changedPoints;\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n res.msBeforeNext = result.msBeforeNext;\n\n return res;\n }\n\n _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n const secDuration = Math.floor(msDuration / 1000);\n\n if (forceExpire) {\n this.client.set(rlKey, points, secDuration, (err) => {\n if (!err) {\n this.client.set(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n } else {\n reject(err);\n }\n });\n } else {\n this.client.incr(rlKey, points, (err, consumedPoints) => {\n if (err || consumedPoints === false) {\n this.client.add(rlKey, points, secDuration, (errAddKey, createdNew) => {\n if (errAddKey || !createdNew) {\n // Try to upsert again in case of race condition\n if (typeof options.attemptNumber === 'undefined' || options.attemptNumber < 3) {\n const nextOptions = Object.assign({}, options);\n nextOptions.attemptNumber = nextOptions.attemptNumber ? (nextOptions.attemptNumber + 1) : 1;\n\n this._upsert(rlKey, points, msDuration, forceExpire, nextOptions)\n .then(resUpsert => resolve(resUpsert))\n .catch(errUpsert => reject(errUpsert));\n } else {\n reject(new Error('Can not add key'));\n }\n } else {\n this.client.add(\n `${rlKey}_expire`,\n secDuration > 0 ? nowMs + (secDuration * 1000) : -1,\n secDuration,\n () => {\n const res = {\n consumedPoints: points,\n msBeforeNext: secDuration > 0 ? secDuration * 1000 : -1,\n };\n resolve(res);\n }\n );\n }\n });\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n }\n });\n }\n\n _get(rlKey) {\n return new Promise((resolve, reject) => {\n const nowMs = Date.now();\n\n this.client.get(rlKey, (err, consumedPoints) => {\n if (!consumedPoints) {\n resolve(null);\n } else {\n this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {\n if (errGetExpire) {\n reject(errGetExpire);\n } else {\n const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;\n const res = {\n consumedPoints,\n msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1,\n };\n resolve(res);\n }\n });\n }\n });\n });\n }\n\n _delete(rlKey) {\n return new Promise((resolve, reject) => {\n this.client.del(rlKey, (err, res) => {\n if (err) {\n reject(err);\n } else if (res === false) {\n resolve(res);\n } else {\n this.client.del(`${rlKey}_expire`, (errDelExpire) => {\n if (errDelExpire) {\n reject(errDelExpire);\n } else {\n resolve(res);\n }\n });\n }\n });\n });\n }\n}\n\nmodule.exports = RateLimiterMemcache;\n", "const RateLimiterRes = require('./RateLimiterRes');\n\nmodule.exports = class RLWrapperBlackAndWhite {\n constructor(opts = {}) {\n this.limiter = opts.limiter;\n this.blackList = opts.blackList;\n this.whiteList = opts.whiteList;\n this.isBlackListed = opts.isBlackListed;\n this.isWhiteListed = opts.isWhiteListed;\n this.runActionAnyway = opts.runActionAnyway;\n }\n\n get limiter() {\n return this._limiter;\n }\n\n set limiter(value) {\n if (typeof value === 'undefined') {\n throw new Error('limiter is not set');\n }\n\n this._limiter = value;\n }\n\n get runActionAnyway() {\n return this._runActionAnyway;\n }\n\n set runActionAnyway(value) {\n this._runActionAnyway = typeof value === 'undefined' ? false : value;\n }\n\n get blackList() {\n return this._blackList;\n }\n\n set blackList(value) {\n this._blackList = Array.isArray(value) ? value : [];\n }\n\n get isBlackListed() {\n return this._isBlackListed;\n }\n\n set isBlackListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isBlackListed must be function');\n }\n this._isBlackListed = func;\n }\n\n get whiteList() {\n return this._whiteList;\n }\n\n set whiteList(value) {\n this._whiteList = Array.isArray(value) ? value : [];\n }\n\n get isWhiteListed() {\n return this._isWhiteListed;\n }\n\n set isWhiteListed(func) {\n if (typeof func === 'undefined') {\n func = () => false;\n }\n if (typeof func !== 'function') {\n throw new Error('isWhiteListed must be function');\n }\n this._isWhiteListed = func;\n }\n\n isBlackListedSomewhere(key) {\n return this.blackList.indexOf(key) >= 0 || this.isBlackListed(key);\n }\n\n isWhiteListedSomewhere(key) {\n return this.whiteList.indexOf(key) >= 0 || this.isWhiteListed(key);\n }\n\n getBlackRes() {\n return new RateLimiterRes(0, Number.MAX_SAFE_INTEGER, 0, false);\n }\n\n getWhiteRes() {\n return new RateLimiterRes(Number.MAX_SAFE_INTEGER, 0, 0, false);\n }\n\n rejectBlack() {\n return Promise.reject(this.getBlackRes());\n }\n\n resolveBlack() {\n return Promise.resolve(this.getBlackRes());\n }\n\n resolveWhite() {\n return Promise.resolve(this.getWhiteRes());\n }\n\n consume(key, pointsToConsume = 1) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.rejectBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.consume(key, pointsToConsume);\n }\n\n if (this.runActionAnyway) {\n this.limiter.consume(key, pointsToConsume).catch(() => {});\n }\n return res;\n }\n\n block(key, secDuration) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.block(key, secDuration);\n }\n\n if (this.runActionAnyway) {\n this.limiter.block(key, secDuration).catch(() => {});\n }\n return res;\n }\n\n penalty(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.penalty(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.penalty(key, points).catch(() => {});\n }\n return res;\n }\n\n reward(key, points) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined') {\n return this.limiter.reward(key, points);\n }\n\n if (this.runActionAnyway) {\n this.limiter.reward(key, points).catch(() => {});\n }\n return res;\n }\n\n get(key) {\n let res;\n if (this.isWhiteListedSomewhere(key)) {\n res = this.resolveWhite();\n } else if (this.isBlackListedSomewhere(key)) {\n res = this.resolveBlack();\n }\n\n if (typeof res === 'undefined' || this.runActionAnyway) {\n return this.limiter.get(key);\n }\n\n return res;\n }\n\n delete(key) {\n return this.limiter.delete(key);\n }\n};\n", "const RateLimiterAbstract = require('./RateLimiterAbstract');\n\nmodule.exports = class RateLimiterUnion {\n constructor(...limiters) {\n if (limiters.length < 1) {\n throw new Error('RateLimiterUnion: at least one limiter have to be passed');\n }\n limiters.forEach((limiter) => {\n if (!(limiter instanceof RateLimiterAbstract)) {\n throw new Error('RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract');\n }\n });\n\n this._limiters = limiters;\n }\n\n consume(key, points = 1) {\n return new Promise((resolve, reject) => {\n const promises = [];\n this._limiters.forEach((limiter) => {\n promises.push(limiter.consume(key, points).catch(rej => ({ rejected: true, rej })));\n });\n\n Promise.all(promises)\n .then((res) => {\n const resObj = {};\n let rejected = false;\n\n res.forEach((item) => {\n if (item.rejected === true) {\n rejected = true;\n }\n });\n\n for (let i = 0; i < res.length; i++) {\n if (rejected && res[i].rejected === true) {\n resObj[this._limiters[i].keyPrefix] = res[i].rej;\n } else if (!rejected) {\n resObj[this._limiters[i].keyPrefix] = res[i];\n }\n }\n\n if (rejected) {\n reject(resObj);\n } else {\n resolve(resObj);\n }\n });\n });\n }\n};\n", "module.exports = class RateLimiterQueueError extends Error {\n constructor(message, extra) {\n super();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = 'CustomError';\n this.message = message;\n if (extra) {\n this.extra = extra;\n }\n }\n};\n", "const RateLimiterQueueError = require('./component/RateLimiterQueueError')\nconst MAX_QUEUE_SIZE = 4294967295;\nconst KEY_DEFAULT = 'limiter';\n\nmodule.exports = class RateLimiterQueue {\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n }) {\n this._queueLimiters = {\n KEY_DEFAULT: new RateLimiterQueueInternal(limiterFlexible, opts)\n };\n this._limiterFlexible = limiterFlexible;\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining(key = KEY_DEFAULT) {\n if (this._queueLimiters[key]) {\n return this._queueLimiters[key].getTokensRemaining()\n } else {\n return Promise.resolve(this._limiterFlexible.points)\n }\n }\n\n removeTokens(tokens, key = KEY_DEFAULT) {\n if (!this._queueLimiters[key]) {\n this._queueLimiters[key] = new RateLimiterQueueInternal(\n this._limiterFlexible, {\n key,\n maxQueueSize: this._maxQueueSize,\n })\n }\n\n return this._queueLimiters[key].removeTokens(tokens)\n }\n};\n\nclass RateLimiterQueueInternal {\n\n constructor(limiterFlexible, opts = {\n maxQueueSize: MAX_QUEUE_SIZE,\n key: KEY_DEFAULT,\n }) {\n this._key = opts.key;\n this._waitTimeout = null;\n this._queue = [];\n this._limiterFlexible = limiterFlexible;\n\n this._maxQueueSize = opts.maxQueueSize\n }\n\n getTokensRemaining() {\n return this._limiterFlexible.get(this._key)\n .then((rlRes) => {\n return rlRes !== null ? rlRes.remainingPoints : this._limiterFlexible.points;\n })\n }\n\n removeTokens(tokens) {\n const _this = this;\n\n return new Promise((resolve, reject) => {\n if (tokens > _this._limiterFlexible.points) {\n reject(new RateLimiterQueueError(`Requested tokens ${tokens} exceeds maximum ${_this._limiterFlexible.points} tokens per interval`));\n return\n }\n\n if (_this._queue.length > 0) {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n } else {\n _this._limiterFlexible.consume(_this._key, tokens)\n .then((res) => {\n resolve(res.remainingPoints);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n reject(rej);\n } else {\n _this._queueRequest.call(_this, resolve, reject, tokens);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n })\n }\n\n _queueRequest(resolve, reject, tokens) {\n const _this = this;\n if (_this._queue.length < _this._maxQueueSize) {\n _this._queue.push({resolve, reject, tokens});\n } else {\n reject(new RateLimiterQueueError(`Number of requests reached it's maximum ${_this._maxQueueSize}`))\n }\n }\n\n _processFIFO() {\n const _this = this;\n\n if (_this._waitTimeout !== null) {\n clearTimeout(_this._waitTimeout);\n _this._waitTimeout = null;\n }\n\n if (_this._queue.length === 0) {\n return;\n }\n\n const item = _this._queue.shift();\n _this._limiterFlexible.consume(_this._key, item.tokens)\n .then((res) => {\n item.resolve(res.remainingPoints);\n _this._processFIFO.call(_this);\n })\n .catch((rej) => {\n if (rej instanceof Error) {\n item.reject(rej);\n _this._processFIFO.call(_this);\n } else {\n _this._queue.unshift(item);\n if (_this._waitTimeout === null) {\n _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);\n }\n }\n });\n }\n}\n", "const RateLimiterRes = require(\"./RateLimiterRes\");\n\n/**\n * Bursty rate limiter exposes only msBeforeNext time and doesn't expose points from bursty limiter by default\n * @type {BurstyRateLimiter}\n */\nmodule.exports = class BurstyRateLimiter {\n constructor(rateLimiter, burstLimiter) {\n this._rateLimiter = rateLimiter;\n this._burstLimiter = burstLimiter\n }\n\n /**\n * Merge rate limiter response objects. Responses can be null\n *\n * @param {RateLimiterRes} [rlRes] Rate limiter response\n * @param {RateLimiterRes} [blRes] Bursty limiter response\n */\n _combineRes(rlRes, blRes) {\n if (!rlRes) {\n return null\n }\n\n return new RateLimiterRes(\n rlRes.remainingPoints,\n Math.min(rlRes.msBeforeNext, blRes ? blRes.msBeforeNext : 0),\n rlRes.consumedPoints,\n rlRes.isFirstInDuration\n )\n }\n\n /**\n * @param key\n * @param pointsToConsume\n * @param options\n * @returns {Promise}\n */\n consume(key, pointsToConsume = 1, options = {}) {\n return this._rateLimiter.consume(key, pointsToConsume, options)\n .catch((rlRej) => {\n if (rlRej instanceof RateLimiterRes) {\n return this._burstLimiter.consume(key, pointsToConsume, options)\n .then((blRes) => {\n return Promise.resolve(this._combineRes(rlRej, blRes))\n })\n .catch((blRej) => {\n if (blRej instanceof RateLimiterRes) {\n return Promise.reject(this._combineRes(rlRej, blRej))\n } else {\n return Promise.reject(blRej)\n }\n }\n )\n } else {\n return Promise.reject(rlRej)\n }\n })\n }\n\n /**\n * It doesn't expose available points from burstLimiter\n *\n * @param key\n * @returns {Promise}\n */\n get(key) {\n return Promise.all([\n this._rateLimiter.get(key),\n this._burstLimiter.get(key),\n ]).then(([rlRes, blRes]) => {\n return this._combineRes(rlRes, blRes);\n });\n }\n\n get points() {\n return this._rateLimiter.points;\n }\n};\n", "const RateLimiterRedis = require('./lib/RateLimiterRedis');\nconst RateLimiterMongo = require('./lib/RateLimiterMongo');\nconst RateLimiterMySQL = require('./lib/RateLimiterMySQL');\nconst RateLimiterPostgres = require('./lib/RateLimiterPostgres');\nconst {RateLimiterClusterMaster, RateLimiterClusterMasterPM2, RateLimiterCluster} = require('./lib/RateLimiterCluster');\nconst RateLimiterMemory = require('./lib/RateLimiterMemory');\nconst RateLimiterMemcache = require('./lib/RateLimiterMemcache');\nconst RLWrapperBlackAndWhite = require('./lib/RLWrapperBlackAndWhite');\nconst RateLimiterUnion = require('./lib/RateLimiterUnion');\nconst RateLimiterQueue = require('./lib/RateLimiterQueue');\nconst BurstyRateLimiter = require('./lib/BurstyRateLimiter');\nconst RateLimiterRes = require('./lib/RateLimiterRes');\n\nmodule.exports = {\n RateLimiterRedis,\n RateLimiterMongo,\n RateLimiterMySQL,\n RateLimiterPostgres,\n RateLimiterMemory,\n RateLimiterMemcache,\n RateLimiterClusterMaster,\n RateLimiterClusterMasterPM2,\n RateLimiterCluster,\n RLWrapperBlackAndWhite,\n RateLimiterUnion,\n RateLimiterQueue,\n BurstyRateLimiter,\n RateLimiterRes,\n};\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hash provides interface for hash functions.\n */\n\n/**\n * Hash interface describes properties of\n * cryptographic hash functions.\n */\nexport interface Hash {\n readonly digestLength: number;\n readonly blockSize: number;\n update(data: Uint8Array): this;\n reset(): this;\n finish(out: Uint8Array): this;\n digest(): Uint8Array;\n clean(): void;\n}\n\nexport interface SerializableHash extends Hash {\n saveState(): any;\n restoreState(savedState: any): this;\n cleanSavedState(savedState: any): void;\n}\n\nexport function isSerializableHash(h: Hash): h is SerializableHash {\n return (\n typeof (h as SerializableHash).saveState !== \"undefined\" &&\n typeof (h as SerializableHash).restoreState !== \"undefined\" &&\n typeof (h as SerializableHash).cleanSavedState !== \"undefined\"\n );\n}\n\n// TODO(dchest): figure out the standardized interface for XOF such as\n// SHAKE and BLAKE2X.\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nexport function select(subject: number, resultIfOne: number, resultIfZero: number): number {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\n\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nexport function lessOrEqual(a: number, b: number): number {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\n\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nexport function compare(a: Uint8Array, b: Uint8Array): number {\n if (a.length !== b.length) {\n return 0;\n }\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\n\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package wipe implements functions for zeroing arrays.\n */\n\nexport type NumericArray = number[] | Uint8Array | Int8Array | Uint16Array\n | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;\n\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nexport function wipe(array: NumericArray): NumericArray {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (let i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hmac implements HMAC algorithm.\n */\n\nimport { Hash, SerializableHash, isSerializableHash } from \"@stablelib/hash\";\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC implements hash-based message authentication algorithm.\n */\nexport class HMAC implements SerializableHash {\n readonly blockSize: number;\n readonly digestLength: number;\n\n private _inner: Hash; // inner hash\n private _outer: Hash; // outer hash\n\n private _finished = false; // true if HMAC was finalized\n\n // Copies of hash states after keying.\n // Need for quick reset without hashing the key again.\n private _innerKeyedState: any | undefined;\n private _outerKeyedState: any | undefined;\n\n /**\n * Constructs a new HMAC with the given Hash and secret key.\n */\n constructor(hash: new () => Hash | SerializableHash, key: Uint8Array) {\n // Initialize inner and outer hashes.\n this._inner = new hash();\n this._outer = new hash();\n\n // Set block and digest sizes for this HMAC\n // instance to values from the hash.\n this.blockSize = this._outer.blockSize;\n this.digestLength = this._outer.digestLength;\n\n // Pad temporary stores a key (or its hash) padded with zeroes.\n const pad = new Uint8Array(this.blockSize);\n\n if (key.length > this.blockSize) {\n // If key is bigger than hash block size, it must be\n // hashed and this hash is used as a key instead.\n this._inner.update(key).finish(pad).clean();\n } else {\n // Otherwise, copy the key into pad.\n pad.set(key);\n }\n\n // Now two different keys are derived from padded key\n // by xoring a different byte value to each.\n\n // To make inner hash key, xor byte 0x36 into pad.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n // Update inner hash with the result.\n this._inner.update(pad);\n\n // To make outer hash key, xor byte 0x5c into pad.\n // But since we already xored 0x36 there, we must\n // first undo this by xoring it again.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n // Update outer hash with the result.\n this._outer.update(pad);\n\n // Save states of both hashes, so that we can quickly restore\n // them later in reset() without the need to remember the actual\n // key and perform this initialization again.\n if (isSerializableHash(this._inner) && isSerializableHash(this._outer)) {\n this._innerKeyedState = this._inner.saveState();\n this._outerKeyedState = this._outer.saveState();\n }\n\n // Clean pad.\n wipe(pad);\n }\n\n /**\n * Returns HMAC state to the state initialized with key\n * to make it possible to run HMAC over the other data with the same\n * key without creating a new instance.\n */\n reset(): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't reset() because hash doesn't implement restoreState()\");\n }\n // Restore keyed states of inner and outer hashes.\n this._inner.restoreState(this._innerKeyedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans HMAC state.\n */\n clean() {\n if (isSerializableHash(this._inner)) {\n this._inner.cleanSavedState(this._innerKeyedState);\n }\n if (isSerializableHash(this._outer)) {\n this._outer.cleanSavedState(this._outerKeyedState);\n }\n this._inner.clean();\n this._outer.clean();\n }\n\n /**\n * Updates state with provided data.\n */\n update(data: Uint8Array): this {\n this._inner.update(data);\n return this;\n }\n\n /**\n * Finalizes HMAC and puts the result in out.\n */\n finish(out: Uint8Array): this {\n if (this._finished) {\n // If HMAC was finalized, outer hash is also finalized,\n // so it produces the same digest it produced when it\n // was finalized.\n this._outer.finish(out);\n return this;\n }\n\n // Finalize inner hash and store the result temporarily.\n this._inner.finish(out);\n\n // Update outer hash with digest of inner hash and and finalize it.\n this._outer.update(out.subarray(0, this.digestLength)).finish(out);\n this._finished = true;\n\n return this;\n }\n\n /**\n * Returns the computed message authentication code.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Saves HMAC state.\n * This function is needed for PBKDF2 optimization.\n */\n saveState(): any {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't saveState() because hash doesn't implement it\");\n }\n return this._inner.saveState();\n }\n\n restoreState(savedState: any): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't restoreState() because hash doesn't implement it\");\n }\n this._inner.restoreState(savedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n cleanSavedState(savedState: any) {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't cleanSavedState() because hash doesn't implement it\");\n }\n this._inner.cleanSavedState(savedState);\n }\n}\n\n/**\n * Returns HMAC using the given hash constructor for the key over data.\n */\nexport function hmac(hash: new () => Hash, key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new HMAC(hash, key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two HMAC digests are equal.\n * Uses constant-time comparison to avoid leaking timing information.\n *\n * Example:\n *\n * const receivedDigest = ...\n * const realDigest = hmac(SHA256, key, data);\n * if (!equal(receivedDigest, realDigest)) {\n * throw new Error(\"Authentication error\");\n * }\n */\nexport const equal = constantTimeEqual;\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hkdf implements HKDF key derivation function.\n */\n\nimport { Hash } from \"@stablelib/hash\";\nimport { HMAC, hmac } from \"@stablelib/hmac\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC-based Extract-and-Expand Key Derivation Function.\n *\n * Implements HKDF from RFC5869.\n *\n * Expands the given master key with salt and info into\n * a limited stream of key material.\n */\nexport class HKDF {\n private _hmac: HMAC;\n private _buffer: Uint8Array;\n private _bufpos: number;\n private _counter = new Uint8Array(1); // starts with zero\n private _hash: new () => Hash;\n private _info?: Uint8Array;\n\n /**\n * Create a new HKDF instance for the given hash function\n * with the master key, optional salt, and info.\n *\n * - Master key is a high-entropy secret key (not a password).\n * - Salt is a non-secret random value.\n * - Info is application- and/or context-specific information.\n */\n constructor(hash: new () => Hash,\n key: Uint8Array,\n salt = new Uint8Array(0),\n info?: Uint8Array) {\n\n this._hash = hash;\n this._info = info;\n\n // HKDF-Extract uses salt as HMAC key, and key as data.\n const okm = hmac(this._hash, salt, key);\n\n // Initialize HMAC for expanding with extracted key.\n this._hmac = new HMAC(hash, okm);\n\n // Allocate buffer.\n this._buffer = new Uint8Array(this._hmac.digestLength);\n this._bufpos = this._buffer.length;\n }\n\n // Fill buffer with new block of HKDF-Extract output.\n private _fillBuffer(): void {\n // Increment counter.\n this._counter[0]++;\n\n const ctr = this._counter[0];\n\n // Check if counter overflowed.\n if (ctr === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n\n // Prepare HMAC instance for new data with old key.\n this._hmac.reset();\n\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (ctr > 1) {\n this._hmac.update(this._buffer);\n }\n\n // Hash in info if it exists.\n if (this._info) {\n this._hmac.update(this._info);\n }\n\n // Hash in the counter.\n this._hmac.update(this._counter);\n\n // Output result to buffer and clean HMAC instance.\n this._hmac.finish(this._buffer);\n\n // Reset buffer position.\n this._bufpos = 0;\n }\n\n /**\n * Expand returns next key material of the given length.\n *\n * It throws if expansion limit is reached (which is\n * 254 digests of the underlying HMAC function).\n */\n expand(length: number): Uint8Array {\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i++) {\n if (this._bufpos === this._buffer.length) {\n this._fillBuffer();\n }\n out[i] = this._buffer[this._bufpos++];\n }\n return out;\n }\n\n clean(): void {\n this._hmac.clean();\n wipe(this._buffer);\n wipe(this._counter);\n this._bufpos = 0;\n }\n}\n\n// TODO(dchest): maybe implement deriveKey?\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\n\nconst QUOTA = 65536;\n\nexport class BrowserRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto?: { getRandomValues: typeof window.crypto.getRandomValues };\n\n constructor() {\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || (self as { msCrypto?: any }).msCrypto) // IE11 has msCrypto\n : null;\n\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { wipe } from \"@stablelib/wipe\";\n\ndeclare function require(name: string): any;\n\nexport class NodeRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto: { randomBytes(n: number): Uint8Array } | undefined;\n\n constructor() {\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n\n // Allocate output array.\n const out = new Uint8Array(length);\n\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n\n // Cleanup.\n wipe(buffer);\n\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { BrowserRandomSource } from \"./browser\";\nimport { NodeRandomSource } from \"./node\";\n\nexport class SystemRandomSource implements RandomSource {\n isAvailable = false;\n name = \"\";\n private _source: RandomSource;\n\n constructor() {\n // Try browser.\n this._source = new BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n\n // If no browser source, try Node.\n this._source = new NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n\n // No sources, we're out of options.\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package int provides helper functions for integerss.\n */\n\n// Shim using 16-bit pieces.\nfunction imulShim(a: number, b: number): number {\n const ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n const bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexport const mul = (Math as { imul?(a: number, b: number): number }).imul || imulShim;\n\n/** 32-bit integer addition. */\nexport function add(a: number, b: number): number {\n return (a + b) | 0;\n}\n\n/** 32-bit integer subtraction. */\nexport function sub(a: number, b: number): number {\n return (a - b) | 0;\n}\n\n/** 32-bit integer left rotation */\nexport function rotl(x: number, n: number): number {\n return x << n | x >>> (32 - n);\n}\n\n/** 32-bit integer left rotation */\nexport function rotr(x: number, n: number): number {\n return x << (32 - n) | x >>> n;\n}\n\nfunction isIntegerShim(n: number): boolean {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexport const isInteger = (Number as { isInteger?(n: number): boolean }).isInteger || isIntegerShim;\n\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexport const MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexport const isSafeInteger = (n: number): boolean =>\n isInteger(n) && (n >= -MAX_SAFE_INTEGER && n <= MAX_SAFE_INTEGER);\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\n\nimport { isSafeInteger } from \"@stablelib/int\";\n\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16BE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16BE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16LE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\n\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16BE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\n\nexport const writeInt16BE = writeUint16BE;\n\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16LE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\n\nexport const writeInt16LE = writeUint16LE;\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32BE(array: Uint8Array, offset = 0): number {\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32BE(array: Uint8Array, offset = 0): number {\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32LE(array: Uint8Array, offset = 0): number {\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\n\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\n\nexport const writeInt32BE = writeUint32BE;\n\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\n\n\nexport const writeInt32LE = writeUint32LE;\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64BE(array: Uint8Array, offset = 0): number {\n const hi = readInt32BE(array, offset);\n const lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64BE(array: Uint8Array, offset = 0): number {\n const hi = readUint32BE(array, offset);\n const lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64LE(array: Uint8Array, offset = 0): number {\n const lo = readInt32LE(array, offset);\n const hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64LE(array: Uint8Array, offset = 0): number {\n const lo = readUint32LE(array, offset);\n const hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64BE = writeUint64BE;\n\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64LE = writeUint64LE;\n\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintBE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintLE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintBE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n let div = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintLE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n let div = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\n\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\n\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\n\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\n\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package random provides functions to access system's\n * cryptographically secure random byte generator.\n */\n\nimport { RandomSource } from \"./source\";\nimport { SystemRandomSource } from \"./source/system\";\nimport { readUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { RandomSource } from \"./source\";\n\nexport const defaultRandomSource = new SystemRandomSource();\n\nexport function randomBytes(length: number, prng: RandomSource = defaultRandomSource): Uint8Array {\n return prng.randomBytes(length);\n}\n\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nexport function randomUint32(prng: RandomSource = defaultRandomSource): number {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = readUint32LE(buf);\n\n // Clean the buffer.\n wipe(buf);\n\n return result;\n}\n\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomString(\n length: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n wipe(buf);\n }\n return out;\n}\n\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomStringForEntropy(\n bits: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package x25519 implements X25519 key agreement.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 32;\nexport const SHARED_KEY_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../sign/ed25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which is ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst _121665 = gf([0xdb41, 1]);\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, inp: GF) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\n\nexport function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n\n unpack25519(x, p);\n\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n\n a[0] = d[0] = 1;\n\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\n\nexport function scalarMultBase(n: Uint8Array): Uint8Array {\n return scalarMult(n, _9);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nexport function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {\n if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n\n const result = scalarMult(mySecretKey, theirPublicKey);\n\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n\n return result;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package sha256 implements SHA-2-256 cryptographic hash function.\n */\n\nimport { SerializableHash } from \"@stablelib/hash\";\nimport { readUint32BE, writeUint32BE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 32;\nexport const BLOCK_SIZE = 64;\n\n/**\n * SHA2-256 cryptographic hash algorithm.\n */\nexport class SHA256 implements SerializableHash {\n /** Length of hash output */\n readonly digestLength: number = DIGEST_LENGTH;\n\n /** Block size */\n readonly blockSize: number = BLOCK_SIZE;\n\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n protected _state = new Int32Array(8); // hash state\n private _temp = new Int32Array(64); // temporary state\n private _buffer = new Uint8Array(128); // buffer for data to hash\n private _bufferLength = 0; // number of bytes in buffer\n private _bytesHashed = 0; // number of total bytes hashed\n private _finished = false; // indicates whether the hash was finalized\n\n constructor() {\n this.reset();\n }\n\n protected _initState() {\n this._state[0] = 0x6a09e667;\n this._state[1] = 0xbb67ae85;\n this._state[2] = 0x3c6ef372;\n this._state[3] = 0xa54ff53a;\n this._state[4] = 0x510e527f;\n this._state[5] = 0x9b05688c;\n this._state[6] = 0x1f83d9ab;\n this._state[7] = 0x5be0cd19;\n }\n\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n reset(): this {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans internal buffers and resets hash state.\n */\n clean() {\n wipe(this._buffer);\n wipe(this._temp);\n this.reset();\n }\n\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n update(data: Uint8Array, dataLength: number = data.length): this {\n if (this._finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n let dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < this.blockSize && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n }\n\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n finish(out: Uint8Array): this {\n if (!this._finished) {\n const bytesHashed = this._bytesHashed;\n const left = this._bufferLength;\n const bitLenHi = (bytesHashed / 0x20000000) | 0;\n const bitLenLo = bytesHashed << 3;\n const padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n\n this._buffer[left] = 0x80;\n for (let i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n\n hashBlocks(this._temp, this._state, this._buffer, 0, padLength);\n\n this._finished = true;\n }\n\n for (let i = 0; i < this.digestLength / 4; i++) {\n writeUint32BE(this._state[i], out, i * 4);\n }\n\n return this;\n }\n\n /**\n * Returns the final hash digest.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Returns hash state to be used with restoreState().\n * Only chain value is saved, not buffers or other\n * state variables.\n */\n saveState(): SavedState {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n state: new Int32Array(this._state),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Restores state saved by saveState() and sets bytesHashed\n * to the given value.\n */\n restoreState(savedState: SavedState): this {\n this._state.set(savedState.state);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans state returned by saveState().\n */\n cleanSavedState(savedState: SavedState) {\n wipe(savedState.state);\n if (savedState.buffer) {\n wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n }\n}\n\nexport type SavedState = {\n state: Int32Array;\n buffer: Uint8Array | undefined;\n bufferLength: number;\n bytesHashed: number;\n};\n\n// Constants\nconst K = new Int32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\nfunction hashBlocks(w: Int32Array, v: Int32Array, p: Uint8Array, pos: number, len: number): number {\n while (len >= 64) {\n let a = v[0];\n let b = v[1];\n let c = v[2];\n let d = v[3];\n let e = v[4];\n let f = v[5];\n let g = v[6];\n let h = v[7];\n\n for (let i = 0; i < 16; i++) {\n let j = pos + i * 4;\n w[i] = readUint32BE(p, j);\n }\n\n for (let i = 16; i < 64; i++) {\n let u = w[i - 2];\n let t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n\n u = w[i - 15];\n let t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n\n for (let i = 0; i < 64; i++) {\n let t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n\n let t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (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 v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n\n pos += 64;\n len -= 64;\n }\n return pos;\n}\n\nexport function hash(data: Uint8Array): Uint8Array {\n const h = new SHA256();\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha implements ChaCha stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\n// Number of ChaCha rounds (ChaCha20).\nconst ROUNDS = 20;\n\n// Applies the ChaCha core function to 16-byte input,\n// 32-byte key key, and puts the result into 64-byte array out.\nfunction core(out: Uint8Array, input: Uint8Array, key: Uint8Array): void {\n let j0 = 0x61707865; // \"expa\" -- ChaCha's \"sigma\" constant\n let j1 = 0x3320646E; // \"nd 3\" for 32-byte keys\n let j2 = 0x79622D32; // \"2-by\"\n let j3 = 0x6B206574; // \"te k\"\n let j4 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let j5 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let j6 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let j7 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let j8 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let j9 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let j10 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let j11 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let j12 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n let j13 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n let j14 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n let j15 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n\n let x0 = j0;\n let x1 = j1;\n let x2 = j2;\n let x3 = j3;\n let x4 = j4;\n let x5 = j5;\n let x6 = j6;\n let x7 = j7;\n let x8 = j8;\n let x9 = j9;\n let x10 = j10;\n let x11 = j11;\n let x12 = j12;\n let x13 = j13;\n let x14 = j14;\n let x15 = j15;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 16) | x12 << 16;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 12) | x4 << 12;\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 16) | x13 << 16;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 12) | x5 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 16) | x14 << 16;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 12) | x6 << 12;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 16) | x15 << 16;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 12) | x7 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 8) | x14 << 8;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 7) | x6 << 7;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 8) | x15 << 8;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 7) | x7 << 7;\n\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 8) | x13 << 8;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 7) | x5 << 7;\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 8) | x12 << 8;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 16) | x15 << 16;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 12) | x5 << 12;\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 16) | x12 << 16;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 12) | x6 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 16) | x13 << 16;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 12) | x7 << 12;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 16) | x14 << 16;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 12) | x4 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 8) | x13 << 8;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 7) | x7 << 7;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 8) | x14 << 8;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 8) | x12 << 8;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 7) | x6 << 7;\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 8) | x15 << 8;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 7) | x5 << 7;\n }\n writeUint32LE(x0 + j0 | 0, out, 0);\n writeUint32LE(x1 + j1 | 0, out, 4);\n writeUint32LE(x2 + j2 | 0, out, 8);\n writeUint32LE(x3 + j3 | 0, out, 12);\n writeUint32LE(x4 + j4 | 0, out, 16);\n writeUint32LE(x5 + j5 | 0, out, 20);\n writeUint32LE(x6 + j6 | 0, out, 24);\n writeUint32LE(x7 + j7 | 0, out, 28);\n writeUint32LE(x8 + j8 | 0, out, 32);\n writeUint32LE(x9 + j9 | 0, out, 36);\n writeUint32LE(x10 + j10 | 0, out, 40);\n writeUint32LE(x11 + j11 | 0, out, 44);\n writeUint32LE(x12 + j12 | 0, out, 48);\n writeUint32LE(x13 + j13 | 0, out, 52);\n writeUint32LE(x14 + j14 | 0, out, 56);\n writeUint32LE(x15 + j15 | 0, out, 60);\n}\n\n/**\n * Encrypt src with ChaCha20 stream generated for the given 32-byte key and\n * 8-byte (as in original implementation) or 12-byte (as in RFC7539) nonce and\n * write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * If nonce is 12 bytes, users should not encrypt more than 256 GiB with the\n * same key and nonce, otherwise the stream will repeat. The function will\n * throw error if counter overflows to prevent this.\n *\n * If nonce is 8 bytes, the output is practically unlimited (2^70 bytes, which\n * is more than a million petabytes). However, it is not recommended to\n * generate 8-byte nonces randomly, as the chance of collision is high.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each ChaCha block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array,\n src: Uint8Array, dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"ChaCha: key size must be 32 bytes\");\n }\n\n if (dst.length < src.length) {\n throw new Error(\"ChaCha: destination is shorter than source\");\n }\n\n let nc: Uint8Array;\n let counterLength: number;\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8 && nonce.length !== 12) {\n throw new Error(\"ChaCha nonce must be 8 or 12 bytes\");\n }\n nc = new Uint8Array(16);\n // First counterLength bytes of nc are counter, starting with zero.\n counterLength = nc.length - nonce.length;\n // Last bytes of nc after counterLength are nonce, set them.\n nc.set(nonce, counterLength);\n } else {\n if (nonce.length !== 16) {\n throw new Error(\"ChaCha nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterLength = nonceInplaceCounterLength;\n }\n\n // Allocate temporary space for ChaCha block.\n const block = new Uint8Array(64);\n\n for (let i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n\n // XOR block bytes with src into dst.\n for (let j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n\n // Increment counter.\n incrementCounter(nc, 0, counterLength);\n }\n\n // Cleanup temporary space.\n wipe(block);\n\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe(nc);\n }\n\n return dst;\n}\n\n/**\n * Generate ChaCha20 stream for the given 32-byte key and 8-byte or 12-byte\n * nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same with respect to\n * the nonce as described in the streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\nfunction incrementCounter(counter: Uint8Array, pos: number, len: number) {\n let carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"ChaCha: counter overflow\");\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\n\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 16;\n\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nexport class Poly1305 {\n readonly digestLength = DIGEST_LENGTH;\n\n private _buffer = new Uint8Array(16);\n private _r = new Uint16Array(10);\n private _h = new Uint16Array(10);\n private _pad = new Uint16Array(8);\n private _leftover = 0;\n private _fin = 0;\n private _finished = false;\n\n constructor(key: Uint8Array) {\n let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff;\n let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n\n private _blocks(m: Uint8Array, mpos: number, bytes: number) {\n let hibit = this._fin ? 0 : 1 << 11;\n\n let h0 = this._h[0],\n h1 = this._h[1],\n h2 = this._h[2],\n h3 = this._h[3],\n h4 = this._h[4],\n h5 = this._h[5],\n h6 = this._h[6],\n h7 = this._h[7],\n h8 = this._h[8],\n h9 = this._h[9];\n\n let r0 = this._r[0],\n r1 = this._r[1],\n r2 = this._r[2],\n r3 = this._r[3],\n r4 = this._r[4],\n r5 = this._r[5],\n r6 = this._r[6],\n r7 = this._r[7],\n r8 = this._r[8],\n r9 = this._r[9];\n\n while (bytes >= 16) {\n let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff;\n let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n let c = 0;\n\n let d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n let d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n let d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n let d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n let d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n let d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n let d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n let d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n let d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n let d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n }\n\n finish(mac: Uint8Array, macpos = 0): this {\n const g = new Uint16Array(10);\n let c: number;\n let mask: number;\n let f: number;\n let i: number;\n\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n\n this._finished = true;\n return this;\n }\n\n update(m: Uint8Array): this {\n let mpos = 0;\n let bytes = m.length;\n let want: number;\n\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (let i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (let i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n\n return this;\n }\n\n digest(): Uint8Array {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished \u2014 others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n let mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n }\n\n clean(): this {\n wipe(this._buffer);\n wipe(this._r);\n wipe(this._h);\n wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n }\n}\n\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nexport function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new Poly1305(key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) {\n return false;\n }\n return constantTimeEqual(a, b);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha20poly1305 implements ChaCha20-Poly1305 AEAD.\n */\n\nimport { AEAD } from \"@stablelib/aead\";\nimport { streamXOR, stream } from \"@stablelib/chacha\";\nimport { Poly1305 } from \"@stablelib/poly1305\";\nimport { wipe } from \"@stablelib/wipe\";\nimport { writeUint64LE } from \"@stablelib/binary\";\nimport { equal } from \"@stablelib/constant-time\";\n\nexport const KEY_LENGTH = 32;\nexport const NONCE_LENGTH = 12;\nexport const TAG_LENGTH = 16;\n\nconst ZEROS = new Uint8Array(16);\n\n/**\n * ChaCha20-Poly1305 Authenticated Encryption with Associated Data.\n *\n * Defined in RFC7539.\n */\nexport class ChaCha20Poly1305 implements AEAD {\n readonly nonceLength = NONCE_LENGTH;\n readonly tagLength = TAG_LENGTH;\n\n private _key: Uint8Array;\n\n /**\n * Creates a new instance with the given 32-byte key.\n */\n constructor(key: Uint8Array) {\n if (key.length !== KEY_LENGTH) {\n throw new Error(\"ChaCha20Poly1305 needs 32-byte key\");\n }\n // Copy key.\n this._key = new Uint8Array(key);\n }\n\n /**\n * Encrypts and authenticates plaintext, authenticates associated data,\n * and returns sealed ciphertext, which includes authentication tag.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If dst is given (it must be the size of plaintext + the size of tag\n * length) the result will be put into it. Dst and plaintext must not\n * overlap.\n */\n seal(nonce: Uint8Array, plaintext: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n // We pass full counter, which has 12-byte nonce and 4-byte block counter,\n // and it will get incremented after generating the block, which is\n // exactly what we need: we only use the first 32 bytes of 64-byte\n // ChaCha block and discard the next 32 bytes.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Allocate space for sealed ciphertext.\n const resultLength = plaintext.length + this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Encrypt plaintext.\n streamXOR(this._key, counter, plaintext, result, 4);\n\n // Authenticate.\n // XXX: can \"simplify\" here: pass full result (which is already padded\n // due to zeroes prepared for tag), and ciphertext length instead of\n // subarray of result.\n this._authenticate(result.subarray(result.length - this.tagLength, result.length),\n authKey, result.subarray(0, result.length - this.tagLength), associatedData);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n /**\n * Authenticates sealed ciphertext (which includes authentication tag) and\n * associated data, decrypts ciphertext and returns decrypted plaintext.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If authentication fails, it returns null.\n *\n * If dst is given (it must be of ciphertext length minus tag length),\n * the result will be put into it. Dst and plaintext must not overlap.\n */\n open(nonce: Uint8Array, sealed: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array | null {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Sealed ciphertext should at least contain tag.\n if (sealed.length < this.tagLength) {\n // TODO(dchest): should we throw here instead?\n return null;\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Authenticate.\n // XXX: can simplify and avoid allocation: since authenticate()\n // already allocates tag (from Poly1305.digest(), it can return)\n // it instead of copying to calculatedTag. But then in seal()\n // we'll need to copy it.\n const calculatedTag = new Uint8Array(this.tagLength);\n this._authenticate(calculatedTag, authKey,\n sealed.subarray(0, sealed.length - this.tagLength), associatedData);\n\n // Constant-time compare tags and return null if they differ.\n if (!equal(calculatedTag,\n sealed.subarray(sealed.length - this.tagLength, sealed.length))) {\n return null;\n }\n\n // Allocate space for decrypted plaintext.\n const resultLength = sealed.length - this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Decrypt.\n streamXOR(this._key, counter,\n sealed.subarray(0, sealed.length - this.tagLength), result, 4);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n clean(): this {\n wipe(this._key);\n return this;\n }\n\n private _authenticate(tagOut: Uint8Array, authKey: Uint8Array,\n ciphertext: Uint8Array, associatedData?: Uint8Array) {\n\n // Initialize Poly1305 with authKey.\n const h = new Poly1305(authKey);\n\n // Authenticate padded associated data.\n if (associatedData) {\n h.update(associatedData);\n if (associatedData.length % 16 > 0) {\n h.update(ZEROS.subarray(associatedData.length % 16));\n }\n }\n\n // Authenticate padded ciphertext.\n h.update(ciphertext);\n if (ciphertext.length % 16 > 0) {\n h.update(ZEROS.subarray(ciphertext.length % 16));\n }\n\n // Authenticate length of associated data.\n // XXX: can avoid allocation here?\n const length = new Uint8Array(8);\n if (associatedData) {\n writeUint64LE(associatedData.length, length);\n }\n h.update(length);\n\n // Authenticate length of ciphertext.\n writeUint64LE(ciphertext.length, length);\n h.update(length);\n\n // Get tag and copy it into tagOut.\n const tag = h.digest();\n for (let i = 0; i < tag.length; i++) {\n tagOut[i] = tag[i];\n }\n\n // Cleanup.\n h.clean();\n wipe(tag);\n wipe(length);\n }\n}\n", "module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\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 \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n", "module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\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)\n\nmodule.exports = function (value) {\n return (\n 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 )\n}\n", "module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\n", "'use strict'\n\nconst varint = require('varint')\n\nmodule.exports = (buf) => {\n if (!(buf instanceof Uint8Array)) {\n throw new Error('arg needs to be a Uint8Array')\n }\n\n const result = []\n\n while (buf.length > 0) {\n const num = varint.decode(buf)\n result.push(num)\n buf = buf.slice(varint.decode.bytes)\n }\n\n return result\n}\n", "'use strict'\n\nconst exp = Math.exp\n\nexports =\nmodule.exports =\nfunction MovingAverage (timespan) {\n if (typeof timespan !== 'number') { throw new Error('must provide a timespan to the moving average constructor') }\n\n if (timespan <= 0) { throw new Error('must provide a timespan > 0 to the moving average constructor') }\n\n let ma // moving average\n let v = 0 // variance\n let d = 0 // deviation\n let f = 0 // forecast\n\n let previousTime\n\n let ret = {}\n\n function alpha (t, pt) {\n return 1 - (exp(-(t - pt) / timespan))\n }\n\n ret.push =\n function push (time, value) {\n if (previousTime) {\n // calculate moving average\n const a = alpha(time, previousTime)\n const diff = value - ma\n const incr = a * diff\n ma = a * value + (1 - a) * ma\n // calculate variance & deviation\n v = (1 - a) * (v + diff * incr)\n d = Math.sqrt(v)\n // calculate forecast\n f = ma + a * diff\n } else {\n ma = value\n }\n previousTime = time\n }\n\n // Exponential Moving Average\n\n ret.movingAverage =\n function movingAverage () {\n return ma\n }\n\n // Variance\n ret.variance =\n function variance () {\n return v\n }\n\n ret.deviation =\n function deviation () {\n return d\n }\n\n ret.forecast =\n function forecast () {\n return f\n }\n\n return ret\n}\n", "/* jshint browser: true */\n\n(function () {\n\n// We'll copy the properties below into the mirror div.\n// Note that some browsers, such as Firefox, do not concatenate properties\n// into their shorthand (e.g. padding-top, padding-bottom etc. -> padding),\n// so we have to list every single property explicitly.\nvar properties = [\n 'direction', // RTL support\n 'boxSizing',\n 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does\n 'height',\n 'overflowX',\n 'overflowY', // copy the scrollbar for IE\n\n 'borderTopWidth',\n 'borderRightWidth',\n 'borderBottomWidth',\n 'borderLeftWidth',\n 'borderStyle',\n\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/font\n 'fontStyle',\n 'fontVariant',\n 'fontWeight',\n 'fontStretch',\n 'fontSize',\n 'fontSizeAdjust',\n 'lineHeight',\n 'fontFamily',\n\n 'textAlign',\n 'textTransform',\n 'textIndent',\n 'textDecoration', // might not make a difference, but better be safe\n\n 'letterSpacing',\n 'wordSpacing',\n\n 'tabSize',\n 'MozTabSize'\n\n];\n\nvar isBrowser = (typeof window !== 'undefined');\nvar isFirefox = (isBrowser && window.mozInnerScreenX != null);\n\nfunction getCaretCoordinates(element, position, options) {\n if (!isBrowser) {\n throw new Error('textarea-caret-position#getCaretCoordinates should only be called in a browser');\n }\n\n var debug = options && options.debug || false;\n if (debug) {\n var el = document.querySelector('#input-textarea-caret-position-mirror-div');\n if (el) el.parentNode.removeChild(el);\n }\n\n // The mirror div will replicate the textarea's style\n var div = document.createElement('div');\n div.id = 'input-textarea-caret-position-mirror-div';\n document.body.appendChild(div);\n\n var style = div.style;\n var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9\n var isInput = element.nodeName === 'INPUT';\n\n // Default textarea styles\n style.whiteSpace = 'pre-wrap';\n if (!isInput)\n style.wordWrap = 'break-word'; // only for textarea-s\n\n // Position off-screen\n style.position = 'absolute'; // required to return coordinates properly\n if (!debug)\n style.visibility = 'hidden'; // not 'display: none' because we want rendering\n\n // Transfer the element's properties to the div\n properties.forEach(function (prop) {\n if (isInput && prop === 'lineHeight') {\n // Special case for s because text is rendered centered and line height may be != height\n style.lineHeight = computed.height;\n } else {\n style[prop] = computed[prop];\n }\n });\n\n if (isFirefox) {\n // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275\n if (element.scrollHeight > parseInt(computed.height))\n style.overflowY = 'scroll';\n } else {\n style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'\n }\n\n div.textContent = element.value.substring(0, position);\n // The second special handling for input type=\"text\" vs textarea:\n // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037\n if (isInput)\n div.textContent = div.textContent.replace(/\\s/g, '\\u00a0');\n\n var span = document.createElement('span');\n // Wrapping must be replicated *exactly*, including when a long word gets\n // onto the next line, with whitespace at the end of the line before (#7).\n // The *only* reliable way to do that is to copy the *entire* rest of the\n // textarea's content into the created at the caret position.\n // For inputs, just '.' would be enough, but no need to bother.\n span.textContent = element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all\n div.appendChild(span);\n\n var coordinates = {\n top: span.offsetTop + parseInt(computed['borderTopWidth']),\n left: span.offsetLeft + parseInt(computed['borderLeftWidth']),\n height: parseInt(computed['lineHeight'])\n };\n\n if (debug) {\n span.style.backgroundColor = '#aaa';\n } else {\n document.body.removeChild(div);\n }\n\n return coordinates;\n}\n\nif (typeof module != 'undefined' && typeof module.exports != 'undefined') {\n module.exports = getCaretCoordinates;\n} else if(isBrowser) {\n window.getCaretCoordinates = getCaretCoordinates;\n}\n\n}());\n", "export const isArray = (what): boolean => Array.isArray(what);\n", "import { isArray } from \"./isArray\";\n\nconst select = (selector) => ({\n el: document.querySelector(selector),\n elements: document.querySelectorAll(selector),\n placeholder(what) {\n this.el.placeholder = what;\n return this;\n },\n getValue() {\n return this.el.value;\n },\n insertAtCaret(text) {\n this.el.setRangeText(\n text,\n this.el.selectionStart,\n this.el.selectionEnd,\n \"end\"\n );\n return this;\n },\n setValue(value) {\n this.el.value = value;\n const event = new Event(\"input\", {\n bubbles: true,\n cancelable: true,\n });\n this.el.dispatchEvent(event);\n return this;\n },\n innerHTML(htmlString) {\n this.el.innerHTML = htmlString;\n return this;\n },\n html(content) {\n this.el.innerHTML = \"\";\n this.append(content);\n return this;\n },\n append(el) {\n const elements = isArray(el) ? el : [el];\n elements.forEach((e) => {\n const newContent = isElement(e) ? e : document.createTextNode(e);\n this.el.appendChild(newContent);\n });\n return this;\n },\n appendListElement(text) {\n const li = document.createElement(\"LI\");\n li.appendChild(document.createTextNode(text));\n this.el.appendChild(li);\n return this;\n },\n removeClass(className) {\n this.el.classList.remove(className);\n return this;\n },\n removeClasses(classes = []) {\n classes.map((className) => this.removeClass(className));\n return this;\n },\n addClass(className) {\n this.el.classList.add(className);\n return this;\n },\n hasClass(cls) {\n return (\" \" + this.el.className + \" \").indexOf(\" \" + cls + \" \") > -1;\n },\n show(shouldShow = true) {\n if (shouldShow) {\n this.removeClass(\"hidden\");\n } else {\n this.hide();\n }\n return this;\n },\n hide() {\n this.addClass(\"hidden\");\n return this;\n },\n toggle(className = \"hidden\") {\n if (this.hasClass(className)) this.removeClass(className);\n else this.addClass(className);\n return this;\n },\n focus() {\n this.el.focus();\n return this;\n },\n listenAll(event, fn) {\n const elements = Array.prototype.slice.call(this.elements);\n elements.map((el) => {\n el.addEventListener(event, (e) => fn(e.srcElement));\n });\n return this;\n },\n listen(event, fn) {\n this.el.addEventListener(event, (e) => fn(e, this));\n return this;\n },\n click() {\n if (this.el) {\n this.el.click();\n }\n },\n checked(value) {\n this.el.checked = !!value;\n return this;\n },\n disable(shouldDisable = true) {\n this.el.disabled = shouldDisable;\n return this;\n },\n});\n\nexport const isElement = (obj) => {\n try {\n return obj instanceof HTMLElement;\n } catch (e) {\n //Browsers not supporting W3 DOM2 don't have HTMLElement and\n //an exception is thrown and we end up here. Testing some\n //properties that all elements have (works on IE7)\n return (\n typeof obj === \"object\" &&\n obj.nodeType === 1 &&\n typeof obj.style === \"object\" &&\n typeof obj.ownerDocument === \"object\"\n );\n }\n};\n\nexport default select;\n", "import select from \"../../utils/dom\";\n\nconst notificationTypes = {\n info: \"info\",\n success: \"success\",\n error: \"error\",\n warning: \"warning\",\n};\n\nconst notification = select(\"#notification\");\nconst cleanNotificationClasses = () =>\n notification.removeClasses(Object.values(notificationTypes));\nnotification.el.onclick = () => cleanNotificationClasses();\n\nconst notificationFactory = () =>\n Object.values(notificationTypes).reduce(\n (acc, notificationType) => ({\n ...acc,\n [notificationType](message) {\n this.showNotification(message, notificationType);\n },\n }),\n {}\n );\n\nconst Notification = (autohideDuration = 5) => ({\n autohideDuration,\n timer: undefined,\n removeAfter() {\n this.timer = setTimeout(() => {\n cleanNotificationClasses();\n }, this.autohideDuration * 1000);\n },\n showNotification(message, type = notificationTypes.info) {\n cleanNotificationClasses();\n notification.innerHTML(message).addClass(type);\n clearTimeout(this.timer);\n this.removeAfter();\n },\n ...notificationFactory(),\n});\n\nconst notify = Notification();\nexport default notify;\n", "import notify from \"./notify\";\n\nconst welcomeUser = () => {\n const lastVisit = localStorage.getItem(\"miropad.user\");\n if (lastVisit) {\n notify.info(`\uD83E\uDD17 Happy to see you again from ${lastVisit}`);\n } else {\n notify.info(\n `

    Welcome \uD83D\uDC4B \uD83D\uDE03

    \n

    Use Ctrl+S: to save your note

    \n

    & Ctrl+P: to format a JSON doc

    \n `,\n 100\n );\n }\n localStorage.setItem(\"miropad.user\", new Date().toLocaleDateString());\n};\n\nexport default welcomeUser;\n", "import notify from \"../components/molecules/notify\";\nimport { isArray } from \"./isArray\";\n\nconst storage = (() => {\n return {\n set: function (key, what) {\n localStorage.setItem(key, what);\n return this;\n },\n update: function (key, attr) {\n const current = JSON.parse(this.get(key));\n localStorage.setItem(\n key,\n JSON.stringify({\n ...current,\n ...attr,\n })\n );\n return this;\n },\n remove: function (key) {\n localStorage.removeItem(key);\n return this;\n },\n get: function (key) {\n if (isArray(key)) {\n return key.reduce((acc, k) => {\n return {\n ...acc,\n [k]: this.get(k),\n };\n }, {});\n }\n\n return localStorage.getItem(key);\n },\n parse: function (key) {\n const value = this.get(key);\n return JSON.parse(value);\n },\n getDictionary: function () {\n const savedTxt = localStorage.getItem(\"__dictionary__\");\n return savedTxt ? JSON.parse(savedTxt) : [];\n },\n removeFromDictionary: function (word) {\n const currentDictionary = this.getDictionary();\n const newDictionary = currentDictionary.filter((w) => {\n return w !== word;\n });\n\n localStorage.setItem(\"__dictionary__\", JSON.stringify(newDictionary));\n },\n saveToDictionary: async function (what) {\n if (what.length) {\n try {\n const cleanText = what.toLowerCase().replace(/[^a-zA-Z\u03AC-\u03CE\u0391-\u03A9]/g, \" \");\n const current = await this.getDictionary();\n const words = [\n ...cleanText.split(\" \").filter((w) => w.length > 3),\n ...current,\n ];\n const distinctWords = [...new Set(words)];\n localStorage.setItem(\"__dictionary__\", JSON.stringify(distinctWords));\n } catch (e) {\n notify.error(\n `\uD83D\uDE31 Something went wrong while trying to save to local storage ${e}`\n ); // eslint-disable-line\n }\n } else {\n notify.warning(\"\uD83D\uDE15 Nothing to save!\"); // eslint-disable-line\n }\n return this;\n },\n };\n})();\n\nexport default storage;\n", "export const configuration = {\n github: {\n client_id: \"70c1955dfe4914c52c10\",\n request_state: \"miro-pad\",\n },\n auth_service: \"https://vercel-api-phi.vercel.app/api/auth\",\n mail_service: {\n api: \"https://vercel-api-phi.vercel.app/api/mail\",\n signature: `Theo Mironidis
    \n Software Engineer
    \n https://teomrd.github.io`,\n },\n file_service: {\n api: \"https://vercel-api-phi.vercel.app/api/upload\",\n },\n} as const;\n", "import storage from \"../localstorage\";\nimport { getNotes } from \"../../components/organisms/noteManager/noteManager\";\nimport notify from \"../../components/molecules/notify\";\nimport { configuration } from \"../../../configuration\";\n\nexport const getGist = (id, token = storage.get(\"authToken\")) =>\n fetch(`https://api.github.com/gists/${id}`, {\n headers: {\n Authorization: `token ${token}`,\n },\n }).then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n });\n\nexport const getAuthenticatedUsersGists = (token = storage.get(\"authToken\")) =>\n fetch(\"https://api.github.com/gists\", {\n headers: {\n Authorization: `token ${token}`,\n },\n }).then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n });\n\nexport const deleteFileOnGist = async (\n fileName,\n gistId = storage.get(\"gistId\"),\n token = storage.get(\"authToken\")\n) => {\n return fetch(`https://api.github.com/gists/${gistId}`, {\n method: \"PATCH\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: {\n [fileName]: null,\n },\n description: \"MiroPad Gist\",\n public: false,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n notify.info(`${fileName} deleted on Gist!`);\n return responseAsJson;\n });\n};\n\nexport const updateGist = async (\n notes = getNotes(),\n gistId = storage.get(\"gistId\"),\n token = storage.get(\"authToken\")\n) => {\n if (gistId && token) {\n const noteToFiles = notes.reduce((acc, { id, text, deleted }) => {\n return {\n ...acc,\n [id]: deleted ? null : { content: text },\n };\n }, {});\n return fetch(`https://api.github.com/gists/${gistId}`, {\n method: \"PATCH\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: noteToFiles,\n description: \"MiroPad Gist\",\n public: false,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n notes.map(({ id, deleted }) => {\n if (deleted) localStorage.removeItem(id);\n });\n return responseAsJson;\n });\n }\n};\n\nexport const createNewGist = (token = storage.get(\"authToken\")) => {\n const notes = getNotes();\n const noteToFiles = notes.reduce((acc, note) => {\n return {\n ...acc,\n [note.id]: {\n content: note.text,\n },\n };\n }, {});\n return fetch(\"https://api.github.com/gists\", {\n method: \"POST\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: noteToFiles,\n description: \"MiroPad Gist\",\n public: false,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n return responseAsJson;\n });\n};\n\nexport const getAuthToken = (code, state) =>\n fetch(`${configuration.auth_service}?state=${state}&code=${code}`, {\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n })\n .then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n return responseAsJson;\n });\n\nexport const publishGist = ({\n note,\n token = storage.get(\"authToken\"),\n} = {}) => {\n return fetch(\"https://api.github.com/gists\", {\n method: \"POST\",\n headers: {\n Authorization: `token ${token}`,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n files: {\n [note.id]: {\n content: note.text,\n },\n },\n description: \"MiroPad Gist\",\n public: true,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response.json();\n })\n .then((responseAsJson) => {\n return responseAsJson;\n });\n};\n", "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\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 \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const 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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\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", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\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.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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 function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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 function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\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 /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\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}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\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\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const 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", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import * as varint from './varint.js'\nimport * as Digest from './hashes/digest.js'\nimport { base58btc } from './bases/base58.js'\nimport { base32 } from './bases/base32.js'\nimport { coerce } from './bytes.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst 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}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n *\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\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\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\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 /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\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 * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n 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 =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\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 /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\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 * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\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\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst 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\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 } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst 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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst 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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n 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})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n", "import { CID } from \"multiformats/cid\";\nimport * as json from \"multiformats/codecs/json\";\nimport { sha256 } from \"multiformats/hashes/sha2\";\n\nconst hashBrowser = async (val) => {\n const bytes = json.encode(val);\n\n const hash = await sha256.digest(bytes);\n const cid = CID.create(1, json.code, hash);\n\n return cid.toString();\n};\n\nexport default hashBrowser;\n", "const isJSON = (str) => {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n};\n\nexport default isJSON;\n", "import select from \"./dom\";\n\nconst _getBasePageTitle = () => {\n const titleSections = document.title.split(\"|\");\n const baseTitle = titleSections[0];\n return baseTitle;\n};\n\nconst setPageTitle = (what) => {\n const baseTitle = _getBasePageTitle();\n document.title = baseTitle.trim() + \" | \" + what.trim();\n select(\".title h3\").html(what.trim());\n};\n\nconst resetPageTitle = () => {\n const baseTitle = _getBasePageTitle();\n document.title = baseTitle;\n select(\"title\").innerHTML(`${TITLE_NAME} v${VERSION}`);\n select(\".title h3\").innerHTML(\n `${TITLE_NAME} v${VERSION}`\n );\n};\n\nexport { setPageTitle, resetPageTitle };\n", "export const url = {\n baseUrl: `${window.location.origin}${window.location.pathname}`,\n get: function () {\n return window.location.href;\n },\n getPageId: function (url = window.location.href) {\n const URLObject = new URL(url);\n const hash = URLObject.hash.substr(1);\n const hashWithVersion = hash.split(\"?\");\n const pageId = hashWithVersion[0] || null;\n return pageId;\n },\n getSearchParams: function (url = window.location.href) {\n const URLObject = new URL(url);\n const urlParts = URLObject.href.split(\"?\");\n const currentParams = urlParts[1] || \"\";\n const searchParams = new URLSearchParams(currentParams);\n return searchParams;\n },\n getParamsObject: function (url = window.location.href) {\n const params = this.getSearchParams(url);\n let parametersObject = {};\n for (const key of params.keys()) {\n parametersObject = {\n ...parametersObject,\n [key]: this.getSearchParam(key, url),\n };\n }\n return parametersObject;\n },\n getSearchParam(param, url = window.location.href) {\n const params = this.getSearchParams(url);\n const paramValue = params.get(param);\n return paramValue;\n },\n deleteParam: function (param) {\n const searchParams = this.getSearchParams();\n if (typeof param === \"object\" && param.length > 0) {\n param.forEach((p) => {\n searchParams.delete(p);\n });\n } else {\n searchParams.delete(param);\n }\n const { pathname } = window.location;\n const hash = this.getPageId();\n return window.location.assign(\n `${hash ? `#${hash}` : pathname}${\n searchParams.toString() ? `?${searchParams.toString()}` : \"\"\n }`\n );\n },\n set: function (pageId = this.getPageId(), params = this.getParamsObject()) {\n const allParams = {\n ...this.getParamsObject(),\n ...params,\n };\n const newParams = new URLSearchParams(allParams);\n return window.location.assign(`#${pageId}?${newParams.toString()}`);\n },\n};\n", "import select from \"../../utils/dom\";\n\nexport const setSavedState = (saved = true) => {\n if (saved) {\n select(\"#save\").removeClass(\"unsaved\");\n select(\"#logo\").removeClass(\"unsaved\");\n } else {\n select(\"#save\").addClass(\"unsaved\");\n select(\"#logo\").addClass(\"unsaved\");\n }\n};\n", "/* eslint-disable indent */\nimport select from \"../../../utils/dom\";\nimport { deleteFileOnGist } from \"../../../utils/github/api\";\nimport hashBrowser from \"../../../utils/hashBrowser\";\nimport isJSON from \"../../../utils/isJSON\";\nimport storage from \"../../../utils/localstorage\";\nimport { resetPageTitle, setPageTitle } from \"../../../utils/pageTitle\";\nimport { url } from \"../../../utils/urlManager\";\nimport notify from \"../../molecules/notify\";\nimport commander from \"../commander/commander\";\nimport { setSavedState } from \"../../../ui/functions/savedState\";\n\nconst encodeTitle = (title) => {\n const encodedTitle = encodeURIComponent(title);\n if (encodedTitle.length === 0) {\n throw new Error(\"You need to start with a valid title for your note!\");\n }\n return encodedTitle;\n};\n\nexport const getDateCreatedFromTitle = (title) => {\n const titleID = getTitleId(title);\n const note = getNote(titleID);\n const { dateCreated } = note || {};\n return dateCreated;\n};\n\nexport const markNoteForDeletion = (id) => {\n const note = getNote(id);\n localStorage.setItem(\n id,\n JSON.stringify({\n title: note.title,\n deleted: true,\n revisions: note.revisions,\n })\n );\n};\n\nexport type Note = {\n id: string;\n title: string;\n text: string;\n dateCreated: number;\n deleted: boolean;\n lines: Array;\n numberOfRevisions: number;\n revisions: {\n [key: string]: {\n text: string;\n dateCreated: number;\n };\n };\n};\n\nexport const getNote = (titleID = url.getPageId(), revision): Note | null => {\n let doc;\n try {\n doc = JSON.parse(storage.get(titleID));\n if (!doc.revisions) {\n throw new Error(\"This is not a note!\");\n }\n } catch (error) {\n return null;\n }\n\n const newerNote = doc\n ? Object.values(doc.revisions).reduce(\n (acc: any, note: any) =>\n note.dateCreated > acc.dateCreated ? note : acc,\n { dateCreated: 0 }\n )\n : {};\n\n const noteToReturn = revision ? doc.revisions[revision] : newerNote;\n\n return titleID\n ? {\n ...doc,\n id: titleID,\n ...(noteToReturn ? noteToReturn : {}),\n numberOfRevisions:\n doc && doc.revisions ? Object.keys(doc.revisions).length : undefined,\n title: doc.title,\n }\n : null;\n};\n\nexport const disableSyncOnCurrentNote = (value) => {\n const { id, title } = getNote();\n storage.update(id, {\n disableSync: value,\n });\n notify.info(`\"${title}\" cloud sync ${value ? \"disabled \uD83D\uDE36\" : \"enabled \u26A1\uFE0F\"}`);\n};\n\nexport const setNoteFromHash = async (hash = url.getPageId()) => {\n if (hash) {\n const version = url.getSearchParam(\"v\");\n const note = getNote(undefined, version);\n if (note) {\n select(\"#revisions\").html(\n `${note.numberOfRevisions} revision${\n note.numberOfRevisions > 1 ? \"s\" : \"\"\n }`\n );\n setPageTitle(note.title);\n select(\".terminal\").setValue(note.text);\n }\n\n if (!note) {\n notify.error(\"404 Note not found \uD83E\uDD37\u200D\u2642\uFE0F\");\n }\n }\n};\n\nexport const resetNoteManager = () => {\n location.hash = \"\";\n resetPageTitle();\n select(\"#revisions\").html(\"\");\n select(\".terminal\").setValue(\"\").focus();\n setSavedState();\n};\n\nexport const getTitle = (note = \"\") =>\n note.split(\"\\n\")[0].trim().replace(\"#\", \"\").trim();\n\nexport const getTitleId = (note) => {\n const title = getTitle(note);\n return encodeTitle(title);\n};\n\nexport const updateNote = async (what) => {\n if (what.length) {\n const titleID = getTitleId(what);\n const title = getTitle(what);\n const existingNote = getNote(titleID);\n if (existingNote === null) {\n // new existingNote\n return saveNote(what);\n }\n const { text } = existingNote;\n const hashOfIncomingNote = await hashBrowser(what);\n const hashOfCurrentNote = await hashBrowser(text);\n\n if (hashOfIncomingNote === hashOfCurrentNote) {\n return;\n }\n\n const currentNote = storage.get(titleID);\n const note = JSON.parse(currentNote);\n storage.set(\n titleID,\n JSON.stringify({\n ...note,\n title,\n revisions: {\n ...((note && note.revisions) || {}),\n [hashOfIncomingNote]: {\n dateCreated: Date.now(),\n text: what,\n },\n },\n })\n );\n }\n};\n\nexport const saveNote = async (\n what = select(\".terminal\").getValue(),\n cid?: string\n) => {\n await storage.saveToDictionary(what);\n if (what.length) {\n const hash = await hashBrowser(what);\n try {\n const title = what.split(\"\\n\")[0].trim().replace(\"#\", \"\").trim();\n\n setPageTitle(title);\n\n const titleID = encodeTitle(title);\n const currentNote = storage.get(titleID);\n const note = JSON.parse(currentNote);\n storage.set(\n titleID,\n JSON.stringify({\n ...note,\n title,\n lines: what.split(\"\\n\"),\n revisions: {\n ...((note && note.revisions) || {}),\n [hash]: {\n dateCreated: Date.now(),\n text: what,\n ...(cid ? { cid: cid } : {}),\n },\n },\n })\n );\n url.set(titleID, {\n v: hash,\n ...(cid ? { cid: cid } : {}),\n });\n if (!cid) {\n url.deleteParam(\"cid\");\n }\n storage.set(\"lastLocalUpdate\", new Date());\n notify.success(\"\uD83D\uDC4C Note saved!\");\n setSavedState();\n } catch (e) {\n notify.error(\n `\uD83D\uDE31 Something went wrong while trying to save to local storage ${e}`\n ); // eslint-disable-line\n }\n } else {\n notify.warning(\"\uD83D\uDE15 Nothing to save!\"); // eslint-disable-line\n }\n};\n\nexport const getNotes = ({ includeDeleted } = {}) =>\n Object.entries(localStorage)\n .filter(([, body]) => typeof body === \"string\")\n .filter(([id, body]) => !id.startsWith(\"__\") && isJSON(body))\n .map(([id, body]) => [id, JSON.parse(body)])\n .filter(([, body]) => !!body.title) // check if title exists and therefore is a note\n .reduce((acc, [noteId]) => [...acc, getNote(noteId)], [])\n .filter(({ deleted }) => (includeDeleted ? true : !deleted));\n\nexport const search = (q) => {\n if (!q) {\n return undefined;\n }\n\n const results = getNotes()\n .map(({ id }) => getNote(id))\n .filter(({ text }) => text.toLowerCase().includes(q.toLowerCase()));\n\n return results[0];\n};\n\nexport const deleteNote = () => {\n const confirmation = confirm(\"Are you sure you want do that?\");\n if (confirmation) {\n const note = getNote();\n resetNoteManager();\n if (note && note.id) {\n deleteFileOnGist(note.id);\n markNoteForDeletion(note.id);\n }\n }\n commander.hide();\n};\n", "import storage from \"./localstorage\";\n\nexport const isUserLoggedIn = () => {\n return !!storage.get(\"authToken\");\n};\n", "import { isElement } from \"../../../utils/dom\";\n\nexport const command = (\n { title, secondary, onclick, onSecondaryClick, icon },\n selected = false\n) => {\n const li = document.createElement(\"LI\");\n li.className = selected ? \"selected\" : \"\";\n if (icon) {\n const iconClone = icon.cloneNode(true);\n li.appendChild(iconClone);\n }\n const liContent = isElement(title) ? title : document.createTextNode(title);\n liContent.onclick = onclick;\n li.appendChild(liContent);\n\n const span = document.createElement(\"span\");\n if (secondary) {\n span.className = \"secondary\";\n const secondaryElement = isElement(secondary)\n ? secondary\n : document.createTextNode(secondary);\n secondaryElement.onclick = onSecondaryClick;\n span.appendChild(secondaryElement);\n }\n li.appendChild(span);\n\n return li;\n};\n", "import { command } from \"./command\";\n\nexport const commands = (commandsToGen, selectedIndex) =>\n commandsToGen.map((props, i) => {\n const li = command(props, i === selectedIndex);\n return li;\n });\n", "export const wordParts = (word, match) => {\n const parts = word.toLowerCase().split(match);\n\n let indexInWord = 0;\n return parts\n .reduce((acc, part, i) => {\n return [...acc, ...(i === 0 ? [part] : [match, part])];\n }, [])\n .filter((p) => p !== \"\")\n .map((syllable) => {\n indexInWord = indexInWord + syllable.length;\n const start = indexInWord - syllable.length;\n const end = start + syllable.length;\n const originalSyllable = word.slice(start, end);\n return originalSyllable;\n });\n};\n", "import { wordParts } from \"./wordParts\";\n\nconst mark = (word) => {\n const markEl = document.createElement(\"mark\");\n markEl.appendChild(document.createTextNode(word));\n return markEl;\n};\n\nexport const div = ({ content = \"\", highlight = \"\" }) => {\n const div = document.createElement(\"div\");\n const words = content.split(\" \");\n const wordsToHighlight = highlight.toLowerCase().split(\" \");\n if (highlight.trim() === \"\") {\n div.appendChild(document.createTextNode(content));\n return div;\n }\n words\n .map((word) => {\n const matches = wordsToHighlight\n .map((wordToHighlight) => {\n return word.toLocaleLowerCase().includes(wordToHighlight)\n ? wordToHighlight\n : undefined;\n })\n .filter((m) => m !== undefined);\n\n return {\n word: word,\n matches: matches,\n };\n })\n .forEach(({ word, matches }) => {\n if (matches.length > 0) {\n const match = matches[0];\n if (word === match) {\n div.appendChild(mark(` ${word}`));\n } else {\n const parts = wordParts(word, match);\n const wordElements = parts.map((syllable) =>\n syllable.toLowerCase() === match\n ? mark(syllable)\n : document.createTextNode(syllable)\n );\n div.appendChild(document.createTextNode(\" \"));\n wordElements.forEach((w) => {\n div.appendChild(w);\n });\n }\n } else {\n div.appendChild(document.createTextNode(` ${word} `));\n }\n });\n return div;\n};\n", "import {\n getGist,\n getAuthToken,\n getAuthenticatedUsersGists,\n createNewGist,\n} from \"./api\";\nimport storage from \"../localstorage\";\nimport { url } from \"../urlManager\";\nimport select from \"../dom\";\nimport { configuration } from \"../../../configuration\";\nimport { updateNote } from \"../../components/organisms/noteManager/noteManager\";\nimport notify from \"../../components/molecules/notify\";\nimport { commands } from \"../../components/molecules/commands\";\nimport commander from \"../../components/organisms/commander/commander\";\nimport { div } from \"../../components/atoms/div/div\";\n\nexport const goAuthenticate = async () => {\n notify.info(\"You need to be authenticated!\");\n commander.hide();\n return window.location.replace(\n `https://github.com/login/oauth/authorize?client_id=${configuration.github.client_id}&scope=gist&state=${configuration.github.request_state}`\n );\n};\n\nexport const setGistToSyncWith = async (token) => {\n notify.info(\"Downloading my Gists!\");\n const gists = await getAuthenticatedUsersGists(token);\n commander.setState({\n mode: commander.getModes().gists,\n });\n\n notify.info(\"Select Gist to sync with\");\n const gistOptions = gists\n .sort(\n (a, b) =>\n new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()\n )\n .map(({ description, updated_at, id }) => ({\n title: div({ content: `${description}(${id})` }),\n secondary: updated_at,\n onclick: async () => {\n await storage.set(\"gistId\", id);\n notify.success(`${description}(${id}) selected for synchronization!`);\n syncNotesWithGitHub();\n commander.hide();\n },\n }));\n\n const gistOptionComponents = commands([\n {\n title: \"Create a new Gist\",\n onclick: async () => {\n notify.info(\"Syncing your MiroPads to a new Gist\");\n try {\n const { id } = await createNewGist();\n storage.set(\"gistId\", id);\n notify.success(\"MiroPads synced to a new Gist \uD83C\uDF89\");\n } catch (error) {\n notify.error(error.message);\n }\n commander.hide();\n },\n },\n ...gistOptions,\n ]);\n select(\"#commands\").html(\"\");\n select(\"#commands\").append(gistOptionComponents);\n};\n\nexport const syncNotesWithGitHub = async (gistId = storage.get(\"gistId\")) => {\n const authToken = storage.get(\"authToken\");\n if (authToken && gistId) {\n select(\"#logo\").addClass(\"loading\");\n const { files } = await getGist(gistId);\n Object.values(files).forEach(({ content }) => {\n updateNote(content);\n });\n storage.set(\"lastSync\", new Date());\n notify.success(\"\u2B07 MiroPad synced \u2705\");\n select(\"#logo\").removeClass(\"loading\");\n }\n};\n\nexport const setAuthTokenFromCallback = async () => {\n const code = url.getSearchParam(\"code\");\n const state = url.getSearchParam(\"state\");\n if (code && state) {\n select(\"#logo\").addClass(\"loading\");\n notify.info(\"\uD83D\uDD10 Authenticating...\");\n try {\n const { token } = await getAuthToken(code, state);\n storage.set(\"authToken\", token);\n notify.info(\"\u26F3 You have been authenticated!\");\n url.deleteParam([\"code\", \"state\"]);\n } catch (error) {\n notify.error(error.message);\n }\n select(\"#logo\").removeClass(\"loading\");\n }\n};\n", "import notify from \"../../components/molecules/notify\";\n\nconst getNewFileHandle = async (title = \"no-titled\") => {\n const options = {\n suggestedName: `${title}`,\n types: [\n {\n description: \"MiroPad text notes\",\n accept: {\n \"text/plain\": [\".miropad\"],\n },\n },\n ],\n };\n\n const handle = await window.showSaveFilePicker(options);\n return handle;\n};\n\nexport const writeFile = async (fileHandle, contents: string) => {\n // Create a FileSystemWritableFileStream to write to.\n const writable = await fileHandle.createWritable();\n // Write the contents of the file to the stream.\n await writable.write(contents);\n // Close the file and write the contents to disk.\n await writable.close();\n};\n\n/**\n * Saves a new file to disk.\n */\nexport const saveFileAs = async (contents: string, title?: string) => {\n try {\n const fileHandle = await getNewFileHandle(title);\n await writeFile(fileHandle, contents);\n } catch (ex) {\n const msg = \"An error occurred trying to save the file.\";\n notify.error(msg);\n return;\n }\n};\n\nexport const saveDataToFile = (() => {\n const a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style = \"display: none\";\n return (data, fileName = `MiroPad-${new Date().toISOString()}.json`) => {\n const json = JSON.stringify(data),\n blob = new Blob([json], { type: \"octet/stream\" }),\n url = window.URL.createObjectURL(blob);\n a.href = url;\n a.download = fileName;\n a.click();\n window.URL.revokeObjectURL(url);\n };\n})();\n", "import showdown from \"showdown\";\n\nconst converter = new showdown.Converter({\n tasklists: true,\n underline: true,\n emoji: true,\n simplifiedAutoLink: true,\n tables: true,\n openLinksInNewWindow: true,\n});\n\nconverter.setFlavor(\"github\");\n\nexport const convertMarkDownToHtml = (md) => converter.makeHtml(md);\n", "import storage from \"./localstorage\";\nimport notify from \"../components/molecules/notify\";\nimport { configuration } from \"../../configuration\";\nimport { getTitle } from \"../components/organisms/noteManager/noteManager\";\nimport { convertMarkDownToHtml } from \"../components/organisms/markdown/mdToHtml\";\n\nexport const handleErrorResponse = (response) => {\n const isSuccessfulRequest = response.status.toString().slice(0, 1) === \"2\";\n if (isSuccessfulRequest) return response;\n else throw new Error(response);\n};\n\nconst wrapTemplate = (body = \"\") => {\n return `\n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n\n \n
    \n
    \n `;\n};\n\nconst sendMail = async (body, email, subject = \"MiroPad note\") => {\n if (!body) {\n notify.error(\"\uD83D\uDC7B No message to send, type something and try again! \uD83E\uDD13\");\n return undefined;\n }\n try {\n await fetch(`${configuration.mail_service.api}`, {\n method: \"POST\",\n headers: {\n \"x-secret-token\": storage.get(\"MIROPAD_SECRET_TOKEN\"),\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n to: email,\n subject,\n html: wrapTemplate(body),\n }),\n })\n .then(handleErrorResponse)\n .then((response) => response.json());\n\n notify.success(\"Email sent \uD83D\uDE80\");\n } catch (error) {\n notify.error(\n \"Error not went through \uD83D\uDCA5! Check your credentials and try again!\"\n );\n }\n};\n\nconst getUserMailingPreferences = () => {\n const savedMail = storage.get(\"mail\");\n if (savedMail) {\n const mailSameAgainQuestion = window.prompt(\n `Mail ${savedMail} again? (y)es/(no)`,\n \"yeap\"\n );\n if (mailSameAgainQuestion === null) {\n return mailSameAgainQuestion;\n }\n if (mailSameAgainQuestion.slice(0, 1).toLowerCase() === \"y\") {\n return savedMail;\n }\n }\n const whoMailing = window.prompt(\"Where do you wanna send the mail to?\");\n const wannaSaveDat = window.prompt(\n \"Do you wanna save that to your preferences for later on? (y)es/(no)\",\n \"yeap\"\n );\n if (wannaSaveDat && wannaSaveDat.slice(0, 1).toLowerCase() === \"y\") {\n storage.set(\"mail\", whoMailing);\n }\n return whoMailing;\n};\n\nconst mailTo = (what) => {\n const email = getUserMailingPreferences();\n if (email === null) {\n notify.info(\"Sending mail cancelled \uD83D\uDE36\");\n return undefined;\n }\n\n notify.info(\"Sending mail... \uD83D\uDE80\");\n const title = getTitle(what);\n const htmlBody = convertMarkDownToHtml(what);\n\n sendMail(htmlBody, email, title);\n};\n\nexport { mailTo };\n", "import notify from \"../components/molecules/notify\";\n\nexport const copyToClipboard = async (\n what,\n message = \"\uD83D\uDCCB Copied to clipboard\"\n) => {\n try {\n await navigator.clipboard.writeText(what);\n notify.success(message);\n } catch (error) {\n notify.error(error.message);\n }\n};\n", "import { isArray } from \"../../../utils/isArray\";\n\nexport const button = (els, fn, id) => {\n const elements = isArray(els) ? els : [els];\n const button = document.createElement(\"button\");\n button.setAttribute(\"type\", \"button\");\n if (id) {\n button.setAttribute(\"id\", id);\n }\n elements.forEach((element) => {\n if (typeof element === \"string\") {\n button.appendChild(document.createTextNode(element));\n } else {\n button.appendChild(element);\n }\n });\n button.onclick = (e) => fn(e);\n\n return button;\n};\n", "import select from \"../../../utils/dom\";\nimport { url } from \"../../../utils/urlManager\";\nimport { copyToClipboard } from \"../../../utils/copyToClipboard\";\nimport { button } from \"../../atoms/button/button\";\nimport { convertMarkDownToHtml } from \"./mdToHtml\";\nimport storage from \"../../../utils/localstorage\";\n\nconst markDownViewer = (() => {\n return {\n view: select(\".preview\"),\n init: function () {\n this.update();\n select(\".terminal\").listen(\"input\", () => this.update());\n const isVisible = Boolean(url.getSearchParam(\"md\"));\n if (isVisible) {\n this.view.show();\n } else {\n this.view.hide();\n }\n return this;\n },\n autoLink: function () {\n const autoLinks = storage.parse(\"__auto-links__\");\n const replacingPatterns = Object.keys(autoLinks).join(\"|\");\n // Regular expression to match text starting with the given patterns\n const regex = new RegExp(`\\\\b(${replacingPatterns})\\\\d+\\\\b(?=\\\\s)`, \"g\");\n const updatedHTML = this.view.el.innerHTML.replace(regex, (match) => {\n const matchingKey = Object.keys(autoLinks).find((link) =>\n match.startsWith(link)\n );\n const link = autoLinks[matchingKey];\n return `${match}`;\n });\n // Replace each matching text with a link\n this.view.innerHTML(updatedHTML);\n },\n update: async function () {\n const md = select(\".terminal\").getValue();\n\n this.view.innerHTML(convertMarkDownToHtml(md));\n\n this.autoLink();\n\n const { elements } = select(\"pre\");\n Array.prototype.slice.call(elements).forEach((el) => {\n const copyBtn = button(\"\uD83D\uDCCB Copy\", async (e) => {\n e.stopPropagation();\n const codeToCopy = e.srcElement.previousSibling.innerHTML;\n await copyToClipboard(codeToCopy, \"\uD83D\uDCCB Code copied to clipboard\");\n });\n el.appendChild(copyBtn);\n });\n\n select(\"code\").listenAll(\"click\", async ({ innerHTML }) => {\n const result = eval(innerHTML);\n select(\".console\").show().innerHTML(result);\n });\n select(\".console\").listen(\"click\", async (e) => {\n e.srcElement.classList.add(\"hidden\");\n const codeToCopy = e.srcElement.innerHTML;\n await copyToClipboard(codeToCopy, \"\uD83D\uDCCB Code copied to clipboard\");\n });\n },\n show: function (mode = true) {\n this.view.show();\n url.set(undefined, {\n md: mode,\n });\n },\n hide: function () {\n this.view.hide();\n url.deleteParam(\"md\");\n },\n toggle: function (mode = \"true\") {\n if (url.getSearchParam(\"md\") === mode) {\n this.hide();\n } else {\n this.show(mode);\n }\n return this;\n },\n };\n})();\n\nexport default markDownViewer;\n", "import isJSON from \"./isJSON\";\nimport notify from \"../components/molecules/notify\";\n\nconst prettifyJSON = (selector) => {\n const el = document.querySelector(selector);\n if (isJSON(el.value)) {\n const prettifiedJSON = JSON.stringify(JSON.parse(el.value), null, 2);\n el.value = prettifiedJSON;\n notify.success(\"\uD83D\uDC4D JSON value prettified\");\n } else {\n notify.error(\"\uD83D\uDE27 Value is not in valid JSON format\");\n }\n};\n\nexport default prettifyJSON;\n", "export const sleep = (ms = 1000) =>\n new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n", "export const icon = (svgIcon, altText, className) => {\n const image = document.createElement(\"IMG\");\n\n if (className) image.classList.add(className);\n if (altText) image.setAttribute(\"alt\", altText);\n image.setAttribute(\"src\", svgIcon);\n return image;\n};\n", "import notify from \"../components/molecules/notify\";\nimport { getNote } from \"../components/organisms/noteManager/noteManager\";\nimport { url } from \"./urlManager\";\n\nexport const share = async () => {\n try {\n const note = getNote();\n const currentUrl = url.get();\n await navigator.share({\n title: note ? note.title : TITLE_NAME,\n text: note ? note.text : \"Temporary note keeping app for the browser\",\n url: currentUrl,\n });\n } catch (error) {\n notify.info(`${error.message}`);\n }\n};\n", "/**\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 mergeOpts from 'merge-options'\nimport { isTest } from 'ipfs-utils/src/env.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport * as dagPB from '@ipld/dag-pb'\nimport * as dagCBOR from '@ipld/dag-cbor'\nimport * as dagJSON from '@ipld/dag-json'\nimport * as dagJOSE from 'dag-jose'\nimport { identity } from 'multiformats/hashes/identity'\nimport { bases, hashes, codecs } from 'multiformats/basics'\nimport { initAssets } from 'ipfs-core-config/init-assets'\nimport { AlreadyInitializedError } from '../errors.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { createStart } from './start.js'\n\nimport { createStop } from './stop.js'\nimport { createDns } from './dns.js'\nimport { createIsOnline } from './is-online.js'\nimport { createResolve } from './resolve.js'\nimport { PinAPI } from './pin/index.js'\nimport { IPNSAPI } from './ipns.js'\nimport { NameAPI } from './name/index.js'\nimport { createRefs } from './refs/index.js'\nimport { createLocal } from './refs/local.js'\nimport { BitswapAPI } from './bitswap/index.js'\nimport { BootstrapAPI } from './bootstrap/index.js'\nimport { BlockAPI } from './block/index.js'\nimport { RootAPI } from './root.js'\nimport { createVersion } from './version.js'\nimport { createId } from './id.js'\nimport { createConfig } from './config/index.js'\nimport { DagAPI } from './dag/index.js'\nimport { createPreloader } from '../preload.js'\nimport { createMfsPreloader } from '../mfs-preload.js'\nimport { createFiles } from './files/index.js'\nimport { KeyAPI } from './key/index.js'\nimport { ObjectAPI } from './object/index.js'\nimport { RepoAPI } from './repo/index.js'\nimport { StatsAPI } from './stats/index.js'\nimport { Storage } from './storage.js'\nimport { Network } from './network.js'\nimport { Service } from '../utils/service.js'\nimport { SwarmAPI } from './swarm/index.js'\nimport { createPing } from './ping.js'\nimport { createDht } from './dht.js'\nimport { createPubsub } from './pubsub.js'\nimport { Multicodecs } from 'ipfs-core-utils/multicodecs'\nimport { Multihashes } from 'ipfs-core-utils/multihashes'\nimport { Multibases } from 'ipfs-core-utils/multibases'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs')\n\nconst IPNS_INIT_KEYSPACE_TIMEOUT = 30000\n\n/**\n * @typedef {import('../types').Options} Options\n * @typedef {import('../types').Print} Print\n * @typedef {import('./storage')} StorageAPI\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('multiformats/bases/interface').MultibaseCodec} MultibaseCodec\n */\n\nclass IPFS {\n /**\n * @param {object} config\n * @param {Print} config.print\n * @param {Storage} config.storage\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {Options} config.options\n */\n constructor ({ print, storage, codecs, options }) {\n const { peerId, repo, keychain } = storage\n const network = Service.create(Network)\n\n const preload = createPreloader(options.preload)\n\n const dns = createDns()\n const isOnline = createIsOnline({ network })\n // @ts-expect-error This type check fails as options.\n // libp2p can be a function, while IPNS router config expects libp2p config\n const ipns = new IPNSAPI(options)\n\n /** @type {MultihashHasher[]} */\n const multihashHashers = Object.values(hashes);\n\n (options.ipld && options.ipld.hashers ? options.ipld.hashers : []).forEach(hasher => multihashHashers.push(hasher))\n\n this.hashers = new Multihashes({\n hashers: multihashHashers,\n loadHasher: options.ipld && options.ipld.loadHasher\n })\n\n /** @type {MultibaseCodec[]} */\n const multibaseCodecs = Object.values(bases);\n\n (options.ipld && options.ipld.bases ? options.ipld.bases : []).forEach(base => multibaseCodecs.push(base))\n\n this.bases = new Multibases({\n bases: multibaseCodecs,\n loadBase: options.ipld && options.ipld.loadBase\n })\n\n const pin = new PinAPI({ repo, codecs })\n const block = new BlockAPI({ codecs, hashers: this.hashers, preload, repo })\n\n const name = new NameAPI({\n dns,\n ipns,\n repo,\n codecs,\n peerId,\n isOnline,\n keychain,\n options\n })\n\n const resolve = createResolve({ repo, codecs, bases: this.bases, name })\n\n const dag = new DagAPI({ repo, codecs, hashers: this.hashers, preload })\n const refs = Object.assign(createRefs({ repo, codecs, resolve, preload }), {\n local: createLocal({ repo: storage.repo })\n })\n const { add, addAll, cat, get, ls } = new RootAPI({\n preload,\n repo,\n options: options.EXPERIMENTAL,\n hashers: this.hashers\n })\n\n const files = createFiles({\n repo,\n preload,\n hashers: this.hashers,\n options\n })\n\n const mfsPreload = createMfsPreloader({\n files,\n preload,\n options: options.preload\n })\n\n this.preload = preload\n this.name = name\n this.ipns = ipns\n this.pin = pin\n this.resolve = resolve\n this.block = block\n this.refs = refs\n\n this.start = createStart({\n network,\n peerId,\n repo,\n preload,\n ipns,\n mfsPreload,\n print,\n keychain,\n hashers: this.hashers,\n options\n })\n\n this.stop = createStop({\n network,\n preload,\n mfsPreload,\n ipns,\n repo\n })\n\n this.dht = createDht({ network, repo, peerId })\n this.pubsub = createPubsub({ network, config: options.config })\n this.dns = dns\n this.isOnline = isOnline\n this.id = createId({ network, peerId })\n this.version = createVersion({ repo })\n this.bitswap = new BitswapAPI({ network })\n this.bootstrap = new BootstrapAPI({ repo })\n this.config = createConfig({ repo })\n this.ping = createPing({ network })\n\n this.add = add\n this.addAll = addAll\n this.cat = cat\n this.get = get\n this.ls = ls\n\n this.dag = dag\n this.files = files\n this.key = new KeyAPI({ keychain })\n this.object = new ObjectAPI({ preload, codecs, repo })\n this.repo = new RepoAPI({ repo, hashers: this.hashers })\n this.stats = new StatsAPI({ repo, network })\n this.swarm = new SwarmAPI({ network })\n\n // For the backwards compatibility\n Object.defineProperty(this, 'libp2p', {\n get () {\n const net = network.try()\n return net ? net.libp2p : undefined\n }\n })\n\n // unimplemented methods\n const notImplemented = () => Promise.reject(errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED'))\n const notImplementedIter = async function * () { throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED') } // eslint-disable-line require-yield\n this.commands = notImplemented\n this.diag = {\n cmds: notImplemented,\n net: notImplemented,\n sys: notImplemented\n }\n this.log = {\n level: notImplemented,\n ls: notImplemented,\n tail: notImplementedIter\n }\n this.mount = notImplemented\n\n this.codecs = codecs\n }\n\n /**\n * `IPFS.create` will do the initialization. Keep this around for backwards\n * compatibility.\n *\n * @deprecated\n */\n async init () { // eslint-disable-line require-await\n throw new AlreadyInitializedError()\n }\n}\n\n/**\n * @param {IPFS} ipfs\n */\nconst addEmptyDir = async (ipfs) => {\n const buf = dagPB.encode({\n Data: new UnixFS({ type: 'directory' }).marshal(),\n Links: []\n })\n\n const cid = await ipfs.block.put(buf, {\n mhtype: 'sha2-256',\n format: 'dag-pb'\n })\n\n await ipfs.pin.add(cid)\n\n return cid\n}\n\n/**\n * @returns {Options}\n */\nconst getDefaultOptions = () => ({\n start: true,\n EXPERIMENTAL: {},\n preload: {\n enabled: !isTest, // preload by default, unless in test env\n addresses: [\n '/dns4/node0.preload.ipfs.io/https',\n '/dns4/node1.preload.ipfs.io/https',\n '/dns4/node2.preload.ipfs.io/https',\n '/dns4/node3.preload.ipfs.io/https'\n ]\n }\n})\n\n/**\n * @param {Options} options\n */\nexport async function create (options = {}) {\n options = mergeOptions(getDefaultOptions(), options)\n const initOptions = options.init || {}\n\n /**\n * @type {BlockCodec}\n */\n const id = {\n name: identity.name,\n code: identity.code,\n encode: (id) => id,\n decode: (id) => id\n }\n\n /** @type {BlockCodec[]} */\n const blockCodecs = Object.values(codecs);\n\n [dagPB, dagCBOR, dagJSON, dagJOSE, id].concat((options.ipld && options.ipld.codecs) || []).forEach(codec => blockCodecs.push(codec))\n\n const multicodecs = new Multicodecs({\n codecs: blockCodecs,\n loadCodec: options.ipld && options.ipld.loadCodec\n })\n\n // eslint-disable-next-line no-console\n const print = options.silent ? log : console.log\n\n log('creating repo')\n const storage = await Storage.start(print, multicodecs, options)\n\n log('getting repo config')\n const config = await storage.repo.config.getAll()\n\n const ipfs = new IPFS({\n storage,\n print,\n codecs: multicodecs,\n options: { ...options, config }\n })\n\n log('starting preload')\n await ipfs.preload.start()\n\n log('starting storage')\n ipfs.ipns.startOffline(storage)\n\n if (storage.isNew && !initOptions.emptyRepo) {\n // add empty unixfs dir object (go-ipfs assumes this exists)\n const cid = await addEmptyDir(ipfs)\n\n log('adding default assets')\n await initAssets({ addAll: ipfs.addAll, print })\n\n log('initializing IPNS keyspace')\n\n if (storage.peerId.publicKey == null) {\n throw errCode(new Error('Public key missing'), 'ERR_MISSING_PUBLIC_KEY')\n }\n\n const timeoutController = new TimeoutController(IPNS_INIT_KEYSPACE_TIMEOUT)\n try {\n await ipfs.ipns.initializeKeyspace(storage.peerId, uint8ArrayFromString(`/ipfs/${cid}`), {\n signal: timeoutController.signal\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n if (options.start !== false) {\n log('starting node')\n await ipfs.start()\n }\n\n return ipfs\n}\n", "import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\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\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "import errcode from 'err-code'\nimport * as Pb from './unixfs.js'\nconst PBData = Pb.Data\n\n/**\n * @typedef {import('./types').Mtime} Mtime\n * @typedef {import('./types').MtimeLike} MtimeLike\n */\n\nconst types = [\n 'raw',\n 'directory',\n 'file',\n 'metadata',\n 'symlink',\n 'hamt-sharded-directory'\n]\n\nconst dirTypes = [\n 'directory',\n 'hamt-sharded-directory'\n]\n\nconst DEFAULT_FILE_MODE = parseInt('0644', 8)\nconst DEFAULT_DIRECTORY_MODE = parseInt('0755', 8)\n\n/**\n * @param {string | number | undefined} [mode]\n */\nexport function parseMode (mode) {\n if (mode == null) {\n return undefined\n }\n\n if (typeof mode === 'number') {\n return mode & 0xFFF\n }\n\n mode = mode.toString()\n\n if (mode.substring(0, 1) === '0') {\n // octal string\n return parseInt(mode, 8) & 0xFFF\n }\n\n // decimal string\n return parseInt(mode, 10) & 0xFFF\n}\n\n/**\n * @param {any} input\n */\nexport function parseMtime (input) {\n if (input == null) {\n return undefined\n }\n\n /** @type {Mtime | undefined} */\n let mtime\n\n // { secs, nsecs }\n if (input.secs != null) {\n mtime = {\n secs: input.secs,\n nsecs: input.nsecs\n }\n }\n\n // UnixFS TimeSpec\n if (input.Seconds != null) {\n mtime = {\n secs: input.Seconds,\n nsecs: input.FractionalNanoseconds\n }\n }\n\n // process.hrtime()\n if (Array.isArray(input)) {\n mtime = {\n secs: input[0],\n nsecs: input[1]\n }\n }\n\n // Javascript Date\n if (input instanceof Date) {\n const ms = input.getTime()\n const secs = Math.floor(ms / 1000)\n\n mtime = {\n secs: secs,\n nsecs: (ms - (secs * 1000)) * 1000\n }\n }\n\n /*\n TODO: https://github.com/ipfs/aegir/issues/487\n\n // process.hrtime.bigint()\n if (input instanceof BigInt) {\n const secs = input / BigInt(1e9)\n const nsecs = input - (secs * BigInt(1e9))\n\n mtime = {\n secs: parseInt(secs.toString()),\n nsecs: parseInt(nsecs.toString())\n }\n }\n */\n\n if (!Object.prototype.hasOwnProperty.call(mtime, 'secs')) {\n return undefined\n }\n\n if (mtime != null && mtime.nsecs != null && (mtime.nsecs < 0 || mtime.nsecs > 999999999)) {\n throw errcode(new Error('mtime-nsecs must be within the range [0,999999999]'), 'ERR_INVALID_MTIME_NSECS')\n }\n\n return mtime\n}\n\nclass UnixFS {\n /**\n * Decode from protobuf https://github.com/ipfs/specs/blob/master/UNIXFS.md\n *\n * @param {Uint8Array} marshaled\n */\n static unmarshal (marshaled) {\n const message = PBData.decode(marshaled)\n const decoded = PBData.toObject(message, {\n defaults: false,\n arrays: true,\n longs: Number,\n objects: false\n })\n\n const data = new UnixFS({\n type: types[decoded.Type],\n data: decoded.Data,\n blockSizes: decoded.blocksizes,\n mode: decoded.mode,\n mtime: decoded.mtime\n ? {\n secs: decoded.mtime.Seconds,\n nsecs: decoded.mtime.FractionalNanoseconds\n }\n : undefined\n })\n\n // make sure we honour the original mode\n data._originalMode = decoded.mode || 0\n\n return data\n }\n\n /**\n * @param {object} [options]\n * @param {string} [options.type='file']\n * @param {Uint8Array} [options.data]\n * @param {number[]} [options.blockSizes]\n * @param {number} [options.hashType]\n * @param {number} [options.fanout]\n * @param {MtimeLike | null} [options.mtime]\n * @param {number | string} [options.mode]\n */\n constructor (options = {\n type: 'file'\n }) {\n const {\n type,\n data,\n blockSizes,\n hashType,\n fanout,\n mtime,\n mode\n } = options\n\n if (type && !types.includes(type)) {\n throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE')\n }\n\n this.type = type || 'file'\n this.data = data\n this.hashType = hashType\n this.fanout = fanout\n\n /** @type {number[]} */\n this.blockSizes = blockSizes || []\n this._originalMode = 0\n this.mode = parseMode(mode)\n\n if (mtime) {\n this.mtime = parseMtime(mtime)\n\n if (this.mtime && !this.mtime.nsecs) {\n this.mtime.nsecs = 0\n }\n }\n }\n\n /**\n * @param {number | undefined} mode\n */\n set mode (mode) {\n this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE\n\n const parsedMode = parseMode(mode)\n\n if (parsedMode !== undefined) {\n this._mode = parsedMode\n }\n }\n\n /**\n * @returns {number | undefined}\n */\n get mode () {\n return this._mode\n }\n\n isDirectory () {\n return Boolean(this.type && dirTypes.includes(this.type))\n }\n\n /**\n * @param {number} size\n */\n addBlockSize (size) {\n this.blockSizes.push(size)\n }\n\n /**\n * @param {number} index\n */\n removeBlockSize (index) {\n this.blockSizes.splice(index, 1)\n }\n\n /**\n * Returns `0` for directories or `data.length + sum(blockSizes)` for everything else\n */\n fileSize () {\n if (this.isDirectory()) {\n // dirs don't have file size\n return 0\n }\n\n let sum = 0\n this.blockSizes.forEach((size) => {\n sum += size\n })\n\n if (this.data) {\n sum += this.data.length\n }\n\n return sum\n }\n\n /**\n * encode to protobuf Uint8Array\n */\n marshal () {\n let type\n\n switch (this.type) {\n case 'raw': type = PBData.DataType.Raw; break\n case 'directory': type = PBData.DataType.Directory; break\n case 'file': type = PBData.DataType.File; break\n case 'metadata': type = PBData.DataType.Metadata; break\n case 'symlink': type = PBData.DataType.Symlink; break\n case 'hamt-sharded-directory': type = PBData.DataType.HAMTShard; break\n default:\n throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE')\n }\n\n let data = this.data\n\n if (!this.data || !this.data.length) {\n data = undefined\n }\n\n let mode\n\n if (this.mode != null) {\n mode = (this._originalMode & 0xFFFFF000) | (parseMode(this.mode) || 0)\n\n if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) {\n mode = undefined\n }\n\n if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) {\n mode = undefined\n }\n }\n\n let mtime\n\n if (this.mtime != null) {\n const parsed = parseMtime(this.mtime)\n\n if (parsed) {\n mtime = {\n Seconds: parsed.secs,\n FractionalNanoseconds: parsed.nsecs\n }\n\n if (mtime.FractionalNanoseconds === 0) {\n delete mtime.FractionalNanoseconds\n }\n }\n }\n\n const pbData = {\n Type: type,\n Data: data,\n filesize: this.isDirectory() ? undefined : this.fileSize(),\n blocksizes: this.blockSizes,\n hashType: this.hashType,\n fanout: this.fanout,\n mode,\n mtime\n }\n\n return PBData.encode(pbData).finish()\n }\n}\n\nexport { UnixFS }\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"ipfs-unixfs\"] || ($protobuf.roots[\"ipfs-unixfs\"] = {});\n\nexport const Data = $root.Data = (() => {\n\n /**\n * Properties of a Data.\n * @exports IData\n * @interface IData\n * @property {Data.DataType} Type Data Type\n * @property {Uint8Array|null} [Data] Data Data\n * @property {number|null} [filesize] Data filesize\n * @property {Array.|null} [blocksizes] Data blocksizes\n * @property {number|null} [hashType] Data hashType\n * @property {number|null} [fanout] Data fanout\n * @property {number|null} [mode] Data mode\n * @property {IUnixTime|null} [mtime] Data mtime\n */\n\n /**\n * Constructs a new Data.\n * @exports Data\n * @classdesc Represents a Data.\n * @implements IData\n * @constructor\n * @param {IData=} [p] Properties to set\n */\n function Data(p) {\n this.blocksizes = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Data Type.\n * @member {Data.DataType} Type\n * @memberof Data\n * @instance\n */\n Data.prototype.Type = 0;\n\n /**\n * Data Data.\n * @member {Uint8Array} Data\n * @memberof Data\n * @instance\n */\n Data.prototype.Data = $util.newBuffer([]);\n\n /**\n * Data filesize.\n * @member {number} filesize\n * @memberof Data\n * @instance\n */\n Data.prototype.filesize = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data blocksizes.\n * @member {Array.} blocksizes\n * @memberof Data\n * @instance\n */\n Data.prototype.blocksizes = $util.emptyArray;\n\n /**\n * Data hashType.\n * @member {number} hashType\n * @memberof Data\n * @instance\n */\n Data.prototype.hashType = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data fanout.\n * @member {number} fanout\n * @memberof Data\n * @instance\n */\n Data.prototype.fanout = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data mode.\n * @member {number} mode\n * @memberof Data\n * @instance\n */\n Data.prototype.mode = 0;\n\n /**\n * Data mtime.\n * @member {IUnixTime|null|undefined} mtime\n * @memberof Data\n * @instance\n */\n Data.prototype.mtime = null;\n\n /**\n * Encodes the specified Data message. Does not implicitly {@link Data.verify|verify} messages.\n * @function encode\n * @memberof Data\n * @static\n * @param {IData} m Data message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Data.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n w.uint32(8).int32(m.Type);\n if (m.Data != null && Object.hasOwnProperty.call(m, \"Data\"))\n w.uint32(18).bytes(m.Data);\n if (m.filesize != null && Object.hasOwnProperty.call(m, \"filesize\"))\n w.uint32(24).uint64(m.filesize);\n if (m.blocksizes != null && m.blocksizes.length) {\n for (var i = 0; i < m.blocksizes.length; ++i)\n w.uint32(32).uint64(m.blocksizes[i]);\n }\n if (m.hashType != null && Object.hasOwnProperty.call(m, \"hashType\"))\n w.uint32(40).uint64(m.hashType);\n if (m.fanout != null && Object.hasOwnProperty.call(m, \"fanout\"))\n w.uint32(48).uint64(m.fanout);\n if (m.mode != null && Object.hasOwnProperty.call(m, \"mode\"))\n w.uint32(56).uint32(m.mode);\n if (m.mtime != null && Object.hasOwnProperty.call(m, \"mtime\"))\n $root.UnixTime.encode(m.mtime, w.uint32(66).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes a Data message from the specified reader or buffer.\n * @function decode\n * @memberof Data\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Data} Data\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Data.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Data();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.Type = r.int32();\n break;\n case 2:\n m.Data = r.bytes();\n break;\n case 3:\n m.filesize = r.uint64();\n break;\n case 4:\n if (!(m.blocksizes && m.blocksizes.length))\n m.blocksizes = [];\n if ((t & 7) === 2) {\n var c2 = r.uint32() + r.pos;\n while (r.pos < c2)\n m.blocksizes.push(r.uint64());\n } else\n m.blocksizes.push(r.uint64());\n break;\n case 5:\n m.hashType = r.uint64();\n break;\n case 6:\n m.fanout = r.uint64();\n break;\n case 7:\n m.mode = r.uint32();\n break;\n case 8:\n m.mtime = $root.UnixTime.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"Type\"))\n throw $util.ProtocolError(\"missing required 'Type'\", { instance: m });\n return m;\n };\n\n /**\n * Creates a Data message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Data\n * @static\n * @param {Object.} d Plain object\n * @returns {Data} Data\n */\n Data.fromObject = function fromObject(d) {\n if (d instanceof $root.Data)\n return d;\n var m = new $root.Data();\n switch (d.Type) {\n case \"Raw\":\n case 0:\n m.Type = 0;\n break;\n case \"Directory\":\n case 1:\n m.Type = 1;\n break;\n case \"File\":\n case 2:\n m.Type = 2;\n break;\n case \"Metadata\":\n case 3:\n m.Type = 3;\n break;\n case \"Symlink\":\n case 4:\n m.Type = 4;\n break;\n case \"HAMTShard\":\n case 5:\n m.Type = 5;\n break;\n }\n if (d.Data != null) {\n if (typeof d.Data === \"string\")\n $util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0);\n else if (d.Data.length)\n m.Data = d.Data;\n }\n if (d.filesize != null) {\n if ($util.Long)\n (m.filesize = $util.Long.fromValue(d.filesize)).unsigned = true;\n else if (typeof d.filesize === \"string\")\n m.filesize = parseInt(d.filesize, 10);\n else if (typeof d.filesize === \"number\")\n m.filesize = d.filesize;\n else if (typeof d.filesize === \"object\")\n m.filesize = new $util.LongBits(d.filesize.low >>> 0, d.filesize.high >>> 0).toNumber(true);\n }\n if (d.blocksizes) {\n if (!Array.isArray(d.blocksizes))\n throw TypeError(\".Data.blocksizes: array expected\");\n m.blocksizes = [];\n for (var i = 0; i < d.blocksizes.length; ++i) {\n if ($util.Long)\n (m.blocksizes[i] = $util.Long.fromValue(d.blocksizes[i])).unsigned = true;\n else if (typeof d.blocksizes[i] === \"string\")\n m.blocksizes[i] = parseInt(d.blocksizes[i], 10);\n else if (typeof d.blocksizes[i] === \"number\")\n m.blocksizes[i] = d.blocksizes[i];\n else if (typeof d.blocksizes[i] === \"object\")\n m.blocksizes[i] = new $util.LongBits(d.blocksizes[i].low >>> 0, d.blocksizes[i].high >>> 0).toNumber(true);\n }\n }\n if (d.hashType != null) {\n if ($util.Long)\n (m.hashType = $util.Long.fromValue(d.hashType)).unsigned = true;\n else if (typeof d.hashType === \"string\")\n m.hashType = parseInt(d.hashType, 10);\n else if (typeof d.hashType === \"number\")\n m.hashType = d.hashType;\n else if (typeof d.hashType === \"object\")\n m.hashType = new $util.LongBits(d.hashType.low >>> 0, d.hashType.high >>> 0).toNumber(true);\n }\n if (d.fanout != null) {\n if ($util.Long)\n (m.fanout = $util.Long.fromValue(d.fanout)).unsigned = true;\n else if (typeof d.fanout === \"string\")\n m.fanout = parseInt(d.fanout, 10);\n else if (typeof d.fanout === \"number\")\n m.fanout = d.fanout;\n else if (typeof d.fanout === \"object\")\n m.fanout = new $util.LongBits(d.fanout.low >>> 0, d.fanout.high >>> 0).toNumber(true);\n }\n if (d.mode != null) {\n m.mode = d.mode >>> 0;\n }\n if (d.mtime != null) {\n if (typeof d.mtime !== \"object\")\n throw TypeError(\".Data.mtime: object expected\");\n m.mtime = $root.UnixTime.fromObject(d.mtime);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Data message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Data\n * @static\n * @param {Data} m Data\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Data.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.blocksizes = [];\n }\n if (o.defaults) {\n d.Type = o.enums === String ? \"Raw\" : 0;\n if (o.bytes === String)\n d.Data = \"\";\n else {\n d.Data = [];\n if (o.bytes !== Array)\n d.Data = $util.newBuffer(d.Data);\n }\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.filesize = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.filesize = o.longs === String ? \"0\" : 0;\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.hashType = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.hashType = o.longs === String ? \"0\" : 0;\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.fanout = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.fanout = o.longs === String ? \"0\" : 0;\n d.mode = 0;\n d.mtime = null;\n }\n if (m.Type != null && m.hasOwnProperty(\"Type\")) {\n d.Type = o.enums === String ? $root.Data.DataType[m.Type] : m.Type;\n }\n if (m.Data != null && m.hasOwnProperty(\"Data\")) {\n d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data;\n }\n if (m.filesize != null && m.hasOwnProperty(\"filesize\")) {\n if (typeof m.filesize === \"number\")\n d.filesize = o.longs === String ? String(m.filesize) : m.filesize;\n else\n d.filesize = o.longs === String ? $util.Long.prototype.toString.call(m.filesize) : o.longs === Number ? new $util.LongBits(m.filesize.low >>> 0, m.filesize.high >>> 0).toNumber(true) : m.filesize;\n }\n if (m.blocksizes && m.blocksizes.length) {\n d.blocksizes = [];\n for (var j = 0; j < m.blocksizes.length; ++j) {\n if (typeof m.blocksizes[j] === \"number\")\n d.blocksizes[j] = o.longs === String ? String(m.blocksizes[j]) : m.blocksizes[j];\n else\n d.blocksizes[j] = o.longs === String ? $util.Long.prototype.toString.call(m.blocksizes[j]) : o.longs === Number ? new $util.LongBits(m.blocksizes[j].low >>> 0, m.blocksizes[j].high >>> 0).toNumber(true) : m.blocksizes[j];\n }\n }\n if (m.hashType != null && m.hasOwnProperty(\"hashType\")) {\n if (typeof m.hashType === \"number\")\n d.hashType = o.longs === String ? String(m.hashType) : m.hashType;\n else\n d.hashType = o.longs === String ? $util.Long.prototype.toString.call(m.hashType) : o.longs === Number ? new $util.LongBits(m.hashType.low >>> 0, m.hashType.high >>> 0).toNumber(true) : m.hashType;\n }\n if (m.fanout != null && m.hasOwnProperty(\"fanout\")) {\n if (typeof m.fanout === \"number\")\n d.fanout = o.longs === String ? String(m.fanout) : m.fanout;\n else\n d.fanout = o.longs === String ? $util.Long.prototype.toString.call(m.fanout) : o.longs === Number ? new $util.LongBits(m.fanout.low >>> 0, m.fanout.high >>> 0).toNumber(true) : m.fanout;\n }\n if (m.mode != null && m.hasOwnProperty(\"mode\")) {\n d.mode = m.mode;\n }\n if (m.mtime != null && m.hasOwnProperty(\"mtime\")) {\n d.mtime = $root.UnixTime.toObject(m.mtime, o);\n }\n return d;\n };\n\n /**\n * Converts this Data to JSON.\n * @function toJSON\n * @memberof Data\n * @instance\n * @returns {Object.} JSON object\n */\n Data.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * DataType enum.\n * @name Data.DataType\n * @enum {number}\n * @property {number} Raw=0 Raw value\n * @property {number} Directory=1 Directory value\n * @property {number} File=2 File value\n * @property {number} Metadata=3 Metadata value\n * @property {number} Symlink=4 Symlink value\n * @property {number} HAMTShard=5 HAMTShard value\n */\n Data.DataType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Raw\"] = 0;\n values[valuesById[1] = \"Directory\"] = 1;\n values[valuesById[2] = \"File\"] = 2;\n values[valuesById[3] = \"Metadata\"] = 3;\n values[valuesById[4] = \"Symlink\"] = 4;\n values[valuesById[5] = \"HAMTShard\"] = 5;\n return values;\n })();\n\n return Data;\n})();\n\nexport const UnixTime = $root.UnixTime = (() => {\n\n /**\n * Properties of an UnixTime.\n * @exports IUnixTime\n * @interface IUnixTime\n * @property {number} Seconds UnixTime Seconds\n * @property {number|null} [FractionalNanoseconds] UnixTime FractionalNanoseconds\n */\n\n /**\n * Constructs a new UnixTime.\n * @exports UnixTime\n * @classdesc Represents an UnixTime.\n * @implements IUnixTime\n * @constructor\n * @param {IUnixTime=} [p] Properties to set\n */\n function UnixTime(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * UnixTime Seconds.\n * @member {number} Seconds\n * @memberof UnixTime\n * @instance\n */\n UnixTime.prototype.Seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0;\n\n /**\n * UnixTime FractionalNanoseconds.\n * @member {number} FractionalNanoseconds\n * @memberof UnixTime\n * @instance\n */\n UnixTime.prototype.FractionalNanoseconds = 0;\n\n /**\n * Encodes the specified UnixTime message. Does not implicitly {@link UnixTime.verify|verify} messages.\n * @function encode\n * @memberof UnixTime\n * @static\n * @param {IUnixTime} m UnixTime message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n UnixTime.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n w.uint32(8).int64(m.Seconds);\n if (m.FractionalNanoseconds != null && Object.hasOwnProperty.call(m, \"FractionalNanoseconds\"))\n w.uint32(21).fixed32(m.FractionalNanoseconds);\n return w;\n };\n\n /**\n * Decodes an UnixTime message from the specified reader or buffer.\n * @function decode\n * @memberof UnixTime\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {UnixTime} UnixTime\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n UnixTime.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.UnixTime();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.Seconds = r.int64();\n break;\n case 2:\n m.FractionalNanoseconds = r.fixed32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"Seconds\"))\n throw $util.ProtocolError(\"missing required 'Seconds'\", { instance: m });\n return m;\n };\n\n /**\n * Creates an UnixTime message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof UnixTime\n * @static\n * @param {Object.} d Plain object\n * @returns {UnixTime} UnixTime\n */\n UnixTime.fromObject = function fromObject(d) {\n if (d instanceof $root.UnixTime)\n return d;\n var m = new $root.UnixTime();\n if (d.Seconds != null) {\n if ($util.Long)\n (m.Seconds = $util.Long.fromValue(d.Seconds)).unsigned = false;\n else if (typeof d.Seconds === \"string\")\n m.Seconds = parseInt(d.Seconds, 10);\n else if (typeof d.Seconds === \"number\")\n m.Seconds = d.Seconds;\n else if (typeof d.Seconds === \"object\")\n m.Seconds = new $util.LongBits(d.Seconds.low >>> 0, d.Seconds.high >>> 0).toNumber();\n }\n if (d.FractionalNanoseconds != null) {\n m.FractionalNanoseconds = d.FractionalNanoseconds >>> 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an UnixTime message. Also converts values to other types if specified.\n * @function toObject\n * @memberof UnixTime\n * @static\n * @param {UnixTime} m UnixTime\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n UnixTime.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if ($util.Long) {\n var n = new $util.Long(0, 0, false);\n d.Seconds = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.Seconds = o.longs === String ? \"0\" : 0;\n d.FractionalNanoseconds = 0;\n }\n if (m.Seconds != null && m.hasOwnProperty(\"Seconds\")) {\n if (typeof m.Seconds === \"number\")\n d.Seconds = o.longs === String ? String(m.Seconds) : m.Seconds;\n else\n d.Seconds = o.longs === String ? $util.Long.prototype.toString.call(m.Seconds) : o.longs === Number ? new $util.LongBits(m.Seconds.low >>> 0, m.Seconds.high >>> 0).toNumber() : m.Seconds;\n }\n if (m.FractionalNanoseconds != null && m.hasOwnProperty(\"FractionalNanoseconds\")) {\n d.FractionalNanoseconds = m.FractionalNanoseconds;\n }\n return d;\n };\n\n /**\n * Converts this UnixTime to JSON.\n * @function toJSON\n * @memberof UnixTime\n * @instance\n * @returns {Object.} JSON object\n */\n UnixTime.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return UnixTime;\n})();\n\nexport const Metadata = $root.Metadata = (() => {\n\n /**\n * Properties of a Metadata.\n * @exports IMetadata\n * @interface IMetadata\n * @property {string|null} [MimeType] Metadata MimeType\n */\n\n /**\n * Constructs a new Metadata.\n * @exports Metadata\n * @classdesc Represents a Metadata.\n * @implements IMetadata\n * @constructor\n * @param {IMetadata=} [p] Properties to set\n */\n function Metadata(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Metadata MimeType.\n * @member {string} MimeType\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.MimeType = \"\";\n\n /**\n * Encodes the specified Metadata message. Does not implicitly {@link Metadata.verify|verify} messages.\n * @function encode\n * @memberof Metadata\n * @static\n * @param {IMetadata} m Metadata message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Metadata.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.MimeType != null && Object.hasOwnProperty.call(m, \"MimeType\"))\n w.uint32(10).string(m.MimeType);\n return w;\n };\n\n /**\n * Decodes a Metadata message from the specified reader or buffer.\n * @function decode\n * @memberof Metadata\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Metadata} Metadata\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Metadata.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Metadata();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.MimeType = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Metadata message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Metadata\n * @static\n * @param {Object.} d Plain object\n * @returns {Metadata} Metadata\n */\n Metadata.fromObject = function fromObject(d) {\n if (d instanceof $root.Metadata)\n return d;\n var m = new $root.Metadata();\n if (d.MimeType != null) {\n m.MimeType = String(d.MimeType);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Metadata message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Metadata\n * @static\n * @param {Metadata} m Metadata\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Metadata.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.MimeType = \"\";\n }\n if (m.MimeType != null && m.hasOwnProperty(\"MimeType\")) {\n d.MimeType = m.MimeType;\n }\n return d;\n };\n\n /**\n * Converts this Metadata to JSON.\n * @function toJSON\n * @memberof Metadata\n * @instance\n * @returns {Object.} JSON object\n */\n Metadata.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Metadata;\n})();\n\nexport { $root as default };\n", "import { CID } from 'multiformats/cid'\nimport { decodeNode } from './pb-decode.js'\nimport { encodeNode } from './pb-encode.js'\nimport { prepare, validate, createNode, createLink, toByteView } from './util.js'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\n/**\n * @typedef {import('./interface.js').PBLink} PBLink\n * @typedef {import('./interface.js').PBNode} PBNode\n */\n\nexport const name = 'dag-pb'\nexport const code = 0x70\n\n/**\n * @param {PBNode} node\n * @returns {ByteView}\n */\nexport function encode (node) {\n validate(node)\n\n const pbn = {}\n if (node.Links) {\n pbn.Links = node.Links.map((l) => {\n const link = {}\n if (l.Hash) {\n link.Hash = l.Hash.bytes // cid -> bytes\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n if (node.Data) {\n pbn.Data = node.Data\n }\n\n return encodeNode(pbn)\n}\n\n/**\n * @param {ByteView | ArrayBufferView} bytes\n * @returns {PBNode}\n */\nexport function decode (bytes) {\n const buf = toByteView(bytes)\n const pbn = decodeNode(buf)\n\n const node = {}\n\n if (pbn.Data) {\n node.Data = pbn.Data\n }\n\n if (pbn.Links) {\n node.Links = pbn.Links.map((l) => {\n const link = {}\n try {\n link.Hash = CID.decode(l.Hash)\n } catch (e) {}\n if (!link.Hash) {\n throw new Error('Invalid Hash field found in link, expected CID')\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n\n return node\n}\n\nexport { prepare, validate, createNode, createLink }\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\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) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\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 implements MultibaseEncoder, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\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 implements MultibaseDecoder, UnibaseDecoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\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\n decode (text: string): Uint8Array {\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n}\n\ntype Decoders = Record>\n\nclass ComposedDecoder implements MultibaseDecoder, CombobaseDecoder {\n readonly decoders: Decoders\n\n constructor (decoders: Decoders) {\n this.decoders = decoders\n }\n\n or (decoder: UnibaseDecoder | ComposedDecoder): ComposedDecoder {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\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}\n\nexport function or (left: UnibaseDecoder | CombobaseDecoder, right: UnibaseDecoder | CombobaseDecoder): ComposedDecoder {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder).prefix]: right })\n } as Decoders)\n}\n\nexport class Codec implements MultibaseCodec, MultibaseEncoder, MultibaseDecoder, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder\n readonly decoder: Decoder\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\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\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\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\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\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\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\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\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 \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\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\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (/** @type {number} */ value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create (code: Code, digest: Uint8Array): Digest {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\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 implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode (digest: MultihashDigest, code: T): digest is MultihashDigest {\n return digest.code === code\n}\n", "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'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format , Prefix extends string> (link: T, base?: API.MultibaseEncoder): API.ToString {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder\n )\n }\n}\n\nexport function toJSON (link: Link): API.LinkJSON {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON (json: API.LinkJSON): CID {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap>()\n\nfunction baseCache (cid: API.UnknownLink): Map {\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}\n\nexport class CID implements API.Link {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\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: Version, code: Format, multihash: API.MultihashDigest, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\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 (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID {\n switch (this.version) {\n case 0: {\n return this as CID\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return (\n CID.createV0(\n multihash as API.MultihashDigest\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID {\n return CID.equals(this, other)\n }\n\n static equals (self: API.Link, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\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: API.Link | U): CID | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n multihash as API.MultihashDigest,\n 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) as API.MultihashDigest\n return CID.create(version, code, digest)\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 /**\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: Version, code: Format, digest: API.MultihashDigest): CID {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 (digest: API.MultihashDigest): CID {\n return CID.create(0, DAG_PB_CODE, digest)\n }\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: Code, digest: API.MultihashDigest): CID {\n return CID.create(1, code, digest)\n }\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: API.ByteView>): CID {\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 /**\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: API.ByteView>): [CID, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest)\n : CID.createV1(specs.codec, digest)\n return [cid as CID, bytes.subarray(specs.size)]\n }\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: API.ByteView>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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: API.ToString, Prefix>, base?: API.MultibaseDecoder): CID {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes (source: API.ToString, Prefix>, base?: API.MultibaseDecoder): [Prefix, API.ByteView>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\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 } else {\n return cid\n }\n}\n\nfunction toStringV1 (bytes: Uint8Array, cache: Map, base: API.MultibaseEncoder): string {\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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "const textDecoder = new TextDecoder()\n\n/**\n * @typedef {import('./interface.js').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface.js').RawPBNode} RawPBNode\n */\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[number, number]}\n */\nfunction decodeVarint (bytes, offset) {\n let v = 0\n\n for (let shift = 0; ; shift += 7) {\n /* c8 ignore next 3 */\n if (shift >= 64) {\n throw new Error('protobuf: varint overflow')\n }\n /* c8 ignore next 3 */\n if (offset >= bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n const b = bytes[offset++]\n v += shift < 28 ? (b & 0x7f) << shift : (b & 0x7f) * (2 ** shift)\n if (b < 0x80) {\n break\n }\n }\n return [v, offset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[Uint8Array, number]}\n */\nfunction decodeBytes (bytes, offset) {\n let byteLen\n ;[byteLen, offset] = decodeVarint(bytes, offset)\n const postOffset = offset + byteLen\n\n /* c8 ignore next 3 */\n if (byteLen < 0 || postOffset < 0) {\n throw new Error('protobuf: invalid length')\n }\n /* c8 ignore next 3 */\n if (postOffset > bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n return [bytes.subarray(offset, postOffset), postOffset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} index\n * @returns {[number, number, number]}\n */\nfunction decodeKey (bytes, index) {\n let wire\n ;[wire, index] = decodeVarint(bytes, index)\n // [wireType, fieldNum, newIndex]\n return [wire & 0x7, wire >> 3, index]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBLink}\n */\nfunction decodeLink (bytes) {\n /** @type {RawPBLink} */\n const link = {}\n const l = bytes.length\n let index = 0\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (fieldNum === 1) {\n if (link.Hash) {\n throw new Error('protobuf: (PBLink) duplicate Hash section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Hash`)\n }\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Name before Hash')\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Hash')\n }\n\n [link.Hash, index] = decodeBytes(bytes, index)\n } else if (fieldNum === 2) {\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Name section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Name`)\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Name')\n }\n\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n link.Name = textDecoder.decode(byts)\n } else if (fieldNum === 3) {\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Tsize section')\n }\n if (wireType !== 0) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Tsize`)\n }\n\n [link.Tsize, index] = decodeVarint(bytes, index)\n } else {\n throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBLink) unexpected end of data')\n }\n\n return link\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBNode}\n */\nexport function decodeNode (bytes) {\n const l = bytes.length\n let index = 0\n /** @type {RawPBLink[]|void} */\n let links = undefined // eslint-disable-line no-undef-init\n let linksBeforeData = false\n /** @type {Uint8Array|void} */\n let data = undefined // eslint-disable-line no-undef-init\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${wireType}`)\n }\n\n if (fieldNum === 1) {\n if (data) {\n throw new Error('protobuf: (PBNode) duplicate Data section')\n }\n\n [data, index] = decodeBytes(bytes, index)\n if (links) {\n linksBeforeData = true\n }\n } else if (fieldNum === 2) {\n if (linksBeforeData) { // interleaved Links/Data/Links\n throw new Error('protobuf: (PBNode) duplicate Links section')\n } else if (!links) {\n links = []\n }\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n links.push(decodeLink(byts))\n } else {\n throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBNode) unexpected end of data')\n }\n\n /** @type {RawPBNode} */\n const node = {}\n if (data) {\n node.Data = data\n }\n node.Links = links || []\n return node\n}\n", "const textEncoder = new TextEncoder()\nconst maxInt32 = 2 ** 32\nconst maxUInt32 = 2 ** 31\n\n/**\n * @typedef {import('./interface.js').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface.js').RawPBNode} RawPBNode\n */\n\n// the encoders work backward from the end of the bytes array\n\n/**\n * encodeLink() is passed a slice of the parent byte array that ends where this\n * link needs to end, so it packs to the right-most part of the passed `bytes`\n *\n * @param {RawPBLink} link\n * @param {Uint8Array} bytes\n * @returns {number}\n */\nfunction encodeLink (link, bytes) {\n let i = bytes.length\n\n if (typeof link.Tsize === 'number') {\n if (link.Tsize < 0) {\n throw new Error('Tsize cannot be negative')\n }\n if (!Number.isSafeInteger(link.Tsize)) {\n throw new Error('Tsize too large for encoding')\n }\n i = encodeVarint(bytes, i, link.Tsize) - 1\n bytes[i] = 0x18\n }\n\n if (typeof link.Name === 'string') {\n const nameBytes = textEncoder.encode(link.Name)\n i -= nameBytes.length\n bytes.set(nameBytes, i)\n i = encodeVarint(bytes, i, nameBytes.length) - 1\n bytes[i] = 0x12\n }\n\n if (link.Hash) {\n i -= link.Hash.length\n bytes.set(link.Hash, i)\n i = encodeVarint(bytes, i, link.Hash.length) - 1\n bytes[i] = 0xa\n }\n\n return bytes.length - i\n}\n\n/**\n * Encodes a PBNode into a new byte array of precisely the correct size\n *\n * @param {RawPBNode} node\n * @returns {Uint8Array}\n */\nexport function encodeNode (node) {\n const size = sizeNode(node)\n const bytes = new Uint8Array(size)\n let i = size\n\n if (node.Data) {\n i -= node.Data.length\n bytes.set(node.Data, i)\n i = encodeVarint(bytes, i, node.Data.length) - 1\n bytes[i] = 0xa\n }\n\n if (node.Links) {\n for (let index = node.Links.length - 1; index >= 0; index--) {\n const size = encodeLink(node.Links[index], bytes.subarray(0, i))\n i -= size\n i = encodeVarint(bytes, i, size) - 1\n bytes[i] = 0x12\n }\n }\n\n return bytes\n}\n\n/**\n * work out exactly how many bytes this link takes up\n *\n * @param {RawPBLink} link\n * @returns\n */\nfunction sizeLink (link) {\n let n = 0\n\n if (link.Hash) {\n const l = link.Hash.length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Name === 'string') {\n const l = textEncoder.encode(link.Name).length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Tsize === 'number') {\n n += 1 + sov(link.Tsize)\n }\n\n return n\n}\n\n/**\n * Work out exactly how many bytes this node takes up\n *\n * @param {RawPBNode} node\n * @returns {number}\n */\nfunction sizeNode (node) {\n let n = 0\n\n if (node.Data) {\n const l = node.Data.length\n n += 1 + l + sov(l)\n }\n\n if (node.Links) {\n for (const link of node.Links) {\n const l = sizeLink(link)\n n += 1 + l + sov(l)\n }\n }\n\n return n\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @param {number} v\n * @returns {number}\n */\nfunction encodeVarint (bytes, offset, v) {\n offset -= sov(v)\n const base = offset\n\n while (v >= maxUInt32) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v /= 128\n }\n\n while (v >= 128) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v >>>= 7\n }\n\n bytes[offset] = v\n\n return base\n}\n\n/**\n * size of varint\n *\n * @param {number} x\n * @returns {number}\n */\nfunction sov (x) {\n if (x % 2 === 0) {\n x++\n }\n return Math.floor((len64(x) + 6) / 7)\n}\n\n/**\n * golang math/bits, how many bits does it take to represent this integer?\n *\n * @param {number} x\n * @returns {number}\n */\nfunction len64 (x) {\n let n = 0\n if (x >= maxInt32) {\n x = Math.floor(x / maxInt32)\n n = 32\n }\n if (x >= (1 << 16)) {\n x >>>= 16\n n += 16\n }\n if (x >= (1 << 8)) {\n x >>>= 8\n n += 8\n }\n return n + len8tab[x]\n}\n\n// golang math/bits\nconst len8tab = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8\n]\n", "import { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./interface.js').PBLink} PBLink\n * @typedef {import('./interface.js').PBNode} PBNode\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\nconst pbNodeProperties = ['Data', 'Links']\nconst pbLinkProperties = ['Hash', 'Name', 'Tsize']\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {PBLink} a\n * @param {PBLink} b\n * @returns {number}\n */\nfunction linkComparator (a, b) {\n if (a === b) {\n return 0\n }\n\n const abuf = a.Name ? textEncoder.encode(a.Name) : []\n const bbuf = b.Name ? textEncoder.encode(b.Name) : []\n\n let x = abuf.length\n let y = bbuf.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (abuf[i] !== bbuf[i]) {\n x = abuf[i]\n y = bbuf[i]\n break\n }\n }\n\n return x < y ? -1 : y < x ? 1 : 0\n}\n\n/**\n * @param {any} node\n * @param {string[]} properties\n * @returns {boolean}\n */\nfunction hasOnlyProperties (node, properties) {\n return !Object.keys(node).some((p) => !properties.includes(p))\n}\n\n/**\n * Converts a CID, or a PBLink-like object to a PBLink\n *\n * @param {any} link\n * @returns {PBLink}\n */\nfunction asLink (link) {\n if (typeof link.asCID === 'object') {\n const Hash = CID.asCID(link)\n if (!Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n return { Hash }\n }\n\n if (typeof link !== 'object' || Array.isArray(link)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n const pbl = {}\n\n if (link.Hash) {\n let cid = CID.asCID(link.Hash)\n try {\n if (!cid) {\n if (typeof link.Hash === 'string') {\n cid = CID.parse(link.Hash)\n } else if (link.Hash instanceof Uint8Array) {\n cid = CID.decode(link.Hash)\n }\n }\n } catch (/** @type {any} */ e) {\n throw new TypeError(`Invalid DAG-PB form: ${e.message}`)\n }\n\n if (cid) {\n pbl.Hash = cid\n }\n }\n\n if (!pbl.Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (typeof link.Name === 'string') {\n pbl.Name = link.Name\n }\n\n if (typeof link.Tsize === 'number') {\n pbl.Tsize = link.Tsize\n }\n\n return pbl\n}\n\n/**\n * @param {any} node\n * @returns {PBNode}\n */\nexport function prepare (node) {\n if (node instanceof Uint8Array || typeof node === 'string') {\n node = { Data: node }\n }\n\n if (typeof node !== 'object' || Array.isArray(node)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n /** @type {PBNode} */\n const pbn = {}\n\n if (node.Data !== undefined) {\n if (typeof node.Data === 'string') {\n pbn.Data = textEncoder.encode(node.Data)\n } else if (node.Data instanceof Uint8Array) {\n pbn.Data = node.Data\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n }\n\n if (node.Links !== undefined) {\n if (Array.isArray(node.Links)) {\n pbn.Links = node.Links.map(asLink)\n pbn.Links.sort(linkComparator)\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n } else {\n pbn.Links = []\n }\n\n return pbn\n}\n\n/**\n * @param {PBNode} node\n */\nexport function validate (node) {\n /*\n type PBLink struct {\n Hash optional Link\n Name optional String\n Tsize optional Int\n }\n\n type PBNode struct {\n Links [PBLink]\n Data optional Bytes\n }\n */\n // @ts-ignore private property for TS\n if (!node || typeof node !== 'object' || Array.isArray(node) || node instanceof Uint8Array || (node['/'] && node['/'] === node.bytes)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (!hasOnlyProperties(node, pbNodeProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties)')\n }\n\n if (node.Data !== undefined && !(node.Data instanceof Uint8Array)) {\n throw new TypeError('Invalid DAG-PB form (Data must be bytes)')\n }\n\n if (!Array.isArray(node.Links)) {\n throw new TypeError('Invalid DAG-PB form (Links must be a list)')\n }\n\n for (let i = 0; i < node.Links.length; i++) {\n const link = node.Links[i]\n // @ts-ignore private property for TS\n if (!link || typeof link !== 'object' || Array.isArray(link) || link instanceof Uint8Array || (link['/'] && link['/'] === link.bytes)) {\n throw new TypeError('Invalid DAG-PB form (bad link)')\n }\n\n if (!hasOnlyProperties(link, pbLinkProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties on link)')\n }\n\n if (link.Hash === undefined) {\n throw new TypeError('Invalid DAG-PB form (link must have a Hash)')\n }\n\n // @ts-ignore private property for TS\n if (link.Hash == null || !link.Hash['/'] || link.Hash['/'] !== link.Hash.bytes) {\n throw new TypeError('Invalid DAG-PB form (link Hash must be a CID)')\n }\n\n if (link.Name !== undefined && typeof link.Name !== 'string') {\n throw new TypeError('Invalid DAG-PB form (link Name must be a string)')\n }\n\n if (link.Tsize !== undefined) {\n if (typeof link.Tsize !== 'number' || link.Tsize % 1 !== 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize must be an integer)')\n }\n if (link.Tsize < 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize cannot be negative)')\n }\n }\n\n if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) {\n throw new TypeError('Invalid DAG-PB form (links must be sorted by Name bytes)')\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {PBLink[]} [links=[]]\n * @returns {PBNode}\n */\nexport function createNode (data, links = []) {\n return prepare({ Data: data, Links: links })\n}\n\n/**\n * @param {string} name\n * @param {number} size\n * @param {CID} cid\n * @returns {PBLink}\n */\nexport function createLink (name, size, cid) {\n return asLink({ Hash: cid, Name: name, Tsize: size })\n}\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nexport function toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n", "import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nexport function toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst _encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\nexport const encodeOptions = {\n ..._encodeOptions,\n typeEncoders: {\n ..._encodeOptions.typeEncoders\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst _decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\n_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const decodeOptions = {\n ..._decodeOptions,\n tags: _decodeOptions.tags.slice()\n}\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => cborg.encode(node, _encodeOptions)\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\nconst typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n]\n\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeofs.includes(typeOf)) {\n return typeOf\n }\n /* c8 ignore next 4 */\n // not going to bother testing this, it's not going to be valid anyway\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n if (isBuffer(value)) {\n return 'Buffer'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {boolean}\n */\nfunction isBuffer (value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n", "class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textDecoder = new TextDecoder()\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\nexport const toString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')\n : utf8Slice(bytes, start, end)\n }\n /* c8 ignore next 11 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? textDecoder.decode(bytes.subarray(start, end))\n : utf8Slice(bytes, start, end)\n }\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// The below code is mostly taken from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n\n/**\n * @param {Uint8Array} buf\n * @param {number} offset\n * @param {number} end\n * @returns {string}\n */\nfunction utf8Slice (buf, offset, end) {\n const res = []\n\n while (offset < end) {\n const firstByte = buf[offset]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (offset + 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[offset + 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[offset + 1]\n thirdByte = buf[offset + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n fourthByte = buf[offset + 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 /* c8 ignore next 5 */\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 offset += 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\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function 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 /* c8 ignore next 10 */\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", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeUint (buf, token) {\n return encodeUintValue(buf, 0, token.value)\n}\n\n/**\n * @param {Bl} buf\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n buf.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n buf.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n buf.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n buf.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeNegint (buf, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = slice(data, pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeBytes (buf, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length)\n buf.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { toString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeArray (buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeMap (buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeTag (buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nconst MINOR_FALSE = 20\nconst MINOR_TRUE = 21\nconst MINOR_NULL = 22\nconst MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (buf, token, options) {\n const float = token.value\n\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n buf.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n buf.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n buf.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\nimport { encodeUint } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst buf = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const length = isMap ? obj.size : keys.length\n if (!length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n refStack = Ref.createCheck(refStack, obj)\n /** @type {TokenOrNestedTokens[]} */\n const entries = []\n let i = 0\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ]\n }\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/*\n(UPDATE, Dec 2020)\nhttps://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some\nof the questions above with a new recommendation for sorting order being much\ncloser to what would be expected in other environments (i.e. no length-first\nweirdness).\nThis new sorting order is not yet implemented here but could be added as an\noption. \"Determinism\" (canonicity) is system dependent and it's difficult to\nchange existing systems that are built with existing expectations. So if a new\nordering is introduced here, the old needs to be kept as well with the user\nhaving the option.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @param {Bl} buf\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options)\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options) {\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n const buf = new Bl(size)\n encoder(buf, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return asU8A(buf.chunks[0])\n }\n }\n buf.reset()\n tokensToEncoded(buf, tokens, encoders, options)\n return buf.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, cborEncoders, options)\n}\n\nexport { objectToTokens, encode, encodeCustom, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (options.rejectDuplicateMapKeys === true) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (token.type === Type.break) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n const tokeniser = options.tokenizer || new Tokeniser(data, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "/* eslint max-depth: [\"error\", 7] */\nimport { Token, Type } from 'cborg'\nimport * as cborgJson from 'cborg/json'\nimport { CID } from 'multiformats'\nimport { base64 } from 'multiformats/bases/base64'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n/**\n * @template T\n * @typedef {import('multiformats').ToString} ToString\n */\n/**\n * @typedef {import('cborg/interface').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nfunction toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal. Encoding a CID means replacing it with a `{\"/\":\"}`\n * object as per the DAG-JSON spec.\n *\n * @param {any} obj\n * @returns {Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const cidString = cid.toString()\n\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.string, cidString, cidString.length), // value\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * bytesEncoder will receive all Uint8Arrays (and friends) during encode, it\n * needs to replace it with a `{\"/\":{\"bytes\":\"Base64ByteString\"}}` object as\n * per the DAG-JSON spec.\n *\n * @param {Uint8Array} bytes\n * @returns {Token[]|null}\n */\nfunction bytesEncoder (bytes) {\n const bytesString = base64.encode(bytes).slice(1) // no mbase prefix\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.map, Infinity, 1), // value\n new Token(Type.string, 'bytes', 5), // inner key\n new Token(Type.string, bytesString, bytesString.length), // inner value\n new Token(Type.break, undefined, 1),\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * taBytesEncoder wraps bytesEncoder() but for the more exotic typed arrays so\n * that we access the underlying ArrayBuffer data\n *\n * @param {Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|Uint8ClampedArray|BigInt64Array|BigUint64Array} obj\n * @returns {Token[]|null}\n */\nfunction taBytesEncoder (obj) {\n return bytesEncoder(new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n}\n\n/**\n * abBytesEncoder wraps bytesEncoder() but for plain ArrayBuffers\n *\n * @param {ArrayBuffer} ab\n * @returns {Token[]|null}\n */\nfunction abBytesEncoder (ab) {\n return bytesEncoder(new Uint8Array(ab))\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null // process with standard number encoder\n}\n\nconst encodeOptions = {\n typeEncoders: {\n Object: cidEncoder,\n Buffer: bytesEncoder,\n Uint8Array: bytesEncoder,\n Int8Array: taBytesEncoder,\n Uint16Array: taBytesEncoder,\n Int16Array: taBytesEncoder,\n Uint32Array: taBytesEncoder,\n Int32Array: taBytesEncoder,\n Float32Array: taBytesEncoder,\n Float64Array: taBytesEncoder,\n Uint8ClampedArray: taBytesEncoder,\n BigInt64Array: taBytesEncoder,\n BigUint64Array: taBytesEncoder,\n DataView: taBytesEncoder,\n ArrayBuffer: abBytesEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass DagJsonTokenizer extends cborgJson.Tokenizer {\n /**\n * @param {Uint8Array} data\n * @param {object} [options]\n */\n constructor (data, options) {\n super(data, options)\n /** @type {Token[]} */\n this.tokenBuffer = []\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this.tokenBuffer.length === 0 && super.done()\n }\n\n /**\n * @returns {Token}\n */\n _next () {\n if (this.tokenBuffer.length > 0) {\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/30406\n return this.tokenBuffer.pop()\n }\n return super.next()\n }\n\n /**\n * Implements rules outlined in https://github.com/ipld/specs/pull/356\n *\n * @returns {Token}\n */\n next () {\n const token = this._next()\n\n if (token.type === Type.map) {\n const keyToken = this._next()\n if (keyToken.type === Type.string && keyToken.value === '/') {\n const valueToken = this._next()\n if (valueToken.type === Type.string) { // *must* be a CID\n const breakToken = this._next() // swallow the end-of-map token\n if (breakToken.type !== Type.break) {\n throw new Error('Invalid encoded CID form')\n }\n this.tokenBuffer.push(valueToken) // CID.parse will pick this up after our tag token\n return new Token(Type.tag, 42, 0)\n }\n if (valueToken.type === Type.map) {\n const innerKeyToken = this._next()\n if (innerKeyToken.type === Type.string && innerKeyToken.value === 'bytes') {\n const innerValueToken = this._next()\n if (innerValueToken.type === Type.string) { // *must* be Bytes\n for (let i = 0; i < 2; i++) {\n const breakToken = this._next() // swallow two end-of-map tokens\n if (breakToken.type !== Type.break) {\n throw new Error('Invalid encoded Bytes form')\n }\n }\n const bytes = base64.decode(`m${innerValueToken.value}`)\n return new Token(Type.bytes, bytes, innerValueToken.value.length)\n }\n this.tokenBuffer.push(innerValueToken) // bail\n }\n this.tokenBuffer.push(innerKeyToken) // bail\n }\n this.tokenBuffer.push(valueToken) // bail\n }\n this.tokenBuffer.push(keyToken) // bail\n }\n return token\n }\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n allowUndefined: false,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\n\n// we're going to get TAG(42)STRING(\"bafy...\") from the tokenizer so we only need\n// to deal with the STRING(\"bafy...\") at this point\ndecodeOptions.tags[42] = CID.parse\n\nexport const name = 'dag-json'\nexport const code = 0x0129\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => cborgJson.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} data\n * @returns {T}\n */\nexport const decode = (data) => {\n const buf = toByteView(data)\n // the tokenizer is stateful so we need a single instance of it\n const options = Object.assign(decodeOptions, { tokenizer: new DagJsonTokenizer(buf, decodeOptions) })\n return cborgJson.decode(buf, options)\n}\n\n/**\n * @template T\n * @param {T} node\n * @returns {ToString}\n */\nexport const format = (node) => utf8Decoder.decode(encode(node))\nexport { format as stringify }\nconst utf8Decoder = new TextDecoder()\n\n/**\n * @template T\n * @param {ToString} data\n * @returns {T}\n */\nexport const parse = (data) => decode(utf8Encoder.encode(data))\nconst utf8Encoder = new TextEncoder()\n", "import { Type } from '../token.js'\nimport { encodeCustom } from '../encode.js'\nimport { encodeErrPrefix } from '../common.js'\nimport { asU8A, fromString } from '../byte-utils.js'\n\n/**\n * @typedef {import('../../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../token').Token} Token\n * @typedef {import('../bl').Bl} Bl\n */\n\nclass JSONEncoder extends Array {\n constructor () {\n super()\n /** @type {{type:Type,elements:number}[]} */\n this.inRecursive = []\n }\n\n /**\n * @param {Bl} buf\n */\n prefix (buf) {\n const recurs = this.inRecursive[this.inRecursive.length - 1]\n if (recurs) {\n if (recurs.type === Type.array) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n buf.push([44]) // ','\n }\n }\n if (recurs.type === Type.map) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n if (recurs.elements % 2 === 1) { // key\n buf.push([44]) // ','\n } else {\n buf.push([58]) // ':'\n }\n }\n }\n }\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.uint.major] (buf, token) {\n this.prefix(buf)\n const is = String(token.value)\n const isa = []\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n }\n buf.push(isa)\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.negint.major] (buf, token) {\n // @ts-ignore hack\n this[Type.uint.major](buf, token)\n }\n\n /**\n * @param {Bl} _buf\n * @param {Token} _token\n */\n [Type.bytes.major] (_buf, _token) {\n throw new Error(`${encodeErrPrefix} unsupported type: Uint8Array`)\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.string.major] (buf, token) {\n this.prefix(buf)\n // buf.push(34) // '\"'\n // encodeUtf8(token.value, byts)\n // buf.push(34) // '\"'\n const byts = fromString(JSON.stringify(token.value))\n buf.push(byts.length > 32 ? asU8A(byts) : byts)\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} _token\n */\n [Type.array.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.array, elements: 0 })\n buf.push([91]) // '['\n }\n\n /**\n * @param {Bl} buf\n * @param {Token} _token\n */\n [Type.map.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.map, elements: 0 })\n buf.push([123]) // '{'\n }\n\n /**\n * @param {Bl} _buf\n * @param {Token} _token\n */\n [Type.tag.major] (_buf, _token) {}\n\n /**\n * @param {Bl} buf\n * @param {Token} token\n */\n [Type.float.major] (buf, token) {\n if (token.type.name === 'break') {\n const recurs = this.inRecursive.pop()\n if (recurs) {\n if (recurs.type === Type.array) {\n buf.push([93]) // ']'\n } else if (recurs.type === Type.map) {\n buf.push([125]) // '}'\n /* c8 ignore next 3 */\n } else {\n throw new Error('Unexpected recursive type; this should not happen!')\n }\n return\n }\n /* c8 ignore next 2 */\n throw new Error('Unexpected break; this should not happen!')\n }\n if (token.value === undefined) {\n throw new Error(`${encodeErrPrefix} unsupported type: undefined`)\n }\n\n this.prefix(buf)\n if (token.type.name === 'true') {\n buf.push([116, 114, 117, 101]) // 'true'\n return\n } else if (token.type.name === 'false') {\n buf.push([102, 97, 108, 115, 101]) // 'false'\n return\n } else if (token.type.name === 'null') {\n buf.push([110, 117, 108, 108]) // 'null'\n return\n }\n\n // number\n const is = String(token.value)\n const isa = []\n let dp = false\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n if (!dp && (isa[i] === 46 || isa[i] === 101 || isa[i] === 69)) { // '[.eE]'\n dp = true\n }\n }\n if (!dp) { // need a decimal point for floats\n isa.push(46) // '.'\n isa.push(48) // '0'\n }\n buf.push(isa)\n }\n}\n\n// The below code is mostly taken and modified from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n// function encodeUtf8 (string, byts) {\n// let codePoint\n// const length = string.length\n// let leadSurrogate = null\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// /* c8 ignore next 9 */\n// if (codePoint > 0xdbff) {\n// // unexpected trail\n// byts.push(0xef, 0xbf, 0xbd)\n// continue\n// } else if (i + 1 === length) {\n// // unpaired lead\n// byts.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// /* c8 ignore next 5 */\n// if (codePoint < 0xdc00) {\n// byts.push(0xef, 0xbf, 0xbd)\n// leadSurrogate = codePoint\n// continue\n// }\n\n// // valid surrogate pair\n// codePoint = (leadSurrogate - 0xd800 << 10 | codePoint - 0xdc00) + 0x10000\n// /* c8 ignore next 4 */\n// } else if (leadSurrogate) {\n// // valid bmp char, but last char was a lead\n// byts.push(0xef, 0xbf, 0xbd)\n// }\n\n// leadSurrogate = null\n\n// // encode utf8\n// if (codePoint < 0x80) {\n// // special JSON escapes\n// switch (codePoint) {\n// case 8: // '\\b'\n// byts.push(92, 98) // '\\\\b'\n// continue\n// case 9: // '\\t'\n// byts.push(92, 116) // '\\\\t'\n// continue\n// case 10: // '\\n'\n// byts.push(92, 110) // '\\\\n'\n// continue\n// case 12: // '\\f'\n// byts.push(92, 102) // '\\\\f'\n// continue\n// case 13: // '\\r'\n// byts.push(92, 114) // '\\\\r'\n// continue\n// case 34: // '\"'\n// byts.push(92, 34) // '\\\\\"'\n// continue\n// case 92: // '\\\\'\n// byts.push(92, 92) // '\\\\\\\\'\n// continue\n// }\n\n// byts.push(codePoint)\n// } else if (codePoint < 0x800) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0x6 | 0xc0,\n// codePoint & 0x3f | 0x80\n// )\n// } else if (codePoint < 0x10000) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0xc | 0xe0,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// /* c8 ignore next 9 */\n// } else if (codePoint < 0x110000) {\n// byts.push(\n// codePoint >> 0x12 | 0xf0,\n// codePoint >> 0xc & 0x3f | 0x80,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// } else {\n// /* c8 ignore next 2 */\n// throw new Error('Invalid code point')\n// }\n// }\n// }\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n if (Array.isArray(e1[0]) || Array.isArray(e2[0])) {\n throw new Error(`${encodeErrPrefix} complex map keys are not supported`)\n }\n const keyToken1 = e1[0]\n const keyToken2 = e2[0]\n if (keyToken1.type !== Type.string || keyToken2.type !== Type.string) {\n throw new Error(`${encodeErrPrefix} non-string map keys are not supported`)\n }\n if (keyToken1 < keyToken2) {\n return -1\n }\n if (keyToken1 > keyToken2) {\n return 1\n }\n /* c8 ignore next 1 */\n throw new Error(`${encodeErrPrefix} unexpected duplicate map keys, this is not supported`)\n}\n\nconst defaultEncodeOptions = { addBreakTokens: true, mapSorter }\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, new JSONEncoder(), options)\n}\n\nexport { encode }\n", "import { decode as _decode, decodeFirst as _decodeFirst } from '../decode.js'\nimport { Token, Type } from '../token.js'\nimport { decodeCodePointsArray } from '../byte-utils.js'\nimport { decodeErrPrefix } from '../common.js'\n\n/**\n * @typedef {import('../../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../../interface').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokenizer {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n /** @type {string[]} */\n this.modeStack = ['value']\n this.lastToken = ''\n }\n\n pos () {\n return this._pos\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this._pos >= this.data.length\n }\n\n /**\n * @returns {number}\n */\n ch () {\n return this.data[this._pos]\n }\n\n /**\n * @returns {string}\n */\n currentMode () {\n return this.modeStack[this.modeStack.length - 1]\n }\n\n skipWhitespace () {\n let c = this.ch()\n // @ts-ignore\n while (c === 32 /* ' ' */ || c === 9 /* '\\t' */ || c === 13 /* '\\r' */ || c === 10 /* '\\n' */) {\n c = this.data[++this._pos]\n }\n }\n\n /**\n * @param {number[]} str\n */\n expect (str) {\n if (this.data.length - this._pos < str.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of input at position ${this._pos}`)\n }\n for (let i = 0; i < str.length; i++) {\n if (this.data[this._pos++] !== str[i]) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...str)}'`)\n }\n }\n }\n\n parseNumber () {\n const startPos = this._pos\n let negative = false\n let float = false\n\n /**\n * @param {number[]} chars\n */\n const swallow = (chars) => {\n while (!this.done()) {\n const ch = this.ch()\n if (chars.includes(ch)) {\n this._pos++\n } else {\n break\n }\n }\n }\n\n // lead\n if (this.ch() === 45) { // '-'\n negative = true\n this._pos++\n }\n if (this.ch() === 48) { // '0'\n this._pos++\n if (this.ch() === 46) { // '.'\n this._pos++\n float = true\n } else {\n return new Token(Type.uint, 0, this._pos - startPos)\n }\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n if (negative && this._pos === startPos + 1) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n if (!this.done() && this.ch() === 46) { // '.'\n if (float) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n float = true\n this._pos++\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n if (!this.done() && (this.ch() === 101 || this.ch() === 69)) { // '[eE]'\n float = true\n this._pos++\n if (!this.done() && (this.ch() === 43 || this.ch() === 45)) { // '+', '-'\n this._pos++\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n // @ts-ignore\n const numStr = String.fromCharCode.apply(null, this.data.subarray(startPos, this._pos))\n const num = parseFloat(numStr)\n if (float) {\n return new Token(Type.float, num, this._pos - startPos)\n }\n if (this.options.allowBigInt !== true || Number.isSafeInteger(num)) {\n return new Token(num >= 0 ? Type.uint : Type.negint, num, this._pos - startPos)\n }\n return new Token(num >= 0 ? Type.uint : Type.negint, BigInt(numStr), this._pos - startPos)\n }\n\n /**\n * @returns {Token}\n */\n parseString () {\n /* c8 ignore next 4 */\n if (this.ch() !== 34) { // '\"'\n // this would be a programming error\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}; this shouldn't happen`)\n }\n this._pos++\n\n // check for simple fast-path, all printable ascii, no escapes\n // >0x10000 elements may fail fn.apply() (http://stackoverflow.com/a/22747272/680742)\n for (let i = this._pos, l = 0; i < this.data.length && l < 0x10000; i++, l++) {\n const ch = this.data[i]\n if (ch === 92 || ch < 32 || ch >= 128) { // '\\', ' ', control-chars or non-trivial\n break\n }\n if (ch === 34) { // '\"'\n // @ts-ignore\n const str = String.fromCharCode.apply(null, this.data.subarray(this._pos, i))\n this._pos = i + 1\n return new Token(Type.string, str, l)\n }\n }\n\n const startPos = this._pos\n const chars = []\n\n const readu4 = () => {\n if (this._pos + 4 >= this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of unicode escape sequence at position ${this._pos}`)\n }\n let u4 = 0\n for (let i = 0; i < 4; i++) {\n let ch = this.ch()\n if (ch >= 48 && ch <= 57) { // '0' && '9'\n ch -= 48\n } else if (ch >= 97 && ch <= 102) { // 'a' && 'f'\n ch = ch - 97 + 10\n } else if (ch >= 65 && ch <= 70) { // 'A' && 'F'\n ch = ch - 65 + 10\n } else {\n throw new Error(`${decodeErrPrefix} unexpected unicode escape character at position ${this._pos}`)\n }\n u4 = u4 * 16 + ch\n this._pos++\n }\n return u4\n }\n\n // mostly taken from feross/buffer and adjusted to fit\n const readUtf8Char = () => {\n const firstByte = this.ch()\n let codePoint = null\n /* c8 ignore next 1 */\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (this._pos + bytesPerSequence > this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected unicode sequence at position ${this._pos}`)\n }\n\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n /* c8 ignore next 6 */\n // this case is dealt with by the caller function\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = this.data[this._pos + 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 = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 2]\n fourthByte = this.data[this._pos + 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 /* c8 ignore next 5 */\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 chars.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n chars.push(codePoint)\n this._pos += bytesPerSequence\n }\n\n // TODO: could take the approach of a quick first scan for special chars like encoding/json/decode.go#unquoteBytes\n // and converting all of the ascii chars from the base array in bulk\n while (!this.done()) {\n const ch = this.ch()\n let ch1\n switch (ch) {\n case 92: // '\\'\n this._pos++\n if (this.done()) {\n throw new Error(`${decodeErrPrefix} unexpected string termination at position ${this._pos}`)\n }\n ch1 = this.ch()\n this._pos++\n switch (ch1) {\n case 34: // '\"'\n case 39: // '\\''\n case 92: // '\\'\n case 47: // '/'\n chars.push(ch1)\n break\n case 98: // 'b'\n chars.push(8)\n break\n case 116: // 't'\n chars.push(9)\n break\n case 110: // 'n'\n chars.push(10)\n break\n case 102: // 'f'\n chars.push(12)\n break\n case 114: // 'r'\n chars.push(13)\n break\n case 117: // 'u'\n chars.push(readu4())\n break\n default:\n throw new Error(`${decodeErrPrefix} unexpected string escape character at position ${this._pos}`)\n }\n break\n case 34: // '\"'\n this._pos++\n return new Token(Type.string, decodeCodePointsArray(chars), this._pos - startPos)\n default:\n if (ch < 32) { // ' '\n throw new Error(`${decodeErrPrefix} invalid control character at position ${this._pos}`)\n } else if (ch < 0x80) {\n chars.push(ch)\n this._pos++\n } else {\n readUtf8Char()\n }\n }\n }\n\n throw new Error(`${decodeErrPrefix} unexpected end of string at position ${this._pos}`)\n }\n\n /**\n * @returns {Token}\n */\n parseValue () {\n switch (this.ch()) {\n case 123: // '{'\n this.modeStack.push('obj-start')\n this._pos++\n return new Token(Type.map, Infinity, 1)\n case 91: // '['\n this.modeStack.push('array-start')\n this._pos++\n return new Token(Type.array, Infinity, 1)\n case 34: { // '\"'\n return this.parseString()\n }\n case 110: // 'n' / null\n this.expect([110, 117, 108, 108]) // 'null'\n return new Token(Type.null, null, 4)\n case 102: // 'f' / // false\n this.expect([102, 97, 108, 115, 101]) // 'false'\n return new Token(Type.false, false, 5)\n case 116: // 't' / // true\n this.expect([116, 114, 117, 101]) // 'true'\n return new Token(Type.true, true, 4)\n case 45: // '-'\n case 48: // '0'\n case 49: // '1'\n case 50: // '2'\n case 51: // '3'\n case 52: // '4'\n case 53: // '5'\n case 54: // '6'\n case 55: // '7'\n case 56: // '8'\n case 57: // '9'\n return this.parseNumber()\n default:\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}`)\n }\n }\n\n /**\n * @returns {Token}\n */\n next () {\n this.skipWhitespace()\n switch (this.currentMode()) {\n case 'value':\n this.modeStack.pop()\n return this.parseValue()\n case 'array-value': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n case 'array-start': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n // @ts-ignore\n case 'obj-key':\n if (this.ch() === 125) { // '}'\n this.modeStack.pop()\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.skipWhitespace()\n case 'obj-start': { // eslint-disable-line no-fallthrough\n this.modeStack.pop()\n if (this.ch() === 125) { // '}'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n const token = this.parseString()\n this.skipWhitespace()\n if (this.ch() !== 58) { // ':'\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('obj-value')\n return token\n }\n case 'obj-value': {\n this.modeStack.pop()\n this.modeStack.push('obj-key')\n this.skipWhitespace()\n return this.parseValue()\n }\n /* c8 ignore next 2 */\n default:\n throw new Error(`${decodeErrPrefix} unexpected parse state at position ${this._pos}; this shouldn't happen`)\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decode(data, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decodeFirst(data, options)\n}\n\nexport { decode, decodeFirst, Tokenizer }\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await = Promise | T\n\nexport function from ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await }): Hasher {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher implements MultihashHasher {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await> {\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", null, "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\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.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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 function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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 function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\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 /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\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}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\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\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const 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", null, "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\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 \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const 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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\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", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import * as varint from './varint.js'\nimport * as Digest from './hashes/digest.js'\nimport { base58btc } from './bases/base58.js'\nimport { base32 } from './bases/base32.js'\nimport { coerce } from './bytes.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst 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}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n *\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\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\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\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 /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\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 * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n 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 =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\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 /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\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 * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\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\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst 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\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 } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst 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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst 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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", null, null, "const typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n];\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nexport function is(value) {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return 'undefined';\n }\n if (value === true || value === false) {\n return 'boolean';\n }\n const typeOf = typeof value;\n if (typeofs.includes(typeOf)) {\n return typeOf;\n }\n if (typeOf === 'function') {\n return 'Function';\n }\n if (Array.isArray(value)) {\n return 'Array';\n }\n if (isBuffer(value)) {\n return 'Buffer';\n }\n const objectType = getObjectType(value);\n if (objectType) {\n return objectType;\n }\n return 'Object';\n}\nfunction isBuffer(value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value);\n}\nfunction getObjectType(value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n}", "class Type {\n constructor(major, name, terminal) {\n this.major = major;\n this.majorEncoded = major << 5;\n this.name = name;\n this.terminal = terminal;\n }\n toString() {\n return `Type[${ this.major }].${ this.name }`;\n }\n compare(typ) {\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;\n }\n}\nType.uint = new Type(0, 'uint', true);\nType.negint = new Type(1, 'negint', true);\nType.bytes = new Type(2, 'bytes', true);\nType.string = new Type(3, 'string', true);\nType.array = new Type(4, 'array', false);\nType.map = new Type(5, 'map', false);\nType.tag = new Type(6, 'tag', false);\nType.float = new Type(7, 'float', true);\nType.false = new Type(7, 'false', true);\nType.true = new Type(7, 'true', true);\nType.null = new Type(7, 'null', true);\nType.undefined = new Type(7, 'undefined', true);\nType.break = new Type(7, 'break', true);\nclass Token {\n constructor(type, value, encodedLength) {\n this.type = type;\n this.value = value;\n this.encodedLength = encodedLength;\n this.encodedBytes = undefined;\n this.byteValue = undefined;\n }\n toString() {\n return `Token[${ this.type }].${ this.value }`;\n }\n}\nexport {\n Type,\n Token\n};", "export const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === 'function';\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\nfunction isBuffer(buf) {\n return useBuffer && globalThis.Buffer.isBuffer(buf);\n}\nexport function asU8A(buf) {\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf);\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;\n}\nexport const toString = useBuffer ? (bytes, start, end) => {\n return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8') : utf8Slice(bytes, start, end);\n} : (bytes, start, end) => {\n return end - start > 64 ? textDecoder.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end);\n};\nexport const fromString = useBuffer ? string => {\n return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string);\n} : string => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string);\n};\nexport const fromArray = arr => {\n return Uint8Array.from(arr);\n};\nexport const slice = useBuffer ? (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end));\n }\n return bytes.slice(start, end);\n} : (bytes, start, end) => {\n return bytes.slice(start, end);\n};\nexport const concat = useBuffer ? (chunks, length) => {\n chunks = chunks.map(c => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));\n return asU8A(globalThis.Buffer.concat(chunks, length));\n} : (chunks, length) => {\n const out = new Uint8Array(length);\n let off = 0;\n for (let b of chunks) {\n if (off + b.length > out.length) {\n b = b.subarray(0, out.length - off);\n }\n out.set(b, off);\n off += b.length;\n }\n return out;\n};\nexport const alloc = useBuffer ? size => {\n return globalThis.Buffer.allocUnsafe(size);\n} : size => {\n return new Uint8Array(size);\n};\nexport const toHex = useBuffer ? d => {\n if (typeof d === 'string') {\n return d;\n }\n return globalThis.Buffer.from(toBytes(d)).toString('hex');\n} : d => {\n if (typeof d === 'string') {\n return d;\n }\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${ p }${ c.toString(16).padStart(2, '0') }`, '');\n};\nexport const fromHex = useBuffer ? hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n return globalThis.Buffer.from(hex, 'hex');\n} : hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n if (!hex.length) {\n return new Uint8Array(0);\n }\n return new Uint8Array(hex.split('').map((c, i, d) => i % 2 === 0 ? `0x${ c }${ d[i + 1] }` : '').filter(Boolean).map(e => parseInt(e, 16)));\n};\nfunction toBytes(obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj;\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj);\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function compare(b1, b2) {\n if (isBuffer(b1) && isBuffer(b2)) {\n return b1.compare(b2);\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue;\n }\n return b1[i] < b2[i] ? -1 : 1;\n }\n return 0;\n}\nfunction utf8ToBytes(string, units = Infinity) {\n let codePoint;\n const length = string.length;\n let leadSurrogate = null;\n const bytes = [];\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n if (codePoint > 55295 && codePoint < 57344) {\n if (!leadSurrogate) {\n if (codePoint > 56319) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n } else if (i + 1 === length) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n }\n leadSurrogate = codePoint;\n continue;\n }\n if (codePoint < 56320) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n leadSurrogate = codePoint;\n continue;\n }\n codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;\n } else if (leadSurrogate) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n }\n leadSurrogate = null;\n if (codePoint < 128) {\n if ((units -= 1) < 0)\n break;\n bytes.push(codePoint);\n } else if (codePoint < 2048) {\n if ((units -= 2) < 0)\n break;\n bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);\n } else if (codePoint < 65536) {\n if ((units -= 3) < 0)\n break;\n bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else if (codePoint < 1114112) {\n if ((units -= 4) < 0)\n break;\n bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else {\n throw new Error('Invalid code point');\n }\n }\n return bytes;\n}\nfunction utf8Slice(buf, offset, end) {\n const res = [];\n while (offset < end) {\n const firstByte = buf[offset];\n let codePoint = null;\n let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint;\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 128) {\n codePoint = firstByte;\n }\n break;\n case 2:\n secondByte = buf[offset + 1];\n if ((secondByte & 192) === 128) {\n tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;\n if (tempCodePoint > 127) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 3:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;\n if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 4:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n fourthByte = buf[offset + 3];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;\n if (tempCodePoint > 65535 && tempCodePoint < 1114112) {\n codePoint = tempCodePoint;\n }\n }\n }\n }\n if (codePoint === null) {\n codePoint = 65533;\n bytesPerSequence = 1;\n } else if (codePoint > 65535) {\n codePoint -= 65536;\n res.push(codePoint >>> 10 & 1023 | 55296);\n codePoint = 56320 | codePoint & 1023;\n }\n res.push(codePoint);\n offset += bytesPerSequence;\n }\n return decodeCodePointsArray(res);\n}\nconst MAX_ARGUMENTS_LENGTH = 4096;\nexport function decodeCodePointsArray(codePoints) {\n const len = codePoints.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints);\n }\n let res = '';\n let i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));\n }\n return res;\n}", "import {\n alloc,\n concat,\n slice\n} from './byte-utils.js';\nconst defaultChunkSize = 256;\nexport class Bl {\n constructor(chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize;\n this.cursor = 0;\n this.maxCursor = -1;\n this.chunks = [];\n this._initReuseChunk = null;\n }\n reset() {\n this.cursor = 0;\n this.maxCursor = -1;\n if (this.chunks.length) {\n this.chunks = [];\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk);\n this.maxCursor = this._initReuseChunk.length - 1;\n }\n }\n push(bytes) {\n let topChunk = this.chunks[this.chunks.length - 1];\n const newMax = this.cursor + bytes.length;\n if (newMax <= this.maxCursor + 1) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n topChunk.set(bytes, chunkPos);\n } else {\n if (topChunk) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n if (chunkPos < topChunk.length) {\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);\n this.maxCursor = this.cursor - 1;\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n topChunk = alloc(this.chunkSize);\n this.chunks.push(topChunk);\n this.maxCursor += topChunk.length;\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk;\n }\n topChunk.set(bytes, 0);\n } else {\n this.chunks.push(bytes);\n this.maxCursor += bytes.length;\n }\n }\n this.cursor += bytes.length;\n }\n toBytes(reset = false) {\n let byts;\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0];\n if (reset && this.cursor > chunk.length / 2) {\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);\n this._initReuseChunk = null;\n this.chunks = [];\n } else {\n byts = slice(chunk, 0, this.cursor);\n }\n } else {\n byts = concat(this.chunks, this.cursor);\n }\n if (reset) {\n this.reset();\n }\n return byts;\n }\n}", "const decodeErrPrefix = 'CBOR decode error:';\nconst encodeErrPrefix = 'CBOR encode error:';\nconst uintMinorPrefixBytes = [];\nuintMinorPrefixBytes[23] = 1;\nuintMinorPrefixBytes[24] = 2;\nuintMinorPrefixBytes[25] = 3;\nuintMinorPrefixBytes[26] = 5;\nuintMinorPrefixBytes[27] = 9;\nfunction assertEnoughData(data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${ decodeErrPrefix } not enough data for type`);\n }\n}\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n decodeErrPrefix,\n assertEnoughData\n} from './common.js';\nexport const uintBoundaries = [\n 24,\n 256,\n 65536,\n 4294967296,\n BigInt('18446744073709551616')\n];\nexport function readUint8(data, offset, options) {\n assertEnoughData(data, offset, 1);\n const value = data[offset];\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint16(data, offset, options) {\n assertEnoughData(data, offset, 2);\n const value = data[offset] << 8 | data[offset + 1];\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint32(data, offset, options) {\n assertEnoughData(data, offset, 4);\n const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint64(data, offset, options) {\n assertEnoughData(data, offset, 8);\n const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value);\n }\n if (options.allowBigInt === true) {\n return value;\n }\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n}\nexport function decodeUint8(data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2);\n}\nexport function decodeUint16(data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3);\n}\nexport function decodeUint32(data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5);\n}\nexport function decodeUint64(data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9);\n}\nexport function encodeUint(buf, token) {\n return encodeUintValue(buf, 0, token.value);\n}\nexport function encodeUintValue(buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint);\n buf.push([major | nuint]);\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint);\n buf.push([\n major | 24,\n nuint\n ]);\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint);\n buf.push([\n major | 25,\n nuint >>> 8,\n nuint & 255\n ]);\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint);\n buf.push([\n major | 26,\n nuint >>> 24 & 255,\n nuint >>> 16 & 255,\n nuint >>> 8 & 255,\n nuint & 255\n ]);\n } else {\n const buint = BigInt(uint);\n if (buint < uintBoundaries[4]) {\n const set = [\n major | 27,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ];\n let lo = Number(buint & BigInt(4294967295));\n let hi = Number(buint >> BigInt(32) & BigInt(4294967295));\n set[8] = lo & 255;\n lo = lo >> 8;\n set[7] = lo & 255;\n lo = lo >> 8;\n set[6] = lo & 255;\n lo = lo >> 8;\n set[5] = lo & 255;\n set[4] = hi & 255;\n hi = hi >> 8;\n set[3] = hi & 255;\n hi = hi >> 8;\n set[2] = hi & 255;\n hi = hi >> 8;\n set[1] = hi & 255;\n buf.push(set);\n } else {\n throw new Error(`${ decodeErrPrefix } encountered BigInt larger than allowable range`);\n }\n }\n}\nencodeUint.encodedSize = function encodedSize(token) {\n return encodeUintValue.encodedSize(token.value);\n};\nencodeUintValue.encodedSize = function encodedSize(uint) {\n if (uint < uintBoundaries[0]) {\n return 1;\n }\n if (uint < uintBoundaries[1]) {\n return 2;\n }\n if (uint < uintBoundaries[2]) {\n return 3;\n }\n if (uint < uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeUint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nexport function decodeNegint8(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeNegint16(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeNegint32(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5);\n}\nconst neg1b = BigInt(-1);\nconst pos1b = BigInt(1);\nexport function decodeNegint64(data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options);\n if (typeof int !== 'bigint') {\n const value = -1 - int;\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9);\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9);\n}\nexport function encodeNegint(buf, token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned);\n}\nencodeNegint.encodedSize = function encodedSize(token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n if (unsigned < uint.uintBoundaries[0]) {\n return 1;\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2;\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3;\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeNegint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport {\n compare,\n fromString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length);\n const buf = slice(data, pos + prefix, pos + prefix + length);\n return new Token(Type.bytes, buf, prefix + length);\n}\nexport function decodeBytesCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeBytes8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeBytes16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeBytes32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeBytes64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer bytes lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nfunction tokenBytes(token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value;\n }\n return token.encodedBytes;\n}\nexport function encodeBytes(buf, token) {\n const bytes = tokenBytes(token);\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length);\n buf.push(bytes);\n}\nencodeBytes.encodedSize = function encodedSize(token) {\n const bytes = tokenBytes(token);\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length;\n};\nencodeBytes.compareTokens = function compareTokens(tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2));\n};\nexport function compareBytes(b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);\n}", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport { encodeBytes } from './2bytes.js';\nimport {\n toString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length, options) {\n const totLength = prefix + length;\n assertEnoughData(data, pos, totLength);\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength);\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength);\n }\n return tok;\n}\nexport function decodeStringCompact(data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options);\n}\nexport function decodeString8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options);\n}\nexport function decodeString16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options);\n}\nexport function decodeString32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options);\n}\nexport function decodeString64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer string lengths not supported`);\n }\n return toToken(data, pos, 9, l, options);\n}\nexport const encodeString = encodeBytes;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix);\n}\nexport function decodeArrayCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeArray8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeArray16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeArray32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeArray64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer array lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeArrayIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeArray(buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value);\n}\nencodeArray.compareTokens = uint.encodeUint.compareTokens;\nencodeArray.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix);\n}\nexport function decodeMapCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeMap8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeMap16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeMap32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeMap64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer map lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeMapIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeMap(buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value);\n}\nencodeMap.compareTokens = uint.encodeUint.compareTokens;\nencodeMap.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nexport function decodeTagCompact(_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1);\n}\nexport function decodeTag8(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeTag16(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeTag32(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5);\n}\nexport function decodeTag64(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9);\n}\nexport function encodeTag(buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value);\n}\nencodeTag.compareTokens = uint.encodeUint.compareTokens;\nencodeTag.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport { decodeErrPrefix } from './common.js';\nimport { encodeUint } from './0uint.js';\nconst MINOR_FALSE = 20;\nconst MINOR_TRUE = 21;\nconst MINOR_NULL = 22;\nconst MINOR_UNDEFINED = 23;\nexport function decodeUndefined(_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${ decodeErrPrefix } undefined values are not supported`);\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1);\n }\n return new Token(Type.undefined, undefined, 1);\n}\nexport function decodeBreak(_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return new Token(Type.break, undefined, 1);\n}\nfunction createToken(value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${ decodeErrPrefix } NaN values are not supported`);\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${ decodeErrPrefix } Infinity values are not supported`);\n }\n }\n return new Token(Type.float, value, bytes);\n}\nexport function decodeFloat16(data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options);\n}\nexport function decodeFloat32(data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options);\n}\nexport function decodeFloat64(data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options);\n}\nexport function encodeFloat(buf, token, options) {\n const float = token.value;\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE]);\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE]);\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL]);\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED]);\n } else {\n let decoded;\n let success = false;\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 249;\n buf.push(ui8a.slice(0, 3));\n success = true;\n } else {\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n ui8a[0] = 250;\n buf.push(ui8a.slice(0, 5));\n success = true;\n }\n }\n }\n if (!success) {\n encodeFloat64(float);\n decoded = readFloat64(ui8a, 1);\n ui8a[0] = 251;\n buf.push(ui8a.slice(0, 9));\n }\n }\n}\nencodeFloat.encodedSize = function encodedSize(token, options) {\n const float = token.value;\n if (float === false || float === true || float === null || float === undefined) {\n return 1;\n }\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n let decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n return 3;\n }\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n return 5;\n }\n }\n return 9;\n};\nconst buffer = new ArrayBuffer(9);\nconst dataView = new DataView(buffer, 1);\nconst ui8a = new Uint8Array(buffer, 0);\nfunction encodeFloat16(inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 31744, false);\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 64512, false);\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 32256, false);\n } else {\n dataView.setFloat32(0, inp);\n const valu32 = dataView.getUint32(0);\n const exponent = (valu32 & 2139095040) >> 23;\n const mantissa = valu32 & 8388607;\n if (exponent === 255) {\n dataView.setUint16(0, 31744, false);\n } else if (exponent === 0) {\n dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);\n } else {\n const logicalExponent = exponent - 127;\n if (logicalExponent < -24) {\n dataView.setUint16(0, 0);\n } else if (logicalExponent < -14) {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false);\n } else {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);\n }\n }\n }\n}\nfunction readFloat16(ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${ decodeErrPrefix } not enough data for float16`);\n }\n const half = (ui8a[pos] << 8) + ui8a[pos + 1];\n if (half === 31744) {\n return Infinity;\n }\n if (half === 64512) {\n return -Infinity;\n }\n if (half === 32256) {\n return NaN;\n }\n const exp = half >> 10 & 31;\n const mant = half & 1023;\n let val;\n if (exp === 0) {\n val = mant * 2 ** -24;\n } else if (exp !== 31) {\n val = (mant + 1024) * 2 ** (exp - 25);\n } else {\n val = mant === 0 ? Infinity : NaN;\n }\n return half & 32768 ? -val : val;\n}\nfunction encodeFloat32(inp) {\n dataView.setFloat32(0, inp, false);\n}\nfunction readFloat32(ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${ decodeErrPrefix } not enough data for float32`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false);\n}\nfunction encodeFloat64(inp) {\n dataView.setFloat64(0, inp, false);\n}\nfunction readFloat64(ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${ decodeErrPrefix } not enough data for float64`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false);\n}\nencodeFloat.compareTokens = encodeUint.compareTokens;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport * as negint from './1negint.js';\nimport * as bytes from './2bytes.js';\nimport * as string from './3string.js';\nimport * as array from './4array.js';\nimport * as map from './5map.js';\nimport * as tag from './6tag.js';\nimport * as float from './7float.js';\nimport { decodeErrPrefix } from './common.js';\nimport { fromArray } from './byte-utils.js';\nfunction invalidMinor(data, pos, minor) {\n throw new Error(`${ decodeErrPrefix } encountered invalid minor (${ minor }) for major ${ data[pos] >>> 5 }`);\n}\nfunction errorer(msg) {\n return () => {\n throw new Error(`${ decodeErrPrefix } ${ msg }`);\n };\n}\nexport const jump = [];\nfor (let i = 0; i <= 23; i++) {\n jump[i] = invalidMinor;\n}\njump[24] = uint.decodeUint8;\njump[25] = uint.decodeUint16;\njump[26] = uint.decodeUint32;\njump[27] = uint.decodeUint64;\njump[28] = invalidMinor;\njump[29] = invalidMinor;\njump[30] = invalidMinor;\njump[31] = invalidMinor;\nfor (let i = 32; i <= 55; i++) {\n jump[i] = invalidMinor;\n}\njump[56] = negint.decodeNegint8;\njump[57] = negint.decodeNegint16;\njump[58] = negint.decodeNegint32;\njump[59] = negint.decodeNegint64;\njump[60] = invalidMinor;\njump[61] = invalidMinor;\njump[62] = invalidMinor;\njump[63] = invalidMinor;\nfor (let i = 64; i <= 87; i++) {\n jump[i] = bytes.decodeBytesCompact;\n}\njump[88] = bytes.decodeBytes8;\njump[89] = bytes.decodeBytes16;\njump[90] = bytes.decodeBytes32;\njump[91] = bytes.decodeBytes64;\njump[92] = invalidMinor;\njump[93] = invalidMinor;\njump[94] = invalidMinor;\njump[95] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 96; i <= 119; i++) {\n jump[i] = string.decodeStringCompact;\n}\njump[120] = string.decodeString8;\njump[121] = string.decodeString16;\njump[122] = string.decodeString32;\njump[123] = string.decodeString64;\njump[124] = invalidMinor;\njump[125] = invalidMinor;\njump[126] = invalidMinor;\njump[127] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 128; i <= 151; i++) {\n jump[i] = array.decodeArrayCompact;\n}\njump[152] = array.decodeArray8;\njump[153] = array.decodeArray16;\njump[154] = array.decodeArray32;\njump[155] = array.decodeArray64;\njump[156] = invalidMinor;\njump[157] = invalidMinor;\njump[158] = invalidMinor;\njump[159] = array.decodeArrayIndefinite;\nfor (let i = 160; i <= 183; i++) {\n jump[i] = map.decodeMapCompact;\n}\njump[184] = map.decodeMap8;\njump[185] = map.decodeMap16;\njump[186] = map.decodeMap32;\njump[187] = map.decodeMap64;\njump[188] = invalidMinor;\njump[189] = invalidMinor;\njump[190] = invalidMinor;\njump[191] = map.decodeMapIndefinite;\nfor (let i = 192; i <= 215; i++) {\n jump[i] = tag.decodeTagCompact;\n}\njump[216] = tag.decodeTag8;\njump[217] = tag.decodeTag16;\njump[218] = tag.decodeTag32;\njump[219] = tag.decodeTag64;\njump[220] = invalidMinor;\njump[221] = invalidMinor;\njump[222] = invalidMinor;\njump[223] = invalidMinor;\nfor (let i = 224; i <= 243; i++) {\n jump[i] = errorer('simple values are not supported');\n}\njump[244] = invalidMinor;\njump[245] = invalidMinor;\njump[246] = invalidMinor;\njump[247] = float.decodeUndefined;\njump[248] = errorer('simple values are not supported');\njump[249] = float.decodeFloat16;\njump[250] = float.decodeFloat32;\njump[251] = float.decodeFloat64;\njump[252] = invalidMinor;\njump[253] = invalidMinor;\njump[254] = invalidMinor;\njump[255] = float.decodeBreak;\nexport const quick = [];\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1);\n}\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1);\n}\nquick[64] = new Token(Type.bytes, new Uint8Array(0), 1);\nquick[96] = new Token(Type.string, '', 1);\nquick[128] = new Token(Type.array, 0, 1);\nquick[160] = new Token(Type.map, 0, 1);\nquick[244] = new Token(Type.false, false, 1);\nquick[245] = new Token(Type.true, true, 1);\nquick[246] = new Token(Type.null, null, 1);\nexport function quickEncodeToken(token) {\n switch (token.type) {\n case Type.false:\n return fromArray([244]);\n case Type.true:\n return fromArray([245]);\n case Type.null:\n return fromArray([246]);\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([64]);\n }\n return;\n case Type.string:\n if (token.value === '') {\n return fromArray([96]);\n }\n return;\n case Type.array:\n if (token.value === 0) {\n return fromArray([128]);\n }\n return;\n case Type.map:\n if (token.value === 0) {\n return fromArray([160]);\n }\n return;\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)]);\n }\n return;\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)]);\n }\n }\n}", "import { is } from './is.js';\nimport {\n Token,\n Type\n} from './token.js';\nimport { Bl } from './bl.js';\nimport { encodeErrPrefix } from './common.js';\nimport { quickEncodeToken } from './jump.js';\nimport { asU8A } from './byte-utils.js';\nimport { encodeUint } from './0uint.js';\nimport { encodeNegint } from './1negint.js';\nimport { encodeBytes } from './2bytes.js';\nimport { encodeString } from './3string.js';\nimport { encodeArray } from './4array.js';\nimport { encodeMap } from './5map.js';\nimport { encodeTag } from './6tag.js';\nimport { encodeFloat } from './7float.js';\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n};\nexport function makeCborEncoders() {\n const encoders = [];\n encoders[Type.uint.major] = encodeUint;\n encoders[Type.negint.major] = encodeNegint;\n encoders[Type.bytes.major] = encodeBytes;\n encoders[Type.string.major] = encodeString;\n encoders[Type.array.major] = encodeArray;\n encoders[Type.map.major] = encodeMap;\n encoders[Type.tag.major] = encodeTag;\n encoders[Type.float.major] = encodeFloat;\n return encoders;\n}\nconst cborEncoders = makeCborEncoders();\nconst buf = new Bl();\nclass Ref {\n constructor(obj, parent) {\n this.obj = obj;\n this.parent = parent;\n }\n includes(obj) {\n let p = this;\n do {\n if (p.obj === obj) {\n return true;\n }\n } while (p = p.parent);\n return false;\n }\n static createCheck(stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${ encodeErrPrefix } object contains circular references`);\n }\n return new Ref(obj, stack);\n }\n}\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n};\nconst typeEncoders = {\n number(obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj);\n } else if (obj >= 0) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n bigint(obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n Uint8Array(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj);\n },\n string(obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj);\n },\n boolean(obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false;\n },\n null(_obj, _typ, _options, _refStack) {\n return simpleTokens.null;\n },\n undefined(_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined;\n },\n ArrayBuffer(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj));\n },\n DataView(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));\n },\n Array(obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyArray,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyArray;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack);\n }\n if (options.addBreakTokens) {\n return [\n new Token(Type.array, obj.length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.array, obj.length),\n entries\n ];\n },\n Object(obj, typ, options, refStack) {\n const isMap = typ !== 'Object';\n const keys = isMap ? obj.keys() : Object.keys(obj);\n const length = isMap ? obj.size : keys.length;\n if (!length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyMap,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyMap;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ];\n }\n sortMapEntries(entries, options);\n if (options.addBreakTokens) {\n return [\n new Token(Type.map, length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.map, length),\n entries\n ];\n }\n};\ntypeEncoders.Map = typeEncoders.Object;\ntypeEncoders.Buffer = typeEncoders.Uint8Array;\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${ typ }Array`] = typeEncoders.DataView;\n}\nfunction objectToTokens(obj, options = {}, refStack) {\n const typ = is(obj);\n const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack);\n if (tokens != null) {\n return tokens;\n }\n }\n const typeEncoder = typeEncoders[typ];\n if (!typeEncoder) {\n throw new Error(`${ encodeErrPrefix } unsupported type: ${ typ }`);\n }\n return typeEncoder(obj, typ, options, refStack);\n}\nfunction sortMapEntries(entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter);\n }\n}\nfunction mapSorter(e1, e2) {\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type);\n }\n const major = keyToken1.type.major;\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);\n if (tcmp === 0) {\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone');\n }\n return tcmp;\n}\nfunction tokensToEncoded(buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options);\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options);\n }\n}\nfunction encodeCustom(data, encoders, options) {\n const tokens = objectToTokens(data, options);\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens);\n if (quickBytes) {\n return quickBytes;\n }\n const encoder = encoders[tokens.type.major];\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options);\n const buf = new Bl(size);\n encoder(buf, tokens, options);\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${ tokens } was wrong`);\n }\n return asU8A(buf.chunks[0]);\n }\n }\n buf.reset();\n tokensToEncoded(buf, tokens, encoders, options);\n return buf.toBytes(true);\n}\nfunction encode(data, options) {\n options = Object.assign({}, defaultEncodeOptions, options);\n return encodeCustom(data, cborEncoders, options);\n}\nexport {\n objectToTokens,\n encode,\n encodeCustom,\n Ref\n};", "import { decodeErrPrefix } from './common.js';\nimport { Type } from './token.js';\nimport {\n jump,\n quick\n} from './jump.js';\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n};\nclass Tokeniser {\n constructor(data, options = {}) {\n this.pos = 0;\n this.data = data;\n this.options = options;\n }\n done() {\n return this.pos >= this.data.length;\n }\n next() {\n const byt = this.data[this.pos];\n let token = quick[byt];\n if (token === undefined) {\n const decoder = jump[byt];\n if (!decoder) {\n throw new Error(`${ decodeErrPrefix } no decoder for major type ${ byt >>> 5 } (byte 0x${ byt.toString(16).padStart(2, '0') })`);\n }\n const minor = byt & 31;\n token = decoder(this.data, this.pos, minor, this.options);\n }\n this.pos += token.encodedLength;\n return token;\n }\n}\nconst DONE = Symbol.for('DONE');\nconst BREAK = Symbol.for('BREAK');\nfunction tokenToArray(token, tokeniser, options) {\n const arr = [];\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options);\n if (value === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed array`);\n }\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found array but not enough entries (got ${ i }, expected ${ token.value })`);\n }\n arr[i] = value;\n }\n return arr;\n}\nfunction tokenToMap(token, tokeniser, options) {\n const useMaps = options.useMaps === true;\n const obj = useMaps ? undefined : {};\n const m = useMaps ? new Map() : undefined;\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options);\n if (key === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed map`);\n }\n if (key === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no key], expected ${ token.value })`);\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${ decodeErrPrefix } non-string keys not supported (got ${ typeof key })`);\n }\n if (options.rejectDuplicateMapKeys === true) {\n if (useMaps && m.has(key) || !useMaps && key in obj) {\n throw new Error(`${ decodeErrPrefix } found repeat map key \"${ key }\"`);\n }\n }\n const value = tokensToObject(tokeniser, options);\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no value], expected ${ token.value })`);\n }\n if (useMaps) {\n m.set(key, value);\n } else {\n obj[key] = value;\n }\n }\n return useMaps ? m : obj;\n}\nfunction tokensToObject(tokeniser, options) {\n if (tokeniser.done()) {\n return DONE;\n }\n const token = tokeniser.next();\n if (token.type === Type.break) {\n return BREAK;\n }\n if (token.type.terminal) {\n return token.value;\n }\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options);\n }\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options);\n }\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options);\n return options.tags[token.value](tagged);\n }\n throw new Error(`${ decodeErrPrefix } tag not supported (${ token.value })`);\n }\n throw new Error('unsupported');\n}\nfunction decode(data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${ decodeErrPrefix } data to decode must be a Uint8Array`);\n }\n options = Object.assign({}, defaultDecodeOptions, options);\n const tokeniser = options.tokenizer || new Tokeniser(data, options);\n const decoded = tokensToObject(tokeniser, options);\n if (decoded === DONE) {\n throw new Error(`${ decodeErrPrefix } did not find any content to decode`);\n }\n if (decoded === BREAK) {\n throw new Error(`${ decodeErrPrefix } got unexpected break`);\n }\n if (!tokeniser.done()) {\n throw new Error(`${ decodeErrPrefix } too many terminals, data makes no sense`);\n }\n return decoded;\n}\nexport {\n Tokeniser,\n tokensToObject,\n decode\n};", "import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\ndecodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => cborg.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(data, decodeOptions)\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n", "// @ts-check\n\nimport { from } from './base.js'\nimport { fromString, toString } from '../bytes.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "// @ts-check\n\nimport { coerce } from '../bytes.js'\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nexport const name = 'raw'\nexport const code = 0x55\n\n/**\n * @param {Uint8Array} node\n * @returns {ByteView}\n */\nexport const encode = (node) => coerce(node)\n\n/**\n * @param {ByteView} data\n * @returns {Uint8Array}\n */\nexport const decode = (data) => coerce(data)\n", "// @ts-check\n\nimport * as identityBase from './bases/identity.js'\nimport * as base2 from './bases/base2.js'\nimport * as base8 from './bases/base8.js'\nimport * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.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 base256emoji from './bases/base256emoji.js'\nimport * as sha2 from './hashes/sha2.js'\nimport * as identity from './hashes/identity.js'\n\nimport * as raw from './codecs/raw.js'\nimport * as json from './codecs/json.js'\n\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n", "\nexport class NotInitializedError extends Error {\n constructor (message = 'not initialized') {\n super(message)\n this.name = 'NotInitializedError'\n this.code = NotInitializedError.code\n }\n}\nNotInitializedError.code = 'ERR_NOT_INITIALIZED'\n\nexport class AlreadyInitializingError extends Error {\n constructor (message = 'cannot initialize an initializing node') {\n super(message)\n this.name = 'AlreadyInitializingError'\n this.code = AlreadyInitializedError.code\n }\n}\nAlreadyInitializingError.code = 'ERR_ALREADY_INITIALIZING'\n\nexport class AlreadyInitializedError extends Error {\n constructor (message = 'cannot re-initialize an initialized node') {\n super(message)\n this.name = 'AlreadyInitializedError'\n this.code = AlreadyInitializedError.code\n }\n}\nAlreadyInitializedError.code = 'ERR_ALREADY_INITIALIZED'\n\nexport class NotStartedError extends Error {\n constructor (message = 'not started') {\n super(message)\n this.name = 'NotStartedError'\n this.code = NotStartedError.code\n }\n}\nNotStartedError.code = 'ERR_NOT_STARTED'\n\nexport class AlreadyStartingError extends Error {\n constructor (message = 'cannot start, already startin') {\n super(message)\n this.name = 'AlreadyStartingError'\n this.code = AlreadyStartingError.code\n }\n}\nAlreadyStartingError.code = 'ERR_ALREADY_STARTING'\n\nexport class AlreadyStartedError extends Error {\n constructor (message = 'cannot start, already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n this.code = AlreadyStartedError.code\n }\n}\nAlreadyStartedError.code = 'ERR_ALREADY_STARTED'\n\nexport class NotEnabledError extends Error {\n constructor (message = 'not enabled') {\n super(message)\n this.name = 'NotEnabledError'\n this.code = NotEnabledError.code\n }\n}\nNotEnabledError.code = 'ERR_NOT_ENABLED'\n", "/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n }\n\n return buf\n}\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\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.\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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 function encode (source) {\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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 function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) 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}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase}\n */\n encode (bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.UnibaseDecoder}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\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 /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder}\n * @implements {API.CombobaseDecoder}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder|ComposedDecoder} decoder\n * @returns {ComposedDecoder}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\n return decoder.decode(input)\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}\n\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} left\n * @param {API.UnibaseDecoder|API.CombobaseDecoder} right\n * @returns {ComposedDecoder}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec}\n * @implements {API.MultibaseEncoder}\n * @implements {API.MultibaseDecoder}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\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\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * bitsPerChar) & 7) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const 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", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "// @ts-check\n\nimport { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n", "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\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 \n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const 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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\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", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n 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})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n", "import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from \"./link/interface.js\"\nimport * as varint from './varint.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\n/**\n * @template {API.Link} T\n * @template {string} Prefix\n * @param {T} link\n * @param {API.MultibaseEncoder} [base]\n * @returns {API.ToString}\n */\nexport const format = (link, base) => {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder<\"z\">} */ (base) || base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n /** @type {API.MultibaseEncoder} */ (base || base32.encoder)\n )\n }\n}\n\n/**\n * @template {API.UnknownLink} Link\n * @param {Link} link\n * @returns {API.LinkJSON}\n */\nexport const toJSON = (link) => ({\n '/': format(link)\n})\n\n/**\n * @template {API.UnknownLink} Link\n * @param {API.LinkJSON} json\n */\nexport const fromJSON = (json) =>\n CID.parse(json['/'])\n\n/** @type {WeakMap>} */\nconst cache = new WeakMap()\n\n/**\n * @param {API.UnknownLink} cid\n * @returns {Map}\n */\nconst 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}\n\n/**\n * @template {unknown} [Data=unknown]\n * @template {number} [Format=number]\n * @template {number} [Alg=number]\n * @template {API.Version} [Version=API.Version]\n * @implements {API.Link}\n */\n\nexport class CID {\n /**\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content.\n * @param {Uint8Array} bytes\n */\n constructor (version, code, multihash, bytes) {\n /** @readonly */\n this.code = code\n /** @readonly */\n this.version = version\n /** @readonly */\n this.multihash = multihash\n /** @readonly */\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n /** @readonly */\n this['/'] = bytes\n }\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\n // ArrayBufferView\n get byteOffset () {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength () {\n return this.bytes.byteLength\n }\n\n /**\n * @returns {CID}\n */\n toV0 () {\n switch (this.version) {\n case 0: {\n return /** @type {CID} */ (this)\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return /** @type {CID} */ (\n CID.createV0(\n /** @type {API.MultihashDigest} */ (multihash)\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @returns {CID}\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 /** @type {CID} */ (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return /** @type {CID} */ (this)\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n /**\n * @param {unknown} other\n * @returns {other is CID}\n */\n equals (other) {\n return CID.equals(this, other)\n }\n\n /**\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {API.Link} self\n * @param {unknown} other\n * @returns {other is CID}\n */\n static equals (self, other) {\n const unknown =\n /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (\n other\n )\n return (\n unknown &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n /**\n * @param {API.MultibaseEncoder} [base]\n * @returns {string}\n */\n toString (base) {\n return format(this, base)\n }\n\n /**\n * @returns {API.LinkJSON}\n */\n toJSON () {\n return { '/': format(this) }\n }\n\n link () {\n return this\n }\n\n get [Symbol.toStringTag] () {\n return 'CID'\n }\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n return `CID(${this.toString()})`\n }\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 * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @template {unknown} U\n * @param {API.Link|U} input\n * @returns {CID|null}\n */\n static asCID (input) {\n if (input == null) {\n return null\n }\n\n const value = /** @type {any} */ (input)\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n /** @type {API.MultihashDigest} */ (multihash),\n 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 =\n /** @type {API.MultihashDigest} */\n (Digest.decode(multihash))\n return CID.create(version, code, digest)\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 /**\n *\n * @template {unknown} Data\n * @template {number} Format\n * @template {number} Alg\n * @template {API.Version} Version\n * @param {Version} version - Version of the CID\n * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param {API.MultihashDigest} digest - (Multi)hash of the of the content.\n * @returns {CID}\n */\n static create (version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n *\n * @template {unknown} [T=unknown]\n * @param {API.MultihashDigest} digest - Multihash.\n * @returns {CID}\n */\n static createV0 (digest) {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @param {Code} code - Content encoding format code.\n * @param {API.MultihashDigest} digest - Miltihash of the content.\n * @returns {CID}\n */\n static createV1 (code, digest) {\n return CID.create(1, code, digest)\n }\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 * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ByteView>} bytes\n * @returns {CID}\n */\n static decode (bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length) {\n throw new Error('Incorrect length')\n }\n return cid\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} bytes\n * @returns {[CID, Uint8Array]}\n */\n static decodeFirst (bytes) {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(/** @type {API.MultihashDigest} */ (digest))\n : CID.createV1(specs.codec, digest)\n return [/** @type {CID} */(cid), bytes.subarray(specs.size)]\n }\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 * @template {unknown} T\n * @template {number} C\n * @template {number} A\n * @template {API.Version} V\n * @param {API.ByteView>} initialBytes\n * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}\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\n let version = /** @type {V} */ (next())\n let codec = /** @type {C} */ (DAG_PB_CODE)\n if (/** @type {number} */(version) === 18) {\n // CIDv0\n version = /** @type {V} */ (0)\n offset = 0\n } else {\n codec = /** @type {C} */ (next())\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = /** @type {A} */ (next()) // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {CID}\n */\n static parse (source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @template {unknown} Data\n * @template {number} Code\n * @template {number} Alg\n * @template {API.Version} Ver\n * @param {API.ToString, Prefix>} source\n * @param {API.MultibaseDecoder} [base]\n * @returns {[Prefix, API.ByteView>]}\n */\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base || base58btc\n return [\n /** @type {Prefix} */ (base58btc.prefix),\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base || base58btc\n return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base || base32\n return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [/** @type {Prefix} */(source[0]), base.decode(source)]\n }\n }\n}\n\n/**\n *\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder<'z'>} base\n */\nconst 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\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 } else {\n return cid\n }\n}\n\n/**\n * @template {string} Prefix\n * @param {Uint8Array} bytes\n * @param {Map} cache\n * @param {API.MultibaseEncoder} base\n */\nconst 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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\n/**\n * @param {API.Version} version\n * @param {number} code\n * @param {Uint8Array} multihash\n * @returns {Uint8Array}\n */\nconst 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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "// @ts-check\n\nimport * 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'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n", "import { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n if (globalThis.Buffer?.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size))\n }\n\n return new Uint8Array(size)\n}\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: number = 0): Uint8Array {\n if (globalThis.Buffer?.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size))\n }\n\n return new Uint8Array(size)\n}\n", "import { bases } from 'multiformats/basics'\nimport { allocUnsafe } from '../alloc.js'\nimport type { MultibaseCodec } from 'multiformats'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\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})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\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\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import { asUint8Array } from './util/as-uint8array.js'\nimport bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'))\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (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}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode (node: T): ByteView {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode (data: ByteView | ArrayBufferView): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "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'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\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: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\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})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\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\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\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\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\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}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\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}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", null, null, "import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\n\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\n\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]);\n\nexport interface IpNetRaw {\n network: Uint8Array;\n mask: Uint8Array;\n}\n\nexport function maskIp(ip: Uint8Array, mask: Uint8Array): Uint8Array {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (\n mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)\n ) {\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}\n\nexport function containsIp(\n net: IpNetRaw,\n ip: Uint8Array | number[] | string\n): boolean {\n if (typeof ip === \"string\") {\n ip = parseIP(ip)!;\n }\n if (ip == null) 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}\n\nexport function iPv4FromIPv6(ip: Uint8Array): Uint8Array {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\n\nexport function isIPv4mappedIPv6(ip: Uint8Array | number[]): boolean {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", null, "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\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: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\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\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\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\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\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: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\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'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\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\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\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\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\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}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\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}\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})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\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}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\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}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\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: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\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\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\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}\n\nfunction onion32bytes (str: string): Uint8Array {\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\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}\n\nfunction bytes2onion (buf: Uint8Array): string {\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", "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'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\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\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\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\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\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\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\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\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\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\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\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\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\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\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\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, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\nclass NoAvailableResolverError extends Error {\n constructor (message = 'No available resolver') {\n super(message)\n this.name = 'NoAvailableResolverError'\n }\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n readonly #string: string\n readonly #tuples: Tuple[]\n readonly #stringTuples: StringTuple[]\n readonly #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\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 } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\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\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\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\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\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\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\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\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\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\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\n decapsulateCode (code: number): Multiaddr {\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\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\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\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\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\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`)\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\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\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\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 /**\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] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\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\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\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 */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\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: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\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/**\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: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\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: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\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?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\nexport const QUICV1 = and(UDP, base('quic-v1'))\n\nconst _WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSockets = or(\n and(_WebSockets, base('p2p')),\n _WebSockets\n)\n\nconst _WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss')),\n and(TCP, base('tls'), base('ws')),\n and(DNS, base('tls'), base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(_WebSocketsSecure, base('p2p')),\n _WebSocketsSecure\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nconst _WebRTCDirect = and(UDP, base('webrtc-direct'), base('certhash'))\nexport const WebRTCDirect = or(\n and(_WebRTCDirect, base('p2p')),\n _WebRTCDirect\n)\n\nconst _WebTransport = and(QUICV1, base('webtransport'), base('certhash'), base('certhash'))\nexport const WebTransport = or(\n and(_WebTransport, base('p2p')),\n _WebTransport\n)\n\n/**\n * @deprecated\n */\nexport const P2PWebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\n/**\n * @deprecated\n */\nexport const P2PWebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n _WebSockets,\n _WebSocketsSecure,\n HTTP,\n HTTPS,\n P2PWebRTCStar,\n P2PWebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS,\n WebRTCDirect,\n WebTransport\n)\n\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(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n P2PWebRTCStar,\n P2PWebRTCDirect,\n WebRTCDirect,\n WebTransport,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = (): Mafmt => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\nexport const WebRTC = or(\n and(Circuit, base('webrtc'), base('p2p')),\n and(Circuit, base('webrtc')),\n and(Reliable, base('webrtc'), base('p2p')),\n and(Reliable, base('webrtc')),\n base('webrtc')\n)\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction): (a: string | Uint8Array | Multiaddr) => boolean {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\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\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches,\n partialMatch\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A suite of util methods that provides efficient validation.\n *\n * Detection of IPFS Paths and identifiers in URLs is a two-stage process:\n *\n * 1. `pathPattern`/`pathGatewayPattern`/`subdomainGatewayPattern` regex is applied to quickly identify potential candidates\n * 2. proper CID validation is applied to remove false-positives\n *\n * @example\n *\n * ```TypeScript\n * import * as isIPFS from 'is-ipfs'\n *\n * isIPFS.multihash('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.multihash('noop') // false\n *\n * isIPFS.cid('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true (CIDv0)\n * isIPFS.cid('bafybeiasb5vpmaounyilfuxbd3lryvosl4yefqrfahsb2esg46q6tu6y5q') // true (CIDv1 in Base32)\n * isIPFS.cid('zdj7WWeQ43G6JJvLWQWZpyHuAMq6uYWRjkBXFad11vE2LHhQ7') // true (CIDv1 in Base58btc)\n * isIPFS.cid('noop') // false\n *\n * isIPFS.base32cid('bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va') // true\n * isIPFS.base32cid('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n *\n * isIPFS.url('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.url('https://ipfs.io/ipfs/QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR?filename=guardian.jpg') // true\n * isIPFS.url('https://ipfs.io/ipns/github.com') // true\n * isIPFS.url('https://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.url('http://en.wikipedia-on-ipfs.org.ipfs.localhost:8080') // true\n * isIPFS.url('https://github.com/ipfs/js-ipfs/blob/master/README.md') // false\n * isIPFS.url('https://google.com') // false\n *\n * isIPFS.path('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.path('/ipfs/QmbcBPAwCDxRMB1Qe7CRQmxdrTSkxKwM9y6rZw2FjGtbsb/?weird-filename=test.jpg') // true\n * isIPFS.path('/ipns/github.com') // true\n * isIPFS.path('/ipfs/js-ipfs/blob/master/README.md') // false\n *\n * isIPFS.urlOrPath('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.urlOrPath('https://ipfs.io/ipns/github.com') // true\n * isIPFS.urlOrPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.urlOrPath('/ipns/github.com') // true\n * isIPFS.urlOrPath('https://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.urlOrPath('https://google.com') // false\n *\n * isIPFS.ipfsUrl('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.ipfsUrl('https://ipfs.io/ipfs/invalid-hash') // false\n *\n * isIPFS.ipnsUrl('https://ipfs.io/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.ipnsUrl('https://ipfs.io/ipns/github.com') // true\n *\n * isIPFS.ipfsPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // true\n * isIPFS.ipfsPath('/ipfs/invalid-hash') // false\n *\n * isIPFS.ipnsPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.ipnsPath('/ipns/github.com') // true\n *\n * isIPFS.cidPath('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o/path/to/file') // true\n * isIPFS.cidPath('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o/') // true\n * isIPFS.cidPath('QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.cidPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o') // false\n * isIPFS.cidPath('/ipfs/QmYjtig7VJQ6XsnUjqqJvj7QaMcCAwtrgNdahSiFofrE7o/file') // false\n *\n * isIPFS.subdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.subdomain('http://bafybeiabc2xofh6tdi6vutusorpumwcikw3hf3st4ecjugo6j52f6xwc6q.ipns.dweb.link') // true\n * isIPFS.subdomain('http://www.bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // false\n * isIPFS.subdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.dweb.link') // false\n *\n * isIPFS.ipfsSubdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.ipfs.dweb.link') // true\n * isIPFS.ipfsSubdomain('http://bafybeie5gq4jxvzmsym6hjlwxej4rwdoxt7wadqvmmwbqi7r27fclha2va.dweb.link') // false\n *\n * isIPFS.ipnsSubdomain('http://bafybeiabc2xofh6tdi6vutusorpumwcikw3hf3st4ecjugo6j52f6xwc6q.ipns.dweb.link') // true\n * isIPFS.ipnsSubdomain('http://bafybeiabc2xofh6tdi6vutusorpumwcikw3hf3st4ecjugo6j52f6xwc6q.dweb.link') // false\n * isIPFS.ipnsSubdomain('http://QmcNioXSC1bfJj1dcFErhUfyjFzoX2HodkRccsFFVJJvg8.ipns.dweb.link') // false\n * isIPFS.ipnsSubdomain('http://en.wikipedia-on-ipfs.org.ipns.localhost:8080') // true (assuming DNSLink)\n * isIPFS.ipnsSubdomain('http://en-wikipedia--on--ipfs-org.ipns.localhost:8080') // true (assuming inlined DNSLink)\n * isIPFS.ipnsSubdomain('http://hostname-without-tld-.ipns.dweb.link') // false (not a CID, invalid DNS label)\n *\n * isIPFS.multiaddr('/ip4/127.0.0.1/udp/1234') // true\n * isIPFS.multiaddr('/ip4/127.0.0.1/udp/1234/http') // true\n * isIPFS.multiaddr('/ip6/::1/udp/1234') // true\n * isIPFS.multiaddr('ip6/::1/udp/1234') // false\n * isIPFS.multiaddr('/yoloinvalid/::1/udp/1234') // false\n *\n * isIPFS.peerMultiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSoooo4') // true\n * isIPFS.peerMultiaddr('/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSoooo4') // true (legacy notation)\n * isIPFS.peerMultiaddr('/ip4/127.0.0.1/tcp/1234/ws/p2p/QmUjNmr8TgJCn1Ao7DvMy4cjoZU15b9bwSCBLE3vwXiwgj') // true\n * isIPFS.peerMultiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSoooo4/p2p-circuit/p2p/QmUjNmr8TgJCn1Ao7DvMy4cjoZU15b9bwSCBLE3vwXiwgj') // true\n * isIPFS.peerMultiaddr('/dnsaddr/bootstrap.libp2p.io') // false (key missing, needs additional DNS lookup to tell if this is valid)\n * isIPFS.peerMultiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN') // true (key present, ip and port can be resolved later)\n * isIPFS.peerMultiaddr('/ip4/127.0.0.1/udp/1234') // false (key missing)\n * ```\n */\n\nimport * as mafmt from '@multiformats/mafmt'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { URL } from 'iso-url'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport const pathGatewayPattern = /^https?:\\/\\/[^/]+\\/(ip[fn]s)\\/([^/?#]+)/\nexport const pathPattern = /^\\/(ip[fn]s)\\/([^/?#]+)/\nconst defaultProtocolMatch = 1\nconst defaultHashMath = 2\n\n// CID, libp2p-key or DNSLink\nexport const subdomainGatewayPattern = /^https?:\\/\\/([^/]+)\\.(ip[fn]s)\\.[^/?]+/\nconst subdomainIdMatch = 1\nconst subdomainProtocolMatch = 2\n\n// Fully qualified domain name (FQDN) that has an explicit .tld suffix\nconst fqdnWithTld = /^(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\\.)+([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])$/\n\nfunction isMultihash (hash: Uint8Array | string): boolean {\n const formatted = convertToString(hash)\n\n if (formatted === false) {\n return false\n }\n\n try {\n Digest.decode(base58btc.decode(`z${formatted}`))\n } catch {\n return false\n }\n\n return true\n}\n\nfunction isMultiaddr (input: string | Uint8Array | Multiaddr): input is Multiaddr {\n try {\n return Boolean(multiaddr(input))\n } catch {\n return false\n }\n}\n\nfunction isBase32EncodedMultibase (hash: CID | string | Uint8Array): boolean {\n try {\n let cid: CID | null\n\n if (isString(hash)) {\n cid = CID.parse(hash)\n } else {\n cid = CID.asCID(hash)\n }\n\n if (cid == null) {\n return false\n }\n\n base32.decode(cid.toString())\n } catch {\n return false\n }\n\n return true\n}\n\nfunction isCID (hash: CID | Uint8Array | string): hash is CID {\n try {\n if (isString(hash)) {\n return Boolean(CID.parse(hash))\n }\n\n if (hash instanceof Uint8Array) {\n return Boolean(CID.decode(hash))\n }\n\n return Boolean(CID.asCID(hash)) // eslint-disable-line no-new\n } catch {\n return false\n }\n}\n\n/**\n * @param {string | Uint8Array | Multiaddr} input\n */\nfunction isPeerMultiaddr (input: string | Uint8Array | Multiaddr): boolean {\n return isMultiaddr(input) && mafmt.P2P.matches(input)\n}\n\n/**\n * @param {string | Uint8Array} input\n * @param {RegExp | string} pattern\n * @param {number} [protocolMatch=1]\n * @param {number} [hashMatch=2]\n */\nfunction isIpfs (input: string | Uint8Array, pattern: RegExp | string, protocolMatch: number = defaultProtocolMatch, hashMatch: number = defaultHashMath): boolean {\n const formatted = convertToString(input)\n if (formatted === false) {\n return false\n }\n\n const match = formatted.match(pattern)\n if (match == null) {\n return false\n }\n\n if (match[protocolMatch] !== 'ipfs') {\n return false\n }\n\n let hash = match[hashMatch]\n\n if (hash != null && pattern === subdomainGatewayPattern) {\n // when doing checks for subdomain context\n // ensure hash is case-insensitive\n // (browsers force-lowercase authority component anyway)\n hash = hash.toLowerCase()\n }\n\n return isCID(hash)\n}\n\n/**\n *\n * @param {string | Uint8Array} input\n * @param {string | RegExp} pattern\n * @param {number} [protocolMatch=1]\n * @param {number} [hashMatch=1]\n */\nfunction isIpns (input: string | Uint8Array, pattern: RegExp | string, protocolMatch: number = defaultProtocolMatch, hashMatch: number = defaultHashMath): boolean {\n const formatted = convertToString(input)\n if (formatted === false) {\n return false\n }\n const match = formatted.match(pattern)\n if (match == null) {\n return false\n }\n\n if (match[protocolMatch] !== 'ipns') {\n return false\n }\n\n let ipnsId = match[hashMatch]\n\n if (ipnsId != null && pattern === subdomainGatewayPattern) {\n // when doing checks for subdomain context\n // ensure ipnsId is case-insensitive\n // (browsers force-lowercase authority compotent anyway)\n ipnsId = ipnsId.toLowerCase()\n // Check if it is cidv1\n if (isCID(ipnsId)) return true\n // Check if it looks like FQDN\n try {\n if (!ipnsId.includes('.') && ipnsId.includes('-')) {\n // name without tld, assuming its inlined into a single DNS label\n // (https://github.com/ipfs/in-web-browsers/issues/169)\n // en-wikipedia--on--ipfs-org \u2192 en.wikipedia-on-ipfs.org\n ipnsId = ipnsId.replace(/--/g, '@').replace(/-/g, '.').replace(/@/g, '-')\n }\n // URL implementation in web browsers forces lowercase of the hostname\n const { hostname } = new URL(`http://${ipnsId}`) // eslint-disable-line no-new\n // Check if potential FQDN has an explicit TLD\n return fqdnWithTld.test(hostname)\n } catch (e) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @param {any} input\n */\nfunction isString (input: any): input is string {\n return typeof input === 'string'\n}\n\n/**\n * @param {Uint8Array | string} input\n */\nfunction convertToString (input: Uint8Array | string): string | false {\n if (input instanceof Uint8Array) {\n return uint8ArrayToString(input, 'base58btc')\n }\n\n if (isString(input)) {\n return input\n }\n\n return false\n}\n\n/**\n * Returns `true` if the provided `url` string includes a valid IPFS subdomain\n * (case-insensitive CIDv1) or `false` otherwise.\n */\nexport const ipfsSubdomain = (url: string | Uint8Array): boolean => isIpfs(url, subdomainGatewayPattern, subdomainProtocolMatch, subdomainIdMatch)\n\n/**\n * Returns `true` if the provided `url` string looks like a valid IPNS subdomain\n * (CIDv1 with `libp2p-key` multicodec or something that looks like a FQDN, for\n * example `en.wikipedia-on-ipfs.org.ipns.localhost:8080`) or `false` otherwise.\n *\n * **Note:** `ipnsSubdomain` method works in offline mode: it does not perform\n * actual IPNS record lookup over DHT or other content routing method. It may\n * return false-positives:\n *\n * - To ensure IPNS record exists, make a call to `/api/v0/name/resolve?arg=`\n * - To ensure DNSLink exists, make a call to `/api/v0/dns?arg=`\n */\nexport const ipnsSubdomain = (url: string | Uint8Array): boolean => isIpns(url, subdomainGatewayPattern, subdomainProtocolMatch, subdomainIdMatch)\n\n/**\n * Returns `true` if the provided `url` string includes a valid IPFS, looks like\n * an IPNS/DNSLink subdomain or `false` otherwise.\n */\nexport const subdomain = (url: string | Uint8Array): boolean => ipfsSubdomain(url) || ipnsSubdomain(url)\n\n/**\n * Returns `true` if the provided string is a valid IPFS url or `false`\n * otherwise.\n */\nexport const ipfsUrl = (url: string | Uint8Array): boolean => isIpfs(url, pathGatewayPattern) || ipfsSubdomain(url)\n\n/**\n * Returns `true` if the provided string is a valid IPNS url or `false`\n * otherwise.\n */\nexport const ipnsUrl = (url: string | Uint8Array): boolean => isIpns(url, pathGatewayPattern) || ipnsSubdomain(url)\n\n/**\n * Returns `true` if the provided string is a valid IPFS or IPNS url or `false`\n * otherwise.\n */\nexport const url = (url: string | Uint8Array): boolean => ipfsUrl(url) || ipnsUrl(url) || subdomain(url)\nexport const path = (path: string | Uint8Array): boolean => isIpfs(path, pathPattern) || isIpns(path, pathPattern)\n\n/**\n * Returns `true` if the provided string or `Uint8Array` is a valid `multihash`\n * or `false` otherwise.\n */\nexport { isMultihash as multihash }\n\n/**\n * Returns `true` if the provided `string`, [`Multiaddr`](https://github.com/multiformats/js-multiaddr)\n * or `Uint8Array` represents a valid multiaddr or `false` otherwise.\n */\nexport { isMultiaddr as multiaddr }\n\n/**\n * Returns `true` if the provided `string`, [`Multiaddr`](https://github.com/multiformats/js-multiaddr)\n * or `Uint8Array` represents a valid libp2p peer multiaddr (matching [`P2P`\n * format from `mafmt`](https://github.com/multiformats/js-mafmt#api)) or\n * `false` otherwise.\n */\nexport { isPeerMultiaddr as peerMultiaddr }\n\n/**\n * Returns `true` if the provided string, `Uint8Array` or [`CID`](https://github.com/multiformats/js-multiformats/#readme)\n * object represents a valid [CID](https://docs.ipfs.io/guides/concepts/cid/) or\n * `false` otherwise.\n */\nexport { isCID as cid }\n\n/**\n * Returns `true` if the provided string is a valid `CID` in Base32 encoding or\n * `false` otherwise.\n */\nexport const base32cid = (cid: CID | string | Uint8Array): boolean => (isCID(cid) && isBase32EncodedMultibase(cid))\n\n/**\n * Returns `true` if the provided string is a valid IPFS or IPNS path or `false`\n * otherwise.\n */\nexport const ipfsPath = (path: string | Uint8Array): boolean => isIpfs(path, pathPattern)\n\n/**\n * Returns `true` if the provided string is a valid IPNS path or `false`\n * otherwise.\n */\nexport const ipnsPath = (path: string | Uint8Array): boolean => isIpns(path, pathPattern)\n\n/**\n * Returns `true` if the provided string is a valid IPFS or IPNS url or path or\n * `false` otherwise.\n */\nexport const urlOrPath = (x: string | Uint8Array): boolean => url(x) || path(x)\n\n/**\n * Returns `true` if the provided string is a valid \"CID path\" (IPFS path\n * without `/ipfs/` prefix) or `false` otherwise.\n */\nexport const cidPath = (path: string | Uint8Array | CID): boolean => isString(path) && !isCID(path) && isIpfs(`/ipfs/${path}`, pathPattern)\n", "export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n", "// @ts-check\n\nimport { from } from './base.js'\nimport { fromString, toString } from '../bytes.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])))\nconst alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])))\n\n/**\n * @param {Uint8Array} data\n * @returns {string}\n */\nfunction encode (data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nfunction decode (str) {\n const byts = []\n for (const char of str) {\n const byt = alphabetCharsToBytes[/** @type {number} */ (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}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n 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})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await>}\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise|T} Await\n */\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code = 0x0\nconst name = 'identity'\n\n/** @type {(input:Uint8Array) => Uint8Array} */\nconst encode = coerce\n\n/**\n * @param {Uint8Array} input\n * @returns {Digest.Digest}\n */\nconst digest = (input) => Digest.create(code, encode(input))\n\nexport const identity = { code, name, encode, digest }\n", "// @ts-check\n\nimport { coerce } from '../bytes.js'\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nexport const name = 'raw'\nexport const code = 0x55\n\n/**\n * @param {Uint8Array} node\n * @returns {ByteView}\n */\nexport const encode = (node) => coerce(node)\n\n/**\n * @param {ByteView} data\n * @returns {Uint8Array}\n */\nexport const decode = (data) => coerce(data)\n", "// @ts-check\n\n/**\n * @template T\n * @typedef {import('./interface.js').ByteView} ByteView\n */\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView}\n */\nexport const encode = (node) => textEncoder.encode(JSON.stringify(node))\n\n/**\n * @template T\n * @param {ByteView} data\n * @returns {T}\n */\nexport const decode = (data) => JSON.parse(textDecoder.decode(data))\n", "// @ts-check\n\nimport * as identityBase from './bases/identity.js'\nimport * as base2 from './bases/base2.js'\nimport * as base8 from './bases/base8.js'\nimport * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.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 base256emoji from './bases/base256emoji.js'\nimport * as sha2 from './hashes/sha2.js'\nimport * as identity from './hashes/identity.js'\n\nimport * as raw from './codecs/raw.js'\nimport * as json from './codecs/json.js'\n\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nconst bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nconst hashes = { ...sha2, ...identity }\nconst codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes, hashes, bases, codecs }\n", "\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n }\n\n return buf\n}\n", "import { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n if (globalThis.Buffer?.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size))\n }\n\n return new Uint8Array(size)\n}\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: number = 0): Uint8Array {\n if (globalThis.Buffer?.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size))\n }\n\n return new Uint8Array(size)\n}\n", "import type { MultibaseCodec } from 'multiformats'\nimport { bases } from 'multiformats/basics'\nimport { allocUnsafe } from '../alloc.js'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\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})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\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\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import bases, { SupportedEncodings } from './util/bases.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\nexport type { SupportedEncodings }\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 */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'))\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "\nimport { nanoid } from 'nanoid'\nimport { SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\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 private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\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: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\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: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/f98719ea086343f7b71f32ea9d9d521d')\n * ```\n */\n static random (): Key {\n return new Key(nanoid().replace(/-/g, ''))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\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\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\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\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 /**\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: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\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 (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces (): string[] {\n return this.list()\n }\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 (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\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 (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\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 (): string {\n return namespaceType(this.baseNamespace())\n }\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 (): string {\n return namespaceValue(this.baseNamespace())\n }\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: string): Key {\n return new Key(this.toString() + ':' + s)\n }\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 (): Key {\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 /**\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 (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\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: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\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: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\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: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n *\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\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: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\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: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\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: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\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: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "/* eslint-disable no-unreachable */\n\nimport * as isIpfs from 'is-ipfs'\nimport { CID } from 'multiformats/cid'\nimport { Key } from 'interface-datastore/key'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport * as dagPB from '@ipld/dag-pb'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\nconst ERR_BAD_PATH = 'ERR_BAD_PATH'\n\nexport const OFFLINE_ERROR = 'This command must be run in online mode. Try running \\'ipfs daemon\\' first.'\nexport const MFS_ROOT_KEY = new Key('/local/filesroot')\nexport const MFS_MAX_CHUNK_SIZE = 262144\nexport const MFS_MAX_LINKS = 174\n\n/**\n * Returns a well-formed ipfs Path.\n * The returned path will always be prefixed with /ipfs/ or /ipns/.\n *\n * @param {string | CID} pathStr - An ipfs-path, or ipns-path or a cid\n * @returns {string} - ipfs-path or ipns-path\n * @throws on an invalid @param pathStr\n */\nexport const normalizePath = (pathStr) => {\n const cid = CID.asCID(pathStr)\n\n if (cid) {\n return `/ipfs/${pathStr}`\n }\n\n const str = pathStr.toString()\n\n try {\n return `/ipfs/${CID.parse(str)}`\n } catch {}\n\n if (isIpfs.path(str)) {\n return str\n } else {\n throw errCode(new Error(`invalid path: ${pathStr}`), ERR_BAD_PATH)\n }\n}\n\n// TODO: do we need both normalizePath and normalizeCidPath?\n// TODO: don't forget ipfs-core-utils/src/to-cid-and-path\n/**\n * @param {Uint8Array|CID|string} path\n */\nexport const normalizeCidPath = (path) => {\n if (path instanceof Uint8Array) {\n return CID.decode(path).toString()\n }\n\n path = path.toString()\n\n if (path.indexOf('/ipfs/') === 0) {\n path = path.substring('/ipfs/'.length)\n }\n\n if (path.charAt(path.length - 1) === '/') {\n path = path.substring(0, path.length - 1)\n }\n\n return path\n}\n\n/**\n * Resolve various styles of an ipfs-path to the hash of the target node.\n * Follows links in the path\n *\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {CID | string | Uint8Array} ipfsPath - A CID or IPFS path\n * @param {{ path?: string, signal?: AbortSignal }} [options] - Optional options passed directly to dag.resolve\n * @returns {Promise<{ cid: CID, remainderPath: string}>}\n */\nexport const resolvePath = async function (repo, codecs, ipfsPath, options = {}) {\n const {\n cid,\n path\n } = toCidAndPath(ipfsPath)\n\n if (path) {\n options.path = path\n }\n\n let lastCid = cid\n let lastRemainderPath = options.path || ''\n\n if (lastRemainderPath.startsWith('/')) {\n lastRemainderPath = lastRemainderPath.substring(1)\n }\n\n if (options.path) {\n try {\n for await (const { value, remainderPath } of resolve(cid, options.path, codecs, repo, {\n signal: options.signal\n })) {\n if (!CID.asCID(value)) {\n break\n }\n\n lastRemainderPath = remainderPath\n lastCid = value\n }\n } catch (/** @type {any} */ err) {\n // TODO: add error codes to IPLD\n if (err.message.startsWith('Object has no property')) {\n err.message = `no link named \"${lastRemainderPath.split('/')[0]}\" under ${lastCid}`\n err.code = 'ERR_NO_LINK'\n }\n throw err\n }\n }\n\n return {\n cid: lastCid,\n remainderPath: lastRemainderPath || ''\n }\n}\n\n/**\n * @typedef {import('ipfs-unixfs-exporter').UnixFSEntry} UnixFSEntry\n *\n * @param {UnixFSEntry} file\n */\nexport const mapFile = (file) => {\n if (file.type !== 'file' && file.type !== 'directory' && file.type !== 'raw') {\n // file.type === object | identity not supported yet\n throw new Error(`Unknown node type '${file.type}'`)\n }\n\n /** @type {import('ipfs-core-types/src/root').IPFSEntry} */\n const output = {\n cid: file.cid,\n path: file.path,\n name: file.name,\n size: file.size,\n type: 'file'\n }\n\n if (file.type === 'directory') {\n // @ts-expect-error - TS type can't be changed from File to Directory\n output.type = 'dir'\n }\n\n if (file.type === 'file') {\n output.size = file.unixfs.fileSize()\n }\n\n if (file.type === 'file' || file.type === 'directory') {\n output.mode = file.unixfs.mode\n\n if (file.unixfs.mtime !== undefined) {\n output.mtime = file.unixfs.mtime\n }\n }\n\n return output\n}\n\nexport const withTimeout = withTimeoutOption(\n /**\n * @template T\n * @param {Promise|T} promise\n * @param {AbortOptions} [_options]\n * @returns {Promise}\n */\n async (promise, _options) => await promise\n)\n\n/**\n * Retrieves IPLD Nodes along the `path` that is rooted at `cid`.\n *\n * @param {CID} cid - the CID where the resolving starts\n * @param {string} path - the path that should be resolved\n * @param {import('ipfs-core-utils/src/multicodecs').Multicodecs} codecs\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {AbortOptions} [options]\n */\nexport const resolve = async function * (cid, path, codecs, repo, options) {\n /**\n * @param {CID} cid\n */\n const load = async (cid) => {\n const codec = await codecs.getCodec(cid.code)\n const block = await repo.blocks.get(cid, options)\n\n return codec.decode(block)\n }\n\n const parts = path.split('/').filter(Boolean)\n let value = await load(cid)\n let lastCid = cid\n\n // End iteration if there isn't a CID to follow any more\n while (parts.length) {\n const key = parts.shift()\n\n if (!key) {\n throw errCode(new Error(`Could not resolve path \"${path}\"`), 'ERR_INVALID_PATH')\n }\n\n // special case for dag-pb, use the link name as the path segment\n if (cid.code === dagPB.code && Array.isArray(value.Links)) {\n const link = value.Links.find((/** @type {PBLink} */ l) => l.Name === key)\n\n if (link) {\n yield {\n value: link.Hash,\n remainderPath: parts.join('/')\n }\n\n value = await load(link.Hash)\n lastCid = link.Hash\n\n continue\n }\n }\n\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n value = value[key]\n\n yield {\n value,\n remainderPath: parts.join('/')\n }\n } else {\n throw errCode(new Error(`no link named \"${key}\" under ${lastCid}`), 'ERR_NO_LINK')\n }\n\n if (CID.asCID(value)) {\n lastCid = value\n value = await load(value)\n }\n }\n\n yield {\n value,\n remainderPath: ''\n }\n}\n", "/* eslint-disable no-unreachable */\n\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport parseDuration from 'parse-duration'\nimport { TimeoutError } from './errors.js'\n\n/**\n * @template {any[]} Args\n * @template {Promise | AsyncIterable} R - The return type of `fn`\n * @param {(...args:Args) => R} fn\n * @param {number} [optionsArgIndex]\n * @returns {(...args:Args) => R}\n */\nexport function withTimeoutOption (fn, optionsArgIndex) {\n // eslint-disable-next-line\n return /** @returns {R} */(/** @type {Args} */...args) => {\n const options = args[optionsArgIndex == null ? args.length - 1 : optionsArgIndex]\n if (!options || !options.timeout) return fn(...args)\n\n const timeout = typeof options.timeout === 'string'\n ? parseDuration(options.timeout)\n : options.timeout\n\n const controller = new TimeoutController(timeout)\n\n options.signal = anySignal([options.signal, controller.signal])\n\n const fnRes = fn(...args)\n // eslint-disable-next-line promise/param-names\n const timeoutPromise = new Promise((_resolve, reject) => {\n controller.signal.addEventListener('abort', () => {\n reject(new TimeoutError())\n })\n })\n\n const start = Date.now()\n\n const maybeThrowTimeoutError = () => {\n if (controller.signal.aborted) {\n throw new TimeoutError()\n }\n\n const timeTaken = Date.now() - start\n\n // if we have starved the event loop by adding microtasks, we could have\n // timed out already but the TimeoutController will never know because it's\n // setTimeout will not fire until we stop adding microtasks\n if (timeTaken > timeout) {\n controller.abort()\n throw new TimeoutError()\n }\n }\n\n // @ts-expect-error\n if (fnRes[Symbol.asyncIterator]) {\n // @ts-expect-error\n return (async function * () {\n // @ts-expect-error\n const it = fnRes[Symbol.asyncIterator]()\n\n try {\n while (true) {\n const { value, done } = await Promise.race([it.next(), timeoutPromise])\n\n if (done) {\n break\n }\n\n maybeThrowTimeoutError()\n\n yield value\n }\n } catch (/** @type {any} */ err) {\n maybeThrowTimeoutError()\n\n throw err\n } finally {\n controller.clear()\n\n if (it.return) {\n it.return()\n }\n }\n })()\n }\n\n // @ts-expect-error\n return (async () => {\n try {\n const res = await Promise.race([fnRes, timeoutPromise])\n\n maybeThrowTimeoutError()\n\n return res\n } catch (/** @type {any} */ err) {\n maybeThrowTimeoutError()\n\n throw err\n } finally {\n controller.clear()\n }\n })()\n }\n}\n", "let durationRE = /(-?(?:\\d+\\.?\\d*|\\d*\\.?\\d+)(?:e[-+]?\\d+)?)\\s*([\\p{L}]*)/uig\n\n\n/**\n * conversion ratios\n */\n\nparse.nanosecond =\nparse.ns = 1 / 1e6\n\nparse['\u00B5s'] =\nparse['\u03BCs'] =\nparse.us =\nparse.microsecond = 1 / 1e3\n\nparse.millisecond =\nparse.ms =\nparse[''] = 1\n\nparse.second =\nparse.sec =\nparse.s = parse.ms * 1000\n\nparse.minute =\nparse.min =\nparse.m = parse.s * 60\n\nparse.hour =\nparse.hr =\nparse.h = parse.m * 60\n\nparse.day =\nparse.d = parse.h * 24\n\nparse.week =\nparse.wk =\nparse.w = parse.d * 7\n\nparse.month =\nparse.b =\nparse.d * (365.25 / 12)\n\nparse.year =\nparse.yr =\nparse.y = parse.d * 365.25\n\n/**\n * convert `str` to ms\n *\n * @param {String} str\n * @param {String} format\n * @return {Number}\n */\n\nfunction parse(str='', format='ms'){\n var result = null\n // ignore commas/placeholders\n str = (str+'').replace(/(\\d)[,_](\\d)/g, '$1$2')\n var isNegative = str[0] === '-';\n str.replace(durationRE, function(_, n, units){\n units = unitRatio(units)\n if (units) result = (result || 0) + Math.abs(parseFloat(n, 10)) * units\n })\n\n return result && ((result / (unitRatio(format) || 1)) * (isNegative ? -1 : 1))\n}\n\nfunction unitRatio(str) {\n return parse[str] || parse[str.toLowerCase().replace(/s$/, '')]\n}\n\nexport default parse\n", "\nexport class TimeoutError extends Error {\n constructor (message = 'request timed out') {\n super(message)\n this.name = 'TimeoutError'\n this.code = TimeoutError.code\n }\n}\n\nTimeoutError.code = 'ERR_TIMEOUT'\n", "import { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\n\nconst IPFS_PREFIX = '/ipfs/'\n\n/**\n * @param {string|Uint8Array|CID} string\n * @returns {{cid:CID, path?:string}}\n */\nexport function toCidAndPath (string) {\n if (string instanceof Uint8Array) {\n try {\n string = CID.decode(string)\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_CID')\n }\n }\n\n let cid = CID.asCID(string)\n\n if (cid) {\n return {\n cid,\n path: undefined\n }\n }\n\n string = string.toString()\n\n if (string.startsWith(IPFS_PREFIX)) {\n string = string.substring(IPFS_PREFIX.length)\n }\n\n const parts = string.split('/')\n let path\n\n try {\n cid = CID.parse(parts.shift() || '')\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_CID')\n }\n\n if (parts.length) {\n path = `/${parts.join('/')}`\n }\n\n return {\n cid,\n path\n }\n}\n", "import { NotStartedError, AlreadyStartingError, AlreadyStartedError } from '../errors.js'\nimport { withTimeout } from '../utils.js'\n\n/**\n * @template T\n * @typedef {import('ipfs-core-types/src/utils').Await} Await\n */\n/**\n * @template {(options:any) => any} T\n * @typedef {Parameters[0]} Options\n */\n/**\n * @template {(options:any) => any} T\n * @typedef {ReturnType extends ? Promise ? U : ReturnType} State\n */\n/**\n * Represents service state which can be not started in which case\n * it is instance of `Error`. Pending in which case it's promise or\n * ready in which case it is the value itself.\n *\n * @template T\n * @typedef {{ status: 'stopped' }\n * | { status: 'starting', ready: Await }\n * | { status: 'started', value: T }\n * | { status: 'stopping', ready: Await }\n * } ServiceState\n */\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @template Options, T\n *\n * Allows you to create a handle to service that can be started or\n * stopped. It enables defining components that need to use service\n * functionality before service is started.\n *\n */\nexport class Service {\n /**\n * Takes `activation` function that takes `options` and (async) returns\n * an implementation.\n *\n * @template {(options:any) => Await} T\n *\n * @param {object} config\n * @param {T} config.start\n * @param {(state:State) => Await} [config.stop]\n * @returns {Service[0], State>}\n */\n static create ({ start, stop }) {\n return new Service(start, stop)\n }\n\n /**\n * Starts the service (by running actiavtion function). Will (async) throw\n * unless service is stopped.\n *\n * @template Options, T\n * @param {Service} service\n * @param {Options} options\n * @returns {Promise}\n */\n static async start (service, options) {\n const { state, activate } = service\n switch (state.status) {\n // If service is in 'stopped' state we activate and transition to\n // to 'pending' state. Once activation is complete transition state to\n // 'started' state.\n // Note: This is the only code that does state transitions from\n // - stopped\n // - started\n // Which ensures no race conditions can occur.\n case 'stopped': {\n try {\n const promise = activate(options)\n service.state = { status: 'starting', ready: promise }\n // Note: MUST await after state transition above otherwise race\n // condition may occur.\n const result = await promise\n service.state = { status: 'started', value: result }\n return result\n // If failed to start, transiton from 'starting' to 'stopped'\n // state.\n } catch (/** @type {any} */ error) {\n service.state = { status: 'stopped' }\n throw error\n }\n }\n case 'starting': {\n throw new AlreadyStartingError()\n }\n case 'started': {\n throw new AlreadyStartedError()\n }\n // If service is stopping we just wait for that to complete\n // and try again.\n case 'stopping': {\n await state.ready\n return await Service.start(service, options)\n }\n default: {\n return Service.panic(service)\n }\n }\n }\n\n /**\n * Stops the service by executing deactivation. If service is stopped\n * or is stopping this is noop. If service is starting up when called\n * it will await for start to complete and then retry stop afterwards.\n * This may (async) throw if `deactivate` does.\n *\n * @template T\n * @param {Service} service\n * @returns {Promise}\n */\n static async stop (service) {\n const { state, deactivate } = service\n switch (state.status) {\n // If stopped there's nothing to do.\n case 'stopped': {\n break\n }\n // If service is starting we await for it to complete\n // and try again. That way\n case 'starting': {\n // We do not want to error stop if start failed.\n try { await state.ready } catch (/** @type {any} */ _) {}\n return await Service.stop(service)\n }\n // if service is stopping we just await for it to complete.\n case 'stopping': {\n return await state.ready\n }\n case 'started': {\n if (deactivate) {\n await deactivate(state.value)\n }\n service.state = { status: 'stopped' }\n break\n }\n default: {\n Service.panic(state)\n }\n }\n }\n\n /**\n * @template T\n * @param {Service} service\n * @returns {T|null}\n */\n static try ({ state }) {\n switch (state.status) {\n case 'started':\n return state.value\n default:\n return null\n }\n }\n\n /**\n * Unwraps state and returns underlying value. If state is in idle state it\n * will throw an error. If state is pending it will wait and return the\n * result or throw on failure. If state is ready returns result.\n *\n * @template T\n * @param {Service} service\n * @param {AbortOptions} [options]\n * @returns {Promise}\n */\n static async use ({ state }, options) {\n switch (state.status) {\n case 'started':\n return state.value\n case 'starting':\n return await withTimeout(state.ready, options)\n default:\n throw new NotStartedError()\n }\n }\n\n // eslint-disable-next-line jsdoc/require-returns-check\n /**\n * @private\n * @param {Service} service\n * @returns {never}\n */\n static panic ({ state }) {\n const status = JSON.stringify({ status: state.status })\n throw RangeError(`Service in invalid state ${status}, should never happen if you see this please report a bug`)\n }\n\n /**\n * Takes `activation` function that takes `options` and (async) returns\n * an implementation.\n *\n * @private\n * @param {(options:Options) => Await} activate\n * @param {(state:T) => Await} [deactivate]\n */\n constructor (activate, deactivate) {\n this.activate = activate\n this.deactivate = deactivate\n\n /**\n * A state machine for this service.\n *\n * @private\n * @type {ServiceState}\n */\n this.state = { status: 'stopped' }\n }\n\n /**\n * Allows you to asynchronously obtain service implementation. If service\n * is starting it will await for completion. If service is stopped or stopping\n * this will (async) throw exception. This allows components that need to use\n * this service convenient API to do it.\n *\n * @param {AbortOptions} [options] - Abort options.\n * @returns {Promise}\n */\n async use (options) {\n return await Service.use(this, options)\n }\n\n /**\n * @returns {T|null}\n */\n try () {\n return Service.try(this)\n }\n}\n", "import { Service } from '../utils/service.js'\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../types').Print} config.print\n * @param {import('../types').Preload} config.preload\n * @param {import('../types').MfsPreload} config.mfsPreload\n * @param {import('./ipns').IPNSAPI} config.ipns\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('../types').Options} config.options\n */\nexport function createStart ({ network, preload, peerId, keychain, repo, ipns, mfsPreload, print, hashers, options }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"start\"]}\n */\n const start = async () => {\n const { libp2p } = await Service.start(network, {\n peerId,\n repo,\n print,\n hashers,\n options\n })\n\n await Promise.all([\n ipns.startOnline({ keychain, libp2p, peerId, repo }),\n preload.start(),\n mfsPreload.start()\n ])\n }\n\n return start\n}\n", "import { Service } from '../utils/service.js'\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('../types').Preload} config.preload\n * @param {import('./ipns').IPNSAPI} config.ipns\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../types').MfsPreload} config.mfsPreload\n */\nexport function createStop ({ network, preload, ipns, repo, mfsPreload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"stop\"]}\n */\n const stop = async () => {\n await Promise.all([\n preload.stop(),\n ipns.stop(),\n mfsPreload.stop()\n ])\n\n await Service.stop(network)\n\n // must be closed after stopping services as some of them\n // will write into the datastore\n await repo.close()\n }\n\n return stop\n}\n", "import hashlru from 'hashlru'\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n * @todo move this to ipfs-utils or it's own package\n *\n * @template T\n * @class TLRU\n */\nexport class TLRU {\n /**\n * Creates an instance of TLRU.\n *\n * @param {number} maxSize\n */\n constructor (maxSize) {\n this.lru = hashlru(maxSize)\n }\n\n /**\n * Get the value from the a key\n *\n * @param {string} key\n * @returns {T|undefined}\n * @memberof TLoRU\n */\n get (key) {\n const value = this.lru.get(key)\n if (value) {\n if ((value.expire) && (value.expire < Date.now())) {\n this.lru.remove(key)\n return undefined\n }\n return value.value\n }\n return undefined\n }\n\n /**\n * Set a key value pair\n *\n * @param {string} key\n * @param {T} value\n * @param {number} ttl - in miliseconds\n * @returns {void}\n */\n set (key, value, ttl) {\n this.lru.set(key, { value, expire: Date.now() + ttl })\n }\n\n /**\n * Find if the cache has the key\n *\n * @param {string} key\n * @returns {boolean}\n */\n has (key) {\n const value = this.get(key)\n if (value) {\n return true\n }\n return false\n }\n\n /**\n * Remove key\n *\n * @param {string} key\n */\n remove (key) {\n this.lru.remove(key)\n }\n\n /**\n * Clears the cache\n *\n * @memberof TLRU\n */\n clear () {\n this.lru.clear()\n }\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "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\tnew AbortError(errorMessage) :\n\tnew 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\tgetDOMException('This operation was aborted.') :\n\t\tsignal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, milliseconds, fallback, options) {\n\tlet timer;\n\n\tconst cancelablePromise = 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 (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\toptions = {\n\t\t\tcustomTimers: {setTimeout, clearTimeout},\n\t\t\t...options\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\ttimer = options.customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (typeof fallback === 'function') {\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\tconst message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\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} finally {\n\t\t\t\toptions.customTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tclearTimeout(timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\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", "var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nclass PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\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 && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\nexport default PriorityQueue;\n", "var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pending, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_throwOnAbort, _PQueue_onEvent;\nimport { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nclass PQueue extends EventEmitter {\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pending.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\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 Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\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 \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${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 \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\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 __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\"),\n ...options,\n };\n return new Promise((resolve, reject) => {\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pending, (_b = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n // TODO: Use options.signal?.throwIfAborted() when targeting Node.js 18\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n throw new AbortError('The task was aborted.');\n }\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), options.timeout);\n }\n if (options.signal) {\n operation = Promise.race([operation, __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_throwOnAbort).call(this, 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 __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n }\n }, options);\n this.emit('add');\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\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 (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, '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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pending = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pending, (_a = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - 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 __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_throwOnAbort = async function _PQueue_throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n // TODO: Reject with signal.throwIfAborted() when targeting Node.js 18\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n }, { once: true });\n });\n}, _PQueue_onEvent = async function _PQueue_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};\nexport default PQueue;\n", "/* eslint-env browser */\n\nimport { TLRU } from './utils/tlru.js'\nimport PQueue from 'p-queue'\nimport HTTP from 'ipfs-utils/src/http.js'\n\n// Avoid sending multiple queries for the same hostname by caching results\nconst cache = new TLRU(1000)\n// TODO: /api/v0/dns does not return TTL yet: https://github.com/ipfs/go-ipfs/issues/5884\n// However we know browsers themselves cache DNS records for at least 1 minute,\n// which acts a provisional default ttl: https://stackoverflow.com/a/36917902/11518426\nconst ttl = 60 * 1000\n\n// @ts-expect-error PQueue@6 is broken\nconst Queue = PQueue.default ? PQueue.default : PQueue\n\n// browsers limit concurrent connections per host,\n// we don't want preload calls to exhaust the limit (~6)\nconst httpQueue = new Queue({ concurrency: 4 })\n\n/**\n * @param {{ Path: string, Message: string }} response\n */\nconst ipfsPath = (response) => {\n if (response.Path) return response.Path\n throw new Error(response.Message)\n}\n\n/**\n * @param {string} fqdn\n * @param {object} opts\n */\nexport async function resolveDnslink (fqdn, opts) { // eslint-disable-line require-await\n /**\n * @param {string} fqdn\n * @param {object} opts\n * @param {boolean} [opts.nocache]\n */\n const resolve = async (fqdn, opts = {}) => {\n // @ts-expect-error - URLSearchParams does not take boolean options, only strings\n const searchParams = new URLSearchParams(opts)\n searchParams.set('arg', fqdn)\n\n // try cache first\n const query = searchParams.toString()\n if (!opts.nocache && cache.has(query)) {\n const response = cache.get(query)\n return ipfsPath(response)\n }\n\n // fallback to delegated DNS resolver\n const response = await httpQueue.add(async () => {\n // Delegated HTTP resolver sending DNSLink queries to ipfs.io\n // TODO: replace hardcoded host with configurable DNS over HTTPS: https://github.com/ipfs/js-ipfs/issues/2212\n const res = await HTTP.get('https://ipfs.io/api/v0/dns', { searchParams })\n const query = new URL(res.url).search.slice(1)\n const json = await res.json()\n cache.set(query, json, ttl)\n\n return json\n })\n return ipfsPath(response)\n }\n\n return resolve(fqdn, opts)\n}\n", "// dns-nodejs gets replaced by dns-browser when bundled\nimport { resolveDnslink } from 'ipfs-core-config/dns'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {string} domain\n * @returns {string}\n */\nfunction fqdnFixups (domain) {\n // Allow resolution of .eth names via .eth.link\n // More context at the go-ipfs counterpart: https://github.com/ipfs/go-ipfs/pull/6448\n if (domain.endsWith('.eth')) {\n domain = domain.replace(/.eth$/, '.eth.link')\n }\n return domain\n}\n\nexport function createDns () {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"dns\"]}\n */\n const resolveDNS = async (domain, options = { recursive: true }) => { // eslint-disable-line require-await\n if (typeof domain !== 'string') {\n throw new Error('Invalid arguments, domain must be a string')\n }\n\n domain = fqdnFixups(domain)\n\n return resolveDnslink(domain, options)\n }\n\n return withTimeoutOption(resolveDNS)\n}\n", "\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n */\nexport function createIsOnline ({ network }) {\n /**\n * @returns {boolean}\n */\n return () => {\n const net = network.try()\n return net != null && Boolean(net.libp2p.isStarted())\n }\n}\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString: () => string\n toCID: () => CID\n toBytes: () => Uint8Array\n equals: (other: PeerId | Uint8Array | string) => boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const symbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[symbol])\n}\n", "\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 */\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static readonly code = 'ABORT_ERR'\n\n static readonly type = 'aborted'\n}\n\nexport class CodeError = Record> extends Error {\n public readonly props: T\n\n constructor (\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(message)\n\n this.name = props?.name ?? 'CodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "import { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, symbol, type PeerId } from '@libp2p/interface-peer-id'\nimport { CodeError } from '@libp2p/interfaces/errors'\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 type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\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\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [symbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id: PeerId | Uint8Array | string): boolean {\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\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\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\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\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\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 } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n", "import * as isIpfs from 'is-ipfs'\nimport { CID } from 'multiformats/cid'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { resolve as res } from '../utils.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-utils/src/multibases').Multibases} config.bases\n * @param {import('ipfs-core-types/src/name').API} config.name\n */\nexport function createResolve ({ repo, codecs, bases, name }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"resolve\"]}\n */\n async function resolve (path, opts = {}) {\n if (!isIpfs.path(path)) {\n throw new Error('invalid argument ' + path)\n }\n\n if (isIpfs.ipnsPath(path)) {\n for await (const resolvedPath of name.resolve(path, opts)) {\n path = resolvedPath\n }\n }\n\n const [, schema, hash, ...rest] = path.split('/') // ['', 'ipfs', 'hash', ...path]\n const base = opts.cidBase ? await bases.getBase(opts.cidBase) : undefined\n const bytes = parseBytes(hash)\n\n // nothing to resolve return the input\n if (rest.length === 0) {\n const str = base ? base.encoder.encode(bytes) : hash\n\n return `/${schema}/${str}`\n }\n\n const cid = CID.decode(bytes)\n\n path = rest.join('/')\n\n const results = res(cid, path, codecs, repo, opts)\n let value = cid\n let remainderPath = path\n\n for await (const result of results) {\n if (CID.asCID(result.value)) {\n value = result.value\n remainderPath = result.remainderPath\n }\n }\n\n return `/ipfs/${value.toString(base && base.encoder)}${remainderPath ? '/' + remainderPath : ''}`\n }\n\n return withTimeoutOption(resolve)\n}\n\n/**\n * Parse the input as a PeerID or a CID or throw an error\n *\n * @param {string} str\n */\nfunction parseBytes (str) {\n try {\n return peerIdFromString(str).toBytes()\n } catch {\n return CID.parse(str).bytes\n }\n}\n", "/**\n * Returns the last item of an (async) iterable, unless empty, in which case\n * return `undefined`\n */\nexport default async function last (source: AsyncIterable | Iterable): Promise {\n let res\n\n for await (const entry of source) {\n res = entry\n }\n\n return res\n}\n", "import last from 'it-last'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @param {object} config\n * @param {ReturnType} config.addAll\n */\nexport function createAdd ({ addAll }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"add\"]}\n */\n return (path, options = {}) => {\n let iter\n\n const cid = CID.asCID(path)\n\n if (cid) {\n iter = addAll([{\n cid,\n ...options\n }], options)\n } else {\n iter = addAll([{\n path: path.toString(),\n ...options\n }], options)\n }\n\n // @ts-expect-error return value of last can be undefined\n return last(iter)\n }\n}\n", "import errCode from 'err-code'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {object} Pinnable\n * @property {string | InstanceType | CID} [path]\n * @property {CID} [cid]\n * @property {boolean} [recursive]\n * @property {any} [metadata]\n *\n * @typedef {CID|string|InstanceType|Pinnable} ToPin\n * @typedef {ToPin|Iterable|AsyncIterable} Source\n *\n * @typedef {object} Pin\n * @property {string|CID} path\n * @property {boolean} recursive\n * @property {any} [metadata]\n */\n\n/**\n * @param {any} thing\n * @returns {thing is IterableIterator & Iterator}\n */\nfunction isIterable (thing) {\n return Symbol.iterator in thing\n}\n\n/**\n * @param {any} thing\n * @returns {thing is AsyncIterableIterator & AsyncIterator}\n */\nfunction isAsyncIterable (thing) {\n return Symbol.asyncIterator in thing\n}\n\n/**\n * @param {any} thing\n * @returns {thing is CID}\n */\nfunction isCID (thing) {\n return CID.asCID(thing) != null\n}\n\n/**\n * Transform one of:\n *\n * ```ts\n * CID\n * String\n * { cid: CID recursive, metadata }\n * { path: String recursive, metadata }\n * Iterable\n * Iterable\n * Iterable<{ cid: CID recursive, metadata }>\n * Iterable<{ path: String recursive, metadata }>\n * AsyncIterable\n * AsyncIterable\n * AsyncIterable<{ cid: CID recursive, metadata }>\n * AsyncIterable<{ path: String recursive, metadata }>\n * ```\n * Into:\n *\n * ```ts\n * AsyncIterable<{ path: CID|String, recursive:boolean, metadata }>\n * ```\n *\n * @param {Source} input\n * @returns {AsyncIterable}\n */\n// eslint-disable-next-line complexity\nexport async function * normaliseInput (input) {\n // must give us something\n if (input === null || input === undefined) {\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n }\n\n // CID\n const cid = CID.asCID(input)\n\n if (cid) {\n yield toPin({ cid })\n return\n }\n\n if (input instanceof String || typeof input === 'string') {\n yield toPin({ path: input })\n return\n }\n\n // { cid: CID recursive, metadata }\n // @ts-expect-error - it still could be iterable or async iterable\n if (input.cid != null || input.path != null) {\n // @ts-expect-error\n return yield toPin(input)\n }\n\n // Iterable\n if (isIterable(input)) {\n const iterator = input[Symbol.iterator]()\n const first = iterator.next()\n\n if (first.done) {\n return iterator\n }\n\n // Iterable\n if (isCID(first.value)) {\n yield toPin({ cid: first.value })\n for (const cid of iterator) {\n yield toPin({ cid })\n }\n return\n }\n\n // Iterable\n if (first.value instanceof String || typeof first.value === 'string') {\n yield toPin({ path: first.value })\n for (const path of iterator) {\n yield toPin({ path })\n }\n return\n }\n\n // Iterable\n if (first.value.cid != null || first.value.path != null) {\n yield toPin(first.value)\n for (const obj of iterator) {\n yield toPin(obj)\n }\n return\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n }\n\n // AsyncIterable\n if (isAsyncIterable(input)) {\n const iterator = input[Symbol.asyncIterator]()\n const first = await iterator.next()\n if (first.done) return iterator\n\n // AsyncIterable\n if (isCID(first.value)) {\n yield toPin({ cid: first.value })\n for await (const cid of iterator) {\n yield toPin({ cid })\n }\n return\n }\n\n // AsyncIterable\n if (first.value instanceof String || typeof first.value === 'string') {\n yield toPin({ path: first.value })\n for await (const path of iterator) {\n yield toPin({ path })\n }\n return\n }\n\n // AsyncIterable<{ cid: CID|String recursive, metadata }>\n if (first.value.cid != null || first.value.path != null) {\n yield toPin(first.value)\n for await (const obj of iterator) {\n yield toPin(obj)\n }\n return\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {Pinnable} input\n */\nfunction toPin (input) {\n const path = input.cid || `${input.path}`\n\n if (!path) {\n throw errCode(new Error('Unexpected input: Please path either a CID or an IPFS path'), 'ERR_UNEXPECTED_INPUT')\n }\n\n /** @type {Pin} */\n const pin = {\n path,\n recursive: input.recursive !== false\n }\n\n if (input.metadata != null) {\n pin.metadata = input.metadata\n }\n\n return pin\n}\n", "\nexport const PinTypes = {\n /** @type {'direct'} */\n direct: 'direct',\n /** @type {'recursive'} */\n recursive: 'recursive',\n /** @type {'indirect'} */\n indirect: 'indirect',\n /** @type {'all'} */\n all: 'all'\n}\n", "/* eslint max-nested-callbacks: [\"error\", 8] */\n\nimport { resolvePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { PinTypes } from 'ipfs-repo/pin-types'\n\n/**\n * @typedef {import('ipfs-core-utils/src/pins/normalise-input').Source} Source\n * @typedef {import('ipfs-core-utils/src/pins/normalise-input').Pin} PinTarget\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('multiformats/cid').CID} CID\n */\n\n/**\n * @template T\n * @typedef {Iterable|AsyncIterable} AwaitIterable\n */\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createAddAll ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n /**\n * @returns {AsyncIterable}\n */\n const pinAdd = async function * () {\n for await (const { path, recursive, metadata } of normaliseInput(source)) {\n const { cid } = await resolvePath(repo, codecs, path)\n\n // verify that each hash can be pinned\n const { reason } = await repo.pins.isPinnedWithType(cid, [PinTypes.recursive, PinTypes.direct])\n\n if (reason === 'recursive' && !recursive) {\n // only disallow trying to override recursive pins\n throw new Error(`${cid} already pinned recursively`)\n }\n\n if (recursive) {\n await repo.pins.pinRecursively(cid, { metadata })\n } else {\n await repo.pins.pinDirectly(cid, { metadata })\n }\n\n yield cid\n }\n }\n\n // When adding a file, we take a lock that gets released after pinning\n // is complete, so don't take a second lock here\n const lock = Boolean(options.lock)\n\n if (!lock) {\n yield * pinAdd()\n return\n }\n\n const release = await repo.gcLock.readLock()\n\n try {\n yield * pinAdd()\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(addAll)\n}\n", "/* eslint max-nested-callbacks: [\"error\", 8] */\n\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { resolvePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport errCode from 'err-code'\nimport { PinTypes } from 'ipfs-repo/pin-types'\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n */\n\n/**\n * @param {string} type\n * @param {CID} cid\n * @param {Record} [metadata]\n */\nfunction toPin (type, cid, metadata) {\n /** @type {import('ipfs-core-types/src/pin').LsResult} */\n const output = {\n type,\n cid\n }\n\n if (metadata) {\n output.metadata = metadata\n }\n\n return output\n}\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createLs ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"ls\"]}\n */\n async function * ls (options = {}) {\n /** @type {import('ipfs-core-types/src/pin').PinQueryType} */\n let type = PinTypes.all\n\n if (options.type) {\n type = options.type\n\n if (!Object.keys(PinTypes).includes(type)) {\n throw errCode(new Error('Invalid pin type'), 'ERR_INVALID_PIN_TYPE')\n }\n }\n\n if (options.paths) {\n // check the pinned state of specific hashes\n let matched = false\n\n for await (const { path } of normaliseInput(options.paths)) {\n const { cid } = await resolvePath(repo, codecs, path)\n const { reason, pinned, parent, metadata } = await repo.pins.isPinnedWithType(cid, type)\n\n if (!pinned) {\n throw errCode(new Error(`path '${path}' is not pinned`), 'ERR_NOT_PINNED')\n }\n\n switch (reason) {\n case PinTypes.direct:\n case PinTypes.recursive:\n matched = true\n yield toPin(reason, cid, metadata)\n break\n default:\n matched = true\n yield toPin(`${PinTypes.indirect} through ${parent}`, cid, metadata)\n }\n }\n\n if (!matched) {\n throw new Error('No match found')\n }\n\n return\n }\n\n if (type === PinTypes.recursive || type === PinTypes.all) {\n for await (const { cid, metadata } of repo.pins.recursiveKeys()) {\n yield toPin(PinTypes.recursive, cid, metadata)\n }\n }\n\n if (type === PinTypes.indirect || type === PinTypes.all) {\n for await (const cid of repo.pins.indirectKeys(options)) {\n yield toPin(PinTypes.indirect, cid)\n }\n }\n\n if (type === PinTypes.direct || type === PinTypes.all) {\n for await (const { cid, metadata } of repo.pins.directKeys()) {\n yield toPin(PinTypes.direct, cid, metadata)\n }\n }\n }\n\n return withTimeoutOption(ls)\n}\n", "import last from 'it-last'\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-types/src/pin').API<{}>[\"rmAll\"]} config.rmAll\n */\nexport function createRm ({ rmAll }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"rm\"]}\n */\n async function rm (path, options = {}) {\n // @ts-expect-error return value of last can be undefined\n const cid = await last(rmAll([{ path, ...options }], options))\n\n if (!cid) {\n throw new Error('CID expected')\n }\n\n return cid\n }\n\n return rm\n}\n", "import { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { resolvePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { PinTypes } from 'ipfs-repo/pin-types'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createRmAll ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/pin').API<{}>[\"rmAll\"]}\n */\n async function * rmAll (source, _options = {}) {\n const release = await repo.gcLock.readLock()\n\n try {\n // verify that each hash can be unpinned\n for await (const { path, recursive } of normaliseInput(source)) {\n const { cid } = await resolvePath(repo, codecs, path)\n const { pinned, reason } = await repo.pins.isPinnedWithType(cid, PinTypes.all)\n\n if (!pinned) {\n throw new Error(`${cid} is not pinned`)\n }\n\n switch (reason) {\n case (PinTypes.recursive):\n if (!recursive) {\n throw new Error(`${cid} is pinned recursively`)\n }\n\n await repo.pins.unpin(cid)\n\n yield cid\n\n break\n case (PinTypes.direct):\n await repo.pins.unpin(cid)\n\n yield cid\n\n break\n default:\n throw new Error(`${cid} is pinned indirectly under ${reason}`)\n }\n }\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(rmAll)\n}\n", "import { createAdd } from './add.js'\nimport { createAddAll } from './add-all.js'\nimport { createLs } from './ls.js'\nimport { createRm } from './rm.js'\nimport { createRmAll } from './rm-all.js'\n\nexport class PinAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ codecs, repo }) {\n const addAll = createAddAll({ codecs, repo })\n this.addAll = addAll\n this.add = createAdd({ addAll })\n const rmAll = createRmAll({ codecs, repo })\n this.rmAll = rmAll\n this.rm = createRm({ rmAll })\n this.ls = createLs({ codecs, repo })\n\n /** @type {import('ipfs-core-types/src/pin/remote').API} */\n this.remote = {\n add: (cid, options = {}) => Promise.reject(new Error('Not implemented')),\n ls: async function * (query, options = {}) { return Promise.reject(new Error('Not implemented')) }, // eslint-disable-line require-yield\n rm: (query, options = {}) => Promise.reject(new Error('Not implemented')),\n rmAll: (query, options = {}) => Promise.reject(new Error('Not implemented')),\n service: {\n add: (name, credentials) => Promise.reject(new Error('Not implemented')),\n rm: (name, options = {}) => Promise.reject(new Error('Not implemented')),\n // @ts-expect-error return types seem to be broken by a recent ts release. doesn't matter here because\n // we are just throwing. Will be removed by https://github.com/protocol/web3-dev-team/pull/58\n ls: (options = {}) => Promise.reject(new Error('Not implemented'))\n }\n }\n }\n}\n", "import errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { IpnsPublisher } from './publisher.js'\nimport { IpnsRepublisher } from './republisher.js'\nimport { IpnsResolver } from './resolver.js'\nimport { TLRU } from '../utils/tlru.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst log = logger('ipfs:ipns')\nconst defaultRecordTtl = 60 * 1000\n\n/**\n * @typedef {import('@libp2p/interface-keys').PrivateKey} PrivateKey\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nexport class IPNS {\n /**\n * @param {import('ipfs-core-types/src/utils').BufferStore} routing\n * @param {import('interface-datastore').Datastore} datastore\n * @param {PeerId} peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} keychain\n * @param {object} options\n * @param {string} options.pass\n * @param {number} [options.initialBroadcastInterval]\n * @param {number} [options.broadcastInterval]\n */\n constructor (routing, datastore, peerId, keychain, options) {\n this.publisher = new IpnsPublisher(routing, datastore)\n this.republisher = new IpnsRepublisher(this.publisher, datastore, peerId, keychain, options)\n this.resolver = new IpnsResolver(routing)\n this.cache = new TLRU(1000)\n this.routing = routing\n }\n\n /**\n * Publish\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n async publish (peerId, value, lifetime = IpnsPublisher.defaultRecordLifetime, options) {\n try {\n await this.publisher.publishWithEOL(peerId, value, lifetime, options)\n\n log(`IPNS value ${uint8ArrayToString(value, 'base32')} was published correctly`)\n\n // // Add to cache\n const id = peerId.toString()\n // @ts-expect-error - parseFloat expects string\n const ttEol = parseFloat(lifetime)\n const ttl = (ttEol < defaultRecordTtl) ? ttEol : defaultRecordTtl\n\n this.cache.set(id, value, ttl)\n\n log(`IPNS value ${uint8ArrayToString(value, 'base32')} was cached correctly`)\n\n return {\n name: id,\n value: value\n }\n } catch (/** @type {any} */ err) {\n log.error(err)\n\n throw err\n }\n }\n\n /**\n * Resolve\n *\n * @param {string} name\n * @param {object} options\n * @param {boolean} [options.nocache]\n * @param {boolean} [options.recursive]\n * @param {AbortSignal} [options.signal]\n */\n async resolve (name, options = {}) {\n if (typeof name !== 'string') {\n throw errcode(new Error('name received is not valid'), 'ERR_INVALID_NAME')\n }\n\n // If recursive, we should not try to get the cached value\n if (!options.nocache && !options.recursive) {\n // Try to get the record from cache\n const id = name.split('/')[2]\n const result = this.cache.get(id)\n\n if (result) {\n return result\n }\n }\n\n try {\n const result = await this.resolver.resolve(name, options)\n\n log(`IPNS record from ${name} was resolved correctly`)\n\n return result\n } catch (/** @type {any} */ err) {\n log.error(err)\n\n throw err\n }\n }\n\n /**\n * Initialize keyspace\n *\n * Sets the ipns record for the given key to point to an empty directory\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {AbortOptions} [options]\n */\n async initializeKeyspace (peerId, value, options) { // eslint-disable-line require-await\n return this.publish(peerId, value, IpnsPublisher.defaultRecordLifetime, options)\n }\n}\n", "import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function dbOpenFailedError (err) {\n err = err || new Error('Cannot open database')\n return errCode(err, 'ERR_DB_OPEN_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbDeleteFailedError (err) {\n err = err || new Error('Delete failed')\n return errCode(err, 'ERR_DB_DELETE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbWriteFailedError (err) {\n err = err || new Error('Write failed')\n return errCode(err, 'ERR_DB_WRITE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n", "import { isPeerId } from '@libp2p/interface-peer-id'\nimport { notFoundError } from 'datastore-core/errors'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport * as ipns from 'ipns'\n\nconst log = logger('ipfs:ipns:publisher')\n\n/**\n * @typedef {import('@libp2p/interface-keys').PrivateKey} PrivateKey\n * @typedef {import('@libp2p/interface-keys').PublicKey} PublicKey\n * @typedef {import('ipns').IPNSEntry} IPNSEntry\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nconst ERR_NOT_FOUND = notFoundError().code\nconst defaultRecordLifetime = 60 * 60 * 1000\n\n// IpnsPublisher is capable of publishing and resolving names to the IPFS routing system.\nexport class IpnsPublisher {\n /**\n * @param {import('ipfs-core-types/src/utils').BufferStore} routing\n * @param {import('interface-datastore').Datastore} datastore\n */\n constructor (routing, datastore) {\n this._routing = routing\n this._datastore = datastore\n }\n\n /**\n * Publish record with a eol\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n async publishWithEOL (peerId, value, lifetime, options) {\n const record = await this._updateOrCreateRecord(peerId, value, lifetime, options)\n\n return this._putRecordToRouting(record, peerId, options)\n }\n\n /**\n * Accepts a keypair, as well as a value (ipfsPath), and publishes it out to the routing system\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {AbortOptions} options\n */\n publish (peerId, value, options) {\n return this.publishWithEOL(peerId, value, defaultRecordLifetime, options)\n }\n\n /**\n * @param {Uint8Array} record\n * @param {PeerId} peerId\n * @param {AbortOptions} [options]\n */\n async _putRecordToRouting (record, peerId, options) {\n if (!(isPeerId(peerId))) {\n const errMsg = 'peerId received is not valid'\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')\n }\n\n if (peerId.publicKey == null) {\n throw errcode(new Error('Public key was missing'), 'ERR_MISSING_PUBLIC_KEY')\n }\n\n const routingKey = ipns.peerIdToRoutingKey(peerId)\n\n await this._publishEntry(routingKey, record, options)\n\n return record\n }\n\n /**\n * @param {Uint8Array} key\n * @param {Uint8Array} entry\n * @param {AbortOptions} [options]\n */\n async _publishEntry (key, entry, options) {\n // Add record to routing (buffer key)\n try {\n const res = await this._routing.put(key, entry, options)\n log(`ipns record for ${uint8ArrayToString(key, 'base32')} was stored in the routing`)\n\n return res\n } catch (/** @type {any} */err) {\n const errMsg = `ipns record for ${uint8ArrayToString(key, 'base32')} could not be stored in the routing - ${err.stack}`\n log.error(errMsg)\n log.error(err)\n\n throw errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING')\n }\n }\n\n /**\n * Returns the record this node has published corresponding to the given peer ID.\n *\n * If `checkRouting` is true and we have no existing record, this method will check the routing system for any existing records.\n *\n * @param {PeerId} peerId\n * @param {object} options\n * @param {boolean} [options.checkRouting]\n */\n async _getPublished (peerId, options = {}) {\n if (!(isPeerId(peerId))) {\n const errMsg = 'peerId received is not valid'\n\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')\n }\n\n const checkRouting = options.checkRouting !== false\n\n try {\n const dsVal = await this._datastore.get(ipns.getLocalKey(peerId.toBytes()))\n\n // unmarshal data\n return this._unmarshalData(dsVal)\n } catch (/** @type {any} */ err) {\n if (err.code !== ERR_NOT_FOUND) {\n const errMsg = `unexpected error getting the ipns record ${peerId.toString()} from datastore`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_UNEXPECTED_DATASTORE_RESPONSE')\n }\n\n if (!checkRouting) {\n throw errcode(err, 'ERR_NOT_FOUND_AND_CHECK_ROUTING_NOT_ENABLED')\n }\n\n // Try to get from routing\n try {\n const routingKey = ipns.peerIdToRoutingKey(peerId)\n const res = await this._routing.get(routingKey)\n\n // unmarshal data\n return this._unmarshalData(res)\n } catch (/** @type {any} */ err) {\n log.error(err)\n\n throw err\n }\n }\n }\n\n /**\n * @param {Uint8Array} data\n */\n _unmarshalData (data) {\n try {\n return ipns.unmarshal(data)\n } catch (/** @type {any} */ err) {\n throw errcode(err, 'ERR_INVALID_RECORD_DATA')\n }\n }\n\n /**\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n async _updateOrCreateRecord (peerId, value, lifetime, options) {\n if (!(isPeerId(peerId))) {\n const errMsg = 'peerId received is not valid'\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')\n }\n\n const getPublishedOptions = {\n checkRouting: true\n }\n\n /** @type {IPNSEntry | undefined} */\n let record\n\n try {\n record = await this._getPublished(peerId, getPublishedOptions)\n } catch (/** @type {any} */ err) {\n if (err.code !== ERR_NOT_FOUND) {\n const errMsg = `unexpected error when determining the last published IPNS record for ${peerId.toString()} ${err.stack}`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_DETERMINING_PUBLISHED_RECORD')\n }\n }\n\n // Determinate the record sequence number\n let seqNumber = 0n\n\n if (record && record.sequence !== undefined) {\n // Increment if the published value is different\n seqNumber = uint8ArrayEquals(record.value, value) ? record.sequence : record.sequence + BigInt(1)\n }\n\n /** @type {IPNSEntry} */\n let entryData\n\n try {\n // Create record\n entryData = await ipns.create(peerId, value, seqNumber, lifetime)\n } catch (/** @type {any} */ err) {\n const errMsg = `ipns record for ${value} could not be created`\n\n log.error(err)\n throw errcode(new Error(errMsg), 'ERR_CREATING_IPNS_RECORD')\n }\n\n // TODO IMPROVEMENT - set ttl (still experimental feature for go)\n\n try {\n // Marshal record\n const data = ipns.marshal(entryData)\n\n // Store the new record\n await this._datastore.put(ipns.getLocalKey(peerId.toBytes()), data, options)\n\n log(`ipns record for ${uint8ArrayToString(value, 'base32')} was stored in the datastore`)\n\n return data\n } catch (/** @type {any} */ err) {\n const errMsg = `ipns record for ${value} could not be stored in the datastore`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_STORING_IN_DATASTORE')\n }\n }\n}\n\nIpnsPublisher.defaultRecordLifetime = defaultRecordLifetime\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\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 */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import NanoDate from 'timestamp-nano'\nimport { Key } from 'interface-datastore/key'\nimport { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport errCode from 'err-code'\nimport { base32upper } from 'multiformats/bases/base32'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { logger } from '@libp2p/logger'\nimport { createCborData, ipnsEntryDataForV1Sig, ipnsEntryDataForV2Sig } from './utils.js'\nimport * as ERRORS from './errors.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { IpnsEntry } from './pb/ipns.js'\nimport type { PrivateKey } from '@libp2p/interface-keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('ipns')\nconst ID_MULTIHASH_CODE = identity.code\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSEntry {\n value: Uint8Array\n signature: Uint8Array // signature of the record\n validityType: IpnsEntry.ValidityType // Type of validation being used\n validity: Uint8Array // expiration datetime for the record in RFC3339 format\n sequence: bigint // number representing the version of the record\n ttl?: bigint // ttl in nanoseconds\n pubKey?: Uint8Array // the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n signatureV2?: Uint8Array // the v2 signature of the record\n data?: Uint8Array // extensible data\n}\n\nexport interface IPNSEntryData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\n/**\n * Creates a new ipns entry and signs it with the given private key.\n * The ipns entry validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * @param {PeerId} peerId - peer id containing private key for signing the record.\n * @param {Uint8Array} value - value to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n */\nexport const create = async (peerId: PeerId, value: Uint8Array, seq: number | bigint, lifetime: number): Promise => {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const [ms, ns] = lifetime.toString().split('.')\n const lifetimeNs = (BigInt(ms) * BigInt(100000)) + BigInt(ns ?? '0')\n\n return await _create(peerId, value, seq, validityType, expirationDate, lifetimeNs)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * @param {PeerId} peerId - PeerId containing private key for signing the record.\n * @param {Uint8Array} value - value to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n */\nexport const createWithExpiration = async (peerId: PeerId, value: Uint8Array, seq: number | bigint, expiration: string): Promise => {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n\n const ttlMs = expirationDate.toDate().getTime() - Date.now()\n const ttlNs = (BigInt(ttlMs) * BigInt(100000)) + BigInt(expirationDate.getNano())\n\n return await _create(peerId, value, seq, validityType, expirationDate, ttlNs)\n}\n\nconst _create = async (peerId: PeerId, value: Uint8Array, seq: number | bigint, validityType: IpnsEntry.ValidityType, expirationDate: NanoDate, ttl: bigint): Promise => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(expirationDate.toString())\n\n if (peerId.privateKey == null) {\n throw errCode(new Error('Missing private key'), ERRORS.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n const signatureV1 = await signLegacyV1(privateKey, value, validityType, isoValidity)\n const data = createCborData(value, isoValidity, validityType, seq, ttl)\n const sigData = ipnsEntryDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData)\n\n const entry: IPNSEntry = {\n value,\n signature: signatureV1,\n validityType,\n validity: isoValidity,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n // if we cannot derive the public key from the PeerId (e.g. RSA PeerIDs),\n // we have to embed it in the IPNS record\n if (peerId.publicKey != null) {\n const digest = Digest.decode(peerId.toBytes())\n\n if (digest.code !== ID_MULTIHASH_CODE || !uint8ArrayEquals(peerId.publicKey, digest.digest)) {\n entry.pubKey = peerId.publicKey\n }\n }\n\n log('ipns entry for %b created', value)\n return entry\n}\n\n/**\n * rawStdEncoding with RFC4648\n */\nconst rawStdEncoding = (key: Uint8Array): string => base32upper.encode(key).slice(1)\n\n/**\n * Get key for storing the record locally.\n * Format: /ipns/${base32()}\n *\n * @param {Uint8Array} key - peer identifier object.\n */\nexport const getLocalKey = (key: Uint8Array): Key => new Key(`/ipns/${rawStdEncoding(key)}`)\n\nexport { unmarshal } from './utils.js'\nexport { marshal } from './utils.js'\nexport { peerIdToRoutingKey } from './utils.js'\nexport { peerIdFromRoutingKey } from './utils.js'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Promise => {\n try {\n const dataForSignature = ipnsEntryDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw errCode(new Error('record signature creation failed'), ERRORS.ERR_SIGNATURE_CREATION)\n }\n}\n", "import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/pbe.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\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 * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface-keys'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string): CodeError> {\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}\n\nfunction typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n// Generates a keypair of the given type and bitsize\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise { // eslint-disable-line require-await\n return typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n// Generates a keypair of the given type and bitsize\n// seed is a 32 byte uint8array\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise { // eslint-disable-line require-await\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\n return Ed25519.generateKeyPairFromSeed(seed)\n}\n\n// Converts a protobuf serialized public key into its\n// representative object\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\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 ?? 'RSA')\n }\n}\n\n// Converts a public key object into a protobuf serialized public key\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\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\n// representative object\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise { // eslint-disable-line require-await\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\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\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n *\n * @param {string} encryptedKey\n * @param {string} password\n */\nexport async function importKey (encryptedKey: string, password: string): Promise { // eslint-disable-line require-await\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n // Only rsa supports pem right now\n const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password)\n if (key === null) {\n throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM')\n }\n let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))\n der = uint8ArrayFromString(der.getBytes(), 'ascii')\n return supportedKeys.rsa.unmarshalRsaPrivateKey(der)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\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 * as crypto from './ed25519.js'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport type { Multibase } from 'multiformats'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n async verify (data: Uint8Array, sig: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n async sign (message: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Ed25519PublicKey {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 (): Promise {\n const encoding = identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\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\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}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const { privateKey, publicKey } = await crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array): Promise {\n const { privateKey, publicKey } = await crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number): Uint8Array {\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", "/*! noble-ed25519 - 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 _8n = BigInt(8);\nconst CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989');\nconst CURVE = Object.freeze({\n a: BigInt(-1),\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'),\n l: CU_O,\n n: CU_O,\n h: BigInt(8),\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n});\nexport { CURVE };\nconst POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');\nconst SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\nconst SQRT_D = BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742');\nconst SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\nconst INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\nconst ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\nconst D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\nclass ExtendedPoint {\n constructor(x, y, z, t) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.t = t;\n }\n static fromAffine(p) {\n if (!(p instanceof Point)) {\n throw new TypeError('ExtendedPoint#fromAffine: expected Point');\n }\n if (p.equals(Point.ZERO))\n return ExtendedPoint.ZERO;\n return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y));\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 this.toAffineBatch(points).map(this.fromAffine);\n }\n equals(other) {\n assertExtPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n const X1Z2 = mod(X1 * Z2);\n const X2Z1 = mod(X2 * Z1);\n const Y1Z2 = mod(Y1 * Z2);\n const Y2Z1 = mod(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n negate() {\n return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));\n }\n double() {\n const { x: X1, y: Y1, z: Z1 } = this;\n const { a } = CURVE;\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(_2n * mod(Z1 * Z1));\n const D = mod(a * A);\n const x1y1 = X1 + Y1;\n const E = mod(mod(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new ExtendedPoint(X3, Y3, Z3, T3);\n }\n add(other) {\n assertExtPoint(other);\n const { x: X1, y: Y1, z: Z1, t: T1 } = this;\n const { x: X2, y: Y2, z: Z2, t: T2 } = other;\n const A = mod((Y1 - X1) * (Y2 + X2));\n const B = mod((Y1 + X1) * (Y2 - X2));\n const F = mod(B - A);\n if (F === _0n)\n return this.double();\n const C = mod(Z1 * _2n * T2);\n const D = mod(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new ExtendedPoint(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n precomputeWindow(W) {\n const windows = 1 + 256 / W;\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(ExtendedPoint.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 = ExtendedPoint.normalizeZ(precomputes);\n pointPrecomputes.set(affinePoint, precomputes);\n }\n }\n let p = ExtendedPoint.ZERO;\n let f = ExtendedPoint.BASE;\n const windows = 1 + 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 ExtendedPoint.normalizeZ([p, f])[0];\n }\n multiply(scalar, affinePoint) {\n return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint);\n }\n multiplyUnsafe(scalar) {\n let n = normalizeScalar(scalar, CURVE.l, false);\n const G = ExtendedPoint.BASE;\n const P0 = ExtendedPoint.ZERO;\n if (n === _0n)\n return P0;\n if (this.equals(P0) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n);\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 isSmallOrder() {\n return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);\n }\n isTorsionFree() {\n let p = this.multiplyUnsafe(CURVE.l / _2n).double();\n if (CURVE.l % _2n)\n p = p.add(this);\n return p.equals(ExtendedPoint.ZERO);\n }\n toAffine(invZ) {\n const { x, y, z } = this;\n const is0 = this.equals(ExtendedPoint.ZERO);\n if (invZ == null)\n invZ = is0 ? _8n : invert(z);\n const ax = mod(x * invZ);\n const ay = mod(y * invZ);\n const zz = mod(z * invZ);\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 fromRistrettoBytes() {\n legacyRist();\n }\n toRistrettoBytes() {\n legacyRist();\n }\n fromRistrettoHash() {\n legacyRist();\n }\n}\nExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy));\nExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nfunction assertExtPoint(other) {\n if (!(other instanceof ExtendedPoint))\n throw new TypeError('ExtendedPoint expected');\n}\nfunction assertRstPoint(other) {\n if (!(other instanceof RistrettoPoint))\n throw new TypeError('RistrettoPoint expected');\n}\nfunction legacyRist() {\n throw new Error('Legacy method: switch to RistrettoPoint');\n}\nclass RistrettoPoint {\n constructor(ep) {\n this.ep = ep;\n }\n static calcElligatorRistrettoMap(r0) {\n const { d } = CURVE;\n const r = mod(SQRT_M1 * r0 * r0);\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ);\n let c = BigInt(-1);\n const D = mod((c - d * r) * mod(r + d));\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);\n let s_ = mod(s * r0);\n if (!edIsNegative(s_))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_;\n if (!Ns_D_is_sq)\n c = r;\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D);\n const s2 = s * s;\n const W0 = mod((s + s) * D);\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE);\n const W2 = mod(_1n - s2);\n const W3 = mod(_1n + s2);\n return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n }\n static hashToCurve(hex) {\n hex = ensureBytes(hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = this.calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = this.calcElligatorRistrettoMap(r2);\n return new RistrettoPoint(R1.add(R2));\n }\n static fromHex(hex) {\n hex = ensureBytes(hex, 32);\n const { a, d } = CURVE;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2);\n const u2 = mod(_1n - a * s2);\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2);\n const { isValid, value: I } = invertSqrt(mod(v * u2_2));\n const Dx = mod(I * u2);\n const Dy = mod(I * Dx * v);\n let x = mod((s + s) * Dx);\n if (edIsNegative(x))\n x = mod(-x);\n const y = mod(u1 * Dy);\n const t = mod(x * y);\n if (!isValid || edIsNegative(t) || y === _0n)\n throw new Error(emsg);\n return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t));\n }\n toRawBytes() {\n let { x, y, z, t } = this.ep;\n const u1 = mod(mod(z + y) * mod(z - y));\n const u2 = mod(x * y);\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));\n const D1 = mod(invsqrt * u1);\n const D2 = mod(invsqrt * u2);\n const zInv = mod(D1 * D2 * t);\n let D;\n if (edIsNegative(t * zInv)) {\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;\n }\n if (edIsNegative(x * zInv))\n y = mod(-y);\n let s = mod((z - y) * D);\n if (edIsNegative(s))\n s = mod(-s);\n return numberTo32BytesLE(s);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n equals(other) {\n assertRstPoint(other);\n const a = this.ep;\n const b = other.ep;\n const one = mod(a.x * b.y) === mod(a.y * b.x);\n const two = mod(a.y * b.y) === mod(a.x * b.x);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistrettoPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistrettoPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistrettoPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistrettoPoint(this.ep.multiplyUnsafe(scalar));\n }\n}\nRistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE);\nRistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO);\nconst pointPrecomputes = new WeakMap();\nclass 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 static fromHex(hex, strict = true) {\n const { d, P } = CURVE;\n hex = ensureBytes(hex, 32);\n const normed = hex.slice();\n normed[31] = hex[31] & ~0x80;\n const y = bytesToNumberLE(normed);\n if (strict && y >= P)\n throw new Error('Expected 0 < hex < P');\n if (!strict && y >= POW_2_256)\n throw new Error('Expected 0 < hex < 2**256');\n const y2 = mod(y * y);\n const u = mod(y2 - _1n);\n const v = mod(d * y2 + _1n);\n let { isValid, value: x } = uvRatio(u, v);\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n;\n const isLastByteOdd = (hex[31] & 0x80) !== 0;\n if (isLastByteOdd !== isXOdd) {\n x = mod(-x);\n }\n return new Point(x, y);\n }\n static async fromPrivateKey(privateKey) {\n return (await getExtendedPublicKey(privateKey)).point;\n }\n toRawBytes() {\n const bytes = numberTo32BytesLE(this.y);\n bytes[31] |= this.x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toX25519() {\n const { y } = this;\n const u = mod((_1n + y) * invert(_1n - y));\n return numberTo32BytesLE(u);\n }\n isTorsionFree() {\n return ExtendedPoint.fromAffine(this).isTorsionFree();\n }\n equals(other) {\n return this.x === other.x && this.y === other.y;\n }\n negate() {\n return new Point(mod(-this.x), this.y);\n }\n add(other) {\n return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiply(scalar) {\n return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();\n }\n}\nPoint.BASE = new Point(CURVE.Gx, CURVE.Gy);\nPoint.ZERO = new Point(_0n, _1n);\nclass Signature {\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, 64);\n const r = Point.fromHex(bytes.slice(0, 32), false);\n const s = bytesToNumberLE(bytes.slice(32, 64));\n return new Signature(r, s);\n }\n assertValidity() {\n const { r, s } = this;\n if (!(r instanceof Point))\n throw new Error('Expected Point instance');\n normalizeScalar(s, CURVE.l, false);\n return this;\n }\n toRawBytes() {\n const u8 = new Uint8Array(64);\n u8.set(this.r.toRawBytes());\n u8.set(numberTo32BytesLE(this.s), 32);\n return u8;\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n}\nexport { ExtendedPoint, RistrettoPoint, Point, Signature };\nfunction concatBytes(...arrays) {\n if (!arrays.every((a) => a instanceof Uint8Array))\n throw new Error('Expected Uint8Array list');\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('Uint8Array expected');\n let hex = '';\n for (let i = 0; i < uint8a.length; i++) {\n hex += hexes[uint8a[i]];\n }\n return 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');\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 numberTo32BytesBE(num) {\n const length = 32;\n const hex = num.toString(16).padStart(length * 2, '0');\n return hexToBytes(hex);\n}\nfunction numberTo32BytesLE(num) {\n return numberTo32BytesBE(num).reverse();\n}\nfunction edIsNegative(num) {\n return (mod(num) & _1n) === _1n;\n}\nfunction bytesToNumberLE(uint8a) {\n if (!(uint8a instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse()));\n}\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nfunction bytes255ToNumberLE(bytes) {\n return mod(bytesToNumberLE(bytes) & MAX_255B);\n}\nfunction mod(a, b = CURVE.P) {\n const res = a % b;\n return res >= _0n ? res : b + res;\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 tmp = new Array(nums.length);\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (num === _0n)\n return acc;\n tmp[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 tmp[i] = mod(acc * tmp[i], p);\n return mod(acc * num, p);\n }, inverted);\n return tmp;\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 pow_2_252_3(x) {\n const { P } = CURVE;\n const _5n = BigInt(5);\n const _10n = BigInt(10);\n const _20n = BigInt(20);\n const _40n = BigInt(40);\n const _80n = BigInt(80);\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P;\n const b4 = (pow2(b2, _2n) * b2) % P;\n const b5 = (pow2(b4, _1n) * x) % P;\n const b10 = (pow2(b5, _5n) * b5) % P;\n const b20 = (pow2(b10, _10n) * b10) % P;\n const b40 = (pow2(b20, _20n) * b20) % P;\n const b80 = (pow2(b40, _40n) * b40) % P;\n const b160 = (pow2(b80, _80n) * b80) % P;\n const b240 = (pow2(b160, _80n) * b80) % P;\n const b250 = (pow2(b240, _10n) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n) * x) % P;\n return { pow_p_5_8, b2 };\n}\nfunction uvRatio(u, v) {\n const v3 = mod(v * v * v);\n const v7 = mod(v3 * v3 * v);\n const pow = pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow);\n const vx2 = mod(v * x * x);\n const root1 = x;\n const root2 = mod(x * SQRT_M1);\n const useRoot1 = vx2 === u;\n const useRoot2 = vx2 === mod(-u);\n const noRoot = vx2 === mod(-u * SQRT_M1);\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2;\n if (edIsNegative(x))\n x = mod(-x);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nfunction invertSqrt(number) {\n return uvRatio(_1n, number);\n}\nfunction modlLE(hash) {\n return mod(bytesToNumberLE(hash), CURVE.l);\n}\nfunction equalBytes(b1, b2) {\n if (b1.length !== b2.length) {\n return false;\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction ensureBytes(hex, expectedLength) {\n const bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);\n if (typeof expectedLength === 'number' && bytes.length !== expectedLength)\n throw new Error(`Expected ${expectedLength} bytes`);\n return bytes;\n}\nfunction normalizeScalar(num, max, strict = true) {\n if (!max)\n throw new TypeError('Specify max value');\n if (typeof num === 'number' && Number.isSafeInteger(num))\n num = BigInt(num);\n if (typeof num === 'bigint' && num < max) {\n if (strict) {\n if (_0n < num)\n return num;\n }\n else {\n if (_0n <= num)\n return num;\n }\n }\n throw new TypeError('Expected valid scalar: 0 < scalar < max');\n}\nfunction adjustBytes25519(bytes) {\n bytes[0] &= 248;\n bytes[31] &= 127;\n bytes[31] |= 64;\n return bytes;\n}\nfunction decodeScalar25519(n) {\n return bytesToNumberLE(adjustBytes25519(ensureBytes(n, 32)));\n}\nfunction checkPrivateKey(key) {\n key =\n typeof key === 'bigint' || typeof key === 'number'\n ? numberTo32BytesBE(normalizeScalar(key, POW_2_256))\n : ensureBytes(key);\n if (key.length !== 32)\n throw new Error(`Expected 32 bytes`);\n return key;\n}\nfunction getKeyFromHash(hashed) {\n const head = adjustBytes25519(hashed.slice(0, 32));\n const prefix = hashed.slice(32, 64);\n const scalar = modlLE(head);\n const point = Point.BASE.multiply(scalar);\n const pointBytes = point.toRawBytes();\n return { head, prefix, scalar, point, pointBytes };\n}\nlet _sha512Sync;\nfunction sha512s(...m) {\n if (typeof _sha512Sync !== 'function')\n throw new Error('utils.sha512Sync must be set to use sync methods');\n return _sha512Sync(...m);\n}\nasync function getExtendedPublicKey(key) {\n return getKeyFromHash(await utils.sha512(checkPrivateKey(key)));\n}\nfunction getExtendedPublicKeySync(key) {\n return getKeyFromHash(sha512s(checkPrivateKey(key)));\n}\nexport async function getPublicKey(privateKey) {\n return (await getExtendedPublicKey(privateKey)).pointBytes;\n}\nfunction getPublicKeySync(privateKey) {\n return getExtendedPublicKeySync(privateKey).pointBytes;\n}\nexport async function sign(message, privateKey) {\n message = ensureBytes(message);\n const { prefix, scalar, pointBytes } = await getExtendedPublicKey(privateKey);\n const r = modlLE(await utils.sha512(prefix, message));\n const R = Point.BASE.multiply(r);\n const k = modlLE(await utils.sha512(R.toRawBytes(), pointBytes, message));\n const s = mod(r + k * scalar, CURVE.l);\n return new Signature(R, s).toRawBytes();\n}\nfunction signSync(message, privateKey) {\n message = ensureBytes(message);\n const { prefix, scalar, pointBytes } = getExtendedPublicKeySync(privateKey);\n const r = modlLE(sha512s(prefix, message));\n const R = Point.BASE.multiply(r);\n const k = modlLE(sha512s(R.toRawBytes(), pointBytes, message));\n const s = mod(r + k * scalar, CURVE.l);\n return new Signature(R, s).toRawBytes();\n}\nfunction prepareVerification(sig, message, publicKey) {\n message = ensureBytes(message);\n if (!(publicKey instanceof Point))\n publicKey = Point.fromHex(publicKey, false);\n const { r, s } = sig instanceof Signature ? sig.assertValidity() : Signature.fromHex(sig);\n const SB = ExtendedPoint.BASE.multiplyUnsafe(s);\n return { r, s, SB, pub: publicKey, msg: message };\n}\nfunction finishVerification(publicKey, r, SB, hashed) {\n const k = modlLE(hashed);\n const kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k);\n const RkA = ExtendedPoint.fromAffine(r).add(kA);\n return RkA.subtract(SB).multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);\n}\nexport async function verify(sig, message, publicKey) {\n const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);\n const hashed = await utils.sha512(r.toRawBytes(), pub.toRawBytes(), msg);\n return finishVerification(pub, r, SB, hashed);\n}\nfunction verifySync(sig, message, publicKey) {\n const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);\n const hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg);\n return finishVerification(pub, r, SB, hashed);\n}\nexport const sync = {\n getExtendedPublicKey: getExtendedPublicKeySync,\n getPublicKey: getPublicKeySync,\n sign: signSync,\n verify: verifySync,\n};\nexport async function getSharedSecret(privateKey, publicKey) {\n const { head } = await getExtendedPublicKey(privateKey);\n const u = Point.fromHex(publicKey).toX25519();\n return curve25519.scalarMult(head, u);\n}\nPoint.BASE._setWindowSize(8);\nfunction cswap(swap, x_2, x_3) {\n const dummy = mod(swap * (x_2 - x_3));\n x_2 = mod(x_2 - dummy);\n x_3 = mod(x_3 + dummy);\n return [x_2, x_3];\n}\nfunction montgomeryLadder(pointU, scalar) {\n const { P } = CURVE;\n const u = normalizeScalar(pointU, P);\n const k = normalizeScalar(scalar, P);\n const a24 = BigInt(121665);\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(255 - 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 = mod(A * A);\n const B = x_2 - z_2;\n const BB = mod(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = mod(D * A);\n const CB = mod(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = mod(dacb * dacb);\n z_3 = mod(x_1 * mod(da_cb * da_cb));\n x_2 = mod(AA * BB);\n z_2 = mod(E * (AA + mod(a24 * E)));\n }\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 const { pow_p_5_8, b2 } = pow_2_252_3(z_2);\n const xp2 = mod(pow2(pow_p_5_8, BigInt(3)) * b2);\n return mod(x_2 * xp2);\n}\nfunction encodeUCoordinate(u) {\n return numberTo32BytesLE(mod(u, CURVE.P));\n}\nfunction decodeUCoordinate(uEnc) {\n const u = ensureBytes(uEnc, 32);\n u[31] &= 127;\n return bytesToNumberLE(u);\n}\nexport const curve25519 = {\n BASE_POINT_U: '0900000000000000000000000000000000000000000000000000000000000000',\n scalarMult(privateKey, publicKey) {\n const u = decodeUCoordinate(publicKey);\n const p = decodeScalar25519(privateKey);\n const pu = montgomeryLadder(u, p);\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n },\n scalarMultBase(privateKey) {\n return curve25519.scalarMult(privateKey, curve25519.BASE_POINT_U);\n },\n};\nconst crypto = {\n node: nodeCrypto,\n web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,\n};\nexport const utils = {\n bytesToHex,\n hexToBytes,\n concatBytes,\n getExtendedPublicKey,\n mod,\n invert,\n TORSION_SUBGROUP: [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n ],\n hashToPrivateScalar: (hash) => {\n hash = ensureBytes(hash);\n if (hash.length < 40 || hash.length > 1024)\n throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');\n return mod(bytesToNumberLE(hash), CURVE.l - _1n) + _1n;\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 new Uint8Array(randomBytes(bytesLength).buffer);\n }\n else {\n throw new Error(\"The environment doesn't have randomBytes function\");\n }\n },\n randomPrivateKey: () => {\n return utils.randomBytes(32);\n },\n sha512: async (...messages) => {\n const message = concatBytes(...messages);\n if (crypto.web) {\n const buffer = await crypto.web.subtle.digest('SHA-512', message.buffer);\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n return Uint8Array.from(crypto.node.createHash('sha512').update(message).digest());\n }\n else {\n throw new Error(\"The environment doesn't have sha512 function\");\n }\n },\n precompute(windowSize = 8, point = Point.BASE) {\n const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);\n cached._setWindowSize(windowSize);\n cached.multiply(_2n);\n return cached;\n },\n sha512Sync: undefined,\n};\nObject.defineProperties(utils, {\n sha512Sync: {\n configurable: false,\n get() {\n return _sha512Sync;\n },\n set(val) {\n if (!_sha512Sync)\n _sha512Sync = val;\n },\n },\n});\n", "import * as ed from '@noble/ed25519'\nimport type { Uint8ArrayKeyPair } from './interface'\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\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport async function generateKey (): Promise {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport async function generateKeyFromSeed (seed: Uint8Array): Promise {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array): Promise {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg, privateKeyRaw)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise {\n return ed.verify(sig, msg, publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\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", "import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed ArrayLikes\n */\nexport function concat (arrays: Array>, length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/* eslint-env browser */\n\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\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n '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-crypto/blob/master/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n", "import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\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// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' }\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions): AESCipher {\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\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\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: Uint8Array, password: string | Uint8Array): Promise { // eslint-disable-line require-await\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: 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 } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt'])\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\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 /**\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: Uint8Array, password: string | Uint8Array): Promise {\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\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\n let cryptoKey: 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 } catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt'])\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\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext)\n return new Uint8Array(plaintext)\n }\n\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\nimport type { Multibase } from 'multiformats'\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 */\nexport async function exporter (privateKey: Uint8Array, password: string): Promise> {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = (): Codec => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\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/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\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}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\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/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\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/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\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", "// 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/**\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 public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\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 */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\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 /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\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\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\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 /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\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 /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\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 /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\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) { 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 */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\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}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\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 } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\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 } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // 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 * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\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 if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = 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 */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\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 /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const 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 */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { 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 }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\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\n private readLongVarint (): LongBits {\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) { 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) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { 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) { 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) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\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) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\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 (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Pick, 'decode'>, opts?: DecodeOptions): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "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'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation {\n (val: T, buf: Uint8Array, pos: number): any\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 public fn: WriterOperation\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op\n\n /**\n * Current tail\n */\n public tail: Op\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\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 implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op\n\n /**\n * Operations tail\n */\n public tail: Op\n\n /**\n * Linked forked states\n */\n public states?: any\n\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 /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\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\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\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 */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\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: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\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 /**\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 (): this {\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 */\n reset (): this {\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 } 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 */\n ldelim (): this {\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 /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\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}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\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 *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n public next?: Op\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\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}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\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\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\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\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\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 } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage (message: Partial, codec: Pick, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: Partial, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array ?\n (ElementType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map ?\n (MapValueType extends PrimitiveTypes ? never : Limits) :\n (T[K] extends PrimitiveTypes ? never : Limits)\n}\n\n// union of collection and array elements\ntype Limits = Partial & ArrayElementLimits & MapValueLimits>\n\nexport interface DecodeOptions {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number, opts?: DecodeOptions): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\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\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: EncodeFunction, decode: DecodeFunction): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "import 'node-forge/lib/util.js'\nimport 'node-forge/lib/jsbn.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport function bigIntegerToUintBase64url (num: { abs: () => any }, len?: number): string {\n // Call `.abs()` to convert to unsigned\n let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian\n\n // toByteArray() gives us back a signed array, which will include a leading 0\n // byte if the most significant bit of the number is 1:\n // https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer\n // Our number will always be positive so we should remove the leading padding.\n buf = buf[0] === 0 ? buf.subarray(1) : buf\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return uint8ArrayToString(buf, 'base64url')\n}\n\n// Convert a base64url encoded string to a BigInteger\nexport function base64urlToBigInteger (str: string): typeof forge.jsbn.BigInteger {\n const buf = base64urlToBuffer(str)\n return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16)\n}\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { base64urlToBuffer } from '../util.js'\nimport webcrypto from '../webcrypto.js'\nimport type { ECDHKey, ECDHKeyPair, JWKEncodedPrivateKey, JWKEncodedPublicKey } from './interface.js'\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n}\n\nconst curveTypes = Object.keys(bits)\nconst names = curveTypes.join(' / ')\n\nexport async function generateEphmeralKeyPair (curve: string): Promise {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve\n },\n true,\n ['deriveBits']\n )\n\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair): Promise => {\n let privateKey\n\n if (forcePrivate != null) {\n privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPrivateKey(curve, forcePrivate),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n ['deriveBits']\n )\n } else {\n privateKey = pair.privateKey\n }\n\n const key = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPublicKey(curve, theirPub),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n []\n )\n\n const buffer = await webcrypto.get().subtle.deriveBits(\n {\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n },\n privateKey,\n bits[curve]\n )\n\n return new Uint8Array(buffer, 0, buffer.byteLength)\n }\n\n const publicKey = await webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n\n const ecdhKey: ECDHKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n }\n\n return ecdhKey\n}\n\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n}\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: JsonWebKey): Uint8Array {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[jwk.crv]\n\n return uint8ArrayConcat([\n Uint8Array.from([4]), // uncompressed point\n base64urlToBuffer(jwk.x, byteLen),\n base64urlToBuffer(jwk.y, byteLen)\n ], 1 + byteLen * 2)\n}\n\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey (curve: string, key: Uint8Array): JWKEncodedPublicKey {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[curve]\n\n if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT')\n }\n\n return {\n kty: 'EC',\n crv: curve,\n x: uint8ArrayToString(key.subarray(1, byteLen + 1), 'base64url'),\n y: uint8ArrayToString(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n }\n}\n\nconst unmarshalPrivateKey = (curve: string, key: ECDHKeyPair): JWKEncodedPrivateKey => ({\n ...unmarshalPublicKey(curve, key.public),\n d: uint8ArrayToString(key.private, 'base64url')\n})\n", "import { generateEphmeralKeyPair } from './ecdh.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 */\nexport default generateEphmeralKeyPair\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\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 */\nexport async function importer (privateKey: string, password: string): Promise {\n const encryptedKey = base64.decode(privateKey)\n const cipher = ciphers.create()\n return cipher.decrypt(encryptedKey, password)\n}\n", "\nexport default {\n SHA1: 20,\n SHA256: 32,\n SHA512: 64\n}\n", "import webcrypto from '../webcrypto.js'\nimport lengths from './lengths.js'\n\nconst hashTypes = {\n SHA1: 'SHA-1',\n SHA256: 'SHA-256',\n SHA512: 'SHA-512'\n}\n\nconst sign = async (key: CryptoKey, data: Uint8Array): Promise => {\n const buf = await webcrypto.get().subtle.sign({ name: 'HMAC' }, key, data)\n return new Uint8Array(buf, 0, buf.byteLength)\n}\n\nexport async function create (hashType: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise<{ digest: (data: Uint8Array) => Promise, length: number }> {\n const hash = hashTypes[hashType]\n\n const key = await webcrypto.get().subtle.importKey(\n 'raw',\n secret,\n {\n name: 'HMAC',\n hash: { name: hash }\n },\n false,\n ['sign']\n )\n\n return {\n async digest (data: Uint8Array) { // eslint-disable-line require-await\n return sign(key, data)\n },\n length: lengths[hashType]\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport * as hmac from '../hmac/index.js'\nimport type { EnhancedKey, EnhancedKeyPair } from './interface.js'\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/**\n * Generates a set of keys for each party by stretching the shared key.\n * (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)\n */\nexport async function keyStretcher (cipherType: 'AES-128' | 'AES-256' | 'Blowfish', hash: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise {\n const cipher = cipherMap[cipherType]\n\n if (cipher == null) {\n const allowed = Object.keys(cipherMap).join(' / ')\n throw new CodeError(`unknown cipher type '${cipherType}'. Must be ${allowed}`, 'ERR_INVALID_CIPHER_TYPE')\n }\n\n if (hash == null) {\n throw new CodeError('missing hash type', 'ERR_MISSING_HASH_TYPE')\n }\n\n const cipherKeySize = cipher.keySize\n const ivSize = cipher.ivSize\n const hmacKeySize = 20\n const seed = uint8ArrayFromString('key expansion')\n const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize)\n\n const m = await hmac.create(hash, secret)\n let a = await m.digest(seed)\n\n const result = []\n let j = 0\n\n while (j < resultLength) {\n const b = await m.digest(uint8ArrayConcat([a, seed]))\n let todo = b.length\n\n if (j + todo > resultLength) {\n todo = resultLength - j\n }\n\n result.push(b)\n j += todo\n a = await m.digest(a)\n }\n\n const half = resultLength / 2\n const resultBuffer = uint8ArrayConcat(result)\n const r1 = resultBuffer.subarray(0, half)\n const r2 = resultBuffer.subarray(half, resultLength)\n\n const createKey = (res: Uint8Array): EnhancedKey => ({\n iv: res.subarray(0, ivSize),\n cipherKey: res.subarray(ivSize, ivSize + cipherKeySize),\n macKey: res.subarray(ivSize + cipherKeySize)\n })\n\n return {\n k1: createKey(r1),\n k2: createKey(r2)\n }\n}\n", "\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { sha256 } from 'multiformats/hashes/sha2'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport 'node-forge/lib/sha512.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { exporter } from './exporter.js'\nimport * as pbm from './keys.js'\nimport * as crypto from './rsa.js'\nimport type { Multibase } from 'multiformats'\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n encrypt (bytes: Uint8Array): Uint8Array {\n return crypto.encrypt(this._key, bytes)\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret (): Uint8Array {\n return crypto.getRandomValues(16)\n }\n\n async sign (message: Uint8Array): Promise { // eslint-disable-line require-await\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): RsaPublicKey {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n decrypt (bytes: Uint8Array): Uint8Array {\n return crypto.decrypt(this._key, bytes)\n }\n\n marshal (): Uint8Array {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes (): Uint8Array {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected PEM format\n */\n async export (password: string, format = 'pkcs-8'): Promise> { // eslint-disable-line require-await\n if (format === 'pkcs-8') {\n const buffer = new forge.util.ByteBuffer(this.marshal())\n const asn1 = forge.asn1.fromDer(buffer)\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n const options = {\n algorithm: 'aes256',\n count: 10000,\n saltSize: 128 / 8,\n prfAlgorithm: 'sha512'\n }\n return forge.pki.encryptRsaPrivateKey(privateKey, password, options)\n } else if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey {\n const jwk = crypto.utils.pkixToJwk(bytes)\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey): Promise {\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number): Promise {\n const keys = await crypto.generateKey(bits)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n", "/*! 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 { CodeError } from '@libp2p/interfaces/errors'\nimport { utils } from '@noble/secp256k1'\n\nexport default function randomBytes (length: number): Uint8Array {\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 utils.randomBytes(length)\n}\n", "import 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { base64urlToBigInteger } from '../util.js'\n\nexport interface JWK {\n encrypt: (msg: string) => string\n decrypt: (msg: string) => string\n}\n\nfunction convert (key: any, types: string[]): Array {\n return types.map(t => base64urlToBigInteger(key[t]))\n}\n\nexport function jwk2priv (key: JsonWebKey): JWK {\n return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']))\n}\n\nexport function jwk2pub (key: JsonWebKey): JWK {\n return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e']))\n}\n", "import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/rsa.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js'\n\n// Convert a PKCS#1 in ASN1 DER format to a JWK key\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n // https://tools.ietf.org/html/rfc7518#section-6.3.1\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(privateKey.n),\n e: bigIntegerToUintBase64url(privateKey.e),\n d: bigIntegerToUintBase64url(privateKey.d),\n p: bigIntegerToUintBase64url(privateKey.p),\n q: bigIntegerToUintBase64url(privateKey.q),\n dp: bigIntegerToUintBase64url(privateKey.dP),\n dq: bigIntegerToUintBase64url(privateKey.dQ),\n qi: bigIntegerToUintBase64url(privateKey.qInv),\n alg: 'RS256'\n }\n}\n\n// Convert a JWK key into PKCS#1 in ASN1 DER format\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\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\n const asn1 = forge.pki.privateKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e),\n d: base64urlToBigInteger(jwk.d),\n p: base64urlToBigInteger(jwk.p),\n q: base64urlToBigInteger(jwk.q),\n dP: base64urlToBigInteger(jwk.dp),\n dQ: base64urlToBigInteger(jwk.dq),\n qInv: base64urlToBigInteger(jwk.qi)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n\n// Convert a PKCIX in ASN1 DER format to a JWK key\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const publicKey = forge.pki.publicKeyFromAsn1(asn1)\n\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(publicKey.n),\n e: bigIntegerToUintBase64url(publicKey.e)\n }\n}\n\n// Convert a JWK key to PKCIX in ASN1 DER format\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const asn1 = forge.pki.publicKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\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 { jwk2pub, jwk2priv } from './jwk2pem.js'\nimport * as utils from './rsa-utils.js'\nimport type { JWKKeyPair } from './interface.js'\n\nexport { utils }\n\nexport async function generateKey (bits: number): Promise {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array): Promise {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n Uint8Array.from(msg)\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array): Promise {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey): Promise {\n return webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\n/*\n\nRSA encryption/decryption for the browser with webcrypto workaround\n\"bloody dark magic. webcrypto's why.\"\n\nExplanation:\n - Convert JWK to nodeForge\n - Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a \"binary-string backed buffer\", so let's make our Uint8Array a binary string\n - Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array\n\n*/\n\nfunction convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array, handle: (msg: string, key: { encrypt: (msg: string) => string, decrypt: (msg: string) => string }) => string): Uint8Array {\n const fkey = pub ? jwk2pub(key) : jwk2priv(key)\n const fmsg = uint8ArrayToString(Uint8Array.from(msg), 'ascii')\n const fomsg = handle(fmsg, fkey)\n return uint8ArrayFromString(fomsg, 'ascii')\n}\n\nexport function encrypt (key: JsonWebKey, msg: Uint8Array): Uint8Array {\n return convertKey(key, true, msg, (msg, key) => key.encrypt(msg))\n}\n\nexport function decrypt (key: JsonWebKey, msg: Uint8Array): Uint8Array {\n return convertKey(key, false, msg, (msg, key) => key.decrypt(msg))\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\nimport * as crypto from './secp256k1.js'\nimport type { Multibase } from 'multiformats'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array): Promise {\n return crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal (): Uint8Array {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n async sign (message: Uint8Array): Promise {\n return crypto.hashAndSign(this._key, message)\n }\n\n get public (): Secp256k1PublicKey {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal (): Uint8Array {\n return this._key\n }\n\n get bytes (): Uint8Array {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any): boolean {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash (): Promise {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 (): Promise {\n const hash = await this.public.hash()\n return uint8ArrayToString(hash, 'base58btc')\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key'): Promise> {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair (): Promise {\n const privateKeyBytes = crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport * as secp from '@noble/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport async function hashAndSign (key: Uint8Array, msg: Uint8Array): Promise {\n const { digest } = await sha256.digest(msg)\n try {\n return await secp.sign(digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise {\n try {\n const { digest } = await sha256.digest(msg)\n return secp.verify(sig, digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.Point.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array): Uint8Array {\n const point = secp.Point.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array): void {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array): void {\n try {\n secp.Point.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n", "import errCode from 'err-code'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { IPNSEntry, IPNSEntryData } from './index.js'\nimport * as ERRORS from './errors.js'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'\nimport { logger } from '@libp2p/logger'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport * as cborg from 'cborg'\nimport type { PublicKey } from '@libp2p/interface-keys'\n\nconst log = logger('ipns:utils')\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\n\n/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = milliseconds * 1000 * 1000\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n\n/**\n * Extracts a public key from the passed PeerId, falling\n * back to the pubKey embedded in the ipns record\n */\nexport const extractPublicKey = async (peerId: PeerId, entry: IpnsEntry): Promise => {\n if (entry == null || peerId == null) {\n const error = new Error('one or more of the provided parameters are not defined')\n\n log.error(error)\n throw errCode(error, ERRORS.ERR_UNDEFINED_PARAMETER)\n }\n\n let pubKey: PublicKey | undefined\n\n if (entry.pubKey != null) {\n try {\n pubKey = unmarshalPublicKey(entry.pubKey)\n } catch (err) {\n log.error(err)\n throw err\n }\n\n const otherId = await peerIdFromKeys(entry.pubKey)\n\n if (!otherId.equals(peerId)) {\n throw errCode(new Error('Embedded public key did not match PeerID'), ERRORS.ERR_INVALID_EMBEDDED_KEY)\n }\n } else if (peerId.publicKey != null) {\n pubKey = unmarshalPublicKey(peerId.publicKey)\n }\n\n if (pubKey != null) {\n return pubKey\n }\n\n throw errCode(new Error('no public key is available'), ERRORS.ERR_UNDEFINED_PARAMETER)\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport const ipnsEntryDataForV1Sig = (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array => {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n\n return uint8ArrayConcat([value, validity, validityTypeBuffer])\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport const ipnsEntryDataForV2Sig = (data: Uint8Array): Uint8Array => {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport const marshal = (obj: IPNSEntry): Uint8Array => {\n return IpnsEntry.encode(obj)\n}\n\nexport const unmarshal = (buf: Uint8Array): IPNSEntry => {\n const message = IpnsEntry.decode(buf)\n\n // protobufjs returns bigints as numbers\n if (message.sequence != null) {\n message.sequence = BigInt(message.sequence)\n }\n\n // protobufjs returns bigints as numbers\n if (message.ttl != null) {\n message.ttl = BigInt(message.ttl)\n }\n\n return {\n value: message.value ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n validityType: message.validityType ?? IpnsEntry.ValidityType.EOL,\n validity: message.validity ?? new Uint8Array(0),\n sequence: message.sequence ?? 0n,\n pubKey: message.pubKey,\n ttl: message.ttl ?? undefined,\n signatureV2: message.signatureV2,\n data: message.data\n }\n}\n\nexport const peerIdToRoutingKey = (peerId: PeerId): Uint8Array => {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n peerId.toBytes()\n ])\n}\n\nexport const peerIdFromRoutingKey = (key: Uint8Array): PeerId => {\n return peerIdFromBytes(key.slice(IPNS_PREFIX.length))\n}\n\nexport const createCborData = (value: Uint8Array, validity: Uint8Array, validityType: string, sequence: bigint, ttl: bigint): Uint8Array => {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw errCode(new Error('Unknown validity type'), ERRORS.ERR_UNRECOGNIZED_VALIDITY)\n }\n\n const data = {\n Value: value,\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport const parseCborData = (buf: Uint8Array): IPNSEntryData => {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw errCode(new Error('Unknown validity type'), ERRORS.ERR_UNRECOGNIZED_VALIDITY)\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n", "\nexport const ERR_IPNS_EXPIRED_RECORD = 'ERR_IPNS_EXPIRED_RECORD'\nexport const ERR_UNRECOGNIZED_VALIDITY = 'ERR_UNRECOGNIZED_VALIDITY'\nexport const ERR_SIGNATURE_CREATION = 'ERR_SIGNATURE_CREATION'\nexport const ERR_SIGNATURE_VERIFICATION = 'ERR_SIGNATURE_VERIFICATION'\nexport const ERR_UNRECOGNIZED_FORMAT = 'ERR_UNRECOGNIZED_FORMAT'\nexport const ERR_PEER_ID_FROM_PUBLIC_KEY = 'ERR_PEER_ID_FROM_PUBLIC_KEY'\nexport const ERR_PUBLIC_KEY_FROM_ID = 'ERR_PUBLIC_KEY_FROM_ID'\nexport const ERR_UNDEFINED_PARAMETER = 'ERR_UNDEFINED_PARAMETER'\nexport const ERR_INVALID_RECORD_DATA = 'ERR_INVALID_RECORD_DATA'\nexport const ERR_INVALID_EMBEDDED_KEY = 'ERR_INVALID_EMBEDDED_KEY'\nexport const ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY'\n", "// @ts-expect-error no types\nimport ReaderClass from 'protobufjs/src/reader.js'\n// @ts-expect-error no types\nimport ReaderBufferClass from 'protobufjs/src/reader_buffer.js'\n// @ts-expect-error no types\nimport WriterClass from 'protobufjs/src/writer.js'\n// @ts-expect-error no types\nimport WriterBufferClass from 'protobufjs/src/writer_buffer.js'\n// @ts-expect-error no types\nimport util from 'protobufjs/src/util/minimal.js'\nimport type { Reader, Writer } from './index.js'\n\nfunction configure (): void {\n util._configure()\n ReaderClass._configure(ReaderBufferClass)\n WriterClass._configure(WriterBufferClass)\n}\n\n// Set up buffer utility according to the environment\nconfigure()\n\n// monkey patch the reader to add native bigint support\nconst methods = [\n 'uint64', 'int64', 'sint64', 'fixed64', 'sfixed64'\n]\n\nfunction patchReader (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (): bigint {\n return BigInt(original.call(this).toString())\n }\n }\n\n return obj\n}\n\nexport function reader (buf: Uint8Array): Reader {\n return patchReader(new ReaderClass(buf))\n}\n\nfunction patchWriter (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (val: bigint) {\n return original.call(this, val.toString())\n }\n }\n\n return obj\n}\n\nexport function writer (): Writer {\n return patchWriter(WriterClass.create())\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { reader } from './utils.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n const r = reader(buf instanceof Uint8Array ? buf : buf.subarray())\n\n return codec.decode(r)\n}\n", "import type { Codec } from './codec.js'\nimport { writer } from './utils.js'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8Array {\n const w = writer()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: T, writer: Writer, opts?: EncodeOptions): void\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\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\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, EncodeOptions } from '../codec.js'\nimport type { Codec } from '../codec.js'\nimport type { Reader, Writer } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: (obj: T, writer: Writer, opts?: EncodeOptions) => void, decode: (reader: Reader, length?: number) => T): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface IpnsEntry {\n value?: Uint8Array\n signature?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n pubKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec => {\n return enumeration(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signature != null) {\n w.uint32(18)\n w.bytes(obj.signature)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.pubKey != null) {\n w.uint32(58)\n w.bytes(obj.pubKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.value = reader.bytes()\n break\n case 2:\n obj.signature = reader.bytes()\n break\n case 3:\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n case 4:\n obj.validity = reader.bytes()\n break\n case 5:\n obj.sequence = reader.uint64()\n break\n case 6:\n obj.ttl = reader.uint64()\n break\n case 7:\n obj.pubKey = reader.bytes()\n break\n case 8:\n obj.signatureV2 = reader.bytes()\n break\n case 9:\n obj.data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: IpnsEntry): Uint8Array => {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): IpnsEntry => {\n return decodeMessage(buf, IpnsEntry.codec())\n }\n}\n", "const typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n];\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nexport function is(value) {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return 'undefined';\n }\n if (value === true || value === false) {\n return 'boolean';\n }\n const typeOf = typeof value;\n if (typeofs.includes(typeOf)) {\n return typeOf;\n }\n if (typeOf === 'function') {\n return 'Function';\n }\n if (Array.isArray(value)) {\n return 'Array';\n }\n if (isBuffer(value)) {\n return 'Buffer';\n }\n const objectType = getObjectType(value);\n if (objectType) {\n return objectType;\n }\n return 'Object';\n}\nfunction isBuffer(value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value);\n}\nfunction getObjectType(value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n}", "class Type {\n constructor(major, name, terminal) {\n this.major = major;\n this.majorEncoded = major << 5;\n this.name = name;\n this.terminal = terminal;\n }\n toString() {\n return `Type[${ this.major }].${ this.name }`;\n }\n compare(typ) {\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;\n }\n}\nType.uint = new Type(0, 'uint', true);\nType.negint = new Type(1, 'negint', true);\nType.bytes = new Type(2, 'bytes', true);\nType.string = new Type(3, 'string', true);\nType.array = new Type(4, 'array', false);\nType.map = new Type(5, 'map', false);\nType.tag = new Type(6, 'tag', false);\nType.float = new Type(7, 'float', true);\nType.false = new Type(7, 'false', true);\nType.true = new Type(7, 'true', true);\nType.null = new Type(7, 'null', true);\nType.undefined = new Type(7, 'undefined', true);\nType.break = new Type(7, 'break', true);\nclass Token {\n constructor(type, value, encodedLength) {\n this.type = type;\n this.value = value;\n this.encodedLength = encodedLength;\n this.encodedBytes = undefined;\n this.byteValue = undefined;\n }\n toString() {\n return `Token[${ this.type }].${ this.value }`;\n }\n}\nexport {\n Type,\n Token\n};", "export const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === 'function';\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\nfunction isBuffer(buf) {\n return useBuffer && globalThis.Buffer.isBuffer(buf);\n}\nexport function asU8A(buf) {\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf);\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;\n}\nexport const toString = useBuffer ? (bytes, start, end) => {\n return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8') : utf8Slice(bytes, start, end);\n} : (bytes, start, end) => {\n return end - start > 64 ? textDecoder.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end);\n};\nexport const fromString = useBuffer ? string => {\n return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string);\n} : string => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string);\n};\nexport const fromArray = arr => {\n return Uint8Array.from(arr);\n};\nexport const slice = useBuffer ? (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end));\n }\n return bytes.slice(start, end);\n} : (bytes, start, end) => {\n return bytes.slice(start, end);\n};\nexport const concat = useBuffer ? (chunks, length) => {\n chunks = chunks.map(c => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));\n return asU8A(globalThis.Buffer.concat(chunks, length));\n} : (chunks, length) => {\n const out = new Uint8Array(length);\n let off = 0;\n for (let b of chunks) {\n if (off + b.length > out.length) {\n b = b.subarray(0, out.length - off);\n }\n out.set(b, off);\n off += b.length;\n }\n return out;\n};\nexport const alloc = useBuffer ? size => {\n return globalThis.Buffer.allocUnsafe(size);\n} : size => {\n return new Uint8Array(size);\n};\nexport const toHex = useBuffer ? d => {\n if (typeof d === 'string') {\n return d;\n }\n return globalThis.Buffer.from(toBytes(d)).toString('hex');\n} : d => {\n if (typeof d === 'string') {\n return d;\n }\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${ p }${ c.toString(16).padStart(2, '0') }`, '');\n};\nexport const fromHex = useBuffer ? hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n return globalThis.Buffer.from(hex, 'hex');\n} : hex => {\n if (hex instanceof Uint8Array) {\n return hex;\n }\n if (!hex.length) {\n return new Uint8Array(0);\n }\n return new Uint8Array(hex.split('').map((c, i, d) => i % 2 === 0 ? `0x${ c }${ d[i + 1] }` : '').filter(Boolean).map(e => parseInt(e, 16)));\n};\nfunction toBytes(obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj;\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj);\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function compare(b1, b2) {\n if (isBuffer(b1) && isBuffer(b2)) {\n return b1.compare(b2);\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue;\n }\n return b1[i] < b2[i] ? -1 : 1;\n }\n return 0;\n}\nfunction utf8ToBytes(string, units = Infinity) {\n let codePoint;\n const length = string.length;\n let leadSurrogate = null;\n const bytes = [];\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n if (codePoint > 55295 && codePoint < 57344) {\n if (!leadSurrogate) {\n if (codePoint > 56319) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n } else if (i + 1 === length) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n continue;\n }\n leadSurrogate = codePoint;\n continue;\n }\n if (codePoint < 56320) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n leadSurrogate = codePoint;\n continue;\n }\n codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;\n } else if (leadSurrogate) {\n if ((units -= 3) > -1)\n bytes.push(239, 191, 189);\n }\n leadSurrogate = null;\n if (codePoint < 128) {\n if ((units -= 1) < 0)\n break;\n bytes.push(codePoint);\n } else if (codePoint < 2048) {\n if ((units -= 2) < 0)\n break;\n bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);\n } else if (codePoint < 65536) {\n if ((units -= 3) < 0)\n break;\n bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else if (codePoint < 1114112) {\n if ((units -= 4) < 0)\n break;\n bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);\n } else {\n throw new Error('Invalid code point');\n }\n }\n return bytes;\n}\nfunction utf8Slice(buf, offset, end) {\n const res = [];\n while (offset < end) {\n const firstByte = buf[offset];\n let codePoint = null;\n let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint;\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 128) {\n codePoint = firstByte;\n }\n break;\n case 2:\n secondByte = buf[offset + 1];\n if ((secondByte & 192) === 128) {\n tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;\n if (tempCodePoint > 127) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 3:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;\n if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {\n codePoint = tempCodePoint;\n }\n }\n break;\n case 4:\n secondByte = buf[offset + 1];\n thirdByte = buf[offset + 2];\n fourthByte = buf[offset + 3];\n if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {\n tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;\n if (tempCodePoint > 65535 && tempCodePoint < 1114112) {\n codePoint = tempCodePoint;\n }\n }\n }\n }\n if (codePoint === null) {\n codePoint = 65533;\n bytesPerSequence = 1;\n } else if (codePoint > 65535) {\n codePoint -= 65536;\n res.push(codePoint >>> 10 & 1023 | 55296);\n codePoint = 56320 | codePoint & 1023;\n }\n res.push(codePoint);\n offset += bytesPerSequence;\n }\n return decodeCodePointsArray(res);\n}\nconst MAX_ARGUMENTS_LENGTH = 4096;\nexport function decodeCodePointsArray(codePoints) {\n const len = codePoints.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints);\n }\n let res = '';\n let i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));\n }\n return res;\n}", "import {\n alloc,\n concat,\n slice\n} from './byte-utils.js';\nconst defaultChunkSize = 256;\nexport class Bl {\n constructor(chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize;\n this.cursor = 0;\n this.maxCursor = -1;\n this.chunks = [];\n this._initReuseChunk = null;\n }\n reset() {\n this.cursor = 0;\n this.maxCursor = -1;\n if (this.chunks.length) {\n this.chunks = [];\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk);\n this.maxCursor = this._initReuseChunk.length - 1;\n }\n }\n push(bytes) {\n let topChunk = this.chunks[this.chunks.length - 1];\n const newMax = this.cursor + bytes.length;\n if (newMax <= this.maxCursor + 1) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n topChunk.set(bytes, chunkPos);\n } else {\n if (topChunk) {\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;\n if (chunkPos < topChunk.length) {\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);\n this.maxCursor = this.cursor - 1;\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n topChunk = alloc(this.chunkSize);\n this.chunks.push(topChunk);\n this.maxCursor += topChunk.length;\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk;\n }\n topChunk.set(bytes, 0);\n } else {\n this.chunks.push(bytes);\n this.maxCursor += bytes.length;\n }\n }\n this.cursor += bytes.length;\n }\n toBytes(reset = false) {\n let byts;\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0];\n if (reset && this.cursor > chunk.length / 2) {\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);\n this._initReuseChunk = null;\n this.chunks = [];\n } else {\n byts = slice(chunk, 0, this.cursor);\n }\n } else {\n byts = concat(this.chunks, this.cursor);\n }\n if (reset) {\n this.reset();\n }\n return byts;\n }\n}", "const decodeErrPrefix = 'CBOR decode error:';\nconst encodeErrPrefix = 'CBOR encode error:';\nconst uintMinorPrefixBytes = [];\nuintMinorPrefixBytes[23] = 1;\nuintMinorPrefixBytes[24] = 2;\nuintMinorPrefixBytes[25] = 3;\nuintMinorPrefixBytes[26] = 5;\nuintMinorPrefixBytes[27] = 9;\nfunction assertEnoughData(data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${ decodeErrPrefix } not enough data for type`);\n }\n}\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n decodeErrPrefix,\n assertEnoughData\n} from './common.js';\nexport const uintBoundaries = [\n 24,\n 256,\n 65536,\n 4294967296,\n BigInt('18446744073709551616')\n];\nexport function readUint8(data, offset, options) {\n assertEnoughData(data, offset, 1);\n const value = data[offset];\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint16(data, offset, options) {\n assertEnoughData(data, offset, 2);\n const value = data[offset] << 8 | data[offset + 1];\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint32(data, offset, options) {\n assertEnoughData(data, offset, 4);\n const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n return value;\n}\nexport function readUint64(data, offset, options) {\n assertEnoughData(data, offset, 8);\n const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];\n const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${ decodeErrPrefix } integer encoded in more bytes than necessary (strict decode)`);\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value);\n }\n if (options.allowBigInt === true) {\n return value;\n }\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n}\nexport function decodeUint8(data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2);\n}\nexport function decodeUint16(data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3);\n}\nexport function decodeUint32(data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5);\n}\nexport function decodeUint64(data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9);\n}\nexport function encodeUint(buf, token) {\n return encodeUintValue(buf, 0, token.value);\n}\nexport function encodeUintValue(buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint);\n buf.push([major | nuint]);\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint);\n buf.push([\n major | 24,\n nuint\n ]);\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint);\n buf.push([\n major | 25,\n nuint >>> 8,\n nuint & 255\n ]);\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint);\n buf.push([\n major | 26,\n nuint >>> 24 & 255,\n nuint >>> 16 & 255,\n nuint >>> 8 & 255,\n nuint & 255\n ]);\n } else {\n const buint = BigInt(uint);\n if (buint < uintBoundaries[4]) {\n const set = [\n major | 27,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ];\n let lo = Number(buint & BigInt(4294967295));\n let hi = Number(buint >> BigInt(32) & BigInt(4294967295));\n set[8] = lo & 255;\n lo = lo >> 8;\n set[7] = lo & 255;\n lo = lo >> 8;\n set[6] = lo & 255;\n lo = lo >> 8;\n set[5] = lo & 255;\n set[4] = hi & 255;\n hi = hi >> 8;\n set[3] = hi & 255;\n hi = hi >> 8;\n set[2] = hi & 255;\n hi = hi >> 8;\n set[1] = hi & 255;\n buf.push(set);\n } else {\n throw new Error(`${ decodeErrPrefix } encountered BigInt larger than allowable range`);\n }\n }\n}\nencodeUint.encodedSize = function encodedSize(token) {\n return encodeUintValue.encodedSize(token.value);\n};\nencodeUintValue.encodedSize = function encodedSize(uint) {\n if (uint < uintBoundaries[0]) {\n return 1;\n }\n if (uint < uintBoundaries[1]) {\n return 2;\n }\n if (uint < uintBoundaries[2]) {\n return 3;\n }\n if (uint < uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeUint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nexport function decodeNegint8(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeNegint16(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeNegint32(data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5);\n}\nconst neg1b = BigInt(-1);\nconst pos1b = BigInt(1);\nexport function decodeNegint64(data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options);\n if (typeof int !== 'bigint') {\n const value = -1 - int;\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9);\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${ decodeErrPrefix } integers outside of the safe integer range are not supported`);\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9);\n}\nexport function encodeNegint(buf, token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned);\n}\nencodeNegint.encodedSize = function encodedSize(token) {\n const negint = token.value;\n const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1;\n if (unsigned < uint.uintBoundaries[0]) {\n return 1;\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2;\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3;\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5;\n }\n return 9;\n};\nencodeNegint.compareTokens = function compareTokens(tok1, tok2) {\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;\n};", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport {\n compare,\n fromString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length);\n const buf = slice(data, pos + prefix, pos + prefix + length);\n return new Token(Type.bytes, buf, prefix + length);\n}\nexport function decodeBytesCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeBytes8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeBytes16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeBytes32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeBytes64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer bytes lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nfunction tokenBytes(token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value;\n }\n return token.encodedBytes;\n}\nexport function encodeBytes(buf, token) {\n const bytes = tokenBytes(token);\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length);\n buf.push(bytes);\n}\nencodeBytes.encodedSize = function encodedSize(token) {\n const bytes = tokenBytes(token);\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length;\n};\nencodeBytes.compareTokens = function compareTokens(tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2));\n};\nexport function compareBytes(b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);\n}", "import {\n Token,\n Type\n} from './token.js';\nimport {\n assertEnoughData,\n decodeErrPrefix\n} from './common.js';\nimport * as uint from './0uint.js';\nimport { encodeBytes } from './2bytes.js';\nimport {\n toString,\n slice\n} from './byte-utils.js';\nfunction toToken(data, pos, prefix, length, options) {\n const totLength = prefix + length;\n assertEnoughData(data, pos, totLength);\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength);\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength);\n }\n return tok;\n}\nexport function decodeStringCompact(data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options);\n}\nexport function decodeString8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options);\n}\nexport function decodeString16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options);\n}\nexport function decodeString32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options);\n}\nexport function decodeString64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer string lengths not supported`);\n }\n return toToken(data, pos, 9, l, options);\n}\nexport const encodeString = encodeBytes;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix);\n}\nexport function decodeArrayCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeArray8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeArray16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeArray32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeArray64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer array lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeArrayIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeArray(buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value);\n}\nencodeArray.compareTokens = uint.encodeUint.compareTokens;\nencodeArray.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport { decodeErrPrefix } from './common.js';\nfunction toToken(_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix);\n}\nexport function decodeMapCompact(data, pos, minor, _options) {\n return toToken(data, pos, 1, minor);\n}\nexport function decodeMap8(data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options));\n}\nexport function decodeMap16(data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options));\n}\nexport function decodeMap32(data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options));\n}\nexport function decodeMap64(data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options);\n if (typeof l === 'bigint') {\n throw new Error(`${ decodeErrPrefix } 64-bit integer map lengths not supported`);\n }\n return toToken(data, pos, 9, l);\n}\nexport function decodeMapIndefinite(data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return toToken(data, pos, 1, Infinity);\n}\nexport function encodeMap(buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value);\n}\nencodeMap.compareTokens = uint.encodeUint.compareTokens;\nencodeMap.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nexport function decodeTagCompact(_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1);\n}\nexport function decodeTag8(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2);\n}\nexport function decodeTag16(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3);\n}\nexport function decodeTag32(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5);\n}\nexport function decodeTag64(data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9);\n}\nexport function encodeTag(buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value);\n}\nencodeTag.compareTokens = uint.encodeUint.compareTokens;\nencodeTag.encodedSize = function encodedSize(token) {\n return uint.encodeUintValue.encodedSize(token.value);\n};", "import {\n Token,\n Type\n} from './token.js';\nimport { decodeErrPrefix } from './common.js';\nimport { encodeUint } from './0uint.js';\nconst MINOR_FALSE = 20;\nconst MINOR_TRUE = 21;\nconst MINOR_NULL = 22;\nconst MINOR_UNDEFINED = 23;\nexport function decodeUndefined(_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${ decodeErrPrefix } undefined values are not supported`);\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1);\n }\n return new Token(Type.undefined, undefined, 1);\n}\nexport function decodeBreak(_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${ decodeErrPrefix } indefinite length items not allowed`);\n }\n return new Token(Type.break, undefined, 1);\n}\nfunction createToken(value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${ decodeErrPrefix } NaN values are not supported`);\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${ decodeErrPrefix } Infinity values are not supported`);\n }\n }\n return new Token(Type.float, value, bytes);\n}\nexport function decodeFloat16(data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options);\n}\nexport function decodeFloat32(data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options);\n}\nexport function decodeFloat64(data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options);\n}\nexport function encodeFloat(buf, token, options) {\n const float = token.value;\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE]);\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE]);\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL]);\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED]);\n } else {\n let decoded;\n let success = false;\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 249;\n buf.push(ui8a.slice(0, 3));\n success = true;\n } else {\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n ui8a[0] = 250;\n buf.push(ui8a.slice(0, 5));\n success = true;\n }\n }\n }\n if (!success) {\n encodeFloat64(float);\n decoded = readFloat64(ui8a, 1);\n ui8a[0] = 251;\n buf.push(ui8a.slice(0, 9));\n }\n }\n}\nencodeFloat.encodedSize = function encodedSize(token, options) {\n const float = token.value;\n if (float === false || float === true || float === null || float === undefined) {\n return 1;\n }\n if (!options || options.float64 !== true) {\n encodeFloat16(float);\n let decoded = readFloat16(ui8a, 1);\n if (float === decoded || Number.isNaN(float)) {\n return 3;\n }\n encodeFloat32(float);\n decoded = readFloat32(ui8a, 1);\n if (float === decoded) {\n return 5;\n }\n }\n return 9;\n};\nconst buffer = new ArrayBuffer(9);\nconst dataView = new DataView(buffer, 1);\nconst ui8a = new Uint8Array(buffer, 0);\nfunction encodeFloat16(inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 31744, false);\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 64512, false);\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 32256, false);\n } else {\n dataView.setFloat32(0, inp);\n const valu32 = dataView.getUint32(0);\n const exponent = (valu32 & 2139095040) >> 23;\n const mantissa = valu32 & 8388607;\n if (exponent === 255) {\n dataView.setUint16(0, 31744, false);\n } else if (exponent === 0) {\n dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);\n } else {\n const logicalExponent = exponent - 127;\n if (logicalExponent < -24) {\n dataView.setUint16(0, 0);\n } else if (logicalExponent < -14) {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false);\n } else {\n dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);\n }\n }\n }\n}\nfunction readFloat16(ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${ decodeErrPrefix } not enough data for float16`);\n }\n const half = (ui8a[pos] << 8) + ui8a[pos + 1];\n if (half === 31744) {\n return Infinity;\n }\n if (half === 64512) {\n return -Infinity;\n }\n if (half === 32256) {\n return NaN;\n }\n const exp = half >> 10 & 31;\n const mant = half & 1023;\n let val;\n if (exp === 0) {\n val = mant * 2 ** -24;\n } else if (exp !== 31) {\n val = (mant + 1024) * 2 ** (exp - 25);\n } else {\n val = mant === 0 ? Infinity : NaN;\n }\n return half & 32768 ? -val : val;\n}\nfunction encodeFloat32(inp) {\n dataView.setFloat32(0, inp, false);\n}\nfunction readFloat32(ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${ decodeErrPrefix } not enough data for float32`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false);\n}\nfunction encodeFloat64(inp) {\n dataView.setFloat64(0, inp, false);\n}\nfunction readFloat64(ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${ decodeErrPrefix } not enough data for float64`);\n }\n const offset = (ui8a.byteOffset || 0) + pos;\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false);\n}\nencodeFloat.compareTokens = encodeUint.compareTokens;", "import {\n Token,\n Type\n} from './token.js';\nimport * as uint from './0uint.js';\nimport * as negint from './1negint.js';\nimport * as bytes from './2bytes.js';\nimport * as string from './3string.js';\nimport * as array from './4array.js';\nimport * as map from './5map.js';\nimport * as tag from './6tag.js';\nimport * as float from './7float.js';\nimport { decodeErrPrefix } from './common.js';\nimport { fromArray } from './byte-utils.js';\nfunction invalidMinor(data, pos, minor) {\n throw new Error(`${ decodeErrPrefix } encountered invalid minor (${ minor }) for major ${ data[pos] >>> 5 }`);\n}\nfunction errorer(msg) {\n return () => {\n throw new Error(`${ decodeErrPrefix } ${ msg }`);\n };\n}\nexport const jump = [];\nfor (let i = 0; i <= 23; i++) {\n jump[i] = invalidMinor;\n}\njump[24] = uint.decodeUint8;\njump[25] = uint.decodeUint16;\njump[26] = uint.decodeUint32;\njump[27] = uint.decodeUint64;\njump[28] = invalidMinor;\njump[29] = invalidMinor;\njump[30] = invalidMinor;\njump[31] = invalidMinor;\nfor (let i = 32; i <= 55; i++) {\n jump[i] = invalidMinor;\n}\njump[56] = negint.decodeNegint8;\njump[57] = negint.decodeNegint16;\njump[58] = negint.decodeNegint32;\njump[59] = negint.decodeNegint64;\njump[60] = invalidMinor;\njump[61] = invalidMinor;\njump[62] = invalidMinor;\njump[63] = invalidMinor;\nfor (let i = 64; i <= 87; i++) {\n jump[i] = bytes.decodeBytesCompact;\n}\njump[88] = bytes.decodeBytes8;\njump[89] = bytes.decodeBytes16;\njump[90] = bytes.decodeBytes32;\njump[91] = bytes.decodeBytes64;\njump[92] = invalidMinor;\njump[93] = invalidMinor;\njump[94] = invalidMinor;\njump[95] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 96; i <= 119; i++) {\n jump[i] = string.decodeStringCompact;\n}\njump[120] = string.decodeString8;\njump[121] = string.decodeString16;\njump[122] = string.decodeString32;\njump[123] = string.decodeString64;\njump[124] = invalidMinor;\njump[125] = invalidMinor;\njump[126] = invalidMinor;\njump[127] = errorer('indefinite length bytes/strings are not supported');\nfor (let i = 128; i <= 151; i++) {\n jump[i] = array.decodeArrayCompact;\n}\njump[152] = array.decodeArray8;\njump[153] = array.decodeArray16;\njump[154] = array.decodeArray32;\njump[155] = array.decodeArray64;\njump[156] = invalidMinor;\njump[157] = invalidMinor;\njump[158] = invalidMinor;\njump[159] = array.decodeArrayIndefinite;\nfor (let i = 160; i <= 183; i++) {\n jump[i] = map.decodeMapCompact;\n}\njump[184] = map.decodeMap8;\njump[185] = map.decodeMap16;\njump[186] = map.decodeMap32;\njump[187] = map.decodeMap64;\njump[188] = invalidMinor;\njump[189] = invalidMinor;\njump[190] = invalidMinor;\njump[191] = map.decodeMapIndefinite;\nfor (let i = 192; i <= 215; i++) {\n jump[i] = tag.decodeTagCompact;\n}\njump[216] = tag.decodeTag8;\njump[217] = tag.decodeTag16;\njump[218] = tag.decodeTag32;\njump[219] = tag.decodeTag64;\njump[220] = invalidMinor;\njump[221] = invalidMinor;\njump[222] = invalidMinor;\njump[223] = invalidMinor;\nfor (let i = 224; i <= 243; i++) {\n jump[i] = errorer('simple values are not supported');\n}\njump[244] = invalidMinor;\njump[245] = invalidMinor;\njump[246] = invalidMinor;\njump[247] = float.decodeUndefined;\njump[248] = errorer('simple values are not supported');\njump[249] = float.decodeFloat16;\njump[250] = float.decodeFloat32;\njump[251] = float.decodeFloat64;\njump[252] = invalidMinor;\njump[253] = invalidMinor;\njump[254] = invalidMinor;\njump[255] = float.decodeBreak;\nexport const quick = [];\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1);\n}\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1);\n}\nquick[64] = new Token(Type.bytes, new Uint8Array(0), 1);\nquick[96] = new Token(Type.string, '', 1);\nquick[128] = new Token(Type.array, 0, 1);\nquick[160] = new Token(Type.map, 0, 1);\nquick[244] = new Token(Type.false, false, 1);\nquick[245] = new Token(Type.true, true, 1);\nquick[246] = new Token(Type.null, null, 1);\nexport function quickEncodeToken(token) {\n switch (token.type) {\n case Type.false:\n return fromArray([244]);\n case Type.true:\n return fromArray([245]);\n case Type.null:\n return fromArray([246]);\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([64]);\n }\n return;\n case Type.string:\n if (token.value === '') {\n return fromArray([96]);\n }\n return;\n case Type.array:\n if (token.value === 0) {\n return fromArray([128]);\n }\n return;\n case Type.map:\n if (token.value === 0) {\n return fromArray([160]);\n }\n return;\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)]);\n }\n return;\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)]);\n }\n }\n}", "import { is } from './is.js';\nimport {\n Token,\n Type\n} from './token.js';\nimport { Bl } from './bl.js';\nimport { encodeErrPrefix } from './common.js';\nimport { quickEncodeToken } from './jump.js';\nimport { asU8A } from './byte-utils.js';\nimport { encodeUint } from './0uint.js';\nimport { encodeNegint } from './1negint.js';\nimport { encodeBytes } from './2bytes.js';\nimport { encodeString } from './3string.js';\nimport { encodeArray } from './4array.js';\nimport { encodeMap } from './5map.js';\nimport { encodeTag } from './6tag.js';\nimport { encodeFloat } from './7float.js';\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n};\nexport function makeCborEncoders() {\n const encoders = [];\n encoders[Type.uint.major] = encodeUint;\n encoders[Type.negint.major] = encodeNegint;\n encoders[Type.bytes.major] = encodeBytes;\n encoders[Type.string.major] = encodeString;\n encoders[Type.array.major] = encodeArray;\n encoders[Type.map.major] = encodeMap;\n encoders[Type.tag.major] = encodeTag;\n encoders[Type.float.major] = encodeFloat;\n return encoders;\n}\nconst cborEncoders = makeCborEncoders();\nconst buf = new Bl();\nclass Ref {\n constructor(obj, parent) {\n this.obj = obj;\n this.parent = parent;\n }\n includes(obj) {\n let p = this;\n do {\n if (p.obj === obj) {\n return true;\n }\n } while (p = p.parent);\n return false;\n }\n static createCheck(stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${ encodeErrPrefix } object contains circular references`);\n }\n return new Ref(obj, stack);\n }\n}\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n};\nconst typeEncoders = {\n number(obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj);\n } else if (obj >= 0) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n bigint(obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj);\n } else {\n return new Token(Type.negint, obj);\n }\n },\n Uint8Array(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj);\n },\n string(obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj);\n },\n boolean(obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false;\n },\n null(_obj, _typ, _options, _refStack) {\n return simpleTokens.null;\n },\n undefined(_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined;\n },\n ArrayBuffer(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj));\n },\n DataView(obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));\n },\n Array(obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyArray,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyArray;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack);\n }\n if (options.addBreakTokens) {\n return [\n new Token(Type.array, obj.length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.array, obj.length),\n entries\n ];\n },\n Object(obj, typ, options, refStack) {\n const isMap = typ !== 'Object';\n const keys = isMap ? obj.keys() : Object.keys(obj);\n const length = isMap ? obj.size : keys.length;\n if (!length) {\n if (options.addBreakTokens === true) {\n return [\n simpleTokens.emptyMap,\n new Token(Type.break)\n ];\n }\n return simpleTokens.emptyMap;\n }\n refStack = Ref.createCheck(refStack, obj);\n const entries = [];\n let i = 0;\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ];\n }\n sortMapEntries(entries, options);\n if (options.addBreakTokens) {\n return [\n new Token(Type.map, length),\n entries,\n new Token(Type.break)\n ];\n }\n return [\n new Token(Type.map, length),\n entries\n ];\n }\n};\ntypeEncoders.Map = typeEncoders.Object;\ntypeEncoders.Buffer = typeEncoders.Uint8Array;\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${ typ }Array`] = typeEncoders.DataView;\n}\nfunction objectToTokens(obj, options = {}, refStack) {\n const typ = is(obj);\n const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack);\n if (tokens != null) {\n return tokens;\n }\n }\n const typeEncoder = typeEncoders[typ];\n if (!typeEncoder) {\n throw new Error(`${ encodeErrPrefix } unsupported type: ${ typ }`);\n }\n return typeEncoder(obj, typ, options, refStack);\n}\nfunction sortMapEntries(entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter);\n }\n}\nfunction mapSorter(e1, e2) {\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type);\n }\n const major = keyToken1.type.major;\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);\n if (tcmp === 0) {\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone');\n }\n return tcmp;\n}\nfunction tokensToEncoded(buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options);\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options);\n }\n}\nfunction encodeCustom(data, encoders, options) {\n const tokens = objectToTokens(data, options);\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens);\n if (quickBytes) {\n return quickBytes;\n }\n const encoder = encoders[tokens.type.major];\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options);\n const buf = new Bl(size);\n encoder(buf, tokens, options);\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${ tokens } was wrong`);\n }\n return asU8A(buf.chunks[0]);\n }\n }\n buf.reset();\n tokensToEncoded(buf, tokens, encoders, options);\n return buf.toBytes(true);\n}\nfunction encode(data, options) {\n options = Object.assign({}, defaultEncodeOptions, options);\n return encodeCustom(data, cborEncoders, options);\n}\nexport {\n objectToTokens,\n encode,\n encodeCustom,\n Ref\n};", "import { decodeErrPrefix } from './common.js';\nimport { Type } from './token.js';\nimport {\n jump,\n quick\n} from './jump.js';\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n};\nclass Tokeniser {\n constructor(data, options = {}) {\n this.pos = 0;\n this.data = data;\n this.options = options;\n }\n done() {\n return this.pos >= this.data.length;\n }\n next() {\n const byt = this.data[this.pos];\n let token = quick[byt];\n if (token === undefined) {\n const decoder = jump[byt];\n if (!decoder) {\n throw new Error(`${ decodeErrPrefix } no decoder for major type ${ byt >>> 5 } (byte 0x${ byt.toString(16).padStart(2, '0') })`);\n }\n const minor = byt & 31;\n token = decoder(this.data, this.pos, minor, this.options);\n }\n this.pos += token.encodedLength;\n return token;\n }\n}\nconst DONE = Symbol.for('DONE');\nconst BREAK = Symbol.for('BREAK');\nfunction tokenToArray(token, tokeniser, options) {\n const arr = [];\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options);\n if (value === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed array`);\n }\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found array but not enough entries (got ${ i }, expected ${ token.value })`);\n }\n arr[i] = value;\n }\n return arr;\n}\nfunction tokenToMap(token, tokeniser, options) {\n const useMaps = options.useMaps === true;\n const obj = useMaps ? undefined : {};\n const m = useMaps ? new Map() : undefined;\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options);\n if (key === BREAK) {\n if (token.value === Infinity) {\n break;\n }\n throw new Error(`${ decodeErrPrefix } got unexpected break to lengthed map`);\n }\n if (key === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no key], expected ${ token.value })`);\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${ decodeErrPrefix } non-string keys not supported (got ${ typeof key })`);\n }\n if (options.rejectDuplicateMapKeys === true) {\n if (useMaps && m.has(key) || !useMaps && key in obj) {\n throw new Error(`${ decodeErrPrefix } found repeat map key \"${ key }\"`);\n }\n }\n const value = tokensToObject(tokeniser, options);\n if (value === DONE) {\n throw new Error(`${ decodeErrPrefix } found map but not enough entries (got ${ i } [no value], expected ${ token.value })`);\n }\n if (useMaps) {\n m.set(key, value);\n } else {\n obj[key] = value;\n }\n }\n return useMaps ? m : obj;\n}\nfunction tokensToObject(tokeniser, options) {\n if (tokeniser.done()) {\n return DONE;\n }\n const token = tokeniser.next();\n if (token.type === Type.break) {\n return BREAK;\n }\n if (token.type.terminal) {\n return token.value;\n }\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options);\n }\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options);\n }\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options);\n return options.tags[token.value](tagged);\n }\n throw new Error(`${ decodeErrPrefix } tag not supported (${ token.value })`);\n }\n throw new Error('unsupported');\n}\nfunction decode(data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${ decodeErrPrefix } data to decode must be a Uint8Array`);\n }\n options = Object.assign({}, defaultDecodeOptions, options);\n const tokeniser = options.tokenizer || new Tokeniser(data, options);\n const decoded = tokensToObject(tokeniser, options);\n if (decoded === DONE) {\n throw new Error(`${ decodeErrPrefix } did not find any content to decode`);\n }\n if (decoded === BREAK) {\n throw new Error(`${ decodeErrPrefix } got unexpected break`);\n }\n if (!tokeniser.done()) {\n throw new Error(`${ decodeErrPrefix } too many terminals, data makes no sense`);\n }\n return decoded;\n}\nexport {\n Tokeniser,\n tokensToObject,\n decode\n};", "import * as ipns from 'ipns'\nimport { importKey } from '@libp2p/crypto/keys'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { TimeoutController } from 'timeout-abort-controller'\n\nconst log = logger('ipfs:ipns:republisher')\n\n/**\n * @typedef {import('@libp2p/interface-keys').PrivateKey} PrivateKey\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nconst minute = 60 * 1000\nconst hour = 60 * minute\n\nconst defaultBroadcastInterval = 4 * hour\nconst defaultRecordLifetime = 24 * hour\n\nexport class IpnsRepublisher {\n /**\n * @param {import('./publisher').IpnsPublisher} publisher\n * @param {import('interface-datastore').Datastore} datastore\n * @param {PeerId} peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} keychain\n * @param {object} options\n * @param {string} options.pass\n * @param {number} [options.initialBroadcastInterval]\n * @param {number} [options.broadcastInterval]\n */\n constructor (publisher, datastore, peerId, keychain, options = { pass: '' }) {\n this._publisher = publisher\n this._datastore = datastore\n this._peerId = peerId\n this._keychain = keychain\n this._options = options\n this._republishHandle = null\n }\n\n async start () { // eslint-disable-line require-await\n if (this._republishHandle) {\n throw errcode(new Error('republisher is already running'), 'ERR_REPUBLISH_ALREADY_RUNNING')\n }\n\n // TODO: this handler should be isolated in another module\n const republishHandle = {\n /** @type {null|(() => Promise)} */\n _task: null,\n /** @type {null|Promise} */\n _inflightTask: null,\n /** @type {null|NodeJS.Timeout} */\n _timeoutId: null,\n /**\n * @param {function(): number} period\n */\n runPeriodically: (period) => {\n republishHandle._timeoutId = setTimeout(async () => {\n republishHandle._timeoutId = null\n\n try {\n // @ts-expect-error - _task could be null\n republishHandle._inflightTask = republishHandle._task()\n await republishHandle._inflightTask\n\n // Schedule next\n if (republishHandle._task) {\n republishHandle.runPeriodically(period)\n }\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }, period())\n },\n cancel: async () => {\n // do not run again\n if (republishHandle._timeoutId != null) {\n clearTimeout(republishHandle._timeoutId)\n }\n republishHandle._task = null\n\n // wait for the currently in flight task to complete\n await republishHandle._inflightTask\n }\n }\n\n const { pass } = this._options\n let firstRun = true\n\n republishHandle._task = async () => {\n const timeoutController = new TimeoutController(30000)\n\n try {\n await this._republishEntries(this._peerId, pass, {\n signal: timeoutController.signal\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n republishHandle.runPeriodically(() => {\n if (firstRun) {\n firstRun = false\n return this._options.initialBroadcastInterval || minute\n }\n\n return this._options.broadcastInterval || defaultBroadcastInterval\n })\n\n this._republishHandle = republishHandle\n }\n\n async stop () {\n const republishHandle = this._republishHandle\n\n if (!republishHandle) {\n throw errcode(new Error('republisher is not running'), 'ERR_REPUBLISH_NOT_RUNNING')\n }\n\n this._republishHandle = null\n\n await republishHandle.cancel()\n }\n\n /**\n * @param {PeerId} peerId\n * @param {string} pass\n * @param {AbortOptions} options\n */\n async _republishEntries (peerId, pass, options) {\n // TODO: Should use list of published entries.\n // We can't currently *do* that because go uses this method for now.\n try {\n await this._republishEntry(peerId, options)\n } catch (/** @type {any} */ err) {\n const errMsg = 'cannot republish entry for the node\\'s private key'\n\n log.error(errMsg)\n return\n }\n\n // keychain needs pass to get the cryptographic keys\n if (pass) {\n try {\n const keys = await this._keychain.listKeys()\n\n for (const key of keys) {\n if (key.name === 'self') {\n continue\n }\n\n const pem = await this._keychain.exportKey(key.name, pass)\n const privKey = await importKey(pem, pass)\n const peerIdKey = await peerIdFromKeys(privKey.public.bytes, privKey.bytes)\n\n await this._republishEntry(peerIdKey, options)\n }\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }\n }\n\n /**\n * @param {PeerId} peerId\n * @param {AbortOptions} options\n */\n async _republishEntry (peerId, options) {\n try {\n const value = await this._getPreviousValue(peerId)\n await this._publisher.publishWithEOL(peerId, value, defaultRecordLifetime, options)\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NO_ENTRY_FOUND') {\n return\n }\n\n throw err\n }\n }\n\n /**\n * @param {PeerId} peerId\n */\n async _getPreviousValue (peerId) {\n if (!(isPeerId(peerId))) {\n throw errcode(new Error('invalid peer ID'), 'ERR_INVALID_PEER_ID')\n }\n\n try {\n const dsVal = await this._datastore.get(ipns.getLocalKey(peerId.toBytes()))\n\n if (!(dsVal instanceof Uint8Array)) {\n throw errcode(new Error(\"found ipns record that we couldn't process\"), 'ERR_INVALID_IPNS_RECORD')\n }\n\n // unmarshal data\n try {\n const record = ipns.unmarshal(dsVal)\n\n return record.value\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(new Error('found ipns record that we couldn\\'t convert to a value'), 'ERR_INVALID_IPNS_RECORD')\n }\n } catch (/** @type {any} */ err) {\n // error handling\n // no need to republish\n if (err && err.notFound) {\n throw errcode(new Error(`no previous entry for record with id: ${peerId.toString()}`), 'ERR_NO_ENTRY_FOUND')\n }\n\n throw err\n }\n }\n}\n", "import * as ipns from 'ipns'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport * as Errors from 'datastore-core/errors'\nimport { ipnsValidator } from 'ipns/validator'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nconst log = logger('ipfs:ipns:resolver')\n\nconst ERR_NOT_FOUND = Errors.notFoundError().code\n\nconst defaultMaximumRecursiveDepth = 32\n\nexport class IpnsResolver {\n /**\n * @param {import('ipfs-core-types/src/utils').BufferStore} routing\n */\n constructor (routing) {\n this._routing = routing\n }\n\n /**\n * @param {string} name\n * @param {object} [options]\n * @param {boolean} [options.recursive]\n * @param {AbortSignal} [options.signal]\n */\n async resolve (name, options = {}) {\n if (typeof name !== 'string') {\n throw errcode(new Error('invalid name'), 'ERR_INVALID_NAME')\n }\n\n const recursive = options.recursive && options.recursive.toString() === 'true'\n\n const nameSegments = name.split('/')\n\n if (nameSegments.length !== 3 || nameSegments[0] !== '') {\n throw errcode(new Error('invalid name'), 'ERR_INVALID_NAME')\n }\n\n const key = nameSegments[2]\n\n // Define a maximum depth if recursive option enabled\n let depth = Infinity\n\n if (recursive) {\n depth = defaultMaximumRecursiveDepth\n }\n\n const res = await this.resolver(key, depth, options)\n\n log(`${name} was locally resolved correctly`)\n return res\n }\n\n /**\n * Recursive resolver according to the specified depth\n *\n * @param {string} name\n * @param {number} depth\n * @param {AbortOptions} options\n * @returns {Promise}\n */\n async resolver (name, depth, options) {\n // Exceeded recursive maximum depth\n if (depth === 0) {\n const errMsg = `could not resolve name (recursion limit of ${defaultMaximumRecursiveDepth} exceeded)`\n log.error(errMsg)\n\n throw errcode(new Error(errMsg), 'ERR_RESOLVE_RECURSION_LIMIT')\n }\n\n const res = await this._resolveName(name, options)\n const nameSegments = res.split('/')\n\n // If obtained a ipfs cid or recursive option is disabled\n if (nameSegments[1] === 'ipfs' || !depth) {\n return res\n }\n\n // continue recursively until depth equals 0\n return this.resolver(nameSegments[2], depth - 1, options)\n }\n\n /**\n * Resolve ipns entries from the provided routing\n *\n * @param {string} name\n * @param {AbortOptions} options\n */\n async _resolveName (name, options) {\n const peerId = peerIdFromString(name)\n const routingKey = ipns.peerIdToRoutingKey(peerId)\n let record\n\n try {\n record = await this._routing.get(routingKey, options)\n } catch (/** @type {any} */ err) {\n log.error('could not get record from routing', err)\n\n if (err.code === ERR_NOT_FOUND) {\n throw errcode(new Error(`record requested for ${name} was not found in the network`), 'ERR_NO_RECORD_FOUND')\n }\n\n throw errcode(new Error(`unexpected error getting the ipns record ${peerId.toString()}`), 'ERR_UNEXPECTED_ERROR_GETTING_RECORD')\n }\n\n // We should have the public key by now (inline, or in the entry)\n return this._validateRecord(peerId, record)\n }\n\n /**\n * Validate a resolved record\n *\n * @param {PeerId} peerId\n * @param {Uint8Array} record\n */\n async _validateRecord (peerId, record) {\n // IPNS entry validation\n await ipnsValidator(uint8ArrayConcat([\n uint8ArrayFromString('/ipns/'),\n peerId.toBytes()\n ]), record)\n\n const ipnsEntry = ipns.unmarshal(record)\n\n return uint8ArrayToString(ipnsEntry.value)\n }\n}\n", "import errCode from 'err-code'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { parseRFC3339, extractPublicKey, ipnsEntryDataForV2Sig, unmarshal, peerIdFromRoutingKey, parseCborData } from './utils.js'\nimport * as ERRORS from './errors.js'\nimport type { IPNSEntry } from './index.js'\nimport type { PublicKey } from '@libp2p/interface-keys'\nimport type { ValidateFn } from '@libp2p/interface-dht'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipns:validator')\n\n/**\n * Validates the given ipns entry against the given public key\n */\nexport const validate = async (publicKey: PublicKey, entry: IPNSEntry): Promise => {\n const { value, validityType, validity } = entry\n\n let dataForSignature: Uint8Array\n let signature: Uint8Array\n\n // Check v2 signature if it's available, otherwise use the v1 signature\n if ((entry.signatureV2 != null) && (entry.data != null)) {\n signature = entry.signatureV2\n dataForSignature = ipnsEntryDataForV2Sig(entry.data)\n\n validateCborDataMatchesPbData(entry)\n } else {\n throw errCode(new Error('missing data or signatureV2'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n // Validate Signature\n let isValid\n try {\n isValid = await publicKey.verify(dataForSignature, signature)\n } catch (err) {\n isValid = false\n }\n if (!isValid) {\n log.error('record signature verification failed')\n throw errCode(new Error('record signature verification failed'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n // Validate according to the validity type\n if (validity != null && validityType === IpnsEntry.ValidityType.EOL) {\n let validityDate\n\n try {\n validityDate = parseRFC3339(uint8ArrayToString(validity))\n } catch (e) {\n log.error('unrecognized validity format (not an rfc3339 format)')\n throw errCode(new Error('unrecognized validity format (not an rfc3339 format)'), ERRORS.ERR_UNRECOGNIZED_FORMAT)\n }\n\n if (validityDate.getTime() < Date.now()) {\n log.error('record has expired')\n throw errCode(new Error('record has expired'), ERRORS.ERR_IPNS_EXPIRED_RECORD)\n }\n } else if (validityType != null) {\n log.error('unrecognized validity type')\n throw errCode(new Error('unrecognized validity type'), ERRORS.ERR_UNRECOGNIZED_VALIDITY)\n }\n\n log('ipns entry for %b is valid', value)\n}\n\nconst validateCborDataMatchesPbData = (entry: IPNSEntry): void => {\n if (entry.data == null) {\n throw errCode(new Error('Record data is missing'), ERRORS.ERR_INVALID_RECORD_DATA)\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value)) {\n throw errCode(new Error('Field \"value\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity)) {\n throw errCode(new Error('Field \"validity\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw errCode(new Error('Field \"validityType\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (data.Sequence !== entry.sequence) {\n throw errCode(new Error('Field \"sequence\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n\n if (data.TTL !== entry.ttl) {\n throw errCode(new Error('Field \"ttl\" did not match between protobuf and CBOR'), ERRORS.ERR_SIGNATURE_VERIFICATION)\n }\n}\n\nexport const ipnsValidator: ValidateFn = async (key, marshalledData) => {\n const peerId = peerIdFromRoutingKey(key)\n const receivedEntry = unmarshal(marshalledData)\n\n // extract public key\n const pubKey = await extractPublicKey(peerId, receivedEntry)\n\n // Record validation\n await validate(pubKey, receivedEntry)\n}\n", "import hashlru from 'hashlru'\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n * @todo move this to ipfs-utils or it's own package\n *\n * @template T\n * @class TLRU\n */\nexport class TLRU {\n /**\n * Creates an instance of TLRU.\n *\n * @param {number} maxSize\n */\n constructor (maxSize) {\n this.lru = hashlru(maxSize)\n }\n\n /**\n * Get the value from the a key\n *\n * @param {string} key\n * @returns {T|undefined}\n * @memberof TLoRU\n */\n get (key) {\n const value = this.lru.get(key)\n if (value) {\n if ((value.expire) && (value.expire < Date.now())) {\n this.lru.remove(key)\n return undefined\n }\n return value.value\n }\n return undefined\n }\n\n /**\n * Set a key value pair\n *\n * @param {string} key\n * @param {T} value\n * @param {number} ttl - in miliseconds\n * @returns {void}\n */\n set (key, value, ttl) {\n this.lru.set(key, { value, expire: Date.now() + ttl })\n }\n\n /**\n * Find if the cache has the key\n *\n * @param {string} key\n * @returns {boolean}\n */\n has (key) {\n const value = this.get(key)\n if (value) {\n return true\n }\n return false\n }\n\n /**\n * Remove key\n *\n * @param {string} key\n */\n remove (key) {\n this.lru.remove(key)\n }\n\n /**\n * Clears the cache\n *\n * @memberof TLRU\n */\n clear () {\n this.lru.clear()\n }\n}\n", "\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nexport default async function all (source: AsyncIterable|Iterable): Promise {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n", "\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nexport const sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @param {string} s\n * @param {string} r\n */\nexport const replaceStartWith = (s, r) => {\n const matcher = new RegExp('^' + r)\n return s.replace(matcher, '')\n}\n", "/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nexport default async function drain (source: AsyncIterable|Iterable): Promise {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n}\n", "\n/**\n * Filters the passed (async) iterable by using the filter function\n */\nexport default async function * filter (source: AsyncIterable|Iterable, fn: (val: T) => boolean|Promise): AsyncGenerator {\n for await (const entry of source) {\n if (await fn(entry)) {\n yield entry\n }\n }\n}\n", "\n/**\n * Stop iteration after n items have been received\n */\nexport default async function * take (source: AsyncIterable|Iterable, limit: number): AsyncGenerator {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n}\n", "import { sortAll } from './utils.js'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\n\n/**\n * @typedef {import('interface-store').Options} Options\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Batch} Batch\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Datastore}\n */\nexport class BaseDatastore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\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\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {Key[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\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 /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (e) =>\n e.key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (key) =>\n key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key) => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nexport function logger (name: string): Logger {\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace: debug(`${name}:trace`)\n })\n}\n\nexport function disable () {\n debug.disable()\n}\n\nexport function enable (namespaces: string) {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string) {\n return debug.enabled(namespaces)\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nimport type { Next } from './index.js'\n\nclass FixedFIFO {\n public buffer: Array | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO | null\n\n constructor (hwm: number) {\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\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\n push (data: Next) {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift () {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty () {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO\n private tail: FixedFIFO\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next) {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\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\n shift () {\n let val = this.tail.shift()\n\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\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty () {\n return this.head.isEmpty()\n }\n}\n", "/**\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 */\n\nimport { FIFO } from './fifo.js'\n\nexport interface Next {\n done?: boolean\n error?: Error\n value?: T\n}\n\ninterface BasePushable {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end: (err?: Error) => this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push: (value: T) => this\n next: () => Promise>\n return: () => { done: boolean }\n throw: (err: Error) => { done: boolean }\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable extends AsyncIterable, BasePushable {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV extends AsyncIterable, BasePushable {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?: (err?: Error) => void\n}\n\ntype NextResult = { done: false, value: T} | { done: true }\n\ninterface getNext { (buffer: FIFO): NextResult }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable (options?: BytePushableOptions): Pushable\nexport function pushable (options: ObjectPushableOptions): Pushable\nexport function pushable (options: Options = {}): Pushable {\n const getNext = (buffer: FIFO): NextResult => {\n const next: Next | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error\n value: next.value\n }\n }\n\n return _pushable>(getNext, options)\n}\n\nexport function pushableV (options?: BytePushableOptions): PushableV\nexport function pushableV (options: ObjectPushableOptions): PushableV\nexport function pushableV (options: Options = {}): PushableV {\n const getNext = (buffer: FIFO): NextResult => {\n let next: Next | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable>(getNext, options)\n}\n\nfunction _pushable (getNext: getNext, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO()\n let pushable: any\n let onNext: ((next: Next) => ReturnType) | null\n let ended: boolean\n\n const waitNext = async (): Promise> => {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise((resolve, reject) => {\n onNext = (next: Next) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n }\n\n const bufferNext = (next: Next) => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error) => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType) => {\n if (ended) {\n return pushable\n }\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\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error) => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = () => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error) => {\n end(err)\n\n return { done: true }\n }\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 }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n }\n }\n\n return pushable\n}\n", "import { BaseDatastore } from './base.js'\nimport * as Errors from './errors.js'\nimport { logger } from '@libp2p/logger'\nimport { pushable } from 'it-pushable'\nimport drain from 'it-drain'\n\nconst log = logger('datastore:core:tiered')\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} Options\n * @typedef {import('interface-datastore').Batch} Batch\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n */\n\n/**\n * @template TEntry\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * A datastore that can combine multiple stores. Puts and deletes\n * will write through to all datastores. Has and get will\n * try each store sequentially. Query will always try the\n * last one first.\n *\n */\nexport class TieredDatastore extends BaseDatastore {\n /**\n * @param {Datastore[]} stores\n */\n constructor (stores) {\n super()\n\n this.stores = stores.slice()\n }\n\n async open () {\n try {\n await Promise.all(this.stores.map((store) => store.open()))\n } catch (/** @type {any} */ err) {\n throw Errors.dbOpenFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} value\n * @param {Options} [options]\n */\n async put (key, value, options) {\n try {\n await Promise.all(this.stores.map(store => store.put(key, value, options)))\n } catch (/** @type {any} */ err) {\n throw Errors.dbWriteFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n async get (key, options) {\n for (const store of this.stores) {\n try {\n const res = await store.get(key, options)\n if (res) return res\n } catch (err) {\n log.error(err)\n }\n }\n throw Errors.notFoundError()\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n async has (key, options) {\n for (const s of this.stores) {\n if (await s.has(key, options)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n async delete (key, options) {\n try {\n await Promise.all(this.stores.map(store => store.delete(key, options)))\n } catch (/** @type {any} */ err) {\n throw Errors.dbDeleteFailedError(err)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n let error\n const pushables = this.stores.map(store => {\n const source = pushable({\n objectMode: true\n })\n\n drain(store.putMany(source, options))\n .catch(err => {\n // store threw while putting, make sure we bubble the error up\n error = err\n })\n\n return source\n })\n\n try {\n for await (const pair of source) {\n if (error) {\n throw error\n }\n\n pushables.forEach(p => p.push(pair))\n\n yield pair\n }\n } finally {\n pushables.forEach(p => p.end())\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n let error\n const pushables = this.stores.map(store => {\n const source = pushable({\n objectMode: true\n })\n\n drain(store.deleteMany(source, options))\n .catch(err => {\n // store threw while deleting, make sure we bubble the error up\n error = err\n })\n\n return source\n })\n\n try {\n for await (const key of source) {\n if (error) {\n throw error\n }\n\n pushables.forEach(p => p.push(key))\n\n yield key\n }\n } finally {\n pushables.forEach(p => p.end())\n }\n }\n\n async close () {\n await Promise.all(this.stores.map(store => store.close()))\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n const batches = this.stores.map(store => store.batch())\n\n return {\n put: (key, value) => {\n batches.forEach(b => b.put(key, value))\n },\n delete: (key) => {\n batches.forEach(b => b.delete(key))\n },\n commit: async (options) => {\n for (const batch of batches) {\n await batch.commit(options)\n }\n }\n }\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n return this.stores[this.stores.length - 1].query(q, options)\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n return this.stores[this.stores.length - 1].queryKeys(q, options)\n }\n}\n", "import { TieredDatastore } from 'datastore-core/tiered'\nimport get from 'dlv'\nimport { IpnsPubsubDatastore } from './pubsub-datastore.js'\nimport { OfflineDatastore } from './offline-datastore.js'\nimport { DHTDatastore } from './dht-datastore.js'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\n/**\n * @param {object} arg\n * @param {import('libp2p').Libp2p} arg.libp2p\n * @param {import('ipfs-repo').IPFSRepo} arg.repo\n * @param {import('@libp2p/interface-peer-id').PeerId} arg.peerId\n * @param {object} arg.options\n */\nexport function createRouting ({ libp2p, repo, peerId, options }) {\n // Setup online routing for IPNS with a tiered routing composed by a DHT and a Pubsub router (if properly enabled)\n /** @type {any[]} */\n const ipnsStores = []\n\n // Add IPNS pubsub if enabled\n let pubsubDs\n if (get(options, 'EXPERIMENTAL.ipnsPubsub', false)) {\n pubsubDs = new IpnsPubsubDatastore(libp2p.pubsub, repo.datastore, peerId)\n ipnsStores.push(pubsubDs)\n }\n\n // Add DHT datastore if enabled\n if (get(options, 'offline', false) !== true && ['dht', 'dhtclient', 'dhtserver'].includes(get(options, 'config.Routing.Type', 'none'))) {\n ipnsStores.push(new DHTDatastore(libp2p.dht))\n }\n\n // Add an offline datastore if we are offline or no other datastores are configured\n if (get(options, 'offline', false) || ipnsStores.length === 0) {\n const offlineDatastore = new OfflineDatastore(repo.datastore)\n ipnsStores.push(offlineDatastore)\n }\n\n // Create ipns routing with a set of datastores\n return new TieredDatastore(ipnsStores)\n}\n", "import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { parseRFC3339 } from './utils.js'\nimport type { SelectFn } from '@libp2p/interface-dht'\n\nexport const ipnsSelector: SelectFn = (key, data) => {\n const entries = data.map((buf, index) => ({\n entry: IpnsEntry.decode(buf),\n index\n }))\n\n entries.sort((a, b) => {\n // having a newer signature version is better than an older signature version\n if (a.entry.signatureV2 != null && b.entry.signatureV2 == null) {\n return -1\n } else if (a.entry.signatureV2 == null && b.entry.signatureV2 != null) {\n return 1\n }\n\n const aSeq = a.entry.sequence ?? 0n\n const bSeq = b.entry.sequence ?? 0n\n\n // choose later sequence number\n if (aSeq > bSeq) {\n return -1\n } else if (aSeq < bSeq) {\n return 1\n }\n\n const aValidty = a.entry.validity ?? new Uint8Array(0)\n const bValidty = b.entry.validity ?? new Uint8Array(0)\n\n // choose longer lived record if sequence numbers the same\n const entryAValidityDate = parseRFC3339(uint8ArrayToString(aValidty))\n const entryBValidityDate = parseRFC3339(uint8ArrayToString(bValidty))\n\n if (entryAValidityDate.getTime() > entryBValidityDate.getTime()) {\n return -1\n }\n\n if (entryAValidityDate.getTime() < entryBValidityDate.getTime()) {\n return 1\n }\n\n return 0\n })\n\n return entries[0].index\n}\n", "import { Key } from 'interface-datastore/key'\n// @ts-expect-error readme is unused\n// eslint-disable-next-line no-unused-vars\nimport readme from './shard-readme.js'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('./types').Shard} Shard\n */\n\nexport const PREFIX = '/repo/flatfs/shard/'\nexport const SHARDING_FN = 'SHARDING'\nexport const README_FN = '_README'\n\n/**\n * @implements {Shard}\n */\nexport class ShardBase {\n /**\n * @param {any} param\n */\n constructor (param) {\n this.param = param\n this.name = 'base'\n this._padding = ''\n }\n\n /**\n * @param {string} s\n */\n fun (s) {\n return 'implement me'\n }\n\n toString () {\n return `${PREFIX}v1/${this.name}/${this.param}`\n }\n}\n/**\n * @implements {Shard}\n */\nexport class Prefix extends ShardBase {\n /**\n * @param {number} prefixLen\n */\n constructor (prefixLen) {\n super(prefixLen)\n this._padding = ''.padStart(prefixLen, '_')\n this.name = 'prefix'\n }\n\n /**\n * @param {string} noslash\n */\n fun (noslash) {\n return (noslash + this._padding).slice(0, this.param)\n }\n}\n\nexport class Suffix extends ShardBase {\n /**\n * @param {number} suffixLen\n */\n constructor (suffixLen) {\n super(suffixLen)\n this._padding = ''.padStart(suffixLen, '_')\n this.name = 'suffix'\n }\n\n /**\n * @param {string} noslash\n */\n fun (noslash) {\n const s = this._padding + noslash\n return s.slice(s.length - this.param)\n }\n}\n\nexport class NextToLast extends ShardBase {\n /**\n * @param {number} suffixLen\n */\n constructor (suffixLen) {\n super(suffixLen)\n this._padding = ''.padStart(suffixLen + 1, '_')\n this.name = 'next-to-last'\n }\n\n /**\n * @param {string} noslash\n */\n fun (noslash) {\n const s = this._padding + noslash\n const offset = s.length - this.param - 1\n return s.slice(offset, offset + this.param)\n }\n}\n\n/**\n * Convert a given string to the matching sharding function.\n *\n * @param {string} str\n * @returns {Shard}\n */\nexport function parseShardFun (str) {\n str = str.trim()\n\n if (str.length === 0) {\n throw new Error('empty shard string')\n }\n\n if (!str.startsWith(PREFIX)) {\n throw new Error(`invalid or no path prefix: ${str}`)\n }\n\n const parts = str.slice(PREFIX.length).split('/')\n const version = parts[0]\n\n if (version !== 'v1') {\n throw new Error(`expect 'v1' version, got '${version}'`)\n }\n\n const name = parts[1]\n\n if (!parts[2]) {\n throw new Error('missing param')\n }\n\n const param = parseInt(parts[2], 10)\n\n switch (name) {\n case 'prefix':\n return new Prefix(param)\n case 'suffix':\n return new Suffix(param)\n case 'next-to-last':\n return new NextToLast(param)\n default:\n throw new Error(`unkown sharding function: ${name}`)\n }\n}\n\n/**\n * @param {string | Uint8Array} path\n * @param {Datastore} store\n */\nexport const readShardFun = async (path, store) => {\n const key = new Key(path).child(new Key(SHARDING_FN))\n // @ts-ignore\n const get = typeof store.getRaw === 'function' ? store.getRaw.bind(store) : store.get.bind(store)\n const res = await get(key)\n return parseShardFun(new TextDecoder().decode(res || '').trim())\n}\n\nexport { default as readme } from './shard-readme.js'\n", "import { BaseDatastore } from './base.js'\nimport { Key } from 'interface-datastore/key'\nimport * as Errors from './errors.js'\n\n/**\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-store').Options} Options\n */\n\n/**\n * @class MemoryDatastore\n * @implements {Datastore}\n */\nexport class MemoryDatastore extends BaseDatastore {\n constructor () {\n super()\n\n /** @type {Record} */\n this.data = {}\n }\n\n open () {\n return Promise.resolve()\n }\n\n close () {\n return Promise.resolve()\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n */\n async put (key, val) { // eslint-disable-line require-await\n this.data[key.toString()] = val\n }\n\n /**\n * @param {Key} key\n */\n async get (key) {\n const exists = await this.has(key)\n if (!exists) throw Errors.notFoundError()\n return this.data[key.toString()]\n }\n\n /**\n * @param {Key} key\n */\n async has (key) { // eslint-disable-line require-await\n return this.data[key.toString()] !== undefined\n }\n\n /**\n * @param {Key} key\n */\n async delete (key) { // eslint-disable-line require-await\n delete this.data[key.toString()]\n }\n\n async * _all () {\n yield * Object.entries(this.data)\n .map(([key, value]) => ({ key: new Key(key), value }))\n }\n\n async * _allKeys () {\n yield * Object.entries(this.data)\n .map(([key]) => new Key(key))\n }\n}\n", "/**\n * Takes an (async) iterable and returns one with each item mapped by the passed\n * function\n */\nexport default async function * map (source: AsyncIterable|Iterable, func: (val: I) => O | Promise): AsyncGenerator {\n for await (const val of source) {\n yield func(val)\n }\n}\n", "import { pushable } from 'it-pushable'\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nexport default async function * merge (...sources: Array|Iterable>): AsyncGenerator {\n const output = pushable({\n objectMode: true\n })\n\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n output.push(item)\n }\n })\n )\n\n output.end()\n } catch (err: any) {\n output.end(err)\n }\n })\n\n yield * output\n}\n", "import { pushable } from 'it-pushable'\nimport merge from 'it-merge'\nimport type * as it from 'it-stream-types'\n\nexport const rawPipe = (...fns: any) => {\n let res\n while (fns.length > 0) {\n res = fns.shift()(res)\n }\n return res\n}\n\nexport const isIterable = (obj: any): obj is it.Source => {\n return obj != null && (\n typeof obj[Symbol.asyncIterator] === 'function' ||\n typeof obj[Symbol.iterator] === 'function' ||\n typeof obj.next === 'function' // Probably, right?\n )\n}\n\nexport const isDuplex = > (obj: any): obj is it.Duplex => {\n return obj != null && typeof obj.sink === 'function' && isIterable(obj.source)\n}\n\nconst duplexPipelineFn = (duplex: it.Duplex) => {\n return (source: any): it.Source => {\n const p = duplex.sink(source)\n\n if (p.then != null) {\n const stream = pushable({\n objectMode: true\n })\n p.then(() => {\n stream.end()\n }, (err: Error) => {\n stream.end(err)\n })\n\n const sourceWrap = async function * () {\n yield * duplex.source\n stream.end()\n }\n\n return merge(stream, sourceWrap())\n }\n\n return duplex.source\n }\n}\n\nexport type Source = it.Source | (() => it.Source) | it.Duplex\nexport type Transform = it.Transform | it.Duplex\nexport type Sink = it.Sink | it.Duplex\n\nexport function pipe (\n first: Source\n): it.Source\n\nexport function pipe (\n first: Source,\n second: Sink\n): B\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Sink\n): C\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Sink\n): D\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Sink\n): E\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Sink\n): F\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Sink\n): G\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Sink\n): H\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Sink\n): I\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Transform,\n tenth: Sink\n): J\n\nexport function pipe (first: any, ...rest: any[]): any {\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 } else if (isIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\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\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\n return rawPipe(...fns)\n}\n", "import { Key } from 'interface-datastore'\nimport {\n readShardFun,\n SHARDING_FN,\n README_FN,\n readme\n} from './shard.js'\nimport { BaseDatastore } from './base.js'\nimport { KeyTransformDatastore } from './keytransform.js'\nimport * as Errors from './errors.js'\n\nconst shardKey = new Key(SHARDING_FN)\nconst shardReadmeKey = new Key(README_FN)\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} Options\n * @typedef {import('interface-datastore').Batch} Batch\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').QueryFilter} QueryFilter\n * @typedef {import('interface-datastore').QueryOrder} QueryOrder\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').KeyQueryFilter} KeyQueryFilter\n * @typedef {import('interface-datastore').KeyQueryOrder} KeyQueryOrder\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('./types').Shard} Shard\n *\n */\n/**\n * @template TValue\n * @typedef {import('interface-store').Await } Await\n */\n\n/**\n * @template TEntry\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * Backend independent abstraction of go-ds-flatfs.\n *\n * Wraps another datastore such that all values are stored\n * sharded according to the given sharding function.\n */\nexport class ShardingDatastore extends BaseDatastore {\n /**\n * @param {Datastore} store\n * @param {Shard} shard\n */\n constructor (store, shard) {\n super()\n\n this.child = new KeyTransformDatastore(store, {\n convert: this._convertKey.bind(this),\n invert: this._invertKey.bind(this)\n })\n this.shard = shard\n }\n\n async open () {\n await this.child.open()\n\n this.shard = await ShardingDatastore.create(this.child, this.shard)\n }\n\n /**\n * @param {Key} key\n */\n _convertKey (key) {\n const s = key.toString()\n if (s === shardKey.toString() || s === shardReadmeKey.toString()) {\n return key\n }\n\n const parent = new Key(this.shard.fun(s))\n return parent.child(key)\n }\n\n /**\n * @param {Key} key\n */\n _invertKey (key) {\n const s = key.toString()\n if (s === shardKey.toString() || s === shardReadmeKey.toString()) {\n return key\n }\n return Key.withNamespaces(key.list().slice(1))\n }\n\n /**\n * @deprecated\n * @param {Datastore} store\n * @param {Shard} shard\n */\n static async createOrOpen (store, shard) {\n try {\n await ShardingDatastore.create(store, shard)\n } catch (/** @type {any} */ err) {\n if (err && err.message !== 'datastore exists') throw err\n }\n return ShardingDatastore.open(store)\n }\n\n /**\n * @deprecated\n * @param {Datastore} store\n */\n static async open (store) {\n const shard = await readShardFun('/', store)\n return new ShardingDatastore(store, shard)\n }\n\n /**\n * @param {Datastore} store\n * @param {Shard} shard\n */\n static async create (store, shard) {\n const hasShard = await store.has(shardKey)\n if (!hasShard && !shard) {\n throw Errors.dbOpenFailedError(Error('Shard is required when datastore doesn\\'t have a shard key already.'))\n }\n if (!hasShard) {\n // @ts-ignore i have no idea what putRaw is or saw any implementation\n const put = typeof store.putRaw === 'function' ? store.putRaw.bind(store) : store.put.bind(store)\n await Promise.all([\n put(shardKey, new TextEncoder().encode(shard.toString() + '\\n')),\n put(shardReadmeKey, new TextEncoder().encode(readme))\n ])\n\n return shard\n }\n\n // test shards\n const diskShard = await readShardFun('/', store)\n const a = (diskShard || '').toString()\n const b = shard.toString()\n if (a !== b) {\n throw new Error(`specified fun ${b} does not match repo shard fun ${a}`)\n }\n return diskShard\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n */\n put (key, val, options) {\n return this.child.put(key, val, options)\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n get (key, options) {\n return this.child.get(key, options)\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n has (key, options) {\n return this.child.has(key, options)\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n */\n delete (key, options) {\n return this.child.delete(key, options)\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n yield * this.child.putMany(source, options)\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n yield * this.child.getMany(source, options)\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n yield * this.child.deleteMany(source, options)\n }\n\n batch () {\n return this.child.batch()\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n /** @type {Query} */\n const tq = {\n ...q,\n filters: [\n /** @type {QueryFilter} */\n ({ key }) => key.toString() !== shardKey.toString(),\n /** @type {QueryFilter} */\n ({ key }) => key.toString() !== shardReadmeKey.toString()\n ].concat(q.filters || [])\n }\n\n return this.child.query(tq, options)\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n /** @type {KeyQuery} */\n const tq = {\n ...q,\n filters: [\n /** @type {KeyQueryFilter} */\n key => key.toString() !== shardKey.toString(),\n /** @type {KeyQueryFilter} */\n key => key.toString() !== shardReadmeKey.toString()\n ].concat(q.filters || [])\n }\n\n return this.child.queryKeys(tq, options)\n }\n\n close () {\n return this.child.close()\n }\n}\n", "\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 */\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static get code (): string {\n return 'ABORT_ERR'\n }\n\n static get type (): string {\n return 'aborted'\n }\n}\n\nexport class CodeError = Record> extends Error {\n public readonly props: T\n\n constructor (\n message: string,\n public readonly code: string,\n props?: T\n ) {\n super(message)\n\n this.name = props?.name ?? 'CodeError'\n this.props = props ?? {} as T // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\n/**\n * @typedef {import('interface-datastore').Key} Key\n */\n\nconst namespace = '/record/'\n\n/**\n * @param {Uint8Array} buf\n */\nexport function encodeBase32 (buf) {\n return uint8ArrayToString(buf, 'base32')\n}\n\n/**\n * converts a binary record key to a pubsub topic key\n *\n * @param {Uint8Array | string} key\n */\nexport function keyToTopic (key) {\n // Record-store keys are arbitrary binary. However, pubsub requires UTF-8 string topic IDs\n // Encodes to \"/record/base64url(key)\"\n if (typeof key === 'string' || key instanceof String) {\n key = uint8ArrayFromString(key.toString())\n }\n\n const b64url = uint8ArrayToString(key, 'base64url')\n\n return `${namespace}${b64url}`\n}\n\n/**\n * converts a pubsub topic key to a binary record key\n *\n * @param {string} topic\n */\nexport function topicToKey (topic) {\n if (topic.substring(0, namespace.length) !== namespace) {\n throw new CodeError('topic received is not from a record', 'ERR_TOPIC_IS_NOT_FROM_RECORD_NAMESPACE')\n }\n\n const key = topic.substring(namespace.length)\n\n return uint8ArrayFromString(key, 'base64url')\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "import { Key } from 'interface-datastore'\nimport { BaseDatastore } from 'datastore-core'\nimport { encodeBase32, keyToTopic, topicToKey } from './utils.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('datastore-pubsub:publisher')\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('./types').SubscriptionKeyFn} SubscriptionKeyFn\n * @typedef {import('@libp2p/interface-pubsub').Message} PubSubMessage\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\n// DatastorePubsub is responsible for providing an api for pubsub to be used as a datastore with\n// [TieredDatastore]{@link https://github.com/ipfs/js-datastore-core/blob/master/src/tiered.js}\nexport class PubSubDatastore extends BaseDatastore {\n /**\n * Creates an instance of DatastorePubsub.\n *\n * @param {import('@libp2p/interface-pubsub').PubSub} pubsub - pubsub implementation\n * @param {import('interface-datastore').Datastore} datastore - datastore instance\n * @param {PeerId} peerId - peer-id instance\n * @param {import('@libp2p/interface-dht').ValidateFn} validator - validator function\n * @param {import('@libp2p/interface-dht').SelectFn} selector - selector function\n * @param {SubscriptionKeyFn} [subscriptionKeyFn] - function to manipulate the key topic received before processing it\n * @memberof DatastorePubsub\n */\n constructor (pubsub, datastore, peerId, validator, selector, subscriptionKeyFn) {\n super()\n\n if (!validator) {\n throw new CodeError('missing validator', 'ERR_INVALID_PARAMETERS')\n }\n\n if (typeof validator !== 'function') {\n throw new CodeError('missing validate function', 'ERR_INVALID_PARAMETERS')\n }\n\n if (typeof selector !== 'function') {\n throw new CodeError('missing select function', 'ERR_INVALID_PARAMETERS')\n }\n\n if (subscriptionKeyFn && typeof subscriptionKeyFn !== 'function') {\n throw new CodeError('invalid subscriptionKeyFn received', 'ERR_INVALID_PARAMETERS')\n }\n\n this._pubsub = pubsub\n this._datastore = datastore\n this._peerId = peerId\n this._validator = validator\n this._selector = selector\n this._handleSubscriptionKeyFn = subscriptionKeyFn\n\n // Bind _onMessage function, which is called by pubsub.\n this._onMessage = this._onMessage.bind(this)\n this._pubsub.addEventListener('message', this._onMessage)\n }\n\n /**\n * Publishes a value through pubsub.\n *\n * @param {Uint8Array} key - identifier of the value to be published.\n * @param {Uint8Array} val - value to be propagated.\n * @param {AbortOptions} [options]\n */\n // @ts-ignore Datastores take keys as Keys, this one takes Uint8Arrays\n async put (key, val, options) {\n if (!(key instanceof Uint8Array)) {\n const errMsg = 'datastore key does not have a valid format'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_DATASTORE_KEY')\n }\n\n if (!(val instanceof Uint8Array)) {\n const errMsg = 'received value is not a Uint8Array'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_VALUE_RECEIVED')\n }\n\n const stringifiedTopic = keyToTopic(key)\n\n log(`publish value for topic ${stringifiedTopic}`)\n\n // Publish record to pubsub\n await this._pubsub.publish(stringifiedTopic, val)\n }\n\n /**\n * Try to subscribe a topic with Pubsub and returns the local value if available.\n *\n * @param {Uint8Array} key - identifier of the value to be subscribed.\n * @param {AbortOptions} [options]\n */\n // @ts-ignore Datastores take keys as Keys, this one takes Uint8Arrays\n async get (key, options) {\n if (!(key instanceof Uint8Array)) {\n const errMsg = 'datastore key does not have a valid format'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_DATASTORE_KEY')\n }\n\n const stringifiedTopic = keyToTopic(key)\n const subscriptions = await this._pubsub.getTopics()\n\n // If already subscribed, just try to get it\n if (subscriptions && Array.isArray(subscriptions) && subscriptions.indexOf(stringifiedTopic) > -1) {\n return this._getLocal(key, options)\n }\n\n // subscribe\n try {\n await this._pubsub.subscribe(stringifiedTopic)\n } catch (/** @type {any} */ err) {\n const errMsg = `cannot subscribe topic ${stringifiedTopic}`\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_SUBSCRIBING_TOPIC')\n }\n log(`subscribed values for key ${stringifiedTopic}`)\n\n return this._getLocal(key)\n }\n\n /**\n * Unsubscribe topic.\n *\n * @param {Uint8Array} key - identifier of the value to unsubscribe.\n * @returns {void}\n */\n unsubscribe (key) {\n const stringifiedTopic = keyToTopic(key)\n\n return this._pubsub.unsubscribe(stringifiedTopic)\n }\n\n /**\n * Get record from local datastore\n *\n * @private\n * @param {Uint8Array} key\n * @param {AbortOptions} [options]\n */\n async _getLocal (key, options) {\n // encode key - base32(/ipns/{cid})\n const routingKey = new Key('/' + encodeBase32(key), false)\n let dsVal\n\n try {\n dsVal = await this._datastore.get(routingKey, options)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n const errMsg = `unexpected error getting the ipns record for ${routingKey.toString()}`\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_UNEXPECTED_ERROR_GETTING_RECORD')\n }\n const errMsg = `local record requested was not found for ${routingKey.toString()}`\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_NOT_FOUND')\n }\n\n if (!(dsVal instanceof Uint8Array)) {\n const errMsg = 'found record that we couldn\\'t convert to a value'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_INVALID_RECORD_RECEIVED')\n }\n\n return dsVal\n }\n\n /**\n * handles pubsub subscription messages\n *\n * @param {CustomEvent} evt\n */\n async _onMessage (evt) {\n const msg = evt.detail\n\n if (msg.type !== 'signed') {\n log.error('unsigned message received, this module can only work with signed messages')\n return\n }\n\n const { data, from, topic } = msg\n let key\n try {\n key = topicToKey(topic)\n } catch (/** @type {any} */ err) {\n log.error(err)\n return\n }\n\n log(`message received for topic ${topic}`)\n\n // Stop if the message is from the peer (it already stored it while publishing to pubsub)\n if (this._peerId.equals(from)) {\n log('message discarded as it is from the same peer')\n return\n }\n\n if (this._handleSubscriptionKeyFn) {\n let res\n\n try {\n res = await this._handleSubscriptionKeyFn(key)\n } catch (/** @type {any} */ err) {\n log.error('message discarded by the subscriptionKeyFn')\n return\n }\n\n key = res\n }\n\n try {\n await this._storeIfSubscriptionIsBetter(key, data)\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }\n\n /**\n * Store the received record if it is better than the current stored\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @param {AbortOptions} [options]\n */\n async _storeIfSubscriptionIsBetter (key, data, options) {\n let isBetter = false\n\n try {\n isBetter = await this._isBetter(key, data)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_VALID_RECORD') {\n throw err\n }\n }\n\n if (isBetter) {\n await this._storeRecord(key, data, options)\n }\n }\n\n /**\n * Validate record according to the received validation function\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} value\n */\n async _validateRecord (key, value) { // eslint-disable-line require-await\n return this._validator(key, value)\n }\n\n /**\n * Select the best record according to the received select function\n *\n * @param {Uint8Array} key\n * @param {Uint8Array[]} records\n */\n async _selectRecord (key, records) {\n const res = await this._selector(key, records)\n\n // If the selected was the first (0), it should be stored (true)\n return res === 0\n }\n\n /**\n * Verify if the record received through pubsub is valid and better than the one currently stored\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} val\n */\n async _isBetter (key, val) {\n try {\n await this._validateRecord(key, val)\n } catch (/** @type {any} */ err) {\n // If not valid, it is not better than the one currently available\n const errMsg = 'record received through pubsub is not valid'\n\n log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_NOT_VALID_RECORD')\n }\n\n // Get Local record\n const dsKey = new Key(key)\n let currentRecord\n\n try {\n currentRecord = await this._getLocal(dsKey.uint8Array())\n } catch (/** @type {any} */ err) {\n // if the old one is invalid, the new one is *always* better\n return true\n }\n\n // if the same record, do not need to store\n if (uint8ArrayEquals(currentRecord, val)) {\n return false\n }\n\n // verify if the received record should replace the current one\n return this._selectRecord(key, [currentRecord, val])\n }\n\n /**\n * add record to datastore\n *\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @param {AbortOptions} [options]\n */\n async _storeRecord (key, data, options) {\n // encode key - base32(/ipns/{cid})\n const routingKey = new Key('/' + encodeBase32(key), false)\n\n await this._datastore.put(routingKey, data, options)\n log(`record for ${keyToTopic(key)} was stored in the datastore`)\n }\n}\n", "import { namespaceLength, namespace, peerIdToRoutingKey } from 'ipns'\nimport { ipnsValidator } from 'ipns/validator'\nimport { ipnsSelector } from 'ipns/selector'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { PubSubDatastore } from 'datastore-pubsub'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\nconst log = logger('ipfs:ipns:pubsub')\n\n/**\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\n// Pubsub datastore aims to manage the pubsub subscriptions for IPNS\nexport class IpnsPubsubDatastore {\n /**\n * @param {import('@libp2p/interface-pubsub').PubSub} pubsub\n * @param {import('interface-datastore').Datastore} localDatastore\n * @param {import('@libp2p/interface-peer-id').PeerId} peerId\n */\n constructor (pubsub, localDatastore, peerId) {\n /** @type {Record} */\n this._subscriptions = {}\n\n // Bind _handleSubscriptionKey function, which is called by PubsubDatastore.\n this._handleSubscriptionKey = this._handleSubscriptionKey.bind(this)\n\n this._pubsubDs = new PubSubDatastore(pubsub, localDatastore, peerId, ipnsValidator, ipnsSelector, this._handleSubscriptionKey)\n }\n\n /**\n * Put a value to the pubsub datastore indexed by the received key properly encoded.\n *\n * @param {Uint8Array} key - identifier of the value.\n * @param {Uint8Array} value - value to be stored.\n * @param {AbortOptions} [options]\n */\n async put (key, value, options) {\n try {\n await this._pubsubDs.put(key, value, options)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n }\n\n /**\n * Get a value from the pubsub datastore indexed by the received key properly encoded.\n * Also, the identifier topic is subscribed to and the pubsub datastore records will be\n * updated once new publishes occur.\n *\n * @param {Uint8Array} key - identifier of the value to be obtained.\n * @param {AbortOptions} [options]\n */\n async get (key, options) {\n let res\n let err\n\n try {\n res = await this._pubsubDs.get(key, options)\n } catch (/** @type {any} */ e) {\n err = e\n }\n\n // Add topic subscribed\n const ns = key.slice(0, namespaceLength)\n\n if (uint8ArrayToString(ns) === namespace) {\n const stringifiedTopic = base58btc.encode(key).substring(1)\n const id = base58btc.encode(key.slice(namespaceLength)).substring(1)\n\n this._subscriptions[stringifiedTopic] = id\n\n log(`subscribed to pubsub topic ${stringifiedTopic}, id ${id}`)\n }\n\n // If no data was obtained, after storing the subscription, return the error.\n if (err) {\n throw err\n }\n\n return res\n }\n\n /**\n * Modify subscription key to have a proper encoding\n *\n * @param {Uint8Array | string} key\n */\n _handleSubscriptionKey (key) {\n if (key instanceof Uint8Array) {\n key = uint8ArrayToString(key, 'base58btc')\n }\n\n const subscriber = this._subscriptions[key]\n\n if (!subscriber) {\n throw errcode(new Error(`key ${key} does not correspond to a subscription`), 'ERR_INVALID_KEY')\n }\n\n try {\n const k = peerIdToRoutingKey(peerIdFromString(subscriber))\n return k\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n }\n\n /**\n * Get pubsub subscriptions related to ipns.\n */\n getSubscriptions () {\n const subscriptions = Object.values(this._subscriptions).filter(Boolean)\n\n return subscriptions.map((sub) => `${namespace}${sub}`)\n }\n\n /**\n * Cancel pubsub subscriptions related to ipns.\n *\n * @param {string} name - ipns path to cancel the pubsub subscription.\n */\n async cancel (name) { // eslint-disable-line require-await\n if (typeof name !== 'string') {\n throw errcode(new Error('invalid subscription name'), 'ERR_INVALID_SUBSCRIPTION_NAME')\n }\n\n // Trim /ipns/ prefix from the name\n if (name.startsWith(namespace)) {\n name = name.substring(namespaceLength)\n }\n\n const stringifiedTopic = Object.keys(this._subscriptions).find((key) => this._subscriptions[key] === name)\n\n // Not found topic\n if (!stringifiedTopic) {\n return {\n canceled: false\n }\n }\n\n // Unsubscribe topic\n const bufTopic = uint8ArrayFromString(stringifiedTopic)\n\n this._pubsubDs.unsubscribe(bufTopic)\n\n delete this._subscriptions[stringifiedTopic]\n log(`unsubscribed pubsub ${stringifiedTopic}: ${name}`)\n\n return {\n canceled: true\n }\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key: Uint8Array\n value: Uint8Array\n timeReceived: string\n}\n\nexport namespace Record {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if ((obj.timeReceived != null && obj.timeReceived !== '')) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: new Uint8Array(0),\n value: new Uint8Array(0),\n timeReceived: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.bytes()\n break\n case 2:\n obj.value = reader.bytes()\n break\n case 5:\n obj.timeReceived = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Record.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Record => {\n return decodeMessage(buf, Record.codec())\n }\n}\n", "/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n", "import {\n Record\n} from './record.js'\nimport * as utils from './utils.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Libp2pRecord {\n public key: Uint8Array\n public value: Uint8Array\n public timeReceived: Date\n\n constructor (key: Uint8Array, value: Uint8Array, timeReceived: Date) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('key must be a Uint8Array')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new Error('value must be a Uint8Array')\n }\n\n this.key = key\n this.value = value\n this.timeReceived = timeReceived\n }\n\n serialize (): Uint8Array {\n return Record.encode(this.prepareSerialize())\n }\n\n /**\n * Return the object format ready to be given to the protobuf library.\n */\n prepareSerialize (): Record {\n return {\n key: this.key,\n value: this.value,\n timeReceived: utils.toRFC3339(this.timeReceived)\n }\n }\n\n /**\n * Decode a protobuf encoded record\n */\n static deserialize (raw: Uint8Array | Uint8ArrayList): Libp2pRecord {\n const rec = Record.decode(raw)\n\n return new Libp2pRecord(rec.key, rec.value, new Date(rec.timeReceived))\n }\n\n /**\n * Create a record from the raw object returned from the protobuf library\n */\n static fromDeserialized (obj: Record): Libp2pRecord {\n const recvtime = utils.parseRFC3339(obj.timeReceived)\n\n if (obj.key == null) {\n throw new Error('key missing from deserialized object')\n }\n\n if (obj.value == null) {\n throw new Error('value missing from deserialized object')\n }\n\n const rec = new Libp2pRecord(\n obj.key, obj.value, recvtime\n )\n\n return rec\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport { Libp2pRecord } from '@libp2p/record'\nimport errcode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst log = logger('ipfs:ipns:offline-datastore')\n\n/**\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\n// Offline datastore aims to mimic the same encoding as routing when storing records\n// to the local datastore\nexport class OfflineDatastore {\n /**\n * @param {import('interface-datastore').Datastore} datastore\n */\n constructor (datastore) {\n this._datastore = datastore\n /** @type {any[]} */\n this.stores = []\n }\n\n /**\n * Put a value to the local datastore indexed by the received key properly encoded.\n *\n * @param {Uint8Array} key - identifier of the value.\n * @param {Uint8Array} value - value to be stored.\n * @param {AbortOptions} [options]\n */\n async put (key, value, options) { // eslint-disable-line require-await\n if (!(key instanceof Uint8Array)) {\n throw errcode(new Error('Offline datastore key must be a Uint8Array'), 'ERR_INVALID_KEY')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw errcode(new Error('Offline datastore value must be a Uint8Array'), 'ERR_INVALID_VALUE')\n }\n\n let routingKey\n\n try {\n routingKey = this._routingKey(key)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')\n }\n\n // Marshal to libp2p record as the DHT does\n const record = new Libp2pRecord(key, value, new Date())\n\n await this._datastore.put(routingKey, record.serialize(), options)\n }\n\n /**\n * Get a value from the local datastore indexed by the received key properly encoded.\n *\n * @param {Uint8Array} key - identifier of the value to be obtained.\n * @param {AbortOptions} [options]\n */\n async get (key, options) {\n if (!(key instanceof Uint8Array)) {\n throw errcode(new Error('Offline datastore key must be a Uint8Array'), 'ERR_INVALID_KEY')\n }\n\n let routingKey\n\n try {\n routingKey = this._routingKey(key)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')\n }\n\n const res = await this._datastore.get(routingKey, options)\n\n // Unmarshal libp2p record as the DHT does\n let record\n try {\n record = Libp2pRecord.deserialize(res)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n\n return record.value\n }\n\n /**\n * encode key properly - base32(/ipns/{cid})\n *\n * @param {Uint8Array} key\n */\n _routingKey (key) {\n return new Key('/dht/record/' + uint8ArrayToString(key, 'base32'), false)\n }\n}\n", "/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nexport default async function drain (source: AsyncIterable | Iterable): Promise {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n}\n", "import drain from 'it-drain'\nimport { notFoundError } from 'datastore-core/errors'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:ipns:dht-datastore')\n\n/**\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n */\n\nexport class DHTDatastore {\n /**\n *\n * @param {import('@libp2p/interface-dht').DHT} dht\n */\n constructor (dht) {\n this._dht = dht\n }\n\n /**\n * @param {Uint8Array} key - identifier of the value.\n * @param {Uint8Array} value - value to be stored.\n * @param {AbortOptions} [options]\n */\n async put (key, value, options) {\n try {\n await drain(this._dht.put(key, value, options))\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n }\n\n /**\n * @param {Uint8Array} key - identifier of the value to be obtained.\n * @param {AbortOptions} [options]\n */\n async get (key, options) {\n for await (const event of this._dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw notFoundError()\n }\n}\n", "import { IPNS } from '../ipns/index.js'\nimport { createRouting } from '../ipns/routing/config.js'\nimport { OfflineDatastore } from '../ipns/routing/offline-datastore.js'\nimport { NotInitializedError, AlreadyInitializedError } from '../errors.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:components:ipns')\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@libp2p/interfaces').AbortOptions} AbortOptions\n *\n * @typedef {object} ExperimentalOptions\n * @property {boolean} [ipnsPubsub]\n *\n * @typedef {object} LibP2POptions\n * @property {DHTConfig} [config]\n *\n * @typedef {object} DHTConfig\n * @property {boolean} [enabled]\n */\n\nexport class IPNSAPI {\n /**\n * @param {object} options\n * @param {string} options.pass\n * @param {boolean} [options.offline]\n * @param {LibP2POptions} [options.libp2p]\n * @param {ExperimentalOptions} [options.EXPERIMENTAL]\n */\n constructor (options = { pass: '' }) {\n this.options = options\n\n /** @type {IPNS | null} */\n this.offline = null\n\n /** @type {IPNS | null} */\n this.online = null\n }\n\n getIPNS () {\n const ipns = this.online || this.offline\n if (ipns) {\n return ipns\n } else {\n throw new NotInitializedError()\n }\n }\n\n get routing () {\n return this.getIPNS().routing\n }\n\n /**\n * Activates IPNS subsystem in an ofline mode. If it was started once already\n * it will throw an exception.\n *\n * This is primarily used for offline ipns modifications, such as the\n * initializeKeyspace feature.\n *\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\n startOffline ({ repo, peerId, keychain }) {\n if (this.offline != null) {\n throw new AlreadyInitializedError()\n }\n\n log('initializing IPNS keyspace (offline)')\n\n const routing = new OfflineDatastore(repo.datastore)\n const ipns = new IPNS(routing, repo.datastore, peerId, keychain, this.options)\n\n this.offline = ipns\n }\n\n /**\n * @param {object} config\n * @param {import('libp2p').Libp2p} config.libp2p\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\n async startOnline ({ libp2p, repo, peerId, keychain }) {\n if (this.online != null) {\n throw new AlreadyInitializedError()\n }\n const routing = createRouting({ libp2p, repo, peerId, options: this.options })\n\n // @ts-expect-error routing is a TieredDatastore which wants keys to be Keys, IPNS needs keys to be Uint8Arrays\n const ipns = new IPNS(routing, repo.datastore, peerId, keychain, this.options)\n await ipns.republisher.start()\n this.online = ipns\n }\n\n async stop () {\n const ipns = this.online\n if (ipns) {\n await ipns.republisher.stop()\n this.online = null\n }\n }\n\n /**\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {number} lifetime\n * @param {AbortOptions} [options]\n */\n publish (peerId, value, lifetime, options) {\n return this.getIPNS().publish(peerId, value, lifetime, options)\n }\n\n /**\n *\n * @param {string} name\n * @param {object} [options]\n * @param {boolean} [options.nocache]\n * @param {boolean} [options.recursive]\n * @param {AbortSignal} [options.signal]\n */\n resolve (name, options) {\n return this.getIPNS().resolve(name, options)\n }\n\n /**\n * @param {PeerId} peerId\n * @param {Uint8Array} value\n * @param {AbortOptions} [options]\n */\n initializeKeyspace (peerId, value, options) {\n return this.getIPNS().initializeKeyspace(peerId, value, options)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport parseDuration from 'parse-duration'\nimport { importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport errcode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { OFFLINE_ERROR, normalizePath } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { resolvePath } from './utils.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\n\nconst log = logger('ipfs:name:publish')\n\n/**\n * IPNS - Inter-Planetary Naming System\n *\n * @param {object} config\n * @param {import('../ipns').IPNSAPI} config.ipns\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('ipfs-core-types/src/root').API<{}>[\"isOnline\"]} config.isOnline\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createPublish ({ ipns, repo, codecs, peerId, isOnline, keychain }) {\n /**\n * @param {string} keyName\n */\n const lookupKey = async keyName => {\n /** @type {import('@libp2p/interface-keys').PrivateKey} */\n let privateKey\n\n if (keyName === 'self' && peerId.privateKey != null) {\n privateKey = await unmarshalPrivateKey(peerId.privateKey)\n } else {\n try {\n // We're exporting and immediately importing the key, so we can just use a throw away password\n const pem = await keychain.exportKey(keyName, 'temp')\n privateKey = await importKey(pem, 'temp')\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw errcode(err, 'ERR_CANNOT_GET_KEY')\n }\n }\n\n return peerIdFromKeys(privateKey.public.bytes, privateKey.bytes)\n }\n\n /**\n * @type {import('ipfs-core-types/src/name').API<{}>[\"publish\"]}\n */\n async function publish (value, options = {}) {\n const resolve = !(options.resolve === false)\n const lifetime = options.lifetime || '24h'\n const key = options.key || 'self'\n\n if (!isOnline()) {\n throw errcode(new Error(OFFLINE_ERROR), 'OFFLINE_ERROR')\n }\n\n // TODO: params related logic should be in the core implementation\n // Normalize path value\n try {\n value = normalizePath(value)\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n\n let pubLifetime = 0\n try {\n pubLifetime = parseDuration(lifetime) || 0\n\n // Calculate lifetime with nanoseconds precision\n pubLifetime = parseFloat(pubLifetime.toFixed(6))\n } catch (/** @type {any} */ err) {\n log.error(err)\n throw err\n }\n\n // TODO: ttl human for cache\n const results = await Promise.all([\n // verify if the path exists, if not, an error will stop the execution\n lookupKey(key),\n // if resolving, do a get so we make sure we have the blocks\n resolve ? resolvePath({ ipns, repo, codecs }, value) : Promise.resolve()\n ])\n\n const bytes = uint8ArrayFromString(value)\n\n // Start publishing process\n const result = await ipns.publish(results[0], bytes, pubLifetime, options)\n\n return {\n name: result.name,\n value: uint8ArrayToString(result.value)\n }\n }\n\n return withTimeoutOption(publish)\n}\n", "import * as isIPFS from 'is-ipfs'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport drain from 'it-drain'\nimport { resolve } from '../../utils.js'\n\n/**\n * resolves the given path by parsing out protocol-specific entries\n * (e.g. /ipns/) and then going through the /ipfs/ entries and returning the final node\n *\n * @param {object} context\n * @param {import('../ipns').IPNSAPI} context.ipns\n * @param {import('ipfs-repo').IPFSRepo} context.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} context.codecs\n * @param {string} name\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n */\nexport async function resolvePath ({ ipns, repo, codecs }, name, options) {\n // ipns path\n if (isIPFS.ipnsPath(name)) {\n return ipns.resolve(name)\n }\n\n const {\n cid,\n path\n } = toCidAndPath(name)\n\n // ipfs path\n await drain(resolve(cid, path || '', codecs, repo, options))\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport mergeOpts from 'merge-options'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { base36 } from 'multiformats/bases/base36'\nimport { peerIdFromString } from '@libp2p/peer-id'\n// @ts-expect-error no types\nimport isDomain from 'is-domain-name'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { OFFLINE_ERROR } from '../../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\nconst log = logger('ipfs:name:resolve')\n\n/**\n *\n * @param {string} result\n * @param {string[]} remainder\n * @returns {string}\n */\nconst appendRemainder = (result, remainder) =>\n remainder.length > 0\n ? result + '/' + remainder.join('/')\n : result\n\n/**\n * IPNS - Inter-Planetary Naming System\n *\n * @param {object} config\n * @param {import('ipfs-core-types/src/root').API<{}>[\"dns\"]} config.dns\n * @param {import('../ipns').IPNSAPI} config.ipns\n * @param {import('ipfs-core-types/src/root').API<{}>[\"isOnline\"]} config.isOnline\n * @param {import('../../types').Options} config.options\n */\nexport function createResolve ({ dns, ipns, isOnline, options: { offline } }) {\n /**\n * @type {import('ipfs-core-types/src/name').API<{}>[\"resolve\"]}\n */\n async function * resolve (name, options = {}) { // eslint-disable-line require-await\n options = mergeOptions({\n nocache: false,\n recursive: true\n }, options)\n\n // TODO: params related logic should be in the core implementation\n if (offline && options && options.nocache) {\n throw errcode(new Error('cannot specify both offline and nocache'), 'ERR_NOCACHE_AND_OFFLINE')\n }\n\n // IPNS resolve needs a online daemon\n if (!isOnline() && !offline) {\n throw errcode(new Error(OFFLINE_ERROR), 'OFFLINE_ERROR')\n }\n\n let ipnsName = name.toString()\n\n if (!ipnsName.startsWith('/ipns/')) {\n ipnsName = `/ipns/${ipnsName}`\n }\n\n let [namespace, hash, ...remainder] = ipnsName.slice(1).split('/')\n\n try {\n if (hash.substring(0, 1) === '1') {\n const id = peerIdFromString(hash)\n const digest = Digest.decode(id.toBytes())\n const libp2pKey = CID.createV1(0x72, digest)\n hash = libp2pKey.toString(base36)\n } else {\n const cid = CID.parse(hash)\n\n if (cid.version === 1) {\n hash = cid.toString(base36)\n }\n }\n } catch (/** @type {any} */ err) {\n // lets check if we have a domain ex. /ipns/ipfs.io and resolve with dns\n if (isDomain(hash)) {\n yield appendRemainder(await dns(hash, options), remainder)\n return\n }\n\n log.error(err)\n throw errcode(new Error('Invalid IPNS name'), 'ERR_IPNS_INVALID_NAME')\n }\n\n // multihash is valid lets resolve with IPNS\n // TODO: convert ipns.resolve to return an iterator\n const value = await ipns.resolve(`/${namespace}/${hash}`, options)\n yield appendRemainder(value instanceof Uint8Array ? uint8ArrayToString(value) : value, remainder)\n }\n\n return withTimeoutOption(resolve)\n}\n", "import { IpnsPubsubDatastore } from '../../../ipns/routing/pubsub-datastore.js'\nimport errcode from 'err-code'\n\n/**\n * @typedef {import('../../../types').ExperimentalOptions} ExperimentalOptions\n * @property {boolean} [ipnsPubsub] - Enable pub-sub on IPNS. (Default: `false`)\n */\n\n/**\n * Get pubsub from IPNS routing\n *\n * @param {import('../../ipns').IPNSAPI} ipns\n * @param {ExperimentalOptions} [options]\n */\nexport function getPubsubRouting (ipns, options) {\n if (!ipns || !(options && options.ipnsPubsub)) {\n throw errcode(new Error('IPNS pubsub subsystem is not enabled'), 'ERR_IPNS_PUBSUB_NOT_ENABLED')\n }\n\n // Only one store and it is pubsub\n if (ipns.routing instanceof IpnsPubsubDatastore) {\n return ipns.routing\n }\n\n // Find in tiered\n const pubsub = (ipns.routing.stores || []).find(s => s instanceof IpnsPubsubDatastore)\n\n if (!pubsub) {\n throw errcode(new Error('IPNS pubsub datastore not found'), 'ERR_PUBSUB_DATASTORE_NOT_FOUND')\n }\n\n return pubsub\n}\n", "import { getPubsubRouting } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\nexport function createCancel ({ ipns, options }) {\n const experimental = options.EXPERIMENTAL\n\n /**\n * @type {import('ipfs-core-types/src/name/pubsub').API<{}>[\"cancel\"]}\n */\n async function cancel (name, options = {}) { // eslint-disable-line require-await\n const pubsub = getPubsubRouting(ipns, experimental)\n return pubsub.cancel(name, options)\n }\n\n return withTimeoutOption(cancel)\n}\n", "import { getPubsubRouting } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\nexport function createState ({ ipns, options }) {\n const experimental = options.EXPERIMENTAL\n\n /**\n * @type {import('ipfs-core-types/src/name/pubsub').API<{}>[\"state\"]}\n */\n async function state (_options = {}) { // eslint-disable-line require-await\n try {\n return { enabled: Boolean(getPubsubRouting(ipns, experimental)) }\n } catch (/** @type {any} */ err) {\n return { enabled: false }\n }\n }\n\n return withTimeoutOption(state)\n}\n", "import { getPubsubRouting } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\nexport function createSubs ({ ipns, options }) {\n const experimental = options.EXPERIMENTAL\n\n /**\n * @type {import('ipfs-core-types/src/name/pubsub').API<{}>[\"subs\"]}\n */\n async function subs (options = {}) { // eslint-disable-line require-await\n const pubsub = getPubsubRouting(ipns, experimental)\n return pubsub.getSubscriptions(options)\n }\n\n return withTimeoutOption(subs)\n}\n", "import { createCancel } from './cancel.js'\nimport { createState } from './state.js'\nimport { createSubs } from './subs.js'\n\nexport class PubSubAPI {\n /**\n * @param {object} config\n * @param {import('../../ipns').IPNSAPI} config.ipns\n * @param {import('../../../types').Options} config.options\n */\n constructor ({ ipns, options }) {\n this.cancel = createCancel({ ipns, options })\n this.state = createState({ ipns, options })\n this.subs = createSubs({ ipns, options })\n }\n}\n", "import { createPublish } from './publish.js'\nimport { createResolve } from './resolve.js'\nimport { PubSubAPI } from './pubsub/index.js'\n\nexport class NameAPI {\n /**\n * @param {object} config\n * @param {import('../ipns').IPNSAPI} config.ipns\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('../../types').Options} config.options\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-types/src/root').API<{}>[\"isOnline\"]} config.isOnline\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n * @param {import('ipfs-core-types/src/root').API<{}>[\"dns\"]} config.dns\n */\n constructor ({ dns, ipns, repo, codecs, peerId, isOnline, keychain, options }) {\n this.publish = createPublish({ ipns, repo, codecs, peerId, isOnline, keychain })\n this.resolve = createResolve({ dns, ipns, isOnline, options })\n this.pubsub = new PubSubAPI({ ipns, options })\n }\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { notFoundError } from 'datastore-core/errors'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport { CID } from 'multiformats/cid'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\n\nconst ERR_NOT_FOUND = notFoundError().code\n\nexport const Format = {\n default: '',\n edges: ' -> '\n}\n\n/**\n * @typedef {object} Node\n * @property {string} [name]\n * @property {CID} cid\n *\n * @typedef {object} TraversalResult\n * @property {Node} parent\n * @property {Node} node\n * @property {boolean} isDuplicate\n *\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-types/src/root').API<{}>[\"resolve\"]} config.resolve\n * @param {import('../../types').Preload} config.preload\n */\nexport function createRefs ({ repo, codecs, resolve, preload }) {\n /**\n * @type {import('ipfs-core-types/src/refs').API<{}>[\"refs\"]}\n */\n async function * refs (ipfsPath, options = {}) {\n if (options.maxDepth === 0) {\n return\n }\n\n if (options.edges && options.format && options.format !== Format.default) {\n throw new Error('Cannot set edges to true and also specify format')\n }\n\n options.format = options.edges ? Format.edges : options.format\n\n if (typeof options.maxDepth !== 'number') {\n options.maxDepth = options.recursive ? Infinity : 1\n }\n\n if (options.timeout) {\n const controller = new TimeoutController(options.timeout)\n const signals = [controller.signal]\n\n if (options.signal) {\n signals.push(options.signal)\n }\n\n options.signal = anySignal(signals)\n }\n\n /** @type {(string|CID)[]} */\n const rawPaths = Array.isArray(ipfsPath) ? ipfsPath : [ipfsPath]\n\n const paths = rawPaths.map(p => getFullPath(preload, p, options))\n\n for (const path of paths) {\n try {\n yield * refsStream(resolve, repo, codecs, path, options)\n } catch (/** @type {any} */ err) {\n yield {\n ref: '',\n err: err.message\n }\n }\n }\n }\n\n return refs\n}\n\n/**\n * @param {import('../../types').Preload} preload\n * @param {string | CID} ipfsPath\n * @param {import('ipfs-core-types/src/refs').RefsOptions} options\n */\nfunction getFullPath (preload, ipfsPath, options) {\n const {\n cid,\n path\n } = toCidAndPath(ipfsPath)\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return `/ipfs/${cid}${path || ''}`\n}\n\n/**\n * Get a stream of refs at the given path\n *\n * @param {import('ipfs-core-types/src/root').API<{}>[\"resolve\"]} resolve\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {string} path\n * @param {import('ipfs-core-types/src/refs').RefsOptions} options\n */\nasync function * refsStream (resolve, repo, codecs, path, options) {\n // Resolve to the target CID of the path\n const resPath = await resolve(path, options)\n const {\n cid\n } = toCidAndPath(resPath)\n\n const maxDepth = options.maxDepth != null ? options.maxDepth : Infinity\n const unique = options.unique || false\n\n // Traverse the DAG, converting it into a stream\n for await (const obj of objectStream(repo, codecs, cid, maxDepth, unique, options)) {\n // Root object will not have a parent\n if (!obj.parent) {\n continue\n }\n\n // Filter out duplicates (isDuplicate flag is only set if options.unique is set)\n if (obj.isDuplicate) {\n continue\n }\n\n // Format the links\n // Clients expect refs to be in the format { ref: }\n yield {\n ref: formatLink(obj.parent.cid, obj.node.cid, obj.node.name, options.format)\n }\n }\n}\n\n/**\n * Get formatted link\n *\n * @param {CID} srcCid\n * @param {CID} dstCid\n * @param {string} [linkName]\n * @param {string} [format]\n */\nfunction formatLink (srcCid, dstCid, linkName = '', format = Format.default) {\n let out = format.replace(//g, srcCid.toString())\n out = out.replace(//g, dstCid.toString())\n out = out.replace(//g, linkName)\n return out\n}\n\n/**\n * Do a depth first search of the DAG, starting from the given root cid\n *\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {CID} rootCid\n * @param {number} maxDepth\n * @param {boolean} uniqueOnly\n * @param {AbortOptions} options\n */\nasync function * objectStream (repo, codecs, rootCid, maxDepth, uniqueOnly, options) { // eslint-disable-line require-await\n const seen = new Set()\n\n /**\n * @param {Node} parent\n * @param {number} depth\n * @returns {AsyncGenerator}\n */\n async function * traverseLevel (parent, depth) {\n const nextLevelDepth = depth + 1\n\n // Check the depth\n if (nextLevelDepth > maxDepth) {\n return\n }\n\n // Get this object's links\n try {\n // Look at each link, parent and the new depth\n for await (const link of getLinks(repo, codecs, parent.cid, options)) {\n yield {\n parent: parent,\n node: link,\n isDuplicate: uniqueOnly && seen.has(link.cid.toString())\n }\n\n if (uniqueOnly) {\n seen.add(link.cid.toString())\n }\n\n yield * traverseLevel(link, nextLevelDepth)\n }\n } catch (/** @type {any} */ err) {\n if (err.code === ERR_NOT_FOUND) {\n err.message = `Could not find object with CID: ${parent.cid}`\n }\n\n throw err\n }\n }\n\n yield * traverseLevel({ cid: rootCid }, 0)\n}\n\n/**\n * Fetch a node and then get all its links\n *\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {CID} cid\n * @param {AbortOptions} options\n * @returns {AsyncGenerator<{ name: string, cid: CID }, void, undefined>}\n */\nasync function * getLinks (repo, codecs, cid, options) {\n const block = await repo.blocks.get(cid, options)\n const codec = await codecs.getCodec(cid.code)\n const value = codec.decode(block)\n const isDagPb = cid.code === dagPB.code\n /** @type {Array} */\n const base = []\n\n for (const [name, cid] of links(value, base)) {\n // special case for dag-pb - use the name of the link\n // instead of the path within the object\n if (isDagPb) {\n const match = name.match(/^Links\\/(\\d+)\\/Hash$/)\n\n if (match) {\n const index = Number(match[1])\n\n if (index < value.Links.length) {\n yield {\n name: value.Links[index].Name,\n cid\n }\n\n continue\n }\n }\n }\n\n yield {\n name,\n cid\n }\n }\n}\n\n/**\n * @param {*} source\n * @param {Array} base\n * @returns {Iterable<[string, CID]>}\n */\nconst links = function * (source, base) {\n if (source == null) {\n return\n }\n\n if (source instanceof Uint8Array) {\n return\n }\n\n for (const [key, value] of Object.entries(source)) {\n const path = [...base, key]\n\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n\n // eslint-disable-next-line max-depth\n if (cid) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n\n if (cid) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n }\n\n // ts requires a @returns annotation when a function is recursive,\n // eslint requires a return when you use a @returns annotation.\n return []\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createLocal ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/refs').API<{}>[\"local\"]}\n */\n async function * refsLocal (options = {}) {\n for await (const cid of repo.blocks.queryKeys({}, { signal: options.signal })) {\n yield { ref: cid.toString() }\n }\n }\n\n return withTimeoutOption(refsLocal)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createWantlist ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"wantlist\"]}\n */\n async function wantlist (options = {}) {\n const { bitswap } = await network.use(options)\n const list = bitswap.getWantlist()\n\n return Array.from(list).map(e => e[1].cid)\n }\n\n return withTimeoutOption(wantlist)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createWantlistForPeer ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"wantlistForPeer\"]}\n */\n async function wantlistForPeer (peerId, options = {}) {\n const { bitswap } = await network.use(options)\n const list = bitswap.wantlistForPeer(peerId)\n\n return Array.from(list).map(e => e[1].cid)\n }\n\n return withTimeoutOption(wantlistForPeer)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createUnwant ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"unwant\"]}\n */\n async function unwant (cids, options = {}) {\n const { bitswap } = await network.use(options)\n\n if (!Array.isArray(cids)) {\n cids = [cids]\n }\n\n return bitswap.unwant(cids)\n }\n\n return withTimeoutOption(unwant)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createStat ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/bitswap').API<{}>[\"stat\"]}\n */\n async function stat (options = {}) {\n /** @type {import('ipfs-bitswap').IPFSBitswap} */\n const bitswap = (await network.use(options)).bitswap\n const snapshot = bitswap.stat().snapshot\n\n return {\n provideBufLen: parseInt(snapshot.providesBufferLength.toString()),\n blocksReceived: BigInt(snapshot.blocksReceived.toString()),\n wantlist: Array.from(bitswap.getWantlist()).map(e => e[1].cid),\n peers: bitswap.peers(),\n dupBlksReceived: BigInt(snapshot.dupBlksReceived.toString()),\n dupDataReceived: BigInt(snapshot.dupDataReceived.toString()),\n dataReceived: BigInt(snapshot.dataReceived.toString()),\n blocksSent: BigInt(snapshot.blocksSent.toString()),\n dataSent: BigInt(snapshot.dataSent.toString())\n }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { createWantlist } from './wantlist.js'\nimport { createWantlistForPeer } from './wantlist-for-peer.js'\nimport { createUnwant } from './unwant.js'\nimport { createStat } from './stat.js'\n\n/**\n * @typedef {import('../../types').NetworkService} NetworkService\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\nexport class BitswapAPI {\n /**\n * @param {object} config\n * @param {NetworkService} config.network\n */\n constructor ({ network }) {\n this.wantlist = createWantlist({ network })\n this.wantlistForPeer = createWantlistForPeer({ network })\n this.unwant = createUnwant({ network })\n this.stat = createStat({ network })\n }\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss')),\n and(TCP, base('tls'), base('ws')),\n and(DNS, base('tls'), base('ws'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nconst _WebRTC = and(UDP, base('webrtc'), base('certhash'))\nexport const WebRTC = or(\n and(_WebRTC, base('p2p')),\n _WebRTC\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS,\n WebRTC\n)\n\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(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n WebRTC,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = (): Mafmt => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction): (a: string | Uint8Array | Multiaddr) => boolean {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\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\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches,\n partialMatch\n }\n}\n", "import { IPFS } from '@multiformats/mafmt'\n\n/**\n * @param {any} ma\n */\nexport function isValidMultiaddr (ma) {\n try {\n return IPFS.matches(ma)\n } catch (/** @type {any} */ err) {\n return false\n }\n}\n", "import { isValidMultiaddr } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createAdd ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"add\"]}\n */\n async function add (multiaddr, options = {}) {\n if (!isValidMultiaddr(multiaddr)) {\n throw new Error(`${multiaddr} is not a valid Multiaddr`)\n }\n\n const config = await repo.config.getAll(options)\n const boostrappers = config.Bootstrap || []\n boostrappers.push(multiaddr.toString())\n\n config.Bootstrap = Array.from(\n new Set(boostrappers)\n ).sort((a, b) => a.localeCompare(b))\n\n await repo.config.replace(config)\n\n return {\n Peers: [multiaddr]\n }\n }\n\n return withTimeoutOption(add)\n}\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\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: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\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\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\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'],\n [281, 0, 'webrtc-w3c'],\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\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\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: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport { CID } from 'multiformats/cid'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport * as Digest from 'multiformats/hashes/digest'\nimport varint from 'varint'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\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\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 uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\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\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 uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\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})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\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}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.decode.bytes)\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\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}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\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: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.decode.bytes)\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.decode.bytes)\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\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\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\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}\n\nfunction onion32bytes (str: string): Uint8Array {\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\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}\n\nfunction bytes2onion (buf: Uint8Array): string {\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", "import { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport varint from 'varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\n/**\n * string -> [[str name, str addr]... ]\n */\nexport function stringToStringTuples (str: string): string[][] {\n const tuples = []\n const parts = str.split('/').slice(1) // skip first empty elem\n if (parts.length === 1 && parts[0] === '') {\n return []\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([part])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n tuples.push([\n part,\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 cleanPath(parts.slice(p).join('/'))\n ])\n break\n }\n\n tuples.push([part, parts[p]])\n }\n\n return tuples\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nexport function stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[str name, str addr]... ] -> [[int code, Uint8Array]... ]\n */\nexport function stringTuplesToTuples (tuples: Array): Tuple[] {\n return tuples.map((tup) => {\n if (!Array.isArray(tup)) {\n tup = [tup]\n }\n const proto = protoFromTuple(tup)\n if (tup.length > 1) {\n return [proto.code, convertToBytes(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * Convert tuples to string tuples\n *\n * [[int code, Uint8Array]... ] -> [[int code, str addr]... ]\n */\nexport function tuplesToStringTuples (tuples: Tuple[]): StringTuple[] {\n return tuples.map(tup => {\n const proto = protoFromTuple(tup)\n if (tup[1] != null) {\n return [proto.code, convertToString(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return fromBytes(uint8ArrayConcat(tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n })))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nexport function sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr)\n return size + (varint.decode.bytes ?? 0)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\n/**\n * Uint8Array -> String\n */\nexport function bytesToString (buf: Uint8Array): string {\n const a = bytesToTuples(buf)\n const b = tuplesToStringTuples(a)\n return stringTuplesToString(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function stringToBytes (str: string): Uint8Array {\n str = cleanPath(str)\n const a = stringToStringTuples(str)\n const b = stringTuplesToTuples(a)\n\n return tuplesToBytes(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function fromString (str: string): Uint8Array {\n return stringToBytes(str)\n}\n\n/**\n * Uint8Array -> Uint8Array\n */\nexport function fromBytes (buf: Uint8Array): Uint8Array {\n const err = validateBytes(buf)\n if (err != null) {\n throw err\n }\n return Uint8Array.from(buf) // copy\n}\n\nexport function validateBytes (buf: Uint8Array): Error | undefined {\n try {\n bytesToTuples(buf) // try to parse. will throw if breaks\n } catch (err: any) {\n return err\n }\n}\n\nexport function isValidBytes (buf: Uint8Array): boolean {\n return validateBytes(buf) === undefined\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n\nexport function protoFromTuple (tup: any[]): Protocol {\n const proto = getProtocol(tup[0])\n return proto\n}\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\nimport * as codec from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport varint from 'varint'\nimport { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport errCode from 'err-code'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A Resolver is a function that takes a {@link Multiaddr} and resolves it into one\n * or more string representations of that {@link Multiaddr}.\n */\nexport interface Resolver { (addr: Multiaddr, options?: AbortOptions): Promise }\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString: () => string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON: () => string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions: () => MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos: () => Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes: () => number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames: () => string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples: () => Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples: () => StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate: (addr: MultiaddrInput) => Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate: (addr: Multiaddr | string) => Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode: (code: number) => Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId: () => string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath: () => string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals: (addr: { bytes: Uint8Array }) => boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve: (options?: AbortOptions) => Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress: () => NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress: (addr?: Multiaddr) => boolean\n}\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 */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\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: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\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 DefaultMultiaddr('/' + [ip, host, transport, addr.port].join('/'))\n}\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: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\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: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass DefaultMultiaddr implements Multiaddr {\n public bytes: Uint8Array\n #string?: string\n #tuples?: Tuple[]\n #stringTuples?: StringTuple[]\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n if (addr instanceof Uint8Array) {\n this.bytes = codec.fromBytes(addr)\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 this.bytes = codec.fromString(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n this.bytes = codec.fromBytes(addr.bytes) // validate + copy buffer\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = codec.bytesToString(this.bytes)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\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\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\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\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\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\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\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.protoCodes().map(code => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n const codes: number[] = []\n const buf = this.bytes\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n const size = codec.sizeForAddr(p, buf.slice(i + n))\n\n i += (size + n)\n codes.push(code)\n }\n\n return codes\n }\n\n protoNames (): string[] {\n return this.protos().map(proto => proto.name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n if (this.#tuples == null) {\n this.#tuples = codec.bytesToTuples(this.bytes)\n }\n\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n if (this.#stringTuples == null) {\n this.#stringTuples = codec.tuplesToStringTuples(this.tuples())\n }\n\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new DefaultMultiaddr(addr)\n return new DefaultMultiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\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 DefaultMultiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new DefaultMultiaddr(codec.tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n const tuples = this.stringTuples().filter((tuple) => {\n if (tuple[0] === names.ipfs.code) {\n return true\n }\n return false\n })\n\n // Get the last ipfs tuple ['ipfs', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\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\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n let path = null\n try {\n path = this.stringTuples().filter((tuple) => {\n const proto = getProtocol(tuple[0])\n if (proto.path === true) {\n return true\n }\n return false\n })[0][1]\n\n if (path == null) {\n path = null\n }\n } catch {\n path = null\n }\n return path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: AbortOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const addresses = await resolver(this, options)\n return addresses.map((a) => new DefaultMultiaddr(a))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\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\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\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 /**\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] (): string {\n return `Multiaddr(${codec.bytesToString(this.bytes)})`\n }\n}\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?: MultiaddrInput): Multiaddr {\n return new DefaultMultiaddr(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createClear ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"clear\"]}\n */\n async function clear (options = {}) {\n const config = await repo.config.getAll(options)\n const removed = config.Bootstrap || []\n config.Bootstrap = []\n\n await repo.config.replace(config)\n\n return { Peers: removed.map(ma => multiaddr(ma)) }\n }\n\n return withTimeoutOption(clear)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createList ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"list\"]}\n */\n async function list (options = {}) {\n /** @type {string[]|null} */\n const peers = (await repo.config.get('Bootstrap', options))\n return { Peers: (peers || []).map(ma => multiaddr(ma)) }\n }\n\n return withTimeoutOption(list)\n}\n", "\nexport default () => ({\n Addresses: {\n Swarm: [\n ],\n Announce: [],\n NoAnnounce: [],\n API: '',\n Gateway: '',\n RPC: '',\n Delegates: [\n '/dns4/node0.delegate.ipfs.io/tcp/443/https',\n '/dns4/node1.delegate.ipfs.io/tcp/443/https',\n '/dns4/node2.delegate.ipfs.io/tcp/443/https',\n '/dns4/node3.delegate.ipfs.io/tcp/443/https'\n ]\n },\n Discovery: {\n MDNS: {\n Enabled: false,\n Interval: 10\n },\n webRTCStar: {\n Enabled: true\n }\n },\n Bootstrap: [\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa',\n '/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt',\n '/dns4/node0.preload.ipfs.io/tcp/443/wss/p2p/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic',\n '/dns4/node1.preload.ipfs.io/tcp/443/wss/p2p/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6',\n '/dns4/node2.preload.ipfs.io/tcp/443/wss/p2p/QmV7gnbW5VTcJ3oyM2Xk1rdFBJ3kTkvxc87UFGsun29STS',\n '/dns4/node3.preload.ipfs.io/tcp/443/wss/p2p/QmY7JB6MQXhxHvq7dBDh4HpbH29v4yE9JRadAVpndvzySN'\n ],\n Pubsub: {\n Enabled: true\n },\n Swarm: {\n ConnMgr: {\n LowWater: 5,\n HighWater: 20\n },\n DisableNatPortMap: true\n },\n Routing: {\n Type: 'dhtclient'\n }\n})\n", "import defaultConfig from 'ipfs-core-config/config'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createReset ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"reset\"]}\n */\n async function reset (options = {}) {\n const config = await repo.config.getAll(options)\n config.Bootstrap = defaultConfig().Bootstrap\n\n await repo.config.replace(config)\n\n return {\n Peers: defaultConfig().Bootstrap.map(ma => multiaddr(ma))\n }\n }\n\n return withTimeoutOption(reset)\n}\n", "import { isValidMultiaddr } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createRm ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/bootstrap').API<{}>[\"rm\"]}\n */\n async function rm (multiaddr, options = {}) {\n if (!isValidMultiaddr(multiaddr)) {\n throw new Error(`${multiaddr} is not a valid Multiaddr`)\n }\n\n const config = await repo.config.getAll(options)\n config.Bootstrap = (config.Bootstrap || []).filter(ma => ma.toString() !== multiaddr.toString())\n\n await repo.config.replace(config)\n\n return { Peers: [multiaddr] }\n }\n\n return withTimeoutOption(rm)\n}\n", "import { createAdd } from './add.js'\nimport { createClear } from './clear.js'\nimport { createList } from './list.js'\nimport { createReset } from './reset.js'\nimport { createRm } from './rm.js'\nexport class BootstrapAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ repo }) {\n this.add = createAdd({ repo })\n this.list = createList({ repo })\n this.rm = createRm({ repo })\n this.clear = createClear({ repo })\n this.reset = createReset({ repo })\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').Preload} config.preload\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createGet ({ preload, repo }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"get\"]}\n */\n async function get (cid, options = {}) { // eslint-disable-line require-await\n if (options.preload !== false) {\n preload(cid)\n }\n\n return repo.blocks.get(cid, options)\n }\n\n return withTimeoutOption(get)\n}\n", "import { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n */\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n *\n */\nexport function createPut ({ codecs, hashers, repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"put\"]}\n */\n async function put (block, options = {}) {\n const release = options.pin ? await repo.gcLock.readLock() : null\n\n try {\n const cidVersion = options.version != null ? options.version : 0\n const codecName = options.format || (cidVersion === 0 ? 'dag-pb' : 'raw')\n\n const hasher = await hashers.getHasher(options.mhtype || 'sha2-256')\n const hash = await hasher.digest(block)\n const codec = await codecs.getCodec(codecName)\n const cid = CID.create(cidVersion, codec.code, hash)\n\n await repo.blocks.put(cid, block, {\n signal: options.signal\n })\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n if (options.pin === true) {\n await repo.pins.pinRecursively(cid, {\n signal: options.signal\n })\n }\n\n return cid\n } finally {\n if (release) {\n release()\n }\n }\n }\n\n return withTimeoutOption(put)\n}\n", "import errCode from 'err-code'\nimport parallel from 'it-parallel'\nimport map from 'it-map'\nimport filter from 'it-filter'\nimport { pipe } from 'it-pipe'\nimport { cleanCid } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst BLOCK_RM_CONCURRENCY = 8\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createRm ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"rm\"]}\n */\n async function * rm (cids, options = {}) {\n if (!Array.isArray(cids)) {\n cids = [cids]\n }\n\n // We need to take a write lock here to ensure that adding and removing\n // blocks are exclusive operations\n const release = await repo.gcLock.writeLock()\n\n try {\n yield * pipe(\n cids,\n source => map(source, cid => {\n return async () => {\n cid = cleanCid(cid)\n\n /** @type {import('ipfs-core-types/src/block').RmResult} */\n const result = { cid }\n\n try {\n const has = await repo.blocks.has(cid)\n\n if (!has) {\n throw errCode(new Error('block not found'), 'ERR_BLOCK_NOT_FOUND')\n }\n\n await repo.blocks.delete(cid)\n } catch (/** @type {any} */ err) {\n if (!options.force) {\n err.message = `cannot remove ${cid}: ${err.message}`\n result.error = err\n }\n }\n\n return result\n }\n }),\n source => parallel(source, { concurrency: BLOCK_RM_CONCURRENCY }),\n source => filter(source, () => !options.quiet)\n )\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(rm)\n}\n", "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", "/**\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 */\n\nimport defer from 'p-defer'\n\ninterface Operation {\n done: boolean\n ok: boolean\n err: Error\n value: T\n}\n\nconst CustomEvent = globalThis.CustomEvent ?? Event\n\nexport interface ParallelOptions {\n /**\n * How many jobs to execute in parallel (default: )\n */\n concurrency?: number\n ordered?: boolean\n}\n\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: Iterable<() => Promise> | AsyncIterable<() => Promise>, options: ParallelOptions = {}): AsyncGenerator {\n let concurrency = options.concurrency ?? Infinity\n\n if (concurrency < 1) {\n concurrency = Infinity\n }\n\n const ordered = options.ordered == null ? false : options.ordered\n const emitter = new EventTarget()\n\n const ops: Array> = []\n let slotAvailable = defer()\n let resultAvailable = defer()\n let sourceFinished = false\n let sourceErr: Error | undefined\n let opErred = false\n\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve()\n })\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\n if (opErred) {\n break\n }\n\n const op: any = {\n done: false\n }\n ops.push(op)\n\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\n sourceFinished = true\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n } catch (err: any) {\n sourceErr = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }\n })\n\n function valuesAvailable (): boolean {\n if (ordered) {\n return ops[0]?.done\n }\n\n return Boolean(ops.find(op => op.done))\n }\n\n function * yieldOrderedValues (): Generator {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0]\n ops.shift()\n\n if (op.ok) {\n yield op.value\n } else {\n // allow the source to exit\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n\n function * yieldUnOrderedValues (): Generator {\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\n if (op.ok) {\n yield op.value\n } else {\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n }\n }\n\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer()\n await resultAvailable.promise\n }\n\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr\n }\n\n if (ordered) {\n yield * yieldOrderedValues()\n } else {\n yield * yieldUnOrderedValues()\n }\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", "/**\n * Takes an (async) iterable and returns one with each item mapped by the passed\n * function\n */\nexport default async function * map (source: AsyncIterable | Iterable, func: (val: I) => O | Promise): AsyncGenerator {\n for await (const val of source) {\n yield func(val)\n }\n}\n", "\n/**\n * Filters the passed (async) iterable by using the filter function\n */\nexport default async function * filter (source: AsyncIterable | Iterable, fn: (val: T) => boolean | Promise): AsyncGenerator {\n for await (const entry of source) {\n if (await fn(entry)) {\n yield entry\n }\n }\n}\n", "import { CID } from 'multiformats/cid'\n\n/**\n * @param {string|Uint8Array|CID} cid\n */\nexport function cleanCid (cid) {\n if (cid instanceof Uint8Array) {\n return CID.decode(cid)\n }\n\n return CID.parse(cid.toString())\n}\n", "import { cleanCid } from './utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\n\nexport function createStat ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/block').API<{}>[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n cid = cleanCid(cid)\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n const block = await repo.blocks.get(cid)\n\n return { cid, size: block.length }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { createGet } from './get.js'\nimport { createPut } from './put.js'\nimport { createRm } from './rm.js'\nimport { createStat } from './stat.js'\n\n/**\n * @typedef {import('../../types').Preload} Preload\n */\n\nexport class BlockAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-core-utils/src/multihashes').Multihashes} config.hashers\n * @param {import('ipfs-core-utils/src/multicodecs').Multicodecs} config.codecs\n * @param {Preload} config.preload\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ codecs, hashers, preload, repo }) {\n this.get = createGet({ preload, repo })\n this.put = createPut({ codecs, hashers, preload, repo })\n this.rm = createRm({ repo })\n this.stat = createStat({ preload, repo })\n }\n}\n", "import errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport blobToIt from 'blob-to-it'\nimport itPeekable from 'it-peekable'\nimport all from 'it-all'\nimport map from 'it-map'\nimport {\n isBytes,\n isReadableStream,\n isBlob\n} from './utils.js'\n\n/**\n * @template T\n * @param {T} thing\n */\nasync function * toAsyncIterable (thing) {\n yield thing\n}\n\n/**\n * @param {import('ipfs-core-types/src/utils').ToContent} input\n */\nexport async function normaliseContent (input) {\n // Bytes | String\n if (isBytes(input)) {\n return toAsyncIterable(toBytes(input))\n }\n\n if (typeof input === 'string' || input instanceof String) {\n return toAsyncIterable(toBytes(input.toString()))\n }\n\n // Blob\n if (isBlob(input)) {\n return blobToIt(input)\n }\n\n // Browser stream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // (Async)Iterator\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n /** @type {any} peekable */\n const peekable = itPeekable(input)\n\n /** @type {any} value */\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n return toAsyncIterable(new Uint8Array(0))\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n if (Number.isInteger(value)) {\n return toAsyncIterable(Uint8Array.from(await all(peekable)))\n }\n\n // (Async)Iterable\n if (isBytes(value) || typeof value === 'string' || value instanceof String) {\n return map(peekable, toBytes)\n }\n }\n\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {ArrayBuffer | ArrayBufferView | string | InstanceType | number[]} chunk\n */\nfunction toBytes (chunk) {\n if (chunk instanceof Uint8Array) {\n return chunk\n }\n\n if (ArrayBuffer.isView(chunk)) {\n return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n }\n\n if (chunk instanceof ArrayBuffer) {\n return new Uint8Array(chunk)\n }\n\n if (Array.isArray(chunk)) {\n return Uint8Array.from(chunk)\n }\n\n return uint8ArrayFromString(chunk.toString())\n}\n", "/**\n * @packageDocumentation\n *\n * Allows treating a browser readable stream as an async iterator.\n *\n * @example\n *\n * ```javascript\n * import toIt from 'browser-readablestream-to-it'\n * import all from 'it-all'\n *\n * const content = [0, 1, 2, 3, 4]\n *\n * const stream = new ReadableStream({\n * start(controller) {\n * for (let i = 0; i < content.length; i++) {\n * controller.enqueue(content[i])\n * }\n *\n * controller.close()\n * }\n * })\n *\n * const arr = await all(toIt(stream))\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * ## preventCancel\n *\n * By default a readable stream will have [.cancel](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/cancel) called on it once it has ended or\n * reading has stopped prematurely.\n *\n * To prevent this behaviour, pass `preventCancel: true` as an option:\n *\n * ```javascript\n * const arr = await all(toIt(stream, { preventCancel: true }))\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\n\nexport interface BrowserReadableStreamToItOptions {\n preventCancel?: boolean\n}\n\n/**\n * Turns a browser readable stream into an async iterable. Async iteration over\n * returned iterable will lock give stream, preventing any other consumer from\n * acquiring a reader. The lock will be released if iteration loop is broken. To\n * prevent stream cancelling optional `{ preventCancel: true }` could be passed\n * as a second argument.\n */\nexport default async function * browserReadableStreamToIt (stream: ReadableStream, options: BrowserReadableStreamToItOptions = {}): AsyncGenerator {\n const reader = stream.getReader()\n\n try {\n while (true) {\n const result = await reader.read()\n\n if (result.done) {\n return\n }\n\n yield result.value\n }\n } finally {\n if (options.preventCancel !== true) {\n await reader.cancel()\n }\n\n reader.releaseLock()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Allows reading Blob contents as an async iterator.\n *\n * @example\n *\n * ```javascript\n * import toIt from 'blob-to-it'\n * import all from 'it-all'\n *\n * const content = [ Uint8Array.from([0, 1, 2, 3, 4]) ]\n * const blob = new Blob(content)\n * const arr = await all(toIt(blob))\n *\n * console.info(arr) // [ [ 0, 1, 2, 3, 4 ] ]\n * ```\n */\n\nimport browserReadableStreamToIt from 'browser-readablestream-to-it'\n\nexport default function blobToIt (blob: Blob): AsyncIterable {\n if (typeof blob.stream === 'function') {\n return browserReadableStreamToIt(blob.stream())\n }\n\n // firefox < 69 does not support blob.stream()\n // @ts-expect-error - response.body is optional, but in practice it's a stream.\n return browserReadableStreamToIt(new Response(blob).body)\n}\n", "\ninterface Peek {\n peek: () => IteratorResult\n}\n\ninterface AsyncPeek {\n peek: () => Promise>\n}\n\ninterface Push {\n push: (value: T) => void\n}\n\ntype Peekable = Iterable & Peek & Push & Iterator\n\ntype AsyncPeekable = AsyncIterable & AsyncPeek & Push & AsyncIterator\n\nexport default function peekableIterator | AsyncIterable> (iterable: I): I extends Iterable\n ? Peekable\n : I extends AsyncIterable\n ? AsyncPeekable\n : never {\n // @ts-expect-error\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error\n : [iterable[Symbol.iterator](), Symbol.iterator]\n\n const queue: any[] = []\n\n // @ts-expect-error\n return {\n peek: () => {\n return iterator.next()\n },\n push: (value: any) => {\n queue.push(value)\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n }\n }\n\n return iterator.next()\n },\n [symbol] () {\n return this\n }\n }\n}\n", "\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nexport default async function all (source: AsyncIterable | Iterable): Promise {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n", "/**\n * @param {any} obj\n * @returns {obj is ArrayBufferView|ArrayBuffer}\n */\nexport function isBytes (obj) {\n return ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer\n}\n\n/**\n * @param {any} obj\n * @returns {obj is globalThis.Blob}\n */\nexport function isBlob (obj) {\n return obj.constructor &&\n (obj.constructor.name === 'Blob' || obj.constructor.name === 'File') &&\n typeof obj.stream === 'function'\n}\n\n/**\n * An object with a path or content property\n *\n * @param {any} obj\n * @returns {obj is import('ipfs-core-types/src/utils').ImportCandidate}\n */\nexport function isFileObject (obj) {\n return typeof obj === 'object' && (obj.path || obj.content)\n}\n\n/**\n * @param {any} value\n * @returns {value is ReadableStream}\n */\nexport const isReadableStream = (value) =>\n value && typeof value.getReader === 'function'\n", "import errCode from 'err-code'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport itPeekable from 'it-peekable'\nimport {\n isBytes,\n isBlob,\n isReadableStream,\n isFileObject\n} from './utils.js'\nimport {\n parseMtime,\n parseMode\n} from 'ipfs-unixfs'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ToContent} ToContent\n * @typedef {import('ipfs-unixfs-importer').ImportCandidate} ImporterImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidate} ImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * @param {ImportCandidate} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\n// eslint-disable-next-line complexity\nexport async function * normaliseCandidateSingle (input, normaliseContent) {\n if (input === null || input === undefined) {\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n }\n\n // String\n if (typeof input === 'string' || input instanceof String) {\n yield toFileObject(input.toString(), normaliseContent)\n return\n }\n\n // Uint8Array|ArrayBuffer|TypedArray\n // Blob|File\n if (isBytes(input) || isBlob(input)) {\n yield toFileObject(input, normaliseContent)\n return\n }\n\n // Browser ReadableStream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // Iterable\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n const peekable = itPeekable(input)\n\n /** @type {any} value **/\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n yield { content: [] }\n return\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n // (Async)Iterable\n // (Async)Iterable\n if (Number.isInteger(value) || isBytes(value) || typeof value === 'string' || value instanceof String) {\n yield toFileObject(peekable, normaliseContent)\n return\n }\n\n throw errCode(new Error('Unexpected input: multiple items passed - if you are using ipfs.add, please use ipfs.addAll instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n // { path, content: ? }\n // Note: Detected _after_ (Async)Iterable because Node.js fs.ReadStreams have a\n // `path` property that passes this check.\n if (isFileObject(input)) {\n yield toFileObject(input, normaliseContent)\n return\n }\n\n throw errCode(new Error('Unexpected input: cannot convert \"' + typeof input + '\" into ImportCandidate'), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {ImportCandidate} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\nasync function toFileObject (input, normaliseContent) {\n // @ts-expect-error - Those properties don't exist on most input types\n const { path, mode, mtime, content } = input\n\n /** @type {ImporterImportCandidate} */\n const file = {\n path: path || '',\n mode: parseMode(mode),\n mtime: parseMtime(mtime)\n }\n\n if (content) {\n file.content = await normaliseContent(content)\n } else if (!path) { // Not already a file object with path or content prop\n // @ts-expect-error - input still can be different ToContent\n file.content = await normaliseContent(input)\n }\n\n return file\n}\n", "import { normaliseContent } from './normalise-content.js'\nimport { normaliseCandidateSingle } from './normalise-candidate-single.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidate} ImportCandidate\n */\n\n/**\n * Transforms any of the `ipfs.add` input types into\n *\n * ```\n * AsyncIterable<{ path, mode, mtime, content: AsyncIterable }>\n * ```\n *\n * See https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options\n *\n * @param {ImportCandidate} input\n */\nexport function normaliseInput (input) {\n return normaliseCandidateSingle(input, normaliseContent)\n}\n", "import last from 'it-last'\nimport { normaliseInput } from 'ipfs-core-utils/files/normalise-input-single'\n\n/**\n * @param {object} context\n * @param {import('ipfs-core-types/src/root').API<{}>[\"addAll\"]} context.addAll\n */\nexport function createAdd ({ addAll }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"add\"]}\n */\n async function add (entry, options = {}) {\n // @ts-expect-error TODO: https://github.com/ipfs/js-ipfs/issues/3290\n const result = await last(addAll(normaliseInput(entry), options))\n // Note this should never happen as `addAll` should yield at least one item\n // but to satisfy type checker we perfom this check and for good measure\n // throw an error in case it does happen.\n if (result == null) {\n throw Error('Failed to add a file, if you see this please report a bug')\n }\n\n return result\n }\n\n return add\n}\n", "/**\n * Takes an (async) iterable that emits things and returns an async iterable that\n * emits those things in fixed-sized batches\n */\nexport default async function * batch (source: AsyncIterable | Iterable, size: number = 1): AsyncGenerator {\n let things: T[] = []\n\n if (size < 1) {\n size = 1\n }\n\n for await (const thing of source) {\n things.push(thing)\n\n while (things.length >= size) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n }\n\n while (things.length > 0) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n}\n", "import batch from 'it-batch'\n\ninterface Success {\n ok: true\n value: T\n}\n\ninterface Failure {\n ok: false\n err: Error\n}\n\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 * parallelBatch (source: AsyncIterable<() => Promise> | Iterable<() => Promise>, size: number = 1): AsyncGenerator {\n for await (const tasks of batch(source, size)) {\n const things: Array | Failure>> = tasks.map(\n async (p: () => Promise) => {\n return await p().then(value => ({ ok: true, value }), err => ({ ok: false, err }))\n })\n\n for (let i = 0; i < things.length; i++) {\n const result = await things[i]\n\n if (result.ok) {\n yield result.value\n } else {\n throw result.err\n }\n }\n }\n}\n", "import { bytes } from 'multiformats'\nimport { from } from 'multiformats/hashes/hasher'\n// @ts-expect-error no types\nimport mur from 'murmurhash3js-revisited'\n\n/**\n * @param {number} number\n * @returns {Uint8Array}\n */\nfunction fromNumberTo32BitBuf (number) {\n const bytes = new Array(4)\n for (let i = 0; i < 4; i++) {\n bytes[i] = number & 0xff\n number = number >> 8\n }\n return new Uint8Array(bytes)\n}\n\nexport const murmur332 = from({\n name: 'murmur3-32',\n code: 0x23,\n encode: (input) => fromNumberTo32BitBuf(mur.x86.hash32(input))\n})\n\nexport const murmur3128 = from({\n name: 'murmur3-128',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input))\n})\n\n// A special-use 0x22 that truncates 64 bits, specifically for use in the UnixFS HAMT\nexport const murmur364 = from({\n name: 'murmur3-x64-64',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input)).subarray(0, 8)\n})\n", "import mergeOptions from 'merge-options'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { murmur3128 } from '@multiformats/murmur3'\n\n/**\n * @param {Uint8Array} buf\n */\nasync function hamtHashFn (buf) {\n return (await murmur3128.encode(buf))\n // Murmur3 outputs 128 bit but, accidentally, IPFS Go's\n // implementation only uses the first 64, so we must do the same\n // for parity..\n .slice(0, 8)\n // Invert buffer because that's how Go impl does it\n .reverse()\n}\n\n/**\n * @typedef {import('./types').UserImporterOptions} UserImporterOptions\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n */\n\n/**\n * @type {ImporterOptions}\n */\nconst defaultOptions = {\n chunker: 'fixed',\n strategy: 'balanced', // 'flat', 'trickle'\n rawLeaves: false,\n onlyHash: false,\n reduceSingleLeafToSelf: true,\n hasher: sha256,\n leafType: 'file', // 'raw'\n cidVersion: 0,\n progress: () => () => {},\n shardSplitThreshold: 1000,\n fileImportConcurrency: 50,\n blockWriteConcurrency: 10,\n minChunkSize: 262144,\n maxChunkSize: 262144,\n avgChunkSize: 262144,\n window: 16,\n // FIXME: This number is too big for JavaScript\n // https://github.com/ipfs/go-ipfs-chunker/blob/d0125832512163708c0804a3cda060e21acddae4/rabin.go#L11\n polynomial: 17437180132763653, // eslint-disable-line no-loss-of-precision\n maxChildrenPerNode: 174,\n layerRepeat: 4,\n wrapWithDirectory: false,\n recursive: false,\n hidden: false,\n timeout: undefined,\n hamtHashFn,\n hamtHashCode: 0x22,\n hamtBucketBits: 8\n}\n\n/**\n * @param {UserImporterOptions} options\n * @returns {ImporterOptions}\n */\nexport default (options = {}) => {\n const defaults = mergeOptions.bind({ ignoreUndefined: true })\n return defaults(defaultOptions, options)\n}\n", "import { CID } from 'multiformats/cid'\nimport * as dagPb from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * @param {Uint8Array} buffer\n * @param {import('interface-blockstore').Blockstore} blockstore\n * @param {import('../types').PersistOptions} options\n */\nconst persist = async (buffer, blockstore, options) => {\n if (!options.codec) {\n options.codec = dagPb\n }\n\n if (!options.hasher) {\n options.hasher = sha256\n }\n\n if (options.cidVersion === undefined) {\n options.cidVersion = 1\n }\n\n if (options.codec === dagPb && options.hasher !== sha256) {\n options.cidVersion = 1\n }\n\n const multihash = await options.hasher.digest(buffer)\n const cid = CID.create(options.cidVersion, options.codec.code, multihash)\n\n if (!options.onlyHash) {\n await blockstore.put(cid, buffer, {\n signal: options.signal\n })\n }\n\n return cid\n}\n\nexport default persist\n", "import { UnixFS } from 'ipfs-unixfs'\nimport persist from '../utils/persist.js'\nimport { encode, prepare } from '@ipld/dag-pb'\n\n/**\n * @typedef {import('../types').Directory} Directory\n */\n\n/**\n * @type {import('../types').UnixFSV1DagBuilder}\n */\nconst dirBuilder = async (item, blockstore, options) => {\n const unixfs = new UnixFS({\n type: 'directory',\n mtime: item.mtime,\n mode: item.mode\n })\n\n const buffer = encode(prepare({ Data: unixfs.marshal() }))\n const cid = await persist(buffer, blockstore, options)\n const path = item.path\n\n return {\n cid,\n path,\n unixfs,\n size: buffer.length\n }\n}\n\nexport default dirBuilder\n", "import errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport persist from '../../utils/persist.js'\nimport { encode, prepare } from '@ipld/dag-pb'\nimport parallelBatch from 'it-parallel-batch'\nimport * as rawCodec from 'multiformats/codecs/raw'\nimport * as dagPb from '@ipld/dag-pb'\n\nimport dagFlat from './flat.js'\nimport dagBalanced from './balanced.js'\nimport dagTrickle from './trickle.js'\nimport bufferImporterFn from './buffer-importer.js'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../../types').File} File\n * @typedef {import('../../types').ImporterOptions} ImporterOptions\n * @typedef {import('../../types').Reducer} Reducer\n * @typedef {import('../../types').DAGBuilder} DAGBuilder\n * @typedef {import('../../types').FileDAGBuilder} FileDAGBuilder\n */\n\n/**\n * @type {{ [key: string]: FileDAGBuilder}}\n */\nconst dagBuilders = {\n flat: dagFlat,\n balanced: dagBalanced,\n trickle: dagTrickle\n}\n\n/**\n * @param {File} file\n * @param {Blockstore} blockstore\n * @param {ImporterOptions} options\n */\nasync function * buildFileBatch (file, blockstore, options) {\n let count = -1\n let previous\n let bufferImporter\n\n if (typeof options.bufferImporter === 'function') {\n bufferImporter = options.bufferImporter\n } else {\n bufferImporter = bufferImporterFn\n }\n\n for await (const entry of parallelBatch(bufferImporter(file, blockstore, options), options.blockWriteConcurrency)) {\n count++\n\n if (count === 0) {\n previous = entry\n continue\n } else if (count === 1 && previous) {\n yield previous\n previous = null\n }\n\n yield entry\n }\n\n if (previous) {\n previous.single = true\n yield previous\n }\n}\n\n/**\n * @param {File} file\n * @param {Blockstore} blockstore\n * @param {ImporterOptions} options\n */\nconst reduce = (file, blockstore, options) => {\n /**\n * @type {Reducer}\n */\n async function reducer (leaves) {\n if (leaves.length === 1 && leaves[0].single && options.reduceSingleLeafToSelf) {\n const leaf = leaves[0]\n\n if (file.mtime !== undefined || file.mode !== undefined) {\n // only one leaf node which is a buffer - we have metadata so convert it into a\n // UnixFS entry otherwise we'll have nowhere to store the metadata\n let buffer = await blockstore.get(leaf.cid)\n\n leaf.unixfs = new UnixFS({\n type: 'file',\n mtime: file.mtime,\n mode: file.mode,\n data: buffer\n })\n\n buffer = encode(prepare({ Data: leaf.unixfs.marshal() }))\n\n // // TODO vmx 2021-03-26: This is what the original code does, it checks\n // // the multihash of the original leaf node and uses then the same\n // // hasher. i wonder if that's really needed or if we could just use\n // // the hasher from `options.hasher` instead.\n // const multihash = mh.decode(leaf.cid.multihash.bytes)\n // let hasher\n // switch multihash {\n // case sha256.code {\n // hasher = sha256\n // break;\n // }\n // //case identity.code {\n // // hasher = identity\n // // break;\n // //}\n // default: {\n // throw new Error(`Unsupported hasher \"${multihash}\"`)\n // }\n // }\n leaf.cid = await persist(buffer, blockstore, {\n ...options,\n codec: dagPb,\n hasher: options.hasher,\n cidVersion: options.cidVersion\n })\n leaf.size = buffer.length\n }\n\n return {\n cid: leaf.cid,\n path: file.path,\n unixfs: leaf.unixfs,\n size: leaf.size\n }\n }\n\n // create a parent node and add all the leaves\n const f = new UnixFS({\n type: 'file',\n mtime: file.mtime,\n mode: file.mode\n })\n\n const links = leaves\n .filter(leaf => {\n if (leaf.cid.code === rawCodec.code && leaf.size) {\n return true\n }\n\n if (leaf.unixfs && !leaf.unixfs.data && leaf.unixfs.fileSize()) {\n return true\n }\n\n return Boolean(leaf.unixfs && leaf.unixfs.data && leaf.unixfs.data.length)\n })\n .map((leaf) => {\n if (leaf.cid.code === rawCodec.code) {\n // node is a leaf buffer\n f.addBlockSize(leaf.size)\n\n return {\n Name: '',\n Tsize: leaf.size,\n Hash: leaf.cid\n }\n }\n\n if (!leaf.unixfs || !leaf.unixfs.data) {\n // node is an intermediate node\n f.addBlockSize((leaf.unixfs && leaf.unixfs.fileSize()) || 0)\n } else {\n // node is a unixfs 'file' leaf node\n f.addBlockSize(leaf.unixfs.data.length)\n }\n\n return {\n Name: '',\n Tsize: leaf.size,\n Hash: leaf.cid\n }\n })\n\n const node = {\n Data: f.marshal(),\n Links: links\n }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, blockstore, options)\n\n return {\n cid,\n path: file.path,\n unixfs: f,\n size: buffer.length + node.Links.reduce((acc, curr) => acc + curr.Tsize, 0)\n }\n }\n\n return reducer\n}\n\n/**\n * @type {import('../../types').UnixFSV1DagBuilder}\n */\nfunction fileBuilder (file, block, options) {\n const dagBuilder = dagBuilders[options.strategy]\n\n if (!dagBuilder) {\n throw errCode(new Error(`Unknown importer build strategy name: ${options.strategy}`), 'ERR_BAD_STRATEGY')\n }\n\n return dagBuilder(buildFileBatch(file, block, options), reduce(file, block, options), options)\n}\n\nexport default fileBuilder\n", "import all from 'it-all'\n\n/**\n * @type {import('../../types').FileDAGBuilder}\n */\nasync function flat (source, reduce) {\n return reduce(await all(source))\n}\n\nexport default flat\n", "import batch from 'it-batch'\n\n/**\n * @typedef {import('../../types').FileDAGBuilder} FileDAGBuilder\n */\n\n/**\n * @type {FileDAGBuilder}\n */\nfunction balanced (source, reduce, options) {\n return reduceToParents(source, reduce, options)\n}\n\n/**\n * @type {FileDAGBuilder}\n */\nasync function reduceToParents (source, reduce, options) {\n const roots = []\n\n for await (const chunked of batch(source, options.maxChildrenPerNode)) {\n roots.push(await reduce(chunked))\n }\n\n if (roots.length > 1) {\n return reduceToParents(roots, reduce, options)\n }\n\n return roots[0]\n}\n\nexport default balanced\n", "import batch from 'it-batch'\n\n/**\n * @typedef {import('ipfs-unixfs').UnixFS} UnixFS\n * @typedef {import('../../types').ImporterOptions} ImporterOptions\n * @typedef {import('../../types').InProgressImportResult} InProgressImportResult\n * @typedef {import('../../types').TrickleDagNode} TrickleDagNode\n * @typedef {import('../../types').Reducer} Reducer\n * @typedef {import('../../types').FileDAGBuilder} FileDAGBuilder\n */\n\n/**\n * @type {FileDAGBuilder}\n */\nasync function trickleStream (source, reduce, options) {\n const root = new Root(options.layerRepeat)\n let iteration = 0\n let maxDepth = 1\n\n /** @type {SubTree} */\n let subTree = root\n\n for await (const layer of batch(source, options.maxChildrenPerNode)) {\n if (subTree.isFull()) {\n if (subTree !== root) {\n root.addChild(await subTree.reduce(reduce))\n }\n\n if (iteration && iteration % options.layerRepeat === 0) {\n maxDepth++\n }\n\n subTree = new SubTree(maxDepth, options.layerRepeat, iteration)\n\n iteration++\n }\n\n subTree.append(layer)\n }\n\n if (subTree && subTree !== root) {\n root.addChild(await subTree.reduce(reduce))\n }\n\n return root.reduce(reduce)\n}\n\nexport default trickleStream\n\nclass SubTree {\n /**\n * @param {number} maxDepth\n * @param {number} layerRepeat\n * @param {number} [iteration=0]\n */\n constructor (maxDepth, layerRepeat, iteration = 0) {\n this.maxDepth = maxDepth\n this.layerRepeat = layerRepeat\n this.currentDepth = 1\n this.iteration = iteration\n\n /** @type {TrickleDagNode} */\n this.root = this.node = this.parent = {\n children: [],\n depth: this.currentDepth,\n maxDepth,\n maxChildren: (this.maxDepth - this.currentDepth) * this.layerRepeat\n }\n }\n\n isFull () {\n if (!this.root.data) {\n return false\n }\n\n if (this.currentDepth < this.maxDepth && this.node.maxChildren) {\n // can descend\n this._addNextNodeToParent(this.node)\n\n return false\n }\n\n // try to find new node from node.parent\n const distantRelative = this._findParent(this.node, this.currentDepth)\n\n if (distantRelative) {\n this._addNextNodeToParent(distantRelative)\n\n return false\n }\n\n return true\n }\n\n /**\n * @param {TrickleDagNode} parent\n */\n _addNextNodeToParent (parent) {\n this.parent = parent\n\n // find site for new node\n const nextNode = {\n children: [],\n depth: parent.depth + 1,\n parent,\n maxDepth: this.maxDepth,\n maxChildren: Math.floor(parent.children.length / this.layerRepeat) * this.layerRepeat\n }\n\n // @ts-ignore\n parent.children.push(nextNode)\n\n this.currentDepth = nextNode.depth\n this.node = nextNode\n }\n\n /**\n *\n * @param {InProgressImportResult[]} layer\n */\n append (layer) {\n this.node.data = layer\n }\n\n /**\n * @param {Reducer} reduce\n */\n reduce (reduce) {\n return this._reduce(this.root, reduce)\n }\n\n /**\n * @param {TrickleDagNode} node\n * @param {Reducer} reduce\n * @returns {Promise}\n */\n async _reduce (node, reduce) {\n /** @type {InProgressImportResult[]} */\n let children = []\n\n if (node.children.length) {\n children = await Promise.all(\n node.children\n // @ts-ignore\n .filter(child => child.data)\n // @ts-ignore\n .map(child => this._reduce(child, reduce))\n )\n }\n\n return reduce((node.data || []).concat(children))\n }\n\n /**\n * @param {TrickleDagNode} node\n * @param {number} depth\n * @returns {TrickleDagNode | undefined}\n */\n _findParent (node, depth) {\n const parent = node.parent\n\n if (!parent || parent.depth === 0) {\n return\n }\n\n if (parent.children.length === parent.maxChildren || !parent.maxChildren) {\n // this layer is full, may be able to traverse to a different branch\n return this._findParent(parent, depth)\n }\n\n return parent\n }\n}\n\nclass Root extends SubTree {\n /**\n * @param {number} layerRepeat\n */\n constructor (layerRepeat) {\n super(0, layerRepeat)\n\n this.root.depth = 0\n this.currentDepth = 1\n }\n\n /**\n * @param {InProgressImportResult} child\n */\n addChild (child) {\n this.root.children.push(child)\n }\n\n /**\n * @param {Reducer} reduce\n */\n reduce (reduce) {\n return reduce((this.root.data || []).concat(this.root.children))\n }\n}\n", "import { UnixFS } from 'ipfs-unixfs'\nimport persist from '../../utils/persist.js'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as raw from 'multiformats/codecs/raw'\n\n/**\n * @typedef {import('../../types').BufferImporter} BufferImporter\n */\n\n/**\n * @type {BufferImporter}\n */\nasync function * bufferImporter (file, block, options) {\n for await (let buffer of file.content) {\n yield async () => {\n options.progress(buffer.length, file.path)\n let unixfs\n\n /** @type {import('../../types').PersistOptions} */\n const opts = {\n codec: dagPb,\n cidVersion: options.cidVersion,\n hasher: options.hasher,\n onlyHash: options.onlyHash\n }\n\n if (options.rawLeaves) {\n opts.codec = raw\n opts.cidVersion = 1\n } else {\n unixfs = new UnixFS({\n type: options.leafType,\n data: buffer\n })\n\n buffer = dagPb.encode({\n Data: unixfs.marshal(),\n Links: []\n })\n }\n\n return {\n cid: await persist(buffer, block, opts),\n unixfs,\n size: buffer.length\n }\n }\n }\n}\n\nexport default bufferImporter\n", "import dirBuilder from './dir.js'\nimport fileBuilder from './file/index.js'\nimport errCode from 'err-code'\nimport rabin from '../chunker/rabin.js'\nimport fixedSize from '../chunker/fixed-size.js'\nimport validateChunks from './validate-chunks.js'\n\n/**\n * @typedef {import('../types').File} File\n * @typedef {import('../types').Directory} Directory\n * @typedef {import('../types').DAGBuilder} DAGBuilder\n * @typedef {import('../types').Chunker} Chunker\n * @typedef {import('../types').ChunkValidator} ChunkValidator\n */\n\n/**\n * @param {any} thing\n * @returns {thing is Iterable}\n */\nfunction isIterable (thing) {\n return Symbol.iterator in thing\n}\n\n/**\n * @param {any} thing\n * @returns {thing is AsyncIterable}\n */\nfunction isAsyncIterable (thing) {\n return Symbol.asyncIterator in thing\n}\n\n/**\n * @param {Uint8Array | AsyncIterable | Iterable} content\n * @returns {AsyncIterable}\n */\nfunction contentAsAsyncIterable (content) {\n try {\n if (content instanceof Uint8Array) {\n return (async function * () {\n yield content\n }())\n } else if (isIterable(content)) {\n return (async function * () {\n yield * content\n }())\n } else if (isAsyncIterable(content)) {\n return content\n }\n } catch {\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n }\n\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n}\n\n/**\n * @type {DAGBuilder}\n */\nasync function * dagBuilder (source, blockstore, options) {\n for await (const entry of source) {\n if (entry.path) {\n if (entry.path.substring(0, 2) === './') {\n options.wrapWithDirectory = true\n }\n\n entry.path = entry.path\n .split('/')\n .filter(path => path && path !== '.')\n .join('/')\n }\n\n if (entry.content) {\n /**\n * @type {Chunker}\n */\n let chunker\n\n if (typeof options.chunker === 'function') {\n chunker = options.chunker\n } else if (options.chunker === 'rabin') {\n chunker = rabin\n } else {\n chunker = fixedSize\n }\n\n /**\n * @type {ChunkValidator}\n */\n let chunkValidator\n\n if (typeof options.chunkValidator === 'function') {\n chunkValidator = options.chunkValidator\n } else {\n chunkValidator = validateChunks\n }\n\n /** @type {File} */\n const file = {\n path: entry.path,\n mtime: entry.mtime,\n mode: entry.mode,\n content: chunker(chunkValidator(contentAsAsyncIterable(entry.content), options), options)\n }\n\n yield () => fileBuilder(file, blockstore, options)\n } else if (entry.path) {\n /** @type {Directory} */\n const dir = {\n path: entry.path,\n mtime: entry.mtime,\n mode: entry.mode\n }\n\n yield () => dirBuilder(dir, blockstore, options)\n } else {\n throw new Error('Import candidate must have content or path or both')\n }\n }\n}\n\nexport default dagBuilder\n", "/**\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'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\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: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\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 } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\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 } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\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\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\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\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\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\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\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: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\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\n return true\n }\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: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\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", "import { Uint8ArrayList } from 'uint8arraylist'\n// @ts-ignore\nimport { create } from 'rabin-wasm'\nimport errcode from 'err-code'\n\n/**\n * @typedef {object} RabinOptions\n * @property {number} min\n * @property {number} max\n * @property {number} bits\n * @property {number} window\n * @property {number} polynomial\n */\n\n/**\n * @type {import('../types').Chunker}\n */\nasync function * rabinChunker (source, options) {\n let min, max, avg\n\n if (options.minChunkSize && options.maxChunkSize && options.avgChunkSize) {\n avg = options.avgChunkSize\n min = options.minChunkSize\n max = options.maxChunkSize\n } else if (!options.avgChunkSize) {\n throw errcode(new Error('please specify an average chunk size'), 'ERR_INVALID_AVG_CHUNK_SIZE')\n } else {\n avg = options.avgChunkSize\n min = avg / 3\n max = avg + (avg / 2)\n }\n\n // validate min/max/avg in the same way as go\n if (min < 16) {\n throw errcode(new Error('rabin min must be greater than 16'), 'ERR_INVALID_MIN_CHUNK_SIZE')\n }\n\n if (max < min) {\n max = min\n }\n\n if (avg < min) {\n avg = min\n }\n\n const sizepow = Math.floor(Math.log2(avg))\n\n for await (const chunk of rabin(source, {\n min: min,\n max: max,\n bits: sizepow,\n window: options.window,\n polynomial: options.polynomial\n })) {\n yield chunk\n }\n}\n\nexport default rabinChunker\n\n/**\n * @param {AsyncIterable} source\n * @param {RabinOptions} options\n */\nasync function * rabin (source, options) {\n const r = await create(options.bits, options.min, options.max, options.window)\n const buffers = new Uint8ArrayList()\n\n for await (const chunk of source) {\n buffers.append(chunk)\n\n const sizes = r.fingerprint(chunk)\n\n for (let i = 0; i < sizes.length; i++) {\n const size = sizes[i]\n const buf = buffers.slice(0, size)\n buffers.consume(size)\n\n yield buf\n }\n }\n\n if (buffers.length) {\n yield buffers.subarray(0)\n }\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * @type {import('../types').Chunker}\n */\nasync function * fixedSizeChunker (source, options) {\n let list = new Uint8ArrayList()\n let currentLength = 0\n let emitted = false\n const maxChunkSize = options.maxChunkSize\n\n for await (const buffer of source) {\n list.append(buffer)\n\n currentLength += buffer.length\n\n while (currentLength >= maxChunkSize) {\n yield list.slice(0, maxChunkSize)\n emitted = true\n\n // throw away consumed bytes\n if (maxChunkSize === list.length) {\n list = new Uint8ArrayList()\n currentLength = 0\n } else {\n const newBl = new Uint8ArrayList()\n newBl.append(list.sublist(maxChunkSize))\n list = newBl\n\n // update our offset\n currentLength -= maxChunkSize\n }\n }\n }\n\n if (!emitted || currentLength) {\n // return any remaining bytes or an empty buffer\n yield list.subarray(0, currentLength)\n }\n}\n\nexport default fixedSizeChunker\n", "import errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\n/**\n * @typedef {import('../types').ChunkValidator} ChunkValidator\n */\n\n/**\n * @type {ChunkValidator}\n */\nasync function * validateChunks (source) {\n for await (const content of source) {\n if (content.length === undefined) {\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n }\n\n if (typeof content === 'string' || content instanceof String) {\n yield uint8ArrayFromString(content.toString())\n } else if (Array.isArray(content)) {\n yield Uint8Array.from(content)\n } else if (content instanceof Uint8Array) {\n yield content\n } else {\n throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')\n }\n }\n}\n\nexport default validateChunks\n", "/**\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n *\n * @typedef {object} DirProps\n * @property {boolean} root\n * @property {boolean} dir\n * @property {string} path\n * @property {boolean} dirty\n * @property {boolean} flat\n * @property {Dir} [parent]\n * @property {string} [parentKey]\n * @property {import('ipfs-unixfs').UnixFS} [unixfs]\n * @property {number} [mode]\n * @property {import('ipfs-unixfs').Mtime} [mtime]\n */\nclass Dir {\n /**\n * @param {DirProps} props\n * @param {ImporterOptions} options\n */\n constructor (props, options) {\n this.options = options || {}\n\n this.root = props.root\n this.dir = props.dir\n this.path = props.path\n this.dirty = props.dirty\n this.flat = props.flat\n this.parent = props.parent\n this.parentKey = props.parentKey\n this.unixfs = props.unixfs\n this.mode = props.mode\n this.mtime = props.mtime\n\n /** @type {CID | undefined} */\n this.cid = undefined\n /** @type {number | undefined} */\n this.size = undefined\n }\n\n /**\n * @param {string} name\n * @param {InProgressImportResult | Dir} value\n */\n async put (name, value) { }\n\n /**\n * @param {string} name\n * @returns {Promise}\n */\n get (name) {\n return Promise.resolve(this)\n }\n\n /**\n * @returns {AsyncIterable<{ key: string, child: InProgressImportResult | Dir}>}\n */\n async * eachChildSeries () { }\n\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) { }\n}\n\nexport default Dir\n", "import { encode, prepare } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport Dir from './dir.js'\nimport persist from './utils/persist.js'\n\n/**\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./dir').DirProps} DirProps\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\nclass DirFlat extends Dir {\n /**\n * @param {DirProps} props\n * @param {ImporterOptions} options\n */\n constructor (props, options) {\n super(props, options)\n\n /** @type {{ [key: string]: InProgressImportResult | Dir }} */\n this._children = {}\n }\n\n /**\n * @param {string} name\n * @param {InProgressImportResult | Dir} value\n */\n async put (name, value) {\n this.cid = undefined\n this.size = undefined\n\n this._children[name] = value\n }\n\n /**\n * @param {string} name\n */\n get (name) {\n return Promise.resolve(this._children[name])\n }\n\n childCount () {\n return Object.keys(this._children).length\n }\n\n directChildrenCount () {\n return this.childCount()\n }\n\n onlyChild () {\n return this._children[Object.keys(this._children)[0]]\n }\n\n async * eachChildSeries () {\n const keys = Object.keys(this._children)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n\n yield {\n key: key,\n child: this._children[key]\n }\n }\n }\n\n /**\n * @param {Blockstore} block\n * @returns {AsyncIterable}\n */\n async * flush (block) {\n const children = Object.keys(this._children)\n const links = []\n\n for (let i = 0; i < children.length; i++) {\n let child = this._children[children[i]]\n\n if (child instanceof Dir) {\n for await (const entry of child.flush(block)) {\n child = entry\n\n yield child\n }\n }\n\n if (child.size != null && child.cid) {\n links.push({\n Name: children[i],\n Tsize: child.size,\n Hash: child.cid\n })\n }\n }\n\n const unixfs = new UnixFS({\n type: 'directory',\n mtime: this.mtime,\n mode: this.mode\n })\n\n /** @type {PBNode} */\n const node = { Data: unixfs.marshal(), Links: links }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, block, this.options)\n const size = buffer.length + node.Links.reduce(\n /**\n * @param {number} acc\n * @param {PBLink} curr\n */\n (acc, curr) => acc + (curr.Tsize == null ? 0 : curr.Tsize),\n 0)\n\n this.cid = cid\n this.size = size\n\n yield {\n cid,\n unixfs,\n path: this.path,\n size\n }\n }\n}\n\nexport default DirFlat\n", "// @ts-expect-error no types\nimport SparseArray from 'sparse-array'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { InfiniteHash } from './consumable-hash.js'\n\nexport interface BucketChild {\n key: string\n value: V\n hash: InfiniteHash\n}\n\ninterface SA {\n length: number\n compactArray(): B[]\n get(i: number): B\n set(i: number, value: B): void\n reduce (fn: (acc: A, curr: B, index: number) => A, initial: A): B\n find(fn: (item: B) => boolean): B | undefined\n bitField(): number[]\n unset(i: number): void\n}\n\nexport interface BucketPosition {\n bucket: Bucket\n pos: number\n hash: InfiniteHash\n existingChild?: BucketChild\n}\n\nexport interface BucketOptions {\n bits: number\n hash(value: Uint8Array | InfiniteHash): InfiniteHash\n}\n\nexport class Bucket {\n _options: BucketOptions\n _popCount: number\n _parent?: Bucket\n _posAtParent: number\n _children: SA | BucketChild>\n\n key: string | null\n\n constructor (options: BucketOptions, parent?: Bucket, posAtParent = 0) {\n this._options = options\n this._popCount = 0\n this._parent = parent\n this._posAtParent = posAtParent\n this._children = new SparseArray()\n this.key = null\n }\n\n async put (key: string, value: T): Promise {\n const place = await this._findNewBucketAndPos(key)\n\n place.bucket._putAt(place, key, value)\n }\n\n async get (key: string): Promise {\n const child = await this._findChild(key)\n\n if (child != null) {\n return child.value\n }\n }\n\n async del (key: string): Promise {\n const place = await this._findPlace(key)\n const child = place.bucket._at(place.pos)\n\n if (child != null && child.key === key) {\n place.bucket._delAt(place.pos)\n }\n }\n\n leafCount (): number {\n const children = this._children.compactArray()\n\n return children.reduce((acc, child) => {\n if (child instanceof Bucket) {\n return acc + child.leafCount()\n }\n\n return acc + 1\n }, 0)\n }\n\n childrenCount (): number {\n return this._children.length\n }\n\n onlyChild (): Bucket | BucketChild {\n return this._children.get(0)\n }\n\n * eachLeafSeries (): Iterable> {\n const children = this._children.compactArray()\n\n for (const child of children) {\n if (child instanceof Bucket) {\n yield * child.eachLeafSeries()\n } else {\n yield child\n }\n }\n }\n\n serialize (map: (value: BucketChild, index: number) => M, reduce: (reduced: Bucket | BucketChild) => M): M {\n const acc: M[] = []\n // serialize to a custom non-sparse representation\n return reduce(this._children.reduce((acc, child, index) => {\n if (child != null) {\n if (child instanceof Bucket) {\n acc.push(child.serialize(map, reduce))\n } else {\n acc.push(map(child, index))\n }\n }\n return acc\n }, acc))\n }\n\n async asyncTransform (asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise): Promise {\n return asyncTransformBucket(this, asyncMap, asyncReduce)\n }\n\n toJSON (): Record {\n return this.serialize(mapNode, reduceNodes)\n }\n\n prettyPrint (): string {\n return JSON.stringify(this.toJSON(), null, ' ')\n }\n\n tableSize (): number {\n return Math.pow(2, this._options.bits)\n }\n\n async _findChild (key: string): Promise | undefined> {\n const result = await this._findPlace(key)\n const child = result.bucket._at(result.pos)\n\n if (child instanceof Bucket) {\n // should not be possible, this._findPlace should always\n // return a location for a child, not a bucket\n return undefined\n }\n\n if (child != null && child.key === key) {\n return child\n }\n }\n\n async _findPlace (key: string | InfiniteHash): Promise> {\n const hashValue = this._options.hash(typeof key === 'string' ? uint8ArrayFromString(key) : key)\n const index = await hashValue.take(this._options.bits)\n\n const child = this._children.get(index)\n\n if (child instanceof Bucket) {\n return child._findPlace(hashValue)\n }\n\n return {\n bucket: this,\n pos: index,\n hash: hashValue,\n existingChild: child\n }\n }\n\n async _findNewBucketAndPos (key: string | InfiniteHash): Promise> {\n const place = await this._findPlace(key)\n\n if ((place.existingChild != null) && place.existingChild.key !== key) {\n // conflict\n const bucket = new Bucket(this._options, place.bucket, place.pos)\n place.bucket._putObjectAt(place.pos, bucket)\n\n // put the previous value\n const newPlace = await bucket._findPlace(place.existingChild.hash)\n newPlace.bucket._putAt(newPlace, place.existingChild.key, place.existingChild.value)\n\n return bucket._findNewBucketAndPos(place.hash)\n }\n\n // no conflict, we found the place\n return place\n }\n\n _putAt (place: BucketPosition, key: string, value: T): void {\n this._putObjectAt(place.pos, {\n key,\n value,\n hash: place.hash\n })\n }\n\n _putObjectAt (pos: number, object: Bucket | BucketChild): void {\n if (this._children.get(pos) == null) {\n this._popCount++\n }\n this._children.set(pos, object)\n }\n\n _delAt (pos: number): void {\n if (pos === -1) {\n throw new Error('Invalid position')\n }\n\n if (this._children.get(pos) != null) {\n this._popCount--\n }\n this._children.unset(pos)\n this._level()\n }\n\n _level (): void {\n if (this._parent != null && this._popCount <= 1) {\n if (this._popCount === 1) {\n // remove myself from parent, replacing me with my only child\n const onlyChild = this._children.find(exists)\n\n if ((onlyChild != null) && !(onlyChild instanceof Bucket)) {\n const hash = onlyChild.hash\n hash.untake(this._options.bits)\n const place = {\n pos: this._posAtParent,\n hash,\n bucket: this._parent\n }\n this._parent._putAt(place, onlyChild.key, onlyChild.value)\n }\n } else {\n this._parent._delAt(this._posAtParent)\n }\n }\n }\n\n _at (index: number): Bucket | BucketChild {\n return this._children.get(index)\n }\n}\n\nfunction exists (o: any): boolean {\n return Boolean(o)\n}\n\nfunction mapNode (node: { key: string }, _: number): string {\n return node.key\n}\n\nfunction reduceNodes (nodes: T): any {\n return nodes\n}\n\nasync function asyncTransformBucket (bucket: Bucket, asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise): Promise {\n const output = []\n\n for (const child of bucket._children.compactArray()) {\n if (child instanceof Bucket) {\n await asyncTransformBucket(child, asyncMap, asyncReduce)\n } else {\n const mappedChildren = await asyncMap(child)\n\n output.push({\n bitField: bucket._children.bitField(),\n children: mappedChildren\n })\n }\n }\n\n return asyncReduce(output)\n}\n", "const START_MASKS = [\n 0b11111111,\n 0b11111110,\n 0b11111100,\n 0b11111000,\n 0b11110000,\n 0b11100000,\n 0b11000000,\n 0b10000000\n]\n\nconst STOP_MASKS = [\n 0b00000001,\n 0b00000011,\n 0b00000111,\n 0b00001111,\n 0b00011111,\n 0b00111111,\n 0b01111111,\n 0b11111111\n]\n\nexport class ConsumableBuffer {\n _value: Uint8Array\n _currentBytePos: number\n _currentBitPos: number\n\n constructor (value: Uint8Array) {\n this._value = value\n this._currentBytePos = value.length - 1\n this._currentBitPos = 7\n }\n\n availableBits (): number {\n return this._currentBitPos + 1 + this._currentBytePos * 8\n }\n\n totalBits (): number {\n return this._value.length * 8\n }\n\n take (bits: number): number {\n let pendingBits = bits\n let result = 0\n while (pendingBits > 0 && this._haveBits()) {\n const byte = this._value[this._currentBytePos]\n const availableBits = this._currentBitPos + 1\n const taking = Math.min(availableBits, pendingBits)\n const value = byteBitsToInt(byte, availableBits - taking, taking)\n result = (result << taking) + value\n\n pendingBits -= taking\n\n this._currentBitPos -= taking\n if (this._currentBitPos < 0) {\n this._currentBitPos = 7\n this._currentBytePos--\n }\n }\n\n return result\n }\n\n untake (bits: number): void {\n this._currentBitPos += bits\n while (this._currentBitPos > 7) {\n this._currentBitPos -= 8\n this._currentBytePos += 1\n }\n }\n\n _haveBits (): boolean {\n return this._currentBytePos >= 0\n }\n}\n\nfunction byteBitsToInt (byte: number, start: number, length: number): number {\n const mask = maskFor(start, length)\n return (byte & mask) >>> start\n}\n\nfunction maskFor (start: number, length: number): number {\n return START_MASKS[start] & STOP_MASKS[Math.min(length + start - 1, 7)]\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { ConsumableBuffer } from './consumable-buffer.js'\n\nexport function wrapHash (hashFn: (value: Uint8Array) => Promise): (value: InfiniteHash | Uint8Array) => InfiniteHash {\n function hashing (value: InfiniteHash | Uint8Array): InfiniteHash {\n if (value instanceof InfiniteHash) {\n // already a hash. return it\n return value\n } else {\n return new InfiniteHash(value, hashFn)\n }\n }\n\n return hashing\n}\n\nexport class InfiniteHash {\n _value: Uint8Array\n _hashFn: (value: Uint8Array) => Promise\n _depth: number\n _availableBits: number\n _currentBufferIndex: number\n _buffers: ConsumableBuffer[]\n\n constructor (value: Uint8Array, hashFn: (value: Uint8Array) => Promise) {\n if (!(value instanceof Uint8Array)) {\n throw new Error('can only hash Uint8Arrays')\n }\n\n this._value = value\n this._hashFn = hashFn\n this._depth = -1\n this._availableBits = 0\n this._currentBufferIndex = 0\n this._buffers = []\n }\n\n async take (bits: number): Promise {\n let pendingBits = bits\n\n while (this._availableBits < pendingBits) {\n await this._produceMoreBits()\n }\n\n let result = 0\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const available = Math.min(hash.availableBits(), pendingBits)\n const took = hash.take(available)\n result = (result << available) + took\n pendingBits -= available\n this._availableBits -= available\n\n if (hash.availableBits() === 0) {\n this._currentBufferIndex++\n }\n }\n\n return result\n }\n\n untake (bits: number): void {\n let pendingBits = bits\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const availableForUntake = Math.min(hash.totalBits() - hash.availableBits(), pendingBits)\n hash.untake(availableForUntake)\n pendingBits -= availableForUntake\n this._availableBits += availableForUntake\n\n if (this._currentBufferIndex > 0 && hash.totalBits() === hash.availableBits()) {\n this._depth--\n this._currentBufferIndex--\n }\n }\n }\n\n async _produceMoreBits (): Promise {\n this._depth++\n\n const value = this._depth > 0 ? uint8ArrayConcat([this._value, Uint8Array.from([this._depth])]) : this._value\n const hashValue = await this._hashFn(value)\n const buffer = new ConsumableBuffer(hashValue)\n\n this._buffers.push(buffer)\n this._availableBits += buffer.availableBits()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A [Hash Mapped Trie](https://en.wikipedia.org/wiki/Hash_array_mapped_trie) implementation for JavaScript.\n *\n * This is used by [@helia/unixfs](https://www.npmjs.com/package/@helia/unixfs) for it's HAMT-sharded directory implementation.\n *\n * @example\n *\n * ```TypeScript\n * import { createHAMT } from 'hamt-sharding'\n * import crypto from 'crypto-promise'\n *\n * // decide how to hash buffers made from keys, can return a Promise\n * const hashFn = async (buf) => {\n * return crypto\n * .createHash('sha256')\n * .update(buf)\n * .digest()\n * }\n *\n * const bucket = createHAMT({\n * hashFn: hashFn\n * })\n *\n * await bucket.put('key', 'value')\n *\n * const output = await bucket.get('key')\n * // output === 'value'\n * ```\n */\n\nimport { Bucket } from './bucket.js'\nimport { wrapHash } from './consumable-hash.js'\nimport type { BucketOptions, BucketPosition, BucketChild } from './bucket.js'\n\ninterface UserBucketOptions {\n hashFn(value: Uint8Array): Promise\n bits?: number\n}\n\nexport function createHAMT (options: UserBucketOptions): Bucket {\n if (options == null || options.hashFn == null) {\n throw new Error('please define an options.hashFn')\n }\n\n const bucketOptions = {\n bits: options.bits ?? 8,\n hash: wrapHash(options.hashFn)\n }\n\n return new Bucket(bucketOptions)\n}\n\nexport { Bucket }\nexport type { BucketOptions, BucketPosition, BucketChild }\n", "import { encode, prepare } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport Dir from './dir.js'\nimport persist from './utils/persist.js'\nimport { createHAMT, Bucket } from 'hamt-sharding'\n\n/**\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n */\n\n/**\n * @typedef {import('./dir').DirProps} DirProps\n */\n\nclass DirSharded extends Dir {\n /**\n * @param {DirProps} props\n * @param {ImporterOptions} options\n */\n constructor (props, options) {\n super(props, options)\n\n /** @type {Bucket} */\n this._bucket = createHAMT({\n hashFn: options.hamtHashFn,\n bits: options.hamtBucketBits\n })\n }\n\n /**\n * @param {string} name\n * @param {InProgressImportResult | Dir} value\n */\n async put (name, value) {\n await this._bucket.put(name, value)\n }\n\n /**\n * @param {string} name\n */\n get (name) {\n return this._bucket.get(name)\n }\n\n childCount () {\n return this._bucket.leafCount()\n }\n\n directChildrenCount () {\n return this._bucket.childrenCount()\n }\n\n onlyChild () {\n return this._bucket.onlyChild()\n }\n\n async * eachChildSeries () {\n for await (const { key, value } of this._bucket.eachLeafSeries()) {\n yield {\n key,\n child: value\n }\n }\n }\n\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) {\n for await (const entry of flush(this._bucket, blockstore, this, this.options)) {\n yield {\n ...entry,\n path: this.path\n }\n }\n }\n}\n\nexport default DirSharded\n\n/**\n * @param {Bucket} bucket\n * @param {Blockstore} blockstore\n * @param {*} shardRoot\n * @param {ImporterOptions} options\n * @returns {AsyncIterable}\n */\nasync function * flush (bucket, blockstore, shardRoot, options) {\n const children = bucket._children\n const links = []\n let childrenSize = 0\n\n for (let i = 0; i < children.length; i++) {\n const child = children.get(i)\n\n if (!child) {\n continue\n }\n\n const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0')\n\n if (child instanceof Bucket) {\n let shard\n\n for await (const subShard of await flush(child, blockstore, null, options)) {\n shard = subShard\n }\n\n if (!shard) {\n throw new Error('Could not flush sharded directory, no subshard found')\n }\n\n links.push({\n Name: labelPrefix,\n Tsize: shard.size,\n Hash: shard.cid\n })\n childrenSize += shard.size\n } else if (typeof child.value.flush === 'function') {\n const dir = child.value\n let flushedDir\n\n for await (const entry of dir.flush(blockstore)) {\n flushedDir = entry\n\n yield flushedDir\n }\n\n const label = labelPrefix + child.key\n links.push({\n Name: label,\n Tsize: flushedDir.size,\n Hash: flushedDir.cid\n })\n\n childrenSize += flushedDir.size\n } else {\n const value = child.value\n\n if (!value.cid) {\n continue\n }\n\n const label = labelPrefix + child.key\n const size = value.size\n\n links.push({\n Name: label,\n Tsize: size,\n Hash: value.cid\n })\n childrenSize += size\n }\n }\n\n // go-ipfs uses little endian, that's why we have to\n // reverse the bit field before storing it\n const data = Uint8Array.from(children.bitField().reverse())\n const dir = new UnixFS({\n type: 'hamt-sharded-directory',\n data,\n fanout: bucket.tableSize(),\n hashType: options.hamtHashCode,\n mtime: shardRoot && shardRoot.mtime,\n mode: shardRoot && shardRoot.mode\n })\n\n const node = {\n Data: dir.marshal(),\n Links: links\n }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, blockstore, options)\n const size = buffer.length + childrenSize\n\n yield {\n cid,\n unixfs: dir,\n size\n }\n}\n", "import DirSharded from './dir-sharded.js'\nimport DirFlat from './dir-flat.js'\n\n/**\n * @typedef {import('./dir').default} Dir\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n */\n\n/**\n * @param {Dir | null} child\n * @param {Dir} dir\n * @param {number} threshold\n * @param {ImporterOptions} options\n * @returns {Promise}\n */\nasync function flatToShard (child, dir, threshold, options) {\n let newDir = dir\n\n if (dir instanceof DirFlat && dir.directChildrenCount() >= threshold) {\n newDir = await convertToShard(dir, options)\n }\n\n const parent = newDir.parent\n\n if (parent) {\n if (newDir !== dir) {\n if (child) {\n child.parent = newDir\n }\n\n if (!newDir.parentKey) {\n throw new Error('No parent key found')\n }\n\n await parent.put(newDir.parentKey, newDir)\n }\n\n return flatToShard(newDir, parent, threshold, options)\n }\n\n // @ts-ignore\n return newDir\n}\n\n/**\n * @param {DirFlat} oldDir\n * @param {ImporterOptions} options\n */\nasync function convertToShard (oldDir, options) {\n const newDir = new DirSharded({\n root: oldDir.root,\n dir: true,\n parent: oldDir.parent,\n parentKey: oldDir.parentKey,\n path: oldDir.path,\n dirty: oldDir.dirty,\n flat: false,\n mtime: oldDir.mtime,\n mode: oldDir.mode\n }, options)\n\n for await (const { key, child } of oldDir.eachChildSeries()) {\n await newDir.put(key, child)\n }\n\n return newDir\n}\n\nexport default flatToShard\n", "const toPathComponents = (path = '') => {\n // split on / unless escaped with \\\n return (path\n .trim()\n .match(/([^\\\\/]|\\\\\\/)+/g) || [])\n .filter(Boolean)\n}\n\nexport default toPathComponents\n", "import DirFlat from './dir-flat.js'\nimport flatToShard from './flat-to-shard.js'\nimport Dir from './dir.js'\nimport toPathComponents from './utils/to-path-components.js'\n\n/**\n * @typedef {import('./types').ImportResult} ImportResult\n * @typedef {import('./types').InProgressImportResult} InProgressImportResult\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {(source: AsyncIterable, blockstore: Blockstore, options: ImporterOptions) => AsyncIterable} TreeBuilder\n */\n\n/**\n * @param {InProgressImportResult} elem\n * @param {Dir} tree\n * @param {ImporterOptions} options\n */\nasync function addToTree (elem, tree, options) {\n const pathElems = toPathComponents(elem.path || '')\n const lastIndex = pathElems.length - 1\n let parent = tree\n let currentPath = ''\n\n for (let i = 0; i < pathElems.length; i++) {\n const pathElem = pathElems[i]\n\n currentPath += `${currentPath ? '/' : ''}${pathElem}`\n\n const last = (i === lastIndex)\n parent.dirty = true\n parent.cid = undefined\n parent.size = undefined\n\n if (last) {\n await parent.put(pathElem, elem)\n tree = await flatToShard(null, parent, options.shardSplitThreshold, options)\n } else {\n let dir = await parent.get(pathElem)\n\n if (!dir || !(dir instanceof Dir)) {\n dir = new DirFlat({\n root: false,\n dir: true,\n parent: parent,\n parentKey: pathElem,\n path: currentPath,\n dirty: true,\n flat: true,\n mtime: dir && dir.unixfs && dir.unixfs.mtime,\n mode: dir && dir.unixfs && dir.unixfs.mode\n }, options)\n }\n\n await parent.put(pathElem, dir)\n\n parent = dir\n }\n }\n\n return tree\n}\n\n/**\n * @param {Dir | InProgressImportResult} tree\n * @param {Blockstore} blockstore\n */\nasync function * flushAndYield (tree, blockstore) {\n if (!(tree instanceof Dir)) {\n if (tree && tree.unixfs && tree.unixfs.isDirectory()) {\n yield tree\n }\n\n return\n }\n\n yield * tree.flush(blockstore)\n}\n\n/**\n * @type {TreeBuilder}\n */\nasync function * treeBuilder (source, block, options) {\n /** @type {Dir} */\n let tree = new DirFlat({\n root: true,\n dir: true,\n path: '',\n dirty: true,\n flat: true\n }, options)\n\n for await (const entry of source) {\n if (!entry) {\n continue\n }\n\n tree = await addToTree(entry, tree, options)\n\n if (!entry.unixfs || !entry.unixfs.isDirectory()) {\n yield entry\n }\n }\n\n if (options.wrapWithDirectory) {\n yield * flushAndYield(tree, block)\n } else {\n for await (const unwrapped of tree.eachChildSeries()) {\n if (!unwrapped) {\n continue\n }\n\n yield * flushAndYield(unwrapped.child, block)\n }\n }\n}\n\nexport default treeBuilder\n", "import parallelBatch from 'it-parallel-batch'\nimport defaultOptions from './options.js'\nimport dagBuilderFn from './dag-builder/index.js'\nimport treeBuilderFn from './tree-builder.js'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').ImportCandidate} ImportCandidate\n * @typedef {import('./types').UserImporterOptions} UserImporterOptions\n * @typedef {import('./types').ImporterOptions} ImporterOptions\n * @typedef {import('./types').Directory} Directory\n * @typedef {import('./types').File} File\n * @typedef {import('./types').ImportResult} ImportResult\n *\n * @typedef {import('./types').Chunker} Chunker\n * @typedef {import('./types').DAGBuilder} DAGBuilder\n * @typedef {import('./types').TreeBuilder} TreeBuilder\n * @typedef {import('./types').BufferImporter} BufferImporter\n * @typedef {import('./types').ChunkValidator} ChunkValidator\n * @typedef {import('./types').Reducer} Reducer\n * @typedef {import('./types').ProgressHandler} ProgressHandler\n */\n\n/**\n * @param {AsyncIterable | Iterable | ImportCandidate} source\n * @param {Blockstore} blockstore\n * @param {UserImporterOptions} options\n * @returns {AsyncGenerator}\n */\nexport async function * importer (source, blockstore, options = {}) {\n const opts = defaultOptions(options)\n\n let dagBuilder\n\n if (typeof options.dagBuilder === 'function') {\n dagBuilder = options.dagBuilder\n } else {\n dagBuilder = dagBuilderFn\n }\n\n let treeBuilder\n\n if (typeof options.treeBuilder === 'function') {\n treeBuilder = options.treeBuilder\n } else {\n treeBuilder = treeBuilderFn\n }\n\n /** @type {AsyncIterable | Iterable} */\n let candidates\n\n if (Symbol.asyncIterator in source || Symbol.iterator in source) {\n // @ts-ignore\n candidates = source\n } else {\n // @ts-ignore\n candidates = [source]\n }\n\n for await (const entry of treeBuilder(parallelBatch(dagBuilder(candidates, blockstore, opts), opts.fileImportConcurrency), blockstore, opts)) {\n yield {\n cid: entry.cid,\n path: entry.path,\n unixfs: entry.unixfs,\n size: entry.size\n }\n }\n}\n", "import errCode from 'err-code'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport itPeekable from 'it-peekable'\nimport map from 'it-map'\nimport {\n isBytes,\n isBlob,\n isReadableStream,\n isFileObject\n} from './utils.js'\nimport {\n parseMtime,\n parseMode\n} from 'ipfs-unixfs'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidate} ImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ToContent} ToContent\n * @typedef {import('ipfs-unixfs-importer').ImportCandidate} ImporterImportCandidate\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * @param {ImportCandidateStream} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\n// eslint-disable-next-line complexity\nexport async function * normaliseCandidateMultiple (input, normaliseContent) {\n // String\n // Uint8Array|ArrayBuffer|TypedArray\n // Blob|File\n // fs.ReadStream\n // @ts-expect-error _readableState is a property of a node fs.ReadStream\n if (typeof input === 'string' || input instanceof String || isBytes(input) || isBlob(input) || input._readableState) {\n throw errCode(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n // Browser ReadableStream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // Iterable\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n const peekable = itPeekable(input)\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n yield * []\n return\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n // (Async)Iterable\n if (Number.isInteger(value)) {\n throw errCode(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n // (Async)Iterable\n // @ts-expect-error private field\n if (value._readableState) {\n // @ts-expect-error Node fs.ReadStreams have a `.path` property so we need to pass it as the content\n yield * map(peekable, (/** @type {ImportCandidate} */ value) => toFileObject({ content: value }, normaliseContent))\n return\n }\n\n if (isBytes(value)) {\n // @ts-expect-error peekable is still an iterable of ImportCandidates\n yield toFileObject({ content: peekable }, normaliseContent)\n return\n }\n\n // (Async)Iterable<(Async)Iterable>\n // (Async)Iterable>\n // ReadableStream<(Async)Iterable>\n // ReadableStream>\n if (isFileObject(value) || value[Symbol.iterator] || value[Symbol.asyncIterator] || isReadableStream(value) || isBlob(value)) {\n yield * map(peekable, (/** @type {ImportCandidate} */ value) => toFileObject(value, normaliseContent))\n return\n }\n }\n\n // { path, content: ? }\n // Note: Detected _after_ (Async)Iterable because Node.js fs.ReadStreams have a\n // `path` property that passes this check.\n if (isFileObject(input)) {\n throw errCode(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT')\n }\n\n throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {ImportCandidate} input\n * @param {(content:ToContent) => Promise>} normaliseContent\n */\nasync function toFileObject (input, normaliseContent) {\n // @ts-expect-error - Those properties don't exist on most input types\n const { path, mode, mtime, content } = input\n\n /** @type {ImporterImportCandidate} */\n const file = {\n path: path || '',\n mode: parseMode(mode),\n mtime: parseMtime(mtime)\n }\n\n if (content) {\n file.content = await normaliseContent(content)\n } else if (!path) { // Not already a file object with path or content prop\n // @ts-expect-error - input still can be different ToContent\n file.content = await normaliseContent(input)\n }\n\n return file\n}\n", "import { normaliseContent } from './normalise-content.js'\nimport { normaliseCandidateMultiple } from './normalise-candidate-multiple.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * Transforms any of the `ipfs.addAll` input types into\n *\n * ```\n * AsyncIterable<{ path, mode, mtime, content: AsyncIterable }>\n * ```\n *\n * See https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options\n *\n * @param {ImportCandidateStream} input\n */\nexport function normaliseInput (input) {\n return normaliseCandidateMultiple(input, normaliseContent)\n}\n", "/**\n * @typedef {object} FixedChunkerOptions\n * @property {'fixed'} chunker\n * @property {number} [maxChunkSize]\n *\n * @typedef {object} RabinChunkerOptions\n * @property {'rabin'} chunker\n * @property {number} avgChunkSize\n * @property {number} [minChunkSize]\n * @property {number} [maxChunkSize]\n *\n * @typedef {FixedChunkerOptions|RabinChunkerOptions} ChunkerOptions\n *\n * Parses chunker string into options used by DAGBuilder in ipfs-unixfs-engine\n *\n *\n * @param {string} [chunker] - Chunker algorithm supported formats:\n * \"size-{size}\"\n * \"rabin\"\n * \"rabin-{avg}\"\n * \"rabin-{min}-{avg}-{max}\"\n *\n * @returns {ChunkerOptions} Chunker options for DAGBuilder\n */\nexport const parseChunkerString = (chunker) => {\n if (!chunker) {\n return {\n chunker: 'fixed'\n }\n } else if (chunker.startsWith('size-')) {\n const sizeStr = chunker.split('-')[1]\n const size = parseInt(sizeStr)\n if (isNaN(size)) {\n throw new Error('Chunker parameter size must be an integer')\n }\n return {\n chunker: 'fixed',\n maxChunkSize: size\n }\n } else if (chunker.startsWith('rabin')) {\n return {\n chunker: 'rabin',\n ...parseRabinString(chunker)\n }\n } else {\n throw new Error(`Unrecognized chunker option: ${chunker}`)\n }\n}\n\n/**\n * @typedef {object} RabinChunkerSettings\n * @property {number} avgChunkSize\n * @property {number} [minChunkSize]\n * @property {number} [maxChunkSize]\n *\n * Parses rabin chunker string\n *\n * @param {string} chunker - Chunker algorithm supported formats:\n * \"rabin\"\n * \"rabin-{avg}\"\n * \"rabin-{min}-{avg}-{max}\"\n *\n * @returns {RabinChunkerSettings} rabin chunker options\n */\nexport const parseRabinString = (chunker) => {\n const options = {}\n const parts = chunker.split('-')\n switch (parts.length) {\n case 1:\n options.avgChunkSize = 262144\n break\n case 2:\n options.avgChunkSize = parseChunkSize(parts[1], 'avg')\n break\n case 4:\n options.minChunkSize = parseChunkSize(parts[1], 'min')\n options.avgChunkSize = parseChunkSize(parts[2], 'avg')\n options.maxChunkSize = parseChunkSize(parts[3], 'max')\n break\n default:\n throw new Error('Incorrect chunker format (expected \"rabin\" \"rabin-[avg]\" or \"rabin-[min]-[avg]-[max]\"')\n }\n\n return options\n}\n\n/**\n *\n * @param {string} str\n * @param {string} name\n * @returns {number}\n */\nexport const parseChunkSize = (str, name) => {\n const size = parseInt(str)\n if (isNaN(size)) {\n throw new Error(`Chunker parameter ${name} must be an integer`)\n }\n\n return size\n}\n", "import { importer } from 'ipfs-unixfs-importer'\nimport { normaliseInput } from 'ipfs-core-utils/files/normalise-input-multiple'\nimport { parseChunkerString } from './utils.js'\nimport { pipe } from 'it-pipe'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport mergeOpts from 'merge-options'\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-unixfs-importer').ImportResult} ImportResult\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n */\n\n/**\n * @template T\n *\n * @typedef {import('it-stream-types').Source} Source\n */\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../../types').Preload} preload\n * @property {Multihashes} hashers\n * @property {import('ipfs-core-types/src/root').ShardingOptions} [options]\n * @param {Context} context\n */\nexport function createAddAll ({ repo, preload, hashers, options }) {\n const isShardingEnabled = options && options.sharding\n\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n const opts = mergeOptions({\n shardSplitThreshold: isShardingEnabled ? 1000 : Infinity,\n strategy: 'balanced'\n }, options, {\n ...parseChunkerString(options.chunker)\n })\n\n // CID v0 is for multihashes encoded with sha2-256\n if (opts.hashAlg && opts.hashAlg !== 'sha2-256' && opts.cidVersion !== 1) {\n opts.cidVersion = 1\n }\n\n if (opts.trickle) {\n opts.strategy = 'trickle'\n }\n\n if (opts.strategy === 'trickle') {\n opts.leafType = 'raw'\n opts.reduceSingleLeafToSelf = false\n }\n\n if (opts.cidVersion > 0 && opts.rawLeaves === undefined) {\n // if the cid version is 1 or above, use raw leaves as this is\n // what go does.\n opts.rawLeaves = true\n }\n\n if (opts.hashAlg !== undefined && opts.rawLeaves === undefined) {\n // if a non-default hash alg has been specified, use raw leaves as this is\n // what go does.\n opts.rawLeaves = true\n }\n\n delete opts.trickle\n\n /** @type {Record} */\n const totals = {}\n\n if (opts.progress) {\n const prog = opts.progress\n\n /**\n * @param {number} bytes\n * @param {string} path\n */\n opts.progress = (bytes, path) => {\n if (!totals[path]) {\n totals[path] = 0\n }\n\n totals[path] += bytes\n\n prog(totals[path], path)\n }\n }\n\n /** @type {MultihashHasher | undefined} */\n let hasher\n\n if (opts.hashAlg != null) {\n hasher = await hashers.getHasher(opts.hashAlg)\n }\n\n const iterator = pipe(\n normaliseInput(source),\n /**\n * @param {Source} source\n */\n source => importer(source, repo.blocks, {\n ...opts,\n hasher,\n pin: false\n }),\n transformFile(opts),\n preloadFile(preload, opts),\n pinFile(repo, opts)\n )\n\n const releaseLock = await repo.gcLock.readLock()\n\n try {\n for await (const added of iterator) {\n const path = added.path ?? added.cid.toString()\n\n // do not keep file totals around forever\n delete totals[path]\n\n yield {\n ...added,\n path\n }\n }\n } finally {\n releaseLock()\n }\n }\n\n return withTimeoutOption(addAll)\n}\n\n/**\n * @param {import('ipfs-core-types/src/root').AddAllOptions} opts\n */\nfunction transformFile (opts) {\n /**\n * @param {Source} source\n */\n async function * transformFile (source) {\n for await (const file of source) {\n let cid = file.cid\n\n if (opts.cidVersion === 1) {\n cid = cid.toV1()\n }\n\n let path = file.path ? file.path : cid.toString()\n\n if (opts.wrapWithDirectory && !file.path) {\n path = ''\n }\n\n yield {\n path,\n cid: cid,\n size: file.size,\n mode: file.unixfs && file.unixfs.mode,\n mtime: file.unixfs && file.unixfs.mtime\n }\n }\n }\n\n return transformFile\n}\n\n/**\n * @param {(cid: CID) => void} preload\n * @param {import('ipfs-core-types/src/root').AddAllOptions} opts\n */\nfunction preloadFile (preload, opts) {\n /**\n * @param {Source} source\n */\n async function * maybePreloadFile (source) {\n for await (const file of source) {\n const isRootFile = !file.path || opts.wrapWithDirectory\n ? file.path === ''\n : !file.path.includes('/')\n\n const shouldPreload = isRootFile && !opts.onlyHash && opts.preload !== false\n\n if (shouldPreload) {\n preload(file.cid)\n }\n\n yield file\n }\n }\n\n return maybePreloadFile\n}\n\n/**\n * @param {import('ipfs-repo').IPFSRepo} repo\n * @param {import('ipfs-core-types/src/root').AddAllOptions} opts\n */\nfunction pinFile (repo, opts) {\n /**\n * @param {Source} source\n */\n async function * maybePinFile (source) {\n for await (const file of source) {\n // Pin a file if it is the root dir of a recursive add or the single file\n // of a direct add.\n const isRootDir = !(file.path && file.path.includes('/'))\n const shouldPin = (opts.pin == null ? true : opts.pin) && isRootDir && !opts.onlyHash\n\n if (shouldPin) {\n await repo.pins.pinRecursively(file.cid)\n }\n\n yield file\n }\n }\n\n return maybePinFile\n}\n", "import errCode from 'err-code'\nimport { CID } from 'multiformats/cid'\nimport resolve from './resolvers/index.js'\nimport last from 'it-last'\n\n/**\n * @typedef {import('ipfs-unixfs').UnixFS} UnixFS\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').ExporterOptions} ExporterOptions\n * @typedef {import('./types').UnixFSFile} UnixFSFile\n * @typedef {import('./types').UnixFSDirectory} UnixFSDirectory\n * @typedef {import('./types').ObjectNode} ObjectNode\n * @typedef {import('./types').RawNode} RawNode\n * @typedef {import('./types').IdentityNode} IdentityNode\n * @typedef {import('./types').UnixFSEntry} UnixFSEntry\n */\n\nconst toPathComponents = (path = '') => {\n // split on / unless escaped with \\\n return (path\n .trim()\n .match(/([^\\\\^/]|\\\\\\/)+/g) || [])\n .filter(Boolean)\n}\n\n/**\n * @param {string|Uint8Array|CID} path\n */\nconst cidAndRest = (path) => {\n if (path instanceof Uint8Array) {\n return {\n cid: CID.decode(path),\n toResolve: []\n }\n }\n\n const cid = CID.asCID(path)\n if (cid) {\n return {\n cid,\n toResolve: []\n }\n }\n\n if (typeof path === 'string') {\n if (path.indexOf('/ipfs/') === 0) {\n path = path.substring(6)\n }\n\n const output = toPathComponents(path)\n\n return {\n cid: CID.parse(output[0]),\n toResolve: output.slice(1)\n }\n }\n\n throw errCode(new Error(`Unknown path type ${path}`), 'ERR_BAD_PATH')\n}\n\n/**\n * @param {string | CID} path\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} [options]\n */\nexport async function * walkPath (path, blockstore, options = {}) {\n let {\n cid,\n toResolve\n } = cidAndRest(path)\n let name = cid.toString()\n let entryPath = name\n const startingDepth = toResolve.length\n\n while (true) {\n const result = await resolve(cid, name, entryPath, toResolve, startingDepth, blockstore, options)\n\n if (!result.entry && !result.next) {\n throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND')\n }\n\n if (result.entry) {\n yield result.entry\n }\n\n if (!result.next) {\n return\n }\n\n // resolve further parts\n toResolve = result.next.toResolve\n cid = result.next.cid\n name = result.next.name\n entryPath = result.next.path\n }\n}\n\n/**\n * @param {string | CID} path\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} [options]\n */\nexport async function exporter (path, blockstore, options = {}) {\n const result = await last(walkPath(path, blockstore, options))\n\n if (!result) {\n throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND')\n }\n\n return result\n}\n\n/**\n * @param {string | CID} path\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} [options]\n */\nexport async function * recursive (path, blockstore, options = {}) {\n const node = await exporter(path, blockstore, options)\n\n if (!node) {\n return\n }\n\n yield node\n\n if (node.type === 'directory') {\n for await (const child of recurse(node, options)) {\n yield child\n }\n }\n\n /**\n * @param {UnixFSDirectory} node\n * @param {ExporterOptions} options\n * @returns {AsyncGenerator}\n */\n async function * recurse (node, options) {\n for await (const file of node.content(options)) {\n yield file\n\n if (file instanceof Uint8Array) {\n continue\n }\n\n if (file.type === 'directory') {\n yield * recurse(file, options)\n }\n }\n }\n}\n", "import errCode from 'err-code'\n\nimport * as dagPb from '@ipld/dag-pb'\nimport * as dagCbor from '@ipld/dag-cbor'\nimport * as raw from 'multiformats/codecs/raw'\nimport { identity } from 'multiformats/hashes/identity'\n\nimport dagPbResolver from './unixfs-v1/index.js'\nimport rawResolver from './raw.js'\nimport dagCborResolver from './dag-cbor.js'\nimport identifyResolver from './identity.js'\n\n/**\n * @typedef {import('../types').Resolver} Resolver\n * @typedef {import('../types').Resolve} Resolve\n */\n\n/**\n * @type {{ [ key: string ]: Resolver }}\n */\nconst resolvers = {\n [dagPb.code]: dagPbResolver,\n [raw.code]: rawResolver,\n [dagCbor.code]: dagCborResolver,\n [identity.code]: identifyResolver\n}\n\n/**\n * @type {Resolve}\n */\nfunction resolve (cid, name, path, toResolve, depth, blockstore, options) {\n const resolver = resolvers[cid.code]\n\n if (!resolver) {\n throw errCode(new Error(`No resolver for code ${cid.code}`), 'ERR_NO_RESOLVER')\n }\n\n return resolver(cid, name, path, toResolve, resolve, depth, blockstore, options)\n}\n\nexport default resolve\n", "const textDecoder = new TextDecoder()\n\n/**\n * @typedef {import('./interface').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface').RawPBNode} RawPBNode\n */\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[number, number]}\n */\nfunction decodeVarint (bytes, offset) {\n let v = 0\n\n for (let shift = 0; ; shift += 7) {\n /* c8 ignore next 3 */\n if (shift >= 64) {\n throw new Error('protobuf: varint overflow')\n }\n /* c8 ignore next 3 */\n if (offset >= bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n const b = bytes[offset++]\n v += shift < 28 ? (b & 0x7f) << shift : (b & 0x7f) * (2 ** shift)\n if (b < 0x80) {\n break\n }\n }\n return [v, offset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[Uint8Array, number]}\n */\nfunction decodeBytes (bytes, offset) {\n let byteLen\n ;[byteLen, offset] = decodeVarint(bytes, offset)\n const postOffset = offset + byteLen\n\n /* c8 ignore next 3 */\n if (byteLen < 0 || postOffset < 0) {\n throw new Error('protobuf: invalid length')\n }\n /* c8 ignore next 3 */\n if (postOffset > bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n return [bytes.subarray(offset, postOffset), postOffset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} index\n * @returns {[number, number, number]}\n */\nfunction decodeKey (bytes, index) {\n let wire\n ;[wire, index] = decodeVarint(bytes, index)\n // [wireType, fieldNum, newIndex]\n return [wire & 0x7, wire >> 3, index]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBLink}\n */\nfunction decodeLink (bytes) {\n /** @type {RawPBLink} */\n const link = {}\n const l = bytes.length\n let index = 0\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (fieldNum === 1) {\n if (link.Hash) {\n throw new Error('protobuf: (PBLink) duplicate Hash section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Hash`)\n }\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Name before Hash')\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Hash')\n }\n\n [link.Hash, index] = decodeBytes(bytes, index)\n } else if (fieldNum === 2) {\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Name section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Name`)\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Name')\n }\n\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n link.Name = textDecoder.decode(byts)\n } else if (fieldNum === 3) {\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Tsize section')\n }\n if (wireType !== 0) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Tsize`)\n }\n\n [link.Tsize, index] = decodeVarint(bytes, index)\n } else {\n throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBLink) unexpected end of data')\n }\n\n return link\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBNode}\n */\nexport function decodeNode (bytes) {\n const l = bytes.length\n let index = 0\n /** @type {RawPBLink[]|void} */\n let links\n let linksBeforeData = false\n /** @type {Uint8Array|void} */\n let data\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${wireType}`)\n }\n\n if (fieldNum === 1) {\n if (data) {\n throw new Error('protobuf: (PBNode) duplicate Data section')\n }\n\n [data, index] = decodeBytes(bytes, index)\n if (links) {\n linksBeforeData = true\n }\n } else if (fieldNum === 2) {\n if (linksBeforeData) { // interleaved Links/Data/Links\n throw new Error('protobuf: (PBNode) duplicate Links section')\n } else if (!links) {\n links = []\n }\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n links.push(decodeLink(byts))\n } else {\n throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBNode) unexpected end of data')\n }\n\n /** @type {RawPBNode} */\n const node = {}\n if (data) {\n node.Data = data\n }\n node.Links = links || []\n return node\n}\n", "const textEncoder = new TextEncoder()\nconst maxInt32 = 2 ** 32\nconst maxUInt32 = 2 ** 31\n\n/**\n * @typedef {import('./interface').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface').RawPBNode} RawPBNode\n */\n\n// the encoders work backward from the end of the bytes array\n\n/**\n * encodeLink() is passed a slice of the parent byte array that ends where this\n * link needs to end, so it packs to the right-most part of the passed `bytes`\n *\n * @param {RawPBLink} link\n * @param {Uint8Array} bytes\n * @returns {number}\n */\nfunction encodeLink (link, bytes) {\n let i = bytes.length\n\n if (typeof link.Tsize === 'number') {\n if (link.Tsize < 0) {\n throw new Error('Tsize cannot be negative')\n }\n if (!Number.isSafeInteger(link.Tsize)) {\n throw new Error('Tsize too large for encoding')\n }\n i = encodeVarint(bytes, i, link.Tsize) - 1\n bytes[i] = 0x18\n }\n\n if (typeof link.Name === 'string') {\n const nameBytes = textEncoder.encode(link.Name)\n i -= nameBytes.length\n bytes.set(nameBytes, i)\n i = encodeVarint(bytes, i, nameBytes.length) - 1\n bytes[i] = 0x12\n }\n\n if (link.Hash) {\n i -= link.Hash.length\n bytes.set(link.Hash, i)\n i = encodeVarint(bytes, i, link.Hash.length) - 1\n bytes[i] = 0xa\n }\n\n return bytes.length - i\n}\n\n/**\n * Encodes a PBNode into a new byte array of precisely the correct size\n *\n * @param {RawPBNode} node\n * @returns {Uint8Array}\n */\nexport function encodeNode (node) {\n const size = sizeNode(node)\n const bytes = new Uint8Array(size)\n let i = size\n\n if (node.Data) {\n i -= node.Data.length\n bytes.set(node.Data, i)\n i = encodeVarint(bytes, i, node.Data.length) - 1\n bytes[i] = 0xa\n }\n\n if (node.Links) {\n for (let index = node.Links.length - 1; index >= 0; index--) {\n const size = encodeLink(node.Links[index], bytes.subarray(0, i))\n i -= size\n i = encodeVarint(bytes, i, size) - 1\n bytes[i] = 0x12\n }\n }\n\n return bytes\n}\n\n/**\n * work out exactly how many bytes this link takes up\n *\n * @param {RawPBLink} link\n * @returns\n */\nfunction sizeLink (link) {\n let n = 0\n\n if (link.Hash) {\n const l = link.Hash.length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Name === 'string') {\n const l = textEncoder.encode(link.Name).length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Tsize === 'number') {\n n += 1 + sov(link.Tsize)\n }\n\n return n\n}\n\n/**\n * Work out exactly how many bytes this node takes up\n *\n * @param {RawPBNode} node\n * @returns {number}\n */\nfunction sizeNode (node) {\n let n = 0\n\n if (node.Data) {\n const l = node.Data.length\n n += 1 + l + sov(l)\n }\n\n if (node.Links) {\n for (const link of node.Links) {\n const l = sizeLink(link)\n n += 1 + l + sov(l)\n }\n }\n\n return n\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @param {number} v\n * @returns {number}\n */\nfunction encodeVarint (bytes, offset, v) {\n offset -= sov(v)\n const base = offset\n\n while (v >= maxUInt32) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v /= 128\n }\n\n while (v >= 128) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v >>>= 7\n }\n\n bytes[offset] = v\n\n return base\n}\n\n/**\n * size of varint\n *\n * @param {number} x\n * @returns {number}\n */\nfunction sov (x) {\n if (x % 2 === 0) {\n x++\n }\n return Math.floor((len64(x) + 6) / 7)\n}\n\n/**\n * golang math/bits, how many bits does it take to represent this integer?\n *\n * @param {number} x\n * @returns {number}\n */\nfunction len64 (x) {\n let n = 0\n if (x >= maxInt32) {\n x = Math.floor(x / maxInt32)\n n = 32\n }\n if (x >= (1 << 16)) {\n x >>>= 16\n n += 16\n }\n if (x >= (1 << 8)) {\n x >>>= 8\n n += 8\n }\n return n + len8tab[x]\n}\n\n// golang math/bits\nconst len8tab = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8\n]\n", "import { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./interface').PBLink} PBLink\n * @typedef {import('./interface').PBNode} PBNode\n */\n\nconst pbNodeProperties = ['Data', 'Links']\nconst pbLinkProperties = ['Hash', 'Name', 'Tsize']\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {PBLink} a\n * @param {PBLink} b\n * @returns {number}\n */\nfunction linkComparator (a, b) {\n if (a === b) {\n return 0\n }\n\n const abuf = a.Name ? textEncoder.encode(a.Name) : []\n const bbuf = b.Name ? textEncoder.encode(b.Name) : []\n\n let x = abuf.length\n let y = bbuf.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (abuf[i] !== bbuf[i]) {\n x = abuf[i]\n y = bbuf[i]\n break\n }\n }\n\n return x < y ? -1 : y < x ? 1 : 0\n}\n\n/**\n * @param {any} node\n * @param {string[]} properties\n * @returns {boolean}\n */\nfunction hasOnlyProperties (node, properties) {\n return !Object.keys(node).some((p) => !properties.includes(p))\n}\n\n/**\n * Converts a CID, or a PBLink-like object to a PBLink\n *\n * @param {any} link\n * @returns {PBLink}\n */\nfunction asLink (link) {\n if (typeof link.asCID === 'object') {\n const Hash = CID.asCID(link)\n if (!Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n return { Hash }\n }\n\n if (typeof link !== 'object' || Array.isArray(link)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n const pbl = {}\n\n if (link.Hash) {\n let cid = CID.asCID(link.Hash)\n try {\n if (!cid) {\n if (typeof link.Hash === 'string') {\n cid = CID.parse(link.Hash)\n } else if (link.Hash instanceof Uint8Array) {\n cid = CID.decode(link.Hash)\n }\n }\n } catch (/** @type {any} */ e) {\n throw new TypeError(`Invalid DAG-PB form: ${e.message}`)\n }\n\n if (cid) {\n pbl.Hash = cid\n }\n }\n\n if (!pbl.Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (typeof link.Name === 'string') {\n pbl.Name = link.Name\n }\n\n if (typeof link.Tsize === 'number') {\n pbl.Tsize = link.Tsize\n }\n\n return pbl\n}\n\n/**\n * @param {any} node\n * @returns {PBNode}\n */\nexport function prepare (node) {\n if (node instanceof Uint8Array || typeof node === 'string') {\n node = { Data: node }\n }\n\n if (typeof node !== 'object' || Array.isArray(node)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n /** @type {PBNode} */\n const pbn = {}\n\n if (node.Data !== undefined) {\n if (typeof node.Data === 'string') {\n pbn.Data = textEncoder.encode(node.Data)\n } else if (node.Data instanceof Uint8Array) {\n pbn.Data = node.Data\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n }\n\n if (node.Links !== undefined) {\n if (Array.isArray(node.Links)) {\n pbn.Links = node.Links.map(asLink)\n pbn.Links.sort(linkComparator)\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n } else {\n pbn.Links = []\n }\n\n return pbn\n}\n\n/**\n * @param {PBNode} node\n */\nexport function validate (node) {\n /*\n type PBLink struct {\n Hash optional Link\n Name optional String\n Tsize optional Int\n }\n\n type PBNode struct {\n Links [PBLink]\n Data optional Bytes\n }\n */\n // @ts-ignore private property for TS\n if (!node || typeof node !== 'object' || Array.isArray(node) || node instanceof Uint8Array || (node['/'] && node['/'] === node.bytes)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (!hasOnlyProperties(node, pbNodeProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties)')\n }\n\n if (node.Data !== undefined && !(node.Data instanceof Uint8Array)) {\n throw new TypeError('Invalid DAG-PB form (Data must be bytes)')\n }\n\n if (!Array.isArray(node.Links)) {\n throw new TypeError('Invalid DAG-PB form (Links must be a list)')\n }\n\n for (let i = 0; i < node.Links.length; i++) {\n const link = node.Links[i]\n // @ts-ignore private property for TS\n if (!link || typeof link !== 'object' || Array.isArray(link) || link instanceof Uint8Array || (link['/'] && link['/'] === link.bytes)) {\n throw new TypeError('Invalid DAG-PB form (bad link)')\n }\n\n if (!hasOnlyProperties(link, pbLinkProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties on link)')\n }\n\n if (link.Hash === undefined) {\n throw new TypeError('Invalid DAG-PB form (link must have a Hash)')\n }\n\n // @ts-ignore private property for TS\n if (link.Hash == null || !link.Hash['/'] || link.Hash['/'] !== link.Hash.bytes) {\n throw new TypeError('Invalid DAG-PB form (link Hash must be a CID)')\n }\n\n if (link.Name !== undefined && typeof link.Name !== 'string') {\n throw new TypeError('Invalid DAG-PB form (link Name must be a string)')\n }\n\n if (link.Tsize !== undefined) {\n if (typeof link.Tsize !== 'number' || link.Tsize % 1 !== 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize must be an integer)')\n }\n if (link.Tsize < 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize cannot be negative)')\n }\n }\n\n if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) {\n throw new TypeError('Invalid DAG-PB form (links must be sorted by Name bytes)')\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {PBLink[]} [links=[]]\n * @returns {PBNode}\n */\nexport function createNode (data, links = []) {\n return prepare({ Data: data, Links: links })\n}\n\n/**\n * @param {string} name\n * @param {number} size\n * @param {CID} cid\n * @returns {PBLink}\n */\nexport function createLink (name, size, cid) {\n return asLink({ Hash: cid, Name: name, Tsize: size })\n}\n", "import { CID } from 'multiformats/cid'\nimport { decodeNode } from './pb-decode.js'\nimport { encodeNode } from './pb-encode.js'\nimport { prepare, validate, createNode, createLink } from './util.js'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @typedef {import('./interface').PBLink} PBLink\n * @typedef {import('./interface').PBNode} PBNode\n */\n\nexport const name = 'dag-pb'\nexport const code = 0x70\n\n/**\n * @param {PBNode} node\n * @returns {ByteView}\n */\nexport function encode (node) {\n validate(node)\n\n const pbn = {}\n if (node.Links) {\n pbn.Links = node.Links.map((l) => {\n const link = {}\n if (l.Hash) {\n link.Hash = l.Hash.bytes // cid -> bytes\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n if (node.Data) {\n pbn.Data = node.Data\n }\n\n return encodeNode(pbn)\n}\n\n/**\n * @param {ByteView} bytes\n * @returns {PBNode}\n */\nexport function decode (bytes) {\n const pbn = decodeNode(bytes)\n\n const node = {}\n\n if (pbn.Data) {\n node.Data = pbn.Data\n }\n\n if (pbn.Links) {\n node.Links = pbn.Links.map((l) => {\n const link = {}\n try {\n link.Hash = CID.decode(l.Hash)\n } catch (e) {}\n if (!link.Hash) {\n throw new Error('Invalid Hash field found in link, expected CID')\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n\n return node\n}\n\nexport { prepare, validate, createNode, createLink }\n", "import errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport findShardCid from '../../utils/find-cid-in-shard.js'\nimport { decode } from '@ipld/dag-pb'\n\nimport contentFile from './content/file.js'\nimport contentDirectory from './content/directory.js'\nimport contentHamtShardedDirectory from './content/hamt-sharded-directory.js'\n\n/**\n * @typedef {import('../../types').Resolve} Resolve\n * @typedef {import('../../types').Resolver} Resolver\n * @typedef {import('../../types').UnixfsV1Resolver} UnixfsV1Resolver\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n */\n\n/**\n * @param {PBNode} node\n * @param {string} name\n */\nconst findLinkCid = (node, name) => {\n const link = node.Links.find(link => link.Name === name)\n\n return link && link.Hash\n}\n\n/**\n * @type {{ [key: string]: UnixfsV1Resolver }}\n */\nconst contentExporters = {\n raw: contentFile,\n file: contentFile,\n directory: contentDirectory,\n 'hamt-sharded-directory': contentHamtShardedDirectory,\n metadata: (cid, node, unixfs, path, resolve, depth, blockstore) => {\n return () => []\n },\n symlink: (cid, node, unixfs, path, resolve, depth, blockstore) => {\n return () => []\n }\n}\n\n/**\n * @type {Resolver}\n */\nconst unixFsResolver = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n const block = await blockstore.get(cid, options)\n const node = decode(block)\n let unixfs\n let next\n\n if (!name) {\n name = cid.toString()\n }\n\n if (node.Data == null) {\n throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS')\n }\n\n try {\n unixfs = UnixFS.unmarshal(node.Data)\n } catch (/** @type {any} */ err) {\n // non-UnixFS dag-pb node? It could happen.\n throw errCode(err, 'ERR_NOT_UNIXFS')\n }\n\n if (!path) {\n path = name\n }\n\n if (toResolve.length) {\n let linkCid\n\n if (unixfs && unixfs.type === 'hamt-sharded-directory') {\n // special case - unixfs v1 hamt shards\n linkCid = await findShardCid(node, toResolve[0], blockstore)\n } else {\n linkCid = findLinkCid(node, toResolve[0])\n }\n\n if (!linkCid) {\n throw errCode(new Error('file does not exist'), 'ERR_NOT_FOUND')\n }\n\n // remove the path component we have resolved\n const nextName = toResolve.shift()\n const nextPath = `${path}/${nextName}`\n\n next = {\n cid: linkCid,\n toResolve,\n name: nextName || '',\n path: nextPath\n }\n }\n\n return {\n entry: {\n type: unixfs.isDirectory() ? 'directory' : 'file',\n name,\n path,\n cid,\n // @ts-ignore\n content: contentExporters[unixfs.type](cid, node, unixfs, path, resolve, depth, blockstore),\n unixfs,\n depth,\n node,\n size: unixfs.fileSize()\n },\n next\n }\n}\n\nexport default unixFsResolver\n", "// @ts-expect-error\nimport SparseArray from 'sparse-array'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { InfiniteHash } from './consumable-hash.js'\n\nexport interface BucketChild {\n key: string\n value: V\n hash: InfiniteHash\n}\n\ninterface SA {\n length: number\n compactArray: () => B[]\n get: (i: number) => B\n set: (i: number, value: B) => void\n reduce: (fn: (acc: A, curr: B, index: number) => A, initial: A) => B\n find: (fn: (item: B) => boolean) => B | undefined\n bitField: () => number[]\n unset: (i: number) => void\n}\n\nexport interface BucketPosition {\n bucket: Bucket\n pos: number\n hash: InfiniteHash\n existingChild?: BucketChild\n}\n\nexport interface BucketOptions {\n bits: number\n hash: (value: Uint8Array | InfiniteHash) => InfiniteHash\n}\n\nexport class Bucket {\n _options: BucketOptions\n _popCount: number\n _parent?: Bucket\n _posAtParent: number\n _children: SA | BucketChild>\n\n key: string | null\n\n constructor (options: BucketOptions, parent?: Bucket, posAtParent = 0) {\n this._options = options\n this._popCount = 0\n this._parent = parent\n this._posAtParent = posAtParent\n this._children = new SparseArray()\n this.key = null\n }\n\n async put (key: string, value: T) {\n const place = await this._findNewBucketAndPos(key)\n\n await place.bucket._putAt(place, key, value)\n }\n\n async get (key: string) {\n const child = await this._findChild(key)\n\n if (child != null) {\n return child.value\n }\n }\n\n async del (key: string) {\n const place = await this._findPlace(key)\n const child = place.bucket._at(place.pos)\n\n if (child != null && child.key === key) {\n place.bucket._delAt(place.pos)\n }\n }\n\n leafCount (): number {\n const children = this._children.compactArray()\n\n return children.reduce((acc, child) => {\n if (child instanceof Bucket) {\n return acc + child.leafCount()\n }\n\n return acc + 1\n }, 0)\n }\n\n childrenCount () {\n return this._children.length\n }\n\n onlyChild () {\n return this._children.get(0)\n }\n\n * eachLeafSeries (): Iterable> {\n const children = this._children.compactArray()\n\n for (const child of children) {\n if (child instanceof Bucket) {\n yield * child.eachLeafSeries()\n } else {\n yield child\n }\n }\n }\n\n serialize (map: (value: BucketChild, index: number) => T, reduce: (reduced: any) => any) {\n const acc: T[] = []\n // serialize to a custom non-sparse representation\n return reduce(this._children.reduce((acc, child, index) => {\n if (child != null) {\n if (child instanceof Bucket) {\n acc.push(child.serialize(map, reduce))\n } else {\n acc.push(map(child, index))\n }\n }\n return acc\n }, acc))\n }\n\n async asyncTransform (asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise) {\n return await asyncTransformBucket(this, asyncMap, asyncReduce)\n }\n\n toJSON () {\n return this.serialize(mapNode, reduceNodes)\n }\n\n prettyPrint () {\n return JSON.stringify(this.toJSON(), null, ' ')\n }\n\n tableSize () {\n return Math.pow(2, this._options.bits)\n }\n\n async _findChild (key: string) {\n const result = await this._findPlace(key)\n const child = result.bucket._at(result.pos)\n\n if (child instanceof Bucket) {\n // should not be possible, this._findPlace should always\n // return a location for a child, not a bucket\n return undefined\n }\n\n if (child != null && child.key === key) {\n return child\n }\n }\n\n async _findPlace (key: string | InfiniteHash): Promise> {\n const hashValue = this._options.hash(typeof key === 'string' ? uint8ArrayFromString(key) : key)\n const index = await hashValue.take(this._options.bits)\n\n const child = this._children.get(index)\n\n if (child instanceof Bucket) {\n return await child._findPlace(hashValue)\n }\n\n return {\n bucket: this,\n pos: index,\n hash: hashValue,\n existingChild: child\n }\n }\n\n async _findNewBucketAndPos (key: string | InfiniteHash): Promise> {\n const place = await this._findPlace(key)\n\n if ((place.existingChild != null) && place.existingChild.key !== key) {\n // conflict\n const bucket = new Bucket(this._options, place.bucket, place.pos)\n place.bucket._putObjectAt(place.pos, bucket)\n\n // put the previous value\n const newPlace = await bucket._findPlace(place.existingChild.hash)\n newPlace.bucket._putAt(newPlace, place.existingChild.key, place.existingChild.value)\n\n return await bucket._findNewBucketAndPos(place.hash)\n }\n\n // no conflict, we found the place\n return place\n }\n\n _putAt (place: BucketPosition, key: string, value: T) {\n this._putObjectAt(place.pos, {\n key: key,\n value: value,\n hash: place.hash\n })\n }\n\n _putObjectAt (pos: number, object: Bucket | BucketChild) {\n if (this._children.get(pos) == null) {\n this._popCount++\n }\n this._children.set(pos, object)\n }\n\n _delAt (pos: number) {\n if (pos === -1) {\n throw new Error('Invalid position')\n }\n\n if (this._children.get(pos) != null) {\n this._popCount--\n }\n this._children.unset(pos)\n this._level()\n }\n\n _level () {\n if (this._parent != null && this._popCount <= 1) {\n if (this._popCount === 1) {\n // remove myself from parent, replacing me with my only child\n const onlyChild = this._children.find(exists)\n\n if ((onlyChild != null) && !(onlyChild instanceof Bucket)) {\n const hash = onlyChild.hash\n hash.untake(this._options.bits)\n const place = {\n pos: this._posAtParent,\n hash: hash,\n bucket: this._parent\n }\n this._parent._putAt(place, onlyChild.key, onlyChild.value)\n }\n } else {\n this._parent._delAt(this._posAtParent)\n }\n }\n }\n\n _at (index: number) {\n return this._children.get(index)\n }\n}\n\nfunction exists (o: any) {\n return Boolean(o)\n}\n\nfunction mapNode (node: any, _: number) {\n return node.key\n}\n\nfunction reduceNodes (nodes: any) {\n return nodes\n}\n\nasync function asyncTransformBucket (bucket: Bucket, asyncMap: (value: BucketChild) => Promise, asyncReduce: (reduced: any) => Promise) {\n const output = []\n\n for (const child of bucket._children.compactArray()) {\n if (child instanceof Bucket) {\n await asyncTransformBucket(child, asyncMap, asyncReduce)\n } else {\n const mappedChildren = await asyncMap(child)\n\n output.push({\n bitField: bucket._children.bitField(),\n children: mappedChildren\n })\n }\n }\n\n return await asyncReduce(output)\n}\n", "const START_MASKS = [\n 0b11111111,\n 0b11111110,\n 0b11111100,\n 0b11111000,\n 0b11110000,\n 0b11100000,\n 0b11000000,\n 0b10000000\n]\n\nconst STOP_MASKS = [\n 0b00000001,\n 0b00000011,\n 0b00000111,\n 0b00001111,\n 0b00011111,\n 0b00111111,\n 0b01111111,\n 0b11111111\n]\n\nexport class ConsumableBuffer {\n _value: Uint8Array\n _currentBytePos: number\n _currentBitPos: number\n\n constructor (value: Uint8Array) {\n this._value = value\n this._currentBytePos = value.length - 1\n this._currentBitPos = 7\n }\n\n availableBits () {\n return this._currentBitPos + 1 + this._currentBytePos * 8\n }\n\n totalBits () {\n return this._value.length * 8\n }\n\n take (bits: number) {\n let pendingBits = bits\n let result = 0\n while (pendingBits > 0 && this._haveBits()) {\n const byte = this._value[this._currentBytePos]\n const availableBits = this._currentBitPos + 1\n const taking = Math.min(availableBits, pendingBits)\n const value = byteBitsToInt(byte, availableBits - taking, taking)\n result = (result << taking) + value\n\n pendingBits -= taking\n\n this._currentBitPos -= taking\n if (this._currentBitPos < 0) {\n this._currentBitPos = 7\n this._currentBytePos--\n }\n }\n\n return result\n }\n\n untake (bits: number) {\n this._currentBitPos += bits\n while (this._currentBitPos > 7) {\n this._currentBitPos -= 8\n this._currentBytePos += 1\n }\n }\n\n _haveBits () {\n return this._currentBytePos >= 0\n }\n}\n\nfunction byteBitsToInt (byte: number, start: number, length: number) {\n const mask = maskFor(start, length)\n return (byte & mask) >>> start\n}\n\nfunction maskFor (start: number, length: number) {\n return START_MASKS[start] & STOP_MASKS[Math.min(length + start - 1, 7)]\n}\n", "import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed ArrayLikes\n */\nexport function concat (arrays: Array>, length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "import { ConsumableBuffer } from './consumable-buffer.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nexport function wrapHash (hashFn: (value: Uint8Array) => Promise) {\n function hashing (value: InfiniteHash | Uint8Array) {\n if (value instanceof InfiniteHash) {\n // already a hash. return it\n return value\n } else {\n return new InfiniteHash(value, hashFn)\n }\n }\n\n return hashing\n}\n\nexport class InfiniteHash {\n _value: Uint8Array\n _hashFn: (value: Uint8Array) => Promise\n _depth: number\n _availableBits: number\n _currentBufferIndex: number\n _buffers: ConsumableBuffer[]\n\n constructor (value: Uint8Array, hashFn: (value: Uint8Array) => Promise) {\n if (!(value instanceof Uint8Array)) {\n throw new Error('can only hash Uint8Arrays')\n }\n\n this._value = value\n this._hashFn = hashFn\n this._depth = -1\n this._availableBits = 0\n this._currentBufferIndex = 0\n this._buffers = []\n }\n\n async take (bits: number) {\n let pendingBits = bits\n\n while (this._availableBits < pendingBits) {\n await this._produceMoreBits()\n }\n\n let result = 0\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const available = Math.min(hash.availableBits(), pendingBits)\n const took = hash.take(available)\n result = (result << available) + took\n pendingBits -= available\n this._availableBits -= available\n\n if (hash.availableBits() === 0) {\n this._currentBufferIndex++\n }\n }\n\n return result\n }\n\n untake (bits: number) {\n let pendingBits = bits\n\n while (pendingBits > 0) {\n const hash = this._buffers[this._currentBufferIndex]\n const availableForUntake = Math.min(hash.totalBits() - hash.availableBits(), pendingBits)\n hash.untake(availableForUntake)\n pendingBits -= availableForUntake\n this._availableBits += availableForUntake\n\n if (this._currentBufferIndex > 0 && hash.totalBits() === hash.availableBits()) {\n this._depth--\n this._currentBufferIndex--\n }\n }\n }\n\n async _produceMoreBits () {\n this._depth++\n\n const value = this._depth > 0 ? uint8ArrayConcat([this._value, Uint8Array.from([this._depth])]) : this._value\n const hashValue = await this._hashFn(value)\n const buffer = new ConsumableBuffer(hashValue)\n\n this._buffers.push(buffer)\n this._availableBits += buffer.availableBits()\n }\n}\n", "import { Bucket } from './bucket.js'\nimport type { BucketOptions, BucketPosition, BucketChild } from './bucket.js'\nimport { wrapHash } from './consumable-hash.js'\n\ninterface UserBucketOptions {\n hashFn: (value: Uint8Array) => Promise\n bits?: number\n}\n\nexport function createHAMT (options: UserBucketOptions) {\n if (options == null || options.hashFn == null) {\n throw new Error('please define an options.hashFn')\n }\n\n const bucketOptions = {\n bits: options.bits ?? 8,\n hash: wrapHash(options.hashFn)\n }\n\n return new Bucket(bucketOptions)\n}\n\nexport { Bucket }\nexport type { BucketOptions, BucketPosition, BucketChild }\n", "import { from } from 'multiformats/hashes/hasher'\nimport { bytes } from 'multiformats'\n// @ts-expect-error no types\nimport mur from 'murmurhash3js-revisited'\n\n/**\n * @param {number} number\n * @returns {Uint8Array}\n */\nfunction fromNumberTo32BitBuf (number) {\n const bytes = new Array(4)\n for (let i = 0; i < 4; i++) {\n bytes[i] = number & 0xff\n number = number >> 8\n }\n return new Uint8Array(bytes)\n}\n\nexport const murmur332 = from({\n name: 'murmur3-32',\n code: 0x23,\n encode: (input) => fromNumberTo32BitBuf(mur.x86.hash32(input))\n})\n\nexport const murmur3128 = from({\n name: 'murmur3-128',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input))\n})\n\n// A special-use 0x22 that truncates 64 bits, specifically for use in the UnixFS HAMT\nexport const murmur364 = from({\n name: 'murmur3-x64-64',\n code: 0x22,\n encode: (input) => bytes.fromHex(mur.x64.hash128(input)).subarray(0, 8)\n})\n", "\nimport { Bucket, createHAMT } from 'hamt-sharding'\nimport { decode } from '@ipld/dag-pb'\nimport { murmur3128 } from '@multiformats/murmur3'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('../types').ExporterOptions} ExporterOptions\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n// FIXME: this is copy/pasted from ipfs-unixfs-importer/src/options.js\n/**\n * @param {Uint8Array} buf\n */\nconst hashFn = async function (buf) {\n return (await murmur3128.encode(buf))\n // Murmur3 outputs 128 bit but, accidentally, IPFS Go's\n // implementation only uses the first 64, so we must do the same\n // for parity..\n .slice(0, 8)\n // Invert buffer because that's how Go impl does it\n .reverse()\n}\n\n/**\n * @param {PBLink[]} links\n * @param {Bucket} bucket\n * @param {Bucket} rootBucket\n */\nconst addLinksToHamtBucket = (links, bucket, rootBucket) => {\n return Promise.all(\n links.map(link => {\n if (link.Name == null) {\n // TODO(@rvagg): what do? this is technically possible\n throw new Error('Unexpected Link without a Name')\n }\n if (link.Name.length === 2) {\n const pos = parseInt(link.Name, 16)\n\n return bucket._putObjectAt(pos, new Bucket({\n hash: rootBucket._options.hash,\n bits: rootBucket._options.bits\n }, bucket, pos))\n }\n\n return rootBucket.put(link.Name.substring(2), true)\n })\n )\n}\n\n/**\n * @param {number} position\n */\nconst toPrefix = (position) => {\n return position\n .toString(16)\n .toUpperCase()\n .padStart(2, '0')\n .substring(0, 2)\n}\n\n/**\n * @param {import('hamt-sharding').BucketPosition} position\n */\nconst toBucketPath = (position) => {\n let bucket = position.bucket\n const path = []\n\n while (bucket._parent) {\n path.push(bucket)\n\n bucket = bucket._parent\n }\n\n path.push(bucket)\n\n return path.reverse()\n}\n\n/**\n * @typedef {import('../types').ShardTraversalContext} ShardTraversalContext\n *\n * @param {PBNode} node\n * @param {string} name\n * @param {Blockstore} blockstore\n * @param {ShardTraversalContext} [context]\n * @param {ExporterOptions} [options]\n * @returns {Promise}\n */\nconst findShardCid = async (node, name, blockstore, context, options) => {\n if (!context) {\n const rootBucket = createHAMT({\n hashFn\n })\n\n context = {\n rootBucket,\n hamtDepth: 1,\n lastBucket: rootBucket\n }\n }\n\n await addLinksToHamtBucket(node.Links, context.lastBucket, context.rootBucket)\n\n const position = await context.rootBucket._findNewBucketAndPos(name)\n let prefix = toPrefix(position.pos)\n const bucketPath = toBucketPath(position)\n\n if (bucketPath.length > context.hamtDepth) {\n context.lastBucket = bucketPath[context.hamtDepth]\n\n prefix = toPrefix(context.lastBucket._posAtParent)\n }\n\n const link = node.Links.find(link => {\n if (link.Name == null) {\n return false\n }\n\n const entryPrefix = link.Name.substring(0, 2)\n const entryName = link.Name.substring(2)\n\n if (entryPrefix !== prefix) {\n // not the entry or subshard we're looking for\n return false\n }\n\n if (entryName && entryName !== name) {\n // not the entry we're looking for\n return false\n }\n\n return true\n })\n\n if (!link) {\n return null\n }\n\n if (link.Name != null && link.Name.substring(2) === name) {\n return link.Hash\n }\n\n context.hamtDepth++\n\n const block = await blockstore.get(link.Hash, options)\n node = decode(block)\n\n return findShardCid(node, name, blockstore, context, options)\n}\n\nexport default findShardCid\n", "/**\n * @param {Uint8Array} block\n * @param {number} blockStart\n * @param {number} requestedStart\n * @param {number} requestedEnd\n */\nfunction extractDataFromBlock (block, blockStart, requestedStart, requestedEnd) {\n const blockLength = block.length\n const blockEnd = blockStart + blockLength\n\n if (requestedStart >= blockEnd || requestedEnd < blockStart) {\n // If we are looking for a byte range that is starts after the start of the block,\n // return an empty block. This can happen when internal nodes contain data\n return new Uint8Array(0)\n }\n\n if (requestedEnd >= blockStart && requestedEnd < blockEnd) {\n // If the end byte is in the current block, truncate the block to the end byte\n block = block.subarray(0, requestedEnd - blockStart)\n }\n\n if (requestedStart >= blockStart && requestedStart < blockEnd) {\n // If the start byte is in the current block, skip to the start byte\n block = block.subarray(requestedStart - blockStart)\n }\n\n return block\n}\n\nexport default extractDataFromBlock\n", "import errCode from 'err-code'\n\n/**\n * @param {number} size\n * @param {number} [offset]\n * @param {number} [length]\n */\nconst validateOffsetAndLength = (size, offset, length) => {\n if (!offset) {\n offset = 0\n }\n\n if (offset < 0) {\n throw errCode(new Error('Offset must be greater than or equal to 0'), 'ERR_INVALID_PARAMS')\n }\n\n if (offset > size) {\n throw errCode(new Error('Offset must be less than the file size'), 'ERR_INVALID_PARAMS')\n }\n\n if (!length && length !== 0) {\n length = size - offset\n }\n\n if (length < 0) {\n throw errCode(new Error('Length must be greater than or equal to 0'), 'ERR_INVALID_PARAMS')\n }\n\n if (offset + length > size) {\n length = size - offset\n }\n\n return {\n offset,\n length\n }\n}\n\nexport default validateOffsetAndLength\n", "import extractDataFromBlock from '../../../utils/extract-data-from-block.js'\nimport validateOffsetAndLength from '../../../utils/validate-offset-and-length.js'\nimport { UnixFS } from 'ipfs-unixfs'\nimport errCode from 'err-code'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as raw from 'multiformats/codecs/raw'\nimport { pushable } from 'it-pushable'\nimport parallel from 'it-parallel'\nimport { pipe } from 'it-pipe'\nimport map from 'it-map'\nimport PQueue from 'p-queue'\n\n/**\n * @typedef {import('../../../types').ExporterOptions} ExporterOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n/**\n * @param {Blockstore} blockstore\n * @param {PBNode | Uint8Array} node\n * @param {import('it-pushable').Pushable} queue\n * @param {number} streamPosition\n * @param {number} start\n * @param {number} end\n * @param {PQueue} walkQueue\n * @param {ExporterOptions} options\n * @returns {Promise}\n */\nasync function walkDAG (blockstore, node, queue, streamPosition, start, end, walkQueue, options) {\n // a `raw` node\n if (node instanceof Uint8Array) {\n queue.push(extractDataFromBlock(node, streamPosition, start, end))\n\n return\n }\n\n if (node.Data == null) {\n throw errCode(new Error('no data in PBNode'), 'ERR_NOT_UNIXFS')\n }\n\n /** @type {UnixFS} */\n let file\n\n try {\n file = UnixFS.unmarshal(node.Data)\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_NOT_UNIXFS')\n }\n\n // might be a unixfs `raw` node or have data on intermediate nodes\n if (file.data != null) {\n const data = file.data\n const buf = extractDataFromBlock(data, streamPosition, start, end)\n\n queue.push(buf)\n\n streamPosition += buf.byteLength\n }\n\n /** @type {Array<{ link: PBLink, blockStart: number }>} */\n const childOps = []\n\n for (let i = 0; i < node.Links.length; i++) {\n const childLink = node.Links[i]\n const childStart = streamPosition // inclusive\n const childEnd = childStart + file.blockSizes[i] // exclusive\n\n if ((start >= childStart && start < childEnd) || // child has offset byte\n (end >= childStart && end <= childEnd) || // child has end byte\n (start < childStart && end > childEnd)) { // child is between offset and end bytes\n childOps.push({\n link: childLink,\n blockStart: streamPosition\n })\n }\n\n streamPosition = childEnd\n\n if (streamPosition > end) {\n break\n }\n }\n\n await pipe(\n childOps,\n (source) => map(source, (op) => {\n return async () => {\n const block = await blockstore.get(op.link.Hash, {\n signal: options.signal\n })\n\n return {\n ...op,\n block\n }\n }\n }),\n (source) => parallel(source, {\n ordered: true\n }),\n async (source) => {\n for await (const { link, block, blockStart } of source) {\n /** @type {PBNode | Uint8Array} */\n let child\n switch (link.Hash.code) {\n case dagPb.code:\n child = dagPb.decode(block)\n break\n case raw.code:\n child = block\n break\n default:\n queue.end(errCode(new Error(`Unsupported codec: ${link.Hash.code}`), 'ERR_NOT_UNIXFS'))\n return\n }\n\n walkQueue.add(async () => {\n await walkDAG(blockstore, child, queue, blockStart, start, end, walkQueue, options)\n })\n }\n }\n )\n}\n\n/**\n * @type {import('../').UnixfsV1Resolver}\n */\nconst fileContent = (cid, node, unixfs, path, resolve, depth, blockstore) => {\n /**\n * @param {ExporterOptions} options\n */\n async function * yieldFileContent (options = {}) {\n const fileSize = unixfs.fileSize()\n\n if (fileSize === undefined) {\n throw new Error('File was a directory')\n }\n\n const {\n offset,\n length\n } = validateOffsetAndLength(fileSize, options.offset, options.length)\n\n if (length === 0) {\n return\n }\n\n // use a queue to walk the DAG instead of recursion to ensure very deep DAGs\n // don't overflow the stack\n const walkQueue = new PQueue({\n concurrency: 1\n })\n const queue = pushable()\n\n walkQueue.add(async () => {\n await walkDAG(blockstore, node, queue, 0, offset, offset + length, walkQueue, options)\n })\n\n walkQueue.on('error', error => {\n queue.end(error)\n })\n\n let read = 0\n\n for await (const buf of queue) {\n if (buf == null) {\n continue\n }\n\n read += buf.byteLength\n\n if (read === length) {\n queue.end()\n }\n\n yield buf\n }\n }\n\n return yieldFileContent\n}\n\nexport default fileContent\n", "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", "/* global EventTarget Event */\n\nimport defer from 'p-defer'\n\ninterface Operation {\n done: boolean\n ok: boolean\n err: Error\n value: T\n}\n\nconst CustomEvent = globalThis.CustomEvent ?? Event\n\nexport interface ParallelOptions {\n /**\n * How many jobs to execute in parallel (default: )\n */\n concurrency?: number\n ordered?: boolean\n}\n\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: Iterable<() => Promise> | AsyncIterable<() => Promise>, options: ParallelOptions = {}): AsyncGenerator {\n let concurrency = options.concurrency ?? Infinity\n\n if (concurrency < 1) {\n concurrency = Infinity\n }\n\n const ordered = options.ordered == null ? false : options.ordered\n const emitter = new EventTarget()\n\n const ops: Array> = []\n let slotAvailable = defer()\n let resultAvailable = defer()\n let sourceFinished = false\n let sourceErr: Error | undefined\n let opErred = false\n\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve()\n })\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\n if (opErred) {\n break\n }\n\n const op: any = {\n done: false\n }\n ops.push(op)\n\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\n sourceFinished = true\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n } catch (err: any) {\n sourceErr = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }\n })\n\n function valuesAvailable () {\n if (ordered) {\n return ops[0]?.done\n }\n\n return Boolean(ops.find(op => op.done))\n }\n\n function * yieldOrderedValues () {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0]\n ops.shift()\n\n if (op.ok) {\n yield op.value\n } else {\n // allow the source to exit\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\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\n if (op.ok) {\n yield op.value\n } else {\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n }\n }\n\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer()\n await resultAvailable.promise\n }\n\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr\n }\n\n if (ordered) {\n yield * yieldOrderedValues()\n } else {\n yield * yieldUnOrderedValues()\n }\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", "var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pending, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_throwOnAbort, _PQueue_onEvent;\nimport EventEmitter from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pending.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\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 Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\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 \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${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 \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\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 __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\"),\n ...options,\n };\n return new Promise((resolve, reject) => {\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pending, (_b = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n // TODO: Use options.signal?.throwIfAborted() when targeting Node.js 18\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n throw new AbortError('The task was aborted.');\n }\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), options.timeout);\n }\n if (options.signal) {\n operation = Promise.race([operation, __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_throwOnAbort).call(this, 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 __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n }\n }, options);\n this.emit('add');\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\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 (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, '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 (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").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 __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pending = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pending, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pending, (_a = __classPrivateFieldGet(this, _PQueue_pending, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - 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 __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pending, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pending, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_throwOnAbort = async function _PQueue_throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n // TODO: Reject with signal.throwIfAborted() when targeting Node.js 18\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n }, { once: true });\n });\n}, _PQueue_onEvent = async function _PQueue_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", "// 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", "var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\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 && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\n", "/**\n * @typedef {import('../../../types').ExporterOptions} ExporterOptions\n * @typedef {import('../../../types').UnixfsV1DirectoryContent} UnixfsV1DirectoryContent\n * @typedef {import('../../../types').UnixfsV1Resolver} UnixfsV1Resolver\n */\n\n/**\n * @type {UnixfsV1Resolver}\n */\nconst directoryContent = (cid, node, unixfs, path, resolve, depth, blockstore) => {\n /**\n * @param {ExporterOptions} [options]\n * @returns {UnixfsV1DirectoryContent}\n */\n async function * yieldDirectoryContent (options = {}) {\n const offset = options.offset || 0\n const length = options.length || node.Links.length\n const links = node.Links.slice(offset, length)\n\n for (const link of links) {\n const result = await resolve(link.Hash, link.Name || '', `${path}/${link.Name || ''}`, [], depth + 1, blockstore, options)\n\n if (result.entry) {\n yield result.entry\n }\n }\n }\n\n return yieldDirectoryContent\n}\n\nexport default directoryContent\n", "import { decode } from '@ipld/dag-pb'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../../../types').ExporterOptions} ExporterOptions\n * @typedef {import('../../../types').Resolve} Resolve\n * @typedef {import('../../../types').UnixfsV1DirectoryContent} UnixfsV1DirectoryContent\n * @typedef {import('../../../types').UnixfsV1Resolver} UnixfsV1Resolver\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n */\n\n/**\n * @type {UnixfsV1Resolver}\n */\nconst hamtShardedDirectoryContent = (cid, node, unixfs, path, resolve, depth, blockstore) => {\n /**\n * @param {ExporterOptions} options\n *\n */\n function yieldHamtDirectoryContent (options = {}) {\n return listDirectory(node, path, resolve, depth, blockstore, options)\n }\n\n return yieldHamtDirectoryContent\n}\n\n/**\n * @param {PBNode} node\n * @param {string} path\n * @param {Resolve} resolve\n * @param {number} depth\n * @param {Blockstore} blockstore\n * @param {ExporterOptions} options\n *\n * @returns {UnixfsV1DirectoryContent}\n */\nasync function * listDirectory (node, path, resolve, depth, blockstore, options) {\n const links = node.Links\n\n for (const link of links) {\n const name = link.Name != null ? link.Name.substring(2) : null\n\n if (name) {\n const result = await resolve(link.Hash, name, `${path}/${name}`, [], depth + 1, blockstore, options)\n\n yield result.entry\n } else {\n // descend into subshard\n const block = await blockstore.get(link.Hash)\n node = decode(block)\n\n for await (const file of listDirectory(node, path, resolve, depth, blockstore, options)) {\n yield file\n }\n }\n }\n}\n\nexport default hamtShardedDirectoryContent\n", "import errCode from 'err-code'\nimport extractDataFromBlock from '../utils/extract-data-from-block.js'\nimport validateOffsetAndLength from '../utils/validate-offset-and-length.js'\n\n/**\n * @typedef {import('../types').ExporterOptions} ExporterOptions\n */\n\n/**\n * @param {Uint8Array} node\n */\nconst rawContent = (node) => {\n /**\n * @param {ExporterOptions} options\n */\n async function * contentGenerator (options = {}) {\n const {\n offset,\n length\n } = validateOffsetAndLength(node.length, options.offset, options.length)\n\n yield extractDataFromBlock(node, 0, offset, offset + length)\n }\n\n return contentGenerator\n}\n\n/**\n * @type {import('../types').Resolver}\n */\nconst resolve = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n if (toResolve.length) {\n throw errCode(new Error(`No link named ${path} found in raw node ${cid}`), 'ERR_NOT_FOUND')\n }\n\n const block = await blockstore.get(cid, options)\n\n return {\n entry: {\n type: 'raw',\n name,\n path,\n cid,\n content: rawContent(block),\n depth,\n size: block.length,\n node: block\n }\n }\n}\n\nexport default resolve\n", "import { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\nimport * as dagCbor from '@ipld/dag-cbor'\n\n/**\n * @typedef {import('../types').Resolver} Resolver\n */\n\n/**\n * @type {Resolver}\n */\nconst resolve = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n const block = await blockstore.get(cid)\n const object = dagCbor.decode(block)\n let subObject = object\n let subPath = path\n\n while (toResolve.length) {\n const prop = toResolve[0]\n\n if (prop in subObject) {\n // remove the bit of the path we have resolved\n toResolve.shift()\n subPath = `${subPath}/${prop}`\n\n const subObjectCid = CID.asCID(subObject[prop])\n if (subObjectCid) {\n return {\n entry: {\n type: 'object',\n name,\n path,\n cid,\n node: block,\n depth,\n size: block.length,\n content: async function * () {\n yield object\n }\n },\n next: {\n cid: subObjectCid,\n name: prop,\n path: subPath,\n toResolve\n }\n }\n }\n\n subObject = subObject[prop]\n } else {\n // cannot resolve further\n throw errCode(new Error(`No property named ${prop} found in cbor node ${cid}`), 'ERR_NO_PROP')\n }\n }\n\n return {\n entry: {\n type: 'object',\n name,\n path,\n cid,\n node: block,\n depth,\n size: block.length,\n content: async function * () {\n yield object\n }\n }\n }\n}\n\nexport default resolve\n", "import errCode from 'err-code'\nimport extractDataFromBlock from '../utils/extract-data-from-block.js'\nimport validateOffsetAndLength from '../utils/validate-offset-and-length.js'\nimport * as mh from 'multiformats/hashes/digest'\n\n/**\n * @typedef {import('../types').ExporterOptions} ExporterOptions\n * @typedef {import('../types').Resolver} Resolver\n */\n\n/**\n * @param {Uint8Array} node\n */\nconst rawContent = (node) => {\n /**\n * @param {ExporterOptions} options\n */\n async function * contentGenerator (options = {}) {\n const {\n offset,\n length\n } = validateOffsetAndLength(node.length, options.offset, options.length)\n\n yield extractDataFromBlock(node, 0, offset, offset + length)\n }\n\n return contentGenerator\n}\n\n/**\n * @type {Resolver}\n */\nconst resolve = async (cid, name, path, toResolve, resolve, depth, blockstore, options) => {\n if (toResolve.length) {\n throw errCode(new Error(`No link named ${path} found in raw node ${cid}`), 'ERR_NOT_FOUND')\n }\n const buf = await mh.decode(cid.multihash.bytes)\n\n return {\n entry: {\n type: 'identity',\n name,\n path,\n cid,\n content: rawContent(buf.digest),\n depth,\n size: buf.digest.length,\n node: buf.digest\n }\n }\n}\n\nexport default resolve\n", "/**\n * Returns the last item of an (async) iterable, unless empty, in which case\n * return `undefined`\n */\nexport default async function last (source: AsyncIterable|Iterable): Promise {\n let res\n\n for await (const entry of source) {\n res = entry\n }\n\n return res\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport { normalizeCidPath } from '../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../types').Preload} preload\n *\n * @param {Context} context\n */\nexport function createCat ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"cat\"]}\n */\n async function * cat (ipfsPath, options = {}) {\n ipfsPath = normalizeCidPath(ipfsPath)\n\n if (options.preload !== false) {\n const pathComponents = ipfsPath.split('/')\n preload(CID.parse(pathComponents[0]))\n }\n\n const file = await exporter(ipfsPath, repo.blocks, options)\n\n // File may not have unixfs prop if small & imported with rawLeaves true\n if (file.type === 'directory') {\n throw new Error('this dag node is a directory')\n }\n\n if (!file.content) {\n throw new Error('this dag node has no content')\n }\n\n yield * file.content(options)\n }\n\n return withTimeoutOption(cat)\n}\n", "import { exporter, recursive } from 'ipfs-unixfs-exporter'\nimport errCode from 'err-code'\nimport { normalizeCidPath } from '../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\nimport { pack } from 'it-tar'\nimport { pipe } from 'it-pipe'\nimport Pako from 'pako'\nimport toBuffer from 'it-to-buffer'\n\n// https://www.gnu.org/software/gzip/manual/gzip.html\nconst DEFAULT_COMPRESSION_LEVEL = 6\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../types').Preload} preload\n *\n * @param {Context} context\n */\nexport function createGet ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"get\"]}\n */\n async function * get (ipfsPath, options = {}) {\n if (options.compressionLevel != null && (options.compressionLevel < -1 || options.compressionLevel > 9)) {\n throw errCode(new Error('Compression level must be between -1 and 9'), 'ERR_INVALID_PARAMS')\n }\n\n if (options.preload !== false) {\n let pathComponents\n\n try {\n pathComponents = normalizeCidPath(ipfsPath).split('/')\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_PATH')\n }\n\n preload(CID.parse(pathComponents[0]))\n }\n\n const ipfsPathOrCid = CID.asCID(ipfsPath) || ipfsPath\n const file = await exporter(ipfsPathOrCid, repo.blocks, options)\n\n if (file.type === 'file' || file.type === 'raw') {\n const args = []\n\n if (!options.compress || options.archive === true) {\n args.push([{\n header: {\n name: file.path,\n mode: file.type === 'file' && file.unixfs.mode,\n mtime: file.type === 'file' && file.unixfs.mtime ? new Date(file.unixfs.mtime.secs * 1000) : undefined,\n size: file.size,\n type: 'file'\n },\n body: file.content()\n }],\n pack()\n )\n } else {\n args.push(\n file.content\n )\n }\n\n if (options.compress) {\n args.push(\n /**\n * @param {AsyncIterable} source\n */\n async function * (source) {\n const buf = await toBuffer(source)\n\n yield Pako.gzip(buf, {\n level: options.compressionLevel || DEFAULT_COMPRESSION_LEVEL\n })\n }\n )\n }\n\n // @ts-expect-error cannot derive type\n yield * pipe(...args)\n\n return\n }\n\n if (file.type === 'directory') {\n /** @type {any[]} */\n const args = [\n recursive(ipfsPathOrCid, repo.blocks, options),\n /**\n * @param {AsyncIterable} source\n */\n async function * (source) {\n for await (const entry of source) {\n /** @type {import('it-tar').TarImportCandidate} */\n const output = {\n header: {\n name: entry.path,\n size: entry.size\n }\n }\n\n if (entry.type === 'file') {\n output.header.type = 'file'\n output.header.mode = entry.unixfs.mode != null ? entry.unixfs.mode : undefined\n output.header.mtime = entry.unixfs.mtime ? new Date(entry.unixfs.mtime.secs * 1000) : undefined\n output.body = entry.content()\n } else if (entry.type === 'raw') {\n output.header.type = 'file'\n output.body = entry.content()\n } else if (entry.type === 'directory') {\n output.header.type = 'directory'\n output.header.mode = entry.unixfs.mode != null ? entry.unixfs.mode : undefined\n output.header.mtime = entry.unixfs.mtime ? new Date(entry.unixfs.mtime.secs * 1000) : undefined\n } else {\n throw errCode(new Error('Not a UnixFS node'), 'ERR_NOT_UNIXFS')\n }\n\n yield output\n }\n },\n pack()\n ]\n\n if (options.compress) {\n if (!options.archive) {\n throw errCode(new Error('file is not regular'), 'ERR_INVALID_PATH')\n }\n\n if (options.compress) {\n args.push(\n /**\n * @param {AsyncIterable} source\n */\n async function * (source) {\n const buf = await toBuffer(source)\n\n yield Pako.gzip(buf, {\n level: options.compressionLevel || DEFAULT_COMPRESSION_LEVEL\n })\n }\n )\n }\n }\n\n // @ts-expect-error cannot derive type\n yield * pipe(...args)\n\n return\n }\n\n throw errCode(new Error('Not a UnixFS node'), 'ERR_NOT_UNIXFS')\n }\n\n return withTimeoutOption(get)\n}\n", "import { Uint8ArrayList, isUint8ArrayList } from 'uint8arraylist'\nimport { compare as uint8ArrayCompare } from 'uint8arrays/compare'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { EntryType, TarEntryHeader } from './index.js'\n\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = uint8ArrayFromString('ustar\\x00', 'binary')\nconst GNU_MAGIC = uint8ArrayFromString('ustar\\x20', 'binary')\nconst GNU_VER = uint8ArrayFromString('\\x20\\x00', 'binary')\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nconst clamp = function (index: number, len: number, defaultValue: number): number {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nconst toType = function (flag: number): EntryType | undefined {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n default:\n return undefined\n }\n}\n\nconst indexOf = function (block: Uint8ArrayList, num: number, offset: number, end: number): number {\n for (; offset < end; offset++) {\n if (block.get(offset) === num) return offset\n }\n return end\n}\n\nconst cksum = function (block: Uint8ArrayList): number {\n let sum = 8 * 32\n for (let i = 0; i < 148; i++) sum += block.get(i)\n for (let j = 156; j < 512; j++) sum += block.get(j)\n return sum\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf: Uint8ArrayList): number {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n let positive\n if (buf.get(0) === 0x80) {\n positive = true\n } else if (buf.get(0) === 0xFF) {\n positive = false\n } else {\n return 0\n }\n\n // build up a base-256 tuple from the least sig to the highest\n let zero = false\n const tuple = []\n for (let i = buf.length - 1; i > 0; i--) {\n const byte = buf.get(i)\n if (positive) tuple.push(byte)\n else if (zero && byte === 0) tuple.push(0)\n else if (zero) {\n zero = false\n tuple.push(0x100 - byte)\n } else tuple.push(0xFF - byte)\n }\n\n let sum = 0\n const l = tuple.length\n for (let i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nconst decodeOct = function (val: Uint8ArrayList, offset: number, length: number): number {\n val = val.sublist(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if ((val.get(offset) & 0x80) !== 0) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val.get(offset) === 32) {\n offset++\n }\n\n const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n\n while (offset < end && val.get(offset) === 0) {\n offset++\n }\n\n if (end === offset) {\n return 0\n }\n\n return parseInt(uint8ArrayToString(val.subarray(offset, end)), 8)\n }\n}\n\nconst decodeStr = function (val: Uint8ArrayList, offset: number, length: number, encoding?: SupportedEncodings): string {\n return uint8ArrayToString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding)\n}\n\nexport function decodeLongPath (buf: Uint8ArrayList | Uint8Array, encoding?: SupportedEncodings): string {\n const list = isUint8ArrayList(buf) ? buf : new Uint8ArrayList(buf)\n return decodeStr(list, 0, buf.length, encoding)\n}\n\nexport function decodePax (buf: Uint8ArrayList | Uint8Array, encoding?: SupportedEncodings): Record {\n let list = isUint8ArrayList(buf) ? buf : new Uint8ArrayList(buf)\n const result: Record = {}\n\n while (list.length > 0) {\n let i = 0\n while (i < buf.length && list.get(i) !== 32) {\n i++\n }\n\n const len = parseInt(uint8ArrayToString(list.subarray(0, i)), 10)\n\n if (len === 0) {\n return result\n }\n\n const b = uint8ArrayToString(list.subarray(i + 1, len - 1), encoding)\n const keyIndex = b.indexOf('=')\n\n if (keyIndex === -1) {\n return result\n }\n\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n list = list.sublist(len)\n }\n\n return result\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, filenameEncoding?: SupportedEncodings): TarEntryHeader | null {\n const list = isUint8ArrayList(buf) ? buf : new Uint8ArrayList(buf)\n let typeflag = list.get(156) === 0 ? 0 : list.get(156) - ZERO_OFFSET\n\n let name = decodeStr(list, 0, 100, filenameEncoding)\n const mode = decodeOct(list, 100, 8)\n const uid = decodeOct(list, 108, 8)\n const gid = decodeOct(list, 116, 8)\n const size = decodeOct(list, 124, 12)\n const mtime = decodeOct(list, 136, 12)\n const type = toType(typeflag)\n const linkname = list.get(157) === 0 ? undefined : decodeStr(list, 157, 100, filenameEncoding)\n const uname = decodeStr(list, 265, 32)\n const gname = decodeStr(list, 297, 32)\n const devmajor = decodeOct(list, 329, 8)\n const devminor = decodeOct(list, 337, 8)\n\n const c = cksum(list)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) {\n return null\n }\n\n // valid checksum\n if (c !== decodeOct(list, 148, 8)) {\n throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n }\n\n if (uint8ArrayCompare(USTAR_MAGIC, list.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (list.get(345) !== 0) {\n name = decodeStr(list, 345, 155, filenameEncoding) + '/' + name\n }\n } else if (uint8ArrayCompare(GNU_MAGIC, list.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) === 0 &&\n uint8ArrayCompare(GNU_VER, list.subarray(VERSION_OFFSET, VERSION_OFFSET + 2)) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n throw new Error('Invalid tar header: unknown format.')\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name != null && name[name.length - 1] === '/') {\n typeflag = 5\n }\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * (mtime ?? 0)),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n", "// @ts-expect-error no types\nimport isoConstants from 'iso-constants'\nimport toBuffer from 'it-to-buffer'\nimport { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as Headers from './pack-headers.js'\nimport type { EntryType, TarEntryHeader, TarImportCandidate } from './index.js'\nimport type { Source, Transform } from 'it-stream-types'\n\nconst { S_IFMT, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK } = isoConstants\nconst DMODE = parseInt('755', 8)\nconst FMODE = parseInt('644', 8)\nconst END_OF_TAR = new Uint8Array(1024)\n\nfunction modeToType (mode: number = 0): EntryType {\n switch (mode & S_IFMT) {\n case S_IFBLK: return 'block-device'\n case S_IFCHR: return 'character-device'\n case S_IFDIR: return 'directory'\n case S_IFIFO: return 'fifo'\n case S_IFLNK: return 'symlink'\n default: return 'file'\n }\n}\n\nfunction getPadding (size: number): Uint8Array {\n size &= 511\n\n if (size !== 0) {\n return END_OF_TAR.subarray(0, 512 - size)\n }\n\n return new Uint8Array(0)\n}\n\nfunction encode (header: TarEntryHeader): Uint8Array {\n if (header.pax == null) {\n const encoded = Headers.encode(header)\n\n if (encoded != null) {\n return encoded\n }\n }\n return encodePax(header)\n}\n\nfunction encodePax (header: TarEntryHeader): Uint8Array {\n const paxHeader = Headers.encodePax(header)\n\n const newHeader: TarEntryHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname,\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n return new Uint8ArrayList(\n Headers.encode(newHeader) ?? new Uint8Array(0),\n paxHeader,\n getPadding(paxHeader.length),\n Headers.encode({ ...newHeader, size: header.size, type: header.type }) ?? new Uint8Array(0)\n ).subarray()\n}\n\nexport function pack (): Transform, AsyncGenerator> {\n return async function * (source: Source) { // eslint-disable-line complexity\n for await (let { header: partialHeader, body } of source) {\n const header: TarEntryHeader = {\n ...partialHeader,\n size: partialHeader.type === 'symlink' ? 0 : partialHeader.size ?? 0,\n type: partialHeader.type ?? modeToType(partialHeader.mode),\n mode: partialHeader.mode ?? (partialHeader.type === 'directory' ? DMODE : FMODE),\n uid: partialHeader.uid ?? 0,\n gid: partialHeader.gid ?? 0,\n mtime: partialHeader.mtime ?? new Date()\n }\n\n if (typeof body === 'string') {\n body = uint8ArrayFromString(body)\n }\n\n if (body instanceof Uint8Array || isUint8ArrayList(body)) {\n header.size = body.length\n\n yield encode(header)\n yield isUint8ArrayList(body) ? body.subarray() : body\n yield getPadding(header.size)\n\n continue\n }\n\n if (header.type === 'symlink' && header.linkname == null) {\n if (body == null) {\n throw new Error('type was symlink but no linkname or body specified')\n }\n\n header.linkname = uint8ArrayToString(await toBuffer(body))\n yield encode(header)\n continue\n }\n\n yield encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n continue\n }\n\n let written = 0\n for await (const chunk of (body ?? [])) {\n written += chunk.length // eslint-disable-line @typescript-eslint/restrict-plus-operands\n yield isUint8ArrayList(chunk) ? chunk.subarray() : chunk\n }\n\n if (written !== header.size) { // corrupting tar\n throw new Error(`size mismatch, wrote ${written} of ${header.size} bytes`)\n }\n\n yield getPadding(header.size)\n }\n\n yield END_OF_TAR\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Collects all `Uint8Array` values from an (async)iterable and returns them as a single `Uint8Array`.\n *\n * @example\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * // This can also be an iterator, generator, etc\n * const values = [Buffer.from([0, 1]), Buffer.from([2, 3])]\n *\n * const result = toBuffer(values)\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * const values = async function * () {\n * yield Buffer.from([0, 1])\n * yield Buffer.from([2, 3])\n * }\n *\n * const result = await toBuffer(values())\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n */\n\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Takes an (async) iterable that yields buffer-like-objects and concats them\n * into one buffer\n */\nfunction toBuffer (source: Iterable): Uint8Array\nfunction toBuffer (source: Iterable | AsyncIterable): Promise\nfunction toBuffer (source: Iterable | AsyncIterable): Promise | Uint8Array {\n if (isAsyncIterable(source)) {\n return (async () => {\n let buffer = new Uint8Array(0)\n\n for await (const buf of source) {\n buffer = uint8ArrayConcat([buffer, buf], buffer.length + buf.length)\n }\n\n return buffer\n })()\n }\n\n const bufs = []\n let length = 0\n\n for (const buf of source) {\n bufs.push(buf)\n length += buf.byteLength\n }\n\n return uint8ArrayConcat(bufs, length)\n}\n\nexport default toBuffer\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { EntryType, TarEntryHeader } from '.'\n\nconst ZEROS = '0000000000000000000'\nconst SEVENS = '7777777777777777777'\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = uint8ArrayFromString('ustar\\x00', 'binary')\nconst USTAR_VER = uint8ArrayFromString('00', 'binary')\nconst MASK = parseInt('7777', 8)\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nconst toTypeflag = function (flag?: EntryType): number {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n default:\n return 0\n }\n}\n\nconst cksum = function (block: Uint8Array): number {\n let sum = 8 * 32\n for (let i = 0; i < 148; i++) sum += block[i]\n for (let j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nconst encodeOct = function (val: number, n: number): Uint8Array {\n const str = val.toString(8)\n\n if (str.length > n) {\n return uint8ArrayFromString(SEVENS.slice(0, n) + ' ')\n }\n\n return uint8ArrayFromString(ZEROS.slice(0, n - str.length) + str + ' ')\n}\n\nconst addLength = function (str: string): string {\n const len = uint8ArrayFromString(str).byteLength\n let digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n\n if (len + digits >= Math.pow(10, digits)) {\n digits++\n }\n\n return `${len + digits}${str}`\n}\n\nexport function encodePax (opts: TarEntryHeader): Uint8Array { // TODO: encode more stuff in pax\n let result = ''\n if (opts.name != null) {\n result += addLength(' path=' + opts.name + '\\n')\n }\n if (opts.linkname != null) {\n result += addLength(' linkpath=' + opts.linkname + '\\n')\n }\n\n const pax = opts.pax\n\n if (pax != null) {\n for (const key in pax) {\n if (Object.prototype.hasOwnProperty.call(pax, key)) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n }\n\n return uint8ArrayFromString(result)\n}\n\nexport function encode (opts: TarEntryHeader): Uint8Array | null {\n const buf = new Uint8Array(512)\n let name = opts.name\n let prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') {\n name += '/'\n }\n\n if (uint8ArrayFromString(name).byteLength !== name.length) {\n return null // utf-8\n }\n\n while (uint8ArrayFromString(name).byteLength > 100) {\n const i = name.indexOf('/')\n if (i === -1) {\n return null\n }\n prefix += prefix !== '' ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (uint8ArrayFromString(name).byteLength > 100 || uint8ArrayFromString(prefix).byteLength > 155) {\n return null\n }\n\n if (opts.linkname != null && uint8ArrayFromString(opts.linkname).byteLength > 100) {\n return null\n }\n\n buf.set(uint8ArrayFromString(name), 0)\n buf.set(encodeOct(opts.mode & MASK, 6), 100)\n buf.set(encodeOct(opts.uid, 6), 108)\n buf.set(encodeOct(opts.gid, 6), 116)\n buf.set(encodeOct(opts.size, 11), 124)\n buf.set(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname != null) {\n buf.set(uint8ArrayFromString(opts.linkname), 157)\n }\n\n buf.set(USTAR_MAGIC, MAGIC_OFFSET)\n buf.set(USTAR_VER, VERSION_OFFSET)\n\n if (opts.uname != null) {\n buf.set(uint8ArrayFromString(opts.uname), 265)\n }\n\n if (opts.gname != null) {\n buf.set(uint8ArrayFromString(opts.gname), 297)\n }\n\n buf.set(encodeOct(opts.devmajor ?? 0, 6), 329)\n buf.set(encodeOct(opts.devminor ?? 0, 6), 337)\n\n if (prefix != null) {\n buf.set(uint8ArrayFromString(prefix), 345)\n }\n\n buf.set(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n", "\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Tracev((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n code = (code + bl_count[bits - 1]) << 1;\n next_code[bits] = code;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let sx = 0; /* running index in sym_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.sym_next !== 0) {\n do {\n dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n lc = s.pending_buf[s.sym_buf + sx++];\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and sym_buf is ok: */\n //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n } while (sx < s.sym_next);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"block list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* block_mask is the bit mask of block-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let block_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"block-listed\") bytes. */\n for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"allow-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"block-listed\" or \"allow-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n bi_windup(s); /* align on byte boundary */\n put_short(s, stored_len);\n put_short(s, ~stored_len);\n if (stored_len) {\n s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n }\n s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->sym_next / 3));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42; /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */\nconst NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE = 113; /* deflate -> FINISH_STATE */\nconst FINISH_STATE = 666; /* stream complete */\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n let n, m;\n let p;\n let wsize = s.w_size;\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= wsize ? m - wsize : 0);\n } while (--n);\n n = wsize;\n//#ifndef FASTEST\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= wsize ? m - wsize : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let n, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n slide_hash(s);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Smallest worthy block size when not flushing or finishing. By default\n * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n * large input and output buffers, the stored block size will be larger.\n */\n let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n /* Copy as many min_block or larger stored blocks directly to next_out as\n * possible. If flushing, copy the remaining available input to next_out as\n * stored blocks, if there is enough space.\n */\n let len, left, have, last = 0;\n let used = s.strm.avail_in;\n do {\n /* Set len to the maximum size block that we can copy directly with the\n * available input data and output space. Set left to how much of that\n * would be copied from what's left in the window.\n */\n len = 65535/* MAX_STORED */; /* maximum deflate stored block length */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n if (s.strm.avail_out < have) { /* need room for header */\n break;\n }\n /* maximum stored block length that will fit in avail_out: */\n have = s.strm.avail_out - have;\n left = s.strstart - s.block_start; /* bytes left in window */\n if (len > left + s.strm.avail_in) {\n len = left + s.strm.avail_in; /* limit len to the input */\n }\n if (len > have) {\n len = have; /* limit len to the output */\n }\n\n /* If the stored block would be less than min_block in length, or if\n * unable to copy all of the available input when flushing, then try\n * copying to the window and the pending buffer instead. Also don't\n * write an empty block when flushing -- deflate() does that.\n */\n if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n flush === Z_NO_FLUSH$2 ||\n len !== left + s.strm.avail_in)) {\n break;\n }\n\n /* Make a dummy stored block in pending to get the header bytes,\n * including any pending bits. This also updates the debugging counts.\n */\n last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n _tr_stored_block(s, 0, 0, last);\n\n /* Replace the lengths in the dummy stored block with len. */\n s.pending_buf[s.pending - 4] = len;\n s.pending_buf[s.pending - 3] = len >> 8;\n s.pending_buf[s.pending - 2] = ~len;\n s.pending_buf[s.pending - 1] = ~len >> 8;\n\n /* Write the stored block header bytes. */\n flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n// /* Update debugging counts for the data about to be copied. */\n// s->compressed_len += len << 3;\n// s->bits_sent += len << 3;\n//#endif\n\n /* Copy uncompressed bytes from the window to next_out. */\n if (left) {\n if (left > len) {\n left = len;\n }\n //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n s.strm.next_out += left;\n s.strm.avail_out -= left;\n s.strm.total_out += left;\n s.block_start += left;\n len -= left;\n }\n\n /* Copy uncompressed bytes directly from next_in to next_out, updating\n * the check value.\n */\n if (len) {\n read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n s.strm.next_out += len;\n s.strm.avail_out -= len;\n s.strm.total_out += len;\n }\n } while (last === 0);\n\n /* Update the sliding window with the last s->w_size bytes of the copied\n * data, or append all of the copied data to the existing window if less\n * than s->w_size bytes were copied. Also update the number of bytes to\n * insert in the hash tables, in the event that deflateParams() switches to\n * a non-zero compression level.\n */\n used -= s.strm.avail_in; /* number of input bytes directly copied */\n if (used) {\n /* If any input was used, then no unused input remains in the window,\n * therefore s->block_start == s->strstart.\n */\n if (used >= s.w_size) { /* supplant the previous history */\n s.matches = 2; /* clear hash */\n //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n s.strstart = s.w_size;\n s.insert = s.strstart;\n }\n else {\n if (s.window_size - s.strstart <= used) {\n /* Slide the window down. */\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n s.strstart += used;\n s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n }\n s.block_start = s.strstart;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* If the last block was written to next_out, then done. */\n if (last) {\n return BS_FINISH_DONE;\n }\n\n /* If flushing and all input has been consumed, then done. */\n if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n s.strm.avail_in === 0 && s.strstart === s.block_start) {\n return BS_BLOCK_DONE;\n }\n\n /* Fill the window with any remaining input. */\n have = s.window_size - s.strstart;\n if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n /* Slide the window down. */\n s.block_start -= s.w_size;\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n have += s.w_size; /* more space now */\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n if (have > s.strm.avail_in) {\n have = s.strm.avail_in;\n }\n if (have) {\n read_buf(s.strm, s.window, s.strstart, have);\n s.strstart += have;\n s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* There was not enough avail_out to write a complete worthy or flushed\n * stored block to next_out. Write a stored block to pending instead, if we\n * have enough input for a worthy block, or if flushing and there is enough\n * room for the remaining input as a stored block in the pending buffer.\n */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n /* maximum stored block length that will fit in pending: */\n have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n min_block = have > s.w_size ? s.w_size : have;\n left = s.strstart - s.block_start;\n if (left >= min_block ||\n ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n s.strm.avail_in === 0 && left <= have)) {\n len = left > have ? have : left;\n last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n len === left ? 1 : 0;\n _tr_stored_block(s, s.block_start, len, last);\n s.block_start += len;\n flush_pending(s.strm);\n }\n\n /* We've done all we can with the available input and output. */\n return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.sym_buf = 0; /* buffer for distances and literals/lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.sym_next = 0; /* running index in sym_buf */\n this.sym_end = 0; /* symbol table full when sym_next reaches this */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const s = strm.state;\n if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n s.status !== GZIP_STATE &&\n//#endif\n s.status !== EXTRA_STATE &&\n s.status !== NAME_STATE &&\n s.status !== COMMENT_STATE &&\n s.status !== HCRC_STATE &&\n s.status !== BUSY_STATE &&\n s.status !== FINISH_STATE)) {\n return 1;\n }\n return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status =\n//#ifdef GZIP\n s.wrap === 2 ? GZIP_STATE :\n//#endif\n s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = -2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n return Z_STREAM_ERROR$2;\n }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n s.status = INIT_STATE; /* to pass state test in deflateReset() */\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n /* We overlay pending_buf and sym_buf. This works since the average size\n * for length/distance pairs over any compressed block is assured to be 31\n * bits or less.\n *\n * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n * possible fixed-codes length/distance pair is then 31 bits total.\n *\n * sym_buf starts one-fourth of the way into pending_buf. So there are\n * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n * in sym_buf is three bytes -- two for the distance and one for the\n * literal/length. As each symbol is consumed, the pointer to the next\n * sym_buf value to read moves forward three bytes. From that symbol, up to\n * 31 bits are written to pending_buf. The closest the written pending_buf\n * bits gets to the next sym_buf symbol to read is just before the last\n * code is written. At that time, 31*(n-2) bits have been written, just\n * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n * symbols are written.) The closest the writing gets to what is unread is\n * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n * can range from 128 to 32768.\n *\n * Therefore, at a minimum, there are 142 bits of space between what is\n * written and what is read in the overlain buffers, so the symbols cannot\n * be overwritten by the compressed data. That space is actually 139 bits,\n * due to the three-bit fixed-code block header.\n *\n * That covers the case where either Z_FIXED is specified, forcing fixed\n * codes, or when the use of fixed codes is chosen, because that choice\n * results in a smaller compressed block than dynamic codes. That latter\n * condition then assures that the above analysis also covers all dynamic\n * blocks. A dynamic-code block will only be chosen to be emitted if it has\n * fewer bits than a fixed-code block would for the same set of symbols.\n * Therefore its average symbol length is assured to be less than 31. So\n * the compressed data for a dynamic block also cannot overwrite the\n * symbols from which it is being constructed.\n */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->sym_buf = s->pending_buf + s->lit_bufsize;\n s.sym_buf = s.lit_bufsize;\n\n //s->sym_end = (s->lit_bufsize - 1) * 3;\n s.sym_end = (s.lit_bufsize - 1) * 3;\n /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (strm.avail_in !== 0 && !strm.input) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Write the header */\n if (s.status === INIT_STATE && s.wrap === 0) {\n s.status = BUSY_STATE;\n }\n if (s.status === INIT_STATE) {\n /* zlib header */\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#ifdef GZIP\n if (s.status === GZIP_STATE) {\n /* gzip header */\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n while (s.pending + left > s.pending_buf_size) {\n let copy = s.pending_buf_size - s.pending;\n // zmemcpy(s.pending_buf + s.pending,\n // s.gzhead.extra + s.gzindex, copy);\n s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n s.pending = s.pending_buf_size;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex += copy;\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n left -= copy;\n }\n // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n // TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n let gzhead_extra = new Uint8Array(s.gzhead.extra);\n // zmemcpy(s->pending_buf + s->pending,\n // s->gzhead->extra + s->gzindex, left);\n s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n s.pending += left;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = NAME_STATE;\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = COMMENT_STATE;\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n }\n s.status = HCRC_STATE;\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n }\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#endif\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = s.level === 0 ? deflate_stored(s, flush) :\n s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush);\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209; /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n// let shoextra; /* extra bits table to use */\n let match; /* use base and extra for symbol >= match */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n match = 20;\n\n } else if (type === LENS$1) {\n base = lbase;\n extra = lext;\n match = 257;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n match = 0;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] + 1 < match) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] >= match) {\n here_op = extra[work[sym] - match];\n here_val = base[work[sym] - match];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 16180; /* i: waiting for magic header */\nconst FLAGS = 16181; /* i: waiting for method and flags (gzip) */\nconst TIME = 16182; /* i: waiting for modification time (gzip) */\nconst OS = 16183; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 16184; /* i: waiting for extra length (gzip) */\nconst EXTRA = 16185; /* i: waiting for extra bytes (gzip) */\nconst NAME = 16186; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 16187; /* i: waiting for end of comment (gzip) */\nconst HCRC = 16188; /* i: waiting for header crc (gzip) */\nconst DICTID = 16189; /* i: waiting for dictionary check value */\nconst DICT = 16190; /* waiting for inflateSetDictionary() call */\nconst TYPE = 16191; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 16193; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 16194; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16195; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 16196; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 16197; /* i: waiting for code length code lengths */\nconst CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 16199; /* i: same as LEN below, but only first time in */\nconst LEN = 16200; /* i: waiting for length/lit/eob code */\nconst LENEXT = 16201; /* i: waiting for length extra bits */\nconst DIST = 16202; /* i: waiting for distance code */\nconst DISTEXT = 16203; /* i: waiting for distance extra bits */\nconst MATCH = 16204; /* o: waiting for output space to copy string */\nconst LIT = 16205; /* o: waiting for output space to write literal */\nconst CHECK = 16206; /* i: waiting for 32-bit check value */\nconst LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 16208; /* finished check, done -- remain here until reset */\nconst BAD = 16209; /* got a data error -- remain here until reset */\nconst MEM = 16210; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 16211; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,\n bit 2 true to validate check value */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib), or\n -1 if raw or no header yet */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const state = strm.state;\n if (!state || state.strm !== strm ||\n state.mode < HEAD || state.mode > SYNC) {\n return 1;\n }\n return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.flags = -1;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.strm = strm;\n state.window = null/*Z_NULL*/;\n state.mode = HEAD; /* to pass state test in inflateReset2() */\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (inflateStateCheck(strm) || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n if (state.wbits === 0) {\n state.wbits = 15;\n }\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n if (len > 15 || len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n state.flags = 0; /* indicate zlib header */\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check =\n /*UPDATE_CHECK(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (inflateStateCheck(strm)) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { Deflate_1 as Deflate, Inflate_1 as Inflate, constants_1 as constants, pako as default, deflate_1 as deflate, deflateRaw_1 as deflateRaw, gzip_1 as gzip, inflate_1 as inflate, inflateRaw_1 as inflateRaw, ungzip_1 as ungzip };\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\n/**\n * Takes an (async) iterable that yields buffer-like-objects and concats them\n * into one buffer\n */\nexport default async function toBuffer (stream: AsyncIterable | Iterable): Promise {\n let buffer = new Uint8Array(0)\n\n for await (const buf of stream) {\n buffer = uint8ArrayConcat([buffer, buf], buffer.length + buf.length)\n }\n\n return buffer\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport errCode from 'err-code'\nimport { normalizeCidPath, mapFile } from '../utils.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {object} Context\n * @property {import('ipfs-repo').IPFSRepo} repo\n * @property {import('../types').Preload} preload\n *\n * @param {Context} context\n */\nexport function createLs ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"ls\"]}\n */\n async function * ls (ipfsPath, options = {}) {\n const legacyPath = normalizeCidPath(ipfsPath)\n const pathComponents = legacyPath.split('/')\n\n if (options.preload !== false) {\n preload(CID.parse(pathComponents[0]))\n }\n\n const ipfsPathOrCid = CID.asCID(legacyPath) || legacyPath\n const file = await exporter(ipfsPathOrCid, repo.blocks, options)\n\n if (file.type === 'file') {\n yield mapFile(file)\n return\n }\n\n if (file.type === 'directory') {\n for await (const child of file.content()) {\n yield mapFile(child)\n }\n\n return\n }\n\n throw errCode(new Error(`Unknown UnixFS type ${file.type}`), 'ERR_UNKNOWN_UNIXFS_TYPE')\n }\n\n return withTimeoutOption(ls)\n}\n", "import { createAdd } from './add.js'\nimport { createAddAll } from './add-all/index.js'\nimport { createCat } from './cat.js'\nimport { createGet } from './get.js'\nimport { createLs } from './ls.js'\n\n/**\n * @typedef {AddAllContext & CatContext & GetContext & ListContext } Context\n * @typedef {import('./add-all').Context} AddAllContext\n * @typedef {import('./cat').Context} CatContext\n * @typedef {import('./get').Context} GetContext\n * @typedef {import('./ls').Context} ListContext\n */\nexport class RootAPI {\n /**\n * @param {Context} context\n */\n constructor ({ preload, repo, hashers, options }) {\n const addAll = createAddAll({\n preload,\n repo,\n options,\n hashers\n })\n\n this.addAll = addAll\n this.add = createAdd({ addAll })\n this.cat = createCat({ repo, preload })\n this.get = createGet({ repo, preload })\n this.ls = createLs({ repo, preload })\n }\n}\n", "\nexport const ipfsCore = '0.18.1'\nexport const commit = ''\nexport const interfaceIpfsCore = '^0.158.1'\n", "import { ipfsCore, interfaceIpfsCore, commit } from '../version.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createVersion ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"version\"]}\n */\n async function version (_options = {}) {\n const repoVersion = await repo.version.get()\n\n return {\n version: ipfsCore,\n commit,\n repo: `${repoVersion}`,\n 'ipfs-core': ipfsCore,\n 'interface-ipfs-core': interfaceIpfsCore\n }\n }\n\n return withTimeoutOption(version)\n}\n", "import { ipfsCore as pkgversion } from '../version.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { NotStartedError } from '../errors.js'\nimport errCode from 'err-code'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:components:id')\n\n/**\n * @typedef {import('libp2p').Libp2p} Libp2p\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-peer-id').PeerId} config.peerId\n * @param {import('../types').NetworkService} config.network\n */\nexport function createId ({ peerId, network }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"id\"]}\n */\n async function id (options = {}) { // eslint-disable-line require-await\n const net = network.try()\n\n if (!net) {\n if (options.peerId) {\n throw new NotStartedError()\n }\n\n if (peerId.publicKey == null) {\n throw errCode(new Error('Public key missing'), 'ERR_MISSING_PUBLIC_KEY')\n }\n\n return {\n id: peerId,\n publicKey: uint8ArrayToString(peerId.publicKey, 'base64pad'),\n addresses: [],\n agentVersion: `js-ipfs/${pkgversion}`,\n protocolVersion: '9000',\n protocols: []\n }\n }\n\n const { libp2p } = net\n const peerIdToId = options.peerId ? options.peerId : peerId\n const peer = await findPeer(peerIdToId, libp2p, options)\n const agentVersion = uint8ArrayToString(peer.metadata.get('AgentVersion') || new Uint8Array())\n const protocolVersion = uint8ArrayToString(peer.metadata.get('ProtocolVersion') || new Uint8Array())\n const idStr = peer.id.toString()\n const publicKeyStr = peer.publicKey ? uint8ArrayToString(peer.publicKey, 'base64pad') : ''\n\n return {\n id: peerIdToId,\n publicKey: publicKeyStr,\n addresses: (peer.addresses || [])\n .map(ma => {\n const str = ma.toString()\n\n // some relay-style transports add our peer id to the ma for us\n // so don't double-add\n if (str.endsWith(`/p2p/${idStr}`)) {\n return str\n }\n\n return `${str}/p2p/${idStr}`\n })\n .sort()\n .map(ma => multiaddr(ma)),\n agentVersion,\n protocolVersion,\n protocols: (peer.protocols || []).sort()\n }\n }\n\n return withTimeoutOption(id)\n}\n\n/**\n * @param {PeerId} peerId\n * @param {Libp2p} libp2p\n * @param {AbortOptions} options\n */\nasync function findPeer (peerId, libp2p, options) {\n let peer = await libp2p.peerStore.get(peerId)\n\n if (!peer) {\n peer = await findPeerOnDht(peerId, libp2p, options)\n }\n\n let publicKey = peerId.publicKey ? peerId.publicKey : await libp2p.peerStore.keyBook.get(peerId)\n\n if (publicKey == null) {\n try {\n publicKey = await libp2p.getPublicKey(peerId, options)\n } catch (err) {\n log.error('Could not load public key for', peerId.toString(), err)\n }\n }\n\n return {\n ...peer,\n publicKey,\n metadata: peer.metadata || new Map(),\n addresses: peer.addresses.map(addr => addr.multiaddr)\n }\n}\n\n/**\n * @param {PeerId} peerId\n * @param {Libp2p} libp2p\n * @param {AbortOptions} options\n */\nasync function findPeerOnDht (peerId, libp2p, options) {\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n for await (const event of libp2p.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n break\n }\n }\n\n const peer = await libp2p.peerStore.get(peerId)\n\n if (!peer) {\n throw errCode(new Error('Could not find peer'), 'ERR_NOT_FOUND')\n }\n\n return peer\n}\n", "var objectSafeSet = set;\n\n/*\n var obj1 = {};\n set(obj1, 'a.aa.aaa', 4); // true\n obj1; // {a: {aa: {aaa: 4}}}\n\n var obj2 = {};\n set(obj2, ['a', 'aa', 'aaa'], 4); // true\n obj2; // {a: {aa: {aaa: 4}}}\n\n var obj3 = {a: {aa: {aaa: 2}}};\n set(obj3, 'a.aa.aaa', 3); // true\n obj3; // {a: {aa: {aaa: 3}}}\n\n const obj5 = {a: {}};\n const sym = Symbol();\n set(obj5.a, sym, 7); // true\n obj5; // {a: {Symbol(): 7}}\n*/\n\nfunction set(obj, propsArg, value) {\n var props, lastProp;\n if (Array.isArray(propsArg)) {\n props = propsArg.slice(0);\n }\n if (typeof propsArg == 'string') {\n props = propsArg.split('.');\n }\n if (typeof propsArg == 'symbol') {\n props = [propsArg];\n }\n if (!Array.isArray(props)) {\n throw new Error('props arg must be an array, a string or a symbol');\n }\n lastProp = props.pop();\n if (!lastProp) {\n return false;\n }\n prototypeCheck(lastProp);\n var thisProp;\n while ((thisProp = props.shift())) {\n prototypeCheck(thisProp);\n if (typeof obj[thisProp] == 'undefined') {\n obj[thisProp] = {};\n }\n obj = obj[thisProp];\n if (!obj || typeof obj != 'object') {\n return false;\n }\n }\n obj[lastProp] = value;\n return true;\n}\n\nfunction prototypeCheck(prop) {\n // coercion is intentional to catch prop values like `['__proto__']`\n if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') {\n throw new Error('setting of prototype values not supported');\n }\n}\n\nexport {objectSafeSet as default};\n", "import set from 'just-safe-set'\nimport getDefaultConfig from 'ipfs-core-config/config'\n\n/**\n * @typedef {import('ipfs-core-types/src/config').Config} Config\n *\n * @typedef {object} Transformer\n * @property {string} description\n * @property {(config: Config) => Config} transform\n */\n\n/**\n * @type {Record}\n */\nexport const profiles = {\n server: {\n description: 'Recommended for nodes with public IPv4 address (servers, VPSes, etc.), disables host and content discovery and UPnP in local networks.',\n transform: (config) => {\n set(config, 'Discovery.MDNS.Enabled', false)\n set(config, 'Discovery.webRTCStar.Enabled', false)\n config.Swarm = {\n ...(config.Swarm || {}),\n DisableNatPortMap: true\n }\n\n return config\n }\n },\n 'local-discovery': {\n description: 'Sets default values to fields affected by `server` profile, enables discovery and UPnP in local networks.',\n transform: (config) => {\n set(config, 'Discovery.MDNS.Enabled', true)\n set(config, 'Discovery.webRTCStar.Enabled', true)\n set(config, 'Swarm', {\n ...(config.Swarm || {}),\n DisableNatPortMap: false\n })\n\n return config\n }\n },\n test: {\n description: 'Reduces external interference, useful for running ipfs in test environments. Note that with these settings node won\\'t be able to talk to the rest of the network without manual bootstrap.',\n transform: (config) => {\n const defaultConfig = getDefaultConfig()\n\n set(config, 'Addresses.API', defaultConfig.Addresses.API ? '/ip4/127.0.0.1/tcp/0' : '')\n set(config, 'Addresses.Gateway', defaultConfig.Addresses.Gateway ? '/ip4/127.0.0.1/tcp/0' : '')\n set(config, 'Addresses.Swarm', defaultConfig.Addresses.Swarm.length ? ['/ip4/127.0.0.1/tcp/0'] : [])\n set(config, 'Addresses.Delegates', [])\n set(config, 'Bootstrap', [])\n set(config, 'Discovery.MDNS.Enabled', false)\n set(config, 'Discovery.webRTCStar.Enabled', false)\n set(config, 'Swarm', {\n ...(config.Swarm || {}),\n DisableNatPortMap: true\n })\n\n return config\n }\n },\n 'default-networking': {\n description: 'Restores default network settings. Inverse profile of the `test` profile.',\n transform: (config) => {\n const defaultConfig = getDefaultConfig()\n\n set(config, 'Addresses.API', defaultConfig.Addresses.API)\n set(config, 'Addresses.Gateway', defaultConfig.Addresses.Gateway)\n set(config, 'Addresses.Swarm', defaultConfig.Addresses.Swarm)\n set(config, 'Addresses.Delegates', defaultConfig.Addresses.Delegates)\n set(config, 'Bootstrap', defaultConfig.Bootstrap)\n set(config, 'Discovery.MDNS.Enabled', defaultConfig.Discovery.MDNS.Enabled)\n set(config, 'Discovery.webRTCStar.Enabled', defaultConfig.Discovery.webRTCStar.Enabled)\n set(config, 'Swarm', {\n ...(config.Swarm || {}),\n DisableNatPortMap: false\n })\n\n return config\n }\n },\n lowpower: {\n description: 'Reduces daemon overhead on the system. May affect node functionality,performance of content discovery and data fetching may be degraded. Recommended for low power systems.',\n transform: (config) => {\n const Swarm = config.Swarm || {}\n const ConnMgr = Swarm.ConnMgr || {}\n ConnMgr.LowWater = 20\n ConnMgr.HighWater = 40\n\n Swarm.ConnMgr = ConnMgr\n config.Swarm = Swarm\n\n return config\n }\n },\n 'default-power': {\n description: 'Inverse of \"lowpower\" profile.',\n transform: (config) => {\n const defaultConfig = getDefaultConfig()\n\n config.Swarm = defaultConfig.Swarm\n\n return config\n }\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { logger } from '@libp2p/logger'\nimport { profiles } from './profiles.js'\n\nconst log = logger('ipfs:core:config')\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createConfig ({ repo }) {\n return {\n getAll: withTimeoutOption(getAll),\n get: withTimeoutOption(get),\n set: withTimeoutOption(set),\n replace: withTimeoutOption(replace),\n profiles: {\n apply: withTimeoutOption(applyProfile),\n list: withTimeoutOption(listProfiles)\n }\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"getAll\"]}\n */\n async function getAll (options = {}) { // eslint-disable-line require-await\n return repo.config.getAll(options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"get\"]}\n */\n async function get (key, options) { // eslint-disable-line require-await\n if (!key) {\n return Promise.reject(new Error('key argument is required'))\n }\n\n return repo.config.get(key, options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"set\"]}\n */\n async function set (key, value, options) { // eslint-disable-line require-await\n return repo.config.set(key, value, options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config').API<{}>[\"replace\"]}\n */\n async function replace (value, options) { // eslint-disable-line require-await\n return repo.config.replace(value, options)\n }\n\n /**\n * @type {import('ipfs-core-types/src/config/profiles').API<{}>[\"apply\"]}\n */\n async function applyProfile (profileName, options = { dryRun: false }) {\n const { dryRun } = options\n\n const profile = profiles[profileName]\n\n if (!profile) {\n throw new Error(`No profile with name '${profileName}' exists`)\n }\n\n try {\n const oldCfg = await repo.config.getAll(options)\n let newCfg = JSON.parse(JSON.stringify(oldCfg)) // clone\n newCfg = profile.transform(newCfg)\n\n if (!dryRun) {\n await repo.config.replace(newCfg, options)\n }\n\n // Scrub private key from output\n // @ts-expect-error `oldCfg.Identity` maybe undefined\n delete oldCfg.Identity.PrivKey\n delete newCfg.Identity.PrivKey\n\n return { original: oldCfg, updated: newCfg }\n } catch (/** @type {any} */ err) {\n log(err)\n\n throw new Error(`Could not apply profile '${profileName}' to config: ${err.message}`)\n }\n }\n}\n\n/**\n * @type {import('ipfs-core-types/src/config/profiles').API<{}>[\"list\"]}\n */\nasync function listProfiles (_options) { // eslint-disable-line require-await\n return Object.keys(profiles).map(name => ({\n name,\n description: profiles[name].description\n }))\n}\n", "import { bytes as binary, CID } from './index.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\n\nfunction readonly ({ enumerable = true, configurable = false } = {}) {\n return { enumerable, configurable, writable: false }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable<[string, CID]>}\n */\nfunction * linksWithin (path, value) {\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n if (cid) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n if (cid) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable<[string, CID]>}\n */\nfunction * links (source, base) {\n if (source == null || source instanceof Uint8Array) {\n return\n }\n const cid = CID.asCID(source)\n if (cid) {\n yield [base.join('/'), cid]\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield * linksWithin(path, value)\n }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable}\n */\nfunction * treeWithin (path, value) {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n yield elementPath.join('/')\n if (typeof element === 'object' && !CID.asCID(element)) {\n yield * tree(element, elementPath)\n }\n }\n } else {\n yield * tree(value, path)\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable}\n */\nfunction * tree (source, base) {\n if (source == null || typeof source !== 'object') {\n return\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield path.join('/')\n if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && !CID.asCID(value)) {\n yield * treeWithin(path, value)\n }\n }\n}\n\n/**\n *\n * @template T\n * @param {T} source\n * @param {string[]} path\n * @returns {API.BlockCursorView}\n */\nfunction get (source, path) {\n let node = /** @type {Record} */(source)\n for (const [index, key] of path.entries()) {\n node = node[key]\n if (node == null) {\n throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)\n }\n const cid = CID.asCID(node)\n if (cid) {\n return { value: cid, remaining: path.slice(index + 1).join('/') }\n }\n }\n return { value: node }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} C - multicodec code corresponding to codec used to encode the block\n * @template {number} A - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @implements {API.BlockView}\n */\nclass Block {\n /**\n * @param {object} options\n * @param {CID} options.cid\n * @param {API.ByteView} options.bytes\n * @param {T} options.value\n */\n constructor ({ cid, bytes, value }) {\n if (!cid || !bytes || typeof value === 'undefined') { throw new Error('Missing required argument') }\n\n this.cid = cid\n this.bytes = bytes\n this.value = value\n this.asBlock = this\n\n // Mark all the properties immutable\n Object.defineProperties(this, {\n cid: readonly(),\n bytes: readonly(),\n value: readonly(),\n asBlock: readonly()\n })\n }\n\n links () {\n return links(this.value, [])\n }\n\n tree () {\n return tree(this.value, [])\n }\n\n /**\n *\n * @param {string} [path]\n * @returns {API.BlockCursorView}\n */\n get (path = '/') {\n return get(this.value, path.split('/').filter(Boolean))\n }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {T} options.value\n * @param {API.BlockEncoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function encode ({ value, codec, hasher }) {\n if (typeof value === 'undefined') throw new Error('Missing required argument \"value\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const bytes = codec.encode(value)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(\n 1,\n codec.code,\n hash\n )\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function decode ({ bytes, codec, hasher }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(1, codec.code, hash)\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @typedef {object} RequiredCreateOptions\n * @property {CID} options.cid\n */\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {{ cid: API.Link, value:T, codec?: API.BlockDecoder, bytes: API.ByteView }|{cid:API.Link, bytes:API.ByteView, value?:void, codec:API.BlockDecoder}} options\n * @returns {API.BlockView}\n */\nfunction createUnsafe ({ bytes, cid, value: maybeValue, codec }) {\n const value = maybeValue !== undefined\n ? maybeValue\n : (codec && codec.decode(bytes))\n\n if (value === undefined) throw new Error('Missing required argument, must either provide \"value\" or \"codec\"')\n\n return new Block({\n // eslint-disable-next-line object-shorthand\n cid: /** @type {CID} */ (cid),\n bytes,\n value\n })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {object} options\n * @param {API.Link} options.cid\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function create ({ bytes, cid, hasher, codec }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!hasher) throw new Error('Missing required argument \"hasher\"')\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error('CID hash does not match bytes')\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec\n })\n}\n\nexport { encode, decode, create, createUnsafe, Block }\n", "import varint from 'varint'\n\nexport const CIDV0_BYTES = {\n SHA2_256: 0x12,\n LENGTH: 0x20,\n DAG_PB: 0x70\n}\n\nexport const V2_HEADER_LENGTH = /* characteristics */ 16 /* v1 offset */ + 8 /* v1 size */ + 8 /* index offset */ + 8\n\n/**\n * Decodes varint and seeks the buffer\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @param {import('./coding').Seekable} seeker\n * @returns {number}\n */\nexport function decodeVarint (bytes, seeker) {\n if (!bytes.length) {\n throw new Error('Unexpected end of data')\n }\n const i = varint.decode(bytes)\n seeker.seek(/** @type {number} */(varint.decode.bytes))\n return i\n}\n\n/**\n * Decode v2 header\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.exactly(V2_HEADER_LENGTH, true) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @returns {import('./coding').CarV2FixedHeader}\n */\nexport function decodeV2Header (bytes) {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let offset = 0\n const header = {\n version: 2,\n /** @type {[bigint, bigint]} */\n characteristics: [\n dv.getBigUint64(offset, true),\n dv.getBigUint64(offset += 8, true)\n ],\n dataOffset: Number(dv.getBigUint64(offset += 8, true)),\n dataSize: Number(dv.getBigUint64(offset += 8, true)),\n indexOffset: Number(dv.getBigUint64(offset += 8, true))\n }\n return header\n}\n\n/**\n * Checks the length of the multihash to be read afterwards\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n */\nexport function getMultihashLength (bytes) {\n // | code | length | .... |\n // where both code and length are varints, so we have to decode\n // them first before we can know total length\n\n varint.decode(bytes) // code\n const codeLength = /** @type {number} */(varint.decode.bytes)\n const length = varint.decode(bytes.subarray(varint.decode.bytes))\n const lengthLength = /** @type {number} */(varint.decode.bytes)\n const mhLength = codeLength + lengthLength + length\n\n return mhLength\n}\n", "/** Auto-generated with @ipld/schema@v4.2.0 at Thu Sep 14 2023 from IPLD Schema:\n *\n * # CarV1HeaderOrV2Pragma is a more relaxed form, and can parse {version:x} where\n * # roots are optional. This is typically useful for the {verison:2} CARv2\n * # pragma.\n *\n * type CarV1HeaderOrV2Pragma struct {\n * \troots optional [&Any]\n * \t# roots is _not_ optional for CarV1 but we defer that check within code to\n * \t# gracefully handle the V2 case where it's just {version:X}\n * \tversion Int\n * }\n *\n * # CarV1Header is the strict form of the header, and requires roots to be\n * # present. This is compatible with the CARv1 specification.\n *\n * # type CarV1Header struct {\n * # \troots [&Any]\n * # \tversion Int\n * # }\n *\n */\n\nconst Kinds = {\n Null: /** @returns {undefined|null} */ (/** @type {any} */ obj) => obj === null ? obj : undefined,\n Int: /** @returns {undefined|number} */ (/** @type {any} */ obj) => Number.isInteger(obj) ? obj : undefined,\n Float: /** @returns {undefined|number} */ (/** @type {any} */ obj) => typeof obj === 'number' && Number.isFinite(obj) ? obj : undefined,\n String: /** @returns {undefined|string} */ (/** @type {any} */ obj) => typeof obj === 'string' ? obj : undefined,\n Bool: /** @returns {undefined|boolean} */ (/** @type {any} */ obj) => typeof obj === 'boolean' ? obj : undefined,\n Bytes: /** @returns {undefined|Uint8Array} */ (/** @type {any} */ obj) => obj instanceof Uint8Array ? obj : undefined,\n Link: /** @returns {undefined|object} */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID === obj ? obj : undefined,\n List: /** @returns {undefined|Array} */ (/** @type {any} */ obj) => Array.isArray(obj) ? obj : undefined,\n Map: /** @returns {undefined|object} */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : undefined\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Types = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Types['CarV1HeaderOrV2Pragma > roots (anon)'](obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Types.Int(obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Reprs = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Reprs['CarV1HeaderOrV2Pragma > roots (anon)'](value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Reprs.Int(value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n\nexport const CarV1HeaderOrV2Pragma = {\n toTyped: Types.CarV1HeaderOrV2Pragma,\n toRepresentation: Reprs.CarV1HeaderOrV2Pragma\n}\n", "import { decode as decodeDagCbor } from '@ipld/dag-cbor'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CIDV0_BYTES, decodeV2Header, decodeVarint, getMultihashLength, V2_HEADER_LENGTH } from './decoder-common.js'\nimport { CarV1HeaderOrV2Pragma } from './header-validator.js'\n\n/**\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').BlockHeader} BlockHeader\n * @typedef {import('./api').BlockIndex} BlockIndex\n * @typedef {import('./coding').BytesReader} BytesReader\n * @typedef {import('./coding').CarHeader} CarHeader\n * @typedef {import('./coding').CarV2Header} CarV2Header\n * @typedef {import('./coding').CarV2FixedHeader} CarV2FixedHeader\n * @typedef {import('./coding').CarDecoder} CarDecoder\n */\n\n/**\n * Reads header data from a `BytesReader`. The header may either be in the form\n * of a `CarHeader` or `CarV2Header` depending on the CAR being read.\n *\n * @name async decoder.readHeader(reader)\n * @param {BytesReader} reader\n * @param {number} [strictVersion]\n * @returns {Promise}\n */\nexport async function readHeader (reader, strictVersion) {\n const length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR header (zero length)')\n }\n const header = await reader.exactly(length, true)\n const block = decodeDagCbor(header)\n if (CarV1HeaderOrV2Pragma.toTyped(block) === undefined) {\n throw new Error('Invalid CAR header format')\n }\n if ((block.version !== 1 && block.version !== 2) || (strictVersion !== undefined && block.version !== strictVersion)) {\n throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== undefined ? ` (expected ${strictVersion})` : ''}`)\n }\n if (block.version === 1) {\n // CarV1HeaderOrV2Pragma makes roots optional, let's make it mandatory\n if (!Array.isArray(block.roots)) {\n throw new Error('Invalid CAR header format')\n }\n return block\n }\n // version 2\n if (block.roots !== undefined) {\n throw new Error('Invalid CAR header format')\n }\n const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true))\n reader.seek(v2Header.dataOffset - reader.pos)\n const v1Header = await readHeader(reader, 1)\n return Object.assign(v1Header, v2Header)\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nasync function readCid (reader) {\n const first = await reader.exactly(2, false)\n if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) {\n // cidv0 32-byte sha2-256\n const bytes = await reader.exactly(34, true)\n const multihash = Digest.decode(bytes)\n return CID.create(0, CIDV0_BYTES.DAG_PB, multihash)\n }\n\n const version = decodeVarint(await reader.upTo(8), reader)\n if (version !== 1) {\n throw new Error(`Unexpected CID version (${version})`)\n }\n const codec = decodeVarint(await reader.upTo(8), reader)\n const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true)\n const multihash = Digest.decode(bytes)\n return CID.create(version, codec, multihash)\n}\n\n/**\n * Reads the leading data of an individual block from CAR data from a\n * `BytesReader`. Returns a `BlockHeader` object which contains\n * `{ cid, length, blockLength }` which can be used to either index the block\n * or read the block binary data.\n *\n * @name async decoder.readBlockHead(reader)\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nexport async function readBlockHead (reader) {\n // length includes a CID + Binary, where CID has a variable length\n // we have to deal with\n const start = reader.pos\n let length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR section (zero length)')\n }\n length += (reader.pos - start)\n const cid = await readCid(reader)\n const blockLength = length - Number(reader.pos - start) // subtract CID length\n\n return { cid, length, blockLength }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nasync function readBlock (reader) {\n const { cid, blockLength } = await readBlockHead(reader)\n const bytes = await reader.exactly(blockLength, true)\n return { bytes, cid }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise}\n */\nasync function readBlockIndex (reader) {\n const offset = reader.pos\n const { cid, length, blockLength } = await readBlockHead(reader)\n const index = { cid, length, blockLength, offset, blockOffset: reader.pos }\n reader.seek(index.blockLength)\n return index\n}\n\n/**\n * Creates a `CarDecoder` from a `BytesReader`. The `CarDecoder` is as async\n * interface that will consume the bytes from the `BytesReader` to yield a\n * `header()` and either `blocks()` or `blocksIndex()` data.\n *\n * @name decoder.createDecoder(reader)\n * @param {BytesReader} reader\n * @returns {CarDecoder}\n */\nexport function createDecoder (reader) {\n const headerPromise = (async () => {\n const header = await readHeader(reader)\n if (header.version === 2) {\n const v1length = reader.pos - header.dataOffset\n reader = limitReader(reader, header.dataSize - v1length)\n }\n return header\n })()\n\n return {\n header: () => headerPromise,\n\n async * blocks () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlock(reader)\n }\n },\n\n async * blocksIndex () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlockIndex(reader)\n }\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from a `Uint8Array`.\n *\n * @name decoder.bytesReader(bytes)\n * @param {Uint8Array} bytes\n * @returns {BytesReader}\n */\nexport function bytesReader (bytes) {\n let pos = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos))\n return out\n },\n\n async exactly (length, seek = false) {\n if (length > bytes.length - pos) {\n throw new Error('Unexpected end of data')\n }\n const out = bytes.subarray(pos, pos + length)\n if (seek) {\n pos += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * @ignore\n * reusable reader for streams and files, we just need a way to read an\n * additional chunk (of some undetermined size) and a way to close the\n * reader when finished\n * @param {() => Promise} readChunk\n * @returns {BytesReader}\n */\nexport function chunkReader (readChunk /*, closer */) {\n let pos = 0\n let have = 0\n let offset = 0\n let currentChunk = new Uint8Array(0)\n\n const read = async (/** @type {number} */ length) => {\n have = currentChunk.length - offset\n const bufa = [currentChunk.subarray(offset)]\n while (have < length) {\n const chunk = await readChunk()\n if (chunk == null) {\n break\n }\n /* c8 ignore next 8 */\n // undo this ignore ^ when we have a fd implementation that can seek()\n if (have < 0) { // because of a seek()\n /* c8 ignore next 4 */\n // toohard to test the else\n if (chunk.length > have) {\n bufa.push(chunk.subarray(-have))\n } // else discard\n } else {\n bufa.push(chunk)\n }\n have += chunk.length\n }\n currentChunk = new Uint8Array(bufa.reduce((p, c) => p + c.length, 0))\n let off = 0\n for (const b of bufa) {\n currentChunk.set(b, off)\n off += b.length\n }\n offset = 0\n }\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length))\n },\n\n async exactly (length, seek = false) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n if (currentChunk.length - offset < length) {\n throw new Error('Unexpected end of data')\n }\n const out = currentChunk.subarray(offset, offset + length)\n if (seek) {\n pos += length\n offset += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n offset += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from an `AsyncIterable`, which allows for\n * consumption of CAR data from a streaming source.\n *\n * @name decoder.asyncIterableReader(asyncIterable)\n * @param {AsyncIterable} asyncIterable\n * @returns {BytesReader}\n */\nexport function asyncIterableReader (asyncIterable) {\n const iterator = asyncIterable[Symbol.asyncIterator]()\n\n async function readChunk () {\n const next = await iterator.next()\n if (next.done) {\n return null\n }\n return next.value\n }\n\n return chunkReader(readChunk)\n}\n\n/**\n * Wraps a `BytesReader` in a limiting `BytesReader` which limits maximum read\n * to `byteLimit` bytes. It _does not_ update `pos` of the original\n * `BytesReader`.\n *\n * @name decoder.limitReader(reader, byteLimit)\n * @param {BytesReader} reader\n * @param {number} byteLimit\n * @returns {BytesReader}\n */\nexport function limitReader (reader, byteLimit) {\n let bytesRead = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n let bytes = await reader.upTo(length)\n if (bytes.length + bytesRead > byteLimit) {\n bytes = bytes.subarray(0, byteLimit - bytesRead)\n }\n return bytes\n },\n\n async exactly (length, seek = false) {\n const bytes = await reader.exactly(length, seek)\n if (bytes.length + bytesRead > byteLimit) {\n throw new Error('Unexpected end of data')\n }\n if (seek) {\n bytesRead += length\n }\n return bytes\n },\n\n seek (length) {\n bytesRead += length\n reader.seek(length)\n },\n\n get pos () {\n return reader.pos\n }\n }\n}\n", "import { encode as dagCborEncode } from '@ipld/dag-cbor'\nimport varint from 'varint'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./coding').CarEncoder} CarEncoder\n * @typedef {import('./coding').IteratorChannel_Writer} IteratorChannel_Writer\n */\n\nconst CAR_V1_VERSION = 1\n\n/**\n * Create a header from an array of roots.\n *\n * @param {CID[]} roots\n * @returns {Uint8Array}\n */\nexport function createHeader (roots) {\n const headerBytes = dagCborEncode({ version: CAR_V1_VERSION, roots })\n const varintBytes = varint.encode(headerBytes.length)\n const header = new Uint8Array(varintBytes.length + headerBytes.length)\n header.set(varintBytes, 0)\n header.set(headerBytes, varintBytes.length)\n return header\n}\n\n/**\n * @param {IteratorChannel_Writer} writer\n * @returns {CarEncoder}\n */\nfunction createEncoder (writer) {\n // none of this is wrapped in a mutex, that needs to happen above this to\n // avoid overwrites\n\n return {\n /**\n * @param {CID[]} roots\n * @returns {Promise}\n */\n async setRoots (roots) {\n const bytes = createHeader(roots)\n await writer.write(bytes)\n },\n\n /**\n * @param {Block} block\n * @returns {Promise}\n */\n async writeBlock (block) {\n const { cid, bytes } = block\n await writer.write(new Uint8Array(varint.encode(cid.bytes.length + bytes.length)))\n await writer.write(cid.bytes)\n if (bytes.length) {\n // zero-length blocks are valid, but it'd be safer if we didn't write them\n await writer.write(bytes)\n }\n },\n\n /**\n * @returns {Promise}\n */\n async close () {\n await writer.end()\n },\n\n /**\n * @returns {number}\n */\n version () {\n return CAR_V1_VERSION\n }\n }\n}\n\nexport { createEncoder }\n", "/**\n * @template {any} T\n * @typedef {import('./coding').IteratorChannel} IteratorChannel\n */\n\nfunction noop () {}\n\n/**\n * @template {any} T\n * @returns {IteratorChannel}\n */\nexport function create () {\n /** @type {T[]} */\n const chunkQueue = []\n /** @type {Promise | null} */\n let drainer = null\n let drainerResolver = noop\n let ended = false\n /** @type {Promise> | null} */\n let outWait = null\n let outWaitResolver = noop\n\n const makeDrainer = () => {\n if (!drainer) {\n drainer = new Promise((resolve) => {\n drainerResolver = () => {\n drainer = null\n drainerResolver = noop\n resolve()\n }\n })\n }\n return drainer\n }\n\n /**\n * @returns {IteratorChannel}\n */\n const writer = {\n /**\n * @param {T} chunk\n * @returns {Promise}\n */\n write (chunk) {\n chunkQueue.push(chunk)\n const drainer = makeDrainer()\n outWaitResolver()\n return drainer\n },\n\n async end () {\n ended = true\n const drainer = makeDrainer()\n outWaitResolver()\n await drainer\n }\n }\n\n /** @type {AsyncIterator} */\n const iterator = {\n /** @returns {Promise>} */\n async next () {\n const chunk = chunkQueue.shift()\n if (chunk) {\n if (chunkQueue.length === 0) {\n drainerResolver()\n }\n return { done: false, value: chunk }\n }\n\n if (ended) {\n drainerResolver()\n return { done: true, value: undefined }\n }\n\n if (!outWait) {\n outWait = new Promise((resolve) => {\n outWaitResolver = () => {\n outWait = null\n outWaitResolver = noop\n return resolve(iterator.next())\n }\n })\n }\n\n return outWait\n }\n }\n\n return { writer, iterator }\n}\n", "import { CID } from 'multiformats/cid'\nimport { bytesReader, readHeader } from './decoder.js'\nimport { createEncoder, createHeader } from './encoder.js'\nimport { create as iteratorChannel } from './iterator-channel.js'\n\n/**\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').BlockWriter} BlockWriter\n * @typedef {import('./api').WriterChannel} WriterChannel\n * @typedef {import('./coding').CarEncoder} CarEncoder\n * @typedef {import('./coding').IteratorChannel} IteratorChannel\n */\n\n/**\n * Provides a writer interface for the creation of CAR files.\n *\n * Creation of a `CarWriter` involves the instatiation of an input / output pair\n * in the form of a `WriterChannel`, which is a\n * `{ writer:CarWriter, out:AsyncIterable }` pair. These two\n * components form what can be thought of as a stream-like interface. The\n * `writer` component (an instantiated `CarWriter`), has methods to\n * {@link CarWriter.put `put()`} new blocks and {@link CarWriter.put `close()`}\n * the writing operation (finalising the CAR archive). The `out` component is\n * an `AsyncIterable` that yields the bytes of the archive. This can be\n * redirected to a file or other sink. In Node.js, you can use the\n * [`Readable.from()`](https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options)\n * API to convert this to a standard Node.js stream, or it can be directly fed\n * to a\n * [`stream.pipeline()`](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback).\n *\n * The channel will provide a form of backpressure. The `Promise` from a\n * `write()` won't resolve until the resulting data is drained from the `out`\n * iterable.\n *\n * It is also possible to ignore the `Promise` from `write()` calls and allow\n * the generated data to queue in memory. This should be avoided for large CAR\n * archives of course due to the memory costs and potential for memory overflow.\n *\n * Load this class with either\n * `import { CarWriter } from '@ipld/car/writer'`\n * (`const { CarWriter } = require('@ipld/car/writer')`). Or\n * `import { CarWriter } from '@ipld/car'`\n * (`const { CarWriter } = require('@ipld/car')`). The former will likely\n * result in smaller bundle sizes where this is important.\n *\n * @name CarWriter\n * @class\n * @implements {BlockWriter}\n */\nexport class CarWriter {\n /**\n * @param {CID[]} roots\n * @param {CarEncoder} encoder\n */\n constructor (roots, encoder) {\n this._encoder = encoder\n /** @type {Promise} */\n this._mutex = encoder.setRoots(roots)\n this._ended = false\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {Promise} The returned promise will only resolve once the\n * bytes this block generates are written to the `out` iterable.\n */\n async put (block) {\n if (!(block.bytes instanceof Uint8Array) || !block.cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n if (this._ended) {\n throw new Error('Already closed')\n }\n const cid = CID.asCID(block.cid)\n if (!cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n this._mutex = this._mutex.then(() => this._encoder.writeBlock({ cid, bytes: block.bytes }))\n return this._mutex\n }\n\n /**\n * Finalise the CAR archive and signal that the `out` iterable should end once\n * any remaining bytes are written.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @returns {Promise}\n */\n async close () {\n if (this._ended) {\n throw new Error('Already closed')\n }\n await this._mutex\n this._ended = true\n return this._encoder.close()\n }\n\n /**\n * Returns the version number of the CAR file being written\n *\n * @returns {number}\n */\n version () {\n return this._encoder.version()\n }\n\n /**\n * Create a new CAR writer \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable }` pair.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {CID[] | CID | void} roots\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable }`.\n */\n static create (roots) {\n roots = toRoots(roots)\n const { encoder, iterator } = encodeWriter()\n const writer = new CarWriter(roots, encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Create a new CAR appender \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable }` pair.\n * This appender does not consider roots and does not produce a CAR header.\n * It is designed to append blocks to an _existing_ CAR archive. It is\n * expected that `out` will be concatenated onto the end of an existing\n * archive that already has a properly formatted header.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable }`.\n */\n static createAppender () {\n const { encoder, iterator } = encodeWriter()\n encoder.setRoots = () => Promise.resolve()\n const writer = new CarWriter([], encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Update the list of roots in the header of an existing CAR as represented\n * in a Uint8Array.\n *\n * This operation is an _overwrite_, the total length of the CAR will not be\n * modified. A rejection will occur if the new header will not be the same\n * length as the existing header, in which case the CAR will not be modified.\n * It is the responsibility of the user to ensure that the roots being\n * replaced encode as the same length as the new roots.\n *\n * The byte array passed in an argument will be modified and also returned\n * upon successful modification.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {Uint8Array} bytes\n * @param {CID[]} roots - A new list of roots to replace the existing list in\n * the CAR header. The new header must take up the same number of bytes as the\n * existing header, so the roots should collectively be the same byte length\n * as the existing roots.\n * @returns {Promise}\n */\n static async updateRootsInBytes (bytes, roots) {\n const reader = bytesReader(bytes)\n await readHeader(reader)\n const newHeader = createHeader(roots)\n if (Number(reader.pos) !== newHeader.length) {\n throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${reader.pos} bytes, new header is ${newHeader.length} bytes)`)\n }\n bytes.set(newHeader, 0)\n return bytes\n }\n}\n\n/**\n * @class\n * @implements {AsyncIterable}\n */\nexport class CarWriterOut {\n /**\n * @param {AsyncIterator} iterator\n */\n constructor (iterator) {\n this._iterator = iterator\n }\n\n [Symbol.asyncIterator] () {\n if (this._iterating) {\n throw new Error('Multiple iterator not supported')\n }\n this._iterating = true\n return this._iterator\n }\n}\n\nfunction encodeWriter () {\n /** @type {IteratorChannel} */\n const iw = iteratorChannel()\n const { writer, iterator } = iw\n const encoder = createEncoder(writer)\n return { encoder, iterator }\n}\n\n/**\n * @private\n * @param {CID[] | CID | void} roots\n * @returns {CID[]}\n */\nfunction toRoots (roots) {\n if (roots === undefined) {\n return []\n }\n\n if (!Array.isArray(roots)) {\n const cid = CID.asCID(roots)\n if (!cid) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n return [cid]\n }\n\n const _roots = []\n for (const root of roots) {\n const _root = CID.asCID(root)\n if (!_root) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n _roots.push(_root)\n }\n return _roots\n}\n\nexport const __browser = true\n", "import { base58btc } from './bases/base58.js'\n\n/**\n * @template [C=number] - multicodec code corresponding to codec used to encode the block\n * @template [A=number] - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template [V=0|1] - CID version\n * @typedef {import('./cid').CID} CID\n */\n\n/**\n * @template [T=unknown] - Logical type of the data encoded in the block\n * @template [C=number] - multicodec code corresponding to codec used to encode the block\n * @template [A=number] - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template [V=0|1] - CID version\n * @typedef {import('./block/interface.js').BlockView} BlockView\n */\n\n/**\n * @param {object} options\n * @param {CID} options.cid\n * @param {(cid: CID) => Promise} options.load\n * @param {Set} [options.seen]\n */\nconst walk = async ({ cid, load, seen }) => {\n seen = seen || new Set()\n const b58Cid = cid.toString(base58btc)\n if (seen.has(b58Cid)) {\n return\n }\n\n const block = await load(cid)\n seen.add(b58Cid)\n\n if (block === null) { // the loader signals with `null` that we should skip this block\n return\n }\n\n for (const [, cid] of block.links()) {\n await walk({ cid, load, seen })\n }\n}\n\nexport { walk }\n", "import { CID } from 'multiformats/cid'\nimport { createUnsafe } from 'multiformats/block'\nimport { CarWriter } from '@ipld/car/writer'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { logger } from '@libp2p/logger'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as json from 'multiformats/codecs/json'\nimport { walk } from 'multiformats/traversal'\n\nconst log = logger('ipfs:components:dag:import')\n\n// blocks that we're OK with not inspecting for links\n/** @type {number[]} */\nconst NO_LINKS_CODECS = [\n raw.code, // raw\n json.code // JSON\n]\n\n/**\n * @typedef {import('../../types').Preload} Preload\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('@ipld/car/api').BlockWriter} BlockWriter\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @template T\n * @template C\n * @template A\n * @template V\n * @typedef {import('multiformats/block').Block} Block\n */\n\n/**\n * @param {object} config\n * @param {IPFSRepo} config.repo\n * @param {Preload} config.preload\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createExport ({ repo, preload, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"export\"]}\n */\n async function * dagExport (root, options = {}) {\n if (options.preload !== false) {\n preload(root)\n }\n\n const cid = CID.asCID(root)\n if (!cid) {\n throw new Error(`Unexpected error converting CID type: ${root}`)\n }\n\n log(`Exporting ${cid} as car`)\n const { writer, out } = await CarWriter.create([cid])\n\n // we need to write with one async channel and send the CarWriter output\n // with another to the caller, but if the write causes an error we capture\n // that and make sure it gets propagated\n /** @type {Error|null} */\n let err = null\n ;(async () => {\n try {\n const load = makeLoader(repo, writer, {\n signal: options.signal,\n timeout: options.timeout\n }, codecs)\n await walk({ cid, load })\n } catch (/** @type {any} */ e) {\n err = e\n } finally {\n writer.close()\n }\n })()\n\n for await (const chunk of out) {\n if (err) {\n break\n }\n yield chunk\n }\n if (err) {\n throw err\n }\n }\n\n return withTimeoutOption(dagExport)\n}\n\n/**\n * @param {IPFSRepo} repo\n * @param {BlockWriter} writer\n * @param {AbortOptions} options\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @returns {(cid:CID)=>Promise|null>}\n */\nfunction makeLoader (repo, writer, options, codecs) {\n return async (cid) => {\n const codec = await codecs.getCodec(cid.code)\n\n if (!codec) {\n throw new Error(`Can't decode links in block with codec 0x${cid.code.toString(16)} to form complete DAG`)\n }\n\n const bytes = await repo.blocks.get(cid, options)\n\n log(`Adding block ${cid} to car`)\n await writer.put({ cid, bytes })\n\n if (NO_LINKS_CODECS.includes(cid.code)) {\n return null // skip this block, no need to look inside\n }\n\n return createUnsafe({ bytes, cid, codec })\n }\n}\n", "\n/**\n * Returns the first result from an (async) iterable, unless empty, in which\n * case returns `undefined`\n */\nexport default async function first (source: AsyncIterable | Iterable): Promise {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry\n }\n\n return undefined\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport first from 'it-first'\nimport last from 'it-last'\nimport { resolve } from '../../utils.js'\nimport errCode from 'err-code'\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createGet ({ codecs, repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"get\"]}\n */\n const get = async function get (cid, options = {}) {\n if (options.preload !== false) {\n preload(cid)\n }\n\n if (options.path) {\n const entry = options.localResolve\n ? await first(resolve(cid, options.path, codecs, repo, options))\n : await last(resolve(cid, options.path, codecs, repo, options))\n /** @type {import('ipfs-core-types/src/dag').GetResult | undefined} - first and last will return undefined when empty */\n const result = (entry)\n\n if (!result) {\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n\n return result\n }\n\n const codec = await codecs.getCodec(cid.code)\n const block = await repo.blocks.get(cid, options)\n const node = codec.decode(block)\n\n return {\n value: node,\n remainderPath: ''\n }\n }\n\n return withTimeoutOption(get)\n}\n", "import {\n asyncIterableReader,\n bytesReader,\n createDecoder\n} from './decoder.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').RootsReader} RootsReader\n * @typedef {import('./coding').BytesReader} BytesReader\n */\n\n/**\n * @class\n * @implements {RootsReader}\n * @property {number} version The version number of the CAR referenced by this reader (should be `1`).\n */\nexport class CarIteratorBase {\n /**\n * @param {number} version\n * @param {CID[]} roots\n * @param {AsyncIterable|void} iterable\n */\n constructor (version, roots, iterable) {\n this._version = version\n this._roots = roots\n this._iterable = iterable\n this._decoded = false\n }\n\n get version () {\n return this._version\n }\n\n /**\n * @returns {Promise}\n */\n async getRoots () {\n return this._roots\n }\n}\n\n/**\n * Provides an iterator over all of the `Block`s in a CAR. Implements a\n * `BlockIterator` interface, or `AsyncIterable`. Where a `Block` is\n * a `{ cid:CID, bytes:Uint8Array }` pair.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const block of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarBlockiterator.fromBytes} or\n * {@link CarBlockiterator.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarBlockIterator` also implements the `RootsReader` interface and provides\n * the {@link CarBlockiterator.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarBlockIterator } from '@ipld/car/iterator'`\n * (`const { CarBlockIterator } = require('@ipld/car/iterator')`). Or\n * `import { CarBlockIterator } from '@ipld/car'`\n * (`const { CarBlockIterator } = require('@ipld/car')`).\n *\n * @name CarBlockIterator\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable}\n * @property {number} version The version number of the CAR referenced by this\n * iterator (should be `1`).\n */\nexport class CarBlockIterator extends CarIteratorBase {\n // inherited method\n /**\n * Get the list of roots defined by the CAR referenced by this iterator. May be\n * zero or more `CID`s.\n *\n * @function getRoots\n * @memberof CarBlockIterator\n * @instance\n * @async\n * @returns {Promise}\n */\n\n /**\n * @returns {AsyncIterator}\n */\n [Symbol.asyncIterator] () {\n if (this._decoded) {\n throw new Error('Cannot decode more than once')\n }\n /* c8 ignore next 3 */\n if (!this._iterable) {\n throw new Error('Block iterable not found')\n }\n this._decoded = true\n return this._iterable[Symbol.asyncIterator]()\n }\n\n /**\n * Instantiate a {@link CarBlockIterator} from a `Uint8Array` blob. Rather\n * than decoding the entire byte array prior to returning the iterator, as in\n * {@link CarReader.fromBytes}, only the header is decoded and the remainder\n * of the CAR is parsed as the `Block`s as yielded.\n *\n * @async\n * @static\n * @memberof CarBlockIterator\n * @param {Uint8Array} bytes\n * @returns {Promise}\n */\n static async fromBytes (bytes) {\n const { version, roots, iterator } = await fromBytes(bytes)\n return new CarBlockIterator(version, roots, iterator)\n }\n\n /**\n * Instantiate a {@link CarBlockIterator} from a `AsyncIterable`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * Rather than decoding the entire byte array prior to returning the iterator,\n * as in {@link CarReader.fromIterable}, only the header is decoded and the\n * remainder of the CAR is parsed as the `Block`s as yielded.\n *\n * @async\n * @static\n * @param {AsyncIterable} asyncIterable\n * @returns {Promise}\n */\n static async fromIterable (asyncIterable) {\n const { version, roots, iterator } = await fromIterable(asyncIterable)\n return new CarBlockIterator(version, roots, iterator)\n }\n}\n\n/**\n * Provides an iterator over all of the `CID`s in a CAR. Implements a\n * `CIDIterator` interface, or `AsyncIterable`. Similar to\n * {@link CarBlockIterator} but only yields the CIDs in the CAR.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const cid of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarCIDiterator.fromBytes} or\n * {@link CarCIDiterator.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarCIDIterator` also implements the `RootsReader` interface and provides\n * the {@link CarCIDiterator.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarCIDIterator } from '@ipld/car/iterator'`\n * (`const { CarCIDIterator } = require('@ipld/car/iterator')`). Or\n * `import { CarCIDIterator } from '@ipld/car'`\n * (`const { CarCIDIterator } = require('@ipld/car')`).\n *\n * @name CarCIDIterator\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable}\n * @property {number} version The version number of the CAR referenced by this\n * iterator (should be `1`).\n */\nexport class CarCIDIterator extends CarIteratorBase {\n // inherited method\n /**\n * Get the list of roots defined by the CAR referenced by this iterator. May be\n * zero or more `CID`s.\n *\n * @function getRoots\n * @memberof CarCIDIterator\n * @instance\n * @async\n * @returns {Promise}\n */\n\n /**\n * @returns {AsyncIterator}\n */\n [Symbol.asyncIterator] () {\n if (this._decoded) {\n throw new Error('Cannot decode more than once')\n }\n /* c8 ignore next 3 */\n if (!this._iterable) {\n throw new Error('Block iterable not found')\n }\n this._decoded = true\n const iterable = this._iterable[Symbol.asyncIterator]()\n return {\n async next () {\n const next = await iterable.next()\n if (next.done) {\n return next\n }\n return { done: false, value: next.value.cid }\n }\n }\n }\n\n /**\n * Instantiate a {@link CarCIDIterator} from a `Uint8Array` blob. Rather\n * than decoding the entire byte array prior to returning the iterator, as in\n * {@link CarReader.fromBytes}, only the header is decoded and the remainder\n * of the CAR is parsed as the `CID`s as yielded.\n *\n * @async\n * @static\n * @memberof CarCIDIterator\n * @param {Uint8Array} bytes\n * @returns {Promise}\n */\n static async fromBytes (bytes) {\n const { version, roots, iterator } = await fromBytes(bytes)\n return new CarCIDIterator(version, roots, iterator)\n }\n\n /**\n * Instantiate a {@link CarCIDIterator} from a `AsyncIterable`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * Rather than decoding the entire byte array prior to returning the iterator,\n * as in {@link CarReader.fromIterable}, only the header is decoded and the\n * remainder of the CAR is parsed as the `CID`s as yielded.\n *\n * @async\n * @static\n * @memberof CarCIDIterator\n * @param {AsyncIterable} asyncIterable\n * @returns {Promise}\n */\n static async fromIterable (asyncIterable) {\n const { version, roots, iterator } = await fromIterable(asyncIterable)\n return new CarCIDIterator(version, roots, iterator)\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable}>}\n */\nasync function fromBytes (bytes) {\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError('fromBytes() requires a Uint8Array')\n }\n return decodeIterator(bytesReader(bytes))\n}\n\n/**\n * @param {AsyncIterable} asyncIterable\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable}>}\n */\nasync function fromIterable (asyncIterable) {\n if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === 'function')) {\n throw new TypeError('fromIterable() requires an async iterable')\n }\n return decodeIterator(asyncIterableReader(asyncIterable))\n}\n\n/**\n * @private\n * @param {BytesReader} reader\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable}>}\n */\nasync function decodeIterator (reader) {\n const decoder = createDecoder(reader)\n const { version, roots } = await decoder.header()\n return { version, roots, iterator: decoder.blocks() }\n}\n", "import { CarBlockIterator } from '@ipld/car/iterator'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport itPeekable from 'it-peekable'\nimport drain from 'it-drain'\nimport map from 'it-map'\nimport { logger } from '@libp2p/logger'\nconst log = logger('ipfs:components:dag:import')\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('ipfs-core-types/src/dag/').ImportRootStatus} RootStatus\n */\n\n/**\n * @param {object} config\n * @param {IPFSRepo} config.repo\n */\nexport function createImport ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"import\"]}\n */\n async function * dagImport (sources, options = {}) {\n const release = await repo.gcLock.readLock()\n\n try {\n const abortOptions = { signal: options.signal, timeout: options.timeout }\n const peekable = itPeekable(sources)\n\n const { value, done } = await peekable.peek()\n\n if (done) {\n return\n }\n\n if (value) {\n // @ts-expect-error\n peekable.push(value)\n }\n\n /**\n * @type {AsyncIterable> | Iterable>}\n */\n let cars\n\n if (value instanceof Uint8Array) {\n // @ts-expect-error\n cars = [peekable]\n } else {\n // @ts-expect-error\n cars = peekable\n }\n\n for await (const car of cars) {\n const roots = await importCar(repo, abortOptions, car)\n\n if (options.pinRoots !== false) { // default=true\n for (const cid of roots) {\n let pinErrorMsg = ''\n\n try { // eslint-disable-line max-depth\n if (await repo.blocks.has(cid)) { // eslint-disable-line max-depth\n log(`Pinning root ${cid}`)\n await repo.pins.pinRecursively(cid)\n } else {\n pinErrorMsg = 'blockstore: block not found'\n }\n } catch (/** @type {any} */ err) {\n pinErrorMsg = err.message\n }\n\n yield { root: { cid, pinErrorMsg } }\n }\n }\n }\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(dagImport)\n}\n\n/**\n * @param {IPFSRepo} repo\n * @param {AbortOptions} options\n * @param {AsyncIterable} source\n * @returns {Promise}\n */\nasync function importCar (repo, options, source) {\n const reader = await CarBlockIterator.fromIterable(source)\n const roots = await reader.getRoots()\n\n await drain(\n repo.blocks.putMany(\n map(reader, ({ cid: key, bytes: value }) => {\n log(`Import block ${key}`)\n\n return { key, value }\n }),\n { signal: options.signal }\n )\n )\n\n return roots\n}\n", "import { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('../../types').Preload} config.preload\n */\nexport function createPut ({ repo, codecs, hashers, preload }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"put\"]}\n */\n async function put (dagNode, options = {}) {\n const release = options.pin ? await repo.gcLock.readLock() : null\n\n try {\n const storeCodec = await codecs.getCodec(options.storeCodec || 'dag-cbor')\n // TODO: doesn't getCodec throw? verify and possibly remove this\n if (!storeCodec) {\n throw new Error(`Unknown storeCodec ${options.storeCodec}, please configure additional BlockCodecs for this IPFS instance`)\n }\n\n if (options.inputCodec) {\n if (!(dagNode instanceof Uint8Array)) {\n throw new Error('Can only inputCodec on raw bytes that can be decoded')\n }\n const inputCodec = await codecs.getCodec(options.inputCodec)\n if (!inputCodec) {\n throw new Error(`Unknown inputCodec ${options.inputCodec}, please configure additional BlockCodecs for this IPFS instance`)\n }\n dagNode = inputCodec.decode(dagNode)\n }\n\n const cidVersion = options.version != null ? options.version : 1\n const hasher = await hashers.getHasher(options.hashAlg || 'sha2-256')\n\n if (!hasher) {\n throw new Error(`Unknown hash algorithm ${options.hashAlg}, please configure additional MultihashHashers for this IPFS instance`)\n }\n\n const buf = storeCodec.encode(dagNode)\n const hash = await hasher.digest(buf)\n const cid = CID.create(cidVersion, storeCodec.code, hash)\n\n await repo.blocks.put(cid, buf, {\n signal: options.signal\n })\n\n if (options.pin) {\n await repo.pins.pinRecursively(cid)\n }\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return cid\n } finally {\n if (release) {\n release()\n }\n }\n }\n\n return withTimeoutOption(put)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { toCidAndPath } from 'ipfs-core-utils/to-cid-and-path'\nimport { resolvePath } from '../../utils.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createResolve ({ repo, codecs, preload }) {\n /**\n * @type {import('ipfs-core-types/src/dag').API<{}>[\"resolve\"]}\n */\n async function dagResolve (ipfsPath, options = {}) {\n const {\n cid\n } = toCidAndPath(ipfsPath)\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return resolvePath(repo, codecs, ipfsPath, options)\n }\n\n return withTimeoutOption(dagResolve)\n}\n", "import { createExport } from './export.js'\nimport { createGet } from './get.js'\nimport { createImport } from './import.js'\nimport { createPut } from './put.js'\nimport { createResolve } from './resolve.js'\n\nexport class DagAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-core-utils/multihashes').Multihashes} config.hashers\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {import('../../types').Preload} config.preload\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\n constructor ({ repo, codecs, hashers, preload }) {\n this.export = createExport({ repo, preload, codecs })\n this.get = createGet({ codecs, repo, preload })\n this.import = createImport({ repo })\n this.resolve = createResolve({ repo, codecs, preload })\n this.put = createPut({ repo, codecs, hashers, preload })\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to URLs.\n *\n * @example Converting multiaddrs to URLs\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\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport type { Multiaddr, StringTuple } from '@multiformats/multiaddr'\n\nexport interface MultiaddrToUriOpts {\n assumeHttp?: boolean\n}\n\ninterface Interpreter { (value: string, ma: StringTuple[]): string }\n\nfunction extractSNI (ma: StringTuple[]): string | null {\n let sniProtoCode: number\n try {\n sniProtoCode = protocols('sni').code\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}\n\nfunction hasTLS (ma: StringTuple[]): boolean {\n return ma.some(([proto, _]) => proto === protocols('tls').code)\n}\n\nfunction interpretNext (headProtoCode: number, headProtoVal: string, restMa: StringTuple[]): string {\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}\n\nconst interpreters: Record = {\n ip4: (value: string, restMa: StringTuple[]) => value,\n ip6: (value: string, restMa: StringTuple[]) => {\n if (restMa.length === 0) {\n return value\n }\n return `[${value}]`\n },\n tcp: (value: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => value,\n dns4: (value: string, restMa: StringTuple[]) => value,\n dns6: (value: string, restMa: StringTuple[]) => value,\n dns: (value: string, restMa: StringTuple[]) => value,\n ipfs: (value: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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: string, restMa: StringTuple[]) => {\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}\n\nexport function multiaddrToUri (input: Multiaddr | string | Uint8Array, opts?: MultiaddrToUriOpts): string {\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\n const protocol = protocols(head[0])\n const interpreter = interpreters[protocol.name]\n\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`)\n }\n\n let uri = interpreter(head[1] ?? '', parts)\n if (opts?.assumeHttp !== false && head[0] === protocols('tcp').code) {\n // If rightmost proto is tcp, we assume http here\n uri = uri.replace('tcp://', 'http://')\n if (head[1] === '443' || head[1] === '80') {\n if (head[1] === '443') {\n uri = uri.replace('http://', 'https://')\n }\n // Drop the port\n uri = uri.substring(0, uri.lastIndexOf(':'))\n }\n }\n\n return uri\n}\n", "export default function arrayShuffle(array) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new TypeError(`Expected an array, got ${typeof array}`);\n\t}\n\n\tarray = [...array];\n\n\tfor (let index = array.length - 1; index > 0; index--) {\n\t\tconst newIndex = Math.floor(Math.random() * (index + 1));\n\t\t[array[index], array[newIndex]] = [array[newIndex], array[index]];\n\t}\n\n\treturn array;\n}\n", "/* eslint-env browser */\n\nimport HTTP from 'ipfs-utils/src/http.js'\nimport { logger } from '@libp2p/logger'\nimport PQueue from 'p-queue'\n\nconst log = logger('ipfs:preload')\n\n// @ts-expect-error PQueue@6 is broken\nconst Queue = PQueue.default ? PQueue.default : PQueue\n\n// browsers limit concurrent connections per host,\n// we don't want preload calls to exhaust the limit (~6)\nconst httpQueue = new Queue({ concurrency: 4 })\n\n/**\n * @param {string} url\n * @param {import('ipfs-core-types/src/utils').AbortOptions} options\n */\nexport function preload (url, options = {}) {\n log(url)\n\n return httpQueue.add(async () => {\n const res = await HTTP.post(url, { signal: options.signal })\n\n // @ts-expect-error\n const reader = res.body.getReader()\n\n try {\n while (true) {\n const { done } = await reader.read()\n if (done) return\n // Read to completion but do not cache\n }\n } finally {\n reader.releaseLock()\n }\n })\n}\n", "import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\nimport { logger } from '@libp2p/logger'\nimport shuffle from 'array-shuffle'\nimport { preload } from 'ipfs-core-config/preload'\nimport hashlru from 'hashlru'\n\nconst log = logger('ipfs:preload')\n\n/**\n * @param {import('./types').PreloadOptions} [options]\n */\nexport function createPreloader (options = {}) {\n options.enabled = Boolean(options.enabled)\n options.addresses = options.addresses || []\n options.cache = options.cache || 1000\n\n if (!options.enabled || !options.addresses.length) {\n log('preload disabled')\n const api = () => {}\n return Object.assign(api, {\n start: () => {},\n stop: () => {}\n })\n }\n\n let stopped = true\n /** @type {AbortController[]} */\n let requests = []\n const apiUris = options.addresses.map((str) => multiaddrToUri(str))\n\n // Avoid preloading the same CID over and over again\n const cache = hashlru(options.cache)\n\n /**\n * @type {import('./types').Preload}\n */\n const api = async cid => {\n try {\n if (stopped) {\n throw new Error(`preload ${cid} but preloader is not started`)\n }\n\n const path = cid.toString()\n\n if (cache.has(path)) {\n // we've preloaded this recently, don't preload it again\n return\n }\n\n // make sure we don't preload this again any time soon\n cache.set(path, true)\n\n const fallbackApiUris = shuffle(apiUris)\n let success = false\n const now = Date.now()\n\n for (const uri of fallbackApiUris) {\n if (stopped) throw new Error(`preload aborted for ${path}`)\n /** @type {AbortController} */\n let controller\n\n try {\n controller = new AbortController()\n requests = requests.concat(controller)\n await preload(`${uri}/api/v0/refs?r=true&arg=${encodeURIComponent(path)}`, { signal: controller.signal })\n success = true\n } catch (/** @type {any} */ err) {\n if (err.type !== 'aborted') log.error(err)\n } finally {\n requests = requests.filter(r => r !== controller)\n }\n\n if (success) break\n }\n\n log(`${success ? '' : 'un'}successfully preloaded ${path} in ${Date.now() - now}ms`)\n } catch (/** @type {any} */ err) {\n log.error(err)\n }\n }\n\n /**\n * @returns {void}\n */\n api.start = () => {\n stopped = false\n }\n\n /**\n * @returns {void}\n */\n api.stop = () => {\n stopped = true\n log(`aborting ${requests.length} pending preload request(s)`)\n requests.forEach(r => r.abort())\n requests = []\n }\n\n return api\n}\n", "import { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:mfs-preload')\n\n/**\n * @typedef {PreloadOptions & MFSPreloadOptions} Options\n * @typedef {object} MFSPreloadOptions\n * @property {number} [interval]\n * @typedef {import('./types').PreloadOptions} PreloadOptions\n */\n\n/**\n * @param {object} config\n * @param {import('./types').Preload} config.preload\n * @param {import('ipfs-core-types/src/files').API} config.files\n * @param {Options} [config.options]\n */\nexport function createMfsPreloader ({ preload, files, options = {} }) {\n options.interval = options.interval || 30 * 1000\n\n if (!options.enabled) {\n log('MFS preload disabled')\n const noop = async () => {}\n return { start: noop, stop: noop }\n }\n\n let rootCid = ''\n /** @type {any} */\n let timeoutId\n\n const preloadMfs = async () => {\n try {\n const stats = await files.stat('/')\n const nextRootCid = stats.cid.toString()\n\n if (rootCid !== nextRootCid) {\n log(`preloading updated MFS root ${rootCid} -> ${stats.cid}`)\n await preload(stats.cid)\n rootCid = nextRootCid\n }\n } catch (/** @type {any} */ err) {\n log.error('failed to preload MFS root', err)\n } finally {\n timeoutId = setTimeout(preloadMfs, options.interval)\n }\n }\n\n return {\n /**\n * @returns {Promise}\n */\n async start () {\n const stats = await files.stat('/')\n rootCid = stats.cid.toString()\n log(`monitoring MFS root ${stats.cid}`)\n timeoutId = setTimeout(preloadMfs, options.interval)\n },\n /**\n * @returns {void}\n */\n stop () {\n clearTimeout(timeoutId)\n }\n }\n}\n", "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", "// 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 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", "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", "export interface WebworkerEventListener {\n (worker: Worker, event: MessageEvent): void\n}\n\nconst events: Record = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n", "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'\n\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", "export const nanoid = (size: number = 21): string => {\n return Math.random().toString().substring(2)\n}\n", "import observer from 'observable-webworkers'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport { nanoid } from './utils.js'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent): void => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return new Promise((resolve) => {\n const listener = (event: MessageEvent): void => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\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\n return emitter\n }\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", "/**\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\nimport PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock(): Promise\n writeLock(): Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock(name: string, options: MorticeOptions): Mortice['readLock']\n writeLock(name: string, options: MorticeOptions): Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\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\n return p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\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\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\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\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\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\n return createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler(): Promise\n}\n\nexport default function createMortice (options?: MorticeOptions): Mortice {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n", "import mortice from 'mortice'\n\n/**\n * @typedef {object} Lock\n * @property {(fn: (...args: any) => any) => (...args: any) => any} readLock\n * @property {(fn: (...args: any) => any) => (...args: any) => any} writeLock\n */\n\n/** @type {Lock} */\nlet lock\n\n/**\n * @param {boolean} [repoOwner]\n */\nexport function createLock (repoOwner = false) {\n if (lock) {\n return lock\n }\n\n const mutex = mortice({\n // ordinarily the main thread would store the read/write lock but\n // if we are the thread that owns the repo, we can store the lock\n // on this process even if we are a worker thread\n singleProcess: repoOwner\n })\n\n lock = {\n readLock: (func) => {\n return async (...args) => {\n const releaseLock = await mutex.readLock()\n\n try {\n return await func.apply(null, args)\n } finally {\n releaseLock()\n }\n }\n },\n\n writeLock: (func) => {\n return async (...args) => {\n const releaseLock = await mutex.writeLock()\n\n try {\n return await func.apply(null, args)\n } finally {\n releaseLock()\n }\n }\n }\n }\n\n return lock\n}\n", "import { CID } from 'multiformats/cid'\nimport { UnixFS } from 'ipfs-unixfs'\nimport * as dagPB from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { MFS_ROOT_KEY } from '../../../utils.js'\n\nconst log = logger('ipfs:mfs:utils:with-mfs-root')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n */\n\n/**\n * @param {MfsContext} context\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n */\nexport async function loadMfsRoot (context, options) {\n if (options && options.signal && options.signal.aborted) {\n throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })\n }\n\n // Open the repo if it's been closed\n await context.repo.datastore.open()\n\n // Load the MFS root CID\n let cid\n\n try {\n const buf = await context.repo.datastore.get(MFS_ROOT_KEY)\n\n cid = CID.decode(buf)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n\n log('Creating new MFS root')\n const buf = dagPB.encode({\n Data: new UnixFS({ type: 'directory' }).marshal(),\n Links: []\n })\n const hash = await sha256.digest(buf)\n cid = CID.createV0(hash)\n await context.repo.blocks.put(cid, buf)\n\n if (options && options.signal && options.signal.aborted) {\n throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })\n }\n\n await context.repo.datastore.put(MFS_ROOT_KEY, cid.bytes)\n }\n\n log(`Loaded MFS root /ipfs/${cid}`)\n\n return cid\n}\n", "\n/**\n * @param {string} [path]\n */\nexport function toPathComponents (path = '') {\n // split on / unless escaped with \\\n return (path\n .trim()\n .match(/([^\\\\^/]|\\\\\\/)+/g) || [])\n .filter(Boolean)\n}\n", "import { loadMfsRoot } from './with-mfs-root.js'\nimport { toPathComponents } from './to-path-components.js'\nimport { exporter } from 'ipfs-unixfs-exporter'\nimport errCode from 'err-code'\nimport { CID } from 'multiformats/cid'\n\nconst IPFS_PREFIX = 'ipfs'\n\n/**\n * @typedef {import('ipfs-unixfs-exporter').UnixFSEntry} UnixFSEntry\n * @typedef {import('ipfs-unixfs-exporter').ExporterOptions} ExporterOptions\n * @typedef {import('../').MfsContext} MfsContext\n *\n * @typedef {object} FilePath\n * @property {'mfs' | 'ipfs'} type\n * @property {'file'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {import('ipfs-unixfs').UnixFS} unixfs\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} DirectoryPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'directory'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {import('ipfs-unixfs').UnixFS} unixfs\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} ObjectPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'object'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} RawPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'raw'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {object} IdentityPath\n * @property {'mfs' | 'ipfs'} type\n * @property {'identity'} entryType\n * @property {number} depth\n * @property {string} mfsPath\n * @property {string} mfsDirectory\n * @property {string[]} parts\n * @property {string} path\n * @property {string} name\n * @property {CID} cid\n * @property {boolean} exists\n * @property {(options?: ExporterOptions) => AsyncIterable} content\n *\n * @typedef {FilePath | DirectoryPath | ObjectPath | RawPath | IdentityPath} MfsPath\n */\n\n/**\n * @param {MfsContext} context\n * @param {string | CID} path\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n */\nexport const toMfsPath = async (context, path, options) => {\n const root = await loadMfsRoot(context, options)\n\n /** @type {MfsPath} */\n // @ts-expect-error fields get set later\n let output = {\n entryType: 'file'\n }\n\n let ipfsPath = ''\n\n if (CID.asCID(path)) {\n ipfsPath = `/ipfs/${path}`\n } else {\n ipfsPath = path.toString()\n }\n\n ipfsPath = ipfsPath.trim()\n ipfsPath = ipfsPath.replace(/(\\/\\/+)/g, '/')\n\n if (ipfsPath.endsWith('/') && ipfsPath.length > 1) {\n ipfsPath = ipfsPath.substring(0, ipfsPath.length - 1)\n }\n\n if (!ipfsPath) {\n throw errCode(new Error('paths must not be empty'), 'ERR_NO_PATH')\n }\n\n if (ipfsPath.substring(0, 1) !== '/') {\n throw errCode(new Error('paths must start with a leading slash'), 'ERR_INVALID_PATH')\n }\n\n if (ipfsPath.substring(ipfsPath.length - 1) === '/') {\n ipfsPath = ipfsPath.substring(0, ipfsPath.length - 1)\n }\n\n const pathComponents = toPathComponents(ipfsPath)\n\n if (pathComponents[0] === IPFS_PREFIX) {\n // e.g. /ipfs/QMfoo or /ipfs/Qmfoo/sub/path\n let mfsDirectory\n\n if (pathComponents.length === 2) {\n mfsDirectory = `/${pathComponents.join('/')}`\n } else {\n mfsDirectory = `/${pathComponents.slice(0, pathComponents.length - 1).join('/')}`\n }\n\n // @ts-expect-error fields being set\n output = {\n type: 'ipfs',\n depth: pathComponents.length - 2,\n entryType: 'file',\n\n mfsPath: `/${pathComponents.join('/')}`,\n mfsDirectory,\n parts: pathComponents,\n path: `/${pathComponents.join('/')}`,\n name: pathComponents[pathComponents.length - 1]\n }\n } else {\n const mfsPath = `/${IPFS_PREFIX}/${root}${pathComponents.length ? '/' + pathComponents.join('/') : ''}`\n const mfsDirectory = `/${IPFS_PREFIX}/${root}/${pathComponents.slice(0, pathComponents.length - 1).join('/')}`\n\n // @ts-expect-error fields being set\n output = {\n type: 'mfs',\n depth: pathComponents.length,\n entryType: 'file',\n\n mfsDirectory,\n mfsPath,\n parts: pathComponents,\n path: `/${pathComponents.join('/')}`,\n name: pathComponents[pathComponents.length - 1]\n }\n }\n\n const cidPath = output.type === 'mfs' ? output.mfsPath : output.path\n\n try {\n const res = await exporter(cidPath, context.repo.blocks, options)\n\n output.cid = res.cid\n output.mfsPath = `/ipfs/${res.path}`\n output.entryType = res.type\n output.content = res.content\n\n if ((output.entryType === 'file' || output.entryType === 'directory') && (res.type === 'file' || res.type === 'directory')) {\n output.unixfs = res.unixfs\n }\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n output.exists = Boolean(output.cid)\n\n return output\n}\n", "import mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { exporter } from 'ipfs-unixfs-exporter'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport * as dagPB from '@ipld/dag-pb'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:stat')\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} withLocal\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n withLocal: false\n}\n\n/**\n * @typedef {import('ipfs-core-types/src/files').StatResult} StatResult\n */\n\n/**\n * @param {MfsContext} context\n */\nexport function createStat (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"stat\"]}\n */\n async function mfsStat (path, options = {}) {\n /** @type {DefaultOptions} */\n options = mergeOptions(defaultOptions, options)\n\n log(`Fetching stats for ${path}`)\n\n const {\n type,\n cid,\n mfsPath\n } = await toMfsPath(context, path, options)\n\n const exportPath = type === 'ipfs' && cid ? cid : mfsPath\n let file\n\n try {\n file = await exporter(exportPath, context.repo.blocks)\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NOT_FOUND') {\n throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND')\n }\n\n throw err\n }\n\n if (!statters[file.type]) {\n throw new Error(`Cannot stat codec ${file.cid.code}`)\n }\n\n return statters[file.type](file)\n }\n\n return withTimeoutOption(mfsStat)\n}\n\n/** @type {Record StatResult>} */\nconst statters = {\n /**\n * @param {import('ipfs-unixfs-exporter').RawNode} file\n */\n raw: (file) => {\n return {\n cid: file.cid,\n size: file.node.length,\n cumulativeSize: file.node.length,\n blocks: 0,\n type: 'file', // for go compatibility\n local: undefined,\n sizeLocal: undefined,\n withLocality: false\n }\n },\n /**\n * @param {import('ipfs-unixfs-exporter').UnixFSFile} file\n */\n file: (file) => {\n /** @type {StatResult} */\n const stat = {\n cid: file.cid,\n type: 'file',\n size: file.unixfs.fileSize(),\n cumulativeSize: dagPB.encode(file.node).length + (file.node.Links || []).reduce((acc, curr) => acc + (curr.Tsize || 0), 0),\n blocks: file.unixfs.blockSizes.length,\n local: undefined,\n sizeLocal: undefined,\n withLocality: false,\n mode: file.unixfs.mode\n }\n\n if (file.unixfs.mtime) {\n stat.mtime = file.unixfs.mtime\n }\n\n return stat\n },\n /**\n * @param {import('ipfs-unixfs-exporter').UnixFSDirectory} file\n */\n directory: (file) => {\n /** @type {StatResult} */\n const stat = {\n cid: file.cid,\n type: 'directory',\n size: 0,\n cumulativeSize: dagPB.encode(file.node).length + (file.node.Links || []).reduce((acc, curr) => acc + (curr.Tsize || 0), 0),\n blocks: file.node.Links.length,\n local: undefined,\n sizeLocal: undefined,\n withLocality: false,\n mode: file.unixfs.mode\n }\n\n if (file.unixfs.mtime) {\n stat.mtime = file.unixfs.mtime\n }\n\n return stat\n },\n /**\n * @param {import('ipfs-unixfs-exporter').ObjectNode} file\n */\n object: (file) => {\n /** @type {StatResult} */\n return {\n cid: file.cid,\n size: file.node.length,\n cumulativeSize: file.node.length,\n type: 'file', // for go compatibility\n blocks: 0,\n local: undefined,\n sizeLocal: undefined,\n withLocality: false\n }\n },\n /**\n * @param {import('ipfs-unixfs-exporter').IdentityNode} file\n */\n identity: (file) => {\n /** @type {StatResult} */\n return {\n cid: file.cid,\n size: file.node.length,\n cumulativeSize: file.node.length,\n blocks: 0,\n type: 'file', // for go compatibility\n local: undefined,\n sizeLocal: undefined,\n withLocality: false\n }\n }\n}\n", "import mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { toTrail } from './utils/to-trail.js'\nimport { addLink } from './utils/add-link.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { pipe } from 'it-pipe'\nimport { importer } from 'ipfs-unixfs-importer'\nimport { recursive } from 'ipfs-unixfs-exporter'\nimport last from 'it-last'\nimport { createCp } from './cp.js'\nimport { createRm } from './rm.js'\nimport { persist } from './utils/persist.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:touch')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('./').MfsContext} MfsContext\n *\n * @typedef {object} DefaultOptions\n * @property {boolean} flush\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {number} shardSplitThreshold\n * @property {boolean} recursive\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n flush: true,\n shardSplitThreshold: 1000,\n hashAlg: 'sha2-256',\n cidVersion: 0,\n recursive: false\n}\n\n/**\n * @param {string} mode\n * @param {number} originalMode\n * @param {boolean} isDirectory\n */\nfunction calculateModification (mode, originalMode, isDirectory) {\n let modification = 0\n\n if (mode.includes('x') || (mode.includes('X') && (isDirectory || (originalMode & 0o1 || originalMode & 0o10 || originalMode & 0o100)))) {\n modification += 1\n }\n\n if (mode.includes('w')) {\n modification += 2\n }\n\n if (mode.includes('r')) {\n modification += 4\n }\n\n return modification\n}\n\n/**\n * @param {string} references\n * @param {number} modification\n */\nfunction calculateUGO (references, modification) {\n let ugo = 0\n\n if (references.includes('u')) {\n ugo += (modification << 6)\n }\n\n if (references.includes('g')) {\n ugo += (modification << 3)\n }\n\n if (references.includes('o')) {\n ugo += (modification)\n }\n\n return ugo\n}\n\n/**\n * @param {string} references\n * @param {string} mode\n * @param {number} modification\n */\nfunction calculateSpecial (references, mode, modification) {\n if (mode.includes('t')) {\n modification += parseInt('1000', 8)\n }\n\n if (mode.includes('s')) {\n if (references.includes('u')) {\n modification += parseInt('4000', 8)\n }\n\n if (references.includes('g')) {\n modification += parseInt('2000', 8)\n }\n }\n\n return modification\n}\n\n/**\n * https://en.wikipedia.org/wiki/Chmod#Symbolic_modes\n *\n * @param {string} input\n * @param {number} originalMode\n * @param {boolean} isDirectory\n */\nfunction parseSymbolicMode (input, originalMode, isDirectory) {\n if (!originalMode) {\n originalMode = 0\n }\n\n const match = input.match(/^(u?g?o?a?)(-?\\+?=?)?(r?w?x?X?s?t?)$/)\n\n if (!match) {\n throw new Error(`Invalid file mode: ${input}`)\n }\n\n let [\n ,\n references,\n operator,\n mode\n ] = match\n\n if (references === 'a' || !references) {\n references = 'ugo'\n }\n\n let modification = calculateModification(mode, originalMode, isDirectory)\n modification = calculateUGO(references, modification)\n modification = calculateSpecial(references, mode, modification)\n\n if (operator === '=') {\n if (references.includes('u')) {\n // blank u bits\n originalMode = originalMode & parseInt('7077', 8)\n\n // or them together\n originalMode = originalMode | modification\n }\n\n if (references.includes('g')) {\n // blank g bits\n originalMode = originalMode & parseInt('7707', 8)\n\n // or them together\n originalMode = originalMode | modification\n }\n\n if (references.includes('o')) {\n // blank o bits\n originalMode = originalMode & parseInt('7770', 8)\n\n // or them together\n originalMode = originalMode | modification\n }\n\n return originalMode\n }\n\n if (operator === '+') {\n return modification | originalMode\n }\n\n if (operator === '-') {\n return modification ^ originalMode\n }\n\n return originalMode\n}\n\n/**\n * @param {string | InstanceType | number} mode\n * @param {UnixFS} metadata\n * @returns {number}\n */\nfunction calculateMode (mode, metadata) {\n if (mode instanceof String || typeof mode === 'string') {\n const strMode = `${mode}`\n\n if (strMode.match(/^\\d+$/g)) {\n mode = parseInt(strMode, 8)\n } else {\n mode = 0 + strMode.split(',').reduce((curr, acc) => {\n return parseSymbolicMode(acc, curr, metadata.isDirectory())\n }, metadata.mode || 0)\n }\n }\n\n return mode\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createChmod (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"chmod\"]}\n */\n async function mfsChmod (path, mode, options = {}) {\n /** @type {DefaultOptions} */\n const opts = mergeOptions(defaultOptions, options)\n\n log(`Fetching stats for ${path}`)\n\n const {\n cid,\n mfsDirectory,\n name\n } = await toMfsPath(context, path, opts)\n\n if (cid.code !== dagPB.code) {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n if (opts.recursive) {\n // recursively export from root CID, change perms of each entry then reimport\n // but do not reimport files, only manipulate dag-pb nodes\n const root = await pipe(\n async function * () {\n for await (const entry of recursive(cid, context.repo.blocks)) {\n if (entry.type !== 'file' && entry.type !== 'directory') {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n entry.unixfs.mode = calculateMode(mode, entry.unixfs)\n\n const node = dagPB.prepare({\n Data: entry.unixfs.marshal(),\n Links: entry.node.Links\n })\n\n yield {\n path: entry.path,\n content: node\n }\n }\n },\n // @ts-expect-error we account for the incompatible source type with our custom dag builder below\n (source) => importer(source, context.repo.blocks, {\n ...opts,\n pin: false,\n dagBuilder: async function * (source, block, opts) {\n for await (const entry of source) {\n yield async function () {\n /** @type {PBNode} */\n // @ts-expect-error - cannot derive type\n const node = entry.content\n\n const buf = dagPB.encode(node)\n const cid = await persist(buf, block, opts)\n\n if (!node.Data) {\n throw errCode(new Error(`${cid} had no data`), 'ERR_INVALID_NODE')\n }\n\n const unixfs = UnixFS.unmarshal(node.Data)\n\n return {\n cid,\n size: buf.length,\n path: entry.path,\n unixfs\n }\n }\n }\n }\n }),\n (nodes) => last(nodes)\n )\n\n if (!root) {\n throw errCode(new Error(`Could not chmod ${path}`), 'ERR_COULD_NOT_CHMOD')\n }\n\n // remove old path from mfs\n await createRm(context)(path, opts)\n\n // add newly created tree to mfs at path\n await createCp(context)(`/ipfs/${root.cid}`, path, opts)\n\n return\n }\n\n const block = await context.repo.blocks.get(cid)\n const node = dagPB.decode(block)\n\n if (!node.Data) {\n throw errCode(new Error(`${cid} had no data`), 'ERR_INVALID_NODE')\n }\n\n const metadata = UnixFS.unmarshal(node.Data)\n metadata.mode = calculateMode(mode, metadata)\n const updatedBlock = dagPB.encode({\n Data: metadata.marshal(),\n Links: node.Links\n })\n\n const hashAlg = opts.hashAlg || defaultOptions.hashAlg\n const hasher = await context.hashers.getHasher(hashAlg)\n const hash = await hasher.digest(updatedBlock)\n const updatedCid = CID.create(opts.cidVersion, dagPB.code, hash)\n\n if (opts.flush) {\n await context.repo.blocks.put(updatedCid, updatedBlock)\n }\n\n const trail = await toTrail(context, mfsDirectory)\n const parent = trail[trail.length - 1]\n const parentCid = CID.decode(parent.cid.bytes)\n const parentBlock = await context.repo.blocks.get(parentCid)\n const parentNode = dagPB.decode(parentBlock)\n\n const result = await addLink(context, {\n parent: parentNode,\n name: name,\n cid: updatedCid,\n size: updatedBlock.length,\n flush: opts.flush,\n // TODO vmx 2021-03-29: decide on the API, whether it should be a `hashAlg` or `hasher`\n hashAlg,\n cidVersion: cid.version,\n shardSplitThreshold: Infinity\n })\n\n parent.cid = result.cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, opts)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, opts)\n }\n\n return withTimeoutOption(mfsChmod)\n}\n", "import { walkPath } from 'ipfs-unixfs-exporter'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('ipfs:mfs:utils:to-trail')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {object} MfsTrail\n * @property {string} name\n * @property {import('multiformats/cid').CID} cid\n * @property {number} [size]\n * @property {string} [type]\n *\n * TODO: export supported types from unixfs-exporter and use for `type` above\n */\n\n/**\n * @param {MfsContext} context\n * @param {string} path\n * @returns {Promise}\n */\nexport async function toTrail (context, path) {\n log(`Creating trail for path ${path}`)\n\n const output = []\n\n for await (const fsEntry of walkPath(path, context.repo.blocks)) {\n output.push({\n name: fsEntry.name,\n cid: fsEntry.cid,\n size: fsEntry.size,\n type: fsEntry.type\n })\n }\n\n return output\n}\n", "import { CID } from 'multiformats/cid'\nimport * as dagPB from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * @typedef {object} PersistOptions\n * @property {import('multiformats/codecs/interface').BlockCodec} [codec]\n * @property {import('multiformats/hashes/interface').MultihashHasher} [hasher]\n * @property {import('multiformats/cid').Version} [cidVersion]\n * @property {boolean} [onlyHash]\n * @property {AbortSignal} [signal]\n */\n\n/**\n * @param {Uint8Array} buffer\n * @param {import('interface-blockstore').Blockstore} blockstore\n * @param {PersistOptions} options\n */\nexport const persist = async (buffer, blockstore, options) => {\n if (!options.codec) {\n options.codec = dagPB\n }\n\n if (!options.hasher) {\n options.hasher = sha256\n }\n\n if (options.cidVersion === undefined) {\n options.cidVersion = 1\n }\n\n if (options.codec === dagPB && options.hasher !== sha256) {\n options.cidVersion = 1\n }\n\n const multihash = await options.hasher.digest(buffer)\n const cid = CID.create(options.cidVersion, options.codec.code, multihash)\n\n if (!options.onlyHash) {\n await blockstore.put(cid, buffer, {\n signal: options.signal\n })\n }\n\n return cid\n}\n", "import { murmur3128 } from '@multiformats/murmur3'\n\nexport const hamtHashCode = murmur3128.code\nexport const hamtBucketBits = 8\n\n/**\n * @param {Uint8Array} buf\n */\nexport async function hamtHashFn (buf) {\n return (await murmur3128.encode(buf))\n // Murmur3 outputs 128 bit but, accidentally, IPFS Go's\n // implementation only uses the first 64, so we must do the same\n // for parity..\n .subarray(0, 8)\n // Invert buffer because that's how Go impl does it\n .reverse()\n}\n", "import { encode, prepare } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { persist } from './persist.js'\nimport { createHAMT, Bucket } from 'hamt-sharding'\nimport {\n hamtHashCode,\n hamtHashFn,\n hamtBucketBits\n} from './hamt-constants.js'\n\n/**\n * @typedef {import('ipfs-unixfs-importer').ImporterOptions} ImporterOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n *\n * @typedef {object} ImportResult\n * @property {CID} cid\n * @property {import('@ipld/dag-pb').PBNode} node\n * @property {number} size\n *\n * @typedef {object} DirContents\n * @property {CID} [cid]\n * @property {number} [size]\n *\n * @typedef {object} DirOptions\n * @property {Mtime} [mtime]\n * @property {number} [mode]\n * @property {import('multiformats/codecs/interface').BlockCodec} [codec]\n * @property {import('multiformats/cid').Version} [cidVersion]\n * @property {boolean} [onlyHash]\n * @property {AbortSignal} [signal]\n */\n\n/**\n * @typedef {object} DirProps\n * @property {boolean} root\n * @property {boolean} dir\n * @property {string} path\n * @property {boolean} dirty\n * @property {boolean} flat\n * @property {Dir} [parent]\n * @property {string} [parentKey]\n * @property {import('ipfs-unixfs').UnixFS} [unixfs]\n * @property {number} [mode]\n * @property {import('ipfs-unixfs').Mtime} [mtime]\n */\nexport class Dir {\n /**\n * @param {DirProps} props\n * @param {DirOptions} options\n */\n constructor (props, options) {\n this.options = options || {}\n this.root = props.root\n this.dir = props.dir\n this.path = props.path\n this.dirty = props.dirty\n this.flat = props.flat\n this.parent = props.parent\n this.parentKey = props.parentKey\n this.unixfs = props.unixfs\n this.mode = props.mode\n this.mtime = props.mtime\n /** @type {CID | undefined} */\n this.cid = undefined\n /** @type {number | undefined} */\n this.size = undefined\n }\n\n /**\n * @param {string} name\n * @param {DirContents} value\n */\n async put (name, value) { }\n /**\n * @param {string} name\n * @returns {Promise}\n */\n get (name) {\n return Promise.resolve(this)\n }\n\n /**\n * @returns {AsyncIterable<{ key: string, child: DirContents}>}\n */\n async * eachChildSeries () { }\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) { }\n}\n\nexport class DirSharded extends Dir {\n /**\n * @param {DirProps} props\n * @param {DirOptions} options\n */\n constructor (props, options) {\n super(props, options)\n\n /** @type {Bucket} */\n this._bucket = createHAMT({\n hashFn: hamtHashFn,\n bits: hamtBucketBits\n })\n }\n\n /**\n * @param {string} name\n * @param {DirContents} value\n */\n async put (name, value) {\n await this._bucket.put(name, value)\n }\n\n /**\n * @param {string} name\n */\n get (name) {\n return this._bucket.get(name)\n }\n\n childCount () {\n return this._bucket.leafCount()\n }\n\n directChildrenCount () {\n return this._bucket.childrenCount()\n }\n\n onlyChild () {\n return this._bucket.onlyChild()\n }\n\n async * eachChildSeries () {\n for await (const { key, value } of this._bucket.eachLeafSeries()) {\n yield {\n key,\n child: value\n }\n }\n }\n\n /**\n * @param {Blockstore} blockstore\n * @returns {AsyncIterable}\n */\n async * flush (blockstore) {\n yield * flush(this._bucket, blockstore, this, this.options)\n }\n}\n\n/**\n * @param {Bucket} bucket\n * @param {Blockstore} blockstore\n * @param {*} shardRoot\n * @param {DirOptions} options\n * @returns {AsyncIterable}\n */\nasync function * flush (bucket, blockstore, shardRoot, options) {\n const children = bucket._children\n const links = []\n let childrenSize = 0\n\n for (let i = 0; i < children.length; i++) {\n const child = children.get(i)\n\n if (!child) {\n continue\n }\n\n const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0')\n\n if (child instanceof Bucket) {\n let shard\n\n for await (const subShard of await flush(child, blockstore, null, options)) {\n shard = subShard\n }\n\n if (!shard) {\n throw new Error('Could not flush sharded directory, no subshard found')\n }\n\n links.push({\n Name: labelPrefix,\n Tsize: shard.size,\n Hash: shard.cid\n })\n childrenSize += shard.size\n } else if (typeof child.value.flush === 'function') {\n const dir = child.value\n let flushedDir\n\n for await (const entry of dir.flush(blockstore)) {\n flushedDir = entry\n\n yield flushedDir\n }\n\n const label = labelPrefix + child.key\n links.push({\n Name: label,\n Tsize: flushedDir.size,\n Hash: flushedDir.cid\n })\n\n childrenSize += flushedDir.size\n } else {\n const value = child.value\n\n if (!value.cid) {\n continue\n }\n\n const label = labelPrefix + child.key\n const size = value.size\n\n links.push({\n Name: label,\n Tsize: size,\n Hash: value.cid\n })\n childrenSize += size\n }\n }\n\n // go-ipfs uses little endian, that's why we have to\n // reverse the bit field before storing it\n const data = Uint8Array.from(children.bitField().reverse())\n const dir = new UnixFS({\n type: 'hamt-sharded-directory',\n data,\n fanout: bucket.tableSize(),\n hashType: hamtHashCode,\n mtime: shardRoot && shardRoot.mtime,\n mode: shardRoot && shardRoot.mode\n })\n\n const node = {\n Data: dir.marshal(),\n Links: links\n }\n const buffer = encode(prepare(node))\n const cid = await persist(buffer, blockstore, options)\n const size = buffer.length + childrenSize\n\n yield {\n cid,\n node,\n size\n }\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport {\n Bucket,\n createHAMT\n} from 'hamt-sharding'\nimport { DirSharded } from './dir-sharded.js'\nimport { logger } from '@libp2p/logger'\nimport { UnixFS } from 'ipfs-unixfs'\nimport last from 'it-last'\nimport { CID } from 'multiformats/cid'\nimport {\n hamtHashCode,\n hamtHashFn,\n hamtBucketBits\n} from './hamt-constants.js'\n\nconst log = logger('ipfs:mfs:core:utils:hamt-utils')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n/**\n * @param {MfsContext} context\n * @param {PBLink[]} links\n * @param {Bucket} bucket\n * @param {object} options\n * @param {PBNode} options.parent\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {string} options.hashAlg\n */\nexport const updateHamtDirectory = async (context, links, bucket, options) => {\n if (!options.parent.Data) {\n throw new Error('Could not update HAMT directory because parent had no data')\n }\n\n // update parent with new bit field\n const data = Uint8Array.from(bucket._children.bitField().reverse())\n const node = UnixFS.unmarshal(options.parent.Data)\n const dir = new UnixFS({\n type: 'hamt-sharded-directory',\n data,\n fanout: bucket.tableSize(),\n hashType: hamtHashCode,\n mode: node.mode,\n mtime: node.mtime\n })\n\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const parent = {\n Data: dir.marshal(),\n Links: links.sort((a, b) => (a.Name || '').localeCompare(b.Name || ''))\n }\n const buf = dagPB.encode(parent)\n const hash = await hasher.digest(buf)\n const cid = CID.create(options.cidVersion, dagPB.code, hash)\n\n if (options.flush) {\n await context.repo.blocks.put(cid, buf)\n }\n\n return {\n node: parent,\n cid,\n size: links.reduce((sum, link) => sum + (link.Tsize || 0), buf.length)\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {PBLink[]} links\n * @param {Bucket} rootBucket\n * @param {Bucket} parentBucket\n * @param {number} positionAtParent\n */\nexport const recreateHamtLevel = async (context, links, rootBucket, parentBucket, positionAtParent) => {\n // recreate this level of the HAMT\n const bucket = new Bucket({\n hash: rootBucket._options.hash,\n bits: rootBucket._options.bits\n }, parentBucket, positionAtParent)\n parentBucket._putObjectAt(positionAtParent, bucket)\n\n await addLinksToHamtBucket(context, links, bucket, rootBucket)\n\n return bucket\n}\n\n/**\n * @param {PBLink[]} links\n */\nexport const recreateInitialHamtLevel = async (links) => {\n const bucket = createHAMT({\n hashFn: hamtHashFn,\n bits: hamtBucketBits\n })\n\n // populate sub bucket but do not recurse as we do not want to pull whole shard in\n await Promise.all(\n links.map(async link => {\n const linkName = (link.Name || '')\n\n if (linkName.length === 2) {\n const pos = parseInt(linkName, 16)\n\n const subBucket = new Bucket({\n hash: bucket._options.hash,\n bits: bucket._options.bits\n }, bucket, pos)\n bucket._putObjectAt(pos, subBucket)\n\n return Promise.resolve()\n }\n\n return bucket.put(linkName.substring(2), {\n size: link.Tsize,\n cid: link.Hash\n })\n })\n )\n\n return bucket\n}\n\n/**\n * @param {MfsContext} context\n * @param {PBLink[]} links\n * @param {Bucket} bucket\n * @param {Bucket} rootBucket\n */\nexport const addLinksToHamtBucket = async (context, links, bucket, rootBucket) => {\n await Promise.all(\n links.map(async link => {\n const linkName = (link.Name || '')\n\n if (linkName.length === 2) {\n log('Populating sub bucket', linkName)\n const pos = parseInt(linkName, 16)\n const block = await context.repo.blocks.get(link.Hash)\n const node = dagPB.decode(block)\n\n const subBucket = new Bucket({\n hash: rootBucket._options.hash,\n bits: rootBucket._options.bits\n }, bucket, pos)\n bucket._putObjectAt(pos, subBucket)\n\n await addLinksToHamtBucket(context, node.Links, subBucket, rootBucket)\n\n return Promise.resolve()\n }\n\n return rootBucket.put(linkName.substring(2), {\n size: link.Tsize,\n cid: link.Hash\n })\n })\n )\n}\n\n/**\n * @param {number} position\n */\nexport const toPrefix = (position) => {\n return position\n .toString(16)\n .toUpperCase()\n .padStart(2, '0')\n .substring(0, 2)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} fileName\n * @param {PBNode} rootNode\n */\nexport const generatePath = async (context, fileName, rootNode) => {\n // start at the root bucket and descend, loading nodes as we go\n const rootBucket = await recreateInitialHamtLevel(rootNode.Links)\n const position = await rootBucket._findNewBucketAndPos(fileName)\n\n // the path to the root bucket\n /** @type {{ bucket: Bucket, prefix: string, node?: PBNode }[]} */\n const path = [{\n bucket: position.bucket,\n prefix: toPrefix(position.pos)\n }]\n let currentBucket = position.bucket\n\n while (currentBucket !== rootBucket) {\n path.push({\n bucket: currentBucket,\n prefix: toPrefix(currentBucket._posAtParent)\n })\n\n // @ts-expect-error - only the root bucket's parent will be undefined\n currentBucket = currentBucket._parent\n }\n\n path.reverse()\n path[0].node = rootNode\n\n // load PbNode for each path segment\n for (let i = 0; i < path.length; i++) {\n const segment = path[i]\n\n if (!segment.node) {\n throw new Error('Could not generate HAMT path')\n }\n\n // find prefix in links\n const link = segment.node.Links\n .filter(link => (link.Name || '').substring(0, 2) === segment.prefix)\n .pop()\n\n // entry was not in shard\n if (!link) {\n // reached bottom of tree, file will be added to the current bucket\n log(`Link ${segment.prefix}${fileName} will be added`)\n // return path\n continue\n }\n\n // found entry\n if (link.Name === `${segment.prefix}${fileName}`) {\n log(`Link ${segment.prefix}${fileName} will be replaced`)\n // file already existed, file will be added to the current bucket\n // return path\n continue\n }\n\n // found subshard\n log(`Found subshard ${segment.prefix}`)\n const block = await context.repo.blocks.get(link.Hash)\n const node = dagPB.decode(block)\n\n // subshard hasn't been loaded, descend to the next level of the HAMT\n if (!path[i + 1]) {\n log(`Loaded new subshard ${segment.prefix}`)\n\n await recreateHamtLevel(context, node.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16))\n const position = await rootBucket._findNewBucketAndPos(fileName)\n\n // i--\n path.push({\n bucket: position.bucket,\n prefix: toPrefix(position.pos),\n node: node\n })\n\n continue\n }\n\n const nextSegment = path[i + 1]\n\n // add intermediate links to bucket\n await addLinksToHamtBucket(context, node.Links, nextSegment.bucket, rootBucket)\n\n nextSegment.node = node\n }\n\n await rootBucket.put(fileName, true)\n\n path.reverse()\n\n return {\n rootBucket,\n path\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {{ name: string, size: number, cid: CID }[]} contents\n * @param {object} [options]\n * @param {Mtime} [options.mtime]\n * @param {number} [options.mode]\n */\nexport const createShard = async (context, contents, options = {}) => {\n const shard = new DirSharded({\n root: true,\n dir: true,\n parent: undefined,\n parentKey: undefined,\n path: '',\n dirty: true,\n flat: false,\n mtime: options.mtime,\n mode: options.mode\n }, options)\n\n for (let i = 0; i < contents.length; i++) {\n await shard._bucket.put(contents[i].name, {\n size: contents[i].size,\n cid: contents[i].cid\n })\n }\n\n const res = await last(shard.flush(context.repo.blocks))\n\n if (!res) {\n throw new Error('Flushing shard yielded no result')\n }\n\n return res\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { logger } from '@libp2p/logger'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { DirSharded } from './dir-sharded.js'\nimport {\n updateHamtDirectory,\n recreateHamtLevel,\n recreateInitialHamtLevel,\n createShard,\n toPrefix,\n addLinksToHamtBucket\n} from './hamt-utils.js'\nimport errCode from 'err-code'\nimport last from 'it-last'\n\nconst log = logger('ipfs:mfs:core:utils:add-link')\n\n/**\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('hamt-sharding').Bucket} Bucket\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('@ipld/dag-pb').PBLink} PBLink\n */\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {number} options.shardSplitThreshold\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {CID} [options.parentCid]\n * @param {PBNode} [options.parent]\n */\nexport async function addLink (context, options) {\n let parent = options.parent\n\n if (options.parentCid) {\n const parentCid = CID.asCID(options.parentCid)\n if (parentCid === null) {\n throw errCode(new Error('Invalid CID passed to addLink'), 'EINVALIDPARENTCID')\n }\n\n if (parentCid.code !== dagPB.code) {\n throw errCode(new Error('Unsupported codec. Only DAG-PB is supported'), 'EINVALIDPARENTCID')\n }\n\n log(`Loading parent node ${parentCid}`)\n const block = await context.repo.blocks.get(parentCid)\n parent = dagPB.decode(block)\n }\n\n if (!parent) {\n throw errCode(new Error('No parent node or CID passed to addLink'), 'EINVALIDPARENT')\n }\n\n if (!options.cid) {\n throw errCode(new Error('No child cid passed to addLink'), 'EINVALIDCHILDCID')\n }\n\n if (!options.name) {\n throw errCode(new Error('No child name passed to addLink'), 'EINVALIDCHILDNAME')\n }\n\n if (!options.size && options.size !== 0) {\n throw errCode(new Error('No child size passed to addLink'), 'EINVALIDCHILDSIZE')\n }\n\n if (!parent.Data) {\n throw errCode(new Error('Parent node with no data passed to addLink'), 'ERR_INVALID_PARENT')\n }\n\n const meta = UnixFS.unmarshal(parent.Data)\n\n if (meta.type === 'hamt-sharded-directory') {\n log('Adding link to sharded directory')\n\n return addToShardedDirectory(context, {\n ...options,\n parent\n })\n }\n\n if (parent.Links.length >= options.shardSplitThreshold) {\n log('Converting directory to sharded directory')\n\n return convertToShardedDirectory(context, {\n ...options,\n parent,\n mtime: meta.mtime,\n mode: meta.mode\n })\n }\n\n log(`Adding ${options.name} (${options.cid}) to regular directory`)\n\n return addToDirectory(context, {\n ...options,\n parent\n })\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {Mtime} [options.mtime]\n * @param {number} [options.mode]\n */\nconst convertToShardedDirectory = async (context, options) => {\n const result = await createShard(context, options.parent.Links.map(link => ({\n name: (link.Name || ''),\n size: link.Tsize || 0,\n cid: link.Hash\n })).concat({\n name: options.name,\n size: options.size,\n cid: options.cid\n }), options)\n\n log(`Converted directory to sharded directory ${result.cid}`)\n\n return result\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {Mtime} [options.mtime]\n * @param {number} [options.mode]\n */\nconst addToDirectory = async (context, options) => {\n // Remove existing link if it exists\n const parentLinks = options.parent.Links.filter((link) => {\n return link.Name !== options.name\n })\n parentLinks.push({\n Name: options.name,\n Tsize: options.size,\n Hash: options.cid\n })\n\n if (!options.parent.Data) {\n throw errCode(new Error('Parent node with no data passed to addToDirectory'), 'ERR_INVALID_PARENT')\n }\n\n const node = UnixFS.unmarshal(options.parent.Data)\n\n let data\n if (node.mtime) {\n // Update mtime if previously set\n const ms = Date.now()\n const secs = Math.floor(ms / 1000)\n\n node.mtime = {\n secs: secs,\n nsecs: (ms - (secs * 1000)) * 1000\n }\n\n data = node.marshal()\n } else {\n data = options.parent.Data\n }\n options.parent = dagPB.prepare({\n Data: data,\n Links: parentLinks\n })\n\n // Persist the new parent PbNode\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const buf = dagPB.encode(options.parent)\n const hash = await hasher.digest(buf)\n const cid = CID.create(options.cidVersion, dagPB.code, hash)\n\n if (options.flush) {\n await context.repo.blocks.put(cid, buf)\n }\n\n return {\n node: options.parent,\n cid,\n size: buf.length\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n */\nconst addToShardedDirectory = async (context, options) => {\n const {\n shard, path\n } = await addFileToShardedDirectory(context, options)\n const result = await last(shard.flush(context.repo.blocks))\n\n if (!result) {\n throw new Error('No result from flushing shard')\n }\n\n const block = await context.repo.blocks.get(result.cid)\n const node = dagPB.decode(block)\n\n // we have written out the shard, but only one sub-shard will have been written so replace it in the original shard\n const parentLinks = options.parent.Links.filter((link) => {\n // TODO vmx 2021-03-31: Check that there cannot be multiple ones matching\n // Remove the old link\n return (link.Name || '').substring(0, 2) !== path[0].prefix\n })\n\n const newLink = node.Links\n .find(link => (link.Name || '').substring(0, 2) === path[0].prefix)\n\n if (!newLink) {\n throw new Error(`No link found with prefix ${path[0].prefix}`)\n }\n\n parentLinks.push(newLink)\n\n return updateHamtDirectory(context, parentLinks, path[0].bucket, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {object} options\n * @param {CID} options.cid\n * @param {string} options.name\n * @param {number} options.size\n * @param {PBNode} options.parent\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n */\nconst addFileToShardedDirectory = async (context, options) => {\n const file = {\n name: options.name,\n cid: options.cid,\n size: options.size\n }\n\n if (!options.parent.Data) {\n throw errCode(new Error('Parent node with no data passed to addFileToShardedDirectory'), 'ERR_INVALID_PARENT')\n }\n\n // start at the root bucket and descend, loading nodes as we go\n const rootBucket = await recreateInitialHamtLevel(options.parent.Links)\n const node = UnixFS.unmarshal(options.parent.Data)\n\n const shard = new DirSharded({\n root: true,\n dir: true,\n parent: undefined,\n parentKey: undefined,\n path: '',\n dirty: true,\n flat: false,\n mode: node.mode\n }, options)\n shard._bucket = rootBucket\n\n if (node.mtime) {\n // update mtime if previously set\n shard.mtime = {\n secs: Math.round(Date.now() / 1000)\n }\n }\n\n // load subshards until the bucket & position no longer changes\n const position = await rootBucket._findNewBucketAndPos(file.name)\n const path = toBucketPath(position)\n path[0].node = options.parent\n let index = 0\n\n while (index < path.length) {\n const segment = path[index]\n index++\n const node = segment.node\n\n if (!node) {\n throw new Error('Segment had no node')\n }\n\n const link = node.Links\n .find(link => (link.Name || '').substring(0, 2) === segment.prefix)\n\n if (!link) {\n // prefix is new, file will be added to the current bucket\n log(`Link ${segment.prefix}${file.name} will be added`)\n index = path.length\n\n break\n }\n\n if (link.Name === `${segment.prefix}${file.name}`) {\n // file already existed, file will be added to the current bucket\n log(`Link ${segment.prefix}${file.name} will be replaced`)\n index = path.length\n\n break\n }\n\n if ((link.Name || '').length > 2) {\n // another file had the same prefix, will be replaced with a subshard\n log(`Link ${link.Name} ${link.Hash} will be replaced with a subshard`)\n index = path.length\n\n break\n }\n\n // load sub-shard\n log(`Found subshard ${segment.prefix}`)\n const block = await context.repo.blocks.get(link.Hash)\n const subShard = dagPB.decode(block)\n\n // subshard hasn't been loaded, descend to the next level of the HAMT\n if (!path[index]) {\n log(`Loaded new subshard ${segment.prefix}`)\n await recreateHamtLevel(context, subShard.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16))\n\n const position = await rootBucket._findNewBucketAndPos(file.name)\n\n path.push({\n bucket: position.bucket,\n prefix: toPrefix(position.pos),\n node: subShard\n })\n\n break\n }\n\n const nextSegment = path[index]\n\n // add next levels worth of links to bucket\n await addLinksToHamtBucket(context, subShard.Links, nextSegment.bucket, rootBucket)\n\n nextSegment.node = subShard\n }\n\n // finally add the new file into the shard\n await shard._bucket.put(file.name, {\n size: file.size,\n cid: file.cid\n })\n\n return {\n shard, path\n }\n}\n\n/**\n * @param {{ pos: number, bucket: Bucket }} position\n * @returns {{ bucket: Bucket, prefix: string, node?: PBNode }[]}\n */\nconst toBucketPath = (position) => {\n const path = [{\n bucket: position.bucket,\n prefix: toPrefix(position.pos)\n }]\n\n let bucket = position.bucket._parent\n let positionInBucket = position.bucket._posAtParent\n\n while (bucket) {\n path.push({\n bucket,\n prefix: toPrefix(positionInBucket)\n })\n\n positionInBucket = bucket._posAtParent\n bucket = bucket._parent\n }\n\n path.reverse()\n\n return path\n}\n", "import { logger } from '@libp2p/logger'\nimport { addLink } from './add-link.js'\nimport {\n decode\n} from '@ipld/dag-pb'\n\nconst log = logger('ipfs:mfs:utils:update-tree')\n\nconst defaultOptions = {\n shardSplitThreshold: 1000\n}\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('./to-trail').MfsTrail} MfsTrail\n */\n\n/**\n * Loop backwards through the trail, replacing links of all components to update CIDs\n *\n * @param {MfsContext} context\n * @param {MfsTrail[]} trail\n * @param {object} options\n * @param {number} options.shardSplitThreshold\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n */\nexport async function updateTree (context, trail, options) {\n options = Object.assign({}, defaultOptions, options)\n\n log('Trail', trail)\n trail = trail.slice().reverse()\n\n let index = 0\n let child\n\n for await (const block of context.repo.blocks.getMany(trail.map(node => node.cid))) {\n const node = decode(block)\n const cid = trail[index].cid\n const name = trail[index].name\n index++\n\n if (!child) {\n child = {\n cid,\n name,\n size: block.length\n }\n\n continue\n }\n\n /** @type {{ cid: CID, size: number }} */\n const result = await addLink(context, {\n parent: node,\n name: child.name,\n cid: child.cid,\n // TODO vmx 2021-04-05: check what to do with the size\n size: child.size,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion\n })\n\n // new child for next loop\n child = {\n cid: result.cid,\n name,\n // TODO vmx 2021-04-05: check what to do with the size\n size: result.size\n }\n }\n\n // @ts-expect-error - child is possibly undefined\n const { cid } = child\n log(`Final CID ${cid}`)\n\n return cid\n}\n", "import { logger } from '@libp2p/logger'\nimport {\n MFS_ROOT_KEY\n} from '../../../utils.js'\nimport errCode from 'err-code'\n\nconst log = logger('ipfs:mfs:utils:update-mfs-root')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n */\n\n/**\n * @param {MfsContext} context\n * @param {import('multiformats/cid').CID} cid\n * @param {import('ipfs-core-types/src/utils').AbortOptions} options\n */\nexport async function updateMfsRoot (context, cid, options) {\n if (options && options.signal && options.signal.aborted) {\n throw errCode(new Error('Request aborted'), 'ERR_ABORTED', { name: 'Aborted' })\n }\n\n log(`New MFS root will be ${cid}`)\n\n await context.repo.datastore.put(MFS_ROOT_KEY, cid.bytes)\n\n return cid\n}\n", "import errCode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { exporter } from 'ipfs-unixfs-exporter'\nimport { createNode } from './utils/create-node.js'\nimport { toPathComponents } from './utils/to-path-components.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { addLink } from './utils/add-link.js'\nimport { loadMfsRoot } from './utils/with-mfs-root.js'\nimport mergeOpts from 'merge-options'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:mkdir')\n\n/**\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} parents\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {number} shardSplitThreshold\n * @property {boolean} flush\n * @property {number} [mode]\n * @property {MtimeLike} [mtime]\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n parents: false,\n hashAlg: 'sha2-256',\n cidVersion: 0,\n shardSplitThreshold: 1000,\n flush: true\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createMkdir (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"mkdir\"]}\n */\n async function mfsMkdir (path, options = {}) {\n /** @type {DefaultOptions} */\n const opts = mergeOptions(defaultOptions, options)\n\n if (!path) {\n throw new Error('no path given to Mkdir')\n }\n\n path = path.trim()\n\n if (path === '/') {\n if (opts.parents) {\n return\n }\n\n throw errCode(new Error('cannot create directory \\'/\\': Already exists'), 'ERR_INVALID_PATH')\n }\n\n if (path.substring(0, 1) !== '/') {\n throw errCode(new Error('paths must start with a leading slash'), 'ERR_INVALID_PATH')\n }\n\n log(`Creating ${path}`)\n\n const pathComponents = toPathComponents(path)\n\n if (pathComponents[0] === 'ipfs') {\n throw errCode(new Error(\"path cannot have the prefix 'ipfs'\"), 'ERR_INVALID_PATH')\n }\n\n const root = await loadMfsRoot(context, opts)\n let parent\n const trail = []\n const emptyDir = await createNode(context, 'directory', opts)\n\n // make sure the containing folder exists, creating it if necessary\n for (let i = 0; i <= pathComponents.length; i++) {\n const subPathComponents = pathComponents.slice(0, i)\n const subPath = `/ipfs/${root}/${subPathComponents.join('/')}`\n\n try {\n parent = await exporter(subPath, context.repo.blocks)\n\n if (parent.type !== 'file' && parent.type !== 'directory') {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n if (i === pathComponents.length) {\n if (opts.parents) {\n return\n }\n\n throw errCode(new Error('file already exists'), 'ERR_ALREADY_EXISTS')\n }\n\n trail.push({\n name: parent.name,\n cid: parent.cid\n })\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NOT_FOUND') {\n if (i < pathComponents.length && !opts.parents) {\n throw errCode(new Error(`Intermediate directory path ${subPath} does not exist, use the -p flag to create it`), 'ERR_NOT_FOUND')\n }\n\n // add the intermediate directory\n await addEmptyDir(context, subPathComponents[subPathComponents.length - 1], emptyDir, trail[trail.length - 1], trail, opts)\n } else {\n throw err\n }\n }\n }\n\n // add an empty dir to the last path component\n // await addEmptyDir(context, pathComponents[pathComponents.length - 1], emptyDir, parent, trail)\n\n // update the tree from the leaf to the root\n const newRootCid = await updateTree(context, trail, opts)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, opts)\n }\n\n return withTimeoutOption(mfsMkdir)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} childName\n * @param {{ cid: CID, node?: PBNode }} emptyDir\n * @param {{ cid?: CID, node?: PBNode }} parent\n * @param {{ name: string, cid: CID }[]} trail\n * @param {DefaultOptions} options\n */\nconst addEmptyDir = async (context, childName, emptyDir, parent, trail, options) => {\n log(`Adding empty dir called ${childName} to ${parent.cid}`)\n\n const result = await addLink(context, {\n parent: parent.node,\n parentCid: parent.cid,\n // TODO vmx 2021-03-09: Remove the usage of size completely\n size: 0,\n cid: emptyDir.cid,\n name: childName,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold\n })\n\n trail[trail.length - 1].cid = result.cid\n\n trail.push({\n name: childName,\n cid: emptyDir.cid\n })\n}\n", "import { UnixFS } from 'ipfs-unixfs'\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('../').MfsContext} MfsContext\n */\n\n/**\n * @param {MfsContext} context\n * @param {'file' | 'directory'} type\n * @param {object} options\n * @param {string} options.hashAlg\n * @param {CIDVersion} options.cidVersion\n * @param {boolean} options.flush\n * @param {MtimeLike} [options.mtime]\n * @param {number} [options.mode]\n */\nexport async function createNode (context, type, options) {\n const metadata = new UnixFS({\n type,\n mode: options.mode,\n mtime: options.mtime\n })\n\n // Persist the new parent PBNode\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const node = {\n Data: metadata.marshal(),\n Links: []\n }\n const buf = dagPB.encode(node)\n const hash = await hasher.digest(buf)\n const cid = CID.create(options.cidVersion, dagPB.code, hash)\n\n if (options.flush) {\n await context.repo.blocks.put(cid, buf)\n }\n\n return {\n cid,\n node\n }\n}\n", "import { createMkdir } from './mkdir.js'\nimport { createStat } from './stat.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport { addLink } from './utils/add-link.js'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport mergeOpts from 'merge-options'\nimport { toTrail } from './utils/to-trail.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:cp')\n\n/**\n * @typedef {import('@ipld/dag-pb').PBNode} DAGNode\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').Mtime} Mtime\n * @typedef {import('./utils/to-mfs-path').MfsPath} MfsPath\n * @typedef {import('./utils/to-trail').MfsTrail} MfsTrail\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} parents\n * @property {boolean} flush\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {number} shardSplitThreshold\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n parents: false,\n flush: true,\n hashAlg: 'sha2-256',\n cidVersion: 0,\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createCp (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"cp\"]}\n */\n async function mfsCp (from, to, opts = {}) {\n /** @type {DefaultOptions} */\n const options = mergeOptions(defaultOptions, opts)\n\n if (!Array.isArray(from)) {\n from = [from]\n }\n\n const sources = await Promise.all(\n from.map((/** @type {CID | string} */ path) => toMfsPath(context, path, options))\n )\n let destination = await toMfsPath(context, to, options)\n\n if (!sources.length || !destination) {\n throw errCode(new Error('Please supply at least one source'), 'ERR_INVALID_PARAMS')\n }\n\n // make sure all sources exist\n const missing = sources.find(source => !source.exists)\n\n if (missing) {\n throw errCode(new Error(`${missing.path} does not exist`), 'ERR_INVALID_PARAMS')\n }\n\n const destinationIsDirectory = isDirectory(destination)\n\n if (destination.exists) {\n log('Destination exists')\n\n if (sources.length === 1 && !destinationIsDirectory) {\n throw errCode(new Error('directory already has entry by that name'), 'ERR_ALREADY_EXISTS')\n }\n } else {\n log('Destination does not exist')\n\n if (sources.length > 1) {\n // copying multiple files to one location, destination will be a directory\n if (!options.parents) {\n throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS')\n }\n\n await createMkdir(context)(destination.path, options)\n destination = await toMfsPath(context, destination.path, options)\n } else if (destination.parts.length > 1) {\n // copying to a folder, create it if necessary\n const parentFolder = `/${destination.parts.slice(0, -1).join('/')}`\n\n try {\n await createStat(context)(parentFolder, options)\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n\n if (!options.parents) {\n throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS')\n }\n\n await createMkdir(context)(parentFolder, options)\n destination = await toMfsPath(context, destination.path, options)\n }\n }\n }\n\n const destinationPath = isDirectory(destination) ? destination.mfsPath : destination.mfsDirectory\n const trail = await toTrail(context, destinationPath)\n\n if (sources.length === 1) {\n const source = sources.pop()\n\n if (!source) {\n throw errCode(new Error('could not find source'), 'ERR_INVALID_PARAMS')\n }\n\n const destinationName = destinationIsDirectory ? source.name : destination.name\n\n log(`Only one source, copying to destination ${destinationIsDirectory ? 'directory' : 'file'} ${destinationName}`)\n\n return copyToFile(context, source, destinationName, trail, options)\n }\n\n log('Multiple sources, wrapping in a directory')\n return copyToDirectory(context, sources, destination, trail, options)\n }\n\n return withTimeoutOption(mfsCp)\n}\n\n/**\n * @param {*} destination\n */\nconst isDirectory = (destination) => {\n return destination.unixfs &&\n destination.unixfs.type &&\n destination.unixfs.type.includes('directory')\n}\n\n/**\n * @param {MfsContext} context\n * @param {MfsPath} source\n * @param {string} destination\n * @param {MfsTrail[]} destinationTrail\n * @param {DefaultOptions} options\n */\nconst copyToFile = async (context, source, destination, destinationTrail, options) => {\n let parent = destinationTrail.pop()\n\n if (!parent) {\n throw errCode(new Error('destination had no parent'), 'ERR_INVALID_PARAMS')\n }\n\n parent = await addSourceToParent(context, source, destination, parent, options)\n\n // update the tree with the new containing directory\n destinationTrail.push(parent)\n\n const newRootCid = await updateTree(context, destinationTrail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {MfsPath[]} sources\n * @param {*} destination\n * @param {MfsTrail[]} destinationTrail\n * @param {DefaultOptions} options\n */\nconst copyToDirectory = async (context, sources, destination, destinationTrail, options) => {\n // copy all the sources to the destination\n for (let i = 0; i < sources.length; i++) {\n const source = sources[i]\n\n destination = await addSourceToParent(context, source, source.name, destination, options)\n }\n\n // update the tree with the new containing directory\n destinationTrail[destinationTrail.length - 1] = destination\n\n const newRootCid = await updateTree(context, destinationTrail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {MfsPath} source\n * @param {string} childName\n * @param {*} parent\n * @param {DefaultOptions} options\n * @returns {Promise}\n */\nconst addSourceToParent = async (context, source, childName, parent, options) => {\n const sourceBlock = await context.repo.blocks.get(source.cid)\n const {\n node,\n cid,\n size\n } = await addLink(context, {\n parentCid: parent.cid,\n size: sourceBlock.length,\n cid: source.cid,\n name: childName,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold\n })\n\n parent.node = node\n parent.cid = cid\n parent.size = size\n\n return parent\n}\n", "import errCode from 'err-code'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport { removeLink } from './utils/remove-link.js'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { toTrail } from './utils/to-trail.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport mergeOpts from 'merge-options'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} recursive\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {boolean} flush\n * @property {number} shardSplitThreshold\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n recursive: false,\n cidVersion: 0,\n hashAlg: 'sha2-256',\n flush: true,\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createRm (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"rm\"]}\n */\n async function mfsRm (paths, opts = {}) {\n /** @type {DefaultOptions} */\n const options = mergeOptions(defaultOptions, opts)\n\n if (!Array.isArray(paths)) {\n paths = [paths]\n }\n\n const sources = await Promise.all(\n paths.map(path => toMfsPath(context, path, options))\n )\n\n if (!sources.length) {\n throw errCode(new Error('Please supply at least one path to remove'), 'ERR_INVALID_PARAMS')\n }\n\n sources.forEach(source => {\n if (source.path === '/') {\n throw errCode(new Error('Cannot delete root'), 'ERR_INVALID_PARAMS')\n }\n })\n\n for (const source of sources) {\n await removePath(context, source.path, options)\n }\n }\n\n return withTimeoutOption(mfsRm)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} path\n * @param {DefaultOptions} options\n */\nconst removePath = async (context, path, options) => {\n const mfsPath = await toMfsPath(context, path, options)\n const trail = await toTrail(context, mfsPath.mfsPath)\n const child = trail[trail.length - 1]\n trail.pop()\n const parent = trail[trail.length - 1]\n\n if (!parent) {\n throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND')\n }\n\n if (child.type === 'directory' && !options.recursive) {\n throw errCode(new Error(`${path} is a directory, use -r to remove directories`), 'ERR_WAS_DIR')\n }\n\n const {\n cid\n } = await removeLink(context, {\n parentCid: parent.cid,\n name: child.name,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold\n })\n\n parent.cid = cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n}\n", "\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { logger } from '@libp2p/logger'\nimport { UnixFS } from 'ipfs-unixfs'\nimport {\n generatePath,\n updateHamtDirectory\n} from './hamt-utils.js'\nimport errCode from 'err-code'\n\nconst log = logger('ipfs:mfs:core:utils:remove-link')\n\n/**\n * @typedef {import('../').MfsContext} MfsContext\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('hamt-sharding').Bucket} Bucket\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n *\n * @typedef {object} RemoveLinkOptions\n * @property {string} name\n * @property {number} shardSplitThreshold\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {boolean} flush\n * @property {CID} [parentCid]\n * @property {PBNode} [parent]\n *\n * @typedef {object} RemoveLinkOptionsInternal\n * @property {string} name\n * @property {number} shardSplitThreshold\n * @property {string} hashAlg\n * @property {CIDVersion} cidVersion\n * @property {boolean} flush\n * @property {PBNode} parent\n */\n\n/**\n * @param {MfsContext} context\n * @param {RemoveLinkOptions} options\n */\nexport async function removeLink (context, options) {\n let parent = options.parent\n\n if (options.parentCid) {\n const parentCid = CID.asCID(options.parentCid)\n if (parentCid === null) {\n throw errCode(new Error('Invalid CID passed to removeLink'), 'EINVALIDPARENTCID')\n }\n\n log(`Loading parent node ${parentCid}`)\n const block = await context.repo.blocks.get(parentCid)\n parent = dagPB.decode(block)\n }\n\n if (!parent) {\n throw errCode(new Error('No parent node or CID passed to removeLink'), 'EINVALIDPARENT')\n }\n\n if (!options.name) {\n throw errCode(new Error('No child name passed to removeLink'), 'EINVALIDCHILDNAME')\n }\n\n if (!parent.Data) {\n throw errCode(new Error('Parent node had no data'), 'ERR_INVALID_NODE')\n }\n\n const meta = UnixFS.unmarshal(parent.Data)\n\n if (meta.type === 'hamt-sharded-directory') {\n log(`Removing ${options.name} from sharded directory`)\n\n return removeFromShardedDirectory(context, {\n ...options,\n parent\n })\n }\n\n log(`Removing link ${options.name} regular directory`)\n\n return removeFromDirectory(context, {\n ...options,\n parent\n })\n}\n\n/**\n * @param {MfsContext} context\n * @param {RemoveLinkOptionsInternal} options\n */\nconst removeFromDirectory = async (context, options) => {\n // Remove existing link if it exists\n options.parent.Links = options.parent.Links.filter((link) => {\n return link.Name !== options.name\n })\n\n const parentBlock = await dagPB.encode(options.parent)\n const hasher = await context.hashers.getHasher(options.hashAlg)\n const hash = await hasher.digest(parentBlock)\n const parentCid = CID.create(options.cidVersion, dagPB.code, hash)\n\n await context.repo.blocks.put(parentCid, parentBlock)\n\n log(`Updated regular directory ${parentCid}`)\n\n return {\n node: options.parent,\n cid: parentCid\n }\n}\n\n/**\n * @param {MfsContext} context\n * @param {RemoveLinkOptionsInternal} options\n */\nconst removeFromShardedDirectory = async (context, options) => {\n const {\n rootBucket, path\n } = await generatePath(context, options.name, options.parent)\n\n await rootBucket.del(options.name)\n\n const {\n node\n } = await updateShard(context, path, options.name, options)\n\n return updateHamtDirectory(context, node.Links, rootBucket, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {{ bucket: Bucket, prefix: string, node?: PBNode }[]} positions\n * @param {string} name\n * @param {RemoveLinkOptionsInternal} options\n * @returns {Promise<{ node: PBNode, cid: CID, size: number }>}\n */\nconst updateShard = async (context, positions, name, options) => {\n const last = positions.pop()\n\n if (!last) {\n throw errCode(new Error('Could not find parent'), 'EINVALIDPARENT')\n }\n\n const {\n bucket,\n prefix,\n node\n } = last\n\n if (!node) {\n throw errCode(new Error('Could not find parent'), 'EINVALIDPARENT')\n }\n\n const link = node.Links\n .find(link => (link.Name || '').substring(0, 2) === prefix)\n\n if (!link) {\n throw errCode(new Error(`No link found with prefix ${prefix} for file ${name}`), 'ERR_NOT_FOUND')\n }\n\n if (link.Name === `${prefix}${name}`) {\n log(`Removing existing link ${link.Name}`)\n\n const links = node.Links.filter((nodeLink) => {\n return nodeLink.Name !== link.Name\n })\n\n await bucket.del(name)\n\n return updateHamtDirectory(context, links, bucket, options)\n }\n\n log(`Descending into sub-shard ${link.Name} for ${prefix}${name}`)\n\n const result = await updateShard(context, positions, name, options)\n\n let cid = result.cid\n let size = result.size\n let newName = prefix\n\n if (result.node.Links.length === 1) {\n log(`Removing subshard for ${prefix}`)\n\n // convert shard back to normal dir\n const link = result.node.Links[0]\n\n newName = `${prefix}${(link.Name || '').substring(2)}`\n cid = link.Hash\n size = link.Tsize || 0\n }\n\n log(`Updating shard ${prefix} with name ${newName}`)\n\n return updateShardParent(context, bucket, node, prefix, newName, size, cid, options)\n}\n\n/**\n * @param {MfsContext} context\n * @param {Bucket} bucket\n * @param {PBNode} parent\n * @param {string} oldName\n * @param {string} newName\n * @param {number} size\n * @param {CID} cid\n * @param {RemoveLinkOptionsInternal} options\n */\nconst updateShardParent = (context, bucket, parent, oldName, newName, size, cid, options) => {\n // Remove existing link if it exists\n const parentLinks = parent.Links.filter((link) => {\n return link.Name !== oldName\n })\n parentLinks.push({\n Name: newName,\n Tsize: size,\n Hash: cid\n })\n\n return updateHamtDirectory(context, parentLinks, bucket, options)\n}\n", "import { createStat } from './stat.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport mergeOpts from 'merge-options'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {}\n\n/**\n * @param {MfsContext} context\n */\nexport function createFlush (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"flush\"]}\n */\n async function mfsFlush (path, options = {}) {\n /** @type {DefaultOptions} */\n options = mergeOptions(defaultOptions, options)\n\n const { cid } = await createStat(context)(path, options)\n\n return cid\n }\n\n return withTimeoutOption(mfsFlush)\n}\n", "import { createCp } from './cp.js'\nimport { createRm } from './rm.js'\nimport mergeOpts from 'merge-options'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} parents\n * @property {boolean} flush\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {number} shardSplitThreshold\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n parents: false,\n flush: true,\n cidVersion: 0,\n hashAlg: 'sha2-256',\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createMv (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"mv\"]}\n */\n async function mfsMv (from, to, options = {}) {\n /** @type {DefaultOptions} */\n const opts = mergeOptions(defaultOptions, options)\n\n await createCp(context)(from, to, opts)\n await createRm(context)(from, {\n ...opts,\n recursive: true\n })\n }\n\n return withTimeoutOption(mfsMv)\n}\n", "import mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { toTrail } from './utils/to-trail.js'\nimport { addLink } from './utils/add-link.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:touch')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {boolean} flush\n * @property {number} shardSplitThreshold\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {MtimeLike} [mtime]\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n flush: true,\n shardSplitThreshold: 1000,\n cidVersion: 0,\n hashAlg: 'sha2-256'\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createTouch (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"touch\"]}\n */\n async function mfsTouch (path, options = {}) {\n /** @type {DefaultOptions} */\n const settings = mergeOptions(defaultOptions, options)\n settings.mtime = settings.mtime || new Date()\n\n log(`Touching ${path} mtime: ${settings.mtime}`)\n\n const {\n cid,\n mfsDirectory,\n name,\n exists\n } = await toMfsPath(context, path, settings)\n\n const hashAlg = options.hashAlg || defaultOptions.hashAlg\n const hasher = await context.hashers.getHasher(hashAlg)\n\n let updatedBlock\n let updatedCid\n\n let cidVersion = settings.cidVersion\n\n if (!exists) {\n const metadata = new UnixFS({\n type: 'file',\n mtime: settings.mtime\n })\n updatedBlock = dagPB.encode({ Data: metadata.marshal(), Links: [] })\n\n const hash = await hasher.digest(updatedBlock)\n\n updatedCid = CID.create(settings.cidVersion, dagPB.code, hash)\n\n if (settings.flush) {\n await context.repo.blocks.put(updatedCid, updatedBlock)\n }\n } else {\n if (cid.code !== dagPB.code) {\n throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')\n }\n\n cidVersion = cid.version\n\n const block = await context.repo.blocks.get(cid)\n const node = dagPB.decode(block)\n\n if (!node.Data) {\n throw errCode(new Error(`${path} had no data`), 'ERR_INVALID_NODE')\n }\n\n const metadata = UnixFS.unmarshal(node.Data)\n\n // @ts-expect-error TODO: restore setting all date types as mtime - it's in the code, just not the signature\n metadata.mtime = settings.mtime\n\n updatedBlock = dagPB.encode({\n Data: metadata.marshal(),\n Links: node.Links\n })\n\n const hash = await hasher.digest(updatedBlock)\n updatedCid = CID.create(settings.cidVersion, dagPB.code, hash)\n\n if (settings.flush) {\n await context.repo.blocks.put(updatedCid, updatedBlock)\n }\n }\n\n const trail = await toTrail(context, mfsDirectory)\n const parent = trail[trail.length - 1]\n const parentCid = parent.cid\n const parentBlock = await context.repo.blocks.get(parentCid)\n const parentNode = dagPB.decode(parentBlock)\n\n const result = await addLink(context, {\n parent: parentNode,\n name: name,\n cid: updatedCid,\n size: updatedBlock.length,\n flush: settings.flush,\n shardSplitThreshold: settings.shardSplitThreshold,\n hashAlg: settings.hashAlg,\n cidVersion\n })\n\n parent.cid = result.cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, settings)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, settings)\n }\n\n return withTimeoutOption(mfsTouch)\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport mergeOpts from 'merge-options'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {object} DefaultOptions\n * @property {number} offset\n * @property {number} length\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n offset: 0,\n length: Infinity\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createRead (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"read\"]}\n */\n function mfsRead (path, options = {}) {\n /** @type {DefaultOptions} */\n options = mergeOptions(defaultOptions, options)\n\n return {\n [Symbol.asyncIterator]: async function * read () {\n const mfsPath = await toMfsPath(context, path, options)\n const result = await exporter(mfsPath.mfsPath, context.repo.blocks)\n\n if (result.type !== 'file' && result.type !== 'raw') {\n throw errCode(new Error(`${path} was not a file or raw bytes`), 'ERR_NOT_FILE')\n }\n\n if (!result.content) {\n throw errCode(new Error(`Could not load content stream from ${path}`), 'ERR_NO_CONTENT')\n }\n\n for await (const buf of result.content({\n offset: options.offset,\n length: options.length\n })) {\n yield buf\n }\n }\n }\n }\n\n return withTimeoutOption(mfsRead)\n}\n", "import errCode from 'err-code'\nimport { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport browserStreamToIt from 'browser-readablestream-to-it'\n\nconst log = logger('ipfs:mfs:utils:to-async-iterator')\n\n/**\n * @param {*} content\n */\nexport function toAsyncIterator (content) {\n if (!content) {\n throw errCode(new Error('paths must start with a leading slash'), 'ERR_INVALID_PATH')\n }\n\n if (typeof content === 'string' || content instanceof String) {\n log('Content was a string')\n\n content = uint8ArrayFromString(content.toString())\n }\n\n if (content.length) {\n log('Content was array-like')\n\n return {\n [Symbol.asyncIterator]: function * bufferContent () {\n yield content\n }\n }\n }\n\n if (content[Symbol.asyncIterator]) {\n log('Content was an async iterator')\n return content\n }\n\n if (content[Symbol.iterator]) {\n log('Content was an iterator')\n return content\n }\n\n if (global.Blob && content instanceof global.Blob) {\n // HTML5 Blob objects (including Files)\n log('Content was an HTML5 Blob')\n return browserStreamToIt(content.stream())\n }\n\n throw errCode(new Error(`Don't know how to convert ${content} into an async iterator`), 'ERR_INVALID_PARAMS')\n}\n", "import { logger } from '@libp2p/logger'\nimport { importer } from 'ipfs-unixfs-importer'\nimport {\n decode\n} from '@ipld/dag-pb'\nimport { createStat } from './stat.js'\nimport { createMkdir } from './mkdir.js'\nimport { addLink } from './utils/add-link.js'\nimport mergeOpts from 'merge-options'\nimport { createLock } from './utils/create-lock.js'\nimport { toAsyncIterator } from './utils/to-async-iterator.js'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { toPathComponents } from './utils/to-path-components.js'\nimport { toTrail } from './utils/to-trail.js'\nimport { updateTree } from './utils/update-tree.js'\nimport { updateMfsRoot } from './utils/update-mfs-root.js'\nimport errCode from 'err-code'\nimport {\n MFS_MAX_CHUNK_SIZE\n} from '../../utils.js'\nimport last from 'it-last'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport {\n parseMode,\n parseMtime\n} from 'ipfs-unixfs'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:mfs:write')\n\n/**\n * @typedef {import('multiformats/cid').Version} CIDVersion\n * @typedef {import('ipfs-unixfs').MtimeLike} MtimeLike\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {import('./utils/to-mfs-path').FilePath} FilePath\n * @typedef {import('./utils/to-mfs-path').MfsPath} MfsPath\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n *\n * @typedef {object} DefaultOptions\n * @property {number} offset\n * @property {number} length\n * @property {boolean} create\n * @property {boolean} truncate\n * @property {boolean} rawLeaves\n * @property {boolean} reduceSingleLeafToSelf\n * @property {CIDVersion} cidVersion\n * @property {string} hashAlg\n * @property {boolean} parents\n * @property {import('ipfs-core-types/src/root').AddProgressFn} progress\n * @property {'trickle' | 'balanced'} strategy\n * @property {boolean} flush\n * @property {'raw' | 'file'} leafType\n * @property {number} shardSplitThreshold\n * @property {MtimeLike} [mtime]\n * @property {number} [mode]\n * @property {AbortSignal} [signal]\n * @property {number} [timeout]\n */\n\n/**\n * @type {DefaultOptions}\n */\nconst defaultOptions = {\n offset: 0, // the offset in the file to begin writing\n length: Infinity, // how many bytes from the incoming buffer to write\n create: false, // whether to create the file if it does not exist\n truncate: false, // whether to truncate the file first\n rawLeaves: false,\n reduceSingleLeafToSelf: false,\n cidVersion: 0,\n hashAlg: 'sha2-256',\n parents: false, // whether to create intermediate directories if they do not exist\n progress: (bytes, path) => {},\n strategy: 'trickle',\n flush: true,\n leafType: 'raw',\n shardSplitThreshold: 1000\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createWrite (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"write\"]}\n */\n async function mfsWrite (path, content, opts = {}) {\n /** @type {DefaultOptions} */\n const options = mergeOptions(defaultOptions, opts)\n\n /** @type {AsyncIterable} */\n let source\n /** @type {MfsPath} */\n let destination\n /** @type {MfsPath} */\n let parent\n log('Reading source, destination and parent')\n await createLock().readLock(async () => {\n source = await toAsyncIterator(content)\n destination = await toMfsPath(context, path, options)\n parent = await toMfsPath(context, destination.mfsDirectory, options)\n })()\n log('Read source, destination and parent')\n // @ts-expect-error - parent may be undefined\n if (!options.parents && !parent.exists) {\n throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST')\n }\n\n // @ts-expect-error\n if (source == null) {\n throw errCode(new Error('could not create source'), 'ERR_NO_SOURCE')\n }\n\n // @ts-expect-error\n if (destination == null) {\n throw errCode(new Error('could not create destination'), 'ERR_NO_DESTINATION')\n }\n\n if (!options.create && !destination.exists) {\n throw errCode(new Error('file does not exist'), 'ERR_NO_EXIST')\n }\n\n if (destination.entryType !== 'file') {\n throw errCode(new Error('not a file'), 'ERR_NOT_A_FILE')\n }\n\n return updateOrImport(context, path, source, destination, options)\n }\n\n return withTimeoutOption(mfsWrite)\n}\n\n/**\n * @param {MfsContext} context\n * @param {string} path\n * @param {AsyncIterable} source\n * @param {FilePath} destination\n * @param {DefaultOptions} options\n */\nconst updateOrImport = async (context, path, source, destination, options) => {\n const child = await write(context, source, destination, options)\n\n // The slow bit is done, now add or replace the DAGLink in the containing directory\n // re-reading the path to the containing folder in case it has changed in the interim\n await createLock().writeLock(async () => {\n const pathComponents = toPathComponents(path)\n const fileName = pathComponents.pop()\n\n if (fileName == null) {\n throw errCode(new Error('source does not exist'), 'ERR_NO_EXIST')\n }\n\n let parentExists = false\n\n try {\n await createStat(context)(`/${pathComponents.join('/')}`, options)\n parentExists = true\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n if (!parentExists) {\n await createMkdir(context)(`/${pathComponents.join('/')}`, options)\n }\n\n // get an updated mfs path in case the root changed while we were writing\n const updatedPath = await toMfsPath(context, path, options)\n const trail = await toTrail(context, updatedPath.mfsDirectory)\n const parent = trail[trail.length - 1]\n\n if (!parent) {\n throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST')\n }\n\n if (!parent.type || !parent.type.includes('directory')) {\n throw errCode(new Error(`cannot write to ${parent.name}: Not a directory`), 'ERR_NOT_A_DIRECTORY')\n }\n\n const parentBlock = await context.repo.blocks.get(parent.cid)\n const parentNode = decode(parentBlock)\n\n const result = await addLink(context, {\n parent: parentNode,\n name: fileName,\n cid: child.cid,\n size: child.size,\n flush: options.flush,\n shardSplitThreshold: options.shardSplitThreshold,\n hashAlg: options.hashAlg,\n cidVersion: options.cidVersion\n })\n\n parent.cid = result.cid\n\n // update the tree with the new child\n const newRootCid = await updateTree(context, trail, options)\n\n // Update the MFS record with the new CID for the root of the tree\n await updateMfsRoot(context, newRootCid, options)\n })()\n}\n\n/**\n * @param {MfsContext} context\n * @param {AsyncIterable} source\n * @param {FilePath} destination\n * @param {DefaultOptions} options\n */\nconst write = async (context, source, destination, options) => {\n if (destination.exists) {\n log(`Overwriting file ${destination.cid} offset ${options.offset} length ${options.length}`)\n } else {\n log(`Writing file offset ${options.offset} length ${options.length}`)\n }\n\n /** @type {Array<() => AsyncIterable>} */\n const sources = []\n\n // pad start of file if necessary\n if (options.offset > 0) {\n if (destination.unixfs) {\n log(`Writing first ${options.offset} bytes of original file`)\n\n sources.push(\n () => {\n return destination.content({\n offset: 0,\n length: options.offset\n })\n }\n )\n\n if (destination.unixfs.fileSize() < options.offset) {\n const extra = options.offset - destination.unixfs.fileSize()\n\n log(`Writing zeros for extra ${extra} bytes`)\n sources.push(\n asyncZeroes(extra)\n )\n }\n } else {\n log(`Writing zeros for first ${options.offset} bytes`)\n sources.push(\n asyncZeroes(options.offset)\n )\n }\n }\n\n sources.push(\n limitAsyncStreamBytes(source, options.length)\n )\n\n const content = countBytesStreamed(catAsyncIterators(sources), (bytesWritten) => {\n if (destination.unixfs && !options.truncate) {\n // if we've done reading from the new source and we are not going\n // to truncate the file, add the end of the existing file to the output\n const fileSize = destination.unixfs.fileSize()\n\n if (fileSize > bytesWritten) {\n log(`Writing last ${fileSize - bytesWritten} of ${fileSize} bytes from original file starting at offset ${bytesWritten}`)\n\n return destination.content({\n offset: bytesWritten\n })\n } else {\n log('Not writing last bytes from original file')\n }\n }\n\n return {\n [Symbol.asyncIterator]: async function * () {}\n }\n })\n\n /** @type {number | undefined} */\n let mode\n\n if (options.mode !== undefined && options.mode !== null) {\n mode = parseMode(options.mode)\n } else if (destination && destination.unixfs) {\n mode = destination.unixfs.mode\n }\n\n /** @type {import('ipfs-unixfs').Mtime | undefined} */\n let mtime\n\n if (options.mtime != null) {\n mtime = parseMtime(options.mtime)\n } else if (destination && destination.unixfs) {\n mtime = destination.unixfs.mtime\n }\n\n const hasher = await context.hashers.getHasher(options.hashAlg)\n\n const result = await last(importer([{\n content: content,\n\n // persist mode & mtime if set previously\n mode,\n mtime\n }], context.repo.blocks, {\n progress: options.progress,\n hasher,\n cidVersion: options.cidVersion,\n strategy: options.strategy,\n rawLeaves: options.rawLeaves,\n reduceSingleLeafToSelf: options.reduceSingleLeafToSelf,\n leafType: options.leafType\n }))\n\n if (!result) {\n throw errCode(new Error(`cannot write to ${parent.name}`), 'ERR_COULD_NOT_WRITE')\n }\n\n log(`Wrote ${result.cid}`)\n\n return {\n cid: result.cid,\n size: result.size\n }\n}\n\n/**\n * @param {AsyncIterable} stream\n * @param {number} limit\n */\nconst limitAsyncStreamBytes = (stream, limit) => {\n return async function * _limitAsyncStreamBytes () {\n let emitted = 0\n\n for await (const buf of stream) {\n emitted += buf.length\n\n if (emitted > limit) {\n yield buf.subarray(0, limit - emitted)\n\n return\n }\n\n yield buf\n }\n }\n}\n\n/**\n * @param {number} count\n * @param {number} chunkSize\n */\nconst asyncZeroes = (count, chunkSize = MFS_MAX_CHUNK_SIZE) => {\n const buf = new Uint8Array(chunkSize)\n\n async function * _asyncZeroes () {\n while (true) {\n yield buf\n }\n }\n\n return limitAsyncStreamBytes(_asyncZeroes(), count)\n}\n\n/**\n * @param {Array<() => AsyncIterable>} sources\n */\nconst catAsyncIterators = async function * (sources) { // eslint-disable-line require-await\n for (let i = 0; i < sources.length; i++) {\n yield * sources[i]()\n }\n}\n\n/**\n * @param {AsyncIterable} source\n * @param {(count: number) => AsyncIterable} notify\n */\nconst countBytesStreamed = async function * (source, notify) {\n let wrote = 0\n\n for await (const buf of source) {\n wrote += buf.length\n\n yield buf\n }\n\n for await (const buf of notify(wrote)) {\n wrote += buf.length\n\n yield buf\n }\n}\n", "import { exporter } from 'ipfs-unixfs-exporter'\nimport { toMfsPath } from './utils/to-mfs-path.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport map from 'it-map'\n\n/**\n * @typedef {import('./').MfsContext} MfsContext\n * @typedef {import('ipfs-core-types/src/files').MFSEntry} MFSEntry\n */\n\n/**\n * @param {import('ipfs-unixfs-exporter').UnixFSEntry} fsEntry\n */\nconst toOutput = (fsEntry) => {\n /** @type {MFSEntry} */\n const output = {\n cid: fsEntry.cid,\n name: fsEntry.name,\n type: fsEntry.type === 'directory' ? 'directory' : 'file',\n size: fsEntry.size\n }\n\n if (fsEntry.type === 'file' || fsEntry.type === 'directory') {\n output.mode = fsEntry.unixfs.mode\n output.mtime = fsEntry.unixfs.mtime\n }\n\n return output\n}\n\n/**\n * @param {MfsContext} context\n */\nexport function createLs (context) {\n /**\n * @type {import('ipfs-core-types/src/files').API<{}>[\"ls\"]}\n */\n async function * mfsLs (path, options = {}) {\n const mfsPath = await toMfsPath(context, path, options)\n const fsEntry = await exporter(mfsPath.mfsPath, context.repo.blocks)\n\n // directory, perhaps sharded\n if (fsEntry.type === 'directory') {\n yield * map(fsEntry.content(options), toOutput)\n\n return\n }\n\n // single file/node\n yield toOutput(fsEntry)\n }\n\n return withTimeoutOption(mfsLs)\n}\n", "import { createLock } from './utils/create-lock.js'\nimport * as isIpfs from 'is-ipfs'\nimport { createStat } from './stat.js'\nimport { createChmod } from './chmod.js'\nimport { createCp } from './cp.js'\nimport { createFlush } from './flush.js'\nimport { createMkdir } from './mkdir.js'\nimport { createMv } from './mv.js'\nimport { createRm } from './rm.js'\nimport { createTouch } from './touch.js'\nimport { createRead } from './read.js'\nimport { createWrite } from './write.js'\nimport { createLs } from './ls.js'\n\n/**\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n *\n * @typedef {object} MfsContext\n * @property {IPFSRepo} repo\n * @property {Multihashes} hashers\n */\n\n/**\n * These operations are read-locked at the function level and will execute simultaneously\n *\n * @type {Record}\n */\nconst readOperations = {\n stat: createStat\n}\n\n/**\n * These operations are locked at the function level and will execute in series\n *\n * @type {Record}\n */\nconst writeOperations = {\n chmod: createChmod,\n cp: createCp,\n flush: createFlush,\n mkdir: createMkdir,\n mv: createMv,\n rm: createRm,\n touch: createTouch\n}\n\n/**\n * These operations are asynchronous and manage their own locking\n *\n * @type {Record}\n */\nconst unwrappedOperations = {\n write: createWrite,\n read: createRead,\n ls: createLs\n}\n\n/**\n * @param {object} arg\n * @param {MfsContext} arg.options\n * @param {*} arg.mfs\n * @param {*} arg.operations\n * @param {*} arg.lock\n */\nconst wrap = ({\n options, mfs, operations, lock\n}) => {\n Object.keys(operations).forEach(key => {\n mfs[key] = lock(operations[key](options))\n })\n}\n\nconst defaultOptions = {\n repoOwner: true,\n repo: null\n}\n\n/**\n * @param {object} options\n * @param {IPFSRepo} options.repo\n * @param {boolean} options.repoOwner\n * @param {Multihashes} options.hashers\n */\nfunction createMfs (options) {\n const {\n repoOwner\n } = Object.assign({}, defaultOptions || {}, options)\n\n const lock = createLock(repoOwner)\n\n /**\n * @param {(fn: (...args: any) => any) => (...args: any) => any} operation\n */\n const readLock = (operation) => {\n return lock.readLock(operation)\n }\n\n /**\n * @param {(fn: (...args: any) => any) => (...args: any) => any} operation\n */\n const writeLock = (operation) => {\n return lock.writeLock(operation)\n }\n\n /** @type {Record} */\n const mfs = {}\n\n wrap({\n options, mfs, operations: readOperations, lock: readLock\n })\n wrap({\n options, mfs, operations: writeOperations, lock: writeLock\n })\n\n Object.keys(unwrappedOperations).forEach(key => {\n mfs[key] = unwrappedOperations[key](options)\n })\n\n return mfs\n}\n\n/**\n * @param {object} context\n * @param {IPFSRepo} context.repo\n * @param {import('../../types').Preload} context.preload\n * @param {import('..').Options} context.options\n * @param {Multihashes} context.hashers\n * @returns {import('ipfs-core-types/src/files').API}\n */\nexport function createFiles ({ repo, preload, hashers, options: constructorOptions }) {\n const methods = createMfs({\n repo,\n repoOwner: constructorOptions.repoOwner !== false,\n hashers\n })\n\n /**\n * @param {any} fn\n */\n const withPreload = fn => {\n /**\n * @param {...any} args\n */\n const wrapped = (...args) => {\n const paths = args.filter(arg => isIpfs.ipfsPath(arg) || isIpfs.cid(arg))\n\n if (paths.length) {\n const options = args[args.length - 1]\n if (options && options.preload !== false) {\n paths.forEach(path => preload(path))\n }\n }\n\n return fn(...args)\n }\n\n return wrapped\n }\n\n return {\n ...methods,\n chmod: methods.chmod,\n cp: withPreload(methods.cp),\n mkdir: methods.mkdir,\n stat: withPreload(methods.stat),\n rm: methods.rm,\n read: withPreload(methods.read),\n touch: methods.touch,\n write: methods.write,\n mv: withPreload(methods.mv),\n flush: methods.flush,\n ls: withPreload(async function * (/** @type {...any} */ ...args) {\n for await (const file of methods.ls(...args)) {\n yield { ...file, size: file.size || 0 }\n }\n })\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createExport ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"export\"]}\n */\n const exportKey = (name, password) =>\n keychain.exportKey(name, password)\n\n return withTimeoutOption(exportKey)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\nconst DEFAULT_KEY_TYPE = 'Ed25519'\nconst DEFAULT_KEY_SIZE = 2048\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createGen ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"gen\"]}\n */\n const gen = (name, options = { type: DEFAULT_KEY_TYPE, size: DEFAULT_KEY_SIZE }) => {\n return keychain.createKey(name, options.type || DEFAULT_KEY_TYPE, options.size || DEFAULT_KEY_SIZE)\n }\n\n return withTimeoutOption(gen)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createImport ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"import\"]}\n */\n const importKey = (name, pem, password) => {\n return keychain.importKey(name, pem, password)\n }\n\n return withTimeoutOption(importKey)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createInfo ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"info\"]}\n */\n const info = (name) => keychain.findKeyByName(name)\n\n return withTimeoutOption(info)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createList ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"list\"]}\n */\n const list = () => keychain.listKeys()\n\n return withTimeoutOption(list)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createRename ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"rename\"]}\n */\n const rename = async (oldName, newName) => {\n const key = await keychain.renameKey(oldName, newName)\n\n return {\n was: oldName,\n now: key.name,\n id: key.id,\n overwrite: false\n }\n }\n\n return withTimeoutOption(rename)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('@libp2p/interface-keychain').KeyChain} config.keychain\n */\nexport function createRm ({ keychain }) {\n /**\n * @type {import('ipfs-core-types/src/key').API<{}>[\"rm\"]}\n */\n const rm = (name) => keychain.removeKey(name)\n\n return withTimeoutOption(rm)\n}\n", "import { createExport } from './export.js'\nimport { createGen } from './gen.js'\nimport { createImport } from './import.js'\nimport { createInfo } from './info.js'\nimport { createList } from './list.js'\nimport { createRename } from './rename.js'\nimport { createRm } from './rm.js'\n\n/**\n * @typedef {import('@libp2p/interface-keychain').KeyChain} Keychain\n */\n\nexport class KeyAPI {\n /**\n * @param {object} config\n * @param {Keychain} config.keychain\n */\n constructor ({ keychain }) {\n this.gen = createGen({ keychain })\n this.list = createList({ keychain })\n this.rm = createRm({ keychain })\n this.rename = createRename({ keychain })\n this.export = createExport({ keychain })\n this.import = createImport({ keychain })\n this.info = createInfo({ keychain })\n }\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createGet ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"get\"]}\n */\n async function get (cid, options = {}) { // eslint-disable-line require-await\n if (options.preload !== false) {\n preload(cid)\n }\n\n const block = await repo.blocks.get(cid, options)\n\n return dagPB.decode(block)\n }\n\n return withTimeoutOption(get)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from './get.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createData ({ repo, preload }) {\n const get = createGet({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"data\"]}\n */\n async function data (multihash, options = {}) {\n const node = await get(multihash, options)\n return node.Data || new Uint8Array(0)\n }\n\n return withTimeoutOption(data)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport * as dagCBOR from '@ipld/dag-cbor'\nimport * as dagJSON from '@ipld/dag-json'\nimport * as raw from 'multiformats/codecs/raw'\nimport { CID } from 'multiformats/cid'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('@ipld/dag-pb').PBLink} DAGLink\n */\n\n/**\n * @param {any} node\n * @param {DAGLink[]} [links]\n * @returns {DAGLink[]}\n */\nfunction findLinks (node, links = []) {\n for (const key in node) {\n const val = node[key]\n\n if (key === '/' && Object.keys(node).length === 1) {\n try {\n links.push({\n Name: '',\n Tsize: 0,\n Hash: CID.parse(val)\n })\n continue\n } catch (/** @type {any} */ _) {\n // not a CID\n }\n }\n\n const cid = CID.asCID(val)\n\n if (cid) {\n links.push({\n Name: '',\n Tsize: 0,\n Hash: cid\n })\n continue\n }\n\n if (Array.isArray(val)) {\n findLinks(val, links)\n }\n\n if (val && typeof val === 'object') {\n findLinks(val, links)\n }\n }\n\n return links\n}\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n */\nexport function createLinks ({ repo, codecs }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"links\"]}\n */\n async function links (cid, options = {}) {\n const codec = await codecs.getCodec(cid.code)\n const block = await repo.blocks.get(cid, options)\n const node = codec.decode(block)\n\n switch (cid.code) {\n case raw.code:\n return []\n case dagPB.code:\n return node.Links\n case dagCBOR.code:\n case dagJSON.code:\n return findLinks(node)\n default:\n throw new Error(`Cannot resolve links from codec ${cid.code}`)\n }\n }\n\n return withTimeoutOption(links)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createNew ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"new\"]}\n */\n async function _new (options = {}) {\n let data\n\n if (options.template) {\n if (options.template === 'unixfs-dir') {\n data = (new UnixFS({ type: 'directory' })).marshal()\n } else {\n throw new Error('unknown template')\n }\n }\n\n const buf = dagPB.encode({\n Data: data,\n Links: []\n })\n const hash = await sha256.digest(buf)\n const cid = CID.createV0(hash)\n\n await repo.blocks.put(cid, buf, {\n signal: options.signal\n })\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n return cid\n }\n\n return withTimeoutOption(_new)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createPut ({ repo, preload }) {\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"put\"]}\n */\n async function put (obj, options = {}) {\n const release = await repo.gcLock.readLock()\n\n try {\n const buf = dagPB.encode(obj)\n const hash = await sha256.digest(buf)\n const cid = CID.createV1(dagPB.code, hash)\n\n await repo.blocks.put(cid, buf, {\n signal: options.signal\n })\n\n if (options.preload !== false) {\n preload(cid)\n }\n\n if (options.pin) {\n await repo.pins.pinRecursively(cid, {\n signal: options.signal\n })\n }\n\n return cid\n } finally {\n release()\n }\n }\n\n return withTimeoutOption(put)\n}\n", "import * as dagPB from '@ipld/dag-pb'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from './get.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').Preload} config.preload\n */\nexport function createStat ({ repo, preload }) {\n const get = createGet({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object').API<{}>[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n const node = await get(cid, options)\n const serialized = dagPB.encode(node)\n const blockSize = serialized.length\n const linkLength = node.Links.reduce((a, l) => a + (l.Tsize || 0), 0)\n\n return {\n Hash: cid,\n NumLinks: node.Links.length,\n BlockSize: blockSize,\n LinksSize: blockSize - (node.Data || []).length,\n DataSize: (node.Data || []).length,\n CumulativeSize: blockSize + linkLength\n }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createAddLink ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"addLink\"]}\n */\n async function addLink (cid, link, options = {}) {\n const node = await get(cid, options)\n\n return put({\n ...node,\n Links: node.Links.concat([link])\n }, options)\n }\n\n return withTimeoutOption(addLink)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createAppendData ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"appendData\"]}\n */\n async function appendData (cid, data, options = {}) {\n const node = await get(cid, options)\n const newData = uint8ArrayConcat([node.Data || [], data])\n\n return put({\n ...node,\n Data: newData\n }, options)\n }\n\n return withTimeoutOption(appendData)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createRmLink ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"rmLink\"]}\n */\n async function rmLink (cid, link, options = {}) {\n const node = await get(cid, options)\n const name = (typeof link === 'string' ? link : link.Name) || ''\n\n node.Links = node.Links.filter(l => l.Name !== name)\n\n return put(node, options)\n }\n\n return withTimeoutOption(rmLink)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { createGet } from '../get.js'\nimport { createPut } from '../put.js'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../../types').Preload} config.preload\n */\nexport function createSetData ({ repo, preload }) {\n const get = createGet({ repo, preload })\n const put = createPut({ repo, preload })\n\n /**\n * @type {import('ipfs-core-types/src/object/patch').API<{}>[\"setData\"]}\n */\n async function setData (cid, data, options = {}) {\n const node = await get(cid, options)\n\n return put({\n ...node,\n Data: data\n }, options)\n }\n\n return withTimeoutOption(setData)\n}\n", "import { createAddLink } from './add-link.js'\nimport { createAppendData } from './append-data.js'\nimport { createRmLink } from './rm-link.js'\nimport { createSetData } from './set-data.js'\n\n/**\n * @typedef {import('../../../types').Preload} Preload\n */\n\nexport class ObjectPatchAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {Preload} config.preload\n */\n constructor ({ repo, preload }) {\n this.addLink = createAddLink({ repo, preload })\n this.appendData = createAppendData({ repo, preload })\n this.rmLink = createRmLink({ repo, preload })\n this.setData = createSetData({ repo, preload })\n }\n}\n", "import { createData } from './data.js'\nimport { createGet } from './get.js'\nimport { createLinks } from './links.js'\nimport { createNew } from './new.js'\nimport { createPut } from './put.js'\nimport { createStat } from './stat.js'\nimport { ObjectPatchAPI } from './patch/index.js'\n\n/**\n * @typedef {import('../../types').Preload} Preload\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\nexport class ObjectAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} config.codecs\n * @param {Preload} config.preload\n */\n constructor ({ repo, codecs, preload }) {\n this.data = createData({ repo, preload })\n this.get = createGet({ repo, preload })\n this.links = createLinks({ repo, codecs })\n this.new = createNew({ repo, preload })\n this.put = createPut({ repo, preload })\n this.stat = createStat({ repo, preload })\n this.patch = new ObjectPatchAPI({ repo, preload })\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { loadMfsRoot } from '../files/utils/with-mfs-root.js'\n\nconst log = logger('ipfs:repo:gc')\n\n/**\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n * @typedef {import('ipfs-core-types/src/refs').API} RefsAPI\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n */\n\n/**\n * Perform mark and sweep garbage collection\n *\n * @param {object} config\n * @param {IPFSRepo} config.repo\n * @param {Multihashes} config.hashers\n */\nexport function createGc ({ repo, hashers }) {\n /**\n * @type {import('ipfs-core-types/src/repo').API<{}>[\"gc\"]}\n */\n async function * gc (options = {}) {\n const start = Date.now()\n let mfsRootCid\n\n try {\n mfsRootCid = await loadMfsRoot({\n repo,\n hashers\n }, options)\n\n // temporarily pin mfs root\n await repo.pins.pinRecursively(mfsRootCid)\n\n yield * repo.gc()\n } finally {\n // gc complete, unpin mfs root\n if (mfsRootCid) {\n await repo.pins.unpin(mfsRootCid)\n }\n }\n\n log(`Complete (${Date.now() - start}ms)`)\n }\n\n return withTimeoutOption(gc)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createStat ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/repo').API<{}>[\"stat\"]}\n */\n async function stat (options = {}) {\n const stats = await repo.stat()\n\n return {\n numObjects: BigInt(stats.numObjects.toString()),\n repoSize: BigInt(stats.repoSize.toString()),\n repoPath: stats.repoPath,\n version: `${stats.version}`,\n storageMax: BigInt(stats.storageMax.toString())\n }\n }\n\n return withTimeoutOption(stat)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { repoVersion } from 'ipfs-repo/constants'\n\n/**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n */\nexport function createVersion ({ repo }) {\n /**\n * @type {import('ipfs-core-types/src/repo').API<{}>[\"version\"]}\n */\n async function version (options = {}) {\n try {\n // @ts-expect-error - not a public API\n await repo._checkInitialized(options)\n } catch (/** @type {any} */ err) {\n // TODO: (dryajov) This is really hacky, there must be a better way\n const match = [\n /Key not found in database \\[\\/version\\]/,\n /ENOENT/,\n /repo is not initialized yet/\n ].some((m) => {\n return m.test(err.message)\n })\n if (match) {\n // this repo has not been initialized\n return repoVersion\n }\n throw err\n }\n\n return repo.version.get()\n }\n\n return withTimeoutOption(version)\n}\n", "import { createGc } from './gc.js'\nimport { createStat } from './stat.js'\nimport { createVersion } from './version.js'\n\n/**\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('ipfs-core-utils/multihashes').Multihashes} Multihashes\n */\n\nexport class RepoAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {Multihashes} config.hashers\n */\n constructor ({ repo, hashers }) {\n this.gc = createGc({ repo, hashers })\n this.stat = createStat({ repo })\n this.version = createVersion({ repo })\n\n /**\n * @param {string} addr\n */\n this.setApiAddr = (addr) => repo.apiAddr.set(addr)\n }\n}\n", "import parseDuration from 'parse-duration'\nimport errCode from 'err-code'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('ipfs-core-types/src/stats').BWOptions} BWOptions\n * @typedef {import('ipfs-core-types/src/stats').BWResult} BandwidthInfo\n * @typedef {import('libp2p').Libp2p} libp2p\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @param {libp2p} libp2p\n * @param {BWOptions} opts\n * @returns {BandwidthInfo}\n */\nfunction getBandwidthStats (libp2p, opts) {\n/*\n let stats\n\n if (!libp2p.metrics) {\n stats = undefined\n } else if (opts.peer) {\n stats = libp2p.metrics.forPeer(opts.peer)\n } else if (opts.proto) {\n stats = libp2p.metrics.forProtocol(opts.proto)\n } else {\n stats = libp2p.metrics.getGlobal()\n }\n*/\n // if (!stats) {\n return {\n totalIn: BigInt(0),\n totalOut: BigInt(0),\n rateIn: 0.0,\n rateOut: 0.0\n }\n // }\n/*\n const movingAverages = stats.getMovingAverages()\n const snapshot = stats.getSnapshot()\n\n return {\n totalIn: snapshot.dataReceived,\n totalOut: snapshot.dataSent,\n rateIn: movingAverages.dataReceived[60000].movingAverage / 60,\n rateOut: movingAverages.dataSent[60000].movingAverage / 60\n }\n*/\n}\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createBw ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/stats').API<{}>[\"bw\"]}\n */\n const bw = async function * (options = {}) {\n const { libp2p } = await network.use(options)\n\n if (!options.poll) {\n yield getBandwidthStats(libp2p, options)\n return\n }\n\n const interval = options.interval || 1000\n let ms = -1\n try {\n ms = typeof interval === 'string' ? parseDuration(interval) || -1 : interval\n if (!ms || ms < 0) throw new Error('invalid duration')\n } catch (/** @type {any} */ err) {\n throw errCode(err, 'ERR_INVALID_POLL_INTERVAL')\n }\n\n let timeoutId\n try {\n while (true) {\n yield getBandwidthStats(libp2p, options)\n // eslint-disable-next-line no-loop-func\n await new Promise(resolve => { timeoutId = setTimeout(resolve, ms) })\n }\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n return withTimeoutOption(bw)\n}\n", "import { createBw } from './bw.js'\nimport { createStat as createRepo } from '../repo/stat.js'\nimport { createStat as createBitswap } from '../bitswap/stat.js'\n\nexport class StatsAPI {\n /**\n * @param {object} config\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {import('../../types').NetworkService} config.network\n */\n constructor ({ repo, network }) {\n this.repo = createRepo({ repo })\n this.bw = createBw({ network })\n this.bitswap = createBitswap({ network })\n }\n}\n", "var objectSafeGet = get;\n\n/*\n const obj = {a: {aa: {aaa: 2}}, b: 4};\n\n get(obj, 'a.aa.aaa'); // 2\n get(obj, ['a', 'aa', 'aaa']); // 2\n\n get(obj, 'b.bb.bbb'); // undefined\n get(obj, ['b', 'bb', 'bbb']); // undefined\n\n get(obj.a, 'aa.aaa'); // 2\n get(obj.a, ['aa', 'aaa']); // 2\n\n get(obj.b, 'bb.bbb'); // undefined\n get(obj.b, ['bb', 'bbb']); // undefined\n\n get(obj.b, 'bb.bbb', 42); // 42\n get(obj.b, ['bb', 'bbb'], 42); // 42\n\n get(null, 'a'); // undefined\n get(undefined, ['a']); // undefined\n\n get(null, 'a', 42); // 42\n get(undefined, ['a'], 42); // 42\n\n const obj = {a: {}};\n const sym = Symbol();\n obj.a[sym] = 4;\n get(obj.a, sym); // 4\n*/\n\nfunction get(obj, propsArg, defaultValue) {\n if (!obj) {\n return defaultValue;\n }\n var props, prop;\n if (Array.isArray(propsArg)) {\n props = propsArg.slice(0);\n }\n if (typeof propsArg == 'string') {\n props = propsArg.split('.');\n }\n if (typeof propsArg == 'symbol') {\n props = [propsArg];\n }\n if (!Array.isArray(props)) {\n throw new Error('props arg must be an array, a string or a symbol');\n }\n while (props.length) {\n prop = props.shift();\n if (!obj) {\n return defaultValue;\n }\n obj = obj[prop];\n if (obj === undefined) {\n return defaultValue;\n }\n }\n return obj;\n}\n\nexport {objectSafeGet as default};\n", "import _get from 'just-safe-get'\nimport debug from 'debug'\nimport errCode from 'err-code'\nimport * as migrator from 'ipfs-repo-migrations'\nimport bytes from 'bytes'\nimport merge from 'merge-options'\nimport * as CONSTANTS from './constants.js'\nimport { version } from './version.js'\nimport { config } from './config.js'\nimport { spec } from './spec.js'\nimport { apiAddr } from './api-addr.js'\nimport { createIdStore } from './idstore.js'\nimport defaultOptions from './default-options.js'\nimport defaultDatastore from './default-datastore.js'\nimport * as ERRORS from './errors.js'\nimport { PinManager } from './pin-manager.js'\nimport { createPinnedBlockstore } from './pinned-blockstore.js'\n// @ts-ignore - no types\nimport mortice from 'mortice'\nimport { gc } from './gc.js'\n\nconst log = debug('ipfs:repo')\n\nconst noLimit = Number.MAX_SAFE_INTEGER\nconst AUTO_MIGRATE_CONFIG_KEY = 'repoAutoMigrate'\n\n/**\n * @typedef {import('./types').Options} Options\n * @typedef {import('./types').RepoLock} RepoLock\n * @typedef {import('./types').LockCloser} LockCloser\n * @typedef {import('./types').GCLock} GCLock\n * @typedef {import('./types').Stat} Stat\n * @typedef {import('./types').Config} Config\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').Backends} Backends\n * @typedef {import('./types').IPFSRepo} IPFSRepo\n */\n\n/**\n * IPFSRepo implements all required functionality to read and write to an ipfs repo.\n */\nclass Repo {\n /**\n * @param {string} path - Where this repo is stored\n * @param {import('./types').loadCodec} loadCodec - a function that will load multiformat block codecs\n * @param {Backends} backends - backends used by this repo\n * @param {Partial} [options] - Configuration\n */\n constructor (path, loadCodec, backends, options) {\n if (typeof path !== 'string') {\n throw new Error('missing repo path')\n }\n\n if (typeof loadCodec !== 'function') {\n throw new Error('missing codec loader')\n }\n\n /** @type {Options} */\n this.options = merge(defaultOptions, options)\n this.closed = true\n this.path = path\n this.root = backends.root\n this.datastore = backends.datastore\n this.keys = backends.keys\n\n const blockstore = backends.blocks\n const pinstore = backends.pins\n\n this.pins = new PinManager({ pinstore, blockstore, loadCodec })\n\n // this blockstore will not delete blocks that have been pinned\n const pinnedBlockstore = createPinnedBlockstore(this.pins, blockstore)\n\n // this blockstore will extract blocks from multihashes with the identity codec\n this.blocks = createIdStore(pinnedBlockstore)\n\n this.version = version(this.root)\n this.config = config(this.root)\n this.spec = spec(this.root)\n this.apiAddr = apiAddr(this.root)\n\n /** @type {GCLock} */\n this.gcLock = mortice({\n name: path,\n singleProcess: this.options.repoOwner !== false\n })\n\n this.gc = gc({ gcLock: this.gcLock, pins: this.pins, blockstore: this.blocks, root: this.root, loadCodec })\n }\n\n /**\n * Initialize a new repo.\n *\n * @param {import('./types').Config} config - config to write into `config`.\n * @returns {Promise}\n */\n async init (config) {\n log('initializing at: %s', this.path)\n await this._openRoot()\n await this.config.replace(buildConfig(config))\n await this.spec.set(buildDatastoreSpec(config))\n await this.version.set(CONSTANTS.repoVersion)\n }\n\n /**\n * Check if the repo is already initialized.\n *\n * @returns {Promise}\n */\n async isInitialized () {\n if (!this.closed) {\n // repo is open, must be initialized\n return true\n }\n\n try {\n // have to open the root datastore in the browser before\n // we can check whether it's been initialized\n await this._openRoot()\n await this._checkInitialized()\n await this.root.close()\n\n return true\n } catch (/** @type {any} */ err) {\n // FIXME: do not use exceptions for flow control\n return false\n }\n }\n\n /**\n * Open the repo. If the repo is already open an error will be thrown.\n * If the repo is not initialized it will throw an error.\n *\n * @returns {Promise}\n */\n async open () {\n if (!this.closed) {\n throw errCode(new Error('repo is already open'), ERRORS.ERR_REPO_ALREADY_OPEN)\n }\n log('opening at: %s', this.path)\n\n // check if the repo is already initialized\n try {\n await this._openRoot()\n await this._checkInitialized()\n\n this._lockfile = await this._openLock()\n log('acquired repo.lock')\n\n const isCompatible = await this.version.check(CONSTANTS.repoVersion)\n\n if (!isCompatible) {\n if (await this._isAutoMigrationEnabled()) {\n await this._migrate(CONSTANTS.repoVersion, {\n root: this.root,\n datastore: this.datastore,\n pins: this.pins.pinstore,\n blocks: this.pins.blockstore,\n keys: this.keys\n })\n } else {\n throw new ERRORS.InvalidRepoVersionError('Incompatible repo versions. Automatic migrations disabled. Please migrate the repo manually.')\n }\n }\n\n log('creating datastore')\n await this.datastore.open()\n\n log('creating blocks')\n await this.blocks.open()\n\n log('creating keystore')\n await this.keys.open()\n\n log('creating pins')\n await this.pins.pinstore.open()\n\n this.closed = false\n log('all opened')\n } catch (/** @type {any} */ err) {\n if (this._lockfile) {\n try {\n await this._closeLock()\n this._lockfile = null\n } catch (/** @type {any} */ err2) {\n log('error removing lock', err2)\n }\n }\n\n throw err\n }\n }\n\n /**\n * Opens the root backend, catching and ignoring an 'Already open' error\n *\n * @private\n */\n async _openRoot () {\n try {\n await this.root.open()\n } catch (/** @type {any} */ err) {\n if (err.message !== 'Already open') {\n throw err\n }\n }\n }\n\n /**\n * Creates a lock on the repo if a locker is specified. The lockfile object will\n * be returned in the callback if one has been created.\n *\n * @private\n * @returns {Promise}\n */\n async _openLock () {\n const lockfile = await this.options.repoLock.lock(this.path)\n\n if (typeof lockfile.close !== 'function') {\n throw errCode(new Error('Locks must have a close method'), 'ERR_NO_CLOSE_FUNCTION')\n }\n\n return lockfile\n }\n\n /**\n * Closes the lock on the repo\n *\n * @private\n */\n _closeLock () {\n return this._lockfile && this._lockfile.close()\n }\n\n /**\n * Check if the repo is already initialized.\n *\n * @private\n */\n async _checkInitialized () {\n log('init check')\n let config\n try {\n [config] = await Promise.all([\n this.config.exists(),\n this.spec.exists(),\n this.version.exists()\n ])\n } catch (/** @type {any} */ err) {\n if (err.code === 'ERR_NOT_FOUND') {\n throw errCode(new Error('repo is not initialized yet'), ERRORS.ERR_REPO_NOT_INITIALIZED, {\n path: this.path\n })\n }\n\n throw err\n }\n\n if (!config) {\n throw errCode(new Error('repo is not initialized yet'), ERRORS.ERR_REPO_NOT_INITIALIZED, {\n path: this.path\n })\n }\n }\n\n /**\n * Close the repo and cleanup.\n *\n * @returns {Promise}\n */\n async close () {\n if (this.closed) {\n throw errCode(new Error('repo is already closed'), ERRORS.ERR_REPO_ALREADY_CLOSED)\n }\n log('closing at: %s', this.path)\n\n try {\n // Delete api, ignoring irrelevant errors\n await this.apiAddr.delete()\n } catch (/** @type {any} */ err) {\n if (err.code !== ERRORS.ERR_REPO_NOT_INITIALIZED && !err.message.startsWith('ENOENT')) {\n throw err\n }\n }\n\n await Promise.all([\n this.root,\n this.blocks,\n this.keys,\n this.datastore,\n this.pins.pinstore\n ].map((store) => store && store.close()))\n\n log('unlocking')\n this.closed = true\n await this._closeLock()\n }\n\n /**\n * Check if a repo exists.\n *\n * @returns {Promise}\n */\n exists () {\n return this.version.exists()\n }\n\n /**\n * Get repo status.\n *\n * @returns {Promise}\n */\n async stat () {\n if (this.datastore && this.keys) {\n const [storageMax, blocks, version, datastore, keys] = await Promise.all([\n this._storageMaxStat(),\n this._blockStat(),\n this.version.get(),\n getSize(this.datastore),\n getSize(this.keys)\n ])\n const size = blocks.size + datastore + keys\n\n return {\n repoPath: this.path,\n storageMax,\n version: version,\n numObjects: blocks.count,\n repoSize: size\n }\n }\n throw errCode(new Error('repo is not initialized yet'), ERRORS.ERR_REPO_NOT_INITIALIZED, {\n path: this.path\n })\n }\n\n /**\n * @private\n */\n async _isAutoMigrationEnabled () {\n if (this.options.autoMigrate !== undefined) {\n return this.options.autoMigrate\n }\n\n // TODO we need to figure out the priority here, between repo options and config.\n let autoMigrateConfig\n try {\n autoMigrateConfig = await this.config.get(AUTO_MIGRATE_CONFIG_KEY)\n } catch (/** @type {any} */ e) {\n if (e.code === ERRORS.NotFoundError.code) {\n autoMigrateConfig = true // Config's default value is True\n } else {\n throw e\n }\n }\n\n return autoMigrateConfig\n }\n\n /**\n * Internal migration\n *\n * @private\n * @param {number} toVersion\n * @param {Backends} backends\n */\n async _migrate (toVersion, backends) {\n const currentRepoVersion = await this.version.get()\n\n if (currentRepoVersion > toVersion) {\n log(`reverting to version ${toVersion}`)\n return migrator.revert(this.path, backends, this.options, toVersion, {\n ignoreLock: true,\n onProgress: this.options.onMigrationProgress\n })\n } else {\n log(`migrating to version ${toVersion}`)\n return migrator.migrate(this.path, backends, this.options, toVersion, {\n ignoreLock: true,\n onProgress: this.options.onMigrationProgress\n })\n }\n }\n\n /**\n * @private\n */\n async _storageMaxStat () {\n try {\n const max = /** @type {number} */(await this.config.get('Datastore.StorageMax'))\n return BigInt(bytes(max))\n } catch (/** @type {any} */ err) {\n return BigInt(noLimit)\n }\n }\n\n /**\n * @private\n */\n async _blockStat () {\n let count = BigInt(0)\n let size = BigInt(0)\n\n if (this.blocks) {\n for await (const { key, value } of this.blocks.query({})) {\n count += BigInt(1)\n size += BigInt(value.byteLength)\n size += BigInt(key.bytes.byteLength)\n }\n }\n\n return { count, size }\n }\n}\n\n/**\n * @param {Datastore} datastore\n */\nasync function getSize (datastore) {\n let sum = BigInt(0)\n for await (const block of datastore.query({})) {\n sum += BigInt(block.value.byteLength)\n sum += BigInt(block.key.uint8Array().byteLength)\n }\n return sum\n}\n\n/**\n * @param {string} path - Where this repo is stored\n * @param {import('./types').loadCodec} loadCodec - a function that will load multiformat block codecs\n * @param {import('./types').Backends} backends - backends used by this repo\n * @param {Partial} [options] - Configuration\n * @returns {import('./types').IPFSRepo}\n */\nexport function createRepo (path, loadCodec, backends, options) {\n return new Repo(path, loadCodec, backends, options)\n}\n\n/**\n * @param {import('./types').Config} _config\n */\nfunction buildConfig (_config) {\n _config.Datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore'))\n\n return _config\n}\n\n/**\n * @param {import('./types').Config} _config\n */\nfunction buildDatastoreSpec (_config) {\n /** @type { {type: string, mounts: Array<{mountpoint: string, type: string, prefix: string, child: {type: string, path: 'string', sync: boolean, shardFunc: string}}>}} */\n const spec = {\n ...defaultDatastore.Spec,\n ..._get(_config, 'Datastore.Spec')\n }\n\n return {\n type: spec.type,\n mounts: spec.mounts.map((mounting) => ({\n mountpoint: mounting.mountpoint,\n type: mounting.child.type,\n path: mounting.child.path,\n shardFunc: mounting.child.shardFunc\n }))\n }\n}\n", "\nimport { CID } from 'multiformats/cid'\nimport { Key } from 'interface-datastore/key'\nimport debug from 'debug'\nimport length from 'it-length'\nimport { base32 } from 'multiformats/bases/base32'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as mhd from 'multiformats/hashes/digest'\n\nconst log = debug('ipfs:repo:migrator:migration-8')\n\n/**\n * @typedef {import('../../types').Migration} Migration\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\n/**\n * @param {*} blockstore\n * @returns {Datastore}\n */\nfunction unwrap (blockstore) {\n if (blockstore.child) {\n return unwrap(blockstore.child)\n }\n\n return blockstore\n}\n\n/**\n * @param {Key} key\n */\nfunction keyToMultihash (key) {\n try {\n const buf = base32.decode(`b${key.toString().toLowerCase().slice(1)}`)\n\n // Extract multihash from CID\n const multihash = CID.decode(buf).multihash.bytes\n\n // Encode and slice off multibase codec\n // Should be uppercase for interop with go\n const multihashStr = base32.encode(multihash).slice(1).toUpperCase()\n\n return new Key(`/${multihashStr}`, false)\n } catch (/** @type {any} */ err) {\n return key\n }\n}\n\n/**\n * @param {Key} key\n */\nfunction keyToCid (key) {\n try {\n const buf = base32.decode(`b${key.toString().toLowerCase().slice(1)}`)\n const digest = mhd.decode(buf)\n\n // CID to Key\n const multihash = base32.encode(CID.createV1(raw.code, digest).bytes).slice(1)\n\n return new Key(`/${multihash.toUpperCase()}`, false)\n } catch {\n return key\n }\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {(percent: number, message: string) => void} onProgress\n * @param {(key: Key) => Key} keyFunction\n */\nasync function process (backends, onProgress, keyFunction) {\n const blockstore = backends.blocks\n await blockstore.open()\n\n const unwrapped = unwrap(blockstore)\n\n const blockCount = await length(unwrapped.queryKeys({\n filters: [(key) => {\n const newKey = keyFunction(key)\n\n return newKey.toString() !== key.toString()\n }]\n }))\n\n try {\n let counter = 0\n\n for await (const block of unwrapped.query({})) {\n const newKey = keyFunction(block.key)\n\n // If the Key is base32 CIDv0 then there's nothing to do\n if (newKey.toString() !== block.key.toString()) {\n counter += 1\n log(`Migrating Block from ${block.key} to ${newKey}`, await unwrapped.has(block.key))\n\n await unwrapped.delete(block.key)\n await unwrapped.put(newKey, block.value)\n\n onProgress((counter / blockCount) * 100, `Migrated Block from ${block.key} to ${newKey}`)\n }\n }\n } finally {\n await blockstore.close()\n }\n}\n\n/** @type {Migration} */\nexport const migration = {\n version: 8,\n description: 'Transforms key names into base32 encoding and converts Block store to use bare multihashes encoded as base32',\n migrate: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keyToMultihash)\n },\n revert: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keyToCid)\n }\n}\n", "/**\n * Consumes the passed iterator and returns the number of items it contained\n */\nexport default async function length (iterator: AsyncIterable | Iterable): Promise {\n let count = 0\n\n for await (const _ of iterator) { // eslint-disable-line no-unused-vars,@typescript-eslint/no-unused-vars\n count++\n }\n\n return count\n}\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const ipfs = $root.ipfs = (() => {\n\n /**\n * Namespace ipfs.\n * @exports ipfs\n * @namespace\n */\n const ipfs = {};\n\n ipfs.pin = (function() {\n\n /**\n * Namespace pin.\n * @memberof ipfs\n * @namespace\n */\n const pin = {};\n\n pin.Set = (function() {\n\n /**\n * Properties of a Set.\n * @memberof ipfs.pin\n * @interface ISet\n * @property {number|null} [version] Set version\n * @property {number|null} [fanout] Set fanout\n * @property {number|null} [seed] Set seed\n */\n\n /**\n * Constructs a new Set.\n * @memberof ipfs.pin\n * @classdesc Represents a Set.\n * @implements ISet\n * @constructor\n * @param {ipfs.pin.ISet=} [p] Properties to set\n */\n function Set(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Set version.\n * @member {number} version\n * @memberof ipfs.pin.Set\n * @instance\n */\n Set.prototype.version = 0;\n\n /**\n * Set fanout.\n * @member {number} fanout\n * @memberof ipfs.pin.Set\n * @instance\n */\n Set.prototype.fanout = 0;\n\n /**\n * Set seed.\n * @member {number} seed\n * @memberof ipfs.pin.Set\n * @instance\n */\n Set.prototype.seed = 0;\n\n /**\n * Encodes the specified Set message. Does not implicitly {@link ipfs.pin.Set.verify|verify} messages.\n * @function encode\n * @memberof ipfs.pin.Set\n * @static\n * @param {ipfs.pin.ISet} m Set message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Set.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.version != null && Object.hasOwnProperty.call(m, \"version\"))\n w.uint32(8).uint32(m.version);\n if (m.fanout != null && Object.hasOwnProperty.call(m, \"fanout\"))\n w.uint32(16).uint32(m.fanout);\n if (m.seed != null && Object.hasOwnProperty.call(m, \"seed\"))\n w.uint32(29).fixed32(m.seed);\n return w;\n };\n\n /**\n * Decodes a Set message from the specified reader or buffer.\n * @function decode\n * @memberof ipfs.pin.Set\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {ipfs.pin.Set} Set\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Set.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.ipfs.pin.Set();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.version = r.uint32();\n break;\n case 2:\n m.fanout = r.uint32();\n break;\n case 3:\n m.seed = r.fixed32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Set message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof ipfs.pin.Set\n * @static\n * @param {Object.} d Plain object\n * @returns {ipfs.pin.Set} Set\n */\n Set.fromObject = function fromObject(d) {\n if (d instanceof $root.ipfs.pin.Set)\n return d;\n var m = new $root.ipfs.pin.Set();\n if (d.version != null) {\n m.version = d.version >>> 0;\n }\n if (d.fanout != null) {\n m.fanout = d.fanout >>> 0;\n }\n if (d.seed != null) {\n m.seed = d.seed >>> 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Set message. Also converts values to other types if specified.\n * @function toObject\n * @memberof ipfs.pin.Set\n * @static\n * @param {ipfs.pin.Set} m Set\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Set.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.version = 0;\n d.fanout = 0;\n d.seed = 0;\n }\n if (m.version != null && m.hasOwnProperty(\"version\")) {\n d.version = m.version;\n }\n if (m.fanout != null && m.hasOwnProperty(\"fanout\")) {\n d.fanout = m.fanout;\n }\n if (m.seed != null && m.hasOwnProperty(\"seed\")) {\n d.seed = m.seed;\n }\n return d;\n };\n\n /**\n * Converts this Set to JSON.\n * @function toJSON\n * @memberof ipfs.pin.Set\n * @instance\n * @returns {Object.} JSON object\n */\n Set.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Set;\n })();\n\n return pin;\n })();\n\n return ipfs;\n})();\n\nexport { $root as default };\n", "\nimport { CID } from 'multiformats/cid'\nimport { ipfs } from './pin.js'\n// @ts-ignore\nimport fnv1a from 'fnv1a'\nimport varint from 'varint'\nimport * as dagPb from '@ipld/dag-pb'\nimport { DEFAULT_FANOUT, MAX_ITEMS, EMPTY_KEY } from './utils.js'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { compare as uint8ArrayCompare } from 'uint8arrays/compare'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\nconst PinSet = ipfs.pin.Set\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('@ipld/dag-pb').PBNode} PBNode\n *\n * @typedef {object} Pin\n * @property {CID} key\n * @property {Uint8Array} [data]\n */\n\n/**\n * @param {PBNode} rootNode\n */\nfunction readHeader (rootNode) {\n // rootNode.data should be a buffer of the format:\n // < varint(headerLength) | header | itemData... >\n const rootData = rootNode.Data\n\n if (!rootData) {\n throw new Error('No data present')\n }\n\n const hdrLength = varint.decode(rootData)\n const vBytes = varint.decode.bytes ?? 0\n\n if (vBytes <= 0) {\n throw new Error('Invalid Set header length')\n }\n\n if (vBytes + hdrLength > rootData.length) {\n throw new Error('Impossibly large set header length')\n }\n\n const hdrSlice = rootData.slice(vBytes, hdrLength + vBytes)\n const header = PinSet.toObject(PinSet.decode(hdrSlice), {\n defaults: false,\n arrays: true,\n longs: Number,\n objects: false\n })\n\n if (header.version !== 1) {\n throw new Error(`Unsupported Set version: ${header.version}`)\n }\n\n if (header.fanout > rootNode.Links.length) {\n throw new Error('Impossibly large fanout')\n }\n\n return {\n header: header,\n data: rootData.slice(hdrLength + vBytes)\n }\n}\n\n/**\n * @param {number} seed\n * @param {CID} key\n */\nfunction hash (seed, key) {\n const buffer = new Uint8Array(4)\n const dataView = new DataView(buffer.buffer)\n dataView.setUint32(0, seed, true)\n const encodedKey = uint8ArrayFromString(key.toString())\n const data = uint8ArrayConcat([buffer, encodedKey], buffer.byteLength + encodedKey.byteLength)\n\n return fnv1a(uint8ArrayToString(data))\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {PBNode} node\n * @returns {AsyncGenerator}\n */\nasync function * walkItems (blockstore, node) {\n const pbh = readHeader(node)\n let idx = 0\n\n for (const link of node.Links) {\n if (idx < pbh.header.fanout) {\n // the first pbh.header.fanout links are fanout bins\n // if a fanout bin is not 'empty', dig into and walk its DAGLinks\n const linkHash = link.Hash\n\n if (!EMPTY_KEY.equals(linkHash)) {\n // walk the links of this fanout bin\n const buf = await blockstore.get(linkHash)\n const node = dagPb.decode(buf)\n\n yield * walkItems(blockstore, node)\n }\n } else {\n // otherwise, the link is a pin\n yield link.Hash\n }\n\n idx++\n }\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {PBNode} rootNode\n * @param {string} name\n */\nexport async function * loadSet (blockstore, rootNode, name) {\n const link = rootNode.Links.find(l => l.Name === name)\n\n if (!link) {\n throw new Error('No link found with name ' + name)\n }\n\n const buf = await blockstore.get(link.Hash)\n const node = dagPb.decode(buf)\n\n yield * walkItems(blockstore, node)\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {Pin[]} items\n */\nfunction storeItems (blockstore, items) {\n return storePins(items, 0)\n\n /**\n * @param {Pin[]} pins\n * @param {number} depth\n */\n async function storePins (pins, depth) {\n const pbHeader = PinSet.encode({\n version: 1,\n fanout: DEFAULT_FANOUT,\n seed: depth\n }).finish()\n\n const header = varint.encode(pbHeader.length)\n const headerBuf = uint8ArrayConcat([header, pbHeader])\n const fanoutLinks = []\n\n for (let i = 0; i < DEFAULT_FANOUT; i++) {\n fanoutLinks.push({\n Name: '',\n Tsize: 1,\n Hash: EMPTY_KEY\n })\n }\n\n if (pins.length <= MAX_ITEMS) {\n const nodes = pins\n .map(item => {\n return ({\n link: {\n Name: '',\n Tsize: 1,\n Hash: item.key\n },\n data: item.data || new Uint8Array()\n })\n })\n // sorting makes any ordering of `pins` produce the same DAGNode\n .sort((a, b) => {\n return uint8ArrayCompare(a.link.Hash.bytes, b.link.Hash.bytes)\n })\n\n const rootLinks = fanoutLinks.concat(nodes.map(item => item.link))\n const rootData = uint8ArrayConcat([headerBuf, ...nodes.map(item => item.data)])\n\n return {\n Data: rootData,\n Links: rootLinks\n }\n } else {\n // If the array of pins is > MAX_ITEMS, we:\n // - distribute the pins among `DEFAULT_FANOUT` bins\n // - create a DAGNode for each bin\n // - add each pin as a DAGLink to that bin\n // - create a root DAGNode\n // - add each bin as a DAGLink\n // - send that root DAGNode via callback\n // (using go-ipfs' \"wasteful but simple\" approach for consistency)\n // https://github.com/ipfs/go-ipfs/blob/master/pin/set.go#L57\n\n /** @type {Pin[][]} */\n const bins = pins.reduce((bins, pin) => {\n const n = hash(depth, pin.key) % DEFAULT_FANOUT\n // @ts-ignore\n bins[n] = n in bins ? bins[n].concat([pin]) : [pin]\n return bins\n }, [])\n\n let idx = 0\n for (const bin of bins) {\n const child = await storePins(bin, depth + 1)\n\n await storeChild(child, idx)\n\n idx++\n }\n\n return {\n Data: headerBuf,\n Links: fanoutLinks\n }\n }\n\n /**\n * @param {PBNode} child\n * @param {number} binIdx\n */\n async function storeChild (child, binIdx) {\n const buf = dagPb.encode(child)\n const digest = await sha256.digest(buf)\n const cid = CID.createV0(digest)\n\n await blockstore.put(cid, buf)\n\n const size = child.Links.reduce((acc, curr) => acc + (curr.Tsize || 0), 0) + buf.length\n\n fanoutLinks[binIdx] = {\n Name: '',\n Tsize: size,\n Hash: cid\n }\n }\n }\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {string} type\n * @param {CID[]} cids\n */\nexport async function storeSet (blockstore, type, cids) {\n const rootNode = await storeItems(blockstore, cids.map(cid => {\n return {\n key: cid\n }\n }))\n const buf = dagPb.encode(rootNode)\n const digest = await sha256.digest(buf)\n const cid = CID.createV0(digest)\n\n await blockstore.put(cid, buf)\n\n const size = rootNode.Links.reduce((acc, curr) => acc + curr.Tsize, 0) + buf.length\n\n return {\n Name: type,\n Tsize: size,\n Hash: cid\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { CID } from 'multiformats/cid'\n\nexport const PIN_DS_KEY = new Key('/local/pins')\nexport const DEFAULT_FANOUT = 256\nexport const MAX_ITEMS = 8192\nexport const EMPTY_KEY = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n\nexport const PinTypes = {\n direct: 'direct',\n recursive: 'recursive'\n}\n\n/**\n * @param {import('multiformats').CID} cid\n */\nexport function cidToKey (cid) {\n return new Key(`/${base32.encode(cid.multihash.bytes).toUpperCase().substring(1)}`)\n}\n", "/**\n * Can be used with Array.sort to sort and array with Uint8Array entries\n */\nexport function compare (a: Uint8Array, b: Uint8Array): number {\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] < b[i]) {\n return -1\n }\n\n if (a[i] > b[i]) {\n return 1\n }\n }\n\n if (a.byteLength > b.byteLength) {\n return 1\n }\n\n if (a.byteLength < b.byteLength) {\n return -1\n }\n\n return 0\n}\n", "\nimport { CID } from 'multiformats/cid'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as cbor from 'cborg'\nimport * as pinset from './pin-set.js'\nimport { cidToKey, PIN_DS_KEY, PinTypes } from './utils.js'\nimport length from 'it-length'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport * as mhd from 'multiformats/hashes/digest'\nimport { base32 } from 'multiformats/bases/base32'\n\n/**\n * @typedef {import('../../types').Migration} Migration\n * @typedef {import('../../types').MigrationProgressCallback} MigrationProgressCallback\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').Version} CIDVersion\n */\n\n/**\n * @param {Blockstore} blockstore\n * @param {Datastore} datastore\n * @param {Datastore} pinstore\n * @param {MigrationProgressCallback} onProgress\n */\nasync function pinsToDatastore (blockstore, datastore, pinstore, onProgress) {\n if (!await datastore.has(PIN_DS_KEY)) {\n return\n }\n\n const mh = await datastore.get(PIN_DS_KEY)\n const cid = CID.decode(mh)\n const pinRootBuf = await blockstore.get(cid)\n const pinRoot = dagPb.decode(pinRootBuf)\n let counter = 0\n const pinCount = (await length(pinset.loadSet(blockstore, pinRoot, PinTypes.recursive))) + (await length(pinset.loadSet(blockstore, pinRoot, PinTypes.direct)))\n\n for await (const cid of pinset.loadSet(blockstore, pinRoot, PinTypes.recursive)) {\n counter++\n\n /** @type {{ depth: number, version?: CIDVersion, codec?: number }} */\n const pin = {\n depth: Infinity\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n await pinstore.put(cidToKey(cid), cbor.encode(pin))\n\n onProgress((counter / pinCount) * 100, `Migrated recursive pin ${cid}`)\n }\n\n for await (const cid of pinset.loadSet(blockstore, pinRoot, PinTypes.direct)) {\n counter++\n\n /** @type {{ depth: number, version?: CIDVersion, codec?: number }} */\n const pin = {\n depth: 0\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n await pinstore.put(cidToKey(cid), cbor.encode(pin))\n\n onProgress((counter / pinCount) * 100, `Migrated direct pin ${cid}`)\n }\n\n await blockstore.delete(cid)\n await datastore.delete(PIN_DS_KEY)\n}\n\n/**\n * @param {Blockstore} blockstore\n * @param {Datastore} datastore\n * @param {Datastore} pinstore\n * @param {MigrationProgressCallback} onProgress\n */\nasync function pinsToDAG (blockstore, datastore, pinstore, onProgress) {\n const recursivePins = []\n const directPins = []\n let counter = 0\n const pinCount = await length(pinstore.queryKeys({}))\n\n for await (const { key, value } of pinstore.query({})) {\n counter++\n const pin = cbor.decode(value)\n const cid = CID.create(\n pin.version || 0,\n pin.codec || dagPb.code,\n mhd.decode(base32.decode('b' + key.toString().toLowerCase().split('/').pop()))\n )\n\n if (pin.depth === 0) {\n onProgress((counter / pinCount) * 100, `Reverted direct pin ${cid}`)\n\n directPins.push(cid)\n } else {\n onProgress((counter / pinCount) * 100, `Reverted recursive pin ${cid}`)\n\n recursivePins.push(cid)\n }\n }\n\n onProgress(100, 'Updating pin root')\n const pinRoot = {\n Links: [\n await pinset.storeSet(blockstore, PinTypes.direct, directPins),\n await pinset.storeSet(blockstore, PinTypes.recursive, recursivePins)\n ]\n }\n const buf = dagPb.encode(pinRoot)\n const digest = await sha256.digest(buf)\n const cid = CID.createV0(digest)\n\n await blockstore.put(cid, buf)\n await datastore.put(PIN_DS_KEY, cid.bytes)\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {MigrationProgressCallback} onProgress\n * @param {*} fn\n */\nasync function process (backends, onProgress, fn) {\n const blockstore = backends.blocks\n const datastore = backends.datastore\n const pinstore = backends.pins\n\n await blockstore.open()\n await datastore.open()\n await pinstore.open()\n\n try {\n await fn(blockstore, datastore, pinstore, onProgress)\n } finally {\n await pinstore.close()\n await datastore.close()\n await blockstore.close()\n }\n}\n\n/** @type {Migration} */\nexport const migration = {\n version: 9,\n description: 'Migrates pins to datastore',\n migrate: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, pinsToDatastore)\n },\n revert: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, pinsToDAG)\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport { notFoundError } from 'datastore-core/errors'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\nexport const CONFIG_KEY = new Key('/config')\nexport const VERSION_KEY = new Key('/version')\n\n/**\n * Level dbs wrap level dbs that wrap level dbs. Find a level-js\n * instance in the chain if one exists.\n *\n * @param {Datastore} store\n * @returns {Datastore | undefined}\n */\nexport function findLevelJs (store) {\n let db = store\n\n // @ts-ignore\n while (db.db || db.child) {\n // @ts-ignore\n db = db.db || db.child\n\n // `Level` is only present in the browser, in node it is LevelDOWN\n // @ts-ignore\n if (db.type === 'level-js' || db.constructor.name === 'Level') {\n return db\n }\n }\n}\n\n/**\n * @param {Key} key\n * @param {function (Key): Promise} has\n * @param {Datastore} store\n * @returns {Promise}\n */\nexport async function hasWithFallback (key, has, store) {\n const result = await has(key)\n\n if (result) {\n return result\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n return false\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n resolve(Boolean(req.result))\n }\n })\n}\n\n/**\n * @param {import('interface-datastore').Key} key\n * @param {function (Key): Promise} get\n * @param {function (Key): Promise} has\n * @param {import('interface-datastore').Datastore} store\n * @returns {Promise}\n */\nasync function getWithFallback (key, get, has, store) {\n if (await has(key)) {\n return get(key)\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n throw notFoundError()\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n if (req.result) {\n return resolve(req.result)\n }\n\n reject(notFoundError())\n }\n })\n}\n\n/**\n * @param {Datastore} store\n */\nfunction wrapStore (store) {\n // necessary since level-js@5 cannot read keys from level-js@4 and earlier\n const originalGet = store.get.bind(store)\n const originalHas = store.has.bind(store)\n /**\n * @param {Key} key\n */\n store.get = (key) => getWithFallback(key, originalGet, originalHas, store)\n /**\n * @param {Key} key\n */\n store.has = (key) => hasWithFallback(key, originalHas, store)\n\n return store\n}\n\n/**\n * @param {import('./types').Backends} backends\n */\nexport function wrapBackends (backends) {\n return {\n ...backends,\n root: wrapStore(backends.root),\n datastore: wrapStore(backends.datastore),\n pins: wrapStore(backends.pins),\n keys: wrapStore(backends.keys)\n }\n}\n", "\nimport { findLevelJs } from '../../utils.js'\nimport { fromString } from 'uint8arrays/from-string'\nimport { toString } from 'uint8arrays/to-string'\n\n/**\n * @typedef {import('../../types').Migration} Migration\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../../types').MigrationProgressCallback} MigrationProgressCallback\n *\n * @typedef {{ type: 'del', key: string | Uint8Array } | { type: 'put', key: string | Uint8Array, value: Uint8Array }} Operation\n * @typedef {function (string, Uint8Array): Operation[]} UpgradeFunction\n * @typedef {function (Uint8Array, Uint8Array): Operation[]} DowngradeFunction\n */\n\n/**\n * @param {string} name\n * @param {Datastore} store\n * @param {(message: string) => void} onProgress\n */\nasync function keysToBinary (name, store, onProgress = () => {}) {\n const db = findLevelJs(store)\n\n // only interested in level-js\n if (!db) {\n onProgress(`${name} did not need an upgrade`)\n\n return\n }\n\n onProgress(`Upgrading ${name}`)\n\n /**\n * @type {UpgradeFunction}\n */\n const upgrade = (key, value) => {\n return [\n { type: 'del', key: key },\n { type: 'put', key: fromString(key), value: value }\n ]\n }\n\n await withEach(db, upgrade)\n}\n\n/**\n * @param {string} name\n * @param {Datastore} store\n * @param {(message: string) => void} onProgress\n */\nasync function keysToStrings (name, store, onProgress = () => {}) {\n const db = findLevelJs(store)\n\n // only interested in level-js\n if (!db) {\n onProgress(`${name} did not need a downgrade`)\n\n return\n }\n\n onProgress(`Downgrading ${name}`)\n\n /**\n * @type {DowngradeFunction}\n */\n const downgrade = (key, value) => {\n return [\n { type: 'del', key: key },\n { type: 'put', key: toString(key), value: value }\n ]\n }\n\n await withEach(db, downgrade)\n}\n\n/**\n * @param {any} store\n * @returns {Datastore}\n */\nfunction unwrap (store) {\n if (store.child) {\n return unwrap(store.child)\n }\n\n return store\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {MigrationProgressCallback} onProgress\n * @param {*} fn\n */\nasync function process (backends, onProgress, fn) {\n /**\n * @type {{ name: string, store: Datastore }[]}\n */\n const datastores = Object.entries(backends)\n .map(([key, backend]) => ({ key, backend: unwrap(backend) }))\n .filter(({ key, backend }) => backend.constructor.name === 'LevelDatastore')\n .map(({ key, backend }) => ({\n name: key,\n store: backend\n }))\n\n onProgress(0, `Migrating ${datastores.length} dbs`)\n let migrated = 0\n\n /**\n * @param {string} message\n */\n const progress = (message) => {\n onProgress(Math.round((migrated / datastores.length) * 100), message)\n }\n\n for (const { name, store } of datastores) {\n await store.open()\n\n try {\n await fn(name, store, progress)\n } finally {\n migrated++\n await store.close()\n }\n }\n\n onProgress(100, `Migrated ${datastores.length} dbs`)\n}\n\n/** @type {Migration} */\nexport const migration = {\n version: 10,\n description: 'Migrates datastore-level keys to binary',\n migrate: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keysToBinary)\n },\n revert: (backends, onProgress = () => {}) => {\n return process(backends, onProgress, keysToStrings)\n }\n}\n\n/**\n * Uses the upgrade strategy from level-js@5.x.x - note we can't call the `.upgrade` command\n * directly because it will be removed in level-js@6.x.x and we can't guarantee users will\n * have migrated by then - e.g. they may jump from level-js@4.x.x straight to level-js@6.x.x\n * so we have to duplicate the code here.\n *\n * @param {any} db\n * @param {UpgradeFunction | DowngradeFunction} fn\n * @returns {Promise}\n */\nfunction withEach (db, fn) {\n /**\n * @param {Operation[]} operations\n * @param {(error?: Error) => void} next\n */\n function batch (operations, next) {\n const store = db.store('readwrite')\n const transaction = store.transaction\n let index = 0\n /** @type {Error | undefined} */\n let error\n\n transaction.onabort = () => next(error || transaction.error || new Error('aborted by user'))\n transaction.oncomplete = () => next()\n\n function loop () {\n const op = operations[index++]\n const key = op.key\n let req\n\n try {\n req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)\n } catch (/** @type {any} */ err) {\n error = err\n transaction.abort()\n return\n }\n\n if (index < operations.length) {\n req.onsuccess = loop\n }\n }\n\n loop()\n }\n\n return new Promise((resolve, reject) => {\n const it = db.iterator()\n // raw keys and values only\n /**\n * @template T\n * @param {T} data\n */\n const id = (data) => data\n it._deserializeKey = it._deserializeValue = id\n next()\n\n function next () {\n /**\n * @param {Error | undefined} err\n * @param {string | undefined} key\n * @param {Uint8Array} value\n */\n const handleNext = (err, key, value) => {\n if (err || key === undefined) {\n /**\n * @param {Error | undefined} err2\n */\n const handleEnd = (err2) => {\n if (err2) {\n reject(err2)\n return\n }\n\n resolve()\n }\n\n it.end(handleEnd)\n\n return\n }\n\n // @ts-ignore\n batch(fn(key, value), next)\n }\n it.next(handleNext)\n }\n })\n}\n", "\nimport { Key } from 'interface-datastore/key'\n\nconst MFS_ROOT_KEY = new Key('/local/filesroot')\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storeMfsRootInDatastore (backends, onProgress = () => {}) {\n onProgress(100, 'Migrating MFS root to repo datastore')\n\n await backends.root.open()\n await backends.datastore.open()\n\n if (await backends.root.has(MFS_ROOT_KEY)) {\n const root = await backends.root.get(MFS_ROOT_KEY)\n await backends.datastore.put(MFS_ROOT_KEY, root)\n await backends.root.delete(MFS_ROOT_KEY)\n }\n\n await backends.datastore.close()\n await backends.root.close()\n\n onProgress(100, 'Stored MFS root in repo datastore')\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storeMfsRootInRoot (backends, onProgress = () => {}) {\n onProgress(100, 'Migrating MFS root to repo root datastore')\n\n await backends.root.open()\n await backends.datastore.open()\n\n if (await backends.datastore.has(MFS_ROOT_KEY)) {\n const root = await backends.datastore.get(MFS_ROOT_KEY)\n await backends.root.put(MFS_ROOT_KEY, root)\n await backends.datastore.delete(MFS_ROOT_KEY)\n }\n\n await backends.datastore.close()\n await backends.root.close()\n\n onProgress(100, 'Stored MFS root in repo root datastore')\n}\n\n/** @type {import('../../types').Migration} */\nexport const migration = {\n version: 11,\n description: 'Store mfs root in the datastore',\n migrate: storeMfsRootInDatastore,\n revert: storeMfsRootInRoot\n}\n", "import $protobuf from 'protobufjs/minimal.js'\nimport { Key } from 'interface-datastore/key'\nimport { Protocols } from './pb/proto-book.js'\nimport { Addresses } from './pb/address-book.js'\nimport { Peer } from './pb/peer.js'\nimport { Envelope } from './pb/envelope.js'\nimport { PeerRecord } from './pb/peer-record.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n// @ts-expect-error Explicitly disable long.js support\n$protobuf.util.Long = undefined\n$protobuf.configure()\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storePeerUnderSingleDatastoreKey (backends, onProgress = () => {}) {\n onProgress(0, 'Storing each peerstore key under a single datastore key')\n\n await backends.datastore.open()\n\n /** @type {Record} */\n const peers = {}\n /** @type {Key[]} */\n const keys = []\n\n for await (const { key, value } of backends.datastore.query({\n prefix: '/peers'\n })) {\n keys.push(key)\n const keyStr = key.toString()\n const [, prefix, type, peerId, metadataKey] = keyStr.split('/')\n\n if (prefix !== 'peers') {\n continue\n }\n\n if (!['protos', 'addrs', 'metadata', 'keys'].includes(type)) {\n continue\n }\n\n if (!peerId) {\n continue\n }\n\n peers[peerId] = peers[peerId] || {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n if (type === 'protos') {\n const protos = Protocols.decode(value)\n\n peers[peerId].protocols = protos.protocols.sort()\n } else if (type === 'addrs') {\n const addrs = Addresses.decode(value)\n\n peers[peerId].addresses = addrs.addrs.sort((a, b) => {\n return multiaddr(a.multiaddr).toString().localeCompare(multiaddr(b.multiaddr).toString())\n })\n\n if (addrs.certifiedRecord && addrs.certifiedRecord.raw) {\n peers[peerId].peerRecordEnvelope = addrs.certifiedRecord.raw\n }\n } else if (type === 'metadata') {\n peers[peerId].metadata.push({ key: metadataKey, value })\n } else if (type === 'keys') {\n peers[peerId].pubKey = value\n }\n }\n\n onProgress(33, 'Read peer data from store')\n\n for (const key of keys) {\n await backends.datastore.delete(key)\n }\n\n onProgress(66, 'Removed existing peer data from store')\n\n for (const peerId of Object.keys(peers)) {\n const peer = peers[peerId]\n peer.metadata = peer.metadata.sort((/** @type {{ key: string }} */ a, /** @type {{ key: string }} */ b) => a.key.localeCompare(b.key))\n\n const data = Peer.encode(peer).finish()\n\n await backends.datastore.put(new Key(`/peers/${peerId}`), data)\n }\n\n await backends.datastore.close()\n\n onProgress(100, 'Stored each peerstore key under a single datastore key')\n}\n\n/**\n * @param {import('../../types').Backends} backends\n * @param {import('../../types').MigrationProgressCallback} onProgress\n */\nasync function storePeerUnderMultipleDatastoreKeys (backends, onProgress = () => {}) {\n onProgress(0, 'Storing each peerstore key under a multiple datastore keys')\n\n await backends.datastore.open()\n\n /** @type {Record} */\n const peers = {}\n /** @type {Key[]} */\n const keys = []\n\n for await (const { key, value } of backends.datastore.query({\n prefix: '/peers'\n })) {\n keys.push(key)\n const keyStr = key.toString()\n\n const [, , peerId] = keyStr.split('/')\n\n peers[peerId] = Peer.decode(value)\n }\n\n onProgress(33, 'Read peer data from store')\n\n for (const key of keys) {\n await backends.datastore.delete(key)\n }\n\n onProgress(66, 'Removed existing peer data from store')\n\n for (const [peerId, peer] of Object.entries(peers)) {\n if (peer.protocols && peer.protocols.length > 0) {\n await backends.datastore.put(new Key(`/peers/protos/${peerId}`), Protocols.encode({\n protocols: peer.protocols\n }).finish())\n }\n\n if (peer.addresses && peer.addresses.length > 0) {\n const peerRecordEnvelope = peer.peerRecordEnvelope\n let certifiedRecord\n\n if (peerRecordEnvelope) {\n const envelope = Envelope.decode(peerRecordEnvelope)\n const record = PeerRecord.decode(envelope.payload)\n\n certifiedRecord = {\n raw: peerRecordEnvelope,\n seq: record.seq\n }\n }\n\n await backends.datastore.put(new Key(`/peers/addrs/${peerId}`), Addresses.encode({\n addrs: peer.addresses,\n certifiedRecord\n }).finish())\n }\n\n if (peer.metadata && peer.metadata.length > 0) {\n for (const { key, value } of peer.metadata) {\n await backends.datastore.put(new Key(`/peers/metadata/${peerId}/${key}`), value)\n }\n }\n\n if (peer.pubKey) {\n await backends.datastore.put(new Key(`/peers/keys/${peerId}`), peer.pubKey)\n }\n }\n\n await backends.datastore.close()\n\n onProgress(100, 'Stored each peerstore key under multiple datastore keys')\n}\n\n/** @type {import('../../types').Migration} */\nexport const migration = {\n version: 12,\n description: 'Store each peerstore peer under a single datastore key',\n migrate: storePeerUnderSingleDatastoreKey,\n revert: storePeerUnderMultipleDatastoreKeys\n}\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Protocols = $root.Protocols = (() => {\n\n /**\n * Properties of a Protocols.\n * @exports IProtocols\n * @interface IProtocols\n * @property {Array.|null} [protocols] Protocols protocols\n */\n\n /**\n * Constructs a new Protocols.\n * @exports Protocols\n * @classdesc Represents a Protocols.\n * @implements IProtocols\n * @constructor\n * @param {IProtocols=} [p] Properties to set\n */\n function Protocols(p) {\n this.protocols = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Protocols protocols.\n * @member {Array.} protocols\n * @memberof Protocols\n * @instance\n */\n Protocols.prototype.protocols = $util.emptyArray;\n\n /**\n * Encodes the specified Protocols message. Does not implicitly {@link Protocols.verify|verify} messages.\n * @function encode\n * @memberof Protocols\n * @static\n * @param {IProtocols} m Protocols message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Protocols.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.protocols != null && m.protocols.length) {\n for (var i = 0; i < m.protocols.length; ++i)\n w.uint32(10).string(m.protocols[i]);\n }\n return w;\n };\n\n /**\n * Decodes a Protocols message from the specified reader or buffer.\n * @function decode\n * @memberof Protocols\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Protocols} Protocols\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Protocols.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Protocols();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.protocols && m.protocols.length))\n m.protocols = [];\n m.protocols.push(r.string());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Protocols message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Protocols\n * @static\n * @param {Object.} d Plain object\n * @returns {Protocols} Protocols\n */\n Protocols.fromObject = function fromObject(d) {\n if (d instanceof $root.Protocols)\n return d;\n var m = new $root.Protocols();\n if (d.protocols) {\n if (!Array.isArray(d.protocols))\n throw TypeError(\".Protocols.protocols: array expected\");\n m.protocols = [];\n for (var i = 0; i < d.protocols.length; ++i) {\n m.protocols[i] = String(d.protocols[i]);\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Protocols message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Protocols\n * @static\n * @param {Protocols} m Protocols\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Protocols.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.protocols = [];\n }\n if (m.protocols && m.protocols.length) {\n d.protocols = [];\n for (var j = 0; j < m.protocols.length; ++j) {\n d.protocols[j] = m.protocols[j];\n }\n }\n return d;\n };\n\n /**\n * Converts this Protocols to JSON.\n * @function toJSON\n * @memberof Protocols\n * @instance\n * @returns {Object.} JSON object\n */\n Protocols.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Protocols;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Addresses = $root.Addresses = (() => {\n\n /**\n * Properties of an Addresses.\n * @exports IAddresses\n * @interface IAddresses\n * @property {Array.|null} [addrs] Addresses addrs\n * @property {Addresses.ICertifiedRecord|null} [certifiedRecord] Addresses certifiedRecord\n */\n\n /**\n * Constructs a new Addresses.\n * @exports Addresses\n * @classdesc Represents an Addresses.\n * @implements IAddresses\n * @constructor\n * @param {IAddresses=} [p] Properties to set\n */\n function Addresses(p) {\n this.addrs = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Addresses addrs.\n * @member {Array.} addrs\n * @memberof Addresses\n * @instance\n */\n Addresses.prototype.addrs = $util.emptyArray;\n\n /**\n * Addresses certifiedRecord.\n * @member {Addresses.ICertifiedRecord|null|undefined} certifiedRecord\n * @memberof Addresses\n * @instance\n */\n Addresses.prototype.certifiedRecord = null;\n\n /**\n * Encodes the specified Addresses message. Does not implicitly {@link Addresses.verify|verify} messages.\n * @function encode\n * @memberof Addresses\n * @static\n * @param {IAddresses} m Addresses message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Addresses.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.addrs != null && m.addrs.length) {\n for (var i = 0; i < m.addrs.length; ++i)\n $root.Addresses.Address.encode(m.addrs[i], w.uint32(10).fork()).ldelim();\n }\n if (m.certifiedRecord != null && Object.hasOwnProperty.call(m, \"certifiedRecord\"))\n $root.Addresses.CertifiedRecord.encode(m.certifiedRecord, w.uint32(18).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes an Addresses message from the specified reader or buffer.\n * @function decode\n * @memberof Addresses\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Addresses} Addresses\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Addresses.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Addresses();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.addrs && m.addrs.length))\n m.addrs = [];\n m.addrs.push($root.Addresses.Address.decode(r, r.uint32()));\n break;\n case 2:\n m.certifiedRecord = $root.Addresses.CertifiedRecord.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Addresses message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Addresses\n * @static\n * @param {Object.} d Plain object\n * @returns {Addresses} Addresses\n */\n Addresses.fromObject = function fromObject(d) {\n if (d instanceof $root.Addresses)\n return d;\n var m = new $root.Addresses();\n if (d.addrs) {\n if (!Array.isArray(d.addrs))\n throw TypeError(\".Addresses.addrs: array expected\");\n m.addrs = [];\n for (var i = 0; i < d.addrs.length; ++i) {\n if (typeof d.addrs[i] !== \"object\")\n throw TypeError(\".Addresses.addrs: object expected\");\n m.addrs[i] = $root.Addresses.Address.fromObject(d.addrs[i]);\n }\n }\n if (d.certifiedRecord != null) {\n if (typeof d.certifiedRecord !== \"object\")\n throw TypeError(\".Addresses.certifiedRecord: object expected\");\n m.certifiedRecord = $root.Addresses.CertifiedRecord.fromObject(d.certifiedRecord);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Addresses message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Addresses\n * @static\n * @param {Addresses} m Addresses\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Addresses.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.addrs = [];\n }\n if (o.defaults) {\n d.certifiedRecord = null;\n }\n if (m.addrs && m.addrs.length) {\n d.addrs = [];\n for (var j = 0; j < m.addrs.length; ++j) {\n d.addrs[j] = $root.Addresses.Address.toObject(m.addrs[j], o);\n }\n }\n if (m.certifiedRecord != null && m.hasOwnProperty(\"certifiedRecord\")) {\n d.certifiedRecord = $root.Addresses.CertifiedRecord.toObject(m.certifiedRecord, o);\n }\n return d;\n };\n\n /**\n * Converts this Addresses to JSON.\n * @function toJSON\n * @memberof Addresses\n * @instance\n * @returns {Object.} JSON object\n */\n Addresses.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n Addresses.Address = (function() {\n\n /**\n * Properties of an Address.\n * @memberof Addresses\n * @interface IAddress\n * @property {Uint8Array|null} [multiaddr] Address multiaddr\n * @property {boolean|null} [isCertified] Address isCertified\n */\n\n /**\n * Constructs a new Address.\n * @memberof Addresses\n * @classdesc Represents an Address.\n * @implements IAddress\n * @constructor\n * @param {Addresses.IAddress=} [p] Properties to set\n */\n function Address(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Address multiaddr.\n * @member {Uint8Array} multiaddr\n * @memberof Addresses.Address\n * @instance\n */\n Address.prototype.multiaddr = $util.newBuffer([]);\n\n /**\n * Address isCertified.\n * @member {boolean|null|undefined} isCertified\n * @memberof Addresses.Address\n * @instance\n */\n Address.prototype.isCertified = null;\n\n // OneOf field names bound to virtual getters and setters\n let $oneOfFields;\n\n /**\n * Address _isCertified.\n * @member {\"isCertified\"|undefined} _isCertified\n * @memberof Addresses.Address\n * @instance\n */\n Object.defineProperty(Address.prototype, \"_isCertified\", {\n get: $util.oneOfGetter($oneOfFields = [\"isCertified\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Address message. Does not implicitly {@link Addresses.Address.verify|verify} messages.\n * @function encode\n * @memberof Addresses.Address\n * @static\n * @param {Addresses.IAddress} m Address message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Address.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.multiaddr != null && Object.hasOwnProperty.call(m, \"multiaddr\"))\n w.uint32(10).bytes(m.multiaddr);\n if (m.isCertified != null && Object.hasOwnProperty.call(m, \"isCertified\"))\n w.uint32(16).bool(m.isCertified);\n return w;\n };\n\n /**\n * Decodes an Address message from the specified reader or buffer.\n * @function decode\n * @memberof Addresses.Address\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Addresses.Address} Address\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Address.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Addresses.Address();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.multiaddr = r.bytes();\n break;\n case 2:\n m.isCertified = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Address message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Addresses.Address\n * @static\n * @param {Object.} d Plain object\n * @returns {Addresses.Address} Address\n */\n Address.fromObject = function fromObject(d) {\n if (d instanceof $root.Addresses.Address)\n return d;\n var m = new $root.Addresses.Address();\n if (d.multiaddr != null) {\n if (typeof d.multiaddr === \"string\")\n $util.base64.decode(d.multiaddr, m.multiaddr = $util.newBuffer($util.base64.length(d.multiaddr)), 0);\n else if (d.multiaddr.length)\n m.multiaddr = d.multiaddr;\n }\n if (d.isCertified != null) {\n m.isCertified = Boolean(d.isCertified);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Address message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Addresses.Address\n * @static\n * @param {Addresses.Address} m Address\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Address.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.multiaddr = \"\";\n else {\n d.multiaddr = [];\n if (o.bytes !== Array)\n d.multiaddr = $util.newBuffer(d.multiaddr);\n }\n }\n if (m.multiaddr != null && m.hasOwnProperty(\"multiaddr\")) {\n d.multiaddr = o.bytes === String ? $util.base64.encode(m.multiaddr, 0, m.multiaddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.multiaddr) : m.multiaddr;\n }\n if (m.isCertified != null && m.hasOwnProperty(\"isCertified\")) {\n d.isCertified = m.isCertified;\n if (o.oneofs)\n d._isCertified = \"isCertified\";\n }\n return d;\n };\n\n /**\n * Converts this Address to JSON.\n * @function toJSON\n * @memberof Addresses.Address\n * @instance\n * @returns {Object.} JSON object\n */\n Address.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Address;\n })();\n\n Addresses.CertifiedRecord = (function() {\n\n /**\n * Properties of a CertifiedRecord.\n * @memberof Addresses\n * @interface ICertifiedRecord\n * @property {number|null} [seq] CertifiedRecord seq\n * @property {Uint8Array|null} [raw] CertifiedRecord raw\n */\n\n /**\n * Constructs a new CertifiedRecord.\n * @memberof Addresses\n * @classdesc Represents a CertifiedRecord.\n * @implements ICertifiedRecord\n * @constructor\n * @param {Addresses.ICertifiedRecord=} [p] Properties to set\n */\n function CertifiedRecord(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * CertifiedRecord seq.\n * @member {number} seq\n * @memberof Addresses.CertifiedRecord\n * @instance\n */\n CertifiedRecord.prototype.seq = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * CertifiedRecord raw.\n * @member {Uint8Array} raw\n * @memberof Addresses.CertifiedRecord\n * @instance\n */\n CertifiedRecord.prototype.raw = $util.newBuffer([]);\n\n /**\n * Encodes the specified CertifiedRecord message. Does not implicitly {@link Addresses.CertifiedRecord.verify|verify} messages.\n * @function encode\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {Addresses.ICertifiedRecord} m CertifiedRecord message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n CertifiedRecord.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.seq != null && Object.hasOwnProperty.call(m, \"seq\"))\n w.uint32(8).uint64(m.seq);\n if (m.raw != null && Object.hasOwnProperty.call(m, \"raw\"))\n w.uint32(18).bytes(m.raw);\n return w;\n };\n\n /**\n * Decodes a CertifiedRecord message from the specified reader or buffer.\n * @function decode\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Addresses.CertifiedRecord} CertifiedRecord\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n CertifiedRecord.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Addresses.CertifiedRecord();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.seq = r.uint64();\n break;\n case 2:\n m.raw = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a CertifiedRecord message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {Object.} d Plain object\n * @returns {Addresses.CertifiedRecord} CertifiedRecord\n */\n CertifiedRecord.fromObject = function fromObject(d) {\n if (d instanceof $root.Addresses.CertifiedRecord)\n return d;\n var m = new $root.Addresses.CertifiedRecord();\n if (d.seq != null) {\n if ($util.Long)\n (m.seq = $util.Long.fromValue(d.seq)).unsigned = true;\n else if (typeof d.seq === \"string\")\n m.seq = parseInt(d.seq, 10);\n else if (typeof d.seq === \"number\")\n m.seq = d.seq;\n else if (typeof d.seq === \"object\")\n m.seq = new $util.LongBits(d.seq.low >>> 0, d.seq.high >>> 0).toNumber(true);\n }\n if (d.raw != null) {\n if (typeof d.raw === \"string\")\n $util.base64.decode(d.raw, m.raw = $util.newBuffer($util.base64.length(d.raw)), 0);\n else if (d.raw.length)\n m.raw = d.raw;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a CertifiedRecord message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Addresses.CertifiedRecord\n * @static\n * @param {Addresses.CertifiedRecord} m CertifiedRecord\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n CertifiedRecord.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.seq = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.seq = o.longs === String ? \"0\" : 0;\n if (o.bytes === String)\n d.raw = \"\";\n else {\n d.raw = [];\n if (o.bytes !== Array)\n d.raw = $util.newBuffer(d.raw);\n }\n }\n if (m.seq != null && m.hasOwnProperty(\"seq\")) {\n if (typeof m.seq === \"number\")\n d.seq = o.longs === String ? String(m.seq) : m.seq;\n else\n d.seq = o.longs === String ? $util.Long.prototype.toString.call(m.seq) : o.longs === Number ? new $util.LongBits(m.seq.low >>> 0, m.seq.high >>> 0).toNumber(true) : m.seq;\n }\n if (m.raw != null && m.hasOwnProperty(\"raw\")) {\n d.raw = o.bytes === String ? $util.base64.encode(m.raw, 0, m.raw.length) : o.bytes === Array ? Array.prototype.slice.call(m.raw) : m.raw;\n }\n return d;\n };\n\n /**\n * Converts this CertifiedRecord to JSON.\n * @function toJSON\n * @memberof Addresses.CertifiedRecord\n * @instance\n * @returns {Object.} JSON object\n */\n CertifiedRecord.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return CertifiedRecord;\n })();\n\n return Addresses;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Peer = $root.Peer = (() => {\n\n /**\n * Properties of a Peer.\n * @exports IPeer\n * @interface IPeer\n * @property {Array.|null} [addresses] Peer addresses\n * @property {Array.|null} [protocols] Peer protocols\n * @property {Array.|null} [metadata] Peer metadata\n * @property {Uint8Array|null} [pubKey] Peer pubKey\n * @property {Uint8Array|null} [peerRecordEnvelope] Peer peerRecordEnvelope\n */\n\n /**\n * Constructs a new Peer.\n * @exports Peer\n * @classdesc Represents a Peer.\n * @implements IPeer\n * @constructor\n * @param {IPeer=} [p] Properties to set\n */\n function Peer(p) {\n this.addresses = [];\n this.protocols = [];\n this.metadata = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Peer addresses.\n * @member {Array.} addresses\n * @memberof Peer\n * @instance\n */\n Peer.prototype.addresses = $util.emptyArray;\n\n /**\n * Peer protocols.\n * @member {Array.} protocols\n * @memberof Peer\n * @instance\n */\n Peer.prototype.protocols = $util.emptyArray;\n\n /**\n * Peer metadata.\n * @member {Array.} metadata\n * @memberof Peer\n * @instance\n */\n Peer.prototype.metadata = $util.emptyArray;\n\n /**\n * Peer pubKey.\n * @member {Uint8Array|null|undefined} pubKey\n * @memberof Peer\n * @instance\n */\n Peer.prototype.pubKey = null;\n\n /**\n * Peer peerRecordEnvelope.\n * @member {Uint8Array|null|undefined} peerRecordEnvelope\n * @memberof Peer\n * @instance\n */\n Peer.prototype.peerRecordEnvelope = null;\n\n // OneOf field names bound to virtual getters and setters\n let $oneOfFields;\n\n /**\n * Peer _pubKey.\n * @member {\"pubKey\"|undefined} _pubKey\n * @memberof Peer\n * @instance\n */\n Object.defineProperty(Peer.prototype, \"_pubKey\", {\n get: $util.oneOfGetter($oneOfFields = [\"pubKey\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Peer _peerRecordEnvelope.\n * @member {\"peerRecordEnvelope\"|undefined} _peerRecordEnvelope\n * @memberof Peer\n * @instance\n */\n Object.defineProperty(Peer.prototype, \"_peerRecordEnvelope\", {\n get: $util.oneOfGetter($oneOfFields = [\"peerRecordEnvelope\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Peer message. Does not implicitly {@link Peer.verify|verify} messages.\n * @function encode\n * @memberof Peer\n * @static\n * @param {IPeer} m Peer message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Peer.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.addresses != null && m.addresses.length) {\n for (var i = 0; i < m.addresses.length; ++i)\n $root.Address.encode(m.addresses[i], w.uint32(10).fork()).ldelim();\n }\n if (m.protocols != null && m.protocols.length) {\n for (var i = 0; i < m.protocols.length; ++i)\n w.uint32(18).string(m.protocols[i]);\n }\n if (m.metadata != null && m.metadata.length) {\n for (var i = 0; i < m.metadata.length; ++i)\n $root.Metadata.encode(m.metadata[i], w.uint32(26).fork()).ldelim();\n }\n if (m.pubKey != null && Object.hasOwnProperty.call(m, \"pubKey\"))\n w.uint32(34).bytes(m.pubKey);\n if (m.peerRecordEnvelope != null && Object.hasOwnProperty.call(m, \"peerRecordEnvelope\"))\n w.uint32(42).bytes(m.peerRecordEnvelope);\n return w;\n };\n\n /**\n * Decodes a Peer message from the specified reader or buffer.\n * @function decode\n * @memberof Peer\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Peer} Peer\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Peer.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Peer();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n if (!(m.addresses && m.addresses.length))\n m.addresses = [];\n m.addresses.push($root.Address.decode(r, r.uint32()));\n break;\n case 2:\n if (!(m.protocols && m.protocols.length))\n m.protocols = [];\n m.protocols.push(r.string());\n break;\n case 3:\n if (!(m.metadata && m.metadata.length))\n m.metadata = [];\n m.metadata.push($root.Metadata.decode(r, r.uint32()));\n break;\n case 4:\n m.pubKey = r.bytes();\n break;\n case 5:\n m.peerRecordEnvelope = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Peer message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Peer\n * @static\n * @param {Object.} d Plain object\n * @returns {Peer} Peer\n */\n Peer.fromObject = function fromObject(d) {\n if (d instanceof $root.Peer)\n return d;\n var m = new $root.Peer();\n if (d.addresses) {\n if (!Array.isArray(d.addresses))\n throw TypeError(\".Peer.addresses: array expected\");\n m.addresses = [];\n for (var i = 0; i < d.addresses.length; ++i) {\n if (typeof d.addresses[i] !== \"object\")\n throw TypeError(\".Peer.addresses: object expected\");\n m.addresses[i] = $root.Address.fromObject(d.addresses[i]);\n }\n }\n if (d.protocols) {\n if (!Array.isArray(d.protocols))\n throw TypeError(\".Peer.protocols: array expected\");\n m.protocols = [];\n for (var i = 0; i < d.protocols.length; ++i) {\n m.protocols[i] = String(d.protocols[i]);\n }\n }\n if (d.metadata) {\n if (!Array.isArray(d.metadata))\n throw TypeError(\".Peer.metadata: array expected\");\n m.metadata = [];\n for (var i = 0; i < d.metadata.length; ++i) {\n if (typeof d.metadata[i] !== \"object\")\n throw TypeError(\".Peer.metadata: object expected\");\n m.metadata[i] = $root.Metadata.fromObject(d.metadata[i]);\n }\n }\n if (d.pubKey != null) {\n if (typeof d.pubKey === \"string\")\n $util.base64.decode(d.pubKey, m.pubKey = $util.newBuffer($util.base64.length(d.pubKey)), 0);\n else if (d.pubKey.length)\n m.pubKey = d.pubKey;\n }\n if (d.peerRecordEnvelope != null) {\n if (typeof d.peerRecordEnvelope === \"string\")\n $util.base64.decode(d.peerRecordEnvelope, m.peerRecordEnvelope = $util.newBuffer($util.base64.length(d.peerRecordEnvelope)), 0);\n else if (d.peerRecordEnvelope.length)\n m.peerRecordEnvelope = d.peerRecordEnvelope;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Peer message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Peer\n * @static\n * @param {Peer} m Peer\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Peer.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.addresses = [];\n d.protocols = [];\n d.metadata = [];\n }\n if (m.addresses && m.addresses.length) {\n d.addresses = [];\n for (var j = 0; j < m.addresses.length; ++j) {\n d.addresses[j] = $root.Address.toObject(m.addresses[j], o);\n }\n }\n if (m.protocols && m.protocols.length) {\n d.protocols = [];\n for (var j = 0; j < m.protocols.length; ++j) {\n d.protocols[j] = m.protocols[j];\n }\n }\n if (m.metadata && m.metadata.length) {\n d.metadata = [];\n for (var j = 0; j < m.metadata.length; ++j) {\n d.metadata[j] = $root.Metadata.toObject(m.metadata[j], o);\n }\n }\n if (m.pubKey != null && m.hasOwnProperty(\"pubKey\")) {\n d.pubKey = o.bytes === String ? $util.base64.encode(m.pubKey, 0, m.pubKey.length) : o.bytes === Array ? Array.prototype.slice.call(m.pubKey) : m.pubKey;\n if (o.oneofs)\n d._pubKey = \"pubKey\";\n }\n if (m.peerRecordEnvelope != null && m.hasOwnProperty(\"peerRecordEnvelope\")) {\n d.peerRecordEnvelope = o.bytes === String ? $util.base64.encode(m.peerRecordEnvelope, 0, m.peerRecordEnvelope.length) : o.bytes === Array ? Array.prototype.slice.call(m.peerRecordEnvelope) : m.peerRecordEnvelope;\n if (o.oneofs)\n d._peerRecordEnvelope = \"peerRecordEnvelope\";\n }\n return d;\n };\n\n /**\n * Converts this Peer to JSON.\n * @function toJSON\n * @memberof Peer\n * @instance\n * @returns {Object.} JSON object\n */\n Peer.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Peer;\n})();\n\nexport const Address = $root.Address = (() => {\n\n /**\n * Properties of an Address.\n * @exports IAddress\n * @interface IAddress\n * @property {Uint8Array|null} [multiaddr] Address multiaddr\n * @property {boolean|null} [isCertified] Address isCertified\n */\n\n /**\n * Constructs a new Address.\n * @exports Address\n * @classdesc Represents an Address.\n * @implements IAddress\n * @constructor\n * @param {IAddress=} [p] Properties to set\n */\n function Address(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Address multiaddr.\n * @member {Uint8Array} multiaddr\n * @memberof Address\n * @instance\n */\n Address.prototype.multiaddr = $util.newBuffer([]);\n\n /**\n * Address isCertified.\n * @member {boolean|null|undefined} isCertified\n * @memberof Address\n * @instance\n */\n Address.prototype.isCertified = null;\n\n // OneOf field names bound to virtual getters and setters\n let $oneOfFields;\n\n /**\n * Address _isCertified.\n * @member {\"isCertified\"|undefined} _isCertified\n * @memberof Address\n * @instance\n */\n Object.defineProperty(Address.prototype, \"_isCertified\", {\n get: $util.oneOfGetter($oneOfFields = [\"isCertified\"]),\n set: $util.oneOfSetter($oneOfFields)\n });\n\n /**\n * Encodes the specified Address message. Does not implicitly {@link Address.verify|verify} messages.\n * @function encode\n * @memberof Address\n * @static\n * @param {IAddress} m Address message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Address.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.multiaddr != null && Object.hasOwnProperty.call(m, \"multiaddr\"))\n w.uint32(10).bytes(m.multiaddr);\n if (m.isCertified != null && Object.hasOwnProperty.call(m, \"isCertified\"))\n w.uint32(16).bool(m.isCertified);\n return w;\n };\n\n /**\n * Decodes an Address message from the specified reader or buffer.\n * @function decode\n * @memberof Address\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Address} Address\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Address.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Address();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.multiaddr = r.bytes();\n break;\n case 2:\n m.isCertified = r.bool();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Address message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Address\n * @static\n * @param {Object.} d Plain object\n * @returns {Address} Address\n */\n Address.fromObject = function fromObject(d) {\n if (d instanceof $root.Address)\n return d;\n var m = new $root.Address();\n if (d.multiaddr != null) {\n if (typeof d.multiaddr === \"string\")\n $util.base64.decode(d.multiaddr, m.multiaddr = $util.newBuffer($util.base64.length(d.multiaddr)), 0);\n else if (d.multiaddr.length)\n m.multiaddr = d.multiaddr;\n }\n if (d.isCertified != null) {\n m.isCertified = Boolean(d.isCertified);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Address message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Address\n * @static\n * @param {Address} m Address\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Address.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.multiaddr = \"\";\n else {\n d.multiaddr = [];\n if (o.bytes !== Array)\n d.multiaddr = $util.newBuffer(d.multiaddr);\n }\n }\n if (m.multiaddr != null && m.hasOwnProperty(\"multiaddr\")) {\n d.multiaddr = o.bytes === String ? $util.base64.encode(m.multiaddr, 0, m.multiaddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.multiaddr) : m.multiaddr;\n }\n if (m.isCertified != null && m.hasOwnProperty(\"isCertified\")) {\n d.isCertified = m.isCertified;\n if (o.oneofs)\n d._isCertified = \"isCertified\";\n }\n return d;\n };\n\n /**\n * Converts this Address to JSON.\n * @function toJSON\n * @memberof Address\n * @instance\n * @returns {Object.} JSON object\n */\n Address.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Address;\n})();\n\nexport const Metadata = $root.Metadata = (() => {\n\n /**\n * Properties of a Metadata.\n * @exports IMetadata\n * @interface IMetadata\n * @property {string|null} [key] Metadata key\n * @property {Uint8Array|null} [value] Metadata value\n */\n\n /**\n * Constructs a new Metadata.\n * @exports Metadata\n * @classdesc Represents a Metadata.\n * @implements IMetadata\n * @constructor\n * @param {IMetadata=} [p] Properties to set\n */\n function Metadata(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Metadata key.\n * @member {string} key\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.key = \"\";\n\n /**\n * Metadata value.\n * @member {Uint8Array} value\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.value = $util.newBuffer([]);\n\n /**\n * Encodes the specified Metadata message. Does not implicitly {@link Metadata.verify|verify} messages.\n * @function encode\n * @memberof Metadata\n * @static\n * @param {IMetadata} m Metadata message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Metadata.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.key != null && Object.hasOwnProperty.call(m, \"key\"))\n w.uint32(10).string(m.key);\n if (m.value != null && Object.hasOwnProperty.call(m, \"value\"))\n w.uint32(18).bytes(m.value);\n return w;\n };\n\n /**\n * Decodes a Metadata message from the specified reader or buffer.\n * @function decode\n * @memberof Metadata\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Metadata} Metadata\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Metadata.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Metadata();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.key = r.string();\n break;\n case 2:\n m.value = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Metadata message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Metadata\n * @static\n * @param {Object.} d Plain object\n * @returns {Metadata} Metadata\n */\n Metadata.fromObject = function fromObject(d) {\n if (d instanceof $root.Metadata)\n return d;\n var m = new $root.Metadata();\n if (d.key != null) {\n m.key = String(d.key);\n }\n if (d.value != null) {\n if (typeof d.value === \"string\")\n $util.base64.decode(d.value, m.value = $util.newBuffer($util.base64.length(d.value)), 0);\n else if (d.value.length)\n m.value = d.value;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Metadata message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Metadata\n * @static\n * @param {Metadata} m Metadata\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Metadata.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.key = \"\";\n if (o.bytes === String)\n d.value = \"\";\n else {\n d.value = [];\n if (o.bytes !== Array)\n d.value = $util.newBuffer(d.value);\n }\n }\n if (m.key != null && m.hasOwnProperty(\"key\")) {\n d.key = m.key;\n }\n if (m.value != null && m.hasOwnProperty(\"value\")) {\n d.value = o.bytes === String ? $util.base64.encode(m.value, 0, m.value.length) : o.bytes === Array ? Array.prototype.slice.call(m.value) : m.value;\n }\n return d;\n };\n\n /**\n * Converts this Metadata to JSON.\n * @function toJSON\n * @memberof Metadata\n * @instance\n * @returns {Object.} JSON object\n */\n Metadata.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Metadata;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const Envelope = $root.Envelope = (() => {\n\n /**\n * Properties of an Envelope.\n * @exports IEnvelope\n * @interface IEnvelope\n * @property {Uint8Array|null} [publicKey] Envelope publicKey\n * @property {Uint8Array|null} [payloadType] Envelope payloadType\n * @property {Uint8Array|null} [payload] Envelope payload\n * @property {Uint8Array|null} [signature] Envelope signature\n */\n\n /**\n * Constructs a new Envelope.\n * @exports Envelope\n * @classdesc Represents an Envelope.\n * @implements IEnvelope\n * @constructor\n * @param {IEnvelope=} [p] Properties to set\n */\n function Envelope(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Envelope publicKey.\n * @member {Uint8Array} publicKey\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.publicKey = $util.newBuffer([]);\n\n /**\n * Envelope payloadType.\n * @member {Uint8Array} payloadType\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.payloadType = $util.newBuffer([]);\n\n /**\n * Envelope payload.\n * @member {Uint8Array} payload\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.payload = $util.newBuffer([]);\n\n /**\n * Envelope signature.\n * @member {Uint8Array} signature\n * @memberof Envelope\n * @instance\n */\n Envelope.prototype.signature = $util.newBuffer([]);\n\n /**\n * Encodes the specified Envelope message. Does not implicitly {@link Envelope.verify|verify} messages.\n * @function encode\n * @memberof Envelope\n * @static\n * @param {IEnvelope} m Envelope message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Envelope.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.publicKey != null && Object.hasOwnProperty.call(m, \"publicKey\"))\n w.uint32(10).bytes(m.publicKey);\n if (m.payloadType != null && Object.hasOwnProperty.call(m, \"payloadType\"))\n w.uint32(18).bytes(m.payloadType);\n if (m.payload != null && Object.hasOwnProperty.call(m, \"payload\"))\n w.uint32(26).bytes(m.payload);\n if (m.signature != null && Object.hasOwnProperty.call(m, \"signature\"))\n w.uint32(42).bytes(m.signature);\n return w;\n };\n\n /**\n * Decodes an Envelope message from the specified reader or buffer.\n * @function decode\n * @memberof Envelope\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Envelope} Envelope\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Envelope.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Envelope();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.publicKey = r.bytes();\n break;\n case 2:\n m.payloadType = r.bytes();\n break;\n case 3:\n m.payload = r.bytes();\n break;\n case 5:\n m.signature = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Envelope message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Envelope\n * @static\n * @param {Object.} d Plain object\n * @returns {Envelope} Envelope\n */\n Envelope.fromObject = function fromObject(d) {\n if (d instanceof $root.Envelope)\n return d;\n var m = new $root.Envelope();\n if (d.publicKey != null) {\n if (typeof d.publicKey === \"string\")\n $util.base64.decode(d.publicKey, m.publicKey = $util.newBuffer($util.base64.length(d.publicKey)), 0);\n else if (d.publicKey.length)\n m.publicKey = d.publicKey;\n }\n if (d.payloadType != null) {\n if (typeof d.payloadType === \"string\")\n $util.base64.decode(d.payloadType, m.payloadType = $util.newBuffer($util.base64.length(d.payloadType)), 0);\n else if (d.payloadType.length)\n m.payloadType = d.payloadType;\n }\n if (d.payload != null) {\n if (typeof d.payload === \"string\")\n $util.base64.decode(d.payload, m.payload = $util.newBuffer($util.base64.length(d.payload)), 0);\n else if (d.payload.length)\n m.payload = d.payload;\n }\n if (d.signature != null) {\n if (typeof d.signature === \"string\")\n $util.base64.decode(d.signature, m.signature = $util.newBuffer($util.base64.length(d.signature)), 0);\n else if (d.signature.length)\n m.signature = d.signature;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Envelope message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Envelope\n * @static\n * @param {Envelope} m Envelope\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Envelope.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.publicKey = \"\";\n else {\n d.publicKey = [];\n if (o.bytes !== Array)\n d.publicKey = $util.newBuffer(d.publicKey);\n }\n if (o.bytes === String)\n d.payloadType = \"\";\n else {\n d.payloadType = [];\n if (o.bytes !== Array)\n d.payloadType = $util.newBuffer(d.payloadType);\n }\n if (o.bytes === String)\n d.payload = \"\";\n else {\n d.payload = [];\n if (o.bytes !== Array)\n d.payload = $util.newBuffer(d.payload);\n }\n if (o.bytes === String)\n d.signature = \"\";\n else {\n d.signature = [];\n if (o.bytes !== Array)\n d.signature = $util.newBuffer(d.signature);\n }\n }\n if (m.publicKey != null && m.hasOwnProperty(\"publicKey\")) {\n d.publicKey = o.bytes === String ? $util.base64.encode(m.publicKey, 0, m.publicKey.length) : o.bytes === Array ? Array.prototype.slice.call(m.publicKey) : m.publicKey;\n }\n if (m.payloadType != null && m.hasOwnProperty(\"payloadType\")) {\n d.payloadType = o.bytes === String ? $util.base64.encode(m.payloadType, 0, m.payloadType.length) : o.bytes === Array ? Array.prototype.slice.call(m.payloadType) : m.payloadType;\n }\n if (m.payload != null && m.hasOwnProperty(\"payload\")) {\n d.payload = o.bytes === String ? $util.base64.encode(m.payload, 0, m.payload.length) : o.bytes === Array ? Array.prototype.slice.call(m.payload) : m.payload;\n }\n if (m.signature != null && m.hasOwnProperty(\"signature\")) {\n d.signature = o.bytes === String ? $util.base64.encode(m.signature, 0, m.signature.length) : o.bytes === Array ? Array.prototype.slice.call(m.signature) : m.signature;\n }\n return d;\n };\n\n /**\n * Converts this Envelope to JSON.\n * @function toJSON\n * @memberof Envelope\n * @instance\n * @returns {Object.} JSON object\n */\n Envelope.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Envelope;\n})();\n\nexport { $root as default };\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\nexport const PeerRecord = $root.PeerRecord = (() => {\n\n /**\n * Properties of a PeerRecord.\n * @exports IPeerRecord\n * @interface IPeerRecord\n * @property {Uint8Array|null} [peerId] PeerRecord peerId\n * @property {number|null} [seq] PeerRecord seq\n * @property {Array.|null} [addresses] PeerRecord addresses\n */\n\n /**\n * Constructs a new PeerRecord.\n * @exports PeerRecord\n * @classdesc Represents a PeerRecord.\n * @implements IPeerRecord\n * @constructor\n * @param {IPeerRecord=} [p] Properties to set\n */\n function PeerRecord(p) {\n this.addresses = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * PeerRecord peerId.\n * @member {Uint8Array} peerId\n * @memberof PeerRecord\n * @instance\n */\n PeerRecord.prototype.peerId = $util.newBuffer([]);\n\n /**\n * PeerRecord seq.\n * @member {number} seq\n * @memberof PeerRecord\n * @instance\n */\n PeerRecord.prototype.seq = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * PeerRecord addresses.\n * @member {Array.} addresses\n * @memberof PeerRecord\n * @instance\n */\n PeerRecord.prototype.addresses = $util.emptyArray;\n\n /**\n * Encodes the specified PeerRecord message. Does not implicitly {@link PeerRecord.verify|verify} messages.\n * @function encode\n * @memberof PeerRecord\n * @static\n * @param {IPeerRecord} m PeerRecord message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n PeerRecord.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.peerId != null && Object.hasOwnProperty.call(m, \"peerId\"))\n w.uint32(10).bytes(m.peerId);\n if (m.seq != null && Object.hasOwnProperty.call(m, \"seq\"))\n w.uint32(16).uint64(m.seq);\n if (m.addresses != null && m.addresses.length) {\n for (var i = 0; i < m.addresses.length; ++i)\n $root.PeerRecord.AddressInfo.encode(m.addresses[i], w.uint32(26).fork()).ldelim();\n }\n return w;\n };\n\n /**\n * Decodes a PeerRecord message from the specified reader or buffer.\n * @function decode\n * @memberof PeerRecord\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {PeerRecord} PeerRecord\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n PeerRecord.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.PeerRecord();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.peerId = r.bytes();\n break;\n case 2:\n m.seq = r.uint64();\n break;\n case 3:\n if (!(m.addresses && m.addresses.length))\n m.addresses = [];\n m.addresses.push($root.PeerRecord.AddressInfo.decode(r, r.uint32()));\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a PeerRecord message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof PeerRecord\n * @static\n * @param {Object.} d Plain object\n * @returns {PeerRecord} PeerRecord\n */\n PeerRecord.fromObject = function fromObject(d) {\n if (d instanceof $root.PeerRecord)\n return d;\n var m = new $root.PeerRecord();\n if (d.peerId != null) {\n if (typeof d.peerId === \"string\")\n $util.base64.decode(d.peerId, m.peerId = $util.newBuffer($util.base64.length(d.peerId)), 0);\n else if (d.peerId.length)\n m.peerId = d.peerId;\n }\n if (d.seq != null) {\n if ($util.Long)\n (m.seq = $util.Long.fromValue(d.seq)).unsigned = true;\n else if (typeof d.seq === \"string\")\n m.seq = parseInt(d.seq, 10);\n else if (typeof d.seq === \"number\")\n m.seq = d.seq;\n else if (typeof d.seq === \"object\")\n m.seq = new $util.LongBits(d.seq.low >>> 0, d.seq.high >>> 0).toNumber(true);\n }\n if (d.addresses) {\n if (!Array.isArray(d.addresses))\n throw TypeError(\".PeerRecord.addresses: array expected\");\n m.addresses = [];\n for (var i = 0; i < d.addresses.length; ++i) {\n if (typeof d.addresses[i] !== \"object\")\n throw TypeError(\".PeerRecord.addresses: object expected\");\n m.addresses[i] = $root.PeerRecord.AddressInfo.fromObject(d.addresses[i]);\n }\n }\n return m;\n };\n\n /**\n * Creates a plain object from a PeerRecord message. Also converts values to other types if specified.\n * @function toObject\n * @memberof PeerRecord\n * @static\n * @param {PeerRecord} m PeerRecord\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n PeerRecord.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.addresses = [];\n }\n if (o.defaults) {\n if (o.bytes === String)\n d.peerId = \"\";\n else {\n d.peerId = [];\n if (o.bytes !== Array)\n d.peerId = $util.newBuffer(d.peerId);\n }\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.seq = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.seq = o.longs === String ? \"0\" : 0;\n }\n if (m.peerId != null && m.hasOwnProperty(\"peerId\")) {\n d.peerId = o.bytes === String ? $util.base64.encode(m.peerId, 0, m.peerId.length) : o.bytes === Array ? Array.prototype.slice.call(m.peerId) : m.peerId;\n }\n if (m.seq != null && m.hasOwnProperty(\"seq\")) {\n if (typeof m.seq === \"number\")\n d.seq = o.longs === String ? String(m.seq) : m.seq;\n else\n d.seq = o.longs === String ? $util.Long.prototype.toString.call(m.seq) : o.longs === Number ? new $util.LongBits(m.seq.low >>> 0, m.seq.high >>> 0).toNumber(true) : m.seq;\n }\n if (m.addresses && m.addresses.length) {\n d.addresses = [];\n for (var j = 0; j < m.addresses.length; ++j) {\n d.addresses[j] = $root.PeerRecord.AddressInfo.toObject(m.addresses[j], o);\n }\n }\n return d;\n };\n\n /**\n * Converts this PeerRecord to JSON.\n * @function toJSON\n * @memberof PeerRecord\n * @instance\n * @returns {Object.} JSON object\n */\n PeerRecord.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n PeerRecord.AddressInfo = (function() {\n\n /**\n * Properties of an AddressInfo.\n * @memberof PeerRecord\n * @interface IAddressInfo\n * @property {Uint8Array|null} [multiaddr] AddressInfo multiaddr\n */\n\n /**\n * Constructs a new AddressInfo.\n * @memberof PeerRecord\n * @classdesc Represents an AddressInfo.\n * @implements IAddressInfo\n * @constructor\n * @param {PeerRecord.IAddressInfo=} [p] Properties to set\n */\n function AddressInfo(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * AddressInfo multiaddr.\n * @member {Uint8Array} multiaddr\n * @memberof PeerRecord.AddressInfo\n * @instance\n */\n AddressInfo.prototype.multiaddr = $util.newBuffer([]);\n\n /**\n * Encodes the specified AddressInfo message. Does not implicitly {@link PeerRecord.AddressInfo.verify|verify} messages.\n * @function encode\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {PeerRecord.IAddressInfo} m AddressInfo message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n AddressInfo.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.multiaddr != null && Object.hasOwnProperty.call(m, \"multiaddr\"))\n w.uint32(10).bytes(m.multiaddr);\n return w;\n };\n\n /**\n * Decodes an AddressInfo message from the specified reader or buffer.\n * @function decode\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {PeerRecord.AddressInfo} AddressInfo\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n AddressInfo.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.PeerRecord.AddressInfo();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.multiaddr = r.bytes();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an AddressInfo message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {Object.} d Plain object\n * @returns {PeerRecord.AddressInfo} AddressInfo\n */\n AddressInfo.fromObject = function fromObject(d) {\n if (d instanceof $root.PeerRecord.AddressInfo)\n return d;\n var m = new $root.PeerRecord.AddressInfo();\n if (d.multiaddr != null) {\n if (typeof d.multiaddr === \"string\")\n $util.base64.decode(d.multiaddr, m.multiaddr = $util.newBuffer($util.base64.length(d.multiaddr)), 0);\n else if (d.multiaddr.length)\n m.multiaddr = d.multiaddr;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an AddressInfo message. Also converts values to other types if specified.\n * @function toObject\n * @memberof PeerRecord.AddressInfo\n * @static\n * @param {PeerRecord.AddressInfo} m AddressInfo\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n AddressInfo.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.multiaddr = \"\";\n else {\n d.multiaddr = [];\n if (o.bytes !== Array)\n d.multiaddr = $util.newBuffer(d.multiaddr);\n }\n }\n if (m.multiaddr != null && m.hasOwnProperty(\"multiaddr\")) {\n d.multiaddr = o.bytes === String ? $util.base64.encode(m.multiaddr, 0, m.multiaddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.multiaddr) : m.multiaddr;\n }\n return d;\n };\n\n /**\n * Converts this AddressInfo to JSON.\n * @function toJSON\n * @memberof PeerRecord.AddressInfo\n * @instance\n * @returns {Object.} JSON object\n */\n AddressInfo.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return AddressInfo;\n })();\n\n return PeerRecord;\n})();\n\nexport { $root as default };\n", null, null, null, "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\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: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\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\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record = {}\nexport const codes: Record = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\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'],\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 [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\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\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: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport { CID } from 'multiformats/cid'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport * as Digest from 'multiformats/hashes/digest'\nimport varint from 'varint'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 777: // memory\n return bytes2str(buf)\n\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 uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\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\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 777: // memory\n return str2bytes(str)\n\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 uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\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})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\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}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.decode.bytes)\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\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}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\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: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.decode.bytes)\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.decode.bytes)\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\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\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\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}\n\nfunction onion32bytes (str: string): Uint8Array {\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\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}\n\nfunction bytes2onion (buf: Uint8Array): string {\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", "import { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport varint from 'varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\n/**\n * string -> [[str name, str addr]... ]\n */\nexport function stringToStringTuples (str: string): string[][] {\n const tuples = []\n const parts = str.split('/').slice(1) // skip first empty elem\n if (parts.length === 1 && parts[0] === '') {\n return []\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([part])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n tuples.push([\n part,\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 cleanPath(parts.slice(p).join('/'))\n ])\n break\n }\n\n tuples.push([part, parts[p]])\n }\n\n return tuples\n}\n\n/**\n * [[str name, str addr]... ] -> string\n */\nexport function stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[str name, str addr]... ] -> [[int code, Uint8Array]... ]\n */\nexport function stringTuplesToTuples (tuples: Array): Tuple[] {\n return tuples.map((tup) => {\n if (!Array.isArray(tup)) {\n tup = [tup]\n }\n const proto = protoFromTuple(tup)\n if (tup.length > 1) {\n return [proto.code, convertToBytes(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * Convert tuples to string tuples\n *\n * [[int code, Uint8Array]... ] -> [[int code, str addr]... ]\n */\nexport function tuplesToStringTuples (tuples: Tuple[]): StringTuple[] {\n return tuples.map(tup => {\n const proto = protoFromTuple(tup)\n if (tup[1] != null) {\n return [proto.code, convertToString(proto.code, tup[1])]\n }\n return [proto.code]\n })\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return fromBytes(uint8ArrayConcat(tuples.map((tup) => {\n const proto = protoFromTuple(tup)\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n })))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nexport function sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr)\n return size + (varint.decode.bytes ?? 0)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\n/**\n * Uint8Array -> String\n */\nexport function bytesToString (buf: Uint8Array): string {\n const a = bytesToTuples(buf)\n const b = tuplesToStringTuples(a)\n return stringTuplesToString(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function stringToBytes (str: string): Uint8Array {\n str = cleanPath(str)\n const a = stringToStringTuples(str)\n const b = stringTuplesToTuples(a)\n\n return tuplesToBytes(b)\n}\n\n/**\n * String -> Uint8Array\n */\nexport function fromString (str: string): Uint8Array {\n return stringToBytes(str)\n}\n\n/**\n * Uint8Array -> Uint8Array\n */\nexport function fromBytes (buf: Uint8Array): Uint8Array {\n const err = validateBytes(buf)\n if (err != null) {\n throw err\n }\n return Uint8Array.from(buf) // copy\n}\n\nexport function validateBytes (buf: Uint8Array): Error | undefined {\n try {\n bytesToTuples(buf) // try to parse. will throw if breaks\n } catch (err: any) {\n return err\n }\n}\n\nexport function isValidBytes (buf: Uint8Array): boolean {\n return validateBytes(buf) === undefined\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport function ParseError (str: string): Error {\n return new Error('Error parsing address: ' + str)\n}\n\nexport function protoFromTuple (tup: any[]): Protocol {\n const proto = getProtocol(tup[0])\n return proto\n}\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\nimport * as codec from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport varint from 'varint'\nimport { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport errCode from 'err-code'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: string\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A Resolver is a function that takes a {@link Multiaddr} and resolves it into one\n * or more string representations of that {@link Multiaddr}.\n */\nexport interface Resolver { (addr: Multiaddr, options?: AbortOptions): Promise }\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map()\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString: () => string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON: () => string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions: () => MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos: () => Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes: () => number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames: () => string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, ], [ 6, ] ]\n * ```\n */\n tuples: () => Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples: () => StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate: (addr: MultiaddrInput) => Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate: (addr: Multiaddr | string) => Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode: (code: number) => Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId: () => string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath: () => string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals: (addr: { bytes: Uint8Array }) => boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve: (options?: AbortOptions) => Promise\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress: () => NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress: (addr?: Multiaddr) => boolean\n}\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 */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\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: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\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 DefaultMultiaddr('/' + [ip, host, transport, addr.port].join('/'))\n}\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: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\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: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass DefaultMultiaddr implements Multiaddr {\n public bytes: Uint8Array\n #string?: string\n #tuples?: Tuple[]\n #stringTuples?: StringTuple[]\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n if (addr instanceof Uint8Array) {\n this.bytes = codec.fromBytes(addr)\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 this.bytes = codec.fromString(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n this.bytes = codec.fromBytes(addr.bytes) // validate + copy buffer\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = codec.bytesToString(this.bytes)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: string | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\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\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\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\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name\n port = parseInt(value ?? '')\n }\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\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\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.protoCodes().map(code => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n const codes: number[] = []\n const buf = this.bytes\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.decode.bytes ?? 0\n\n const p = getProtocol(code)\n const size = codec.sizeForAddr(p, buf.slice(i + n))\n\n i += (size + n)\n codes.push(code)\n }\n\n return codes\n }\n\n protoNames (): string[] {\n return this.protos().map(proto => proto.name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n if (this.#tuples == null) {\n this.#tuples = codec.bytesToTuples(this.bytes)\n }\n\n return this.#tuples\n }\n\n stringTuples (): Array<[number, string?]> {\n if (this.#stringTuples == null) {\n this.#stringTuples = codec.tuplesToStringTuples(this.tuples())\n }\n\n return this.#stringTuples\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new DefaultMultiaddr(addr)\n return new DefaultMultiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\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 DefaultMultiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new DefaultMultiaddr(codec.tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n const tuples = this.stringTuples().filter((tuple) => {\n if (tuple[0] === names.ipfs.code) {\n return true\n }\n return false\n })\n\n // Get the last ipfs tuple ['ipfs', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\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\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n let path = null\n try {\n path = this.stringTuples().filter((tuple) => {\n const proto = getProtocol(tuple[0])\n if (proto.path === true) {\n return true\n }\n return false\n })[0][1]\n\n if (path == null) {\n path = null\n }\n } catch {\n path = null\n }\n return path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: AbortOptions): Promise {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER')\n }\n\n const addresses = await resolver(this, options)\n return addresses.map((a) => new DefaultMultiaddr(a))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\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\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\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 /**\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] (): string {\n return `Multiaddr(${codec.bytesToString(this.bytes)})`\n }\n}\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?: MultiaddrInput): Multiaddr {\n return new DefaultMultiaddr(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { migration as migration8 } from './migration-8/index.js'\nimport { migration as migration9 } from './migration-9/index.js'\nimport { migration as migration10 } from './migration-10/index.js'\nimport { migration as migration11 } from './migration-11/index.js'\nimport { migration as migration12 } from './migration-12/index.js'\n\n/**\n * @type {import('../types').Migration}\n */\nconst emptyMigration = {\n description: 'Empty migration.',\n // @ts-ignore\n migrate: () => {},\n // @ts-ignore\n revert: () => {},\n empty: true\n}\n\nexport default [\n Object.assign({ version: 1 }, emptyMigration),\n Object.assign({ version: 2 }, emptyMigration),\n Object.assign({ version: 3 }, emptyMigration),\n Object.assign({ version: 4 }, emptyMigration),\n Object.assign({ version: 5 }, emptyMigration),\n Object.assign({ version: 6 }, emptyMigration),\n Object.assign({ version: 7 }, emptyMigration),\n migration8,\n migration9,\n migration10,\n migration11,\n migration12\n]\n", "\nimport debug from 'debug'\nimport { CONFIG_KEY, VERSION_KEY } from '../utils.js'\nimport { MissingRepoOptionsError } from '../errors.js'\n\nconst log = debug('ipfs:repo:migrator:repo:init')\n\n/**\n * @param {import('../types').Backends} backends\n */\nexport async function isRepoInitialized (backends) {\n if (!backends) {\n throw new MissingRepoOptionsError('Please pass repo options when trying to open a repo')\n }\n\n const root = backends.root\n\n try {\n await root.open()\n const versionCheck = await root.has(VERSION_KEY)\n const configCheck = await root.has(CONFIG_KEY)\n if (!versionCheck || !configCheck) {\n log(`Version entry present: ${versionCheck}`)\n log(`Config entry present: ${configCheck}`)\n return false\n }\n\n return true\n } catch (/** @type {any} */ e) {\n log('While checking if repo is initialized error was thrown: ' + e.message)\n return false\n } finally {\n if (root !== undefined) {\n try {\n await root.close()\n } catch {}\n }\n }\n}\n", "\n/**\n * Exception raised when trying to revert migration that is not possible\n * to revert.\n */\nexport class NonReversibleMigrationError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'NonReversibleMigrationError'\n this.code = NonReversibleMigrationError.code\n this.message = message\n }\n}\nNonReversibleMigrationError.code = 'ERR_NON_REVERSIBLE_MIGRATION'\n\n/**\n * Exception raised when repo is not initialized.\n */\nexport class NotInitializedRepoError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'NotInitializedRepoError'\n this.code = NotInitializedRepoError.code\n this.message = message\n }\n}\nNotInitializedRepoError.code = 'ERR_NOT_INITIALIZED_REPO'\n\n/**\n * Exception raised when required parameter is not provided.\n */\nexport class RequiredParameterError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'RequiredParameterError'\n this.code = RequiredParameterError.code\n this.message = message\n }\n}\nRequiredParameterError.code = 'ERR_REQUIRED_PARAMETER'\n\n/**\n * Exception raised when value is not valid.\n */\nexport class InvalidValueError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'InvalidValueError'\n this.code = InvalidValueError.code\n this.message = message\n }\n}\nInvalidValueError.code = 'ERR_INVALID_VALUE'\n\n/**\n * Exception raised when config is not passed.\n */\nexport class MissingRepoOptionsError extends Error {\n /**\n * @param {string} message\n */\n constructor (message) {\n super(message)\n this.name = 'MissingRepoOptionsError'\n this.code = MissingRepoOptionsError.code\n this.message = message\n }\n}\nMissingRepoOptionsError.code = 'ERR_MISSING_REPO_OPTIONS'\n", "\nimport { isRepoInitialized } from './init.js'\nimport { MissingRepoOptionsError, NotInitializedRepoError } from '../errors.js'\nimport { VERSION_KEY } from '../utils.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\n/**\n * Function that has responsibility to retrieve version of repo from its root datastore's instance.\n * This function needs to be cross-repo-version functional to be able to fetch any version number,\n * even in case of change of repo's versioning.\n *\n * @param {import('../types').Backends} backends\n */\nexport async function getVersion (backends) {\n if (!(await isRepoInitialized(backends))) {\n throw new NotInitializedRepoError('Repo is not initialized!')\n }\n\n const store = backends.root\n await store.open()\n\n try {\n return parseInt(uint8ArrayToString(await store.get(VERSION_KEY)))\n } finally {\n await store.close()\n }\n}\n\n/**\n * Function for setting a version in cross-repo-version manner.\n *\n * @param {number} version\n * @param {import('../types').Backends} backends\n */\nexport async function setVersion (version, backends) {\n if (!backends) {\n throw new MissingRepoOptionsError('Please pass repo options when trying to open a repo')\n }\n\n const store = backends.root\n await store.open()\n await store.put(VERSION_KEY, uint8ArrayFromString(String(version)))\n await store.close()\n}\n", "/* eslint complexity: [\"error\", 28] */\n\nimport defaultMigrations from './migrations/index.js'\nimport * as repoVersion from './repo/version.js'\nimport * as Errors from './errors.js'\nimport { wrapBackends } from './utils.js'\nimport debug from 'debug'\n\nconst log = debug('ipfs:repo:migrator')\n\n/**\n * @typedef {import('./types').Migration} Migration\n * @typedef {import('./types').MigrationOptions} MigrationOptions\n * @typedef {import('./types').ProgressCallback} ProgressCallback\n * @typedef {import('./types').MigrationProgressCallback} MigrationProgressCallback\n */\n\n/**\n * Returns the version of latest migration.\n * If no migrations are present returns 0.\n *\n * @param {Migration[]} [migrations] - Array of migrations to consider. If undefined, the bundled migrations are used. Mainly for testing purpose.\n */\nexport function getLatestMigrationVersion (migrations) {\n migrations = migrations || defaultMigrations\n\n if (!Array.isArray(migrations) || migrations.length === 0) {\n return 0\n }\n\n return migrations[migrations.length - 1].version\n}\n\n/**\n * Main function to execute forward migrations.\n * It acquire lock on the provided path before doing any migrations.\n *\n * Signature of the progress callback is: function(migrationObject: object, currentMigrationNumber: int, totalMigrationsCount: int)\n *\n * @param {string} path - Path to initialized (!) JS-IPFS repo\n * @param {import('./types').Backends} backends\n * @param {import('./types').RepoOptions} repoOptions - Options that are passed to migrations, that can use them to correctly construct datastore. Options are same like for IPFSRepo.\n * @param {number} toVersion - Version to which the repo should be migrated.\n * @param {MigrationOptions} [options] - Options for migration\n */\nexport async function migrate (path, backends, repoOptions, toVersion, options = {}) {\n const ignoreLock = options.ignoreLock ?? false\n const onProgress = options.onProgress\n const isDryRun = options.isDryRun ?? false\n const migrations = options.migrations ?? defaultMigrations\n\n if (!path) {\n throw new errors.RequiredParameterError('Path argument is required!')\n }\n\n if (!repoOptions) {\n throw new errors.RequiredParameterError('repoOptions argument is required!')\n }\n\n if (!toVersion) {\n throw new errors.RequiredParameterError('toVersion argument is required!')\n }\n\n if (!Number.isInteger(toVersion) || toVersion <= 0) {\n throw new errors.InvalidValueError('Version has to be positive integer!')\n }\n\n // make sure we can read pre-level@5 datastores\n backends = wrapBackends(backends)\n\n const currentVersion = await repoVersion.getVersion(backends)\n\n if (currentVersion === toVersion) {\n log('Nothing to migrate.')\n return\n }\n\n if (currentVersion > toVersion) {\n throw new errors.InvalidValueError(`Current repo's version (${currentVersion}) is higher then toVersion (${toVersion}), you probably wanted to revert it?`)\n }\n\n verifyAvailableMigrations(migrations, currentVersion, toVersion)\n\n let lock\n\n if (!isDryRun && !ignoreLock) {\n lock = await repoOptions.repoLock.lock(path)\n }\n\n try {\n for (const migration of migrations) {\n if (toVersion !== undefined && migration.version > toVersion) {\n break\n }\n\n if (migration.version <= currentVersion) {\n continue\n }\n\n log(`Migrating version ${migration.version}`)\n\n try {\n if (!isDryRun) {\n /** @type {MigrationProgressCallback} */\n let progressCallback = () => {}\n\n if (onProgress) { // eslint-disable-line max-depth\n progressCallback = (percent, message) => onProgress(migration.version, percent.toFixed(2), message)\n }\n\n await migration.migrate(backends, progressCallback)\n }\n } catch (/** @type {any} */ e) {\n const lastSuccessfullyMigratedVersion = migration.version - 1\n\n log(`An exception was raised during execution of migration. Setting the repo's version to last successfully migrated version: ${lastSuccessfullyMigratedVersion}`)\n await repoVersion.setVersion(lastSuccessfullyMigratedVersion, backends)\n\n throw new Error(`During migration to version ${migration.version} exception was raised: ${e.stack || e.message || e}`)\n }\n\n log(`Migrating to version ${migration.version} finished`)\n }\n\n if (!isDryRun) {\n await repoVersion.setVersion(toVersion || getLatestMigrationVersion(migrations), backends)\n }\n\n log('Repo successfully migrated', toVersion !== undefined ? `to version ${toVersion}!` : 'to latest version!')\n } finally {\n if (!isDryRun && !ignoreLock && lock) {\n await lock.close()\n }\n }\n}\n\n/**\n * Main function to execute backward migration (reversion).\n * It acquire lock on the provided path before doing any migrations.\n *\n * Signature of the progress callback is: function(migrationObject: object, currentMigrationNumber: int, totalMigrationsCount: int)\n *\n * @param {string} path - Path to initialized (!) JS-IPFS repo\n * @param {import('./types').Backends} backends\n * @param {import('./types').RepoOptions} repoOptions - Options that are passed to migrations, that can use them to correctly construct datastore. Options are same like for IPFSRepo.\n * @param {number} toVersion - Version to which the repo will be reverted.\n * @param {MigrationOptions} [options] - Options for the reversion\n */\nexport async function revert (path, backends, repoOptions, toVersion, options = {}) {\n const ignoreLock = options.ignoreLock ?? false\n const onProgress = options.onProgress\n const isDryRun = options.isDryRun ?? false\n const migrations = options.migrations ?? defaultMigrations\n\n if (!path) {\n throw new errors.RequiredParameterError('Path argument is required!')\n }\n\n if (!repoOptions) {\n throw new errors.RequiredParameterError('repoOptions argument is required!')\n }\n\n if (!toVersion) {\n throw new errors.RequiredParameterError('When reverting migrations, you have to specify to which version to revert!')\n }\n\n if (!Number.isInteger(toVersion) || toVersion <= 0) {\n throw new errors.InvalidValueError('Version has to be positive integer!')\n }\n\n // make sure we can read pre-level@5 datastores\n backends = wrapBackends(backends)\n\n const currentVersion = await repoVersion.getVersion(backends)\n\n if (currentVersion === toVersion) {\n log('Nothing to revert.')\n return\n }\n\n if (currentVersion < toVersion) {\n throw new errors.InvalidValueError(`Current repo's version (${currentVersion}) is lower then toVersion (${toVersion}), you probably wanted to migrate it?`)\n }\n\n verifyAvailableMigrations(migrations, toVersion, currentVersion, true)\n\n let lock\n if (!isDryRun && !ignoreLock) {\n lock = await repoOptions.repoLock.lock(path)\n }\n\n log(`Reverting from version ${currentVersion} to ${toVersion}`)\n\n try {\n const reversedMigrationArray = migrations.slice().reverse()\n\n for (const migration of reversedMigrationArray) {\n if (migration.version <= toVersion) {\n break\n }\n\n if (migration.version > currentVersion) {\n continue\n }\n\n log(`Reverting migration version ${migration.version}`)\n\n try {\n if (!isDryRun) {\n /** @type {MigrationProgressCallback} */\n let progressCallback = () => {}\n\n if (onProgress) { // eslint-disable-line max-depth\n progressCallback = (percent, message) => onProgress(migration.version, percent.toFixed(2), message)\n }\n\n await migration.revert(backends, progressCallback)\n }\n } catch (/** @type {any} */ e) {\n const lastSuccessfullyRevertedVersion = migration.version\n log(`An exception was raised during execution of migration. Setting the repo's version to last successfully reverted version: ${lastSuccessfullyRevertedVersion}`)\n await repoVersion.setVersion(lastSuccessfullyRevertedVersion, backends)\n\n e.message = `During reversion to version ${migration.version} exception was raised: ${e.message}`\n throw e\n }\n\n log(`Reverting to version ${migration.version} finished`)\n }\n\n if (!isDryRun) {\n await repoVersion.setVersion(toVersion, backends)\n }\n\n log(`All migrations successfully reverted to version ${toVersion}!`)\n } finally {\n if (!isDryRun && !ignoreLock && lock) {\n await lock.close()\n }\n }\n}\n\n/**\n * Function checks if all migrations in given range are available.\n *\n * @param {Migration[]} migrations\n * @param {number} fromVersion\n * @param {number} toVersion\n * @param {boolean} checkReversibility - Will additionally checks if all the migrations in the range are reversible\n */\nfunction verifyAvailableMigrations (migrations, fromVersion, toVersion, checkReversibility = false) {\n let migrationCounter = 0\n for (const migration of migrations) {\n if (migration.version > toVersion) {\n break\n }\n\n if (migration.version > fromVersion) {\n if (checkReversibility && !migration.revert) {\n throw new errors.NonReversibleMigrationError(`It is not possible to revert to version ${fromVersion} because migration version ${migration.version} is not reversible. Cancelling reversion.`)\n }\n\n migrationCounter++\n }\n }\n\n if (migrationCounter !== (toVersion - fromVersion)) {\n throw new errors.InvalidValueError(`The ipfs-repo-migrations package does not have all migration to migrate from version ${fromVersion} to ${toVersion}`)\n }\n}\n\nexport const getCurrentRepoVersion = repoVersion.getVersion\nexport const errors = Errors\nexport const migrations = defaultMigrations\n", "\nimport { Key } from 'interface-datastore/key'\nimport debug from 'debug'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { getWithFallback, hasWithFallback } from './utils/level.js'\n\nconst log = debug('ipfs:repo:version')\nconst versionKey = new Key('version')\n\n/**\n *\n * @param {import('interface-datastore').Datastore} store\n */\nexport function version (store) {\n return {\n /**\n * Check if a version file exists.\n *\n */\n async exists () { // eslint-disable-line require-await\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migratiion to v10 or above\n return hasWithFallback(versionKey, store.has.bind(store), store)\n },\n /**\n * Get the current version.\n *\n * @returns {Promise}\n */\n async get () {\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migratiion to v10 or above\n const buf = await getWithFallback(versionKey, store.get.bind(store), store.has.bind(store), store)\n return parseInt(uint8ArrayToString(buf), 10)\n },\n /**\n * Set the version of the repo, writing it to the underlying store.\n *\n * @param {number} version\n * @returns {Promise}\n */\n set (version) {\n return store.put(versionKey, uint8ArrayFromString(String(version)))\n },\n /**\n * Check the current version, and returns true if versions matches\n *\n * @param {number} expected\n */\n async check (expected) {\n const version = await this.get()\n log('comparing version: %s and %s', version, expected)\n // Version 6 and 7 are the same\n // TODO: Clean up the compatibility logic. Repo feature detection would be ideal, or a better version schema\n const compatibleVersion = (version === 6 && expected === 7) || (expected === 6 && version === 7)\n\n return version === expected || compatibleVersion\n }\n }\n}\n", "/**\n * Error raised when there is lock already in place when repo is being opened.\n */\nexport class LockExistsError extends Error {\n /**\n * @param {string} [message]\n */\n constructor (message) {\n super(message)\n this.name = 'LockExistsError'\n this.code = LockExistsError.code\n }\n}\nLockExistsError.code = 'ERR_LOCK_EXISTS'\n\n/**\n * Error raised when requested item is not found.\n */\nexport class NotFoundError extends Error {\n /**\n * @param {string} [message]\n */\n constructor (message) {\n super(message)\n this.name = 'NotFoundError'\n this.code = NotFoundError.code\n }\n}\nNotFoundError.code = 'ERR_NOT_FOUND'\n\n/**\n * Error raised when version of the stored repo is not compatible with version of this package.\n */\nexport class InvalidRepoVersionError extends Error {\n /**\n * @param {string} [message]\n */\n constructor (message) {\n super(message)\n this.name = 'InvalidRepoVersionError'\n this.code = InvalidRepoVersionError.code\n }\n}\nInvalidRepoVersionError.code = 'ERR_INVALID_REPO_VERSION'\n\nexport const ERR_REPO_NOT_INITIALIZED = 'ERR_REPO_NOT_INITIALIZED'\nexport const ERR_REPO_ALREADY_OPEN = 'ERR_REPO_ALREADY_OPEN'\nexport const ERR_REPO_ALREADY_CLOSED = 'ERR_REPO_ALREADY_CLOSED'\n", "\nimport { NotFoundError } from '../errors.js'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Key} Key\n */\n\n/**\n * @param {Key} key\n * @param {function (Key): Promise} has\n * @param {Datastore} store\n * @returns {Promise}\n */\nexport async function hasWithFallback (key, has, store) {\n const result = await has(key)\n\n if (result) {\n return result\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n return false\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n resolve(Boolean(req.result))\n }\n })\n}\n\n/**\n * @param {import('interface-datastore').Key} key\n * @param {function (Key): Promise} get\n * @param {function (Key): Promise} has\n * @param {import('interface-datastore').Datastore} store\n * @returns {Promise}\n */\nexport async function getWithFallback (key, get, has, store) {\n if (await has(key)) {\n return get(key)\n }\n\n // Newer versions of level.js changed the key type from Uint8Array|string\n // to Uint8Array so fall back to trying Uint8Arrays if we are using level.js\n // and the string version of the key did not work\n const levelJs = findLevelJs(store)\n\n if (!levelJs) {\n throw new NotFoundError()\n }\n\n return new Promise((resolve, reject) => {\n // drop down to IndexDB API, otherwise level-js will monkey around with the keys/values\n // @ts-ignore\n const req = levelJs.store('readonly').get(key.toString())\n req.transaction.onabort = () => {\n reject(req.transaction.error)\n }\n req.transaction.oncomplete = () => {\n if (req.result) {\n return resolve(req.result)\n }\n\n reject(new NotFoundError())\n }\n })\n}\n\n/**\n * Level dbs wrap level dbs that wrap level dbs. Find a level-js\n * instance in the chain if one exists.\n *\n * @param {Datastore} store\n * @returns {Datastore | undefined}\n */\nfunction findLevelJs (store) {\n let db = store\n\n // @ts-ignore\n while (db.db || db.child) {\n // @ts-ignore\n db = db.db || db.child\n\n // `Level` is only present in the browser, in node it is LevelDOWN\n // @ts-ignore\n if (db.type === 'level-js' || db.constructor.name === 'Level') {\n return db\n }\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport PQueue from 'p-queue'\nimport _get from 'just-safe-get'\nimport _set from 'just-safe-set'\nimport errCode from 'err-code'\nimport { NotFoundError } from './errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { getWithFallback, hasWithFallback } from './utils/level.js'\n\n// @ts-ignore types are broken in p-queue@6.x.x - also, if we imported via esm\n// we can use the default, if via cjs we need to get the default via prop access\nconst Queue = PQueue.default ? PQueue.default : PQueue\n\nconst configKey = new Key('config')\n\n/**\n * @typedef {import('./types').Config} Config\n * @typedef {import('interface-datastore').Datastore} Datastore\n */\n\n/**\n * @param {Datastore} store\n */\nexport function config (store) {\n const setQueue = new Queue({ concurrency: 1 })\n\n const configStore = {\n /**\n * Get the current configuration from the repo.\n *\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config read\n * @returns {Promise}\n */\n async getAll (options = {}) { // eslint-disable-line require-await\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migratiion to v10 or above\n const encodedValue = await getWithFallback(configKey, store.get.bind(store), store.has.bind(store), store)\n\n return JSON.parse(uint8ArrayToString(encodedValue))\n },\n\n /**\n * Get the value for the passed configuration key from the repo.\n *\n * @param {string} key - the config key to get\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config read\n */\n async get (key, options = {}) {\n if (key == null) {\n throw new NotFoundError(`Key ${key} does not exist in config`)\n }\n\n const config = await this.getAll(options)\n const value = _get(config, key)\n\n if (value === undefined) {\n throw new NotFoundError(`Key ${key} does not exist in config`)\n }\n\n return value\n },\n\n /**\n * Set the current configuration for this repo.\n *\n * @param {string} key - the config key to be written\n * @param {any} [value] - the config value to be written\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config write\n */\n set (key, value, options = {}) {\n // @ts-ignore ts thinks key will only be a string, but it may not be\n if (typeof key !== 'string' && !(key instanceof String)) {\n throw errCode(new Error('Invalid key type: ' + typeof key), 'ERR_INVALID_KEY')\n }\n\n if (value === undefined || (value instanceof Uint8Array)) {\n throw errCode(new Error('Invalid value type: ' + typeof value), 'ERR_INVALID_VALUE')\n }\n\n return setQueue.add(() => _maybeDoSet({\n key: key,\n value: value\n }, options.signal))\n },\n\n /**\n * Set the current configuration for this repo.\n *\n * @param {Config} [value] - the config value to be written\n * @param {object} [options] - options\n * @param {AbortSignal} [options.signal] - abort this config write\n */\n replace (value, options = {}) {\n if (!value || (value instanceof Uint8Array)) {\n throw errCode(new Error('Invalid value type: ' + typeof value), 'ERR_INVALID_VALUE')\n }\n\n return setQueue.add(() => _maybeDoSet({\n key: undefined,\n value: value\n }, options.signal))\n },\n\n /**\n * Check if a config file exists.\n *\n */\n async exists () { // eslint-disable-line require-await\n // level-js@5.x cannot read keys from level-js@4.x dbs so fall back to\n // using IndexedDB API with string keys - only necessary until we do\n // the migration to v10 or above\n return hasWithFallback(configKey, store.has.bind(store), store)\n }\n }\n\n return configStore\n\n /**\n * @param {{ key: any; value: any; }} m\n * @param {AbortSignal | undefined} signal\n */\n async function _maybeDoSet (m, signal) {\n if (signal && signal.aborted) {\n return\n }\n\n const key = m.key\n const value = m.value\n if (key) {\n const config = await configStore.getAll()\n if (typeof config === 'object' && config !== null) {\n _set(config, key, value)\n }\n return _saveAll(config)\n }\n return _saveAll(value)\n }\n\n /**\n * @param {unknown} config\n */\n function _saveAll (config) {\n const buf = uint8ArrayFromString(JSON.stringify(config, null, 2))\n return store.put(configKey, buf)\n }\n}\n", "export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n", "import isPlainObject from 'is-plain-obj';\n\nexport default function sortKeys(object, options = {}) {\n\tif (!isPlainObject(object) && !Array.isArray(object)) {\n\t\tthrow new TypeError('Expected a plain object or array');\n\t}\n\n\tconst {deep, compare} = options;\n\tconst seenInput = [];\n\tconst seenOutput = [];\n\n\tconst deepSortArray = array => {\n\t\tconst seenIndex = seenInput.indexOf(array);\n\t\tif (seenIndex !== -1) {\n\t\t\treturn seenOutput[seenIndex];\n\t\t}\n\n\t\tconst result = [];\n\t\tseenInput.push(array);\n\t\tseenOutput.push(result);\n\n\t\tresult.push(...array.map(item => {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\treturn deepSortArray(item);\n\t\t\t}\n\n\t\t\tif (isPlainObject(item)) {\n\t\t\t\treturn _sortKeys(item);\n\t\t\t}\n\n\t\t\treturn item;\n\t\t}));\n\n\t\treturn result;\n\t};\n\n\tconst _sortKeys = object => {\n\t\tconst seenIndex = seenInput.indexOf(object);\n\t\tif (seenIndex !== -1) {\n\t\t\treturn seenOutput[seenIndex];\n\t\t}\n\n\t\tconst result = {};\n\t\tconst keys = Object.keys(object).sort(compare);\n\n\t\tseenInput.push(object);\n\t\tseenOutput.push(result);\n\n\t\tfor (const key of keys) {\n\t\t\tconst value = object[key];\n\t\t\tlet newValue;\n\n\t\t\tif (deep && Array.isArray(value)) {\n\t\t\t\tnewValue = deepSortArray(value);\n\t\t\t} else {\n\t\t\t\tnewValue = deep && isPlainObject(value) ? _sortKeys(value) : value;\n\t\t\t}\n\n\t\t\tObject.defineProperty(result, key, {\n\t\t\t\t...Object.getOwnPropertyDescriptor(object, key),\n\t\t\t\tvalue: newValue\n\t\t\t});\n\t\t}\n\n\t\treturn result;\n\t};\n\n\tif (Array.isArray(object)) {\n\t\treturn deep ? deepSortArray(object) : object.slice();\n\t}\n\n\treturn _sortKeys(object);\n}\n", "\nimport { Key } from 'interface-datastore'\nimport sortKeys from 'sort-keys'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst specKey = new Key('datastore_spec')\n\n/**\n *\n * @param {import('interface-datastore').Datastore} store\n */\nexport function spec (store) {\n return {\n /**\n * Check if a datastore spec file exists.\n *\n */\n exists () {\n return store.has(specKey)\n },\n /**\n * Get the current datastore spec.\n *\n * @returns {Promise}\n */\n async get () {\n const buf = await store.get(specKey)\n return JSON.parse(uint8ArrayToString(buf))\n },\n /**\n * Set the datastore spec of the repo, writing it to the underlying store.\n * TODO unclear on what the type should be or if it's required\n *\n * @param {any} spec\n * @returns {Promise}\n */\n async set (spec) {\n return store.put(specKey, uint8ArrayFromString(JSON.stringify(sortKeys(spec, { deep: true }))))\n }\n }\n}\n", "\nimport { Key } from 'interface-datastore/key'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst apiFile = new Key('api')\n\n/**\n *\n * @param {import('interface-datastore').Datastore} store\n */\nexport function apiAddr (store) {\n return {\n /**\n * Get the current configuration from the repo.\n *\n * @returns {Promise}\n */\n async get () {\n const value = await store.get(apiFile)\n return value && value.toString()\n },\n /**\n * Set the current configuration for this repo.\n * TODO: fix find the proper type or remove this API\n *\n * @param {string} value - the api address to be written\n */\n set (value) {\n return store.put(apiFile, uint8ArrayFromString(value.toString()))\n },\n /**\n * Deletes api file\n */\n delete () {\n return store.delete(apiFile)\n }\n }\n}\n", "\nimport filter from 'it-filter'\nimport { pushable } from 'it-pushable'\nimport drain from 'it-drain'\nimport { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\nimport { identity } from 'multiformats/hashes/identity'\n\n/**\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} DatastoreOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n */\n\n/**\n * @param {Blockstore} store\n * @returns {Blockstore}\n */\nexport function createIdStore (store) {\n return {\n open () {\n return store.open()\n },\n\n close () {\n return store.close()\n },\n\n query (query, options) {\n return store.query(query, options)\n },\n\n queryKeys (query, options) {\n return store.queryKeys(query, options)\n },\n\n async get (cid, options) {\n const extracted = extractContents(cid)\n if (extracted.isIdentity) {\n return Promise.resolve(extracted.digest)\n }\n return store.get(cid, options)\n },\n\n async * getMany (cids, options) {\n for await (const cid of cids) {\n yield this.get(cid, options)\n }\n },\n\n async put (cid, buf, options) {\n const { isIdentity } = extractContents(cid)\n\n if (isIdentity) {\n return\n }\n\n await store.put(cid, buf, options)\n },\n\n async * putMany (pairs, options) {\n // in order to return all blocks. we're going to assemble a seperate iterable\n // return rather than return the resolves of store.putMany using the same\n // process used by blockstore.putMany\n const output = pushable({\n objectMode: true\n })\n\n // process.nextTick runs on the microtask queue, setImmediate runs on the next\n // event loop iteration so is slower. Use process.nextTick if it is available.\n const runner = globalThis.process && globalThis.process.nextTick ? globalThis.process.nextTick : (globalThis.setImmediate || globalThis.setTimeout)\n\n runner(async () => {\n try {\n await drain(store.putMany(async function * () {\n for await (const { key, value } of pairs) {\n if (!extractContents(key).isIdentity) {\n yield { key, value }\n }\n\n // if non identity blocks successfully write, blocks are included in output\n output.push({ key, value })\n }\n }()))\n\n output.end()\n } catch (/** @type {any} */ err) {\n output.end(err)\n }\n })\n\n yield * output\n },\n\n has (cid, options) {\n const { isIdentity } = extractContents(cid)\n if (isIdentity) {\n return Promise.resolve(true)\n }\n return store.has(cid, options)\n },\n\n delete (cid, options) {\n const { isIdentity } = extractContents(cid)\n if (isIdentity) {\n return Promise.resolve()\n }\n return store.delete(cid, options)\n },\n\n deleteMany (cids, options) {\n return store.deleteMany(filter(cids, (cid) => !extractContents(cid).isIdentity), options)\n },\n\n batch () {\n const batch = store.batch()\n\n return {\n put (cid, buf) {\n const { isIdentity } = extractContents(cid)\n\n if (isIdentity) {\n return\n }\n\n batch.put(cid, buf)\n },\n delete (cid) {\n const { isIdentity } = extractContents(cid)\n\n if (isIdentity) {\n return\n }\n\n batch.delete(cid)\n },\n commit: (options) => {\n return batch.commit(options)\n }\n }\n }\n }\n}\n\n/**\n * @param {CID} k\n * @returns {{ isIdentity: false } | { isIdentity: true, digest: Uint8Array}}\n */\nfunction extractContents (k) {\n const cid = CID.asCID(k)\n\n if (cid == null) {\n throw errCode(new Error('Not a valid cid'), 'ERR_INVALID_CID')\n }\n\n if (cid.multihash.code !== identity.code) {\n return {\n isIdentity: false\n }\n }\n\n return {\n isIdentity: true,\n digest: cid.multihash.digest\n }\n}\n", "\nimport { LockExistsError } from '../errors.js'\nimport debug from 'debug'\n\nconst log = debug('ipfs:repo:lock:memory')\nconst lockFile = 'repo.lock'\n\n/** @type {Record} */\nconst LOCKS = {}\n\n/**\n * @typedef {import('../types').LockCloser} LockCloser\n */\n\n/**\n * Lock the repo in the given dir.\n *\n * @param {string} dir\n * @returns {Promise}\n */\nasync function lock (dir) {\n const file = dir + '/' + lockFile\n log('locking %s', file)\n\n if (LOCKS[file] === true) {\n throw new LockExistsError(`Lock already being held for file: ${file}`)\n }\n\n LOCKS[file] = true\n const closer = {\n async close () {\n if (LOCKS[file]) {\n delete LOCKS[file]\n }\n }\n }\n return closer\n}\n\n/**\n * Check if the repo in the given directory is locked.\n *\n * @param {string} dir\n * @returns {Promise}\n */\nasync function locked (dir) {\n const file = dir + '/' + lockFile\n log(`checking lock: ${file}`)\n\n return Boolean(LOCKS[file])\n}\n\nexport const MemoryLock = {\n lock,\n locked\n}\n", "import { MemoryLock } from './locks/memory.js'\n\n/**\n * @type {Partial}\n */\nexport default {\n autoMigrate: true,\n onMigrationProgress: () => {},\n repoOwner: true,\n repoLock: MemoryLock\n}\n", "\n// Default configuration for the datastore spec in node.js\nexport default {\n Spec: {\n type: 'mount',\n mounts: [\n {\n mountpoint: '/blocks',\n type: 'measure',\n prefix: 'flatfs.datastore',\n child: {\n type: 'flatfs',\n path: 'blocks',\n sync: true,\n shardFunc: '/repo/flatfs/shard/v1/next-to-last/2'\n }\n },\n {\n mountpoint: '/',\n type: 'measure',\n prefix: 'leveldb.datastore',\n child: {\n type: 'levelds',\n path: 'datastore',\n compression: 'none'\n }\n }\n ]\n }\n}\n", "/* eslint max-nested-callbacks: [\"error\", 8] */\n\nimport { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\nimport debug from 'debug'\nimport first from 'it-first'\nimport { createUnsafe } from 'multiformats/block'\nimport * as cborg from 'cborg'\nimport * as dagPb from '@ipld/dag-pb'\nimport {\n cidToKey,\n keyToMultihash\n} from './utils/blockstore.js'\nimport { walkDag } from './utils/walk-dag.js'\nimport { PinTypes } from './pin-types.js'\nimport QuickLRU from 'quick-lru'\n\n/**\n * @typedef {import('./types').PinType} PinType\n * @typedef {import('./types').PinQueryType} PinQueryType\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('./types').PinOptions} PinOptions\n * @typedef {import('./types').AbortOptions} AbortOptions\n * @typedef {import('./types').Pins} Pins\n */\n\n/**\n * @typedef {object} PinInternal\n * @property {number} depth\n * @property {import('multiformats/cid').Version} [version]\n * @property {number} [codec]\n * @property {Record} [metadata]\n */\n\n/**\n * @typedef {object} FetchCompleteDagOptions\n * @property {AbortSignal} [signal]\n * @property {number} [cidCacheMaxSize]\n */\n\nconst CID_CACHE_MAX_SIZE = 2048\n\n/**\n * @param {string} type\n */\nfunction invalidPinTypeErr (type) {\n const errMsg = `Invalid type '${type}', must be one of {direct, indirect, recursive, all}`\n return errCode(new Error(errMsg), 'ERR_INVALID_PIN_TYPE')\n}\n\n/**\n * @implements {Pins}\n */\nexport class PinManager {\n /**\n * @param {object} config\n * @param {import('interface-datastore').Datastore} config.pinstore\n * @param {import('interface-blockstore').Blockstore} config.blockstore\n * @param {import('./types').loadCodec} config.loadCodec\n */\n constructor ({ pinstore, blockstore, loadCodec }) {\n this.pinstore = pinstore\n this.blockstore = blockstore\n this.loadCodec = loadCodec\n this.log = debug('ipfs:repo:pin')\n this.directPins = new Set()\n this.recursivePins = new Set()\n }\n\n /**\n * @param {CID} cid\n * @param {PinOptions & AbortOptions} [options]\n */\n async pinDirectly (cid, options = {}) {\n await this.blockstore.get(cid, options)\n\n /** @type {PinInternal} */\n const pin = {\n depth: 0\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n if (options.metadata) {\n pin.metadata = options.metadata\n }\n\n return this.pinstore.put(cidToKey(cid), cborg.encode(pin))\n }\n\n /**\n * @param {CID} cid\n * @param {AbortOptions} [options]\n */\n unpin (cid, options) {\n return this.pinstore.delete(cidToKey(cid), options)\n }\n\n /**\n * @param {CID} cid\n * @param {PinOptions & FetchCompleteDagOptions & AbortOptions} [options]\n */\n async pinRecursively (cid, options = {}) {\n await this.fetchCompleteDag(cid, options)\n\n /** @type {PinInternal} */\n const pin = {\n depth: Infinity\n }\n\n if (cid.version !== 0) {\n pin.version = cid.version\n }\n\n if (cid.code !== dagPb.code) {\n pin.codec = cid.code\n }\n\n if (options.metadata) {\n pin.metadata = options.metadata\n }\n\n await this.pinstore.put(cidToKey(cid), cborg.encode(pin))\n }\n\n /**\n * @param {AbortOptions} [options]\n */\n async * directKeys (options) {\n for await (const entry of this.pinstore.query({\n filters: [(entry) => {\n const pin = cborg.decode(entry.value)\n\n return pin.depth === 0\n }]\n })) {\n const pin = cborg.decode(entry.value)\n const version = pin.version || 0\n const codec = pin.codec != null ? pin.codec : dagPb.code\n const multihash = keyToMultihash(entry.key)\n\n yield {\n cid: CID.create(version, codec, multihash),\n metadata: pin.metadata\n }\n }\n }\n\n /**\n * @param {AbortOptions} [options]\n */\n async * recursiveKeys (options) {\n for await (const entry of this.pinstore.query({\n filters: [(entry) => {\n const pin = cborg.decode(entry.value)\n\n return pin.depth === Infinity\n }]\n })) {\n const pin = cborg.decode(entry.value)\n const version = pin.version || 0\n const codec = pin.codec != null ? pin.codec : dagPb.code\n const multihash = keyToMultihash(entry.key)\n\n yield {\n cid: CID.create(version, codec, multihash),\n metadata: pin.metadata\n }\n }\n }\n\n /**\n * @param {AbortOptions} [options]\n */\n async * indirectKeys (options) {\n for await (const { cid } of this.recursiveKeys()) {\n for await (const childCid of walkDag(cid, this.blockstore, this.loadCodec, options)) {\n // recursive pins override indirect pins\n const types = [\n PinTypes.recursive\n ]\n\n const result = await this.isPinnedWithType(childCid, types)\n\n if (result.pinned) {\n continue\n }\n\n yield childCid\n }\n }\n }\n\n /**\n * @param {CID} cid\n * @param {PinQueryType|PinQueryType[]} types\n * @param {AbortOptions} [options]\n */\n async isPinnedWithType (cid, types, options) {\n if (!Array.isArray(types)) {\n types = [types]\n }\n\n const all = types.includes(PinTypes.all)\n const direct = types.includes(PinTypes.direct)\n const recursive = types.includes(PinTypes.recursive)\n const indirect = types.includes(PinTypes.indirect)\n\n if (recursive || direct || all) {\n const result = await first(this.pinstore.query({\n prefix: cidToKey(cid).toString(),\n filters: [entry => {\n if (all) {\n return true\n }\n\n const pin = cborg.decode(entry.value)\n\n return types.includes(pin.depth === 0 ? PinTypes.direct : PinTypes.recursive)\n }],\n limit: 1\n }))\n\n if (result) {\n const pin = cborg.decode(result.value)\n\n return {\n cid,\n pinned: true,\n reason: pin.depth === 0 ? PinTypes.direct : PinTypes.recursive,\n metadata: pin.metadata\n }\n }\n }\n\n const self = this\n\n /**\n * @param {CID} key\n * @param {AsyncIterable<{ cid: CID, metadata: any }>} source\n */\n async function * findChild (key, source) {\n for await (const { cid: parentCid } of source) {\n for await (const childCid of walkDag(parentCid, self.blockstore, self.loadCodec)) {\n if (childCid.equals(key)) {\n yield parentCid\n return\n }\n }\n }\n }\n\n if (all || indirect) {\n // indirect (default)\n // check each recursive key to see if multihash is under it\n\n const parentCid = await first(findChild(cid, this.recursiveKeys()))\n\n if (parentCid) {\n return {\n cid,\n pinned: true,\n reason: PinTypes.indirect,\n parent: parentCid\n }\n }\n }\n\n return {\n cid,\n pinned: false\n }\n }\n\n /**\n * @param {CID} cid\n * @param {FetchCompleteDagOptions} [options]\n */\n async fetchCompleteDag (cid, options = {}) {\n const seen = new QuickLRU({ maxSize: options.cidCacheMaxSize ?? CID_CACHE_MAX_SIZE })\n\n /**\n * @param {CID} cid\n * @param {AbortOptions} options\n */\n const walkDag = async (cid, options) => {\n if (seen.has(cid.toString())) {\n return\n }\n\n seen.set(cid.toString(), true)\n\n const bytes = await this.blockstore.get(cid, options)\n const codec = await this.loadCodec(cid.code)\n const block = createUnsafe({ bytes, cid, codec })\n\n await Promise.all(\n [...block.links()].map(([, childCid]) => walkDag(childCid, options))\n )\n }\n\n await walkDag(cid, options)\n }\n\n /**\n * Throws an error if the pin type is invalid\n *\n * @param {any} type\n * @returns {type is PinType}\n */\n static checkPinType (type) {\n if (typeof type !== 'string' || !Object.keys(PinTypes).includes(type)) {\n throw invalidPinTypeErr(type)\n }\n return true\n }\n}\n", "\n/**\n * Returns the first result from an (async) iterable, unless empty, in which\n * case returns `undefined`\n */\nexport default async function first (source: AsyncIterable|Iterable): Promise {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry\n }\n\n return undefined\n}\n", "import { bytes as binary, CID } from './index.js'\n// Linter can see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\n\nfunction readonly ({ enumerable = true, configurable = false } = {}) {\n return { enumerable, configurable, writable: false }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable<[string, CID]>}\n */\nfunction * linksWithin (path, value) {\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n if (cid) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n if (cid) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable<[string, CID]>}\n */\nfunction * links (source, base) {\n if (source == null || source instanceof Uint8Array) {\n return\n }\n const cid = CID.asCID(source)\n if (cid) {\n yield [base.join('/'), cid]\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield * linksWithin(path, value)\n }\n}\n\n/**\n * @param {[string|number, string]} path\n * @param {any} value\n * @returns {Iterable}\n */\nfunction * treeWithin (path, value) {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n yield elementPath.join('/')\n if (typeof element === 'object' && !CID.asCID(element)) {\n yield * tree(element, elementPath)\n }\n }\n } else {\n yield * tree(value, path)\n }\n}\n\n/**\n * @template T\n * @param {T} source\n * @param {Array} base\n * @returns {Iterable}\n */\nfunction * tree (source, base) {\n if (source == null || typeof source !== 'object') {\n return\n }\n for (const [key, value] of Object.entries(source)) {\n const path = /** @type {[string|number, string]} */ ([...base, key])\n yield path.join('/')\n if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && !CID.asCID(value)) {\n yield * treeWithin(path, value)\n }\n }\n}\n\n/**\n *\n * @template T\n * @param {T} source\n * @param {string[]} path\n * @returns {API.BlockCursorView}\n */\nfunction get (source, path) {\n let node = /** @type {Record} */(source)\n for (const [index, key] of path.entries()) {\n node = node[key]\n if (node == null) {\n throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)\n }\n const cid = CID.asCID(node)\n if (cid) {\n return { value: cid, remaining: path.slice(index + 1).join('/') }\n }\n }\n return { value: node }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} C - multicodec code corresponding to codec used to encode the block\n * @template {number} A - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @implements {API.BlockView}\n */\nclass Block {\n /**\n * @param {object} options\n * @param {CID} options.cid\n * @param {API.ByteView} options.bytes\n * @param {T} options.value\n */\n constructor ({ cid, bytes, value }) {\n if (!cid || !bytes || typeof value === 'undefined') { throw new Error('Missing required argument') }\n\n this.cid = cid\n this.bytes = bytes\n this.value = value\n this.asBlock = this\n\n // Mark all the properties immutable\n Object.defineProperties(this, {\n cid: readonly(),\n bytes: readonly(),\n value: readonly(),\n asBlock: readonly()\n })\n }\n\n links () {\n return links(this.value, [])\n }\n\n tree () {\n return tree(this.value, [])\n }\n\n /**\n *\n * @param {string} [path]\n * @returns {API.BlockCursorView}\n */\n get (path = '/') {\n return get(this.value, path.split('/').filter(Boolean))\n }\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {T} options.value\n * @param {API.BlockEncoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function encode ({ value, codec, hasher }) {\n if (typeof value === 'undefined') throw new Error('Missing required argument \"value\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const bytes = codec.encode(value)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(\n 1,\n codec.code,\n hash\n )\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @param {object} options\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function decode ({ bytes, codec, hasher }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')\n\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n /** @type {CID} */\n const cid = CID.create(1, codec.code, hash)\n\n return new Block({ value, bytes, cid })\n}\n\n/**\n * @typedef {object} RequiredCreateOptions\n * @property {CID} options.cid\n */\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {{ cid: API.Link, value:T, codec?: API.BlockDecoder, bytes: API.ByteView }|{cid:API.Link, bytes:API.ByteView, value?:void, codec:API.BlockDecoder}} options\n * @returns {API.BlockView}\n */\nfunction createUnsafe ({ bytes, cid, value: maybeValue, codec }) {\n const value = maybeValue !== undefined\n ? maybeValue\n : (codec && codec.decode(bytes))\n\n if (value === undefined) throw new Error('Missing required argument, must either provide \"value\" or \"codec\"')\n\n return new Block({\n // eslint-disable-next-line object-shorthand\n cid: /** @type {CID} */ (cid),\n bytes,\n value\n })\n}\n\n/**\n * @template {unknown} T - Logical type of the data encoded in the block\n * @template {number} Code - multicodec code corresponding to codec used to encode the block\n * @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template {API.Version} V - CID version\n * @param {object} options\n * @param {API.Link} options.cid\n * @param {API.ByteView} options.bytes\n * @param {API.BlockDecoder} options.codec\n * @param {API.MultihashHasher} options.hasher\n * @returns {Promise>}\n */\nasync function create ({ bytes, cid, hasher, codec }) {\n if (!bytes) throw new Error('Missing required argument \"bytes\"')\n if (!hasher) throw new Error('Missing required argument \"hasher\"')\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error('CID hash does not match bytes')\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec\n })\n}\n\nexport { encode, decode, create, createUnsafe, Block }\n", "import { Key } from 'interface-datastore/key'\nimport { CID } from 'multiformats'\nimport * as raw from 'multiformats/codecs/raw'\nimport errCode from 'err-code'\nimport { base32 } from 'multiformats/bases/base32'\nimport * as Digest from 'multiformats/hashes/digest'\n\n/**\n * Transform a cid to the appropriate datastore key.\n *\n * @param {CID} c\n */\nexport function cidToKey (c) {\n const cid = CID.asCID(c)\n\n if (cid == null) {\n throw errCode(new Error('Not a valid cid'), 'ERR_INVALID_CID')\n }\n\n const encoded = base32.encode(cid.multihash.bytes)\n\n return new Key('/' + encoded.slice(1).toUpperCase(), false)\n}\n\n/**\n * Transform a datastore Key instance to a CID\n * As Key is a multihash of the CID, it is reconstructed using IPLD's RAW codec.\n * Hence it is highly probable that stored CID will differ from a CID retrieved from blockstore.\n *\n * @param {Key} key\n */\nexport function keyToCid (key) {\n // Block key is of the form /\n return CID.createV1(raw.code, keyToMultihash(key))\n}\n\n/**\n * @param {Key | string} key\n */\nexport function keyToMultihash (key) {\n return Digest.decode(base32.decode(`b${key.toString().toLowerCase().substring(1)}`))\n}\n", "import debug from 'debug'\nimport { createUnsafe } from 'multiformats/block'\n\nconst log = debug('ipfs:repo:utils:walk-dag')\n\n/**\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('../types').loadCodec} loadCodec\n * @typedef {import('../types').AbortOptions} AbortOptions\n */\n\n/**\n * @param {CID} cid\n * @param {Blockstore} blockstore\n * @param {loadCodec} loadCodec\n * @param {AbortOptions} [options]\n * @returns {AsyncGenerator}\n */\nexport async function * walkDag (cid, blockstore, loadCodec, options) {\n try {\n const bytes = await blockstore.get(cid, options)\n const codec = await loadCodec(cid.code)\n const block = createUnsafe({ bytes, cid, codec })\n\n for (const [, childCid] of block.links()) {\n yield childCid\n yield * walkDag(childCid, blockstore, loadCodec, options)\n }\n } catch (/** @type {any} */ err) {\n log('Could not walk DAG for CID', cid.toString(), err)\n\n throw err\n }\n}\n", "export default class QuickLRU extends Map {\n\tconstructor(options = {}) {\n\t\tsuper();\n\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tif (typeof options.maxAge === 'number' && options.maxAge === 0) {\n\t\t\tthrow new TypeError('`maxAge` must be a number greater than 0');\n\t\t}\n\n\t\t// TODO: Use private class fields when ESLint supports them.\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.maxAge = options.maxAge || Number.POSITIVE_INFINITY;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t// TODO: Use private class methods when targeting Node.js 16.\n\t_emitEvictions(cache) {\n\t\tif (typeof this.onEviction !== 'function') {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const [key, item] of cache) {\n\t\t\tthis.onEviction(key, item.value);\n\t\t}\n\t}\n\n\t_deleteIfExpired(key, item) {\n\t\tif (typeof item.expiry === 'number' && item.expiry <= Date.now()) {\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tthis.onEviction(key, item.value);\n\t\t\t}\n\n\t\t\treturn this.delete(key);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t_getOrDeleteIfExpired(key, item) {\n\t\tconst deleted = this._deleteIfExpired(key, item);\n\t\tif (deleted === false) {\n\t\t\treturn item.value;\n\t\t}\n\t}\n\n\t_getItemValue(key, item) {\n\t\treturn item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;\n\t}\n\n\t_peek(key, cache) {\n\t\tconst item = cache.get(key);\n\n\t\treturn this._getItemValue(key, item);\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\t\t\tthis._emitEvictions(this.oldCache);\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\t_moveToRecent(key, item) {\n\t\tthis.oldCache.delete(key);\n\t\tthis._set(key, item);\n\t}\n\n\t* _entriesAscending() {\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield item;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.cache) {\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\tconst item = this.cache.get(key);\n\n\t\t\treturn this._getItemValue(key, item);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst item = this.oldCache.get(key);\n\t\t\tif (this._deleteIfExpired(key, item) === false) {\n\t\t\t\tthis._moveToRecent(key, item);\n\t\t\t\treturn item.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tset(key, value, {maxAge = this.maxAge} = {}) {\n\t\tconst expiry =\n\t\t\ttypeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?\n\t\t\t\tDate.now() + maxAge :\n\t\t\t\tundefined;\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, {\n\t\t\t\tvalue,\n\t\t\t\texpiry\n\t\t\t});\n\t\t} else {\n\t\t\tthis._set(key, {value, expiry});\n\t\t}\n\t}\n\n\thas(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn !this._deleteIfExpired(key, this.cache.get(key));\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn !this._deleteIfExpired(key, this.oldCache.get(key));\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this._peek(key, this.cache);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this._peek(key, this.oldCache);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\tresize(newSize) {\n\t\tif (!(newSize && newSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tconst items = [...this._entriesAscending()];\n\t\tconst removeCount = items.length - newSize;\n\t\tif (removeCount < 0) {\n\t\t\tthis.cache = new Map(items);\n\t\t\tthis.oldCache = new Map();\n\t\t\tthis._size = items.length;\n\t\t} else {\n\t\t\tif (removeCount > 0) {\n\t\t\t\tthis._emitEvictions(items.slice(0, removeCount));\n\t\t\t}\n\n\t\t\tthis.oldCache = new Map(items.slice(removeCount));\n\t\t\tthis.cache = new Map();\n\t\t\tthis._size = 0;\n\t\t}\n\n\t\tthis.maxSize = newSize;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield [key, value.value];\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t* entriesDescending() {\n\t\tlet items = [...this.cache];\n\t\tfor (let i = items.length - 1; i >= 0; --i) {\n\t\t\tconst item = items[i];\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield [key, value.value];\n\t\t\t}\n\t\t}\n\n\t\titems = [...this.oldCache];\n\t\tfor (let i = items.length - 1; i >= 0; --i) {\n\t\t\tconst item = items[i];\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t* entriesAscending() {\n\t\tfor (const [key, value] of this._entriesAscending()) {\n\t\t\tyield [key, value.value];\n\t\t}\n\t}\n\n\tget size() {\n\t\tif (!this._size) {\n\t\t\treturn this.oldCache.size;\n\t\t}\n\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n\n\tentries() {\n\t\treturn this.entriesAscending();\n\t}\n\n\tforEach(callbackFunction, thisArgument = this) {\n\t\tfor (const [key, value] of this.entriesAscending()) {\n\t\t\tcallbackFunction.call(thisArgument, value, key, this);\n\t\t}\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn JSON.stringify([...this.entriesAscending()]);\n\t}\n}\n", "\nimport map from 'it-map'\nimport errCode from 'err-code'\nimport { PinTypes } from './pin-types.js'\n\n/**\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Options} DatastoreOptions\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('./pin-manager').Pins} Pins\n */\n\n/**\n * @param {Pins} pins\n * @param {Blockstore} store\n * @returns {Blockstore}\n */\nexport function createPinnedBlockstore (pins, store) {\n return {\n open () {\n return store.open()\n },\n\n close () {\n return store.close()\n },\n\n query (query, options) {\n return store.query(query, options)\n },\n\n queryKeys (query, options) {\n return store.queryKeys(query, options)\n },\n\n async get (cid, options) {\n return store.get(cid, options)\n },\n\n async * getMany (cids, options) {\n yield * store.getMany(cids, options)\n },\n\n async put (cid, buf, options) {\n await store.put(cid, buf, options)\n },\n\n async * putMany (pairs, options) {\n yield * store.putMany(pairs, options)\n },\n\n has (cid, options) {\n return store.has(cid, options)\n },\n\n async delete (cid, options) {\n await ensureNotPinned(cid, pins)\n\n return store.delete(cid, options)\n },\n\n deleteMany (cids, options) {\n return store.deleteMany(map(cids, async cid => {\n await ensureNotPinned(cid, pins)\n\n return cid\n }), options)\n },\n\n batch () {\n return store.batch()\n }\n }\n}\n\n/**\n * @param {CID} cid\n * @param {Pins} pins\n */\nasync function ensureNotPinned (cid, pins) {\n const { pinned, reason } = await pins.isPinnedWithType(cid, PinTypes.all)\n\n if (pinned) {\n throw errCode(new Error(`pinned: ${reason}`), 'ERR_BLOCK_PINNED')\n }\n}\n", "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 cancelablePromise = 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 (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\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\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} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\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", "\nexport 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'\n\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", "import { nanoid } from 'nanoid'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport observer from 'observable-webworkers'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n return await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return await new Promise((resolve) => {\n const listener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\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\n return emitter\n }\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", "import PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock: () => Promise\n writeLock: () => Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock: (name: string, options: MorticeOptions) => Mortice['readLock']\n writeLock: (name: string, options: MorticeOptions) => Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => await pTimeout((async () => {\n return await new Promise((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return await p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\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 await createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\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\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 return await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return await 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\n return await createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler: () => Promise\n}\n\nexport default function createMortice (options?: MorticeOptions) {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n", "\nimport { CID } from 'multiformats/cid'\nimport debug from 'debug'\nimport { notFoundError } from 'datastore-core/errors'\nimport parallelBatch from 'it-parallel-batch'\nimport { pipe } from 'it-pipe'\nimport merge from 'it-merge'\nimport map from 'it-map'\nimport filter from 'it-filter'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { walkDag } from './utils/walk-dag.js'\n\nconst log = debug('ipfs:repo:gc')\nconst ERR_NOT_FOUND = notFoundError().code\n\n// Limit on the number of parallel block remove operations\nconst BLOCK_RM_CONCURRENCY = 256\n\nconst MFS_ROOT_KEY = new Key('/local/filesroot')\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('./types').loadCodec} loadCodec\n * @typedef {import('./types').GCErrorResult} GCErrorResult\n * @typedef {import('./types').GCSuccessResult} GCSuccessResult\n */\n\n/**\n * Perform mark and sweep garbage collection\n *\n * @param {object} config\n * @param {import('./types').GCLock} config.gcLock\n * @param {import('./types').Pins} config.pins\n * @param {Blockstore} config.blockstore\n * @param {import('interface-datastore').Datastore} config.root\n * @param {loadCodec} config.loadCodec\n */\nexport function gc ({ gcLock, pins, blockstore, root, loadCodec }) {\n /**\n * @returns {AsyncGenerator}\n */\n async function * gc () {\n const start = Date.now()\n log('Creating set of marked blocks')\n\n const release = await gcLock.writeLock()\n\n try {\n // Mark all blocks that are being used\n const markedSet = await createMarkedSet({ pins, blockstore, root, loadCodec })\n // Get all blocks keys from the blockstore\n const blockKeys = blockstore.queryKeys({})\n\n // Delete blocks that are not being used\n // @ts-ignore ts cannot tell that we filter out null results\n yield * deleteUnmarkedBlocks({ blockstore }, markedSet, blockKeys)\n\n log(`Complete (${Date.now() - start}ms)`)\n } finally {\n release()\n }\n }\n\n return gc\n}\n\n/**\n * Get Set of CIDs of blocks to keep\n *\n * @param {object} config\n * @param {import('./pin-manager').Pins} config.pins\n * @param {import('interface-blockstore').Blockstore} config.blockstore\n * @param {import('interface-datastore').Datastore} config.root\n * @param {loadCodec} config.loadCodec\n */\nasync function createMarkedSet ({ pins, blockstore, loadCodec, root }) {\n const mfsSource = (async function * () {\n let mh\n try {\n mh = await root.get(MFS_ROOT_KEY)\n } catch (/** @type {any} */ err) {\n if (err.code === ERR_NOT_FOUND) {\n log('No blocks in MFS')\n return\n }\n\n throw err\n }\n\n const rootCid = CID.decode(mh)\n yield rootCid\n yield * walkDag(rootCid, blockstore, loadCodec)\n })()\n\n const pinsSource = merge(\n map(pins.recursiveKeys(), ({ cid }) => cid),\n pins.indirectKeys(),\n map(pins.directKeys(), ({ cid }) => cid),\n mfsSource\n )\n\n const output = new Set()\n\n for await (const cid of merge(pinsSource, mfsSource)) {\n output.add(base32.encode(cid.multihash.bytes))\n }\n\n return output\n}\n\n/**\n * Delete all blocks that are not marked as in use\n *\n * @param {object} arg\n * @param {Blockstore} arg.blockstore\n * @param {Set} markedSet\n * @param {AsyncIterable} blockKeys\n */\nasync function * deleteUnmarkedBlocks ({ blockstore }, markedSet, blockKeys) {\n // Iterate through all blocks and find those that are not in the marked set\n // blockKeys yields { key: Key() }\n let blocksCount = 0\n let removedBlocksCount = 0\n\n /**\n * @param {CID} cid\n */\n const removeBlock = async (cid) => {\n return async function remove () {\n blocksCount++\n\n try {\n const b32 = base32.encode(cid.multihash.bytes)\n\n if (markedSet.has(b32)) {\n return null\n }\n\n try {\n await blockstore.delete(cid)\n removedBlocksCount++\n } catch (/** @type {any} */ err) {\n return {\n err: new Error(`Could not delete block with CID ${cid}: ${err.message}`)\n }\n }\n\n return { cid }\n } catch (/** @type {any} */ err) {\n const msg = `Could delete block with CID ${cid}`\n log(msg, err)\n return { err: new Error(msg + `: ${err.message}`) }\n }\n }\n }\n\n yield * pipe(\n parallelBatch(map(blockKeys, removeBlock), BLOCK_RM_CONCURRENCY),\n // filter nulls (blocks that were retained)\n source => filter(source, Boolean)\n )\n\n log(`Marked set has ${markedSet.size} unique blocks. Blockstore has ${blocksCount} blocks. ` +\n `Deleted ${removedBlocksCount} blocks.`)\n}\n", "/**\n * Takes an (async) iterable that emits things and returns an async iterable that\n * emits those things in fixed-sized batches\n */\nexport default async function * batch (source: AsyncIterable | Iterable, size: number = 1): AsyncGenerator {\n let things: T[] = []\n\n if (size < 1) {\n size = 1\n }\n\n for await (const thing of source) {\n things.push(thing)\n\n while (things.length >= size) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n }\n\n while (things.length > 0) {\n yield things.slice(0, size)\n\n things = things.slice(size)\n }\n}\n", "import batch from 'it-batch'\n\ninterface Success {\n ok: true\n value: T\n}\n\ninterface Failure {\n ok: false\n err: Error\n}\n\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 * parallelBatch (source: AsyncIterable<() => Promise>|Iterable<() => Promise>, size: number = 1): AsyncGenerator {\n for await (const tasks of batch(source, size)) {\n const things: Array|Failure>> = tasks.map(\n async (p: () => Promise) => {\n return await p().then(value => ({ ok: true, value }), err => ({ ok: false, err }))\n })\n\n for (let i = 0; i < things.length; i++) {\n const result = await things[i]\n\n if (result.ok) {\n yield result.value\n } else {\n throw result.err\n }\n }\n }\n}\n", "import all from 'it-all'\n\nexport interface CompareFunction {\n (a: T, b: T): number\n}\n\n/**\n * Collects all values from an async iterator, sorts them\n * using the passed function and yields them\n */\nexport default async function * sort (source: AsyncIterable | Iterable, sorter: CompareFunction): AsyncGenerator {\n const arr = await all(source)\n\n yield * arr.sort(sorter)\n}\n", "import { Key } from 'interface-datastore'\nimport { BaseDatastore, Errors } from 'datastore-core'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport take from 'it-take'\nimport sort from 'it-sort'\nimport { Level } from 'level'\n\n/**\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Batch} Batch\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Options} QueryOptions\n * @typedef {import('abstract-level').AbstractLevel} LevelDb\n */\n\n/**\n * A datastore backed by leveldb\n */\nexport class LevelDatastore extends BaseDatastore {\n /**\n * @param {string | LevelDb} path\n * @param {import('level').DatabaseOptions & import('level').OpenOptions} [opts]\n */\n constructor (path, opts = {}) {\n super()\n\n /** @type {LevelDb} */\n this.db = typeof path === 'string'\n ? new Level(path, {\n ...opts,\n keyEncoding: 'utf8',\n valueEncoding: 'view'\n })\n : path\n\n /** @type {import('level').OpenOptions} */\n this.opts = {\n createIfMissing: true,\n compression: false, // same default as go\n ...opts\n }\n }\n\n async open () {\n try {\n await this.db.open(this.opts)\n } catch (/** @type {any} */ err) {\n throw Errors.dbOpenFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} value\n */\n async put (key, value) {\n try {\n await this.db.put(key.toString(), value)\n } catch (/** @type {any} */ err) {\n throw Errors.dbWriteFailedError(err)\n }\n }\n\n /**\n * @param {Key} key\n * @returns {Promise}\n */\n async get (key) {\n let data\n try {\n data = await this.db.get(key.toString())\n } catch (/** @type {any} */ err) {\n if (err.notFound) throw Errors.notFoundError(err)\n throw Errors.dbWriteFailedError(err)\n }\n return data\n }\n\n /**\n * @param {Key} key\n * @returns {Promise}\n */\n async has (key) {\n try {\n await this.db.get(key.toString())\n } catch (/** @type {any} */ err) {\n if (err.notFound) return false\n throw err\n }\n return true\n }\n\n /**\n * @param {Key} key\n * @returns {Promise}\n */\n async delete (key) {\n try {\n await this.db.del(key.toString())\n } catch (/** @type {any} */ err) {\n throw Errors.dbDeleteFailedError(err)\n }\n }\n\n close () {\n return this.db && this.db.close()\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Array<{ type: 'put', key: string, value: Uint8Array; } | { type: 'del', key: string }>} */\n const ops = []\n return {\n put: (key, value) => {\n ops.push({\n type: 'put',\n key: key.toString(),\n value: value\n })\n },\n delete: (key) => {\n ops.push({\n type: 'del',\n key: key.toString()\n })\n },\n commit: () => {\n return this.db.batch(ops)\n }\n }\n }\n\n /**\n * @param {Query} q\n */\n query (q) {\n let it = this._query({\n values: true,\n prefix: q.prefix\n })\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n const { offset, limit } = q\n if (offset) {\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (limit) {\n it = take(it, limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n */\n queryKeys (q) {\n let it = map(this._query({\n values: false,\n prefix: q.prefix\n }), ({ key }) => key)\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n const { offset, limit } = q\n if (offset) {\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (limit) {\n it = take(it, limit)\n }\n\n return it\n }\n\n /**\n * @param {object} opts\n * @param {boolean} opts.values\n * @param {string} [opts.prefix]\n * @returns {AsyncIterable}\n */\n _query (opts) {\n /** @type {import('level').IteratorOptions} */\n const iteratorOpts = {\n keys: true,\n keyEncoding: 'buffer',\n values: opts.values\n }\n\n // Let the db do the prefix matching\n if (opts.prefix != null) {\n const prefix = opts.prefix.toString()\n // Match keys greater than or equal to `prefix` and\n iteratorOpts.gte = prefix\n // less than `prefix` + \\xFF (hex escape sequence)\n iteratorOpts.lt = prefix + '\\xFF'\n }\n\n const iterator = this.db.iterator(iteratorOpts)\n\n if (iterator[Symbol.asyncIterator]) {\n return levelIteratorToIterator(iterator)\n }\n\n // @ts-expect-error support older level\n if (iterator.next != null && iterator.end != null) {\n // @ts-expect-error support older level\n return oldLevelIteratorToIterator(iterator)\n }\n\n throw new Error('Level returned incompatible iterator')\n }\n}\n\n/**\n * @param {import('level').Iterator} li - Level iterator\n * @returns {AsyncIterable}\n */\nasync function * levelIteratorToIterator (li) {\n for await (const [key, value] of li) {\n yield { key: new Key(key, false), value }\n }\n\n await li.close()\n}\n\n/**\n * @typedef {object} LevelIterator\n * @property {(cb: (err: Error, key: string | Uint8Array | null, value: any)=> void)=>void} next\n * @property {(cb: (err: Error) => void) => void } end\n */\n\n/**\n * @param {LevelIterator} li - Level iterator\n * @returns {AsyncIterable}\n */\nfunction oldLevelIteratorToIterator (li) {\n return {\n [Symbol.asyncIterator] () {\n return {\n next: () => new Promise((resolve, reject) => {\n li.next((err, key, value) => {\n if (err) return reject(err)\n if (key == null) {\n return li.end(err => {\n if (err) return reject(err)\n resolve({ done: true, value: undefined })\n })\n }\n resolve({ done: false, value: { key: new Key(key, false), value } })\n })\n }),\n return: () => new Promise((resolve, reject) => {\n li.end(err => {\n if (err) return reject(err)\n resolve({ done: true, value: undefined })\n })\n })\n }\n }\n }\n}\n", "import drain from 'it-drain'\nimport { pushable } from 'it-pushable'\nimport { Key } from 'interface-datastore/key'\nimport { CID } from 'multiformats/cid'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { base32, base32pad } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport errcode from 'err-code'\nimport { BaseBlockstore } from 'blockstore-core/base'\n\n/**\n * Transform a cid to the appropriate datastore key.\n *\n * @param {CID} cid\n * @returns {Key}\n */\nfunction cidToKey (cid) {\n const c = CID.asCID(cid)\n\n if (!c) {\n throw errcode(new Error('Not a valid cid'), 'ERR_INVALID_CID')\n }\n\n return new Key('/' + base32.encode(c.multihash.bytes).slice(1).toUpperCase(), false)\n}\n\n/**\n * Transform a datastore Key instance to a CID\n * As Key is a multihash of the CID, it is reconstructed using IPLD's RAW codec.\n * Hence it is highly probable that stored CID will differ from a CID retrieved from blockstore.\n *\n * @param {Key} key\n * @returns {CID}\n */\nfunction keyToCid (key) {\n // Block key is of the form \n return CID.createV1(raw.code, Digest.decode(base32.decode('b' + key.toString().slice(1).toLowerCase())))\n}\n\n/**\n * Tries to decode a prefix as the first part of a CID and then\n * strip off the version and codec bytes to just leave part of\n * the multihash.\n *\n * Only really works if the prefix length aligns with the byte\n * boundaries of the encoding.\n *\n * @param {string} prefix\n * @returns {string}\n */\nfunction convertPrefix (prefix) {\n const firstChar = prefix.substring(0, 1)\n\n if (firstChar === '/') {\n return convertPrefix(prefix.substring(1))\n }\n\n /** @type {(input: string) => Uint8Array } */\n let decoder\n\n if (firstChar.toLowerCase() === 'b') {\n // v1 cid prefix, remove version and codec bytes\n decoder = (input) => base32.decode(input.toLowerCase()).subarray(2)\n } else if (firstChar.toLowerCase() === 'c') {\n // v1 cid prefix, remove version and codec bytes\n decoder = (input) => base32pad.decode(input.toLowerCase()).subarray(2)\n } else if (firstChar === 'z') {\n // v1 cid\n decoder = (input) => base58btc.decode(input).subarray(2)\n } else if (firstChar === 'Q') {\n // v0 cid prefix\n decoder = (input) => base58btc.decode('z' + input)\n } else {\n decoder = (input) => base32.decode('b' + input.toLowerCase()).subarray(2)\n }\n\n let bytes\n\n // find the longest prefix that we can safely decode\n for (let i = 1; i < prefix.length; i++) {\n try {\n bytes = decoder(prefix.substring(0, i))\n } catch (/** @type {any} */ err) {\n if (err.message !== 'Unexpected end of data') {\n throw err\n }\n }\n }\n\n let str = '/C'\n\n if (bytes) {\n // slice one character from the end of the string to ensure we don't end up\n // with a padded value which could have a non-matching string at the end\n str = `/${base32.encode(bytes).slice(1, -1).toUpperCase() || 'C'}`\n }\n\n return str\n}\n\n/**\n * @param {import('interface-blockstore').Query} query\n * @returns {import('interface-datastore').Query}\n */\nfunction convertQuery (query) {\n return {\n ...query,\n prefix: query.prefix ? convertPrefix(query.prefix) : undefined,\n filters: query.filters\n ? query.filters.map(\n filter => (pair) => {\n return filter({ key: keyToCid(pair.key), value: pair.value })\n }\n )\n : undefined,\n orders: query.orders\n ? query.orders.map(\n order => (a, b) => {\n return order({ key: keyToCid(a.key), value: a.value }, { key: keyToCid(b.key), value: b.value })\n }\n )\n : undefined\n }\n}\n\n/**\n * @param {import('interface-blockstore').KeyQuery} query\n * @returns {import('interface-datastore').KeyQuery}\n */\nfunction convertKeyQuery (query) {\n return {\n ...query,\n prefix: query.prefix ? convertPrefix(query.prefix) : undefined,\n filters: query.filters\n ? query.filters.map(\n filter => (key) => {\n return filter(keyToCid(key))\n }\n )\n : undefined,\n orders: query.orders\n ? query.orders.map(\n order => (a, b) => {\n return order(keyToCid(a), keyToCid(b))\n }\n )\n : undefined\n }\n}\n\n/**\n * @typedef {import('interface-blockstore').Query} Query\n * @typedef {import('interface-blockstore').KeyQuery} KeyQuery\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Options} Options\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n */\n\n/**\n * @implements {Blockstore}\n */\nexport class BlockstoreDatastoreAdapter extends BaseBlockstore {\n /**\n * @param {Datastore} datastore\n */\n constructor (datastore) {\n super()\n\n this.child = datastore\n }\n\n open () {\n return this.child.open()\n }\n\n close () {\n return this.child.close()\n }\n\n /**\n * @param {Query} query\n * @param {Options} [options]\n */\n async * query (query, options) {\n for await (const { key, value } of this.child.query(convertQuery(query), options)) {\n yield { key: keyToCid(key), value }\n }\n }\n\n /**\n * @param {KeyQuery} query\n * @param {Options} [options]\n */\n async * queryKeys (query, options) {\n for await (const key of this.child.queryKeys(convertKeyQuery(query), options)) {\n yield keyToCid(key)\n }\n }\n\n /**\n * @param {CID} cid\n * @param {Options} [options]\n * @returns\n */\n async get (cid, options) {\n return this.child.get(cidToKey(cid), options)\n }\n\n /**\n * @param {AsyncIterable | Iterable} cids\n * @param {Options} [options]\n */\n async * getMany (cids, options) {\n for await (const cid of cids) {\n yield this.get(cid, options)\n }\n }\n\n /**\n * @param {CID} cid\n * @param {Uint8Array} value\n * @param {Options} [options]\n */\n async put (cid, value, options) {\n await this.child.put(cidToKey(cid), value, options)\n }\n\n /**\n * @param {AsyncIterable | Iterable} blocks\n * @param {Options} [options]\n */\n async * putMany (blocks, options) { // eslint-disable-line require-await\n // we cannot simply chain to `store.putMany` because we convert a CID into\n // a key based on the multihash only, so we lose the version & codec and\n // cannot give the user back the CID they used to create the block, so yield\n // to `store.putMany` but return the actual block the user passed in.\n //\n // nb. we want to use `store.putMany` here so bitswap can control batching\n // up block HAVEs to send to the network - if we use multiple `store.put`s\n // it will not be able to guess we are about to `store.put` more blocks\n const output = pushable({\n objectMode: true\n })\n\n // process.nextTick runs on the microtask queue, setImmediate runs on the next\n // event loop iteration so is slower. Use process.nextTick if it is available.\n const runner = globalThis.process && globalThis.process.nextTick ? globalThis.process.nextTick : (globalThis.setImmediate || globalThis.setTimeout)\n\n runner(async () => {\n try {\n const store = this.child\n\n await drain(this.child.putMany(async function * () {\n for await (const block of blocks) {\n const key = cidToKey(block.key)\n const exists = await store.has(key, options)\n\n if (!exists) {\n yield { key, value: block.value }\n }\n\n // there is an assumption here that after the yield has completed\n // the underlying datastore has finished writing the block\n output.push(block)\n }\n }()))\n\n output.end()\n } catch (/** @type {any} */ err) {\n output.end(err)\n }\n })\n\n yield * output\n }\n\n /**\n * @param {CID} cid\n * @param {Options} [options]\n */\n has (cid, options) {\n return this.child.has(cidToKey(cid), options)\n }\n\n /**\n * @param {CID} cid\n * @param {Options} [options]\n */\n delete (cid, options) {\n return this.child.delete(cidToKey(cid), options)\n }\n\n /**\n * @param {AsyncIterable | Iterable} cids\n * @param {Options} [options]\n */\n deleteMany (cids, options) {\n const out = pushable({\n objectMode: true\n })\n\n drain(this.child.deleteMany((async function * () {\n for await (const cid of cids) {\n yield cidToKey(cid)\n\n out.push(cid)\n }\n\n out.end()\n }()), options)).catch(err => {\n out.end(err)\n })\n\n return out\n }\n}\n", "import drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nconst sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @typedef {import('interface-blockstore').Options} Options\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Query} Query\n * @typedef {import('interface-blockstore').KeyQuery} KeyQuery\n * @typedef {import('interface-blockstore').Batch} Batch\n *\n * @typedef {import('multiformats').CID} CID\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Blockstore}\n */\nexport class BaseBlockstore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {CID} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\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\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {CID[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\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 /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (/** @type {Pair} */ e) =>\n e.key.toString().startsWith(q.prefix || '')\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= (q.offset || 0))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (/** @type {CID} */ cid) => cid.toString().startsWith(q.prefix || ''))\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import { createRepo as create } from 'ipfs-repo'\nimport { LevelDatastore } from 'datastore-level'\nimport { BlockstoreDatastoreAdapter } from 'blockstore-datastore-adapter'\nimport { MemoryLock } from 'ipfs-repo/locks/memory'\n\n/**\n * @typedef {import('ipfs-repo-migrations').ProgressCallback} MigrationProgressCallback\n */\n\n/**\n * @param {(...args: any[]) => void} print\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {object} options\n * @param {string} [options.path]\n * @param {boolean} [options.autoMigrate]\n * @param {MigrationProgressCallback} [options.onMigrationProgress]\n * @param {number} [options.peerStoreCacheSize]\n */\nexport function createRepo (print, codecs, options) {\n const repoPath = options.path || 'ipfs'\n\n return create(repoPath, (codeOrName) => codecs.getCodec(codeOrName), {\n root: new LevelDatastore(repoPath, {\n prefix: '',\n version: 2\n }),\n blocks: new BlockstoreDatastoreAdapter(\n new LevelDatastore(`${repoPath}/blocks`, {\n prefix: '',\n version: 2\n })\n ),\n datastore: new LevelDatastore(`${repoPath}/datastore`, {\n prefix: '',\n version: 2\n }),\n keys: new LevelDatastore(`${repoPath}/keys`, {\n prefix: '',\n version: 2\n }),\n pins: new LevelDatastore(`${repoPath}/pins`, {\n prefix: '',\n version: 2\n })\n }, {\n autoMigrate: options.autoMigrate,\n onMigrationProgress: options.onMigrationProgress || print,\n repoLock: MemoryLock\n })\n}\n", "import get from 'dlv'\nimport mergeOpts from 'merge-options'\nimport errCode from 'err-code'\nimport { routers } from 'ipfs-core-config/libp2p-pubsub-routers'\nimport { delegatedPeerRouting } from '@libp2p/delegated-peer-routing'\nimport { delegatedContentRouting } from '@libp2p/delegated-content-routing'\nimport { create as ipfsHttpClient } from 'ipfs-http-client'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { ipfsCore as pkgversion } from '../version.js'\nimport { libp2pConfig as getEnvLibp2pOptions } from 'ipfs-core-config/libp2p'\nimport { createLibp2p as createNode } from 'libp2p'\nimport { kadDHT } from '@libp2p/kad-dht'\nimport { bootstrap } from '@libp2p/bootstrap'\nimport { ipnsValidator } from 'ipns/validator'\nimport { ipnsSelector } from 'ipns/selector'\nimport { webSockets } from '@libp2p/websockets'\nimport { mplex } from '@libp2p/mplex'\nimport { noise } from '@chainsafe/libp2p-noise'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true, concatArrays: true })\n\n/**\n * @typedef {object} DekOptions\n * @property {string} hash\n * @property {string} salt\n * @property {number} iterationCount\n * @property {number} keyLength\n *\n * @typedef {object} KeychainConfig\n * @property {string} [pass]\n * @property {DekOptions} [dek]\n *\n * @typedef {import('ipfs-repo').IPFSRepo} Repo\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('../types').Options} IPFSOptions\n * @typedef {import('libp2p').Libp2p} LibP2P\n * @typedef {import('libp2p').Libp2pOptions} Libp2pOptions\n * @typedef {import('ipfs-core-types/src/config').Config} IPFSConfig\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {object} config\n * @param {Repo} config.repo\n * @param {IPFSOptions|undefined} config.options\n * @param {PeerId} config.peerId\n * @param {Multiaddr[]|undefined} config.multiaddrs\n * @param {KeychainConfig|undefined} config.keychainConfig\n * @param {Partial|undefined} config.config\n */\nexport function createLibp2p ({\n options = {},\n peerId,\n multiaddrs = [],\n repo,\n keychainConfig = {},\n config = {}\n}) {\n const { datastore } = repo\n\n const libp2pOptions = getLibp2pOptions({\n options,\n config,\n datastore,\n keychainConfig,\n peerId,\n multiaddrs\n })\n\n if (typeof options.libp2p === 'function') {\n return options.libp2p({ libp2pOptions, options, config, datastore, peerId })\n }\n\n // do not start by default\n libp2pOptions.start = false\n\n return createNode(libp2pOptions)\n}\n\n/**\n * @param {object} input\n * @param {IPFSOptions} input.options\n * @param {Partial} input.config\n * @param {Repo['datastore']} input.datastore\n * @param {KeychainConfig} input.keychainConfig\n * @param {PeerId} input.peerId\n * @param {Multiaddr[]} input.multiaddrs\n * @returns {Libp2pOptions}\n */\nfunction getLibp2pOptions ({ options, config, datastore, keychainConfig, peerId, multiaddrs }) {\n const getPubsubRouter = () => {\n const router = get(config, 'Pubsub.Router') || 'gossipsub'\n\n const availableRouters = routers()\n\n if (!availableRouters[router]) {\n throw errCode(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${router} router.`), 'ERR_NOT_SUPPORTED')\n }\n\n return availableRouters[router]\n }\n\n /** @type {Libp2pOptions} */\n const libp2pDefaults = {\n datastore,\n peerId: peerId\n }\n\n /** @type {Libp2pOptions} */\n const libp2pOptions = {\n addresses: {\n listen: multiaddrs.map(ma => ma.toString()),\n announce: get(options, 'addresses.announce', get(config, 'Addresses.Announce', [])),\n noAnnounce: get(options, 'addresses.noAnnounce', get(config, 'Addresses.NoAnnounce', []))\n },\n connectionManager: get(options, 'connectionManager', {\n maxConnections: get(options, 'config.Swarm.ConnMgr.HighWater', get(config, 'Swarm.ConnMgr.HighWater')),\n minConnections: get(options, 'config.Swarm.ConnMgr.LowWater', get(config, 'Swarm.ConnMgr.LowWater'))\n }),\n keychain: keychainConfig,\n identify: {\n host: {\n agentVersion: `js-ipfs/${pkgversion}`\n }\n },\n contentRouters: [],\n peerRouters: [],\n peerDiscovery: [],\n transports: [],\n streamMuxers: [\n mplex({\n maxInboundStreams: 256,\n maxOutboundStreams: 1024\n })\n ],\n connectionEncryption: [\n noise()\n ],\n relay: {\n enabled: get(options, 'relay.enabled', get(config, 'relay.enabled', true)),\n hop: {\n enabled: get(options, 'relay.hop.enabled', get(config, 'relay.hop.enabled', false)),\n active: get(options, 'relay.hop.active', get(config, 'relay.hop.active', false))\n }\n },\n nat: {\n enabled: !get(config, 'Swarm.DisableNatPortMap', false)\n }\n }\n\n if (get(options, 'config.Pubsub.Enabled', get(config, 'Pubsub.Enabled', true))) {\n libp2pOptions.pubsub = getPubsubRouter()\n }\n\n if (get(config, 'Routing.Type', 'dhtclient') !== 'none') {\n libp2pOptions.dht = kadDHT({\n clientMode: get(config, 'Routing.Type', 'dht') !== 'dhtserver',\n kBucketSize: get(options, 'dht.kBucketSize', 20),\n validators: {\n ipns: ipnsValidator\n },\n selectors: {\n ipns: ipnsSelector\n }\n })\n }\n\n const boostrapNodes = get(options, 'config.Bootstrap', get(config, 'Bootstrap', []))\n\n if (boostrapNodes.length > 0) {\n libp2pOptions.peerDiscovery?.push(\n bootstrap({\n list: boostrapNodes\n })\n )\n }\n\n /** @type {import('libp2p').Libp2pOptions | undefined} */\n let constructorOptions = get(options, 'libp2p', undefined)\n\n if (typeof constructorOptions === 'function') {\n constructorOptions = undefined\n }\n\n // Merge defaults with Node.js/browser/other environments options and configuration\n /** @type {Libp2pOptions} */\n const libp2pFinalConfig = mergeOptions(\n libp2pDefaults,\n getEnvLibp2pOptions(),\n libp2pOptions,\n constructorOptions\n )\n\n // Set up Delegate Routing based on the presence of Delegates in the config\n const delegateHosts = get(options, 'config.Addresses.Delegates',\n get(config, 'Addresses.Delegates', [])\n )\n\n if (delegateHosts.length > 0) {\n // Pick a random delegate host\n const delegateString = delegateHosts[Math.floor(Math.random() * delegateHosts.length)]\n const delegateAddr = multiaddr(delegateString).toOptions()\n const delegateApiOptions = {\n host: delegateAddr.host,\n // port is a string atm, so we need to convert for the check\n // @ts-expect-error - parseInt(input:string) => number\n protocol: parseInt(delegateAddr.port) === 443 ? 'https' : 'http',\n port: delegateAddr.port\n }\n\n const delegateHttpClient = ipfsHttpClient(delegateApiOptions)\n\n libp2pFinalConfig.contentRouters?.push(delegatedContentRouting(delegateHttpClient))\n libp2pFinalConfig.peerRouters?.push(delegatedPeerRouting(delegateHttpClient))\n }\n\n // TODO: fixme\n if (!get(options, 'config.Discovery.MDNS.Enabled', get(config, 'Discovery.MDNS.Enabled', true))) {\n libp2pFinalConfig.peerDiscovery = libp2pFinalConfig.peerDiscovery?.filter(d => {\n try {\n if (typeof d === 'function') {\n // @ts-expect-error not components\n return d({})[Symbol.toStringTag] !== '@libp2p/mdns'\n }\n } catch {}\n return true\n })\n }\n\n if (libp2pFinalConfig.transports == null) {\n libp2pFinalConfig.transports = []\n }\n\n // add WebSocket transport if not overridden by user config\n if (libp2pFinalConfig.transports.find(t => {\n try {\n if (typeof t === 'function') {\n return t({})[Symbol.toStringTag] === '@libp2p/websockets'\n }\n } catch {}\n return false\n }) == null) {\n libp2pFinalConfig.transports.push(webSockets())\n }\n\n return libp2pFinalConfig\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from 'byte-access'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n /**\n * Returns these hi/lo bits as a BigInt\n */\n toBigInt (unsigned?: boolean): bigint {\n if (unsigned === true) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Returns these hi/lo bits as a Number - this may overflow, toBigInt\n * should be preferred\n */\n toNumber (unsigned?: boolean): number {\n return Number(this.toBigInt(unsigned))\n }\n\n /**\n * ZigZag decode a LongBits object\n */\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * ZigZag encode a LongBits object\n */\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Encode a LongBits object as a varint byte array\n */\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n /**\n * Parse a LongBits object from a BigInt\n */\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a Number\n */\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a varint byte array\n */\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n\n i = 0\n } else {\n for (; i < 4; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n } else if (offset < buf.byteLength) {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw RangeError('invalid varint encoding')\n }\n}\n", "import { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\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)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\ninterface VarintCodec {\n encodingLength: (value: number) => number\n encode: ((value: number) => Uint8Array) & ((value: number, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: number, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => number\n}\n\nexport const unsigned: VarintCodec = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf?: any, offset: number = 0) {\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(true)\n }\n}\n\nexport const signed: VarintCodec = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0) {\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(false)\n }\n}\n\nexport const zigzag: VarintCodec = {\n encodingLength (value: number): number {\n return unsigned.encodingLength(value >= 0 ? value * 2 : value * -2 - 1)\n },\n\n // @ts-expect-error types are wrong\n encode (value: any, buf?: any, offset?: any) {\n value = value >= 0 ? value * 2 : (value * -2) - 1\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n const value = unsigned.decode(buf, offset)\n\n return (value & 1) !== 0 ? (value + 1) / -2 : value / 2\n }\n}\n", "\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n", "import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { unsigned } 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'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\n\nexport interface RecordEnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList): Promise => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\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: Record, peerId: PeerId): Promise => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\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\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\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: Uint8Array | Uint8ArrayList, domain: string): Promise => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw new CodeError('envelope signature is not valid for the given domain', codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\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\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope): boolean {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string): Promise {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\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\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n", "\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\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", "/* 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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.peerId)\n }\n\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16)\n w.uint64(obj.seq)\n }\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\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n", "import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 32)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 64)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n /**\n * Return the list of protocols with registered handlers\n */\n getProtocols: () => string[]\n\n /**\n * Add a protocol handler\n */\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n\n /**\n * Remove a protocol handler\n */\n unhandle: (protocol: string) => Promise\n\n /**\n * Return the handler for the passed protocol\n */\n getHandler: (protocol: string) => StreamHandlerRecord\n\n /**\n * Register a topology handler for a protocol - the topology will be\n * invoked when peers are discovered on the network that support the\n * passed protocol.\n *\n * An id will be returned that can later be used to unregister the\n * topology.\n */\n register: (protocol: string, topology: Topology) => Promise\n\n /**\n * Remove the topology handler with the passed id.\n */\n unregister: (id: string) => void\n\n /**\n * Return all topology handlers that wish to be informed about peers\n * that support the passed protocol.\n */\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n\n /**\n * Invoked when a new peer is connects that supports the configured\n * protocol\n */\n onConnect?: onConnectHandler\n\n /**\n * Invoked when a peer that supports the configured protocol disconnects\n */\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n", "import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = (): void => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] (): string {\n return symbol.toString()\n }\n\n readonly [symbol] = true\n\n async setRegistrar (registrar: Registrar): Promise {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId): void {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n", "\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter> extends EventTarget {\n #listeners = new Map()\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit): boolean {\n return this.dispatchEvent(new CustomEvent(type as string, detail))\n }\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 public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n", "import type { RPC } from './message/rpc.js'\nimport type { MessageId, MsgIdStr, PeerIdStr, TopicStr, MsgIdToStrFn } from './types.js'\n\nexport type CacheEntry = MessageId & {\n topic: TopicStr\n}\n\ninterface MessageCacheEntry {\n message: RPC.IMessage\n /**\n * Tracks if the message has been validated by the app layer and thus forwarded\n */\n validated: boolean\n /**\n * Tracks peers that sent this message before it has been validated by the app layer\n */\n originatingPeers: Set\n /**\n * For every message and peer the number of times this peer asked for the message\n */\n iwantCounts: Map\n}\n\nexport class MessageCache {\n msgs = new Map()\n\n msgIdToStrFn: MsgIdToStrFn\n\n history: CacheEntry[][] = []\n\n /** Track with accounting of messages in the mcache that are not yet validated */\n notValidatedCount = 0\n\n /**\n * Holds history of messages in timebounded history arrays\n */\n constructor(\n /**\n * The number of indices in the cache history used for gossiping. That means that a message\n * won't get gossiped anymore when shift got called `gossip` many times after inserting the\n * message in the cache.\n */\n private readonly gossip: number,\n historyCapacity: number,\n msgIdToStrFn: MsgIdToStrFn\n ) {\n this.msgIdToStrFn = msgIdToStrFn\n for (let i = 0; i < historyCapacity; i++) {\n this.history[i] = []\n }\n }\n\n get size(): number {\n return this.msgs.size\n }\n\n /**\n * Adds a message to the current window and the cache\n * Returns true if the message is not known and is inserted in the cache\n */\n put(messageId: MessageId, msg: RPC.IMessage, validated = false): boolean {\n const { msgIdStr } = messageId\n // Don't add duplicate entries to the cache.\n if (this.msgs.has(msgIdStr)) {\n return false\n }\n\n this.msgs.set(msgIdStr, {\n message: msg,\n validated,\n originatingPeers: new Set(),\n iwantCounts: new Map()\n })\n\n this.history[0].push({ ...messageId, topic: msg.topic })\n\n if (!validated) {\n this.notValidatedCount++\n }\n\n return true\n }\n\n observeDuplicate(msgId: MsgIdStr, fromPeerIdStr: PeerIdStr): void {\n const entry = this.msgs.get(msgId)\n\n if (\n entry &&\n // if the message is already validated, we don't need to store extra peers sending us\n // duplicates as the message has already been forwarded\n !entry.validated\n ) {\n entry.originatingPeers.add(fromPeerIdStr)\n }\n }\n\n /**\n * Retrieves a message from the cache by its ID, if it is still present\n */\n get(msgId: Uint8Array): RPC.IMessage | undefined {\n return this.msgs.get(this.msgIdToStrFn(msgId))?.message\n }\n\n /**\n * Increases the iwant count for the given message by one and returns the message together\n * with the iwant if the message exists.\n */\n getWithIWantCount(msgIdStr: string, p: string): { msg: RPC.IMessage; count: number } | null {\n const msg = this.msgs.get(msgIdStr)\n if (!msg) {\n return null\n }\n\n const count = (msg.iwantCounts.get(p) ?? 0) + 1\n msg.iwantCounts.set(p, count)\n\n return { msg: msg.message, count }\n }\n\n /**\n * Retrieves a list of message IDs for a set of topics\n */\n getGossipIDs(topics: Set): Map {\n const msgIdsByTopic = new Map()\n for (let i = 0; i < this.gossip; i++) {\n this.history[i].forEach((entry) => {\n const msg = this.msgs.get(entry.msgIdStr)\n if (msg && msg.validated && topics.has(entry.topic)) {\n let msgIds = msgIdsByTopic.get(entry.topic)\n if (!msgIds) {\n msgIds = []\n msgIdsByTopic.set(entry.topic, msgIds)\n }\n msgIds.push(entry.msgId)\n }\n })\n }\n\n return msgIdsByTopic\n }\n\n /**\n * Gets a message with msgId and tags it as validated.\n * This function also returns the known peers that have sent us this message. This is used to\n * prevent us sending redundant messages to peers who have already propagated it.\n */\n validate(msgId: MsgIdStr): { message: RPC.IMessage; originatingPeers: Set } | null {\n const entry = this.msgs.get(msgId)\n if (!entry) {\n return null\n }\n\n if (!entry.validated) {\n this.notValidatedCount--\n }\n\n const { message, originatingPeers } = entry\n entry.validated = true\n // Clear the known peers list (after a message is validated, it is forwarded and we no\n // longer need to store the originating peers).\n entry.originatingPeers = new Set()\n return { message, originatingPeers }\n }\n\n /**\n * Shifts the current window, discarding messages older than this.history.length of the cache\n */\n shift(): void {\n const lastCacheEntries = this.history[this.history.length - 1]\n lastCacheEntries.forEach((cacheEntry) => {\n const entry = this.msgs.get(cacheEntry.msgIdStr)\n if (entry) {\n this.msgs.delete(cacheEntry.msgIdStr)\n if (!entry.validated) {\n this.notValidatedCount--\n }\n }\n })\n\n this.history.pop()\n this.history.unshift([])\n }\n\n remove(msgId: MsgIdStr): MessageCacheEntry | null {\n const entry = this.msgs.get(msgId)\n if (!entry) {\n return null\n }\n\n // Keep the message on the history vector, it will be dropped on a shift()\n this.msgs.delete(msgId)\n return entry\n }\n}\n", "import cjs from \"./rpc.cjs\"\n\nexport const {RPC} = cjs\n", "export const second = 1000\nexport const minute = 60 * second\n\n// Protocol identifiers\n\nexport const FloodsubID = '/floodsub/1.0.0'\n\n/**\n * The protocol ID for version 1.0.0 of the Gossipsub protocol\n * It is advertised along with GossipsubIDv11 for backwards compatability\n */\nexport const GossipsubIDv10 = '/meshsub/1.0.0'\n\n/**\n * The protocol ID for version 1.1.0 of the Gossipsub protocol\n * See the spec for details about how v1.1.0 compares to v1.0.0:\n * https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md\n */\nexport const GossipsubIDv11 = '/meshsub/1.1.0'\n\n// Overlay parameters\n\n/**\n * GossipsubD sets the optimal degree for a Gossipsub topic mesh. For example, if GossipsubD == 6,\n * each peer will want to have about six peers in their mesh for each topic they're subscribed to.\n * GossipsubD should be set somewhere between GossipsubDlo and GossipsubDhi.\n */\nexport const GossipsubD = 6\n\n/**\n * GossipsubDlo sets the lower bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have fewer than GossipsubDlo peers, we will attempt to graft some more into the mesh at\n * the next heartbeat.\n */\nexport const GossipsubDlo = 4\n\n/**\n * GossipsubDhi sets the upper bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have more than GossipsubDhi peers, we will select some to prune from the mesh at the next heartbeat.\n */\nexport const GossipsubDhi = 12\n\n/**\n * GossipsubDscore affects how peers are selected when pruning a mesh due to over subscription.\n * At least GossipsubDscore of the retained peers will be high-scoring, while the remainder are\n * chosen randomly.\n */\nexport const GossipsubDscore = 4\n\n/**\n * GossipsubDout sets the quota for the number of outbound connections to maintain in a topic mesh.\n * When the mesh is pruned due to over subscription, we make sure that we have outbound connections\n * to at least GossipsubDout of the survivor peers. This prevents sybil attackers from overwhelming\n * our mesh with incoming connections.\n *\n * GossipsubDout must be set below GossipsubDlo, and must not exceed GossipsubD / 2.\n */\nexport const GossipsubDout = 2\n\n// Gossip parameters\n\n/**\n * GossipsubHistoryLength controls the size of the message cache used for gossip.\n * The message cache will remember messages for GossipsubHistoryLength heartbeats.\n */\nexport const GossipsubHistoryLength = 5\n\n/**\n * GossipsubHistoryGossip controls how many cached message ids we will advertise in\n * IHAVE gossip messages. When asked for our seen message IDs, we will return\n * only those from the most recent GossipsubHistoryGossip heartbeats. The slack between\n * GossipsubHistoryGossip and GossipsubHistoryLength allows us to avoid advertising messages\n * that will be expired by the time they're requested.\n *\n * GossipsubHistoryGossip must be less than or equal to GossipsubHistoryLength to\n * avoid a runtime panic.\n */\nexport const GossipsubHistoryGossip = 3\n\n/**\n * GossipsubDlazy affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to at least GossipsubDlazy peers outside our mesh. The actual\n * number may be more, depending on GossipsubGossipFactor and how many peers we're\n * connected to.\n */\nexport const GossipsubDlazy = 6\n\n/**\n * GossipsubGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to GossipsubGossipFactor * (total number of non-mesh peers), or\n * GossipsubDlazy, whichever is greater.\n */\nexport const GossipsubGossipFactor = 0.25\n\n/**\n * GossipsubGossipRetransmission controls how many times we will allow a peer to request\n * the same message id through IWANT gossip before we start ignoring them. This is designed\n * to prevent peers from spamming us with requests and wasting our resources.\n */\nexport const GossipsubGossipRetransmission = 3\n\n// Heartbeat interval\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const GossipsubHeartbeatInitialDelay = 100\n\n/**\n * GossipsubHeartbeatInterval controls the time between heartbeats.\n */\nexport const GossipsubHeartbeatInterval = second\n\n/**\n * GossipsubFanoutTTL controls how long we keep track of the fanout state. If it's been\n * GossipsubFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const GossipsubFanoutTTL = minute\n\n/**\n * GossipsubPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to GossipsubPrunePeers other peers that we\n * know of.\n */\nexport const GossipsubPrunePeers = 16\n\n/**\n * GossipsubPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of GossipsubPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least GossipsubPruneBackoff\n * before attempting to re-graft.\n */\nexport const GossipsubPruneBackoff = minute\n\n/**\n * GossipsubPruneBackoffTicks is the number of heartbeat ticks for attempting to prune expired\n * backoff timers.\n */\nexport const GossipsubPruneBackoffTicks = 15\n\n/**\n * GossipsubConnectors controls the number of active connection attempts for peers obtained through PX.\n */\nexport const GossipsubConnectors = 8\n\n/**\n * GossipsubMaxPendingConnections sets the maximum number of pending connections for peers attempted through px.\n */\nexport const GossipsubMaxPendingConnections = 128\n\n/**\n * GossipsubConnectionTimeout controls the timeout for connection attempts.\n */\nexport const GossipsubConnectionTimeout = 30 * second\n\n/**\n * GossipsubDirectConnectTicks is the number of heartbeat ticks for attempting to reconnect direct peers\n * that are not currently connected.\n */\nexport const GossipsubDirectConnectTicks = 300\n\n/**\n * GossipsubDirectConnectInitialDelay is the initial delay before opening connections to direct peers\n */\nexport const GossipsubDirectConnectInitialDelay = second\n\n/**\n * GossipsubOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every GossipsubOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const GossipsubOpportunisticGraftTicks = 60\n\n/**\n * GossipsubOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const GossipsubOpportunisticGraftPeers = 2\n\n/**\n * If a GRAFT comes before GossipsubGraftFloodThreshold has elapsed since the last PRUNE,\n * then there is an extra score penalty applied to the peer through P7.\n */\nexport const GossipsubGraftFloodThreshold = 10 * second\n\n/**\n * GossipsubMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const GossipsubMaxIHaveLength = 5000\n\n/**\n * GossipsubMaxIHaveMessages is the maximum number of IHAVE messages to accept from a peer within a heartbeat.\n */\nexport const GossipsubMaxIHaveMessages = 10\n\n/**\n * Time to wait for a message requested through IWANT following an IHAVE advertisement.\n * If the message is not received within this window, a broken promise is declared and\n * the router may apply bahavioural penalties.\n */\nexport const GossipsubIWantFollowupTime = 3 * second\n\n/**\n * Time in milliseconds to keep message ids in the seen cache\n */\nexport const GossipsubSeenTTL = 2 * minute\n\nexport const TimeCacheDuration = 120 * 1000\n\nexport const ERR_TOPIC_VALIDATOR_REJECT = 'ERR_TOPIC_VALIDATOR_REJECT'\nexport const ERR_TOPIC_VALIDATOR_IGNORE = 'ERR_TOPIC_VALIDATOR_IGNORE'\n\n/**\n * If peer score is better than this, we accept messages from this peer\n * within ACCEPT_FROM_WHITELIST_DURATION_MS from the last time computing score.\n **/\nexport const ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE = 0\n\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept up to this\n * number of messages from that peer.\n */\nexport const ACCEPT_FROM_WHITELIST_MAX_MESSAGES = 128\n\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept messages from\n * this peer up to this time duration.\n */\nexport const ACCEPT_FROM_WHITELIST_DURATION_MS = 1000\n\n/**\n * The default MeshMessageDeliveriesWindow to be used in metrics.\n */\nexport const DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS = 1000\n", "/**\n * Pseudo-randomly shuffles an array\n *\n * Mutates the input array\n */\nexport function shuffle(arr: T[]): T[] {\n if (arr.length <= 1) {\n return arr\n }\n const randInt = () => {\n return Math.floor(Math.random() * Math.floor(arr.length))\n }\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", "import { toString } from 'uint8arrays/to-string'\n\n/**\n * Browser friendly function to convert Uint8Array message id to base64 string.\n */\nexport function messageIdToString(msgId: Uint8Array): string {\n return toString(msgId, 'base64')\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Pushable } from 'it-pushable'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\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 */\nexport const StrictSign = 'StrictSign'\n\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 */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface SignedMessage {\n type: 'signed'\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber: bigint\n signature: Uint8Array\n key: Uint8Array\n}\n\nexport interface UnsignedMessage {\n type: 'unsigned'\n topic: string\n data: Uint8Array\n}\n\nexport type Message = SignedMessage | UnsignedMessage\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends EventEmitter {\n id: PeerId\n protocol: string\n outboundStream?: Pushable\n inboundStream?: AsyncIterable\n isWritable: boolean\n\n close: () => void\n write: (buf: Uint8Array | Uint8ArrayList) => void\n attachInboundStream: (stream: Stream) => AsyncIterable\n attachOutboundStream: (stream: Stream) => Promise>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\ninterface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent\n 'message': CustomEvent\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport enum TopicValidatorResult {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n Accept = 'accept',\n /**\n * The message is neither delivered nor forwarded to the network\n */\n Ignore = 'ignore',\n /**\n * The message is considered invalid, and it should be rejected\n */\n Reject = 'reject'\n}\n\nexport interface TopicValidatorFn {\n (peer: PeerId, message: Message): TopicValidatorResult | Promise\n}\n\nexport interface PubSub = PubSubEvents> extends EventEmitter {\n /**\n * The global signature policy controls whether or not we sill send and receive\n * signed or unsigned messages.\n *\n * Signed messages prevent spoofing message senders and should be preferred to\n * using unsigned messages.\n */\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n\n /**\n * A list of multicodecs that contain the pubsub protocol name.\n */\n multicodecs: string[]\n\n /**\n * Pubsub routers support message validators per topic, which will validate the message\n * before its propagations. They are stored in a map where keys are the topic name and\n * values are the validators.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const validateMessage = (msgTopic, msg) => {\n * const input = uint8ArrayToString(msg.data)\n * const validInputs = ['a', 'b', 'c']\n *\n * if (!validInputs.includes(input)) {\n * throw new Error('no valid input received')\n * }\n * }\n * libp2p.pubsub.topicValidators.set(topic, validateMessage)\n * ```\n */\n topicValidators: Map\n\n getPeers: () => PeerId[]\n\n /**\n * Gets a list of topics the node is subscribed to.\n *\n * ```js\n * const topics = libp2p.pubsub.getTopics()\n * ```\n */\n getTopics: () => string[]\n\n /**\n * Subscribes to a pubsub topic.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const handler = (msg) => {\n * if (msg.topic === topic) {\n * // msg.data - pubsub data received\n * }\n * }\n *\n * libp2p.pubsub.addEventListener('message', handler)\n * libp2p.pubsub.subscribe(topic)\n * ```\n */\n subscribe: (topic: string) => void\n\n /**\n * Unsubscribes from a pubsub topic.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const handler = (msg) => {\n * // msg.data - pubsub data received\n * }\n *\n * libp2p.pubsub.removeEventListener(topic handler)\n * libp2p.pubsub.unsubscribe(topic)\n * ```\n */\n unsubscribe: (topic: string) => void\n\n /**\n * Gets a list of the PeerIds that are subscribed to one topic.\n *\n * @example\n *\n * ```js\n * const peerIds = libp2p.pubsub.getSubscribers(topic)\n * ```\n */\n getSubscribers: (topic: string) => PeerId[]\n\n /**\n * Publishes messages to the given topic.\n *\n * @example\n *\n * ```js\n * const topic = 'topic'\n * const data = uint8ArrayFromString('data')\n *\n * await libp2p.pubsub.publish(topic, data)\n * ```\n */\n publish: (topic: string, data: Uint8Array) => Promise\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent\n 'stream:outbound': CustomEvent\n 'close': CustomEvent\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PrivateKey } from '@libp2p/interface-keys'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { RPC } from './message/rpc.js'\nimport { Message, TopicValidatorResult } from '@libp2p/interface-pubsub'\n\nexport type MsgIdStr = string\nexport type PeerIdStr = string\nexport type TopicStr = string\nexport type IPStr = string\n\nexport interface AddrInfo {\n id: PeerId\n addrs: Multiaddr[]\n}\n\n/**\n * Compute a local non-spec'ed msg-id for faster de-duplication of seen messages.\n * Used exclusively for a local seen_cache\n */\nexport type FastMsgIdFn = (msg: RPC.IMessage) => string | number\n\n/**\n * By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n * Application could use this option to provide a more efficient function.\n */\nexport type MsgIdToStrFn = (msgId: Uint8Array) => string\n\n/**\n * Compute spec'ed msg-id. Used for IHAVE / IWANT messages\n */\nexport interface MsgIdFn {\n (msg: Message): Promise | Uint8Array\n}\n\nexport interface DataTransform {\n /**\n * Takes the data published by peers on a topic and transforms the data.\n * Should be the reverse of outboundTransform(). Example:\n * - `inboundTransform()`: decompress snappy payload\n * - `outboundTransform()`: compress snappy payload\n */\n inboundTransform(topic: TopicStr, data: Uint8Array): Uint8Array\n\n /**\n * Takes the data to be published (a topic and associated data) transforms the data. The\n * transformed data will then be used to create a `RawGossipsubMessage` to be sent to peers.\n */\n outboundTransform(topic: TopicStr, data: Uint8Array): Uint8Array\n}\n\nexport enum SignaturePolicy {\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 */\n 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 */\n StrictNoSign = 'StrictNoSign'\n}\n\nexport type PublishOpts = {\n allowPublishToZeroPeers?: boolean\n ignoreDuplicatePublishError?: boolean\n}\n\nexport enum PublishConfigType {\n Signing,\n Anonymous\n}\n\nexport type PublishConfig =\n | {\n type: PublishConfigType.Signing\n author: PeerId\n key: Uint8Array\n privateKey: PrivateKey\n }\n | { type: PublishConfigType.Anonymous }\n\nexport type RejectReasonObj =\n | { reason: RejectReason.Error; error: ValidateError }\n | { reason: Exclude }\n\nexport enum RejectReason {\n /**\n * The message failed the configured validation during decoding.\n * SelfOrigin is considered a ValidationError\n */\n Error = 'error',\n /**\n * Custom validator fn reported status IGNORE.\n */\n Ignore = 'ignore',\n /**\n * Custom validator fn reported status REJECT.\n */\n Reject = 'reject',\n /**\n * The peer that sent the message OR the source from field is blacklisted.\n * Causes messages to be ignored, not penalized, neither do score record creation.\n */\n Blacklisted = 'blacklisted'\n}\n\nexport enum ValidateError {\n /// The message has an invalid signature,\n InvalidSignature = 'invalid_signature',\n /// The sequence number was the incorrect size\n InvalidSeqno = 'invalid_seqno',\n /// The PeerId was invalid\n InvalidPeerId = 'invalid_peerid',\n /// Signature existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n SignaturePresent = 'signature_present',\n /// Sequence number existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n SeqnoPresent = 'seqno_present',\n /// Message source existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n FromPresent = 'from_present',\n /// The data transformation failed.\n TransformFailed = 'transform_failed'\n}\n\nexport enum MessageStatus {\n duplicate = 'duplicate',\n invalid = 'invalid',\n valid = 'valid'\n}\n\n/**\n * Store both Uint8Array and string message id so that we don't have to convert data between the two.\n * See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/274\n */\nexport type MessageId = {\n msgId: Uint8Array\n msgIdStr: MsgIdStr\n}\n\n/**\n * Typesafe conversion of MessageAcceptance -> RejectReason. TS ensures all values covered\n */\nexport function rejectReasonFromAcceptance(\n acceptance: Exclude\n): RejectReason.Ignore | RejectReason.Reject {\n switch (acceptance) {\n case TopicValidatorResult.Ignore:\n return RejectReason.Ignore\n case TopicValidatorResult.Reject:\n return RejectReason.Reject\n }\n}\n", "import { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport { StrictSign, StrictNoSign } from '@libp2p/interface-pubsub'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { PublishConfig, PublishConfigType } from '../types.js'\n\n/**\n * Prepare a PublishConfig object from a PeerId.\n */\nexport async function getPublishConfigFromPeerId(\n signaturePolicy: typeof StrictSign | typeof StrictNoSign,\n peerId?: PeerId\n): Promise {\n switch (signaturePolicy) {\n case StrictSign: {\n if (!peerId) {\n throw Error('Must provide PeerId')\n }\n\n if (peerId.privateKey == null) {\n throw Error('Cannot sign message, no private key present')\n }\n\n if (peerId.publicKey == null) {\n throw Error('Cannot sign message, no public key present')\n }\n\n // Transform privateKey once at initialization time instead of once per message\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return {\n type: PublishConfigType.Signing,\n author: peerId,\n key: peerId.publicKey,\n privateKey\n }\n }\n\n case StrictNoSign:\n return {\n type: PublishConfigType.Anonymous\n }\n\n default:\n throw new Error(`Unknown signature policy \"${signaturePolicy}\"`)\n }\n}\n", "export const ERR_INVALID_PEER_SCORE_PARAMS = 'ERR_INVALID_PEER_SCORE_PARAMS'\nexport const ERR_INVALID_PEER_SCORE_THRESHOLDS = 'ERR_INVALID_PEER_SCORE_THRESHOLDS'\n", "import { ERR_INVALID_PEER_SCORE_PARAMS } from './constants.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n// This file defines PeerScoreParams and TopicScoreParams interfaces\n// as well as constructors, default constructors, and validation functions\n// for these interfaces\n\nexport interface PeerScoreParams {\n /**\n * Score parameters per topic.\n */\n topics: Record\n\n /**\n * Aggregate topic score cap; this limits the total contribution of topics towards a positive\n * score. It must be positive (or 0 for no cap).\n */\n topicScoreCap: number\n\n /**\n * P5: Application-specific peer scoring\n */\n appSpecificScore: (p: string) => number\n appSpecificWeight: number\n\n /**\n * P6: IP-colocation factor.\n * The parameter has an associated counter which counts the number of peers with the same IP.\n * If the number of peers in the same IP exceeds IPColocationFactorThreshold, then the value\n * is the square of the difference, ie (PeersInSameIP - IPColocationThreshold)^2.\n * If the number of peers in the same IP is less than the threshold, then the value is 0.\n * The weight of the parameter MUST be negative, unless you want to disable for testing.\n * Note: In order to simulate many IPs in a managable manner when testing, you can set the weight to 0\n * thus disabling the IP colocation penalty.\n */\n IPColocationFactorWeight: number\n IPColocationFactorThreshold: number\n IPColocationFactorWhitelist: Set\n\n /**\n * P7: behavioural pattern penalties.\n * This parameter has an associated counter which tracks misbehaviour as detected by the\n * router. The router currently applies penalties for the following behaviors:\n * - attempting to re-graft before the prune backoff time has elapsed.\n * - not following up in IWANT requests for messages advertised with IHAVE.\n *\n * The value of the parameter is the square of the counter, which decays with BehaviourPenaltyDecay.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n behaviourPenaltyWeight: number\n behaviourPenaltyThreshold: number\n behaviourPenaltyDecay: number\n\n /**\n * the decay interval for parameter counters.\n */\n decayInterval: number\n\n /**\n * counter value below which it is considered 0.\n */\n decayToZero: number\n\n /**\n * time to remember counters for a disconnected peer.\n */\n retainScore: number\n}\n\nexport interface TopicScoreParams {\n /**\n * The weight of the topic.\n */\n topicWeight: number\n\n /**\n * P1: time in the mesh\n * This is the time the peer has ben grafted in the mesh.\n * The value of the parameter is the time/TimeInMeshQuantum, capped by TimeInMeshCap\n * The weight of the parameter MUST be positive (or zero to disable).\n */\n timeInMeshWeight: number\n timeInMeshQuantum: number\n timeInMeshCap: number\n\n /**\n * P2: first message deliveries\n * This is the number of message deliveries in the topic.\n * The value of the parameter is a counter, decaying with FirstMessageDeliveriesDecay, and capped\n * by FirstMessageDeliveriesCap.\n * The weight of the parameter MUST be positive (or zero to disable).\n */\n firstMessageDeliveriesWeight: number\n firstMessageDeliveriesDecay: number\n firstMessageDeliveriesCap: number\n\n /**\n * P3: mesh message deliveries\n * This is the number of message deliveries in the mesh, within the MeshMessageDeliveriesWindow of\n * message validation; deliveries during validation also count and are retroactively applied\n * when validation succeeds.\n * This window accounts for the minimum time before a hostile mesh peer trying to game the score\n * could replay back a valid message we just sent them.\n * It effectively tracks first and near-first deliveries, ie a message seen from a mesh peer\n * before we have forwarded it to them.\n * The parameter has an associated counter, decaying with MeshMessageDeliveriesDecay.\n * If the counter exceeds the threshold, its value is 0.\n * If the counter is below the MeshMessageDeliveriesThreshold, the value is the square of\n * the deficit, ie (MessageDeliveriesThreshold - counter)^2\n * The penalty is only activated after MeshMessageDeliveriesActivation time in the mesh.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n meshMessageDeliveriesWeight: number\n meshMessageDeliveriesDecay: number\n meshMessageDeliveriesCap: number\n meshMessageDeliveriesThreshold: number\n meshMessageDeliveriesWindow: number\n meshMessageDeliveriesActivation: number\n\n /**\n * P3b: sticky mesh propagation failures\n * This is a sticky penalty that applies when a peer gets pruned from the mesh with an active\n * mesh message delivery penalty.\n * The weight of the parameter MUST be negative (or zero to disable)\n */\n meshFailurePenaltyWeight: number\n meshFailurePenaltyDecay: number\n\n /**\n * P4: invalid messages\n * This is the number of invalid messages in the topic.\n * The value of the parameter is the square of the counter, decaying with\n * InvalidMessageDeliveriesDecay.\n * The weight of the parameter MUST be negative (or zero to disable).\n */\n invalidMessageDeliveriesWeight: number\n invalidMessageDeliveriesDecay: number\n}\n\nexport const defaultPeerScoreParams: PeerScoreParams = {\n topics: {},\n topicScoreCap: 10.0,\n appSpecificScore: () => 0.0,\n appSpecificWeight: 10.0,\n IPColocationFactorWeight: -5.0,\n IPColocationFactorThreshold: 10.0,\n IPColocationFactorWhitelist: new Set(),\n behaviourPenaltyWeight: -10.0,\n behaviourPenaltyThreshold: 0.0,\n behaviourPenaltyDecay: 0.2,\n decayInterval: 1000.0,\n decayToZero: 0.1,\n retainScore: 3600 * 1000\n}\n\nexport const defaultTopicScoreParams: TopicScoreParams = {\n topicWeight: 0.5,\n timeInMeshWeight: 1,\n timeInMeshQuantum: 1,\n timeInMeshCap: 3600,\n\n firstMessageDeliveriesWeight: 1,\n firstMessageDeliveriesDecay: 0.5,\n firstMessageDeliveriesCap: 2000,\n\n meshMessageDeliveriesWeight: -1,\n meshMessageDeliveriesDecay: 0.5,\n meshMessageDeliveriesCap: 100,\n meshMessageDeliveriesThreshold: 20,\n meshMessageDeliveriesWindow: 10,\n meshMessageDeliveriesActivation: 5000,\n\n meshFailurePenaltyWeight: -1,\n meshFailurePenaltyDecay: 0.5,\n\n invalidMessageDeliveriesWeight: -1,\n invalidMessageDeliveriesDecay: 0.3\n}\n\nexport function createPeerScoreParams(p: Partial = {}): PeerScoreParams {\n return {\n ...defaultPeerScoreParams,\n ...p,\n topics: p.topics\n ? Object.entries(p.topics).reduce((topics, [topic, topicScoreParams]) => {\n topics[topic] = createTopicScoreParams(topicScoreParams)\n return topics\n }, {} as Record)\n : {}\n }\n}\n\nexport function createTopicScoreParams(p: Partial = {}): TopicScoreParams {\n return {\n ...defaultTopicScoreParams,\n ...p\n }\n}\n\n// peer score parameter validation\nexport function validatePeerScoreParams(p: PeerScoreParams): void {\n for (const [topic, params] of Object.entries(p.topics)) {\n try {\n validateTopicScoreParams(params)\n } catch (e) {\n throw new CodeError(\n `invalid score parameters for topic ${topic}: ${(e as Error).message}`,\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n }\n\n // check that the topic score is 0 or something positive\n if (p.topicScoreCap < 0) {\n throw new CodeError('invalid topic score cap; must be positive (or 0 for no cap)', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check that we have an app specific score; the weight can be anything (but expected positive)\n if (p.appSpecificScore === null || p.appSpecificScore === undefined) {\n throw new CodeError('missing application specific score function', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the IP colocation factor\n if (p.IPColocationFactorWeight > 0) {\n throw new CodeError(\n 'invalid IPColocationFactorWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.IPColocationFactorWeight !== 0 && p.IPColocationFactorThreshold < 1) {\n throw new CodeError('invalid IPColocationFactorThreshold; must be at least 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the behaviour penalty\n if (p.behaviourPenaltyWeight > 0) {\n throw new CodeError(\n 'invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.behaviourPenaltyWeight !== 0 && (p.behaviourPenaltyDecay <= 0 || p.behaviourPenaltyDecay >= 1)) {\n throw new CodeError('invalid BehaviourPenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check the decay parameters\n if (p.decayInterval < 1000) {\n throw new CodeError('invalid DecayInterval; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.decayToZero <= 0 || p.decayToZero >= 1) {\n throw new CodeError('invalid DecayToZero; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // no need to check the score retention; a value of 0 means that we don't retain scores\n}\n\nexport function validateTopicScoreParams(p: TopicScoreParams): void {\n // make sure we have a sane topic weight\n if (p.topicWeight < 0) {\n throw new CodeError('invalid topic weight; must be >= 0', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P1\n if (p.timeInMeshQuantum === 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be non zero', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight < 0) {\n throw new CodeError('invalid TimeInMeshWeight; must be positive (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshQuantum <= 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshCap <= 0) {\n throw new CodeError('invalid TimeInMeshCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P2\n if (p.firstMessageDeliveriesWeight < 0) {\n throw new CodeError(\n 'invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (\n p.firstMessageDeliveriesWeight !== 0 &&\n (p.firstMessageDeliveriesDecay <= 0 || p.firstMessageDeliveriesDecay >= 1)\n ) {\n throw new CodeError('invalid FirstMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.firstMessageDeliveriesWeight !== 0 && p.firstMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid FirstMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P3\n if (p.meshMessageDeliveriesWeight > 0) {\n throw new CodeError(\n 'invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.meshMessageDeliveriesWeight !== 0 && (p.meshMessageDeliveriesDecay <= 0 || p.meshMessageDeliveriesDecay >= 1)) {\n throw new CodeError('invalid MeshMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesThreshold <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesThreshold; must be positive', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWindow < 0) {\n throw new CodeError('invalid MeshMessageDeliveriesWindow; must be non-negative', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesActivation < 1000) {\n throw new CodeError('invalid MeshMessageDeliveriesActivation; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P3b\n if (p.meshFailurePenaltyWeight > 0) {\n throw new CodeError(\n 'invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.meshFailurePenaltyWeight !== 0 && (p.meshFailurePenaltyDecay <= 0 || p.meshFailurePenaltyDecay >= 1)) {\n throw new CodeError('invalid MeshFailurePenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n\n // check P4\n if (p.invalidMessageDeliveriesWeight > 0) {\n throw new CodeError(\n 'invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)',\n ERR_INVALID_PEER_SCORE_PARAMS\n )\n }\n if (p.invalidMessageDeliveriesDecay <= 0 || p.invalidMessageDeliveriesDecay >= 1) {\n throw new CodeError('invalid InvalidMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS)\n }\n}\n", "import { ERR_INVALID_PEER_SCORE_THRESHOLDS } from './constants.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n// This file defines PeerScoreThresholds interface\n// as well as a constructor, default constructor, and validation function\n// for this interface\n\nexport interface PeerScoreThresholds {\n /**\n * gossipThreshold is the score threshold below which gossip propagation is supressed;\n * should be negative.\n */\n gossipThreshold: number\n\n /**\n * publishThreshold is the score threshold below which we shouldn't publish when using flood\n * publishing (also applies to fanout and floodsub peers); should be negative and <= GossipThreshold.\n */\n publishThreshold: number\n\n /**\n * graylistThreshold is the score threshold below which message processing is supressed altogether,\n * implementing an effective graylist according to peer score; should be negative and <= PublisThreshold.\n */\n graylistThreshold: number\n\n /**\n * acceptPXThreshold is the score threshold below which PX will be ignored; this should be positive\n * and limited to scores attainable by bootstrappers and other trusted nodes.\n */\n acceptPXThreshold: number\n\n /**\n * opportunisticGraftThreshold is the median mesh score threshold before triggering opportunistic\n * grafting; this should have a small positive value.\n */\n opportunisticGraftThreshold: number\n}\n\nexport const defaultPeerScoreThresholds: PeerScoreThresholds = {\n gossipThreshold: -10,\n publishThreshold: -50,\n graylistThreshold: -80,\n acceptPXThreshold: 10,\n opportunisticGraftThreshold: 20\n}\n\nexport function createPeerScoreThresholds(p: Partial = {}): PeerScoreThresholds {\n return {\n ...defaultPeerScoreThresholds,\n ...p\n }\n}\n\nexport function validatePeerScoreThresholds(p: PeerScoreThresholds): void {\n if (p.gossipThreshold > 0) {\n throw new CodeError('invalid gossip threshold; it must be <= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n if (p.publishThreshold > 0 || p.publishThreshold > p.gossipThreshold) {\n throw new CodeError(\n 'invalid publish threshold; it must be <= 0 and <= gossip threshold',\n ERR_INVALID_PEER_SCORE_THRESHOLDS\n )\n }\n if (p.graylistThreshold > 0 || p.graylistThreshold > p.publishThreshold) {\n throw new CodeError(\n 'invalid graylist threshold; it must be <= 0 and <= publish threshold',\n ERR_INVALID_PEER_SCORE_THRESHOLDS\n )\n }\n if (p.acceptPXThreshold < 0) {\n throw new CodeError('invalid accept PX threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n if (p.opportunisticGraftThreshold < 0) {\n throw new CodeError('invalid opportunistic grafting threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS)\n }\n}\n", "import type { PeerStats } from './peer-stats.js'\nimport type { PeerScoreParams } from './peer-score-params.js'\n\nexport function computeScore(\n peer: string,\n pstats: PeerStats,\n params: PeerScoreParams,\n peerIPs: Map>\n): number {\n let score = 0\n\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n const topicParams = params.topics[topic]\n if (topicParams === undefined) {\n // we are not scoring this topic\n return\n }\n\n let topicScore = 0\n\n // P1: time in Mesh\n if (tstats.inMesh) {\n let p1 = tstats.meshTime / topicParams.timeInMeshQuantum\n if (p1 > topicParams.timeInMeshCap) {\n p1 = topicParams.timeInMeshCap\n }\n topicScore += p1 * topicParams.timeInMeshWeight\n }\n\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap\n }\n topicScore += p2 * topicParams.firstMessageDeliveriesWeight\n\n // P3: mesh message deliveries\n if (\n tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold\n ) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries\n const p3 = deficit * deficit\n topicScore += p3 * topicParams.meshMessageDeliveriesWeight\n }\n\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty\n topicScore += p3b * topicParams.meshFailurePenaltyWeight\n\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries\n topicScore += p4 * topicParams.invalidMessageDeliveriesWeight\n\n // update score, mixing with topic weight\n score += topicScore * topicParams.topicWeight\n })\n\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap\n }\n\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer)\n score += p5 * params.appSpecificWeight\n\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return\n }\n\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip)\n const numPeersInIP = peersInIP ? peersInIP.size : 0\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold\n const p6 = surplus * surplus\n score += p6 * params.IPColocationFactorWeight\n }\n })\n\n // P7: behavioural pattern penalty\n if (pstats.behaviourPenalty > params.behaviourPenaltyThreshold) {\n const excess = pstats.behaviourPenalty - params.behaviourPenaltyThreshold\n const p7 = excess * excess\n score += p7 * params.behaviourPenaltyWeight\n }\n\n return score\n}\n", "import { TimeCacheDuration } from '../constants.js'\nimport Denque from 'denque'\n\nexport enum DeliveryRecordStatus {\n /**\n * we don't know (yet) if the message is valid\n */\n unknown,\n /**\n * we know the message is valid\n */\n valid,\n /**\n * we know the message is invalid\n */\n invalid,\n /**\n * we were instructed by the validator to ignore the message\n */\n ignored\n}\n\nexport interface DeliveryRecord {\n status: DeliveryRecordStatus\n firstSeen: number\n validated: number\n peers: Set\n}\n\ninterface DeliveryQueueEntry {\n msgId: string\n expire: number\n}\n\n/**\n * Map of canonical message ID to DeliveryRecord\n *\n * Maintains an internal queue for efficient gc of old messages\n */\nexport class MessageDeliveries {\n private records: Map\n public queue: Denque\n\n constructor() {\n this.records = new Map()\n this.queue = new Denque()\n }\n\n ensureRecord(msgIdStr: string): DeliveryRecord {\n let drec = this.records.get(msgIdStr)\n if (drec) {\n return drec\n }\n\n // record doesn't exist yet\n // create record\n drec = {\n status: DeliveryRecordStatus.unknown,\n firstSeen: Date.now(),\n validated: 0,\n peers: new Set()\n }\n this.records.set(msgIdStr, drec)\n\n // and add msgId to the queue\n const entry: DeliveryQueueEntry = {\n msgId: msgIdStr,\n expire: Date.now() + TimeCacheDuration\n }\n this.queue.push(entry)\n\n return drec\n }\n\n gc(): void {\n const now = Date.now()\n // queue is sorted by expiry time\n // remove expired messages, remove from queue until first un-expired message found\n let head = this.queue.peekFront()\n while (head && head.expire < now) {\n this.records.delete(head.msgId)\n this.queue.shift()\n head = this.queue.peekFront()\n }\n }\n\n clear(): void {\n this.records.clear()\n this.queue.clear()\n }\n}\n", "/**\n * Exclude up to `ineed` items from a set if item meets condition `cond`\n */\nexport function removeItemsFromSet(\n superSet: Set,\n ineed: number,\n cond: (peer: T) => boolean = () => true\n): Set {\n const subset = new Set()\n if (ineed <= 0) return subset\n\n for (const id of superSet) {\n if (subset.size >= ineed) break\n if (cond(id)) {\n subset.add(id)\n superSet.delete(id)\n }\n }\n\n return subset\n}\n\n/**\n * Exclude up to `ineed` items from a set\n */\nexport function removeFirstNItemsFromSet(superSet: Set, ineed: number): Set {\n return removeItemsFromSet(superSet, ineed, () => true)\n}\n\nexport class MapDef extends Map {\n constructor(private readonly getDefault: () => V) {\n super()\n }\n\n getOrDefault(key: K): V {\n let value = super.get(key)\n if (value === undefined) {\n value = this.getDefault()\n this.set(key, value)\n }\n return value\n }\n}\n", "import { PeerScoreParams, validatePeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats, TopicStats } from './peer-stats.js'\nimport { computeScore } from './compute-score.js'\nimport { MessageDeliveries, DeliveryRecordStatus } from './message-deliveries.js'\nimport { logger } from '@libp2p/logger'\nimport { MsgIdStr, PeerIdStr, RejectReason, TopicStr, IPStr } from '../types.js'\nimport type { Metrics, ScorePenalty } from '../metrics.js'\nimport { MapDef } from '../utils/set.js'\n\nconst log = logger('libp2p:gossipsub:score')\n\ninterface PeerScoreOpts {\n /**\n * Miliseconds to cache computed score per peer\n */\n scoreCacheValidityMs: number\n\n computeScore?: typeof computeScore\n}\n\ninterface ScoreCacheEntry {\n /** The cached score */\n score: number\n /** Unix timestamp in miliseconds, the time after which the cached score for a peer is no longer valid */\n cacheUntil: number\n}\n\nexport type PeerScoreStatsDump = Record\n\nexport class PeerScore {\n /**\n * Per-peer stats for score calculation\n */\n readonly peerStats = new Map()\n /**\n * IP colocation tracking; maps IP => set of peers.\n */\n readonly peerIPs = new MapDef>(() => new Set())\n /**\n * Cache score up to decayInterval if topic stats are unchanged.\n */\n readonly scoreCache = new Map()\n /**\n * Recent message delivery timing/participants\n */\n readonly deliveryRecords = new MessageDeliveries()\n\n _backgroundInterval?: ReturnType\n\n private readonly scoreCacheValidityMs: number\n private readonly computeScore: typeof computeScore\n\n constructor(readonly params: PeerScoreParams, private readonly metrics: Metrics | null, opts: PeerScoreOpts) {\n validatePeerScoreParams(params)\n this.scoreCacheValidityMs = opts.scoreCacheValidityMs\n this.computeScore = opts.computeScore ?? computeScore\n }\n\n get size(): number {\n return this.peerStats.size\n }\n\n /**\n * Start PeerScore instance\n */\n start(): void {\n if (this._backgroundInterval) {\n log('Peer score already running')\n return\n }\n this._backgroundInterval = setInterval(() => this.background(), this.params.decayInterval)\n log('started')\n }\n\n /**\n * Stop PeerScore instance\n */\n stop(): void {\n if (!this._backgroundInterval) {\n log('Peer score already stopped')\n return\n }\n clearInterval(this._backgroundInterval)\n delete this._backgroundInterval\n this.peerIPs.clear()\n this.peerStats.clear()\n this.deliveryRecords.clear()\n log('stopped')\n }\n\n /**\n * Periodic maintenance\n */\n background(): void {\n this.refreshScores()\n this.deliveryRecords.gc()\n }\n\n dumpPeerScoreStats(): PeerScoreStatsDump {\n return Object.fromEntries(Array.from(this.peerStats.entries()).map(([peer, stats]) => [peer, stats]))\n }\n\n /**\n * Decays scores, and purges score records for disconnected peers once their expiry has elapsed.\n */\n public refreshScores(): void {\n const now = Date.now()\n const decayToZero = this.params.decayToZero\n\n this.peerStats.forEach((pstats, id) => {\n if (!pstats.connected) {\n // has the retention period expired?\n if (now > pstats.expire) {\n // yes, throw it away (but clean up the IP tracking first)\n this.removeIPsForPeer(id, pstats.knownIPs)\n this.peerStats.delete(id)\n this.scoreCache.delete(id)\n }\n\n // we don't decay retained scores, as the peer is not active.\n // this way the peer cannot reset a negative score by simply disconnecting and reconnecting,\n // unless the retention period has elapsed.\n // similarly, a well behaved peer does not lose its score by getting disconnected.\n return\n }\n\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n const tparams = this.params.topics[topic]\n if (tparams === undefined) {\n // we are not scoring this topic\n // should be unreachable, we only add scored topics to pstats\n return\n }\n\n // decay counters\n tstats.firstMessageDeliveries *= tparams.firstMessageDeliveriesDecay\n if (tstats.firstMessageDeliveries < decayToZero) {\n tstats.firstMessageDeliveries = 0\n }\n\n tstats.meshMessageDeliveries *= tparams.meshMessageDeliveriesDecay\n if (tstats.meshMessageDeliveries < decayToZero) {\n tstats.meshMessageDeliveries = 0\n }\n\n tstats.meshFailurePenalty *= tparams.meshFailurePenaltyDecay\n if (tstats.meshFailurePenalty < decayToZero) {\n tstats.meshFailurePenalty = 0\n }\n\n tstats.invalidMessageDeliveries *= tparams.invalidMessageDeliveriesDecay\n if (tstats.invalidMessageDeliveries < decayToZero) {\n tstats.invalidMessageDeliveries = 0\n }\n\n // update mesh time and activate mesh message delivery parameter if need be\n if (tstats.inMesh) {\n tstats.meshTime = now - tstats.graftTime\n if (tstats.meshTime > tparams.meshMessageDeliveriesActivation) {\n tstats.meshMessageDeliveriesActive = true\n }\n }\n })\n\n // decay P7 counter\n pstats.behaviourPenalty *= this.params.behaviourPenaltyDecay\n if (pstats.behaviourPenalty < decayToZero) {\n pstats.behaviourPenalty = 0\n }\n })\n }\n\n /**\n * Return the score for a peer\n */\n score(id: PeerIdStr): number {\n this.metrics?.scoreFnCalls.inc()\n\n const pstats = this.peerStats.get(id)\n if (!pstats) {\n return 0\n }\n\n const now = Date.now()\n const cacheEntry = this.scoreCache.get(id)\n\n // Found cached score within validity period\n if (cacheEntry && cacheEntry.cacheUntil > now) {\n return cacheEntry.score\n }\n\n this.metrics?.scoreFnRuns.inc()\n\n const score = this.computeScore(id, pstats, this.params, this.peerIPs)\n const cacheUntil = now + this.scoreCacheValidityMs\n\n if (cacheEntry) {\n this.metrics?.scoreCachedDelta.observe(Math.abs(score - cacheEntry.score))\n cacheEntry.score = score\n cacheEntry.cacheUntil = cacheUntil\n } else {\n this.scoreCache.set(id, { score, cacheUntil })\n }\n\n return score\n }\n\n /**\n * Apply a behavioural penalty to a peer\n */\n addPenalty(id: PeerIdStr, penalty: number, penaltyLabel: ScorePenalty): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n pstats.behaviourPenalty += penalty\n this.metrics?.onScorePenalty(penaltyLabel)\n }\n }\n\n addPeer(id: PeerIdStr): void {\n // create peer stats (not including topic stats for each topic to be scored)\n // topic stats will be added as needed\n const pstats: PeerStats = {\n connected: true,\n expire: 0,\n topics: {},\n knownIPs: new Set(),\n behaviourPenalty: 0\n }\n this.peerStats.set(id, pstats)\n }\n\n /** Adds a new IP to a peer, if the peer is not known the update is ignored */\n addIP(id: PeerIdStr, ip: string): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n pstats.knownIPs.add(ip)\n }\n\n this.peerIPs.getOrDefault(ip).add(id)\n }\n\n /** Remove peer association with IP */\n removeIP(id: PeerIdStr, ip: string): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n pstats.knownIPs.delete(ip)\n }\n\n const peersWithIP = this.peerIPs.get(ip)\n if (peersWithIP) {\n peersWithIP.delete(id)\n if (peersWithIP.size === 0) {\n this.peerIPs.delete(ip)\n }\n }\n }\n\n removePeer(id: PeerIdStr): void {\n const pstats = this.peerStats.get(id)\n if (!pstats) {\n return\n }\n\n // decide whether to retain the score; this currently only retains non-positive scores\n // to dissuade attacks on the score function.\n if (this.score(id) > 0) {\n this.removeIPsForPeer(id, pstats.knownIPs)\n this.peerStats.delete(id)\n return\n }\n\n // furthermore, when we decide to retain the score, the firstMessageDelivery counters are\n // reset to 0 and mesh delivery penalties applied.\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n tstats.firstMessageDeliveries = 0\n\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold\n if (tstats.inMesh && tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries\n tstats.meshFailurePenalty += deficit * deficit\n }\n\n tstats.inMesh = false\n tstats.meshMessageDeliveriesActive = false\n })\n\n pstats.connected = false\n pstats.expire = Date.now() + this.params.retainScore\n }\n\n /** Handles scoring functionality as a peer GRAFTs to a topic. */\n graft(id: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n // if we are scoring the topic, update the mesh status.\n tstats.inMesh = true\n tstats.graftTime = Date.now()\n tstats.meshTime = 0\n tstats.meshMessageDeliveriesActive = false\n }\n }\n }\n\n /** Handles scoring functionality as a peer PRUNEs from a topic. */\n prune(id: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(id)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n // sticky mesh delivery rate failure penalty\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold\n if (tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries\n tstats.meshFailurePenalty += deficit * deficit\n }\n tstats.meshMessageDeliveriesActive = false\n tstats.inMesh = false\n\n // TODO: Consider clearing score cache on important penalties\n // this.scoreCache.delete(id)\n }\n }\n }\n\n validateMessage(msgIdStr: MsgIdStr): void {\n this.deliveryRecords.ensureRecord(msgIdStr)\n }\n\n deliverMessage(from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr): void {\n this.markFirstMessageDelivery(from, topic)\n\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n const now = Date.now()\n\n // defensive check that this is the first delivery trace -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n log(\n 'unexpected delivery: message from %s was first seen %s ago and has delivery status %s',\n from,\n now - drec.firstSeen,\n DeliveryRecordStatus[drec.status]\n )\n return\n }\n\n // mark the message as valid and reward mesh peers that have already forwarded it to us\n drec.status = DeliveryRecordStatus.valid\n drec.validated = now\n drec.peers.forEach((p) => {\n // this check is to make sure a peer can't send us a message twice and get a double count\n // if it is a first delivery.\n if (p !== from.toString()) {\n this.markDuplicateMessageDelivery(p, topic)\n }\n })\n }\n\n /**\n * Similar to `rejectMessage` except does not require the message id or reason for an invalid message.\n */\n rejectInvalidMessage(from: PeerIdStr, topic: TopicStr): void {\n this.markInvalidMessageDelivery(from, topic)\n }\n\n rejectMessage(from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr, reason: RejectReason): void {\n switch (reason) {\n // these messages are not tracked, but the peer is penalized as they are invalid\n case RejectReason.Error:\n this.markInvalidMessageDelivery(from, topic)\n return\n\n // we ignore those messages, so do nothing.\n case RejectReason.Blacklisted:\n return\n\n // the rest are handled after record creation\n }\n\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n\n // defensive check that this is the first rejection -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n log(\n 'unexpected rejection: message from %s was first seen %s ago and has delivery status %d',\n from,\n Date.now() - drec.firstSeen,\n DeliveryRecordStatus[drec.status]\n )\n return\n }\n\n if (reason === RejectReason.Ignore) {\n // we were explicitly instructed by the validator to ignore the message but not penalize the peer\n drec.status = DeliveryRecordStatus.ignored\n drec.peers.clear()\n return\n }\n\n // mark the message as invalid and penalize peers that have already forwarded it.\n drec.status = DeliveryRecordStatus.invalid\n\n this.markInvalidMessageDelivery(from, topic)\n drec.peers.forEach((p) => {\n this.markInvalidMessageDelivery(p, topic)\n })\n\n // release the delivery time tracking map to free some memory early\n drec.peers.clear()\n }\n\n duplicateMessage(from: PeerIdStr, msgIdStr: MsgIdStr, topic: TopicStr): void {\n const drec = this.deliveryRecords.ensureRecord(msgIdStr)\n\n if (drec.peers.has(from)) {\n // we have already seen this duplicate\n return\n }\n\n switch (drec.status) {\n case DeliveryRecordStatus.unknown:\n // the message is being validated; track the peer delivery and wait for\n // the Deliver/Reject/Ignore notification.\n drec.peers.add(from)\n break\n\n case DeliveryRecordStatus.valid:\n // mark the peer delivery time to only count a duplicate delivery once.\n drec.peers.add(from)\n this.markDuplicateMessageDelivery(from, topic, drec.validated)\n break\n\n case DeliveryRecordStatus.invalid:\n // we no longer track delivery time\n this.markInvalidMessageDelivery(from, topic)\n break\n\n case DeliveryRecordStatus.ignored:\n // the message was ignored; do nothing (we don't know if it was valid)\n break\n }\n }\n\n /**\n * Increments the \"invalid message deliveries\" counter for all scored topics the message is published in.\n */\n public markInvalidMessageDelivery(from: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(from)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n tstats.invalidMessageDeliveries += 1\n }\n }\n }\n\n /**\n * Increments the \"first message deliveries\" counter for all scored topics the message is published in,\n * as well as the \"mesh message deliveries\" counter, if the peer is in the mesh for the topic.\n * Messages already known (with the seenCache) are counted with markDuplicateMessageDelivery()\n */\n public markFirstMessageDelivery(from: PeerIdStr, topic: TopicStr): void {\n const pstats = this.peerStats.get(from)\n if (pstats) {\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats) {\n let cap = this.params.topics[topic].firstMessageDeliveriesCap\n tstats.firstMessageDeliveries = Math.min(cap, tstats.firstMessageDeliveries + 1)\n\n if (tstats.inMesh) {\n cap = this.params.topics[topic].meshMessageDeliveriesCap\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1)\n }\n }\n }\n }\n\n /**\n * Increments the \"mesh message deliveries\" counter for messages we've seen before,\n * as long the message was received within the P3 window.\n */\n public markDuplicateMessageDelivery(from: PeerIdStr, topic: TopicStr, validatedTime?: number): void {\n const pstats = this.peerStats.get(from)\n if (pstats) {\n const now = validatedTime !== undefined ? Date.now() : 0\n\n const tstats = this.getPtopicStats(pstats, topic)\n if (tstats && tstats.inMesh) {\n const tparams = this.params.topics[topic]\n\n // check against the mesh delivery window -- if the validated time is passed as 0, then\n // the message was received before we finished validation and thus falls within the mesh\n // delivery window.\n if (validatedTime !== undefined) {\n const deliveryDelayMs = now - validatedTime\n const isLateDelivery = deliveryDelayMs > tparams.meshMessageDeliveriesWindow\n this.metrics?.onDuplicateMsgDelivery(topic, deliveryDelayMs, isLateDelivery)\n\n if (isLateDelivery) {\n return\n }\n }\n\n const cap = tparams.meshMessageDeliveriesCap\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1)\n }\n }\n }\n\n /**\n * Removes an IP list from the tracking list for a peer.\n */\n private removeIPsForPeer(id: PeerIdStr, ipsToRemove: Set): void {\n for (const ipToRemove of ipsToRemove) {\n const peerSet = this.peerIPs.get(ipToRemove)\n if (peerSet) {\n peerSet.delete(id)\n if (peerSet.size === 0) {\n this.peerIPs.delete(ipToRemove)\n }\n }\n }\n }\n\n /**\n * Returns topic stats if they exist, otherwise if the supplied parameters score the\n * topic, inserts the default stats and returns a reference to those. If neither apply, returns None.\n */\n private getPtopicStats(pstats: PeerStats, topic: TopicStr): TopicStats | null {\n let topicStats: TopicStats | undefined = pstats.topics[topic]\n\n if (topicStats !== undefined) {\n return topicStats\n }\n\n if (this.params.topics[topic] !== undefined) {\n topicStats = {\n inMesh: false,\n graftTime: 0,\n meshTime: 0,\n firstMessageDeliveries: 0,\n meshMessageDeliveries: 0,\n meshMessageDeliveriesActive: false,\n meshFailurePenalty: 0,\n invalidMessageDeliveries: 0\n }\n pstats.topics[topic] = topicStats\n\n return topicStats\n }\n\n return null\n }\n}\n", "import { MsgIdStr, MsgIdToStrFn, PeerIdStr, RejectReason } from './types.js'\nimport type { Metrics } from './metrics.js'\n\n/**\n * IWantTracer is an internal tracer that tracks IWANT requests in order to penalize\n * peers who don't follow up on IWANT requests after an IHAVE advertisement.\n * The tracking of promises is probabilistic to avoid using too much memory.\n *\n * Note: Do not confuse these 'promises' with JS Promise objects.\n * These 'promises' are merely expectations of a peer's behavior.\n */\nexport class IWantTracer {\n /**\n * Promises to deliver a message\n * Map per message id, per peer, promise expiration time\n */\n private readonly promises = new Map>()\n /**\n * First request time by msgId. Used for metrics to track expire times.\n * Necessary to know if peers are actually breaking promises or simply sending them a bit later\n */\n private readonly requestMsByMsg = new Map()\n private readonly requestMsByMsgExpire: number\n\n constructor(\n private readonly gossipsubIWantFollowupMs: number,\n private readonly msgIdToStrFn: MsgIdToStrFn,\n private readonly metrics: Metrics | null\n ) {\n this.requestMsByMsgExpire = 10 * gossipsubIWantFollowupMs\n }\n\n get size(): number {\n return this.promises.size\n }\n\n get requestMsByMsgSize(): number {\n return this.requestMsByMsg.size\n }\n\n /**\n * Track a promise to deliver a message from a list of msgIds we are requesting\n */\n addPromise(from: PeerIdStr, msgIds: Uint8Array[]): void {\n // pick msgId randomly from the list\n const ix = Math.floor(Math.random() * msgIds.length)\n const msgId = msgIds[ix]\n const msgIdStr = this.msgIdToStrFn(msgId)\n\n let expireByPeer = this.promises.get(msgIdStr)\n if (!expireByPeer) {\n expireByPeer = new Map()\n this.promises.set(msgIdStr, expireByPeer)\n }\n\n const now = Date.now()\n\n // If a promise for this message id and peer already exists we don't update the expiry\n if (!expireByPeer.has(from)) {\n expireByPeer.set(from, now + this.gossipsubIWantFollowupMs)\n\n if (this.metrics) {\n this.metrics.iwantPromiseStarted.inc(1)\n if (!this.requestMsByMsg.has(msgIdStr)) {\n this.requestMsByMsg.set(msgIdStr, now)\n }\n }\n }\n }\n\n /**\n * Returns the number of broken promises for each peer who didn't follow up on an IWANT request.\n *\n * This should be called not too often relative to the expire times, since it iterates over the whole data.\n */\n getBrokenPromises(): Map {\n const now = Date.now()\n const result = new Map()\n\n let brokenPromises = 0\n\n this.promises.forEach((expireByPeer, msgId) => {\n expireByPeer.forEach((expire, p) => {\n // the promise has been broken\n if (expire < now) {\n // add 1 to result\n result.set(p, (result.get(p) ?? 0) + 1)\n // delete from tracked promises\n expireByPeer.delete(p)\n // for metrics\n brokenPromises++\n }\n })\n // clean up empty promises for a msgId\n if (!expireByPeer.size) {\n this.promises.delete(msgId)\n }\n })\n\n this.metrics?.iwantPromiseBroken.inc(brokenPromises)\n\n return result\n }\n\n /**\n * Someone delivered a message, stop tracking promises for it\n */\n deliverMessage(msgIdStr: MsgIdStr, isDuplicate = false): void {\n this.trackMessage(msgIdStr)\n\n const expireByPeer = this.promises.get(msgIdStr)\n\n // Expired promise, check requestMsByMsg\n if (expireByPeer) {\n this.promises.delete(msgIdStr)\n\n if (this.metrics) {\n this.metrics.iwantPromiseResolved.inc(1)\n if (isDuplicate) this.metrics.iwantPromiseResolvedFromDuplicate.inc(1)\n this.metrics.iwantPromiseResolvedPeers.inc(expireByPeer.size)\n }\n }\n }\n\n /**\n * A message got rejected, so we can stop tracking promises and let the score penalty apply from invalid message delivery,\n * unless its an obviously invalid message.\n */\n rejectMessage(msgIdStr: MsgIdStr, reason: RejectReason): void {\n this.trackMessage(msgIdStr)\n\n // A message got rejected, so we can stop tracking promises and let the score penalty apply.\n // With the expection of obvious invalid messages\n switch (reason) {\n case RejectReason.Error:\n return\n }\n\n this.promises.delete(msgIdStr)\n }\n\n clear(): void {\n this.promises.clear()\n }\n\n prune(): void {\n const maxMs = Date.now() - this.requestMsByMsgExpire\n let count = 0\n\n for (const [k, v] of this.requestMsByMsg.entries()) {\n if (v < maxMs) {\n // messages that stay too long in the requestMsByMsg map, delete\n this.requestMsByMsg.delete(k)\n count++\n } else {\n // recent messages, keep them\n // sort by insertion order\n break\n }\n }\n\n this.metrics?.iwantMessagePruned.inc(count)\n }\n\n private trackMessage(msgIdStr: MsgIdStr): void {\n if (this.metrics) {\n const requestMs = this.requestMsByMsg.get(msgIdStr)\n if (requestMs !== undefined) {\n this.metrics.iwantPromiseDeliveryTime.observe((Date.now() - requestMs) / 1000)\n this.requestMsByMsg.delete(msgIdStr)\n }\n }\n }\n}\n", "type SimpleTimeCacheOpts = {\n validityMs: number\n}\n\ntype CacheValue = {\n value: T\n validUntilMs: number\n}\n\n/**\n * This is similar to https://github.com/daviddias/time-cache/blob/master/src/index.js\n * for our own need, we don't use lodash throttle to improve performance.\n * This gives 4x - 5x performance gain compared to npm TimeCache\n */\nexport class SimpleTimeCache {\n private readonly entries = new Map>()\n private readonly validityMs: number\n\n constructor(opts: SimpleTimeCacheOpts) {\n this.validityMs = opts.validityMs\n\n // allow negative validityMs so that this does not cache anything, spec test compliance.spec.js\n // sends duplicate messages and expect peer to receive all. Application likely uses positive validityMs\n }\n\n get size(): number {\n return this.entries.size\n }\n\n /** Returns true if there was a key collision and the entry is dropped */\n put(key: string | number, value: T): boolean {\n if (this.entries.has(key)) {\n // Key collisions break insertion order in the entries cache, which break prune logic.\n // prune relies on each iterated entry to have strictly ascending validUntilMs, else it\n // won't prune expired entries and SimpleTimeCache will grow unexpectedly.\n // As of Oct 2022 NodeJS v16, inserting the same key twice with different value does not\n // change the key position in the iterator stream. A unit test asserts this behaviour.\n return true\n }\n\n this.entries.set(key, { value, validUntilMs: Date.now() + this.validityMs })\n return false\n }\n\n prune(): void {\n const now = Date.now()\n\n for (const [k, v] of this.entries.entries()) {\n if (v.validUntilMs < now) {\n this.entries.delete(k)\n } else {\n // Entries are inserted with strictly ascending validUntilMs.\n // Stop early to save iterations\n break\n }\n }\n }\n\n has(key: string): boolean {\n return this.entries.has(key)\n }\n\n get(key: string | number): T | undefined {\n const value = this.entries.get(key)\n return value && value.validUntilMs >= Date.now() ? value.value : undefined\n }\n\n clear(): void {\n this.entries.clear()\n }\n}\n", "import { TopicValidatorResult } from '@libp2p/interface-pubsub'\nimport type { IRPC } from './message/rpc.js'\nimport type { PeerScoreThresholds } from './score/peer-score-thresholds.js'\nimport { MessageStatus, PeerIdStr, RejectReason, RejectReasonObj, TopicStr, ValidateError } from './types.js'\n\n/** Topic label as provided in `topicStrToLabel` */\nexport type TopicLabel = string\nexport type TopicStrToLabel = Map\n\nexport enum MessageSource {\n forward = 'forward',\n publish = 'publish'\n}\n\ntype LabelsGeneric = Record\ntype CollectFn = (metric: Gauge) => void\n\ninterface Gauge {\n // Sorry for this mess, `prom-client` API choices are not great\n // If the function signature was `inc(value: number, labels?: Labels)`, this would be simpler\n inc(value?: number): void\n inc(labels: Labels, value?: number): void\n inc(arg1?: Labels | number, arg2?: number): void\n\n set(value: number): void\n set(labels: Labels, value: number): void\n set(arg1?: Labels | number, arg2?: number): void\n\n addCollect(collectFn: CollectFn): void\n}\n\ninterface Histogram {\n startTimer(): () => void\n\n observe(value: number): void\n observe(labels: Labels, values: number): void\n observe(arg1: Labels | number, arg2?: number): void\n\n reset(): void\n}\n\ninterface AvgMinMax {\n set(values: number[]): void\n set(labels: Labels, values: number[]): void\n set(arg1?: Labels | number[], arg2?: number[]): void\n}\n\ntype GaugeConfig = {\n name: string\n help: string\n labelNames?: keyof Labels extends string ? (keyof Labels)[] : undefined\n}\n\ntype HistogramConfig = {\n name: string\n help: string\n labelNames?: (keyof Labels)[]\n buckets?: number[]\n}\n\ntype AvgMinMaxConfig = GaugeConfig\n\nexport interface MetricsRegister {\n gauge(config: GaugeConfig): Gauge\n histogram(config: HistogramConfig): Histogram\n avgMinMax(config: AvgMinMaxConfig): AvgMinMax\n}\n\nexport enum InclusionReason {\n /** Peer was a fanaout peer. */\n Fanout = 'fanout',\n /** Included from random selection. */\n Random = 'random',\n /** Peer subscribed. */\n Subscribed = 'subscribed',\n /** On heartbeat, peer was included to fill the outbound quota. */\n Outbound = 'outbound',\n /** On heartbeat, not enough peers in mesh */\n NotEnough = 'not_enough',\n /** On heartbeat opportunistic grafting due to low mesh score */\n Opportunistic = 'opportunistic'\n}\n\n/// Reasons why a peer was removed from the mesh.\nexport enum ChurnReason {\n /// Peer disconnected.\n Dc = 'disconnected',\n /// Peer had a bad score.\n BadScore = 'bad_score',\n /// Peer sent a PRUNE.\n Prune = 'prune',\n /// Peer unsubscribed.\n Unsub = 'unsubscribed',\n /// Too many peers.\n Excess = 'excess'\n}\n\n/// Kinds of reasons a peer's score has been penalized\nexport enum ScorePenalty {\n /// A peer grafted before waiting the back-off time.\n GraftBackoff = 'graft_backoff',\n /// A Peer did not respond to an IWANT request in time.\n BrokenPromise = 'broken_promise',\n /// A Peer did not send enough messages as expected.\n MessageDeficit = 'message_deficit',\n /// Too many peers under one IP address.\n IPColocation = 'IP_colocation'\n}\n\nexport enum IHaveIgnoreReason {\n LowScore = 'low_score',\n MaxIhave = 'max_ihave',\n MaxIasked = 'max_iasked'\n}\n\nexport enum ScoreThreshold {\n graylist = 'graylist',\n publish = 'publish',\n gossip = 'gossip',\n mesh = 'mesh'\n}\n\nexport type PeersByScoreThreshold = Record\n\nexport type ToSendGroupCount = {\n direct: number\n floodsub: number\n mesh: number\n fanout: number\n}\n\nexport type ToAddGroupCount = {\n fanout: number\n random: number\n}\n\nexport type PromiseDeliveredStats =\n | { expired: false; requestedCount: number; maxDeliverMs: number }\n | { expired: true; maxDeliverMs: number }\n\nexport type TopicScoreWeights = { p1w: T; p2w: T; p3w: T; p3bw: T; p4w: T }\nexport type ScoreWeights = {\n byTopic: Map>\n p5w: T\n p6w: T\n p7w: T\n score: T\n}\n\nexport type Metrics = ReturnType\n\n/**\n * A collection of metrics used throughout the Gossipsub behaviour.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function getMetrics(\n register: MetricsRegister,\n topicStrToLabel: TopicStrToLabel,\n opts: { gossipPromiseExpireSec: number; behaviourPenaltyThreshold: number; maxMeshMessageDeliveriesWindowSec: number }\n) {\n // Using function style instead of class to prevent having to re-declare all MetricsPrometheus types.\n\n return {\n /* Metrics for static config */\n protocolsEnabled: register.gauge<{ protocol: string }>({\n name: 'gossipsub_protocol',\n help: 'Status of enabled protocols',\n labelNames: ['protocol']\n }),\n\n /* Metrics per known topic */\n /** Status of our subscription to this topic. This metric allows analyzing other topic metrics\n * filtered by our current subscription status.\n * = rust-libp2p `topic_subscription_status` */\n topicSubscriptionStatus: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_topic_subscription_status',\n help: 'Status of our subscription to this topic',\n labelNames: ['topicStr']\n }),\n /** Number of peers subscribed to each topic. This allows us to analyze a topic's behaviour\n * regardless of our subscription status. */\n topicPeersCount: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_topic_peer_count',\n help: 'Number of peers subscribed to each topic',\n labelNames: ['topicStr']\n }),\n\n /* Metrics regarding mesh state */\n /** Number of peers in our mesh. This metric should be updated with the count of peers for a\n * topic in the mesh regardless of inclusion and churn events.\n * = rust-libp2p `mesh_peer_counts` */\n meshPeerCounts: register.gauge<{ topicStr: TopicStr }>({\n name: 'gossipsub_mesh_peer_count',\n help: 'Number of peers in our mesh',\n labelNames: ['topicStr']\n }),\n /** Number of times we include peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_inclusion_events` */\n meshPeerInclusionEvents: register.gauge<{ topic: TopicLabel; reason: InclusionReason }>({\n name: 'gossipsub_mesh_peer_inclusion_events_total',\n help: 'Number of times we include peers in a topic mesh for different reasons',\n labelNames: ['topic', 'reason']\n }),\n /** Number of times we remove peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_churn_events` */\n meshPeerChurnEvents: register.gauge<{ topic: TopicLabel; reason: ChurnReason }>({\n name: 'gossipsub_peer_churn_events_total',\n help: 'Number of times we remove peers in a topic mesh for different reasons',\n labelNames: ['topic', 'reason']\n }),\n\n /* General Metrics */\n /** Gossipsub supports floodsub, gossipsub v1.0 and gossipsub v1.1. Peers are classified based\n * on which protocol they support. This metric keeps track of the number of peers that are\n * connected of each type. */\n peersPerProtocol: register.gauge<{ protocol: string }>({\n name: 'gossipsub_peers_per_protocol_count',\n help: 'Peers connected for each topic',\n labelNames: ['protocol']\n }),\n /** The time it takes to complete one iteration of the heartbeat. */\n heartbeatDuration: register.histogram({\n name: 'gossipsub_heartbeat_duration_seconds',\n help: 'The time it takes to complete one iteration of the heartbeat',\n // Should take <10ms, over 1s it's a huge issue that needs debugging, since a heartbeat will be cancelled\n buckets: [0.01, 0.1, 1]\n }),\n /** Heartbeat run took longer than heartbeat interval so next is skipped */\n heartbeatSkipped: register.gauge({\n name: 'gossipsub_heartbeat_skipped',\n help: 'Heartbeat run took longer than heartbeat interval so next is skipped'\n }),\n\n /** Message validation results for each topic.\n * Invalid == Reject?\n * = rust-libp2p `invalid_messages`, `accepted_messages`, `ignored_messages`, `rejected_messages` */\n asyncValidationResult: register.gauge<{ topic: TopicLabel; acceptance: TopicValidatorResult }>({\n name: 'gossipsub_async_validation_result_total',\n help: 'Message validation result for each topic',\n labelNames: ['topic', 'acceptance']\n }),\n /** When the user validates a message, it tries to re propagate it to its mesh peers. If the\n * message expires from the memcache before it can be validated, we count this a cache miss\n * and it is an indicator that the memcache size should be increased.\n * = rust-libp2p `mcache_misses` */\n asyncValidationMcacheHit: register.gauge<{ hit: 'hit' | 'miss' }>({\n name: 'gossipsub_async_validation_mcache_hit_total',\n help: 'Async validation result reported by the user layer',\n labelNames: ['hit']\n }),\n\n // peer stream\n peerReadStreamError: register.gauge({\n name: 'gossipsub_peer_read_stream_err_count_total',\n help: 'Peer read stream error'\n }),\n\n // RPC outgoing. Track byte length + data structure sizes\n rpcRecvBytes: register.gauge({ name: 'gossipsub_rpc_recv_bytes_total', help: 'RPC recv' }),\n rpcRecvCount: register.gauge({ name: 'gossipsub_rpc_recv_count_total', help: 'RPC recv' }),\n rpcRecvSubscription: register.gauge({ name: 'gossipsub_rpc_recv_subscription_total', help: 'RPC recv' }),\n rpcRecvMessage: register.gauge({ name: 'gossipsub_rpc_recv_message_total', help: 'RPC recv' }),\n rpcRecvControl: register.gauge({ name: 'gossipsub_rpc_recv_control_total', help: 'RPC recv' }),\n rpcRecvIHave: register.gauge({ name: 'gossipsub_rpc_recv_ihave_total', help: 'RPC recv' }),\n rpcRecvIWant: register.gauge({ name: 'gossipsub_rpc_recv_iwant_total', help: 'RPC recv' }),\n rpcRecvGraft: register.gauge({ name: 'gossipsub_rpc_recv_graft_total', help: 'RPC recv' }),\n rpcRecvPrune: register.gauge({ name: 'gossipsub_rpc_recv_prune_total', help: 'RPC recv' }),\n rpcDataError: register.gauge({ name: 'gossipsub_rpc_data_err_count_total', help: 'RPC data error' }),\n rpcRecvError: register.gauge({ name: 'gossipsub_rpc_recv_err_count_total', help: 'RPC recv error' }),\n\n /** Total count of RPC dropped because acceptFrom() == false */\n rpcRecvNotAccepted: register.gauge({\n name: 'gossipsub_rpc_rcv_not_accepted_total',\n help: 'Total count of RPC dropped because acceptFrom() == false'\n }),\n\n // RPC incoming. Track byte length + data structure sizes\n rpcSentBytes: register.gauge({ name: 'gossipsub_rpc_sent_bytes_total', help: 'RPC sent' }),\n rpcSentCount: register.gauge({ name: 'gossipsub_rpc_sent_count_total', help: 'RPC sent' }),\n rpcSentSubscription: register.gauge({ name: 'gossipsub_rpc_sent_subscription_total', help: 'RPC sent' }),\n rpcSentMessage: register.gauge({ name: 'gossipsub_rpc_sent_message_total', help: 'RPC sent' }),\n rpcSentControl: register.gauge({ name: 'gossipsub_rpc_sent_control_total', help: 'RPC sent' }),\n rpcSentIHave: register.gauge({ name: 'gossipsub_rpc_sent_ihave_total', help: 'RPC sent' }),\n rpcSentIWant: register.gauge({ name: 'gossipsub_rpc_sent_iwant_total', help: 'RPC sent' }),\n rpcSentGraft: register.gauge({ name: 'gossipsub_rpc_sent_graft_total', help: 'RPC sent' }),\n rpcSentPrune: register.gauge({ name: 'gossipsub_rpc_sent_prune_total', help: 'RPC sent' }),\n\n // publish message. Track peers sent to and bytes\n /** Total count of msg published by topic */\n msgPublishCount: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_count_total',\n help: 'Total count of msg published by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we publish a msg to */\n msgPublishPeers: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_peers_total',\n help: 'Total count of peers that we publish a msg to',\n labelNames: ['topic']\n }),\n /** Total count of peers (by group) that we publish a msg to */\n // NOTE: Do not use 'group' label since it's a generic already used by Prometheus to group instances\n msgPublishPeersByGroup: register.gauge<{ topic: TopicLabel; peerGroup: keyof ToSendGroupCount }>({\n name: 'gossipsub_msg_publish_peers_by_group',\n help: 'Total count of peers (by group) that we publish a msg to',\n labelNames: ['topic', 'peerGroup']\n }),\n /** Total count of msg publish data.length bytes */\n msgPublishBytes: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_publish_bytes_total',\n help: 'Total count of msg publish data.length bytes',\n labelNames: ['topic']\n }),\n\n /** Total count of msg forwarded by topic */\n msgForwardCount: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_forward_count_total',\n help: 'Total count of msg forwarded by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we forward a msg to */\n msgForwardPeers: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_forward_peers_total',\n help: 'Total count of peers that we forward a msg to',\n labelNames: ['topic']\n }),\n\n /** Total count of recv msgs before any validation */\n msgReceivedPreValidation: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_prevalidation_total',\n help: 'Total count of recv msgs before any validation',\n labelNames: ['topic']\n }),\n /** Total count of recv msgs error */\n msgReceivedError: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_msg_received_error_total',\n help: 'Total count of recv msgs error',\n labelNames: ['topic']\n }),\n /** Tracks distribution of recv msgs by duplicate, invalid, valid */\n msgReceivedStatus: register.gauge<{ topic: TopicLabel; status: MessageStatus }>({\n name: 'gossipsub_msg_received_status_total',\n help: 'Tracks distribution of recv msgs by duplicate, invalid, valid',\n labelNames: ['topic', 'status']\n }),\n /** Tracks specific reason of invalid */\n msgReceivedInvalid: register.gauge<{ topic: TopicLabel; error: RejectReason | ValidateError }>({\n name: 'gossipsub_msg_received_invalid_total',\n help: 'Tracks specific reason of invalid',\n labelNames: ['topic', 'error']\n }),\n /** Track duplicate message delivery time */\n duplicateMsgDeliveryDelay: register.histogram({\n name: 'gossisub_duplicate_msg_delivery_delay_seconds',\n help: 'Time since the 1st duplicated message validated',\n labelNames: ['topic'],\n buckets: [\n 0.25 * opts.maxMeshMessageDeliveriesWindowSec,\n 0.5 * opts.maxMeshMessageDeliveriesWindowSec,\n 1 * opts.maxMeshMessageDeliveriesWindowSec,\n 2 * opts.maxMeshMessageDeliveriesWindowSec,\n 4 * opts.maxMeshMessageDeliveriesWindowSec\n ]\n }),\n /** Total count of late msg delivery total by topic */\n duplicateMsgLateDelivery: register.gauge<{ topic: TopicLabel }>({\n name: 'gossisub_duplicate_msg_late_delivery_total',\n help: 'Total count of late duplicate message delivery by topic, which triggers P3 penalty',\n labelNames: ['topic']\n }),\n\n duplicateMsgIgnored: register.gauge<{ topic: TopicLabel }>({\n name: 'gossisub_ignored_published_duplicate_msgs_total',\n help: 'Total count of published duplicate message ignored by topic',\n labelNames: ['topic']\n }),\n\n /* Metrics related to scoring */\n /** Total times score() is called */\n scoreFnCalls: register.gauge({\n name: 'gossipsub_score_fn_calls_total',\n help: 'Total times score() is called'\n }),\n /** Total times score() call actually computed computeScore(), no cache */\n scoreFnRuns: register.gauge({\n name: 'gossipsub_score_fn_runs_total',\n help: 'Total times score() call actually computed computeScore(), no cache'\n }),\n scoreCachedDelta: register.histogram({\n name: 'gossipsub_score_cache_delta',\n help: 'Delta of score between cached values that expired',\n buckets: [10, 100, 1000]\n }),\n /** Current count of peers by score threshold */\n peersByScoreThreshold: register.gauge<{ threshold: ScoreThreshold }>({\n name: 'gossipsub_peers_by_score_threshold_count',\n help: 'Current count of peers by score threshold',\n labelNames: ['threshold']\n }),\n score: register.avgMinMax({\n name: 'gossipsub_score',\n help: 'Avg min max of gossip scores',\n labelNames: ['topic', 'p']\n }),\n /** Separate score weights */\n scoreWeights: register.avgMinMax<{ topic?: TopicLabel; p: string }>({\n name: 'gossipsub_score_weights',\n help: 'Separate score weights',\n labelNames: ['topic', 'p']\n }),\n /** Histogram of the scores for each mesh topic. */\n // TODO: Not implemented\n scorePerMesh: register.avgMinMax<{ topic: TopicLabel }>({\n name: 'gossipsub_score_per_mesh',\n help: 'Histogram of the scores for each mesh topic',\n labelNames: ['topic']\n }),\n /** A counter of the kind of penalties being applied to peers. */\n // TODO: Not fully implemented\n scoringPenalties: register.gauge<{ penalty: ScorePenalty }>({\n name: 'gossipsub_scoring_penalties_total',\n help: 'A counter of the kind of penalties being applied to peers',\n labelNames: ['penalty']\n }),\n behaviourPenalty: register.histogram({\n name: 'gossipsub_peer_stat_behaviour_penalty',\n help: 'Current peer stat behaviour_penalty at each scrape',\n buckets: [\n 0.25 * opts.behaviourPenaltyThreshold,\n 0.5 * opts.behaviourPenaltyThreshold,\n 1 * opts.behaviourPenaltyThreshold,\n 2 * opts.behaviourPenaltyThreshold,\n 4 * opts.behaviourPenaltyThreshold\n ]\n }),\n\n // TODO:\n // - iasked per peer (on heartbeat)\n // - when promise is resolved, track messages from promises\n\n /** Total received IHAVE messages that we ignore for some reason */\n ihaveRcvIgnored: register.gauge<{ reason: IHaveIgnoreReason }>({\n name: 'gossipsub_ihave_rcv_ignored_total',\n help: 'Total received IHAVE messages that we ignore for some reason',\n labelNames: ['reason']\n }),\n /** Total received IHAVE messages by topic */\n ihaveRcvMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ihave_rcv_msgids_total',\n help: 'Total received IHAVE messages by topic',\n labelNames: ['topic']\n }),\n /** Total messages per topic we don't have. Not actual requests.\n * The number of times we have decided that an IWANT control message is required for this\n * topic. A very high metric might indicate an underperforming network.\n * = rust-libp2p `topic_iwant_msgs` */\n ihaveRcvNotSeenMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_ihave_rcv_not_seen_msgids_total',\n help: 'Total messages per topic we do not have, not actual requests',\n labelNames: ['topic']\n }),\n\n /** Total received IWANT messages by topic */\n iwantRcvMsgids: register.gauge<{ topic: TopicLabel }>({\n name: 'gossipsub_iwant_rcv_msgids_total',\n help: 'Total received IWANT messages by topic',\n labelNames: ['topic']\n }),\n /** Total requested messageIDs that we don't have */\n iwantRcvDonthaveMsgids: register.gauge({\n name: 'gossipsub_iwant_rcv_dont_have_msgids_total',\n help: 'Total requested messageIDs that we do not have'\n }),\n iwantPromiseStarted: register.gauge({\n name: 'gossipsub_iwant_promise_sent_total',\n help: 'Total count of started IWANT promises'\n }),\n /** Total count of resolved IWANT promises */\n iwantPromiseResolved: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_total',\n help: 'Total count of resolved IWANT promises'\n }),\n /** Total count of resolved IWANT promises from duplicate messages */\n iwantPromiseResolvedFromDuplicate: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_from_duplicate_total',\n help: 'Total count of resolved IWANT promises from duplicate messages'\n }),\n /** Total count of peers we have asked IWANT promises that are resolved */\n iwantPromiseResolvedPeers: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_peers',\n help: 'Total count of peers we have asked IWANT promises that are resolved'\n }),\n iwantPromiseBroken: register.gauge({\n name: 'gossipsub_iwant_promise_broken',\n help: 'Total count of broken IWANT promises'\n }),\n iwantMessagePruned: register.gauge({\n name: 'gossipsub_iwant_message_pruned',\n help: 'Total count of pruned IWANT messages'\n }),\n /** Histogram of delivery time of resolved IWANT promises */\n iwantPromiseDeliveryTime: register.histogram({\n name: 'gossipsub_iwant_promise_delivery_seconds',\n help: 'Histogram of delivery time of resolved IWANT promises',\n buckets: [\n 0.5 * opts.gossipPromiseExpireSec,\n 1 * opts.gossipPromiseExpireSec,\n 2 * opts.gossipPromiseExpireSec,\n 4 * opts.gossipPromiseExpireSec\n ]\n }),\n iwantPromiseUntracked: register.gauge({\n name: 'gossip_iwant_promise_untracked',\n help: 'Total count of untracked IWANT promise'\n }),\n\n /* Data structure sizes */\n /** Unbounded cache sizes */\n cacheSize: register.gauge<{ cache: string }>({\n name: 'gossipsub_cache_size',\n help: 'Unbounded cache sizes',\n labelNames: ['cache']\n }),\n /** Current mcache msg count */\n mcacheSize: register.gauge({\n name: 'gossipsub_mcache_size',\n help: 'Current mcache msg count'\n }),\n mcacheNotValidatedCount: register.gauge({\n name: 'gossipsub_mcache_not_validated_count',\n help: 'Current mcache msg count not validated'\n }),\n\n fastMsgIdCacheCollision: register.gauge({\n name: 'gossipsub_fastmsgid_cache_collision_total',\n help: 'Total count of key collisions on fastmsgid cache put'\n }),\n\n newConnectionCount: register.gauge<{ status: string }>({\n name: 'gossipsub_new_connection_total',\n help: 'Total new connection by status',\n labelNames: ['status']\n }),\n\n topicStrToLabel: topicStrToLabel,\n\n toTopic(topicStr: TopicStr): TopicLabel {\n return this.topicStrToLabel.get(topicStr) ?? topicStr\n },\n\n /** We joined a topic */\n onJoin(topicStr: TopicStr): void {\n this.topicSubscriptionStatus.set({ topicStr }, 1)\n this.meshPeerCounts.set({ topicStr }, 0) // Reset count\n },\n\n /** We left a topic */\n onLeave(topicStr: TopicStr): void {\n this.topicSubscriptionStatus.set({ topicStr }, 0)\n this.meshPeerCounts.set({ topicStr }, 0) // Reset count\n },\n\n /** Register the inclusion of peers in our mesh due to some reason. */\n onAddToMesh(topicStr: TopicStr, reason: InclusionReason, count: number): void {\n const topic = this.toTopic(topicStr)\n this.meshPeerInclusionEvents.inc({ topic, reason }, count)\n },\n\n /** Register the removal of peers in our mesh due to some reason */\n // - remove_peer_from_mesh()\n // - heartbeat() Churn::BadScore\n // - heartbeat() Churn::Excess\n // - on_disconnect() Churn::Ds\n onRemoveFromMesh(topicStr: TopicStr, reason: ChurnReason, count: number): void {\n const topic = this.toTopic(topicStr)\n this.meshPeerChurnEvents.inc({ topic, reason }, count)\n },\n\n onReportValidationMcacheHit(hit: boolean): void {\n this.asyncValidationMcacheHit.inc({ hit: hit ? 'hit' : 'miss' })\n },\n\n onReportValidation(topicStr: TopicStr, acceptance: TopicValidatorResult): void {\n const topic = this.toTopic(topicStr)\n this.asyncValidationResult.inc({ topic: topic, acceptance })\n },\n\n /**\n * - in handle_graft() Penalty::GraftBackoff\n * - in apply_iwant_penalties() Penalty::BrokenPromise\n * - in metric_score() P3 Penalty::MessageDeficit\n * - in metric_score() P6 Penalty::IPColocation\n */\n onScorePenalty(penalty: ScorePenalty): void {\n // Can this be labeled by topic too?\n this.scoringPenalties.inc({ penalty }, 1)\n },\n\n onIhaveRcv(topicStr: TopicStr, ihave: number, idonthave: number): void {\n const topic = this.toTopic(topicStr)\n this.ihaveRcvMsgids.inc({ topic }, ihave)\n this.ihaveRcvNotSeenMsgids.inc({ topic }, idonthave)\n },\n\n onIwantRcv(iwantByTopic: Map, iwantDonthave: number): void {\n for (const [topicStr, iwant] of iwantByTopic) {\n const topic = this.toTopic(topicStr)\n this.iwantRcvMsgids.inc({ topic }, iwant)\n }\n\n this.iwantRcvDonthaveMsgids.inc(iwantDonthave)\n },\n\n onForwardMsg(topicStr: TopicStr, tosendCount: number): void {\n const topic = this.toTopic(topicStr)\n this.msgForwardCount.inc({ topic }, 1)\n this.msgForwardPeers.inc({ topic }, tosendCount)\n },\n\n onPublishMsg(topicStr: TopicStr, tosendGroupCount: ToSendGroupCount, tosendCount: number, dataLen: number): void {\n const topic = this.toTopic(topicStr)\n this.msgPublishCount.inc({ topic }, 1)\n this.msgPublishBytes.inc({ topic }, tosendCount * dataLen)\n this.msgPublishPeers.inc({ topic }, tosendCount)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'direct' }, tosendGroupCount.direct)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'floodsub' }, tosendGroupCount.floodsub)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'mesh' }, tosendGroupCount.mesh)\n this.msgPublishPeersByGroup.inc({ topic, peerGroup: 'fanout' }, tosendGroupCount.fanout)\n },\n\n onMsgRecvPreValidation(topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedPreValidation.inc({ topic }, 1)\n },\n\n onMsgRecvError(topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedError.inc({ topic }, 1)\n },\n\n onMsgRecvResult(topicStr: TopicStr, status: MessageStatus): void {\n const topic = this.toTopic(topicStr)\n this.msgReceivedStatus.inc({ topic, status })\n },\n\n onMsgRecvInvalid(topicStr: TopicStr, reason: RejectReasonObj): void {\n const topic = this.toTopic(topicStr)\n\n const error = reason.reason === RejectReason.Error ? reason.error : reason.reason\n this.msgReceivedInvalid.inc({ topic, error }, 1)\n },\n\n onDuplicateMsgDelivery(topicStr: TopicStr, deliveryDelayMs: number, isLateDelivery: boolean): void {\n this.duplicateMsgDeliveryDelay.observe(deliveryDelayMs / 1000)\n if (isLateDelivery) {\n const topic = this.toTopic(topicStr)\n this.duplicateMsgLateDelivery.inc({ topic }, 1)\n }\n },\n\n onPublishDuplicateMsg(topicStr: TopicStr): void {\n const topic = this.toTopic(topicStr)\n this.duplicateMsgIgnored.inc({ topic }, 1)\n },\n\n onPeerReadStreamError(): void {\n this.peerReadStreamError.inc(1)\n },\n\n onRpcRecvError(): void {\n this.rpcRecvError.inc(1)\n },\n\n onRpcDataError(): void {\n this.rpcDataError.inc(1)\n },\n\n onRpcRecv(rpc: IRPC, rpcBytes: number): void {\n this.rpcRecvBytes.inc(rpcBytes)\n this.rpcRecvCount.inc(1)\n if (rpc.subscriptions) this.rpcRecvSubscription.inc(rpc.subscriptions.length)\n if (rpc.messages) this.rpcRecvMessage.inc(rpc.messages.length)\n if (rpc.control) {\n this.rpcRecvControl.inc(1)\n if (rpc.control.ihave) this.rpcRecvIHave.inc(rpc.control.ihave.length)\n if (rpc.control.iwant) this.rpcRecvIWant.inc(rpc.control.iwant.length)\n if (rpc.control.graft) this.rpcRecvGraft.inc(rpc.control.graft.length)\n if (rpc.control.prune) this.rpcRecvPrune.inc(rpc.control.prune.length)\n }\n },\n\n onRpcSent(rpc: IRPC, rpcBytes: number): void {\n this.rpcSentBytes.inc(rpcBytes)\n this.rpcSentCount.inc(1)\n if (rpc.subscriptions) this.rpcSentSubscription.inc(rpc.subscriptions.length)\n if (rpc.messages) this.rpcSentMessage.inc(rpc.messages.length)\n if (rpc.control) {\n const ihave = rpc.control.ihave?.length ?? 0\n const iwant = rpc.control.iwant?.length ?? 0\n const graft = rpc.control.graft?.length ?? 0\n const prune = rpc.control.prune?.length ?? 0\n if (ihave > 0) this.rpcSentIHave.inc(ihave)\n if (iwant > 0) this.rpcSentIWant.inc(iwant)\n if (graft > 0) this.rpcSentGraft.inc(graft)\n if (prune > 0) this.rpcSentPrune.inc(prune)\n if (ihave > 0 || iwant > 0 || graft > 0 || prune > 0) this.rpcSentControl.inc(1)\n }\n },\n\n registerScores(scores: number[], scoreThresholds: PeerScoreThresholds): void {\n let graylist = 0\n let publish = 0\n let gossip = 0\n let mesh = 0\n\n for (const score of scores) {\n if (score >= scoreThresholds.graylistThreshold) graylist++\n if (score >= scoreThresholds.publishThreshold) publish++\n if (score >= scoreThresholds.gossipThreshold) gossip++\n if (score >= 0) mesh++\n }\n\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.graylist }, graylist)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.publish }, publish)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.gossip }, gossip)\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.mesh }, mesh)\n\n // Register full score too\n this.score.set(scores)\n },\n\n registerScoreWeights(sw: ScoreWeights): void {\n for (const [topic, wsTopic] of sw.byTopic) {\n this.scoreWeights.set({ topic, p: 'p1' }, wsTopic.p1w)\n this.scoreWeights.set({ topic, p: 'p2' }, wsTopic.p2w)\n this.scoreWeights.set({ topic, p: 'p3' }, wsTopic.p3w)\n this.scoreWeights.set({ topic, p: 'p3b' }, wsTopic.p3bw)\n this.scoreWeights.set({ topic, p: 'p4' }, wsTopic.p4w)\n }\n\n this.scoreWeights.set({ p: 'p5' }, sw.p5w)\n this.scoreWeights.set({ p: 'p6' }, sw.p6w)\n this.scoreWeights.set({ p: 'p7' }, sw.p7w)\n },\n\n registerScorePerMesh(mesh: Map>, scoreByPeer: Map): void {\n const peersPerTopicLabel = new Map>()\n\n mesh.forEach((peers, topicStr) => {\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = this.topicStrToLabel.get(topicStr) ?? 'unknown'\n let peersInMesh = peersPerTopicLabel.get(topicLabel)\n if (!peersInMesh) {\n peersInMesh = new Set()\n peersPerTopicLabel.set(topicLabel, peersInMesh)\n }\n peers.forEach((p) => peersInMesh?.add(p))\n })\n\n for (const [topic, peers] of peersPerTopicLabel) {\n const meshScores: number[] = []\n peers.forEach((peer) => {\n meshScores.push(scoreByPeer.get(peer) ?? 0)\n })\n this.scorePerMesh.set({ topic }, meshScores)\n }\n }\n }\n}\n", "\nimport 'node-forge/lib/aes.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport interface Cipher {\n update: (data: Uint8Array) => Uint8Array\n}\n\nexport function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array): Cipher {\n const cipher2 = forge.cipher.createCipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n\nexport function createDecipheriv (mode: any, key: Uint8Array, iv: Uint8Array): Cipher {\n const cipher2 = forge.cipher.createDecipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\n// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw new CodeError(`Hash '${hash}' is unknown or not supported. Must be ${types}`, 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { randomBytes } from '@libp2p/crypto'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { PublicKey } from '@libp2p/interface-keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { RPC } from '../message/rpc.js'\nimport { PublishConfig, PublishConfigType, TopicStr, ValidateError } from '../types.js'\nimport { StrictSign, StrictNoSign, Message } from '@libp2p/interface-pubsub'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport const SignPrefix = uint8ArrayFromString('libp2p-pubsub:')\n\nexport type RawMessageAndMessage = {\n raw: RPC.IMessage\n msg: Message\n}\n\nexport async function buildRawMessage(\n publishConfig: PublishConfig,\n topic: TopicStr,\n originalData: Uint8Array,\n transformedData: Uint8Array\n): Promise {\n switch (publishConfig.type) {\n case PublishConfigType.Signing: {\n const rpcMsg: RPC.IMessage = {\n from: publishConfig.author.toBytes(),\n data: transformedData,\n seqno: randomBytes(8),\n topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsg).finish()])\n\n rpcMsg.signature = await publishConfig.privateKey.sign(bytes)\n rpcMsg.key = publishConfig.key\n\n const msg: Message = {\n type: 'signed',\n from: publishConfig.author,\n data: originalData,\n sequenceNumber: BigInt(`0x${uint8ArrayToString(rpcMsg.seqno as Uint8Array, 'base16')}`),\n topic,\n signature: rpcMsg.signature,\n key: rpcMsg.key\n }\n return {\n raw: rpcMsg,\n msg: msg\n }\n }\n\n case PublishConfigType.Anonymous: {\n return {\n raw: {\n from: undefined,\n data: transformedData,\n seqno: undefined,\n topic,\n signature: undefined,\n key: undefined\n },\n msg: {\n type: 'unsigned',\n data: originalData,\n topic\n }\n }\n }\n }\n}\n\nexport type ValidationResult = { valid: true; message: Message } | { valid: false; error: ValidateError }\n\nexport async function validateToRawMessage(\n signaturePolicy: typeof StrictNoSign | typeof StrictSign,\n msg: RPC.IMessage\n): Promise {\n // If strict-sign, verify all\n // If anonymous (no-sign), ensure no preven\n\n switch (signaturePolicy) {\n case StrictNoSign:\n if (msg.signature != null) return { valid: false, error: ValidateError.SignaturePresent }\n if (msg.seqno != null) return { valid: false, error: ValidateError.SeqnoPresent }\n if (msg.key != null) return { valid: false, error: ValidateError.FromPresent }\n\n return { valid: true, message: { type: 'unsigned', topic: msg.topic, data: msg.data ?? new Uint8Array(0) } }\n\n case StrictSign: {\n // Verify seqno\n if (msg.seqno == null) return { valid: false, error: ValidateError.InvalidSeqno }\n if (msg.seqno.length !== 8) {\n return { valid: false, error: ValidateError.InvalidSeqno }\n }\n\n if (msg.signature == null) return { valid: false, error: ValidateError.InvalidSignature }\n if (msg.from == null) return { valid: false, error: ValidateError.InvalidPeerId }\n\n let fromPeerId: PeerId\n try {\n // TODO: Fix PeerId types\n fromPeerId = peerIdFromBytes(msg.from)\n } catch (e) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n\n // - check from defined\n // - transform source to PeerId\n // - parse signature\n // - get .key, else from source\n // - check key == source if present\n // - verify sig\n\n let publicKey: PublicKey\n if (msg.key) {\n publicKey = unmarshalPublicKey(msg.key)\n // TODO: Should `fromPeerId.pubKey` be optional?\n if (fromPeerId.publicKey !== undefined && !uint8ArrayEquals(publicKey.bytes, fromPeerId.publicKey)) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n } else {\n if (fromPeerId.publicKey == null) {\n return { valid: false, error: ValidateError.InvalidPeerId }\n }\n publicKey = unmarshalPublicKey(fromPeerId.publicKey)\n }\n\n const rpcMsgPreSign: RPC.IMessage = {\n from: msg.from,\n data: msg.data,\n seqno: msg.seqno,\n topic: msg.topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsgPreSign).finish()])\n\n if (!(await publicKey.verify(bytes, msg.signature))) {\n return { valid: false, error: ValidateError.InvalidSignature }\n }\n\n return {\n valid: true,\n message: {\n type: 'signed',\n from: fromPeerId,\n data: msg.data ?? new Uint8Array(0),\n sequenceNumber: BigInt(`0x${uint8ArrayToString(msg.seqno, 'base16')}`),\n topic: msg.topic,\n signature: msg.signature,\n key: msg.key ?? marshalPublicKey(publicKey)\n }\n }\n }\n }\n}\n", "import { randomBytes } from '@libp2p/crypto'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message, PubSubRPCMessage } from '@libp2p/interface-pubsub'\nimport { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'\nimport { codes } from './errors.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: Uint8Array, seqno: bigint): Uint8Array => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n\n const msgId = new Uint8Array(key.length + seqnoBytes.length)\n msgId.set(key, 0)\n msgId.set(seqnoBytes, key.length)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array): Uint8Array | Promise => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set | number[], b: Set | number[]): boolean => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray: T | T[]): T[] {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nconst isSigned = async (message: PubSubRPCMessage): Promise => {\n if ((message.sequenceNumber == null) || (message.from == null) || (message.signature == null)) {\n return false\n }\n // if a public key is present in the `from` field, the message should be signed\n const fromID = peerIdFromBytes(message.from)\n if (fromID.publicKey != null) {\n return true\n }\n\n if (message.key != null) {\n const signingID = await peerIdFromKeys(message.key)\n return signingID.equals(fromID)\n }\n\n return false\n}\n\nexport const toMessage = async (message: PubSubRPCMessage): Promise => {\n if (message.from == null) {\n throw new CodeError('RPC message was missing from', codes.ERR_MISSING_FROM)\n }\n\n if (!await isSigned(message)) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n const from = peerIdFromBytes(message.from)\n\n const msg: Message = {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber ?? new Uint8Array(0)),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n key: message.key ?? from.publicKey ?? new Uint8Array(0)\n }\n\n if (msg.key.length === 0) {\n throw new CodeError('Signed RPC message was missing key', codes.ERR_MISSING_KEY)\n }\n\n return msg\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n", "import { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message } from '@libp2p/interface-pubsub'\nimport { msgId } from '@libp2p/pubsub/utils'\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport function msgIdFnStrictSign(msg: Message): Uint8Array {\n if (msg.type !== 'signed') {\n throw new Error('expected signed message type')\n }\n // Should never happen\n if (msg.sequenceNumber == null) throw Error('missing seqno field')\n\n // TODO: Should use .from here or key?\n return msgId(msg.from.toBytes(), msg.sequenceNumber)\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport async function msgIdFnStrictNoSign(msg: Message): Promise {\n return await sha256.encode(msg.data)\n}\n", "import type { PeerScoreParams } from './peer-score-params.js'\nimport type { PeerStats } from './peer-stats.js'\n\ntype TopicLabel = string\ntype TopicStr = string\ntype TopicStrToLabel = Map\n\nexport interface TopicScoreWeights {\n p1w: T\n p2w: T\n p3w: T\n p3bw: T\n p4w: T\n}\nexport interface ScoreWeights {\n byTopic: Map>\n p5w: T\n p6w: T\n p7w: T\n score: T\n}\n\nexport function computeScoreWeights(\n peer: string,\n pstats: PeerStats,\n params: PeerScoreParams,\n peerIPs: Map>,\n topicStrToLabel: TopicStrToLabel\n): ScoreWeights {\n let score = 0\n\n const byTopic = new Map>()\n\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = topicStrToLabel.get(topic) ?? 'unknown'\n const topicParams = params.topics[topic]\n if (topicParams === undefined) {\n // we are not scoring this topic\n return\n }\n\n let topicScores = byTopic.get(topicLabel)\n if (!topicScores) {\n topicScores = {\n p1w: 0,\n p2w: 0,\n p3w: 0,\n p3bw: 0,\n p4w: 0\n }\n byTopic.set(topicLabel, topicScores)\n }\n\n let p1w = 0\n let p2w = 0\n let p3w = 0\n let p3bw = 0\n let p4w = 0\n\n // P1: time in Mesh\n if (tstats.inMesh) {\n const p1 = Math.max(tstats.meshTime / topicParams.timeInMeshQuantum, topicParams.timeInMeshCap)\n p1w += p1 * topicParams.timeInMeshWeight\n }\n\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap\n }\n p2w += p2 * topicParams.firstMessageDeliveriesWeight\n\n // P3: mesh message deliveries\n if (\n tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold\n ) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries\n const p3 = deficit * deficit\n p3w += p3 * topicParams.meshMessageDeliveriesWeight\n }\n\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty\n p3bw += p3b * topicParams.meshFailurePenaltyWeight\n\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries\n p4w += p4 * topicParams.invalidMessageDeliveriesWeight\n\n // update score, mixing with topic weight\n score += (p1w + p2w + p3w + p3bw + p4w) * topicParams.topicWeight\n\n topicScores.p1w += p1w\n topicScores.p2w += p2w\n topicScores.p3w += p3w\n topicScores.p3bw += p3bw\n topicScores.p4w += p4w\n })\n\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap\n\n // Proportionally apply cap to all individual contributions\n const capF = params.topicScoreCap / score\n for (const ws of byTopic.values()) {\n ws.p1w *= capF\n ws.p2w *= capF\n ws.p3w *= capF\n ws.p3bw *= capF\n ws.p4w *= capF\n }\n }\n\n let p5w = 0\n let p6w = 0\n let p7w = 0\n\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer)\n p5w += p5 * params.appSpecificWeight\n\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return\n }\n\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip)\n const numPeersInIP = peersInIP ? peersInIP.size : 0\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold\n const p6 = surplus * surplus\n p6w += p6 * params.IPColocationFactorWeight\n }\n })\n\n // P7: behavioural pattern penalty\n const p7 = pstats.behaviourPenalty * pstats.behaviourPenalty\n p7w += p7 * params.behaviourPenaltyWeight\n\n score += p5w + p6w + p7w\n\n return {\n byTopic,\n p5w,\n p6w,\n p7w,\n score\n }\n}\n\nexport function computeAllPeersScoreWeights(\n peerIdStrs: Iterable,\n peerStats: Map,\n params: PeerScoreParams,\n peerIPs: Map>,\n topicStrToLabel: TopicStrToLabel\n): ScoreWeights {\n const sw: ScoreWeights = {\n byTopic: new Map(),\n p5w: [],\n p6w: [],\n p7w: [],\n score: []\n }\n\n for (const peerIdStr of peerIdStrs) {\n const pstats = peerStats.get(peerIdStr)\n if (pstats) {\n const swPeer = computeScoreWeights(peerIdStr, pstats, params, peerIPs, topicStrToLabel)\n\n for (const [topic, swPeerTopic] of swPeer.byTopic) {\n let swTopic = sw.byTopic.get(topic)\n if (!swTopic) {\n swTopic = {\n p1w: [],\n p2w: [],\n p3w: [],\n p3bw: [],\n p4w: []\n }\n sw.byTopic.set(topic, swTopic)\n }\n\n swTopic.p1w.push(swPeerTopic.p1w)\n swTopic.p2w.push(swPeerTopic.p2w)\n swTopic.p3w.push(swPeerTopic.p3w)\n swTopic.p3bw.push(swPeerTopic.p3bw)\n swTopic.p4w.push(swPeerTopic.p4w)\n }\n\n sw.p5w.push(swPeer.p5w)\n sw.p6w.push(swPeer.p6w)\n sw.p7w.push(swPeer.p7w)\n sw.score.push(swPeer.score)\n } else {\n sw.p5w.push(0)\n sw.p6w.push(0)\n sw.p7w.push(0)\n sw.score.push(0)\n }\n }\n\n return sw\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO {\n public buffer: Array | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO | null\n\n constructor (hwm: number) {\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\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\n push (data: Next): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO\n private tail: FixedFIFO\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\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\n shift (): Next | undefined {\n let val = this.tail.shift()\n\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\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\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 */\n\nimport deferred from 'p-defer'\nimport { FIFO, type Next } from './fifo.js'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable extends AsyncGenerator, BasePushable {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV extends AsyncGenerator, BasePushable {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult { done: false, value: T }\nexport type NextResult = ValueResult | DoneResult\n\ninterface getNext { (buffer: FIFO): NextResult }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable (options?: BytePushableOptions): Pushable\nexport function pushable (options: ObjectPushableOptions): Pushable\nexport function pushable (options: Options = {}): Pushable {\n const getNext = (buffer: FIFO): NextResult => {\n const next: Next | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\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\n return _pushable>(getNext, options)\n}\n\nexport function pushableV (options?: BytePushableOptions): PushableV\nexport function pushableV (options: ObjectPushableOptions): PushableV\nexport function pushableV (options: Options = {}): PushableV {\n const getNext = (buffer: FIFO): NextResult => {\n let next: Next | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\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\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable>(getNext, options)\n}\n\nfunction _pushable (getNext: getNext, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO()\n let pushable: any\n let onNext: ((next: Next) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise>((resolve, reject) => {\n onNext = (next: Next) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\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\n const bufferNext = (next: Next): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\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\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n", "\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\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", "import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n", "import { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\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: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n\n constructor (...data: Appendable[]) {\n // Define symbol\n Object.defineProperty(this, symbol, { value: true })\n\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] () {\n yield * this.bufs\n }\n\n get byteLength () {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]) {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]) {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\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 } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\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 } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\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?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number) {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\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\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\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\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\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\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\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: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\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\n return true\n }\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: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\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", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\n\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)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\ninterface VarintCodec {\n encodingLength: (value: number) => number\n encode: ((value: number) => Uint8Array) & ((value: number, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: number, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => number\n}\n\nexport const unsigned: VarintCodec = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf?: any, offset: number = 0) {\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(true)\n }\n}\n\nexport const signed: VarintCodec = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0) {\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(false)\n }\n}\n\nexport const zigzag: VarintCodec = {\n encodingLength (value: number): number {\n return unsigned.encodingLength(value >= 0 ? value * 2 : value * -2 - 1)\n },\n\n // @ts-expect-error\n encode (value: any, buf?: any, offset?: any) {\n value = value >= 0 ? value * 2 : (value * -2) - 1\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n const value = unsigned.decode(buf, offset)\n\n return (value & 1) !== 0 ? (value + 1) / -2 : value / 2\n }\n}\n", "\nexport function alloc (len: number) {\n return new Uint8Array(len)\n}\n\nexport function allocUnsafe (len: number) {\n if (globalThis?.Buffer?.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport type { LengthEncoderFunction } from './index.js'\nimport type { Source, Transform } from 'it-stream-types'\nimport { allocUnsafe } from './alloc.js'\n\ninterface EncoderOptions {\n lengthEncoder?: LengthEncoderFunction\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = unsigned.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n unsigned.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (options?: EncoderOptions): Transform {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n const encoder = async function * (source: Source): Source {\n for await (const chunk of source) {\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\n }\n }\n\n return encoder\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n", "/* eslint max-depth: [\"error\", 6] */\n\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport errCode from 'err-code'\nimport type { LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport interface ReadState {\n dataLength: number\n}\n\nexport interface DecoderOptions {\n lengthDecoder?: LengthDecoderFunction\n onData?: (data: Uint8ArrayList) => void\n onLength?: (length: number) => void\n maxLengthLength?: number\n maxDataLength?: number\n}\n\nexport interface ReadResult {\n mode: string\n chunk?: Uint8ArrayList\n buffer: Uint8ArrayList\n state?: ReadState\n data?: Uint8ArrayList\n}\n\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\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = unsigned.decode(buf)\n defaultDecoder.bytes = unsigned.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (options?: DecoderOptions): Transform {\n const decoder = async function * (source: Source): Source {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n for await (const buf of source) {\n buffer.append(buf)\n\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\n if (dataLength < 0) {\n throw errCode(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH')\n }\n\n if (dataLength > maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (buffer.byteLength > 0) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF')\n }\n }\n\n return decoder\n}\n\n/**\n * @param {*} reader\n * @param {import('./types').DecoderOptions} [options]\n * @returns\n */\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number) => { byteLength = l }\n return decode({\n ...(options ?? {}),\n onLength\n })(varByteSource)\n}\n", "import { Stream } from '@libp2p/interface-connection'\nimport { abortableSource } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport { pushable, Pushable } from 'it-pushable'\nimport { encode, decode } from 'it-length-prefixed'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\ntype OutboundStreamOpts = {\n /** Max size in bytes for pushable buffer. If full, will throw on .push */\n maxBufferSize?: number\n}\n\ntype InboundStreamOpts = {\n /** Max size in bytes for reading messages from the stream */\n maxDataLength?: number\n}\n\nexport class OutboundStream {\n private readonly pushable: Pushable\n private readonly closeController: AbortController\n private readonly maxBufferSize: number\n\n constructor(private readonly rawStream: Stream, errCallback: (e: Error) => void, opts: OutboundStreamOpts) {\n this.pushable = pushable({ objectMode: false })\n this.closeController = new AbortController()\n this.maxBufferSize = opts.maxBufferSize ?? Infinity\n\n pipe(\n abortableSource(this.pushable, this.closeController.signal, { returnOnAbort: true }),\n encode(),\n this.rawStream\n ).catch(errCallback)\n }\n\n get protocol(): string {\n // TODO remove this non-nullish assertion after https://github.com/libp2p/js-libp2p-interfaces/pull/265 is incorporated\n return this.rawStream.stat.protocol!\n }\n\n push(data: Uint8Array): void {\n if (this.pushable.readableLength > this.maxBufferSize) {\n throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`)\n }\n\n this.pushable.push(data)\n }\n\n close(): void {\n this.closeController.abort()\n // similar to pushable.end() but clear the internal buffer\n this.pushable.return()\n this.rawStream.close()\n }\n}\n\nexport class InboundStream {\n public readonly source: AsyncIterable\n\n private readonly rawStream: Stream\n private readonly closeController: AbortController\n\n constructor(rawStream: Stream, opts: InboundStreamOpts = {}) {\n this.rawStream = rawStream\n this.closeController = new AbortController()\n\n this.source = abortableSource(pipe(this.rawStream, decode(opts)), this.closeController.signal, {\n returnOnAbort: true\n })\n }\n\n close(): void {\n this.closeController.abort()\n this.rawStream.close()\n }\n}\n", "import type { IRPC, RPC } from './rpc.js'\nimport protobuf from 'protobufjs/minimal.js'\n\nexport type DecodeRPCLimits = {\n maxSubscriptions: number\n maxMessages: number\n maxIhaveMessageIDs: number\n maxIwantMessageIDs: number\n maxControlMessages: number\n maxPeerInfos: number\n}\n\nexport const defaultDecodeRpcLimits: DecodeRPCLimits = {\n maxSubscriptions: Infinity,\n maxMessages: Infinity,\n maxIhaveMessageIDs: Infinity,\n maxIwantMessageIDs: Infinity,\n maxControlMessages: Infinity,\n maxPeerInfos: Infinity\n}\n\n/**\n * Copied code from src/message/rpc.cjs but with decode limits to prevent OOM attacks\n */\nexport function decodeRpc(bytes: Uint8Array, opts: DecodeRPCLimits): IRPC {\n // Mutate to use the option as stateful counter. Must limit the total count of messageIDs across all IWANT, IHAVE\n // else one count put 100 messageIDs into each 100 IWANT and \"get around\" the limit\n opts = { ...opts }\n\n const r = protobuf.Reader.create(bytes)\n const l = bytes.length\n\n const c = l === undefined ? r.len : r.pos + l\n const m: IRPC = {}\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n if (!(m.subscriptions && m.subscriptions.length)) m.subscriptions = []\n if (m.subscriptions.length < opts.maxSubscriptions) m.subscriptions.push(decodeSubOpts(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 2:\n if (!(m.messages && m.messages.length)) m.messages = []\n if (m.messages.length < opts.maxMessages) m.messages.push(decodeMessage(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 3:\n m.control = decodeControlMessage(r, r.uint32(), opts)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeSubOpts(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m: RPC.ISubOpts = {}\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.subscribe = r.bool()\n break\n case 2:\n m.topic = r.string()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeMessage(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IMessage\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.from = r.bytes()\n break\n case 2:\n m.data = r.bytes()\n break\n case 3:\n m.seqno = r.bytes()\n break\n case 4:\n m.topic = r.string()\n break\n case 5:\n m.signature = r.bytes()\n break\n case 6:\n m.key = r.bytes()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n if (!m.topic) throw Error(\"missing required 'topic'\")\n return m\n}\n\nfunction decodeControlMessage(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlMessage\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n if (!(m.ihave && m.ihave.length)) m.ihave = []\n if (m.ihave.length < opts.maxControlMessages) m.ihave.push(decodeControlIHave(r, r.uint32(), opts))\n else r.skipType(t & 7)\n break\n case 2:\n if (!(m.iwant && m.iwant.length)) m.iwant = []\n if (m.iwant.length < opts.maxControlMessages) m.iwant.push(decodeControlIWant(r, r.uint32(), opts))\n else r.skipType(t & 7)\n break\n case 3:\n if (!(m.graft && m.graft.length)) m.graft = []\n if (m.graft.length < opts.maxControlMessages) m.graft.push(decodeControlGraft(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 4:\n if (!(m.prune && m.prune.length)) m.prune = []\n if (m.prune.length < opts.maxControlMessages) m.prune.push(decodeControlPrune(r, r.uint32(), opts))\n else r.skipType(t & 7)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlIHave(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlIHave\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string()\n break\n case 2:\n if (!(m.messageIDs && m.messageIDs.length)) m.messageIDs = []\n if (opts.maxIhaveMessageIDs-- > 0) m.messageIDs.push(r.bytes())\n else r.skipType(t & 7)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlIWant(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlIWant\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n if (!(m.messageIDs && m.messageIDs.length)) m.messageIDs = []\n if (opts.maxIwantMessageIDs-- > 0) m.messageIDs.push(r.bytes())\n else r.skipType(t & 7)\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlGraft(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlGraft\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodeControlPrune(r: protobuf.Reader, l: number, opts: DecodeRPCLimits) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IControlPrune\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.topicID = r.string()\n break\n case 2:\n if (!(m.peers && m.peers.length)) m.peers = []\n if (opts.maxPeerInfos-- > 0) m.peers.push(decodePeerInfo(r, r.uint32()))\n else r.skipType(t & 7)\n break\n case 3:\n m.backoff = r.uint64() as unknown as number\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n\nfunction decodePeerInfo(r: protobuf.Reader, l: number) {\n const c = l === undefined ? r.len : r.pos + l\n const m = {} as RPC.IPeerInfo\n while (r.pos < c) {\n const t = r.uint32()\n switch (t >>> 3) {\n case 1:\n m.peerID = r.bytes()\n break\n case 2:\n m.signedPeerRecord = r.bytes()\n break\n default:\n r.skipType(t & 7)\n break\n }\n }\n return m\n}\n", "import { Multiaddr } from '@multiformats/multiaddr'\nimport { convertToString } from '@multiformats/multiaddr/convert'\n\n// Protocols https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n// code size name\n// 4 32 ip4\n// 41 128 ip6\nenum Protocol {\n ip4 = 4,\n ip6 = 41\n}\n\nexport function multiaddrToIPStr(multiaddr: Multiaddr): string | null {\n for (const tuple of multiaddr.tuples()) {\n switch (tuple[0]) {\n case Protocol.ip4:\n case Protocol.ip6:\n return convertToString(tuple[0], tuple[1]!)\n }\n }\n\n return null\n}\n", "import { pipe } from 'it-pipe'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport { RecordEnvelope } from '@libp2p/peer-record'\nimport { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id'\nimport { Logger, logger } from '@libp2p/logger'\nimport { createTopology } from '@libp2p/topology'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\n\nimport { MessageCache } from './message-cache.js'\nimport { RPC, IRPC } from './message/rpc.js'\nimport * as constants from './constants.js'\nimport { shuffle, messageIdToString } from './utils/index.js'\nimport {\n PeerScore,\n PeerScoreParams,\n PeerScoreThresholds,\n createPeerScoreParams,\n createPeerScoreThresholds,\n PeerScoreStatsDump\n} from './score/index.js'\nimport { IWantTracer } from './tracer.js'\nimport { SimpleTimeCache } from './utils/time-cache.js'\nimport {\n ACCEPT_FROM_WHITELIST_DURATION_MS,\n ACCEPT_FROM_WHITELIST_MAX_MESSAGES,\n ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE\n} from './constants.js'\nimport {\n ChurnReason,\n getMetrics,\n IHaveIgnoreReason,\n InclusionReason,\n Metrics,\n MetricsRegister,\n ScorePenalty,\n TopicStrToLabel,\n ToSendGroupCount\n} from './metrics.js'\nimport {\n MsgIdFn,\n PublishConfig,\n TopicStr,\n MsgIdStr,\n ValidateError,\n PeerIdStr,\n MessageStatus,\n RejectReason,\n RejectReasonObj,\n FastMsgIdFn,\n AddrInfo,\n DataTransform,\n rejectReasonFromAcceptance,\n MsgIdToStrFn,\n MessageId,\n PublishOpts\n} from './types.js'\nimport { buildRawMessage, validateToRawMessage } from './utils/buildRawMessage.js'\nimport { msgIdFnStrictNoSign, msgIdFnStrictSign } from './utils/msgIdFn.js'\nimport { computeAllPeersScoreWeights } from './score/scoreMetrics.js'\nimport { getPublishConfigFromPeerId } from './utils/publishConfig.js'\nimport type { GossipsubOptsSpec } from './config.js'\nimport {\n Message,\n PublishResult,\n PubSub,\n PubSubEvents,\n PubSubInit,\n StrictNoSign,\n StrictSign,\n SubscriptionChangeData,\n TopicValidatorFn,\n TopicValidatorResult\n} from '@libp2p/interface-pubsub'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport { removeFirstNItemsFromSet, removeItemsFromSet } from './utils/set.js'\nimport { pushable } from 'it-pushable'\nimport { InboundStream, OutboundStream } from './stream.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { decodeRpc, DecodeRPCLimits, defaultDecodeRpcLimits } from './message/decodeRpc.js'\nimport { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport { PeerStore } from '@libp2p/interface-peer-store'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddrToIPStr } from './utils/multiaddr.js'\n\ntype ConnectionDirection = 'inbound' | 'outbound'\n\ntype ReceivedMessageResult =\n | { code: MessageStatus.duplicate; msgIdStr: MsgIdStr }\n | ({ code: MessageStatus.invalid; msgIdStr?: MsgIdStr } & RejectReasonObj)\n | { code: MessageStatus.valid; messageId: MessageId; msg: Message }\n\nexport const multicodec: string = constants.GossipsubIDv11\n\nexport interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {\n /** if dial should fallback to floodsub */\n fallbackToFloodsub: boolean\n /** if self-published messages should be sent to all peers */\n floodPublish: boolean\n /** whether PX is enabled; this should be enabled in bootstrappers and other well connected/trusted nodes. */\n doPX: boolean\n /** peers with which we will maintain direct connections */\n directPeers: AddrInfo[]\n /**\n * If true will not forward messages to mesh peers until reportMessageValidationResult() is called.\n * Messages will be cached in mcache for some time after which they are evicted. Calling\n * reportMessageValidationResult() after the message is dropped from mcache won't forward the message.\n */\n asyncValidation: boolean\n /** Do not throw `InsufficientPeers` error if publishing to zero peers */\n allowPublishToZeroPeers: boolean\n /** Do not throw `PublishError.Duplicate` if publishing duplicate messages */\n ignoreDuplicatePublishError: boolean\n /** For a single stream, await processing each RPC before processing the next */\n awaitRpcHandler: boolean\n /** For a single RPC, await processing each message before processing the next */\n awaitRpcMessageHandler: boolean\n\n /** message id function */\n msgIdFn: MsgIdFn\n /** fast message id function */\n fastMsgIdFn: FastMsgIdFn\n /** Uint8Array message id to string function */\n msgIdToStrFn: MsgIdToStrFn\n /** override the default MessageCache */\n messageCache: MessageCache\n /** peer score parameters */\n scoreParams: Partial\n /** peer score thresholds */\n scoreThresholds: Partial\n /** customize GossipsubIWantFollowupTime in order not to apply IWANT penalties */\n gossipsubIWantFollowupMs: number\n\n /** override constants for fine tuning */\n prunePeers?: number\n pruneBackoff?: number\n graftFloodThreshold?: number\n opportunisticGraftPeers?: number\n opportunisticGraftTicks?: number\n directConnectTicks?: number\n\n dataTransform?: DataTransform\n metricsRegister?: MetricsRegister | null\n metricsTopicStrToLabel?: TopicStrToLabel\n\n // Debug\n /** Prefix tag for debug logs */\n debugName?: string\n\n /**\n * Specify the maximum number of inbound gossipsub protocol\n * streams that are allowed to be open concurrently\n */\n maxInboundStreams?: number\n\n /**\n * Specify the maximum number of outbound gossipsub protocol\n * streams that are allowed to be open concurrently\n */\n maxOutboundStreams?: number\n\n /**\n * Specify max buffer size in bytes for OutboundStream.\n * If full it will throw and reject sending any more data.\n */\n maxOutboundBufferSize?: number\n\n /**\n * Specify max size to skip decoding messages whose data\n * section exceeds this size.\n *\n */\n maxInboundDataLength?: number\n\n /**\n * If provided, only allow topics in this list\n */\n allowedTopics?: string[] | Set\n\n /**\n * Limits to bound protobuf decoding\n */\n decodeRpcLimits?: DecodeRPCLimits\n}\n\nexport interface GossipsubMessage {\n propagationSource: PeerId\n msgId: MsgIdStr\n msg: Message\n}\n\nexport interface GossipsubEvents extends PubSubEvents {\n 'gossipsub:heartbeat': CustomEvent\n 'gossipsub:message': CustomEvent\n}\n\nenum GossipStatusCode {\n started,\n stopped\n}\n\ntype GossipStatus =\n | {\n code: GossipStatusCode.started\n registrarTopologyIds: string[]\n heartbeatTimeout: ReturnType\n hearbeatStartMs: number\n }\n | {\n code: GossipStatusCode.stopped\n }\n\ninterface GossipOptions extends GossipsubOpts {\n scoreParams: PeerScoreParams\n scoreThresholds: PeerScoreThresholds\n}\n\ninterface AcceptFromWhitelistEntry {\n /** number of messages accepted since recomputing the peer's score */\n messagesAccepted: number\n /** have to recompute score after this time */\n acceptUntil: number\n}\n\nexport interface GossipSubComponents {\n peerId: PeerId\n peerStore: PeerStore\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport class GossipSub extends EventEmitter implements PubSub {\n /**\n * The signature policy to follow by default\n */\n public readonly globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n public multicodecs: string[] = [constants.GossipsubIDv11, constants.GossipsubIDv10]\n\n private publishConfig: PublishConfig | undefined\n\n private readonly dataTransform: DataTransform | undefined\n\n // State\n\n public readonly peers = new Set()\n public readonly streamsInbound = new Map()\n public readonly streamsOutbound = new Map()\n\n /** Ensures outbound streams are created sequentially */\n private outboundInflightQueue = pushable<{ peerId: PeerId; connection: Connection }>({ objectMode: true })\n\n /** Direct peers */\n public readonly direct = new Set()\n\n /** Floodsub peers */\n private readonly floodsubPeers = new Set()\n\n /** Cache of seen messages */\n private readonly seenCache: SimpleTimeCache\n\n /**\n * Map of peer id and AcceptRequestWhileListEntry\n */\n private readonly acceptFromWhitelist = new Map()\n\n /**\n * Map of topics to which peers are subscribed to\n */\n private readonly topics = new Map>()\n\n /**\n * List of our subscriptions\n */\n private readonly subscriptions = new Set()\n\n /**\n * Map of topic meshes\n * topic => peer id set\n */\n public readonly mesh = new Map>()\n\n /**\n * Map of topics to set of peers. These mesh peers are the ones to which we are publishing without a topic membership\n * topic => peer id set\n */\n public readonly fanout = new Map>()\n\n /**\n * Map of last publish time for fanout topics\n * topic => last publish time\n */\n private readonly fanoutLastpub = new Map()\n\n /**\n * Map of pending messages to gossip\n * peer id => control messages\n */\n public readonly gossip = new Map()\n\n /**\n * Map of control messages\n * peer id => control message\n */\n public readonly control = new Map()\n\n /**\n * Number of IHAVEs received from peer in the last heartbeat\n */\n private readonly peerhave = new Map()\n\n /** Number of messages we have asked from peer in the last heartbeat */\n private readonly iasked = new Map()\n\n /** Prune backoff map */\n private readonly backoff = new Map>()\n\n /**\n * Connection direction cache, marks peers with outbound connections\n * peer id => direction\n */\n private readonly outbound = new Map()\n private readonly msgIdFn: MsgIdFn\n\n /**\n * A fast message id function used for internal message de-duplication\n */\n private readonly fastMsgIdFn: FastMsgIdFn | undefined\n\n private readonly msgIdToStrFn: MsgIdToStrFn\n\n /** Maps fast message-id to canonical message-id */\n private readonly fastMsgIdCache: SimpleTimeCache | undefined\n\n /**\n * Short term cache for published message ids. This is used for penalizing peers sending\n * our own messages back if the messages are anonymous or use a random author.\n */\n private readonly publishedMessageIds: SimpleTimeCache\n\n /**\n * A message cache that contains the messages for last few heartbeat ticks\n */\n private readonly mcache: MessageCache\n\n /** Peer score tracking */\n public readonly score: PeerScore\n\n /**\n * Custom validator function per topic.\n * Must return or resolve quickly (< 100ms) to prevent causing penalties for late messages.\n * If you need to apply validation that may require longer times use `asyncValidation` option and callback the\n * validation result through `Gossipsub.reportValidationResult`\n */\n public readonly topicValidators = new Map()\n\n /**\n * Make this protected so child class may want to redirect to its own log.\n */\n protected readonly log: Logger\n\n /**\n * Number of heartbeats since the beginning of time\n * This allows us to amortize some resource cleanup -- eg: backoff cleanup\n */\n private heartbeatTicks = 0\n\n /**\n * Tracks IHAVE/IWANT promises broken by peers\n */\n readonly gossipTracer: IWantTracer\n\n private readonly components: GossipSubComponents\n\n private directPeerInitial: ReturnType | null = null\n\n public static multicodec: string = constants.GossipsubIDv11\n\n // Options\n readonly opts: Required\n private readonly decodeRpcLimits: DecodeRPCLimits\n\n private readonly metrics: Metrics | null\n private status: GossipStatus = { code: GossipStatusCode.stopped }\n private maxInboundStreams?: number\n private maxOutboundStreams?: number\n private allowedTopics: Set | null\n\n private heartbeatTimer: {\n _intervalId: ReturnType | undefined\n runPeriodically: (fn: () => void, period: number) => void\n cancel: () => void\n } | null = null\n\n constructor(components: GossipSubComponents, options: Partial = {}) {\n super()\n\n const opts = {\n fallbackToFloodsub: true,\n floodPublish: true,\n doPX: false,\n directPeers: [],\n D: constants.GossipsubD,\n Dlo: constants.GossipsubDlo,\n Dhi: constants.GossipsubDhi,\n Dscore: constants.GossipsubDscore,\n Dout: constants.GossipsubDout,\n Dlazy: constants.GossipsubDlazy,\n heartbeatInterval: constants.GossipsubHeartbeatInterval,\n fanoutTTL: constants.GossipsubFanoutTTL,\n mcacheLength: constants.GossipsubHistoryLength,\n mcacheGossip: constants.GossipsubHistoryGossip,\n seenTTL: constants.GossipsubSeenTTL,\n gossipsubIWantFollowupMs: constants.GossipsubIWantFollowupTime,\n prunePeers: constants.GossipsubPrunePeers,\n pruneBackoff: constants.GossipsubPruneBackoff,\n graftFloodThreshold: constants.GossipsubGraftFloodThreshold,\n opportunisticGraftPeers: constants.GossipsubOpportunisticGraftPeers,\n opportunisticGraftTicks: constants.GossipsubOpportunisticGraftTicks,\n directConnectTicks: constants.GossipsubDirectConnectTicks,\n ...options,\n scoreParams: createPeerScoreParams(options.scoreParams),\n scoreThresholds: createPeerScoreThresholds(options.scoreThresholds)\n }\n\n this.components = components\n this.decodeRpcLimits = opts.decodeRpcLimits ?? defaultDecodeRpcLimits\n\n this.globalSignaturePolicy = opts.globalSignaturePolicy ?? StrictSign\n\n // Also wants to get notified of peers connected using floodsub\n if (opts.fallbackToFloodsub) {\n this.multicodecs.push(constants.FloodsubID)\n }\n\n // From pubsub\n this.log = logger(opts.debugName ?? 'libp2p:gossipsub')\n\n // Gossipsub\n\n this.opts = opts as Required\n this.direct = new Set(opts.directPeers.map((p) => p.id.toString()))\n this.seenCache = new SimpleTimeCache({ validityMs: opts.seenTTL })\n this.publishedMessageIds = new SimpleTimeCache({ validityMs: opts.seenTTL })\n\n if (options.msgIdFn) {\n // Use custom function\n this.msgIdFn = options.msgIdFn\n } else {\n switch (this.globalSignaturePolicy) {\n case StrictSign:\n this.msgIdFn = msgIdFnStrictSign\n break\n case StrictNoSign:\n this.msgIdFn = msgIdFnStrictNoSign\n break\n }\n }\n\n if (options.fastMsgIdFn) {\n this.fastMsgIdFn = options.fastMsgIdFn\n this.fastMsgIdCache = new SimpleTimeCache({ validityMs: opts.seenTTL })\n }\n\n // By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n this.msgIdToStrFn = options.msgIdToStrFn ?? messageIdToString\n\n this.mcache = options.messageCache || new MessageCache(opts.mcacheGossip, opts.mcacheLength, this.msgIdToStrFn)\n\n if (options.dataTransform) {\n this.dataTransform = options.dataTransform\n }\n\n if (options.metricsRegister) {\n if (!options.metricsTopicStrToLabel) {\n throw Error('Must set metricsTopicStrToLabel with metrics')\n }\n\n // in theory, each topic has its own meshMessageDeliveriesWindow param\n // however in lodestar, we configure it mostly the same so just pick the max of positive ones\n // (some topics have meshMessageDeliveriesWindow as 0)\n const maxMeshMessageDeliveriesWindowMs = Math.max(\n ...Object.values(opts.scoreParams.topics).map((topicParam) => topicParam.meshMessageDeliveriesWindow),\n constants.DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS\n )\n\n const metrics = getMetrics(options.metricsRegister, options.metricsTopicStrToLabel, {\n gossipPromiseExpireSec: this.opts.gossipsubIWantFollowupMs / 1000,\n behaviourPenaltyThreshold: opts.scoreParams.behaviourPenaltyThreshold,\n maxMeshMessageDeliveriesWindowSec: maxMeshMessageDeliveriesWindowMs / 1000\n })\n\n metrics.mcacheSize.addCollect(() => this.onScrapeMetrics(metrics))\n for (const protocol of this.multicodecs) {\n metrics.protocolsEnabled.set({ protocol }, 1)\n }\n\n this.metrics = metrics\n } else {\n this.metrics = null\n }\n\n this.gossipTracer = new IWantTracer(this.opts.gossipsubIWantFollowupMs, this.msgIdToStrFn, this.metrics)\n\n /**\n * libp2p\n */\n this.score = new PeerScore(this.opts.scoreParams, this.metrics, {\n scoreCacheValidityMs: opts.heartbeatInterval\n })\n\n this.maxInboundStreams = options.maxInboundStreams\n this.maxOutboundStreams = options.maxOutboundStreams\n\n this.allowedTopics = opts.allowedTopics ? new Set(opts.allowedTopics) : null\n }\n\n getPeers(): PeerId[] {\n return [...this.peers.keys()].map((str) => peerIdFromString(str))\n }\n\n isStarted(): boolean {\n return this.status.code === GossipStatusCode.started\n }\n\n // LIFECYCLE METHODS\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node and sends our\n * our subscriptions to every peer connected\n */\n async start(): Promise {\n // From pubsub\n if (this.isStarted()) {\n return\n }\n\n this.log('starting')\n\n this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId)\n\n // Create the outbound inflight queue\n // This ensures that outbound stream creation happens sequentially\n this.outboundInflightQueue = pushable({ objectMode: true })\n pipe(this.outboundInflightQueue, async (source) => {\n for await (const { peerId, connection } of source) {\n await this.createOutboundStream(peerId, connection)\n }\n }).catch((e) => this.log.error('outbound inflight queue error', e))\n\n // set direct peer addresses in the address book\n await Promise.all(\n this.opts.directPeers.map(async (p) => {\n await this.components.peerStore.addressBook.add(p.id, p.addrs)\n })\n )\n\n const registrar = this.components.registrar\n // Incoming streams\n // Called after a peer dials us\n await Promise.all(\n this.multicodecs.map((multicodec) =>\n registrar.handle(multicodec, this.onIncomingStream.bind(this), {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams\n })\n )\n )\n\n // # How does Gossipsub interact with libp2p? Rough guide from Mar 2022\n //\n // ## Setup:\n // Gossipsub requests libp2p to callback, TBD\n //\n // `this.libp2p.handle()` registers a handler for `/meshsub/1.1.0` and other Gossipsub protocols\n // The handler callback is registered in libp2p Upgrader.protocols map.\n //\n // Upgrader receives an inbound connection from some transport and (`Upgrader.upgradeInbound`):\n // - Adds encryption (NOISE in our case)\n // - Multiplex stream\n // - Create a muxer and register that for each new stream call Upgrader.protocols handler\n //\n // ## Topology\n // - new instance of Topology (unlinked to libp2p) with handlers\n // - registar.register(topology)\n\n // register protocol with topology\n // Topology callbacks called on connection manager changes\n const topology = createTopology({\n onConnect: this.onPeerConnected.bind(this),\n onDisconnect: this.onPeerDisconnected.bind(this)\n })\n const registrarTopologyIds = await Promise.all(\n this.multicodecs.map((multicodec) => registrar.register(multicodec, topology))\n )\n\n // Schedule to start heartbeat after `GossipsubHeartbeatInitialDelay`\n const heartbeatTimeout = setTimeout(this.runHeartbeat, constants.GossipsubHeartbeatInitialDelay)\n // Then, run heartbeat every `heartbeatInterval` offset by `GossipsubHeartbeatInitialDelay`\n\n this.status = {\n code: GossipStatusCode.started,\n registrarTopologyIds,\n heartbeatTimeout: heartbeatTimeout,\n hearbeatStartMs: Date.now() + constants.GossipsubHeartbeatInitialDelay\n }\n\n this.score.start()\n // connect to direct peers\n this.directPeerInitial = setTimeout(() => {\n Promise.resolve()\n .then(async () => {\n await Promise.all(Array.from(this.direct).map(async (id) => await this.connect(id)))\n })\n .catch((err) => {\n this.log(err)\n })\n }, constants.GossipsubDirectConnectInitialDelay)\n\n this.log('started')\n }\n\n /**\n * Unmounts the gossipsub protocol and shuts down every connection\n */\n async stop(): Promise {\n this.log('stopping')\n // From pubsub\n\n if (this.status.code !== GossipStatusCode.started) {\n return\n }\n\n const { registrarTopologyIds } = this.status\n this.status = { code: GossipStatusCode.stopped }\n\n // unregister protocol and handlers\n const registrar = this.components.registrar\n registrarTopologyIds.forEach((id) => registrar.unregister(id))\n\n this.outboundInflightQueue.end()\n\n for (const outboundStream of this.streamsOutbound.values()) {\n outboundStream.close()\n }\n this.streamsOutbound.clear()\n\n for (const inboundStream of this.streamsInbound.values()) {\n inboundStream.close()\n }\n this.streamsInbound.clear()\n\n this.peers.clear()\n this.subscriptions.clear()\n\n // Gossipsub\n\n if (this.heartbeatTimer) {\n this.heartbeatTimer.cancel()\n this.heartbeatTimer = null\n }\n\n this.score.stop()\n\n this.mesh.clear()\n this.fanout.clear()\n this.fanoutLastpub.clear()\n this.gossip.clear()\n this.control.clear()\n this.peerhave.clear()\n this.iasked.clear()\n this.backoff.clear()\n this.outbound.clear()\n this.gossipTracer.clear()\n this.seenCache.clear()\n if (this.fastMsgIdCache) this.fastMsgIdCache.clear()\n if (this.directPeerInitial) clearTimeout(this.directPeerInitial)\n\n this.log('stopped')\n }\n\n /** FOR DEBUG ONLY - Dump peer stats for all peers. Data is cloned, safe to mutate */\n dumpPeerScoreStats(): PeerScoreStatsDump {\n return this.score.dumpPeerScoreStats()\n }\n\n /**\n * On an inbound stream opened\n */\n private onIncomingStream({ stream, connection }: IncomingStreamData) {\n if (!this.isStarted()) {\n return\n }\n\n const peerId = connection.remotePeer\n // add peer to router\n this.addPeer(peerId, connection.stat.direction, connection.remoteAddr)\n // create inbound stream\n this.createInboundStream(peerId, stream)\n // attempt to create outbound stream\n this.outboundInflightQueue.push({ peerId, connection })\n }\n\n /**\n * Registrar notifies an established connection with pubsub protocol\n */\n private onPeerConnected(peerId: PeerId, connection: Connection): void {\n this.metrics?.newConnectionCount.inc({ status: connection.stat.status })\n // libp2p may emit a closed connection and never issue peer:disconnect event\n // see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/398\n if (!this.isStarted() || connection.stat.status !== 'OPEN') {\n return\n }\n\n this.addPeer(peerId, connection.stat.direction, connection.remoteAddr)\n this.outboundInflightQueue.push({ peerId, connection })\n }\n\n /**\n * Registrar notifies a closing connection with pubsub protocol\n */\n private onPeerDisconnected(peerId: PeerId): void {\n this.log('connection ended %p', peerId)\n this.removePeer(peerId)\n }\n\n private async createOutboundStream(peerId: PeerId, connection: Connection): Promise {\n if (!this.isStarted()) {\n return\n }\n\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // TODO make this behavior more robust\n // This behavior is different than for inbound streams\n // If an outbound stream already exists, don't create a new stream\n if (this.streamsOutbound.has(id)) {\n return\n }\n\n try {\n const stream = new OutboundStream(\n await connection.newStream(this.multicodecs),\n (e) => this.log.error('outbound pipe error', e),\n { maxBufferSize: this.opts.maxOutboundBufferSize }\n )\n\n this.log('create outbound stream %p', peerId)\n\n this.streamsOutbound.set(id, stream)\n\n const protocol = stream.protocol\n if (protocol === constants.FloodsubID) {\n this.floodsubPeers.add(id)\n }\n this.metrics?.peersPerProtocol.inc({ protocol }, 1)\n\n // Immediately send own subscriptions via the newly attached stream\n if (this.subscriptions.size > 0) {\n this.log('send subscriptions to', id)\n this.sendSubscriptions(id, Array.from(this.subscriptions), true)\n }\n } catch (e) {\n this.log.error('createOutboundStream error', e)\n }\n }\n\n private async createInboundStream(peerId: PeerId, stream: Stream): Promise {\n if (!this.isStarted()) {\n return\n }\n\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // TODO make this behavior more robust\n // This behavior is different than for outbound streams\n // If a peer initiates a new inbound connection\n // we assume that one is the new canonical inbound stream\n const priorInboundStream = this.streamsInbound.get(id)\n if (priorInboundStream !== undefined) {\n this.log('replacing existing inbound steam %s', id)\n priorInboundStream.close()\n }\n\n this.log('create inbound stream %s', id)\n\n const inboundStream = new InboundStream(stream, { maxDataLength: this.opts.maxInboundDataLength })\n this.streamsInbound.set(id, inboundStream)\n\n this.pipePeerReadStream(peerId, inboundStream.source).catch((err) => this.log(err))\n }\n\n /**\n * Add a peer to the router\n */\n private addPeer(peerId: PeerId, direction: ConnectionDirection, addr: Multiaddr): void {\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n this.log('new peer %p', peerId)\n\n this.peers.add(id)\n\n // Add to peer scoring\n this.score.addPeer(id)\n const currentIP = multiaddrToIPStr(addr)\n if (currentIP !== null) {\n this.score.addIP(id, currentIP)\n } else {\n this.log('Added peer has no IP in current address %s %s', id, addr.toString())\n }\n\n // track the connection direction. Don't allow to unset outbound\n if (!this.outbound.has(id)) {\n this.outbound.set(id, direction === 'outbound')\n }\n }\n }\n\n /**\n * Removes a peer from the router\n */\n private removePeer(peerId: PeerId): void {\n const id = peerId.toString()\n\n if (!this.peers.has(id)) {\n return\n }\n\n // delete peer\n this.log('delete peer %p', peerId)\n this.peers.delete(id)\n\n const outboundStream = this.streamsOutbound.get(id)\n const inboundStream = this.streamsInbound.get(id)\n\n if (outboundStream) {\n this.metrics?.peersPerProtocol.inc({ protocol: outboundStream.protocol }, -1)\n }\n\n // close streams\n outboundStream?.close()\n inboundStream?.close()\n\n // remove streams\n this.streamsOutbound.delete(id)\n this.streamsInbound.delete(id)\n\n // remove peer from topics map\n for (const peers of this.topics.values()) {\n peers.delete(id)\n }\n\n // Remove this peer from the mesh\n for (const [topicStr, peers] of this.mesh) {\n if (peers.delete(id) === true) {\n this.metrics?.onRemoveFromMesh(topicStr, ChurnReason.Dc, 1)\n }\n }\n\n // Remove this peer from the fanout\n for (const peers of this.fanout.values()) {\n peers.delete(id)\n }\n\n // Remove from floodsubPeers\n this.floodsubPeers.delete(id)\n // Remove from gossip mapping\n this.gossip.delete(id)\n // Remove from control mapping\n this.control.delete(id)\n // Remove from backoff mapping\n this.outbound.delete(id)\n\n // Remove from peer scoring\n this.score.removePeer(id)\n\n this.acceptFromWhitelist.delete(id)\n }\n\n // API METHODS\n\n get started(): boolean {\n return this.status.code === GossipStatusCode.started\n }\n\n /**\n * Get a the peer-ids in a topic mesh\n */\n getMeshPeers(topic: TopicStr): PeerIdStr[] {\n const peersInTopic = this.mesh.get(topic)\n return peersInTopic ? Array.from(peersInTopic) : []\n }\n\n /**\n * Get a list of the peer-ids that are subscribed to one topic.\n */\n getSubscribers(topic: TopicStr): PeerId[] {\n const peersInTopic = this.topics.get(topic)\n return (peersInTopic ? Array.from(peersInTopic) : []).map((str) => peerIdFromString(str))\n }\n\n /**\n * Get the list of topics which the peer is subscribed to.\n */\n getTopics(): TopicStr[] {\n return Array.from(this.subscriptions)\n }\n\n // TODO: Reviewing Pubsub API\n\n // MESSAGE METHODS\n\n /**\n * Responsible for processing each RPC message received by other peers.\n */\n private async pipePeerReadStream(peerId: PeerId, stream: AsyncIterable): Promise {\n try {\n await pipe(stream, async (source) => {\n for await (const data of source) {\n try {\n // TODO: Check max gossip message size, before decodeRpc()\n const rpcBytes = data.subarray()\n // Note: This function may throw, it must be wrapped in a try {} catch {} to prevent closing the stream.\n // TODO: What should we do if the entire RPC is invalid?\n const rpc = decodeRpc(rpcBytes, this.decodeRpcLimits)\n\n this.metrics?.onRpcRecv(rpc, rpcBytes.length)\n\n // Since processRpc may be overridden entirely in unsafe ways,\n // the simplest/safest option here is to wrap in a function and capture all errors\n // to prevent a top-level unhandled exception\n // This processing of rpc messages should happen without awaiting full validation/execution of prior messages\n if (this.opts.awaitRpcHandler) {\n try {\n await this.handleReceivedRpc(peerId, rpc)\n } catch (err) {\n this.metrics?.onRpcRecvError()\n this.log(err)\n }\n } else {\n this.handleReceivedRpc(peerId, rpc).catch((err) => {\n this.metrics?.onRpcRecvError()\n this.log(err)\n })\n }\n } catch (e) {\n this.metrics?.onRpcDataError()\n this.log(e as Error)\n }\n }\n })\n } catch (err) {\n this.metrics?.onPeerReadStreamError()\n this.handlePeerReadStreamError(err as Error, peerId)\n }\n }\n\n /**\n * Handle error when read stream pipe throws, less of the functional use but more\n * to for testing purposes to spy on the error handling\n * */\n private handlePeerReadStreamError(err: Error, peerId: PeerId): void {\n this.log.error(err)\n this.onPeerDisconnected(peerId)\n }\n\n /**\n * Handles an rpc request from a peer\n */\n public async handleReceivedRpc(from: PeerId, rpc: IRPC): Promise {\n // Check if peer is graylisted in which case we ignore the event\n if (!this.acceptFrom(from.toString())) {\n this.log('received message from unacceptable peer %p', from)\n this.metrics?.rpcRecvNotAccepted.inc()\n return\n }\n\n const subscriptions = rpc.subscriptions ? rpc.subscriptions.length : 0\n const messages = rpc.messages ? rpc.messages.length : 0\n let ihave = 0\n let iwant = 0\n let graft = 0\n let prune = 0\n if (rpc.control) {\n if (rpc.control.ihave) ihave = rpc.control.ihave.length\n if (rpc.control.iwant) iwant = rpc.control.iwant.length\n if (rpc.control.graft) graft = rpc.control.graft.length\n if (rpc.control.prune) prune = rpc.control.prune.length\n }\n this.log(\n `rpc.from ${from.toString()} subscriptions ${subscriptions} messages ${messages} ihave ${ihave} iwant ${iwant} graft ${graft} prune ${prune}`\n )\n\n // Handle received subscriptions\n if (rpc.subscriptions && rpc.subscriptions.length > 0) {\n // update peer subscriptions\n\n const subscriptions: { topic: TopicStr; subscribe: boolean }[] = []\n\n rpc.subscriptions.forEach((subOpt) => {\n const topic = subOpt.topic\n const subscribe = subOpt.subscribe === true\n\n if (topic != null) {\n if (this.allowedTopics && !this.allowedTopics.has(topic)) {\n // Not allowed: subscription data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n return\n }\n\n this.handleReceivedSubscription(from, topic, subscribe)\n\n subscriptions.push({ topic, subscribe })\n }\n })\n\n this.dispatchEvent(\n new CustomEvent('subscription-change', {\n detail: { peerId: from, subscriptions }\n })\n )\n }\n\n // Handle messages\n // TODO: (up to limit)\n if (rpc.messages) {\n for (const message of rpc.messages) {\n if (this.allowedTopics && !this.allowedTopics.has(message.topic)) {\n // Not allowed: message cache data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n continue\n }\n\n const handleReceivedMessagePromise = this.handleReceivedMessage(from, message)\n // Should never throw, but handle just in case\n .catch((err) => {\n this.metrics?.onMsgRecvError(message.topic)\n this.log(err)\n })\n\n if (this.opts.awaitRpcMessageHandler) {\n await handleReceivedMessagePromise\n }\n }\n }\n\n // Handle control messages\n if (rpc.control) {\n await this.handleControlMessage(from.toString(), rpc.control)\n }\n }\n\n /**\n * Handles a subscription change from a peer\n */\n private handleReceivedSubscription(from: PeerId, topic: TopicStr, subscribe: boolean): void {\n this.log('subscription update from %p topic %s', from, topic)\n\n let topicSet = this.topics.get(topic)\n if (topicSet == null) {\n topicSet = new Set()\n this.topics.set(topic, topicSet)\n }\n\n if (subscribe) {\n // subscribe peer to new topic\n topicSet.add(from.toString())\n } else {\n // unsubscribe from existing topic\n topicSet.delete(from.toString())\n }\n\n // TODO: rust-libp2p has A LOT more logic here\n }\n\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n private async handleReceivedMessage(from: PeerId, rpcMsg: RPC.IMessage): Promise {\n this.metrics?.onMsgRecvPreValidation(rpcMsg.topic)\n\n const validationResult = await this.validateReceivedMessage(from, rpcMsg)\n\n this.metrics?.onMsgRecvResult(rpcMsg.topic, validationResult.code)\n\n switch (validationResult.code) {\n case MessageStatus.duplicate:\n // Report the duplicate\n this.score.duplicateMessage(from.toString(), validationResult.msgIdStr, rpcMsg.topic)\n // due to the collision of fastMsgIdFn, 2 different messages may end up the same fastMsgId\n // so we need to also mark the duplicate message as delivered or the promise is not resolved\n // and peer gets penalized. See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/385\n this.gossipTracer.deliverMessage(validationResult.msgIdStr, true)\n this.mcache.observeDuplicate(validationResult.msgIdStr, from.toString())\n return\n\n case MessageStatus.invalid:\n // invalid messages received\n // metrics.register_invalid_message(&raw_message.topic)\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n if (validationResult.msgIdStr) {\n const msgIdStr = validationResult.msgIdStr\n this.score.rejectMessage(from.toString(), msgIdStr, rpcMsg.topic, validationResult.reason)\n this.gossipTracer.rejectMessage(msgIdStr, validationResult.reason)\n } else {\n this.score.rejectInvalidMessage(from.toString(), rpcMsg.topic)\n }\n\n this.metrics?.onMsgRecvInvalid(rpcMsg.topic, validationResult)\n return\n\n case MessageStatus.valid:\n // Tells score that message arrived (but is maybe not fully validated yet).\n // Consider the message as delivered for gossip promises.\n this.score.validateMessage(validationResult.messageId.msgIdStr)\n this.gossipTracer.deliverMessage(validationResult.messageId.msgIdStr)\n\n // Add the message to our memcache\n // if no validation is required, mark the message as validated\n this.mcache.put(validationResult.messageId, rpcMsg, !this.opts.asyncValidation)\n\n // Dispatch the message to the user if we are subscribed to the topic\n if (this.subscriptions.has(rpcMsg.topic)) {\n const isFromSelf = this.components.peerId.equals(from)\n\n if (!isFromSelf || this.opts.emitSelf) {\n super.dispatchEvent(\n new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: from,\n msgId: validationResult.messageId.msgIdStr,\n msg: validationResult.msg\n }\n })\n )\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: validationResult.msg }))\n }\n }\n\n // Forward the message to mesh peers, if no validation is required\n // If asyncValidation is ON, expect the app layer to call reportMessageValidationResult(), then forward\n if (!this.opts.asyncValidation) {\n // TODO: in rust-libp2p\n // .forward_msg(&msg_id, raw_message, Some(propagation_source))\n this.forwardMessage(validationResult.messageId.msgIdStr, rpcMsg, from.toString())\n }\n }\n }\n\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n private async validateReceivedMessage(\n propagationSource: PeerId,\n rpcMsg: RPC.IMessage\n ): Promise {\n // Fast message ID stuff\n const fastMsgIdStr = this.fastMsgIdFn?.(rpcMsg)\n const msgIdCached = fastMsgIdStr !== undefined ? this.fastMsgIdCache?.get(fastMsgIdStr) : undefined\n\n if (msgIdCached) {\n // This message has been seen previously. Ignore it\n return { code: MessageStatus.duplicate, msgIdStr: msgIdCached }\n }\n\n // Perform basic validation on message and convert to RawGossipsubMessage for fastMsgIdFn()\n const validationResult = await validateToRawMessage(this.globalSignaturePolicy, rpcMsg)\n\n if (!validationResult.valid) {\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: validationResult.error }\n }\n\n const msg = validationResult.message\n\n // Try and perform the data transform to the message. If it fails, consider it invalid.\n try {\n if (this.dataTransform) {\n msg.data = this.dataTransform.inboundTransform(rpcMsg.topic, msg.data)\n }\n } catch (e) {\n this.log('Invalid message, transform failed', e)\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: ValidateError.TransformFailed }\n }\n\n // TODO: Check if message is from a blacklisted source or propagation origin\n // - Reject any message from a blacklisted peer\n // - Also reject any message that originated from a blacklisted peer\n // - reject messages claiming to be from ourselves but not locally published\n\n // Calculate the message id on the transformed data.\n const msgId = await this.msgIdFn(msg)\n const msgIdStr = this.msgIdToStrFn(msgId)\n const messageId = { msgId, msgIdStr }\n\n // Add the message to the duplicate caches\n if (fastMsgIdStr !== undefined && this.fastMsgIdCache) {\n const collision = this.fastMsgIdCache.put(fastMsgIdStr, msgIdStr)\n if (collision) {\n this.metrics?.fastMsgIdCacheCollision.inc()\n }\n }\n\n if (this.seenCache.has(msgIdStr)) {\n return { code: MessageStatus.duplicate, msgIdStr }\n } else {\n this.seenCache.put(msgIdStr)\n }\n\n // (Optional) Provide custom validation here with dynamic validators per topic\n // NOTE: This custom topicValidator() must resolve fast (< 100ms) to allow scores\n // to not penalize peers for long validation times.\n const topicValidator = this.topicValidators.get(rpcMsg.topic)\n if (topicValidator != null) {\n let acceptance: TopicValidatorResult\n // Use try {} catch {} in case topicValidator() is synchronous\n try {\n acceptance = await topicValidator(propagationSource, msg)\n } catch (e) {\n const errCode = (e as { code: string }).code\n if (errCode === constants.ERR_TOPIC_VALIDATOR_IGNORE) acceptance = TopicValidatorResult.Ignore\n if (errCode === constants.ERR_TOPIC_VALIDATOR_REJECT) acceptance = TopicValidatorResult.Reject\n else acceptance = TopicValidatorResult.Ignore\n }\n\n if (acceptance !== TopicValidatorResult.Accept) {\n return { code: MessageStatus.invalid, reason: rejectReasonFromAcceptance(acceptance), msgIdStr }\n }\n }\n\n return { code: MessageStatus.valid, messageId, msg }\n }\n\n /**\n * Return score of a peer.\n */\n getScore(peerId: PeerIdStr): number {\n return this.score.score(peerId)\n }\n\n /**\n * Send an rpc object to a peer with subscriptions\n */\n private sendSubscriptions(toPeer: PeerIdStr, topics: string[], subscribe: boolean): void {\n this.sendRpc(toPeer, {\n subscriptions: topics.map((topic) => ({ topic, subscribe }))\n })\n }\n\n /**\n * Handles an rpc control message from a peer\n */\n private async handleControlMessage(id: PeerIdStr, controlMsg: RPC.IControlMessage): Promise {\n if (controlMsg === undefined) {\n return\n }\n\n const iwant = controlMsg.ihave ? this.handleIHave(id, controlMsg.ihave) : []\n const ihave = controlMsg.iwant ? this.handleIWant(id, controlMsg.iwant) : []\n const prune = controlMsg.graft ? await this.handleGraft(id, controlMsg.graft) : []\n controlMsg.prune && (await this.handlePrune(id, controlMsg.prune))\n\n if (!iwant.length && !ihave.length && !prune.length) {\n return\n }\n\n const sent = this.sendRpc(id, { messages: ihave, control: { iwant, prune } })\n const iwantMessageIds = iwant[0]?.messageIDs\n if (iwantMessageIds) {\n if (sent) {\n this.gossipTracer.addPromise(id, iwantMessageIds)\n } else {\n this.metrics?.iwantPromiseUntracked.inc(1)\n }\n }\n }\n\n /**\n * Whether to accept a message from a peer\n */\n public acceptFrom(id: PeerIdStr): boolean {\n if (this.direct.has(id)) {\n return true\n }\n\n const now = Date.now()\n const entry = this.acceptFromWhitelist.get(id)\n\n if (entry && entry.messagesAccepted < ACCEPT_FROM_WHITELIST_MAX_MESSAGES && entry.acceptUntil >= now) {\n entry.messagesAccepted += 1\n return true\n }\n\n const score = this.score.score(id)\n if (score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE) {\n // peer is unlikely to be able to drop its score to `graylistThreshold`\n // after 128 messages or 1s\n this.acceptFromWhitelist.set(id, {\n messagesAccepted: 0,\n acceptUntil: now + ACCEPT_FROM_WHITELIST_DURATION_MS\n })\n } else {\n this.acceptFromWhitelist.delete(id)\n }\n\n return score >= this.opts.scoreThresholds.graylistThreshold\n }\n\n /**\n * Handles IHAVE messages\n */\n private handleIHave(id: PeerIdStr, ihave: RPC.IControlIHave[]): RPC.IControlIWant[] {\n if (!ihave.length) {\n return []\n }\n\n // we ignore IHAVE gossip from any peer whose score is below the gossips threshold\n const score = this.score.score(id)\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IHAVE: ignoring peer %s with score below threshold [ score = %d ]', id, score)\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.LowScore })\n return []\n }\n\n // IHAVE flood protection\n const peerhave = (this.peerhave.get(id) ?? 0) + 1\n this.peerhave.set(id, peerhave)\n if (peerhave > constants.GossipsubMaxIHaveMessages) {\n this.log(\n 'IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring',\n id,\n peerhave\n )\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIhave })\n return []\n }\n\n const iasked = this.iasked.get(id) ?? 0\n if (iasked >= constants.GossipsubMaxIHaveLength) {\n this.log('IHAVE: peer %s has already advertised too many messages (%d); ignoring', id, iasked)\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIasked })\n return []\n }\n\n // string msgId => msgId\n const iwant = new Map()\n\n ihave.forEach(({ topicID, messageIDs }) => {\n if (!topicID || !messageIDs || !this.mesh.has(topicID)) {\n return\n }\n\n let idonthave = 0\n\n messageIDs.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId)\n if (!this.seenCache.has(msgIdStr)) {\n iwant.set(msgIdStr, msgId)\n idonthave++\n }\n })\n\n this.metrics?.onIhaveRcv(topicID, messageIDs.length, idonthave)\n })\n\n if (!iwant.size) {\n return []\n }\n\n let iask = iwant.size\n if (iask + iasked > constants.GossipsubMaxIHaveLength) {\n iask = constants.GossipsubMaxIHaveLength - iasked\n }\n\n this.log('IHAVE: Asking for %d out of %d messages from %s', iask, iwant.size, id)\n\n let iwantList = Array.from(iwant.values())\n // ask in random order\n shuffle(iwantList)\n\n // truncate to the messages we are actually asking for and update the iasked counter\n iwantList = iwantList.slice(0, iask)\n this.iasked.set(id, iasked + iask)\n\n // do not add gossipTracer promise here until a successful sendRpc()\n\n return [\n {\n messageIDs: iwantList\n }\n ]\n }\n\n /**\n * Handles IWANT messages\n * Returns messages to send back to peer\n */\n private handleIWant(id: PeerIdStr, iwant: RPC.IControlIWant[]): RPC.IMessage[] {\n if (!iwant.length) {\n return []\n }\n\n // we don't respond to IWANT requests from any per whose score is below the gossip threshold\n const score = this.score.score(id)\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IWANT: ignoring peer %s with score below threshold [score = %d]', id, score)\n return []\n }\n\n const ihave = new Map()\n const iwantByTopic = new Map()\n let iwantDonthave = 0\n\n iwant.forEach(({ messageIDs }) => {\n messageIDs &&\n messageIDs.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId)\n const entry = this.mcache.getWithIWantCount(msgIdStr, id)\n if (entry == null) {\n iwantDonthave++\n return\n }\n\n iwantByTopic.set(entry.msg.topic, 1 + (iwantByTopic.get(entry.msg.topic) ?? 0))\n\n if (entry.count > constants.GossipsubGossipRetransmission) {\n this.log('IWANT: Peer %s has asked for message %s too many times: ignoring request', id, msgId)\n return\n }\n\n ihave.set(msgIdStr, entry.msg)\n })\n })\n\n this.metrics?.onIwantRcv(iwantByTopic, iwantDonthave)\n\n if (!ihave.size) {\n this.log('IWANT: Could not provide any wanted messages to %s', id)\n return []\n }\n\n this.log('IWANT: Sending %d messages to %s', ihave.size, id)\n\n return Array.from(ihave.values())\n }\n\n /**\n * Handles Graft messages\n */\n private async handleGraft(id: PeerIdStr, graft: RPC.IControlGraft[]): Promise {\n const prune: TopicStr[] = []\n const score = this.score.score(id)\n const now = Date.now()\n let doPX = this.opts.doPX\n\n graft.forEach(({ topicID }) => {\n if (!topicID) {\n return\n }\n const peersInMesh = this.mesh.get(topicID)\n if (!peersInMesh) {\n // don't do PX when there is an unknown topic to avoid leaking our peers\n doPX = false\n // spam hardening: ignore GRAFTs for unknown topics\n return\n }\n\n // check if peer is already in the mesh; if so do nothing\n if (peersInMesh.has(id)) {\n return\n }\n\n // we don't GRAFT to/from direct peers; complain loudly if this happens\n if (this.direct.has(id)) {\n this.log('GRAFT: ignoring request from direct peer %s', id)\n // this is possibly a bug from a non-reciprical configuration; send a PRUNE\n prune.push(topicID)\n // but don't px\n doPX = false\n return\n }\n\n // make sure we are not backing off that peer\n const expire = this.backoff.get(topicID)?.get(id)\n if (typeof expire === 'number' && now < expire) {\n this.log('GRAFT: ignoring backed off peer %s', id)\n // add behavioral penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff)\n // no PX\n doPX = false\n // check the flood cutoff -- is the GRAFT coming too fast?\n const floodCutoff = expire + this.opts.graftFloodThreshold - this.opts.pruneBackoff\n if (now < floodCutoff) {\n // extra penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff)\n }\n // refresh the backoff\n this.addBackoff(id, topicID)\n prune.push(topicID)\n return\n }\n\n // check the score\n if (score < 0) {\n // we don't GRAFT peers with negative score\n this.log('GRAFT: ignoring peer %s with negative score: score=%d, topic=%s', id, score, topicID)\n // we do send them PRUNE however, because it's a matter of protocol correctness\n prune.push(topicID)\n // but we won't PX to them\n doPX = false\n // add/refresh backoff so that we don't reGRAFT too early even if the score decays\n this.addBackoff(id, topicID)\n return\n }\n\n // check the number of mesh peers; if it is at (or over) Dhi, we only accept grafts\n // from peers with outbound connections; this is a defensive check to restrict potential\n // mesh takeover attacks combined with love bombing\n if (peersInMesh.size >= this.opts.Dhi && !this.outbound.get(id)) {\n prune.push(topicID)\n this.addBackoff(id, topicID)\n return\n }\n\n this.log('GRAFT: Add mesh link from %s in %s', id, topicID)\n this.score.graft(id, topicID)\n peersInMesh.add(id)\n\n this.metrics?.onAddToMesh(topicID, InclusionReason.Subscribed, 1)\n })\n\n if (!prune.length) {\n return []\n }\n\n return await Promise.all(prune.map((topic) => this.makePrune(id, topic, doPX)))\n }\n\n /**\n * Handles Prune messages\n */\n private async handlePrune(id: PeerIdStr, prune: RPC.IControlPrune[]): Promise {\n const score = this.score.score(id)\n\n for (const { topicID, backoff, peers } of prune) {\n if (topicID == null) {\n continue\n }\n\n const peersInMesh = this.mesh.get(topicID)\n if (!peersInMesh) {\n return\n }\n\n this.log('PRUNE: Remove mesh link to %s in %s', id, topicID)\n this.score.prune(id, topicID)\n if (peersInMesh.has(id)) {\n peersInMesh.delete(id)\n this.metrics?.onRemoveFromMesh(topicID, ChurnReason.Unsub, 1)\n }\n\n // is there a backoff specified by the peer? if so obey it\n if (typeof backoff === 'number' && backoff > 0) {\n this.doAddBackoff(id, topicID, backoff * 1000)\n } else {\n this.addBackoff(id, topicID)\n }\n\n // PX\n if (peers && peers.length) {\n // we ignore PX from peers with insufficient scores\n if (score < this.opts.scoreThresholds.acceptPXThreshold) {\n this.log(\n 'PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]',\n id,\n score,\n topicID\n )\n continue\n }\n await this.pxConnect(peers)\n }\n }\n }\n\n /**\n * Add standard backoff log for a peer in a topic\n */\n private addBackoff(id: PeerIdStr, topic: TopicStr): void {\n this.doAddBackoff(id, topic, this.opts.pruneBackoff)\n }\n\n /**\n * Add backoff expiry interval for a peer in a topic\n *\n * @param id\n * @param topic\n * @param interval - backoff duration in milliseconds\n */\n private doAddBackoff(id: PeerIdStr, topic: TopicStr, interval: number): void {\n let backoff = this.backoff.get(topic)\n if (!backoff) {\n backoff = new Map()\n this.backoff.set(topic, backoff)\n }\n const expire = Date.now() + interval\n const existingExpire = backoff.get(id) ?? 0\n if (existingExpire < expire) {\n backoff.set(id, expire)\n }\n }\n\n /**\n * Apply penalties from broken IHAVE/IWANT promises\n */\n private applyIwantPenalties(): void {\n this.gossipTracer.getBrokenPromises().forEach((count, p) => {\n this.log(\"peer %s didn't follow up in %d IWANT requests; adding penalty\", p, count)\n this.score.addPenalty(p, count, ScorePenalty.BrokenPromise)\n })\n }\n\n /**\n * Clear expired backoff expiries\n */\n private clearBackoff(): void {\n // we only clear once every GossipsubPruneBackoffTicks ticks to avoid iterating over the maps too much\n if (this.heartbeatTicks % constants.GossipsubPruneBackoffTicks !== 0) {\n return\n }\n\n const now = Date.now()\n this.backoff.forEach((backoff, topic) => {\n backoff.forEach((expire, id) => {\n if (expire < now) {\n backoff.delete(id)\n }\n })\n if (backoff.size === 0) {\n this.backoff.delete(topic)\n }\n })\n }\n\n /**\n * Maybe reconnect to direct peers\n */\n private async directConnect(): Promise {\n const toconnect: string[] = []\n this.direct.forEach((id) => {\n if (!this.streamsOutbound.has(id)) {\n toconnect.push(id)\n }\n })\n\n await Promise.all(toconnect.map(async (id) => await this.connect(id)))\n }\n\n /**\n * Maybe attempt connection given signed peer records\n */\n private async pxConnect(peers: RPC.IPeerInfo[]): Promise {\n if (peers.length > this.opts.prunePeers) {\n shuffle(peers)\n peers = peers.slice(0, this.opts.prunePeers)\n }\n const toconnect: string[] = []\n\n await Promise.all(\n peers.map(async (pi) => {\n if (!pi.peerID) {\n return\n }\n\n const p = peerIdFromBytes(pi.peerID).toString()\n\n if (this.peers.has(p)) {\n return\n }\n\n if (!pi.signedPeerRecord) {\n toconnect.push(p)\n return\n }\n\n // The peer sent us a signed record\n // This is not a record from the peer who sent the record, but another peer who is connected with it\n // Ensure that it is valid\n try {\n const envelope = await RecordEnvelope.openAndCertify(pi.signedPeerRecord, 'libp2p-peer-record')\n const eid = envelope.peerId\n if (!envelope.peerId.equals(p)) {\n this.log(\"bogus peer record obtained through px: peer ID %p doesn't match expected peer %p\", eid, p)\n return\n }\n if (!(await this.components.peerStore.addressBook.consumePeerRecord(envelope))) {\n this.log('bogus peer record obtained through px: could not add peer record to address book')\n return\n }\n toconnect.push(p)\n } catch (e) {\n this.log('bogus peer record obtained through px: invalid signature or not a peer record')\n }\n })\n )\n\n if (!toconnect.length) {\n return\n }\n\n await Promise.all(toconnect.map(async (id) => await this.connect(id)))\n }\n\n /**\n * Connect to a peer using the gossipsub protocol\n */\n private async connect(id: PeerIdStr): Promise {\n this.log('Initiating connection with %s', id)\n const peerId = peerIdFromString(id)\n const connection = await this.components.connectionManager.openConnection(peerId)\n for (const multicodec of this.multicodecs) {\n for (const topology of this.components.registrar.getTopologies(multicodec)) {\n topology.onConnect(peerId, connection)\n }\n }\n }\n\n /**\n * Subscribes to a topic\n */\n subscribe(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub has not started')\n }\n\n if (!this.subscriptions.has(topic)) {\n this.subscriptions.add(topic)\n\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], true)\n }\n }\n\n this.join(topic)\n }\n\n /**\n * Unsubscribe to a topic\n */\n unsubscribe(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub is not started')\n }\n\n const wasSubscribed = this.subscriptions.delete(topic)\n\n this.log('unsubscribe from %s - am subscribed %s', topic, wasSubscribed)\n\n if (wasSubscribed) {\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], false)\n }\n }\n\n this.leave(topic)\n }\n\n /**\n * Join topic\n */\n private join(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started')\n }\n\n // if we are already in the mesh, return\n if (this.mesh.has(topic)) {\n return\n }\n\n this.log('JOIN %s', topic)\n this.metrics?.onJoin(topic)\n\n const toAdd = new Set()\n\n // check if we have mesh_n peers in fanout[topic] and add them to the mesh if we do,\n // removing the fanout entry.\n const fanoutPeers = this.fanout.get(topic)\n if (fanoutPeers) {\n // Remove fanout entry and the last published time\n this.fanout.delete(topic)\n this.fanoutLastpub.delete(topic)\n\n // remove explicit peers, peers with negative scores, and backoffed peers\n fanoutPeers.forEach((id) => {\n // TODO:rust-libp2p checks `self.backoffs.is_backoff_with_slack()`\n if (!this.direct.has(id) && this.score.score(id) >= 0) {\n toAdd.add(id)\n }\n })\n\n this.metrics?.onAddToMesh(topic, InclusionReason.Fanout, toAdd.size)\n }\n\n // check if we need to get more peers, which we randomly select\n if (toAdd.size < this.opts.D) {\n const fanoutCount = toAdd.size\n const newPeers = this.getRandomGossipPeers(\n topic,\n this.opts.D,\n (id: PeerIdStr): boolean =>\n // filter direct peers and peers with negative score\n !toAdd.has(id) && !this.direct.has(id) && this.score.score(id) >= 0\n )\n\n newPeers.forEach((peer) => {\n toAdd.add(peer)\n })\n\n this.metrics?.onAddToMesh(topic, InclusionReason.Random, toAdd.size - fanoutCount)\n }\n\n this.mesh.set(topic, toAdd)\n\n toAdd.forEach((id) => {\n this.log('JOIN: Add mesh link to %s in %s', id, topic)\n this.sendGraft(id, topic)\n\n // rust-libp2p\n // - peer_score.graft()\n // - Self::control_pool_add()\n // - peer_added_to_mesh()\n })\n }\n\n /**\n * Leave topic\n */\n private leave(topic: TopicStr): void {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started')\n }\n\n this.log('LEAVE %s', topic)\n this.metrics?.onLeave(topic)\n\n // Send PRUNE to mesh peers\n const meshPeers = this.mesh.get(topic)\n if (meshPeers) {\n Promise.all(\n Array.from(meshPeers).map(async (id) => {\n this.log('LEAVE: Remove mesh link to %s in %s', id, topic)\n return await this.sendPrune(id, topic)\n })\n ).catch((err) => {\n this.log('Error sending prunes to mesh peers', err)\n })\n this.mesh.delete(topic)\n }\n }\n\n private selectPeersToForward(topic: TopicStr, propagationSource?: PeerIdStr, excludePeers?: Set) {\n const tosend = new Set()\n\n // Add explicit peers\n const peersInTopic = this.topics.get(topic)\n if (peersInTopic) {\n this.direct.forEach((peer) => {\n if (peersInTopic.has(peer) && propagationSource !== peer && !excludePeers?.has(peer)) {\n tosend.add(peer)\n }\n })\n\n // As of Mar 2022, spec + golang-libp2p include this while rust-libp2p does not\n // rust-libp2p: https://github.com/libp2p/rust-libp2p/blob/6cc3b4ec52c922bfcf562a29b5805c3150e37c75/protocols/gossipsub/src/behaviour.rs#L2693\n // spec: https://github.com/libp2p/specs/blob/10712c55ab309086a52eec7d25f294df4fa96528/pubsub/gossipsub/gossipsub-v1.0.md?plain=1#L361\n this.floodsubPeers.forEach((peer) => {\n if (\n peersInTopic.has(peer) &&\n propagationSource !== peer &&\n !excludePeers?.has(peer) &&\n this.score.score(peer) >= this.opts.scoreThresholds.publishThreshold\n ) {\n tosend.add(peer)\n }\n })\n }\n\n // add mesh peers\n const meshPeers = this.mesh.get(topic)\n if (meshPeers && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n if (propagationSource !== peer && !excludePeers?.has(peer)) {\n tosend.add(peer)\n }\n })\n }\n\n return tosend\n }\n\n private selectPeersToPublish(topic: TopicStr): {\n tosend: Set\n tosendCount: ToSendGroupCount\n } {\n const tosend = new Set()\n const tosendCount: ToSendGroupCount = {\n direct: 0,\n floodsub: 0,\n mesh: 0,\n fanout: 0\n }\n\n const peersInTopic = this.topics.get(topic)\n if (peersInTopic) {\n // flood-publish behavior\n // send to direct peers and _all_ peers meeting the publishThreshold\n if (this.opts.floodPublish) {\n peersInTopic.forEach((id) => {\n if (this.direct.has(id)) {\n tosend.add(id)\n tosendCount.direct++\n } else if (this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id)\n tosendCount.floodsub++\n }\n })\n } else {\n // non-flood-publish behavior\n // send to direct peers, subscribed floodsub peers\n // and some mesh peers above publishThreshold\n\n // direct peers (if subscribed)\n this.direct.forEach((id) => {\n if (peersInTopic.has(id)) {\n tosend.add(id)\n tosendCount.direct++\n }\n })\n\n // floodsub peers\n // Note: if there are no floodsub peers, we save a loop through peersInTopic Map\n this.floodsubPeers.forEach((id) => {\n if (peersInTopic.has(id) && this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id)\n tosendCount.floodsub++\n }\n })\n\n // Gossipsub peers handling\n const meshPeers = this.mesh.get(topic)\n if (meshPeers && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.mesh++\n })\n }\n\n // We are not in the mesh for topic, use fanout peers\n else {\n const fanoutPeers = this.fanout.get(topic)\n if (fanoutPeers && fanoutPeers.size > 0) {\n fanoutPeers.forEach((peer) => {\n tosend.add(peer)\n tosendCount.fanout++\n })\n }\n\n // We have no fanout peers, select mesh_n of them and add them to the fanout\n else {\n // If we are not in the fanout, then pick peers in topic above the publishThreshold\n const newFanoutPeers = this.getRandomGossipPeers(topic, this.opts.D, (id) => {\n return this.score.score(id) >= this.opts.scoreThresholds.publishThreshold\n })\n\n if (newFanoutPeers.size > 0) {\n // eslint-disable-line max-depth\n this.fanout.set(topic, newFanoutPeers)\n\n newFanoutPeers.forEach((peer) => {\n // eslint-disable-line max-depth\n tosend.add(peer)\n tosendCount.fanout++\n })\n }\n }\n\n // We are publishing to fanout peers - update the time we published\n this.fanoutLastpub.set(topic, Date.now())\n }\n }\n }\n\n return { tosend, tosendCount }\n }\n\n /**\n * Forwards a message from our peers.\n *\n * For messages published by us (the app layer), this class uses `publish`\n */\n private forwardMessage(\n msgIdStr: string,\n rawMsg: RPC.IMessage,\n propagationSource?: PeerIdStr,\n excludePeers?: Set\n ): void {\n // message is fully validated inform peer_score\n if (propagationSource) {\n this.score.deliverMessage(propagationSource, msgIdStr, rawMsg.topic)\n }\n\n const tosend = this.selectPeersToForward(rawMsg.topic, propagationSource, excludePeers)\n\n // Note: Don't throw if tosend is empty, we can have a mesh with a single peer\n\n // forward the message to peers\n tosend.forEach((id) => {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n this.sendRpc(id, { messages: [rawMsg] })\n })\n\n this.metrics?.onForwardMsg(rawMsg.topic, tosend.size)\n }\n\n /**\n * App layer publishes a message to peers, return number of peers this message is published to\n * Note: `async` due to crypto only if `StrictSign`, otherwise it's a sync fn.\n *\n * For messages not from us, this class uses `forwardMessage`.\n */\n async publish(topic: TopicStr, data: Uint8Array, opts?: PublishOpts): Promise {\n const transformedData = this.dataTransform ? this.dataTransform.outboundTransform(topic, data) : data\n\n if (this.publishConfig == null) {\n throw Error('PublishError.Uninitialized')\n }\n\n // Prepare raw message with user's publishConfig\n const { raw: rawMsg, msg } = await buildRawMessage(this.publishConfig, topic, data, transformedData)\n\n // calculate the message id from the un-transformed data\n const msgId = await this.msgIdFn(msg)\n const msgIdStr = this.msgIdToStrFn(msgId)\n\n // Current publish opt takes precedence global opts, while preserving false value\n const ignoreDuplicatePublishError = opts?.ignoreDuplicatePublishError ?? this.opts.ignoreDuplicatePublishError\n\n if (this.seenCache.has(msgIdStr)) {\n // This message has already been seen. We don't re-publish messages that have already\n // been published on the network.\n if (ignoreDuplicatePublishError) {\n this.metrics?.onPublishDuplicateMsg(topic)\n return { recipients: [] }\n }\n throw Error('PublishError.Duplicate')\n }\n\n const { tosend, tosendCount } = this.selectPeersToPublish(topic)\n const willSendToSelf = this.opts.emitSelf === true && this.subscriptions.has(topic)\n\n // Current publish opt takes precedence global opts, while preserving false value\n const allowPublishToZeroPeers = opts?.allowPublishToZeroPeers ?? this.opts.allowPublishToZeroPeers\n\n if (tosend.size === 0 && !allowPublishToZeroPeers && !willSendToSelf) {\n throw Error('PublishError.InsufficientPeers')\n }\n\n // If the message isn't a duplicate and we have sent it to some peers add it to the\n // duplicate cache and memcache.\n this.seenCache.put(msgIdStr)\n // all published messages are valid\n this.mcache.put({ msgId, msgIdStr }, rawMsg, true)\n\n // If the message is anonymous or has a random author add it to the published message ids cache.\n this.publishedMessageIds.put(msgIdStr)\n\n // Send to set of peers aggregated from direct, mesh, fanout\n for (const id of tosend) {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n const sent = this.sendRpc(id, { messages: [rawMsg] })\n\n // did not actually send the message\n if (!sent) {\n tosend.delete(id)\n }\n }\n\n this.metrics?.onPublishMsg(topic, tosendCount, tosend.size, rawMsg.data != null ? rawMsg.data.length : 0)\n\n // Dispatch the message to the user if we are subscribed to the topic\n if (willSendToSelf) {\n tosend.add(this.components.peerId.toString())\n\n super.dispatchEvent(\n new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: this.components.peerId,\n msgId: msgIdStr,\n msg\n }\n })\n )\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: msg }))\n }\n\n return {\n recipients: Array.from(tosend.values()).map((str) => peerIdFromString(str))\n }\n }\n\n /**\n * This function should be called when `asyncValidation` is `true` after\n * the message got validated by the caller. Messages are stored in the `mcache` and\n * validation is expected to be fast enough that the messages should still exist in the cache.\n * There are three possible validation outcomes and the outcome is given in acceptance.\n *\n * If acceptance = `MessageAcceptance.Accept` the message will get propagated to the\n * network. The `propagation_source` parameter indicates who the message was received by and\n * will not be forwarded back to that peer.\n *\n * If acceptance = `MessageAcceptance.Reject` the message will be deleted from the memcache\n * and the P\u2084 penalty will be applied to the `propagationSource`.\n *\n * If acceptance = `MessageAcceptance.Ignore` the message will be deleted from the memcache\n * but no P\u2084 penalty will be applied.\n *\n * This function will return true if the message was found in the cache and false if was not\n * in the cache anymore.\n *\n * This should only be called once per message.\n */\n reportMessageValidationResult(msgId: MsgIdStr, propagationSource: PeerId, acceptance: TopicValidatorResult): void {\n if (acceptance === TopicValidatorResult.Accept) {\n const cacheEntry = this.mcache.validate(msgId)\n this.metrics?.onReportValidationMcacheHit(cacheEntry !== null)\n\n if (cacheEntry != null) {\n const { message: rawMsg, originatingPeers } = cacheEntry\n // message is fully validated inform peer_score\n this.score.deliverMessage(propagationSource.toString(), msgId, rawMsg.topic)\n\n this.forwardMessage(msgId, cacheEntry.message, propagationSource.toString(), originatingPeers)\n this.metrics?.onReportValidation(rawMsg.topic, acceptance)\n }\n // else, Message not in cache. Ignoring forwarding\n }\n\n // Not valid\n else {\n const cacheEntry = this.mcache.remove(msgId)\n this.metrics?.onReportValidationMcacheHit(cacheEntry !== null)\n\n if (cacheEntry) {\n const rejectReason = rejectReasonFromAcceptance(acceptance)\n const { message: rawMsg, originatingPeers } = cacheEntry\n\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n this.score.rejectMessage(propagationSource.toString(), msgId, rawMsg.topic, rejectReason)\n for (const peer of originatingPeers) {\n this.score.rejectMessage(peer, msgId, rawMsg.topic, rejectReason)\n }\n\n this.metrics?.onReportValidation(rawMsg.topic, acceptance)\n }\n // else, Message not in cache. Ignoring forwarding\n }\n }\n\n /**\n * Sends a GRAFT message to a peer\n */\n private sendGraft(id: PeerIdStr, topic: string): void {\n const graft = [\n {\n topicID: topic\n }\n ]\n\n this.sendRpc(id, { control: { graft } })\n }\n\n /**\n * Sends a PRUNE message to a peer\n */\n private async sendPrune(id: PeerIdStr, topic: string): Promise {\n const prune = [await this.makePrune(id, topic, this.opts.doPX)]\n\n this.sendRpc(id, { control: { prune } })\n }\n\n /**\n * Send an rpc object to a peer\n */\n private sendRpc(id: PeerIdStr, rpc: IRPC): boolean {\n const outboundStream = this.streamsOutbound.get(id)\n if (!outboundStream) {\n this.log(`Cannot send RPC to ${id} as there is no open stream to it available`)\n return false\n }\n\n // piggyback control message retries\n const ctrl = this.control.get(id)\n if (ctrl) {\n this.piggybackControl(id, rpc, ctrl)\n this.control.delete(id)\n }\n\n // piggyback gossip\n const ihave = this.gossip.get(id)\n if (ihave) {\n this.piggybackGossip(id, rpc, ihave)\n this.gossip.delete(id)\n }\n\n const rpcBytes = RPC.encode(rpc).finish()\n try {\n outboundStream.push(rpcBytes)\n } catch (e) {\n this.log.error(`Cannot send rpc to ${id}`, e)\n\n // if the peer had control messages or gossip, re-attach\n if (ctrl) {\n this.control.set(id, ctrl)\n }\n if (ihave) {\n this.gossip.set(id, ihave)\n }\n\n return false\n }\n\n this.metrics?.onRpcSent(rpc, rpcBytes.length)\n\n return true\n }\n\n /** Mutates `outRpc` adding graft and prune control messages */\n public piggybackControl(id: PeerIdStr, outRpc: IRPC, ctrl: RPC.IControlMessage): void {\n if (ctrl.graft) {\n if (!outRpc.control) outRpc.control = {}\n if (!outRpc.control.graft) outRpc.control.graft = []\n for (const graft of ctrl.graft) {\n if (graft.topicID && this.mesh.get(graft.topicID)?.has(id)) {\n outRpc.control.graft.push(graft)\n }\n }\n }\n\n if (ctrl.prune) {\n if (!outRpc.control) outRpc.control = {}\n if (!outRpc.control.prune) outRpc.control.prune = []\n for (const prune of ctrl.prune) {\n if (prune.topicID && !this.mesh.get(prune.topicID)?.has(id)) {\n outRpc.control.prune.push(prune)\n }\n }\n }\n }\n\n /** Mutates `outRpc` adding ihave control messages */\n private piggybackGossip(id: PeerIdStr, outRpc: IRPC, ihave: RPC.IControlIHave[]): void {\n if (!outRpc.control) outRpc.control = {}\n outRpc.control.ihave = ihave\n }\n\n /**\n * Send graft and prune messages\n *\n * @param tograft - peer id => topic[]\n * @param toprune - peer id => topic[]\n */\n private async sendGraftPrune(\n tograft: Map,\n toprune: Map,\n noPX: Map\n ): Promise {\n const doPX = this.opts.doPX\n for (const [id, topics] of tograft) {\n const graft = topics.map((topicID) => ({ topicID }))\n let prune: RPC.IControlPrune[] = []\n // If a peer also has prunes, process them now\n const pruning = toprune.get(id)\n if (pruning) {\n prune = await Promise.all(\n pruning.map(async (topicID) => await this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false)))\n )\n toprune.delete(id)\n }\n\n this.sendRpc(id, { control: { graft, prune } })\n }\n for (const [id, topics] of toprune) {\n const prune = await Promise.all(\n topics.map(async (topicID) => await this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false)))\n )\n this.sendRpc(id, { control: { prune } })\n }\n }\n\n /**\n * Emits gossip - Send IHAVE messages to a random set of gossip peers\n */\n private emitGossip(peersToGossipByTopic: Map>): void {\n const gossipIDsByTopic = this.mcache.getGossipIDs(new Set(peersToGossipByTopic.keys()))\n for (const [topic, peersToGossip] of peersToGossipByTopic) {\n this.doEmitGossip(topic, peersToGossip, gossipIDsByTopic.get(topic) ?? [])\n }\n }\n\n /**\n * Send gossip messages to GossipFactor peers above threshold with a minimum of D_lazy\n * Peers are randomly selected from the heartbeat which exclude mesh + fanout peers\n * We also exclude direct peers, as there is no reason to emit gossip to them\n * @param topic\n * @param candidateToGossip - peers to gossip\n * @param messageIDs - message ids to gossip\n */\n private doEmitGossip(topic: string, candidateToGossip: Set, messageIDs: Uint8Array[]): void {\n if (!messageIDs.length) {\n return\n }\n\n // shuffle to emit in random order\n shuffle(messageIDs)\n\n // if we are emitting more than GossipsubMaxIHaveLength ids, truncate the list\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // we do the truncation (with shuffling) per peer below\n this.log('too many messages for gossip; will truncate IHAVE list (%d messages)', messageIDs.length)\n }\n\n if (!candidateToGossip.size) return\n let target = this.opts.Dlazy\n const factor = constants.GossipsubGossipFactor * candidateToGossip.size\n let peersToGossip: Set | PeerIdStr[] = candidateToGossip\n if (factor > target) {\n target = factor\n }\n if (target > peersToGossip.size) {\n target = peersToGossip.size\n } else {\n // only shuffle if needed\n peersToGossip = shuffle(Array.from(peersToGossip)).slice(0, target)\n }\n\n // Emit the IHAVE gossip to the selected peers up to the target\n peersToGossip.forEach((id) => {\n let peerMessageIDs = messageIDs\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // shuffle and slice message IDs per peer so that we emit a different set for each peer\n // we have enough reduncancy in the system that this will significantly increase the message\n // coverage when we do truncate\n peerMessageIDs = shuffle(peerMessageIDs.slice()).slice(0, constants.GossipsubMaxIHaveLength)\n }\n this.pushGossip(id, {\n topicID: topic,\n messageIDs: peerMessageIDs\n })\n })\n }\n\n /**\n * Flush gossip and control messages\n */\n private flush(): void {\n // send gossip first, which will also piggyback control\n for (const [peer, ihave] of this.gossip.entries()) {\n this.gossip.delete(peer)\n this.sendRpc(peer, { control: { ihave } })\n }\n // send the remaining control messages\n for (const [peer, control] of this.control.entries()) {\n this.control.delete(peer)\n this.sendRpc(peer, { control: { graft: control.graft, prune: control.prune } })\n }\n }\n\n /**\n * Adds new IHAVE messages to pending gossip\n */\n private pushGossip(id: PeerIdStr, controlIHaveMsgs: RPC.IControlIHave): void {\n this.log('Add gossip to %s', id)\n const gossip = this.gossip.get(id) || []\n this.gossip.set(id, gossip.concat(controlIHaveMsgs))\n }\n\n /**\n * Make a PRUNE control message for a peer in a topic\n */\n private async makePrune(id: PeerIdStr, topic: string, doPX: boolean): Promise {\n this.score.prune(id, topic)\n if (this.streamsOutbound.get(id)!.protocol === constants.GossipsubIDv10) {\n // Gossipsub v1.0 -- no backoff, the peer won't be able to parse it anyway\n return {\n topicID: topic,\n peers: []\n }\n }\n // backoff is measured in seconds\n // GossipsubPruneBackoff is measured in milliseconds\n // The protobuf has it as a uint64\n const backoff = this.opts.pruneBackoff / 1000\n if (!doPX) {\n return {\n topicID: topic,\n peers: [],\n backoff: backoff\n }\n }\n // select peers for Peer eXchange\n const peers = this.getRandomGossipPeers(topic, this.opts.prunePeers, (xid) => {\n return xid !== id && this.score.score(xid) >= 0\n })\n const px = await Promise.all(\n Array.from(peers).map(async (peerId) => {\n // see if we have a signed record to send back; if we don't, just send\n // the peer ID and let the pruned peer find them in the DHT -- we can't trust\n // unsigned address records through PX anyways\n // Finding signed records in the DHT is not supported at the time of writing in js-libp2p\n const id = peerIdFromString(peerId)\n\n return {\n peerID: id.toBytes(),\n signedPeerRecord: await this.components.peerStore.addressBook.getRawEnvelope(id)\n }\n })\n )\n return {\n topicID: topic,\n peers: px,\n backoff: backoff\n }\n }\n\n private readonly runHeartbeat = () => {\n const timer = this.metrics?.heartbeatDuration.startTimer()\n\n this.heartbeat()\n .catch((err) => {\n this.log('Error running heartbeat', err)\n })\n .finally(() => {\n if (timer != null) {\n timer()\n }\n\n // Schedule the next run if still in started status\n if (this.status.code === GossipStatusCode.started) {\n // Clear previous timeout before overwriting `status.heartbeatTimeout`, it should be completed tho.\n clearTimeout(this.status.heartbeatTimeout)\n\n // NodeJS setInterval function is innexact, calls drift by a few miliseconds on each call.\n // To run the heartbeat precisely setTimeout() must be used recomputing the delay on every loop.\n let msToNextHeartbeat =\n this.opts.heartbeatInterval - ((Date.now() - this.status.hearbeatStartMs) % this.opts.heartbeatInterval)\n\n // If too close to next heartbeat, skip one\n if (msToNextHeartbeat < this.opts.heartbeatInterval * 0.25) {\n msToNextHeartbeat += this.opts.heartbeatInterval\n this.metrics?.heartbeatSkipped.inc()\n }\n\n this.status.heartbeatTimeout = setTimeout(this.runHeartbeat, msToNextHeartbeat)\n }\n })\n }\n\n /**\n * Maintains the mesh and fanout maps in gossipsub.\n */\n public async heartbeat(): Promise {\n const { D, Dlo, Dhi, Dscore, Dout, fanoutTTL } = this.opts\n\n this.heartbeatTicks++\n\n // cache scores throught the heartbeat\n const scores = new Map()\n const getScore = (id: string): number => {\n let s = scores.get(id)\n if (s === undefined) {\n s = this.score.score(id)\n scores.set(id, s)\n }\n return s\n }\n\n // peer id => topic[]\n const tograft = new Map()\n // peer id => topic[]\n const toprune = new Map()\n // peer id => don't px\n const noPX = new Map()\n\n // clean up expired backoffs\n this.clearBackoff()\n\n // clean up peerhave/iasked counters\n this.peerhave.clear()\n this.metrics?.cacheSize.set({ cache: 'iasked' }, this.iasked.size)\n this.iasked.clear()\n\n // apply IWANT request penalties\n this.applyIwantPenalties()\n\n // ensure direct peers are connected\n if (this.heartbeatTicks % this.opts.directConnectTicks === 0) {\n // we only do this every few ticks to allow pending connections to complete and account for restarts/downtime\n await this.directConnect()\n }\n\n // EXTRA: Prune caches\n this.fastMsgIdCache?.prune()\n this.seenCache.prune()\n this.gossipTracer.prune()\n this.publishedMessageIds.prune()\n\n /**\n * Instead of calling getRandomGossipPeers multiple times to:\n * + get more mesh peers\n * + more outbound peers\n * + oppportunistic grafting\n * + emitGossip\n *\n * We want to loop through the topic peers only a single time and prepare gossip peers for all topics to improve the performance\n */\n\n const peersToGossipByTopic = new Map>()\n // maintain the mesh for topics we have joined\n this.mesh.forEach((peers, topic) => {\n const peersInTopic = this.topics.get(topic)\n const candidateMeshPeers = new Set()\n const peersToGossip = new Set()\n peersToGossipByTopic.set(topic, peersToGossip)\n\n if (peersInTopic) {\n const shuffledPeers = shuffle(Array.from(peersInTopic))\n const backoff = this.backoff.get(topic)\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id)\n if (\n peerStreams &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !peers.has(id) &&\n !this.direct.has(id)\n ) {\n const score = getScore(id)\n if ((!backoff || !backoff.has(id)) && score >= 0) candidateMeshPeers.add(id)\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n }\n }\n }\n\n // prune/graft helper functions (defined per topic)\n const prunePeer = (id: PeerIdStr, reason: ChurnReason): void => {\n this.log('HEARTBEAT: Remove mesh link to %s in %s', id, topic)\n // no need to update peer score here as we do it in makePrune\n // add prune backoff record\n this.addBackoff(id, topic)\n // remove peer from mesh\n peers.delete(id)\n // after pruning a peer from mesh, we want to gossip topic to it if its score meet the gossip threshold\n if (getScore(id) >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n this.metrics?.onRemoveFromMesh(topic, reason, 1)\n // add to toprune\n const topics = toprune.get(id)\n if (!topics) {\n toprune.set(id, [topic])\n } else {\n topics.push(topic)\n }\n }\n\n const graftPeer = (id: PeerIdStr, reason: InclusionReason): void => {\n this.log('HEARTBEAT: Add mesh link to %s in %s', id, topic)\n // update peer score\n this.score.graft(id, topic)\n // add peer to mesh\n peers.add(id)\n // when we add a new mesh peer, we don't want to gossip messages to it\n peersToGossip.delete(id)\n this.metrics?.onAddToMesh(topic, reason, 1)\n // add to tograft\n const topics = tograft.get(id)\n if (!topics) {\n tograft.set(id, [topic])\n } else {\n topics.push(topic)\n }\n }\n\n // drop all peers with negative score, without PX\n peers.forEach((id) => {\n const score = getScore(id)\n\n // Record the score\n\n if (score < 0) {\n this.log('HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s', id, score, topic)\n prunePeer(id, ChurnReason.BadScore)\n noPX.set(id, true)\n }\n })\n\n // do we have enough peers?\n if (peers.size < Dlo) {\n const ineed = D - peers.size\n // slice up to first `ineed` items and remove them from candidateMeshPeers\n // same to `const newMeshPeers = candidateMeshPeers.slice(0, ineed)`\n const newMeshPeers = removeFirstNItemsFromSet(candidateMeshPeers, ineed)\n\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.NotEnough)\n })\n }\n\n // do we have to many peers?\n if (peers.size > Dhi) {\n let peersArray = Array.from(peers)\n // sort by score\n peersArray.sort((a, b) => getScore(b) - getScore(a))\n // We keep the first D_score peers by score and the remaining up to D randomly\n // under the constraint that we keep D_out peers in the mesh (if we have that many)\n peersArray = peersArray.slice(0, Dscore).concat(shuffle(peersArray.slice(Dscore)))\n\n // count the outbound peers we are keeping\n let outbound = 0\n peersArray.slice(0, D).forEach((p) => {\n if (this.outbound.get(p)) {\n outbound++\n }\n })\n\n // if it's less than D_out, bubble up some outbound peers from the random selection\n if (outbound < Dout) {\n const rotate = (i: number): void => {\n // rotate the peersArray to the right and put the ith peer in the front\n const p = peersArray[i]\n for (let j = i; j > 0; j--) {\n peersArray[j] = peersArray[j - 1]\n }\n peersArray[0] = p\n }\n\n // first bubble up all outbound peers already in the selection to the front\n if (outbound > 0) {\n let ihave = outbound\n for (let i = 1; i < D && ihave > 0; i++) {\n if (this.outbound.get(peersArray[i])) {\n rotate(i)\n ihave--\n }\n }\n }\n\n // now bubble up enough outbound peers outside the selection to the front\n let ineed = D - outbound\n for (let i = D; i < peersArray.length && ineed > 0; i++) {\n if (this.outbound.get(peersArray[i])) {\n rotate(i)\n ineed--\n }\n }\n }\n\n // prune the excess peers\n peersArray.slice(D).forEach((p) => {\n prunePeer(p, ChurnReason.Excess)\n })\n }\n\n // do we have enough outbound peers?\n if (peers.size >= Dlo) {\n // count the outbound peers we have\n let outbound = 0\n peers.forEach((p) => {\n if (this.outbound.get(p)) {\n outbound++\n }\n })\n\n // if it's less than D_out, select some peers with outbound connections and graft them\n if (outbound < Dout) {\n const ineed = Dout - outbound\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => this.outbound.get(id) === true)\n\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.Outbound)\n })\n }\n }\n\n // should we try to improve the mesh with opportunistic grafting?\n if (this.heartbeatTicks % this.opts.opportunisticGraftTicks === 0 && peers.size > 1) {\n // Opportunistic grafting works as follows: we check the median score of peers in the\n // mesh; if this score is below the opportunisticGraftThreshold, we select a few peers at\n // random with score over the median.\n // The intention is to (slowly) improve an underperforming mesh by introducing good\n // scoring peers that may have been gossiping at us. This allows us to get out of sticky\n // situations where we are stuck with poor peers and also recover from churn of good peers.\n\n // now compute the median peer score in the mesh\n const peersList = Array.from(peers).sort((a, b) => getScore(a) - getScore(b))\n const medianIndex = Math.floor(peers.size / 2)\n const medianScore = getScore(peersList[medianIndex])\n\n // if the median score is below the threshold, select a better peer (if any) and GRAFT\n if (medianScore < this.opts.scoreThresholds.opportunisticGraftThreshold) {\n const ineed = this.opts.opportunisticGraftPeers\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => getScore(id) > medianScore)\n for (const id of newMeshPeers) {\n this.log('HEARTBEAT: Opportunistically graft peer %s on topic %s', id, topic)\n graftPeer(id, InclusionReason.Opportunistic)\n }\n }\n }\n })\n\n // expire fanout for topics we haven't published to in a while\n const now = Date.now()\n this.fanoutLastpub.forEach((lastpb, topic) => {\n if (lastpb + fanoutTTL < now) {\n this.fanout.delete(topic)\n this.fanoutLastpub.delete(topic)\n }\n })\n\n // maintain our fanout for topics we are publishing but we have not joined\n this.fanout.forEach((fanoutPeers, topic) => {\n // checks whether our peers are still in the topic and have a score above the publish threshold\n const topicPeers = this.topics.get(topic)\n fanoutPeers.forEach((id) => {\n if (!topicPeers!.has(id) || getScore(id) < this.opts.scoreThresholds.publishThreshold) {\n fanoutPeers.delete(id)\n }\n })\n\n const peersInTopic = this.topics.get(topic)\n const candidateFanoutPeers = []\n // the fanout map contains topics to which we are not subscribed.\n const peersToGossip = new Set()\n peersToGossipByTopic.set(topic, peersToGossip)\n\n if (peersInTopic) {\n const shuffledPeers = shuffle(Array.from(peersInTopic))\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id)\n if (\n peerStreams &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !fanoutPeers.has(id) &&\n !this.direct.has(id)\n ) {\n const score = getScore(id)\n if (score >= this.opts.scoreThresholds.publishThreshold) candidateFanoutPeers.push(id)\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold) peersToGossip.add(id)\n }\n }\n }\n\n // do we need more peers?\n if (fanoutPeers.size < D) {\n const ineed = D - fanoutPeers.size\n candidateFanoutPeers.slice(0, ineed).forEach((id) => {\n fanoutPeers.add(id)\n peersToGossip?.delete(id)\n })\n }\n })\n\n this.emitGossip(peersToGossipByTopic)\n\n // send coalesced GRAFT/PRUNE messages (will piggyback gossip)\n await this.sendGraftPrune(tograft, toprune, noPX)\n\n // flush pending gossip that wasn't piggybacked above\n this.flush()\n\n // advance the message history window\n this.mcache.shift()\n\n this.dispatchEvent(new CustomEvent('gossipsub:heartbeat'))\n }\n\n /**\n * Given a topic, returns up to count peers subscribed to that topic\n * that pass an optional filter function\n *\n * @param topic\n * @param count\n * @param filter - a function to filter acceptable peers\n */\n private getRandomGossipPeers(\n topic: string,\n count: number,\n filter: (id: string) => boolean = () => true\n ): Set {\n const peersInTopic = this.topics.get(topic)\n\n if (!peersInTopic) {\n return new Set()\n }\n\n // Adds all peers using our protocol\n // that also pass the filter function\n let peers: string[] = []\n peersInTopic.forEach((id) => {\n const peerStreams = this.streamsOutbound.get(id)\n if (!peerStreams) {\n return\n }\n if (this.multicodecs.includes(peerStreams.protocol) && filter(id)) {\n peers.push(id)\n }\n })\n\n // Pseudo-randomly shuffles peers\n peers = shuffle(peers)\n if (count > 0 && peers.length > count) {\n peers = peers.slice(0, count)\n }\n\n return new Set(peers)\n }\n\n private onScrapeMetrics(metrics: Metrics): void {\n /* Data structure sizes */\n metrics.mcacheSize.set(this.mcache.size)\n metrics.mcacheNotValidatedCount.set(this.mcache.notValidatedCount)\n // Arbitrary size\n metrics.cacheSize.set({ cache: 'direct' }, this.direct.size)\n metrics.cacheSize.set({ cache: 'seenCache' }, this.seenCache.size)\n metrics.cacheSize.set({ cache: 'fastMsgIdCache' }, this.fastMsgIdCache?.size ?? 0)\n metrics.cacheSize.set({ cache: 'publishedMessageIds' }, this.publishedMessageIds.size)\n metrics.cacheSize.set({ cache: 'mcache' }, this.mcache.size)\n metrics.cacheSize.set({ cache: 'score' }, this.score.size)\n metrics.cacheSize.set({ cache: 'gossipTracer.promises' }, this.gossipTracer.size)\n metrics.cacheSize.set({ cache: 'gossipTracer.requests' }, this.gossipTracer.requestMsByMsgSize)\n // Bounded by topic\n metrics.cacheSize.set({ cache: 'topics' }, this.topics.size)\n metrics.cacheSize.set({ cache: 'subscriptions' }, this.subscriptions.size)\n metrics.cacheSize.set({ cache: 'mesh' }, this.mesh.size)\n metrics.cacheSize.set({ cache: 'fanout' }, this.fanout.size)\n // Bounded by peer\n metrics.cacheSize.set({ cache: 'peers' }, this.peers.size)\n metrics.cacheSize.set({ cache: 'streamsOutbound' }, this.streamsOutbound.size)\n metrics.cacheSize.set({ cache: 'streamsInbound' }, this.streamsInbound.size)\n metrics.cacheSize.set({ cache: 'acceptFromWhitelist' }, this.acceptFromWhitelist.size)\n metrics.cacheSize.set({ cache: 'gossip' }, this.gossip.size)\n metrics.cacheSize.set({ cache: 'control' }, this.control.size)\n metrics.cacheSize.set({ cache: 'peerhave' }, this.peerhave.size)\n metrics.cacheSize.set({ cache: 'outbound' }, this.outbound.size)\n // 2D nested data structure\n let backoffSize = 0\n for (const backoff of this.backoff.values()) {\n backoffSize += backoff.size\n }\n metrics.cacheSize.set({ cache: 'backoff' }, backoffSize)\n\n // Peer counts\n\n for (const [topicStr, peers] of this.topics) {\n metrics.topicPeersCount.set({ topicStr }, peers.size)\n }\n\n for (const [topicStr, peers] of this.mesh) {\n metrics.meshPeerCounts.set({ topicStr }, peers.size)\n }\n\n // Peer scores\n\n const scores: number[] = []\n const scoreByPeer = new Map()\n metrics.behaviourPenalty.reset()\n\n for (const peerIdStr of this.peers.keys()) {\n const score = this.score.score(peerIdStr)\n scores.push(score)\n scoreByPeer.set(peerIdStr, score)\n metrics.behaviourPenalty.observe(this.score.peerStats.get(peerIdStr)?.behaviourPenalty ?? 0)\n }\n\n metrics.registerScores(scores, this.opts.scoreThresholds)\n\n // Breakdown score per mesh topicLabel\n\n metrics.registerScorePerMesh(this.mesh, scoreByPeer)\n\n // Breakdown on each score weight\n\n const sw = computeAllPeersScoreWeights(\n this.peers.keys(),\n this.score.peerStats,\n this.score.params,\n this.score.peerIPs,\n metrics.topicStrToLabel\n )\n\n metrics.registerScoreWeights(sw)\n }\n}\n\nexport function gossipsub(\n init: Partial = {}\n): (components: GossipSubComponents) => PubSub {\n return (components: GossipSubComponents) => new GossipSub(components, init)\n}\n", "import { gossipsub } from '@chainsafe/libp2p-gossipsub'\n\n/** @typedef {import('@libp2p/interface-pubsub').PubSub} PubSub */\n\n/** @type {() => Record PubSub>}>} */\nexport const routers = () => ({\n gossipsub: gossipsub({\n fallbackToFloodsub: true,\n emitSelf: true,\n maxInboundStreams: 64,\n maxOutboundStreams: 128\n })\n})\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug)\n * module.\n *\n * @example\n *\n * ```JavaScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * log('something happened: %s', 'it was ok')\n * log.error('something bad happened: %o', err)\n *\n * log('with this peer: %p', aPeerId)\n * log('and this base58btc: %b', aUint8Array)\n * log('and this base32: %t', aUint8Array)\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\nimport debug from 'debug'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId } from '@libp2p/interface/peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\nexport interface ComponentLogger {\n forComponent(name: string): Logger\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\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\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\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: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\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 (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\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: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\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\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString(): string\n toCID(): CID\n toBytes(): Uint8Array\n equals(other: PeerId | Uint8Array | string): boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const symbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[symbol])\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```JavaScript\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\nimport { CodeError } from '@libp2p/interface/errors'\nimport { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, symbol, type PeerId } from '@libp2p/interface/peer-id'\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 type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\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\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [symbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id: PeerId | Uint8Array | string): boolean {\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\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\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\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\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\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 } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n", "\nexport interface ClearableSignal extends AbortSignal {\n clear: () => void\n}\n\n/**\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: Array): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n controller.abort()\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { anySignal } from 'any-signal'\nimport { CID } from 'multiformats/cid'\nimport defer from 'p-defer'\nimport PQueue from 'p-queue'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { AbortOptions } from 'ipfs-core-types/src/utils'\n\nconst log = logger('libp2p:delegated-peer-routing')\n\nconst DEFAULT_TIMEOUT = 30e3 // 30 second default\nconst CONCURRENT_HTTP_REQUESTS = 4\n\nexport interface HTTPClientExtraOptions {\n headers?: Record\n searchParams?: URLSearchParams\n}\n\nexport enum EventTypes {\n SENDING_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADDING_PEER,\n DIALING_PEER\n}\n\n/**\n * The types of messages set/received during DHT queries\n */\nexport enum MessageType {\n PUT_VALUE = 0,\n GET_VALUE,\n ADD_PROVIDER,\n GET_PROVIDERS,\n FIND_NODE,\n PING\n}\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport interface SendingQueryEvent {\n type: EventTypes.SENDING_QUERY\n name: 'SENDING_QUERY'\n}\n\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageType: MessageType\n messageName: MessageName\n providers: PeerInfo[]\n closer: PeerInfo[]\n record?: DHTRecord\n}\n\nexport interface FinalPeerEvent {\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n}\n\nexport interface QueryErrorEvent {\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n}\n\nexport interface ProviderEvent {\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n}\n\nexport interface ValueEvent {\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n}\n\nexport interface AddingPeerEvent {\n type: EventTypes.ADDING_PEER\n name: 'ADDING_PEER'\n peer: PeerId\n}\n\nexport interface DialingPeerEvent {\n peer: PeerId\n type: EventTypes.DIALING_PEER\n name: 'DIALING_PEER'\n}\n\nexport type QueryEvent = SendingQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddingPeerEvent | DialingPeerEvent\n\nexport interface Delegate {\n getEndpointConfig(): { protocol: string, host: string, port: string }\n\n dht: {\n findPeer(peerId: PeerId, options?: AbortOptions): AsyncIterable\n query(peerId: PeerId | CID, options?: AbortOptions): AsyncIterable\n }\n}\n\nclass DelegatedPeerRouting implements PeerRouting, Startable {\n private readonly client: Delegate\n private readonly httpQueue: PQueue\n private started: boolean\n private abortController: AbortController\n\n /**\n * Create a new DelegatedPeerRouting instance\n */\n constructor (client: Delegate) {\n if (client == null) {\n throw new Error('missing ipfs http client')\n }\n\n this.client = client\n this.started = false\n this.abortController = new AbortController()\n\n // limit concurrency to avoid request flood in web browser\n // https://github.com/libp2p/js-libp2p-delegated-content-routing/issues/12\n this.httpQueue = new PQueue({\n concurrency: CONCURRENT_HTTP_REQUESTS\n })\n\n const {\n protocol,\n host,\n port\n } = client.getEndpointConfig()\n\n log(`enabled DelegatedPeerRouting via ${protocol}://${host}:${port}`)\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n stop (): void {\n this.httpQueue.clear()\n this.abortController.abort()\n this.abortController = new AbortController()\n this.started = false\n }\n\n /**\n * Attempts to find the given peer\n */\n async findPeer (id: PeerId, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('findPeer starts: %p', id)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.findPeer(id, {\n ...options,\n signal\n })) {\n if (event.name === 'FINAL_PEER' && event.peer.multiaddrs.length > 0) {\n const peerInfo: PeerInfo = {\n id: event.peer.id,\n multiaddrs: event.peer.multiaddrs,\n protocols: []\n }\n\n return peerInfo\n }\n }\n\n throw new CodeError('Not found', 'ERR_NOT_FOUND')\n } catch (err: any) {\n log.error('findPeer errored: %o', err)\n\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('findPeer finished: %p', id)\n }\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options: HTTPClientExtraOptions & AbortOptions = {}): AsyncGenerator {\n let cidOrPeerId: CID | PeerId\n const cid = CID.asCID(key)\n\n if (cid != null) {\n cidOrPeerId = cid\n } else {\n cidOrPeerId = peerIdFromBytes(key)\n }\n\n log('getClosestPeers starts: %s', cidOrPeerId)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.query(cidOrPeerId, {\n ...options,\n signal\n })) {\n if (event.name === 'PEER_RESPONSE') {\n yield * event.closer.map(closer => ({\n id: closer.id,\n multiaddrs: closer.multiaddrs,\n protocols: []\n }))\n }\n }\n } catch (err) {\n log.error('getClosestPeers errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('getClosestPeers finished: %b', key)\n }\n }\n}\n\nexport function delegatedPeerRouting (client: Delegate): (components?: any) => PeerRouting {\n return () => new DelegatedPeerRouting(client)\n}\n", "import { logger } from '@libp2p/logger'\nimport { anySignal } from 'any-signal'\nimport errCode from 'err-code'\nimport drain from 'it-drain'\nimport defer from 'p-defer'\nimport PQueue from 'p-queue'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { AbortOptions } from 'ipfs-core-types/src/utils'\nimport type { CID } from 'multiformats/cid'\n\nconst log = logger('libp2p:delegated-content-routing')\n\nconst DEFAULT_TIMEOUT = 30e3 // 30 second default\nconst CONCURRENT_HTTP_REQUESTS = 4\nconst CONCURRENT_HTTP_REFS_REQUESTS = 2\n\nexport interface HTTPClientExtraOptions {\n headers?: Record\n searchParams?: URLSearchParams\n}\n\nexport enum EventTypes {\n SENDING_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADDING_PEER,\n DIALING_PEER\n}\n\n/**\n * The types of messages set/received during DHT queries\n */\nexport enum MessageType {\n PUT_VALUE = 0,\n GET_VALUE,\n ADD_PROVIDER,\n GET_PROVIDERS,\n FIND_NODE,\n PING\n}\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport interface SendingQueryEvent {\n type: EventTypes.SENDING_QUERY\n name: 'SENDING_QUERY'\n}\n\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageType: MessageType\n messageName: MessageName\n providers: PeerInfo[]\n closer: PeerInfo[]\n record?: DHTRecord\n}\n\nexport interface FinalPeerEvent {\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n}\n\nexport interface QueryErrorEvent {\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n}\n\nexport interface ProviderEvent {\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n}\n\nexport interface ValueEvent {\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n}\n\nexport interface AddingPeerEvent {\n type: EventTypes.ADDING_PEER\n name: 'ADDING_PEER'\n peer: PeerId\n}\n\nexport interface DialingPeerEvent {\n peer: PeerId\n type: EventTypes.DIALING_PEER\n name: 'DIALING_PEER'\n}\n\nexport type QueryEvent = SendingQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddingPeerEvent | DialingPeerEvent\n\nexport interface DHTProvideOptions extends AbortOptions {\n recursive?: boolean\n}\n\nexport interface StatResult {\n cid: CID\n size: number\n}\n\nexport interface Delegate {\n getEndpointConfig(): { protocol: string, host: string, port: string }\n\n block: {\n stat(cid: CID, options?: AbortOptions): Promise\n }\n\n dht: {\n findProvs(cid: CID, options?: HTTPClientExtraOptions & AbortOptions): AsyncIterable\n provide(cid: CID, options?: HTTPClientExtraOptions & DHTProvideOptions): AsyncIterable\n put(key: string | Uint8Array, value: Uint8Array, options?: HTTPClientExtraOptions & AbortOptions): AsyncIterable\n get(key: string | Uint8Array, options?: HTTPClientExtraOptions & AbortOptions): AsyncIterable\n }\n}\n\n/**\n * An implementation of content routing, using a delegated peer\n */\nclass DelegatedContentRouting implements ContentRouting, Startable {\n private readonly client: Delegate\n private readonly httpQueue: PQueue\n private readonly httpQueueRefs: PQueue\n private started: boolean\n private abortController: AbortController\n\n /**\n * Create a new DelegatedContentRouting instance\n */\n constructor (client: Delegate) {\n if (client == null) {\n throw new Error('missing ipfs http client')\n }\n\n this.client = client\n this.started = false\n this.abortController = new AbortController()\n\n // limit concurrency to avoid request flood in web browser\n // https://github.com/libp2p/js-libp2p-delegated-content-routing/issues/12\n this.httpQueue = new PQueue({\n concurrency: CONCURRENT_HTTP_REQUESTS\n })\n // sometimes refs requests take long time, they need separate queue\n // to not suffocate regular business\n this.httpQueueRefs = new PQueue({\n concurrency: CONCURRENT_HTTP_REFS_REQUESTS\n })\n\n const {\n protocol,\n host,\n port\n } = client.getEndpointConfig()\n\n log(`enabled DelegatedContentRouting via ${protocol}://${host}:${port}`)\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n stop (): void {\n this.httpQueue.clear()\n this.httpQueueRefs.clear()\n this.abortController.abort()\n this.abortController = new AbortController()\n this.started = false\n }\n\n /**\n * Search the dht for providers of the given CID.\n *\n * - call `findProviders` on the delegated node.\n */\n async * findProviders (key: CID, options: HTTPClientExtraOptions & AbortOptions = {}): AsyncIterable {\n log('findProviders starts: %c', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.findProvs(key, {\n ...options,\n signal\n })) {\n if (event.name === 'PROVIDER') {\n yield * event.providers.map(prov => {\n const peerInfo: PeerInfo = {\n id: prov.id,\n protocols: [],\n multiaddrs: prov.multiaddrs\n }\n\n return peerInfo\n })\n }\n }\n } catch (err) {\n log.error('findProviders errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('findProviders finished: %c', key)\n }\n }\n\n /**\n * Announce to the network that the delegated node can provide the given key.\n *\n * Currently this uses the following hack\n * - delegate is one of bootstrap nodes, so we are always connected to it\n * - call block stat on the delegated node, so it fetches the content\n * - call dht provide with the passed cid\n *\n * N.B. this must be called for every block in the dag you want provided otherwise\n * the delegate will only be able to supply the root block of the dag when asked\n * for the data by an interested peer.\n */\n async provide (key: CID, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('provide starts: %c', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n await this.client.block.stat(key, {\n ...options,\n signal\n })\n await drain(this.client.dht.provide(key, {\n ...options,\n signal\n }))\n } catch (err) {\n log.error('provide errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('provide finished: %c', key)\n }\n }\n\n /**\n * Stores a value in the backing key/value store of the delegated content router.\n * This may fail if the delegated node's content routing implementation does not\n * use a key/value store, or if the delegated operation fails.\n */\n async put (key: Uint8Array, value: Uint8Array, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('put value start: %b', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n await drain(this.client.dht.put(key, value, {\n ...options,\n signal\n }))\n } catch (err) {\n log.error('put errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('put finished: %b', key)\n }\n }\n\n /**\n * Fetches an value from the backing key/value store of the delegated content router.\n * This may fail if the delegated node's content routing implementation does not\n * use a key/value store, or if the delegated operation fails.\n */\n async get (key: Uint8Array, options: HTTPClientExtraOptions & AbortOptions = {}): Promise {\n log('get value start: %b', key)\n options.timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n const signal = anySignal([this.abortController.signal, options.signal])\n const onStart = defer()\n const onFinish = defer()\n\n void this.httpQueue.add(async () => {\n onStart.resolve()\n return onFinish.promise\n })\n\n try {\n await onStart.promise\n\n for await (const event of this.client.dht.get(key, {\n ...options,\n signal\n })) {\n if (event.name === 'VALUE') {\n log('get value finished: %b', key)\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n } catch (err) {\n log.error('put errored:', err)\n throw err\n } finally {\n signal.clear()\n onFinish.resolve()\n log('put finished: %b', key)\n }\n }\n}\n\nexport function delegatedContentRouting (client: Delegate): (components?: any) => ContentRouting {\n return () => new DelegatedContentRouting(client)\n}\n", "/**\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 */\n\nfunction isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nfunction drain (source: Iterable): void\nfunction drain (source: Iterable | AsyncIterable): Promise\nfunction drain (source: Iterable | AsyncIterable): Promise | void {\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 } else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\n\nexport default drain\n", "/**\n * @typedef {import('multiformats/bases/interface').MultibaseCodec} MultibaseCodec\n * @typedef {import('./types').LoadBaseFn} LoadBaseFn\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @type {LoadBaseFn}\n */\nconst LOAD_BASE = (name) => Promise.reject(new Error(`No base found for \"${name}\"`))\n\nexport class Multibases {\n /**\n * @param {object} options\n * @param {LoadBaseFn} [options.loadBase]\n * @param {MultibaseCodec[]} options.bases\n */\n constructor (options) {\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._basesByName = {}\n\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._basesByPrefix = {}\n\n this._loadBase = options.loadBase || LOAD_BASE\n\n // Enable all supplied codecs\n for (const base of options.bases) {\n this.addBase(base)\n }\n }\n\n /**\n * Add support for a multibase codec\n *\n * @param {MultibaseCodec} base\n */\n addBase (base) {\n if (this._basesByName[base.name] || this._basesByPrefix[base.prefix]) {\n throw new Error(`Codec already exists for codec \"${base.name}\"`)\n }\n\n this._basesByName[base.name] = base\n this._basesByPrefix[base.prefix] = base\n }\n\n /**\n * Remove support for a multibase codec\n *\n * @param {MultibaseCodec} base\n */\n removeBase (base) {\n delete this._basesByName[base.name]\n delete this._basesByPrefix[base.prefix]\n }\n\n /**\n * @param {string} nameOrPrefix\n */\n async getBase (nameOrPrefix) {\n if (this._basesByName[nameOrPrefix]) {\n return this._basesByName[nameOrPrefix]\n }\n\n if (this._basesByPrefix[nameOrPrefix]) {\n return this._basesByPrefix[nameOrPrefix]\n }\n\n // If not supported, attempt to dynamically load this codec\n const base = await this._loadBase(nameOrPrefix)\n\n if (this._basesByName[base.name] == null && this._basesByPrefix[base.prefix] == null) {\n this.addBase(base)\n }\n\n return base\n }\n\n listBases () {\n return Object.values(this._basesByName)\n }\n}\n", "/**\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('./types').LoadCodecFn} LoadCodecFn\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @type {LoadCodecFn}\n */\nconst LOAD_CODEC = (codeOrName) => Promise.reject(new Error(`No codec found for \"${codeOrName}\"`))\n\nexport class Multicodecs {\n /**\n * @param {object} options\n * @param {LoadCodecFn} [options.loadCodec]\n * @param {BlockCodec[]} options.codecs\n */\n constructor (options) {\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._codecsByName = {}\n\n // Object with current list of active resolvers\n /** @type {Record}} */\n this._codecsByCode = {}\n\n this._loadCodec = options.loadCodec || LOAD_CODEC\n\n // Enable all supplied codecs\n for (const codec of options.codecs) {\n this.addCodec(codec)\n }\n }\n\n /**\n * Add support for a block codec\n *\n * @param {BlockCodec} codec\n */\n addCodec (codec) {\n if (this._codecsByName[codec.name] || this._codecsByCode[codec.code]) {\n throw new Error(`Resolver already exists for codec \"${codec.name}\"`)\n }\n\n this._codecsByName[codec.name] = codec\n this._codecsByCode[codec.code] = codec\n }\n\n /**\n * Remove support for a block codec\n *\n * @param {BlockCodec} codec\n */\n removeCodec (codec) {\n delete this._codecsByName[codec.name]\n delete this._codecsByCode[codec.code]\n }\n\n /**\n * @param {number | string} code\n */\n async getCodec (code) {\n const table = typeof code === 'string' ? this._codecsByName : this._codecsByCode\n\n if (table[code]) {\n return table[code]\n }\n\n // If not supported, attempt to dynamically load this codec\n const codec = await this._loadCodec(code)\n\n if (table[code] == null) {\n this.addCodec(codec)\n }\n\n return codec\n }\n\n listCodecs () {\n return Object.values(this._codecsByName)\n }\n}\n", "/**\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('./types').LoadHasherFn} LoadHasherFn\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * @type {LoadHasherFn}\n */\nconst LOAD_HASHER = (codeOrName) => Promise.reject(new Error(`No hasher found for \"${codeOrName}\"`))\n\nexport class Multihashes {\n /**\n * @param {object} options\n * @param {LoadHasherFn} [options.loadHasher]\n * @param {MultihashHasher[]} options.hashers\n */\n constructor (options) {\n // Object with current list of active hashers\n /** @type {Record}} */\n this._hashersByName = {}\n\n // Object with current list of active hashers\n /** @type {Record}} */\n this._hashersByCode = {}\n\n this._loadHasher = options.loadHasher || LOAD_HASHER\n\n // Enable all supplied hashers\n for (const hasher of options.hashers) {\n this.addHasher(hasher)\n }\n }\n\n /**\n * Add support for a multibase hasher\n *\n * @param {MultihashHasher} hasher\n */\n addHasher (hasher) {\n if (this._hashersByName[hasher.name] || this._hashersByCode[hasher.code]) {\n throw new Error(`Resolver already exists for codec \"${hasher.name}\"`)\n }\n\n this._hashersByName[hasher.name] = hasher\n this._hashersByCode[hasher.code] = hasher\n }\n\n /**\n * Remove support for a multibase hasher\n *\n * @param {MultihashHasher} hasher\n */\n removeHasher (hasher) {\n delete this._hashersByName[hasher.name]\n delete this._hashersByCode[hasher.code]\n }\n\n /**\n * @param {number | string} code\n */\n async getHasher (code) {\n const table = typeof code === 'string' ? this._hashersByName : this._hashersByCode\n\n if (table[code]) {\n return table[code]\n }\n\n // If not supported, attempt to dynamically load this hasher\n const hasher = await this._loadHasher(code)\n\n if (table[code] == null) {\n this.addHasher(hasher)\n }\n\n return hasher\n }\n\n listHashers () {\n return Object.values(this._hashersByName)\n }\n}\n", "\n/* eslint-env browser */\n\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport { isBrowser, isWebWorker, isNode } from 'ipfs-utils/src/env.js'\nimport parseDuration from 'parse-duration'\nimport { logger } from '@libp2p/logger'\nimport HTTP from 'ipfs-utils/src/http.js'\nimport mergeOpts from 'merge-options'\nimport { toUrlString } from 'ipfs-core-utils/to-url-string'\nimport getAgent from 'ipfs-core-utils/agent'\n\nconst log = logger('ipfs-http-client:lib:error-handler')\nconst merge = mergeOpts.bind({ ignoreUndefined: true })\n\nconst DEFAULT_PROTOCOL = isBrowser || isWebWorker ? location.protocol : 'http'\nconst DEFAULT_HOST = isBrowser || isWebWorker ? location.hostname : 'localhost'\nconst DEFAULT_PORT = isBrowser || isWebWorker ? location.port : '5001'\n\n/**\n * @typedef {import('ipfs-utils/src/types').HTTPOptions} HTTPOptions\n * @typedef {import('../types').Options} Options\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {Options|URL|Multiaddr|string} [options]\n * @returns {Options}\n */\nconst normalizeOptions = (options = {}) => {\n let url\n /** @type {Options} */\n let opts = {}\n let agent\n\n if (typeof options === 'string' || isMultiaddr(options)) {\n url = new URL(toUrlString(options))\n } else if (options instanceof URL) {\n url = options\n } else if (typeof options.url === 'string' || isMultiaddr(options.url)) {\n url = new URL(toUrlString(options.url))\n opts = options\n } else if (options.url instanceof URL) {\n url = options.url\n opts = options\n } else {\n opts = options || {}\n\n const protocol = (opts.protocol || DEFAULT_PROTOCOL).replace(':', '')\n const host = (opts.host || DEFAULT_HOST).split(':')[0]\n const port = (opts.port || DEFAULT_PORT)\n\n url = new URL(`${protocol}://${host}:${port}`)\n }\n\n if (opts.apiPath) {\n url.pathname = opts.apiPath\n } else if (url.pathname === '/' || url.pathname === undefined) {\n url.pathname = 'api/v0'\n }\n\n if (isNode) {\n const Agent = getAgent(url)\n\n agent = opts.agent || new Agent({\n keepAlive: true,\n // Similar to browsers which limit connections to six per host\n maxSockets: 6\n })\n }\n\n return {\n ...opts,\n host: url.host,\n protocol: url.protocol.replace(':', ''),\n port: Number(url.port),\n apiPath: url.pathname,\n url,\n agent\n }\n}\n\n/**\n * @param {Response} response\n */\nexport const errorHandler = async (response) => {\n let msg\n\n try {\n if ((response.headers.get('Content-Type') || '').startsWith('application/json')) {\n const data = await response.json()\n log(data)\n msg = data.Message || data.message\n } else {\n msg = await response.text()\n }\n } catch (/** @type {any} */ err) {\n log('Failed to parse error response', err)\n // Failed to extract/parse error message from response\n msg = err.message\n }\n\n /** @type {Error} */\n let error = new HTTP.HTTPError(response)\n\n if (msg) {\n // This is what rs-ipfs returns where there's a timeout\n if (msg.includes('deadline has elapsed')) {\n error = new HTTP.TimeoutError()\n }\n\n // This is what go-ipfs returns where there's a timeout\n if (msg && msg.includes('context deadline exceeded')) {\n error = new HTTP.TimeoutError()\n }\n }\n\n // This also gets returned\n if (msg && msg.includes('request timed out')) {\n error = new HTTP.TimeoutError()\n }\n\n // If we managed to extract a message from the response, use it\n if (msg) {\n error.message = msg\n }\n\n throw error\n}\n\nconst KEBAB_REGEX = /[A-Z\\u00C0-\\u00D6\\u00D8-\\u00DE]/g\n\n/**\n * @param {string} str\n */\nconst kebabCase = (str) => {\n return str.replace(KEBAB_REGEX, function (match) {\n return '-' + match.toLowerCase()\n })\n}\n\n/**\n * @param {string | number} value\n */\nconst parseTimeout = (value) => {\n return typeof value === 'string' ? parseDuration(value) : value\n}\n\nexport class Client extends HTTP {\n /**\n * @param {Options|URL|Multiaddr|string} [options]\n */\n constructor (options = {}) {\n const opts = normalizeOptions(options)\n\n super({\n timeout: parseTimeout(opts.timeout || 0) || undefined,\n headers: opts.headers,\n base: `${opts.url}`,\n handleError: errorHandler,\n transformSearchParams: (search) => {\n const out = new URLSearchParams()\n\n for (const [key, value] of search) {\n if (\n value !== 'undefined' &&\n value !== 'null' &&\n key !== 'signal'\n ) {\n out.append(kebabCase(key), value)\n }\n\n // @ts-expect-error server timeouts are strings\n if (key === 'timeout' && !isNaN(value)) {\n out.append(kebabCase(key), value)\n }\n }\n\n return out\n },\n // @ts-expect-error this can be a https agent or a http agent\n agent: opts.agent\n })\n\n // @ts-expect-error - cannot delete no-optional fields\n delete this.get\n // @ts-expect-error - cannot delete no-optional fields\n delete this.put\n // @ts-expect-error - cannot delete no-optional fields\n delete this.delete\n // @ts-expect-error - cannot delete no-optional fields\n delete this.options\n\n const fetch = this.fetch\n\n /**\n * @param {string | Request} resource\n * @param {HTTPOptions} options\n */\n this.fetch = (resource, options = {}) => {\n if (typeof resource === 'string' && !resource.startsWith('/')) {\n resource = `${opts.url}/${resource}`\n }\n\n return fetch.call(this, resource, merge(options, {\n method: 'POST'\n }))\n }\n }\n}\n\nexport const HTTPError = HTTP.HTTPError\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n\n/**\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {string|Multiaddr|URL} url - A string, multiaddr or URL to convert to a url string\n * @returns {string}\n */\nexport function toUrlString (url) {\n try {\n // @ts-expect-error\n url = multiaddrToUri(multiaddr(url))\n } catch (/** @type {any} */ err) { }\n\n url = url.toString()\n\n return url\n}\n", "\nexport default () => {}\n", "\n/* eslint-env browser */\n\nimport { Client } from './core.js'\n\n// Set default configuration and call create function with them\n/**\n * @typedef { import(\"../types\").Options } Options\n */\n\n/**\n * @template T\n * @typedef {(client: Client, clientOptions: Options) => T} Fn\n */\n\n/**\n * @template T\n * @typedef {(clientOptions: Options) => T} Factory\n */\n\n/**\n * @template T\n * @param {Fn} fn\n * @returns {Factory}\n */\nexport const configure = (fn) => {\n return (options) => {\n return fn(new Client(options), options)\n }\n}\n", "\n/**\n * @param {number | string | undefined} mode\n */\nexport function modeToString (mode) {\n if (mode == null) {\n return undefined\n }\n\n if (typeof mode === 'string') {\n return mode\n }\n\n return mode.toString(8).padStart(4, '0')\n}\n", "import errCode from 'err-code'\n\n/**\n * @param {any} input\n */\nexport function parseMtime (input) {\n if (input == null) {\n return undefined\n }\n\n /** @type {{ secs: number, nsecs?: number } | undefined} */\n let mtime\n\n // { secs, nsecs }\n if (input.secs != null) {\n mtime = {\n secs: input.secs,\n nsecs: input.nsecs\n }\n }\n\n // UnixFS TimeSpec\n if (input.Seconds != null) {\n mtime = {\n secs: input.Seconds,\n nsecs: input.FractionalNanoseconds\n }\n }\n\n // process.hrtime()\n if (Array.isArray(input)) {\n mtime = {\n secs: input[0],\n nsecs: input[1]\n }\n }\n\n // Javascript Date\n if (input instanceof Date) {\n const ms = input.getTime()\n const secs = Math.floor(ms / 1000)\n\n mtime = {\n secs: secs,\n nsecs: (ms - (secs * 1000)) * 1000\n }\n }\n\n /*\n TODO: https://github.com/ipfs/aegir/issues/487\n\n // process.hrtime.bigint()\n if (input instanceof BigInt) {\n const secs = input / BigInt(1e9)\n const nsecs = input - (secs * BigInt(1e9))\n\n mtime = {\n secs: parseInt(secs.toString()),\n nsecs: parseInt(nsecs.toString())\n }\n }\n */\n\n if (!Object.prototype.hasOwnProperty.call(mtime, 'secs')) {\n return undefined\n }\n\n if (mtime != null && mtime.nsecs != null && (mtime.nsecs < 0 || mtime.nsecs > 999999999)) {\n throw errCode(new Error('mtime-nsecs must be within the range [0,999999999]'), 'ERR_INVALID_MTIME_NSECS')\n }\n\n return mtime\n}\n", "import { modeToString } from './mode-to-string.js'\nimport { parseMtime } from '../lib/parse-mtime.js'\n\n/**\n * @param {*} params\n * @returns {URLSearchParams}\n */\nexport function toUrlSearchParams ({ arg, searchParams, hashAlg, mtime, mode, ...options } = {}) {\n if (searchParams) {\n options = {\n ...options,\n ...searchParams\n }\n }\n\n if (hashAlg) {\n options.hash = hashAlg\n }\n\n if (mtime != null) {\n mtime = parseMtime(mtime)\n\n options.mtime = mtime.secs\n options.mtimeNsecs = mtime.nsecs\n }\n\n if (mode != null) {\n options.mode = modeToString(mode)\n }\n\n if (options.timeout && !isNaN(options.timeout)) {\n // server API expects timeouts as strings\n options.timeout = `${options.timeout}ms`\n }\n\n if (arg === undefined || arg === null) {\n arg = []\n } else if (!Array.isArray(arg)) {\n arg = [arg]\n }\n\n const urlSearchParams = new URLSearchParams(options)\n\n arg.forEach((/** @type {any} */ arg) => urlSearchParams.append('arg', arg))\n\n return urlSearchParams\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createWantlist = configure(api => {\n /**\n * @type {BitswapAPI[\"wantlist\"]}\n */\n async function wantlist (options = {}) {\n const res = await (await api.post('bitswap/wantlist', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })).json()\n\n return (res.Keys || []).map((/** @type {{ '/': string }} */ k) => CID.parse(k['/']))\n }\n return wantlist\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createWantlistForPeer = configure(api => {\n /**\n * @type {BitswapAPI[\"wantlistForPeer\"]}\n */\n async function wantlistForPeer (peerId, options = {}) {\n const res = await (await api.post('bitswap/wantlist', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n peer: peerId.toString()\n }),\n headers: options.headers\n })).json()\n\n return (res.Keys || []).map((/** @type {{ '/': string }} */ k) => CID.parse(k['/']))\n }\n return wantlistForPeer\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {BitswapAPI[\"stat\"]}\n */\n async function stat (options = {}) {\n const res = await api.post('bitswap/stat', {\n searchParams: toUrlSearchParams(options),\n signal: options.signal,\n headers: options.headers\n })\n\n return toCoreInterface(await res.json())\n }\n return stat\n})\n\n/**\n * @param {any} res\n */\nfunction toCoreInterface (res) {\n return {\n provideBufLen: res.ProvideBufLen,\n wantlist: (res.Wantlist || []).map((/** @type {{ '/': string }} */ k) => CID.parse(k['/'])),\n peers: (res.Peers || []).map((/** @type {string} */ str) => peerIdFromString(str)),\n blocksReceived: BigInt(res.BlocksReceived),\n dataReceived: BigInt(res.DataReceived),\n blocksSent: BigInt(res.BlocksSent),\n dataSent: BigInt(res.DataSent),\n dupBlksReceived: BigInt(res.DupBlksReceived),\n dupDataReceived: BigInt(res.DupDataReceived)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bitswap').API} BitswapAPI\n */\n\nexport const createUnwant = configure(api => {\n /**\n * @type {BitswapAPI[\"unwant\"]}\n */\n async function unwant (cid, options = {}) {\n const res = await api.post('bitswap/unwant', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n return res.json()\n }\n return unwant\n})\n", "import { createWantlist } from './wantlist.js'\nimport { createWantlistForPeer } from './wantlist-for-peer.js'\nimport { createStat } from './stat.js'\nimport { createUnwant } from './unwant.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createBitswap (config) {\n return {\n wantlist: createWantlist(config),\n wantlistForPeer: createWantlistForPeer(config),\n unwant: createUnwant(config),\n stat: createStat(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {BlockAPI[\"get\"]}\n */\n async function get (cid, options = {}) {\n const res = await api.post('block/get', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n return new Uint8Array(await res.arrayBuffer())\n }\n return get\n})\n", "import errCode from 'err-code'\nimport itPeekable from 'it-peekable'\nimport browserStreamToIt from 'browser-readablestream-to-it'\nimport all from 'it-all'\nimport {\n isBytes,\n isBlob,\n isReadableStream\n} from './utils.js'\n\n/**\n * @param {import('ipfs-core-types/src/utils').ToContent} input\n */\nexport async function normaliseContent (input) {\n // Bytes\n if (isBytes(input)) {\n return new Blob([input])\n }\n\n // String\n if (typeof input === 'string' || input instanceof String) {\n return new Blob([input.toString()])\n }\n\n // Blob | File\n if (isBlob(input)) {\n return input\n }\n\n // Browser stream\n if (isReadableStream(input)) {\n input = browserStreamToIt(input)\n }\n\n // (Async)Iterator\n if (Symbol.iterator in input || Symbol.asyncIterator in input) {\n /** @type {any} peekable */\n const peekable = itPeekable(input)\n\n /** @type {any} value **/\n const { value, done } = await peekable.peek()\n\n if (done) {\n // make sure empty iterators result in empty files\n return itToBlob(peekable)\n }\n\n peekable.push(value)\n\n // (Async)Iterable\n if (Number.isInteger(value)) {\n return new Blob([Uint8Array.from(await all(peekable))])\n }\n\n // (Async)Iterable\n if (isBytes(value) || typeof value === 'string' || value instanceof String) {\n return itToBlob(peekable)\n }\n }\n\n throw errCode(new Error(`Unexpected input: ${input}`), 'ERR_UNEXPECTED_INPUT')\n}\n\n/**\n * @param {AsyncIterable|Iterable} stream\n */\nasync function itToBlob (stream) {\n const parts = []\n\n for await (const chunk of stream) {\n parts.push(chunk)\n }\n\n return new Blob(parts)\n}\n", "import { normaliseContent } from './normalise-content.browser.js'\nimport { normaliseCandidateMultiple } from './normalise-candidate-multiple.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n * @typedef {import('ipfs-core-types/src/utils').BrowserImportCandidate} BrowserImportCandidate\n */\n\n/**\n * Transforms any of the `ipfs.addAll` input types into\n *\n * ```\n * AsyncIterable<{ path, mode, mtime, content: Blob }>\n * ```\n *\n * See https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options\n *\n * @param {ImportCandidateStream} input\n * @returns {AsyncGenerator}\n */\nexport function normaliseInput (input) {\n // @ts-expect-error browser normaliseContent returns a Blob not an AsyncIterable\n return normaliseCandidateMultiple(input, normaliseContent, true)\n}\n", "\n/**\n * @param {number | string | undefined} mode\n */\nexport function modeToString (mode) {\n if (mode == null) {\n return undefined\n }\n\n if (typeof mode === 'string') {\n return mode\n }\n\n return mode.toString(8).padStart(4, '0')\n}\n", "\n// Import browser version otherwise electron-renderer will end up with node\n// version and fail.\nimport { normaliseInput } from './files/normalise-input-multiple.browser.js'\nimport { modeToString } from './mode-to-string.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream\n */\n\n/**\n * @param {ImportCandidateStream} source\n * @param {AbortController} abortController\n * @param {Headers|Record} [headers]\n */\nexport async function multipartRequest (source, abortController, headers = {}) {\n const parts = []\n const formData = new FormData()\n let index = 0\n let total = 0\n\n for await (const { content, path, mode, mtime } of normaliseInput(source)) {\n let fileSuffix = ''\n const type = content ? 'file' : 'dir'\n\n if (index > 0) {\n fileSuffix = `-${index}`\n }\n\n let fieldName = type + fileSuffix\n const qs = []\n\n if (mode !== null && mode !== undefined) {\n qs.push(`mode=${modeToString(mode)}`)\n }\n\n if ((mtime) != null) {\n const { secs, nsecs } = (mtime)\n\n qs.push(`mtime=${secs}`)\n\n if (nsecs != null) {\n qs.push(`mtime-nsecs=${nsecs}`)\n }\n }\n\n if (qs.length) {\n fieldName = `${fieldName}?${qs.join('&')}`\n }\n\n if (content) {\n formData.set(fieldName, content, path != null ? encodeURIComponent(path) : undefined)\n const end = total + content.size\n parts.push({ name: path, start: total, end })\n total = end\n } else if (path != null) {\n formData.set(fieldName, new File([''], encodeURIComponent(path), { type: 'application/x-directory' }))\n } else {\n throw new Error('path or content or both must be set')\n }\n\n index++\n }\n\n return {\n total,\n parts,\n headers,\n body: formData\n }\n}\n", "import { anySignal } from 'any-signal'\n\n/**\n * @param {any[]} signals\n * @returns {AbortSignal[]}\n */\nfunction filter (signals) {\n return signals.filter(Boolean)\n}\n\n/**\n * @param {...AbortSignal|undefined} signals\n */\nexport function abortSignal (...signals) {\n return anySignal(filter(signals))\n}\n", "import { CID } from 'multiformats/cid'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n */\n\nexport const createPut = configure(api => {\n /**\n * @type {BlockAPI[\"put\"]}\n */\n async function put (data, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n let res\n try {\n const response = await api.post('block/put', {\n signal: signal,\n searchParams: toUrlSearchParams(options),\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n res = await response.json()\n } catch (/** @type {any} */ err) {\n // Retry with \"protobuf\"/\"cbor\" format for go-ipfs\n // TODO: remove when https://github.com/ipfs/go-cid/issues/75 resolved\n if (options.format === 'dag-pb') {\n return put(data, { ...options, format: 'protobuf' })\n } else if (options.format === 'dag-cbor') {\n return put(data, { ...options, format: 'cbor' })\n }\n\n throw err\n }\n\n return CID.parse(res.Key)\n }\n\n return put\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n * @typedef {import('ipfs-core-types/src/block').RmResult} RmResult\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {BlockAPI[\"rm\"]}\n */\n async function * rm (cid, options = {}) {\n if (!Array.isArray(cid)) {\n cid = [cid]\n }\n\n const res = await api.post('block/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.map(cid => cid.toString()),\n 'stream-channels': true,\n ...options\n }),\n headers: options.headers\n })\n\n for await (const removed of res.ndjson()) {\n yield toCoreInterface(removed)\n }\n }\n\n return rm\n})\n\n/**\n * @param {*} removed\n */\nfunction toCoreInterface (removed) {\n /** @type {RmResult} */\n const out = {\n cid: CID.parse(removed.Hash)\n }\n\n if (removed.Error) {\n out.error = new Error(removed.Error)\n }\n\n return out\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/block').API} BlockAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {BlockAPI[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n const res = await api.post('block/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return { cid: CID.parse(data.Key), size: data.Size }\n }\n\n return stat\n})\n", "import { createGet } from './get.js'\nimport { createPut } from './put.js'\nimport { createRm } from './rm.js'\nimport { createStat } from './stat.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createBlock (config) {\n return {\n get: createGet(config),\n put: createPut(config),\n rm: createRm(config),\n stat: createStat(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createAdd = configure(api => {\n /**\n * @type {BootstrapAPI[\"add\"]}\n */\n async function add (addr, options = {}) {\n const res = await api.post('bootstrap/add', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return add\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createClear = configure(api => {\n /**\n * @type {BootstrapAPI[\"clear\"]}\n */\n async function clear (options = {}) {\n const res = await api.post('bootstrap/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n all: true\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return clear\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createList = configure(api => {\n /**\n * @type {BootstrapAPI[\"list\"]}\n */\n async function list (options = {}) {\n const res = await api.post('bootstrap/list', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return list\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createReset = configure(api => {\n /**\n * @type {BootstrapAPI[\"reset\"]}\n */\n async function reset (options = {}) {\n const res = await api.post('bootstrap/add', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n default: true\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return reset\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multiaddr } from '@multiformats/multiaddr'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/bootstrap').API} BootstrapAPI\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {BootstrapAPI[\"rm\"]}\n */\n async function rm (addr, options = {}) {\n const res = await api.post('bootstrap/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n\n const { Peers } = await res.json()\n\n return { Peers: Peers.map((/** @type {string} */ ma) => multiaddr(ma)) }\n }\n\n return rm\n})\n", "import { createAdd } from './add.js'\nimport { createClear } from './clear.js'\nimport { createList } from './list.js'\nimport { createReset } from './reset.js'\nimport { createRm } from './rm.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createBootstrap (config) {\n return {\n add: createAdd(config),\n clear: createClear(config),\n list: createList(config),\n reset: createReset(config),\n rm: createRm(config)\n }\n}\n", "import { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config/profiles').API} ConfigProfilesAPI\n */\n\nexport const createApply = configure(api => {\n /**\n * @type {ConfigProfilesAPI[\"apply\"]}\n */\n async function apply (profile, options = {}) {\n const res = await api.post('config/profile/apply', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: profile,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return {\n original: data.OldCfg, updated: data.NewCfg\n }\n }\n\n return apply\n})\n", "\n/**\n * Convert object properties to camel case.\n * NOT recursive!\n * e.g.\n * AgentVersion => agentVersion\n * ID => id\n *\n * @param {Record} obj\n */\nexport function objectToCamel (obj) {\n if (obj == null) {\n return obj\n }\n\n const caps = /^[A-Z]+$/\n\n /** @type {Record} */\n const output = {}\n\n return Object.keys(obj).reduce((camelObj, k) => {\n if (caps.test(k)) { // all caps\n camelObj[k.toLowerCase()] = obj[k]\n } else if (caps.test(k[0])) { // pascal\n camelObj[k[0].toLowerCase() + k.slice(1)] = obj[k]\n } else {\n camelObj[k] = obj[k]\n }\n return camelObj\n }, output)\n}\n", "import { objectToCamel } from '../../lib/object-to-camel.js'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config/profiles').API} ConfigProfilesAPI\n */\n\nexport const createList = configure(api => {\n /**\n * @type {ConfigProfilesAPI[\"list\"]}\n */\n async function list (options = {}) {\n const res = await api.post('config/profile/list', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n const data = await res.json()\n\n return data.map((/** @type {Record} */ profile) => objectToCamel(profile))\n }\n return list\n})\n", "import { createApply } from './apply.js'\nimport { createList } from './list.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createProfiles (config) {\n return {\n apply: createApply(config),\n list: createList(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {ConfigAPI[\"get\"]}\n */\n const get = async (key, options = {}) => {\n if (!key) {\n throw new Error('key argument is required')\n }\n\n const res = await api.post('config', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: key,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return data.Value\n }\n\n return get\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createGetAll = configure(api => {\n /**\n * @type {ConfigAPI[\"getAll\"]}\n */\n const getAll = async (options = {}) => {\n const res = await api.post('config/show', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return data\n }\n\n return getAll\n})\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createReplace = configure(api => {\n /**\n * @type {ConfigAPI[\"replace\"]}\n */\n const replace = async (config, options = {}) => {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('config/replace', {\n signal,\n searchParams: toUrlSearchParams(options),\n ...(\n await multipartRequest([uint8ArrayFromString(JSON.stringify(config))], controller, options.headers)\n )\n })\n\n await res.text()\n }\n\n return replace\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/config').API} ConfigAPI\n */\n\nexport const createSet = configure(api => {\n /**\n * @type {ConfigAPI[\"set\"]}\n */\n const set = async (key, value, options = {}) => {\n if (typeof key !== 'string') {\n throw new Error('Invalid key type')\n }\n\n const params = {\n ...options,\n ...encodeParam(key, value)\n }\n\n const res = await api.post('config', {\n signal: options.signal,\n searchParams: toUrlSearchParams(params),\n headers: options.headers\n })\n\n await res.text()\n }\n\n return set\n})\n\n/**\n * @param {*} key\n * @param {*} value\n */\nconst encodeParam = (key, value) => {\n switch (typeof value) {\n case 'boolean':\n return { arg: [key, value.toString()], bool: true }\n case 'string':\n return { arg: [key, value] }\n default:\n return { arg: [key, JSON.stringify(value)], json: true }\n }\n}\n", "import { createProfiles } from './profiles/index.js'\nimport { createGet } from './get.js'\nimport { createGetAll } from './get-all.js'\nimport { createReplace } from './replace.js'\nimport { createSet } from './set.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createConfig (config) {\n return {\n getAll: createGetAll(config),\n get: createGet(config),\n set: createSet(config),\n replace: createReplace(config),\n profiles: createProfiles(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\nexport const createExport = configure(api => {\n /**\n * @type {DAGAPI[\"export\"]}\n */\n async function * dagExport (root, options = {}) {\n const res = await api.post('dag/export', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: root.toString()\n }),\n headers: options.headers\n })\n\n yield * res.iterator()\n }\n\n return dagExport\n})\n", "import { CID } from 'multiformats/cid'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/**\n * Retrieves IPLD Nodes along the `path` that is rooted at `cid`.\n *\n * @param {CID} cid - the CID where the resolving starts\n * @param {string} path - the path that should be resolved\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {(cid: CID, options?: AbortOptions) => Promise} getBlock\n * @param {AbortOptions} [options]\n */\nexport async function * resolve (cid, path, codecs, getBlock, options) {\n /**\n * @param {CID} cid\n */\n const load = async (cid) => {\n const codec = await codecs.getCodec(cid.code)\n const block = await getBlock(cid, options)\n\n return codec.decode(block)\n }\n\n const parts = path.split('/').filter(Boolean)\n let value = await load(cid)\n let lastCid = cid\n\n // End iteration if there isn't a CID to follow any more\n while (parts.length) {\n const key = parts.shift()\n\n if (!key) {\n throw errCode(new Error(`Could not resolve path \"${path}\"`), 'ERR_INVALID_PATH')\n }\n\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n value = value[key]\n\n yield {\n value,\n remainderPath: parts.join('/')\n }\n } else {\n throw errCode(new Error(`no link named \"${key}\" under ${lastCid}`), 'ERR_NO_LINK')\n }\n\n const cid = CID.asCID(value)\n\n if (cid) {\n lastCid = cid\n value = await load(value)\n }\n }\n\n yield {\n value,\n remainderPath: ''\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { resolve } from '../lib/resolve.js'\nimport first from 'it-first'\nimport last from 'it-last'\nimport errCode from 'err-code'\nimport { createGet as createBlockGet } from '../block/get.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} options\n */\nexport const createGet = (codecs, options) => {\n const fn = configure((api, opts) => {\n const getBlock = createBlockGet(opts)\n\n /**\n * @type {DAGAPI[\"get\"]}\n */\n const get = async (cid, options = {}) => {\n if (options.path) {\n const entry = options.localResolve\n ? await first(resolve(cid, options.path, codecs, getBlock, options))\n : await last(resolve(cid, options.path, codecs, getBlock, options))\n /** @type {import('ipfs-core-types/src/dag').GetResult | undefined} - first and last will return undefined when empty */\n const result = (entry)\n\n if (!result) {\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n\n return result\n }\n\n const codec = await codecs.getCodec(cid.code)\n const block = await getBlock(cid, options)\n const node = codec.decode(block)\n\n return {\n value: node,\n remainderPath: ''\n }\n }\n\n return get\n })\n\n return fn(options)\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\nexport const createImport = configure(api => {\n /**\n * @type {DAGAPI[\"import\"]}\n */\n async function * dagImport (source, options = {}) {\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n const { headers, body } = await multipartRequest(source, controller, options.headers)\n\n const res = await api.post('dag/import', {\n signal,\n headers,\n body,\n searchParams: toUrlSearchParams({ 'pin-roots': options.pinRoots })\n })\n\n for await (const { Root } of res.ndjson()) {\n if (Root !== undefined) {\n const { Cid: { '/': Cid }, PinErrorMsg } = Root\n\n yield {\n root: {\n cid: CID.parse(Cid),\n pinErrorMsg: PinErrorMsg\n }\n }\n }\n }\n }\n\n return dagImport\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} options\n */\nexport const createPut = (codecs, options) => {\n const fn = configure((api) => {\n /**\n * @type {DAGAPI[\"put\"]}\n */\n const put = async (dagNode, options = {}) => {\n const settings = {\n storeCodec: 'dag-cbor',\n hashAlg: 'sha2-256',\n ...options\n }\n\n let serialized\n\n if (settings.inputCodec) {\n // if you supply an inputCodec, we assume you're passing in a raw, encoded\n // block using that codec, so we'll just pass that on to the server and let\n // it deal with the decode/encode/store cycle\n if (!(dagNode instanceof Uint8Array)) {\n throw new Error('Can only inputCodec on raw bytes that can be decoded')\n }\n serialized = dagNode\n } else {\n // if you don't supply an inputCodec, we assume you've passed in a JavaScript\n // object you want to have encoded using storeCodec, so we'll prepare it for\n // you if we have the codec\n const storeCodec = await codecs.getCodec(settings.storeCodec)\n serialized = storeCodec.encode(dagNode)\n // now we have a serialized form, the server should be told to receive it\n // in that format\n settings.inputCodec = settings.storeCodec\n }\n\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, settings.signal)\n\n const res = await api.post('dag/put', {\n timeout: settings.timeout,\n signal,\n searchParams: toUrlSearchParams(settings),\n ...(\n await multipartRequest([serialized], controller, settings.headers)\n )\n })\n const data = await res.json()\n\n return CID.parse(data.Cid['/'])\n }\n\n return put\n })\n\n return fn(options)\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dag').API} DAGAPI\n */\n\nexport const createResolve = configure(api => {\n /**\n * @type {DAGAPI[\"resolve\"]}\n */\n const resolve = async (ipfsPath, options = {}) => {\n const res = await api.post('dag/resolve', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${ipfsPath}${options.path ? `/${options.path}`.replace(/\\/[/]+/g, '/') : ''}`,\n ...options\n }),\n headers: options.headers\n })\n\n const data = await res.json()\n\n return { cid: CID.parse(data.Cid['/']), remainderPath: data.RemPath }\n }\n\n return resolve\n})\n", "import { createExport } from './export.js'\nimport { createGet } from './get.js'\nimport { createImport } from './import.js'\nimport { createPut } from './put.js'\nimport { createResolve } from './resolve.js'\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} config\n */\nexport function createDag (codecs, config) {\n return {\n export: createExport(config),\n get: createGet(codecs, config),\n import: createImport(config),\n put: createPut(codecs, config),\n resolve: createResolve(config)\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport {\n SendingQuery,\n PeerResponse,\n FinalPeer,\n QueryError,\n Provider,\n Value,\n AddingPeer,\n DialingPeer\n} from './response-types.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\n/**\n * @param {{Type: number, ID: string, Extra: string, Responses: {ID: string, Addrs: string[]}[]}} event\n * @returns {import('ipfs-core-types/src/dht').QueryEvent}\n */\nexport const mapEvent = (event) => {\n if (event.Type === SendingQuery) {\n return {\n name: 'SENDING_QUERY',\n type: event.Type\n }\n }\n\n if (event.Type === PeerResponse) {\n return {\n from: peerIdFromString(event.ID),\n name: 'PEER_RESPONSE',\n type: event.Type,\n // TODO: how to infer this from the go-ipfs response\n messageType: 0,\n // TODO: how to infer this from the go-ipfs response\n messageName: 'PUT_VALUE',\n closer: (event.Responses || []).map(({ ID, Addrs }) => ({ id: peerIdFromString(ID), multiaddrs: Addrs.map(addr => multiaddr(addr)), protocols: [] })),\n providers: (event.Responses || []).map(({ ID, Addrs }) => ({ id: peerIdFromString(ID), multiaddrs: Addrs.map(addr => multiaddr(addr)), protocols: [] }))\n // TODO: how to infer this from the go-ipfs response\n // record: ???\n }\n }\n\n if (event.Type === FinalPeer) {\n // dht.query ends with a FinalPeer event with no Responses\n /** @type {import('@libp2p/interface-peer-info').PeerInfo} */\n let peer = {\n // @ts-expect-error go-ipfs does not return this\n id: event.ID ?? peerIdFromString(event.ID),\n /** @type {Multiaddr[]} */\n multiaddrs: [],\n protocols: []\n }\n\n if (event.Responses && event.Responses.length) {\n // dht.findPeer has the result in the Responses field\n peer = {\n id: peerIdFromString(event.Responses[0].ID),\n multiaddrs: event.Responses[0].Addrs.map(addr => multiaddr(addr)),\n protocols: []\n }\n }\n\n return {\n name: 'FINAL_PEER',\n type: event.Type,\n peer\n }\n }\n\n if (event.Type === QueryError) {\n return {\n name: 'QUERY_ERROR',\n type: event.Type,\n error: new Error(event.Extra)\n }\n }\n\n if (event.Type === Provider) {\n return {\n name: 'PROVIDER',\n type: event.Type,\n providers: event.Responses.map(({ ID, Addrs }) => ({ id: peerIdFromString(ID), multiaddrs: Addrs.map(addr => multiaddr(addr)), protocols: [] }))\n }\n }\n\n if (event.Type === Value) {\n return {\n name: 'VALUE',\n type: event.Type,\n value: uint8ArrayFromString(event.Extra, 'base64pad')\n }\n }\n\n if (event.Type === AddingPeer) {\n const peers = event.Responses.map(({ ID }) => peerIdFromString(ID))\n\n if (!peers.length) {\n throw new Error('No peer found')\n }\n\n return {\n name: 'ADDING_PEER',\n type: event.Type,\n peer: peers[0]\n }\n }\n\n if (event.Type === DialingPeer) {\n return {\n name: 'DIALING_PEER',\n type: event.Type,\n peer: peerIdFromString(event.ID)\n }\n }\n\n throw new Error('Unknown DHT event type')\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createFindPeer = configure(api => {\n /**\n * @type {DHTAPI[\"findPeer\"]}\n */\n async function * findPeer (peerId, options = {}) {\n const res = await api.post('dht/findpeer', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: peerId,\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return findPeer\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createFindProvs = configure(api => {\n /**\n * @type {DHTAPI[\"findProvs\"]}\n */\n async function * findProvs (cid, options = {}) {\n const res = await api.post('dht/findprovs', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cid.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return findProvs\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {DHTAPI[\"get\"]}\n */\n async function * get (key, options = {}) {\n const res = await api.post('dht/get', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n // arg: base36.encode(key),\n arg: key instanceof Uint8Array ? uint8ArrayToString(key) : key.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return get\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n * @typedef {import('multiformats/cid').CID} CID\n */\n\nexport const createProvide = configure(api => {\n /**\n * @type {DHTAPI[\"provide\"]}\n */\n async function * provide (cids, options = { recursive: false }) {\n /** @type {CID[]} */\n const cidArr = Array.isArray(cids) ? cids : [cids]\n\n const res = await api.post('dht/provide', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: cidArr.map(cid => cid.toString()),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return provide\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { abortSignal } from '../lib/abort-signal.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createPut = configure(api => {\n /**\n * @type {DHTAPI[\"put\"]}\n */\n async function * put (key, value, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('dht/put', {\n signal,\n searchParams: toUrlSearchParams({\n arg: key instanceof Uint8Array ? uint8ArrayToString(key) : key.toString(),\n ...options\n }),\n ...(\n await multipartRequest([value], controller, options.headers)\n )\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return put\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { mapEvent } from './map-event.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/dht').API} DHTAPI\n */\n\nexport const createQuery = configure(api => {\n /**\n * @type {DHTAPI[\"query\"]}\n */\n async function * query (peerId, options = {}) {\n const res = await api.post('dht/query', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: peerId.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n for await (const event of res.ndjson()) {\n yield mapEvent(event)\n }\n }\n\n return query\n})\n", "import { createFindPeer } from './find-peer.js'\nimport { createFindProvs } from './find-provs.js'\nimport { createGet } from './get.js'\nimport { createProvide } from './provide.js'\nimport { createPut } from './put.js'\nimport { createQuery } from './query.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createDht (config) {\n return {\n findPeer: createFindPeer(config),\n findProvs: createFindProvs(config),\n get: createGet(config),\n provide: createProvide(config),\n put: createPut(config),\n query: createQuery(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/diag').API} DiagAPI\n */\n\nexport const createCmds = configure(api => {\n /**\n * @type {DiagAPI[\"cmds\"]}\n */\n async function cmds (options = {}) {\n const res = await api.post('diag/cmds', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return res.json()\n }\n return cmds\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/diag').API} DiagAPI\n */\n\nexport const createNet = configure(api => {\n /**\n * @type {DiagAPI[\"net\"]}\n */\n async function net (options = {}) {\n const res = await api.post('diag/net', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n return res.json()\n }\n return net\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/diag').API} DiagAPI\n */\n\nexport const createSys = configure(api => {\n /**\n * @type {DiagAPI[\"sys\"]}\n */\n async function sys (options = {}) {\n const res = await api.post('diag/sys', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return res.json()\n }\n return sys\n})\n", "import { createCmds } from './cmds.js'\nimport { createNet } from './net.js'\nimport { createSys } from './sys.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createDiag (config) {\n return {\n cmds: createCmds(config),\n net: createNet(config),\n sys: createSys(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createChmod = configure(api => {\n /**\n * @type {FilesAPI[\"chmod\"]}\n */\n async function chmod (path, mode, options = {}) {\n const res = await api.post('files/chmod', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n mode,\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return chmod\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createCp = configure(api => {\n /**\n * @type {FilesAPI[\"cp\"]}\n */\n async function cp (sources, destination, options = {}) {\n /** @type {import('ipfs-core-types/src/utils').IPFSPath[]} */\n const sourceArr = Array.isArray(sources) ? sources : [sources]\n\n const res = await api.post('files/cp', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: sourceArr.concat(destination).map(src => CID.asCID(src) ? `/ipfs/${src}` : src),\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return cp\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createFlush = configure(api => {\n /**\n * @type {FilesAPI[\"flush\"]}\n */\n async function flush (path, options = {}) {\n if (!path || typeof path !== 'string') {\n throw new Error('ipfs.files.flush requires a path')\n }\n\n const res = await api.post('files/flush', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return CID.parse(data.Cid)\n }\n return flush\n})\n", "import { objectToCamel } from './object-to-camel.js'\n\n/**\n * @param {Record} entry\n */\nexport function objectToCamelWithMetadata (entry) {\n const file = objectToCamel(entry)\n\n if (Object.prototype.hasOwnProperty.call(file, 'mode')) {\n file.mode = parseInt(file.mode, 8)\n }\n\n if (Object.prototype.hasOwnProperty.call(file, 'mtime')) {\n file.mtime = {\n secs: file.mtime,\n nsecs: file.mtimeNsecs || 0\n }\n\n delete file.mtimeNsecs\n }\n\n return file\n}\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamelWithMetadata } from '../lib/object-to-camel-with-metadata.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\nexport const createLs = configure(api => {\n /**\n * @type {FilesAPI[\"ls\"]}\n */\n async function * ls (path, options = {}) {\n if (!path) {\n throw new Error('ipfs.files.ls requires a path')\n }\n\n const res = await api.post('files/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: CID.asCID(path) ? `/ipfs/${path}` : path,\n // default long to true, diverges from go-ipfs where its false by default\n long: true,\n ...options,\n stream: true\n }),\n headers: options.headers\n })\n\n for await (const result of res.ndjson()) {\n // go-ipfs does not yet support the \"stream\" option\n if ('Entries' in result) {\n for (const entry of result.Entries || []) {\n yield toCoreInterface(objectToCamelWithMetadata(entry))\n }\n } else {\n yield toCoreInterface(objectToCamelWithMetadata(result))\n }\n }\n }\n return ls\n})\n\n/**\n * @param {*} entry\n */\nfunction toCoreInterface (entry) {\n if (entry.hash) {\n entry.cid = CID.parse(entry.hash)\n }\n\n delete entry.hash\n\n entry.type = entry.type === 1 ? 'directory' : 'file'\n\n return entry\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createMkdir = configure(api => {\n /**\n * @type {FilesAPI[\"mkdir\"]}\n */\n async function mkdir (path, options = {}) {\n const res = await api.post('files/mkdir', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return mkdir\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createMv = configure(api => {\n /**\n * @type {FilesAPI[\"mv\"]}\n */\n async function mv (sources, destination, options = {}) {\n if (!Array.isArray(sources)) {\n sources = [sources]\n }\n\n const res = await api.post('files/mv', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: sources.concat(destination),\n ...options\n }),\n headers: options.headers\n })\n await res.text()\n }\n\n return mv\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n// @ts-expect-error no types\nimport toIterable from 'stream-to-it/source.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createRead = configure(api => {\n /**\n * @type {FilesAPI[\"read\"]}\n */\n async function * read (path, options = {}) {\n const res = await api.post('files/read', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n count: options.length,\n ...options\n }),\n headers: options.headers\n })\n\n yield * toIterable(res.body)\n }\n return read\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport HTTP from 'ipfs-utils/src/http.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {FilesAPI[\"rm\"]}\n */\n async function rm (path, options = {}) {\n const res = await api.post('files/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n\n const body = await res.text()\n // we don't expect text body to be ever present\n // (if so, it means an error such as https://github.com/ipfs/go-ipfs/issues/8606)\n if (body !== '') {\n /** @type {Error} */\n const error = new HTTP.HTTPError(res)\n error.message = body\n throw error\n }\n }\n return rm\n})\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamelWithMetadata } from '../lib/object-to-camel-with-metadata.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {FilesAPI[\"stat\"]}\n */\n async function stat (path, options = {}) {\n const res = await api.post('files/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n data.WithLocality = data.WithLocality || false\n return toCoreInterface(objectToCamelWithMetadata(data))\n }\n return stat\n})\n\n/**\n * @param {*} entry\n */\nfunction toCoreInterface (entry) {\n entry.cid = CID.parse(entry.hash)\n delete entry.hash\n return entry\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createTouch = configure(api => {\n /**\n * @type {FilesAPI[\"touch\"]}\n */\n async function touch (path, options = {}) {\n const res = await api.post('files/touch', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n\n await res.text()\n }\n return touch\n})\n", "import { modeToString } from '../lib/mode-to-string.js'\nimport { parseMtime } from '../lib/parse-mtime.js'\nimport { configure } from '../lib/configure.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { abortSignal } from '../lib/abort-signal.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/files').API} FilesAPI\n */\n\nexport const createWrite = configure(api => {\n /**\n * @type {FilesAPI[\"write\"]}\n */\n async function write (path, input, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('files/write', {\n signal,\n searchParams: toUrlSearchParams({\n arg: path,\n streamChannels: true,\n count: options.length,\n ...options\n }),\n ...(\n await multipartRequest([{\n content: input,\n path: 'arg',\n mode: modeToString(options.mode),\n mtime: parseMtime(options.mtime)\n }], controller, options.headers)\n )\n })\n\n await res.text()\n }\n return write\n})\n", "import { createChmod } from './chmod.js'\nimport { createCp } from './cp.js'\nimport { createFlush } from './flush.js'\nimport { createLs } from './ls.js'\nimport { createMkdir } from './mkdir.js'\nimport { createMv } from './mv.js'\nimport { createRead } from './read.js'\nimport { createRm } from './rm.js'\nimport { createStat } from './stat.js'\nimport { createTouch } from './touch.js'\nimport { createWrite } from './write.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createFiles (config) {\n return {\n chmod: createChmod(config),\n cp: createCp(config),\n flush: createFlush(config),\n ls: createLs(config),\n mkdir: createMkdir(config),\n mv: createMv(config),\n read: createRead(config),\n rm: createRm(config),\n stat: createStat(config),\n touch: createTouch(config),\n write: createWrite(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createExport = configure(api => {\n /**\n * @type {KeyAPI[\"export\"]}\n */\n const exportKey = async (name, password, options = {}) => {\n throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED')\n }\n\n return exportKey\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createGen = configure(api => {\n /**\n * @type {KeyAPI[\"gen\"]}\n */\n async function gen (name, options) {\n const opts = options ?? { type: 'Ed25519' }\n\n const res = await api.post('key/gen', {\n signal: opts.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n ...opts\n }),\n headers: opts.headers\n })\n const data = await res.json()\n\n // @ts-expect-error server output is not typed\n return objectToCamel(data)\n }\n return gen\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createImport = configure(api => {\n /**\n * @type {KeyAPI[\"import\"]}\n */\n async function importKey (name, pem, password, options = {}) {\n const res = await api.post('key/import', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n pem,\n password,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n // @ts-expect-error server output is not typed\n return objectToCamel(data)\n }\n return importKey\n})\n", "import { configure } from '../lib/configure.js'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createInfo = configure(api => {\n /**\n * @type {KeyAPI[\"info\"]}\n */\n const info = async (name, options = {}) => {\n throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED')\n }\n\n return info\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createList = configure(api => {\n /**\n * @type {KeyAPI[\"list\"]}\n */\n async function list (options = {}) {\n const res = await api.post('key/list', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n const data = await res.json()\n\n return (data.Keys || []).map((/** @type {any} **/ k) => objectToCamel(k))\n }\n return list\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createRename = configure(api => {\n /**\n * @type {KeyAPI[\"rename\"]}\n */\n async function rename (oldName, newName, options = {}) {\n const res = await api.post('key/rename', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n oldName,\n newName\n ],\n ...options\n }),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return rename\n})\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/key').API} KeyAPI\n */\n\nexport const createRm = configure(api => {\n /**\n * @type {KeyAPI[\"rm\"]}\n */\n async function rm (name, options = {}) {\n const res = await api.post('key/rm', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n // @ts-expect-error server output is not typed\n return objectToCamel(data.Keys[0])\n }\n return rm\n})\n", "import { createExport } from './export.js'\nimport { createGen } from './gen.js'\nimport { createImport } from './import.js'\nimport { createInfo } from './info.js'\nimport { createList } from './list.js'\nimport { createRename } from './rename.js'\nimport { createRm } from './rm.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createKey (config) {\n return {\n export: createExport(config),\n gen: createGen(config),\n import: createImport(config),\n info: createInfo(config),\n list: createList(config),\n rename: createRename(config),\n rm: createRm(config)\n }\n}\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/log').API} LogAPI\n */\n\nexport const createLevel = configure(api => {\n /**\n * @type {LogAPI[\"level\"]}\n */\n async function level (subsystem, level, options = {}) {\n const res = await api.post('log/level', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n subsystem,\n level\n ],\n ...options\n }),\n headers: options.headers\n })\n\n return objectToCamel(await res.json())\n }\n return level\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/log').API} LogAPI\n */\n\nexport const createLs = configure(api => {\n /**\n * @type {LogAPI[\"ls\"]}\n */\n async function ls (options = {}) {\n const res = await api.post('log/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n const data = await res.json()\n return data.Strings\n }\n return ls\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/log').API} LogAPI\n */\n\nexport const createTail = configure(api => {\n /**\n * @type {LogAPI[\"tail\"]}\n */\n async function * tail (options = {}) {\n const res = await api.post('log/tail', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n yield * res.ndjson()\n }\n return tail\n})\n", "import { createLevel } from './level.js'\nimport { createLs } from './ls.js'\nimport { createTail } from './tail.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createLog (config) {\n return {\n level: createLevel(config),\n ls: createLs(config),\n tail: createTail(config)\n }\n}\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name').API} NameAPI\n */\n\nexport const createPublish = configure(api => {\n /**\n * @type {NameAPI[\"publish\"]}\n */\n async function publish (path, options = {}) {\n const res = await api.post('name/publish', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${path}`,\n ...options\n }),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return publish\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name').API} NameAPI\n */\n\nexport const createResolve = configure(api => {\n /**\n * @type {NameAPI[\"resolve\"]}\n */\n async function * resolve (path, options = {}) {\n const res = await api.post('name/resolve', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n stream: true,\n ...options\n }),\n headers: options.headers\n })\n\n for await (const result of res.ndjson()) {\n yield result.Path\n }\n }\n return resolve\n})\n", "import { objectToCamel } from '../../lib/object-to-camel.js'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name/pubsub').API} NamePubsubAPI\n */\n\nexport const createCancel = configure(api => {\n /**\n * @type {NamePubsubAPI[\"cancel\"]}\n */\n async function cancel (name, options = {}) {\n const res = await api.post('name/pubsub/cancel', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: name,\n ...options\n }),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return cancel\n})\n", "import { objectToCamel } from '../../lib/object-to-camel.js'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name/pubsub').API} NamePubsubAPI\n */\n\nexport const createState = configure(api => {\n /**\n * @type {NamePubsubAPI[\"state\"]}\n */\n async function state (options = {}) {\n const res = await api.post('name/pubsub/state', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return objectToCamel(await res.json())\n }\n return state\n})\n", "import { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/name/pubsub').API} NamePubsubAPI\n */\n\nexport const createSubs = configure(api => {\n /**\n * @type {NamePubsubAPI[\"subs\"]}\n */\n async function subs (options = {}) {\n const res = await api.post('name/pubsub/subs', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n const data = await res.json()\n\n return data.Strings || []\n }\n return subs\n})\n", "import { createCancel } from './cancel.js'\nimport { createState } from './state.js'\nimport { createSubs } from './subs.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createPubsub (config) {\n return {\n cancel: createCancel(config),\n state: createState(config),\n subs: createSubs(config)\n }\n}\n", "import { createPublish } from './publish.js'\nimport { createResolve } from './resolve.js'\nimport { createPubsub } from './pubsub/index.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createName (config) {\n return {\n publish: createPublish(config),\n resolve: createResolve(config),\n pubsub: createPubsub(config)\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createData = configure(api => {\n /**\n * @type {ObjectAPI[\"data\"]}\n */\n async function data (cid, options = {}) {\n const res = await api.post('object/data', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid instanceof Uint8Array ? CID.decode(cid) : cid}`,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.arrayBuffer()\n\n return new Uint8Array(data, 0, data.byteLength)\n }\n return data\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {ObjectAPI[\"get\"]}\n */\n async function get (cid, options = {}) {\n const res = await api.post('object/get', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid instanceof Uint8Array ? CID.decode(cid) : cid}`,\n dataEncoding: 'base64',\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return {\n Data: uint8ArrayFromString(data.Data, 'base64pad'),\n Links: (data.Links || []).map((/** @type {any} */ link) => ({\n Name: link.Name,\n Hash: CID.parse(link.Hash),\n Tsize: link.Size\n }))\n }\n }\n return get\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createLinks = configure(api => {\n /**\n * @type {ObjectAPI[\"links\"]}\n */\n async function links (cid, options = {}) {\n const res = await api.post('object/links', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid instanceof Uint8Array ? CID.decode(cid) : cid}`,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return (data.Links || []).map((/** @type {any} */ l) => ({\n Name: l.Name,\n Tsize: l.Size,\n Hash: CID.parse(l.Hash)\n }))\n }\n return links\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createNew = configure(api => {\n /**\n * @type {ObjectAPI[\"new\"]}\n */\n async function newObject (options = {}) {\n const res = await api.post('object/new', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: options.template,\n ...options\n }),\n headers: options.headers\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return newObject\n})\n", "import { configure } from '../lib/configure.js'\nimport { createPut as createDagPut } from '../dag/put.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} options\n */\nexport const createPut = (codecs, options) => {\n const fn = configure((api) => {\n const dagPut = createDagPut(codecs, options)\n\n /**\n * @type {ObjectAPI[\"put\"]}\n */\n async function put (obj, options = {}) {\n return dagPut(obj, {\n ...options,\n storeCodec: 'dag-pb',\n hashAlg: 'sha2-256',\n version: 1\n })\n }\n return put\n })\n\n return fn(options)\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object').API} ObjectAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {ObjectAPI[\"stat\"]}\n */\n async function stat (cid, options = {}) {\n const res = await api.post('object/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${cid}`,\n ...options\n }),\n headers: options.headers\n })\n\n const output = await res.json()\n\n return {\n ...output,\n Hash: CID.parse(output.Hash)\n }\n }\n return stat\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createAddLink = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"addLink\"]}\n */\n async function addLink (cid, dLink, options = {}) {\n const res = await api.post('object/patch/add-link', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n `${cid}`,\n // @ts-expect-error loose types\n dLink.Name || dLink.name || '',\n // @ts-expect-error loose types\n (dLink.Hash || dLink.cid || '').toString() || null\n ],\n ...options\n }),\n headers: options.headers\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n\n return addLink\n})\n", "import { CID } from 'multiformats/cid'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\nimport { abortSignal } from '../../lib/abort-signal.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createAppendData = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"appendData\"]}\n */\n async function appendData (cid, data, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('object/patch/append-data', {\n signal,\n searchParams: toUrlSearchParams({\n arg: `${cid}`,\n ...options\n }),\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return appendData\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createRmLink = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"rmLink\"]}\n */\n async function rmLink (cid, dLink, options = {}) {\n const res = await api.post('object/patch/rm-link', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: [\n `${cid}`,\n // @ts-expect-error loose types\n dLink.Name || dLink.name || null\n ],\n ...options\n }),\n headers: options.headers\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return rmLink\n})\n", "import { CID } from 'multiformats/cid'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { configure } from '../../lib/configure.js'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\nimport { abortSignal } from '../../lib/abort-signal.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/object/patch').API} ObjectPatchAPI\n */\n\nexport const createSetData = configure(api => {\n /**\n * @type {ObjectPatchAPI[\"setData\"]}\n */\n async function setData (cid, data, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('object/patch/set-data', {\n signal,\n searchParams: toUrlSearchParams({\n arg: [\n `${cid}`\n ],\n ...options\n }),\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n\n const { Hash } = await res.json()\n\n return CID.parse(Hash)\n }\n return setData\n})\n", "import { createAddLink } from './add-link.js'\nimport { createAppendData } from './append-data.js'\nimport { createRmLink } from './rm-link.js'\nimport { createSetData } from './set-data.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createPatch (config) {\n return {\n addLink: createAddLink(config),\n appendData: createAppendData(config),\n rmLink: createRmLink(config),\n setData: createSetData(config)\n }\n}\n", "import { createData } from './data.js'\nimport { createGet } from './get.js'\nimport { createLinks } from './links.js'\nimport { createNew } from './new.js'\nimport { createPut } from './put.js'\nimport { createStat } from './stat.js'\nimport { createPatch } from './patch/index.js'\n\n/**\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {import('../types').Options} config\n */\nexport function createObject (codecs, config) {\n return {\n data: createData(config),\n get: createGet(config),\n links: createLinks(config),\n new: createNew(config),\n put: createPut(codecs, config),\n stat: createStat(config),\n patch: createPatch(config)\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\nexport const createAddAll = configure(api => {\n /**\n * @type {PinAPI[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n for await (const { path, recursive, metadata } of normaliseInput(source)) {\n const res = await api.post('pin/add', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n arg: path,\n recursive,\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n stream: true\n }),\n headers: options.headers\n })\n\n for await (const pin of res.ndjson()) {\n if (pin.Pins) { // non-streaming response\n for (const cid of pin.Pins) {\n yield CID.parse(cid)\n }\n continue\n }\n\n yield CID.parse(pin)\n }\n }\n }\n return addAll\n})\n", "import { createAddAll } from './add-all.js'\nimport last from 'it-last'\nimport { configure } from '../lib/configure.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createAdd (config) {\n const all = createAddAll(config)\n\n return configure(() => {\n /**\n * @type {PinAPI[\"add\"]}\n */\n async function add (path, options = {}) {\n // @ts-expect-error last can return undefined\n return last(all([{\n path,\n ...options\n }], options))\n }\n return add\n })(config)\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\n/**\n * @param {string} type\n * @param {string} cid\n * @param {Record} metadata\n */\nfunction toPin (type, cid, metadata) {\n /** @type {import('ipfs-core-types/src/pin').LsResult} */\n const pin = {\n type,\n cid: CID.parse(cid)\n }\n\n if (metadata) {\n pin.metadata = metadata\n }\n\n return pin\n}\n\nexport const createLs = configure(api => {\n /**\n * @type {PinAPI[\"ls\"]}\n */\n async function * ls (options = {}) {\n /** @type {any[]} */\n let paths = []\n\n if (options.paths) {\n paths = Array.isArray(options.paths) ? options.paths : [options.paths]\n }\n\n const res = await api.post('pin/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n ...options,\n arg: paths.map(path => `${path}`),\n stream: true\n }),\n headers: options.headers\n })\n\n for await (const pin of res.ndjson()) {\n if (pin.Keys) { // non-streaming response\n for (const cid of Object.keys(pin.Keys)) {\n yield toPin(pin.Keys[cid].Type, cid, pin.Keys[cid].Metadata)\n }\n return\n }\n\n yield toPin(pin.Type, pin.Cid, pin.Metadata)\n }\n }\n return ls\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { normaliseInput } from 'ipfs-core-utils/pins/normalise-input'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\nexport const createRmAll = configure(api => {\n /**\n * @type {PinAPI[\"rmAll\"]}\n */\n async function * rmAll (source, options = {}) {\n for await (const { path, recursive } of normaliseInput(source)) {\n const searchParams = new URLSearchParams(options.searchParams)\n searchParams.append('arg', `${path}`)\n\n if (recursive != null) searchParams.set('recursive', String(recursive))\n\n const res = await api.post('pin/rm', {\n signal: options.signal,\n headers: options.headers,\n searchParams: toUrlSearchParams({\n ...options,\n arg: `${path}`,\n recursive\n })\n })\n\n for await (const pin of res.ndjson()) {\n if (pin.Pins) { // non-streaming response\n yield * pin.Pins.map((/** @type {string} */ cid) => CID.parse(cid))\n continue\n }\n yield CID.parse(pin)\n }\n }\n }\n return rmAll\n})\n", "import { createRmAll } from './rm-all.js'\nimport last from 'it-last'\nimport { configure } from '../lib/configure.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin').API} PinAPI\n */\n\n/**\n * @param {import('../types').Options} config\n */\nexport const createRm = (config) => {\n const all = createRmAll(config)\n\n return configure(() => {\n /**\n * @type {PinAPI[\"rm\"]}\n */\n async function rm (path, options = {}) {\n // @ts-expect-error last can return undefined\n return last(all([{\n path,\n ...options\n }], options))\n }\n return rm\n })(config)\n}\n", "import { CID } from 'multiformats/cid'\nimport { toUrlSearchParams } from '../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').Pin} Pin\n * @typedef {import('ipfs-core-types/src/pin/remote').AddOptions} AddOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').Query} Query\n * @typedef {import('ipfs-core-types/src/pin/remote').Status} Status\n */\n\n/**\n * @param {object} json\n * @param {string} json.Name\n * @param {string} json.Cid\n * @param {Status} json.Status\n * @returns {Pin}\n */\nexport const decodePin = ({ Name: name, Status: status, Cid: cid }) => {\n return {\n cid: CID.parse(cid),\n name,\n status\n }\n}\n\n/**\n * @param {any} service\n * @returns {string}\n */\nexport const encodeService = (service) => {\n if (typeof service === 'string' && service !== '') {\n return service\n } else {\n throw new TypeError('service name must be passed')\n }\n}\n\n/**\n * @param {any} cid\n * @returns {string}\n */\nexport const encodeCID = (cid) => {\n if (CID.asCID(cid)) {\n return cid.toString()\n } else {\n throw new TypeError(`CID instance expected instead of ${typeof cid}`)\n }\n}\n\n/**\n * @param {Query & { all?: boolean }} query\n * @returns {URLSearchParams}\n */\nexport const encodeQuery = ({ service, cid, name, status, all }) => {\n const query = toUrlSearchParams({\n service: encodeService(service),\n name,\n force: all ? true : undefined\n })\n\n if (cid) {\n for (const value of cid) {\n query.append('cid', encodeCID(value))\n }\n }\n\n if (status) {\n for (const value of status) {\n query.append('status', value)\n }\n }\n\n return query\n}\n\n/**\n * @param {AddOptions & {cid:CID}} options\n * @returns {URLSearchParams}\n */\nexport const encodeAddParams = ({ cid, service, background, name, origins }) => {\n const params = toUrlSearchParams({\n arg: encodeCID(cid),\n service: encodeService(service),\n name,\n background: background ? true : undefined\n })\n\n if (origins) {\n for (const origin of origins) {\n params.append('origin', origin.toString())\n }\n }\n\n return params\n}\n", "import { encodeAddParams, decodePin } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createAdd (client) {\n /**\n * @type {RemotePiningAPI[\"add\"]}\n */\n async function add (cid, { timeout, signal, headers, ...query }) {\n const response = await client.post('pin/remote/add', {\n timeout,\n signal,\n headers,\n searchParams: encodeAddParams({ cid, ...query })\n })\n\n return decodePin(await response.json())\n }\n\n return add\n}\n", "import { encodeQuery, decodePin } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createLs (client) {\n /**\n * @type {RemotePiningAPI[\"ls\"]}\n */\n async function * ls ({ timeout, signal, headers, ...query }) {\n const response = await client.post('pin/remote/ls', {\n timeout,\n signal,\n headers,\n searchParams: encodeQuery(query)\n })\n\n for await (const pin of response.ndjson()) {\n yield decodePin(pin)\n }\n }\n\n return ls\n}\n", "import { encodeQuery } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createRm (client) {\n /**\n * @type {RemotePiningAPI[\"rm\"]}\n */\n async function rm ({ timeout, signal, headers, ...query }) {\n await client.post('pin/remote/rm', {\n timeout,\n signal,\n headers,\n searchParams: encodeQuery({\n ...query,\n all: false\n })\n })\n }\n\n return rm\n}\n", "import { encodeQuery } from './utils.js'\n\n/**\n * @typedef {import('../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote').API} RemotePiningAPI\n */\n\n/**\n * @param {import('../../lib/core').Client} client\n */\nexport function createRmAll (client) {\n /**\n * @type {RemotePiningAPI[\"rmAll\"]}\n */\n async function rmAll ({ timeout, signal, headers, ...query }) {\n await client.post('pin/remote/rm', {\n timeout,\n signal,\n headers,\n searchParams: encodeQuery({\n ...query,\n all: true\n })\n })\n }\n\n return rmAll\n}\n", "/**\n * @typedef {import('ipfs-core-types/src/pin/remote/service').RemotePinServiceWithStat} RemotePinServiceWithStat\n */\n\n/**\n * @param {URL} url\n */\nexport function encodeEndpoint (url) {\n const href = String(url)\n if (href === 'undefined') {\n throw Error('endpoint is required')\n }\n // Workaround trailing `/` issue in go-ipfs\n // @see https://github.com/ipfs/go-ipfs/issues/7826\n return href[href.length - 1] === '/' ? href.slice(0, -1) : href\n}\n\n/**\n * @param {any} json\n * @returns {RemotePinServiceWithStat}\n */\nexport function decodeRemoteService (json) {\n return {\n service: json.Service,\n endpoint: new URL(json.ApiEndpoint),\n ...(json.Stat && { stat: decodeStat(json.Stat) })\n }\n}\n\n/**\n * @param {any} json\n * @returns {import('ipfs-core-types/src/pin/remote/service').Stat}\n */\nexport function decodeStat (json) {\n switch (json.Status) {\n case 'valid': {\n const { Pinning, Pinned, Queued, Failed } = json.PinCount\n return {\n status: 'valid',\n pinCount: {\n queued: Queued,\n pinning: Pinning,\n pinned: Pinned,\n failed: Failed\n }\n }\n }\n case 'invalid': {\n return { status: 'invalid' }\n }\n default: {\n return { status: json.Status }\n }\n }\n}\n", "import { toUrlSearchParams } from '../../../lib/to-url-search-params.js'\nimport { encodeEndpoint } from './utils.js'\n\n/**\n * @typedef {import('../../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote/service').API} RemotePiningServiceAPI\n */\n\n/**\n * @param {import('../../../lib/core').Client} client\n */\nexport function createAdd (client) {\n /**\n * @type {RemotePiningServiceAPI[\"add\"]}\n */\n async function add (name, options) {\n const { endpoint, key, headers, timeout, signal } = options\n\n await client.post('pin/remote/service/add', {\n timeout,\n signal,\n searchParams: toUrlSearchParams({\n arg: [name, encodeEndpoint(endpoint), key]\n }),\n headers\n })\n }\n\n return add\n}\n", "import { toUrlSearchParams } from '../../../lib/to-url-search-params.js'\nimport { decodeRemoteService } from './utils.js'\n\n/**\n * @typedef {import('../../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote/service').API} RemotePiningServiceAPI\n */\n\n/**\n * @param {import('../../../lib/core').Client} client\n */\nexport function createLs (client) {\n /**\n * @type {RemotePiningServiceAPI[\"ls\"]}\n */\n async function ls (options = {}) {\n // @ts-expect-error cannot derive option type from typedef\n const { stat, headers, timeout, signal } = options\n\n const response = await client.post('pin/remote/service/ls', {\n timeout,\n signal,\n headers,\n searchParams: stat === true ? toUrlSearchParams({ stat }) : undefined\n })\n\n /** @type {{RemoteServices: object[]}} */\n const { RemoteServices } = await response.json()\n\n return RemoteServices.map(decodeRemoteService)\n }\n\n return ls\n}\n", "import { toUrlSearchParams } from '../../../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../../../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pin/remote/service').API} RemotePiningServiceAPI\n */\n\n/**\n * @param {import('../../../lib/core').Client} client\n */\nexport function createRm (client) {\n /**\n * @type {RemotePiningServiceAPI[\"rm\"]}\n */\n async function rm (name, options = {}) {\n await client.post('pin/remote/service/rm', {\n signal: options.signal,\n headers: options.headers,\n searchParams: toUrlSearchParams({\n arg: name\n })\n })\n }\n\n return rm\n}\n", "import { Client } from '../../../lib/core.js'\nimport { createAdd } from './add.js'\nimport { createLs } from './ls.js'\nimport { createRm } from './rm.js'\n\n/**\n * @param {import('../../../types').Options} config\n */\nexport function createService (config) {\n const client = new Client(config)\n\n return {\n add: createAdd(client),\n ls: createLs(client),\n rm: createRm(client)\n }\n}\n", "import { Client } from '../../lib/core.js'\nimport { createAdd } from './add.js'\nimport { createLs } from './ls.js'\nimport { createRm } from './rm.js'\nimport { createRmAll } from './rm-all.js'\nimport { createService } from './service/index.js'\n\n/**\n * @param {import('../../types').Options} config\n */\nexport function createRemote (config) {\n const client = new Client(config)\n\n return {\n add: createAdd(client),\n ls: createLs(client),\n rm: createRm(client),\n rmAll: createRmAll(client),\n service: createService(config)\n }\n}\n", "import { createAddAll } from './add-all.js'\nimport { createAdd } from './add.js'\nimport { createLs } from './ls.js'\nimport { createRmAll } from './rm-all.js'\nimport { createRm } from './rm.js'\nimport { createRemote } from './remote/index.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createPin (config) {\n return {\n addAll: createAddAll(config),\n add: createAdd(config),\n ls: createLs(config),\n rmAll: createRmAll(config),\n rm: createRm(config),\n remote: createRemote(config)\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { base64url } from 'multiformats/bases/base64'\n\n/* HTTP RPC:\n * - wraps binary data in multibase. base64url is used to avoid issues\n * when a binary data is passed as search param in URL.\n * Historical context: https://github.com/ipfs/go-ipfs/issues/7939\n * Multibase wrapping introduced in: https://github.com/ipfs/go-ipfs/pull/8183\n */\n\n/**\n * @param {Array} strings\n * @returns {Array} strings\n */\nconst rpcArrayToTextArray = strings => {\n if (Array.isArray(strings)) {\n return strings.map(rpcToText)\n }\n return strings\n}\n\n/**\n * @param {string} mb\n * @returns {string}\n */\nconst rpcToText = mb => uint8ArrayToString(rpcToBytes(mb))\n\n/**\n * @param {string} mb\n * @returns {Uint8Array}\n */\nconst rpcToBytes = mb => base64url.decode(mb)\n\n/**\n * @param {string} mb\n * @returns {bigint}\n */\nconst rpcToBigInt = mb => BigInt(`0x${uint8ArrayToString(base64url.decode(mb), 'base16')}`)\n\n/**\n * @param {string} text\n * @returns {string}\n */\nconst textToUrlSafeRpc = text => base64url.encode(uint8ArrayFromString(text))\n\nexport { rpcArrayToTextArray, rpcToText, rpcToBytes, rpcToBigInt, textToUrlSafeRpc }\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { rpcArrayToTextArray } from '../lib/http-rpc-wire-format.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n */\n\nexport const createLs = configure(api => {\n /**\n * @type {PubsubAPI[\"ls\"]}\n */\n async function ls (options = {}) {\n const { Strings } = await (await api.post('pubsub/ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })).json()\n\n return rpcArrayToTextArray(Strings) || []\n }\n return ls\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { textToUrlSafeRpc } from '../lib/http-rpc-wire-format.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n */\n\nexport const createPeers = configure(api => {\n /**\n * @type {PubsubAPI[\"peers\"]}\n */\n async function peers (topic, options = {}) {\n const res = await api.post('pubsub/peers', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: textToUrlSafeRpc(topic),\n ...options\n }),\n headers: options.headers\n })\n\n const { Strings } = await res.json()\n\n return Strings || []\n }\n return peers\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { abortSignal } from '../lib/abort-signal.js'\nimport { textToUrlSafeRpc } from '../lib/http-rpc-wire-format.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n */\n\nexport const createPublish = configure(api => {\n /**\n * @type {PubsubAPI[\"publish\"]}\n */\n async function publish (topic, data, options = {}) {\n const searchParams = toUrlSearchParams({\n arg: textToUrlSafeRpc(topic),\n ...options\n })\n\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n\n const res = await api.post('pubsub/pub', {\n signal,\n searchParams,\n ...(\n await multipartRequest([data], controller, options.headers)\n )\n })\n\n await res.text()\n }\n return publish\n})\n", "import { logger } from '@libp2p/logger'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { textToUrlSafeRpc, rpcToText, rpcToBytes, rpcToBigInt } from '../lib/http-rpc-wire-format.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\nconst log = logger('ipfs-http-client:pubsub:subscribe')\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('@libp2p/interface-pubsub').Message} Message\n * @typedef {(err: Error, fatal: boolean, msg?: Message) => void} ErrorHandlerFn\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n * @typedef {import('../types').Options} Options\n */\n\n/**\n * @param {Options} options\n * @param {import('./subscription-tracker').SubscriptionTracker} subsTracker\n */\nexport const createSubscribe = (options, subsTracker) => {\n return configure((api) => {\n /**\n * @type {PubsubAPI[\"subscribe\"]}\n */\n async function subscribe (topic, handler, options = {}) { // eslint-disable-line require-await\n options.signal = subsTracker.subscribe(topic, handler, options.signal)\n\n /** @type {(value?: any) => void} */\n let done\n /** @type {(error: Error) => void} */\n let fail\n\n const result = new Promise((resolve, reject) => {\n done = resolve\n fail = reject\n })\n\n // In Firefox, the initial call to fetch does not resolve until some data\n // is received. If this doesn't happen within 1 second assume success\n const ffWorkaround = setTimeout(() => done(), 1000)\n\n // Do this async to not block Firefox\n api.post('pubsub/sub', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: textToUrlSafeRpc(topic),\n ...options\n }),\n headers: options.headers\n })\n .catch((err) => {\n // Initial subscribe fail, ensure we clean up\n subsTracker.unsubscribe(topic, handler)\n\n fail(err)\n })\n .then((response) => {\n clearTimeout(ffWorkaround)\n\n if (!response) {\n // if there was no response, the subscribe failed\n return\n }\n\n readMessages(response, {\n onMessage: (message) => {\n if (!handler) {\n return\n }\n\n if (typeof handler === 'function') {\n handler(message)\n return\n }\n\n if (typeof handler.handleEvent === 'function') {\n handler.handleEvent(message)\n }\n },\n onEnd: () => subsTracker.unsubscribe(topic, handler),\n onError: options.onError\n })\n\n done()\n })\n\n return result\n }\n return subscribe\n })(options)\n}\n\n/**\n * @param {import('ipfs-utils/src/types').ExtendedResponse} response\n * @param {object} options\n * @param {(message: Message) => void} options.onMessage\n * @param {() => void} options.onEnd\n * @param {ErrorHandlerFn} [options.onError]\n */\nasync function readMessages (response, { onMessage, onEnd, onError }) {\n onError = onError || log\n\n try {\n for await (const msg of response.ndjson()) {\n try {\n if (!msg.from) {\n continue\n }\n\n if (msg.from != null && msg.seqno != null) {\n onMessage({\n type: 'signed',\n from: peerIdFromString(msg.from),\n data: rpcToBytes(msg.data),\n sequenceNumber: rpcToBigInt(msg.seqno),\n topic: rpcToText(msg.topicIDs[0]),\n key: rpcToBytes(msg.key ?? 'u'),\n signature: rpcToBytes(msg.signature ?? 'u')\n })\n } else {\n onMessage({\n type: 'unsigned',\n data: rpcToBytes(msg.data),\n topic: rpcToText(msg.topicIDs[0])\n })\n }\n } catch (/** @type {any} */ err) {\n err.message = `Failed to parse pubsub message: ${err.message}`\n onError(err, false, msg) // Not fatal\n }\n }\n } catch (/** @type {any} */ err) {\n if (!isAbortError(err)) {\n onError(err, true) // Fatal\n }\n } finally {\n onEnd()\n }\n}\n\n/**\n * @param {Error & {type?:string}} error\n * @returns {boolean}\n */\nconst isAbortError = error => {\n switch (error.type) {\n case 'aborted':\n return true\n // It is `abort` in Electron instead of `aborted`\n case 'abort':\n return true\n default:\n // FIXME: In testing with Chrome, err.type is undefined (should not be!)\n // Temporarily use the name property instead.\n return error.name === 'AbortError'\n }\n}\n", "\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/pubsub').API} PubsubAPI\n * @typedef {import('../types').Options} Options\n */\n\n/**\n * @param {Options} options\n * @param {import('./subscription-tracker').SubscriptionTracker} subsTracker\n */\nexport const createUnsubscribe = (options, subsTracker) => {\n /**\n * @type {PubsubAPI[\"unsubscribe\"]}\n */\n async function unsubscribe (topic, handler) {\n subsTracker.unsubscribe(topic, handler)\n }\n return unsubscribe\n}\n", "\n/**\n * @typedef {import('@libp2p/interface-pubsub').Message} Message\n * @typedef {import('@libp2p/interfaces/events').EventHandler} MessageHandlerFn\n *\n * @typedef {object} Subscription\n * @property {MessageHandlerFn} handler\n * @property {AbortController} controller\n */\n\nexport class SubscriptionTracker {\n constructor () {\n /** @type {Map} */\n this._subs = new Map()\n }\n\n /**\n * @param {string} topic\n * @param {MessageHandlerFn} handler\n * @param {AbortSignal} [signal]\n */\n subscribe (topic, handler, signal) {\n const topicSubs = this._subs.get(topic) || []\n\n if (topicSubs.find(s => s.handler === handler)) {\n throw new Error(`Already subscribed to ${topic} with this handler`)\n }\n\n // Create controller so a call to unsubscribe can cancel the request\n const controller = new AbortController()\n\n this._subs.set(topic, [{ handler, controller }].concat(topicSubs))\n\n // If there is an external signal, forward the abort event\n if (signal) {\n signal.addEventListener('abort', () => this.unsubscribe(topic, handler))\n }\n\n return controller.signal\n }\n\n /**\n * @param {string} topic\n * @param {MessageHandlerFn} [handler]\n */\n unsubscribe (topic, handler) {\n const subs = this._subs.get(topic) || []\n let unsubs\n\n if (handler) {\n this._subs.set(topic, subs.filter(s => s.handler !== handler))\n unsubs = subs.filter(s => s.handler === handler)\n } else {\n this._subs.set(topic, [])\n unsubs = subs\n }\n\n if (!(this._subs.get(topic) || []).length) {\n this._subs.delete(topic)\n }\n\n unsubs.forEach(s => s.controller.abort())\n }\n}\n", "import { createLs } from './ls.js'\nimport { createPeers } from './peers.js'\nimport { createPublish } from './publish.js'\nimport { createSubscribe } from './subscribe.js'\nimport { createUnsubscribe } from './unsubscribe.js'\nimport { SubscriptionTracker } from './subscription-tracker.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createPubsub (config) {\n const subscriptionTracker = new SubscriptionTracker()\n\n return {\n ls: createLs(config),\n peers: createPeers(config),\n publish: createPublish(config),\n subscribe: createSubscribe(config, subscriptionTracker),\n unsubscribe: createUnsubscribe(config, subscriptionTracker)\n }\n}\n", "import { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/refs').API} RefsAPI\n */\n\nexport const createLocal = configure(api => {\n /**\n * @type {RefsAPI[\"local\"]}\n */\n async function * refsLocal (options = {}) {\n const res = await api.post('refs/local', {\n signal: options.signal,\n transform: objectToCamel,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n yield * res.ndjson()\n }\n return refsLocal\n})\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamel } from '../lib/object-to-camel.js'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { createLocal } from './local.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/refs').API} RefsAPI\n */\n\nexport const createRefs = configure((api, opts) => {\n /**\n * @type {RefsAPI[\"refs\"]}\n */\n const refs = async function * (args, options = {}) {\n /** @type {import('ipfs-core-types/src/utils').IPFSPath[]} */\n const argsArr = Array.isArray(args) ? args : [args]\n\n const res = await api.post('refs', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: argsArr.map(arg => `${arg instanceof Uint8Array ? CID.decode(arg) : arg}`),\n ...options\n }),\n headers: options.headers,\n transform: objectToCamel\n })\n\n yield * res.ndjson()\n }\n\n return Object.assign(refs, {\n local: createLocal(opts)\n })\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/repo').API} RepoAPI\n */\n\nexport const createGc = configure(api => {\n /**\n * @type {RepoAPI[\"gc\"]}\n */\n async function * gc (options = {}) {\n const res = await api.post('repo/gc', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers,\n transform: (res) => {\n return {\n err: res.Error ? new Error(res.Error) : null,\n cid: (res.Key || {})['/'] ? CID.parse(res.Key['/']) : null\n }\n }\n })\n\n yield * res.ndjson()\n }\n return gc\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/repo').API} RepoAPI\n */\n\nexport const createStat = configure(api => {\n /**\n * @type {RepoAPI[\"stat\"]}\n */\n async function stat (options = {}) {\n const res = await api.post('repo/stat', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n const data = await res.json()\n\n return {\n numObjects: BigInt(data.NumObjects),\n repoSize: BigInt(data.RepoSize),\n repoPath: data.RepoPath,\n version: data.Version,\n storageMax: BigInt(data.StorageMax)\n }\n }\n return stat\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/repo').API} RepoAPI\n */\n\nexport const createVersion = configure(api => {\n /**\n * @type {RepoAPI[\"version\"]}\n */\n async function version (options = {}) {\n const res = await (await api.post('repo/version', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })).json()\n\n return res.Version\n }\n return version\n})\n", "import { createGc } from './gc.js'\nimport { createStat } from './stat.js'\nimport { createVersion } from './version.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createRepo (config) {\n return {\n gc: createGc(config),\n stat: createStat(config),\n version: createVersion(config)\n }\n}\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/stats').API} StatsAPI\n */\n\nexport const createBw = configure(api => {\n /**\n * @type {StatsAPI[\"bw\"]}\n */\n async function * bw (options = {}) {\n const res = await api.post('stats/bw', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers,\n transform: (stats) => ({\n totalIn: BigInt(stats.TotalIn),\n totalOut: BigInt(stats.TotalOut),\n rateIn: parseFloat(stats.RateIn),\n rateOut: parseFloat(stats.RateOut)\n })\n })\n\n yield * res.ndjson()\n }\n return bw\n})\n", "import { createStat as createBitswap } from '../bitswap/stat.js'\nimport { createStat as createRepo } from '../repo/stat.js'\nimport { createBw } from './bw.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createStats (config) {\n return {\n bitswap: createBitswap(config),\n repo: createRepo(config),\n bw: createBw(config)\n }\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createAddrs = configure(api => {\n /**\n * @type {SwarmAPI[\"addrs\"]}\n */\n async function addrs (options = {}) {\n const res = await api.post('swarm/addrs', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n /** @type {{ Addrs: Record }} */\n const { Addrs } = await res.json()\n\n return Object.keys(Addrs).map(id => ({\n id: peerIdFromString(id),\n addrs: (Addrs[id] || []).map(a => multiaddr(a))\n }))\n }\n return addrs\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createConnect = configure(api => {\n /**\n * @type {SwarmAPI[\"connect\"]}\n */\n async function connect (addr, options = {}) {\n const res = await api.post('swarm/connect', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n const { Strings } = await res.json()\n\n return Strings || []\n }\n return connect\n})\n", "import { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createDisconnect = configure(api => {\n /**\n * @type {SwarmAPI[\"disconnect\"]}\n */\n async function disconnect (addr, options = {}) {\n const res = await api.post('swarm/disconnect', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: addr,\n ...options\n }),\n headers: options.headers\n })\n const { Strings } = await res.json()\n\n return Strings || []\n }\n return disconnect\n})\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createLocalAddrs = configure(api => {\n /**\n * @type {SwarmAPI[\"localAddrs\"]}\n */\n async function localAddrs (options = {}) {\n const res = await api.post('swarm/addrs/local', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n /** @type {{ Strings: string[] }} */\n const { Strings } = await res.json()\n\n return (Strings || []).map(a => multiaddr(a))\n }\n return localAddrs\n})\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from '../lib/configure.js'\nimport { toUrlSearchParams } from '../lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/swarm').API} SwarmAPI\n */\n\nexport const createPeers = configure(api => {\n /**\n * @type {SwarmAPI[\"peers\"]}\n */\n async function peers (options = {}) {\n const res = await api.post('swarm/peers', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n /** @type {{ Peers: { Peer: string, Addr: string, Muxer?: string, Latency?: string, Streams?: string[], Direction?: 0 | 1 }[] }} */\n const { Peers } = await res.json()\n\n return (Peers || []).map(peer => {\n return {\n addr: multiaddr(peer.Addr),\n peer: peerIdFromString(peer.Peer),\n muxer: peer.Muxer,\n latency: peer.Latency,\n streams: peer.Streams,\n direction: peer.Direction == null ? undefined : peer.Direction === 0 ? 'inbound' : 'outbound'\n }\n })\n }\n return peers\n})\n", "import { createAddrs } from './addrs.js'\nimport { createConnect } from './connect.js'\nimport { createDisconnect } from './disconnect.js'\nimport { createLocalAddrs } from './local-addrs.js'\nimport { createPeers } from './peers.js'\n\n/**\n * @param {import('../types').Options} config\n */\nexport function createSwarm (config) {\n return {\n addrs: createAddrs(config),\n connect: createConnect(config),\n disconnect: createDisconnect(config),\n localAddrs: createLocalAddrs(config),\n peers: createPeers(config)\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { multipartRequest } from 'ipfs-core-utils/multipart-request'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\nimport { abortSignal } from './lib/abort-signal.js'\n\n/**\n * @typedef {import('ipfs-utils/src/types').ProgressFn} IPFSUtilsHttpUploadProgressFn\n * @typedef {import('ipfs-core-types/src/root').AddProgressFn} IPFSCoreAddProgressFn\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n * @typedef {import('ipfs-core-types/src/root').AddResult} AddResult\n */\n\nexport const createAddAll = configure((api) => {\n /**\n * @type {RootAPI[\"addAll\"]}\n */\n async function * addAll (source, options = {}) {\n // allow aborting requests on body errors\n const controller = new AbortController()\n const signal = abortSignal(controller.signal, options.signal)\n const { headers, body, total, parts } =\n await multipartRequest(source, controller, options.headers)\n\n // In browser response body only starts streaming once upload is\n // complete, at which point all the progress updates are invalid. If\n // length of the content is computable we can interpret progress from\n // `{ total, loaded}` passed to `onUploadProgress` and `multipart.total`\n // in which case we disable progress updates to be written out.\n const [progressFn, onUploadProgress] = typeof options.progress === 'function'\n ? createProgressHandler(total, parts, options.progress)\n : [undefined, undefined]\n\n const res = await api.post('add', {\n searchParams: toUrlSearchParams({\n 'stream-channels': true,\n ...options,\n progress: Boolean(progressFn)\n }),\n onUploadProgress,\n signal,\n headers,\n body\n })\n\n for await (let file of res.ndjson()) {\n file = objectToCamel(file)\n\n if (file.hash !== undefined) {\n yield toCoreInterface(file)\n } else if (progressFn) {\n progressFn(file.bytes || 0, file.name)\n }\n }\n }\n return addAll\n})\n\n/**\n * Returns simple progress callback when content length isn't computable or a\n * progress event handler that calculates progress from upload progress events.\n *\n * @param {number} total\n * @param {{name:string, start:number, end:number}[]|null} parts\n * @param {IPFSCoreAddProgressFn} progress\n * @returns {[IPFSCoreAddProgressFn|undefined, IPFSUtilsHttpUploadProgressFn|undefined]}\n */\nconst createProgressHandler = (total, parts, progress) =>\n parts ? [undefined, createOnUploadProgress(total, parts, progress)] : [progress, undefined]\n\n/**\n * Creates a progress handler that interpolates progress from upload progress\n * events and total size of the content that is added.\n *\n * @param {number} size - actual content size\n * @param {{name:string, start:number, end:number}[]} parts\n * @param {IPFSCoreAddProgressFn} progress\n * @returns {IPFSUtilsHttpUploadProgressFn}\n */\nconst createOnUploadProgress = (size, parts, progress) => {\n let index = 0\n const count = parts.length\n return ({ loaded, total }) => {\n // Derive position from the current progress.\n const position = Math.floor(loaded / total * size)\n while (index < count) {\n const { start, end, name } = parts[index]\n // If within current part range report progress and break the loop\n if (position < end) {\n progress(position - start, name)\n break\n // If passed current part range report final byte for the chunk and\n // move to next one.\n } else {\n progress(end - start, name)\n index += 1\n }\n }\n }\n}\n\n/**\n * @param {object} input\n * @param {string} input.name\n * @param {string} input.hash\n * @param {string} input.size\n * @param {string} [input.mode]\n * @param {number} [input.mtime]\n * @param {number} [input.mtimeNsecs]\n */\nfunction toCoreInterface ({ name, hash, size, mode, mtime, mtimeNsecs }) {\n /** @type {AddResult} */\n const output = {\n path: name,\n cid: CID.parse(hash),\n size: parseInt(size)\n }\n\n if (mode != null) {\n output.mode = parseInt(mode, 8)\n }\n\n if (mtime != null) {\n output.mtime = {\n secs: mtime,\n nsecs: mtimeNsecs || 0\n }\n }\n\n return output\n}\n", "import { createAddAll } from './add-all.js'\nimport last from 'it-last'\nimport { configure } from './lib/configure.js'\nimport { normaliseInput } from 'ipfs-core-utils/files/normalise-input-single'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\n/**\n * @param {import('./types').Options} options\n */\nexport function createAdd (options) {\n const all = createAddAll(options)\n return configure(() => {\n /**\n * @type {RootAPI[\"add\"]}\n */\n async function add (input, options = {}) {\n // @ts-expect-error - last may return undefined if source is empty\n return await last(all(normaliseInput(input), options))\n }\n return add\n })(options)\n}\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createCat = configure(api => {\n /**\n * @type {RootAPI[\"cat\"]}\n */\n async function * cat (path, options = {}) {\n const res = await api.post('cat', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path.toString(),\n ...options\n }),\n headers: options.headers\n })\n\n yield * res.iterator()\n }\n\n return cat\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createCommands = configure(api => {\n /**\n * @type {RootAPI[\"commands\"]}\n */\n const commands = async (options = {}) => {\n const res = await api.post('commands', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return res.json()\n }\n return commands\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createDns = configure(api => {\n /**\n * @type {RootAPI[\"dns\"]}\n */\n const dns = async (domain, options = {}) => {\n const res = await api.post('dns', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: domain,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n return data.Path\n }\n\n return dns\n})\n", "import { configure } from './lib/configure.js'\n\nexport const createGetEndpointConfig = configure(api => {\n return () => {\n const url = new URL(api.opts.base || '')\n return {\n host: url.hostname,\n port: url.port,\n protocol: url.protocol,\n pathname: url.pathname,\n 'api-path': url.pathname\n }\n }\n})\n", "import { CID } from 'multiformats/cid'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createGet = configure(api => {\n /**\n * @type {RootAPI[\"get\"]}\n */\n async function * get (path, options = {}) {\n /** @type {Record} */\n const opts = {\n arg: `${path instanceof Uint8Array ? CID.decode(path) : path}`,\n ...options\n }\n\n if (opts.compressionLevel) {\n opts['compression-level'] = opts.compressionLevel\n delete opts.compressionLevel\n }\n\n const res = await api.post('get', {\n signal: options.signal,\n searchParams: toUrlSearchParams(opts),\n headers: options.headers\n })\n\n yield * res.iterator()\n }\n\n return get\n})\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createId = configure(api => {\n /**\n * @type {RootAPI[\"id\"]}\n */\n async function id (options = {}) {\n const res = await api.post('id', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: options.peerId ? options.peerId.toString() : undefined,\n ...options\n }),\n headers: options.headers\n })\n const data = await res.json()\n\n const output = {\n ...objectToCamel(data)\n }\n\n output.id = peerIdFromString(output.id)\n\n if (output.addresses) {\n output.addresses = output.addresses.map((/** @type {string} */ ma) => multiaddr(ma))\n }\n\n // @ts-expect-error server output is not typed\n return output\n }\n return id\n})\n", "import { createId } from './id.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\n/**\n * @param {import('./types').Options} options\n */\nexport const createIsOnline = options => {\n const id = createId(options)\n\n /**\n * @type {RootAPI[\"isOnline\"]}\n */\n async function isOnline (options = {}) {\n const res = await id(options)\n\n return Boolean(res && res.addresses && res.addresses.length)\n }\n return isOnline\n}\n", "import { CID } from 'multiformats/cid'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\nimport { createStat } from './files/stat.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createLs = configure((api, opts) => {\n /**\n * @type {RootAPI[\"ls\"]}\n */\n async function * ls (path, options = {}) {\n const pathStr = `${path instanceof Uint8Array ? CID.decode(path) : path}`\n\n /**\n * @param {*} link\n */\n async function mapLink (link) {\n let hash = link.Hash\n\n if (hash.includes('/')) {\n // the hash is a path, but we need the CID\n const ipfsPath = hash.startsWith('/ipfs/') ? hash : `/ipfs/${hash}`\n const stats = await createStat(opts)(ipfsPath)\n\n hash = stats.cid\n } else {\n hash = CID.parse(hash)\n }\n\n /** @type {import('ipfs-core-types/src/root').IPFSEntry} */\n const entry = {\n name: link.Name,\n path: pathStr + (link.Name ? `/${link.Name}` : ''),\n size: link.Size,\n cid: hash,\n type: typeOf(link)\n }\n\n if (link.Mode) {\n entry.mode = parseInt(link.Mode, 8)\n }\n\n if (link.Mtime !== undefined && link.Mtime !== null) {\n entry.mtime = {\n secs: link.Mtime\n }\n\n if (link.MtimeNsecs !== undefined && link.MtimeNsecs !== null) {\n entry.mtime.nsecs = link.MtimeNsecs\n }\n }\n\n return entry\n }\n\n const res = await api.post('ls', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: pathStr,\n ...options\n }),\n headers: options.headers\n })\n\n for await (let result of res.ndjson()) {\n result = result.Objects\n\n if (!result) {\n throw new Error('expected .Objects in results')\n }\n\n result = result[0]\n if (!result) {\n throw new Error('expected one array in results.Objects')\n }\n\n const links = result.Links\n if (!Array.isArray(links)) {\n throw new Error('expected one array in results.Objects[0].Links')\n }\n\n if (!links.length) {\n // no links, this is a file, yield a single result\n yield mapLink(result)\n\n return\n }\n\n yield * links.map(mapLink)\n }\n }\n return ls\n})\n\n/**\n * @param {any} link\n */\nfunction typeOf (link) {\n switch (link.Type) {\n case 1:\n case 5:\n return 'dir'\n case 2:\n return 'file'\n default:\n return 'file'\n }\n}\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createMount = configure(api => {\n /**\n * @type {RootAPI[\"mount\"]}\n */\n async function mount (options = {}) {\n const res = await api.post('dns', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n return objectToCamel(await res.json())\n }\n return mount\n})\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createPing = configure(api => {\n /**\n * @type {RootAPI[\"ping\"]}\n */\n async function * ping (peerId, options = {}) {\n const res = await api.post('ping', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: `${peerId}`,\n ...options\n }),\n headers: options.headers,\n transform: objectToCamel\n })\n\n yield * res.ndjson()\n }\n return ping\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createResolve = configure(api => {\n /**\n * @type {RootAPI[\"resolve\"]}\n */\n async function resolve (path, options = {}) {\n const res = await api.post('resolve', {\n signal: options.signal,\n searchParams: toUrlSearchParams({\n arg: path,\n ...options\n }),\n headers: options.headers\n })\n const { Path } = await res.json()\n return Path\n }\n return resolve\n})\n", "import { configure } from './lib/configure.js'\nimport errCode from 'err-code'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createStart = configure(api => {\n /**\n * @type {RootAPI[\"start\"]}\n */\n const start = async (options = {}) => {\n throw errCode(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED')\n }\n\n return start\n})\n", "import { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createStop = configure(api => {\n /**\n * @type {RootAPI[\"stop\"]}\n */\n async function stop (options = {}) {\n const res = await api.post('shutdown', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n await res.text()\n }\n return stop\n})\n", "import { objectToCamel } from './lib/object-to-camel.js'\nimport { configure } from './lib/configure.js'\nimport { toUrlSearchParams } from './lib/to-url-search-params.js'\n\n/**\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('ipfs-core-types/src/root').API} RootAPI\n */\n\nexport const createVersion = configure(api => {\n /**\n * @type {RootAPI[\"version\"]}\n */\n async function version (options = {}) {\n const res = await api.post('version', {\n signal: options.signal,\n searchParams: toUrlSearchParams(options),\n headers: options.headers\n })\n\n // @ts-expect-error server output is not typed\n return {\n ...objectToCamel(await res.json()),\n 'ipfs-http-client': '1.0.0'\n }\n }\n\n return version\n})\n", "/* eslint-env browser */\n\nimport { Multibases } from 'ipfs-core-utils/multibases'\nimport { Multicodecs } from 'ipfs-core-utils/multicodecs'\nimport { Multihashes } from 'ipfs-core-utils/multihashes'\nimport * as dagPB from '@ipld/dag-pb'\nimport * as dagCBOR from '@ipld/dag-cbor'\nimport * as dagJSON from '@ipld/dag-json'\nimport * as dagJOSE from 'dag-jose'\nimport { identity } from 'multiformats/hashes/identity'\nimport { bases, hashes, codecs } from 'multiformats/basics'\nimport { createBitswap } from './bitswap/index.js'\nimport { createBlock } from './block/index.js'\nimport { createBootstrap } from './bootstrap/index.js'\nimport { createConfig } from './config/index.js'\nimport { createDag } from './dag/index.js'\nimport { createDht } from './dht/index.js'\nimport { createDiag } from './diag/index.js'\nimport { createFiles } from './files/index.js'\nimport { createKey } from './key/index.js'\nimport { createLog } from './log/index.js'\nimport { createName } from './name/index.js'\nimport { createObject } from './object/index.js'\nimport { createPin } from './pin/index.js'\nimport { createPubsub } from './pubsub/index.js'\nimport { createRefs } from './refs/index.js'\nimport { createRepo } from './repo/index.js'\nimport { createStats } from './stats/index.js'\nimport { createSwarm } from './swarm/index.js'\nimport { createAdd } from './add.js'\nimport { createAddAll } from './add-all.js'\nimport { createCat } from './cat.js'\nimport { createCommands } from './commands.js'\nimport { createDns } from './dns.js'\nimport { createGetEndpointConfig } from './get-endpoint-config.js'\nimport { createGet } from './get.js'\nimport { createId } from './id.js'\nimport { createIsOnline } from './is-online.js'\nimport { createLs } from './ls.js'\nimport { createMount } from './mount.js'\nimport { createPing } from './ping.js'\nimport { createResolve } from './resolve.js'\nimport { createStart } from './start.js'\nimport { createStop } from './stop.js'\nimport { createVersion } from './version.js'\nimport globSourceImport from 'ipfs-utils/src/files/glob-source.js'\n\n/**\n * @typedef {import('multiformats/codecs/interface').BlockCodec} BlockCodec\n * @typedef {import('multiformats/hashes/interface').MultihashHasher} MultihashHasher\n * @typedef {import('multiformats/bases/interface').MultibaseCodec} MultibaseCodec\n * @typedef {import('./types').Options} Options\n * @typedef {import('./types').LoadBaseFn} LoadBaseFn\n * @typedef {import('./types').LoadCodecFn} LoadCodecFn\n * @typedef {import('./types').LoadHasherFn} LoadHasherFn\n * @typedef {import('./types').IPLDOptions} IPLDOptions\n * @typedef {import('./types').HTTPClientExtraOptions} HTTPClientExtraOptions\n * @typedef {import('./types').EndpointConfig} EndpointConfig\n * @typedef {import('./types').IPFSHTTPClient} IPFSHTTPClient\n */\n\n/**\n * @param {Options} options\n */\nexport function create (options = {}) {\n /**\n * @type {BlockCodec}\n */\n const id = {\n name: identity.name,\n code: identity.code,\n encode: (id) => id,\n decode: (id) => id\n }\n\n /** @type {MultibaseCodec[]} */\n const multibaseCodecs = Object.values(bases);\n\n (options.ipld && options.ipld.bases ? options.ipld.bases : []).forEach(base => multibaseCodecs.push(base))\n\n const multibases = new Multibases({\n bases: multibaseCodecs,\n loadBase: options.ipld && options.ipld.loadBase\n })\n\n /** @type {BlockCodec[]} */\n const blockCodecs = Object.values(codecs);\n\n [dagPB, dagCBOR, dagJSON, dagJOSE, id].concat((options.ipld && options.ipld.codecs) || []).forEach(codec => blockCodecs.push(codec))\n\n const multicodecs = new Multicodecs({\n codecs: blockCodecs,\n loadCodec: options.ipld && options.ipld.loadCodec\n })\n\n /** @type {MultihashHasher[]} */\n const multihashHashers = Object.values(hashes);\n\n (options.ipld && options.ipld.hashers ? options.ipld.hashers : []).forEach(hasher => multihashHashers.push(hasher))\n\n const multihashes = new Multihashes({\n hashers: multihashHashers,\n loadHasher: options.ipld && options.ipld.loadHasher\n })\n\n /** @type {IPFSHTTPClient} */\n const client = {\n add: createAdd(options),\n addAll: createAddAll(options),\n bitswap: createBitswap(options),\n block: createBlock(options),\n bootstrap: createBootstrap(options),\n cat: createCat(options),\n commands: createCommands(options),\n config: createConfig(options),\n dag: createDag(multicodecs, options),\n dht: createDht(options),\n diag: createDiag(options),\n dns: createDns(options),\n files: createFiles(options),\n get: createGet(options),\n getEndpointConfig: createGetEndpointConfig(options),\n id: createId(options),\n isOnline: createIsOnline(options),\n key: createKey(options),\n log: createLog(options),\n ls: createLs(options),\n mount: createMount(options),\n name: createName(options),\n object: createObject(multicodecs, options),\n pin: createPin(options),\n ping: createPing(options),\n pubsub: createPubsub(options),\n refs: createRefs(options),\n repo: createRepo(options),\n resolve: createResolve(options),\n start: createStart(options),\n stats: createStats(options),\n stop: createStop(options),\n swarm: createSwarm(options),\n version: createVersion(options),\n bases: multibases,\n codecs: multicodecs,\n hashers: multihashes\n }\n\n return client\n}\n\nexport { CID } from 'multiformats/cid'\nexport { multiaddr } from '@multiformats/multiaddr'\nexport { default as urlSource } from 'ipfs-utils/src/files/url-source.js'\nexport const globSource = globSourceImport\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { AbortError } from 'abortable-iterator'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport * as mafmt from '@multiformats/mafmt'\nimport { CODE_CIRCUIT } from './constants.js'\nimport { createListener } from './listener.js'\nimport { toMultiaddrConnection } from './socket-to-conn.js'\nimport { cleanMultiaddr, cleanUrlSIO } from './utils.js'\nimport { WebRTCInitiator } from '@libp2p/webrtc-peer'\nimport randomBytes from 'iso-random-stream/src/random.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { symbol } from '@libp2p/interface-transport'\nimport type { WRTC, WebRTCInitiatorInit, WebRTCReceiver, WebRTCReceiverInit } from '@libp2p/webrtc-peer'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Transport, Listener, DialOptions, CreateListenerOptions } from '@libp2p/interface-transport'\nimport type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport type { WebRTCStarSocket, HandshakeSignal } from '@libp2p/webrtc-star-protocol'\nimport { symbol as peerDiscoverySymbol } from '@libp2p/interface-peer-discovery'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst webrtcSupport = 'RTCPeerConnection' in globalThis\nconst log = logger('libp2p:webrtc-star')\n\nconst noop = () => {}\n\nexport class WebRTCStarDiscovery extends EventEmitter implements PeerDiscovery, Startable {\n private started = false\n\n get [peerDiscoverySymbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/webrtc-star-discovery'\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n dispatchEvent (event: CustomEvent) {\n if (!this.isStarted()) {\n return false\n }\n\n return super.dispatchEvent(event)\n }\n}\n\nexport interface WebRTCStarInit {\n wrtc?: WRTC\n}\n\nexport interface WebRTCStarDialOptions extends DialOptions {\n channelOptions?: WebRTCInitiatorInit\n}\n\nexport interface WebRTCStarListenerOptions extends CreateListenerOptions, WebRTCInitiatorInit {\n channelOptions?: WebRTCReceiverInit\n}\n\nexport interface SignalServerServerEvents {\n 'error': CustomEvent\n 'listening': CustomEvent\n 'peer': CustomEvent\n 'connection': CustomEvent\n 'disconnect': CustomEvent\n 'reconnect': CustomEvent\n}\n\nexport interface SignalServer extends EventEmitter {\n signallingAddr: Multiaddr\n socket: WebRTCStarSocket\n connections: MultiaddrConnection[]\n channels: Map\n pendingSignals: Map\n close: () => Promise\n}\n\nexport interface WebRTCStarComponents {\n peerId: PeerId\n}\n\n/**\n * @class WebRTCStar\n */\nexport class WebRTCStar implements Transport {\n public wrtc?: WRTC\n public discovery: () => PeerDiscovery & Startable\n public sigServers: Map\n private readonly _discovery: WebRTCStarDiscovery\n public peerId?: PeerId\n\n constructor (init?: WebRTCStarInit) {\n if (init?.wrtc != null) {\n this.wrtc = init.wrtc\n }\n\n // Keep Signalling references\n this.sigServers = new Map()\n\n // Discovery\n this._discovery = new WebRTCStarDiscovery()\n this.discovery = () => this._discovery\n this.peerDiscovered = this.peerDiscovered.bind(this)\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/webrtc-star'\n }\n\n async dial (ma: Multiaddr, options: WebRTCStarDialOptions) {\n const rawConn = await this._connect(ma, options)\n const maConn = toMultiaddrConnection(rawConn, { remoteAddr: ma, signal: options.signal })\n log('new outbound connection %s', maConn.remoteAddr)\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: WebRTCStarDialOptions) {\n if (options.signal?.aborted === true) {\n throw new AbortError()\n }\n\n const channelOptions = {\n ...(options.channelOptions ?? {})\n }\n\n // Use custom WebRTC implementation\n if (this.wrtc != null) {\n channelOptions.wrtc = this.wrtc\n }\n\n const cOpts = ma.toOptions()\n const intentId = uint8ArrayToString(randomBytes(36), 'hex')\n\n return await new Promise((resolve, reject) => {\n const sio = this.sigServers.get(cleanUrlSIO(ma))\n\n if (sio?.socket == null) {\n return reject(errcode(new Error('unknown signal server to use'), 'ERR_UNKNOWN_SIGNAL_SERVER'))\n }\n\n let connected: boolean = false\n\n log('dialing %s:%s', cOpts.host, cOpts.port)\n const channel = new WebRTCInitiator(channelOptions)\n\n const onError = (evt: CustomEvent) => {\n const err = evt.detail\n\n if (!connected) {\n const msg = `connection error ${cOpts.host}:${cOpts.port}: ${err.message}`\n log.error(msg)\n done(err)\n }\n }\n\n const onReady = () => {\n connected = true\n\n log('connection opened %s:%s', cOpts.host, cOpts.port)\n done()\n }\n\n const onAbort = () => {\n log.error('connection aborted %s:%s', cOpts.host, cOpts.port)\n channel.close().finally(() => {\n done(new AbortError())\n })\n }\n\n const done = (err?: Error) => {\n channel.removeEventListener('ready', onReady)\n options.signal?.removeEventListener('abort', onAbort)\n\n if (err == null) {\n resolve(channel)\n } else {\n reject(err)\n }\n }\n\n channel.addEventListener('ready', onReady, {\n once: true\n })\n channel.addEventListener('close', () => {\n channel.removeEventListener('error', onError)\n })\n options.signal?.addEventListener('abort', onAbort)\n\n channel.addEventListener('signal', (evt) => {\n const signal = evt.detail\n\n sio.socket.emit('ss-handshake', {\n intentId: intentId,\n srcMultiaddr: sio.signallingAddr.toString(),\n dstMultiaddr: ma.toString(),\n signal: signal\n })\n })\n\n sio.socket.on('ws-handshake', (offer) => {\n if (offer.intentId === intentId && offer.err != null) {\n channel.close().finally(() => {\n reject(errcode(new Error(offer.err), 'ERR_SIGNALLING_FAILED'))\n })\n }\n\n if (offer.intentId !== intentId || offer.answer == null || channel.closed) {\n return\n }\n\n channel.handleSignal(offer.signal)\n })\n })\n }\n\n /**\n * Creates a WebrtcStar 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: WebRTCStarListenerOptions): Listener {\n if (!webrtcSupport && this.wrtc == null) {\n throw errcode(new Error('no WebRTC support'), 'ERR_NO_WEBRTC_SUPPORT')\n }\n\n options.channelOptions = options.channelOptions ?? {}\n\n if (this.wrtc != null) {\n options.channelOptions.wrtc = this.wrtc\n }\n\n if (this.peerId == null) {\n throw errcode(new Error('PeerId not set'), 'ERR_MISSING_PEER_ID')\n }\n\n return createListener(options.upgrader, options.handler ?? noop, this.peerId, this, options)\n }\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid TCP addresses\n */\n filter (multiaddrs: Multiaddr[]) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n return mafmt.WebRTCStar.matches(ma)\n })\n }\n\n peerDiscovered (maStr: string) {\n log('peer discovered: %s', maStr)\n maStr = cleanMultiaddr(maStr)\n\n const ma = multiaddr(maStr)\n const peerIdStr = ma.getPeerId()\n\n if (peerIdStr == null) {\n return\n }\n\n const peerId = peerIdFromString(peerIdStr)\n\n this._discovery.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: [ma],\n protocols: []\n }\n }))\n }\n}\n", "\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n", "\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\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", "import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS\n)\n\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(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = () => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction) {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\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\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr) {\n let ma: Multiaddr\n\n try {\n ma = multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches: matches,\n partialMatch: partialMatch\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { connect, ManagerOptions, SocketOptions } from 'socket.io-client'\nimport pDefer from 'p-defer'\nimport { WebRTCReceiver } from '@libp2p/webrtc-peer'\nimport { toMultiaddrConnection } from './socket-to-conn.js'\nimport { cleanUrlSIO } from './utils.js'\nimport { CODE_P2P } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Upgrader, ConnectionHandler, Listener, ListenerEvents } from '@libp2p/interface-transport'\nimport type { WebRTCStar, WebRTCStarListenerOptions, SignalServer, SignalServerServerEvents } from './transport.js'\nimport type { WebRTCReceiverInit } from '@libp2p/webrtc-peer'\nimport type { WebRTCStarSocket, HandshakeSignal } from '@libp2p/webrtc-star-protocol'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\n\nconst log = logger('libp2p:webrtc-star:listener')\n\nconst sioOptions: Partial = {\n transports: ['websocket'],\n path: '/socket.io-next/' // This should be removed when socket.io@2 support is removed\n}\n\nclass SigServer extends EventEmitter implements SignalServer {\n public signallingAddr: Multiaddr\n public socket: WebRTCStarSocket\n public connections: MultiaddrConnection[]\n public channels: Map\n public pendingSignals: Map\n\n private readonly upgrader: Upgrader\n private readonly handler: ConnectionHandler\n private readonly channelOptions?: WebRTCReceiverInit\n\n constructor (signallingUrl: string, signallingAddr: Multiaddr, upgrader: Upgrader, handler: ConnectionHandler, channelOptions?: WebRTCReceiverInit) {\n super()\n\n this.signallingAddr = signallingAddr\n this.socket = connect(signallingUrl, sioOptions)\n this.connections = []\n this.channels = new Map()\n this.pendingSignals = new Map()\n\n this.upgrader = upgrader\n this.handler = handler\n this.channelOptions = channelOptions\n\n this.handleWsHandshake = this.handleWsHandshake.bind(this)\n\n let previouslyConnected = false\n\n this.socket.on('connect_error', err => {\n // @ts-expect-error `.type` is missing from the types\n if (previouslyConnected && err.type === 'TransportError') {\n // if we've had an open connection before, and this is a\n // transport error, let socket.io's reconnect logic take over\n return\n }\n\n this.dispatchEvent(new CustomEvent('error', {\n detail: err\n }))\n })\n this.socket.on('error', (err: Error) => {\n this.dispatchEvent(new CustomEvent('error', {\n detail: err\n }))\n })\n this.socket.on('ws-handshake', this.handleWsHandshake)\n this.socket.on('ws-peer', (maStr) => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: maStr\n }))\n })\n this.socket.on('connect', () => {\n this.socket.emit('ss-join', this.signallingAddr.toString())\n\n if (previouslyConnected) {\n this.dispatchEvent(new CustomEvent('reconnect'))\n }\n })\n this.socket.once('connect', () => {\n // make sure we can reconnect in future\n previouslyConnected = true\n this.dispatchEvent(new CustomEvent('listening'))\n })\n this.socket.on('disconnect', () => {\n this.dispatchEvent(new CustomEvent('disconnect'))\n })\n }\n\n _createChannel (intentId: string, srcMultiaddr: string, dstMultiaddr: string) {\n const channelOptions: WebRTCReceiverInit = {\n ...this.channelOptions\n }\n\n const channel = new WebRTCReceiver(channelOptions)\n\n const onError = (evt: CustomEvent) => {\n const err = evt.detail\n\n log.error('incoming connection errored', err)\n }\n\n channel.addEventListener('error', onError)\n channel.addEventListener('close', () => {\n channel.removeEventListener('error', onError)\n }, {\n once: true\n })\n\n channel.addEventListener('signal', (evt) => {\n const signal = evt.detail\n\n this.socket.emit('ss-handshake', {\n intentId,\n srcMultiaddr,\n dstMultiaddr,\n answer: true,\n signal\n })\n })\n\n channel.addEventListener('ready', () => {\n const maConn = toMultiaddrConnection(channel, { remoteAddr: this.signallingAddr })\n log('new inbound connection %s', maConn.remoteAddr)\n\n try {\n this.upgrader.upgradeInbound(maConn)\n .then(conn => {\n log('inbound connection %s upgraded', maConn.remoteAddr)\n\n this.connections.push(maConn)\n\n const untrackConn = () => {\n this.connections = this.connections.filter(c => c !== maConn)\n this.channels.delete(intentId)\n this.pendingSignals.delete(intentId)\n }\n\n channel.addEventListener('close', untrackConn, {\n once: true\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: conn\n }))\n this.handler(conn)\n })\n .catch(err => {\n log.error('inbound connection failed to upgrade', err)\n maConn.close().catch(err => {\n log.error('inbound connection failed to close after failing to upgrade', err)\n })\n })\n } catch (err: any) {\n log.error('inbound connection failed to upgrade', err)\n maConn.close().catch(err => {\n log.error('inbound connection failed to close after failing to upgrade', err)\n })\n }\n }, {\n once: true\n })\n\n return channel\n }\n\n handleWsHandshake (offer: HandshakeSignal) {\n log('incoming handshake. signal type \"%s\" is answer %s', offer.signal.type, offer.answer)\n\n if (offer.answer === true || offer.err != null || offer.intentId == null) {\n return\n }\n\n const intentId = offer.intentId\n let pendingSignals = this.pendingSignals.get(intentId)\n\n if (pendingSignals == null) {\n pendingSignals = []\n this.pendingSignals.set(intentId, pendingSignals)\n }\n\n pendingSignals.push(offer)\n\n let channel = this.channels.get(intentId)\n\n if (channel == null) {\n if (offer.signal.type !== 'offer') {\n log('handshake is not an offer and channel does not exist, buffering until we receive an offer')\n return\n }\n\n log('creating new channel to handle offer handshake')\n channel = this._createChannel(offer.intentId, offer.srcMultiaddr, offer.dstMultiaddr)\n this.channels.set(intentId, channel)\n } else {\n log('channel already exists, using it to handle handshake')\n }\n\n while (pendingSignals.length > 0) {\n const handshake = pendingSignals.shift()\n\n if (handshake?.signal != null) {\n channel.handleSignal(handshake.signal)\n }\n }\n }\n\n async close () {\n // Close listener\n this.socket.emit('ss-leave', this.signallingAddr.toString())\n this.socket.removeAllListeners()\n this.socket.close()\n\n await Promise.all([\n ...this.connections.map(async maConn => await maConn.close()),\n ...Array.from(this.channels.values()).map(async channel => await channel.close())\n ])\n\n this.dispatchEvent(new CustomEvent('close'))\n }\n}\n\nclass WebRTCListener extends EventEmitter implements Listener {\n private listeningAddr?: Multiaddr\n private signallingUrl?: string\n private readonly upgrader: Upgrader\n private readonly handler: ConnectionHandler\n private readonly peerId: PeerId\n private readonly transport: WebRTCStar\n private readonly options: WebRTCStarListenerOptions\n\n constructor (upgrader: Upgrader, handler: ConnectionHandler, peerId: PeerId, transport: WebRTCStar, options: WebRTCStarListenerOptions) {\n super()\n\n this.upgrader = upgrader\n this.handler = handler\n this.peerId = peerId\n this.transport = transport\n this.options = options\n }\n\n async listen (ma: Multiaddr) {\n // Should only be used if not already listening\n if (this.listeningAddr != null) {\n throw errCode(new Error('listener already in use'), 'ERR_ALREADY_LISTENING')\n }\n\n const defer = pDefer() // eslint-disable-line @typescript-eslint/no-invalid-void-type\n\n // Should be kept unmodified\n this.listeningAddr = ma\n\n let signallingAddr: Multiaddr\n if (!ma.protoCodes().includes(CODE_P2P)) {\n signallingAddr = ma.encapsulate(`/p2p/${this.peerId.toString()}`)\n } else {\n signallingAddr = ma\n }\n\n const signallingUrl = this.signallingUrl = cleanUrlSIO(ma)\n\n log('connecting to signalling server on: %s', this.signallingUrl)\n const server: SignalServer = new SigServer(this.signallingUrl, signallingAddr, this.upgrader, this.handler, this.options.channelOptions)\n server.addEventListener('error', (evt) => {\n const err = evt.detail\n\n log('error connecting to signalling server %o', err)\n server.close().catch(err => {\n log.error('error closing server after error', err)\n })\n defer.reject(err)\n })\n server.addEventListener('listening', () => {\n log('connected to signalling server')\n this.dispatchEvent(new CustomEvent('listening'))\n defer.resolve()\n })\n server.addEventListener('peer', (evt) => {\n this.transport.peerDiscovered(evt.detail)\n })\n server.addEventListener('connection', (evt) => {\n const conn = evt.detail\n\n if (conn.remoteAddr == null) {\n try {\n conn.remoteAddr = ma.decapsulateCode(CODE_P2P).encapsulate(`/p2p/${conn.remotePeer.toString()}`)\n } catch (err) {\n log.error('could not determine remote address', err)\n }\n }\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: conn\n }))\n })\n server.addEventListener('disconnect', () => {\n // Ensure we error if we try to dial while we are disconnected from\n // the signalling server\n this.transport.sigServers.delete(signallingUrl)\n })\n server.addEventListener('reconnect', () => {\n // We can dial via the signalling server again\n this.transport.sigServers.set(signallingUrl, server)\n })\n\n // Store listen and signal reference addresses\n this.transport.sigServers.set(this.signallingUrl, server)\n\n return await defer.promise\n }\n\n async close () {\n if (this.signallingUrl != null) {\n const server = this.transport.sigServers.get(this.signallingUrl)\n\n if (server != null) {\n await server.close()\n this.transport.sigServers.delete(this.signallingUrl)\n }\n }\n\n this.dispatchEvent(new CustomEvent('close'))\n\n // Reset state\n this.listeningAddr = undefined\n }\n\n getAddrs () {\n if (this.listeningAddr != null) {\n return [\n this.listeningAddr\n ]\n }\n\n return []\n }\n}\n\nexport function createListener (upgrader: Upgrader, handler: ConnectionHandler, peerId: PeerId, transport: WebRTCStar, options: WebRTCStarListenerOptions) {\n return new WebRTCListener(upgrader, handler, peerId, transport, options)\n}\n", "const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n", "import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n", "// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nexport const decode = (base64) => {\n let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n", "import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"./contrib/base64-arraybuffer.js\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n", "import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n", "/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n", "export const globalThisShim = (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n", "import { globalThisShim as globalThis } from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = globalThis.setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = globalThis.clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = globalThis.setTimeout.bind(globalThis);\n obj.clearTimeoutFn = globalThis.clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n", "import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} opts - options\n * @protected\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n */\n open() {\n this.readyState = \"opening\";\n this.doOpen();\n return this;\n }\n /**\n * Closes the transport.\n */\n close() {\n if (this.readyState === \"opening\" || this.readyState === \"open\") {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n */\n send(packets) {\n if (this.readyState === \"open\") {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n /**\n * Pauses the transport, in order not to lose packets during an upgrade.\n *\n * @param onPause\n */\n pause(onPause) { }\n}\n", "// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n", "// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n", "// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n", "// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nexport function XHR(opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n", "import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport { XHR as XMLHttpRequest } from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false,\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @package\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @protected\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} onPause - callback upon buffers are flushed and transport is paused\n * @package\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @private\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @protected\n */\n onData(data) {\n const callback = (packet) => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @protected\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} packets - data packets\n * @protected\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, (data) => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data,\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @package\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @package\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n", "import { globalThisShim as globalThis } from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return (cb) => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n", "import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket, } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @param {Object} opts - connection options\n * @protected\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n get name() {\n return \"websocket\";\n }\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = (closeEvent) => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent,\n });\n this.ws.onmessage = (ev) => this.onData(ev.data);\n this.ws.onerror = (e) => this.onError(\"websocket error\", e);\n }\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, (data) => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @private\n */\n check() {\n return !!WebSocket;\n }\n}\n", "import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling,\n};\n", "// imported from https://github.com/galkn/parseuri\n/**\n * Parses a URI\n *\n * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.\n *\n * See:\n * - https://developer.mozilla.org/en-US/docs/Web/API/URL\n * - https://caniuse.com/url\n * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B\n *\n * History of the parse() method:\n * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c\n * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3\n * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@\\/?#]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@\\/?#]*)(?::([^:@\\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.slice(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.slice(-1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n", "import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri - uri or options\n * @param {Object} opts - options\n */\n constructor(uri, opts = {}) {\n super();\n this.writeBuffer = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n addTrailingSlash: true,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024,\n },\n transportOptions: {},\n closeOnBeforeunload: true,\n }, opts);\n this.opts.path =\n this.opts.path.replace(/\\/$/, \"\") +\n (this.opts.addTrailingSlash ? \"/\" : \"\");\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n this.beforeunloadEventListener = () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n };\n addEventListener(\"beforeunload\", this.beforeunloadEventListener, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\",\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} name - transport name\n * @return {Transport}\n * @private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port,\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", (reason) => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} name - transport name\n * @private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", (msg) => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = (err) => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState && this.opts.upgrade) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} msg - message.\n * @param {Object} options.\n * @param {Function} callback function.\n * @return {Socket} for chaining.\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} type: packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} fn - callback function.\n * @private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options,\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"beforeunload\", this.beforeunloadEventListener, false);\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} upgrades - server upgrades\n * @private\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n", "import { Socket } from \"./socket.js\";\nexport { Socket };\nexport const protocol = Socket.protocol;\nexport { Transport } from \"./transport.js\";\nexport { transports } from \"./transports/index.js\";\nexport { installTimerFunctions } from \"./util.js\";\nexport { parse } from \"./contrib/parseuri.js\";\nexport { nextTick } from \"./transports/websocket-constructor.js\";\n", "import { parse } from \"engine.io-client\";\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n * Defaults to window.location.\n * @public\n */\nexport function url(uri, path = \"\", loc) {\n let obj = uri;\n // default to window.location\n loc = loc || (typeof location !== \"undefined\" && location);\n if (null == uri)\n uri = loc.protocol + \"//\" + loc.host;\n // relative path support\n if (typeof uri === \"string\") {\n if (\"/\" === uri.charAt(0)) {\n if (\"/\" === uri.charAt(1)) {\n uri = loc.protocol + uri;\n }\n else {\n uri = loc.host + uri;\n }\n }\n if (!/^(https?|wss?):\\/\\//.test(uri)) {\n if (\"undefined\" !== typeof loc) {\n uri = loc.protocol + \"//\" + uri;\n }\n else {\n uri = \"https://\" + uri;\n }\n }\n // parse\n obj = parse(uri);\n }\n // make sure we treat `localhost:80` and `localhost` equally\n if (!obj.port) {\n if (/^(http|ws)$/.test(obj.protocol)) {\n obj.port = \"80\";\n }\n else if (/^(http|ws)s$/.test(obj.protocol)) {\n obj.port = \"443\";\n }\n }\n obj.path = obj.path || \"/\";\n const ipv6 = obj.host.indexOf(\":\") !== -1;\n const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n // define unique id\n obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n // define href\n obj.href =\n obj.protocol +\n \"://\" +\n host +\n (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n return obj;\n}\n", "import { Emitter } from \"@socket.io/component-emitter\";\nimport { deconstructPacket, reconstructPacket } from \"./binary.js\";\nimport { isBinary, hasBinary } from \"./is-binary.js\";\n/**\n * Protocol version.\n *\n * @public\n */\nexport const protocol = 5;\nexport var PacketType;\n(function (PacketType) {\n PacketType[PacketType[\"CONNECT\"] = 0] = \"CONNECT\";\n PacketType[PacketType[\"DISCONNECT\"] = 1] = \"DISCONNECT\";\n PacketType[PacketType[\"EVENT\"] = 2] = \"EVENT\";\n PacketType[PacketType[\"ACK\"] = 3] = \"ACK\";\n PacketType[PacketType[\"CONNECT_ERROR\"] = 4] = \"CONNECT_ERROR\";\n PacketType[PacketType[\"BINARY_EVENT\"] = 5] = \"BINARY_EVENT\";\n PacketType[PacketType[\"BINARY_ACK\"] = 6] = \"BINARY_ACK\";\n})(PacketType || (PacketType = {}));\n/**\n * A socket.io Encoder instance\n */\nexport class Encoder {\n /**\n * Encoder constructor\n *\n * @param {function} replacer - custom replacer to pass down to JSON.parse\n */\n constructor(replacer) {\n this.replacer = replacer;\n }\n /**\n * Encode a packet as a single string if non-binary, or as a\n * buffer sequence, depending on packet type.\n *\n * @param {Object} obj - packet object\n */\n encode(obj) {\n if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {\n if (hasBinary(obj)) {\n return this.encodeAsBinary({\n type: obj.type === PacketType.EVENT\n ? PacketType.BINARY_EVENT\n : PacketType.BINARY_ACK,\n nsp: obj.nsp,\n data: obj.data,\n id: obj.id,\n });\n }\n }\n return [this.encodeAsString(obj)];\n }\n /**\n * Encode packet as string.\n */\n encodeAsString(obj) {\n // first is type\n let str = \"\" + obj.type;\n // attachments if we have them\n if (obj.type === PacketType.BINARY_EVENT ||\n obj.type === PacketType.BINARY_ACK) {\n str += obj.attachments + \"-\";\n }\n // if we have a namespace other than `/`\n // we append it followed by a comma `,`\n if (obj.nsp && \"/\" !== obj.nsp) {\n str += obj.nsp + \",\";\n }\n // immediately followed by the id\n if (null != obj.id) {\n str += obj.id;\n }\n // json data\n if (null != obj.data) {\n str += JSON.stringify(obj.data, this.replacer);\n }\n return str;\n }\n /**\n * Encode packet as 'buffer sequence' by removing blobs, and\n * deconstructing packet into object with placeholders and\n * a list of buffers.\n */\n encodeAsBinary(obj) {\n const deconstruction = deconstructPacket(obj);\n const pack = this.encodeAsString(deconstruction.packet);\n const buffers = deconstruction.buffers;\n buffers.unshift(pack); // add packet info to beginning of data list\n return buffers; // write all the buffers\n }\n}\n/**\n * A socket.io Decoder instance\n *\n * @return {Object} decoder\n */\nexport class Decoder extends Emitter {\n /**\n * Decoder constructor\n *\n * @param {function} reviver - custom reviver to pass down to JSON.stringify\n */\n constructor(reviver) {\n super();\n this.reviver = reviver;\n }\n /**\n * Decodes an encoded packet string into packet JSON.\n *\n * @param {String} obj - encoded packet\n */\n add(obj) {\n let packet;\n if (typeof obj === \"string\") {\n if (this.reconstructor) {\n throw new Error(\"got plaintext data when reconstructing a packet\");\n }\n packet = this.decodeString(obj);\n const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;\n if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {\n packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;\n // binary packet's json\n this.reconstructor = new BinaryReconstructor(packet);\n // no attachments, labeled binary but no binary data to follow\n if (packet.attachments === 0) {\n super.emitReserved(\"decoded\", packet);\n }\n }\n else {\n // non-binary full packet\n super.emitReserved(\"decoded\", packet);\n }\n }\n else if (isBinary(obj) || obj.base64) {\n // raw binary data\n if (!this.reconstructor) {\n throw new Error(\"got binary data when not reconstructing a packet\");\n }\n else {\n packet = this.reconstructor.takeBinaryData(obj);\n if (packet) {\n // received final buffer\n this.reconstructor = null;\n super.emitReserved(\"decoded\", packet);\n }\n }\n }\n else {\n throw new Error(\"Unknown type: \" + obj);\n }\n }\n /**\n * Decode a packet String (JSON data)\n *\n * @param {String} str\n * @return {Object} packet\n */\n decodeString(str) {\n let i = 0;\n // look up type\n const p = {\n type: Number(str.charAt(0)),\n };\n if (PacketType[p.type] === undefined) {\n throw new Error(\"unknown packet type \" + p.type);\n }\n // look up attachments if type binary\n if (p.type === PacketType.BINARY_EVENT ||\n p.type === PacketType.BINARY_ACK) {\n const start = i + 1;\n while (str.charAt(++i) !== \"-\" && i != str.length) { }\n const buf = str.substring(start, i);\n if (buf != Number(buf) || str.charAt(i) !== \"-\") {\n throw new Error(\"Illegal attachments\");\n }\n p.attachments = Number(buf);\n }\n // look up namespace (if any)\n if (\"/\" === str.charAt(i + 1)) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (\",\" === c)\n break;\n if (i === str.length)\n break;\n }\n p.nsp = str.substring(start, i);\n }\n else {\n p.nsp = \"/\";\n }\n // look up id\n const next = str.charAt(i + 1);\n if (\"\" !== next && Number(next) == next) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (null == c || Number(c) != c) {\n --i;\n break;\n }\n if (i === str.length)\n break;\n }\n p.id = Number(str.substring(start, i + 1));\n }\n // look up json data\n if (str.charAt(++i)) {\n const payload = this.tryParse(str.substr(i));\n if (Decoder.isPayloadValid(p.type, payload)) {\n p.data = payload;\n }\n else {\n throw new Error(\"invalid payload\");\n }\n }\n return p;\n }\n tryParse(str) {\n try {\n return JSON.parse(str, this.reviver);\n }\n catch (e) {\n return false;\n }\n }\n static isPayloadValid(type, payload) {\n switch (type) {\n case PacketType.CONNECT:\n return typeof payload === \"object\";\n case PacketType.DISCONNECT:\n return payload === undefined;\n case PacketType.CONNECT_ERROR:\n return typeof payload === \"string\" || typeof payload === \"object\";\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n return Array.isArray(payload) && payload.length > 0;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n return Array.isArray(payload);\n }\n }\n /**\n * Deallocates a parser's resources\n */\n destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n this.reconstructor = null;\n }\n }\n}\n/**\n * A manager of a binary event's 'buffer sequence'. Should\n * be constructed whenever a packet of type BINARY_EVENT is\n * decoded.\n *\n * @param {Object} packet\n * @return {BinaryReconstructor} initialized reconstructor\n */\nclass BinaryReconstructor {\n constructor(packet) {\n this.packet = packet;\n this.buffers = [];\n this.reconPack = packet;\n }\n /**\n * Method to be called when binary data received from connection\n * after a BINARY_EVENT packet.\n *\n * @param {Buffer | ArrayBuffer} binData - the raw binary data received\n * @return {null | Object} returns null if more binary data is expected or\n * a reconstructed packet object if all buffers have been received.\n */\n takeBinaryData(binData) {\n this.buffers.push(binData);\n if (this.buffers.length === this.reconPack.attachments) {\n // done with buffer list\n const packet = reconstructPacket(this.reconPack, this.buffers);\n this.finishedReconstruction();\n return packet;\n }\n return null;\n }\n /**\n * Cleans up binary packet reconstruction variables.\n */\n finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }\n}\n", "const withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj.buffer instanceof ArrayBuffer;\n};\nconst toString = Object.prototype.toString;\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeFile = typeof File === \"function\" ||\n (typeof File !== \"undefined\" &&\n toString.call(File) === \"[object FileConstructor]\");\n/**\n * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.\n *\n * @private\n */\nexport function isBinary(obj) {\n return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||\n (withNativeBlob && obj instanceof Blob) ||\n (withNativeFile && obj instanceof File));\n}\nexport function hasBinary(obj, toJSON) {\n if (!obj || typeof obj !== \"object\") {\n return false;\n }\n if (Array.isArray(obj)) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (hasBinary(obj[i])) {\n return true;\n }\n }\n return false;\n }\n if (isBinary(obj)) {\n return true;\n }\n if (obj.toJSON &&\n typeof obj.toJSON === \"function\" &&\n arguments.length === 1) {\n return hasBinary(obj.toJSON(), true);\n }\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {\n return true;\n }\n }\n return false;\n}\n", "import { isBinary } from \"./is-binary.js\";\n/**\n * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.\n *\n * @param {Object} packet - socket.io event packet\n * @return {Object} with deconstructed packet and list of buffers\n * @public\n */\nexport function deconstructPacket(packet) {\n const buffers = [];\n const packetData = packet.data;\n const pack = packet;\n pack.data = _deconstructPacket(packetData, buffers);\n pack.attachments = buffers.length; // number of binary 'attachments'\n return { packet: pack, buffers: buffers };\n}\nfunction _deconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (isBinary(data)) {\n const placeholder = { _placeholder: true, num: buffers.length };\n buffers.push(data);\n return placeholder;\n }\n else if (Array.isArray(data)) {\n const newData = new Array(data.length);\n for (let i = 0; i < data.length; i++) {\n newData[i] = _deconstructPacket(data[i], buffers);\n }\n return newData;\n }\n else if (typeof data === \"object\" && !(data instanceof Date)) {\n const newData = {};\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n newData[key] = _deconstructPacket(data[key], buffers);\n }\n }\n return newData;\n }\n return data;\n}\n/**\n * Reconstructs a binary packet from its placeholder packet and buffers\n *\n * @param {Object} packet - event packet with placeholders\n * @param {Array} buffers - binary buffers to put in placeholder positions\n * @return {Object} reconstructed packet\n * @public\n */\nexport function reconstructPacket(packet, buffers) {\n packet.data = _reconstructPacket(packet.data, buffers);\n delete packet.attachments; // no longer useful\n return packet;\n}\nfunction _reconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (data && data._placeholder === true) {\n const isIndexValid = typeof data.num === \"number\" &&\n data.num >= 0 &&\n data.num < buffers.length;\n if (isIndexValid) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n }\n else {\n throw new Error(\"illegal attachments\");\n }\n }\n else if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n }\n else if (typeof data === \"object\") {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n }\n return data;\n}\n", "export function on(obj, ev, fn) {\n obj.on(ev, fn);\n return function subDestroy() {\n obj.off(ev, fn);\n };\n}\n", "import { PacketType } from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n connect: 1,\n connect_error: 1,\n disconnect: 1,\n disconnecting: 1,\n // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n newListener: 1,\n removeListener: 1,\n});\n/**\n * A Socket is the fundamental class for interacting with the server.\n *\n * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n * console.log(\"connected\");\n * });\n *\n * // send an event to the server\n * socket.emit(\"foo\", \"bar\");\n *\n * socket.on(\"foobar\", () => {\n * // an event was received from the server\n * });\n *\n * // upon disconnection\n * socket.on(\"disconnect\", (reason) => {\n * console.log(`disconnected due to ${reason}`);\n * });\n */\nexport class Socket extends Emitter {\n /**\n * `Socket` constructor.\n */\n constructor(io, nsp, opts) {\n super();\n /**\n * Whether the socket is currently connected to the server.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n * console.log(socket.connected); // true\n * });\n *\n * socket.on(\"disconnect\", () => {\n * console.log(socket.connected); // false\n * });\n */\n this.connected = false;\n /**\n * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will\n * be transmitted by the server.\n */\n this.recovered = false;\n /**\n * Buffer for packets received before the CONNECT packet\n */\n this.receiveBuffer = [];\n /**\n * Buffer for packets that will be sent once the socket is connected\n */\n this.sendBuffer = [];\n /**\n * The queue of packets to be sent with retry in case of failure.\n *\n * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.\n * @private\n */\n this._queue = [];\n /**\n * A sequence to generate the ID of the {@link QueuedPacket}.\n * @private\n */\n this._queueSeq = 0;\n this.ids = 0;\n this.acks = {};\n this.flags = {};\n this.io = io;\n this.nsp = nsp;\n if (opts && opts.auth) {\n this.auth = opts.auth;\n }\n this._opts = Object.assign({}, opts);\n if (this.io._autoConnect)\n this.open();\n }\n /**\n * Whether the socket is currently disconnected\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n * console.log(socket.disconnected); // false\n * });\n *\n * socket.on(\"disconnect\", () => {\n * console.log(socket.disconnected); // true\n * });\n */\n get disconnected() {\n return !this.connected;\n }\n /**\n * Subscribe to open, close and packet events\n *\n * @private\n */\n subEvents() {\n if (this.subs)\n return;\n const io = this.io;\n this.subs = [\n on(io, \"open\", this.onopen.bind(this)),\n on(io, \"packet\", this.onpacket.bind(this)),\n on(io, \"error\", this.onerror.bind(this)),\n on(io, \"close\", this.onclose.bind(this)),\n ];\n }\n /**\n * Whether the Socket will try to reconnect when its Manager connects or reconnects.\n *\n * @example\n * const socket = io();\n *\n * console.log(socket.active); // true\n *\n * socket.on(\"disconnect\", (reason) => {\n * if (reason === \"io server disconnect\") {\n * // the disconnection was initiated by the server, you need to manually reconnect\n * console.log(socket.active); // false\n * }\n * // else the socket will automatically try to reconnect\n * console.log(socket.active); // true\n * });\n */\n get active() {\n return !!this.subs;\n }\n /**\n * \"Opens\" the socket.\n *\n * @example\n * const socket = io({\n * autoConnect: false\n * });\n *\n * socket.connect();\n */\n connect() {\n if (this.connected)\n return this;\n this.subEvents();\n if (!this.io[\"_reconnecting\"])\n this.io.open(); // ensure open\n if (\"open\" === this.io._readyState)\n this.onopen();\n return this;\n }\n /**\n * Alias for {@link connect()}.\n */\n open() {\n return this.connect();\n }\n /**\n * Sends a `message` event.\n *\n * This method mimics the WebSocket.send() method.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send\n *\n * @example\n * socket.send(\"hello\");\n *\n * // this is equivalent to\n * socket.emit(\"message\", \"hello\");\n *\n * @return self\n */\n send(...args) {\n args.unshift(\"message\");\n this.emit.apply(this, args);\n return this;\n }\n /**\n * Override `emit`.\n * If the event is in `events`, it's emitted normally.\n *\n * @example\n * socket.emit(\"hello\", \"world\");\n *\n * // all serializable datastructures are supported (no need to call JSON.stringify)\n * socket.emit(\"hello\", 1, \"2\", { 3: [\"4\"], 5: Uint8Array.from([6]) });\n *\n * // with an acknowledgement from the server\n * socket.emit(\"hello\", \"world\", (val) => {\n * // ...\n * });\n *\n * @return self\n */\n emit(ev, ...args) {\n if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n throw new Error('\"' + ev.toString() + '\" is a reserved event name');\n }\n args.unshift(ev);\n if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {\n this._addToQueue(args);\n return this;\n }\n const packet = {\n type: PacketType.EVENT,\n data: args,\n };\n packet.options = {};\n packet.options.compress = this.flags.compress !== false;\n // event ack callback\n if (\"function\" === typeof args[args.length - 1]) {\n const id = this.ids++;\n const ack = args.pop();\n this._registerAckCallback(id, ack);\n packet.id = id;\n }\n const isTransportWritable = this.io.engine &&\n this.io.engine.transport &&\n this.io.engine.transport.writable;\n const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);\n if (discardPacket) {\n }\n else if (this.connected) {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n }\n else {\n this.sendBuffer.push(packet);\n }\n this.flags = {};\n return this;\n }\n /**\n * @private\n */\n _registerAckCallback(id, ack) {\n var _a;\n const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;\n if (timeout === undefined) {\n this.acks[id] = ack;\n return;\n }\n // @ts-ignore\n const timer = this.io.setTimeoutFn(() => {\n delete this.acks[id];\n for (let i = 0; i < this.sendBuffer.length; i++) {\n if (this.sendBuffer[i].id === id) {\n this.sendBuffer.splice(i, 1);\n }\n }\n ack.call(this, new Error(\"operation has timed out\"));\n }, timeout);\n this.acks[id] = (...args) => {\n // @ts-ignore\n this.io.clearTimeoutFn(timer);\n ack.apply(this, [null, ...args]);\n };\n }\n /**\n * Emits an event and waits for an acknowledgement\n *\n * @example\n * // without timeout\n * const response = await socket.emitWithAck(\"hello\", \"world\");\n *\n * // with a specific timeout\n * try {\n * const response = await socket.timeout(1000).emitWithAck(\"hello\", \"world\");\n * } catch (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n *\n * @return a Promise that will be fulfilled when the server acknowledges the event\n */\n emitWithAck(ev, ...args) {\n // the timeout flag is optional\n const withErr = this.flags.timeout !== undefined || this._opts.ackTimeout !== undefined;\n return new Promise((resolve, reject) => {\n args.push((arg1, arg2) => {\n if (withErr) {\n return arg1 ? reject(arg1) : resolve(arg2);\n }\n else {\n return resolve(arg1);\n }\n });\n this.emit(ev, ...args);\n });\n }\n /**\n * Add the packet to the queue.\n * @param args\n * @private\n */\n _addToQueue(args) {\n let ack;\n if (typeof args[args.length - 1] === \"function\") {\n ack = args.pop();\n }\n const packet = {\n id: this._queueSeq++,\n tryCount: 0,\n pending: false,\n args,\n flags: Object.assign({ fromQueue: true }, this.flags),\n };\n args.push((err, ...responseArgs) => {\n if (packet !== this._queue[0]) {\n // the packet has already been acknowledged\n return;\n }\n const hasError = err !== null;\n if (hasError) {\n if (packet.tryCount > this._opts.retries) {\n this._queue.shift();\n if (ack) {\n ack(err);\n }\n }\n }\n else {\n this._queue.shift();\n if (ack) {\n ack(null, ...responseArgs);\n }\n }\n packet.pending = false;\n return this._drainQueue();\n });\n this._queue.push(packet);\n this._drainQueue();\n }\n /**\n * Send the first packet of the queue, and wait for an acknowledgement from the server.\n * @param force - whether to resend a packet that has not been acknowledged yet\n *\n * @private\n */\n _drainQueue(force = false) {\n if (!this.connected || this._queue.length === 0) {\n return;\n }\n const packet = this._queue[0];\n if (packet.pending && !force) {\n return;\n }\n packet.pending = true;\n packet.tryCount++;\n this.flags = packet.flags;\n this.emit.apply(this, packet.args);\n }\n /**\n * Sends a packet.\n *\n * @param packet\n * @private\n */\n packet(packet) {\n packet.nsp = this.nsp;\n this.io._packet(packet);\n }\n /**\n * Called upon engine `open`.\n *\n * @private\n */\n onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this._sendConnectPacket(data);\n });\n }\n else {\n this._sendConnectPacket(this.auth);\n }\n }\n /**\n * Sends a CONNECT packet to initiate the Socket.IO session.\n *\n * @param data\n * @private\n */\n _sendConnectPacket(data) {\n this.packet({\n type: PacketType.CONNECT,\n data: this._pid\n ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)\n : data,\n });\n }\n /**\n * Called upon engine or manager `error`.\n *\n * @param err\n * @private\n */\n onerror(err) {\n if (!this.connected) {\n this.emitReserved(\"connect_error\", err);\n }\n }\n /**\n * Called upon engine `close`.\n *\n * @param reason\n * @param description\n * @private\n */\n onclose(reason, description) {\n this.connected = false;\n delete this.id;\n this.emitReserved(\"disconnect\", reason, description);\n }\n /**\n * Called with socket packet.\n *\n * @param packet\n * @private\n */\n onpacket(packet) {\n const sameNamespace = packet.nsp === this.nsp;\n if (!sameNamespace)\n return;\n switch (packet.type) {\n case PacketType.CONNECT:\n if (packet.data && packet.data.sid) {\n this.onconnect(packet.data.sid, packet.data.pid);\n }\n else {\n this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n }\n break;\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n this.onevent(packet);\n break;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n this.onack(packet);\n break;\n case PacketType.DISCONNECT:\n this.ondisconnect();\n break;\n case PacketType.CONNECT_ERROR:\n this.destroy();\n const err = new Error(packet.data.message);\n // @ts-ignore\n err.data = packet.data.data;\n this.emitReserved(\"connect_error\", err);\n break;\n }\n }\n /**\n * Called upon a server event.\n *\n * @param packet\n * @private\n */\n onevent(packet) {\n const args = packet.data || [];\n if (null != packet.id) {\n args.push(this.ack(packet.id));\n }\n if (this.connected) {\n this.emitEvent(args);\n }\n else {\n this.receiveBuffer.push(Object.freeze(args));\n }\n }\n emitEvent(args) {\n if (this._anyListeners && this._anyListeners.length) {\n const listeners = this._anyListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, args);\n }\n }\n super.emit.apply(this, args);\n if (this._pid && args.length && typeof args[args.length - 1] === \"string\") {\n this._lastOffset = args[args.length - 1];\n }\n }\n /**\n * Produces an ack callback to emit with an event.\n *\n * @private\n */\n ack(id) {\n const self = this;\n let sent = false;\n return function (...args) {\n // prevent double callbacks\n if (sent)\n return;\n sent = true;\n self.packet({\n type: PacketType.ACK,\n id: id,\n data: args,\n });\n };\n }\n /**\n * Called upon a server acknowlegement.\n *\n * @param packet\n * @private\n */\n onack(packet) {\n const ack = this.acks[packet.id];\n if (\"function\" === typeof ack) {\n ack.apply(this, packet.data);\n delete this.acks[packet.id];\n }\n else {\n }\n }\n /**\n * Called upon server connect.\n *\n * @private\n */\n onconnect(id, pid) {\n this.id = id;\n this.recovered = pid && this._pid === pid;\n this._pid = pid; // defined only if connection state recovery is enabled\n this.connected = true;\n this.emitBuffered();\n this.emitReserved(\"connect\");\n this._drainQueue(true);\n }\n /**\n * Emit buffered events (received and emitted).\n *\n * @private\n */\n emitBuffered() {\n this.receiveBuffer.forEach((args) => this.emitEvent(args));\n this.receiveBuffer = [];\n this.sendBuffer.forEach((packet) => {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n });\n this.sendBuffer = [];\n }\n /**\n * Called upon server disconnect.\n *\n * @private\n */\n ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }\n /**\n * Called upon forced client/server side disconnections,\n * this method ensures the manager stops tracking us and\n * that reconnections don't get triggered for this.\n *\n * @private\n */\n destroy() {\n if (this.subs) {\n // clean subscriptions to avoid reconnections\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs = undefined;\n }\n this.io[\"_destroy\"](this);\n }\n /**\n * Disconnects the socket manually. In that case, the socket will not try to reconnect.\n *\n * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"disconnect\", (reason) => {\n * // console.log(reason); prints \"io client disconnect\"\n * });\n *\n * socket.disconnect();\n *\n * @return self\n */\n disconnect() {\n if (this.connected) {\n this.packet({ type: PacketType.DISCONNECT });\n }\n // remove socket from pool\n this.destroy();\n if (this.connected) {\n // fire events\n this.onclose(\"io client disconnect\");\n }\n return this;\n }\n /**\n * Alias for {@link disconnect()}.\n *\n * @return self\n */\n close() {\n return this.disconnect();\n }\n /**\n * Sets the compress flag.\n *\n * @example\n * socket.compress(false).emit(\"hello\");\n *\n * @param compress - if `true`, compresses the sending data\n * @return self\n */\n compress(compress) {\n this.flags.compress = compress;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n * ready to send messages.\n *\n * @example\n * socket.volatile.emit(\"hello\"); // the server may or may not receive it\n *\n * @returns self\n */\n get volatile() {\n this.flags.volatile = true;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n * given number of milliseconds have elapsed without an acknowledgement from the server:\n *\n * @example\n * socket.timeout(5000).emit(\"my-event\", (err) => {\n * if (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n * });\n *\n * @returns self\n */\n timeout(timeout) {\n this.flags.timeout = timeout;\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @example\n * socket.onAny((event, ...args) => {\n * console.log(`got ${event}`);\n * });\n *\n * @param listener\n */\n onAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @example\n * socket.prependAny((event, ...args) => {\n * console.log(`got event ${event}`);\n * });\n *\n * @param listener\n */\n prependAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @example\n * const catchAllListener = (event, ...args) => {\n * console.log(`got event ${event}`);\n * }\n *\n * socket.onAny(catchAllListener);\n *\n * // remove a specific listener\n * socket.offAny(catchAllListener);\n *\n * // or remove all listeners\n * socket.offAny();\n *\n * @param listener\n */\n offAny(listener) {\n if (!this._anyListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n */\n listenersAny() {\n return this._anyListeners || [];\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * Note: acknowledgements sent to the server are not included.\n *\n * @example\n * socket.onAnyOutgoing((event, ...args) => {\n * console.log(`sent event ${event}`);\n * });\n *\n * @param listener\n */\n onAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * Note: acknowledgements sent to the server are not included.\n *\n * @example\n * socket.prependAnyOutgoing((event, ...args) => {\n * console.log(`sent event ${event}`);\n * });\n *\n * @param listener\n */\n prependAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @example\n * const catchAllListener = (event, ...args) => {\n * console.log(`sent event ${event}`);\n * }\n *\n * socket.onAnyOutgoing(catchAllListener);\n *\n * // remove a specific listener\n * socket.offAnyOutgoing(catchAllListener);\n *\n * // or remove all listeners\n * socket.offAnyOutgoing();\n *\n * @param [listener] - the catch-all listener (optional)\n */\n offAnyOutgoing(listener) {\n if (!this._anyOutgoingListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyOutgoingListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyOutgoingListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n */\n listenersAnyOutgoing() {\n return this._anyOutgoingListeners || [];\n }\n /**\n * Notify the listeners for each packet sent\n *\n * @param packet\n *\n * @private\n */\n notifyOutgoingListeners(packet) {\n if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n const listeners = this._anyOutgoingListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, packet.data);\n }\n }\n }\n}\n", "/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nexport function Backoff(opts) {\n opts = opts || {};\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n this.factor = opts.factor || 2;\n this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n this.jitter = jitter;\n};\n", "import { Socket as Engine, installTimerFunctions, nextTick, } from \"engine.io-client\";\nimport { Socket } from \"./socket.js\";\nimport * as parser from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Backoff } from \"./contrib/backo2.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\nexport class Manager extends Emitter {\n constructor(uri, opts) {\n var _a;\n super();\n this.nsps = {};\n this.subs = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n opts.path = opts.path || \"/socket.io\";\n this.opts = opts;\n installTimerFunctions(this, opts);\n this.reconnection(opts.reconnection !== false);\n this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n this.reconnectionDelay(opts.reconnectionDelay || 1000);\n this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n this.backoff = new Backoff({\n min: this.reconnectionDelay(),\n max: this.reconnectionDelayMax(),\n jitter: this.randomizationFactor(),\n });\n this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n this._readyState = \"closed\";\n this.uri = uri;\n const _parser = opts.parser || parser;\n this.encoder = new _parser.Encoder();\n this.decoder = new _parser.Decoder();\n this._autoConnect = opts.autoConnect !== false;\n if (this._autoConnect)\n this.open();\n }\n reconnection(v) {\n if (!arguments.length)\n return this._reconnection;\n this._reconnection = !!v;\n return this;\n }\n reconnectionAttempts(v) {\n if (v === undefined)\n return this._reconnectionAttempts;\n this._reconnectionAttempts = v;\n return this;\n }\n reconnectionDelay(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelay;\n this._reconnectionDelay = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n return this;\n }\n randomizationFactor(v) {\n var _a;\n if (v === undefined)\n return this._randomizationFactor;\n this._randomizationFactor = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n return this;\n }\n reconnectionDelayMax(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelayMax;\n this._reconnectionDelayMax = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n return this;\n }\n timeout(v) {\n if (!arguments.length)\n return this._timeout;\n this._timeout = v;\n return this;\n }\n /**\n * Starts trying to reconnect if reconnection is enabled and we have not\n * started reconnecting yet\n *\n * @private\n */\n maybeReconnectOnOpen() {\n // Only try to reconnect if it's the first time we're connecting\n if (!this._reconnecting &&\n this._reconnection &&\n this.backoff.attempts === 0) {\n // keeps reconnection from firing twice for the same reconnection loop\n this.reconnect();\n }\n }\n /**\n * Sets the current transport `socket`.\n *\n * @param {Function} fn - optional, callback\n * @return self\n * @public\n */\n open(fn) {\n if (~this._readyState.indexOf(\"open\"))\n return this;\n this.engine = new Engine(this.uri, this.opts);\n const socket = this.engine;\n const self = this;\n this._readyState = \"opening\";\n this.skipReconnect = false;\n // emit `open`\n const openSubDestroy = on(socket, \"open\", function () {\n self.onopen();\n fn && fn();\n });\n // emit `error`\n const errorSub = on(socket, \"error\", (err) => {\n self.cleanup();\n self._readyState = \"closed\";\n this.emitReserved(\"error\", err);\n if (fn) {\n fn(err);\n }\n else {\n // Only do this if there is no fn to handle the error\n self.maybeReconnectOnOpen();\n }\n });\n if (false !== this._timeout) {\n const timeout = this._timeout;\n if (timeout === 0) {\n openSubDestroy(); // prevents a race condition with the 'open' event\n }\n // set timer\n const timer = this.setTimeoutFn(() => {\n openSubDestroy();\n socket.close();\n // @ts-ignore\n socket.emit(\"error\", new Error(\"timeout\"));\n }, timeout);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n this.subs.push(openSubDestroy);\n this.subs.push(errorSub);\n return this;\n }\n /**\n * Alias for open()\n *\n * @return self\n * @public\n */\n connect(fn) {\n return this.open(fn);\n }\n /**\n * Called upon transport open.\n *\n * @private\n */\n onopen() {\n // clear old subs\n this.cleanup();\n // mark as open\n this._readyState = \"open\";\n this.emitReserved(\"open\");\n // add new subs\n const socket = this.engine;\n this.subs.push(on(socket, \"ping\", this.onping.bind(this)), on(socket, \"data\", this.ondata.bind(this)), on(socket, \"error\", this.onerror.bind(this)), on(socket, \"close\", this.onclose.bind(this)), on(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n }\n /**\n * Called upon a ping.\n *\n * @private\n */\n onping() {\n this.emitReserved(\"ping\");\n }\n /**\n * Called with data.\n *\n * @private\n */\n ondata(data) {\n try {\n this.decoder.add(data);\n }\n catch (e) {\n this.onclose(\"parse error\", e);\n }\n }\n /**\n * Called when parser fully decodes a packet.\n *\n * @private\n */\n ondecoded(packet) {\n // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a \"parse error\"\n nextTick(() => {\n this.emitReserved(\"packet\", packet);\n }, this.setTimeoutFn);\n }\n /**\n * Called upon socket error.\n *\n * @private\n */\n onerror(err) {\n this.emitReserved(\"error\", err);\n }\n /**\n * Creates a new socket for the given `nsp`.\n *\n * @return {Socket}\n * @public\n */\n socket(nsp, opts) {\n let socket = this.nsps[nsp];\n if (!socket) {\n socket = new Socket(this, nsp, opts);\n this.nsps[nsp] = socket;\n }\n else if (this._autoConnect && !socket.active) {\n socket.connect();\n }\n return socket;\n }\n /**\n * Called upon a socket close.\n *\n * @param socket\n * @private\n */\n _destroy(socket) {\n const nsps = Object.keys(this.nsps);\n for (const nsp of nsps) {\n const socket = this.nsps[nsp];\n if (socket.active) {\n return;\n }\n }\n this._close();\n }\n /**\n * Writes a packet.\n *\n * @param packet\n * @private\n */\n _packet(packet) {\n const encodedPackets = this.encoder.encode(packet);\n for (let i = 0; i < encodedPackets.length; i++) {\n this.engine.write(encodedPackets[i], packet.options);\n }\n }\n /**\n * Clean up transport subscriptions and packet buffer.\n *\n * @private\n */\n cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }\n /**\n * Close the current socket.\n *\n * @private\n */\n _close() {\n this.skipReconnect = true;\n this._reconnecting = false;\n this.onclose(\"forced close\");\n if (this.engine)\n this.engine.close();\n }\n /**\n * Alias for close()\n *\n * @private\n */\n disconnect() {\n return this._close();\n }\n /**\n * Called upon engine close.\n *\n * @private\n */\n onclose(reason, description) {\n this.cleanup();\n this.backoff.reset();\n this._readyState = \"closed\";\n this.emitReserved(\"close\", reason, description);\n if (this._reconnection && !this.skipReconnect) {\n this.reconnect();\n }\n }\n /**\n * Attempt a reconnection.\n *\n * @private\n */\n reconnect() {\n if (this._reconnecting || this.skipReconnect)\n return this;\n const self = this;\n if (this.backoff.attempts >= this._reconnectionAttempts) {\n this.backoff.reset();\n this.emitReserved(\"reconnect_failed\");\n this._reconnecting = false;\n }\n else {\n const delay = this.backoff.duration();\n this._reconnecting = true;\n const timer = this.setTimeoutFn(() => {\n if (self.skipReconnect)\n return;\n this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n // check again for the case socket closed in above events\n if (self.skipReconnect)\n return;\n self.open((err) => {\n if (err) {\n self._reconnecting = false;\n self.reconnect();\n this.emitReserved(\"reconnect_error\", err);\n }\n else {\n self.onreconnect();\n }\n });\n }, delay);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n }\n /**\n * Called upon successful reconnect.\n *\n * @private\n */\n onreconnect() {\n const attempt = this.backoff.attempts;\n this._reconnecting = false;\n this.backoff.reset();\n this.emitReserved(\"reconnect\", attempt);\n }\n}\n", "import { url } from \"./url.js\";\nimport { Manager } from \"./manager.js\";\nimport { Socket } from \"./socket.js\";\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n if (typeof uri === \"object\") {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n const parsed = url(uri, opts.path || \"/socket.io\");\n const source = parsed.source;\n const id = parsed.id;\n const path = parsed.path;\n const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n const newConnection = opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n let io;\n if (newConnection) {\n io = new Manager(source, opts);\n }\n else {\n if (!cache[id]) {\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n Manager,\n Socket,\n io: lookup,\n connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nexport { protocol } from \"socket.io-parser\";\n/**\n * Expose constructors for standalone build.\n *\n * @public\n */\nexport { Manager, Socket, lookup as io, lookup as connect, lookup as default, };\n", "\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter> extends EventTarget {\n #listeners: Map = new Map()\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent(type: keyof EventMap, detail: CustomEventInit): boolean {\n return this.dispatchEvent(new CustomEvent(type as string, detail))\n }\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 public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n", "import { Logger, logger } from '@libp2p/logger'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport errCode from 'err-code'\nimport randombytes from 'iso-random-stream/src/random.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { Pushable, pushable } from 'it-pushable'\nimport defer, { DeferredPromise } from 'p-defer'\nimport { WebRTCDataChannel } from './channel.js'\nimport delay from 'delay'\nimport type { WebRTCPeerInit, WebRTCPeerEvents, WRTC } from './index.js'\nimport type { Duplex, Sink } from 'it-stream-types'\n\n// const ICECOMPLETE_TIMEOUT = 5 * 1000\n\nconst DEFAULT_PEER_CONNECTION_CONFIG: RTCConfiguration = {\n iceServers: [{\n urls: [\n 'stun:stun.l.google.com:19302',\n 'stun:global.stun.twilio.com:3478'\n ]\n }]\n}\n\nfunction getBrowserRTC (): WRTC {\n if (typeof globalThis === 'undefined') {\n throw errCode(new Error('No WebRTC support detected'), 'ERR_WEBRTC_SUPPORT')\n }\n\n const wrtc: WRTC = {\n // @ts-expect-error browser-specific properties\n RTCPeerConnection: globalThis.RTCPeerConnection ?? globalThis.mozRTCPeerConnection ?? globalThis.webkitRTCPeerConnection,\n // @ts-expect-error browser-specific properties\n RTCSessionDescription: globalThis.RTCSessionDescription ?? globalThis.mozRTCSessionDescription ?? globalThis.webkitRTCSessionDescription,\n // @ts-expect-error browser-specific properties\n RTCIceCandidate: globalThis.RTCIceCandidate ?? globalThis.mozRTCIceCandidate ?? globalThis.webkitRTCIceCandidate\n }\n\n if (wrtc.RTCPeerConnection == null) {\n throw errCode(new Error('No WebRTC support detected'), 'ERR_WEBRTC_SUPPORT')\n }\n\n return wrtc\n}\n\nexport class WebRTCPeer extends EventEmitter implements Duplex {\n public id: string\n public source: Pushable\n public sink: Sink\n public closed: boolean\n protected wrtc: WRTC\n protected peerConnection: RTCPeerConnection\n protected channel?: WebRTCDataChannel\n protected log: Logger\n private readonly connected: DeferredPromise\n\n constructor (opts: WebRTCPeerInit & { logPrefix: string }) {\n super()\n\n this.id = opts.id ?? uint8ArrayToString(randombytes(4), 'hex').slice(0, 7)\n this.log = logger(`libp2p:webrtc-peer:${opts.logPrefix}:${this.id}`)\n this.wrtc = opts.wrtc ?? getBrowserRTC()\n this.peerConnection = new this.wrtc.RTCPeerConnection(\n Object.assign({}, DEFAULT_PEER_CONNECTION_CONFIG, opts.peerConnectionConfig)\n )\n this.closed = false\n this.connected = defer()\n\n // duplex properties\n this.source = pushable()\n this.sink = async (source) => {\n await this.connected.promise\n\n if (this.channel == null) {\n throw errCode(new Error('Connected but no channel?!'), 'ERR_DATA_CHANNEL')\n }\n\n for await (const buf of source) {\n await this.channel.send(buf)\n }\n\n await this.close()\n }\n }\n\n protected handleDataChannelEvent (event: { channel?: RTCDataChannel}) {\n const dataChannel = event.channel\n\n if (dataChannel == null) {\n // In some situations `pc.createDataChannel()` returns `undefined` (in wrtc),\n // which is invalid behavior. Handle it gracefully.\n // See: https://github.com/feross/simple-peer/issues/163\n this.close(errCode(new Error('Data channel event is missing `channel` property'), 'ERR_DATA_CHANNEL'))\n .catch(err => {\n this.log('Error closing after event channel was found to be null', err)\n })\n\n return\n }\n\n this.channel = new WebRTCDataChannel(dataChannel, {\n log: this.log,\n onMessage: (event) => {\n this.source.push(new Uint8Array(event.data))\n },\n onOpen: () => {\n this.connected.resolve()\n this.dispatchEvent(new CustomEvent('ready'))\n },\n onClose: () => {\n this.close().catch(err => {\n this.log('error closing connection after channel close', err)\n })\n },\n onError: (err) => {\n this.close(err).catch(err => {\n this.log('error closing connection after channel error', err)\n })\n }\n })\n }\n\n async close (err?: Error) {\n this.closed = true\n\n if (err == null && this.channel != null) {\n // wait for the channel to flush all data before closing the channel\n while (this.channel.bufferedAmount > 0) {\n await delay(100)\n }\n }\n\n this.channel?.close()\n this.peerConnection.close()\n this.source.end(err)\n this.dispatchEvent(new CustomEvent('close'))\n }\n}\n", "import errCode from 'err-code'\nimport defer, { DeferredPromise } from 'p-defer'\nimport type { Logger } from '@libp2p/logger'\n\nconst MAX_BUFFERED_AMOUNT = 64 * 1024\nconst CHANNEL_CLOSING_TIMEOUT = 5 * 1000\n\nexport interface WebRTCDataChannelOptions {\n onMessage: (event: MessageEvent) => void\n onOpen: () => void\n onClose: () => void\n onError: (err: Error) => void\n log: Logger\n}\n\nexport class WebRTCDataChannel {\n public label: string\n private readonly channel: RTCDataChannel\n private readonly closingInterval: NodeJS.Timer\n private open: DeferredPromise\n private readonly log: Logger\n\n constructor (channel: RTCDataChannel, opts: WebRTCDataChannelOptions) {\n this.label = channel.label\n this.open = defer()\n this.channel = channel\n this.channel.binaryType = 'arraybuffer'\n this.log = opts.log\n\n if (typeof this.channel.bufferedAmountLowThreshold === 'number') {\n this.channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT\n }\n\n channel.addEventListener('message', event => {\n opts.onMessage(event)\n })\n channel.addEventListener('bufferedamountlow', () => {\n this.log('stop backpressure: bufferedAmount %d', this.channel.bufferedAmount)\n this.open.resolve()\n })\n channel.addEventListener('open', () => {\n this.open.resolve()\n opts.onOpen()\n })\n channel.addEventListener('close', () => {\n opts.onClose()\n })\n channel.addEventListener('error', event => {\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n if (event.error?.message === 'Transport channel closed') {\n return this.close()\n }\n\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n opts.log.error('channel encounter an error in state \"%s\" message: \"%s\" detail: \"%s', channel.readyState, event.error?.message, event.error?.errorDetail) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n const err = event.error instanceof Error\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n ? event.error\n // @ts-expect-error ChannelErrorEvent is just an Event in the types?\n : new Error(`datachannel error: ${event.error?.message} ${event.error?.errorDetail}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n\n opts.onError(errCode(err, 'ERR_DATA_CHANNEL'))\n })\n\n // HACK: Chrome will sometimes get stuck in readyState \"closing\", let's check for this condition\n // https://bugs.chromium.org/p/chromium/issues/detail?id=882743\n let isClosing = false\n this.closingInterval = setInterval(() => { // No \"onclosing\" event\n if (channel.readyState === 'closing') {\n if (isClosing) {\n opts.onClose() // closing timed out: equivalent to onclose firing\n }\n isClosing = true\n } else {\n isClosing = false\n }\n }, CHANNEL_CLOSING_TIMEOUT)\n }\n\n async send (data: Uint8Array) {\n await this.open.promise\n\n this.channel.send(data)\n\n if (this.channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {\n this.log('start backpressure: bufferedAmount %d', this.channel.bufferedAmount)\n this.open = defer()\n }\n }\n\n close () {\n clearInterval(this.closingInterval)\n this.channel.close()\n }\n\n get bufferedAmount () {\n return this.channel.bufferedAmount\n }\n}\n", "import { EventEmitter } from '@libp2p/interfaces/events'\nimport errCode from 'err-code'\nimport type { WebRTCPeerEvents, WRTC, Signal, OfferSignal, AnswerSignal, CandidateSignal, RenegotiateSignal, GoodbyeSignal } from './index.js'\nimport type { Logger } from '@libp2p/logger'\n\nexport interface WebRTCHandshakeOptions {\n log: Logger\n peerConnection: RTCPeerConnection\n offerOptions?: RTCOfferOptions\n wrtc: WRTC\n}\n\nexport class WebRTCHandshake extends EventEmitter {\n protected log: Logger\n protected peerConnection: RTCPeerConnection\n protected status: 'idle' | 'negotiating'\n protected wrtc: WRTC\n\n constructor (options: WebRTCHandshakeOptions) {\n super()\n\n this.log = options.log\n this.peerConnection = options.peerConnection\n this.wrtc = options.wrtc\n this.status = 'idle'\n\n this.peerConnection.addEventListener('negotiationneeded', () => {\n this.log('peer connection negotiation needed')\n\n this.handleRenegotiate({ type: 'renegotiate' }).catch(err => {\n this.log.error('could not renegotiate %o', err)\n })\n })\n }\n\n async handleSignal (signal: Signal) {\n this.log('incoming signal \"%s\"', signal.type)\n\n if (signal.type === 'offer') {\n return await this.handleOffer(signal)\n } else if (signal.type === 'answer') {\n return await this.handleAnswer(signal)\n } else if (signal.type === 'candidate') {\n return await this.handleCandidate(signal)\n } else if (signal.type === 'renegotiate') {\n return await this.handleRenegotiate(signal)\n } else if (signal.type === 'goodbye') {\n return await this.handleGoodye(signal)\n } else {\n // @ts-expect-error all types are handled above\n this.log(`Unknown signal type ${signal.type}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n }\n }\n\n async handleOffer (signal: OfferSignal) {}\n async handleAnswer (signal: AnswerSignal) {}\n async handleRenegotiate (signal: RenegotiateSignal) {}\n async handleGoodye (signal: GoodbyeSignal) {\n this.peerConnection.close()\n }\n\n async handleCandidate (signal: CandidateSignal) {\n const iceCandidate = new this.wrtc.RTCIceCandidate(signal.candidate)\n\n try {\n await this.peerConnection.addIceCandidate(iceCandidate)\n } catch (err) {\n if (iceCandidate.address == null || iceCandidate.address.endsWith('.local')) {\n this.log('ignoring unsupported ICE candidate.')\n } else {\n throw errCode(err, 'ERR_ADD_ICE_CANDIDATE')\n }\n }\n }\n}\n", "import { WebRTCPeer } from './peer.js'\nimport { WebRTCHandshake } from './handshake.js'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { WebRTCHandshakeOptions } from './handshake.js'\nimport type { WebRTCReceiverInit, OfferSignal, Signal, CandidateSignal } from './index.js'\n\nconst log = logger('libp2p:webrtc-peer:receiver')\n\nexport class WebRTCReceiver extends WebRTCPeer {\n private readonly handshake: WebRTCReceiverHandshake\n\n constructor (opts: WebRTCReceiverInit = {}) {\n super({\n ...opts,\n logPrefix: 'receiver'\n })\n\n this.handshake = new WebRTCReceiverHandshake({\n log: this.log,\n peerConnection: this.peerConnection,\n wrtc: this.wrtc,\n answerOptions: opts.answerOptions\n })\n\n this.handshake.addEventListener('signal', event => this.dispatchEvent(new CustomEvent('signal', {\n detail: event.detail\n })))\n this.peerConnection.addEventListener('datachannel', (event) => {\n this.handleDataChannelEvent(event)\n })\n }\n\n handleSignal (signal: Signal) {\n this.handshake.handleSignal(signal).catch(err => {\n this.log('error handling signal %o %o', signal, err)\n })\n }\n}\n\ninterface WebRTCReceiverHandshakeOptions extends WebRTCHandshakeOptions {\n answerOptions?: RTCAnswerOptions\n}\n\nclass WebRTCReceiverHandshake extends WebRTCHandshake {\n private readonly options: WebRTCReceiverHandshakeOptions\n private iceCandidates: CandidateSignal[]\n\n constructor (options: WebRTCReceiverHandshakeOptions) {\n super(options)\n\n this.options = options\n this.status = 'idle'\n this.iceCandidates = []\n }\n\n async handleRenegotiate () {\n log.trace('renegotiate')\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: {\n type: 'renegotiate'\n }\n }))\n }\n\n async handleOffer (signal: OfferSignal) {\n await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(signal))\n\n // add any candidates we were sent before the offer arrived\n for (const candidate of this.iceCandidates) {\n await this.handleCandidate(candidate)\n }\n this.iceCandidates = []\n\n const answer = await this.peerConnection.createAnswer(this.options.answerOptions)\n\n await this.peerConnection.setLocalDescription(answer)\n\n log.trace('handle offer', this.peerConnection.localDescription)\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: this.peerConnection.localDescription ?? answer\n }))\n }\n\n async handleCandidate (signal: CandidateSignal) {\n if (this.peerConnection.remoteDescription == null || this.peerConnection.remoteDescription.type == null) {\n // we haven't been sent an offer yet, cache the remote ICE candidates\n this.iceCandidates.push(signal)\n\n return\n }\n\n await super.handleCandidate(signal)\n }\n}\n", "import { WebRTCPeer } from './peer.js'\nimport { WebRTCHandshake } from './handshake.js'\nimport randombytes from 'iso-random-stream/src/random.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { pEvent } from 'p-event'\nimport delay from 'delay'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { WebRTCHandshakeOptions } from './handshake.js'\nimport type { WebRTCInitiatorInit, AnswerSignal, Signal } from './index.js'\n\nconst log = logger('libp2p:webrtc-peer:initator')\n\nconst ICECOMPLETE_TIMEOUT = 1000\n\nexport class WebRTCInitiator extends WebRTCPeer {\n private readonly handshake: WebRTCInitiatorHandshake\n\n constructor (opts: WebRTCInitiatorInit = {}) {\n super({\n ...opts,\n logPrefix: 'initiator'\n })\n\n this.handleDataChannelEvent({\n channel: this.peerConnection.createDataChannel(\n opts.dataChannelLabel ?? uint8ArrayToString(randombytes(20), 'hex').slice(0, 7),\n opts.dataChannelInit\n )\n })\n\n this.handshake = new WebRTCInitiatorHandshake({\n log: this.log,\n peerConnection: this.peerConnection,\n wrtc: this.wrtc,\n offerOptions: opts.offerOptions\n })\n this.handshake.addEventListener('signal', event => {\n this.dispatchEvent(new CustomEvent('signal', { detail: event.detail }))\n })\n }\n\n handleSignal (signal: Signal) {\n this.handshake.handleSignal(signal).catch(err => {\n this.log('error handling signal %o %o', signal, err)\n })\n }\n}\n\ninterface WebRTCInitiatorHandshakeOptions extends WebRTCHandshakeOptions {\n offerOptions?: RTCOfferOptions\n}\n\nclass WebRTCInitiatorHandshake extends WebRTCHandshake {\n private readonly options: WebRTCInitiatorHandshakeOptions\n\n constructor (options: WebRTCInitiatorHandshakeOptions) {\n super(options)\n\n this.options = options\n this.status = 'idle'\n\n this.peerConnection.addEventListener('icecandidate', (event) => {\n if (event.candidate == null) {\n return\n }\n\n const signal = {\n type: 'candidate',\n candidate: {\n candidate: event.candidate.candidate,\n sdpMLineIndex: event.candidate.sdpMLineIndex,\n sdpMid: event.candidate.sdpMid\n }\n }\n\n log.trace('create candidate', signal)\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: signal\n }))\n this.dispatchEvent(new CustomEvent('ice-candidate'))\n })\n }\n\n async handleRenegotiate () {\n if (this.status === 'negotiating') {\n this.log('already negotiating, queueing')\n return\n }\n\n this.status = 'negotiating'\n\n const offer = await this.peerConnection.createOffer(this.options.offerOptions)\n\n await this.peerConnection.setLocalDescription(offer)\n\n // wait for at least one candidate before sending the offer\n await pEvent(this, 'ice-candidate')\n await delay(ICECOMPLETE_TIMEOUT)\n\n log.trace('renegotiate', this.peerConnection.localDescription)\n\n this.dispatchEvent(new CustomEvent('signal', {\n detail: this.peerConnection.localDescription ?? offer\n }))\n }\n\n async handleAnswer (signal: AnswerSignal) {\n log.trace('handle answer', signal)\n\n await this.peerConnection.setRemoteDescription(new this.wrtc.RTCSessionDescription(signal))\n this.status = 'idle'\n }\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.on || emitter.addListener || emitter.addEventListener;\n\tconst removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\t\tif (options.filter && !options.filter(value)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = error => {\n\t\t\tcancel();\n\t\t\treject(error);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, options.timeout);\n\t\ttimeout.cancel = cancel;\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\tif (options.filter && !options.filter(value)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport { logger } from '@libp2p/logger'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { WebRTCPeer } from '@libp2p/webrtc-peer'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:webrtc-star:socket')\n\nexport interface ToMultiaddrConnectionOptions extends AbortOptions {\n remoteAddr: Multiaddr\n}\n\n/**\n * Convert a socket into a MultiaddrConnection\n * https://github.com/libp2p/js-libp2p-interfaces/tree/master/src/transport#multiaddrconnection\n */\nexport function toMultiaddrConnection (socket: WebRTCPeer, options: ToMultiaddrConnectionOptions): MultiaddrConnection {\n const { sink, source } = socket\n\n const maConn: MultiaddrConnection = {\n remoteAddr: options.remoteAddr,\n\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(source, options.signal) : source,\n\n timeline: { open: Date.now() },\n\n async close () {\n if (socket.closed) {\n return\n }\n\n const start = Date.now()\n\n // Attempt to end the socket. If it takes longer to close than the\n // timeout, destroy it manually.\n const timeout = setTimeout(() => {\n if (maConn.remoteAddr != null) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing socket to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n }\n\n if (!socket.closed) {\n socket.close().catch(err => {\n log.error('could not close socket', err)\n })\n }\n }, CLOSE_TIMEOUT)\n\n try {\n await socket.close()\n } finally {\n clearTimeout(timeout)\n }\n }\n }\n\n 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 }, {\n once: true\n })\n\n return maConn\n}\n", "import { multiaddr, isName } from '@multiformats/multiaddr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport function cleanUrlSIO (ma: Multiaddr) {\n const maStrSplit = ma.toString().split('/')\n const tcpProto = ma.protos()[1].name\n const wsProto = ma.protos()[2].name\n const tcpPort = ma.stringTuples()[1][1]\n\n if (tcpProto !== 'tcp' || (wsProto !== 'ws' && wsProto !== 'wss')) {\n throw new Error(`invalid multiaddr: ${ma.toString()}`)\n }\n\n if (!isName(ma)) {\n return `http://${maStrSplit[2]}:${maStrSplit[4]}`\n }\n\n if (wsProto === 'ws') {\n return `http://${maStrSplit[2]}${tcpPort == null || tcpPort === '80' ? '' : `:${tcpPort}`}`\n }\n\n if (wsProto === 'wss') {\n return `https://${maStrSplit[2]}${tcpPort == null || tcpPort === '443' ? '' : `:${tcpPort}`}`\n }\n\n throw new Error('invalid multiaddr: ' + ma.toString())\n}\n\nexport function cleanMultiaddr (maStr: string) {\n const legacy = '/libp2p-webrtc-star'\n\n if (maStr.startsWith(legacy)) {\n maStr = maStr.substring(legacy.length, maStr.length)\n let ma = multiaddr(maStr)\n const tuppleIPFS = ma.stringTuples().filter((tupple) => {\n return tupple[0] === 421 // ipfs code\n })[0]\n\n if (tuppleIPFS[1] == null) {\n throw new Error('invalid multiaddr: ' + maStr)\n }\n\n ma = ma.decapsulate('p2p')\n ma = ma.encapsulate('/p2p-webrtc-star')\n ma = ma.encapsulate(`/p2p/${tuppleIPFS[1]}`)\n maStr = ma.toString()\n }\n\n return maStr\n}\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = 'RSA' | 'Ed25519' | 'secp256k1'\n\ninterface BasePeerId {\n readonly type: PeerIdType\n readonly multihash: MultihashDigest\n readonly privateKey?: Uint8Array\n readonly publicKey?: Uint8Array\n\n toString: () => string\n toCID: () => CID\n toBytes: () => Uint8Array\n equals: (other: PeerId | Uint8Array | string) => boolean\n}\n\nexport interface RSAPeerId extends BasePeerId {\n readonly type: 'RSA'\n readonly publicKey?: Uint8Array\n}\n\nexport interface Ed25519PeerId extends BasePeerId {\n readonly type: 'Ed25519'\n readonly publicKey: Uint8Array\n}\n\nexport interface Secp256k1PeerId extends BasePeerId {\n readonly type: 'secp256k1'\n readonly publicKey: Uint8Array\n}\n\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId\n\nexport const symbol = Symbol.for('@libp2p/peer-id')\n\nexport function isPeerId (other: any): other is PeerId {\n return other != null && Boolean(other[symbol])\n}\n", "import { CID } from 'multiformats/cid'\nimport { bases } from 'multiformats/basics'\nimport { base58btc } from 'multiformats/bases/base58'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { Ed25519PeerId, PeerIdType, RSAPeerId, Secp256k1PeerId, symbol } from '@libp2p/interface-peer-id'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\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\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37\n\ninterface PeerIdInit {\n type: PeerIdType\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n publicKey?: Uint8Array\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest\n privateKey?: Uint8Array\n}\n\nclass PeerIdImpl {\n public type: PeerIdType\n public readonly multihash: MultihashDigest\n public readonly privateKey?: Uint8Array\n public readonly publicKey?: Uint8Array\n private string?: string\n\n constructor (init: PeerIdInit) {\n this.type = init.type\n this.multihash = init.multihash\n this.privateKey = init.privateKey\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n get [symbol] (): boolean {\n return true\n }\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toBytes (): Uint8Array {\n return this.multihash.bytes\n }\n\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id: PeerId | Uint8Array | string): boolean {\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this as PeerId)\n } else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nclass RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {\n public readonly type = 'RSA'\n public readonly publicKey?: Uint8Array\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nclass Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {\n public readonly type = 'Ed25519'\n public readonly publicKey: Uint8Array\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nclass Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {\n public readonly type = 'secp256k1'\n public readonly publicKey: Uint8Array\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.multihash.digest\n }\n}\n\nexport function createPeerId (init: PeerIdInit): PeerId {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init)\n }\n\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init)\n }\n\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init)\n }\n\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromPeerId (other: any): PeerId {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other)\n }\n\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other)\n }\n\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other)\n }\n\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')\n}\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder): PeerId {\n decoder = decoder ?? baseDecoder\n\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\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash })\n } else {\n return new RSAPeerIdImpl({ multihash })\n }\n }\n\n return peerIdFromBytes(baseDecoder.decode(str))\n}\n\nexport function peerIdFromBytes (buf: Uint8Array): PeerId {\n try {\n const multihash = Digest.decode(buf)\n\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash })\n } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash })\n }\n }\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash })\n }\n } catch {\n return peerIdFromCID(CID.decode(buf))\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): PeerId {\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\n const multihash = cid.multihash\n\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash })\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 } else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash })\n }\n }\n\n throw new Error('Supplied PeerID CID is invalid')\n}\n\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })\n }\n\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })\n}\n", "import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface UpgraderOptions {\n skipEncryption?: boolean\n skipProtection?: boolean\n muxerFactory?: StreamMuxerFactory\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n", "import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n", "import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { Transport } from '@libp2p/interface-transport'\nimport { WebRTCStar, WebRTCStarComponents, WebRTCStarInit } from './transport.js'\n\nexport interface WebRTCStarTuple {\n transport: (components: WebRTCStarComponents) => Transport\n discovery: (components?: WebRTCStarComponents) => PeerDiscovery\n}\n\nexport function webRTCStar (init: WebRTCStarInit = {}): WebRTCStarTuple {\n const transport = new WebRTCStar(init)\n\n return {\n transport: (components: WebRTCStarComponents) => {\n transport.peerId = components.peerId\n return transport\n },\n discovery: transport.discovery\n }\n}\n", "import { webRTCStar } from '@libp2p/webrtc-star'\n\nexport function libp2pConfig () {\n const webRtcStar = webRTCStar()\n\n /** @type {import('libp2p').Libp2pOptions} */\n const options = {\n transports: [\n webRtcStar.transport\n ],\n peerDiscovery: [\n webRtcStar.discovery\n ],\n connectionManager: {\n maxParallelDials: 150, // 150 total parallel multiaddr dials\n maxDialsPerPeer: 4, // Allow 4 multiaddrs to be dialed per peer in parallel\n dialTimeout: 10e3, // 10 second dial timeout per peer dial\n autoDial: true\n },\n nat: {\n enabled: false\n }\n }\n\n return options\n}\n", "\n/**\n * Implemented by components that have a lifecycle\n */\nexport interface Startable {\n isStarted: () => boolean\n\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?: () => void | Promise\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?: () => void | Promise\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?: () => void | Promise\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?: () => void | Promise\n}\n\nexport function isStartable (obj: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\nexport async function start (...objs: any[]): Promise {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\nexport async function stop (...objs: any[]): Promise {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes, messages } from './errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './content-routing/utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error module with no types\n} from 'set-delayed-interval'\nimport { setMaxListeners } from 'events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:peer-routing')\n\nexport interface RefreshManagerInit {\n /**\n * Whether to enable the Refresh manager\n */\n enabled?: boolean\n\n /**\n * Boot delay to start the Refresh Manager (in ms)\n */\n bootDelay?: number\n\n /**\n * Interval between each Refresh Manager run (in ms)\n */\n interval?: number\n\n /**\n * How long to let each refresh run (in ms)\n */\n timeout?: number\n}\n\nexport interface PeerRoutingInit {\n routers?: PeerRouting[]\n refreshManager?: RefreshManagerInit\n}\n\nexport interface DefaultPeerRoutingComponents {\n peerId: PeerId\n peerStore: PeerStore\n}\n\nexport class DefaultPeerRouting implements PeerRouting, Startable {\n private readonly components: DefaultPeerRoutingComponents\n private readonly routers: PeerRouting[]\n private readonly refreshManagerInit: RefreshManagerInit\n private timeoutId?: ReturnType\n private started: boolean\n private abortController?: TimeoutController\n\n constructor (components: DefaultPeerRoutingComponents, init: PeerRoutingInit) {\n this.components = components\n this.routers = init.routers ?? []\n this.refreshManagerInit = init.refreshManager ?? {}\n this.started = false\n\n this._findClosestPeersTask = this._findClosestPeersTask.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start peer routing service.\n */\n async start () {\n if (this.started || this.routers.length === 0 || this.timeoutId != null || this.refreshManagerInit.enabled === false) {\n return\n }\n\n this.timeoutId = setDelayedInterval(\n this._findClosestPeersTask, this.refreshManagerInit.interval, this.refreshManagerInit.bootDelay\n )\n\n this.started = true\n }\n\n /**\n * Recurrent task to find closest peers and add their addresses to the Address Book.\n */\n async _findClosestPeersTask () {\n if (this.abortController != null) {\n // we are already running the query\n return\n }\n\n try {\n this.abortController = new TimeoutController(this.refreshManagerInit.timeout ?? 10e3)\n\n // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning\n // appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.abortController.signal)\n } catch {}\n\n // nb getClosestPeers adds the addresses to the address book\n await drain(this.getClosestPeers(this.components.peerId.toBytes(), { signal: this.abortController.signal }))\n } catch (err: any) {\n log.error(err)\n } finally {\n this.abortController?.clear()\n this.abortController = undefined\n }\n }\n\n /**\n * Stop peer routing service.\n */\n async stop () {\n clearDelayedInterval(this.timeoutId)\n\n // abort query if it is in-flight\n this.abortController?.abort()\n\n this.started = false\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: AbortOptions): Promise {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n if (id.toString() === this.components.peerId.toString()) {\n throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF)\n }\n\n const output = await pipe(\n merge(\n ...this.routers.map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n log.error(err)\n }\n })())\n ),\n (source) => filter(source, Boolean),\n (source) => storeAddresses(source, this.components.peerStore),\n async (source) => await first(source)\n )\n\n if (output != null) {\n return output\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.getClosestPeers(key, options))\n ),\n (source) => storeAddresses(source, this.components.peerStore),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n}\n", "export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n DHT_DISABLED = 'DHT is not available',\n PUBSUB_DISABLED = 'PubSub is not available',\n CONN_ENCRYPTION_REQUIRED = 'At least one connection encryption module is required',\n ERR_TRANSPORTS_REQUIRED = 'At least one transport module is required',\n ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',\n NOT_FOUND = 'Not found'\n}\n\nexport enum codes {\n DHT_DISABLED = 'ERR_DHT_DISABLED',\n ERR_PUBSUB_DISABLED = 'ERR_PUBSUB_DISABLED',\n PUBSUB_NOT_STARTED = 'ERR_PUBSUB_NOT_STARTED',\n DHT_NOT_STARTED = 'ERR_DHT_NOT_STARTED',\n CONN_ENCRYPTION_REQUIRED = 'ERR_CONN_ENCRYPTION_REQUIRED',\n ERR_TRANSPORTS_REQUIRED = 'ERR_TRANSPORTS_REQUIRED',\n ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',\n ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',\n ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',\n ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',\n ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',\n ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',\n ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',\n ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',\n ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',\n ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',\n ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',\n ERR_DIALED_SELF = 'ERR_DIALED_SELF',\n ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',\n ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',\n ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',\n ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',\n ERR_INVALID_KEY = 'ERR_INVALID_KEY',\n ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',\n ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',\n ERR_INVALID_PEER = 'ERR_INVALID_PEER',\n ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',\n ERR_NOT_FOUND = 'ERR_NOT_FOUND',\n ERR_TIMEOUT = 'ERR_TIMEOUT',\n ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',\n ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',\n ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',\n ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',\n ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',\n ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',\n ERR_FIND_SELF = 'ERR_FIND_SELF',\n ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',\n ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',\n ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',\n ERR_KEYCHAIN_REQUIRED = 'ERR_KEYCHAIN_REQUIRED',\n ERR_INVALID_CMS = 'ERR_INVALID_CMS',\n ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',\n ERR_NO_KEY = 'ERR_NO_KEY',\n ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',\n ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',\n ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',\n ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',\n ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',\n ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',\n ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',\n ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',\n ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',\n ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',\n ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',\n ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',\n ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',\n ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',\n ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',\n ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',\n ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',\n ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',\n ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',\n ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',\n ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',\n ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS',\n ERR_CONNECTION_DENIED = 'ERR_CONNECTION_DENIED'\n}\n", "import errCode from 'err-code'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport type { Source } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\n/**\n * Store the multiaddrs from every peer in the passed peer store\n */\nexport async function * storeAddresses (source: Source, peerStore: PeerStore) {\n yield * map(source, async (peer) => {\n // ensure we have the addresses for a given peer\n await peerStore.addressBook.add(peer.id, peer.multiaddrs)\n\n return peer\n })\n}\n\n/**\n * Filter peers by unique peer id\n */\nexport function uniquePeers (source: Source) {\n /** @type Set */\n const seen = new Set()\n\n return filter(source, (peer) => {\n // dedupe by peer id\n if (seen.has(peer.id.toString())) {\n return false\n }\n\n seen.add(peer.id.toString())\n\n return true\n })\n}\n\n/**\n * Require at least `min` peers to be yielded from `source`\n */\nexport async function * requirePeers (source: Source, min: number = 1) {\n let seen = 0\n\n for await (const peer of source) {\n seen++\n\n yield peer\n }\n\n if (seen < min) {\n throw errCode(new Error('not found'), 'NOT_FOUND')\n }\n}\n", "import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './utils.js'\nimport drain from 'it-drain'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats/cid'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport interface CompoundContentRoutingComponents {\n peerStore: PeerStore\n dht?: DualDHT\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: CompoundContentRoutingComponents\n\n constructor (components: CompoundContentRoutingComponents, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.findProviders(key, options))\n ),\n (source) => storeAddresses(source, this.components.peerStore),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\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: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n await Promise.all(this.routers.map(async (router) => 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: Uint8Array, value: Uint8Array, options?: AbortOptions) {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.dht\n\n if (dht != null) {\n await drain(dht.put(key, value, options))\n }\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.dht\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, nVals: number, options: AbortOptions) { // eslint-disable-line require-await\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n if (nVals == null || nVals === 0) {\n return\n }\n\n let gotValues = 0\n const dht = this.components.dht\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n yield { from: event.from, val: event.value }\n\n gotValues++\n\n if (gotValues === nVals) {\n break\n }\n }\n }\n }\n\n if (gotValues === 0) {\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n }\n}\n", "import type { AddressManagerEvents } from '@libp2p/interface-address-manager'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { TransportManager } from '@libp2p/interface-transport'\n\nexport interface AddressManagerInit {\n /**\n * Pass an function in this field to override the list of addresses\n * that are announced to the network\n */\n announceFilter?: AddressFilter\n\n /**\n * list of multiaddrs string representation to listen\n */\n listen?: string[]\n\n /**\n * list of multiaddrs string representation to announce\n */\n announce?: string[]\n\n /**\n * list of multiaddrs string representation to never announce\n */\n noAnnounce?: string[]\n}\n\nexport interface DefaultAddressManagerComponents {\n peerId: PeerId\n transportManager: TransportManager\n}\n\n/**\n * A function that takes a list of multiaddrs and returns a list\n * to announce\n */\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\nexport class DefaultAddressManager extends EventEmitter {\n private readonly components: DefaultAddressManagerComponents\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n private readonly listen: string[]\n private readonly announce: Set\n private readonly observed: Set\n private readonly announceFilter: AddressFilter\n\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: DefaultAddressManagerComponents, init: AddressManagerInit) {\n super()\n\n const { listen = [], announce = [] } = init\n\n this.components = components\n this.listen = listen.map(ma => ma.toString())\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.observed = new Set()\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return Array.from(this.observed).map((a) => multiaddr(a))\n }\n\n /**\n * Add peer observed addresses\n * Signal that we have confidence an observed multiaddr is publicly dialable -\n * this will make it appear in the output of getAddresses()\n */\n confirmObservedAddr (addr: Multiaddr): void {\n\n }\n\n /**\n * Signal that we do not have confidence an observed multiaddr is publicly dialable -\n * this will remove it from the output of getObservedAddrs()\n */\n removeObservedAddr (addr: Multiaddr): void {\n\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: string | Multiaddr): void {\n let ma = multiaddr(addr)\n const remotePeer = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (remotePeer != null) {\n const remotePeerId = peerIdFromString(remotePeer)\n\n // use same encoding for comparison\n if (remotePeerId.equals(this.components.peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${this.components.peerId.toString()}`))\n }\n }\n\n const addrString = ma.toString()\n\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\n this.observed.add(addrString)\n this.dispatchEvent(new CustomEvent('change:addresses'))\n }\n\n getAddresses (): Multiaddr[] {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString())\n\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\n addrs = addrs.concat(this.getObservedAddrs().map(ma => ma.toString()))\n\n // dedupe multiaddrs\n const addrSet = new Set(addrs)\n\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\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`)\n })\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport mergeOptions from 'merge-options'\nimport { LatencyMonitor, SummaryObject } from './latency-monitor.js'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { codes } from '../errors.js'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { setMaxListeners } from 'events'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { ConnectionManager, ConnectionManagerEvents, Dialer } from '@libp2p/interface-connection-manager'\nimport * as STATUS from '@libp2p/interface-connection/status'\nimport type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'\nimport { multiaddr, Multiaddr, Resolver } from '@multiformats/multiaddr'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'\nimport { RateLimiterMemory } from 'rate-limiter-flexible'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { Upgrader } from '@libp2p/interface-transport'\nimport { getPeerAddress } from '../get-peer.js'\n\nconst log = logger('libp2p:connection-manager')\n\nexport interface ConnectionManagerConfig {\n /**\n * The maximum number of connections libp2p is willing to have before it starts disconnecting. Defaults to `Infinity`\n */\n maxConnections: number\n\n /**\n * The minimum number of connections below which libp2p not activate preemptive disconnections. Defaults to `0`.\n */\n minConnections: number\n\n /**\n * Sets the maximum event loop delay (measured in milliseconds) this node is willing to endure before it starts disconnecting peers. Defaults to `Infinity`.\n */\n maxEventLoopDelay?: number\n\n /**\n * Sets the poll interval (in milliseconds) for assessing the current state and determining if this peer needs to force a disconnect. Defaults to `2000` (2 seconds).\n */\n pollInterval?: number\n\n /**\n * If true, try to connect to all discovered peers up to the connection manager limit\n */\n autoDial?: boolean\n\n /**\n * How long to wait between attempting to keep our number of concurrent connections\n * above minConnections\n */\n autoDialInterval: number\n\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n */\n dialTimeout?: number\n\n /**\n * When a new inbound connection is opened, the upgrade process (e.g. protect,\n * encrypt, multiplex etc) must complete within this number of ms.\n */\n inboundUpgradeTimeout: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n\n /**\n * On startup we try to dial any peer that has previously been\n * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)\n */\n startupReconnectTimeout?: number\n\n /**\n * A list of multiaddrs that will always be allowed (except if they are in the\n * deny list) to open connections to this node even if we've reached maxConnections\n */\n allow?: string[]\n\n /**\n * A list of multiaddrs that will never be allowed to open connections to\n * this node under any circumstances\n */\n deny?: string[]\n\n /**\n * If more than this many connections are opened per second by a single\n * host, reject subsequent connections\n */\n inboundConnectionThreshold?: number\n\n /**\n * The maximum number of parallel incoming connections allowed that have yet to\n * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc\n */\n maxIncomingPendingConnections?: number\n}\n\nconst defaultOptions: Partial = {\n maxConnections: Infinity,\n minConnections: 0,\n maxEventLoopDelay: Infinity,\n pollInterval: 2000,\n autoDialInterval: 10000,\n inboundConnectionThreshold: 5,\n maxIncomingPendingConnections: 10\n}\n\nconst STARTUP_RECONNECT_TIMEOUT = 60000\n\nexport interface DefaultConnectionManagerComponents {\n peerId: PeerId\n metrics?: Metrics\n upgrader: Upgrader\n peerStore: PeerStore\n dialer: Dialer\n}\n\nexport type ConnectionManagerInit = ConnectionManagerConfig\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager extends EventEmitter implements ConnectionManager, Startable {\n private readonly components: DefaultConnectionManagerComponents\n private readonly opts: ConnectionManagerInit\n private readonly connections: Map\n private started: boolean\n private readonly latencyMonitor?: LatencyMonitor\n private readonly startupReconnectTimeout: number\n private connectOnStartupController?: TimeoutController\n private readonly dialTimeout: number\n private readonly allow: Multiaddr[]\n private readonly deny: Multiaddr[]\n private readonly inboundConnectionRateLimiter: RateLimiterMemory\n private incomingPendingConnections: number\n\n constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerConfig) {\n super()\n\n this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n\n if (this.opts.maxConnections < this.opts.minConnections) {\n throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log('options: %o', this.opts)\n\n this.components = components\n\n /**\n * Map of connections per peer\n */\n this.connections = new Map()\n\n this.started = false\n\n if (init.maxEventLoopDelay != null && init.maxEventLoopDelay > 0 && init.maxEventLoopDelay !== Infinity) {\n this.latencyMonitor = new LatencyMonitor({\n latencyCheckIntervalMs: init.pollInterval,\n dataEmitIntervalMs: init.pollInterval\n })\n }\n\n try {\n // This emitter gets listened to a lot\n setMaxListeners?.(Infinity, this)\n } catch {}\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n\n this.startupReconnectTimeout = init.startupReconnectTimeout ?? STARTUP_RECONNECT_TIMEOUT\n this.dialTimeout = init.dialTimeout ?? 30000\n\n this.allow = (init.allow ?? []).map(ma => multiaddr(ma))\n this.deny = (init.deny ?? []).map(ma => multiaddr(ma))\n\n this.inboundConnectionRateLimiter = new RateLimiterMemory({\n points: this.opts.inboundConnectionThreshold,\n duration: 1\n })\n\n this.incomingPendingConnections = 0\n }\n\n isStarted () {\n return this.started\n }\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.components.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.stat.direction === 'inbound') {\n metric.inbound++\n } else {\n metric.outbound++\n }\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.components.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric: Record = {}\n\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.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.components.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n\n // latency monitor\n this.latencyMonitor?.start()\n this._onLatencyMeasure = this._onLatencyMeasure.bind(this)\n this.latencyMonitor?.addEventListener('data', this._onLatencyMeasure)\n\n this.started = true\n log('started')\n }\n\n async afterStart () {\n this.components.upgrader.addEventListener('connection', this.onConnect)\n this.components.upgrader.addEventListener('connectionEnd', this.onDisconnect)\n\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: PeerId[] = []\n\n for (const peer of await this.components.peerStore.all()) {\n const tags = await this.components.peerStore.getTags(peer.id)\n const hasKeepAlive = tags.filter(tag => tag.name === KEEP_ALIVE).length > 0\n\n if (hasKeepAlive) {\n keepAlivePeers.push(peer.id)\n }\n }\n\n this.connectOnStartupController?.clear()\n this.connectOnStartupController = new TimeoutController(this.startupReconnectTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.connectOnStartupController.signal)\n } catch {}\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.openConnection(peer, {\n signal: this.connectOnStartupController?.signal\n })\n .catch(err => {\n log.error(err)\n })\n })\n )\n })\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n this.connectOnStartupController?.clear()\n })\n }\n\n async beforeStop () {\n // if we are still dialing KEEP_ALIVE peers, abort those dials\n this.connectOnStartupController?.abort()\n this.components.upgrader.removeEventListener('connection', this.onConnect)\n this.components.upgrader.removeEventListener('connectionEnd', this.onDisconnect)\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop () {\n this.latencyMonitor?.removeEventListener('data', this._onLatencyMeasure)\n this.latencyMonitor?.stop()\n\n this.started = false\n await this._close()\n log('stopped')\n }\n\n /**\n * Cleans up the connections\n */\n async _close () {\n // Close all connections we're tracking\n const tasks: Array> = []\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 } catch (err) {\n log.error(err)\n }\n })())\n }\n }\n\n log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n }\n\n onConnect (evt: CustomEvent) {\n void this._onConnect(evt).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\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\n const peerId = connection.remotePeer\n const peerIdStr = peerId.toString()\n const storedConns = this.connections.get(peerIdStr)\n\n if (storedConns != null) {\n storedConns.push(connection)\n } else {\n this.connections.set(peerIdStr, [connection])\n }\n\n if (peerId.publicKey != null) {\n await this.components.peerStore.keyBook.set(peerId, peerId.publicKey)\n }\n\n const numConnections = this.getConnections().length\n const toPrune = numConnections - this.opts.maxConnections\n\n await this._checkMaxLimit('maxConnections', numConnections, toPrune)\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: connection }))\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return\n }\n\n const peerId = connection.remotePeer.toString()\n let storedConn = this.connections.get(peerId)\n\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id)\n this.connections.set(peerId, storedConn)\n } else if (storedConn != null) {\n this.connections.delete(peerId)\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: connection }))\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId.toString()) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { peerId, multiaddr } = getPeerAddress(peerIdOrMultiaddr)\n\n if (peerId == null && multiaddr == null) {\n throw errCode(new TypeError('Can only open connections to PeerIds or Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n if (peerId != null) {\n log('dial to', peerId)\n\n const existingConnections = this.getConnections(peerId)\n\n if (existingConnections.length > 0) {\n log('had an existing connection to %p', peerId)\n\n return existingConnections[0]\n }\n }\n\n let timeoutController: TimeoutController | undefined\n\n if (options?.signal == null) {\n timeoutController = new TimeoutController(this.dialTimeout)\n options.signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n const connection = await this.components.dialer.dial(peerIdOrMultiaddr, options)\n let peerConnections = this.connections.get(connection.remotePeer.toString())\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(connection.remotePeer.toString(), peerConnections)\n }\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\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n }\n }\n\n async closeConnections (peerId: PeerId): Promise {\n const connections = this.connections.get(peerId.toString()) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n return await connection.close()\n })\n )\n }\n\n /**\n * Get all open connections with a peer\n */\n getAll (peerId: PeerId): Connection[] {\n if (!isPeerId(peerId)) {\n throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const id = peerId.toString()\n const connections = this.connections.get(id)\n\n // Return all open connections\n if (connections != null) {\n return connections.filter(connection => connection.stat.status === STATUS.OPEN)\n }\n\n return []\n }\n\n /**\n * If the event loop is slow, maybe close a connection\n */\n _onLatencyMeasure (evt: CustomEvent) {\n const { detail: summary } = evt\n\n this._checkMaxLimit('maxEventLoopDelay', summary.avgMs, 1)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * If the `value` of `name` has exceeded its limit, maybe close a connection\n */\n async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {\n const limit = this.opts[name]\n\n if (limit == null) {\n log.trace('limit %s was not set so it cannot be applied', name)\n return\n }\n\n log.trace('checking limit of %s. current value: %d of %d', name, value, limit)\n if (value > limit) {\n log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.peerId, name, value, limit, toPrune)\n await this._pruneConnections(toPrune)\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 _pruneConnections (toPrune: number) {\n const connections = this.getConnections()\n const peerValues = new PeerMap()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n const tags = await this.components.peerStore.getTags(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, tags.reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\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\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n // if the peers have an equal tag value then we want to close short-lived connections first\n const connectionALifespan = a.stat.timeline.open\n const connectionBLifespan = b.stat.timeline.open\n\n if (connectionALifespan < connectionBLifespan) {\n return 1\n }\n\n if (connectionALifespan > connectionBLifespan) {\n return -1\n }\n\n return 0\n })\n\n // close some connections\n const toClose = []\n\n for (const connection of sortedConnections) {\n log('too many connections open - closing a connection to %p', connection.remotePeer)\n toClose.push(connection)\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n\n // TODO: should not need to invoke this manually\n this.onDisconnect(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n })\n )\n }\n\n async acceptIncomingConnection (maConn: MultiaddrConnection): Promise {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString())\n })\n\n if (denyConnection) {\n log('connection from %s refused - connection remote address was in deny list', maConn.remoteAddr)\n return false\n }\n\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString())\n })\n\n if (allowConnection) {\n this.incomingPendingConnections++\n\n return true\n }\n\n // check pending connections\n if (this.incomingPendingConnections === this.opts.maxIncomingPendingConnections) {\n log('connection from %s refused - incomingPendingConnections exceeded by peer %s', maConn.remoteAddr)\n return false\n }\n\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address\n\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1)\n } catch {\n log('connection from %s refused - inboundConnectionThreshold exceeded by host %s', host, maConn.remoteAddr)\n return false\n }\n }\n\n if (this.getConnections().length < this.opts.maxConnections) {\n this.incomingPendingConnections++\n\n return true\n }\n\n log('connection from %s refused - maxConnections exceeded', maConn.remoteAddr)\n return false\n }\n\n afterUpgradeInbound () {\n this.incomingPendingConnections--\n }\n}\n", "/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor:visibility-change-emitter')\n\ninterface VisibilityChangeEmitterEvents {\n 'visibilityChange': CustomEvent\n}\n\ntype Hidden = 'hidden' | 'mozHidden' | 'msHidden' | 'webkitHidden'\n\n/**\n * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.\n *\n * Warning: This does not work on all browsers, but should work on all modern browsers\n *\n * @example\n *\n * const myVisibilityEmitter = new VisibilityChangeEmitter();\n *\n * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {\n * if ( pageInFocus ){\n * // Page is in focus\n * console.log('In focus');\n * }\n * else {\n * // Page is blurred\n * console.log('Out of focus');\n * }\n * });\n * // To access the visibility state directly, call:\n * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());\n */\nexport class VisibilityChangeEmitter extends EventEmitter {\n private hidden: Hidden\n private visibilityChange: string\n\n constructor () {\n super()\n\n this.hidden = 'hidden'\n this.visibilityChange = 'visibilityChange'\n\n if (globalThis.document != null) {\n this._initializeVisibilityVarNames()\n this._addVisibilityChangeListener()\n }\n }\n\n /**\n * document.hidden and document.visibilityChange are the two variables we need to check for;\n * Since these variables are named differently in different browsers, this function sets\n * the appropriate name based on the browser being used. Once executed, tha actual names of\n * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange\n * respectively\n *\n * @private\n */\n _initializeVisibilityVarNames () {\n let hidden: Hidden = 'hidden'\n let visibilityChange = 'visibilitychange'\n\n if (typeof globalThis.document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support\n hidden = 'hidden'\n visibilityChange = 'visibilitychange'\n // @ts-expect-error mozHidden is a non-standard field name\n } else if (typeof globalThis.document.mozHidden !== 'undefined') {\n hidden = 'mozHidden'\n visibilityChange = 'mozvisibilitychange'\n // @ts-expect-error msHidden is a non-standard field name\n } else if (typeof globalThis.document.msHidden !== 'undefined') {\n hidden = 'msHidden'\n visibilityChange = 'msvisibilitychange'\n // @ts-expect-error webkitHidden is a non-standard field name\n } else if (typeof globalThis.document.webkitHidden !== 'undefined') {\n hidden = 'webkitHidden'\n visibilityChange = 'webkitvisibilitychange'\n }\n\n this.hidden = hidden\n this.visibilityChange = visibilityChange\n }\n\n /**\n * Adds an event listener on the document that listens to changes in document.visibilityChange\n * (or whatever name by which the visibilityChange variable is known in the browser)\n *\n * @private\n */\n _addVisibilityChangeListener () {\n // @ts-expect-error cannot index document object with string key\n if (typeof globalThis.document.addEventListener === 'undefined' || typeof document[this.hidden] === 'undefined') {\n log('Checking page visibility requires a browser that supports the Page Visibility API.')\n } else {\n // Handle page visibility change\n globalThis.document.addEventListener(this.visibilityChange, this._handleVisibilityChange.bind(this), false)\n }\n }\n\n /**\n * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and\n * ```undefined``` if the page visibility API is not supported by the browser.\n */\n isVisible () {\n // @ts-expect-error cannot index document object with string key\n if (this.hidden === undefined || document[this.hidden] === undefined) {\n return undefined\n }\n\n // @ts-expect-error cannot index document object with string key\n return document[this.hidden] == null\n }\n\n /**\n * The function that is called when document.visibilityChange has changed\n * It emits an event called visibilityChange and sends the value of document.hidden as a\n * parameter\n *\n * @private\n */\n _handleVisibilityChange () {\n // @ts-expect-error cannot index document object with string key\n const visible = globalThis.document[this.hidden] === false\n log(visible ? 'Page Visible' : 'Page Hidden')\n\n // Emit the event\n this.dispatchEvent(new CustomEvent('visibilityChange', {\n detail: visible\n }))\n }\n}\n", "/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { VisibilityChangeEmitter } from './visibility-change-emitter.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor')\n\nexport interface LatencyMonitorEvents {\n 'data': CustomEvent\n}\n\nexport interface LatencyMonitorInit {\n /**\n * How often to add a latency check event (ms)\n */\n latencyCheckIntervalMs?: number\n\n /**\n * How often to summarize latency check events. null or 0 disables event firing\n */\n dataEmitIntervalMs?: number\n\n /**\n * What cb-style async function to use\n */\n asyncTestFn?: (cb: () => void) => void\n\n /**\n * What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.\n */\n latencyRandomPercentage?: number\n}\n\nexport interface SummaryObject {\n /**\n * How many events were called\n */\n events: number\n\n /**\n * What was the min time for a cb to be called\n */\n minMs: number\n\n /**\n * What was the max time for a cb to be called\n */\n maxMs: number\n\n /**\n * What was the average time for a cb to be called\n */\n avgMs: number\n\n /**\n * How long this interval was in ms\n */\n lengthMs: number\n}\n\ninterface LatencyData {\n startTime: number\n events: number\n minMs: number\n maxMs: number\n totalMs: number\n}\n\n/**\n * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling\n * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.\n * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.\n *\n * @extends {EventEmitter}\n *\n * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop\n * and timing how long it takes to get back.\n *\n * @example\n * const monitor = new LatencyMonitor();\n * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));\n *\n * @example\n * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});\n * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));\n */\nexport class LatencyMonitor extends EventEmitter {\n private readonly latencyCheckIntervalMs: number\n private readonly latencyRandomPercentage: number\n private readonly latencyCheckMultiply: number\n private readonly latencyCheckSubtract: number\n private readonly dataEmitIntervalMs?: number\n private readonly asyncTestFn?: (cb: () => void) => void\n\n private readonly now: (num?: any) => any\n private readonly getDeltaMS: (num: number) => number\n private visibilityChangeEmitter?: VisibilityChangeEmitter\n private latencyData: LatencyData\n private checkLatencyID?: NodeJS.Timeout\n private emitIntervalID?: NodeJS.Timeout\n\n constructor (init: LatencyMonitorInit = {}) {\n super()\n\n const { latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = init\n\n // 0 isn't valid here, so its ok to use ||\n this.latencyCheckIntervalMs = latencyCheckIntervalMs ?? 500 // 0.5s\n this.latencyRandomPercentage = latencyRandomPercentage ?? 10\n this.latencyCheckMultiply = 2 * (this.latencyRandomPercentage / 100.0) * this.latencyCheckIntervalMs\n this.latencyCheckSubtract = this.latencyCheckMultiply / 2\n\n this.dataEmitIntervalMs = (dataEmitIntervalMs === null || dataEmitIntervalMs === 0)\n ? undefined\n : dataEmitIntervalMs ?? 5 * 1000 // 5s\n log('latencyCheckIntervalMs: %s dataEmitIntervalMs: %s',\n this.latencyCheckIntervalMs, this.dataEmitIntervalMs)\n if (this.dataEmitIntervalMs != null) {\n log('Expecting ~%s events per summary', this.latencyCheckIntervalMs / this.dataEmitIntervalMs)\n } else {\n log('Not emitting summaries')\n }\n\n this.asyncTestFn = asyncTestFn // If there is no asyncFn, we measure latency\n\n // If process: use high resolution timer\n if (globalThis.process?.hrtime != null) {\n log('Using process.hrtime for timing')\n this.now = globalThis.process.hrtime // eslint-disable-line no-undef\n this.getDeltaMS = (startTime) => {\n const hrtime = this.now(startTime)\n return (hrtime[0] * 1000) + (hrtime[1] / 1000000)\n }\n // Let's try for a timer that only monotonically increases\n } else if (typeof window !== 'undefined' && window.performance?.now != null) {\n log('Using performance.now for timing')\n this.now = window.performance.now.bind(window.performance)\n this.getDeltaMS = (startTime) => Math.round(this.now() - startTime)\n } else {\n log('Using Date.now for timing')\n this.now = Date.now\n this.getDeltaMS = (startTime) => this.now() - startTime\n }\n\n this.latencyData = this.initLatencyData()\n }\n\n start () {\n // We check for isBrowser because of browsers set max rates of timeouts when a page is hidden,\n // so we fall back to another library\n // See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs\n if (isBrowser()) {\n this.visibilityChangeEmitter = new VisibilityChangeEmitter()\n\n this.visibilityChangeEmitter.addEventListener('visibilityChange', (evt) => {\n const { detail: pageInFocus } = evt\n\n if (pageInFocus) {\n this._startTimers()\n } else {\n this._emitSummary()\n this._stopTimers()\n }\n })\n }\n\n if (this.visibilityChangeEmitter?.isVisible() === true) {\n this._startTimers()\n }\n }\n\n stop () {\n this._stopTimers()\n }\n\n /**\n * Start internal timers\n *\n * @private\n */\n _startTimers () {\n // Timer already started, ignore this\n if (this.checkLatencyID != null) {\n return\n }\n\n this.checkLatency()\n\n if (this.dataEmitIntervalMs != null) {\n this.emitIntervalID = setInterval(() => this._emitSummary(), this.dataEmitIntervalMs)\n if (typeof this.emitIntervalID.unref === 'function') {\n this.emitIntervalID.unref() // Doesn't block exit\n }\n }\n }\n\n /**\n * Stop internal timers\n *\n * @private\n */\n _stopTimers () {\n if (this.checkLatencyID != null) {\n clearTimeout(this.checkLatencyID)\n this.checkLatencyID = undefined\n }\n if (this.emitIntervalID != null) {\n clearInterval(this.emitIntervalID)\n this.emitIntervalID = undefined\n }\n }\n\n /**\n * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show\n *\n * @private\n */\n _emitSummary () {\n const summary = this.getSummary()\n if (summary.events > 0) {\n this.dispatchEvent(new CustomEvent('data', {\n detail: summary\n }))\n }\n }\n\n /**\n * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,\n * it will not count for this time period\n */\n getSummary (): SummaryObject {\n // We might want to adjust for the number of expected events\n // Example: first 1 event it comes back, then such a long blocker that the next emit check comes\n // Then this fires - looks like no latency!!\n const latency = {\n events: this.latencyData.events,\n minMs: this.latencyData.minMs,\n maxMs: this.latencyData.maxMs,\n avgMs: this.latencyData.events > 0\n ? this.latencyData.totalMs / this.latencyData.events\n : Number.POSITIVE_INFINITY,\n lengthMs: this.getDeltaMS(this.latencyData.startTime)\n }\n this.latencyData = this.initLatencyData() // Clear\n\n log.trace('Summary: %O', latency)\n return latency\n }\n\n /**\n * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found,\n * it will simply report on event loop latency.\n */\n checkLatency () {\n // Randomness is needed to avoid alignment by accident to regular things in the event loop\n const randomness = (Math.random() * this.latencyCheckMultiply) - this.latencyCheckSubtract\n\n // We use this to ensure that in case some overlap somehow, we don't take the wrong startTime/offset\n const localData = {\n deltaOffset: Math.ceil(this.latencyCheckIntervalMs + randomness),\n startTime: this.now()\n }\n\n const cb = () => {\n // We are already stopped, ignore this datapoint\n if (this.checkLatencyID == null) {\n return\n }\n const deltaMS = this.getDeltaMS(localData.startTime) - localData.deltaOffset\n this.checkLatency() // Start again ASAP\n\n // Add the data point. If this gets complex, refactor it\n this.latencyData.events++\n this.latencyData.minMs = Math.min(this.latencyData.minMs, deltaMS)\n this.latencyData.maxMs = Math.max(this.latencyData.maxMs, deltaMS)\n this.latencyData.totalMs += deltaMS\n log.trace('MS: %s Data: %O', deltaMS, this.latencyData)\n }\n log.trace('localData: %O', localData)\n\n this.checkLatencyID = setTimeout(() => {\n // This gets rid of including event loop\n if (this.asyncTestFn != null) {\n // Clear timing related things\n localData.deltaOffset = 0\n localData.startTime = this.now()\n this.asyncTestFn(cb)\n } else {\n // setTimeout is not more accurate than 1ms, so this will ensure positive numbers. Add 1 to emitted data to remove.\n // This is not the best, but for now it'll be just fine. This isn't meant to be sub ms accurate.\n localData.deltaOffset -= 1\n // If there is no function to test, we mean check latency which is a special case that is really cb => cb()\n // We avoid that for the few extra function all overheads. Also, we want to keep the timers different\n cb()\n }\n }, localData.deltaOffset)\n\n if (typeof this.checkLatencyID.unref === 'function') {\n this.checkLatencyID.unref() // Doesn't block exit\n }\n }\n\n initLatencyData (): LatencyData {\n return {\n startTime: this.now(),\n minMs: Number.POSITIVE_INFINITY,\n maxMs: Number.NEGATIVE_INFINITY,\n events: 0,\n totalMs: 0\n }\n }\n}\n\nfunction isBrowser () {\n return typeof globalThis.window !== 'undefined'\n}\n", "\nexport const OPEN = 'OPEN'\nexport const CLOSING = 'CLOSING'\nexport const CLOSED = 'CLOSED'\n", "\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\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 * ```JavaScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator<[PeerId, T]> {\n return this.entries()\n }\n\n clear (): void {\n this.map.clear()\n }\n\n delete (peer: PeerId): void {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T): void {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values (): IterableIterator {\n return this.map.values()\n }\n\n get size (): number {\n return this.map.size\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\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 * ```JavaScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as list entries because list 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 * ```JavaScript\n * import { peerList } from '@libp2p/peer-collections'\n *\n * const list = peerList()\n * list.push(peerId)\n * ```\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList | Iterable) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList): PeerList {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]): void {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]): number {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length (): number {\n return this.list.length\n }\n}\n", "\nexport const KEEP_ALIVE = 'keep-alive'\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr\n */\nexport function getPeerAddress (peer: PeerId | Multiaddr): { peerId?: PeerId, multiaddr?: Multiaddr } {\n if (isPeerId(peer)) {\n return {\n peerId: peer\n }\n }\n\n if (isMultiaddr(peer)) {\n const peerId = peer.getPeerId()\n\n return {\n multiaddr: peer,\n peerId: peerId == null ? undefined : peerIdFromString(peerId)\n }\n }\n\n throw errCode(\n new Error(`${peer} is not a PeerId or a Multiaddr`), // eslint-disable-line @typescript-eslint/restrict-template-expressions\n codes.ERR_INVALID_MULTIADDR\n )\n}\n", "import { logger } from '@libp2p/logger'\nimport mergeOptions from 'merge-options'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:connection-manager:auto-dialler')\n\nexport interface AutoDiallerInit {\n /**\n * Should preemptively guarantee connections are above the low watermark\n */\n enabled?: boolean\n\n /**\n * The minimum number of connections to avoid pruning\n */\n minConnections?: number\n\n /**\n * How often, in milliseconds, it should preemptively guarantee connections are above the low watermark\n */\n autoDialInterval?: number\n}\n\nexport interface AutoDiallerComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n peerStore: PeerStore\n}\n\nconst defaultOptions: Partial = {\n enabled: true,\n minConnections: 0,\n autoDialInterval: 10000\n}\n\nexport class AutoDialler implements Startable {\n private readonly components: AutoDiallerComponents\n private readonly options: Required\n private running: boolean\n private autoDialTimeout?: ReturnType\n\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 wether we know their keys and protocols.\n */\n constructor (components: AutoDiallerComponents, init: AutoDiallerInit) {\n this.components = components\n this.options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n this.running = false\n this._autoDial = this._autoDial.bind(this)\n\n log('options: %j', this.options)\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Starts the auto dialer\n */\n async start () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = true\n\n void this._autoDial().catch(err => {\n log.error('could start autodial', err)\n })\n\n log('started')\n }\n\n /**\n * Stops the auto dialler\n */\n async stop () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = false\n\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n log('stopped')\n }\n\n async _autoDial () {\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n const minConnections = this.options.minConnections\n\n // Already has enough connections\n if (this.components.connectionManager.getConnections().length >= minConnections) {\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n\n return\n }\n\n // Sort peers on whether we know protocols or public keys for them\n const allPeers = await this.components.peerStore.all()\n\n const peers = await pipe(\n // shuffle the peers\n allPeers.sort(() => Math.random() > 0.5 ? 1 : -1),\n (source) => filter(source, (peer) => !peer.id.equals(this.components.peerId)),\n (source) => sort(source, (a, b) => {\n if (b.protocols.length > a.protocols.length) {\n return 1\n } else if (b.id.publicKey != null && a.id.publicKey == null) {\n return 1\n }\n return -1\n }),\n async (source) => await all(source)\n )\n\n for (let i = 0; this.running && i < peers.length && this.components.connectionManager.getConnections().length < minConnections; i++) {\n // Connection Manager was stopped during async dial\n if (!this.running) {\n return\n }\n\n const peer = peers[i]\n\n if (this.components.connectionManager.getConnections(peer.id).length === 0) {\n log('connecting to a peerStore stored peer %p', peer.id)\n try {\n await this.components.connectionManager.openConnection(peer.id)\n } catch (err: any) {\n log.error('could not connect to peerStore stored peer', err)\n }\n }\n }\n\n // Connection Manager was stopped\n if (!this.running) {\n return\n }\n\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay as CircuitPB } from './pb/index.js'\nimport { codes } from '../errors.js'\nimport { streamToMaConnection } from '@libp2p/utils/stream-to-ma-conn'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { createListener } from './listener.js'\nimport { handleCanHop, handleHop, hop } from './circuit/hop.js'\nimport { handleStop } from './circuit/stop.js'\nimport { StreamHandler } from './circuit/stream-handler.js'\nimport { symbol, Upgrader } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { RelayConfig } from './index.js'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:circuit')\n\nexport interface CircuitComponents {\n peerId: PeerId\n peerStore: PeerStore\n registrar: Registrar\n connectionManager: ConnectionManager\n upgrader: Upgrader\n addressManager: AddressManager\n}\n\nexport class Circuit implements Transport, Startable {\n private handler?: ConnectionHandler\n private readonly components: CircuitComponents\n private readonly _init: RelayConfig\n private _started: boolean\n\n constructor (components: CircuitComponents, init: RelayConfig) {\n this._init = init\n this.components = components\n this._started = false\n }\n\n isStarted () {\n return this._started\n }\n\n async start (): Promise {\n if (this._started) {\n return\n }\n\n this._started = true\n\n await this.components.registrar.handle(RELAY_CODEC, (data) => {\n void this._onProtocol(data).catch(err => {\n log.error(err)\n })\n }, { ...this._init })\n .catch(err => {\n log.error(err)\n })\n }\n\n async stop () {\n await this.components.registrar.unhandle(RELAY_CODEC)\n }\n\n hopEnabled () {\n return true\n }\n\n hopActive () {\n return true\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return 'libp2p/circuit-relay-v1'\n }\n\n async _onProtocol (data: IncomingStreamData) {\n const { connection, stream } = data\n const controller = new TimeoutController(this._init.hop.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n try {\n const source = abortableDuplex(stream, controller.signal)\n const streamHandler = new StreamHandler({\n stream: {\n ...stream,\n ...source\n }\n })\n const request = await streamHandler.read()\n\n if (request == null) {\n log('request was invalid, could not read from stream')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n\n let virtualConnection: Duplex | undefined\n\n switch (request.type) {\n case CircuitPB.Type.CAN_HOP: {\n log('received CAN_HOP request from %p', connection.remotePeer)\n await handleCanHop({ circuit: this, connection, streamHandler })\n break\n }\n case CircuitPB.Type.HOP: {\n log('received HOP request from %p', connection.remotePeer)\n await handleHop({\n connection,\n request,\n streamHandler,\n circuit: this,\n connectionManager: this.components.connectionManager\n })\n break\n }\n case CircuitPB.Type.STOP: {\n log('received STOP request from %p', connection.remotePeer)\n virtualConnection = await handleStop({\n connection,\n request,\n streamHandler\n })\n break\n }\n default: {\n log('Request of type %s not supported', request.type)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n }\n\n if (virtualConnection != null) {\n const remoteAddr = connection.remoteAddr\n .encapsulate('/p2p-circuit')\n .encapsulate(multiaddr(request.dstPeer?.addrs[0]))\n const localAddr = multiaddr(request.srcPeer?.addrs[0])\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr,\n localAddr\n })\n const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'\n log('new %s connection %s', type, maConn.remoteAddr)\n\n const conn = await this.components.upgrader.upgradeInbound(maConn)\n log('%s connection %s upgraded', type, maConn.remoteAddr)\n\n if (this.handler != null) {\n this.handler(conn)\n }\n }\n } finally {\n controller.clear()\n }\n }\n\n /**\n * Dial a peer over a relay\n */\n async dial (ma: Multiaddr, options: AbortOptions = {}): Promise {\n // Check the multiaddr to see if it contains a relay and a destination peer\n const addrs = ma.toString().split('/p2p-circuit')\n const relayAddr = multiaddr(addrs[0])\n const destinationAddr = multiaddr(addrs[addrs.length - 1])\n const relayId = relayAddr.getPeerId()\n const destinationId = destinationAddr.getPeerId()\n\n if (relayId == null || destinationId == null) {\n const errMsg = 'Circuit relay dial failed as addresses did not have peer id'\n log.error(errMsg)\n throw errCode(new Error(errMsg), codes.ERR_RELAYED_DIAL)\n }\n\n const relayPeer = peerIdFromString(relayId)\n const destinationPeer = peerIdFromString(destinationId)\n\n let disconnectOnFailure = false\n const relayConnections = this.components.connectionManager.getConnections(relayPeer)\n let relayConnection = relayConnections[0]\n\n if (relayConnection == null) {\n await this.components.peerStore.addressBook.add(relayPeer, [relayAddr])\n relayConnection = await this.components.connectionManager.openConnection(relayPeer, options)\n disconnectOnFailure = true\n }\n\n try {\n const virtualConnection = await hop({\n ...options,\n connection: relayConnection,\n request: {\n type: CircuitPB.Type.HOP,\n srcPeer: {\n id: this.components.peerId.toBytes(),\n addrs: this.components.addressManager.getAddresses().map(addr => addr.bytes)\n },\n dstPeer: {\n id: destinationPeer.toBytes(),\n addrs: [multiaddr(destinationAddr).bytes]\n }\n }\n })\n\n const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`)\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr: ma,\n localAddr\n })\n log('new outbound connection %s', maConn.remoteAddr)\n\n return await this.components.upgrader.upgradeOutbound(maConn)\n } catch (err: any) {\n log.error('Circuit relay dial failed', err)\n disconnectOnFailure && await relayConnection.close()\n throw err\n }\n }\n\n /**\n * Create a listener\n */\n createListener (options: CreateListenerOptions): Listener {\n // Called on successful HOP and STOP requests\n this.handler = options.handler\n\n return createListener({\n connectionManager: this.components.connectionManager,\n peerStore: this.components.peerStore\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can dial on\n *\n * @param {Multiaddr[]} multiaddrs\n * @returns {Multiaddr[]}\n */\n filter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return mafmt.Circuit.matches(ma)\n })\n }\n}\n", "// @ts-expect-error no types\nimport ReaderClass from 'protobufjs/src/reader.js'\n// @ts-expect-error no types\nimport ReaderBufferClass from 'protobufjs/src/reader_buffer.js'\n// @ts-expect-error no types\nimport WriterClass from 'protobufjs/src/writer.js'\n// @ts-expect-error no types\nimport WriterBufferClass from 'protobufjs/src/writer_buffer.js'\n// @ts-expect-error no types\nimport util from 'protobufjs/src/util/minimal.js'\nimport type { Reader, Writer } from './index.js'\n\nfunction configure (): void {\n util._configure()\n ReaderClass._configure(ReaderBufferClass)\n WriterClass._configure(WriterBufferClass)\n}\n\n// Set up buffer utility according to the environment\nconfigure()\n\n// monkey patch the reader to add native bigint support\nconst methods = [\n 'uint64', 'int64', 'sint64', 'fixed64', 'sfixed64'\n]\n\nfunction patchReader (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (): bigint {\n return BigInt(original.call(this).toString())\n }\n }\n\n return obj\n}\n\nexport function reader (buf: Uint8Array): Reader {\n return patchReader(new ReaderClass(buf))\n}\n\nfunction patchWriter (obj: any): any {\n for (const method of methods) {\n if (obj[method] == null) {\n continue\n }\n\n const original = obj[method]\n obj[method] = function (val: bigint) {\n return original.call(this, val.toString())\n }\n }\n\n return obj\n}\n\nexport function writer (): Writer {\n return patchWriter(WriterClass.create())\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { reader } from './utils.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n const r = reader(buf instanceof Uint8Array ? buf : buf.subarray())\n\n return codec.decode(r)\n}\n", "import type { Codec } from './codec.js'\nimport { writer } from './utils.js'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8Array {\n const w = writer()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction {\n (value: T, writer: Writer, opts?: EncodeOptions): void\n}\n\nexport interface DecodeFunction {\n (reader: Reader, length?: number): T\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction): Codec {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\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\n return v[val]\n }\n\n const encode: EncodeFunction = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, EncodeOptions } from '../codec.js'\nimport type { Codec } from '../codec.js'\nimport type { Reader, Writer } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (encode: (obj: T, writer: Writer, opts?: EncodeOptions) => void, decode: (reader: Reader, length?: number) => T): Codec {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface CircuitRelay {\n type?: CircuitRelay.Type\n srcPeer?: CircuitRelay.Peer\n dstPeer?: CircuitRelay.Peer\n code?: CircuitRelay.Status\n}\n\nexport namespace CircuitRelay {\n export enum Status {\n SUCCESS = 'SUCCESS',\n HOP_SRC_ADDR_TOO_LONG = 'HOP_SRC_ADDR_TOO_LONG',\n HOP_DST_ADDR_TOO_LONG = 'HOP_DST_ADDR_TOO_LONG',\n HOP_SRC_MULTIADDR_INVALID = 'HOP_SRC_MULTIADDR_INVALID',\n HOP_DST_MULTIADDR_INVALID = 'HOP_DST_MULTIADDR_INVALID',\n HOP_NO_CONN_TO_DST = 'HOP_NO_CONN_TO_DST',\n HOP_CANT_DIAL_DST = 'HOP_CANT_DIAL_DST',\n HOP_CANT_OPEN_DST_STREAM = 'HOP_CANT_OPEN_DST_STREAM',\n HOP_CANT_SPEAK_RELAY = 'HOP_CANT_SPEAK_RELAY',\n HOP_CANT_RELAY_TO_SELF = 'HOP_CANT_RELAY_TO_SELF',\n STOP_SRC_ADDR_TOO_LONG = 'STOP_SRC_ADDR_TOO_LONG',\n STOP_DST_ADDR_TOO_LONG = 'STOP_DST_ADDR_TOO_LONG',\n STOP_SRC_MULTIADDR_INVALID = 'STOP_SRC_MULTIADDR_INVALID',\n STOP_DST_MULTIADDR_INVALID = 'STOP_DST_MULTIADDR_INVALID',\n STOP_RELAY_REFUSED = 'STOP_RELAY_REFUSED',\n MALFORMED_MESSAGE = 'MALFORMED_MESSAGE'\n }\n\n enum __StatusValues {\n SUCCESS = 100,\n HOP_SRC_ADDR_TOO_LONG = 220,\n HOP_DST_ADDR_TOO_LONG = 221,\n HOP_SRC_MULTIADDR_INVALID = 250,\n HOP_DST_MULTIADDR_INVALID = 251,\n HOP_NO_CONN_TO_DST = 260,\n HOP_CANT_DIAL_DST = 261,\n HOP_CANT_OPEN_DST_STREAM = 262,\n HOP_CANT_SPEAK_RELAY = 270,\n HOP_CANT_RELAY_TO_SELF = 280,\n STOP_SRC_ADDR_TOO_LONG = 320,\n STOP_DST_ADDR_TOO_LONG = 321,\n STOP_SRC_MULTIADDR_INVALID = 350,\n STOP_DST_MULTIADDR_INVALID = 351,\n STOP_RELAY_REFUSED = 390,\n MALFORMED_MESSAGE = 400\n }\n\n export namespace Status {\n export const codec = () => {\n return enumeration(__StatusValues)\n }\n }\n\n export enum Type {\n HOP = 'HOP',\n STOP = 'STOP',\n STATUS = 'STATUS',\n CAN_HOP = 'CAN_HOP'\n }\n\n enum __TypeValues {\n HOP = 1,\n STOP = 2,\n STATUS = 3,\n CAN_HOP = 4\n }\n\n export namespace Type {\n export const codec = () => {\n return enumeration(__TypeValues)\n }\n }\n\n export interface Peer {\n id: Uint8Array\n addrs: Uint8Array[]\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.id != null && obj.id.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0),\n addrs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.type != null) {\n w.uint32(8)\n CircuitRelay.Type.codec().encode(obj.type, w)\n }\n\n if (obj.srcPeer != null) {\n w.uint32(18)\n CircuitRelay.Peer.codec().encode(obj.srcPeer, w, {\n writeDefaults: false\n })\n }\n\n if (obj.dstPeer != null) {\n w.uint32(26)\n CircuitRelay.Peer.codec().encode(obj.dstPeer, w, {\n writeDefaults: false\n })\n }\n\n if (obj.code != null) {\n w.uint32(32)\n CircuitRelay.Status.codec().encode(obj.code, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = CircuitRelay.Type.codec().decode(reader)\n break\n case 2:\n obj.srcPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 3:\n obj.dstPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 4:\n obj.code = CircuitRelay.Status.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: CircuitRelay): Uint8Array => {\n return encodeMessage(obj, CircuitRelay.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): CircuitRelay => {\n return decodeMessage(buf, CircuitRelay.codec())\n }\n}\n", "import { abortableSource } from 'abortable-iterator'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:stream:converter')\n\nexport interface Timeline {\n /**\n * Connection opening timestamp\n */\n open: number\n\n /**\n * Connection upgraded timestamp\n */\n upgraded?: number\n\n /**\n * Connection closed timestamp\n */\n close?: number\n}\n\nexport interface StreamOptions {\n signal?: AbortSignal\n\n}\n\nexport interface StreamProperties {\n stream: Duplex\n remoteAddr: Multiaddr\n localAddr: Multiaddr\n}\n\n/**\n * Convert a duplex iterable into a MultiaddrConnection.\n * https://github.com/libp2p/interface-transport#multiaddrconnection\n */\nexport function streamToMaConnection (props: StreamProperties, options: StreamOptions = {}) {\n const { stream, remoteAddr } = props\n const { sink, source } = stream\n\n const mapSource = (async function * () {\n for await (const list of source) {\n yield * list\n }\n }())\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n await close()\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log(err)\n }\n }\n },\n source: (options.signal != null) ? abortableSource(mapSource, options.signal) : mapSource,\n remoteAddr,\n /** @type {Timeline} */\n timeline: { open: Date.now(), close: undefined },\n async close () {\n await sink(async function * () {\n yield new Uint8Array(0)\n }())\n await close()\n }\n }\n\n async function close () {\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n return await Promise.resolve()\n }\n\n return maConn\n}\n", "\nexport const RELAY_CODEC = '/libp2p/circuit/relay/0.1.0'\n", "import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Listener } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { multiaddr } from '@multiformats/multiaddr'\n\nexport interface ListenerOptions {\n peerStore: PeerStore\n connectionManager: ConnectionManager\n}\n\nexport function createListener (options: ListenerOptions): Listener {\n const listeningAddrs = new Map()\n\n /**\n * Add swarm handler and listen for incoming connections\n */\n async function listen (addr: Multiaddr): Promise {\n const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')\n const ma = multiaddr(addrString)\n\n const relayPeerStr = ma.getPeerId()\n\n if (relayPeerStr == null) {\n throw new Error('Could not determine relay peer from multiaddr')\n }\n\n const relayPeerId = peerIdFromString(relayPeerStr)\n\n await options.peerStore.addressBook.add(relayPeerId, [ma])\n\n const relayConn = await options.connectionManager.openConnection(relayPeerId)\n const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')\n\n listeningAddrs.set(relayConn.remotePeer.toString(), relayedAddr)\n listener.dispatchEvent(new CustomEvent('listening'))\n }\n\n /**\n * Get fixed up multiaddrs\n *\n * NOTE: This method will grab the peers multiaddrs and expand them such that:\n *\n * a) If it's an existing /p2p-circuit address for a specific relay i.e.\n * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the\n * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where\n * `QmPeer` is this peers id\n * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit\n * addr, such when dialing over a relay with this address, it will create the circuit using\n * the encapsulated transport address. This is useful when for example, a peer should only\n * be dialed over TCP rather than any other transport\n *\n * @returns {Multiaddr[]}\n */\n function getAddrs () {\n const addrs = []\n for (const addr of listeningAddrs.values()) {\n addrs.push(addr)\n }\n return addrs\n }\n\n const listener: Listener = Object.assign(new EventEmitter(), {\n close: async () => await Promise.resolve(),\n listen,\n getAddrs\n })\n\n // Remove listeningAddrs when a peer disconnects\n options.connectionManager.addEventListener('peer:disconnect', (evt) => {\n const { detail: connection } = evt\n const deleted = listeningAddrs.delete(connection.remotePeer.toString())\n\n if (deleted) {\n // Announce listen addresses change\n listener.dispatchEvent(new CustomEvent('close'))\n }\n })\n\n return listener\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { validateAddrs } from './utils.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { pipe } from 'it-pipe'\nimport { codes as Errors } from '../../errors.js'\nimport { stop } from './stop.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { Duplex } from 'it-stream-types'\nimport type { Circuit } from '../transport.js'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:hop')\n\nexport interface HopRequest {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n circuit: Circuit\n connectionManager: ConnectionManager\n}\n\nexport async function handleHop (hopRequest: HopRequest): Promise {\n const {\n connection,\n request,\n streamHandler,\n circuit,\n connectionManager\n } = hopRequest\n\n // Ensure hop is enabled\n if (!circuit.hopEnabled()) {\n log('HOP request received but we are not acting as a relay')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n }\n\n // Validate the HOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid hop request via peer %p %o', connection.remotePeer, err)\n\n return\n }\n\n if (request.dstPeer == null) {\n log('HOP request received but we do not receive a dstPeer')\n return\n }\n\n // Get the connection to the destination (stop) peer\n const destinationPeer = peerIdFromBytes(request.dstPeer.id)\n\n const destinationConnections = connectionManager.getConnections(destinationPeer)\n if (destinationConnections.length === 0 && !circuit.hopActive()) {\n log('HOP request received but we are not connected to the destination peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // TODO: Handle being an active relay\n if (destinationConnections.length === 0) {\n log('did not have connection to remote peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // Handle the incoming HOP request by performing a STOP request\n const stopRequest = {\n type: CircuitPB.Type.STOP,\n dstPeer: request.dstPeer,\n srcPeer: request.srcPeer\n }\n\n let destinationStream: Duplex\n try {\n log('performing STOP request')\n const result = await stop({\n connection: destinationConnections[0],\n request: stopRequest\n })\n\n if (result == null) {\n throw new Error('Could not stop')\n }\n\n destinationStream = result\n } catch (err: any) {\n log.error(err)\n\n return\n }\n\n log('hop request from %p is valid', connection.remotePeer)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n const sourceStream = streamHandler.rest()\n\n log('creating related connections')\n // Short circuit the two streams to create the relayed connection\n return await pipe(\n sourceStream,\n destinationStream,\n sourceStream\n )\n}\n\nexport interface HopConfig extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Performs a HOP request to a relay peer, to request a connection to another\n * peer. A new, virtual, connection will be created between the two via the relay.\n */\nexport async function hop (options: HopConfig): Promise> {\n const {\n connection,\n request,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write(request)\n\n const response = await streamHandler.read()\n\n if (response == null) {\n throw errCode(new Error('HOP request had no response'), Errors.ERR_HOP_REQUEST_FAILED)\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('hop request was successful')\n\n return streamHandler.rest()\n }\n\n log('hop request failed with code %d, closing stream', response.code)\n streamHandler.close()\n\n throw errCode(new Error(`HOP request failed with code \"${response.code ?? 'unknown'}\"`), Errors.ERR_HOP_REQUEST_FAILED)\n}\n\nexport interface CanHopOptions extends AbortOptions {\n connection: Connection\n}\n\n/**\n * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities\n */\nexport async function canHop (options: CanHopOptions) {\n const {\n connection,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write({\n type: CircuitPB.Type.CAN_HOP\n })\n\n const response = await streamHandler.read()\n await streamHandler.close()\n\n if (response == null || response.code !== CircuitPB.Status.SUCCESS) {\n return false\n }\n\n return true\n}\n\nexport interface HandleCanHopOptions {\n connection: Connection\n streamHandler: StreamHandler\n circuit: Circuit\n}\n\n/**\n * Creates an unencoded CAN_HOP response based on the Circuits configuration\n */\nexport function handleCanHop (options: HandleCanHopOptions) {\n const {\n connection,\n streamHandler,\n circuit\n } = options\n const canHop = circuit.hopEnabled()\n log('can hop (%s) request from %p', canHop, connection.remotePeer)\n streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: canHop ? CircuitPB.Status.SUCCESS : CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { StreamHandler } from './stream-handler.js'\n\n/**\n * Write a response\n */\nfunction writeResponse (streamHandler: StreamHandler, status: CircuitRelay.Status) {\n streamHandler.write({\n type: CircuitRelay.Type.STATUS,\n code: status\n })\n}\n\n/**\n * Validate incomming HOP/STOP message\n */\nexport function validateAddrs (msg: CircuitRelay, streamHandler: StreamHandler) {\n try {\n if (msg.dstPeer?.addrs != null) {\n msg.dstPeer.addrs.forEach((addr) => {\n return multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_DST_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_DST_MULTIADDR_INVALID)\n throw err\n }\n\n try {\n if (msg.srcPeer?.addrs != null) {\n msg.srcPeer.addrs.forEach((addr) => {\n return multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_SRC_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_SRC_MULTIADDR_INVALID)\n throw err\n }\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\n\n/**\n * A specialized `AsyncGenerator` that lets you pass a number to the `.next` method which\n * will attempt to return only that many bytes.\n */\nexport interface Reader extends AsyncGenerator {\n next: (...args: [] | [number | undefined]) => Promise>\n}\n\n/**\n * Returns an `AsyncGenerator` that allows reading a set number of bytes from the passed source.\n *\n * @example\n *\n * ```javascript\n * import { reader } from 'it-reader'\n *\n * const stream = reader(source)\n *\n * // read 10 bytes from the stream\n * const { done, value } = await stream.next(10)\n *\n * if (done === true) {\n * // stream finished\n * }\n *\n * if (value != null) {\n * // do something with value\n * }\n * ```\n */\nexport function reader (source: Source) {\n const reader: Reader = (async function * (): AsyncGenerator {\n // @ts-expect-error first yield in stream is ignored\n let bytes: number | undefined = yield // Allows us to receive 8 when reader.next(8) is called\n let bl = new Uint8ArrayList()\n\n for await (const chunk of source) {\n if (bytes == null) {\n bl.append(chunk)\n bytes = yield bl\n bl = new Uint8ArrayList()\n continue\n }\n\n bl.append(chunk)\n\n while (bl.length >= bytes) {\n const data = bl.sublist(0, bytes)\n bl.consume(bytes)\n bytes = yield data\n\n // If we no longer want a specific byte length, we yield the rest now\n if (bytes == null) {\n if (bl.length > 0) {\n bytes = yield bl\n bl = new Uint8ArrayList()\n }\n break // bytes is null and/or no more buffer to yield\n }\n }\n }\n\n // Consumer wants more bytes but the source has ended and our buffer\n // is not big enough to satisfy.\n if (bytes != null) {\n throw Object.assign(\n new Error(`stream ended before ${bytes} bytes became available`),\n { code: 'ERR_UNDER_READ', buffer: bl }\n )\n }\n })()\n\n void reader.next()\n return reader\n}\n", "import { Reader, reader } from 'it-reader'\nimport { pushable } from 'it-pushable'\nimport defer from 'p-defer'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Handshake {\n reader: Reader\n writer: Pushable\n stream: Duplex\n rest: () => Source\n write: (data: TSink) => void\n read: () => Promise\n}\n\n// Convert a duplex stream into a reader and writer and rest stream\nexport function handshake (stream: Duplex): Handshake {\n const writer = pushable() // Write bytes on demand to the sink\n const source = reader(stream.source) // Read bytes on demand from the source\n\n // Waits for a source to be passed to the rest stream's sink\n const sourcePromise = defer>()\n let sinkErr: Error\n\n const sinkPromise = stream.sink((async function * () {\n yield * writer\n const source = await sourcePromise.promise\n yield * source\n })())\n\n sinkPromise.catch(err => {\n sinkErr = err\n })\n\n const rest: Duplex = {\n sink: async source => {\n if (sinkErr != null) {\n return await Promise.reject(sinkErr)\n }\n\n sourcePromise.resolve(source)\n return await sinkPromise\n },\n source\n }\n\n return {\n reader: source,\n writer,\n stream: rest,\n rest: () => writer.end(),\n write: writer.push,\n read: async () => {\n const res = await source.next()\n\n if (res.value != null) {\n return res.value\n }\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport * as lp from 'it-length-prefixed'\nimport { Handshake, handshake } from 'it-handshake'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stream-handler')\n\nexport interface StreamHandlerOptions {\n /**\n * A duplex iterable\n */\n stream: Stream\n\n /**\n * max bytes length of message\n */\n maxLength?: number\n}\n\nexport class StreamHandler {\n private readonly stream: Stream\n private readonly shake: Handshake\n private readonly decoder: Source\n\n constructor (options: StreamHandlerOptions) {\n const { stream, maxLength = 4096 } = options\n\n this.stream = stream\n this.shake = handshake(this.stream)\n this.decoder = lp.decode.fromReader(this.shake.reader, { maxDataLength: maxLength })\n }\n\n /**\n * Read and decode message\n */\n async read () {\n // @ts-expect-error FIXME is a source, needs to be a generator\n const msg = await this.decoder.next()\n\n if (msg.value != null) {\n const value = CircuitRelay.decode(msg.value)\n log('read message type', value.type)\n return value\n }\n\n log('read received no value, closing stream')\n // End the stream, we didn't get data\n this.close()\n }\n\n /**\n * Encode and write array of buffers\n */\n write (msg: CircuitRelay) {\n log('write message type %s', msg.type)\n this.shake.write(lp.encode.single(CircuitRelay.encode(msg)))\n }\n\n /**\n * Return the handshake rest stream and invalidate handler\n */\n rest () {\n this.shake.rest()\n return this.shake.stream\n }\n\n /**\n * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message\n */\n end (msg: CircuitRelay) {\n this.write(msg)\n this.close()\n }\n\n /**\n * Close the stream\n */\n close () {\n log('closing the stream')\n void this.rest().sink([]).catch(err => {\n log.error(err)\n })\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { validateAddrs } from './utils.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stop')\n\nexport interface HandleStopOptions {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n}\n\n/**\n * Handles incoming STOP requests\n */\nexport function handleStop (options: HandleStopOptions): Duplex | undefined {\n const {\n connection,\n request,\n streamHandler\n } = options\n\n // Validate the STOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid stop request via peer %p %o', connection.remotePeer, err)\n return\n }\n\n // The request is valid\n log('stop request is valid')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n\n return streamHandler.rest()\n}\n\nexport interface StopOptions extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Creates a STOP request\n */\nexport async function stop (options: StopOptions) {\n const {\n connection,\n request,\n signal\n } = options\n\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n log('starting stop request to %p', connection.remotePeer)\n const streamHandler = new StreamHandler({ stream })\n\n streamHandler.write(request)\n const response = await streamHandler.read()\n\n if (response == null) {\n streamHandler.close()\n return\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('stop request to %p was successful', connection.remotePeer)\n return streamHandler.rest()\n }\n\n log('stop request failed with code %d', response.code)\n streamHandler.close()\n}\n", "import { logger } from '@libp2p/logger'\nimport { codes } from '../errors.js'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error set-delayed-interval does not export types\n} from 'set-delayed-interval'\nimport { AutoRelay } from './auto-relay.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { TransportManager } from '@libp2p/interface-transport'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { StreamHandlerOptions } from '@libp2p/interface-registrar'\n\nexport interface RelayConfig extends StreamHandlerOptions {\n enabled: boolean\n advertise: RelayAdvertiseConfig\n hop: HopConfig\n autoRelay: AutoRelayConfig\n}\n\nexport interface HopConfig {\n enabled?: boolean\n active?: boolean\n timeout: number\n}\n\nconst log = logger('libp2p:relay')\n\nexport interface RelayAdvertiseConfig {\n bootDelay?: number\n enabled?: boolean\n ttl?: number\n}\n\nexport interface AutoRelayConfig {\n enabled?: boolean\n\n /**\n * maximum number of relays to listen\n */\n maxListeners: number\n}\n\nexport interface RelayInit extends RelayConfig {\n addressSorter?: AddressSorter\n}\n\nexport interface RelayComponents {\n peerId: PeerId\n contentRouting: ContentRouting\n peerStore: PeerStore\n connectionManager: ConnectionManager\n transportManager: TransportManager\n}\n\nexport class Relay implements Startable {\n private readonly components: RelayComponents\n private readonly init: RelayInit\n // @ts-expect-error this field isn't used anywhere?\n private readonly autoRelay?: AutoRelay\n private timeout?: any\n private started: boolean\n\n /**\n * Creates an instance of Relay\n */\n constructor (components: RelayComponents, init: RelayInit) {\n this.components = components\n // Create autoRelay if enabled\n this.autoRelay = init.autoRelay?.enabled !== false\n ? new AutoRelay(components, {\n addressSorter: init.addressSorter,\n ...init.autoRelay\n })\n : undefined\n\n this.started = false\n this.init = init\n this._advertiseService = this._advertiseService.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start Relay service\n */\n async start () {\n // Advertise service if HOP enabled\n if (this.init.hop.enabled !== false && this.init.advertise.enabled !== false) {\n this.timeout = setDelayedInterval(\n this._advertiseService, this.init.advertise.ttl, this.init.advertise.bootDelay\n )\n }\n\n this.started = true\n }\n\n /**\n * Stop Relay service\n */\n async stop () {\n if (this.timeout != null) {\n clearDelayedInterval(this.timeout)\n }\n\n this.started = false\n }\n\n /**\n * Advertise hop relay service in the network.\n */\n async _advertiseService () {\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n await this.components.contentRouting.provide(cid)\n } catch (err: any) {\n if (err.code === codes.ERR_NO_ROUTERS_AVAILABLE) {\n log.error('a content router, such as a DHT, must be provided in order to advertise the relay service', err)\n // Stop the advertise\n await this.stop()\n } else {\n log.error(err)\n }\n }\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * Convert a namespace string into a cid\n */\nexport async function namespaceToCid (namespace: string): Promise {\n const bytes = new TextEncoder().encode(namespace)\n const hash = await sha256.digest(bytes)\n\n return CID.createV0(hash)\n}\n", "const minute = 60 * 1000\n\n/**\n * Delay before HOP relay service is advertised on the network\n */\nexport const ADVERTISE_BOOT_DELAY = 15 * minute\n\n/**\n * Delay Between HOP relay service advertisements on the network\n */\nexport const ADVERTISE_TTL = 30 * minute\n\n/**\n * Multicodec code\n */\nexport const CIRCUIT_PROTO_CODE = 290\n\n/**\n * PeerStore metadaBook key for HOP relay service\n */\nexport const HOP_METADATA_KEY = 'hop_relay'\n\n/**\n * PeerStore metadaBook value for HOP relay service\n */\nexport const HOP_METADATA_VALUE = 'true'\n\n/**\n * Relay HOP relay service namespace for discovery\n */\nexport const RELAY_RENDEZVOUS_NS = '/libp2p/relay'\n", "import { Netmask } from 'netmask';\nimport ip_regex from 'ip-regex';\nimport { isIP } from '@chainsafe/is-ip';\nimport ipaddr from 'ipaddr.js';\nconst { isValid: is_valid, parse } = ipaddr;\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(ip_range => new Netmask(ip_range));\nfunction ipv4_check(ip_addr) {\n for (let r of NETMASK_RANGES) {\n if (r.contains(ip_addr))\n return true;\n }\n return false;\n}\nfunction ipv6_check(ip_addr) {\n return /^::$/.test(ip_addr) ||\n /^::1$/.test(ip_addr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ip_addr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ip_addr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ip_addr);\n}\nexport default (ip) => {\n if (is_valid(ip)) {\n const parsed = parse(ip);\n if (parsed.kind() === 'ipv4')\n return ipv4_check(parsed.toNormalizedString());\n else if (parsed.kind() === 'ipv6')\n return ipv6_check(ip);\n }\n else if (isIP(ip) && ip_regex.v6().test(ip))\n return ipv6_check(ip);\n return undefined;\n};\n", "const word = '[a-fA-F\\\\d:]';\n\nconst boundry = options => options && options.includeBoundaries\n\t? `(?:(?<=\\\\s|^)(?=${word})|(?<=${word})(?=\\\\s|$))`\n\t: '';\n\nconst v4 = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]\\\\d|\\\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]\\\\d|\\\\d)){3}';\n\nconst v6segment = '[a-fA-F\\\\d]{1,4}';\n\nconst v6 = `\n(?:\n(?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\\s*\\/\\/.*$/gm, '').replace(/\\n/g, '').trim();\n\n// Pre-compile only the exact regexes because adding a global flag make regexes stateful\nconst v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);\nconst v4exact = new RegExp(`^${v4}$`);\nconst v6exact = new RegExp(`^${v6}$`);\n\nconst ipRegex = options => options && options.exact\n\t? v46Exact\n\t: new RegExp(`(?:${boundry(options)}${v4}${boundry(options)})|(?:${boundry(options)}${v6}${boundry(options)})`, 'g');\n\nipRegex.v4 = options => options && options.exact ? v4exact : new RegExp(`${boundry(options)}${v4}${boundry(options)}`, 'g');\nipRegex.v6 = options => options && options.exact ? v6exact : new RegExp(`${boundry(options)}${v6}${boundry(options)}`, 'g');\n\nexport default ipRegex;\n", "'use strict'\n\nimport is_ip_private from './lib/index.js'\nexport default is_ip_private", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport isIpPrivate from 'private-ip'\n\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return Boolean(isIpPrivate(address))\n}\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\nimport type { Address } from '@libp2p/interface-peer-store'\nimport { isPrivate } from './multiaddr/is-private.js'\n\n/**\n * Compare function for array.sort().\n * This sort aims to move the private addresses to the end of the array.\n * In case of equality, a certified address will come first.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n // Check certified?\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n\n/**\n * A test thing\n */\nexport async function something (): Promise {\n return Uint8Array.from([0, 1, 2])\n}\n", "import { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { canHop } from './circuit/hop.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n CIRCUIT_PROTO_CODE,\n HOP_METADATA_KEY,\n HOP_METADATA_VALUE,\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressSorter, PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport sort from 'it-sort'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport type { RelayComponents } from './index.js'\n\nconst log = logger('libp2p:auto-relay')\n\nconst noop = () => {}\n\nexport interface AutoRelayInit {\n addressSorter?: AddressSorter\n maxListeners?: number\n onError?: (error: Error, msg?: string) => void\n}\n\nexport class AutoRelay {\n private readonly components: RelayComponents\n private readonly addressSorter: AddressSorter\n private readonly maxListeners: number\n private readonly listenRelays: Set\n private readonly onError: (error: Error, msg?: string) => void\n\n constructor (components: RelayComponents, init: AutoRelayInit) {\n this.components = components\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxListeners = init.maxListeners ?? 1\n this.listenRelays = new Set()\n this.onError = init.onError ?? noop\n\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n\n this.components.peerStore.addEventListener('change:protocols', (evt) => {\n void this._onProtocolChange(evt).catch(err => {\n log.error(err)\n })\n })\n this.components.connectionManager.addEventListener('peer:disconnect', this._onPeerDisconnected)\n }\n\n /**\n * Check if a peer supports the relay protocol.\n * If the protocol is not supported, check if it was supported before and remove it as a listen relay.\n * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if\n * inside the threshold.\n */\n async _onProtocolChange (evt: CustomEvent) {\n const {\n peerId,\n protocols\n } = evt.detail\n const id = peerId.toString()\n\n // Check if it has the protocol\n const hasProtocol = protocols.find(protocol => protocol === RELAY_CODEC)\n\n // If no protocol, check if we were keeping the peer before as a listenRelay\n if (hasProtocol == null) {\n if (this.listenRelays.has(id)) {\n await this._removeListenRelay(id)\n }\n\n return\n }\n\n if (this.listenRelays.has(id)) {\n return\n }\n\n // If protocol, check if can hop, store info in the metadataBook and listen on it\n try {\n const connections = this.components.connectionManager.getConnections(peerId)\n\n if (connections.length === 0) {\n return\n }\n\n const connection = connections[0]\n\n // Do not hop on a relayed connection\n if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {\n log(`relayed connection to ${id} will not be used to hop on`)\n return\n }\n\n const supportsHop = await canHop({ connection })\n\n if (supportsHop) {\n await this.components.peerStore.metadataBook.setValue(peerId, HOP_METADATA_KEY, uint8ArrayFromString(HOP_METADATA_VALUE))\n await this._addListenRelay(connection, id)\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n /**\n * Peer disconnects\n */\n _onPeerDisconnected (evt: CustomEvent) {\n const connection = evt.detail\n const peerId = connection.remotePeer\n const id = peerId.toString()\n\n // Not listening on this relay\n if (!this.listenRelays.has(id)) {\n return\n }\n\n this._removeListenRelay(id).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Attempt to listen on the given relay connection\n */\n async _addListenRelay (connection: Connection, id: string): Promise {\n try {\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n // Get peer known addresses and sort them with public addresses first\n const remoteAddrs = await pipe(\n await this.components.peerStore.addressBook.get(connection.remotePeer),\n (source) => sort(source, this.addressSorter),\n async (source) => await all(source)\n )\n\n // Attempt to listen on relay\n const result = await Promise.all(\n remoteAddrs.map(async addr => {\n try {\n let multiaddr = addr.multiaddr\n\n if (multiaddr.getPeerId() == null) {\n multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)\n }\n\n multiaddr = multiaddr.encapsulate('/p2p-circuit')\n\n // Announce multiaddrs will update on listen success by TransportManager event being triggered\n await this.components.transportManager.listen([multiaddr])\n return true\n } catch (err: any) {\n log.error('error listening on circuit address', err)\n this.onError(err)\n }\n\n return false\n })\n )\n\n if (result.includes(true)) {\n this.listenRelays.add(id)\n }\n } catch (err: any) {\n this.onError(err)\n this.listenRelays.delete(id)\n }\n }\n\n /**\n * Remove listen relay\n */\n async _removeListenRelay (id: string) {\n if (this.listenRelays.delete(id)) {\n // TODO: this should be responsibility of the connMgr\n await this._listenOnAvailableHopRelays([id])\n }\n }\n\n /**\n * Try to listen on available hop relay connections.\n * The following order will happen while we do not have enough relays.\n * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.\n * 2. Dial and try to listen on the peers we know that support hop but are not connected.\n * 3. Search the network.\n */\n async _listenOnAvailableHopRelays (peersToIgnore: string[] = []) {\n // TODO: The peer redial issue on disconnect should be handled by connection gating\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n const knownHopsToDial = []\n const peers = await this.components.peerStore.all()\n\n // Check if we have known hop peers to use and attempt to listen on the already connected\n for (const { id, metadata } of peers) {\n const idStr = id.toString()\n\n // Continue to next if listening on this or peer to ignore\n if (this.listenRelays.has(idStr)) {\n continue\n }\n\n if (peersToIgnore.includes(idStr)) {\n continue\n }\n\n const supportsHop = metadata.get(HOP_METADATA_KEY)\n\n // Continue to next if it does not support Hop\n if ((supportsHop == null) || uint8ArrayToString(supportsHop) !== HOP_METADATA_VALUE) {\n continue\n }\n\n const connections = this.components.connectionManager.getConnections(id)\n\n // If not connected, store for possible later use.\n if (connections.length === 0) {\n knownHopsToDial.push(id)\n continue\n }\n\n await this._addListenRelay(connections[0], idStr)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to listen on known peers that are not connected\n for (const peerId of knownHopsToDial) {\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to find relays to hop on the network\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n for await (const provider of this.components.contentRouting.findProviders(cid)) {\n if (provider.multiaddrs.length === 0) {\n continue\n }\n\n const peerId = provider.id\n\n if (peerId.equals(this.components.peerId)) {\n // Skip the provider if it's us as dialing will fail\n continue\n }\n\n await this.components.peerStore.addressBook.add(peerId, provider.multiaddrs)\n\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n async _tryToListenOnRelay (peerId: PeerId) {\n try {\n const connection = await this.components.connectionManager.openConnection(peerId)\n await this._addListenRelay(connection, peerId.toString())\n } catch (err: any) {\n log.error('Could not use %p as relay', peerId, err)\n this.onError(err, `could not connect and listen on known hop relay ${peerId.toString()}`)\n }\n }\n}\n", "/* eslint max-nested-callbacks: [\"error\", 5] */\n\nimport { logger } from '@libp2p/logger'\nimport sanitize from 'sanitize-filename'\nimport mergeOptions from 'merge-options'\nimport { Key } from 'interface-datastore/key'\nimport { CMS } from './cms.js'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { pbkdf2, randomBytes } from '@libp2p/crypto'\nimport type { Startable } from '@libp2p/interfaces/dist/src/startable'\nimport type { Datastore } from 'interface-datastore'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { KeyTypes } from '@libp2p/crypto/keys'\n\nconst log = logger('libp2p:keychain')\n\nexport interface DEKConfig {\n hash: string\n salt: string\n iterationCount: number\n keyLength: number\n}\n\nexport interface KeyChainInit {\n pass?: string\n dek?: DEKConfig\n}\n\n/**\n * Information about a key.\n */\nexport interface KeyInfo {\n /**\n * The universally unique key id\n */\n id: string\n\n /**\n * The local key name.\n */\n name: string\n}\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\nconst privates = new WeakMap()\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterationCount: 1000\n}\n\nconst defaultOptions = {\n // See https://cryptosense.com/parametesr-choice-for-pbkdf2/\n dek: {\n keyLength: 512 / 8,\n iterationCount: 10000,\n salt: 'you should override this value with a crypto secure random number',\n hash: 'sha2-512'\n }\n}\n\nfunction validateKeyName (name: string) {\n if (name == null) {\n return false\n }\n if (typeof name !== 'string') {\n return false\n }\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Throws an error after a delay\n *\n * This assumes than an error indicates that the keychain is under attack. Delay returning an\n * error to make brute force attacks harder.\n */\nasync function randomDelay () {\n const min = 200\n const max = 1000\n const delay = Math.random() * (max - min) + min\n\n await new Promise(resolve => setTimeout(resolve, delay))\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction DsName (name: string) {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction DsInfoName (name: string) {\n return new Key(infoPrefix + name)\n}\n\nexport interface KeyChainComponents {\n peerId: PeerId\n datastore: Datastore\n}\n\n/**\n * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n *\n */\nexport class KeyChain implements Startable {\n private readonly components: KeyChainComponents\n private readonly init: KeyChainInit\n private started: boolean\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: KeyChainComponents, init: KeyChainInit) {\n this.components = components\n this.init = mergeOptions(defaultOptions, init)\n\n // Enforce NIST SP 800-132\n if (this.init.pass != null && this.init.pass?.length < 20) {\n throw new Error('pass must be least 20 characters')\n }\n if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {\n throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)\n }\n if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {\n throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)\n }\n\n const dek = this.init.pass != null && this.init.dek?.salt != null\n ? pbkdf2(\n this.init.pass,\n this.init.dek?.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n\n privates.set(this, { dek })\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n const dsname = DsInfoName('self')\n\n if (!(await this.components.datastore.has(dsname))) {\n await this.importPeer('self', this.components.peerId)\n }\n\n this.started = true\n }\n\n stop () {\n this.started = false\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data\n * using the Cryptographic Message Syntax (CMS).\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content\n */\n get cms () {\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n\n return new CMS(this, dek)\n }\n\n /**\n * Generates the options for a keychain. A random salt is produced.\n *\n * @returns {object}\n */\n static generateOptions (): KeyChainInit {\n const options = Object.assign({}, defaultOptions)\n const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding\n options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')\n return options\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data.\n * The default options for a keychain.\n *\n * @returns {object}\n */\n static get options () {\n return defaultOptions\n }\n\n /**\n * Create a new key.\n *\n * @param {string} name - The local key name; cannot already exist.\n * @param {string} type - One of the key types; 'rsa'.\n * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only\n */\n async createKey (name: string, type: KeyTypes, size = 2048): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error('Invalid key name'), codes.ERR_INVALID_KEY_NAME)\n }\n\n if (typeof type !== 'string') {\n await randomDelay()\n throw errCode(new Error('Invalid key type'), codes.ERR_INVALID_KEY_TYPE)\n }\n\n const dsname = DsName(name)\n const exists = await this.components.datastore.has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error('Key name already exists'), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n switch (type.toLowerCase()) {\n case 'rsa':\n if (!Number.isSafeInteger(size) || size < 2048) {\n await randomDelay()\n throw errCode(new Error('Invalid RSA key size'), codes.ERR_INVALID_KEY_SIZE)\n }\n break\n default:\n break\n }\n\n let keyInfo\n try {\n const keypair = await generateKeyPair(type, size)\n const kid = await keypair.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await keypair.export(dek)\n keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.datastore.batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n\n await batch.commit()\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n return keyInfo\n }\n\n /**\n * List all the keys.\n *\n * @returns {Promise}\n */\n async listKeys () {\n const query = {\n prefix: infoPrefix\n }\n\n const info = []\n for await (const value of this.components.datastore.query(query)) {\n info.push(JSON.parse(uint8ArrayToString(value.value)))\n }\n\n return info\n }\n\n /**\n * Find a key by it's id\n */\n async findKeyById (id: string): Promise {\n try {\n const keys = await this.listKeys()\n return keys.find((k) => k.id === id)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Find a key by it's name.\n *\n * @param {string} name - The local key name.\n * @returns {Promise}\n */\n async findKeyByName (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n const dsname = DsInfoName(name)\n try {\n const res = await this.components.datastore.get(dsname)\n return JSON.parse(uint8ArrayToString(res))\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Remove an existing key.\n *\n * @param {string} name - The local key name; must already exist.\n * @returns {Promise}\n */\n async removeKey (name: string) {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n const dsname = DsName(name)\n const keyInfo = await this.findKeyByName(name)\n const batch = this.components.datastore.batch()\n batch.delete(dsname)\n batch.delete(DsInfoName(name))\n await batch.commit()\n return keyInfo\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise}\n */\n async renameKey (oldName: string, newName: string): Promise {\n if (!validateKeyName(oldName) || oldName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid old key name '${oldName}'`), codes.ERR_OLD_KEY_NAME_INVALID)\n }\n if (!validateKeyName(newName) || newName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid new key name '${newName}'`), codes.ERR_NEW_KEY_NAME_INVALID)\n }\n const oldDsname = DsName(oldName)\n const newDsname = DsName(newName)\n const oldInfoName = DsInfoName(oldName)\n const newInfoName = DsInfoName(newName)\n\n const exists = await this.components.datastore.has(newDsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${newName}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n try {\n const pem = await this.components.datastore.get(oldDsname)\n const res = await this.components.datastore.get(oldInfoName)\n\n const keyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n const batch = this.components.datastore.batch()\n batch.put(newDsname, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDsname)\n batch.delete(oldInfoName)\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PEM encrypted PKCS #8 string\n */\n async exportKey (name: string, password: string) {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (password == null) {\n await randomDelay()\n throw errCode(new Error('Password is required'), codes.ERR_PASSWORD_REQUIRED)\n }\n\n const dsname = DsName(name)\n try {\n const res = await this.components.datastore.get(dsname)\n const pem = uint8ArrayToString(res)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = await importKey(pem, dek)\n return await privateKey.export(password)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PeerId\n */\n async exportPeerId (name: string) {\n const password = 'temporary-password'\n const pem = await this.exportKey(name, password)\n const privateKey = await importKey(pem, password)\n\n return await peerIdFromKeys(privateKey.public.bytes, privateKey.bytes)\n }\n\n /**\n * Import a new key from a PEM encoded PKCS #8 string\n *\n * @param {string} name - The local key name; must not already exist.\n * @param {string} pem - The PEM encoded PKCS #8 string\n * @param {string} password - The password.\n * @returns {Promise}\n */\n async importKey (name: string, pem: string, password: string): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (pem == null) {\n await randomDelay()\n throw errCode(new Error('PEM encoded key is required'), codes.ERR_PEM_REQUIRED)\n }\n const dsname = DsName(name)\n const exists = await this.components.datastore.has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n let privateKey\n try {\n privateKey = await importKey(pem, password)\n } catch (err: any) {\n await randomDelay()\n throw errCode(new Error('Cannot read the key, most likely the password is wrong'), codes.ERR_CANNOT_READ_KEY)\n }\n\n let kid\n try {\n kid = await privateKey.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n pem = await privateKey.export(dek)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n const keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.datastore.batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n\n return keyInfo\n }\n\n /**\n * Import a peer key\n */\n async importPeer (name: string, peer: PeerId): Promise {\n try {\n if (!validateKeyName(name)) {\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (peer == null) {\n throw errCode(new Error('PeerId is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n if (peer.privateKey == null) {\n throw errCode(new Error('PeerId.privKey is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peer.privateKey)\n\n const dsname = DsName(name)\n const exists = await this.components.datastore.has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await privateKey.export(dek)\n const keyInfo: KeyInfo = {\n name: name,\n id: peer.toString()\n }\n const batch = this.components.datastore.batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Gets the private key as PEM encoded PKCS #8 string\n */\n async getPrivateKey (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n try {\n const dsname = DsName(name)\n const res = await this.components.datastore.get(dsname)\n return uint8ArrayToString(res)\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (oldPass: string, newPass: string) {\n if (typeof oldPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid old pass type '${typeof oldPass}'`), codes.ERR_INVALID_OLD_PASS_TYPE)\n }\n if (typeof newPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid new pass type '${typeof newPass}'`), codes.ERR_INVALID_NEW_PASS_TYPE)\n }\n if (newPass.length < 20) {\n await randomDelay()\n throw errCode(new Error(`Invalid pass length ${newPass.length}`), codes.ERR_INVALID_PASS_LENGTH)\n }\n log('recreating keychain')\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const oldDek = cached.dek\n this.init.pass = newPass\n const newDek = newPass != null && this.init.dek?.salt != null\n ? pbkdf2(\n newPass,\n this.init.dek.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n privates.set(this, { dek: newDek })\n const keys = await this.listKeys()\n for (const key of keys) {\n const res = await this.components.datastore.get(DsName(key.name))\n const pem = uint8ArrayToString(res)\n const privateKey = await importKey(pem, oldDek)\n const password = newDek.toString()\n const keyAsPEM = await privateKey.export(password)\n\n // Update stored key\n const batch = this.components.datastore.batch()\n const keyInfo = {\n name: key.name,\n id: key.id\n }\n batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))\n batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n }\n log('keychain reconstructed')\n }\n}\n", "import 'node-forge/lib/pkcs7.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { certificateForKey, findAsync } from './util.js'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { codes } from '../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { KeyChain } from './index.js'\n\nconst log = logger('libp2p:keychain:cms')\n\nconst privates = new WeakMap()\n\n/**\n * Cryptographic Message Syntax (aka PKCS #7)\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content.\n *\n * See RFC 5652 for all the details.\n */\nexport class CMS {\n private readonly keychain: KeyChain\n\n /**\n * Creates a new instance with a keychain\n */\n constructor (keychain: KeyChain, dek: string) {\n if (keychain == null) {\n throw errCode(new Error('keychain is required'), codes.ERR_KEYCHAIN_REQUIRED)\n }\n\n this.keychain = keychain\n privates.set(this, { dek })\n }\n\n /**\n * Creates some protected data.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n */\n async encrypt (name: string, plain: Uint8Array): Promise {\n if (!(plain instanceof Uint8Array)) {\n throw errCode(new Error('Plain data must be a Uint8Array'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const key = await this.keychain.findKeyByName(name)\n const pem = await this.keychain.getPrivateKey(name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n const certificate = await certificateForKey(key, privateKey)\n\n // create a p7 enveloped message\n const p7 = forge.pkcs7.createEnvelopedData()\n p7.addRecipient(certificate)\n p7.content = forge.util.createBuffer(plain)\n p7.encrypt()\n\n // convert message to DER\n const der = forge.asn1.toDer(p7.toAsn1()).getBytes()\n return uint8ArrayFromString(der, 'ascii')\n }\n\n /**\n * Reads some protected data.\n *\n * The keychain must contain one of the keys used to encrypt the data. If none of the keys\n * exists, an Error is returned with the property 'missingKeys'. It is array of key ids.\n */\n async decrypt (cmsData: Uint8Array): Promise {\n if (!(cmsData instanceof Uint8Array)) {\n throw errCode(new Error('CMS data is required'), codes.ERR_INVALID_PARAMETERS)\n }\n\n let cms: any\n try {\n const buf = forge.util.createBuffer(uint8ArrayToString(cmsData, 'ascii'))\n const obj = forge.asn1.fromDer(buf)\n\n cms = forge.pkcs7.messageFromAsn1(obj)\n } catch (err: any) {\n log.error(err)\n throw errCode(new Error('Invalid CMS'), codes.ERR_INVALID_CMS)\n }\n\n // Find a recipient whose key we hold. We only deal with recipient certs\n // issued by ipfs (O=ipfs).\n const recipients: any = cms.recipients\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'O' && a.value === 'ipfs'))\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'CN'))\n // @ts-expect-error cms types not defined\n .map(r => {\n return {\n recipient: r,\n // @ts-expect-error cms types not defined\n keyId: r.issuer.find(a => a.shortName === 'CN').value\n }\n })\n\n const r = await findAsync(recipients, async (recipient: any) => {\n try {\n const key = await this.keychain.findKeyById(recipient.keyId)\n if (key != null) {\n return true\n }\n } catch (err: any) {\n return false\n }\n return false\n })\n\n if (r == null) {\n // @ts-expect-error cms types not defined\n const missingKeys: string[] = recipients.map(r => r.keyId)\n throw errCode(new Error(`Decryption needs one of the key(s): ${missingKeys.join(', ')}`), codes.ERR_MISSING_KEYS, {\n missingKeys\n })\n }\n\n const key = await this.keychain.findKeyById(r.keyId)\n\n if (key == null) {\n throw errCode(new Error('No key available to decrypto'), codes.ERR_NO_KEY)\n }\n\n const pem = await this.keychain.getPrivateKey(key.name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n cms.decrypt(r.recipient, privateKey)\n return uint8ArrayFromString(cms.content.getBytes(), 'ascii')\n }\n}\n", "import 'node-forge/lib/x509.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\n\nconst pki = forge.pki\n\n/**\n * Gets a self-signed X.509 certificate for the key.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n *\n * TODO: move to libp2p-crypto package\n */\nexport const certificateForKey = (key: any, privateKey: forge.pki.rsa.PrivateKey) => {\n const publicKey = pki.rsa.setPublicKey(privateKey.n, privateKey.e)\n const cert = pki.createCertificate()\n cert.publicKey = publicKey\n cert.serialNumber = '01'\n cert.validity.notBefore = new Date()\n cert.validity.notAfter = new Date()\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10) // eslint-disable-line @typescript-eslint/restrict-plus-operands\n const attrs = [{\n name: 'organizationName',\n value: 'ipfs'\n }, {\n shortName: 'OU',\n value: 'keystore'\n }, {\n name: 'commonName',\n value: key.id\n }]\n cert.setSubject(attrs)\n cert.setIssuer(attrs)\n cert.setExtensions([{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n emailProtection: true,\n timeStamping: true\n }, {\n name: 'nsCertType',\n client: true,\n server: true,\n email: true,\n objsign: true,\n sslCA: true,\n emailCA: true,\n objCA: true\n }])\n // self-sign certificate\n cert.sign(privateKey)\n\n return cert\n}\n\n/**\n * Finds the first item in a collection that is matched in the\n * `asyncCompare` function.\n *\n * `asyncCompare` is an async function that must\n * resolve to either `true` or `false`.\n *\n * @param {Array} array\n * @param {function(*)} asyncCompare - An async function that returns a boolean\n */\nexport async function findAsync (array: T[], asyncCompare: (val: T) => Promise) {\n const promises = array.map(asyncCompare)\n const results = await Promise.all(promises)\n const index = results.findIndex(result => result)\n return array[index]\n}\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\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n Secp256k1 = 'Secp256k1'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n Secp256k1 = 2\n}\n\nexport namespace KeyType {\n export const codec = () => {\n return enumeration(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PublicKey): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {\n return decodeMessage(buf, PublicKey.codec())\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PrivateKey): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec())\n }\n}\n", "import * as keysPBM from './keys.js'\nimport 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { keyStretcher } from './key-stretcher.js'\nimport generateEphemeralKeyPair from './ephemeral-keys.js'\nimport { importer } from './importer.js'\nimport * as RSA from './rsa-class.js'\nimport * as Ed25519 from './ed25519-class.js'\nimport * as Secp256k1 from './secp256k1-class.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface-keys'\n\nexport { keyStretcher }\nexport { generateEphemeralKeyPair }\nexport { keysPBM }\n\nexport type KeyTypes = 'RSA' | 'Ed25519' | 'secp256k1'\n\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n}\n\nfunction unsupportedKey (type: string) {\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}\n\nfunction typeToKey (type: string) {\n type = type.toLowerCase()\n\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type]\n }\n\n throw unsupportedKey(type)\n}\n\n// Generates a keypair of the given type and bitsize\nexport async function generateKeyPair (type: KeyTypes, bits?: number): Promise { // eslint-disable-line require-await\n return await typeToKey(type).generateKeyPair(bits ?? 2048)\n}\n\n// Generates a keypair of the given type and bitsize\n// seed is a 32 byte uint8array\nexport async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise { // eslint-disable-line require-await\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\n return await Ed25519.generateKeyPairFromSeed(seed)\n}\n\n// Converts a protobuf serialized public key into its\n// representative object\nexport function unmarshalPublicKey (buf: Uint8Array): PublicKey {\n const decoded = keysPBM.PublicKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\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 ?? 'RSA')\n }\n}\n\n// Converts a public key object into a protobuf serialized public key\nexport function marshalPublicKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\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\n// representative object\nexport async function unmarshalPrivateKey (buf: Uint8Array): Promise { // eslint-disable-line require-await\n const decoded = keysPBM.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return await 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\nexport function marshalPrivateKey (key: { bytes: Uint8Array }, type?: string): Uint8Array {\n type = (type ?? 'rsa').toLowerCase()\n typeToKey(type) // check type\n return key.bytes\n}\n\n/**\n *\n * @param {string} encryptedKey\n * @param {string} password\n */\nexport async function importKey (encryptedKey: string, password: string): Promise { // eslint-disable-line require-await\n try {\n const key = await importer(encryptedKey, password)\n return await unmarshalPrivateKey(key)\n } catch (_) {\n // Ignore and try the old pem decrypt\n }\n\n // Only rsa supports pem right now\n const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password)\n if (key === null) {\n throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM')\n }\n let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))\n der = uint8ArrayFromString(der.getBytes(), 'ascii')\n return await supportedKeys.rsa.unmarshalRsaPrivateKey(der)\n}\n", "/* eslint-env browser */\n\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\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(\n new Error(\n '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-crypto/blob/master/README.md#web-crypto-api'\n ),\n { code: 'ERR_MISSING_WEB_CRYPTO' }\n )\n }\n\n return nativeCrypto\n }\n}\n", "import 'node-forge/lib/util.js'\nimport 'node-forge/lib/jsbn.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nexport function bigIntegerToUintBase64url (num: { abs: () => any}, len?: number) {\n // Call `.abs()` to convert to unsigned\n let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian\n\n // toByteArray() gives us back a signed array, which will include a leading 0\n // byte if the most significant bit of the number is 1:\n // https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer\n // Our number will always be positive so we should remove the leading padding.\n buf = buf[0] === 0 ? buf.subarray(1) : buf\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return uint8ArrayToString(buf, 'base64url')\n}\n\n// Convert a base64url encoded string to a BigInteger\nexport function base64urlToBigInteger (str: string): typeof forge.jsbn.BigInteger {\n const buf = base64urlToBuffer(str)\n return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16)\n}\n\nexport function base64urlToBuffer (str: string, len?: number) {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport webcrypto from '../webcrypto.js'\nimport { base64urlToBuffer } from '../util.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { ECDHKey, ECDHKeyPair } from './interface.js'\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n}\n\nconst curveTypes = Object.keys(bits)\nconst names = curveTypes.join(' / ')\n\nexport async function generateEphmeralKeyPair (curve: string) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve\n },\n true,\n ['deriveBits']\n )\n\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair) => {\n let privateKey\n\n if (forcePrivate != null) {\n privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPrivateKey(curve, forcePrivate),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n ['deriveBits']\n )\n } else {\n privateKey = pair.privateKey\n }\n\n const key = await webcrypto.get().subtle.importKey(\n 'jwk',\n unmarshalPublicKey(curve, theirPub),\n {\n name: 'ECDH',\n namedCurve: curve\n },\n false,\n []\n )\n\n const buffer = await webcrypto.get().subtle.deriveBits(\n {\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n },\n privateKey,\n bits[curve]\n )\n\n return new Uint8Array(buffer, 0, buffer.byteLength)\n }\n\n const publicKey = await webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n\n const ecdhKey: ECDHKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n }\n\n return ecdhKey\n}\n\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n}\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: JsonWebKey) {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[jwk.crv]\n\n return uint8ArrayConcat([\n Uint8Array.from([4]), // uncompressed point\n base64urlToBuffer(jwk.x, byteLen),\n base64urlToBuffer(jwk.y, byteLen)\n ], 1 + byteLen * 2)\n}\n\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey (curve: string, key: Uint8Array) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')\n }\n\n const byteLen = curveLengths[curve]\n\n if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT')\n }\n\n return {\n kty: 'EC',\n crv: curve,\n x: uint8ArrayToString(key.subarray(1, byteLen + 1), 'base64url'),\n y: uint8ArrayToString(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n }\n}\n\nconst unmarshalPrivateKey = (curve: string, key: ECDHKeyPair) => ({\n ...unmarshalPublicKey(curve, key.public),\n d: uint8ArrayToString(key.private, 'base64url')\n})\n", "import { concat } from 'uint8arrays/concat'\nimport { fromString } from 'uint8arrays/from-string'\nimport webcrypto from '../webcrypto.js'\nimport type { CreateOptions, AESCipher } from './interface.js'\n\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nexport function create (opts?: CreateOptions) {\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\n const crypto = webcrypto.get()\n keyLength *= 8 // Browser crypto uses bits instead of bytes\n\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: Uint8Array, password: string | Uint8Array) { // eslint-disable-line require-await\n const salt = crypto.getRandomValues(new Uint8Array(saltLength))\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength))\n const aesGcm = { name: algorithm, iv: nonce }\n\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\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', 'deriveBits'])\n const 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 /**\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: Uint8Array, password: string | Uint8Array) {\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\n if (typeof password === 'string') {\n password = fromString(password)\n }\n\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', 'deriveBits'])\n const 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\n const cipher: AESCipher = {\n encrypt,\n decrypt\n }\n\n return cipher\n}\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\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 */\nexport async function importer (privateKey: string, password: string) {\n const encryptedKey = base64.decode(privateKey)\n const cipher = ciphers.create()\n return await cipher.decrypt(encryptedKey, password)\n}\n", "\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport 'node-forge/lib/sha512.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport * as crypto from './rsa.js'\nimport * as pbm from './keys.js'\nimport { exporter } from './exporter.js'\n\nexport class RsaPublicKey {\n private readonly _key: JsonWebKey\n\n constructor (key: JsonWebKey) {\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal () {\n return crypto.utils.jwkToPkix(this._key)\n }\n\n get bytes () {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n encrypt (bytes: Uint8Array) {\n return crypto.encrypt(this._key, bytes)\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class RsaPrivateKey {\n private readonly _key: JsonWebKey\n private readonly _publicKey: JsonWebKey\n\n constructor (key: JsonWebKey, publicKey: JsonWebKey) {\n this._key = key\n this._publicKey = publicKey\n }\n\n genSecret () {\n return crypto.getRandomValues(16)\n }\n\n async sign (message: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndSign(this._key, message)\n }\n\n get public () {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')\n }\n\n return new RsaPublicKey(this._publicKey)\n }\n\n decrypt (bytes: Uint8Array) {\n return crypto.decrypt(this._key, bytes)\n }\n\n marshal () {\n return crypto.utils.jwkToPkcs1(this._key)\n }\n\n get bytes () {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 /**\n * Exports the key into a password protected PEM format\n */\n async export (password: string, format = 'pkcs-8') { // eslint-disable-line require-await\n if (format === 'pkcs-8') {\n const buffer = new forge.util.ByteBuffer(this.marshal())\n const asn1 = forge.asn1.fromDer(buffer)\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n const options = {\n algorithm: 'aes256',\n count: 10000,\n saltSize: 128 / 8,\n prfAlgorithm: 'sha512'\n }\n return forge.pki.encryptRsaPrivateKey(privateKey, password, options)\n } else if (format === 'libp2p-key') {\n return await exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport async function unmarshalRsaPrivateKey (bytes: Uint8Array) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes)\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport function unmarshalRsaPublicKey (bytes: Uint8Array) {\n const jwk = crypto.utils.pkixToJwk(bytes)\n return new RsaPublicKey(jwk)\n}\n\nexport async function fromJwk (jwk: JsonWebKey) {\n const keys = await crypto.unmarshalPrivateKey(jwk)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n\nexport async function generateKeyPair (bits: number) {\n const keys = await crypto.generateKey(bits)\n return new RsaPrivateKey(keys.privateKey, keys.publicKey)\n}\n", "import { utils } from '@noble/secp256k1'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\nexport default function randomBytes (length: number): Uint8Array {\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 utils.randomBytes(length)\n}\n", "import 'node-forge/lib/asn1.js'\nimport 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n// Convert a PKCS#1 in ASN1 DER format to a JWK key\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const privateKey = forge.pki.privateKeyFromAsn1(asn1)\n\n // https://tools.ietf.org/html/rfc7518#section-6.3.1\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(privateKey.n),\n e: bigIntegerToUintBase64url(privateKey.e),\n d: bigIntegerToUintBase64url(privateKey.d),\n p: bigIntegerToUintBase64url(privateKey.p),\n q: bigIntegerToUintBase64url(privateKey.q),\n dp: bigIntegerToUintBase64url(privateKey.dP),\n dq: bigIntegerToUintBase64url(privateKey.dQ),\n qi: bigIntegerToUintBase64url(privateKey.qInv),\n alg: 'RS256'\n }\n}\n\n// Convert a JWK key into PKCS#1 in ASN1 DER format\nexport function jwkToPkcs1 (jwk: JsonWebKey) {\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\n const asn1 = forge.pki.privateKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e),\n d: base64urlToBigInteger(jwk.d),\n p: base64urlToBigInteger(jwk.p),\n q: base64urlToBigInteger(jwk.q),\n dP: base64urlToBigInteger(jwk.dp),\n dQ: base64urlToBigInteger(jwk.dq),\n qInv: base64urlToBigInteger(jwk.qi)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n\n// Convert a PKCIX in ASN1 DER format to a JWK key\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))\n const publicKey = forge.pki.publicKeyFromAsn1(asn1)\n\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(publicKey.n),\n e: bigIntegerToUintBase64url(publicKey.e)\n }\n}\n\n// Convert a JWK key to PKCIX in ASN1 DER format\nexport function jwkToPkix (jwk: JsonWebKey) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')\n }\n\n const asn1 = forge.pki.publicKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e)\n })\n\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')\n}\n", "import 'node-forge/lib/rsa.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { base64urlToBigInteger } from '../util.js'\n\nfunction convert (key: any, types: string[]) {\n return types.map(t => base64urlToBigInteger(key[t]))\n}\n\nexport function jwk2priv (key: JsonWebKey) {\n return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']))\n}\n\nexport function jwk2pub (key: JsonWebKey) {\n return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e']))\n}\n", "import webcrypto from '../webcrypto.js'\nimport randomBytes from '../random-bytes.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport * as utils from './rsa-utils.js'\nimport { jwk2pub, jwk2priv } from './jwk2pem.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\nexport { utils }\n\nexport async function generateKey (bits: number) {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\n// Takes a jwk key\nexport async function unmarshalPrivateKey (key: JsonWebKey) {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign']\n )\n\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ]\n\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n })\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array) {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n Uint8Array.from(msg)\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array) {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return await webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')\n }\n\n return await Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nasync function derivePublicFromPrivate (jwKey: JsonWebKey) {\n return await webcrypto.get().subtle.importKey(\n 'jwk',\n {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n },\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n true,\n ['verify']\n )\n}\n\n/*\n\nRSA encryption/decryption for the browser with webcrypto workaround\n\"bloody dark magic. webcrypto's why.\"\n\nExplanation:\n - Convert JWK to nodeForge\n - Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a \"binary-string backed buffer\", so let's make our Uint8Array a binary string\n - Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array\n\n*/\n\nfunction convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array, handle: (msg: string, key: { encrypt: (msg: string) => string, decrypt: (msg: string) => string}) => string) {\n const fkey = pub ? jwk2pub(key) : jwk2priv(key)\n const fmsg = uint8ArrayToString(Uint8Array.from(msg), 'ascii')\n const fomsg = handle(fmsg, fkey)\n return uint8ArrayFromString(fomsg, 'ascii')\n}\n\nexport function encrypt (key: JsonWebKey, msg: Uint8Array) {\n return convertKey(key, true, msg, (msg, key) => key.encrypt(msg))\n}\n\nexport function decrypt (key: JsonWebKey, msg: Uint8Array) {\n return convertKey(key, false, msg, (msg, key) => key.decrypt(msg))\n}\n", "import { base64 } from 'multiformats/bases/base64'\nimport * as ciphers from '../ciphers/aes-gcm.js'\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 */\nexport async function exporter (privateKey: Uint8Array, password: string) {\n const cipher = ciphers.create()\n const encryptedKey = await cipher.encrypt(privateKey, password)\n return base64.encode(encryptedKey)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { identity } from 'multiformats/hashes/identity'\nimport * as crypto from './ed25519.js'\nimport * as pbm from './keys.js'\nimport { exporter } from './exporter.js'\n\nexport class Ed25519PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = ensureKey(key, crypto.publicKeyLength)\n }\n\n async verify (data: Uint8Array, sig: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal () {\n return this._key\n }\n\n get bytes () {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Ed25519PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }\n\n async sign (message: Uint8Array) { // eslint-disable-line require-await\n return await crypto.hashAndSign(this._key, message)\n }\n\n get public () {\n return new Ed25519PublicKey(this._publicKey)\n }\n\n marshal () {\n return this._key\n }\n\n get bytes () {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 = await identity.digest(this.public.bytes)\n return base58btc.encode(encoding.bytes).substring(1)\n }\n\n /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key') { // eslint-disable-line require-await\n if (format === 'libp2p-key') {\n return await exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array) {\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\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}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array) {\n bytes = ensureKey(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKey(bytes)\n}\n\nexport async function generateKeyPair () {\n const { privateKey, publicKey } = await crypto.generateKey()\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nexport async function generateKeyPairFromSeed (seed: Uint8Array) {\n const { privateKey, publicKey } = await crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKey(privateKey, publicKey)\n}\n\nfunction ensureKey (key: Uint8Array, length: number) {\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", "import * as ed from '@noble/ed25519'\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\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport async function generateKey () {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport async function generateKeyFromSeed (seed: Uint8Array) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = await ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return await ed.sign(msg, privateKeyRaw)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array) {\n return await ed.verify(sig, msg, publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array) {\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", "import { sha256 } from 'multiformats/hashes/sha2'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as crypto from './secp256k1.js'\nimport { exporter } from './exporter.js'\nimport * as keysProtobuf from './keys.js'\n\nexport class Secp256k1PublicKey {\n private readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n crypto.validatePublicKey(key)\n this._key = key\n }\n\n async verify (data: Uint8Array, sig: Uint8Array) {\n return await crypto.hashAndVerify(this._key, sig, data)\n }\n\n marshal () {\n return crypto.compressPublicKey(this._key)\n }\n\n get bytes () {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\n}\n\nexport class Secp256k1PrivateKey {\n private readonly _key: Uint8Array\n private readonly _publicKey: Uint8Array\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this._key = key\n this._publicKey = publicKey ?? crypto.computePublicKey(key)\n crypto.validatePrivateKey(this._key)\n crypto.validatePublicKey(this._publicKey)\n }\n\n async sign (message: Uint8Array) {\n return await crypto.hashAndSign(this._key, message)\n }\n\n get public () {\n return new Secp256k1PublicKey(this._publicKey)\n }\n\n marshal () {\n return this._key\n }\n\n get bytes () {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray()\n }\n\n equals (key: any) {\n return uint8ArrayEquals(this.bytes, key.bytes)\n }\n\n async hash () {\n const { bytes } = await sha256.digest(this.bytes)\n\n return bytes\n }\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 /**\n * Exports the key into a password protected `format`\n */\n async export (password: string, format = 'libp2p-key') { // eslint-disable-line require-await\n if (format === 'libp2p-key') {\n return await exporter(this.bytes, password)\n } else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')\n }\n }\n}\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array) {\n return new Secp256k1PrivateKey(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array) {\n return new Secp256k1PublicKey(bytes)\n}\n\nexport async function generateKeyPair () {\n const privateKeyBytes = await crypto.generateKey()\n return new Secp256k1PrivateKey(privateKeyBytes)\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport * as secp from '@noble/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey () {\n return secp.utils.randomPrivateKey()\n}\n\n/**\n * Hash and sign message with private key\n */\nexport async function hashAndSign (key: Uint8Array, msg: Uint8Array) {\n const { digest } = await sha256.digest(msg)\n try {\n return await secp.sign(digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array) {\n try {\n const { digest } = await sha256.digest(msg)\n return secp.verify(sig, digest, key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT')\n }\n}\n\nexport function compressPublicKey (key: Uint8Array) {\n const point = secp.Point.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressPublicKey (key: Uint8Array) {\n const point = secp.Point.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validatePrivateKey (key: Uint8Array) {\n try {\n secp.getPublicKey(key, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n\nexport function validatePublicKey (key: Uint8Array) {\n try {\n secp.Point.fromHex(key)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')\n }\n}\n\nexport function computePublicKey (privateKey: Uint8Array) {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')\n }\n}\n", "\nimport 'node-forge/lib/aes.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array) {\n const cipher2 = forge.cipher.createCipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n\nexport function createDecipheriv (mode: any, key: Uint8Array, iv: Uint8Array) {\n const cipher2 = forge.cipher.createDecipher('AES-CTR', uint8ArrayToString(key, 'ascii'))\n cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })\n return {\n update: (data: Uint8Array) => {\n cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))\n return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')\n }\n }\n}\n", "// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw new CodeError(`Hash '${hash}' is unknown or not supported. Must be ${types}`, 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n", "export default async function pReflect(promise) {\n\ttry {\n\t\tconst value = await promise;\n\n\t\treturn {\n\t\t\tstatus: 'fulfilled',\n\t\t\tvalue,\n\t\t\tisFulfilled: true,\n\t\t\tisRejected: false\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: 'rejected',\n\t\t\treason: error,\n\t\t\tisFulfilled: false,\n\t\t\tisRejected: true\n\t\t};\n\t}\n}\n\nexport function isFulfilled(promiseResult) {\n\treturn 'value' in promiseResult;\n}\n\nexport function isRejected(promiseResult) {\n\treturn 'reason' in promiseResult;\n}\n", "/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\t\treturn current.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n}\n", "import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n", "import pReflect from 'p-reflect';\nimport pLimit from 'p-limit';\n\nexport default async function pSettle(array, options = {}) {\n\tconst {concurrency = Number.POSITIVE_INFINITY} = options;\n\tconst limit = pLimit(concurrency);\n\n\treturn Promise.all(array.map(element => {\n\t\tif (element && typeof element.then === 'function') {\n\t\t\treturn pReflect(element);\n\t\t}\n\n\t\tif (typeof element === 'function') {\n\t\t\treturn pReflect(limit(() => element()));\n\t\t}\n\n\t\treturn pReflect(Promise.resolve(element));\n\t}));\n}\n", "import { logger } from '@libp2p/logger'\nimport pSettle from 'p-settle'\nimport { codes } from './errors.js'\nimport errCode from 'err-code'\nimport { FaultTolerance } from '@libp2p/interface-transport'\nimport type { Listener, Transport, TransportManager, TransportManagerEvents, Upgrader } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:transports')\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport interface DefaultTransportManagerComponents {\n metrics?: Metrics\n addressManager: AddressManager\n upgrader: Upgrader\n}\n\nexport class DefaultTransportManager extends EventEmitter implements TransportManager, Startable {\n private readonly components: DefaultTransportManagerComponents\n private readonly transports: Map\n private readonly listeners: Map\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: DefaultTransportManagerComponents, init: TransportManagerInit = {}) {\n super()\n\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\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport) {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw errCode(new Error('Transport must have a valid tag'), codes.ERR_INVALID_KEY)\n }\n\n if (this.transports.has(tag)) {\n throw errCode(new Error('There is already a transport with this tag'), codes.ERR_DUPLICATE_TRANSPORT)\n }\n\n log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs()\n\n await this.listen(addrs)\n\n this.started = true\n }\n\n /**\n * Stops all listeners\n */\n async stop () {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: AbortOptions): Promise {\n const transport = this.transportForMultiaddr(ma)\n\n if (transport == null) {\n throw errCode(new Error(`No transport available for address ${String(ma)}`), codes.ERR_TRANSPORT_UNAVAILABLE)\n }\n\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n })\n } catch (err: any) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED\n }\n\n throw err\n }\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\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 /**\n * Returns all the transports instances\n */\n getTransports () {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr (ma: Multiaddr) {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]) {\n if (addrs == null || addrs.length === 0) {\n log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n const couldNotListen = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs)\n const tasks = []\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n log('creating listener for %s on %s', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n })\n\n let listeners = this.listeners.get(key)\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.dispatchEvent(new CustomEvent('listener:listening', {\n detail: listener\n }))\n })\n listener.addEventListener('close', () => {\n this.dispatchEvent(new CustomEvent('listener:close', {\n detail: listener\n }))\n })\n\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr))\n }\n\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key)\n continue\n }\n\n const results = await pSettle(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.isFulfilled)\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES)\n }\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 errCode(new Error(message), codes.ERR_NO_VALID_ADDRESSES)\n }\n log(`libp2p in dial mode only: ${message}`)\n }\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: string) {\n log('removing %s', key)\n\n // Close any running listeners\n for (const listener of this.listeners.get(key) ?? []) {\n await listener.close()\n }\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\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\n await Promise.all(tasks)\n }\n}\n", "import type { Metric, Metrics } from '@libp2p/interface-metrics'\n\nexport interface TrackedMapInit {\n name: string\n metrics: Metrics\n}\n\nclass TrackedMap extends Map {\n private readonly metric: Metric\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { name, metrics } = init\n\n this.metric = metrics.registerMetric(name)\n this.updateComponentMetric()\n }\n\n set (key: K, value: V) {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K) {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear () {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric () {\n this.metric.update(this.size)\n }\n}\n\nexport interface CreateTrackedMapInit {\n /**\n * The metric name to use\n */\n name: string\n\n /**\n * A metrics implementation\n */\n metrics?: Metrics\n}\n\nexport function trackedMap (config: CreateTrackedMapInit): Map {\n const { name, metrics } = config\n let map: Map\n\n if (metrics != null) {\n map = new TrackedMap({ name, metrics })\n } else {\n map = new Map()\n }\n\n return map\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mss from '@libp2p/multistream-select'\nimport { codes } from './errors.js'\nimport { createConnection } from './connection/index.js'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { MultiaddrConnection, Connection, Stream, ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Upgrader, UpgraderEvents, UpgraderOptions } from '@libp2p/interface-transport'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:upgrader')\n\ninterface CreateConectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: Duplex\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncryption: ConnectionEncrypter[]\n muxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade\n * must complete\n */\n inboundUpgradeTimeout: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxOutboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection) {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.stat.direction === direction && stream.stat.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport interface DefaultUpgraderComponents {\n peerId: PeerId\n metrics?: Metrics\n connectionManager: ConnectionManager\n connectionGater: ConnectionGater\n connectionProtector?: ConnectionProtector\n registrar: Registrar\n peerStore: PeerStore\n}\n\nexport class DefaultUpgrader extends EventEmitter implements Upgrader {\n private readonly components: DefaultUpgraderComponents\n private readonly connectionEncryption: Map\n private readonly muxers: Map\n private readonly inboundUpgradeTimeout: number\n\n constructor (components: DefaultUpgraderComponents, init: UpgraderInit) {\n super()\n\n this.components = components\n this.connectionEncryption = new Map()\n\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter)\n })\n\n this.muxers = new Map()\n\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)\n\n if (!accept) {\n throw errCode(new Error('connection denied'), codes.ERR_CONNECTION_DENIED)\n }\n\n let encryptedConn\n let remotePeer\n let upgradedConn: Duplex\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n\n const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const abortableStream = abortableDuplex(maConn, timeoutController.signal)\n maConn.source = abortableStream.source\n maConn.sink = abortableStream.sink\n\n if (await this.components.connectionGater.denyInboundConnection(maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n log('starting the inbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n log('protecting the inbound connection')\n protectedConn = await protector.protect(maConn)\n }\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\n if (await this.components.connectionGater.denyInboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n } else {\n const idStr = maConn.remoteAddr.getPeerId()\n\n if (idStr == null) {\n throw errCode(new Error('inbound connection that skipped encryption must have a peer id'), codes.ERR_INVALID_MULTIADDR)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\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 } catch (err: any) {\n log.error('Failed to upgrade inbound connection', err)\n throw err\n }\n\n if (await this.components.connectionGater.denyInboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n log('Successfully upgraded inbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n } finally {\n this.components.connectionManager.afterUpgradeInbound()\n timeoutController.clear()\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise {\n const idStr = maConn.remoteAddr.getPeerId()\n let remotePeerId: PeerId | undefined\n\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr)\n\n if (await this.components.connectionGater.denyOutboundConnection(remotePeerId, maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n }\n\n let encryptedConn\n let remotePeer: PeerId\n let upgradedConn\n let cryptoProtocol\n let muxerFactory\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n log('Starting the outbound connection upgrade')\n\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n\n // Protect\n let protectedConn = maConn\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n protectedConn = await protector.protect(maConn)\n }\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\n if (await this.components.connectionGater.denyOutboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n } else {\n if (remotePeerId == null) {\n throw errCode(new Error('Encryption was skipped but no peer id was passed'), codes.ERR_INVALID_PEER)\n }\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\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 } catch (err: any) {\n log.error('Failed to upgrade outbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.connectionGater.denyOutboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n log('Successfully upgraded outbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\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\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('%s: incoming stream opened on %s', direction, protocol)\n\n if (connection == null) {\n return\n }\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS))\n\n return\n }\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.stat.protocol = protocol\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 this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n connection.addStream(muxedStream)\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n this._onStream({ connection, stream: muxedStream, protocol })\n })\n .catch(err => {\n log.error(err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n })\n },\n // Run anytime a stream closes\n onStreamEnd: muxedStream => {\n connection?.removeStream(muxedStream.id)\n }\n })\n\n newStream = async (protocols: string[], options: AbortOptions = {}): Promise => {\n if (muxer == null) {\n throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)\n }\n\n log('%s: starting new stream on %s', direction, protocols)\n const muxedStream = await muxer.newStream()\n let controller: TimeoutController | undefined\n\n try {\n if (options.signal == null) {\n log('No abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n controller = new TimeoutController(30000)\n options.signal = controller.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n }\n\n const { stream, protocol } = await mss.select(muxedStream, protocols, options)\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar)\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount === outgoingLimit) {\n const err = errCode(new Error(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\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 this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(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.stat.protocol = protocol\n\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n return muxedStream\n } catch (err: any) {\n log.error('could not create new stream', err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n\n if (err.code != null) {\n throw err\n }\n\n throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL)\n } finally {\n if (controller != null) {\n controller.clear()\n }\n }\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 log.error(err)\n })\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.stat.status === 'OPEN') {\n await connection.close()\n }\n } catch (err: any) {\n log.error(err)\n } finally {\n this.dispatchEvent(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n }\n })().catch(err => {\n log.error(err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = () => {\n throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED)\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer: remotePeer,\n stat: {\n status: 'OPEN',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol\n },\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => muxer != null ? muxer.streams : errConnectionNotMultiplexed(),\n close: async () => {\n await maConn.close()\n // Ensure remaining streams are closed\n if (muxer != null) {\n muxer.close()\n }\n }\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: connection\n }))\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler } = this.components.registrar.getHandler(protocol)\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: Duplex): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('handling inbound crypto protocol selection', protocols)\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting inbound connection...')\n\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\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: MultiaddrConnection, remotePeerId?: PeerId): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('selecting outbound crypto protocol', protocols)\n\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting outbound connection to %p', remotePeerId)\n\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\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: MultiaddrConnection, muxers: Map): Promise<{stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('outbound selecting muxer %s', protocols)\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n log('%s selected as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing outbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\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: MultiaddrConnection, muxers: Map): Promise<{stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing inbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n}\n", "\nexport const PROTOCOL_ID = '/multistream/1.0.0'\n\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", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { PROTOCOL_ID } from './index.js'\nimport type { Duplex } from 'it-stream-types'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { pushable } from 'it-pushable'\nimport merge from 'it-merge'\nimport { reader } from 'it-reader'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:select')\n\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 * ```js\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: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options: MultistreamSelectInit = {}): Promise> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n const { reader, writer, rest, stream: shakeStream } = handshake(stream)\n\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n log('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n multistream.writeAll(writer, [p1, p2], options)\n\n let response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n rest()\n return { stream: shakeStream, protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n log('select: write \"%s\"', protocol)\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n const response = await multistream.readString(reader, options)\n log('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n rest() // End our writer so others can start writing to stream\n return { stream: shakeStream, protocol }\n }\n }\n\n rest()\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n}\n\n/**\n * Lazily 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 */\nexport function lazySelect (stream: Duplex, protocol: string): ProtocolStream\nexport function lazySelect (stream: Duplex, protocol: string): ProtocolStream\nexport function lazySelect (stream: Duplex, protocol: string): ProtocolStream {\n // This is a signal to write the multistream headers if the consumer tries to\n // read from the source\n const negotiateTrigger = pushable()\n let negotiated = false\n return {\n stream: {\n sink: async source => await stream.sink((async function * () {\n let first = true\n for await (const chunk of merge(source, negotiateTrigger)) {\n if (first) {\n first = false\n negotiated = true\n negotiateTrigger.end()\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n const list = new Uint8ArrayList(multistream.encode(p1), multistream.encode(p2))\n if (chunk.length > 0) list.append(chunk)\n yield * list\n } else {\n yield chunk\n }\n }\n })()),\n source: (async function * () {\n if (!negotiated) negotiateTrigger.push(new Uint8Array())\n const byteReader = reader(stream.source)\n let response = await multistream.readString(byteReader)\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(byteReader)\n }\n if (response !== protocol) {\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n }\n for await (const chunk of byteReader) {\n yield * chunk\n }\n })()\n },\n protocol\n }\n}\n", "\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport first from 'it-first'\nimport { abortableSource } from 'abortable-iterator'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Pushable } from 'it-pushable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Source } from 'it-stream-types'\nimport type { Reader } from 'it-reader'\nimport type { MultistreamSelectInit } from '.'\nimport { MAX_PROTOCOL_LENGTH } from './constants.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:mss')\n\nconst NewLine = uint8ArrayFromString('\\n')\n\nexport function encode (buffer: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const list = new Uint8ArrayList(buffer, NewLine)\n\n return lp.encode.single(list)\n}\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport function write (writer: Pushable, buffer: Uint8Array | Uint8ArrayList, options: MultistreamSelectInit = {}) {\n const encoded = encode(buffer)\n\n if (options.writeBytes === true) {\n writer.push(encoded.subarray())\n } else {\n writer.push(encoded)\n }\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport function writeAll (writer: Pushable, buffers: Uint8Array[], options: MultistreamSelectInit = {}) {\n const list = new Uint8ArrayList()\n\n for (const buf of buffers) {\n list.append(encode(buf))\n }\n\n if (options.writeBytes === true) {\n writer.push(list.subarray())\n } else {\n writer.push(list)\n }\n}\n\nexport async function read (reader: Reader, options?: AbortOptions): Promise {\n let byteLength = 1 // Read single byte chunks until the length is known\n const varByteSource = { // No return impl - we want the reader to remain readable\n [Symbol.asyncIterator]: () => varByteSource,\n next: async () => await reader.next(byteLength)\n }\n\n let input: Source = varByteSource\n\n // If we have been passed an abort signal, wrap the input source in an abortable\n // iterator that will throw if the operation is aborted\n if (options?.signal != null) {\n input = abortableSource(varByteSource, options.signal)\n }\n\n // Once the length has been parsed, read chunk for that length\n const onLength = (l: number) => {\n byteLength = l\n }\n\n const buf = await pipe(\n input,\n lp.decode({ onLength, maxDataLength: MAX_PROTOCOL_LENGTH }),\n async (source) => await first(source)\n )\n\n if (buf == null || buf.length === 0) {\n throw errCode(new Error('no buffer returned'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n if (buf.get(buf.byteLength - 1) !== NewLine[0]) {\n log.error('Invalid mss message - missing newline - %s', buf.subarray())\n throw errCode(new Error('missing newline'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\nexport async function readString (reader: Reader, options?: AbortOptions) {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n", "import { logger } from '@libp2p/logger'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { PROTOCOL_ID } from './constants.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:handle')\n\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 * ```js\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: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n const { writer, reader, rest, stream: shakeStream } = handshake(stream)\n\n while (true) {\n const protocol = await multistream.readString(reader, options)\n log('read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n log('respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n multistream.write(writer, uint8ArrayFromString(PROTOCOL_ID), options)\n continue\n }\n\n if (protocols.includes(protocol)) {\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n log('respond with \"%s\" for \"%s\"', protocol, protocol)\n rest()\n return { stream: shakeStream, protocol }\n }\n\n if (protocol === 'ls') {\n // \\n\\n\\n\n multistream.write(writer, new Uint8ArrayList(...protocols.map(p => multistream.encode(uint8ArrayFromString(p)))), options)\n // multistream.writeAll(writer, protocols.map(p => uint8ArrayFromString(p)))\n log('respond with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n multistream.write(writer, uint8ArrayFromString('na'), options)\n log('respond with \"na\" for \"%s\"', protocol)\n }\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'\nimport { symbol } from '@libp2p/interface-connection'\nimport type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\nconst log = logger('libp2p:connection')\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream: (protocols: string[], options?: AbortOptions) => Promise\n close: () => Promise\n getStreams: () => Stream[]\n stat: ConnectionStat\n}\n\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 implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n /**\n * Connection metadata\n */\n public readonly stat: ConnectionStat\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: AbortOptions) => Promise\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: () => Promise\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n private _closing: boolean\n\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: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, getStreams, stat } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.stat = {\n ...stat,\n status: OPEN\n }\n this._newStream = newStream\n this._close = close\n this._getStreams = getStreams\n this.tags = []\n this._closing = false\n }\n\n get [Symbol.toStringTag] () {\n return 'Connection'\n }\n\n get [symbol] () {\n return true\n }\n\n /**\n * Get all the streams of the muxer\n */\n get streams () {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: AbortOptions): Promise {\n if (this.stat.status === CLOSING) {\n throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')\n }\n\n if (this.stat.status === CLOSED) {\n throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.stat.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Add a stream when it is opened to the registry\n */\n addStream (stream: Stream) {\n stream.stat.direction = 'inbound'\n }\n\n /**\n * Remove stream registry after it is closed\n */\n removeStream (id: string) {\n\n }\n\n /**\n * Close the connection\n */\n async close () {\n if (this.stat.status === CLOSED || this._closing) {\n return\n }\n\n this.stat.status = CLOSING\n\n // close all streams - this can throw if we're not multiplexed\n try {\n this.streams.forEach(s => s.close())\n } catch (err) {\n log.error(err)\n }\n\n // Close raw connection\n this._closing = true\n await this._close()\n this._closing = false\n\n this.stat.timeline.close = Date.now()\n this.stat.status = CLOSED\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type * as Status from './status.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface ConnectionStat {\n /**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * Once a multiplexer has been negotiated for this stream, it will be set on the stat object\n */\n multiplexer?: string\n\n /**\n * Once a connection encrypter has been negotiated for this stream, it will be set on the stat object\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: keyof typeof Status\n}\n\nexport interface StreamTimeline {\n open: number\n close?: number\n}\n\nexport interface StreamStat {\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * Once a protocol has been negotiated for this stream, it will be set on the stat object\n */\n protocol?: string\n}\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex {\n /**\n * Closes the stream for **reading** *and* **writing**.\n *\n * Any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `CLOSE` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink and the source will return normally.\n */\n close: () => void\n\n /**\n * Closes the stream for **reading**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * This function is called automatically by the muxer when it receives a `CLOSE` message from the remote.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeRead: () => void\n\n /**\n * Closes the stream for **writing**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeWrite: () => void\n\n /**\n * Closes the stream for **reading** *and* **writing**. This should be called when a *local error* has occurred.\n *\n * Note, if called without an error any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `RESET` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink will return and the source will throw if an error is passed or return normally if not.\n */\n abort: (err: Error) => void\n\n /**\n * Closes the stream *immediately* for **reading** *and* **writing**. This should be called when a *remote error* has occurred.\n *\n * This function is called automatically by the muxer when it receives a `RESET` message from the remote.\n *\n * The sink will return and the source will throw.\n */\n reset: () => void\n\n /**\n * Unique identifier for a stream. Identifiers are not unique across muxers.\n */\n id: string\n\n /**\n * Stats about this stream\n */\n stat: StreamStat\n\n /**\n * User defined stream metadata\n */\n metadata: Record\n}\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n id: string\n stat: ConnectionStat\n remoteAddr: Multiaddr\n remotePeer: PeerId\n tags: string[]\n streams: Stream[]\n\n newStream: (multicodecs: string | string[], options?: AbortOptions) => Promise\n addStream: (stream: Stream) => void\n removeStream: (id: string) => void\n close: () => Promise\n}\n\nexport const symbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface ConnectionGater {\n /**\n * denyDialMultiaddr tests whether we're permitted to Dial the\n * specified peer.\n *\n * This is called by the dialer.connectToPeer implementation before\n * dialling a peer.\n *\n * Return true to prevent dialing the passed peer.\n */\n denyDialPeer: (peerId: PeerId) => Promise\n\n /**\n * denyDialMultiaddr tests whether we're permitted to dial the specified\n * multiaddr for the given peer.\n *\n * This is called by the dialer.connectToPeer implementation after it has\n * resolved the peer's addrs, and prior to dialling each.\n *\n * Return true to prevent dialing the passed peer on the passed multiaddr.\n */\n denyDialMultiaddr: (peerId: PeerId, multiaddr: Multiaddr) => Promise\n\n /**\n * denyInboundConnection tests whether an incipient inbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has accepted a connection from its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyInboundConnection: (maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundConnection tests whether an incipient outbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has created a connection with its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyOutboundConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyInboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyOutboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyInboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyOutboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * Used by the address book to filter passed addresses.\n *\n * Return true to allow storing the passed multiaddr for the passed peer.\n */\n filterMultiaddrForPeer: (peer: PeerId, multiaddr: Multiaddr) => Promise\n}\n\nexport interface ConnectionProtector {\n\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect: (connection: MultiaddrConnection) => Promise\n}\n\nexport interface MultiaddrConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex {\n close: (err?: Error) => Promise\n remoteAddr: Multiaddr\n timeline: MultiaddrConnectionTimeline\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar'\nimport merge from 'merge-options'\nimport type { Registrar, StreamHandler, Topology } from '@libp2p/interface-registrar'\nimport type { PeerProtocolsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:registrar')\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\nexport interface RegistrarComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n peerStore: PeerStore\n}\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar implements Registrar {\n private readonly topologies: Map>\n private readonly handlers: Map\n private readonly components: RegistrarComponents\n\n constructor (components: RegistrarComponents) {\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onConnect = this._onConnect.bind(this)\n\n this.components.connectionManager.addEventListener('peer:disconnect', this._onDisconnect)\n this.components.connectionManager.addEventListener('peer:connect', this._onConnect)\n\n // happens after identify\n this.components.peerStore.addEventListener('change:protocols', this._onProtocolChange)\n }\n\n getProtocols () {\n return Array.from(new Set([\n ...this.topologies.keys(),\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string) {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL)\n }\n\n return handler\n }\n\n getTopologies (protocol: string) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise {\n if (this.handlers.has(protocol)) {\n throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocols to self protocols in the Protobook\n await this.components.peerStore.protoBook.add(this.components.peerId, [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: string | string[]) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Remove protocols from self protocols in the Protobook\n await this.components.peerStore.protoBook.remove(this.components.peerId, protocolList)\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise {\n if (!isTopology(topology)) {\n log.error('topology must be an instance of interfaces/topology')\n throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n // Set registrar\n await topology.setRegistrar(this)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.peerStore.protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(connection.remotePeer)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * On peer connected if we already have their protocols. Usually used for reconnects\n * as change:protocols event won't be emitted due to identical protocols.\n */\n _onConnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.peerStore.protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onConnect(connection.remotePeer, connection)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Check if a new peer support the multicodecs for this topology\n */\n _onProtocolChange (evt: CustomEvent) {\n const { peerId, protocols, oldProtocols } = evt.detail\n const removed = oldProtocols.filter(protocol => !protocols.includes(protocol))\n const added = protocols.filter(protocol => !oldProtocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(peerId)\n }\n }\n\n for (const protocol of added) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n const connection = this.components.connectionManager.getConnections(peerId)[0]\n\n if (connection == null) {\n continue\n }\n topology.onConnect(peerId, connection)\n }\n }\n }\n}\n", "import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n getProtocols: () => string[]\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n unhandle: (protocol: string) => Promise\n getHandler: (protocol: string) => StreamHandlerRecord\n\n register: (protocol: string, topology: Topology) => Promise\n unregister: (id: string) => void\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n onConnect?: onConnectHandler\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport { Identify } from './pb/message.js'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport {\n MULTICODEC_IDENTIFY,\n MULTICODEC_IDENTIFY_PUSH,\n IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION\n} from './consts.js'\nimport { codes } from '../errors.js'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:identify')\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8\n\nexport interface HostProperties {\n agentVersion: string\n}\n\nexport interface IdentifyServiceInit {\n /**\n * The prefix to use for the protocol (default: 'ipfs')\n */\n protocolPrefix: string\n\n /**\n * What details we should send as part of an identify message\n */\n host: HostProperties\n\n /**\n * How long we should wait for a remote peer to send their identify response\n */\n timeout: number\n\n /**\n * Identify responses larger than this in bytes will be rejected (default: 8192)\n */\n maxIdentifyMessageSize?: number\n\n maxInboundStreams: number\n maxOutboundStreams: number\n\n maxPushIncomingStreams: number\n maxPushOutgoingStreams: number\n}\n\nexport interface IdentifyServiceComponents {\n peerId: PeerId\n peerStore: PeerStore\n connectionManager: ConnectionManager\n registrar: Registrar\n addressManager: AddressManager\n}\n\nexport class IdentifyService implements Startable {\n private readonly components: IdentifyServiceComponents\n private readonly identifyProtocolStr: string\n private readonly identifyPushProtocolStr: string\n public readonly host: {\n protocolVersion: string\n agentVersion: string\n }\n\n private readonly init: IdentifyServiceInit\n private started: boolean\n\n constructor (components: IdentifyServiceComponents, init: IdentifyServiceInit) {\n this.components = components\n this.started = false\n this.init = init\n\n this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`\n this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`\n\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n ...init.host\n }\n\n // When a new connection happens, trigger identify\n this.components.connectionManager.addEventListener('peer:connect', (evt) => {\n const connection = evt.detail\n this.identify(connection).catch(log.error)\n })\n\n // When self multiaddrs change, trigger identify-push\n this.components.peerStore.addEventListener('change:multiaddrs', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.peerId.equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n\n // When self protocols change, trigger identify-push\n this.components.peerStore.addEventListener('change:protocols', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.peerId.equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n if (this.started) {\n return\n }\n\n await this.components.peerStore.metadataBook.setValue(this.components.peerId, 'AgentVersion', uint8ArrayFromString(this.host.agentVersion))\n await this.components.peerStore.metadataBook.setValue(this.components.peerId, 'ProtocolVersion', uint8ArrayFromString(this.host.protocolVersion))\n\n await this.components.registrar.handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n await this.components.registrar.handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxPushIncomingStreams,\n maxOutboundStreams: this.init.maxPushOutgoingStreams\n })\n\n this.started = true\n }\n\n async stop () {\n await this.components.registrar.unhandle(this.identifyProtocolStr)\n await this.components.registrar.unhandle(this.identifyPushProtocolStr)\n\n this.started = false\n }\n\n /**\n * Send an Identify Push update to the list of connections\n */\n async push (connections: Connection[]): Promise {\n const signedPeerRecord = await this.components.peerStore.addressBook.getRawEnvelope(this.components.peerId)\n const listenAddrs = this.components.addressManager.getAddresses().map((ma) => ma.bytes)\n const protocols = await this.components.peerStore.protoBook.get(this.components.peerId)\n\n const pushes = connections.map(async connection => {\n let stream: Stream | undefined\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n stream = await connection.newStream([this.identifyPushProtocolStr], {\n signal: timeoutController.signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await source.sink(pipe(\n [Identify.encode({\n listenAddrs,\n signedPeerRecord,\n protocols\n })],\n lp.encode()\n ))\n } catch (err: any) {\n // Just log errors\n log.error('could not push identify update to peer', err)\n } finally {\n if (stream != null) {\n stream.close()\n }\n\n timeoutController.clear()\n }\n })\n\n await Promise.all(pushes)\n }\n\n /**\n * Calls `push` on all peer connections\n */\n async pushToPeerStore () {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return\n }\n\n const connections: Connection[] = []\n\n for (const conn of this.components.connectionManager.getConnections()) {\n const peerId = conn.remotePeer\n const peer = await this.components.peerStore.get(peerId)\n\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n continue\n }\n\n connections.push(conn)\n }\n\n await this.push(connections)\n }\n\n async _identify (connection: Connection, options: AbortOptions = {}): Promise {\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.identifyProtocolStr], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data == null) {\n throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED)\n }\n\n try {\n return Identify.decode(data)\n } catch (err: any) {\n throw errCode(err, codes.ERR_INVALID_MESSAGE)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Requests the `Identify` message from peer associated with the given `connection`.\n * If the identified peer does not match the `PeerId` associated with the connection,\n * an error will be thrown.\n */\n async identify (connection: Connection, options: AbortOptions = {}): Promise {\n const message = await this._identify(connection, options)\n\n const {\n publicKey,\n listenAddrs,\n protocols,\n observedAddr,\n signedPeerRecord,\n agentVersion,\n protocolVersion\n } = message\n\n if (publicKey == null) {\n throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY)\n }\n\n const id = await peerIdFromKeys(publicKey)\n\n if (!connection.remotePeer.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (this.components.peerId.equals(id)) {\n throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER)\n }\n\n // Get the observedAddr if there is one\n const cleanObservedAddr = IdentifyService.getCleanMultiaddr(observedAddr)\n\n if (signedPeerRecord != null) {\n log('received signed peer record from %p', id)\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN)\n\n if (!envelope.peerId.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (await this.components.peerStore.addressBook.consumePeerRecord(envelope)) {\n await this.components.peerStore.protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n return\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('no signed peer record received from %p', id)\n }\n\n log('falling back to legacy addresses from %p', id)\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.peerStore.addressBook.set(id, listenAddrs.map((addr) => multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n await this.components.peerStore.protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.peerStore.metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n // TODO: Add and score our observed addr\n log('received observed address of %s', cleanObservedAddr?.toString())\n // this.components.addressManager.addObservedAddr(observedAddr)\n }\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: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const publicKey = this.components.peerId.publicKey ?? new Uint8Array(0)\n const peerData = await this.components.peerStore.get(this.components.peerId)\n const multiaddrs = this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n let signedPeerRecord = peerData.peerRecordEnvelope\n\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.components.peerId,\n multiaddrs\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.peerId)\n await this.components.peerStore.addressBook.consumePeerRecord(envelope)\n signedPeerRecord = envelope.marshal().subarray()\n }\n\n const message = Identify.encode({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr: connection.remoteAddr.bytes,\n protocols: peerData.protocols\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const msgWithLenPrefix = pipe([message], lp.encode())\n await source.sink(msgWithLenPrefix)\n } catch (err: any) {\n log.error('could not respond to identify request', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n }\n\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n let message: Identify | undefined\n try {\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data != null) {\n message = Identify.decode(data)\n }\n } catch (err: any) {\n return log.error('received invalid message', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n\n if (message == null) {\n return log.error('received invalid message')\n }\n\n const id = connection.remotePeer\n\n if (this.components.peerId.equals(id)) {\n log('received push from ourselves?')\n return\n }\n\n log('received push from %p', id)\n\n if (message.signedPeerRecord != null) {\n log('received signedPeerRecord in push')\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(message.signedPeerRecord, PeerRecord.DOMAIN)\n\n if (await this.components.peerStore.addressBook.consumePeerRecord(envelope)) {\n log('consumed signedPeerRecord sent in push')\n\n await this.components.peerStore.protoBook.set(id, message.protocols)\n return\n } else {\n log('failed to consume signedPeerRecord sent in push')\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('did not receive signedPeerRecord in push')\n }\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.peerStore.addressBook.set(id,\n message.listenAddrs.map((addr) => multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n // Update the protocols\n try {\n await this.components.peerStore.protoBook.set(id, message.protocols)\n } catch (err: any) {\n log.error('received invalid protocols', err)\n }\n\n log('handled push from %p', id)\n }\n\n /**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\n static getCleanMultiaddr (addr: Uint8Array | string | null | undefined) {\n if (addr != null && addr.length > 0) {\n try {\n return multiaddr(addr)\n } catch {\n\n }\n }\n }\n}\n\n/**\n * The protocols the IdentifyService supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n}\n\nexport const Message = { Identify }\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Identify {\n protocolVersion?: string\n agentVersion?: string\n publicKey?: Uint8Array\n listenAddrs: Uint8Array[]\n observedAddr?: Uint8Array\n protocols: string[]\n signedPeerRecord?: Uint8Array\n}\n\nexport namespace Identify {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.protocolVersion != null) {\n w.uint32(42)\n w.string(obj.protocolVersion)\n }\n\n if (obj.agentVersion != null) {\n w.uint32(50)\n w.string(obj.agentVersion)\n }\n\n if (obj.publicKey != null) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (obj.observedAddr != null) {\n w.uint32(34)\n w.bytes(obj.observedAddr)\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(26)\n w.string(value)\n }\n }\n\n if (obj.signedPeerRecord != null) {\n w.uint32(66)\n w.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n listenAddrs: [],\n protocols: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Identify): Uint8Array => {\n return encodeMessage(obj, Identify.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {\n return decodeMessage(buf, Identify.codec())\n }\n}\n", "import errCode from 'err-code'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\n\nexport interface RecordEnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\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: Record, peerId: PeerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\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\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\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: Uint8Array | Uint8ArrayList, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\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\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\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\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n", "\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if (opts.writeDefaults === true || (obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if (opts.writeDefaults === true || (obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if (opts.writeDefaults === true || (obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\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/**\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: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n\n if (a.length !== b.length) {\n return false\n }\n\n b.sort(sort)\n\n return a.sort(sort).every((item, index) => b[index].equals(item))\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.peerId)\n }\n\n if (opts.writeDefaults === true || obj.seq !== 0n) {\n w.uint32(16)\n w.uint64(obj.seq)\n }\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 writeDefaults: true\n })\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n", "\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\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", "import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\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 */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\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\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\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\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n", "export const version = '0.42.2'\nexport const name = 'libp2p'\n", "\nimport { version } from '../version.js'\n\nexport const PROTOCOL_VERSION = 'ipfs/0.1.0' // deprecated\nexport const AGENT_VERSION = `js-libp2p/${version}`\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0' // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0' // deprecated\n\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", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport * as lp from 'it-length-prefixed'\nimport { FetchRequest, FetchResponse } from './pb/proto.js'\nimport { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport { fromString as uint8arrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8arrayToString } from 'uint8arrays/to-string'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nconst log = logger('libp2p:fetch')\n\nexport interface FetchServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a remote peer to send any data\n */\n timeout: number\n}\n\nexport interface HandleMessageOptions {\n stream: Stream\n protocol: string\n}\n\nexport interface LookupFunction {\n (key: string): Promise\n}\n\nexport interface FetchServiceComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\n/**\n * A simple libp2p protocol for requesting a value corresponding to a key from a peer.\n * Developers can register one or more lookup function for retrieving the value corresponding to\n * a given key. Each lookup function must act on a distinct part of the overall key space, defined\n * by a fixed prefix that all keys that should be routed to that lookup function will start with.\n */\nexport class FetchService implements Startable {\n public readonly protocol: string\n private readonly components: FetchServiceComponents\n private readonly lookupFunctions: Map\n private started: boolean\n private readonly init: FetchServiceInit\n\n constructor (components: FetchServiceComponents, init: FetchServiceInit) {\n this.started = false\n this.components = components\n this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.lookupFunctions = new Map() // Maps key prefix to value lookup function\n this.handleMessage = this.handleMessage.bind(this)\n this.init = init\n }\n\n async start () {\n await this.components.registrar.handle(this.protocol, (data) => {\n void this.handleMessage(data)\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n data.stream.close()\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer\n */\n async fetch (peer: PeerId, key: string, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const connection = await this.components.connectionManager.openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n log('using default timeout of %d ms', this.init.timeout)\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream(this.protocol, {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n log('fetch %s', key)\n\n const result = await pipe(\n [FetchRequest.encode({ identifier: key })],\n lp.encode(),\n source,\n lp.decode(),\n async function (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n const response = FetchResponse.decode(buf)\n\n switch (response.status) {\n case (FetchResponse.StatusCode.OK): {\n log('received status for %s ok', key)\n return response.data\n }\n case (FetchResponse.StatusCode.NOT_FOUND): {\n log('received status for %s not found', key)\n return null\n }\n case (FetchResponse.StatusCode.ERROR): {\n log('received status for %s error', key)\n const errmsg = uint8arrayToString(response.data)\n throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)\n }\n default: {\n log('received status for %s unknown', key)\n throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)\n }\n }\n }\n )\n\n return result ?? null\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Invoked when a fetch request is received. Reads the request message off the given stream and\n * responds based on looking up the key in the request via the lookup callback that corresponds\n * to the key's prefix.\n */\n async handleMessage (data: IncomingStreamData) {\n const { stream } = data\n const self = this\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n // for await (const buf of source) {\n const request = FetchRequest.decode(buf)\n\n let response: FetchResponse\n const lookup = self._getLookupFunction(request.identifier)\n if (lookup != null) {\n log('look up data with identifier %s', request.identifier)\n const data = await lookup(request.identifier)\n if (data != null) {\n log('sending status for %s ok', request.identifier)\n response = { status: FetchResponse.StatusCode.OK, data }\n } else {\n log('sending status for %s not found', request.identifier)\n response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }\n }\n } else {\n log('sending status for %s error', request.identifier)\n const errmsg = uint8arrayFromString(`No lookup function registered for key: ${request.identifier}`)\n response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }\n }\n\n yield FetchResponse.encode(response)\n },\n lp.encode(),\n stream\n )\n }\n\n /**\n * Given a key, finds the appropriate function for looking up its corresponding value, based on\n * the key's prefix.\n */\n _getLookupFunction (key: string) {\n for (const prefix of this.lookupFunctions.keys()) {\n if (key.startsWith(prefix)) {\n return this.lookupFunctions.get(prefix)\n }\n }\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix\n *\n * @example\n *\n * ```js\n * // ...\n * libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })\n * ```\n */\n registerLookupFunction (prefix: string, lookup: LookupFunction) {\n if (this.lookupFunctions.has(prefix)) {\n throw errCode(new Error(\"Fetch protocol handler for key prefix '\" + prefix + \"' already registered\"), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n this.lookupFunctions.set(prefix, lookup)\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix.\n *\n * @example\n *\n * ```js\n * // ...\n * libp2p.fetchService.unregisterLookupFunction('/prefix')\n * ```\n */\n unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {\n if (lookup != null) {\n const existingLookup = this.lookupFunctions.get(prefix)\n\n if (existingLookup !== lookup) {\n return\n }\n }\n\n this.lookupFunctions.delete(prefix)\n }\n}\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\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface FetchRequest {\n identifier: string\n}\n\nexport namespace FetchRequest {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || obj.identifier !== '') {\n w.uint32(10)\n w.string(obj.identifier)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n identifier: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identifier = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchRequest): Uint8Array => {\n return encodeMessage(obj, FetchRequest.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchRequest => {\n return decodeMessage(buf, FetchRequest.codec())\n }\n}\n\nexport interface FetchResponse {\n status: FetchResponse.StatusCode\n data: Uint8Array\n}\n\nexport namespace FetchResponse {\n export enum StatusCode {\n OK = 'OK',\n NOT_FOUND = 'NOT_FOUND',\n ERROR = 'ERROR'\n }\n\n enum __StatusCodeValues {\n OK = 0,\n NOT_FOUND = 1,\n ERROR = 2\n }\n\n export namespace StatusCode {\n export const codec = () => {\n return enumeration(__StatusCodeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.status != null && __StatusCodeValues[obj.status] !== 0)) {\n w.uint32(8)\n FetchResponse.StatusCode.codec().encode(obj.status, w)\n }\n\n if (opts.writeDefaults === true || (obj.data != null && obj.data.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n status: StatusCode.OK,\n data: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.status = FetchResponse.StatusCode.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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchResponse): Uint8Array => {\n return encodeMessage(obj, FetchResponse.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchResponse => {\n return decodeMessage(buf, FetchResponse.codec())\n }\n}\n", "\n// https://github.com/libp2p/specs/tree/master/fetch#wire-protocol\nexport const PROTOCOL_VERSION = '0.0.1'\nexport const PROTOCOL_NAME = 'fetch'\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { randomBytes } from '@libp2p/crypto'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION } from './constants.js'\nimport type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { setMaxListeners } from 'events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nconst log = logger('libp2p:ping')\n\nexport interface PingServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a ping response\n */\n timeout: number\n}\n\nexport interface PingServiceComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport class PingService implements Startable {\n public readonly protocol: string\n private readonly components: PingServiceComponents\n private started: boolean\n private readonly init: PingServiceInit\n\n constructor (components: PingServiceComponents, init: PingServiceInit) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.init = init\n }\n\n async start () {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData) {\n const { stream } = data\n\n void pipe(stream, stream)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n *\n * @param {PeerId|Multiaddr} peer\n * @returns {Promise}\n */\n async ping (peer: PeerId, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.connectionManager.openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [data],\n source,\n async (source) => await first(source)\n )\n const end = Date.now()\n\n if (result == null || !uint8ArrayEquals(data, result.subarray())) {\n throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK)\n }\n\n return end - start\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n}\n", "\nexport const PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\n", "\nexport async function upnpNat () {\n throw new Error('Not supported in browsers')\n}\n\nexport async function pmpNat () {\n throw new Error('Not supported in browsers')\n}\n", "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 { upnpNat, NatAPI } from '@achingbrain/nat-port-mapper'\nimport { logger } from '@libp2p/logger'\nimport { fromNodeAddress } from '@multiformats/multiaddr'\nimport { isBrowser } from 'wherearewe'\nimport isPrivateIp from 'private-ip'\nimport * as pkg from './version.js'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { TransportManager } from '@libp2p/interface-transport'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:nat')\nconst DEFAULT_TTL = 7200\n\nfunction highPort (min = 1024, max = 65535) {\n return Math.floor(Math.random() * (max - min + 1) + min)\n}\n\nexport interface PMPOptions {\n /**\n * Whether to enable PMP as well as UPnP\n */\n enabled?: boolean\n}\n\nexport interface NatManagerInit {\n /**\n * Whether to enable the NAT manager\n */\n enabled: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n externalAddress?: string\n\n /**\n * Pass a value to use instead of auto-detection\n */\n localAddress?: string\n\n /**\n * A string value to use for the port mapping description on the gateway\n */\n description?: string\n\n /**\n * How long UPnP port mappings should last for in seconds (minimum 1200)\n */\n ttl?: number\n\n /**\n * Whether to automatically refresh UPnP port mappings when their TTL is reached\n */\n keepAlive: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n gateway?: string\n}\n\nexport interface NatManagerComponents {\n peerId: PeerId\n transportManager: TransportManager\n addressManager: AddressManager\n}\n\nexport class NatManager implements Startable {\n private readonly components: NatManagerComponents\n private readonly enabled: boolean\n private readonly externalAddress?: string\n private readonly localAddress?: string\n private readonly description: string\n private readonly ttl: number\n private readonly keepAlive: boolean\n private readonly gateway?: string\n private started: boolean\n private client?: NatAPI\n\n constructor (components: NatManagerComponents, init: NatManagerInit) {\n this.components = components\n\n this.started = false\n this.enabled = init.enabled\n this.externalAddress = init.externalAddress\n this.localAddress = init.localAddress\n this.description = init.description ?? `${pkg.name}@${pkg.version} ${this.components.peerId.toString()}`\n this.ttl = init.ttl ?? DEFAULT_TTL\n this.keepAlive = init.keepAlive ?? true\n this.gateway = init.gateway\n\n if (this.ttl < DEFAULT_TTL) {\n throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n start () {}\n\n /**\n * Attempt to use uPnP to configure port mapping using the current gateway.\n *\n * Run after start to ensure the transport manager has all addresses configured.\n */\n afterStart () {\n if (isBrowser || !this.enabled || this.started) {\n return\n }\n\n this.started = true\n\n // done async to not slow down startup\n void this._start().catch((err) => {\n // hole punching errors are non-fatal\n log.error(err)\n })\n }\n\n async _start () {\n const addrs = this.components.transportManager.getAddrs()\n\n for (const addr of addrs) {\n // try to open uPnP ports for each thin waist address\n const { family, host, port, transport } = addr.toOptions()\n\n if (!addr.isThinWaistAddress() || transport !== 'tcp') {\n // only bare tcp addresses\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (isLoopback(addr)) {\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (family !== 4) {\n // ignore ipv6\n // eslint-disable-next-line no-continue\n continue\n }\n\n const client = await this._getClient()\n const publicIp = this.externalAddress ?? await client.externalIp()\n const isPrivate = isPrivateIp(publicIp)\n\n if (isPrivate === true) {\n throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)\n }\n\n if (isPrivate == null) {\n throw new Error(`${publicIp} is not an IP address`)\n }\n\n const publicPort = highPort()\n\n log(`opening uPnP connection from ${publicIp}:${publicPort} to ${host}:${port}`)\n\n await client.map({\n publicPort,\n localPort: port,\n localAddress: this.localAddress,\n protocol: transport.toUpperCase() === 'TCP' ? 'TCP' : 'UDP'\n })\n\n this.components.addressManager.addObservedAddr(fromNodeAddress({\n family: 4,\n address: publicIp,\n port: publicPort\n }, transport))\n }\n }\n\n async _getClient () {\n if (this.client != null) {\n return this.client\n }\n\n this.client = await upnpNat({\n description: this.description,\n ttl: this.ttl,\n keepAlive: this.keepAlive,\n gateway: this.gateway\n })\n\n return this.client\n }\n\n /**\n * Stops the NAT manager\n */\n async stop () {\n if (isBrowser || this.client == null) {\n return\n }\n\n try {\n await this.client.close()\n this.client = undefined\n } catch (err: any) {\n log.error(err)\n }\n }\n}\n", "/**\n * Check if a given ip address is a loopback address\n */\nexport function isLoopbackAddr (ip: string) {\n return /^127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n /^::1$/.test(ip)\n}\n", "import { isLoopbackAddr } from 'is-loopback-addr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr is a loopback address.\n */\nexport function isLoopback (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return isLoopbackAddr(address)\n}\n", "import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { logger } from '@libp2p/logger'\nimport { protocols } from '@multiformats/multiaddr'\nimport type { TransportManager } from '@libp2p/interface-transport'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:peer-record-updater')\n\nexport interface PeerRecordUpdaterComponents {\n peerId: PeerId\n peerStore: PeerStore\n transportManager: TransportManager\n addressManager: AddressManager\n}\n\nexport class PeerRecordUpdater implements Startable {\n private readonly components: PeerRecordUpdaterComponents\n private started: boolean\n\n constructor (components: PeerRecordUpdaterComponents) {\n this.components = components\n this.started = false\n this.update = this.update.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n this.components.transportManager.addEventListener('listener:listening', this.update)\n this.components.transportManager.addEventListener('listener:close', this.update)\n this.components.addressManager.addEventListener('change:addresses', this.update)\n }\n\n async stop () {\n this.started = false\n this.components.transportManager.removeEventListener('listener:listening', this.update)\n this.components.transportManager.removeEventListener('listener:close', this.update)\n this.components.addressManager.removeEventListener('change:addresses', this.update)\n }\n\n /**\n * Create (or update if existing) self peer record and store it in the AddressBook.\n */\n update () {\n Promise.resolve()\n .then(async () => {\n const peerRecord = new PeerRecord({\n peerId: this.components.peerId,\n multiaddrs: this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.peerId)\n await this.components.peerStore.addressBook.consumePeerRecord(envelope)\n })\n .catch(err => {\n log.error('Could not update self peer record: %o', err)\n })\n }\n}\n", "import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTPeerRouting implements PeerRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async findPeer (peerId: PeerId, options: AbortOptions = {}) {\n for await (const event of this.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n return event.peer\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}) {\n for await (const event of this.dht.getClosestPeers(key, options)) {\n if (event.name === 'FINAL_PEER') {\n yield event.peer\n }\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport { codes } from './errors.js'\nimport { PeerRecord, RecordEnvelope } from '@libp2p/peer-record'\nimport { pipe } from 'it-pipe'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport each from 'it-foreach'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { AddressFilter, Peer, PeerMultiaddrsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Store } from './store.js'\nimport type { Envelope } from '@libp2p/interface-record'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:peer-store:address-book')\nconst EVENT_NAME = 'change:multiaddrs'\n\nasync function allowAll () {\n return true\n}\n\nexport class PeerStoreAddressBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n private readonly addressFilter: AddressFilter\n\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store, addressFilter?: AddressFilter) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n this.addressFilter = addressFilter ?? allowAll\n }\n\n /**\n * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope.\n * This will return a boolean that indicates if the record was successfully processed and added\n * into the AddressBook.\n */\n async consumePeerRecord (envelope: Envelope) {\n log.trace('consumePeerRecord await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('consumePeerRecord got write lock')\n\n let peerId\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n let peerRecord\n try {\n peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n } catch (err: any) {\n log.error('invalid peer record received')\n return false\n }\n\n peerId = peerRecord.peerId\n const multiaddrs = peerRecord.multiaddrs\n\n // Verify peerId\n if (!peerId.equals(envelope.peerId)) {\n log('signing key does not match PeerId in the PeerRecord')\n return false\n }\n\n // ensure the record has multiaddrs\n if (multiaddrs == null || multiaddrs.length === 0) {\n return false\n }\n\n if (await this.store.has(peerId)) {\n peer = await this.store.load(peerId)\n\n if (peer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\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 return false\n }\n }\n }\n\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter, true)\n\n // Replace unsigned addresses by the new ones from the record\n // TODO: Once we have ttls for the addresses, we should merge these in\n updatedPeer = await this.store.patchOrCreate(peerId, {\n addresses,\n peerRecordEnvelope: envelope.marshal().subarray()\n })\n\n log('stored provided peer record for %p', peerRecord.peerId)\n } finally {\n log.trace('consumePeerRecord release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(({ multiaddr }) => multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n return true\n }\n\n async getRawEnvelope (peerId: PeerId) {\n log.trace('getRawEnvelope await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getRawEnvelope got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.peerRecordEnvelope\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getRawEnvelope release read lock')\n release()\n }\n }\n\n /**\n * Get an Envelope containing a PeerRecord for the given peer.\n * Returns undefined if no record exists.\n */\n async getPeerRecord (peerId: PeerId) {\n const raw = await this.getRawEnvelope(peerId)\n\n if (raw == null) {\n return undefined\n }\n\n return await RecordEnvelope.createFromProtobuf(raw)\n }\n\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.addresses\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let hasPeer = false\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length && addresses.length === peer.addresses.length) {\n // not changing anything, no need to update\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, { addresses })\n\n log('set multiaddrs for %p', peerId)\n } finally {\n log.trace('set multiaddrs for %p', peerId)\n log('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (!hasPeer) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async add (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let hasPeer\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, { addresses })\n\n log('added multiaddrs for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (hasPeer === true) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n addresses: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: [],\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n }\n }\n}\n\nasync function filterMultiaddrs (peerId: PeerId, multiaddrs: Multiaddr[], addressFilter: AddressFilter, isCertified: boolean = false) {\n return await pipe(\n multiaddrs,\n (source) => each(source, (multiaddr) => {\n if (!isMultiaddr(multiaddr)) {\n log.error('multiaddr must be an instance of Multiaddr')\n throw errcode(new Error('multiaddr must be an instance of Multiaddr'), codes.ERR_INVALID_PARAMETERS)\n }\n }),\n (source) => filter(source, async (multiaddr) => await addressFilter(peerId, multiaddr)),\n (source) => map(source, (multiaddr) => {\n return {\n multiaddr,\n isCertified\n }\n }),\n async (source) => await all(source)\n )\n}\n", "\nexport const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS',\n ERR_NOT_FOUND: 'ERR_NOT_FOUND'\n}\n", "\n/**\n * Invokes the passed function for each item in an iterable\n */\nexport default async function * forEach (source: AsyncIterable|Iterable, fn: (thing: T) => void | Promise): AsyncGenerator {\n for await (const thing of source) {\n await fn(thing)\n yield thing\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, KeyBook, PeerPublicKeyChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:key-book')\n\nconst EVENT_NAME = 'change:pubkey'\n\nexport class PeerStoreKeyBook implements KeyBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The KeyBook is responsible for keeping the known public keys of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Set the Peer public key\n */\n async set (peerId: PeerId, publicKey: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(publicKey instanceof Uint8Array)) {\n log.error('publicKey must be an instance of Uint8Array to store data')\n throw errcode(new Error('publicKey must be an instance of PublicKey'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let updatedKey = false\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if ((peer.pubKey != null) && uint8arrayEquals(peer.pubKey, publicKey)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: publicKey\n })\n updatedKey = true\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n if (updatedKey) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: publicKey,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n }\n\n /**\n * Get Public key of the given PeerId, if stored\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await write lock')\n const release = await this.store.lock.readLock()\n log.trace('get got write lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.pubKey\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log('get release write lock')\n release()\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: undefined\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: undefined,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, MetadataBook, PeerMetadataChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:metadata-book')\n\nconst EVENT_NAME = 'change:metadata'\n\nexport class PeerStoreMetadataBook implements MetadataBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The MetadataBook is responsible for keeping metadata\n * about known peers\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Get the known data of a provided peer\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return new Map()\n }\n\n /**\n * Get specific metadata value, if it exists\n */\n async getValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('getValue await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getValue got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata.get(key)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getValue release write lock')\n release()\n }\n }\n\n async set (peerId: PeerId, metadata: Map) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(metadata instanceof Map)) {\n log.error('valid metadata must be provided to store data')\n throw errcode(new Error('valid metadata must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.mergeOrCreate(peerId, {\n metadata\n })\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n /**\n * Set metadata key and value of a provided peer\n */\n async setValue (peerId: PeerId, key: string, value: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (typeof key !== 'string' || !(value instanceof Uint8Array)) {\n log.error('valid key and value must be provided to store data')\n throw errcode(new Error('valid key and value must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('setValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('setValue got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const existingValue = peer.metadata.get(key)\n\n if (existingValue != null && uint8ArrayEquals(value, existingValue)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n metadata: new Map([[key, value]])\n })\n } finally {\n log.trace('setValue release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: updatedPeer.metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n if (peer != null) {\n await this.store.patch(peerId, {\n metadata: new Map()\n })\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: new Map(),\n oldMetadata: peer.metadata\n }\n }))\n }\n }\n\n async deleteValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('deleteValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('deleteValue got write lock')\n\n let metadata\n let peer: Peer | undefined\n\n try {\n peer = await this.store.load(peerId)\n metadata = peer.metadata\n\n metadata.delete(key)\n\n await this.store.patch(peerId, {\n metadata\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('deleteValue release write lock')\n release()\n }\n\n if (metadata != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { Peer, PeerProtocolsChangeData, PeerStore, ProtoBook } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:proto-book')\n\nconst EVENT_NAME = 'change:protocols'\n\nexport class PeerStoreProtoBook implements ProtoBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The ProtoBook is responsible for keeping the known supported\n * protocols of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n async get (peerId: PeerId) {\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.protocols\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n\n log('stored provided protocols for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async add (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...peer.protocols,\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n protocols\n })\n\n log('added provided protocols for %p', peerId)\n } finally {\n log.trace('add release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async remove (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('remove await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('remove got write lock')\n\n let peer: Peer | undefined\n let updatedPeer: Peer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const protocolSet = new Set(peer.protocols)\n\n for (const protocol of protocols) {\n protocolSet.delete(protocol)\n }\n\n if (peer.protocols.length === protocolSet.size) {\n return\n }\n\n protocols = Array.from(protocolSet)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n } finally {\n log.trace('remove release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n protocols: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: [],\n oldProtocols: peer.protocols\n }\n }))\n }\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { Metadata, Peer as PeerPB } from './pb/peer.js'\nimport mortice from 'mortice'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport type { Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PersistentPeerStoreComponents } from './index.js'\n\nconst log = logger('libp2p:peer-store:store')\n\nconst NAMESPACE_COMMON = '/peers/'\n\nexport interface Store {\n has: (peerId: PeerId) => Promise\n save: (peer: Peer) => Promise\n load: (peerId: PeerId) => Promise\n delete: (peerId: PeerId) => Promise\n merge: (peerId: PeerId, data: Partial) => Promise\n mergeOrCreate: (peerId: PeerId, data: Partial) => Promise\n patch: (peerId: PeerId, data: Partial) => Promise\n patchOrCreate: (peerId: PeerId, data: Partial) => Promise\n all: () => AsyncIterable\n\n lock: {\n readLock: () => Promise<() => void>\n writeLock: () => Promise<() => void>\n }\n}\n\nexport class PersistentStore {\n private readonly components: PersistentPeerStoreComponents\n public lock: any\n\n constructor (components: PersistentPeerStoreComponents) {\n this.components = components\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n }\n\n _peerIdToDatastoreKey (peerId: PeerId) {\n if (peerId.type == null) {\n log.error('peerId must be an instance of peer-id to store data')\n throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n }\n\n async has (peerId: PeerId) {\n return await this.components.datastore.has(this._peerIdToDatastoreKey(peerId))\n }\n\n async delete (peerId: PeerId) {\n await this.components.datastore.delete(this._peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise {\n const buf = await this.components.datastore.get(this._peerIdToDatastoreKey(peerId))\n const peer = PeerPB.decode(buf)\n const metadata = new Map()\n\n for (const meta of peer.metadata) {\n metadata.set(meta.key, meta.value)\n }\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,\n pubKey: peer.pubKey ?? undefined,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined\n }\n }\n\n async save (peer: Peer) {\n if (peer.pubKey != null && peer.id.publicKey != null && !uint8arrayEquals(peer.pubKey, peer.id.publicKey)) {\n log.error('peer publicKey bytes do not match peer id publicKey bytes')\n throw errcode(new Error('publicKey bytes do not match peer id publicKey bytes'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // dedupe addresses\n const addressSet = new Set()\n const addresses = peer.addresses\n .filter(address => {\n if (addressSet.has(address.multiaddr.toString())) {\n return false\n }\n\n addressSet.add(address.multiaddr.toString())\n return true\n })\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ multiaddr, isCertified }) => ({\n multiaddr: multiaddr.bytes,\n isCertified\n }))\n\n const metadata: Metadata[] = []\n\n ;[...peer.metadata.keys()].sort().forEach(key => {\n const value = peer.metadata.get(key)\n\n if (value != null) {\n metadata.push({ key, value })\n }\n })\n\n const buf = PeerPB.encode({\n addresses,\n protocols: peer.protocols.sort(),\n pubKey: peer.pubKey,\n metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope\n })\n\n await this.components.datastore.put(this._peerIdToDatastoreKey(peer.id), buf.subarray())\n\n return await this.load(peer.id)\n }\n\n async patch (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._patch(peerId, data, peer)\n }\n\n async patchOrCreate (peerId: PeerId, data: Partial) {\n let peer: Peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._patch(peerId, data, peer)\n }\n\n async _patch (peerId: PeerId, data: Partial, peer: Peer) {\n return await this.save({\n ...peer,\n ...data,\n id: peerId\n })\n }\n\n async merge (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._merge(peerId, data, peer)\n }\n\n async mergeOrCreate (peerId: PeerId, data: Partial) {\n /** @type {Peer} */\n let peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._merge(peerId, data, peer)\n }\n\n async _merge (peerId: PeerId, data: Partial, peer: Peer) {\n // if the peer has certified addresses, use those in\n // favour of the supplied versions\n const addresses = new Map()\n\n peer.addresses.forEach((addr) => {\n addresses.set(addr.multiaddr.toString(), addr.isCertified)\n })\n\n ;(data.addresses ?? []).forEach(addr => {\n const addrString = addr.multiaddr.toString()\n const isAlreadyCertified = Boolean(addresses.get(addrString))\n\n const isCertified = isAlreadyCertified || addr.isCertified\n\n addresses.set(addrString, isCertified)\n })\n\n return await this.save({\n id: peerId,\n addresses: Array.from(addresses.entries()).map(([addrStr, isCertified]) => {\n return {\n multiaddr: multiaddr(addrStr),\n isCertified\n }\n }),\n protocols: Array.from(new Set([\n ...(peer.protocols ?? []),\n ...(data.protocols ?? [])\n ])),\n metadata: new Map([\n ...(peer.metadata?.entries() ?? []),\n ...(data.metadata?.entries() ?? [])\n ]),\n pubKey: data.pubKey ?? (peer != null ? peer.pubKey : undefined),\n peerRecordEnvelope: data.peerRecordEnvelope ?? (peer != null ? peer.peerRecordEnvelope : undefined)\n })\n }\n\n async * all () {\n for await (const key of this.components.datastore.queryKeys({\n prefix: NAMESPACE_COMMON\n })) {\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\n yield this.load(peerIdFromBytes(buf))\n }\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n metadata: Metadata[]\n pubKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n}\n\nexport namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10)\n Address.codec().encode(value, w, {\n writeDefaults: true\n })\n }\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\n if (obj.metadata != null) {\n for (const value of obj.metadata) {\n w.uint32(26)\n Metadata.codec().encode(value, w, {\n writeDefaults: true\n })\n }\n }\n\n if (obj.pubKey != null) {\n w.uint32(34)\n w.bytes(obj.pubKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42)\n w.bytes(obj.peerRecordEnvelope)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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 3:\n obj.metadata.push(Metadata.codec().decode(reader, reader.uint32()))\n break\n case 4:\n obj.pubKey = reader.bytes()\n break\n case 5:\n obj.peerRecordEnvelope = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n}\n\nexport namespace Address {\n let _codec: Codec

    \n\n export const codec = (): Codec
    => {\n if (_codec == null) {\n _codec = message
    ((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (obj.isCertified != null) {\n w.uint32(16)\n w.bool(obj.isCertified)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Address): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Address => {\n return decodeMessage(buf, Address.codec())\n }\n}\n\nexport interface Metadata {\n key: string\n value: Uint8Array\n}\n\nexport namespace Metadata {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || obj.key !== '') {\n w.uint32(10)\n w.string(obj.key)\n }\n\n if (opts.writeDefaults === true || (obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: '',\n value: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\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\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Metadata): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { PeerStoreAddressBook } from './address-book.js'\nimport { PeerStoreKeyBook } from './key-book.js'\nimport { PeerStoreMetadataBook } from './metadata-book.js'\nimport { PeerStoreProtoBook } from './proto-book.js'\nimport { PersistentStore, Store } from './store.js'\nimport type { PeerStore, AddressBook, KeyBook, MetadataBook, ProtoBook, PeerStoreEvents, PeerStoreInit, Peer, TagOptions } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport errCode from 'err-code'\nimport { Tag, Tags } from './pb/tags.js'\nimport type { Datastore } from 'interface-datastore'\n\nconst log = logger('libp2p:peer-store')\n\nexport interface PersistentPeerStoreComponents {\n peerId: PeerId\n datastore: Datastore\n}\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore extends EventEmitter implements PeerStore {\n public addressBook: AddressBook\n public keyBook: KeyBook\n public metadataBook: MetadataBook\n public protoBook: ProtoBook\n\n private readonly components: PersistentPeerStoreComponents\n private readonly store: Store\n\n constructor (components: PersistentPeerStoreComponents, init: PeerStoreInit = {}) {\n super()\n\n this.components = components\n this.store = new PersistentStore(components)\n this.addressBook = new PeerStoreAddressBook(this.dispatchEvent.bind(this), this.store, init.addressFilter)\n this.keyBook = new PeerStoreKeyBook(this.dispatchEvent.bind(this), this.store)\n this.metadataBook = new PeerStoreMetadataBook(this.dispatchEvent.bind(this), this.store)\n this.protoBook = new PeerStoreProtoBook(this.dispatchEvent.bind(this), this.store)\n }\n\n async forEach (fn: (peer: Peer) => void) {\n log.trace('getPeers await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getPeers got read lock')\n\n try {\n for await (const peer of this.store.all()) {\n if (peer.id.equals(this.components.peerId)) {\n // Skip self peer if present\n continue\n }\n\n fn(peer)\n }\n } finally {\n log.trace('getPeers release read lock')\n release()\n }\n }\n\n async all (): Promise {\n const output: Peer[] = []\n\n await this.forEach(peer => {\n output.push(peer)\n })\n\n return output\n }\n\n /**\n * Delete the information of the given peer in every book\n */\n async delete (peerId: PeerId) {\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n log.trace('delete release write lock')\n release()\n }\n }\n\n /**\n * Get the stored information of a given peer\n */\n async get (peerId: PeerId) {\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n log.trace('get release read lock')\n release()\n }\n }\n\n /**\n * Returns true if we have a record of the peer\n */\n async has (peerId: PeerId) {\n log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n log.trace('has release read lock')\n release()\n }\n }\n\n async tagPeer (peerId: PeerId, tag: string, options: TagOptions = {}) {\n const providedValue = options.value ?? 0\n const value = Math.round(providedValue)\n const ttl = options.ttl ?? undefined\n\n if (value !== providedValue || value < 0 || value > 100) {\n throw errCode(new Error('Tag value must be between 0-100'), 'ERR_TAG_VALUE_OUT_OF_BOUNDS')\n }\n\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n for (const t of tags) {\n if (t.name === tag) {\n throw errCode(new Error('Peer already tagged'), 'ERR_DUPLICATE_TAG')\n }\n }\n\n tags.push({\n name: tag,\n value,\n expiry: ttl == null ? undefined : BigInt(Date.now() + ttl)\n })\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async unTagPeer (peerId: PeerId, tag: string) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n tags = tags.filter(t => t.name !== tag)\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async getTags (peerId: PeerId) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n const now = BigInt(Date.now())\n const unexpiredTags = tags.filter(tag => tag.expiry == null || tag.expiry > now)\n\n if (unexpiredTags.length !== tags.length) {\n // remove any expired tags\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags: unexpiredTags }).subarray())\n }\n\n return unexpiredTags.map(t => ({\n name: t.name,\n value: t.value ?? 0\n }))\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Tags {\n tags: Tag[]\n}\n\nexport namespace Tags {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.tags != null) {\n for (const value of obj.tags) {\n w.uint32(10)\n Tag.codec().encode(value, w, {\n writeDefaults: true\n })\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n tags: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.tags.push(Tag.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tags): Uint8Array => {\n return encodeMessage(obj, Tags.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tags => {\n return decodeMessage(buf, Tags.codec())\n }\n}\n\nexport interface Tag {\n name: string\n value?: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || obj.name !== '') {\n w.uint32(10)\n w.string(obj.name)\n }\n\n if (obj.value != null) {\n w.uint32(16)\n w.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n w.uint32(24)\n w.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n name: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.name = reader.string()\n break\n case 2:\n obj.value = reader.uint32()\n break\n case 3:\n obj.expiry = reader.uint64()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tag): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tag => {\n return decodeMessage(buf, Tag.codec())\n }\n}\n", "import drain from 'it-drain'\nimport errCode from 'err-code'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTContentRouting implements ContentRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async provide (cid: CID) {\n await drain(this.dht.provide(cid))\n }\n\n async * findProviders (cid: CID, options: AbortOptions = {}) {\n for await (const event of this.dht.findProviders(cid, options)) {\n if (event.name === 'PROVIDER') {\n yield * event.providers\n }\n }\n }\n\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise {\n await drain(this.dht.put(key, value, options))\n }\n\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n for await (const event of this.dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n}\n", "import errCode from 'err-code'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport { isStartable, Startable } from '@libp2p/interfaces/startable'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { TransportManager, Upgrader } from '@libp2p/interface-transport'\nimport type { Datastore } from 'interface-datastore'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { ConnectionManager, Dialer } from '@libp2p/interface-connection-manager'\n\nexport interface Components {\n peerId: PeerId\n addressManager: AddressManager\n peerStore: PeerStore\n upgrader: Upgrader\n registrar: Registrar\n connectionManager: ConnectionManager\n transportManager: TransportManager\n connectionGater: ConnectionGater\n contentRouting: ContentRouting\n peerRouting: PeerRouting\n datastore: Datastore\n connectionProtector?: ConnectionProtector\n dialer: Dialer\n metrics?: Metrics\n dht?: DualDHT\n pubsub?: PubSub\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dht?: DualDHT\n pubsub?: PubSub\n dialer?: Dialer\n}\n\nexport class DefaultComponents implements Components, Startable {\n private _peerId?: PeerId\n private _addressManager?: AddressManager\n private _peerStore?: PeerStore\n private _upgrader?: Upgrader\n private _metrics?: Metrics\n private _registrar?: Registrar\n private _connectionManager?: ConnectionManager\n private _transportManager?: TransportManager\n private _connectionGater?: ConnectionGater\n private _contentRouting?: ContentRouting\n private _peerRouting?: PeerRouting\n private _datastore?: Datastore\n private _connectionProtector?: ConnectionProtector\n private _dht?: DualDHT\n private _pubsub?: PubSub\n private _dialer?: Dialer\n private _started = false\n\n constructor (init: ComponentsInit = {}) {\n this._peerId = init.peerId\n this._addressManager = init.addressManager\n this._peerStore = init.peerStore\n this._upgrader = init.upgrader\n this._metrics = init.metrics\n this._registrar = init.registrar\n this._connectionManager = init.connectionManager\n this._transportManager = init.transportManager\n this._connectionGater = init.connectionGater\n this._contentRouting = init.contentRouting\n this._peerRouting = init.peerRouting\n this._datastore = init.datastore\n this._connectionProtector = init.connectionProtector\n this._dht = init.dht\n this._pubsub = init.pubsub\n this._dialer = init.dialer\n }\n\n isStarted () {\n return this._started\n }\n\n async beforeStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStart != null) {\n await startable.beforeStart()\n }\n })\n )\n }\n\n async start () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.start()\n })\n )\n\n this._started = true\n }\n\n async afterStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStart != null) {\n await startable.afterStart()\n }\n })\n )\n }\n\n async beforeStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStop != null) {\n await startable.beforeStop()\n }\n })\n )\n }\n\n async stop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.stop()\n })\n )\n\n this._started = false\n }\n\n async afterStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStop != null) {\n await startable.afterStop()\n }\n })\n )\n }\n\n get peerId (): PeerId {\n if (this._peerId == null) {\n throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._peerId\n }\n\n set peerId (peerId: PeerId) {\n this._peerId = peerId\n }\n\n get addressManager (): AddressManager {\n if (this._addressManager == null) {\n throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._addressManager\n }\n\n set addressManager (addressManager: AddressManager) {\n this._addressManager = addressManager\n }\n\n get peerStore (): PeerStore {\n if (this._peerStore == null) {\n throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._peerStore\n }\n\n set peerStore (peerStore: PeerStore) {\n this._peerStore = peerStore\n }\n\n get upgrader (): Upgrader {\n if (this._upgrader == null) {\n throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._upgrader\n }\n\n set upgrader (upgrader: Upgrader) {\n this._upgrader = upgrader\n }\n\n get registrar (): Registrar {\n if (this._registrar == null) {\n throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._registrar\n }\n\n set registrar (registrar: Registrar) {\n this._registrar = registrar\n }\n\n get connectionManager (): ConnectionManager {\n if (this._connectionManager == null) {\n throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._connectionManager\n }\n\n set connectionManager (connectionManager: ConnectionManager) {\n this._connectionManager = connectionManager\n }\n\n get transportManager (): TransportManager {\n if (this._transportManager == null) {\n throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._transportManager\n }\n\n set transportManager (transportManager: TransportManager) {\n this._transportManager = transportManager\n }\n\n get connectionGater (): ConnectionGater {\n if (this._connectionGater == null) {\n throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._connectionGater\n }\n\n set connectionGater (connectionGater: ConnectionGater) {\n this._connectionGater = connectionGater\n }\n\n get contentRouting (): ContentRouting {\n if (this._contentRouting == null) {\n throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._contentRouting\n }\n\n set contentRouting (contentRouting: ContentRouting) {\n this._contentRouting = contentRouting\n }\n\n get peerRouting (): PeerRouting {\n if (this._peerRouting == null) {\n throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._peerRouting\n }\n\n set peerRouting (peerRouting: PeerRouting) {\n this._peerRouting = peerRouting\n }\n\n get datastore (): Datastore {\n if (this._datastore == null) {\n throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._datastore\n }\n\n set datastore (datastore: Datastore) {\n this._datastore = datastore\n }\n\n get connectionProtector (): ConnectionProtector | undefined {\n return this._connectionProtector\n }\n\n set connectionProtector (connectionProtector: ConnectionProtector | undefined) {\n this._connectionProtector = connectionProtector\n }\n\n get dialer (): Dialer {\n if (this._dialer == null) {\n throw errCode(new Error('dialer not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this._dialer\n }\n\n set dialer (dialer: Dialer) {\n this._dialer = dialer\n }\n\n get metrics (): Metrics | undefined {\n return this._metrics\n }\n\n set metrics (metrics: Metrics | undefined) {\n this._metrics = metrics\n }\n\n get dht (): DualDHT | undefined {\n return this._dht\n }\n\n set dht (dht: DualDHT | undefined) {\n this._dht = dht\n }\n\n get pubsub (): PubSub | undefined {\n return this._pubsub\n }\n\n set pubsub (pubsub: PubSub | undefined) {\n this._pubsub = pubsub\n }\n}\n", "import debug from 'debug'\nimport Receptacle from 'receptacle'\nimport * as utils from './utils.js'\nimport type { DNSJSON } from './utils'\n\nconst log = Object.assign(debug('dns-over-http-resolver'), {\n error: debug('dns-over-http-resolver:error')\n})\n\nexport interface Request { (resource: string, signal: AbortSignal): Promise }\n\ninterface ResolverOptions {\n maxCache?: number\n request?: Request\n}\n\n/**\n * DNS over HTTP resolver.\n * Uses a list of servers to resolve DNS records with HTTP requests.\n */\nclass Resolver {\n private readonly _cache: Receptacle\n private readonly _TXTcache: Receptacle\n private _servers: string[]\n private readonly _request: Request\n private _abortControllers: AbortController[]\n\n /**\n * @class\n * @param {object} [options]\n * @param {number} [options.maxCache = 100] - maximum number of cached dns records\n * @param {Request} [options.request] - function to return DNSJSON\n */\n constructor (options: ResolverOptions = {}) {\n this._cache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._TXTcache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._servers = [\n 'https://cloudflare-dns.com/dns-query',\n 'https://dns.google/resolve'\n ]\n this._request = options.request ?? utils.request\n this._abortControllers = []\n }\n\n /**\n * Cancel all outstanding DNS queries made by this resolver. Any outstanding\n * requests will be aborted and promises rejected.\n */\n cancel () {\n this._abortControllers.forEach(controller => controller.abort())\n }\n\n /**\n * Get an array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n getServers () {\n return this._servers\n }\n\n /**\n * Get a shuffled array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n _getShuffledServers () {\n const newServers = [...this._servers]\n\n for (let i = newServers.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i)\n const temp = newServers[i]\n newServers[i] = newServers[j]\n newServers[j] = temp\n }\n\n return newServers\n }\n\n /**\n * Sets the IP address and port of servers to be used when performing DNS resolution.\n *\n * @param {string[]} servers - array of RFC 5952 formatted addresses.\n */\n setServers (servers: string[]) {\n this._servers = servers\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into the appropriate DNS record\n *\n * @param {string} hostname - host name to resolve\n * @param {string} [rrType = 'A'] - resource record type\n */\n async resolve (hostname: string, rrType = 'A') {\n switch (rrType) {\n case 'A':\n return await this.resolve4(hostname)\n case 'AAAA':\n return await this.resolve6(hostname)\n case 'TXT':\n return await this.resolveTxt(hostname)\n default:\n throw new Error(`${rrType} is not supported`)\n }\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv4 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve4 (hostname: string) {\n const recordType = 'A'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryA ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv6 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve6 (hostname: string) {\n const recordType = 'AAAA'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryAaaa ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into a Text record\n *\n * @param {string} hostname - host name to resolve\n */\n async resolveTxt (hostname: string) {\n const recordType = 'TXT'\n const cached = this._TXTcache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => [a.data.replace(/['\"]+/g, '')])\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._TXTcache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryTxt ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n clearCache () {\n this._cache.clear()\n this._TXTcache.clear()\n }\n}\n\nexport default Resolver\n", "const globalFetch = globalThis.fetch;\nconst globalHeaders = globalThis.Headers;\nconst globalRequest = globalThis.Request;\nconst globalResponse = globalThis.Response;\nexport {\n globalFetch as fetch\n};\nexport {\n globalHeaders as Headers\n};\nexport {\n globalRequest as Request\n};\nexport {\n globalResponse as Response\n};", "import { fetch as nativeFetch, Headers } from 'native-fetch'\n\n/**\n * Build fetch resource for request\n */\nexport function buildResource (serverResolver: string, hostname: string, recordType: string) {\n return `${serverResolver}?name=${hostname}&type=${recordType}`\n}\n\nexport interface DNSJSON {\n Question: Question[]\n Answer: Answer[]\n}\n\ninterface Question {\n name: string\n type: number\n}\n\ninterface Answer {\n name: string\n type: number\n data: string\n TTL: number\n}\n\n/**\n * Use fetch to find the record\n */\nexport async function request (resource: string, signal: AbortSignal) {\n const req = await nativeFetch(resource, {\n headers: new Headers({\n accept: 'application/dns-json'\n }),\n signal\n })\n const res = await req.json()\n\n return res as DNSJSON\n}\n\n/**\n * Creates cache key composed by recordType and hostname\n *\n * @param {string} hostname\n * @param {string} recordType\n */\nexport function getCacheKey (hostname: string, recordType: string) {\n return `${recordType}_${hostname}`\n}\n", "import dns from 'dns-over-http-resolver'\n\nexport default dns\n", "/**\n * @packageDocumentation\n *\n * Provides strategies for resolving multiaddrs.\n */\n\nimport { getProtocol } from '../protocols-table.js'\nimport Resolver from './dns.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\n\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\n/**\n * Resolver for dnsaddr addresses.\n *\n * @example\n *\n * ```typescript\n * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const addresses = await dnsaddrResolver(ma)\n *\n * console.info(addresses)\n * //[\n * // '/dnsaddr/am6.bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb',\n * // '/dnsaddr/ny5.bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa',\n * // '/dnsaddr/sg1.bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt',\n * // '/dnsaddr/sv15.bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN'\n * //]\n * ```\n */\nexport async function dnsaddrResolver (addr: Multiaddr, options: AbortOptions = {}): Promise {\n const resolver = new Resolver()\n\n if (options.signal != null) {\n options.signal.addEventListener('abort', () => {\n resolver.cancel()\n })\n }\n\n const peerId = addr.getPeerId()\n const [, hostname] = addr.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n if (hostname == null) {\n throw new Error('No hostname found in multiaddr')\n }\n\n const records = await resolver.resolveTxt(`_dnsaddr.${hostname}`)\n\n let addresses = records.flat().map((a) => a.split('=')[1])\n\n if (peerId != null) {\n addresses = addresses.filter((entry) => entry.includes(peerId))\n }\n\n return addresses\n}\n", "import mergeOptions from 'merge-options'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport * as Constants from './constants.js'\nimport { AGENT_VERSION } from './identify/consts.js'\nimport * as RelayConstants from './circuit/constants.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { FaultTolerance } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Libp2pInit } from './index.js'\nimport { codes, messages } from './errors.js'\nimport errCode from 'err-code'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'\n\nconst DefaultConfig: Partial = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n maxConnections: 300,\n minConnections: 50,\n autoDial: true,\n autoDialInterval: 10000,\n maxParallelDials: Constants.MAX_PARALLEL_DIALS,\n maxDialsPerPeer: Constants.MAX_PER_PEER_DIALS,\n dialTimeout: Constants.DIAL_TIMEOUT,\n inboundUpgradeTimeout: Constants.INBOUND_UPGRADE_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: publicAddressesFirst\n },\n connectionGater: {},\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n },\n peerRouting: {\n refreshManager: {\n enabled: true,\n interval: 6e5,\n bootDelay: 10e3\n }\n },\n nat: {\n enabled: true,\n ttl: 7200,\n keepAlive: true\n },\n relay: {\n enabled: true,\n advertise: {\n bootDelay: RelayConstants.ADVERTISE_BOOT_DELAY,\n enabled: false,\n ttl: RelayConstants.ADVERTISE_TTL\n },\n hop: {\n enabled: false,\n active: false,\n timeout: 30000\n },\n autoRelay: {\n enabled: false,\n maxListeners: 2\n }\n },\n identify: {\n protocolPrefix: 'ipfs',\n host: {\n agentVersion: AGENT_VERSION\n },\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 },\n ping: {\n protocolPrefix: 'ipfs',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n },\n fetch: {\n protocolPrefix: 'libp2p',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n }\n}\n\nexport function validateConfig (opts: RecursivePartial): Libp2pInit {\n const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {\n throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)\n }\n\n if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {\n throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)\n }\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)\n }\n\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (resultingOptions.identify.host.agentVersion === AGENT_VERSION) {\n if (isNode || isElectronMain) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.process.version}`\n } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`\n }\n }\n\n return resultingOptions\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerIdProto {\n id: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.id != null && obj.id.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.pubKey != null) {\n w.uint32(18)\n w.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n w.uint32(26)\n w.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerIdProto): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n", "import { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerIdProto } from './proto.js'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\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}\n\nexport async function createFromProtobuf (buf: Uint8Array): Promise {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return await createFromParts(\n id,\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }): Promise {\n return await createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array): Promise {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return await createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey)\n\n return await createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n", "import { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { Startable, isStartable } from '@libp2p/interfaces/startable'\nimport { isMultiaddr, Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { CompoundContentRouting } from './content-routing/index.js'\nimport { codes } from './errors.js'\nimport { DefaultAddressManager } from './address-manager/index.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { AutoDialler } from './connection-manager/auto-dialler.js'\nimport { Circuit } from './circuit/transport.js'\nimport { Relay } from './circuit/index.js'\nimport { KeyChain } from './keychain/index.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { DefaultUpgrader } from './upgrader.js'\nimport { DefaultRegistrar } from './registrar.js'\nimport { IdentifyService } from './identify/index.js'\nimport { FetchService } from './fetch/index.js'\nimport { PingService } from './ping/index.js'\nimport { NatManager } from './nat-manager.js'\nimport { PeerRecordUpdater } from './peer-record-updater.js'\nimport { DHTPeerRouting } from './dht/dht-peer-routing.js'\nimport { PersistentPeerStore } from '@libp2p/peer-store'\nimport { DHTContentRouting } from './dht/dht-content-routing.js'\nimport { DefaultComponents } from './components.js'\nimport type { Components } from './components.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions, Topology } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'\nimport { validateConfig } from './config.js'\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport errCode from 'err-code'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { DummyDHT } from './dht/dummy-dht.js'\nimport { DummyPubSub } from './pubsub/dummy-pubsub.js'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport { DefaultDialer } from './connection-manager/dialer/index.js'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Datastore } from 'interface-datastore'\n\nconst log = logger('libp2p')\n\nexport class Libp2pNode extends EventEmitter implements Libp2p {\n public peerId: PeerId\n public dht: DualDHT\n public pubsub: PubSub\n public identifyService: IdentifyService\n public fetchService: FetchService\n public pingService: PingService\n public components: Components\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public keychain: KeyChain\n public connectionManager: ConnectionManager\n public registrar: Registrar\n public metrics?: Metrics\n\n private started: boolean\n private readonly services: Startable[]\n\n constructor (init: Libp2pInit) {\n super()\n\n this.started = false\n this.peerId = init.peerId\n const components = this.components = new DefaultComponents({\n peerId: init.peerId,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: {\n denyDialPeer: async () => await Promise.resolve(false),\n denyDialMultiaddr: async () => await Promise.resolve(false),\n denyInboundConnection: async () => await Promise.resolve(false),\n denyOutboundConnection: async () => await Promise.resolve(false),\n denyInboundEncryptedConnection: async () => await Promise.resolve(false),\n denyOutboundEncryptedConnection: async () => await Promise.resolve(false),\n denyInboundUpgradedConnection: async () => await Promise.resolve(false),\n denyOutboundUpgradedConnection: async () => await Promise.resolve(false),\n filterMultiaddrForPeer: async () => await Promise.resolve(true),\n ...init.connectionGater\n }\n })\n components.peerStore = new PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n })\n\n this.services = [\n components\n ]\n\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.components.metrics = this.configureComponent(init.metrics(this.components))\n }\n\n this.peerStore = this.components.peerStore\n\n this.peerStore.addEventListener('peer', evt => {\n const { detail: peerData } = evt\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peerData }))\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.components.connectionProtector = init.connectionProtector(components)\n }\n\n // Set up the Upgrader\n this.components.upgrader = new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map(fn => this.configureComponent(fn(this.components))),\n muxers: (init.streamMuxers ?? []).map(fn => this.configureComponent(fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n })\n\n // Create the dialer\n this.components.dialer = new DefaultDialer(this.components, init.connectionManager)\n\n // Create the Connection Manager\n this.connectionManager = this.components.connectionManager = new DefaultConnectionManager(this.components, init.connectionManager)\n\n // forward connection manager events\n this.components.connectionManager.addEventListener('peer:disconnect', (event) => {\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: event.detail }))\n })\n this.components.connectionManager.addEventListener('peer:connect', (event) => {\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: event.detail }))\n })\n\n // Create the Registrar\n this.registrar = this.components.registrar = new DefaultRegistrar(this.components)\n\n // Setup the transport manager\n this.components.transportManager = new DefaultTransportManager(this.components, init.transportManager)\n\n // Addresses {listen, announce, noAnnounce}\n this.components.addressManager = new DefaultAddressManager(this.components, init.addresses)\n\n // update our peer record when addresses change\n this.configureComponent(new PeerRecordUpdater(this.components))\n\n this.configureComponent(new AutoDialler(this.components, {\n enabled: init.connectionManager.autoDial,\n minConnections: init.connectionManager.minConnections,\n autoDialInterval: init.connectionManager.autoDialInterval\n }))\n\n // Create keychain\n const keychainOpts = KeyChain.generateOptions()\n this.keychain = this.configureComponent(new KeyChain(this.components, {\n ...keychainOpts,\n ...init.keychain\n }))\n\n // Create the Nat Manager\n this.services.push(new NatManager(this.components, init.nat))\n\n init.transports.forEach((fn) => {\n this.components.transportManager.add(this.configureComponent(fn(this.components)))\n })\n\n // Add the identify service\n this.identifyService = new IdentifyService(this.components, {\n ...init.identify\n })\n this.configureComponent(this.identifyService)\n\n // dht provided components (peerRouting, contentRouting, dht)\n if (init.dht != null) {\n this.dht = this.components.dht = init.dht(this.components)\n } else {\n this.dht = new DummyDHT()\n }\n\n // Create pubsub if provided\n if (init.pubsub != null) {\n this.pubsub = this.components.pubsub = init.pubsub(this.components)\n } else {\n this.pubsub = new DummyPubSub()\n }\n\n // Attach remaining APIs\n // peer and content routing will automatically get modules from _modules and _dht\n\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map(fn => this.configureComponent(fn(this.components)))\n\n if (init.dht != null) {\n // add dht to routers\n peerRouters.push(this.configureComponent(new DHTPeerRouting(this.dht)))\n\n // use dht for peer discovery\n this.dht.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n\n this.peerRouting = this.components.peerRouting = this.configureComponent(new DefaultPeerRouting(this.components, {\n ...init.peerRouting,\n routers: peerRouters\n }))\n\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map(fn => this.configureComponent(fn(this.components)))\n\n if (init.dht != null) {\n // add dht to routers\n contentRouters.push(this.configureComponent(new DHTContentRouting(this.dht)))\n }\n\n this.contentRouting = this.components.contentRouting = this.configureComponent(new CompoundContentRouting(this.components, {\n routers: contentRouters\n }))\n\n if (init.relay.enabled) {\n this.components.transportManager.add(this.configureComponent(new Circuit(this.components, init.relay)))\n\n this.configureComponent(new Relay(this.components, {\n addressSorter: init.connectionManager.addressSorter,\n ...init.relay\n }))\n }\n\n this.fetchService = this.configureComponent(new FetchService(this.components, {\n ...init.fetch\n }))\n\n this.pingService = this.configureComponent(new PingService(this.components, {\n ...init.ping\n }))\n\n // Discovery modules\n for (const fn of init.peerDiscovery ?? []) {\n const service = this.configureComponent(fn(this.components))\n\n service.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n }\n\n private configureComponent (component: T): T {\n if (isStartable(component)) {\n this.services.push(component)\n }\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start () {\n if (this.started) {\n return\n }\n\n this.started = true\n\n log('libp2p is starting')\n\n try {\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStart != null) {\n await service.beforeStart()\n }\n })\n )\n\n // start any startables\n await Promise.all(\n this.services.map(service => service.start())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStart != null) {\n await service.afterStart()\n }\n })\n )\n\n log('libp2p has started')\n } catch (err: any) {\n log.error('An error occurred starting libp2p', err)\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop () {\n if (!this.started) {\n return\n }\n\n log('libp2p is stopping')\n\n this.started = false\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStop != null) {\n await service.beforeStop()\n }\n })\n )\n\n await Promise.all(\n this.services.map(service => service.stop())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStop != null) {\n await service.afterStop()\n }\n })\n )\n\n log('libp2p has stopped')\n }\n\n isStarted () {\n return this.started\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.connectionManager.getConnections(peerId)\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n return await this.components.connectionManager.openConnection(peer, options)\n }\n\n async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}) {\n if (protocols == null) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n const connection = await this.dial(peer, options)\n\n return await connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.addressManager.getAddresses()\n }\n\n getProtocols (): string[] {\n return this.components.registrar.getProtocols()\n }\n\n async hangUp (peer: PeerId | Multiaddr): Promise {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '')\n }\n\n await this.components.connectionManager.closeConnections(peer)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise {\n log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.pubKey != null) {\n return peerInfo.pubKey\n }\n\n if (this.dht == null) {\n throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ])\n\n // search the dht\n for await (const event of this.dht.get(peerKey, options)) {\n if (event.name === 'VALUE') {\n const key = unmarshalPublicKey(event.value)\n\n await this.peerStore.keyBook.set(peer, event.value)\n\n return key.bytes\n }\n }\n\n throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)\n }\n\n async fetch (peer: PeerId | Multiaddr, key: string, options: AbortOptions = {}): Promise {\n if (isMultiaddr(peer)) {\n const peerId = peerIdFromString(peer.getPeerId() ?? '')\n await this.components.peerStore.addressBook.add(peerId, [peer])\n peer = peerId\n }\n\n return await this.fetchService.fetch(peer, key, options)\n }\n\n async ping (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n if (isMultiaddr(peer)) {\n const peerId = peerIdFromString(peer.getPeerId() ?? '')\n await this.components.peerStore.addressBook.add(peerId, [peer])\n peer = peerId\n }\n\n return await this.pingService.ping(peer, options)\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.unhandle(protocol)\n })\n )\n }\n\n async register (protocol: string, topology: Topology): Promise {\n return await this.registrar.register(protocol, topology)\n }\n\n unregister (id: string) {\n this.registrar.unregister(id)\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events.\n * Known peers may be emitted.\n */\n onDiscoveryPeer (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n log.error(new Error(codes.ERR_DISCOVERED_SELF))\n return\n }\n\n if (peer.multiaddrs.length > 0) {\n void this.components.peerStore.addressBook.add(peer.id, peer.multiaddrs).catch(err => log.error(err))\n }\n\n if (peer.protocols.length > 0) {\n void this.components.peerStore.protoBook.set(peer.id, peer.protocols).catch(err => log.error(err))\n }\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peer }))\n }\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: Libp2pOptions): Promise {\n if (options.peerId == null) {\n const datastore = options.datastore as Datastore | undefined\n\n if (datastore != null) {\n try {\n // try load the peer id from the keychain\n // @ts-expect-error missing the peer id property\n const keyChain = new KeyChain({\n datastore\n }, {\n ...KeyChain.generateOptions(),\n ...(options.keychain ?? {})\n })\n\n options.peerId = await keyChain.exportPeerId('self')\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n }\n\n if (options.peerId == null) {\n // no peer id in the keychain, create a new peer id\n options.peerId = await createEd25519PeerId()\n }\n\n return new Libp2pNode(validateConfig(options))\n}\n", "import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { symbol } from '@libp2p/interface-peer-discovery'\n\nexport class DummyDHT extends EventEmitter implements DualDHT {\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/dummy-dht'\n }\n\n get wan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get lan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findProviders (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findPeer (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n getClosestPeers (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n provide (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n put (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async getMode (): Promise<'client' | 'server'> {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async setMode (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async refreshRoutingTable (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n}\n", "import { EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign, TopicValidatorFn } from '@libp2p/interface-pubsub'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\n\nexport class DummyPubSub extends EventEmitter implements PubSub {\n public topicValidators = new Map()\n\n isStarted (): boolean {\n return false\n }\n\n start (): void | Promise {\n\n }\n\n stop (): void | Promise {\n\n }\n\n get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n get multicodecs (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getPeers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getTopics (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n subscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n unsubscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getSubscribers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n async publish (): Promise {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { isMultiaddr, Multiaddr, Resolver, multiaddr, resolvers } from '@multiformats/multiaddr'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'events'\nimport { DialAction, DialRequest } from './dial-request.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { codes } from '../../errors.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PER_PEER_DIALS,\n MAX_ADDRS_TO_DIAL\n} from '../../constants.js'\nimport type { Connection, ConnectionGater } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { getPeerAddress } from '../../get-peer.js'\nimport type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { Dialer } from '@libp2p/interface-connection-manager'\nimport type { TransportManager } from '@libp2p/interface-transport'\n\nconst log = logger('libp2p:dialer')\n\nexport interface DialTarget {\n id: string\n addrs: Multiaddr[]\n}\n\nexport interface PendingDial {\n dialRequest: DialRequest\n controller: TimeoutController\n promise: Promise\n destroy: () => void\n}\n\nexport interface PendingDialTarget {\n resolve: (value: any) => void\n reject: (err: Error) => void\n}\n\nexport interface DialerInit {\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take\n */\n dialTimeout?: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n}\n\nexport interface DefaultDialerComponents {\n peerId: PeerId\n metrics?: Metrics\n peerStore: PeerStore\n transportManager: TransportManager\n connectionGater: ConnectionGater\n}\n\nexport class DefaultDialer implements Startable, Dialer {\n private readonly components: DefaultDialerComponents\n private readonly addressSorter: AddressSorter\n private readonly maxAddrsToDial: number\n private readonly timeout: number\n private readonly maxDialsPerPeer: number\n public tokens: number[]\n public pendingDials: Map\n public pendingDialTargets: Map\n private started: boolean\n\n constructor (components: DefaultDialerComponents, init: DialerInit = {}) {\n this.started = false\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxAddrsToDial = init.maxAddrsToDial ?? MAX_ADDRS_TO_DIAL\n this.timeout = init.dialTimeout ?? DIAL_TIMEOUT\n this.maxDialsPerPeer = init.maxDialsPerPeer ?? MAX_PER_PEER_DIALS\n this.tokens = [...new Array(init.maxParallelDials ?? MAX_PARALLEL_DIALS)].map((_, index) => index)\n this.components = components\n this.pendingDials = trackedMap({\n name: 'libp2p_dialler_pending_dials',\n metrics: components.metrics\n })\n this.pendingDialTargets = trackedMap({\n name: 'libp2p_dialler_pending_dial_targets',\n metrics: components.metrics\n })\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n /**\n * Clears any pending dials\n */\n async stop () {\n this.started = false\n\n for (const dial of this.pendingDials.values()) {\n try {\n dial.controller.abort()\n } catch (err: any) {\n log.error(err)\n }\n }\n this.pendingDials.clear()\n\n for (const pendingTarget of this.pendingDialTargets.values()) {\n pendingTarget.abort()\n }\n this.pendingDialTargets.clear()\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async dial (peerIdOrMultiaddr: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { peerId, multiaddr } = getPeerAddress(peerIdOrMultiaddr)\n\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)\n }\n\n if (multiaddr != null) {\n log('storing multiaddrs %p', peerId, multiaddr)\n await this.components.peerStore.addressBook.add(peerId, [multiaddr])\n }\n\n if (await this.components.connectionGater.denyDialPeer(peerId)) {\n throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)\n }\n }\n\n log('creating dial target for %p', peerId)\n\n // resolving multiaddrs can involve dns lookups so allow them to be aborted\n const controller = new AbortController()\n const controllerId = randomId()\n this.pendingDialTargets.set(controllerId, controller)\n let signal = controller.signal\n\n // merge with the passed signal, if any\n if (options.signal != null) {\n signal = anySignal([signal, options.signal])\n }\n\n let dialTarget: DialTarget\n\n try {\n dialTarget = await this._createDialTarget({ peerId, multiaddr }, {\n ...options,\n signal\n })\n } finally {\n // done resolving the multiaddrs so remove the abort controller\n this.pendingDialTargets.delete(controllerId)\n }\n\n if (dialTarget.addrs.length === 0) {\n throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)\n }\n\n // try to join an in-flight dial for this peer if one is available\n const pendingDial = this.pendingDials.get(dialTarget.id) ?? this._createPendingDial(dialTarget, options)\n\n try {\n const connection = await pendingDial.promise\n log('dial succeeded to %s', dialTarget.id)\n return connection\n } catch (err: any) {\n log('dial failed to %s', dialTarget.id, err)\n // Error is a timeout\n if (pendingDial.controller.signal.aborted) {\n err.code = codes.ERR_TIMEOUT\n }\n log.error(err)\n throw err\n } finally {\n pendingDial.destroy()\n }\n }\n\n /**\n * Creates a DialTarget. The DialTarget is used to create and track\n * the DialRequest to a given peer.\n *\n * If a multiaddr is received it should be the only address attempted.\n *\n * Multiaddrs not supported by the available transports will be filtered out.\n */\n async _createDialTarget (peerIdOrMultiaddr: { peerId?: PeerId, multiaddr?: Multiaddr }, options: AbortOptions): Promise {\n let addrs: Multiaddr[] = []\n\n if (isMultiaddr(peerIdOrMultiaddr.multiaddr)) {\n addrs.push(peerIdOrMultiaddr.multiaddr)\n }\n\n // only load addresses if a peer id was passed, otherwise only dial the passed multiaddr\n if (!isMultiaddr(peerIdOrMultiaddr.multiaddr) && isPeerId(peerIdOrMultiaddr.peerId)) {\n addrs.push(...await this._loadAddresses(peerIdOrMultiaddr.peerId))\n }\n\n addrs = (await Promise.all(\n addrs.map(async (ma) => await this._resolve(ma, options))\n ))\n .flat()\n // Multiaddrs not supported by the available transports will be filtered out.\n .filter(ma => Boolean(this.components.transportManager.transportForMultiaddr(ma)))\n\n // deduplicate addresses\n addrs = [...new Set(addrs.map(ma => ma.toString()))].map(ma => multiaddr(ma))\n\n if (addrs.length > this.maxAddrsToDial) {\n throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)\n }\n\n const peerId = isPeerId(peerIdOrMultiaddr.peerId) ? peerIdOrMultiaddr.peerId : undefined\n\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`\n addrs = addrs.map(addr => {\n const addressPeerId = addr.getPeerId()\n\n if (addressPeerId == null || !peerId.equals(addressPeerId)) {\n return addr.encapsulate(peerIdMultiaddr)\n }\n\n return addr\n })\n }\n\n return {\n id: peerId == null ? randomId() : peerId.toString(),\n addrs\n }\n }\n\n /**\n * Loads a list of addresses from the peer store for the passed peer id\n */\n async _loadAddresses (peer: PeerId): Promise {\n const addresses = await this.components.peerStore.addressBook.get(peer)\n\n return (await Promise.all(\n addresses.map(async address => {\n const deny = await this.components.connectionGater.denyDialMultiaddr(peer, address.multiaddr)\n\n if (deny) {\n return false\n }\n\n return address\n })\n ))\n .filter(isTruthy)\n // Sort addresses so, for example, we try certified public address first\n .sort(this.addressSorter)\n .map(address => address.multiaddr)\n }\n\n /**\n * Creates a PendingDial that wraps the underlying DialRequest\n */\n _createPendingDial (dialTarget: DialTarget, options: AbortOptions = {}): PendingDial {\n /**\n * @param {Multiaddr} addr\n * @param {{ signal: { aborted: any; }; }} options\n */\n const dialAction: DialAction = async (addr, options = {}) => {\n if (options.signal?.aborted === true) {\n throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)\n }\n\n return await this.components.transportManager.dial(addr, options).catch(err => {\n log.error('dial to %s failed', addr, err)\n throw err\n })\n }\n\n const dialRequest = new DialRequest({\n addrs: dialTarget.addrs,\n dialAction,\n dialer: this\n })\n\n // Combine the timeout signal and options.signal, if provided\n const timeoutController = new TimeoutController(this.timeout)\n\n const signals = [timeoutController.signal]\n ;(options.signal != null) && signals.push(options.signal)\n const signal = anySignal(signals)\n\n // this signal will potentially be used while dialing lots of\n // peers so prevent MaxListenersExceededWarning appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, signal)\n } catch {}\n\n const pendingDial = {\n dialRequest,\n controller: timeoutController,\n promise: dialRequest.run({ ...options, signal }),\n destroy: () => {\n timeoutController.clear()\n this.pendingDials.delete(dialTarget.id)\n }\n }\n this.pendingDials.set(dialTarget.id, pendingDial)\n\n return pendingDial\n }\n\n getTokens (num: number) {\n const total = Math.min(num, this.maxDialsPerPeer, this.tokens.length)\n const tokens = this.tokens.splice(0, total)\n log('%d tokens request, returning %d, %d remaining', num, total, this.tokens.length)\n return tokens\n }\n\n releaseToken (token: number) {\n // Guard against duplicate releases\n if (this.tokens.includes(token)) {\n return\n }\n\n log('token %d released', token)\n this.tokens.push(token)\n }\n\n /**\n * Resolve multiaddr recursively\n */\n async _resolve (ma: Multiaddr, options: AbortOptions): Promise {\n // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place\n // Now only supporting resolve for dnsaddr\n const resolvableProto = ma.protoNames().includes('dnsaddr')\n\n // Multiaddr is not resolvable? End recursion!\n if (!resolvableProto) {\n return [ma]\n }\n\n const resolvedMultiaddrs = await this._resolveRecord(ma, options)\n const recursiveMultiaddrs = await Promise.all(resolvedMultiaddrs.map(async (nm) => {\n return await this._resolve(nm, options)\n }))\n\n const addrs = recursiveMultiaddrs.flat()\n return addrs.reduce((array, newM) => {\n if (array.find(m => m.equals(newM)) == null) {\n array.push(newM)\n }\n return array\n }, ([]))\n }\n\n /**\n * Resolve a given multiaddr. If this fails, an empty array will be returned\n */\n async _resolveRecord (ma: Multiaddr, options: AbortOptions): Promise {\n try {\n ma = multiaddr(ma.toString()) // Use current multiaddr module\n const multiaddrs = await ma.resolve(options)\n return multiaddrs\n } catch (err) {\n log.error(`multiaddr ${ma.toString()} could not be resolved`, err)\n return []\n }\n }\n}\n\n/**\n * Type safe version of `list.filter(Boolean)`\n */\nfunction isTruthy (e: T | false | null | undefined): e is T {\n return Boolean(e)\n}\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n", "import errCode from 'err-code'\nimport { anySignal } from 'any-signal'\nimport FIFO from 'p-fifo'\nimport { setMaxListeners } from 'events'\nimport { codes } from '../../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Dialer } from '@libp2p/interface-connection-manager'\n\nconst log = logger('libp2p:dialer:dial-request')\n\nexport interface DialAction {\n (m: Multiaddr, options: AbortOptions): Promise\n}\n\nexport interface DialRequestOptions {\n addrs: Multiaddr[]\n dialAction: DialAction\n dialer: Dialer\n}\n\nexport class DialRequest {\n private readonly addrs: Multiaddr[]\n private readonly dialer: Dialer\n private readonly dialAction: DialAction\n\n /**\n * Manages running the `dialAction` on multiple provided `addrs` in parallel\n * up to a maximum determined by the number of tokens returned\n * from `dialer.getTokens`. Once a DialRequest is created, it can be\n * started using `DialRequest.run(options)`. Once a single dial has succeeded,\n * all other dials in the request will be cancelled.\n */\n constructor (options: DialRequestOptions) {\n const {\n addrs,\n dialAction,\n dialer\n } = options\n\n this.addrs = addrs\n this.dialer = dialer\n this.dialAction = dialAction\n }\n\n async run (options: AbortOptions = {}): Promise {\n const tokens = this.dialer.getTokens(this.addrs.length)\n\n // If no tokens are available, throw\n if (tokens.length < 1) {\n throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)\n }\n\n const tokenHolder = new FIFO()\n\n for (const token of tokens) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n }\n\n const dialAbortControllers: Array<(AbortController | undefined)> = this.addrs.map(() => {\n const controller = new AbortController()\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n return controller\n })\n\n if (options.signal != null) {\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, options.signal)\n } catch {}\n }\n\n let completedDials = 0\n let done = false\n\n try {\n return await Promise.any(this.addrs.map(async (addr, i) => {\n const token = await tokenHolder.shift() // get token\n // End attempt once another attempt succeeded\n if (done) {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)\n }\n\n const controller = dialAbortControllers[i]\n if (controller == null) {\n throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)\n }\n let conn\n try {\n const signal = controller.signal\n conn = await this.dialAction(addr, { ...options, signal: (options.signal != null) ? anySignal([signal, options.signal]) : signal })\n // Remove the successful AbortController so it is not aborted\n dialAbortControllers[i] = undefined\n } finally {\n completedDials++\n // If we have more or equal dials remaining than tokens, recycle the token, otherwise release it\n if (this.addrs.length - completedDials >= tokens.length) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n } else {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n }\n }\n\n if (conn == null) {\n // Notify Promise.any that attempt was not successful\n // to prevent from returning undefined despite there\n // were successful dial attempts\n throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)\n } else {\n // This dial succeeded, don't attempt anything else\n done = true\n }\n\n return conn\n }))\n } finally {\n // success/failure happened, abort everything else\n dialAbortControllers.forEach(c => {\n if (c !== undefined) {\n c.abort()\n }\n })\n tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer\n }\n }\n}\n", "/**\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 */\n\nimport { createLibp2pNode } from './libp2p.js'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport type { TransportManagerInit } from './transport-manager.js'\nimport type { IdentifyServiceInit } from './identify/index.js'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { Datastore } from 'interface-datastore'\nimport type { PeerStoreInit } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { RelayConfig } from './circuit/index.js'\nimport type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { Transport } from '@libp2p/interface-transport'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PingServiceInit } from './ping/index.js'\nimport type { FetchServiceInit } from './fetch/index.js'\nimport type { Components } from './components.js'\nimport type { Libp2p } from '@libp2p/interface-libp2p'\nimport type { KeyChainInit } from './keychain/index.js'\nimport type { NatManagerInit } from './nat-manager.js'\nimport type { AddressManagerInit } from './address-manager/index.js'\nimport type { PeerRoutingInit } from './peer-routing.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\n\n/**\n * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).\n */\nexport interface Libp2pInit {\n /**\n * peerId instance (it will be created if not provided)\n */\n peerId: PeerId\n\n /**\n * Addresses for transport listening and to advertise to the network\n */\n addresses: AddressManagerInit\n\n /**\n * libp2p Connection Manager configuration\n */\n connectionManager: ConnectionManagerInit\n\n /**\n * A connection gater can deny new connections based on user criteria\n */\n connectionGater: Partial\n\n /**\n * libp2p transport manager configuration\n */\n transportManager: TransportManagerInit\n\n /**\n * An optional datastore to persist peer information, DHT records, etc.\n *\n * An in-memory datastore will be used if one is not provided.\n */\n datastore: Datastore\n\n /**\n * libp2p PeerStore configuration\n */\n peerStore: PeerStoreInit\n\n /**\n * libp2p Peer routing service configuration\n */\n peerRouting: PeerRoutingInit\n\n /**\n * keychain configuration\n */\n keychain: KeyChainInit\n\n /**\n * The NAT manager controls uPNP hole punching\n */\n nat: NatManagerInit\n\n /**\n * If configured as a relay this node will relay certain\n * types of traffic for other peers\n */\n relay: RelayConfig\n\n /**\n * libp2p identify protocol options\n */\n identify: IdentifyServiceInit\n\n /**\n * libp2p ping protocol options\n */\n ping: PingServiceInit\n\n /**\n * libp2p fetch protocol options\n */\n fetch: FetchServiceInit\n\n /**\n * An array that must include at least 1 compliant transport\n */\n transports: Array<(components: Components) => Transport>\n streamMuxers?: Array<(components: Components) => StreamMuxerFactory>\n connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>\n peerDiscovery?: Array<(components: Components) => PeerDiscovery>\n peerRouters?: Array<(components: Components) => PeerRouting>\n contentRouters?: Array<(components: Components) => ContentRouting>\n\n /**\n * Pass a DHT implementation to enable DHT operations\n */\n dht?: (components: Components) => DualDHT\n\n /**\n * A Metrics implementation can be supplied to collect metrics on this node\n */\n metrics?: (components: Components) => Metrics\n\n /**\n * If a PubSub implmentation is supplied, PubSub operations will become available\n */\n pubsub?: (components: Components) => PubSub\n\n /**\n * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys\n */\n connectionProtector?: (components: Components) => ConnectionProtector\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits, so that you can be notified of relevant network events.\n */\nexport interface Libp2pEvents {\n /**\n * @example\n *\n * ```js\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent\n}\n\nexport type { Libp2p }\n\nexport type Libp2pOptions = RecursivePartial & { start?: boolean }\n\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 * ```js\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 *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [mplex()],\n * connectionEncryption: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p (options: Libp2pOptions): Promise {\n const node = await createLibp2pNode(options)\n\n if (options.start !== false) {\n await node.start()\n }\n\n return node\n}\n", "// @ts-expect-error no types\nimport KBuck from 'k-bucket'\nimport * as utils from '../utils.js'\nimport Queue from 'p-queue'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { logger } from '@libp2p/logger'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Logger } from '@libp2p/logger'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport type { Metric, Metrics } from '@libp2p/interface-metrics'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nexport const KAD_CLOSE_TAG_NAME = 'kad-close'\nexport const KAD_CLOSE_TAG_VALUE = 50\nexport const KBUCKET_SIZE = 20\nexport const PING_TIMEOUT = 10000\nexport const PING_CONCURRENCY = 10\n\nexport interface KBucketPeer {\n id: Uint8Array\n peer: PeerId\n}\n\nexport interface KBucket {\n id: Uint8Array\n contacts: KBucketPeer[]\n dontSplit: boolean\n left: KBucket\n right: KBucket\n}\n\ninterface KBucketTreeEvents {\n 'ping': (oldContacts: KBucketPeer[], newContact: KBucketPeer) => void\n 'added': (contact: KBucketPeer) => void\n 'removed': (contact: KBucketPeer) => void\n}\n\nexport interface KBucketTree {\n root: KBucket\n localNodeId: Uint8Array\n\n on: (\n event: U, listener: KBucketTreeEvents[U]\n ) => this\n\n closest: (key: Uint8Array, count: number) => KBucketPeer[]\n closestPeer: (key: Uint8Array) => KBucketPeer\n remove: (key: Uint8Array) => void\n add: (peer: KBucketPeer) => void\n get: (key: Uint8Array) => Uint8Array\n count: () => number\n toIterable: () => Iterable\n}\n\nexport interface RoutingTableInit {\n lan: boolean\n protocol: string\n kBucketSize?: number\n pingTimeout?: number\n pingConcurrency?: number\n tagName?: string\n tagValue?: number\n}\n\nexport interface RoutingTableComponents {\n peerId: PeerId\n peerStore: PeerStore\n connectionManager: ConnectionManager\n metrics?: Metrics\n}\n\n/**\n * A wrapper around `k-bucket`, to provide easy store and\n * retrieval for peers.\n */\nexport class RoutingTable implements Startable {\n public kBucketSize: number\n public kb?: KBucketTree\n public pingQueue: Queue\n\n private readonly log: Logger\n private readonly components: RoutingTableComponents\n private readonly lan: boolean\n private readonly pingTimeout: number\n private readonly pingConcurrency: number\n private running: boolean\n private readonly protocol: string\n private readonly tagName: string\n private readonly tagValue: number\n private metrics?: {\n routingTableSize: Metric\n pingQueueSize: Metric\n pingRunning: Metric\n }\n\n constructor (components: RoutingTableComponents, init: RoutingTableInit) {\n const { kBucketSize, pingTimeout, lan, pingConcurrency, protocol, tagName, tagValue } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:routing-table`)\n this.kBucketSize = kBucketSize ?? KBUCKET_SIZE\n this.pingTimeout = pingTimeout ?? PING_TIMEOUT\n this.pingConcurrency = pingConcurrency ?? PING_CONCURRENCY\n this.lan = lan\n this.running = false\n this.protocol = protocol\n this.tagName = tagName ?? KAD_CLOSE_TAG_NAME\n this.tagValue = tagValue ?? KAD_CLOSE_TAG_VALUE\n\n const updatePingQueueSizeMetric = (): void => {\n this.metrics?.pingQueueSize.update(this.pingQueue.size)\n this.metrics?.pingRunning.update(this.pingQueue.pending)\n }\n\n this.pingQueue = new Queue({ concurrency: this.pingConcurrency })\n this.pingQueue.addListener('add', updatePingQueueSizeMetric)\n this.pingQueue.addListener('next', updatePingQueueSizeMetric)\n\n this._onPing = this._onPing.bind(this)\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n async start (): Promise {\n this.running = true\n\n if (this.components.metrics != null) {\n this.metrics = {\n routingTableSize: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_routing_table_size`),\n pingQueueSize: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_ping_queue_size`),\n pingRunning: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_ping_running`)\n }\n }\n\n const kBuck: KBucketTree = new KBuck({\n localNodeId: await utils.convertPeerId(this.components.peerId),\n numberOfNodesPerKBucket: this.kBucketSize,\n numberOfNodesToPing: 1\n })\n this.kb = kBuck\n\n // test whether to evict peers\n kBuck.on('ping', this._onPing)\n\n // tag kad-close peers\n this._tagPeers(kBuck)\n }\n\n async stop (): Promise {\n this.running = false\n this.pingQueue.clear()\n this.kb = undefined\n }\n\n /**\n * Keep track of our k-closest peers and tag them in the peer store as such\n * - this will lower the chances that connections to them get closed when\n * we reach connection limits\n */\n _tagPeers (kBuck: KBucketTree): void {\n let kClosest = new PeerSet()\n\n const updatePeerTags = utils.debounce(() => {\n const newClosest = new PeerSet(\n kBuck.closest(kBuck.localNodeId, KBUCKET_SIZE).map(contact => contact.peer)\n )\n const addedPeers = newClosest.difference(kClosest)\n const removedPeers = kClosest.difference(newClosest)\n\n Promise.resolve()\n .then(async () => {\n for (const peer of addedPeers) {\n await this.components.peerStore.tagPeer(peer, this.tagName, {\n value: this.tagValue\n })\n }\n\n for (const peer of removedPeers) {\n await this.components.peerStore.unTagPeer(peer, this.tagName)\n }\n })\n .catch(err => {\n this.log.error('Could not update peer tags', err)\n })\n\n kClosest = newClosest\n })\n\n kBuck.on('added', () => {\n updatePeerTags()\n })\n kBuck.on('removed', () => {\n updatePeerTags()\n })\n }\n\n /**\n * Called on the `ping` event from `k-bucket` when a bucket is full\n * and cannot split.\n *\n * `oldContacts.length` is defined by the `numberOfNodesToPing` param\n * passed to the `k-bucket` constructor.\n *\n * `oldContacts` will not be empty and is the list of contacts that\n * have not been contacted for the longest.\n */\n _onPing (oldContacts: KBucketPeer[], newContact: KBucketPeer): void {\n // add to a queue so multiple ping requests do not overlap and we don't\n // flood the network with ping requests if lots of newContact requests\n // are received\n this.pingQueue.add(async () => {\n if (!this.running) {\n return\n }\n\n let responded = 0\n\n try {\n await Promise.all(\n oldContacts.map(async oldContact => {\n let timeoutController\n\n try {\n timeoutController = new TimeoutController(this.pingTimeout)\n\n const options = {\n signal: timeoutController.signal\n }\n\n this.log('pinging old contact %p', oldContact.peer)\n const connection = await this.components.connectionManager.openConnection(oldContact.peer, options)\n const stream = await connection.newStream(this.protocol, options)\n stream.close()\n responded++\n } catch (err: any) {\n if (this.running && this.kb != null) {\n // only evict peers if we are still running, otherwise we evict when dialing is\n // cancelled due to shutdown in progress\n this.log.error('could not ping peer %p', oldContact.peer, err)\n this.log('evicting old contact after ping failed %p', oldContact)\n this.kb.remove(oldContact.id)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n this.metrics?.routingTableSize.update(this.size)\n }\n })\n )\n\n if (this.running && responded < oldContacts.length && this.kb != null) {\n this.log('adding new contact %p', newContact.peer)\n this.kb.add(newContact)\n }\n } catch (err: any) {\n this.log.error('could not process k-bucket ping event', err)\n }\n })\n .catch(err => {\n this.log.error('could not process k-bucket ping event', err)\n })\n }\n\n // -- Public Interface\n\n /**\n * Amount of currently stored peers\n */\n get size (): number {\n if (this.kb == null) {\n return 0\n }\n\n return this.kb.count()\n }\n\n /**\n * Find a specific peer by id\n */\n async find (peer: PeerId): Promise {\n const key = await utils.convertPeerId(peer)\n const closest = this.closestPeer(key)\n\n if (closest != null && peer.equals(closest)) {\n return closest\n }\n\n return undefined\n }\n\n /**\n * Retrieve the closest peers to the given key\n */\n closestPeer (key: Uint8Array): PeerId | undefined {\n const res = this.closestPeers(key, 1)\n\n if (res.length > 0) {\n return res[0]\n }\n\n return undefined\n }\n\n /**\n * Retrieve the `count`-closest peers to the given key\n */\n closestPeers (key: Uint8Array, count = this.kBucketSize): PeerId[] {\n if (this.kb == null) {\n return []\n }\n\n const closest = this.kb.closest(key, count)\n\n return closest.map(p => p.peer)\n }\n\n /**\n * Add or update the routing table with the given peer\n */\n async add (peer: PeerId): Promise {\n if (this.kb == null) {\n throw new Error('RoutingTable is not started')\n }\n\n const id = await utils.convertPeerId(peer)\n\n this.kb.add({ id, peer })\n\n this.log('added %p with kad id %b', peer, id)\n\n this.metrics?.routingTableSize.update(this.size)\n }\n\n /**\n * Remove a given peer from the table\n */\n async remove (peer: PeerId): Promise {\n if (this.kb == null) {\n throw new Error('RoutingTable is not started')\n }\n\n const id = await utils.convertPeerId(peer)\n\n this.kb.remove(id)\n\n this.metrics?.routingTableSize.update(this.size)\n }\n}\n", "import { Netmask } from 'netmask';\nimport ip_regex from 'ip-regex';\nimport { isIP } from '@chainsafe/is-ip';\nimport ipaddr from 'ipaddr.js';\nconst { isValid: is_valid, parse } = ipaddr;\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(ip_range => new Netmask(ip_range));\nfunction ipv4_check(ip_addr) {\n for (let r of NETMASK_RANGES) {\n if (r.contains(ip_addr))\n return true;\n }\n return false;\n}\nfunction ipv6_check(ip_addr) {\n return /^::$/.test(ip_addr) ||\n /^::1$/.test(ip_addr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\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(ip_addr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ip_addr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ip_addr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ip_addr);\n}\nexport default (ip) => {\n if (is_valid(ip)) {\n const parsed = parse(ip);\n if (parsed.kind() === 'ipv4')\n return ipv4_check(parsed.toNormalizedString());\n else if (parsed.kind() === 'ipv6')\n return ipv6_check(ip);\n }\n else if (isIP(ip) && ip_regex.v6().test(ip))\n return ipv6_check(ip);\n return undefined;\n};\n", "'use strict'\n\nimport is_ip_private from './lib/index.js'\nexport default is_ip_private", "// MaxRecordAge specifies the maximum time that any node will hold onto a record\n// from the time its received. This does not apply to any other forms of validity that\n// the record may contain.\n// For example, a record may contain an ipns entry with an EOL saying its valid\n// until the year 2020 (a great time in the future). For that record to stick around\n// it must be rebroadcasted more frequently than once every 'MaxRecordAge'\n\nexport const second = 1000\nexport const minute = 60 * second\nexport const hour = 60 * minute\n\nexport const MAX_RECORD_AGE = 36 * hour\n\nexport const LAN_PREFIX = '/lan'\n\nexport const PROTOCOL_PREFIX = '/ipfs'\n\nexport const PROTOCOL_DHT = '/kad/1.0.0'\n\nexport const RECORD_KEY_PREFIX = '/dht/record'\n\nexport const PROVIDER_KEY_PREFIX = '/dht/provider'\n\nexport const PROVIDERS_LRU_CACHE_SIZE = 256\n\nexport const PROVIDERS_VALIDITY = 24 * hour\n\nexport const PROVIDERS_CLEANUP_INTERVAL = hour\n\nexport const READ_MESSAGE_TIMEOUT = 10 * second\n\n// The number of records that will be retrieved on a call to getMany()\nexport const GET_MANY_RECORD_COUNT = 16\n\n// K is the maximum number of requests to perform before returning failure\nexport const K = 20\n\n// Alpha is the concurrency for asynchronous requests\nexport const ALPHA = 3\n\n// How often we look for our closest DHT neighbours\nexport const QUERY_SELF_INTERVAL = Number(5 * minute)\n\n// How long to look for our closest DHT neighbours for\nexport const QUERY_SELF_TIMEOUT = Number(30 * second)\n\n// How often we try to find new peers\nexport const TABLE_REFRESH_INTERVAL = Number(5 * minute)\n\n// How how long to look for new peers for\nexport const TABLE_REFRESH_QUERY_TIMEOUT = Number(30 * second)\n\n// When a timeout is not specified, run a query for this long\nexport const DEFAULT_QUERY_TIMEOUT = Number(30 * second)\n", "import { sha256 } from 'multiformats/hashes/sha2'\nimport { Key } from 'interface-datastore/key'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport isPrivateIp from 'private-ip'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { RECORD_KEY_PREFIX } from './constants.js'\n\n// const IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nconst PK_PREFIX = uint8ArrayFromString('/pk/')\n\nexport function removePrivateAddresses (peer: PeerInfo): PeerInfo {\n return {\n ...peer,\n multiaddrs: peer.multiaddrs.filter(multiaddr => {\n const [[type, addr]] = multiaddr.stringTuples()\n\n // treat /dns, /dns4, and /dns6 addrs as public\n if (type === 53 || type === 54 || type === 55) {\n // localhost can be a dns address but it's private\n if (addr === 'localhost') {\n return false\n }\n\n return true\n }\n\n if (type !== 4 && type !== 6) {\n return false\n }\n\n if (addr == null) {\n return false\n }\n\n const isPrivate = isPrivateIp(addr)\n\n if (isPrivate == null) {\n // not an ip address\n return true\n }\n\n return !isPrivate\n })\n }\n}\n\nexport function removePublicAddresses (peer: PeerInfo): PeerInfo {\n return {\n ...peer,\n multiaddrs: peer.multiaddrs.filter(multiaddr => {\n const [[type, addr]] = multiaddr.stringTuples()\n\n if (addr === 'localhost') {\n return true\n }\n\n if (type !== 4 && type !== 6) {\n return false\n }\n\n if (addr == null) {\n return false\n }\n\n const isPrivate = isPrivateIp(addr)\n\n if (isPrivate == null) {\n // not an ip address\n return false\n }\n\n return isPrivate\n })\n }\n}\n\n/**\n * Creates a DHT ID by hashing a given Uint8Array\n */\nexport async function convertBuffer (buf: Uint8Array): Promise {\n const multihash = await sha256.digest(buf)\n\n return multihash.digest\n}\n\n/**\n * Creates a DHT ID by hashing a Peer ID\n */\nexport async function convertPeerId (peerId: PeerId): Promise {\n return await convertBuffer(peerId.toBytes())\n}\n\n/**\n * Convert a Uint8Array to their SHA2-256 hash\n */\nexport function bufferToKey (buf: Uint8Array): Key {\n return new Key('/' + uint8ArrayToString(buf, 'base32'), false)\n}\n\n/**\n * Convert a Uint8Array to their SHA2-256 hash\n */\nexport function bufferToRecordKey (buf: Uint8Array): Key {\n return new Key(`${RECORD_KEY_PREFIX}/${uint8ArrayToString(buf, 'base32')}`, false)\n}\n\n/**\n * Generate the key for a public key.\n */\nexport function keyForPublicKey (peer: PeerId): Uint8Array {\n return uint8ArrayConcat([\n PK_PREFIX,\n peer.toBytes()\n ])\n}\n\nexport function isPublicKeyKey (key: Uint8Array): boolean {\n return uint8ArrayToString(key.subarray(0, 4)) === '/pk/'\n}\n\nexport function isIPNSKey (key: Uint8Array): boolean {\n return uint8ArrayToString(key.subarray(0, 4)) === '/ipns/'\n}\n\nexport function fromPublicKeyKey (key: Uint8Array): PeerId {\n return peerIdFromBytes(key.subarray(4))\n}\n\n/**\n * Create a new put record, encodes and signs it if enabled\n */\nexport function createPutRecord (key: Uint8Array, value: Uint8Array): Uint8Array {\n const timeReceived = new Date()\n const rec = new Libp2pRecord(key, value, timeReceived)\n\n return rec.serialize()\n}\n\nexport function debounce (callback: () => void, wait: number = 100): () => void {\n let timeout: ReturnType\n\n return (): void => {\n clearTimeout(timeout)\n timeout = setTimeout(() => { callback() }, wait)\n }\n}\n", "\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\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 * ```JavaScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator<[PeerId, T]> {\n return this.entries()\n }\n\n clear (): void {\n this.map.clear()\n }\n\n delete (peer: PeerId): void {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T): void {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values (): IterableIterator {\n return this.map.values()\n }\n\n get size (): number {\n return this.map.size\n }\n}\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\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 * ```JavaScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n", "import { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\n/**\n * We can't use PeerIds as list entries because list 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 * ```JavaScript\n * import { peerList } from '@libp2p/peer-collections'\n *\n * const list = peerList()\n * list.push(peerId)\n * ```\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList | Iterable) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList): PeerList {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]): void {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]): number {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length (): number {\n return this.list.length\n }\n}\n", "import { allocUnsafe } from './alloc.js'\nimport { asUint8Array } from './util/as-uint8array.js'\n\n/**\n * Returns the xor distance between two arrays\n */\nexport function xor (a: Uint8Array, b: Uint8Array): Uint8Array {\n if (a.length !== b.length) {\n throw new Error('Inputs should have the same length')\n }\n\n const result = allocUnsafe(a.length)\n\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i]\n }\n\n return asUint8Array(result)\n}\n", "export default [\n 77591, 22417, 43971, 28421, 740, 29829, 71467, 228973, 196661, 78537, 27689, 36431, 44415, 14362, 19456, 106025,\n 96308, 2882, 49509, 21149, 87173, 131409, 75844, 23676, 121838, 30291, 17492, 2953, 7564, 110620, 129477, 127283,\n 53113, 72417, 165166, 109690, 21200, 102125, 24049, 71504, 90342, 25307, 72039, 26812, 26715, 32264, 133800, 71161,\n 88956, 171987, 51779, 24425, 16671, 30251, 186294, 247761, 14202, 2121, 8465, 35024, 4876, 85917, 169730, 3638,\n 256836, 96184, 943, 18678, 6583, 52907, 35807, 112254, 214097, 18796, 11595, 9243, 23554, 887, 268203, 382004,\n 24590, 111335, 11625, 16619, 29039, 102425, 69006, 97976, 92362, 32552, 63717, 41433, 128974, 137630, 59943, 10019,\n 13986, 35430, 33665, 108037, 43799, 43280, 38195, 29078, 58629, 18265, 14425, 46832, 235538, 40830, 77881, 110717,\n 58937, 3463, 325358, 51300, 47623, 117252, 19007, 10170, 20540, 91237, 294813, 4951, 79841, 56232, 36270, 128547,\n 69209, 66275, 100156, 32063, 73531, 34439, 80937, 28892, 44466, 88595, 216307, 32583, 49620, 16605, 82127, 45807,\n 21630, 78726, 20235, 40163, 111007, 96926, 5567, 72083, 21665, 58844, 39419, 179767, 48328, 42662, 51550, 5251,\n 37811, 49608, 81056, 50854, 55513, 20922, 18891, 197409, 164656, 32593, 71449, 220474, 58919, 85682, 67854, 13758,\n 35066, 3565, 61905, 214793, 119572, 141419, 21504, 10302, 27354, 67003, 46131, 32668, 15165, 64871, 34450, 17821,\n 2757, 11452, 34189, 5160, 12257, 85523, 560, 53385, 65887, 119549, 135620, 312353, 115979, 122356, 10867, 193231,\n 124537, 54783, 90675, 120791, 4715, 142253, 50943, 17271, 43358, 25331, 4917, 120566, 34580, 12878, 33786, 160528,\n 32523, 4869, 301307, 104817, 81491, 23276, 8832, 97911, 31265, 52065, 7998, 49622, 9715, 43998, 34091, 84587,\n 20664, 69041, 29419, 53205, 10838, 58288, 116145, 6185, 5154, 141795, 35924, 21307, 144738, 43730, 12085, 8279,\n 10002, 119, 133779, 199668, 72938, 31768, 39176, 67875, 38453, 9700, 44144, 4121, 116048, 41733, 12868, 82669,\n 92308, 128, 34262, 11332, 7712, 90764, 36141, 13553, 71312, 77470, 117314, 96549, 49135, 23602, 54468, 28605,\n 6327, 62308, 17171, 67531, 21319, 14105, 894, 107722, 46157, 8503, 51069, 100472, 45138, 15246, 14577, 35609,\n 191464, 1757, 13364, 161349, 32067, 91705, 81144, 52339, 5408, 91066, 21983, 14157, 100545, 4372, 26630, 129112,\n 1423, 29676, 213626, 4397, 88436, 99190, 6877, 49958, 26122, 114348, 60661, 29818, 293118, 50042, 179738, 16400,\n 163423, 89627, 31040, 43973, 36638, 45952, 5153, 1894, 109322, 1898, 134021, 12402, 112077, 68309, 190269, 69866,\n 31938, 107383, 11522, 105232, 11248, 14868, 39852, 71707, 186525, 16530, 38162, 106212, 11700, 5130, 16608, 26998,\n 59586, 108399, 230033, 43683, 48135, 82179, 2073, 5015, 196684, 189293, 16378, 23452, 8301, 35640, 11632, 214551,\n 29240, 57644, 33137, 91949, 55157, 52384, 117313, 5090, 17717, 89668, 49363, 82238, 241035, 66216, 29066, 184088,\n 97206, 62820, 26595, 4241, 135635, 173672, 8202, 459, 71355, 146294, 29587, 3008, 135385, 141203, 14803, 6634,\n 45094, 69362, 50925, 546, 51884, 62011, 83296, 234584, 44515, 56050, 89476, 87751, 19373, 12691, 149923, 19794,\n 13833, 35846, 87557, 58339, 2884, 19145, 25647, 12224, 11024, 77338, 64608, 122297, 53025, 7205, 36189, 36294,\n 170779, 21750, 7739, 173883, 75192, 35664, 224240, 113121, 30181, 26267, 27036, 117827, 92015, 106516, 55628, 203549,\n 67949, 60462, 60844, 35911, 20457, 1820, 920, 19773, 8738, 73173, 181993, 38521, 98254, 76257, 46008, 92796,\n 5384, 26868, 151566, 22124, 2411, 15919, 186872, 180021, 28099, 152961, 78811, 80237, 62352, 102653, 74259, 184890,\n 16792, 123702, 224945, 29940, 19512, 75283, 14059, 112691, 92811, 233329, 20411, 138569, 53341, 109802, 50600, 134528,\n 66747, 5529, 166531, 31578, 64732, 67189, 1596, 126357, 967, 167999, 206598, 109752, 119431, 207825, 78791, 91938,\n 10301, 27311, 24233, 252343, 28831, 32812, 66002, 112267, 90895, 8786, 8095, 16824, 22866, 21813, 60507, 174833,\n 19549, 130985, 117051, 52110, 6938, 81923, 123864, 38061, 919, 18680, 53534, 46739, 112893, 161529, 85429, 26761,\n 11900, 81121, 91968, 15390, 217947, 56524, 1713, 6654, 37089, 85630, 138866, 61850, 16491, 75577, 16884, 98296,\n 73523, 6140, 44645, 6062, 36366, 29844, 57946, 37932, 42472, 5266, 20834, 19309, 33753, 127182, 134259, 35810,\n 41805, 45878, 312001, 14881, 47757, 49251, 120050, 44252, 3708, 25856, 107864, 120347, 1228, 36550, 41682, 34496,\n 47025, 8393, 173365, 246526, 12894, 161607, 35670, 90785, 126572, 2095, 124731, 157033, 58694, 554, 12786, 9642,\n 4817, 16136, 47864, 174698, 66992, 4639, 69284, 10625, 40710, 27763, 51738, 30404, 264105, 137904, 109882, 52487,\n 42824, 57514, 2740, 10479, 146799, 107390, 16586, 88038, 174951, 9410, 16185, 44158, 5568, 40658, 46108, 12763,\n 97385, 26175, 108859, 664, 230732, 67470, 46663, 14395, 50750, 141320, 93140, 15361, 47997, 55784, 6791, 307840,\n 118569, 107326, 18056, 58281, 260415, 54691, 8790, 73332, 45633, 7511, 45674, 143373, 14031, 11799, 94491, 35646,\n 96544, 14560, 26049, 32983, 25791, 83814, 42094, 231370, 63955, 139212, 2359, 169908, 3108, 183486, 105867, 28197,\n 32941, 124968, 26402, 88267, 149768, 23053, 3078, 19091, 52924, 25383, 19209, 111548, 97361, 3959, 24880, 235061,\n 9099, 24921, 161254, 151405, 20508, 7159, 34381, 20133, 11434, 74036, 19974, 34769, 36585, 1076, 22454, 17354,\n 38727, 235160, 111547, 96454, 117448, 156940, 91330, 37299, 7310, 26915, 117060, 51369, 22620, 61861, 322264, 106850,\n 111694, 15091, 2624, 40345, 300446, 177064, 1707, 27389, 54792, 327783, 132669, 183543, 59003, 17744, 20603, 151134,\n 106923, 53084, 71803, 279424, 319816, 11579, 21946, 16728, 38274, 72711, 5085, 83391, 88646, 40159, 25027, 34680,\n 10752, 12988, 54126, 30365, 18338, 100445, 230674, 44874, 84974, 143877, 123253, 139372, 28082, 91477, 144002, 13096,\n 219729, 46016, 50029, 42377, 14601, 6660, 58244, 58978, 23918, 88206, 113611, 64452, 17541, 41032, 10942, 12021,\n 49189, 10978, 40175, 37156, 10947, 71709, 106894, 112538, 57007, 137486, 150608, 152719, 40615, 7746, 279716, 13101,\n 19524, 28708, 40578, 72320, 1096, 182051, 94527, 51275, 22833, 45164, 81917, 77519, 48508, 5421, 140302, 37845,\n 149830, 5587, 27579, 5357, 428725, 248187, 6326, 206760, 39814, 32585, 89923, 44341, 288753, 284443, 96368, 31201,\n 94189, 119504, 20359, 52073, 103216, 179, 27934, 32801, 96035, 34111, 34309, 101326, 18198, 20704, 210266, 37643,\n 27880, 141873, 106000, 19414, 56614, 167714, 66483, 107885, 86602, 4379, 20796, 75467, 4987, 5017, 118857, 26003,\n 34308, 114428, 29198, 6686, 29697, 73632, 3739, 69795, 16798, 41504, 7207, 30722, 21436, 36735, 28067, 28545,\n 3239, 11221, 36031, 41889, 100010, 19247, 317673, 29495, 174554, 6424, 129725, 53845, 94986, 7955, 59676, 2604,\n 191497, 19735, 102214, 62954, 23844, 11872, 179525, 261436, 34492, 428, 78404, 142035, 16747, 17246, 27578, 37021,\n 33672, 57944, 26056, 135760, 2369, 61674, 122066, 31327, 19374, 157065, 40553, 130982, 69619, 71290, 38855, 72100,\n 92903, 95940, 51422, 165999, 65713, 57873, 50726, 7288, 20272, 2081, 42326, 22624, 81120, 57914, 79352, 19447,\n 1684, 72302, 11774, 302559, 161481, 96396, 13692, 414988, 3721, 79066, 56627, 46883, 21150, 11747, 12184, 5856,\n 113458, 176117, 84416, 52079, 27933, 3354, 59765, 141359, 2212, 216309, 2555, 23458, 196722, 142463, 45701, 44548,\n 28798, 19418, 215, 29916, 9396, 10574, 114226, 84475, 13520, 18694, 34056, 4524, 90302, 62930, 13539, 19407,\n 77209, 7728, 38088, 9535, 2263, 23875, 183945, 17750, 26274, 67172, 10585, 28042, 22199, 7478, 51331, 66030,\n 26774, 192929, 31434, 25850, 50197, 52926, 178158, 4679, 181256, 70184, 229600, 9959, 105594, 72158, 73974, 2726,\n 35085, 78087, 23284, 35568, 51713, 155676, 5401, 27254, 11966, 17569, 223253, 71993, 103357, 111477, 55722, 30504,\n 26034, 46774, 35392, 36285, 214814, 41143, 163465, 1051, 16094, 81044, 6636, 76489, 179102, 20712, 39178, 35683,\n 125177, 54219, 30617, 52994, 25324, 50123, 2543, 87529, 58995, 10688, 125199, 12388, 60158, 125481, 131646, 7642,\n 133350, 65874, 3438, 97277, 101450, 10075, 56344, 116821, 50778, 60547, 98016, 106135, 13859, 14255, 16300, 77373,\n 173521, 8285, 45932, 37426, 4054, 114295, 55947, 7703, 39114, 52, 51119, 128135, 19714, 60715, 9554, 50492,\n 88180, 2823, 118271, 52993, 122625, 97919, 23859, 37895, 25040, 33614, 32102, 20431, 3577, 9275, 15686, 43031,\n 157741, 110358, 1884, 40291, 125391, 13736, 5008, 64881, 87336, 77381, 70711, 43032, 49155, 118587, 70494, 4318,\n 10168, 30126, 12580, 10524, 280104, 104001, 145413, 2862, 84140, 6603, 106005, 13566, 12780, 11251, 42830, 571,\n 179910, 82443, 13146, 469, 42714, 32591, 265217, 424024, 92553, 54721, 134100, 6007, 15242, 114681, 59030, 16718,\n 85465, 200214, 85982, 55174, 165013, 23493, 56964, 82529, 109150, 32706, 27568, 82442, 5350, 14976, 13165, 44890,\n 60021, 21343, 33978, 17264, 4655, 22328, 27819, 75730, 16567, 55483, 14510, 17926, 45827, 150609, 3704, 7385,\n 272531, 161543, 76904, 122163, 52405, 2039, 19165, 41623, 14423, 228354, 3369, 176360, 85491, 7122, 35789, 303724,\n 4465, 13628, 2233, 55311, 118771, 20713, 10006, 221519, 45115, 71021, 35650, 29775, 7337, 10864, 20665, 21142,\n 1746, 15080, 1624, 32449, 10905, 105743, 229797, 7701, 3940, 22997, 178467, 57208, 389057, 39683, 59403, 63344,\n 63125, 54847, 69691, 18336, 56448, 3362, 37202, 18282, 29648, 138224, 35867, 10495, 5911, 28814, 26653, 31514,\n 176702, 26550, 45621, 11734, 4525, 40543, 73944, 121080, 27858, 155561, 14887, 44670, 30742, 8796, 107455, 113472,\n 56369, 75581, 183777, 240095, 133699, 153299, 8768, 160464, 26058, 49078, 103971, 21875, 71486, 44888, 17156, 9678,\n 89541, 123019, 102337, 3972, 83930, 21245, 87852, 109660, 287918, 183019, 686, 10100, 39177, 283941, 11274, 24736,\n 26793, 26214, 25995, 77011, 141580, 4070, 23742, 46285, 46632, 30700, 26669, 19056, 35951, 115575, 174034, 56097,\n 35463, 87425, 24575, 44245, 38701, 82317, 85922, 281616, 100333, 147697, 61503, 7730, 84330, 8530, 59917, 61597,\n 17173, 9092, 32658, 90288, 193136, 39023, 20381, 56654, 31132, 7779, 1919, 1375, 117128, 30819, 11169, 40938,\n 23935, 115201, 101155, 151034, 4835, 11231, 74550, 89388, 59951, 91704, 107312, 167882, 115062, 12732, 72738, 88703,\n 464019, 158267, 57995, 60496, 737, 14371, 123867, 4174, 243339, 159946, 7568, 16025, 134556, 110916, 38103, 191,\n 80226, 88794, 29688, 27230, 10454, 76308, 57647, 77409, 113483, 66864, 14745, 19808, 12023, 46583, 84805, 16015,\n 17102, 2231, 20611, 3547, 95740, 250131, 34559, 108894, 8498, 15853, 159169, 148920, 20942, 2813, 93160, 45188,\n 210613, 45531, 52587, 149062, 39782, 28194, 57849, 60965, 84954, 89766, 84453, 100927, 16501, 27658, 165311, 103841,\n 54192, 207341, 19558, 20084, 319622, 5672, 205467, 98462, 61849, 36279, 13609, 147177, 24726, 165015, 209489, 59591,\n 31157, 6551, 117580, 75060, 141146, 277310, 21072, 22023, 106474, 63041, 137443, 122965, 68371, 5383, 42146, 98961,\n 113467, 30863, 23794, 4843, 99630, 30392, 82679, 13699, 241612, 33601, 93146, 24319, 18643, 32155, 95669, 40440,\n 15333, 34089, 67799, 142144, 58245, 38633, 114531, 117400, 77861, 188726, 5507, 2568, 8853, 10987, 107222, 2663,\n 2421, 11530, 13345, 30075, 41785, 118661, 104786, 17459, 12490, 16281, 71936, 193555, 17431, 5944, 71758, 26485,\n 77317, 20803, 367167, 158, 7362, 93430, 11735, 172445, 46002, 11532, 54482, 930, 62911, 2235, 23004, 179236,\n 4764, 101859, 208113, 22477, 55163, 95579, 14098, 67320, 162556, 90709, 156949, 3826, 57492, 4025, 34092, 87442,\n 104565, 6718, 186015, 28214, 14209, 10039, 107186, 233912, 58877, 81637, 55265, 39828, 6194, 145813, 50831, 105849,\n 4974, 88319, 122296, 10272, 197216, 95714, 51540, 72418, 23324, 91555, 8743, 140452, 250249, 51666, 34124, 7229,\n 38592, 129641, 78169, 174242, 22464, 149964, 51450, 14034, 10026, 95376, 26190, 120062, 14401, 8700, 265, 31386,\n 143573, 7203, 229889, 61567, 4227, 140981, 2466, 72052, 10787, 10062, 30958, 6099, 38471, 30103, 23202, 208101,\n 70847, 467, 58934, 32271, 32984, 36637, 24107, 30771, 17109, 73353, 13650, 2098, 157040, 67366, 66904, 106018,\n 265380, 107238, 18535, 44025, 32681, 144983, 62505, 91295, 56120, 3082, 77508, 10322, 63023, 36700, 81885, 224127,\n 16721, 45023, 239261, 111272, 13852, 7866, 149243, 204199, 32309, 22084, 42029, 38316, 126644, 104973, 14406, 43454,\n 67322, 61310, 15789, 40285, 24026, 181047, 6301, 70927, 23319, 115823, 27248, 66693, 115875, 278566, 63007, 146844,\n 56841, 59007, 87368, 180001, 22370, 42114, 80605, 12022, 10374, 308, 25079, 14689, 12618, 63368, 7936, 264973,\n 212291, 136713, 95999, 105801, 18965, 32075, 48700, 52230, 35119, 96912, 32992, 8586, 16606, 101333, 101812, 14969,\n 39930, 759, 193090, 27387, 42914, 12937, 5058, 62646, 64528, 38624, 25743, 37502, 3716, 4435, 30352, 178687,\n 26461, 132611, 42002, 138442, 35833, 59582, 16345, 8048, 60319, 49349, 309, 47800, 49739, 90482, 26405, 34470,\n 63786, 32479, 85028, 39866, 47846, 11649, 23934, 29466, 2816, 42864, 31828, 7410, 74885, 49632, 47629, 111801,\n 90749, 19536, 18767, 105764, 59606, 21223, 10746, 76298, 22220, 39408, 7190, 79654, 64856, 11602, 82156, 272765,\n 17079, 70089, 245473, 51813, 184407, 384678, 1576, 122249, 5064, 27481, 6188, 25790, 74361, 27541, 318284, 45430,\n 31488, 620, 93579, 45723, 192118, 22670, 51913, 4162, 70244, 35966, 26397, 16199, 50899, 209613, 121702, 287507,\n 2993, 36101, 132229, 67345, 33062, 76295, 118628, 78705, 52316, 34375, 107083, 107454, 44863, 127561, 33964, 3073,\n 154010, 190914, 55967, 39074, 6272, 31047, 5550, 41123, 26154, 98638, 47110, 19998, 148091, 50229, 31329, 59900,\n 195442, 19106, 61347, 73497, 70015, 682, 45850, 25776, 38022, 148951, 6288, 37411, 232526, 109277, 27286, 32342,\n 9262, 5220, 16651, 23175, 46740, 129438, 78614, 121925, 66914, 88710, 127952, 5563, 21500, 34521, 10739, 14863,\n 191006, 62956, 17359, 16749, 67027, 56284, 69134, 43301, 35039, 58883, 54466, 60823, 404451, 75743, 59856, 86979,\n 7923, 34273, 83785, 32142, 7693, 268986, 197428, 282681, 17049, 22346, 22990, 92245, 107180, 3357, 37104, 96724,\n 49153, 7683, 31197, 43267, 82231, 164276, 23696, 20848, 188364, 22309, 24821, 158707, 1018, 22514, 70922, 27792,\n 45589, 59709, 10765, 736, 35218, 63479, 51987, 24275, 63588, 55361, 92929, 81964, 4658, 20122, 12330, 44058,\n 13065, 311456, 72224, 8337, 211229, 38979, 22590, 138478, 52757, 32595, 133600, 8838, 31549, 94412, 43391, 90056,\n 1585, 94802, 127271, 6223, 31889, 137038, 132910, 2165, 57616, 230152, 6080, 10748, 36737, 74579, 134062, 50525,\n 180532, 119270, 34556, 76155, 82394, 52595, 29258, 31435, 87820, 67996, 26943, 183878, 38007, 2410, 13526, 180297,\n 69856, 3503, 187396, 167700, 7838, 16701, 9199, 56267, 3661, 37407, 65994, 23767, 5708, 62508, 221700, 67088,\n 86978, 46776, 84434, 32088, 5612, 9149, 88244, 21685, 95151, 46750, 189612, 2979, 506311, 2594, 3628, 40074,\n 105039, 78243, 28523, 6651, 38058, 71999, 30992, 12764, 68261, 108991, 6165, 26450, 61961, 13400, 22426, 7490,\n 60890, 109623, 2070, 12958, 50355, 67979, 257096, 7213, 42578, 52121, 35716, 65461, 7516, 124758, 39268, 302,\n 64712, 14977, 1467, 219452, 2840, 34229, 11121, 21602, 19270, 63574, 8024, 1532, 17331, 79839, 78885, 52029,\n 180767, 57957, 6069, 91265, 61380, 55767, 8927, 32881, 287603, 22149, 35029, 68876, 6428, 199567, 46926, 13412,\n 104132, 21434, 366616, 45060, 110046, 81924, 128910, 45886, 52821, 130416, 29416, 77342, 21762, 67329, 121432, 79924,\n 11724, 38625, 81006, 102033, 28338, 13326, 3250, 82056, 82526, 38212, 21112, 12382, 111495, 3263, 7414, 86274,\n 93490, 40844, 30224, 45212, 24019, 48411, 71367, 24941, 76729, 57776, 3769, 38114, 202019, 197745, 31953, 237533,\n 33270, 201580, 255648, 100798, 44741, 32241, 98468, 106931, 10085, 15090, 170358, 33154, 66787, 18819, 69760, 25061,\n 234005, 82660, 6295, 131975, 16874, 9076, 4094, 25005, 17740, 40908, 19533, 220019, 44330, 99792, 50040, 19619,\n 13950, 55228, 24423, 31253, 95308, 103177, 184795, 28590, 82285, 5059, 3210, 75525, 49894, 70007, 56178, 10580,\n 36051, 139681, 21617, 98736, 3555, 106306, 164189, 37352, 63915, 47824, 24883, 145530, 61904, 28444, 11483, 19837,\n 145446, 30420, 112972, 85939, 11835, 191233, 2262, 20705, 58630, 1753, 148334, 1197, 144714, 6887, 11223, 107667,\n 60879, 77914, 4151, 57417, 81594, 96681, 169430, 1784, 20444, 95138, 254041, 27038, 596, 7117, 72808, 13759,\n 3353, 126776, 21074, 55322, 27081, 36942, 39547, 139830, 179275, 4453, 713, 8722, 71399, 19204, 25785, 22794,\n 23923, 104114, 11291, 25458, 102309, 88396, 75288, 230440, 206396, 104551, 58447, 130857, 37247, 94734, 31548, 176529,\n 226077, 65159, 20104, 10096, 66881, 94191, 237909, 27109, 37404, 1520, 27421, 25220, 113003, 23423, 24884, 50585,\n 6286, 231877, 150800, 11789, 3226, 90004, 60642, 5053, 202400, 61442, 132531, 175329, 57138, 30116, 103847, 9973,\n 75367, 16452, 32360, 59119, 21246, 10191, 164804, 23305, 61051, 37348, 154530, 13214, 5468, 50403, 66754, 130976,\n 50559, 80515, 14436, 155492, 84017, 5472, 43107, 41240, 2890, 90431, 70188, 382, 76234, 48040, 50211, 281038,\n 237007, 32115, 142178, 1536, 22761, 96429, 1811, 31243, 1679, 49143, 55209, 17402, 235054, 61494, 7462, 77030,\n 34925, 87609, 78002, 9499, 9027, 73289, 201078, 101379, 63544, 27666, 5469, 10642, 30029, 49816, 132979, 95620,\n 58086, 351930, 116300, 2110, 2043, 30845, 6154, 11279, 16727, 4122, 2277, 27281, 4971, 3650, 39060, 61970,\n 65951, 39674, 75686, 38151, 11370, 130809, 177895, 32665, 63725, 122267, 7857, 39618, 118483, 44792, 157755, 178624,\n 136994, 24260, 41308, 22471, 12404, 21707, 12486, 30473, 52781, 50246, 20247, 39065, 909, 56825, 103158, 128603,\n 31542, 1089, 41935, 32744, 12428, 37963, 84420, 33134, 72921, 208449, 42622, 168151, 127335, 147107, 46699, 38216,\n 12591, 94342, 85814, 31423, 24944, 2605, 87542, 67473, 192551, 4496, 56321, 91819, 17630, 6300, 256183, 114569,\n 202090, 33209, 35289, 34897, 24967, 40520, 43470, 5344, 10199, 34810, 14283, 10381, 10017, 62923, 49924, 23233,\n 64539, 13051, 35686, 19698, 11570, 135555, 120868, 44924, 87065, 52318, 52335, 47586, 140906, 245885, 109834, 78668,\n 9065, 46990, 25258, 72022, 61243, 40838, 4545, 146387, 10537, 11557, 17470, 36930, 68104, 46711, 24264, 79401,\n 81043, 18225, 120488, 24746, 84338, 81652, 28266, 13776, 21878, 46973, 1047, 230465, 73357, 95777, 24973, 210160,\n 62210, 58404, 110633, 169651, 6937, 41870, 9909, 26822, 191062, 76553, 27519, 96256, 239070, 2478, 205678, 67955,\n 58532, 20601, 50120, 19148, 78501, 195724, 110740, 8249, 109665, 27446, 30568, 57631, 31425, 49752, 32820, 65504,\n 50079, 3663, 102256, 219898, 23849, 211315, 14645, 4359, 91767, 9528, 12449, 49366, 7941, 49763, 107848, 8930,\n 27086, 50686, 9744, 10447, 81935, 39513, 46514, 1670, 29229, 6172, 22312, 137280, 97759, 9806, 14445, 22976,\n 56458, 73391, 34983, 93760, 174219, 52573, 33149, 59747, 2429, 136277, 75123, 165263, 91040, 7446, 57632, 48633,\n 97140, 246081, 84766, 151684, 79918, 93268, 120346, 54059, 54875, 77858, 32996, 103590, 45276, 11968, 19600, 25849,\n 17159, 132907, 42828, 16817, 4913, 99462, 103303, 27395, 5737, 74184, 20749, 21160, 14377, 77062, 131403, 158735,\n 10999, 27799, 77785, 9320, 34366, 51593, 61070, 33746, 47048, 29268, 36675, 30262, 53297, 9832, 82000, 20188,\n 122292, 39917, 7331, 18160, 68301, 185935, 134830, 15031, 4935, 10004, 165845, 185534, 46923, 30109, 44134, 122631,\n 18874, 22903, 112790, 26561, 18549, 348902, 82871, 140345, 255565, 135390, 63556, 103747, 145055, 179600, 145662, 296111,\n 61661, 211987, 23952, 52342, 126343, 48450, 32919, 44277, 82185, 9591, 62139, 205363, 376969, 394874, 108461, 18040,\n 120885, 14798, 39863, 16571, 16794, 58271, 81025, 55206, 14640, 118656, 6361, 44092, 85970, 6262, 153863, 108244,\n 180200, 72264, 79947, 38044, 10050, 5735, 61221, 80712, 5471, 115689, 11391, 11661, 184257, 20010, 60116, 30320,\n 19327, 134598, 45455, 27542, 18004, 125092, 452272, 1549, 91523, 46567, 180063, 156026, 2608, 11174, 58848, 37788,\n 65907, 80194, 30490, 5786, 40775, 119519, 106241, 11323, 156297, 8425, 61495, 2617, 29675, 2425, 59886, 112582,\n 49142, 59618, 4863, 50597, 86710, 50650, 168632, 27693, 85641, 83643, 18993, 25768, 84284, 28090, 93592, 36627,\n 312804, 43381, 9887, 9402, 100931, 97165, 3311, 173330, 66805, 28935, 4963, 184460, 3201, 78102, 19126, 21607,\n 37496, 24938, 22615, 16153, 32862, 134792, 153318, 61120, 6067, 2812, 12826, 12792, 23825, 37559, 64662, 202250,\n 102694, 155488, 85881, 149193, 46233, 65383, 15521, 106982, 11358, 176786, 25752, 39717, 34208, 24510, 32464, 77742,\n 39371, 72028, 138229, 60688, 71386, 102834, 132477, 2208, 11548, 63670, 271279, 28351, 30338, 38620, 32491, 99845,\n 143885, 152266, 13252, 2825, 178663, 108097, 1775, 78201, 14897, 113573, 163346, 62292, 171129, 22183, 96598, 38733,\n 64971, 166776, 117445, 9968, 146393, 44677, 74867, 20908, 97328, 12761, 25656, 26785, 9148, 112344, 26115, 99176,\n 110121, 22437, 49547, 6180, 79320, 5835, 31392, 43328, 33377, 75870, 119860, 69497, 80273, 7325, 155219, 43167,\n 111173, 28347, 20222, 3763, 71752, 55041, 47252, 14618, 28088, 15012, 97805, 194698, 54636, 2036, 41349, 6173,\n 96604, 61530, 51859, 43782, 13361, 24334, 22668, 24792, 7070, 23441, 16789, 3209, 36211, 208475, 26242, 32880,\n 122181, 182407, 21444, 31060, 88459, 29929, 77907, 12716, 10934, 97005, 20599, 31690, 8403, 58445, 30303, 22700,\n 10336, 86731, 103115, 337709, 72556, 46788, 112566, 47684, 67089, 53548, 36874, 56487, 41387, 125985, 26893, 40071,\n 106683, 73712, 18787, 40105, 72992, 67246, 137276, 50802, 36790, 70328, 138827, 22466, 39263, 183295, 29858, 50975,\n 9322, 57397, 10654, 24364, 30383, 55799, 41600, 23584, 127295, 296610, 129078, 143558, 244131, 86397, 36049, 1085,\n 80677, 3820, 108139, 5476, 34767, 24683, 7758, 13060, 7239, 131671, 250593, 59556, 103392, 29810, 4188, 252323,\n 39404, 116877, 7651, 43600, 40338, 13554, 157253, 39196, 25978, 144387, 61211, 234, 50104, 6129, 10449, 93777,\n 9240, 356378, 274148, 4439, 72970, 3724, 147770, 78680, 62570, 115877, 40027, 40547, 36817, 224392, 64609, 34795,\n 165027, 67440, 2477, 37206, 23431, 50754, 164797, 46018, 94995, 170982, 27051, 7957, 22767, 3674, 27900, 56419,\n 18930, 60701, 41302, 2692, 84749, 339721, 61996, 111094, 80221, 50129, 1045, 8153, 62945, 19202, 8250, 37208,\n 37418, 32560, 79477, 41106, 88569, 33963, 36693, 5892, 30570, 1581, 66471, 49647, 11922, 160717, 29442, 5643,\n 114865, 82962, 95982, 132098, 22633, 22838, 94726, 54556, 28566, 205039, 162340, 33216, 16849, 35847, 221339, 94851,\n 26533, 71469, 1805, 3804, 12935, 45483, 71020, 36310, 65381, 192960, 34240, 35165, 59773, 1248, 46954, 155332,\n 96864, 4246, 388800, 16129, 57133, 74592, 44807, 442014, 38203, 42574, 80818, 91592, 26377, 36424, 65760, 977,\n 77387, 22628, 147610, 28018, 30561, 98454, 6969, 119628, 63648, 18170, 36854, 26601, 64018, 22027, 37279, 51395,\n 152934, 21153, 9430, 58760, 194742, 5330, 55115, 34158, 28917, 174111, 13171, 122326, 1526, 43896, 66094, 25325,\n 4234, 148354, 11450, 275, 18999, 112191, 44365, 22723, 68409, 8733, 57746, 96565, 75007, 14196, 108844, 29475,\n 88599, 177563, 100792, 106156, 86323, 93726, 14248, 135341, 194131, 40126, 47099, 14779, 8272, 39597, 95983, 171398,\n 65882, 28052, 10393, 47213, 40689, 22120, 72212, 106829, 34964, 109146, 753, 648, 21660, 30047, 17527, 181025,\n 5619, 145357, 4085, 216883, 9359, 186951, 24779, 53931, 24545, 36197, 223296, 62628, 168101, 4243, 107313, 30321,\n 26642, 13049, 51059, 31027, 107912, 807, 73550, 26551, 84369, 122422, 165872, 49754, 74213, 234264, 33151, 52014,\n 33100, 87183, 22365, 52500, 40013, 23302, 5652, 72723, 21404, 26107, 48434, 587, 94049, 168493, 96418, 32871,\n 70860, 31709, 25128, 443, 71597, 166253, 15670, 70994, 26341, 133675, 28280, 75491, 54756, 47955, 56028, 26182,\n 11952, 113272, 472197, 64640, 110753, 17919, 337, 50642, 22576, 142, 87371, 53391, 93210, 126694, 15285, 19642,\n 85667, 14148, 1506, 42092, 52962, 33243, 11970, 20734, 135843, 57044, 58880, 13002, 219134, 22876, 64754, 232519,\n 4257, 43120, 321573, 24799, 64526, 124728, 52579, 81472, 70831, 276848, 17403, 74359, 23021, 182101, 74597, 23744,\n 148267, 12055, 7976, 5349, 11772, 67540, 167347, 65318, 18720, 127832, 108238, 22828, 90233, 9987, 259080, 118185,\n 73209, 79270, 13775, 90100, 137742, 90799, 70569, 15699, 19961, 9087, 67475, 57872, 39731, 8810, 134897, 131868,\n 146849, 19898, 3334, 2281, 167061, 91073, 60356, 467742, 74712, 188, 53179, 137679, 92769, 29241, 9537, 132595,\n 80119, 1041, 88962, 5976, 40171, 44911, 102859, 139059, 104558, 98987, 47761, 19272, 71472, 113864, 175377, 73338,\n 10857, 23402, 23758, 1591, 139864, 5644, 4076, 118760, 16427, 134198, 18853, 20291, 100849, 37423, 22038, 36677,\n 19071, 195521, 57445, 11069, 31869, 55718, 66882, 148490, 44, 41296, 75242, 49704, 166810, 9906, 20943, 122258,\n 49112, 105667, 15969, 10344, 6408, 187694, 21399, 72742, 58970, 14867, 14376, 81889, 41856, 23225, 15042, 56993,\n 16074, 131389, 74276, 72407, 53875, 383108, 53597, 37363, 68993, 44854, 122548, 430927, 198279, 38430, 80409, 12245,\n 2981, 628, 2818, 17760, 37437, 238229, 7968, 46892, 2200, 3730, 34190, 65983, 37959, 112291, 87850, 70827,\n 6522, 20750, 73913, 111621, 41652, 19587, 2780, 58668, 25916, 85259, 18200, 168962, 95781, 42445, 102050, 7776,\n 57662, 103313, 47742, 96358, 41964, 66174, 100396, 29069, 204735, 19679, 27978, 7479, 40264, 22534, 61183, 36081,\n 107436, 58223, 14680, 23002, 101311, 24716, 124108, 12908, 5646, 31750, 40380, 14215, 232799, 102772, 14122, 96775,\n 61398, 50917, 12096, 149880, 67833, 598749, 124194, 155871, 49216, 790, 14677, 65319, 56917, 7440, 145744, 95701,\n 12206, 49405, 129269, 76199, 45732, 9767, 11058, 9047, 210885, 11051, 7392, 26307, 2130, 8132, 147526, 20802,\n 232698, 115660, 50060, 59789, 57344, 107623, 80343, 112676, 23291, 9866, 160971, 34032, 118291, 15719, 59730, 164911,\n 28975, 2659, 58046, 78480, 21854, 66209, 53863, 109085, 116045, 29021, 46481, 107552, 22130, 18764, 70254, 31272,\n 11300, 52460, 43933, 84738, 20721, 53869, 190840, 79673, 105300, 7561, 321817, 66924, 13940, 33281, 101046, 183181,\n 32176, 71878, 5678, 62924, 79535, 56646, 40303, 19559, 27703, 93042, 73368, 42187, 3670, 37376, 46440, 7023,\n 36816, 109628, 20680, 5940, 276440, 275233, 170848, 112093, 136996, 14984, 20226, 111441, 77693, 112960, 48577, 39370,\n 55707, 50314, 123404, 26570, 54281, 61372, 123391, 4857, 35928, 246740, 132507, 106646, 44241, 7196, 92258, 9825,\n 37688, 51197, 303141, 5590, 15476, 132986, 10955, 85782, 34486, 26696, 7991, 28813, 18858, 39546, 11703, 11365,\n 38185, 5716, 93555, 11925, 40121, 60002, 6985, 10976, 171384, 3887, 43394, 13337, 56346, 6381, 252336, 39573,\n 75042, 53711, 1028, 31781, 44295, 95925, 131713, 7214, 68125, 43571, 70954, 213234, 1628, 8760, 13391, 65485,\n 17320, 56038, 1710, 25248, 60803, 57399, 19839, 3870, 326, 281556, 50945, 72400, 21460, 316244, 75619, 56246,\n 98775, 481, 13513, 55765, 50427, 7388, 123519, 32929, 57908, 27124, 61316, 101097, 57467, 30228, 48792, 10788,\n 20402, 37318, 50526, 155730, 34456, 158065, 145305, 17832, 43733, 64052, 4506, 35072, 205355, 177028, 184004, 187081,\n 68616, 35938, 83703, 10367, 36892, 93186, 260137, 51934, 89970, 4985, 23445, 26755, 21558, 7948, 78741, 23376,\n 124405, 85594, 68596, 57536, 49351, 12619, 56593, 132668, 99924, 109728, 71844, 71935, 196018, 65464, 17617, 14987,\n 89701, 143773, 33997, 8687, 22701, 33258, 2914, 4436, 72108, 85610, 9671, 49067, 2327, 82988, 1361, 1672,\n 44033, 35777, 30269, 24057, 10605, 82236, 616, 15793, 13919, 47249, 112086, 116698, 9484, 80207, 90574, 33304,\n 68624, 93127, 56101, 42210, 160929, 4827, 38995, 38095, 4701, 125119, 5027, 33680, 9236, 231236, 14135, 87837,\n 23318, 70261, 78893, 30151, 81482, 14332, 1084, 74256, 27532, 46644, 79185, 3148, 62615, 6981, 55672, 31668,\n 36825, 1849, 14536, 37446, 14738, 23779, 43058, 162749, 72199, 1168, 21346, 5592, 85932, 85302, 9668, 18351,\n 57135, 150360, 2080, 228015, 77953, 34670, 119302, 151751, 31009, 106725, 84265, 45214, 59289, 74178, 113071, 263206,\n 111009, 4021, 44449, 188119, 192629, 123592, 392506, 292847, 114487, 12831, 205858, 9852, 20780, 79648, 75767, 357014,\n 97721, 18166, 21005, 67950, 33226, 204009, 16536, 2987, 11335, 66717, 144910, 47950, 17262, 55060, 15063, 2934,\n 51038, 26775, 178497, 66008, 3427, 49433, 128592, 20036, 157553, 63861, 3089, 23015, 51210, 28696, 35933, 49942,\n 71135, 231518, 99620, 17248, 21835, 176536, 20676, 16944, 38700, 165831, 233253, 295625, 36723, 13023, 52745, 10907,\n 19423, 67972, 125868, 95473, 82875, 1183, 108455, 52685, 33417, 64095, 21433, 52438, 33191, 127809, 44505, 211823,\n 7810, 2752, 95548, 162031, 7185, 91196, 47563, 61721, 33359, 17897, 23682, 42806, 178101, 22874, 49707, 199897,\n 75419, 82456, 8618, 11171, 79712, 116847, 18783, 44190, 46564, 5346, 59046, 95032, 7893, 14916, 3214, 26800,\n 24172, 121453, 34362, 10250, 17408, 18888, 4840, 68696, 22831, 13162, 36005, 32512, 14800, 62357, 41723, 45046,\n 27247, 37486, 5372, 2564, 34261, 298500, 66509, 133920, 89138, 31305, 117697, 19097, 108304, 81386, 84106, 23802,\n 46411, 63304, 946, 51417, 41777, 41041, 19501, 115864, 60743, 294354, 37955, 94165, 18116, 1156, 17937, 20645,\n 57114, 90804, 58042, 48643, 92288, 9861, 2557, 88546, 61333, 101008, 12853, 5148, 87856, 4152, 144503, 73841,\n 18718, 9789, 147565, 10846, 42085, 12789, 30223, 8993, 56352, 67203, 2448, 28215, 6052, 23540, 126319, 75933,\n 36689, 80235, 23231, 23561, 21383, 38800, 77548, 102798, 21234, 31468, 158608, 46188, 63960, 191679, 8051, 67014,\n 11185, 170078, 42186, 28827, 34777, 41930, 212079, 12421, 34750, 24111, 110344, 73918, 45171, 70826, 141949, 40063,\n 23979, 24254, 37309, 26724, 27179, 24718, 83648, 54938, 14591, 17425, 29525, 102675, 48975, 48654, 12316, 8929,\n 60640, 41709, 50168, 63264, 89812, 50716, 48632, 38755, 138583, 160123, 55579, 71829, 24230, 233277, 46322, 39650,\n 166388, 34718, 24108, 98252, 7031, 106695, 62498, 18258, 35062, 217827, 78731, 34824, 33354, 19520, 60852, 2432,\n 60224, 8587, 2836, 62955, 702, 20227, 42285, 40560, 95592, 62486, 11094, 53035, 143291, 18842, 46177, 77994,\n 1770, 9657, 107422, 172915, 32655, 128716, 25886, 25164, 156740, 119928, 165875, 85817, 11007, 89110, 33956, 12652,\n 65156, 180266, 8494, 36889, 19958, 20955, 96, 1264, 118288, 135769, 44754, 86671, 5632, 19026, 168220, 289120,\n 33569, 93821, 66144, 70635, 7687, 5642, 2714, 55445, 56636, 71545, 184182, 93133, 7332, 37389, 12643, 52315,\n 22729, 11014, 158742, 17050, 152889, 50178, 34601, 41945, 52136, 9948, 26914, 63548, 95721, 115951, 40759, 8960,\n 158258, 38938, 49232, 48325, 42234, 81523, 253019, 66128, 40978, 20048, 238048, 38760, 62928, 122560, 118532, 43687,\n 137472, 163689, 26680, 9878, 17448, 51035, 16211, 60834, 36749, 29178, 14241, 59868, 150086, 2305, 26477, 42422,\n 34342, 165341, 83279, 33894, 14257, 29928, 12743, 13957, 125571, 89134, 66712, 10952, 16507, 147839, 30146, 7249,\n 16565, 45399, 39874, 114565, 215780, 31990, 230881, 171477, 102, 196546, 44538, 10880, 84948, 281705, 86651, 10617,\n 31395, 2342, 453658, 43569, 60561, 132901, 21845, 17727, 58556, 258242, 22262, 58728, 4008, 77997, 11806, 37431,\n 30599, 81375, 109137, 185787, 114085, 217292, 97453, 169085, 30593, 60212, 11544, 102056, 65580, 2384, 91655, 4855,\n 95725, 7295, 157994, 16228, 20669, 53276, 141590, 105246, 17334, 25440, 76067, 17967, 39321, 38911, 11362, 28559,\n 63807, 21627, 26468, 85816, 40120, 1025, 15234, 58319, 69516, 66512, 124548, 75845, 78873, 22137, 46681, 51242,\n 85683, 32909, 76747, 35555, 43396, 101465, 1765, 73094, 1077, 2962, 39028, 66777, 57831, 42048, 15828, 13962,\n 36041, 63657, 52412, 5242, 58846, 2141, 5506, 219012, 134451, 3936, 182230, 17558, 17153, 152237, 22621, 49377,\n 170216, 35257, 68233, 65374, 6510, 11126, 212151, 7184, 2480, 22517, 3437, 33073, 30156, 16557, 3768, 55067,\n 86829, 91000, 12350, 148650, 66017, 79424, 70885, 49066, 28250, 21369, 51213, 34533, 11510, 3258, 18176, 18465,\n 84413, 6315, 36411, 163765, 4346, 356, 107618, 598, 13727, 285026, 162695, 8749, 14583, 7132, 63521, 184253,\n 32378, 25991, 5604, 30961, 53675, 4874, 84693, 5086, 34811, 26978, 56564, 7904, 33519, 51221, 113942, 69253,\n 6664, 125563, 22055, 220680, 102008, 742, 51930, 19494, 176108, 44424, 35123, 13025, 75685, 11759, 74335, 22250,\n 181453, 131147, 16984, 132115, 154311, 11991, 76452, 52609, 85351, 196, 30969, 9198, 74919, 2529, 56838, 71779,\n 29187, 116304, 3504, 62330, 41190, 86153, 28393, 254926, 104228, 105189, 13264, 84359, 3574, 12415, 8534, 57147,\n 10175, 188174, 59504, 60932, 66318, 16407, 107921, 17638, 99103, 49278, 28403, 39786, 145865, 8462, 3558, 43406,\n 142271, 29139, 21989, 36552, 93955, 72365, 7176, 13556, 106185, 37957, 321774, 17782, 129017, 51154, 27938, 24952,\n 1935, 39366, 2791, 33489, 41582, 56078, 24558, 9311, 5449, 218786, 27808, 190429, 68013, 36020, 86003, 29735,\n 3404, 87348, 119357, 115714, 2324, 86796, 81973, 40992, 43376, 93621, 28784, 16808, 36367, 2517, 2909, 191926,\n 24978, 55303, 53308, 205724, 60068, 3098, 21375, 64784, 23949, 26579, 63121, 12319, 80145, 39967, 97861, 6757,\n 70143, 67642, 37082, 34698, 69140, 122883, 46151, 62187, 80934, 429, 19437, 135071, 137885, 222647, 13331, 154065,\n 327, 61778, 74257, 40116, 37493, 14855, 85079, 237641, 42342, 102164, 199965, 71204, 4662, 29368, 5042, 113914,\n 122214, 8955, 13149, 102503, 43173, 5659, 163787, 69003, 307084, 63392, 171080, 21390, 81918, 86666, 36622, 24126,\n 28887, 5736, 28054, 207170, 163428, 79891, 346467, 95363, 38980, 111806, 80828, 9200, 19288, 294896, 114468, 87405,\n 111715, 141705, 7015, 72754, 68463, 48738, 243147, 33397, 101210, 37051, 98801, 82847, 20397, 4940, 185559, 18716,\n 54718, 83491, 11725, 40803, 1128, 12128, 23060, 5174, 7745, 67007, 46701, 1571, 27807, 180186, 256996, 18975,\n 16837, 7877, 212758, 250379, 15440, 87954, 57755, 24719, 124057, 83461, 258, 50864, 8874, 29038, 71289, 31627,\n 15429, 9005, 4061, 113851, 107716, 82819, 13651, 79656, 117851, 17539, 111446, 12938, 39724, 190787, 4352, 15402,\n 21070, 62708, 8539, 23777, 73853, 13552, 38810, 86117, 16285, 56400, 1718, 75342, 142863, 29033, 378, 110113,\n 180321, 32586, 23606, 26393, 160984, 207987, 23783, 8406, 16904, 24596, 47274, 11693, 46539, 60524, 78595, 48423,\n 31718, 20170, 9009, 146268, 15183, 191060, 172765, 1349, 138436, 37365, 10970, 40509, 225817, 20021, 70394, 152138,\n 21541, 66559, 66544, 89352, 2725, 17258, 91345, 7313, 3815, 115868, 8660, 40362, 4071, 103524, 39388, 118275,\n 21950, 6549, 38226, 32754, 209574, 29201, 43495, 18028, 20296, 40597, 18370, 47520, 202450, 24134, 2219, 8195,\n 69545, 38041, 136934, 46374, 19041, 159811, 84865, 58620, 846, 98749, 13569, 30714, 97246, 32186, 4479, 27355,\n 92973, 35214, 151491, 75963, 37631, 1561, 27200, 238083, 23182, 60756, 12291, 25766, 39355, 102333, 87362, 65741,\n 59906, 19538, 201575, 48772, 102938, 24438, 292580, 39964, 66366, 9004, 61379, 50548, 37622, 38732, 28379, 68180,\n 76622, 17488, 69849, 5963, 7219, 48143, 43413, 55358, 540, 58691, 29506, 19245, 52193, 48621, 5518, 13048,\n 118625, 44755, 191081, 42061, 89197, 2259, 60665, 66994, 71210, 51232, 3585, 142096, 55024, 7892, 8345, 58653,\n 463307, 65658, 64319, 137941, 136323, 53499, 12746, 43492, 6978, 95163, 29925, 60175, 5128, 7352, 41463, 184756,\n 121146, 20473, 18426, 4598, 5309, 54580, 14277, 121151, 10691, 56711, 43880, 63409, 76682, 11830, 172218, 264898,\n 32632, 66536, 81062, 31649, 25788, 92774, 60222, 11100, 63159, 9432, 224657, 25240, 53613, 152, 138620, 163829,\n 2397, 85345, 12501, 37507, 64932, 38575, 43522, 65789, 80198, 78796, 35226, 3851, 108891, 73311, 3060, 28391,\n 93671, 39663, 46142, 30982, 66041, 37281, 68157, 26553, 71872, 81142, 211527, 39747, 118119, 22695, 2859, 11066,\n 20232, 168911, 7933, 197005, 17066, 111071, 44434, 133994, 120798, 12766, 227798, 45756, 132852, 29917, 36076, 55352,\n 65281, 129800, 41958, 18944, 84678, 18580, 168093, 132621, 39997, 54092, 27740, 32354, 3770, 114118, 103242, 43918,\n 15899, 18574, 145944, 3190, 123469, 219903, 24169, 100571, 62403, 16776, 92779, 14535, 17168, 16475, 14304, 37231,\n 1712, 28218, 242754, 61688, 28980, 1318, 51359, 222657, 99200, 67989, 31772, 23932, 35351, 201251, 49041, 27306,\n 19128, 40135, 3986, 77333, 19649, 120683, 151927, 21081, 7076, 78375, 77501, 101599, 8011, 89585, 96715, 58179,\n 5378, 102138, 106793, 26051, 217276, 4197, 16297, 27014, 46721, 13322, 22806, 5278, 29629, 70632, 9647, 71519,\n 58818, 40603, 128530, 8903, 36770, 56900, 31483, 26935, 43845, 34265, 34920, 87658, 6114, 84767, 64250, 47318,\n 50720, 19264, 162514, 33357, 13117, 6705, 46696, 75032, 71054, 87004, 42035, 69138, 11903, 99854, 102328, 19611,\n 34525, 69312, 6431, 49842, 101600, 133178, 108751, 41829, 89939, 225664, 48916, 99556, 9195, 130387, 5960, 36857,\n 116724, 53518, 94002, 39077, 53996, 6945, 22261, 64291, 8314, 152785, 57588, 16522, 9091, 5048, 87671, 35441,\n 39509, 1945, 12423, 158923, 178413, 37549, 14095, 1475, 73188, 62878, 4819, 24012, 68534, 42606, 4010, 120809,\n 57497, 59564, 101758, 103718, 32701, 80116, 12345, 95834, 46918, 21468, 53213, 15665, 31200, 3867, 5140, 96013,\n 250744, 21016, 10069, 13968, 35449, 180829, 27683, 39704, 59956, 22893, 3115, 26293, 32785, 75934, 62445, 141162,\n 62720, 2018, 83638, 19949, 114012, 95006, 3330, 99829, 130935, 309272, 9565, 55874, 121727, 37017, 23586, 319858,\n 40970, 27602, 8625, 112329, 61060, 100088, 118525, 25922, 16232, 1907, 60671, 51583, 44553, 80993, 5262, 94679,\n 8676, 940, 20736, 11823, 3020, 16476, 12340, 152600, 97416, 3703, 25744, 66826, 16245, 16876, 46446, 84798,\n 74227, 176020, 45192, 61955, 75496, 23946, 23626, 40372, 26036, 6149, 11822, 30582, 16541, 41914, 82385, 232823,\n 40921, 80773, 14930, 3631, 7517, 39619, 4348, 36180, 126106, 138939, 62611, 1477, 113512, 47321, 25052, 14546,\n 118881, 29060, 23589, 128322, 36795, 18401, 137921, 104699, 267929, 36194, 172791, 18113, 4766, 188215, 30083, 332586,\n 94089, 5805, 77909, 22194, 68234, 154976, 43220, 40660, 70001, 184893, 138095, 11128, 103010, 22663, 5108, 212615,\n 8485, 5565, 49222, 54614, 26530, 42639, 16319, 55062, 152662, 105595, 21114, 22216, 10294, 68158, 10436, 86950,\n 7206, 62115, 3977, 3657, 59874, 456, 118617, 18156, 106663, 112229, 80992, 17442, 8217, 55551, 5133, 34344,\n 251927, 51153, 39364, 201321, 7816, 66803, 23057, 156724, 145664, 14276, 95705, 979, 2796, 6875, 13429, 212525,\n 50602, 26276, 28284, 3424, 19465, 52397, 46963, 31420, 51399, 206476, 92317, 48851, 637, 100820, 83349, 10317,\n 60227, 21972, 6908, 282439, 32857, 224767, 95629, 83882, 42106, 87338, 69757, 29840, 68709, 37665, 45244, 114577,\n 49188, 175943, 54009, 186746, 106158, 70168, 3358, 234002, 50555, 9221, 129338, 9562, 20118, 32923, 78479, 118280,\n 65752, 4977, 10474, 102174, 60947, 129006, 10570, 83451, 8598, 8078, 159367, 123785, 80438, 16742, 5905, 5281,\n 181513, 42402, 6977, 163136, 93179, 42191, 14968, 50421, 112401, 105440, 33456, 57347, 121611, 4221, 94954, 36517,\n 24046, 27796, 6255, 33394, 72990, 135408, 116627, 1233, 57874, 25654, 95419, 68156, 401399, 313338, 55208, 45573,\n 93124, 119251, 47200, 38196, 11909, 130667, 45391, 73904, 64964, 167846, 4137, 115606, 52036, 62214, 7969, 160925,\n 7187, 1132, 134835, 40309, 73195, 64494, 80472, 444841, 61111, 26500, 45323, 40743, 53625, 52797, 22659, 15631,\n 29739, 36706, 28841, 39147, 102836, 26794, 10536, 14845, 87305, 45874, 12241, 127587, 83833, 57183, 79722, 30844,\n 41304, 84655, 20825, 92500, 3722, 25655, 27811, 10157, 81634, 31362, 34088, 92487, 70123, 22190, 185100, 72658,\n 139035, 192523, 88241, 2078, 230490, 44528, 85638, 100198, 22088, 29982, 291233, 241062, 13865, 4445, 137791, 37835,\n 107218, 31726, 19718, 38234, 72528, 23046, 19177, 66695, 5109, 17251, 28077, 5617, 21554, 47839, 72425, 133825,\n 1486, 73065, 181275, 141508, 21768, 62971, 63082, 2512, 34200, 9904, 120309, 6392, 91243, 68416, 268253, 41199,\n 116757, 138551, 185526, 41246, 28986, 4093, 19057, 17295, 4148, 245766, 122360, 35356, 112075, 20301, 75441, 10998,\n 7977, 19769, 62922, 937, 63547, 100196, 26427, 157820, 20983, 236696, 22935, 8140, 90315, 156004, 47204, 140973,\n 7726, 45097, 52725, 22636, 23436, 257282, 105247, 522, 88389, 216031, 202204, 46812, 211666, 19693, 68828, 81691,\n 45925, 11256, 30292, 372, 5236, 167826, 88328, 232776, 151611, 5360, 82104, 18841, 80393, 25465, 18285, 20320,\n 72377, 31730, 33160, 45803, 38715, 27705, 37379, 24163, 18360, 103586, 4015, 32305, 269494, 91252, 20080, 36567,\n 54650, 7797, 57073, 12650, 31164, 42209, 6375, 261663, 105528, 81661, 106002, 2800, 5375, 17247, 43151, 4442,\n 15727, 194619, 100855, 144898, 62320, 78465, 39929, 16454, 1967, 28311, 61363, 17219, 9395, 8745, 121445, 76939,\n 80385, 162380, 22009, 54191, 44248, 16299, 122830, 48151, 74429, 78291, 64755, 14238, 44966, 2511, 17712, 67954,\n 93583, 829, 105899, 49935, 84750, 11591, 33185, 85447, 42717, 27409, 208542, 28965, 62052, 52525, 5597, 25694,\n 65594, 16343, 63224, 276188, 12475, 9331, 127507, 38522, 57287, 24128, 133161, 79723, 105548, 133695, 48917, 27558,\n 43278, 46520, 13778, 141954, 110785, 83366, 17715, 46317, 105763, 66298, 147013, 41086, 94180, 16478, 220447, 44611,\n 730, 19722, 78975, 117889, 125643, 26254, 16574, 18480, 65006, 15806, 38549, 246418, 46052, 36056, 8440, 34984,\n 30170, 3163, 59800, 4458, 115442, 4283, 41970, 33507, 104078, 1653, 22, 121158, 276486, 3655, 6338, 24048,\n 133421, 23641, 2161, 24422, 36006, 8086, 10675, 181474, 12307, 29514, 59143, 14729, 52509, 87128, 122470, 19446,\n 80852, 33314, 24573, 119864, 14237, 9652, 57779, 6612, 51851, 15284, 98871, 90581, 124466, 156831, 21190, 22015,\n 71380, 161906, 87247, 69201, 18392, 17908, 108470, 72962, 40719, 14338, 17911, 95260, 43339, 20610, 78916, 20710,\n 72451, 11315, 31448, 17263, 58853, 178878, 48111, 116002, 45497, 80506, 82605, 85880, 36300, 121755, 25215, 36118,\n 301929, 88728, 405223, 276136, 553, 34704, 212438, 49970, 78329, 922, 20711, 25036, 257130, 38295, 145369, 18128,\n 15385, 30829, 55656, 48345, 8012, 3561, 28004, 122041, 192900, 58338, 112508, 41085, 29976, 87040, 47117, 23905,\n 4336, 92061, 138880, 97407, 42083, 172121, 6256, 25192, 172671, 5, 93568, 1420, 12677, 31605, 56743, 40620,\n 6015, 78415, 231077, 31298, 80026, 13902, 19048, 24924, 170586, 32955, 176119, 87859, 36731, 6773, 27711, 24658,\n 26475, 115216, 133207, 93250, 95820, 88522, 8317, 5714, 124047, 55219, 86860, 19677, 23961, 22928, 162209, 8904,\n 225992, 359835, 56084, 96201, 29392, 96558, 86071, 93643, 55114, 13347, 8183, 95129, 82012, 2017, 123336, 34219,\n 115554, 157159, 47747, 101684, 41008, 18735, 193781, 104151, 226906, 7552, 179874, 124113, 31159, 21162, 44010, 14771,\n 51268, 166128, 31382, 73124, 77438, 92830, 205709, 12113, 1292, 38937, 13114, 1334, 2118, 15597, 69581, 14449,\n 21934, 76618, 48728, 67038, 14967, 51495, 24243, 87736, 147249, 26720, 11119, 46063, 43749, 5843, 44147, 152629,\n 133428, 65703, 14269, 45604, 57982, 28672, 55616, 45957, 8438, 95433, 37698, 220862, 132034, 39456, 61870, 4161,\n 26501, 73560, 56418, 9845, 4654, 20916, 10456, 88920, 119358, 9015, 65931, 96507, 48029, 38534, 21676, 109081,\n 43078, 34943, 25089, 6131, 28766, 23665, 5477, 10255, 16695, 67, 45778, 42443, 42770, 29534, 23733, 100513,\n 62617, 42630, 48746, 14191, 43753, 50295, 26007, 8792, 57243, 43119, 54725, 164253, 58250, 112304, 131796, 25165,\n 4651, 3188, 24831, 47748, 3705, 19540, 13211, 102095, 5593, 18699, 23666, 32005, 117571, 33541, 60584, 74573,\n 86311, 99443, 25172, 27222, 168938, 7143, 11853, 53560, 18834, 19960, 86522, 28217, 53266, 117700, 72989, 34323,\n 18721, 66450, 34346, 74056, 47217, 202002, 46269, 9429, 68582, 75458, 37823, 82843, 96652, 32549, 145144, 27958,\n 19820, 158086, 31955, 201406, 135379, 31207, 192545, 12950, 51704, 9094, 248263, 76147, 64028, 110009, 79407, 89345,\n 99284, 223492, 47966, 26848, 15359, 201137, 2861, 110507, 71231, 72297, 31851, 118777, 71039, 151051, 240855, 16333,\n 50766, 14727, 7939, 4149, 80908, 418780, 88378, 59276, 1327, 7284, 38576, 79814, 65820, 42199, 84860, 49574,\n 62596, 12396, 70598, 40117, 8648, 7994, 16836, 7630, 14047, 359699, 106878, 525, 29037, 28064, 13380, 11675,\n 50669, 74216, 103539, 180314, 27449, 56299, 172344, 19274, 7301, 246099, 32043, 19422, 36506, 129317, 6806, 30140,\n 4614, 46639, 66926, 932, 86600, 6322, 27847, 233103, 10541, 39025, 34887, 3517, 12972, 26220, 2031, 66561,\n 115015, 48658, 47596, 12714, 33845, 3893, 16165, 35237, 89983, 14769, 11962, 147224, 47018, 29977, 27979, 5552,\n 82338, 86023, 131368, 1218, 24853, 237840, 132193, 15455, 40873, 3668, 65351, 53388, 15229, 59889, 272245, 47934,\n 11858, 34347, 18038, 90853, 86981, 300602, 19343, 114181, 29362, 84921, 6095, 106059, 79472, 38015, 1206, 48741,\n 6208, 80000, 21916, 17423, 6002, 108083, 24479, 34931, 56661, 9511, 26995, 100694, 163853, 35997, 81254, 58321,\n 18919, 171890, 86877, 91341, 74503, 70477, 53412, 7027, 59281, 39892, 131302, 5864, 15947, 61301, 67466, 162369,\n 47956, 27874, 35624, 282324, 21270, 111847, 102548, 41482, 30955, 116737, 28264, 8592, 55458, 22301, 75090, 29821,\n 30697, 51709, 3041, 19208, 8038, 24634, 30467, 87509, 126428, 19389, 18814, 152686, 20701, 83474, 45832, 80891,\n 105808, 11378, 153223, 120770, 98186, 150633, 49838, 9141, 12755, 30962, 5260, 74490, 21256, 31678, 65062, 33326,\n 289838, 187831, 20595, 89768, 2805, 58535, 10844, 70085, 12090, 2451, 138068, 98544, 24461, 4511, 6754, 41684,\n 28203, 3383, 65355, 82833, 30161, 83924, 234361, 128424, 28921, 222594, 33975, 125491, 34069, 11508, 67464, 144226,\n 41850, 98703, 34371, 7901, 21254, 38398, 65651, 23549, 53883, 213340, 123269, 12028, 71764, 177701, 28758, 2623,\n 68395, 11549, 15232, 68603, 9660, 63116, 36079, 57093, 31198, 20475, 48467, 89984, 35619, 186847, 107469, 31389,\n 43631, 73867, 41949, 68841, 114250, 1605, 30564, 63403, 17588, 27680, 99533, 12641, 70325, 50428, 73426, 78379,\n 11855, 91651, 72081, 91720, 60198, 15743, 12065, 83398, 140046, 6761, 46598, 45900, 5068, 886, 62448, 148968,\n 37347, 19405, 9680, 15819, 43496, 63370, 75667, 163700, 37639, 3633, 22774, 34341, 183131, 134335, 37200, 23915,\n 7054, 14194, 12970, 26438, 13350, 285521, 25594, 8219, 104410, 91039, 168804, 138480, 149734, 15907, 33818, 61132,\n 60082, 4622, 110187, 56736, 13551, 73571, 3945, 73463, 65498, 17758, 263266, 17593, 2710, 27585, 54469, 38200,\n 45367, 63754, 28881, 3473, 12791, 98287, 31895, 65787, 4463, 94536, 24951, 36332, 59901, 28803, 52130, 86403,\n 7668, 181822, 74831, 18977, 9850, 177206, 145485, 109798, 7292, 31421, 26280, 77211, 58511, 12507, 127004, 11113,\n 147, 8729, 56208, 43066, 79926, 129937, 31345, 83947, 39915, 46146, 98763, 42566, 1337, 13192, 18323, 105163,\n 80570, 117753, 16555, 72883, 11077, 159438, 40764, 70933, 83329, 26066, 12276, 72059, 21655, 173836, 126713, 69454,\n 153482, 91585, 70644, 102558, 110483, 6764, 127864, 190133, 3961, 101798, 20945, 71138, 82402, 90884, 69669, 44753,\n 923, 16939, 59700, 164258, 25969, 27082, 31399, 43846, 6306, 246093, 51342, 6153, 151581, 202801, 182731, 56475,\n 162188, 89426, 141356, 14355, 121815, 27536, 28023, 65257, 77523, 106668, 127314, 24947, 12790, 38796, 169698, 23555,\n 10725, 44573, 183083, 42088, 62716, 43265, 105958, 32050, 44067, 50118, 1668, 3874, 6243, 318411, 16599, 1691,\n 94999, 52378, 28671, 216728, 123258, 2059, 34969, 69225, 5913, 136280, 171443, 141515, 91662, 22175, 135282, 80020,\n 92270, 1663, 4808, 4482, 3495, 34691, 5226, 109830, 108512, 17342, 107488, 11606, 123190, 100247, 29666, 146527,\n 113014, 15794, 30894, 13224, 39585, 243192, 22351, 9903, 7836, 47699, 11078, 25468, 122291, 48821, 26780, 122679,\n 75521, 81450, 630, 4895, 92900, 55074, 74293, 17441, 3563, 111657, 103102, 51613, 12318, 52370, 36191, 68245,\n 34269, 40445, 41354, 122901, 168604, 182500, 62012, 42557, 11259, 24428, 115113, 86345, 12362, 3909, 78430, 86852,\n 134602, 20459, 47853, 93879, 22577, 7659, 3688, 38555, 13349, 17381, 56715, 91639, 12493, 10895, 92438, 3142,\n 37057, 28928, 2004, 36427, 32268, 34222, 209974, 10432, 67436, 41989, 173518, 107930, 27079, 62729, 30908, 55558,\n 5828, 45031, 14902, 53546, 8204, 144263, 60255, 14520, 88212, 86582, 109589, 69356, 8064, 47449, 8505, 66558,\n 16886, 4844, 52817, 111260, 215129, 12941, 91118, 650, 20770, 6273, 73089, 40618, 62790, 2873, 35002, 14023,\n 97208, 19386, 102646, 36993, 143736, 135457, 35385, 113601, 17893, 32627, 84439, 100619, 56016, 6581, 57264, 172160,\n 45452, 111710, 203627, 70131, 24100, 322787, 1996, 35665, 70078, 22358, 90922, 83658, 4097, 63200, 58499, 14542,\n 99153, 52159, 6615, 12414, 63415, 31986, 16823, 1579, 65405, 137809, 8841, 16898, 48082, 259, 33014, 42375,\n 12260, 179850, 73667, 91389, 98882, 29532, 17311, 326251, 41092, 5928, 20742, 44964, 48019, 43505, 9317, 49265,\n 6643, 192712, 48424, 163487, 19861, 20113, 70848, 31928, 105333, 23685, 78563, 14638, 54755, 7158, 24142, 44018,\n 20774, 125255, 20331, 24280, 10163, 1285, 2336, 39851, 4299, 117269, 46714, 63816, 87779, 159624, 11731, 9971,\n 990, 137317, 108831, 50994, 74554, 162680, 23640, 131597, 146962, 170620, 34829, 91205, 21184, 1913, 63616, 18427,\n 93136, 156592, 17519, 67565, 115882, 138220, 78622, 88535, 18115, 2711, 33554, 109492, 54298, 971, 24914, 25863,\n 36363, 45715, 27099, 194995, 14299, 178181, 111488, 72395, 322385, 157719, 130787, 11897, 81843, 83999, 11369, 49280,\n 118604, 40922, 61332, 110343, 53407, 75639, 40582, 300440, 54722, 25637, 13694, 48248, 48278, 194521, 56203, 52779,\n 48783, 72627, 10953, 376, 16733, 280238, 26351, 230789, 15132, 25168, 137270, 3588, 63704, 73376, 94031, 74284,\n 19443, 159557, 9697, 39901, 13351, 119050, 15406, 146455, 3460, 29556, 75195, 37673, 102524, 92329, 47289, 98413,\n 15311, 100684, 56345, 7116, 95480, 11590, 7200, 167, 23610, 58426, 17730, 136656, 27944, 53151, 2701, 8824,\n 103124, 3017, 90744, 113588, 53216, 79736, 65940, 26931, 498, 29568, 80540, 143543, 21292, 1740, 59268, 16561,\n 180816, 42323, 50174, 40890, 52866, 10703, 57169, 4700, 17191, 4424, 93511, 49698, 166650, 26972, 48631, 165169,\n 82879, 69326, 202970, 4007, 2376, 231325, 139592, 22119, 62851, 37504, 68816, 58345, 67398, 186643, 43331, 277416,\n 53749, 15746, 23102, 17432, 4793, 151138, 48822, 54265, 48203, 198688, 14305, 54287, 2291, 18018, 113378, 123260,\n 7180, 97549, 87027, 120085, 2920, 76080, 8190, 102005, 5641, 64580, 14955, 59802, 54028, 58884, 19367, 81779,\n 412567, 85957, 97053, 103637, 78871, 29364, 27637, 141728, 4767, 30686, 112738, 130146, 42745, 12730, 105040, 14844,\n 232, 210944, 36581, 152317, 135543, 29744, 3129, 55647, 58149, 46319, 27265, 17499, 28005, 59948, 7170, 34138,\n 5702, 293047, 110892, 408, 91760, 218674, 18469, 46095, 81403, 14389, 4610, 35672, 73060, 11006, 74848, 104820,\n 118143, 190357, 20043, 105358, 141735, 5115, 27093, 45924, 123073, 52599, 29433, 9616, 238350, 78610, 24851, 58858,\n 26769, 31969, 24613, 18294, 4982, 32735, 39639, 143563, 112073, 202205, 12567, 4873, 88601, 44897, 81503, 101648,\n 81362, 34662, 85277, 17574, 48173, 21435, 221188, 40215, 39576, 80786, 26544, 64668, 81841, 10731, 37733, 247986,\n 149188, 127703, 495, 18382, 54388, 72446, 43071, 30974, 198723, 89608, 41360, 190, 33045, 8386, 31658, 19992,\n 237838, 119015, 137622, 50890, 100913, 6460, 116233, 267230, 26621, 104129, 65114, 14190, 41542, 14888, 85962, 23342,\n 23041, 26453, 43725, 71809, 45186, 4770, 46452, 53894, 56616, 221286, 18973, 9038, 109299, 55365, 19366, 26863,\n 18808, 60909, 69353, 41738, 83463, 12100, 68561, 72860, 3980, 13796, 49340, 12332, 31311, 27418, 4255, 53430,\n 18976, 45523, 510, 14224, 30477, 26581, 4530, 3651, 101663, 139840, 22709, 150861, 31996, 63923, 120623, 262522,\n 3076, 10528, 2929, 14672, 130238, 18087, 9816, 121894, 100308, 25085, 55111, 14565, 18952, 53293, 2042, 369988,\n 23674, 61789, 133529, 28783, 108293, 35477, 47119, 36448, 71049, 40015, 33055, 78598, 198442, 1833, 159937, 40654,\n 77444, 189245, 113153, 8621, 18599, 38553, 35223, 166072, 2375, 11659, 21786, 89523, 6032, 12116, 63046, 159398,\n 18454, 3678, 32521, 47626, 11411, 103527, 38896, 42946, 15696, 26370, 10185, 8413, 37080, 165583, 4331, 63555,\n 14907, 72220, 50056, 6623, 62236, 36565, 49783, 10049, 17503, 100581, 55951, 146244, 24724, 9626, 17969, 25524,\n 109300, 173965, 99994, 101056, 46459, 43647, 53737, 277968, 8347, 123521, 74858, 33829, 44762, 77574, 877, 81377,\n 222525, 123532, 30602, 43881, 53145, 2973, 16284, 81940, 61281, 127044, 63620, 9875, 14756, 114829, 19032, 9202,\n 52759, 119141, 23928, 120551, 19607, 3599, 33401, 76821, 73233, 117430, 39968, 36539, 7071, 5446, 121735, 194059,\n 15206, 45283, 6706, 15603, 65615, 1207, 165723, 92275, 34773, 104447, 8396, 32353, 205240, 164323, 13600, 60555,\n 79205, 25532, 22907, 33410, 57480, 107111, 69630, 32137, 47832, 70913, 33161, 20321, 2371, 117348, 10714, 86246,\n 1625, 11763, 17900, 268, 78457, 99175, 97940, 101092, 86660, 32221, 14041, 128504, 125080, 53744, 124263, 31017,\n 13897, 403, 31859, 21964, 5633, 111630, 5547, 77329, 17961, 18241, 84995, 25984, 12983, 67491, 62168, 47262,\n 5241, 297, 51191, 7351, 8967, 147212, 82060, 16821, 782, 11033, 82431, 62957, 5026, 43459, 77963, 203477,\n 53528, 6247, 191852, 87774, 74164, 215654, 13467, 1522, 219964, 28589, 244104, 16242, 117821, 67725, 72570, 156792,\n 17186, 15979, 26990, 44128, 193014, 35276, 57125, 16212, 166451, 68017, 6905, 77608, 16364, 53777, 75921, 76426,\n 37975, 26203, 269296, 64099, 84122, 12077, 38533, 830, 4407, 20139, 963, 43028, 38902, 42911, 37503, 83343,\n 85045, 16979, 1165, 60835, 137387, 58380, 86990, 110066, 134540, 56331, 193845, 81238, 17922, 163093, 38744, 110641,\n 12502, 56404, 34862, 26865, 125964, 12965, 111648, 25547, 7771, 27196, 136980, 9555, 29551, 107158, 57885, 18831,\n 37705, 35505, 101742, 13970, 102109, 62548, 124657, 23328, 11124, 89592, 146376, 248050, 6241, 22033, 18337, 80685,\n 29898, 11908, 216623, 67721, 106162, 146610, 21377, 15085, 91552, 42041, 62560, 122532, 125336, 102365, 121537, 142559,\n 29693, 223919, 11515, 110495, 18776, 22494, 5895, 185059, 103592, 229351, 51220, 100102, 37027, 257855, 29359, 54123,\n 36066, 106493, 12244, 79258, 32002, 432, 56205, 94836, 90182, 6726, 14762, 29391, 48938, 26864, 38083, 60364,\n 3310, 60192, 14766, 205567, 57504, 110760, 22649, 24666, 46333, 21517, 3430, 13135, 28873, 27052, 158809, 11597,\n 20529, 6695, 23138, 22960, 37137, 45574, 6545, 305877, 43423, 26153, 24769, 59844, 14501, 10430, 134352, 56169,\n 13213, 103432, 49523, 35181, 13435, 12408, 129475, 64620, 230854, 77390, 51990, 15653, 83248, 33466, 44571, 117828,\n 51481, 2187, 10559, 68019, 18021, 54895, 48247, 18354, 33737, 4554, 108595, 37288, 39767, 116707, 9175, 3726,\n 108877, 21616, 83684, 49862, 1938, 8543, 276466, 20134, 108498, 48770, 102254, 31914, 131520, 185291, 100559, 51890,\n 209, 19526, 76471, 50544, 71814, 99351, 8172, 198526, 28816, 20419, 9109, 98389, 136777, 76479, 75596, 30635,\n 165417, 48216, 120220, 25955, 211071, 39314, 24308, 32164, 2559, 146280, 43403, 9233, 17947, 90585, 1786, 86920,\n 125662, 2457, 64741, 32152, 32918, 122882, 78538, 44001, 31723, 56426, 23375, 103172, 88177, 145697, 52506, 49319,\n 68016, 31664, 41488, 18486, 110400, 7030, 28241, 986, 109199, 19900, 42147, 56864, 65287, 49183, 7858, 24000,\n 30453, 840, 16673, 25907, 68916, 89927, 6309, 158335, 36407, 199737, 130464, 13137, 59603, 201778, 195292, 21015,\n 42466, 179062, 172561, 89492, 11075, 180407, 31868, 72493, 20998, 60217, 9865, 19530, 39274, 130266, 54539, 21623,\n 12535, 13505, 40641, 73375, 4087, 85633, 2153, 3117, 70680, 55788, 92096, 47509, 98493, 37490, 271936, 151475,\n 3032, 16171, 96642, 34106, 78425, 125761, 19591, 3366, 19316, 54508, 24183, 50786, 194248, 91528, 33253, 34622,\n 108355, 41741, 705, 3814, 3883, 108929, 13203, 67831, 10142, 59754, 68208, 29128, 84820, 56880, 38794, 24972,\n 48571, 40821, 40476, 18137, 164254, 24064, 236309, 79181, 11282, 395, 39169, 2013, 51587, 28551, 9645, 701,\n 109513, 115899, 113566, 12762, 62045, 58322, 103726, 41343, 40866, 244102, 143816, 2490, 70346, 40973, 52618, 15412,\n 30720, 104315, 38917, 42027, 93676, 17513, 107418, 20706, 123890, 13399, 97727, 24044, 87962, 65606, 44250, 98044,\n 65276, 74790, 101473, 19350, 91570, 1326, 87790, 172042, 7577, 100813, 86896, 85891, 41512, 108130, 27794, 14875,\n 71431, 12835, 156250, 58135, 3759, 22476, 42176, 115873, 34686, 56523, 73643, 108505, 51491, 20838, 12721, 32863,\n 45700, 29496, 13700, 34294, 55360, 29206, 155942, 123812, 7706, 163234, 203, 132720, 49358, 144431, 8130, 175788,\n 35818, 3270, 76832, 25710, 54095, 97274, 28779, 94621, 74396, 19092, 128242, 58067, 20885, 14670, 93255, 15107,\n 63291, 23654, 126900, 129421, 59294, 262659, 9798, 3251, 67344, 28600, 44629, 50672, 29072, 26999, 31526, 23183,\n 49175, 165843, 175455, 17282, 175411, 32022, 45989, 30298, 90690, 78118, 83156, 23749, 35636, 31317, 7069, 80381,\n 94561, 133756, 14960, 97404, 6138, 41065, 78041, 32843, 16601, 34123, 9559, 146529, 123377, 96395, 54441, 42012,\n 84257, 123541, 10745, 22139, 106459, 11720, 150883, 172651, 154996, 110538, 4728, 53447, 25704, 2009, 71152, 119354,\n 21166, 66604, 1429, 216162, 8637, 122250, 63520, 27180, 29172, 36124, 276428, 107787, 77184, 4680, 14952, 104903,\n 24418, 14793, 51561, 52931, 8371, 26342, 48526, 7118, 92066, 67280, 40653, 8847, 34597, 105438, 14198, 50163,\n 61188, 146286, 50315, 41205, 170829, 161496, 585, 197359, 95056, 1687, 365794, 91349, 48507, 5804, 49263, 5146,\n 104902, 96365, 117343, 132222, 46084, 96919, 16875, 8073, 262381, 79982, 52663, 13928, 16056, 153908, 15145, 109256,\n 132308, 18763, 24904, 167644, 13618, 40750, 18686, 147124, 114709, 150038, 52849, 2938, 12568, 48617, 8778, 5459,\n 44202, 44591, 74914, 17183, 248689, 13878, 7822, 80060, 23116, 194037, 18487, 2067, 7798, 43077, 33678, 244028,\n 31320, 74273, 2794, 19466, 8218, 36280, 183997, 48124, 19416, 29656, 19280, 98734, 7715, 18311, 30701, 133602,\n 150307, 126956, 7378, 2933, 79903, 13178, 12593, 86571, 26604, 92446, 13574, 44205, 65699, 427599, 21118, 8245,\n 14407, 27877, 47936, 33542, 7916, 26460, 117762, 21596, 37818, 2249, 127359, 209394, 60044, 47677, 308089, 36791,\n 154971, 31417, 6998, 150042, 174360, 12255, 43009, 29335, 48739, 3912, 101398, 53340, 2580, 146939, 151295, 45360,\n 125275, 15273, 45383, 27456, 48761, 23314, 8750, 60801, 85823, 104759, 27894, 123685, 66968, 39480, 26917, 55290,\n 83305, 2696, 98390, 57569, 145853, 340733, 4919, 20024, 52268, 30884, 7413, 203685, 70989, 112855, 4129, 50536,\n 349518, 68205, 332641, 159581, 135361, 236026, 37563, 176404, 64899, 6578, 122033, 63871, 1850, 85234, 82089, 66124,\n 74145, 121098, 107351, 12687, 36881, 117334, 13136, 14698, 85933, 93866, 18047, 32620, 310, 15094, 46000, 88451,\n 23632, 36645, 27940, 87618, 80520, 58892, 20976, 27702, 140090, 96075, 67841, 103292, 238964, 87778, 107338, 17019,\n 83427, 67522, 7302, 8261, 47570, 116787, 8730, 80484, 61772, 174422, 56005, 131193, 52875, 14588, 28471, 59817,\n 9586, 15720, 158155, 51307, 109734, 15196, 11025, 59331, 3884, 52626, 102602, 84797, 25158, 27314, 4437, 20488,\n 76214, 189248, 35023, 114952, 157376, 2827, 62439, 102878, 129749, 36405, 10329, 109339, 108633, 36662, 1254, 13267,\n 5470, 87105, 58004, 15397, 10434, 159667, 21864, 52022, 179464, 3013, 32147, 31496, 116832, 18494, 105502, 129227,\n 107267, 50033, 13481, 9954, 24267, 22141, 16257, 116154, 36185, 950, 115685, 11305, 176708, 2048, 178671, 112573,\n 287867, 162328, 497663, 95170, 50979, 193861, 50987, 30368, 136257, 31830, 46549, 15119, 169876, 23788, 17462, 249887,\n 57377, 1949, 35448, 14791, 43769, 210091, 3783, 34612, 282103, 88380, 245190, 5457, 20491, 98908, 11402, 86899,\n 117916, 16028, 162584, 60644, 320177, 156096, 31065, 55876, 22000, 77655, 9992, 23397, 13757, 317623, 63978, 215255,\n 2443, 17648, 93231, 27388, 104529, 93807, 55505, 140477, 12046, 112040, 70887, 40152, 94365, 112353, 25063, 114679,\n 266061, 71248, 119555, 15589, 2244, 617, 14129, 211431, 70110, 100652, 7777, 4383, 85911, 89221, 21010, 120615,\n 58357, 86405, 37554, 41647, 18, 15143, 69662, 60491, 14714, 186134, 148344, 42347, 5410, 168175, 44535, 42449,\n 343894, 129417, 99682, 20659, 27272, 140483, 63455, 222159, 17536, 13722, 42637, 62324, 11976, 114691, 148109, 2283,\n 32057, 182393, 4295, 147364, 33705, 2075, 44303, 30274, 28331, 63740, 69740, 29148, 10346, 44862, 33716, 73937,\n 153333, 12930, 38784, 247159, 2515, 41053, 20256, 83368, 256189, 54639, 115240, 5096, 24661, 175419, 153552, 26516,\n 141, 138176, 63885, 34115, 47222, 55709, 2765, 28479, 38875, 236608, 12229, 22921, 77291, 54426, 45388, 2860,\n 57787, 114579, 295139, 105782, 17826, 71066, 19119, 54364, 69385, 16568, 12323, 28057, 33346, 34919, 124763, 155533,\n 101386, 31644, 8627, 49001, 303600, 29868, 63213, 9103, 77280, 71333, 9696, 138789, 37059, 24823, 5057, 21352,\n 32368, 114208, 56803, 19424, 10445, 58514, 8661, 209508, 26187, 171838, 10460, 63454, 14016, 122504, 41328, 21329,\n 46618, 32493, 38225, 7855, 31763, 7945, 29876, 8734, 6438, 24205, 97490, 139977, 130740, 47323, 33195, 85390,\n 57194, 13813, 60600, 21313, 96251, 7699, 27584, 170521, 139271, 1363, 4402, 336738, 129223, 84983, 69150, 13147,\n 3590, 163929, 207225, 155260, 55916, 20288, 4503, 8398, 98490, 11773, 27512, 37113, 84976, 86558, 28365, 11756,\n 116005, 182148, 13733, 115313, 47644, 67208, 85069, 9347, 14995, 226141, 14704, 101835, 41159, 35314, 13113, 63526,\n 214039, 29978, 50446, 83339, 17440, 129441, 72522, 118641, 97816, 24907, 73844, 15717, 118884, 167255, 96509, 162793,\n 30847, 36849, 51297, 78974, 77793, 10427, 1873, 2972, 9999, 35074, 28190, 64297, 146836, 46298, 60038, 163007,\n 108919, 61219, 2403, 75022, 127339, 4233, 110389, 69022, 9833, 128097, 88016, 79390, 222936, 22570, 94657, 28462,\n 56956, 38803, 81536, 30474, 152794, 19566, 16481, 147408, 74574, 81895, 20731, 1918, 1366, 76367, 187321, 54494,\n 24366, 21690, 61696, 33283, 107477, 77499, 31112, 414383, 74362, 18463, 218441, 120929, 59848, 258629, 201924, 69269,\n 454, 19989, 13054, 59894, 3623, 58908, 20681, 35723, 78523, 102680, 38988, 184112, 108087, 50944, 132704, 52966,\n 21699, 18860, 96349, 201411, 82697, 85395, 95658, 5093, 6427, 177894, 44191, 32755, 26961, 155739, 6249, 31310,\n 81030, 26574, 84311, 120155, 86730, 113535, 7424, 48888, 13516, 45747, 98098, 20077, 183995, 81945, 43210, 26704,\n 40420, 75831, 45648, 11180, 6855, 57927, 65528, 124096, 34851, 2598, 156633, 107572, 127352, 38169, 123845, 60142,\n 62722, 105584, 232364, 23211, 68120, 1601, 22169, 89299, 747, 258039, 80572, 7258, 152249, 11862, 101204, 8834,\n 121434, 33761, 19175, 133142, 46343, 40178, 48723, 3589, 41977, 30210, 38868, 62257, 10087, 82658, 87827, 90646,\n 16415, 47552, 351723, 28298, 72225, 91146, 272760, 1701, 11295, 1652, 109651, 300747, 51863, 198800, 29446, 11794,\n 32345, 37538, 22356, 33102, 37590, 113544, 37970, 11478, 179743, 25454, 103417, 59905, 221970, 105196, 145604, 7817,\n 164809, 102360, 16974, 75840, 255333, 56902, 6659, 1954, 645, 59400, 67769, 7689, 18675, 5215, 13793, 20536,\n 27852, 3387, 29523, 259718, 16860, 94625, 43143, 29245, 15848, 233581, 22685, 63631, 78557, 22836, 133302, 84513,\n 1348, 51826, 47129, 98836, 58284, 1830, 1749, 94642, 10933, 6145, 12506, 10975, 13879, 103781, 144434, 10268,\n 28409, 32346, 52968, 121567, 107374, 77268, 23686, 35097, 10501, 155275, 15303, 47136, 21102, 168741, 55332, 90385,\n 15996, 84817, 681, 137803, 25054, 142275, 6163, 38175, 8056, 124296, 240642, 65621, 4934, 178205, 16101, 62803,\n 60964, 18230, 100622, 76465, 44689, 14545, 9543, 47514, 16852, 93380, 28048, 12047, 107106, 37575, 101485, 77047,\n 57326, 34819, 96137, 76916, 6469, 46264, 115983, 75768, 87668, 69942, 13027, 165, 8373, 114231, 26434, 52844,\n 42799, 182044, 23580, 146254, 38081, 43236, 33883, 146220, 382894, 14606, 46035, 36481, 166621, 35417, 95382, 2957,\n 59384, 60428, 36358, 66343, 75378, 22267, 22950, 83528, 17577, 56474, 25285, 4619, 179691, 75355, 95836, 53295,\n 34588, 171410, 4487, 14679, 84208, 44015, 18562, 109133, 54101, 11531, 86052, 174479, 303157, 28095, 9953, 35642,\n 14564, 39802, 16145, 77606, 117406, 53038, 121117, 53624, 22062, 1212, 7632, 127157, 237292, 189087, 10478, 127345,\n 102515, 181997, 86752, 87623, 10966, 121602, 68783, 68681, 83042, 114380, 138349, 191305, 67176, 50085, 39016, 1427,\n 42384, 1412, 67118, 122616, 72389, 25260, 2237, 13576, 137346, 19938, 20304, 2191, 68759, 5373, 61364, 238507,\n 75814, 23931, 69565, 38993, 131741, 38364, 12528, 87762, 5679, 129853, 5310, 186831, 32653, 90338, 260176, 389531,\n 108118, 26843, 43985, 50175, 30563, 25106, 56965, 18130, 140428, 4542, 165503, 117991, 24219, 229605, 1819, 129663,\n 1240, 3797, 76093, 18398, 71339, 51919, 93043, 27175, 47060, 216257, 6483, 35051, 1217, 16512, 80798, 129064,\n 13225, 69339, 8548, 237079, 72298, 2575, 34280, 51379, 117910, 55671, 53345, 247552, 29486, 39328, 140821, 34681,\n 57045, 60177, 5004, 90269, 78522, 2479, 322607, 48474, 61296, 13057, 31558, 4678, 59271, 6699, 27044, 31988,\n 35944, 12503, 83480, 4389, 136508, 3781, 114121, 70279, 4488, 155829, 42214, 2898, 68191, 75695, 305850, 45041,\n 74344, 106509, 30087, 17429, 93292, 12477, 290, 23080, 114802, 35714, 18751, 26554, 105424, 17775, 2144, 2412,\n 100610, 65192, 113975, 52975, 180272, 135050, 129815, 76238, 106483, 21440, 63186, 4260, 46189, 9711, 28249, 4169,\n 23429, 23390, 8324, 141585, 63809, 67668, 38457, 38063, 39226, 59972, 1189, 203916, 62368, 14403, 16949, 61767,\n 85801, 1739, 40147, 35049, 76757, 33124, 62102, 15780, 103593, 103009, 53484, 22952, 67973, 114645, 6566, 5245,\n 50462, 7601, 8288, 3513, 194571, 80276, 1908, 54592, 5124, 58571, 2513, 6800, 273997, 193904, 1119, 17991,\n 117245, 2508, 129156, 82366, 26278, 71465, 63341, 56943, 39662, 106116, 94966, 156875, 9736, 2204, 122308, 94418,\n 27134, 1280, 24539, 49022, 45314, 3764, 50904, 46424, 30699, 28087, 293839, 9400, 33646, 40165, 822, 147499,\n 50263, 116179, 29085, 11863, 31314, 5578, 17797, 5104, 12454, 1604, 15342, 219206, 10232, 67800, 94261, 25872,\n 13565, 90339, 78971, 75377, 26649, 41184, 47695, 11514, 35369, 20767, 14227, 41953, 309396, 148270, 147938, 33074,\n 14453, 27499, 109019, 39018, 25738, 240196, 158931, 52820, 8612, 95853, 21524, 137010, 84901, 70869, 70021, 116794,\n 48404, 38771, 6732, 1070, 70990, 187297, 49140, 5238, 576, 3564, 253975, 16027, 16483, 2811, 37775, 19034,\n 25259, 4053, 2000, 70083, 95774, 19713, 33431, 92703, 91314, 42381, 288770, 48194, 95985, 3991, 77418, 13406,\n 241328, 245086, 56533, 35275, 62725, 9246, 51924, 70181, 95331, 16163, 31410, 79016, 39312, 120878, 119371, 275987,\n 80124, 27712, 9186, 220, 23598, 146167, 85209, 68238, 282190, 57048, 31273, 30555, 80913, 17594, 75779, 59160,\n 135002, 101219, 189377, 29225, 96735, 60126, 62522, 104000, 27620, 86814, 17240, 147533, 11001, 5425, 43682, 410,\n 49460, 87270, 69480, 46315, 59448, 1816, 76201, 9431, 11788, 87960, 29063, 65539, 47347, 11678, 33846, 7008,\n 196704, 9895, 6753, 8633, 120892, 59970, 572824, 115934, 6646, 202559, 892, 48351, 37611, 251282, 57823, 67263,\n 57750, 26527, 34485, 90747, 7685, 88370, 6144, 64182, 1709, 41969, 21458, 62327, 181657, 49247, 225330, 122600,\n 114574, 107124, 85361, 111833, 63243, 71420, 15655, 191178, 72430, 18063, 51425, 54002, 12364, 53225, 86557, 18193,\n 97580, 41232, 138398, 67821, 128724, 8944, 233212, 101353, 52099, 42127, 14006, 120107, 32789, 32132, 3498, 18123,\n 33758, 56058, 5779, 128760, 59888, 98869, 18445, 84702, 51911, 13234, 218379, 20093, 39031, 8074, 70195, 20708,\n 23462, 24355, 131384, 60189, 26390, 10403, 41060, 7140, 10781, 49410, 42261, 87202, 82566, 41663, 43105, 60276,\n 2768, 5733, 74176, 28329, 2297, 145430, 131632, 83615, 122915, 105441, 655, 224102, 5284, 136426, 67763, 16294,\n 188511, 32538, 61049, 27893, 3394, 13951, 159099, 28542, 17930, 145360, 9492, 190122, 32285, 78855, 26440, 13570,\n 58648, 73908, 4239, 124561, 2444, 74172, 53131, 11468, 10794, 73566, 11623, 35343, 64710, 30481, 4163, 10328,\n 38309, 29901, 10538, 154377, 76132, 92405, 24839, 11679, 3465, 13449, 11637, 7824, 2337, 57754, 1260, 14458,\n 41118, 19878, 38661, 13416, 159180, 37074, 163164, 54137, 28627, 52134, 184900, 8520, 40385, 29546, 30502, 22386,\n 66527, 107458, 6850, 24022, 47983, 30603, 35083, 8934, 304066, 39500, 9, 28261, 33026, 77251, 9374, 44833,\n 116312, 34990, 29236, 63563, 125639, 135405, 165398, 159055, 55690, 88141, 69643, 236964, 31983, 25572, 20436, 36746,\n 60896, 31850, 16179, 11828, 5888, 3043, 66368, 9750, 31167, 7915, 53111, 36430, 1333, 64344, 93659, 20061,\n 60596, 180191, 51630, 6792, 30244, 43509, 101058, 22409, 420, 44210, 109783, 43223, 27030, 72477, 72831, 32679,\n 29235, 7675, 47556, 12258, 39907, 149412, 84926, 118247, 24692, 71717, 105038, 86009, 45941, 41189, 89453, 29856,\n 52543, 30627, 226798, 67303, 59230, 67415, 34408, 1367, 99685, 16867, 128419, 52147, 4111, 125381, 117881, 16173,\n 44093, 102224, 31575, 23234, 24870, 83790, 127407, 239098, 3200, 994, 1255, 100903, 242275, 117266, 55116, 38205,\n 16140, 29662, 11307, 40414, 208793, 123355, 56470, 4862, 75600, 30119, 58218, 70828, 24075, 26974, 7802, 192353,\n 4851, 5475, 78720, 66596, 3409, 28573, 64396, 30381, 30690, 59859, 88256, 5406, 99945, 103064, 34463, 37727,\n 24238, 86643, 60088, 4057, 23741, 5967, 162904, 38240, 28356, 93858, 25510, 122879, 6897, 3278, 7057, 11971,\n 4400, 35461, 211413, 21395, 59615, 39471, 87233, 55795, 128426, 3051, 22470, 41950, 14705, 3974, 180108, 80476,\n 78442, 204996, 91987, 15634, 67610, 139015, 142373, 35611, 51134, 10387, 4353, 153456, 57749, 181039, 14183, 68447,\n 151532, 21107, 36452, 20551, 3186, 46247, 46383, 129666, 88736, 140662, 146243, 2066, 8360, 7978, 64818, 106963,\n 17896, 47801, 10723, 114821, 223295, 74192, 3293, 3393, 16987, 74064, 11277, 91622, 4270, 29828, 27951, 387869,\n 103235, 1374, 61988, 120083, 477, 145892, 128378, 11779, 211263, 61354, 18221, 17869, 46530, 83061, 108538, 157981,\n 90608, 67199, 95080, 49064, 195814, 12302, 66307, 10348, 231346, 160732, 112859, 63633, 146558, 21271, 31037, 198802,\n 47622, 12862, 95710, 3910, 77850, 73961, 85585, 34752, 61000, 4082, 24595, 103679, 71107, 8208, 79568, 150019,\n 16615, 24961, 139857, 32664, 197366, 4559, 54735, 32696, 4126, 162019, 75698, 13916, 70108, 159638, 19834, 9349,\n 24675, 175560, 49643, 18206, 52459, 27992, 10809, 88865, 401975, 133172, 29000, 34558, 30915, 3658, 25834, 42430,\n 36562, 125265, 18182, 10155, 40149, 97082, 208980, 19575, 60853, 90529, 66545, 9600, 789, 46420, 2317, 88593,\n 55595, 98980, 115302, 5742, 169155, 1073, 177901, 3472, 11189, 63711, 78643, 65472, 50459, 127979, 93, 42202,\n 67053, 21720, 157650, 11145, 141378, 42033, 22824, 85705, 79114, 35584, 15974, 1510, 54172, 28562, 12451, 104226,\n 19190, 97151, 73024, 20948, 5151, 81741, 21499, 29006, 84183, 198074, 54003, 45120, 170125, 26240, 35177, 28389,\n 64863, 79974, 60778, 176915, 232183, 45342, 2038, 80253, 41564, 40703, 32689, 5430, 100689, 5366, 23007, 134279,\n 14266, 26712, 73993, 24934, 64242, 52113, 102887, 61801, 46415, 201049, 54251, 62133, 122757, 164883, 30815, 139966,\n 2319, 30842, 766, 13362, 10287, 134518, 86111, 81665, 82440, 28333, 43019, 18963, 8804, 161944, 23439, 102144,\n 101145, 80029, 39052, 248708, 30350, 117340, 11878, 128467, 974, 138625, 63961, 5237, 74778, 61834, 67040, 43814,\n 13690, 65947, 33809, 232476, 115258, 181745, 28824, 94013, 9510, 10246, 93722, 81976, 7217, 114383, 3493, 16014,\n 69045, 72692, 12145, 80981, 9507, 6692, 1620, 60820, 330444, 35474, 33962, 4797, 7053, 295463, 46445, 27026,\n 12491, 77988, 49524, 35675, 90947, 29114, 166705, 101385, 133782, 32704, 6186, 84595, 176031, 185623, 45966, 151302,\n 63069, 1699, 107491, 947, 15458, 74452, 196212, 6046, 10498, 12163, 10239, 35191, 243951, 9277, 9090, 29539,\n 54460, 22820, 26514, 112549, 60372, 51753, 48756, 21812, 70861, 260326, 41, 44222, 10441, 16961, 48148, 138771,\n 216194, 5914, 52153, 53400, 212036, 56519, 26245, 10117, 45888, 15294, 138019, 90913, 26368, 43842, 42111, 23348,\n 6082, 194845, 161089, 156206, 51546, 11647, 30759, 302912, 262094, 8635, 78876, 26535, 35283, 54183, 31183, 85484,\n 147873, 12989, 5197, 6356, 72894, 65347, 20150, 27370, 73787, 1493, 45918, 12366, 190217, 20724, 13858, 10981,\n 67449, 81213, 7553, 14115, 72242, 271517, 11842, 48310, 88743, 143726, 22177, 3290, 243231, 58452, 62937, 12592,\n 1654, 40066, 33477, 13751, 9921, 128442, 15868, 7106, 75236, 83773, 10775, 36938, 10482, 170465, 17368, 17469,\n 161508, 32752, 98340, 800, 19824, 264456, 3901, 87319, 2867, 26782, 9630, 113102, 185815, 24197, 44584, 86366,\n 40224, 3636, 140916, 31731, 267731, 9567, 53678, 72984, 29389, 27963, 17106, 50282, 284911, 60170, 8322, 12608,\n 23374, 89652, 5268, 39044, 229766, 8869, 151350, 31436, 177342, 12269, 183212, 120418, 116270, 2843, 78888, 69192,\n 7865, 184099, 1086, 129897, 18383, 70508, 20242, 18508, 229924, 124569, 35749, 50589, 55626, 9884, 83115, 40971,\n 30671, 18135, 14452, 38861, 17844, 201826, 5549, 26413, 17189, 13561, 38539, 10679, 143331, 3314, 36785, 171194,\n 49685, 187713, 67506, 4618, 104039, 17060, 195080, 50648, 33159, 19238, 67559, 134840, 28599, 157523, 17130, 38064,\n 117398, 94355, 31918, 13575, 34538, 40326, 13997, 3494, 348283, 62481, 26862, 3603, 104426, 244363, 153709, 112487,\n 304612, 199674, 41239, 35545, 54869, 293005, 28223, 26277, 26899, 4533, 18518, 15492, 38587, 80488, 70485, 160395,\n 263, 60162, 11382, 222152, 4696, 250751, 51921, 182609, 10707, 48463, 46243, 1227, 49111, 111564, 46502, 33342,\n 56846, 68541, 63559, 858, 139927, 16654, 229375, 76759, 26478, 33205, 95828, 23399, 92945, 2637, 35630, 28470,\n 143992, 50214, 14174, 21456, 166191, 65665, 1711, 21594, 78019, 97599, 111701, 36, 147151, 110246, 189022, 43021,\n 30397, 40757, 131935, 42065, 73335, 48039, 26596, 28984, 15102, 2361, 7421, 202167, 69744, 43766, 52826, 3642,\n 83304, 33873, 75140, 63169, 192389, 36551, 92748, 13039, 123959, 233220, 21738, 84447, 77230, 20228, 187852, 19095,\n 25799, 92136, 108774, 29237, 53947, 2299, 118106, 2687, 8830, 42331, 202924, 33667, 2023, 73763, 30704, 19363,\n 19779, 16737, 35629, 48081, 24068, 101013, 162338, 291912, 13749, 24745, 328289, 167679, 70086, 48299, 23306, 16732,\n 17801, 43322, 54589, 3586, 63653, 43624, 53474, 925, 109177, 251316, 43805, 13082, 19511, 86565, 142182, 92461,\n 17117, 101033, 103319, 64589, 4022, 4351, 235897, 5352, 82705, 107142, 46391, 156084, 5860, 61365, 10558, 13045,\n 7717, 18357, 33922, 12590, 33065, 6928, 46993, 783, 46937, 67846, 8952, 26295, 6107, 119656, 18799, 17458,\n 50747, 4229, 179559, 112727, 118080, 20683, 41464, 125468, 51560, 49749, 44231, 7359, 35339, 62988, 136487, 67015,\n 5208, 29150, 24956, 105186, 48858, 6143, 18097, 6972, 16404, 73489, 58742, 97196, 36357, 164616, 5834, 32267,\n 13746, 147733, 15113, 132091, 34127, 106298, 39729, 106426, 22294, 9780, 15602, 36213, 71502, 42808, 66802, 599,\n 60755, 5851, 39120, 67363, 108623, 126368, 72770, 91263, 32486, 30596, 151717, 7951, 52002, 43103, 11768, 68942,\n 40901, 39344, 24037, 127500, 116890, 48403, 16926, 86750, 17745, 48648, 159545, 34460, 58419, 5634, 114317, 67865,\n 31462, 23352, 24010, 98185, 125708, 69686, 68337, 13610, 26271, 70691, 2980, 4768, 27225, 102402, 75453, 28106,\n 8104, 6931, 1176, 6274, 6475, 112635, 22498, 6176, 238686, 26832, 28893, 90319, 14441, 15682, 15087, 39517,\n 45270, 109134, 104440, 45965, 47645, 81772, 7876, 52683, 87720, 12898, 4505, 185665, 2769, 113401, 15664, 57592,\n 105229, 137381, 97059, 119268, 6876, 43309, 33886, 128363, 35476, 144249, 67013, 143587, 83367, 25703, 91436, 59347,\n 53236, 2289, 16519, 19844, 46309, 58558, 99834, 23313, 218816, 231303, 36388, 51333, 183535, 109792, 139277, 54306,\n 90139, 18235, 8275, 32710, 37677, 82464, 86025, 92204, 88842, 117723, 37570, 128723, 234242, 76350, 73795, 34896,\n 148247, 58424, 11105, 11744, 45746, 63372, 17118, 49772, 199520, 81902, 38004, 22911, 33752, 3125, 1995, 53792,\n 4689, 26909, 108150, 146062, 69674, 41811, 161444, 84855, 8999, 28561, 16731, 93937, 3189, 21967, 24890, 22943,\n 1356, 145300, 51569, 28802, 517, 118679, 31703, 40607, 48098, 108854, 25003, 10233, 73969, 177495, 5248, 24516,\n 215347, 146192, 48712, 60626, 69188, 40735, 5866, 586, 101541, 6509, 47590, 52129, 5969, 222045, 110933, 25733,\n 24223, 65339, 62812, 2414, 155418, 35819, 16022, 78423, 43138, 20995, 128255, 240673, 46745, 236093, 72176, 57085,\n 97841, 61248, 107, 36068, 193177, 105427, 55726, 215229, 20446, 47228, 100420, 87091, 14429, 121708, 23605, 21157,\n 187721, 21880, 2997, 203976, 99166, 95068, 25877, 7724, 98925, 83401, 4829, 13182, 18229, 13718, 239662, 38653,\n 116505, 153497, 30589, 89029, 38962, 181302, 43853, 78872, 180301, 4786, 248240, 7401, 106136, 112590, 77745, 19731,\n 60880, 77789, 125748, 135487, 5975, 48627, 34084, 12419, 215770, 47557, 254582, 10364, 106495, 21856, 67539, 88981,\n 38805, 21428, 48732, 42316, 12149, 16078, 52808, 25327, 51322, 33850, 51147, 12253, 122354, 46077, 56483, 254553,\n 115417, 81834, 150991, 94662, 86668, 7381, 12841, 100650, 18218, 15741, 22372, 68294, 50705, 15535, 84660, 61887,\n 22553, 72299, 31361, 24824, 17743, 46820, 64288, 31582, 77006, 111674, 116384, 30760, 80920, 86149, 77192, 51979,\n 79691, 60342, 122805, 103800, 240873, 160744, 233114, 78962, 54920, 8608, 3484, 316104, 72548, 24337, 5088, 230040,\n 21926, 10172, 36838, 26, 86221, 83458, 102176, 12062, 17571, 41929, 41170, 28428, 68239, 41750, 103930, 2634,\n 18313, 53019, 34825, 97837, 63115, 24606, 73157, 152474, 14715, 91439, 37033, 109806, 140259, 30668, 174760, 380,\n 135597, 95673, 136073, 65073, 134249, 13829, 17279, 122305, 4420, 46444, 10237, 64848, 203623, 70728, 10349, 182885,\n 65075, 24519, 25783, 40318, 34139, 22222, 63394, 55266, 102764, 41422, 20126, 65100, 90408, 53640, 35128, 48932,\n 11192, 38935, 96839, 34782, 39492, 19396, 41332, 6250, 5511, 19492, 51304, 25936, 104466, 54099, 73771, 86115,\n 5080, 7669, 30891, 111700, 13931, 25276, 72289, 135447, 14820, 258641, 25265, 31005, 281179, 75286, 393, 95359,\n 14623, 13584, 6680, 101227, 80173, 44933, 76666, 54542, 13244, 39348, 458, 25379, 109451, 134348, 81143, 6959,\n 65554, 12027, 51311, 8716, 57589, 140731, 28467, 23316, 17272, 30458, 25980, 55229, 77197, 83798, 28302, 114784,\n 7428, 34548, 26241, 14712, 39336, 103304, 18928, 54080, 12870, 334, 87722, 15208, 16895, 142098, 114262, 39820,\n 83913, 57817, 28682, 7721, 14900, 108672, 11250, 62246, 42849, 415188, 1724, 26555, 24549, 25505, 26443, 107450,\n 145899, 61035, 43528, 6901, 60726, 65906, 267741, 21338, 147590, 42079, 18924, 73017, 135236, 15393, 5206, 4026,\n 84185, 1531, 5988, 113890, 82647, 303391, 7386, 69844, 71611, 189865, 76523, 31877, 13315, 19314, 198575, 32821,\n 1928, 67641, 25913, 104475, 103489, 3297, 70391, 18406, 15446, 113347, 19295, 93790, 27856, 1792, 167471, 116449,\n 8541, 4408, 41757, 63233, 25765, 86680, 64501, 27034, 24816, 34975, 6079, 4486, 49693, 36229, 16917, 21581,\n 62426, 27862, 11612, 54284, 35702, 194034, 355, 24277, 48262, 87411, 70504, 310164, 118018, 12516, 47559, 43502,\n 57433, 107139, 9290, 66533, 80863, 14634, 34312, 91725, 28606, 21342, 67241, 72355, 43244, 375789, 37402, 174015,\n 105070, 8342, 44167, 67494, 1890, 16365, 11723, 271002, 1865, 47918, 8350, 45564, 27742, 25110, 125803, 8553,\n 49504, 81925, 62211, 4534, 15491, 19011, 80373, 206920, 667, 102405, 128623, 245524, 5553, 113309, 192739, 65766,\n 19567, 22832, 261958, 29679, 21293, 71134, 20962, 105123, 24721, 860, 21752, 33448, 18372, 157167, 94822, 35770,\n 173224, 232737, 75729, 28937, 46828, 28062, 25453, 5207, 140366, 36665, 30652, 6169, 67920, 150458, 92040, 23186,\n 184604, 92330, 20891, 176492, 49427, 27828, 38305, 42495, 143982, 49560, 25503, 90043, 29747, 65328, 47830, 12932,\n 11068, 77721, 9003, 25213, 94205, 140426, 46090, 89945, 138173, 192691, 33329, 112232, 129905, 35709, 27514, 1841,\n 19957, 31411, 127476, 53572, 17497, 173549, 55063, 175135, 19841, 69314, 5192, 237921, 117660, 150697, 4060, 273045,\n 50414, 98940, 65348, 153665, 164423, 58804, 156695, 48994, 213928, 86036, 28608, 8355, 39574, 34540, 16927, 135680,\n 18374, 151587, 10830, 53805, 16878, 16623, 4282, 48030, 8537, 14986, 46102, 13062, 72897, 72, 33050, 108227,\n 39451, 45935, 651, 113320, 40535, 95176, 57450, 48843, 5003, 19019, 10407, 211163, 3848, 1068, 4988, 32091,\n 30095, 41692, 15099, 43602, 107434, 50744, 7627, 171349, 16313, 150832, 352665, 207750, 33937, 38256, 51091, 156000,\n 87889, 90663, 84175, 24908, 114900, 50365, 31494, 83829, 5398, 169342, 47521, 54818, 18935, 8356, 43094, 41212,\n 174536, 10082, 92550, 6678, 60614, 23355, 69721, 14796, 34149, 128830, 58187, 3179, 208, 40325, 28399, 225029,\n 401412, 51150, 31580, 207268, 6657, 10993, 69818, 64282, 289845, 23308, 12961, 38447, 6681, 52944, 31855, 2572,\n 47646, 120728, 179148, 37240, 45196, 218274, 4816, 3695, 21961, 50084, 35209, 18073, 51452, 27004, 6100, 33941,\n 1377, 84831, 171214, 85, 141510, 9078, 99227, 32610, 6417, 11718, 49868, 65579, 87902, 73018, 49062, 46280,\n 61742, 21512, 40862, 107733, 15941, 29168, 157765, 144919, 14487, 5767, 158014, 140070, 7241, 573, 71584, 16921,\n 223566, 40331, 179473, 35081, 47926, 140885, 41508, 52104, 59180, 42310, 32811, 29048, 123517, 102413, 80208, 10104,\n 14746, 12649, 153641, 126022, 37965, 113017, 4171, 83, 142592, 2809, 6362, 50416, 71323, 116894, 260776, 16204,\n 1524, 5760, 30351, 12658, 20703, 54403, 36083, 45408, 74772, 4946, 14485, 50759, 111222, 10890, 2195, 167147,\n 92962, 130534, 16283, 177256, 35016, 15472, 210156, 151187, 73922, 117691, 43250, 52051, 37392, 24811, 24358, 30830,\n 5775, 818, 21969, 1476, 127322, 151783, 58392, 31021, 106913, 65215, 89407, 90802, 28531, 11690, 20234, 95249,\n 44602, 37256, 18707, 11928, 5161, 4410, 26571, 51903, 49768, 22008, 25252, 65780, 209499, 68769, 203726, 13249,\n 137363, 48845, 86823, 6658, 5674, 31881, 1083, 1823, 108676, 34518, 166752, 13791, 14287, 91576, 91429, 8665,\n 11529, 26401, 16191, 91972, 30964, 5254, 28486, 54697, 79613, 66520, 18447, 22870, 45203, 194466, 22822, 51703,\n 12278, 76716, 44595, 73455, 33546, 12235, 144843, 36154, 51247, 11116, 33040, 3180, 225753, 60864, 1972, 28469,\n 12891, 28879, 10338, 144157, 56294, 353058, 38302, 41447, 87532, 110616, 27065, 168438, 6557, 1213, 50804, 144643,\n 24817, 2390, 136531, 38174, 247513, 16190, 4059, 122791, 131994, 137430, 39506, 57650, 16305, 5188, 54309, 106128,\n 20628, 88071, 67394, 395446, 250285, 66176, 91254, 1399, 114196, 43915, 60230, 44853, 27206, 106353, 43013, 18733,\n 345105, 226453, 51202, 16607, 57106, 117175, 35492, 10476, 89598, 127439, 15187, 39624, 13688, 61570, 10615, 31111,\n 59370, 6238, 175252, 32143, 224492, 41388, 95408, 34384, 148238, 78307, 38959, 9340, 160091, 61443, 15737, 11216,\n 41244, 170, 38299, 102443, 113097, 26382, 14027, 33707, 3957, 76300, 66160, 19431, 18900, 6952, 1717, 108656,\n 82206, 188021, 257335, 27295, 43999, 41210, 31777, 46956, 57457, 12657, 11489, 15697, 48060, 204748, 53583, 82422,\n 284790, 30503, 137341, 8120, 19615, 220311, 15991, 10217, 63424, 9808, 67431, 70976, 98221, 4491, 15177, 28535,\n 144789, 751, 13230, 2394, 1504, 33977, 132104, 30316, 22230, 931, 97193, 185240, 24826, 22687, 174322, 15307,\n 22988, 1390, 188745, 180325, 29580, 59068, 74903, 18994, 29195, 79, 15436, 7622, 38462, 11566, 138710, 44828,\n 45774, 37768, 99236, 68137, 84083, 19282, 22698, 17134, 74807, 126662, 173497, 46248, 16938, 119735, 3212, 28292,\n 213652, 49013, 9975, 32180, 45660, 86250, 4801, 68788, 95490, 77482, 113751, 11994, 44624, 94452, 46839, 128497,\n 100316, 5798, 58588, 73184, 202987, 65417, 37790, 88524, 1606, 43156, 97964, 105717, 34947, 11203, 100060, 37742,\n 130074, 93653, 107799, 94311, 196106, 41347, 8035, 10780, 16390, 27883, 118236, 167395, 1979, 25006, 19375, 31628,\n 18916, 144723, 78502, 114047, 103107, 86492, 107686, 5844, 20934, 206963, 23556, 22591, 16562, 146333, 20167, 10471,\n 117434, 33085, 2863, 9740, 36669, 41849, 37271, 22790, 18209, 28979, 8231, 12952, 54408, 21731, 25130, 45208,\n 55748, 138120, 75826, 414, 29593, 9925, 292865, 25999, 683, 123149, 7036, 92159, 86055, 61827, 103680, 23176,\n 54918, 58466, 57578, 13305, 5709, 86479, 16697, 31064, 17660, 200919, 10770, 49793, 33423, 32370, 52047, 16488,\n 62555, 6459, 8426, 83493, 7763, 59725, 82812, 18628, 67760, 79405, 68557, 9612, 7673, 28102, 56517, 69620,\n 171797, 32458, 29541, 15870, 81109, 32080, 207644, 71495, 21202, 11039, 91036, 61230, 2810, 130800, 32260, 4613,\n 60590, 37112, 75214, 33979, 126402, 155062, 30642, 63875, 12810, 194463, 82799, 47664, 16725, 36685, 43367, 61099,\n 449, 172150, 102867, 21691, 301838, 36745, 7130, 18671, 57316, 34852, 38034, 54182, 35578, 65900, 99486, 19771,\n 3456, 2658, 16914, 99866, 28390, 28109, 8262, 21147, 34353, 20006, 4228, 137085, 1675, 203023, 283196, 198286,\n 214375, 163329, 290603, 152574, 40471, 83506, 30068, 14730, 23177, 131539, 34759, 27668, 32178, 71896, 104799, 116305,\n 85430, 119262, 42860, 25160, 8911, 23428, 49437, 105322, 6519, 16203, 6349, 74711, 1230, 38045, 8540, 75165,\n 44736, 25909, 51026, 317034, 4984, 32281, 91312, 27060, 44431, 17817, 45363, 155937, 239085, 35697, 59784, 91993,\n 29531, 126740, 213757, 76560, 167776, 285273, 24262, 8237, 65030, 41160, 74437, 48804, 118916, 13159, 37842, 1031,\n 75349, 1478, 11655, 108777, 23435, 277425, 101734, 67469, 70231, 124711, 43532, 28514, 65526, 54956, 1000, 21882,\n 17728, 25302, 40952, 52214, 149632, 1999, 2111, 3259, 63362, 89961, 220561, 39777, 26335, 9063, 10572, 12416,\n 34551, 34623, 38604, 24723, 5947, 15588, 69927, 66252, 119177, 69173, 46629, 28714, 70715, 212408, 20521, 406913,\n 74380, 11716, 50659, 50862, 37009, 88460, 130101, 7210, 53853, 538, 65120, 151950, 55806, 163748, 52837, 13153,\n 21100, 16674, 64536, 6091, 138201, 44837, 58547, 3723, 163, 2177, 32288, 85454, 34033, 8497, 14282, 25742,\n 10535, 10741, 79559, 117493, 243787, 49337, 100718, 79495, 40139, 42956, 7551, 55433, 15421, 31509, 23034, 45081,\n 547, 61176, 53434, 328001, 8470, 36263, 30145, 4519, 74173, 53935, 11845, 73774, 60211, 78025, 3, 4102,\n 73782, 109293, 315332, 48412, 26683, 13714, 6865, 20128, 18490, 104141, 325, 39470, 171970, 115860, 15707, 7268,\n 73301, 74336, 31370, 2368, 111827, 107757, 136231, 142844, 97138, 96638, 84053, 38691, 23801, 1588, 10573, 122098,\n 77039, 240, 186135, 146101, 11996, 18143, 112963, 46171, 155836, 348769, 47795, 121213, 116266, 132515, 3344, 144804,\n 31286, 99187, 255838, 129694, 35894, 48779, 55235, 148582, 71967, 65282, 15174, 13920, 47080, 6147, 108242, 157593,\n 125025, 7136, 1286, 28957, 127956, 28402, 98813, 20805, 7532, 109417, 40610, 5041, 32958, 15142, 18408, 108596,\n 33543, 50517, 27748, 80114, 233434, 91447, 487, 37094, 100048, 30541, 43477, 10639, 89862, 155868, 37667, 8726,\n 60684, 237903, 73408, 99589, 12190, 38739, 97348, 3914, 13594, 2680, 149016, 13907, 30171, 28343, 23530, 115225,\n 61104, 35821, 147679, 14337, 4297, 244282, 24085, 326976, 56428, 7851, 21303, 131620, 71446, 83253, 68692, 111870,\n 5224, 15813, 38197, 49026, 45057, 13660, 3306, 76345, 40671, 27905, 91072, 996, 68527, 62085, 91351, 122634,\n 55109, 168209, 2024, 27560, 112707, 17352, 8306, 167115, 169921, 166958, 5031, 46020, 11844, 67284, 19130, 76185,\n 6920, 32849, 5450, 14610, 22451, 21002, 17392, 31872, 66682, 84796, 13709, 40210, 59898, 12029, 8719, 53564,\n 21462, 91884, 21647, 88379, 194428, 12754, 37797, 132826, 160016, 22567, 54383, 53186, 77611, 31107, 8339, 4694,\n 19185, 90355, 23597, 17222, 140675, 28442, 23668, 55977, 9128, 61555, 28774, 155229, 17658, 9390, 24379, 69357,\n 15752, 127381, 239631, 62460, 93181, 55913, 45133, 140155, 18676, 25249, 33164, 29581, 82837, 67223, 22362, 29975,\n 7317, 52813, 1943, 29613, 20012, 207130, 49617, 49651, 5636, 15334, 36313, 29226, 28084, 95247, 72072, 19000,\n 224932, 15811, 114, 32127, 38097, 37508, 88507, 37225, 27359, 91626, 12193, 69279, 20608, 11055, 88156, 92808,\n 2152, 57259, 55275, 72789, 24475, 104414, 1708, 9882, 3818, 48661, 66897, 1631, 34806, 227930, 85815, 87753,\n 18321, 250664, 72733, 25107, 206797, 50891, 8082, 196411, 92596, 96764, 152823, 65514, 22819, 387277, 62176, 51225,\n 40329, 15563, 189, 3659, 73670, 64357, 51793, 275136, 33482, 86653, 74615, 67058, 11318, 125720, 15388, 22388,\n 8267, 1730, 102663, 170910, 40784, 7144, 85373, 13040, 7088, 94309, 583, 44224, 140424, 77439, 18496, 164026,\n 36578, 4722, 9151, 5824, 63365, 26510, 35199, 40500, 79277, 32495, 44614, 35233, 9566, 203293, 152144, 7097,\n 2330, 183480, 98629, 13423, 330887, 44130, 68600, 30939, 97829, 31012, 345465, 56747, 94879, 4939, 160027, 149761,\n 99423, 46099, 32251, 15332, 8761, 96094, 128555, 5763, 235318, 222223, 55729, 30241, 55420, 201746, 3987, 81382,\n 8259, 49325, 23287, 7719, 24633, 251100, 92311, 18591, 110533, 64759, 170260, 393860, 7175, 21144, 132887, 3593,\n 75346, 101277, 91109, 16387, 259187, 11627, 57459, 173829, 44694, 55780, 49797, 89192, 120443, 62622, 3904, 14814,\n 23887, 1027, 112258, 64955, 99800, 11132, 66353, 36202, 48624, 18158, 88481, 96882, 43059, 11040, 2455, 7077,\n 21651, 181159, 99126, 100434, 61388, 68186, 19161, 110468, 120052, 8819, 55324, 41494, 7014, 37689, 3618, 87729,\n 92615, 207943, 9823, 128657, 12587, 15857, 6379, 67628, 51216, 71775, 157617, 63244, 1503, 3864, 218754, 110864,\n 5769, 21492, 7243, 1192, 87921, 85529, 31512, 18537, 42698, 35350, 73510, 84474, 34301, 8991, 21013, 35034,\n 566, 38832, 19838, 35586, 37216, 39413, 55006, 12178, 59742, 856, 84563, 6900, 25632, 17437, 49786, 30723,\n 13847, 70845, 4044, 7843, 23944, 235976, 55530, 48942, 6518, 20939, 73769, 192653, 52936, 95207, 23895, 132542,\n 142982, 22632, 87452, 48042, 54018, 178468, 10728, 26230, 23559, 363, 81269, 142012, 5718, 346258, 31456, 84333,\n 246476, 51018, 66692, 101804, 120570, 39962, 30373, 70593, 2864, 60541, 19425, 54209, 104092, 7201, 31545, 48018,\n 25865, 15442, 46257, 40443, 8328, 6451, 111782, 47527, 97754, 33046, 470, 245116, 31095, 39, 91934, 87208,\n 73470, 36708, 36521, 12801, 70624, 36272, 8892, 79768, 12427, 55454, 103756, 5908, 52390, 62962, 22720, 141138,\n 94634, 41689, 128402, 126390, 6628, 106394, 35527, 134394, 82727, 254651, 194502, 148064, 89549, 3202, 28359, 957,\n 21954, 27906, 49840, 142747, 8307, 24206, 48978, 1186, 71728, 133038, 71474, 91306, 6333, 110959, 74600, 70387,\n 18983, 62609, 56057, 22970, 1147, 135850, 1321, 28834, 3578, 59715, 102227, 32827, 81415, 99952, 55636, 257598,\n 390, 22702, 35701, 85872, 402916, 39216, 189795, 14929, 19467, 10112, 144422, 61514, 5279, 63421, 134686, 41436,\n 8424, 51925, 10598, 132295, 124416, 4604, 194739, 210929, 57866, 31829, 51626, 50007, 9976, 91878, 61906, 56168,\n 81906, 60918, 61859, 40017, 23059, 16887, 40927, 62064, 12785, 32893, 32913, 21782, 93965, 20169, 44387, 79084,\n 38463, 11457, 93950, 27127, 157050, 2697, 337088, 5116, 54128, 48255, 33279, 8821, 27352, 25515, 124022, 65710,\n 28906, 38557, 33390, 1722, 104435, 72215, 38551, 12094, 30978, 25113, 6671, 37355, 175109, 42862, 98024, 65406,\n 221276, 59624, 118012, 64637, 78760, 86697, 21426, 1639, 40350, 12584, 67193, 84144, 31396, 7863, 143011, 69629,\n 63112, 9454, 28666, 65798, 46372, 134721, 6314, 51402, 30837, 151922, 2847, 38676, 38008, 92823, 136245, 17540,\n 5504, 109295, 205242, 37606, 5211, 214892, 1586, 20670, 208711, 137743, 19328, 40652, 16995, 20023, 14657, 154919,\n 34422, 12996, 13918, 38221, 47690, 16398, 2959, 37680, 89122, 6721, 198469, 91876, 172043, 83898, 101992, 26084,\n 94570, 3635, 76958, 22853, 76497, 38266, 176590, 168403, 44464, 142840, 79180, 184594, 1984, 41806, 83147, 11985,\n 6546, 366068, 59732, 24533, 271505, 8736, 39084, 222992, 93429, 28962, 58985, 86665, 8432, 30028, 14548, 32439,\n 54424, 165029, 55175, 27458, 69046, 121277, 46168, 33732, 20661, 24581, 135574, 123110, 37556, 79260, 72611, 16957,\n 12939, 46162, 58238, 44907, 72936, 253758, 41324, 32518, 96480, 11949, 124438, 65280, 43256, 34107, 53533, 43531,\n 37037, 28366, 45970, 32741, 173438, 6121, 194202, 62969, 26355, 30314, 58370, 28455, 1848, 50519, 82830, 90393,\n 21761, 295490, 10936, 256940, 133568, 44050, 20269, 4089, 27457, 21610, 219460, 36743, 14821, 101388, 52005, 13124,\n 30979, 140816, 167362, 26054, 18458, 60789, 34917, 40447, 26606, 33422, 9066, 3452, 83614, 5761, 20263, 137238,\n 25038, 91310, 101, 52322, 74548, 42572, 38084, 214054, 186568, 31802, 17665, 30620, 141936, 37730, 14420, 4265,\n 187218, 49640, 188208, 51441, 55388, 96452, 66659, 40869, 42039, 60967, 221027, 19234, 178581, 29105, 96050, 9165,\n 196118, 157335, 3738, 40354, 117436, 2965, 34136, 59659, 15570, 50843, 230035, 31444, 71260, 43886, 18316, 5387,\n 38500, 168508, 17406, 32174, 8828, 103373, 143806, 90367, 3560, 18719, 122310, 16508, 26719, 2541, 105429, 6645,\n 37998, 73190, 10591, 235916, 49737, 87112, 233941, 53188, 32193, 79154, 4544, 52905, 126477, 7580, 63501, 57314,\n 3216, 31337, 6541, 103083, 60846, 49, 9756, 15481, 1355, 43840, 14319, 13743, 27486, 10222, 73114, 230718,\n 418644, 16706, 6674, 279748, 23058, 45273, 295831, 86306, 2743, 5535, 88773, 21829, 35253, 120938, 31153, 3169,\n 16839, 42847, 8751, 80974, 33942, 36867, 35514, 16485, 26474, 77775, 56877, 5391, 48346, 3882, 108713, 31403,\n 27804, 55248, 26235, 43821, 136104, 40118, 175507, 28034, 203908, 18732, 1788, 34030, 106427, 36958, 54359, 7251,\n 44936, 15356, 69139, 455, 157915, 22173, 140291, 50348, 43275, 82066, 49621, 54952, 15216, 36226, 96695, 66855,\n 6936, 1987, 8227, 196087, 4631, 68827, 99004, 47541, 110265, 17953, 147605, 110242, 58520, 31312, 38724, 329975,\n 642, 3155, 34497, 75937, 6207, 73843, 6120, 17249, 51429, 117746, 3218, 910, 68961, 319671, 14938, 29555,\n 34700, 1649, 66673, 72268, 9655, 76800, 153087, 6941, 210168, 27130, 35398, 1780, 73242, 3135, 56689, 19556,\n 165307, 8765, 35967, 121458, 13333, 70453, 17350, 117253, 22265, 13340, 44265, 39869, 441, 3742, 135025, 23581,\n 33309, 16543, 17731, 13291, 157637, 283005, 21408, 101360, 63887, 52312, 83873, 5338, 233779, 23759, 186949, 34531,\n 177320, 38069, 156465, 91004, 19353, 59852, 68160, 14891, 1338, 1072, 29823, 1950, 28901, 81407, 313445, 73038,\n 84807, 162348, 240257, 37162, 138934, 16111, 58013, 41253, 102951, 16457, 96056, 19541, 56402, 67217, 41638, 94381,\n 89674, 29481, 37456, 80815, 151579, 13937, 13683, 132537, 19699, 134545, 67020, 29816, 222341, 141235, 427578, 48868,\n 129557, 233342, 23077, 87871, 16213, 18728, 16184, 9469, 37913, 19680, 2798, 171356, 178328, 13216, 50049, 72690,\n 71904, 124644, 55455, 7504, 29052, 41036, 266546, 19899, 30391, 188755, 8659, 59469, 16, 104298, 112943, 53865,\n 76203, 138226, 68857, 139953, 14125, 107625, 119795, 173133, 4398, 50273, 48808, 54390, 16466, 122086, 31835, 67035,\n 50971, 48859, 7508, 46427, 66477, 73021, 84615, 39985, 83076, 46779, 201569, 53336, 36443, 60865, 168164, 143810,\n 51393, 25548, 169307, 32896, 24485, 38424, 21837, 29087, 275813, 51674, 6714, 64883, 46169, 187369, 55186, 76192,\n 12852, 12018, 62134, 31067, 118303, 16542, 12125, 10579, 4928, 26291, 43854, 7091, 10946, 253716, 109062, 39283,\n 17261, 113012, 258512, 47764, 125126, 32646, 55892, 80279, 201623, 149872, 3192, 385, 1208, 48750, 5376, 58738,\n 22335, 5427, 82416, 47811, 32435, 143086, 38930, 94128, 59975, 156037, 37977, 38224, 62485, 7698, 50405, 71027,\n 16462, 21559, 136153, 34131, 107506, 162069, 63703, 3101, 215029, 40407, 4178, 3774, 9187, 80019, 17880, 97926,\n 67579, 2600, 18405, 8351, 47924, 86638, 70820, 92206, 86453, 29610, 42241, 119200, 3198, 15466, 67813, 57863,\n 35454, 4779, 99518, 4649, 104641, 144269, 33730, 38073, 65864, 6838, 109456, 193298, 154007, 5623, 45741, 30846,\n 182578, 25573, 157224, 1543, 58575, 138703, 146140, 44971, 49356, 18275, 59064, 20300, 13122, 11848, 24453, 11973,\n 9797, 86843, 2919, 25530, 49210, 1130, 161220, 76788, 75373, 85604, 34926, 36014, 17777, 17255, 51533, 11676,\n 92226, 51845, 119859, 21525, 5936, 18507, 28050, 1140, 31418, 14857, 34207, 47859, 10750, 36382, 32079, 106909,\n 59426, 87757, 38393, 110042, 15965, 97104, 33757, 35344, 97993, 53979, 33651, 45407, 41884, 82515, 173089, 7177,\n 58371, 35365, 47543, 51927, 35587, 10670, 23544, 29306, 84233, 39976, 76076, 62097, 9007, 8668, 28119, 78281,\n 120790, 19835, 143020, 54968, 18670, 64959, 20649, 34469, 42570, 33001, 136570, 87796, 120044, 1106, 58700, 63951,\n 127623, 12805, 83057, 40212, 31773, 49850, 7361, 54336, 347524, 101314, 23751, 19569, 48791, 29174, 49369, 20467,\n 7465, 75842, 38281, 623, 112457, 60210, 28849, 51003, 94720, 6426, 90047, 85560, 43761, 3579, 85105, 34607,\n 90410, 118528, 7224, 42907, 111163, 18168, 6960, 161135, 191298, 5247, 100584, 127552, 171568, 20121, 91173, 12636,\n 54615, 20199, 63730, 98105, 2396, 40387, 14438, 125012, 4765, 33235, 12865, 45299, 37728, 82098, 77872, 114037,\n 59253, 19675, 24838, 398016, 102561, 11446, 17069, 57508, 178277, 65836, 99941, 26114, 2585, 271882, 136866, 50126,\n 11027, 155648, 118367, 14585, 8910, 123015, 335383, 40434, 41016, 53021, 14439, 87098, 176860, 201543, 121888, 2358,\n 9286, 5739, 22666, 54270, 37884, 169381, 33984, 93859, 16124, 89364, 72207, 51639, 76366, 99029, 65812, 2198,\n 12147, 174891, 194289, 6986, 30252, 88822, 21284, 11445, 288337, 160821, 33034, 100869, 43852, 25761, 52882, 1144,\n 103809, 1924, 84458, 86079, 43411, 13542, 139276, 18141, 34978, 41298, 7276, 26481, 173800, 33210, 17951, 142652,\n 33616, 33677, 2210, 19941, 98568, 2486, 192414, 80136, 12058, 235883, 50963, 249638, 29572, 27221, 47034, 6124,\n 72107, 63346, 97620, 158513, 299699, 40388, 23235, 37176, 224244, 198386, 121323, 67992, 23827, 63170, 17838, 106622,\n 158590, 26807, 5345, 23489, 91891, 55474, 74834, 37981, 13058, 5977, 72552, 34706, 26828, 145172, 19904, 21367,\n 34043, 960, 77092, 91381, 4733, 47446, 7680, 41697, 5170, 16960, 14741, 46101, 13656, 473, 51842, 37433,\n 11103, 11551, 121951, 13191, 97536, 165932, 50397, 51628, 129028, 9069, 44885, 6590, 59195, 47045, 32940, 225472,\n 90345, 21833, 13303, 29407, 96615, 141951, 5198, 6028, 18395, 7181, 3861, 14966, 156358, 167182, 36529, 55253,\n 25942, 173153, 30959, 27261, 50691, 150176, 162201, 38467, 48462, 80602, 42163, 118482, 168, 108756, 26011, 17166,\n 54149, 456538, 22512, 91374, 13816, 90358, 131615, 18132, 226707, 1824, 28139, 26860, 42253, 93877, 77351, 65575,\n 8980, 80574, 22020, 27948, 40422, 91324, 76376, 13528, 39281, 91685, 82215, 122541, 144066, 1983, 193851, 17283,\n 26320, 2739, 194978, 4790, 26845, 42627, 61300, 65815, 174612, 55133, 4200, 191130, 79771, 158321, 52280, 166796,\n 221620, 62461, 11278, 4067, 88152, 83409, 31717, 121367, 13522, 47325, 37945, 10406, 174348, 249321, 154101, 64912,\n 29938, 51775, 17220, 15776, 166138, 78890, 84425, 54121, 42861, 16368, 24572, 291647, 10197, 32073, 22651, 11677,\n 97509, 26952, 35787, 18424, 41910, 71614, 94977, 72318, 41594, 70024, 275419, 37702, 60199, 7335, 39107, 61315,\n 18271, 18394, 33768, 87884, 104277, 123724, 7277, 56288, 71981, 189803, 49320, 3352, 6798, 14240, 8954, 69220,\n 94433, 57372, 28620, 68863, 193727, 85575, 42309, 41667, 67689, 42081, 22543, 44824, 12719, 28540, 114236, 101553,\n 27638, 27296, 4300, 5353, 4663, 19379, 94098, 3758, 95888, 95144, 80344, 87320, 28447, 259518, 12718, 71391,\n 152731, 37063, 24132, 31911, 104896, 15672, 103782, 1521, 4945, 72541, 23717, 122632, 15619, 87175, 206120, 29428,\n 189780, 61416, 28350, 44457, 972, 1175, 47233, 198738, 95789, 41907, 21953, 97034, 59341, 22864, 53713, 16873,\n 32971, 20693, 20954, 31336, 21477, 16169, 38370, 16412, 9019, 3841, 24599, 21938, 17085, 6484, 81198, 76413,\n 5849, 72514, 12320, 65247, 276175, 37234, 59796, 52642, 16312, 57349, 198507, 94148, 46134, 18958, 125552, 1747,\n 18725, 151873, 14901, 5490, 68287, 29470, 3689, 64794, 40814, 26018, 25692, 54450, 2703, 88278, 124886, 173087,\n 174000, 24159, 179477, 24276, 46004, 201876, 209202, 445, 52876, 31948, 30206, 157610, 39180, 18439, 44124, 50469,\n 5774, 96278, 222758, 200216, 50290, 45486, 20435, 46986, 46276, 140133, 142326, 15569, 13363, 47522, 92583, 2182,\n 7135, 16853, 22998, 30272, 4952, 63263, 35623, 39096, 53789, 44864, 20053, 110392, 124213, 4630, 16087, 28221,\n 127787, 25839, 77481, 44693, 13464, 113146, 6983, 27069, 55717, 50102, 4760, 7107, 26186, 66507, 59145, 36032,\n 104182, 71328, 29425, 64317, 50781, 47465, 94298, 69706, 74899, 22754, 120756, 25108, 93077, 56834, 73286, 39928,\n 16218, 41699, 176763, 7555, 70819, 50083, 26895, 23315, 26014, 16773, 123079, 41712, 5719, 31516, 90427, 158540,\n 85051, 183128, 40864, 27505, 55392, 9058, 45224, 96857, 30901, 136622, 96557, 56304, 120061, 11501, 151448, 5773,\n 89743, 7769, 86069, 2935, 18471, 41628, 10114, 33660, 110170, 49479, 26745, 92846, 33221, 26731, 18795, 87076,\n 8550, 2100, 29972, 120289, 3077, 72490, 33784, 2630, 208722, 50861, 63483, 79029, 6419, 39467, 14302, 45286,\n 64207, 9686, 67513, 44170, 1050, 77246, 59266, 17055, 53801, 7150, 11111, 42432, 4278, 94579, 362117, 36175,\n 42902, 41933, 39002, 98489, 22913, 74161, 84773, 57036, 17556, 162288, 74485, 178760, 93867, 73635, 128860, 50362,\n 261, 67455, 80001, 46080, 35662, 4368, 25247, 19230, 74393, 22588, 1822, 27682, 235324, 13798, 85998, 13194,\n 235067, 23514, 71669, 147632, 23191, 134748, 214683, 105101, 1518, 25489, 247114, 7380, 54842, 26922, 3971, 26361,\n 20844, 68642, 170517, 77339, 123255, 8963, 77818, 150998, 48466, 36806, 2732, 23261, 11741, 236162, 18243, 126216,\n 28690, 50546, 16385, 92760, 197383, 246558, 201295, 88255, 67588, 71687, 176076, 172653, 169058, 33906, 63747, 24835,\n 157621, 43338, 30050, 46152, 132741, 2770, 51371, 94835, 6614, 15112, 11749, 56936, 1250, 19027, 399017, 58036,\n 100215, 23388, 55815, 308768, 124152, 94803, 9521, 64186, 8971, 28, 30427, 62163, 7616, 103838, 35079, 29203,\n 131235, 7743, 17389, 10882, 37420, 61460, 228512, 85363, 41581, 131077, 62822, 119647, 10130, 54445, 26925, 19968,\n 29016, 24446, 74028, 24176, 61448, 67185, 9254, 8563, 119129, 9771, 99184, 37716, 39514, 10532, 221512, 258753,\n 218630, 55980, 23394, 32141, 61924, 66749, 32411, 3741, 36475, 26678, 77010, 44946, 91203, 128749, 116953, 20476,\n 49625, 53116, 13735, 102335, 29376, 51946, 83407, 67892, 59212, 34685, 21083, 1546, 112982, 32972, 74397, 1078,\n 190545, 16082, 86140, 58591, 89611, 101531, 10061, 105104, 76319, 20035, 17551, 52611, 169061, 190842, 100780, 23907,\n 90413, 115619, 9675, 34710, 193435, 49443, 129734, 11183, 258877, 16318, 136182, 126808, 44635, 27304, 192375, 2599,\n 125648, 47051, 12091, 23814, 721, 58800, 40137, 66726, 97930, 60877, 74487, 7942, 54326, 9841, 41428, 13762,\n 8211, 85383, 6950, 99177, 79806, 201786, 296464, 124087, 13144, 29741, 41721, 47634, 55088, 254286, 106408, 17041,\n 99064, 12942, 64086, 45233, 14005, 2612, 55827, 255, 7984, 13980, 38574, 12776, 46654, 73499, 249951, 2101,\n 26676, 25996, 132326, 116415, 119062, 50449, 31033, 23038, 11589, 179252, 20007, 14860, 129270, 21143, 17796, 144715,\n 60106, 70758, 69842, 34674, 282133, 44014, 16774, 57268, 38528, 24053, 46373, 201667, 28327, 471023, 51889, 102667,\n 21193, 114909, 84132, 69317, 96723, 67969, 16134, 68145, 15058, 28765, 32035, 2524, 101089, 98664, 25045, 76571,\n 14957, 86040, 118506, 262428, 154764, 81573, 39681, 283900, 73287, 127825, 544, 80448, 52347, 38512, 175971, 15180,\n 45467, 33086, 46552, 48894, 81107, 43213, 36672, 54025, 76703, 8053, 7608, 13299, 56619, 20752, 238099, 54164,\n 105133, 1444, 32942, 953, 37564, 8000, 66316, 119463, 106817, 404, 13667, 149108, 128597, 31267, 10269, 49836,\n 106150, 1484, 52330, 76965, 160486, 171648, 38456, 31263, 22424, 37738, 66245, 67467, 143369, 60471, 75610, 20895,\n 115528, 86070, 60854, 40796, 49347, 18989, 15030, 11371, 37578, 15779, 79867, 10187, 86462, 46402, 155626, 93200,\n 40229, 7090, 57547, 108053, 99598, 11088, 47505, 41218, 206017, 2173, 20988, 30219, 22919, 80563, 57566, 42369,\n 93141, 41675, 2407, 182519, 120495, 27154, 16702, 29456, 14349, 7958, 16688, 117177, 140375, 42467, 261919, 74916,\n 153569, 10836, 34742, 49526, 7621, 105997, 12212, 2270, 392377, 7755, 17959, 25086, 232152, 138791, 33847, 13860,\n 35316, 5811, 1344, 71259, 50452, 207539, 92635, 50359, 5821, 33674, 30255, 2086, 2587, 96264, 17543, 42,\n 6029, 9580, 43007, 139248, 82831, 12917, 29607, 25786, 51467, 42137, 85161, 100698, 31561, 88989, 121990, 278500,\n 3602, 109344, 37982, 15279, 116442, 28936, 30880, 87894, 58079, 128661, 126731, 67392, 28051, 146885, 4861, 16216,\n 97344, 42827, 147561, 153948, 22684, 21335, 47685, 1853, 43349, 15185, 59642, 10229, 25520, 187921, 108972, 5579,\n 98037, 24945, 6697, 19193, 63734, 137934, 75056, 89740, 19767, 224268, 56138, 63643, 151661, 39313, 70618, 84031,\n 89723, 84074, 13703, 85626, 35460, 8867, 64845, 3439, 57906, 99776, 63968, 49270, 81130, 34356, 16210, 23547,\n 36446, 34090, 140028, 72439, 2221, 22163, 57058, 363492, 113754, 18913, 95451, 48663, 54464, 54037, 176097, 68425,\n 3023, 34906, 29482, 117389, 341780, 80431, 58330, 16753, 92616, 60907, 94846, 147486, 4498, 48646, 7773, 46801,\n 7778, 18946, 464978, 47558, 33223, 177444, 7328, 15626, 63337, 94700, 11743, 9351, 255024, 39098, 16447, 42647,\n 96230, 39769, 58840, 10068, 63439, 35800, 65843, 58823, 413844, 9156, 51258, 7434, 61791, 85018, 6872, 3692,\n 28096, 7121, 33024, 6009, 75532, 31997, 192535, 9661, 3304, 9547, 14753, 31987, 25314, 55689, 15896, 20430,\n 39472, 31340, 99744, 25398, 115569, 54883, 28719, 205423, 23071, 57855, 64638, 149867, 25671, 82403, 37616, 20668,\n 39989, 77996, 74948, 140555, 175248, 64810, 36515, 46595, 4958, 248773, 24045, 28728, 136673, 168704, 20804, 114833,\n 100325, 27135, 21205, 96151, 153134, 45992, 7093, 13992, 76047, 1980, 19432, 145001, 75159, 87462, 17710, 1013,\n 45556, 34297, 144882, 20648, 26061, 11319, 129567, 108555, 18872, 464580, 33386, 22717, 65948, 167189, 5603, 135042,\n 79542, 8801, 202632, 18114, 91882, 5973, 5239, 67315, 4431, 60916, 47819, 71693, 32597, 32606, 18183, 45072,\n 80329, 76385, 24749, 51305, 40314, 156514, 14693, 130345, 13168, 66214, 18029, 12858, 34801, 27628, 14544, 10823,\n 40522, 40185, 33739, 148694, 23548, 9923, 61012, 28859, 17933, 19442, 34364, 99849, 164107, 141167, 30629, 21054,\n 6744, 36491, 8096, 42474, 41706, 155060, 30650, 10600, 163442, 1143, 96655, 61390, 52359, 7559, 51568, 64256,\n 203854, 4467, 22453, 14504, 436398, 7878, 6980, 8293, 63610, 293747, 16167, 35763, 19627, 147603, 15419, 18032,\n 110744, 51346, 33681, 54571, 40472, 48615, 39073, 21604, 13754, 173027, 92560, 11083, 47299, 63062, 11813, 52007,\n 29883, 9734, 139722, 15953, 1550, 20651, 13616, 49306, 16113, 90089, 92326, 7584, 30712, 72424, 164858, 6831,\n 152871, 55746, 197721, 34167, 196442, 6022, 112107, 55215, 7538, 123381, 4920, 43539, 77165, 8939, 50392, 34192,\n 20225, 79762, 22505, 58667, 40770, 29788, 97180, 82835, 4568, 8579, 13273, 363569, 35898, 49983, 436, 36598,\n 3237, 131691, 62418, 35591, 8101, 4073, 379438, 65218, 76072, 33887, 2968, 27573, 212619, 288680, 68278, 72851,\n 150504, 217896, 6913, 121339, 22017, 35340, 51072, 43616, 75043, 31437, 10833, 81487, 4364, 22968, 41454, 106687,\n 85446, 19863, 109625, 149241, 524, 141850, 214404, 54376, 657, 237023, 9401, 108137, 53800, 32474, 49712, 53334,\n 126876, 27337, 45552, 177696, 8269, 15036, 12097, 42240, 2328, 125374, 119295, 99715, 2500, 19624, 39441, 27220,\n 102691, 60957, 94543, 39101, 18566, 67362, 13975, 78230, 25017, 34017, 239007, 90027, 39351, 41681, 35354, 43822,\n 1043, 916, 58587, 141983, 94818, 38799, 75459, 41114, 67432, 16195, 36606, 59568, 22272, 126769, 31424, 68659,\n 12287, 134302, 257977, 5756, 207285, 95637, 47248, 117689, 19583, 77451, 22373, 12200, 54993, 117118, 34244, 29386,\n 34562, 53819, 71267, 64172, 77665, 49368, 7716, 59301, 25749, 45426, 194789, 17297, 2650, 1766, 32501, 45198,\n 20403, 20984, 6600, 14171, 94604, 19037, 5402, 29896, 9938, 59935, 109708, 88081, 145182, 44844, 39167, 352626,\n 164173, 35374, 45982, 6122, 154, 73419, 220487, 53834, 53601, 17992, 8609, 229321, 5610, 68098, 66815, 71012,\n 95069, 140968, 27396, 8957, 134489, 24656, 86659, 56598, 134852, 17316, 123838, 255436, 6613, 41610, 138033, 81452,\n 32023, 32396, 123687, 63398, 8693, 29712, 30407, 19296, 121188, 3551, 36099, 20032, 111948, 56624, 16547, 27453,\n 35916, 15378, 52039, 56849, 13489, 22214, 73177, 53097, 277349, 2157, 14029, 187886, 10260, 141743, 246460, 91880,\n 50869, 3788, 49486, 133566, 54950, 33120, 129337, 53768, 18333, 9525, 26902, 312251, 10297, 9020, 70759, 16647,\n 112432, 59260, 84609, 9818, 82766, 73569, 468, 46001, 75780, 55028, 52106, 11498, 43645, 108069, 17150, 17753,\n 29417, 16705, 31799, 9606, 289, 122254, 115975, 8620, 6133, 255357, 56908, 14456, 133464, 43554, 79224, 11247,\n 29630, 160, 12756, 25464, 65960, 350428, 62521, 321796, 100359, 67358, 35169, 46172, 113128, 48988, 88868, 31094,\n 33266, 6847, 60887, 98188, 49659, 69117, 92977, 220228, 13947, 80181, 35103, 62170, 97351, 13475, 2440, 199768,\n 19498, 36597, 46971, 25234, 67806, 62881, 84717, 73648, 181966, 10488, 94149, 21550, 26655, 63436, 48375, 14405,\n 165650, 9621, 24439, 28043, 42735, 4490, 29963, 56674, 45373, 1934, 262446, 50855, 67098, 26898, 5261, 52696,\n 40644, 33900, 9440, 180286, 87162, 22940, 19704, 26936, 69769, 10254, 101759, 27406, 12243, 48000, 73926, 113215,\n 54935, 5726, 192787, 4312, 106216, 9366, 11550, 52949, 23457, 212271, 277152, 133895, 108374, 6191, 96477, 29980,\n 218916, 58024, 54696, 40853, 91124, 65894, 91170, 65908, 252552, 6793, 29212, 15389, 44516, 122515, 52617, 35058,\n 9017, 103536, 39510, 49136, 19242, 130652, 662077, 74699, 47024, 31422, 8517, 73351, 24399, 13867, 128360, 4810,\n 4434, 61779, 111983, 61036, 17798, 110240, 59722, 102960, 39688, 10001, 23803, 23039, 176498, 56659, 44814, 134295,\n 17188, 77577, 74466, 226175, 102472, 154333, 63900, 111747, 18062, 41171, 79669, 32773, 408933, 42562, 28931, 30907,\n 107388, 43487, 2946, 240310, 23938, 24354, 319, 184983, 7927, 6488, 1422, 10790, 68809, 68209, 64775, 4361,\n 202, 17123, 59634, 51200, 44391, 18188, 17843, 2619, 74278, 3230, 9540, 47187, 21702, 36274, 56894, 43907,\n 16310, 34790, 16866, 6150, 5561, 13587, 107545, 108873, 126867, 86986, 28640, 33427, 19017, 5762, 80637, 17430,\n 46903, 2047, 131055, 25958, 13558, 5444, 47152, 13900, 44563, 122857, 45348, 70863, 39593, 54332, 38068, 33637,\n 318, 40310, 143467, 18502, 24520, 11377, 62013, 28942, 27246, 28269, 83545, 17999, 59015, 90707, 30065, 15161,\n 34720, 1263, 37008, 2012, 6060, 98575, 92933, 5721, 299, 199555, 24578, 29223, 2985, 743, 115825, 109523,\n 136657, 47454, 26378, 53586, 3733, 174945, 93340, 244456, 5693, 37386, 28782, 89767, 27545, 23573, 18798, 136425,\n 34320, 84778, 20041, 48453, 38215, 7477, 71958, 40621, 8773, 5874, 187927, 105965, 51100, 43533, 18083, 8443,\n 10180, 43597, 2003, 183999, 69689, 12216, 129696, 146188, 62389, 34044, 68410, 12765, 43273, 26949, 266807, 3345,\n 34477, 79197, 5688, 47539, 213110, 21634, 22257, 50092, 32222, 42346, 39530, 63668, 98, 134978, 74022, 5152,\n 59088, 174145, 37220, 9934, 9545, 118937, 5724, 87240, 19875, 15784, 40143, 23263, 87513, 181654, 285152, 37881,\n 263241, 4966, 43934, 10433, 186657, 6470, 74416, 225854, 25908, 142677, 246262, 32280, 6192, 75890, 45546, 143264,\n 135305, 29742, 47013, 77787, 11732, 126658, 8763, 37950, 21806, 57557, 113464, 89465, 108995, 164574, 23894, 22996,\n 23169, 15369, 23117, 17642, 130607, 40503, 36239, 280990, 44666, 9981, 40427, 147487, 26869, 168452, 32886, 32991,\n 46798, 240839, 15111, 70502, 65697, 88548, 44145, 28701, 48767, 31139, 206777, 35659, 181164, 166262, 14554, 171445,\n 31786, 66523, 76607, 17956, 6507, 31279, 90476, 116611, 167918, 6560, 1243, 115324, 80128, 41867, 55897, 187323,\n 37069, 32596, 189444, 145931, 13390, 105530, 65709, 26805, 6999, 55714, 41300, 22915, 68951, 22138, 21120, 22264,\n 10058, 19945, 33635, 56123, 99085, 10032, 5818, 6016, 46649, 57476, 35264, 94413, 112522, 262288, 93686, 83038,\n 14341, 23204, 28807, 66084, 77987, 6101, 126673, 7133, 38126, 5923, 122091, 170240, 97772, 46874, 215746, 43948,\n 41622, 3272, 55596, 8332, 146411, 251315, 13533, 8561, 81521, 115449, 48616, 175175, 2063, 186556, 3036, 134537,\n 75772, 29728, 82360, 22973, 186559, 86348, 89100, 38388, 82297, 45610, 2613, 87082, 9986, 177812, 57884, 23591,\n 47485, 42543, 33582, 44713, 74439, 257444, 252451, 31825, 35631, 38540, 33066, 5147, 13973, 4343, 51830, 70378,\n 22827, 26448, 95560, 36896, 241741, 48067, 203953, 298860, 61620, 20450, 3220, 67272, 6586, 107662, 100160, 108684,\n 6929, 57226, 4762, 7457, 1320, 40404, 77204, 99309, 62750, 208653, 59977, 44000, 74315, 34332, 5819, 172217,\n 64904, 114077, 18147, 84012, 1791, 98456, 90930, 21446, 116669, 103938, 7422, 85140, 59713, 5768, 326211, 16239,\n 75411, 13229, 29398, 10758, 236107, 1539, 112472, 95979, 152154, 151294, 306, 21196, 38146, 10700, 6891, 84282,\n 109646, 56492, 40539, 6589, 119491, 51354, 30685, 140209, 136906, 29622, 73617, 49553, 70525, 51671, 166869, 139616,\n 74395, 37439, 49595, 45678, 11959, 33211, 86560, 52434, 9282, 62690, 112155, 130810, 5243, 108261, 99970, 265613,\n 72551, 80049, 6391, 33365, 90721, 66737, 69872, 87011, 1860, 9032, 112544, 60905, 37371, 89015, 140351, 19076,\n 850, 373531, 2802, 36725, 218795, 72062, 28990, 16550, 24614, 7815, 6187, 26336, 33373, 32162, 42791, 73555,\n 32062, 23386, 10244, 56392, 49442, 27076, 136262, 12412, 14883, 1134, 33675, 97153, 199281, 15608, 100152, 74072,\n 47942, 254301, 36451, 16026, 10687, 65067, 56708, 254030, 30290, 50490, 13864, 57941, 259331, 35588, 23485, 43486,\n 24869, 21620, 92971, 22072, 88645, 1048, 182050, 13343, 32452, 14825, 19509, 3325, 216938, 45740, 99716, 189082,\n 53740, 78245, 25609, 24311, 176777, 47340, 308354, 40669, 66085, 14102, 125339, 9225, 128709, 97207, 1271, 200933,\n 78439, 113451, 88975, 18324, 46521, 11819, 18570, 141756, 72512, 170020, 52754, 63550, 118515, 103073, 93330, 32736,\n 50499, 14722, 31600, 68452, 398867, 29316, 172786, 18417, 104924, 2606, 5670, 84818, 16288, 67106, 59580, 82929,\n 607401, 291, 85829, 359, 15897, 35830, 50696, 65630, 52672, 22115, 356968, 29895, 40837, 231192, 34024, 38957,\n 26722, 406, 23335, 124952, 72068, 68804, 13268, 147101, 164740, 276569, 162596, 66943, 11569, 26654, 66358, 4777,\n 23229, 102127, 5848, 978, 2921, 59666, 5371, 28212, 90108, 42938, 39320, 2499, 4271, 108792, 33510, 125072,\n 71653, 65239, 38250, 66357, 38577, 13964, 86251, 35708, 50755, 36010, 29448, 12209, 3844, 38222, 206337, 100876,\n 67827, 137088, 14167, 252225, 84163, 195270, 1306, 5703, 54198, 779, 46802, 22028, 51124, 86759, 70560, 113164,\n 35685, 162145, 45471, 34561, 422, 2611, 6464, 47486, 19223, 38246, 9191, 18331, 89942, 243642, 212364, 15893,\n 17518, 22617, 6409, 30046, 126182, 59716, 36560, 104428, 18846, 26592, 19458, 50793, 147333, 30826, 1388, 27647,\n 10922, 14495, 33545, 19269, 135828, 39727, 41601, 46931, 233379, 49169, 131130, 182112, 16276, 82381, 118209, 142445,\n 128310, 19672, 28740, 82907, 33436, 3118, 102206, 28723, 24819, 41937, 38854, 5157, 3881, 111491, 1142, 9776,\n 421673, 152241, 29309, 14961, 87854, 6054, 15424, 3796, 82656, 54996, 2108, 55367, 239450, 154525, 9643, 118103,\n 106041, 64601, 68549, 48707, 30266, 25772, 18740, 9462, 229669, 91798, 112152, 191327, 14493, 72828, 8175, 66636,\n 236474, 25817, 87351, 129027, 76653, 20422, 22983, 71240, 27846, 44661, 12399, 46158, 77704, 53101, 35032, 11072,\n 17300, 109294, 33638, 24408, 1895, 11241, 760, 17584, 82479, 125877, 63150, 141075, 34259, 23274, 81698, 15732,\n 43577, 48340, 91584, 14688, 16379, 24481, 150280, 96420, 262050, 48635, 43727, 61819, 56268, 72003, 88178, 17281,\n 79912, 13218, 122519, 125295, 166396, 11811, 2171, 118930, 67746, 17636, 178278, 174656, 95661, 173039, 83845, 79689,\n 17473, 98555, 127696, 203415, 54730, 22925, 232239, 9309, 12136, 175026, 20740, 180188, 10747, 39816, 314017, 266131,\n 10040, 175732, 112550, 220651, 31974, 37393, 888, 23008, 86799, 4303, 64905, 148467, 75337, 251, 3284, 370102,\n 50264, 9835, 5438, 23655, 4481, 29851, 329, 12855, 7162, 64931, 78141, 12804, 42372, 296771, 83547, 18624,\n 34874, 86271, 3360, 48665, 77735, 88767, 11463, 63527, 28889, 22258, 29140, 194315, 113924, 25499, 6406, 31334,\n 1845, 4802, 49184, 43455, 35469, 127594, 92970, 61038, 115005, 38840, 87761, 106838, 8811, 20572, 55637, 11162,\n 96721, 132425, 108925, 2948, 125457, 36356, 3502, 75270, 27622, 127192, 2561, 123095, 49394, 61155, 16897, 110064,\n 9699, 89448, 53356, 19628, 220310, 21622, 83036, 9885, 112214, 6087, 26713, 17901, 161912, 91492, 3440, 68594,\n 9266, 92238, 8087, 6866, 150194, 72175, 80701, 13459, 31836, 43243, 239700, 95846, 44749, 50647, 21945, 230538,\n 120612, 132371, 244604, 5193, 105637, 34661, 41341, 68775, 85393, 1874, 8771, 33718, 49672, 77403, 595452, 99507,\n 6490, 58895, 128742, 7704, 39239, 73217, 43816, 62824, 37804, 199976, 22361, 80005, 87514, 94832, 14089, 4574,\n 139975, 59142, 75523, 100268, 43906, 53442, 15152, 2547, 186002, 17011, 19513, 204282, 3343, 60568, 128318, 119250,\n 4298, 51871, 41336, 71759, 21921, 45074, 98169, 145889, 99427, 11350, 1237, 5520, 28799, 7803, 53702, 21026,\n 136352, 38293, 128690, 12158, 90132, 44600, 10184, 26957, 39459, 126025, 78904, 82999, 59373, 39301, 150198, 120529,\n 153042, 20177, 50089, 14764, 271571, 30530, 123161, 38975, 101562, 22941, 5648, 124654, 109243, 69817, 71675, 49162,\n 106884, 21241, 107795, 30258, 16572, 188262, 141456, 7688, 60718, 8271, 11044, 32440, 104608, 103419, 236109, 93156,\n 43293, 128929, 42107, 67180, 25201, 115254, 185488, 130954, 72813, 167547, 20537, 39969, 38432, 22582, 184022, 1139,\n 27199, 5655, 17767, 97412, 122606, 209377, 27070, 35871, 326617, 188954, 42680, 73512, 80911, 22629, 3011, 95021,\n 315242, 157737, 383, 41821, 41808, 19335, 27950, 15674, 25677, 110950, 35375, 76835, 59108, 57370, 35262, 16569,\n 160415, 37706, 78086, 32041, 49691, 137143, 9782, 172080, 50148, 77917, 6323, 10110, 69172, 17711, 21795, 59511,\n 76184, 135114, 31046, 132319, 59105, 157578, 20549, 80778, 57649, 158421, 65143, 4575, 72235, 21899, 10797, 92745,\n 34035, 106079, 80159, 4508, 78304, 25350, 75457, 46458, 32937, 25623, 47, 8531, 104751, 84953, 8138, 36508,\n 187199, 66310, 115274, 13253, 32461, 38536, 1916, 42007, 187160, 35055, 26325, 84394, 35963, 94216, 45590, 97782\n]\n", "/**\n * Consumes the passed iterator and returns the number of items it contained\n */\nexport default async function length (iterator: AsyncIterable | Iterable): Promise {\n let count = 0\n\n for await (const _ of iterator) { // eslint-disable-line no-unused-vars,@typescript-eslint/no-unused-vars\n count++\n }\n\n return count\n}\n", "import { xor as uint8ArrayXor } from 'uint8arrays/xor'\nimport GENERATED_PREFIXES from './generated-prefix-list.js'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { randomBytes } from '@libp2p/crypto'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { logger } from '@libp2p/logger'\nimport length from 'it-length'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { TABLE_REFRESH_INTERVAL, TABLE_REFRESH_QUERY_TIMEOUT } from '../constants.js'\nimport type { RoutingTable } from './index.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { PeerRouting } from '../peer-routing/index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\n/**\n * Cannot generate random KadIds longer than this + 1\n */\nconst MAX_COMMON_PREFIX_LENGTH = 15\n\nexport interface RoutingTableRefreshInit {\n peerRouting: PeerRouting\n routingTable: RoutingTable\n lan: boolean\n refreshInterval?: number\n refreshQueryTimeout?: number\n}\n\n/**\n * A wrapper around `k-bucket`, to provide easy store and\n * retrieval for peers.\n */\nexport class RoutingTableRefresh {\n private readonly log: Logger\n private readonly peerRouting: PeerRouting\n private readonly routingTable: RoutingTable\n private readonly refreshInterval: number\n private readonly refreshQueryTimeout: number\n private readonly commonPrefixLengthRefreshedAt: Date[]\n private refreshTimeoutId?: NodeJS.Timer\n\n constructor (init: RoutingTableRefreshInit) {\n const { peerRouting, routingTable, refreshInterval, refreshQueryTimeout, lan } = init\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:routing-table:refresh`)\n this.peerRouting = peerRouting\n this.routingTable = routingTable\n this.refreshInterval = refreshInterval ?? TABLE_REFRESH_INTERVAL\n this.refreshQueryTimeout = refreshQueryTimeout ?? TABLE_REFRESH_QUERY_TIMEOUT\n this.commonPrefixLengthRefreshedAt = []\n\n this.refreshTable = this.refreshTable.bind(this)\n }\n\n async start (): Promise {\n this.log(`refreshing routing table every ${this.refreshInterval}ms`)\n this.refreshTable(true)\n }\n\n async stop (): Promise {\n if (this.refreshTimeoutId != null) {\n clearTimeout(this.refreshTimeoutId)\n }\n }\n\n /**\n * To speed lookups, we seed the table with random PeerIds. This means\n * when we are asked to locate a peer on the network, we can find a KadId\n * that is close to the requested peer ID and query that, then network\n * peers will tell us who they know who is close to the fake ID\n */\n refreshTable (force: boolean = false): void {\n this.log('refreshing routing table')\n\n const prefixLength = this._maxCommonPrefix()\n const refreshCpls = this._getTrackedCommonPrefixLengthsForRefresh(prefixLength)\n\n this.log(`max common prefix length ${prefixLength}`)\n this.log(`tracked CPLs [ ${refreshCpls.map(date => date.toISOString()).join(', ')} ]`)\n\n /**\n * If we see a gap at a common prefix length in the Routing table, we ONLY refresh up until\n * the maximum cpl we have in the Routing Table OR (2 * (Cpl+ 1) with the gap), whichever\n * is smaller.\n *\n * This is to prevent refreshes for Cpls that have no peers in the network but happen to be\n * before a very high max Cpl for which we do have peers in the network.\n *\n * The number of 2 * (Cpl + 1) can be proved and a proof would have been written here if\n * the programmer had paid more attention in the Math classes at university.\n *\n * So, please be patient and a doc explaining it will be published soon.\n *\n * https://github.com/libp2p/go-libp2p-kad-dht/commit/2851c88acb0a3f86bcfe3cfd0f4604a03db801d8#diff-ad45f4ba97ffbc4083c2eb87a4420c1157057b233f048030d67c6b551855ccf6R219\n */\n Promise.all(\n refreshCpls.map(async (lastRefresh, index) => {\n try {\n await this._refreshCommonPrefixLength(index, lastRefresh, force)\n\n if (this._numPeersForCpl(prefixLength) === 0) {\n const lastCpl = Math.min(2 * (index + 1), refreshCpls.length - 1)\n\n for (let n = index + 1; n < lastCpl + 1; n++) {\n try {\n await this._refreshCommonPrefixLength(n, lastRefresh, force)\n } catch (err: any) {\n this.log.error(err)\n }\n }\n }\n } catch (err: any) {\n this.log.error(err)\n }\n })\n ).catch(err => {\n this.log.error(err)\n }).then(() => {\n this.refreshTimeoutId = setTimeout(this.refreshTable, this.refreshInterval)\n\n if (this.refreshTimeoutId.unref != null) {\n this.refreshTimeoutId.unref()\n }\n }).catch(err => {\n this.log.error(err)\n })\n }\n\n async _refreshCommonPrefixLength (cpl: number, lastRefresh: Date, force: boolean): Promise {\n if (!force && lastRefresh.getTime() > (Date.now() - this.refreshInterval)) {\n this.log('not running refresh for cpl %s as time since last refresh not above interval', cpl)\n return\n }\n\n // gen a key for the query to refresh the cpl\n const peerId = await this._generateRandomPeerId(cpl)\n\n this.log('starting refreshing cpl %s with key %p (routing table size was %s)', cpl, peerId, this.routingTable.size)\n\n const controller = new TimeoutController(this.refreshQueryTimeout)\n\n try {\n const peers = await length(this.peerRouting.getClosestPeers(peerId.toBytes(), { signal: controller.signal }))\n\n this.log(`found ${peers} peers that were close to imaginary peer %p`, peerId)\n this.log('finished refreshing cpl %s with key %p (routing table size is now %s)', cpl, peerId, this.routingTable.size)\n } finally {\n controller.clear()\n }\n }\n\n _getTrackedCommonPrefixLengthsForRefresh (maxCommonPrefix: number): Date[] {\n if (maxCommonPrefix > MAX_COMMON_PREFIX_LENGTH) {\n maxCommonPrefix = MAX_COMMON_PREFIX_LENGTH\n }\n\n const dates = []\n\n for (let i = 0; i <= maxCommonPrefix; i++) {\n // defaults to the zero value if we haven't refreshed it yet.\n dates[i] = this.commonPrefixLengthRefreshedAt[i] ?? new Date()\n }\n\n return dates\n }\n\n async _generateRandomPeerId (targetCommonPrefixLength: number): Promise {\n if (this.routingTable.kb == null) {\n throw new Error('Routing table not started')\n }\n\n const randomData = randomBytes(2)\n const randomUint16 = (randomData[1] << 8) + randomData[0]\n\n const key = await this._makePeerId(this.routingTable.kb.localNodeId, randomUint16, targetCommonPrefixLength)\n\n return peerIdFromBytes(key)\n }\n\n async _makePeerId (localKadId: Uint8Array, randomPrefix: number, targetCommonPrefixLength: number): Promise {\n if (targetCommonPrefixLength > MAX_COMMON_PREFIX_LENGTH) {\n throw new Error(`Cannot generate peer ID for common prefix length greater than ${MAX_COMMON_PREFIX_LENGTH}`)\n }\n\n const view = new DataView(localKadId.buffer, localKadId.byteOffset, localKadId.byteLength)\n const localPrefix = view.getUint16(0, false)\n\n // For host with ID `L`, an ID `K` belongs to a bucket with ID `B` ONLY IF CommonPrefixLen(L,K) is EXACTLY B.\n // Hence, to achieve a targetPrefix `T`, we must toggle the (T+1)th bit in L & then copy (T+1) bits from L\n // to our randomly generated prefix.\n const toggledLocalPrefix = localPrefix ^ (0x8000 >> targetCommonPrefixLength)\n\n // Combine the toggled local prefix and the random bits at the correct offset\n // such that ONLY the first `targetCommonPrefixLength` bits match the local ID.\n const mask = 65535 << (16 - (targetCommonPrefixLength + 1))\n const targetPrefix = (toggledLocalPrefix & mask) | (randomPrefix & ~mask)\n\n // Convert to a known peer ID.\n const keyPrefix = GENERATED_PREFIXES[targetPrefix]\n\n const keyBuffer = new ArrayBuffer(34)\n const keyView = new DataView(keyBuffer, 0, keyBuffer.byteLength)\n keyView.setUint8(0, sha256.code)\n keyView.setUint8(1, 32)\n keyView.setUint32(2, keyPrefix, false)\n\n return new Uint8Array(keyView.buffer, keyView.byteOffset, keyView.byteLength)\n }\n\n /**\n * returns the maximum common prefix length between any peer in the table\n * and the current peer\n */\n _maxCommonPrefix (): number {\n // xor our KadId with every KadId in the k-bucket tree,\n // return the longest id prefix that is the same\n let prefixLength = 0\n\n for (const length of this._prefixLengths()) {\n if (length > prefixLength) {\n prefixLength = length\n }\n }\n\n return prefixLength\n }\n\n /**\n * Returns the number of peers in the table with a given prefix length\n */\n _numPeersForCpl (prefixLength: number): number {\n let count = 0\n\n for (const length of this._prefixLengths()) {\n if (length === prefixLength) {\n count++\n }\n }\n\n return count\n }\n\n /**\n * Yields the common prefix length of every peer in the table\n */\n * _prefixLengths (): Generator {\n if (this.routingTable.kb == null) {\n return\n }\n\n for (const { id } of this.routingTable.kb.toIterable()) {\n const distance = uint8ArrayXor(this.routingTable.kb.localNodeId, id)\n let leadingZeros = 0\n\n for (const byte of distance) {\n if (byte === 0) {\n leadingZeros++\n } else {\n break\n }\n }\n\n yield leadingZeros\n }\n }\n}\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\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key?: Uint8Array\n value?: Uint8Array\n author?: Uint8Array\n signature?: Uint8Array\n timeReceived?: string\n}\n\nexport namespace Record {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.key != null) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if (obj.value != null) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if (obj.author != null) {\n w.uint32(26)\n w.bytes(obj.author)\n }\n\n if (obj.signature != null) {\n w.uint32(34)\n w.bytes(obj.signature)\n }\n\n if (obj.timeReceived != null) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.bytes()\n break\n case 2:\n obj.value = reader.bytes()\n break\n case 3:\n obj.author = reader.bytes()\n break\n case 4:\n obj.signature = reader.bytes()\n break\n case 5:\n obj.timeReceived = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Record.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Record => {\n return decodeMessage(buf, Record.codec())\n }\n}\n\nexport interface Message {\n type?: Message.MessageType\n clusterLevelRaw?: number\n key?: Uint8Array\n record?: Uint8Array\n closerPeers: Message.Peer[]\n providerPeers: Message.Peer[]\n}\n\nexport namespace Message {\n export enum MessageType {\n PUT_VALUE = 'PUT_VALUE',\n GET_VALUE = 'GET_VALUE',\n ADD_PROVIDER = 'ADD_PROVIDER',\n GET_PROVIDERS = 'GET_PROVIDERS',\n FIND_NODE = 'FIND_NODE',\n PING = 'PING'\n }\n\n enum __MessageTypeValues {\n PUT_VALUE = 0,\n GET_VALUE = 1,\n ADD_PROVIDER = 2,\n GET_PROVIDERS = 3,\n FIND_NODE = 4,\n PING = 5\n }\n\n export namespace MessageType {\n export const codec = (): Codec => {\n return enumeration(__MessageTypeValues)\n }\n }\n\n export enum ConnectionType {\n NOT_CONNECTED = 'NOT_CONNECTED',\n CONNECTED = 'CONNECTED',\n CAN_CONNECT = 'CAN_CONNECT',\n CANNOT_CONNECT = 'CANNOT_CONNECT'\n }\n\n enum __ConnectionTypeValues {\n NOT_CONNECTED = 0,\n CONNECTED = 1,\n CAN_CONNECT = 2,\n CANNOT_CONNECT = 3\n }\n\n export namespace ConnectionType {\n export const codec = (): Codec => {\n return enumeration(__ConnectionTypeValues)\n }\n }\n\n export interface Peer {\n id?: Uint8Array\n addrs: Uint8Array[]\n connection?: Message.ConnectionType\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.id != null) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (obj.connection != null) {\n w.uint32(24)\n Message.ConnectionType.codec().encode(obj.connection, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addrs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs.push(reader.bytes())\n break\n case 3:\n obj.connection = Message.ConnectionType.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.type != null) {\n w.uint32(8)\n Message.MessageType.codec().encode(obj.type, w)\n }\n\n if (obj.clusterLevelRaw != null) {\n w.uint32(80)\n w.int32(obj.clusterLevelRaw)\n }\n\n if (obj.key != null) {\n w.uint32(18)\n w.bytes(obj.key)\n }\n\n if (obj.record != null) {\n w.uint32(26)\n w.bytes(obj.record)\n }\n\n if (obj.closerPeers != null) {\n for (const value of obj.closerPeers) {\n w.uint32(66)\n Message.Peer.codec().encode(value, w)\n }\n }\n\n if (obj.providerPeers != null) {\n for (const value of obj.providerPeers) {\n w.uint32(74)\n Message.Peer.codec().encode(value, w)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n closerPeers: [],\n providerPeers: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = Message.MessageType.codec().decode(reader)\n break\n case 10:\n obj.clusterLevelRaw = reader.int32()\n break\n case 2:\n obj.key = reader.bytes()\n break\n case 3:\n obj.record = reader.bytes()\n break\n case 8:\n obj.closerPeers.push(Message.Peer.codec().decode(reader, reader.uint32()))\n break\n case 9:\n obj.providerPeers.push(Message.Peer.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, Message.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Message => {\n return decodeMessage(buf, Message.codec())\n }\n}\n", "import { peerIdFromBytes } from '@libp2p/peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { Message as PBMessage } from './dht.js'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const MESSAGE_TYPE = PBMessage.MessageType\nexport const CONNECTION_TYPE = PBMessage.ConnectionType\nexport const MESSAGE_TYPE_LOOKUP = Object.keys(MESSAGE_TYPE)\n\ninterface PBPeer {\n id: Uint8Array\n addrs: Uint8Array[]\n connection: PBMessage.ConnectionType\n}\n\n/**\n * Represents a single DHT control message.\n */\nexport class Message {\n public type: PBMessage.MessageType\n public key: Uint8Array\n private clusterLevelRaw: number\n public closerPeers: PeerInfo[]\n public providerPeers: PeerInfo[]\n public record?: Libp2pRecord\n\n constructor (type: PBMessage.MessageType, key: Uint8Array, level: number) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('Key must be a Uint8Array')\n }\n\n this.type = type\n this.key = key\n this.clusterLevelRaw = level\n this.closerPeers = []\n this.providerPeers = []\n this.record = undefined\n }\n\n /**\n * @type {number}\n */\n get clusterLevel (): number {\n const level = this.clusterLevelRaw - 1\n if (level < 0) {\n return 0\n }\n\n return level\n }\n\n set clusterLevel (level) {\n this.clusterLevelRaw = level\n }\n\n /**\n * Encode into protobuf\n */\n serialize (): Uint8Array {\n return PBMessage.encode({\n key: this.key,\n type: this.type,\n clusterLevelRaw: this.clusterLevelRaw,\n closerPeers: this.closerPeers.map(toPbPeer),\n providerPeers: this.providerPeers.map(toPbPeer),\n record: this.record == null ? undefined : this.record.serialize().subarray()\n })\n }\n\n /**\n * Decode from protobuf\n */\n static deserialize (raw: Uint8ArrayList | Uint8Array): Message {\n const dec = PBMessage.decode(raw)\n\n const msg = new Message(dec.type ?? PBMessage.MessageType.PUT_VALUE, dec.key ?? Uint8Array.from([]), dec.clusterLevelRaw ?? 0)\n msg.closerPeers = dec.closerPeers.map(fromPbPeer)\n msg.providerPeers = dec.providerPeers.map(fromPbPeer)\n\n if (dec.record?.length != null) {\n msg.record = Libp2pRecord.deserialize(dec.record)\n }\n\n return msg\n }\n}\n\nfunction toPbPeer (peer: PeerInfo): PBPeer {\n const output: PBPeer = {\n id: peer.id.toBytes(),\n addrs: (peer.multiaddrs ?? []).map((m) => m.bytes),\n connection: CONNECTION_TYPE.CONNECTED\n }\n\n return output\n}\n\nfunction fromPbPeer (peer: PBMessage.Peer): PeerInfo {\n if (peer.id == null) {\n throw new Error('Invalid peer in message')\n }\n\n return {\n id: peerIdFromBytes(peer.id),\n multiaddrs: (peer.addrs ?? []).map((a) => multiaddr(a)),\n protocols: []\n }\n}\n", "import { MESSAGE_TYPE_LOOKUP } from '../message/index.js'\nimport type { Message } from '../message/dht.js'\nimport type { SendingQueryEvent, PeerResponseEvent, DialingPeerEvent, AddingPeerEvent, ValueEvent, ProviderEvent, QueryErrorEvent, FinalPeerEvent } from '@libp2p/interface-dht'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Libp2pRecord } from '@libp2p/record'\n\nexport interface QueryEventFields {\n to: PeerId\n type: Message.MessageType\n}\n\nexport function sendingQueryEvent (fields: QueryEventFields): SendingQueryEvent {\n return {\n ...fields,\n name: 'SENDING_QUERY',\n type: 0,\n messageName: fields.type,\n messageType: MESSAGE_TYPE_LOOKUP.indexOf(fields.type.toString())\n }\n}\n\nexport interface PeerResponseEventField {\n from: PeerId\n messageType: Message.MessageType\n closer?: PeerInfo[]\n providers?: PeerInfo[]\n record?: Libp2pRecord\n}\n\nexport function peerResponseEvent (fields: PeerResponseEventField): PeerResponseEvent {\n return {\n ...fields,\n name: 'PEER_RESPONSE',\n type: 1,\n messageName: fields.messageType,\n closer: (fields.closer != null) ? fields.closer : [],\n providers: (fields.providers != null) ? fields.providers : []\n }\n}\n\nexport interface FinalPeerEventFields {\n from: PeerId\n peer: PeerInfo\n}\n\nexport function finalPeerEvent (fields: FinalPeerEventFields): FinalPeerEvent {\n return {\n ...fields,\n name: 'FINAL_PEER',\n type: 2\n }\n}\n\nexport interface ErrorEventFields {\n from: PeerId\n error: Error\n}\n\nexport function queryErrorEvent (fields: ErrorEventFields): QueryErrorEvent {\n return {\n ...fields,\n name: 'QUERY_ERROR',\n type: 3\n }\n}\n\nexport interface ProviderEventFields {\n from: PeerId\n providers: PeerInfo[]\n}\n\nexport function providerEvent (fields: ProviderEventFields): ProviderEvent {\n return {\n ...fields,\n name: 'PROVIDER',\n type: 4\n }\n}\n\nexport interface ValueEventFields {\n from: PeerId\n value: Uint8Array\n}\n\nexport function valueEvent (fields: ValueEventFields): ValueEvent {\n return {\n ...fields,\n name: 'VALUE',\n type: 5\n }\n}\n\nexport interface PeerEventFields {\n peer: PeerId\n}\n\nexport function addingPeerEvent (fields: PeerEventFields): AddingPeerEvent {\n return {\n ...fields,\n name: 'ADDING_PEER',\n type: 6\n }\n}\n\nexport interface DialingPeerEventFields {\n peer: PeerId\n}\n\nexport function dialingPeerEvent (fields: DialingPeerEventFields): DialingPeerEvent {\n return {\n ...fields,\n name: 'DIALING_PEER',\n type: 7\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { pipe } from 'it-pipe'\nimport * as lp from 'it-length-prefixed'\nimport drain from 'it-drain'\nimport first from 'it-first'\nimport { Message } from './message/index.js'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport {\n dialingPeerEvent,\n sendingQueryEvent,\n peerResponseEvent,\n queryErrorEvent\n} from './query/events.js'\nimport { logger } from '@libp2p/logger'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Logger } from '@libp2p/logger'\nimport type { Duplex } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { abortableDuplex } from 'abortable-iterator'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { KadDHTComponents } from './index.js'\nimport type { QueryEvent } from '@libp2p/interface-dht'\n\nexport interface NetworkInit {\n protocol: string\n lan: boolean\n}\n\ninterface NetworkEvents {\n 'peer': CustomEvent\n}\n\n/**\n * Handle network operations for the dht\n */\nexport class Network extends EventEmitter implements Startable {\n private readonly log: Logger\n private readonly protocol: string\n private running: boolean\n private readonly components: KadDHTComponents\n\n /**\n * Create a new network\n */\n constructor (components: KadDHTComponents, init: NetworkInit) {\n super()\n\n const { protocol, lan } = init\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:network`)\n this.running = false\n this.protocol = protocol\n }\n\n /**\n * Start the network\n */\n async start (): Promise {\n if (this.running) {\n return\n }\n\n this.running = true\n }\n\n /**\n * Stop all network activity\n */\n async stop (): Promise {\n this.running = false\n }\n\n /**\n * Is the network online?\n */\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * Send a request and record RTT for latency measurements\n */\n async * sendRequest (to: PeerId, msg: Message, options: AbortOptions = {}): AsyncGenerator {\n if (!this.running) {\n return\n }\n\n this.log('sending %s to %p', msg.type, to)\n yield dialingPeerEvent({ peer: to })\n yield sendingQueryEvent({ to, type: msg.type })\n\n let stream: Stream | undefined\n\n try {\n const connection = await this.components.connectionManager.openConnection(to, options)\n const stream = await connection.newStream(this.protocol, options)\n\n const response = await this._writeReadMessage(stream, msg.serialize(), options)\n\n yield peerResponseEvent({\n from: to,\n messageType: response.type,\n closer: response.closerPeers,\n providers: response.providerPeers,\n record: response.record\n })\n } catch (err: any) {\n yield queryErrorEvent({ from: to, error: err })\n } finally {\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Sends a message without expecting an answer\n */\n async * sendMessage (to: PeerId, msg: Message, options: AbortOptions = {}): AsyncGenerator {\n if (!this.running) {\n return\n }\n\n this.log('sending %s to %p', msg.type, to)\n yield dialingPeerEvent({ peer: to })\n yield sendingQueryEvent({ to, type: msg.type })\n\n let stream: Stream | undefined\n\n try {\n const connection = await this.components.connectionManager.openConnection(to, options)\n const stream = await connection.newStream(this.protocol, options)\n\n await this._writeMessage(stream, msg.serialize(), options)\n\n yield peerResponseEvent({ from: to, messageType: msg.type })\n } catch (err: any) {\n yield queryErrorEvent({ from: to, error: err })\n } finally {\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Write a message to the given stream\n */\n async _writeMessage (stream: Duplex, msg: Uint8Array | Uint8ArrayList, options: AbortOptions): Promise {\n if (options.signal != null) {\n stream = abortableDuplex(stream, options.signal)\n }\n\n await pipe(\n [msg],\n lp.encode(),\n stream,\n drain\n )\n }\n\n /**\n * Write a message and read its response.\n * If no response is received after the specified timeout\n * this will error out.\n */\n async _writeReadMessage (stream: Duplex, msg: Uint8Array | Uint8ArrayList, options: AbortOptions): Promise {\n if (options.signal != null) {\n stream = abortableDuplex(stream, options.signal)\n }\n\n const res = await pipe(\n [msg],\n lp.encode(),\n stream,\n lp.decode(),\n async source => {\n const buf = await first(source)\n\n if (buf != null) {\n return buf\n }\n\n throw new CodeError('No message received', 'ERR_NO_MESSAGE_RECEIVED')\n }\n )\n\n const message = Message.deserialize(res)\n\n // tell any listeners about new peers we've seen\n message.closerPeers.forEach(peerData => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerData\n }))\n })\n message.providerPeers.forEach(peerData => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerData\n }))\n })\n\n return message\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Libp2pRecord } from './index.js'\nimport type { Validators } from '@libp2p/interface-dht'\n\n/**\n * Checks a record and ensures it is still valid.\n * It runs the needed validators.\n * If verification fails the returned Promise will reject with the error.\n */\nexport async function verifyRecord (validators: Validators, record: Libp2pRecord): Promise {\n const key = record.key\n const keyString = uint8ArrayToString(key)\n const parts = keyString.split('/')\n\n if (parts.length < 3) {\n // No validator available\n return\n }\n\n const validator = validators[parts[1].toString()]\n\n if (validator == null) {\n const errMsg = 'Invalid record keytype'\n\n throw new CodeError(errMsg, 'ERR_INVALID_RECORD_KEY_TYPE')\n }\n\n await validator(key, record.value)\n}\n\n/**\n * Validator for public key records.\n * Verifies that the passed in record value is the PublicKey\n * that matches the passed in key.\n * If validation fails the returned Promise will reject with the error.\n *\n * @param {Uint8Array} key - A valid key is of the form `'/pk/'`\n * @param {Uint8Array} publicKey - The public key to validate against (protobuf encoded).\n */\nconst validatePublicKeyRecord = async (key: Uint8Array, publicKey: Uint8Array): Promise => {\n if (!(key instanceof Uint8Array)) {\n throw new CodeError('\"key\" must be a Uint8Array', 'ERR_INVALID_RECORD_KEY_NOT_BUFFER')\n }\n\n if (key.byteLength < 5) {\n throw new CodeError('invalid public key record', 'ERR_INVALID_RECORD_KEY_TOO_SHORT')\n }\n\n const prefix = uint8ArrayToString(key.subarray(0, 4))\n\n if (prefix !== '/pk/') {\n throw new CodeError('key was not prefixed with /pk/', 'ERR_INVALID_RECORD_KEY_BAD_PREFIX')\n }\n\n const keyhash = key.slice(4)\n\n const publicKeyHash = await sha256.digest(publicKey)\n\n if (!uint8ArrayEquals(keyhash, publicKeyHash.bytes)) {\n throw new CodeError('public key does not match passed in key', 'ERR_INVALID_RECORD_HASH_MISMATCH')\n }\n}\n\nexport const validators: Validators = {\n pk: validatePublicKeyRecord\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Selectors } from '@libp2p/interface-dht'\n\n/**\n * Select the best record out of the given records\n */\nexport function bestRecord (selectors: Selectors, k: Uint8Array, records: Uint8Array[]): number {\n if (records.length === 0) {\n const errMsg = 'No records given'\n\n throw new CodeError(errMsg, 'ERR_NO_RECORDS_RECEIVED')\n }\n\n const kStr = uint8ArrayToString(k)\n const parts = kStr.split('/')\n\n if (parts.length < 3) {\n const errMsg = 'Record key does not have a selector function'\n\n throw new CodeError(errMsg, 'ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY')\n }\n\n const selector = selectors[parts[1].toString()]\n\n if (selector == null) {\n const errMsg = `Unrecognized key prefix: ${parts[1]}`\n\n throw new CodeError(errMsg, 'ERR_UNRECOGNIZED_KEY_PREFIX')\n }\n\n if (records.length === 1) {\n return 0\n }\n\n return selector(k, records)\n}\n\n/**\n * Best record selector, for public key records.\n * Simply returns the first record, as all valid public key\n * records are equal\n */\nfunction publickKey (k: Uint8Array, records: Uint8Array[]): number {\n return 0\n}\n\nexport const selectors: Selectors = {\n pk: publickKey\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { verifyRecord } from '@libp2p/record/validators'\nimport { bestRecord } from '@libp2p/record/selectors'\nimport parallel from 'it-parallel'\nimport map from 'it-map'\nimport {\n valueEvent,\n queryErrorEvent\n} from '../query/events.js'\nimport { Message, MESSAGE_TYPE } from '../message/index.js'\nimport { pipe } from 'it-pipe'\nimport {\n ALPHA\n} from '../constants.js'\nimport { createPutRecord, convertBuffer, bufferToRecordKey } from '../utils.js'\nimport { logger } from '@libp2p/logger'\nimport type { Validators, Selectors, ValueEvent, QueryOptions, QueryEvent } from '@libp2p/interface-dht'\nimport type { PeerRouting } from '../peer-routing/index.js'\nimport type { QueryManager } from '../query/manager.js'\nimport type { RoutingTable } from '../routing-table/index.js'\nimport type { Network } from '../network.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { QueryFunc } from '../query/types.js'\nimport type { KadDHTComponents } from '../index.js'\n\nexport interface ContentFetchingInit {\n validators: Validators\n selectors: Selectors\n peerRouting: PeerRouting\n queryManager: QueryManager\n routingTable: RoutingTable\n network: Network\n lan: boolean\n}\n\nexport class ContentFetching {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly validators: Validators\n private readonly selectors: Selectors\n private readonly peerRouting: PeerRouting\n private readonly queryManager: QueryManager\n private readonly routingTable: RoutingTable\n private readonly network: Network\n\n constructor (components: KadDHTComponents, init: ContentFetchingInit) {\n const { validators, selectors, peerRouting, queryManager, routingTable, network, lan } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:content-fetching`)\n this.validators = validators\n this.selectors = selectors\n this.peerRouting = peerRouting\n this.queryManager = queryManager\n this.routingTable = routingTable\n this.network = network\n }\n\n async putLocal (key: Uint8Array, rec: Uint8Array): Promise {\n const dsKey = bufferToRecordKey(key)\n await this.components.datastore.put(dsKey, rec)\n }\n\n /**\n * Attempt to retrieve the value for the given key from\n * the local datastore\n */\n async getLocal (key: Uint8Array): Promise {\n this.log('getLocal %b', key)\n\n const dsKey = bufferToRecordKey(key)\n\n this.log('fetching record for key %k', dsKey)\n\n const raw = await this.components.datastore.get(dsKey)\n this.log('found %k in local datastore', dsKey)\n\n const rec = Libp2pRecord.deserialize(raw)\n\n await verifyRecord(this.validators, rec)\n\n return rec\n }\n\n /**\n * Send the best record found to any peers that have an out of date record\n */\n async * sendCorrectionRecord (key: Uint8Array, vals: ValueEvent[], best: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n this.log('sendCorrection for %b', key)\n const fixupRec = createPutRecord(key, best)\n\n for (const { value, from } of vals) {\n // no need to do anything\n if (uint8ArrayEquals(value, best)) {\n this.log('record was ok')\n continue\n }\n\n // correct ourself\n if (this.components.peerId.equals(from)) {\n try {\n const dsKey = bufferToRecordKey(key)\n this.log(`Storing corrected record for key ${dsKey.toString()}`)\n await this.components.datastore.put(dsKey, fixupRec.subarray())\n } catch (err: any) {\n this.log.error('Failed error correcting self', err)\n }\n\n continue\n }\n\n // send correction\n let sentCorrection = false\n const request = new Message(MESSAGE_TYPE.PUT_VALUE, key, 0)\n request.record = Libp2pRecord.deserialize(fixupRec)\n\n for await (const event of this.network.sendRequest(from, request, options)) {\n if (event.name === 'PEER_RESPONSE' && (event.record != null) && uint8ArrayEquals(event.record.value, Libp2pRecord.deserialize(fixupRec).value)) {\n sentCorrection = true\n }\n\n yield event\n }\n\n if (!sentCorrection) {\n yield queryErrorEvent({ from, error: new CodeError('value not put correctly', 'ERR_PUT_VALUE_INVALID') })\n }\n\n this.log.error('Failed error correcting entry')\n }\n }\n\n /**\n * Store the given key/value pair in the DHT\n */\n async * put (key: Uint8Array, value: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n this.log('put key %b value %b', key, value)\n\n // create record in the dht format\n const record = createPutRecord(key, value)\n\n // store the record locally\n const dsKey = bufferToRecordKey(key)\n this.log(`storing record for key ${dsKey.toString()}`)\n await this.components.datastore.put(dsKey, record.subarray())\n\n // put record to the closest peers\n yield * pipe(\n this.peerRouting.getClosestPeers(key, { signal: options.signal }),\n (source) => map(source, (event) => {\n return async () => {\n if (event.name !== 'FINAL_PEER') {\n return [event]\n }\n\n const events = []\n\n const msg = new Message(MESSAGE_TYPE.PUT_VALUE, key, 0)\n msg.record = Libp2pRecord.deserialize(record)\n\n this.log('send put to %p', event.peer.id)\n for await (const putEvent of this.network.sendRequest(event.peer.id, msg, options)) {\n events.push(putEvent)\n\n if (putEvent.name !== 'PEER_RESPONSE') {\n continue\n }\n\n if (!(putEvent.record != null && uint8ArrayEquals(putEvent.record.value, Libp2pRecord.deserialize(record).value))) {\n events.push(queryErrorEvent({ from: event.peer.id, error: new CodeError('value not put correctly', 'ERR_PUT_VALUE_INVALID') }))\n }\n }\n\n return events\n }\n }),\n (source) => parallel(source, {\n ordered: false,\n concurrency: ALPHA\n }),\n async function * (source) {\n for await (const events of source) {\n yield * events\n }\n }\n )\n }\n\n /**\n * Get the value to the given key\n */\n async * get (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n this.log('get %b', key)\n\n const vals: ValueEvent[] = []\n\n for await (const event of this.getMany(key, options)) {\n if (event.name === 'VALUE') {\n vals.push(event)\n }\n\n yield event\n }\n\n if (vals.length === 0) {\n return\n }\n\n const records = vals.map((v) => v.value)\n let i = 0\n\n try {\n i = bestRecord(this.selectors, key, records)\n } catch (err: any) {\n // Assume the first record if no selector available\n if (err.code !== 'ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY') {\n throw err\n }\n }\n\n const best = records[i]\n this.log('GetValue %b %b', key, best)\n\n if (best == null) {\n throw new CodeError('best value was not found', 'ERR_NOT_FOUND')\n }\n\n yield * this.sendCorrectionRecord(key, vals, best, options)\n\n yield vals[i]\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n this.log('getMany values for %b', key)\n\n try {\n const localRec = await this.getLocal(key)\n\n yield valueEvent({\n value: localRec.value,\n from: this.components.peerId\n })\n } catch (err: any) {\n this.log('error getting local value for %b', key, err)\n }\n\n const id = await convertBuffer(key)\n const rtp = this.routingTable.closestPeers(id)\n\n this.log('found %d peers in routing table', rtp.length)\n\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n const getValueQuery: QueryFunc = async function * ({ peer, signal }) {\n for await (const event of self.peerRouting.getValueOrPeers(peer, key, { signal })) {\n yield event\n\n if (event.name === 'PEER_RESPONSE' && (event.record != null)) {\n yield valueEvent({ from: peer, value: event.record.value })\n }\n }\n }\n\n // we have peers, lets send the actual query to them\n yield * this.queryManager.run(key, rtp, getValueQuery, options)\n }\n}\n", "import { Message, MESSAGE_TYPE } from '../message/index.js'\nimport parallel from 'it-parallel'\nimport map from 'it-map'\nimport { convertBuffer } from '../utils.js'\nimport { ALPHA } from '../constants.js'\nimport { pipe } from 'it-pipe'\nimport {\n queryErrorEvent,\n peerResponseEvent,\n providerEvent\n} from '../query/events.js'\nimport { logger } from '@libp2p/logger'\nimport type { PeerResponseEvent, ProviderEvent, QueryEvent, QueryOptions } from '@libp2p/interface-dht'\nimport type { PeerRouting } from '../peer-routing/index.js'\nimport type { QueryManager } from '../query/manager.js'\nimport type { RoutingTable } from '../routing-table/index.js'\nimport type { Network } from '../network.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { Providers } from '../providers.js'\nimport type { QueryFunc } from '../query/types.js'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { KadDHTComponents } from '../index.js'\n\nexport interface ContentRoutingInit {\n network: Network\n peerRouting: PeerRouting\n queryManager: QueryManager\n routingTable: RoutingTable\n providers: Providers\n lan: boolean\n}\n\nexport class ContentRouting {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly network: Network\n private readonly peerRouting: PeerRouting\n private readonly queryManager: QueryManager\n private readonly routingTable: RoutingTable\n private readonly providers: Providers\n\n constructor (components: KadDHTComponents, init: ContentRoutingInit) {\n const { network, peerRouting, queryManager, routingTable, providers, lan } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:content-routing`)\n this.network = network\n this.peerRouting = peerRouting\n this.queryManager = queryManager\n this.routingTable = routingTable\n this.providers = providers\n }\n\n /**\n * Announce to the network that we can provide the value for a given key and\n * are contactable on the given multiaddrs\n */\n async * provide (key: CID, multiaddrs: Multiaddr[], options: AbortOptions = {}): AsyncGenerator {\n this.log('provide %s', key)\n\n // Add peer as provider\n await this.providers.addProvider(key, this.components.peerId)\n\n const msg = new Message(MESSAGE_TYPE.ADD_PROVIDER, key.multihash.bytes, 0)\n msg.providerPeers = [{\n id: this.components.peerId,\n multiaddrs,\n protocols: []\n }]\n\n let sent = 0\n\n const maybeNotifyPeer = (event: QueryEvent) => {\n return async () => {\n if (event.name !== 'FINAL_PEER') {\n return [event]\n }\n\n const events = []\n\n this.log('putProvider %s to %p', key, event.peer.id)\n\n try {\n this.log('sending provider record for %s to %p', key, event.peer.id)\n\n for await (const sendEvent of this.network.sendMessage(event.peer.id, msg, options)) {\n if (sendEvent.name === 'PEER_RESPONSE') {\n this.log('sent provider record for %s to %p', key, event.peer.id)\n sent++\n }\n\n events.push(sendEvent)\n }\n } catch (err: any) {\n this.log.error('error sending provide record to peer %p', event.peer.id, err)\n events.push(queryErrorEvent({ from: event.peer.id, error: err }))\n }\n\n return events\n }\n }\n\n // Notify closest peers\n yield * pipe(\n this.peerRouting.getClosestPeers(key.multihash.bytes, options),\n (source) => map(source, (event) => maybeNotifyPeer(event)),\n (source) => parallel(source, {\n ordered: false,\n concurrency: ALPHA\n }),\n async function * (source) {\n for await (const events of source) {\n yield * events\n }\n }\n )\n\n this.log('sent provider records to %d peers', sent)\n }\n\n /**\n * Search the dht for up to `K` providers of the given CID.\n */\n async * findProviders (key: CID, options: QueryOptions): AsyncGenerator {\n const toFind = this.routingTable.kBucketSize\n const target = key.multihash.bytes\n const id = await convertBuffer(target)\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n this.log('findProviders %c', key)\n\n const provs = await this.providers.getProviders(key)\n\n // yield values if we have some, also slice because maybe we got lucky and already have too many?\n if (provs.length > 0) {\n const providers: PeerInfo[] = []\n\n for (const peerId of provs.slice(0, toFind)) {\n providers.push({\n id: peerId,\n multiaddrs: ((await this.components.peerStore.addressBook.get(peerId)) ?? []).map(address => address.multiaddr),\n protocols: []\n })\n }\n\n yield peerResponseEvent({ from: this.components.peerId, messageType: MESSAGE_TYPE.GET_PROVIDERS, providers })\n yield providerEvent({ from: this.components.peerId, providers })\n }\n\n // All done\n if (provs.length >= toFind) {\n return\n }\n\n /**\n * The query function to use on this particular disjoint path\n */\n const findProvidersQuery: QueryFunc = async function * ({ peer, signal }) {\n const request = new Message(MESSAGE_TYPE.GET_PROVIDERS, target, 0)\n\n yield * self.network.sendRequest(peer, request, { signal })\n }\n\n const providers = new Set(provs.map(p => p.toString()))\n\n for await (const event of this.queryManager.run(target, this.routingTable.closestPeers(id), findProvidersQuery, options)) {\n yield event\n\n if (event.name === 'PEER_RESPONSE') {\n this.log('Found %d provider entries for %c and %d closer peers', event.providers.length, key, event.closer.length)\n\n const newProviders = []\n\n for (const peer of event.providers) {\n if (providers.has(peer.id.toString())) {\n continue\n }\n\n providers.add(peer.id.toString())\n newProviders.push(peer)\n }\n\n if (newProviders.length > 0) {\n yield providerEvent({ from: event.from, providers: newProviders })\n }\n\n if (providers.size === toFind) {\n return\n }\n }\n }\n }\n}\n", "/**\n * Can be used with Array.sort to sort and array with Uint8Array entries\n */\nexport function compare (a: Uint8Array, b: Uint8Array): number {\n if (globalThis.Buffer != null) {\n return globalThis.Buffer.compare(a, b)\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] < b[i]) {\n return -1\n }\n\n if (a[i] > b[i]) {\n return 1\n }\n }\n\n if (a.byteLength > b.byteLength) {\n return 1\n }\n\n if (a.byteLength < b.byteLength) {\n return -1\n }\n\n return 0\n}\n", "import * as utils from '../utils.js'\nimport { compare as uint8ArrayCompare } from 'uint8arrays/compare'\nimport { xor as uint8ArrayXor } from 'uint8arrays/xor'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\ninterface PeerDistance {\n peerId: PeerId\n distance: Uint8Array\n}\n\n/**\n * Maintains a list of peerIds sorted by distance from a DHT key.\n */\nexport class PeerDistanceList {\n /**\n * The DHT key from which distance is calculated\n */\n private readonly originDhtKey: Uint8Array\n\n /**\n * The maximum size of the list\n */\n private readonly capacity: number\n\n private peerDistances: PeerDistance[]\n\n constructor (originDhtKey: Uint8Array, capacity: number) {\n this.originDhtKey = originDhtKey\n this.capacity = capacity\n this.peerDistances = []\n }\n\n /**\n * The length of the list\n */\n get length (): number {\n return this.peerDistances.length\n }\n\n /**\n * The peerIds in the list, in order of distance from the origin key\n */\n get peers (): PeerId[] {\n return this.peerDistances.map(pd => pd.peerId)\n }\n\n /**\n * Add a peerId to the list.\n */\n async add (peerId: PeerId): Promise {\n if (this.peerDistances.find(pd => pd.peerId.equals(peerId)) != null) {\n return\n }\n\n const dhtKey = await utils.convertPeerId(peerId)\n const el = {\n peerId,\n distance: uint8ArrayXor(this.originDhtKey, dhtKey)\n }\n\n this.peerDistances.push(el)\n this.peerDistances.sort((a, b) => uint8ArrayCompare(a.distance, b.distance))\n this.peerDistances = this.peerDistances.slice(0, this.capacity)\n }\n\n /**\n * Indicates whether any of the peerIds passed as a parameter are closer\n * to the origin key than the furthest peerId in the PeerDistanceList.\n */\n async anyCloser (peerIds: PeerId[]): Promise {\n if (peerIds.length === 0) {\n return false\n }\n\n if (this.length === 0) {\n return true\n }\n\n const dhtKeys = await Promise.all(peerIds.map(utils.convertPeerId))\n const furthestDistance = this.peerDistances[this.peerDistances.length - 1].distance\n\n for (const dhtKey of dhtKeys) {\n const keyDistance = uint8ArrayXor(this.originDhtKey, dhtKey)\n\n if (uint8ArrayCompare(keyDistance, furthestDistance) < 0) {\n return true\n }\n }\n\n return false\n }\n}\n", "import { CodeError } from '@libp2p/interfaces/errors'\nimport { verifyRecord } from '@libp2p/record/validators'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { Message, MESSAGE_TYPE } from '../message/index.js'\nimport * as utils from '../utils.js'\nimport {\n queryErrorEvent,\n finalPeerEvent,\n valueEvent\n} from '../query/events.js'\nimport { PeerDistanceList } from '../peer-list/peer-distance-list.js'\nimport { Libp2pRecord } from '@libp2p/record'\nimport { logger } from '@libp2p/logger'\nimport { keys } from '@libp2p/crypto'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { DHTRecord, DialingPeerEvent, FinalPeerEvent, QueryEvent, QueryOptions, Validators } from '@libp2p/interface-dht'\nimport type { RoutingTable } from '../routing-table/index.js'\nimport type { QueryManager } from '../query/manager.js'\nimport type { Network } from '../network.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { QueryFunc } from '../query/types.js'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { KadDHTComponents } from '../index.js'\n\nexport interface PeerRoutingInit {\n routingTable: RoutingTable\n network: Network\n validators: Validators\n queryManager: QueryManager\n lan: boolean\n}\n\nexport class PeerRouting {\n private readonly components: KadDHTComponents\n private readonly log: Logger\n private readonly routingTable: RoutingTable\n private readonly network: Network\n private readonly validators: Validators\n private readonly queryManager: QueryManager\n\n constructor (components: KadDHTComponents, init: PeerRoutingInit) {\n const { routingTable, network, validators, queryManager, lan } = init\n\n this.components = components\n this.routingTable = routingTable\n this.network = network\n this.validators = validators\n this.queryManager = queryManager\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:peer-routing`)\n }\n\n /**\n * Look if we are connected to a peer with the given id.\n * Returns its id and addresses, if found, otherwise `undefined`.\n */\n async findPeerLocal (peer: PeerId): Promise {\n let peerData\n const p = await this.routingTable.find(peer)\n\n if (p != null) {\n this.log('findPeerLocal found %p in routing table', peer)\n\n try {\n peerData = await this.components.peerStore.get(p)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n if (peerData == null) {\n try {\n peerData = await this.components.peerStore.get(peer)\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n if (peerData != null) {\n this.log('findPeerLocal found %p in peer store', peer)\n\n return {\n id: peerData.id,\n multiaddrs: peerData.addresses.map((address) => address.multiaddr),\n protocols: []\n }\n }\n\n return undefined\n }\n\n /**\n * Get a value via rpc call for the given parameters\n */\n async * _getValueSingle (peer: PeerId, key: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n const msg = new Message(MESSAGE_TYPE.GET_VALUE, key, 0)\n yield * this.network.sendRequest(peer, msg, options)\n }\n\n /**\n * Get the public key directly from a node\n */\n async * getPublicKeyFromNode (peer: PeerId, options: AbortOptions = {}): AsyncGenerator {\n const pkKey = utils.keyForPublicKey(peer)\n\n for await (const event of this._getValueSingle(peer, pkKey, options)) {\n yield event\n\n if (event.name === 'PEER_RESPONSE' && event.record != null) {\n const recPeer = await peerIdFromKeys(keys.marshalPublicKey({ bytes: event.record.value }))\n\n // compare hashes of the pub key\n if (!recPeer.equals(peer)) {\n throw new CodeError('public key does not match id', 'ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID')\n }\n\n if (recPeer.publicKey == null) {\n throw new CodeError('public key missing', 'ERR_PUBLIC_KEY_MISSING')\n }\n\n yield valueEvent({ from: peer, value: recPeer.publicKey })\n }\n }\n\n throw new CodeError(`Node not responding with its public key: ${peer.toString()}`, 'ERR_INVALID_RECORD')\n }\n\n /**\n * Search for a peer with the given ID\n */\n async * findPeer (id: PeerId, options: QueryOptions = {}): AsyncGenerator {\n this.log('findPeer %p', id)\n\n // Try to find locally\n const pi = await this.findPeerLocal(id)\n\n // already got it\n if (pi != null) {\n this.log('found local')\n yield finalPeerEvent({\n from: this.components.peerId,\n peer: pi\n })\n return\n }\n\n const key = await utils.convertPeerId(id)\n const peers = this.routingTable.closestPeers(key)\n\n // sanity check\n const match = peers.find((p) => p.equals(id))\n\n if (match != null) {\n try {\n const peer = await this.components.peerStore.get(id)\n\n this.log('found in peerStore')\n yield finalPeerEvent({\n from: this.components.peerId,\n peer: {\n id: peer.id,\n multiaddrs: peer.addresses.map((address) => address.multiaddr),\n protocols: []\n }\n })\n\n return\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n const findPeerQuery: QueryFunc = async function * ({ peer, signal }) {\n const request = new Message(MESSAGE_TYPE.FIND_NODE, id.toBytes(), 0)\n\n for await (const event of self.network.sendRequest(peer, request, { signal })) {\n yield event\n\n if (event.name === 'PEER_RESPONSE') {\n const match = event.closer.find((p) => p.id.equals(id))\n\n // found the peer\n if (match != null) {\n yield finalPeerEvent({ from: event.from, peer: match })\n }\n }\n }\n }\n\n let foundPeer = false\n\n for await (const event of this.queryManager.run(id.toBytes(), peers, findPeerQuery, options)) {\n if (event.name === 'FINAL_PEER') {\n foundPeer = true\n }\n\n yield event\n }\n\n if (!foundPeer) {\n yield queryErrorEvent({ from: this.components.peerId, error: new CodeError('Not found', 'ERR_NOT_FOUND') })\n }\n }\n\n /**\n * Kademlia 'node lookup' operation on a key, which could be a the\n * bytes from a multihash or a peer ID\n */\n async * getClosestPeers (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n this.log('getClosestPeers to %b', key)\n const id = await utils.convertBuffer(key)\n const tablePeers = this.routingTable.closestPeers(id)\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n const peers = new PeerDistanceList(id, this.routingTable.kBucketSize)\n await Promise.all(tablePeers.map(async peer => { await peers.add(peer) }))\n\n const getCloserPeersQuery: QueryFunc = async function * ({ peer, signal }) {\n self.log('closerPeersSingle %s from %p', uint8ArrayToString(key, 'base32'), peer)\n const request = new Message(MESSAGE_TYPE.FIND_NODE, key, 0)\n\n yield * self.network.sendRequest(peer, request, { signal })\n }\n\n for await (const event of this.queryManager.run(key, tablePeers, getCloserPeersQuery, options)) {\n yield event\n\n if (event.name === 'PEER_RESPONSE') {\n await Promise.all(event.closer.map(async peerData => { await peers.add(peerData.id) }))\n }\n }\n\n this.log('found %d peers close to %b', peers.length, key)\n\n for (const peer of peers.peers) {\n yield finalPeerEvent({\n from: this.components.peerId,\n peer: {\n id: peer,\n multiaddrs: (await (this.components.peerStore.addressBook.get(peer)) ?? []).map(addr => addr.multiaddr),\n protocols: []\n }\n })\n }\n }\n\n /**\n * Query a particular peer for the value for the given key.\n * It will either return the value or a list of closer peers.\n *\n * Note: The peerStore is updated with new addresses found for the given peer.\n */\n async * getValueOrPeers (peer: PeerId, key: Uint8Array, options: AbortOptions = {}): AsyncGenerator {\n for await (const event of this._getValueSingle(peer, key, options)) {\n if (event.name === 'PEER_RESPONSE') {\n if (event.record != null) {\n // We have a record\n try {\n await this._verifyRecordOnline(event.record)\n } catch (err: any) {\n const errMsg = 'invalid record received, discarded'\n this.log(errMsg)\n\n yield queryErrorEvent({ from: event.from, error: new CodeError(errMsg, 'ERR_INVALID_RECORD') })\n continue\n }\n }\n }\n\n yield event\n }\n }\n\n /**\n * Verify a record, fetching missing public keys from the network.\n * Throws an error if the record is invalid.\n */\n async _verifyRecordOnline (record: DHTRecord): Promise {\n if (record.timeReceived == null) {\n throw new CodeError('invalid record received', 'ERR_INVALID_RECORD')\n }\n\n await verifyRecord(this.validators, new Libp2pRecord(record.key, record.value, record.timeReceived))\n }\n\n /**\n * Get the nearest peers to the given query, but if closer\n * than self\n */\n async getCloserPeersOffline (key: Uint8Array, closerThan: PeerId): Promise {\n const id = await utils.convertBuffer(key)\n const ids = this.routingTable.closestPeers(id)\n const output: PeerInfo[] = []\n\n for (const peerId of ids) {\n if (peerId.equals(closerThan)) {\n continue\n }\n\n try {\n const addresses = await this.components.peerStore.addressBook.get(peerId)\n const protocols = await this.components.peerStore.protoBook.get(peerId)\n\n output.push({\n id: peerId,\n multiaddrs: addresses.map((address) => address.multiaddr),\n protocols\n })\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n }\n\n if (output.length > 0) {\n this.log('getCloserPeersOffline found %d peer(s) closer to %b than %p', output.length, key, closerThan)\n } else {\n this.log('getCloserPeersOffline could not find peer closer to %b than %p', key, closerThan)\n }\n\n return output\n }\n}\n", "import cache from 'hashlru'\nimport varint from 'varint'\nimport { Key } from 'interface-datastore/key'\nimport Queue from 'p-queue'\nimport {\n PROVIDERS_CLEANUP_INTERVAL,\n PROVIDERS_VALIDITY,\n PROVIDERS_LRU_CACHE_SIZE,\n PROVIDER_KEY_PREFIX\n} from './constants.js'\nimport { logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Datastore } from 'interface-datastore'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:kad-dht:providers')\n\nexport interface ProvidersInit {\n cacheSize?: number\n /**\n * How often invalid records are cleaned. (in seconds)\n */\n cleanupInterval?: number\n /**\n * How long is a provider valid for. (in seconds)\n */\n provideValidity?: number\n}\n\nexport interface ProvidersComponents {\n datastore: Datastore\n}\n\n/**\n * This class manages known providers.\n * A provider is a peer that we know to have the content for a given CID.\n *\n * Every `cleanupInterval` providers are checked if they\n * are still valid, i.e. younger than the `provideValidity`.\n * If they are not, they are deleted.\n *\n * To ensure the list survives restarts of the daemon,\n * providers are stored in the datastore, but to ensure\n * access is fast there is an LRU cache in front of that.\n */\nexport class Providers implements Startable {\n private readonly components: ProvidersComponents\n private readonly cache: ReturnType\n private readonly cleanupInterval: number\n private readonly provideValidity: number\n private readonly syncQueue: Queue\n private started: boolean\n private cleaner?: NodeJS.Timer\n\n constructor (components: ProvidersComponents, init: ProvidersInit = {}) {\n const { cacheSize, cleanupInterval, provideValidity } = init\n\n this.components = components\n this.cleanupInterval = cleanupInterval ?? PROVIDERS_CLEANUP_INTERVAL\n this.provideValidity = provideValidity ?? PROVIDERS_VALIDITY\n this.cache = cache(cacheSize ?? PROVIDERS_LRU_CACHE_SIZE)\n this.syncQueue = new Queue({ concurrency: 1 })\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * Start the provider cleanup service\n */\n async start (): Promise {\n if (this.started) {\n return\n }\n\n this.started = true\n\n this.cleaner = setInterval(\n () => {\n this._cleanup().catch(err => {\n log.error(err)\n })\n },\n this.cleanupInterval\n )\n }\n\n /**\n * Release any resources.\n */\n async stop (): Promise {\n this.started = false\n\n if (this.cleaner != null) {\n clearInterval(this.cleaner)\n this.cleaner = undefined\n }\n }\n\n /**\n * Check all providers if they are still valid, and if not delete them\n */\n async _cleanup (): Promise {\n await this.syncQueue.add(async () => {\n const start = Date.now()\n\n let count = 0\n let deleteCount = 0\n const deleted = new Map>()\n const batch = this.components.datastore.batch()\n\n // Get all provider entries from the datastore\n const query = this.components.datastore.query({ prefix: PROVIDER_KEY_PREFIX })\n\n for await (const entry of query) {\n try {\n // Add a delete to the batch for each expired entry\n const { cid, peerId } = parseProviderKey(entry.key)\n const time = readTime(entry.value).getTime()\n const now = Date.now()\n const delta = now - time\n const expired = delta > this.provideValidity\n\n log('comparing: %d - %d = %d > %d %s', now, time, delta, this.provideValidity, expired ? '(expired)' : '')\n\n if (expired) {\n deleteCount++\n batch.delete(entry.key)\n const peers = deleted.get(cid) ?? new Set()\n peers.add(peerId)\n deleted.set(cid, peers)\n }\n count++\n } catch (err: any) {\n log.error(err.message)\n }\n }\n\n // Commit the deletes to the datastore\n if (deleted.size > 0) {\n log('deleting %d / %d entries', deleteCount, count)\n await batch.commit()\n } else {\n log('nothing to delete')\n }\n\n // Clear expired entries from the cache\n for (const [cid, peers] of deleted) {\n const key = makeProviderKey(cid)\n const provs = this.cache.get(key)\n\n if (provs != null) {\n for (const peerId of peers) {\n provs.delete(peerId)\n }\n\n if (provs.size === 0) {\n this.cache.remove(key)\n } else {\n this.cache.set(key, provs)\n }\n }\n }\n\n log('Cleanup successful (%dms)', Date.now() - start)\n })\n }\n\n /**\n * Get the currently known provider peer ids for a given CID\n */\n async _getProvidersMap (cid: CID): Promise> {\n const cacheKey = makeProviderKey(cid)\n let provs: Map = this.cache.get(cacheKey)\n\n if (provs == null) {\n provs = await loadProviders(this.components.datastore, cid)\n this.cache.set(cacheKey, provs)\n }\n\n return provs\n }\n\n /**\n * Add a new provider for the given CID\n */\n async addProvider (cid: CID, provider: PeerId): Promise {\n await this.syncQueue.add(async () => {\n log('%p provides %s', provider, cid)\n const provs = await this._getProvidersMap(cid)\n\n log('loaded %s provs', provs.size)\n const now = new Date()\n provs.set(provider.toString(), now)\n\n const dsKey = makeProviderKey(cid)\n this.cache.set(dsKey, provs)\n\n await writeProviderEntry(this.components.datastore, cid, provider, now)\n })\n }\n\n /**\n * Get a list of providers for the given CID\n */\n async getProviders (cid: CID): Promise {\n return await this.syncQueue.add(async () => {\n log('get providers for %s', cid)\n const provs = await this._getProvidersMap(cid)\n\n return [...provs.keys()].map(peerIdStr => {\n return peerIdFromString(peerIdStr)\n })\n }, {\n // no timeout is specified for this queue so it will not\n // throw, but this is required to get the right return\n // type since p-queue@7.3.4\n throwOnTimeout: true\n })\n }\n}\n\n/**\n * Encode the given key its matching datastore key\n */\nfunction makeProviderKey (cid: CID | string): string {\n const cidStr = typeof cid === 'string' ? cid : uint8ArrayToString(cid.multihash.bytes, 'base32')\n\n return `${PROVIDER_KEY_PREFIX}/${cidStr}`\n}\n\n/**\n * Write a provider into the given store\n */\nasync function writeProviderEntry (store: Datastore, cid: CID, peer: PeerId, time: Date): Promise {\n const dsKey = [\n makeProviderKey(cid),\n '/',\n peer.toString()\n ].join('')\n\n const key = new Key(dsKey)\n const buffer = Uint8Array.from(varint.encode(time.getTime()))\n\n await store.put(key, buffer)\n}\n\n/**\n * Parse the CID and provider peer id from the key\n */\nfunction parseProviderKey (key: Key): { cid: string, peerId: string } {\n const parts = key.toString().split('/')\n\n if (parts.length !== 5) {\n throw new Error(`incorrectly formatted provider entry key in datastore: ${key.toString()}`)\n }\n\n return {\n cid: parts[3],\n peerId: parts[4]\n }\n}\n\n/**\n * Load providers for the given CID from the store\n */\nasync function loadProviders (store: Datastore, cid: CID): Promise> {\n const providers = new Map()\n const query = store.query({ prefix: makeProviderKey(cid) })\n\n for await (const entry of query) {\n const { peerId } = parseProviderKey(entry.key)\n providers.set(peerId, readTime(entry.value))\n }\n\n return providers\n}\n\nfunction readTime (buf: Uint8Array): Date {\n return new Date(varint.decode(buf))\n}\n", "import { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport {\n ALPHA, K, DEFAULT_QUERY_TIMEOUT\n} from '../constants.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { queryPath } from './query-path.js'\nimport merge from 'it-merge'\nimport { setMaxListeners } from 'events'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { QueryFunc } from './types.js'\nimport type { QueryEvent, QueryOptions } from '@libp2p/interface-dht'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport type { Metric, Metrics } from '@libp2p/interface-metrics'\n\nexport interface CleanUpEvents {\n 'cleanup': CustomEvent\n}\n\nexport interface QueryManagerInit {\n lan?: boolean\n disjointPaths?: number\n alpha?: number\n}\n\nexport interface QueryManagerComponents {\n peerId: PeerId\n metrics?: Metrics\n}\n\n/**\n * Keeps track of all running queries\n */\nexport class QueryManager implements Startable {\n private readonly components: QueryManagerComponents\n private readonly lan: boolean\n public disjointPaths: number\n private readonly alpha: number\n private readonly controllers: Set\n private running: boolean\n private queries: number\n private metrics?: {\n runningQueries: Metric\n queryTime: Metric\n }\n\n constructor (components: QueryManagerComponents, init: QueryManagerInit) {\n const { lan = false, disjointPaths = K, alpha = ALPHA } = init\n\n this.components = components\n this.disjointPaths = disjointPaths ?? K\n this.controllers = new Set()\n this.running = false\n this.alpha = alpha ?? ALPHA\n this.lan = lan\n this.queries = 0\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * Starts the query manager\n */\n async start (): Promise {\n this.running = true\n\n if (this.components.metrics != null && this.metrics == null) {\n this.metrics = {\n runningQueries: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_running_queries`),\n queryTime: this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan ? 'lan' : 'wan'}_query_time_seconds`)\n }\n }\n }\n\n /**\n * Stops all queries\n */\n async stop (): Promise {\n this.running = false\n\n for (const controller of this.controllers) {\n controller.abort()\n }\n\n this.controllers.clear()\n }\n\n async * run (key: Uint8Array, peers: PeerId[], queryFunc: QueryFunc, options: QueryOptions = {}): AsyncGenerator {\n if (!this.running) {\n throw new Error('QueryManager not started')\n }\n\n const stopQueryTimer = this.metrics?.queryTime.timer()\n let timeoutController\n\n if (options.signal == null) {\n // don't let queries run forever\n timeoutController = new TimeoutController(DEFAULT_QUERY_TIMEOUT)\n options.signal = timeoutController.signal\n\n // this signal will get listened to for network requests, etc\n // so make sure we don't make a lot of noise in the logs\n try {\n if (setMaxListeners != null) {\n setMaxListeners(Infinity, timeoutController.signal)\n }\n } catch {} // fails on node < 15.4\n }\n\n // allow us to stop queries on shut down\n const abortController = new AbortController()\n this.controllers.add(abortController)\n const signals = [abortController.signal]\n\n if (options.signal != null) {\n signals.push(options.signal)\n }\n\n const signal = anySignal(signals)\n\n // this signal will get listened to for every invocation of queryFunc\n // so make sure we don't make a lot of noise in the logs\n try {\n if (setMaxListeners != null) {\n setMaxListeners(Infinity, signal)\n }\n } catch {} // fails on node < 15.4\n\n const log = logger(`libp2p:kad-dht:${this.lan ? 'lan' : 'wan'}:query:` + uint8ArrayToString(key, 'base58btc'))\n\n // query a subset of peers up to `kBucketSize / 2` in length\n const peersToQuery = peers.slice(0, Math.min(this.disjointPaths, peers.length))\n const startTime = Date.now()\n const cleanUp = new EventEmitter()\n\n try {\n log('query:start')\n this.queries++\n this.metrics?.runningQueries.update(this.queries)\n\n if (peers.length === 0) {\n log.error('Running query with no peers')\n return\n }\n\n // make sure we don't get trapped in a loop\n const peersSeen = new PeerSet()\n\n // Create query paths from the starting peers\n const paths = peersToQuery.map((peer, index) => {\n return queryPath({\n key,\n startingPeer: peer,\n ourPeerId: this.components.peerId,\n signal,\n query: queryFunc,\n pathIndex: index,\n numPaths: peersToQuery.length,\n alpha: this.alpha,\n cleanUp,\n queryFuncTimeout: options.queryFuncTimeout,\n log,\n peersSeen\n })\n })\n\n // Execute the query along each disjoint path and yield their results as they become available\n for await (const event of merge(...paths)) {\n yield event\n\n if (event.name === 'QUERY_ERROR') {\n log('error', event.error)\n }\n }\n } catch (err: any) {\n if (!this.running && err.code === 'ERR_QUERY_ABORTED') {\n // ignore query aborted errors that were thrown during query manager shutdown\n } else {\n throw err\n }\n } finally {\n this.controllers.delete(abortController)\n\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n this.queries--\n this.metrics?.runningQueries.update(this.queries)\n\n if (stopQueryTimer != null) {\n stopQueryTimer()\n }\n\n cleanUp.dispatchEvent(new CustomEvent('cleanup'))\n log('query:done in %dms', Date.now() - startTime)\n }\n }\n}\n", "import Queue from 'p-queue'\nimport { xor } from 'uint8arrays/xor'\nimport { toString } from 'uint8arrays/to-string'\nimport defer from 'p-defer'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { convertPeerId, convertBuffer } from '../utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport { queryErrorEvent } from './events.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { CleanUpEvents } from './manager.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { QueryFunc } from '../query/types.js'\nimport type { QueryEvent } from '@libp2p/interface-dht'\nimport type { PeerSet } from '@libp2p/peer-collections'\n\nconst MAX_XOR = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')\n\nexport interface QueryPathOptions {\n /**\n * What are we trying to find\n */\n key: Uint8Array\n\n /**\n * Where we start our query\n */\n startingPeer: PeerId\n\n /**\n * Who we are\n */\n ourPeerId: PeerId\n\n /**\n * When to stop querying\n */\n signal: AbortSignal\n\n /**\n * The query function to run with each peer\n */\n query: QueryFunc\n\n /**\n * How many concurrent node/value lookups to run\n */\n alpha: number\n\n /**\n * How many concurrent node/value lookups to run\n */\n pathIndex: number\n\n /**\n * How many concurrent node/value lookups to run\n */\n numPaths: number\n\n /**\n * will emit a 'cleanup' event if the caller exits the for..await of early\n */\n cleanUp: EventEmitter\n\n /**\n * A timeout for queryFunc in ms\n */\n queryFuncTimeout?: number\n\n /**\n * Query log\n */\n log: Logger\n\n /**\n * Set of peers seen by this and other paths\n */\n peersSeen: PeerSet\n}\n\n/**\n * Walks a path through the DHT, calling the passed query function for\n * every peer encountered that we have not seen before\n */\nexport async function * queryPath (options: QueryPathOptions): AsyncGenerator {\n const { key, startingPeer, ourPeerId, signal, query, alpha, pathIndex, numPaths, cleanUp, queryFuncTimeout, log, peersSeen } = options\n // Only ALPHA node/value lookups are allowed at any given time for each process\n // https://github.com/libp2p/specs/tree/master/kad-dht#alpha-concurrency-parameter-%CE%B1\n const queue = new Queue({\n concurrency: alpha\n })\n\n // perform lookups on kadId, not the actual value\n const kadId = await convertBuffer(key)\n\n /**\n * Adds the passed peer to the query queue if it's not us and no\n * other path has passed through this peer\n */\n function queryPeer (peer: PeerId, peerKadId: Uint8Array): void {\n if (peer == null) {\n return\n }\n\n peersSeen.add(peer)\n\n const peerXor = BigInt('0x' + toString(xor(peerKadId, kadId), 'base16'))\n\n queue.add(async () => {\n let timeout\n const signals = [signal]\n\n if (queryFuncTimeout != null) {\n timeout = new TimeoutController(queryFuncTimeout)\n signals.push(timeout.signal)\n }\n\n const compoundSignal = anySignal(signals)\n\n try {\n for await (const event of query({\n key,\n peer,\n signal: compoundSignal,\n pathIndex,\n numPaths\n })) {\n if (compoundSignal.aborted) {\n return\n }\n\n // if there are closer peers and the query has not completed, continue the query\n if (event.name === 'PEER_RESPONSE') {\n for (const closerPeer of event.closer) {\n if (peersSeen.has(closerPeer.id)) { // eslint-disable-line max-depth\n log('already seen %p in query', closerPeer.id)\n continue\n }\n\n if (ourPeerId.equals(closerPeer.id)) { // eslint-disable-line max-depth\n log('not querying ourselves')\n continue\n }\n\n const closerPeerKadId = await convertPeerId(closerPeer.id)\n const closerPeerXor = BigInt('0x' + toString(xor(closerPeerKadId, kadId), 'base16'))\n\n // only continue query if closer peer is actually closer\n if (closerPeerXor > peerXor) { // eslint-disable-line max-depth\n log('skipping %p as they are not closer to %b than %p', closerPeer.id, key, peer)\n continue\n }\n\n log('querying closer peer %p', closerPeer.id)\n queryPeer(closerPeer.id, closerPeerKadId)\n }\n }\n\n // TODO: we have upgraded to p-queue@7, this should no longer be necessary\n queue.emit('completed', event)\n }\n\n timeout?.clear()\n } catch (err: any) {\n if (signal.aborted) {\n // TODO: we have upgraded to p-queue@7, this should no longer be necessary\n queue.emit('error', err)\n } else {\n // TODO: we have upgraded to p-queue@7, this should no longer be necessary\n queue.emit('completed', queryErrorEvent({\n from: peer,\n error: err\n }))\n }\n } finally {\n timeout?.clear()\n }\n }, {\n // use xor value as the queue priority - closer peers should execute first\n // subtract it from MAX_XOR because higher priority values execute sooner\n\n // @ts-expect-error this is supposed to be a Number but it's ok to use BigInts\n // as long as all priorities are BigInts since we won't mix BigInts and Number\n // values in arithmetic operations\n priority: MAX_XOR - peerXor\n }).catch(err => {\n log.error(err)\n })\n }\n\n // begin the query with the starting peer\n queryPeer(startingPeer, await convertPeerId(startingPeer))\n\n // yield results as they come in\n yield * toGenerator(queue, signal, cleanUp, log)\n}\n\nasync function * toGenerator (queue: Queue, signal: AbortSignal, cleanUp: EventEmitter, log: Logger): AsyncGenerator {\n let deferred = defer()\n let running = true\n const results: QueryEvent[] = []\n\n const cleanup = (): void => {\n if (!running) {\n return\n }\n\n log('clean up queue, results %d, queue size %d, pending tasks %d', results.length, queue.size, queue.pending)\n\n running = false\n queue.clear()\n results.splice(0, results.length)\n }\n\n queue.on('completed', result => {\n results.push(result)\n deferred.resolve()\n })\n queue.on('error', err => {\n log('queue error', err)\n cleanup()\n deferred.reject(err)\n })\n queue.on('idle', () => {\n log('queue idle')\n running = false\n deferred.resolve()\n })\n\n // clear the queue and throw if the query is aborted\n signal.addEventListener('abort', () => {\n log('abort queue')\n const wasRunning = running\n cleanup()\n\n if (wasRunning) {\n deferred.reject(new CodeError('Query aborted', 'ERR_QUERY_ABORTED'))\n }\n })\n\n // the user broke out of the loop early, ensure we resolve the deferred result\n // promise and clear the queue of any remaining jobs\n cleanUp.addEventListener('cleanup', () => {\n cleanup()\n deferred.resolve()\n })\n\n while (running) { // eslint-disable-line no-unmodified-loop-condition\n await deferred.promise\n deferred = defer()\n\n // yield all available results\n while (results.length > 0) {\n const result = results.shift()\n\n if (result != null) {\n yield result\n }\n }\n }\n\n // yield any remaining results\n yield * results\n}\n", "import { pushable } from 'it-pushable'\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nexport default async function * merge (...sources: Array | Iterable>): AsyncGenerator {\n const output = pushable({\n objectMode: true\n })\n\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n output.push(item)\n }\n })\n )\n\n output.end()\n } catch (err: any) {\n output.end(err)\n }\n })\n\n yield * output\n}\n", "import { CID } from 'multiformats/cid'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { logger } from '@libp2p/logger'\nimport type { Providers } from '../../providers'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { Message } from '../../message/index.js'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:add-provider')\n\nexport interface AddProviderHandlerInit {\n providers: Providers\n}\n\nexport class AddProviderHandler implements DHTMessageHandler {\n private readonly providers: Providers\n\n constructor (init: AddProviderHandlerInit) {\n const { providers } = init\n this.providers = providers\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n log('start')\n\n if (msg.key == null || msg.key.length === 0) {\n throw new CodeError('Missing key', 'ERR_MISSING_KEY')\n }\n\n let cid: CID\n try {\n // this is actually just the multihash, not the whole CID\n cid = CID.decode(msg.key)\n } catch (err: any) {\n throw new CodeError('Invalid CID', 'ERR_INVALID_CID')\n }\n\n if (msg.providerPeers == null || msg.providerPeers.length === 0) {\n log.error('no providers found in message')\n }\n\n await Promise.all(\n msg.providerPeers.map(async (pi) => {\n // Ignore providers not from the originator\n if (!pi.id.equals(peerId)) {\n log('invalid provider peer %p from %p', pi.id, peerId)\n return\n }\n\n if (pi.multiaddrs.length < 1) {\n log('no valid addresses for provider %p. Ignore', peerId)\n return\n }\n\n log('received provider %p for %s (addrs %s)', peerId, cid, pi.multiaddrs.map((m) => m.toString()))\n\n await this.providers.addProvider(cid, pi.id)\n })\n )\n\n return undefined\n }\n}\n", "import { Message } from '../../message/index.js'\nimport { logger } from '@libp2p/logger'\nimport {\n removePrivateAddresses,\n removePublicAddresses\n} from '../../utils.js'\nimport { equals as uint8ArrayEquals } from 'uint8arrays'\nimport { protocols } from '@multiformats/multiaddr'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { PeerRouting } from '../../peer-routing/index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:find-node')\n\nexport interface FindNodeHandlerInit {\n peerRouting: PeerRouting\n lan: boolean\n}\n\nexport interface FindNodeHandlerComponents {\n peerId: PeerId\n addressManager: AddressManager\n}\n\nexport class FindNodeHandler implements DHTMessageHandler {\n private readonly peerRouting: PeerRouting\n private readonly lan: boolean\n private readonly components: FindNodeHandlerComponents\n\n constructor (components: FindNodeHandlerComponents, init: FindNodeHandlerInit) {\n const { peerRouting, lan } = init\n\n this.components = components\n this.peerRouting = peerRouting\n this.lan = Boolean(lan)\n }\n\n /**\n * Process `FindNode` DHT messages\n */\n async handle (peerId: PeerId, msg: Message): Promise {\n log('incoming request from %p for peers closer to %b', peerId, msg.key)\n\n let closer: PeerInfo[] = []\n\n if (uint8ArrayEquals(this.components.peerId.toBytes(), msg.key)) {\n closer = [{\n id: this.components.peerId,\n multiaddrs: this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code)),\n protocols: []\n }]\n } else {\n closer = await this.peerRouting.getCloserPeersOffline(msg.key, peerId)\n }\n\n closer = closer\n .map(this.lan ? removePublicAddresses : removePrivateAddresses)\n .filter(({ multiaddrs }) => multiaddrs.length)\n\n const response = new Message(msg.type, new Uint8Array(0), msg.clusterLevel)\n\n if (closer.length > 0) {\n response.closerPeers = closer\n } else {\n log('could not find any peers closer to %b than %p', msg.key, peerId)\n }\n\n return response\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { Message } from '../../message/index.js'\nimport {\n removePrivateAddresses,\n removePublicAddresses\n} from '../../utils.js'\nimport { logger } from '@libp2p/logger'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { Providers } from '../../providers.js'\nimport type { PeerRouting } from '../../peer-routing/index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:get-providers')\n\nexport interface GetProvidersHandlerInit {\n peerRouting: PeerRouting\n providers: Providers\n lan: boolean\n}\n\nexport interface GetProvidersHandlerComponents {\n peerStore: PeerStore\n}\n\nexport class GetProvidersHandler implements DHTMessageHandler {\n private readonly components: GetProvidersHandlerComponents\n private readonly peerRouting: PeerRouting\n private readonly providers: Providers\n private readonly lan: boolean\n\n constructor (components: GetProvidersHandlerComponents, init: GetProvidersHandlerInit) {\n const { peerRouting, providers, lan } = init\n\n this.components = components\n this.peerRouting = peerRouting\n this.providers = providers\n this.lan = Boolean(lan)\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n let cid\n try {\n cid = CID.decode(msg.key)\n } catch (err: any) {\n throw new CodeError('Invalid CID', 'ERR_INVALID_CID')\n }\n\n log('%p asking for providers for %s', peerId, cid)\n\n const [peers, closer] = await Promise.all([\n this.providers.getProviders(cid),\n this.peerRouting.getCloserPeersOffline(msg.key, peerId)\n ])\n\n const providerPeers = await this._getPeers(peers)\n const closerPeers = await this._getPeers(closer.map(({ id }) => id))\n const response = new Message(msg.type, msg.key, msg.clusterLevel)\n\n if (providerPeers.length > 0) {\n response.providerPeers = providerPeers\n }\n\n if (closerPeers.length > 0) {\n response.closerPeers = closerPeers\n }\n\n log('got %s providers %s closerPeers', providerPeers.length, closerPeers.length)\n return response\n }\n\n async _getAddresses (peerId: PeerId): Promise {\n const addrs = await this.components.peerStore.addressBook.get(peerId)\n\n return addrs.map(address => address.multiaddr)\n }\n\n async _getPeers (peerIds: PeerId[]): Promise {\n const output: PeerInfo[] = []\n const addrFilter = this.lan ? removePublicAddresses : removePrivateAddresses\n\n for (const peerId of peerIds) {\n const peer = addrFilter({\n id: peerId,\n multiaddrs: await this._getAddresses(peerId),\n protocols: []\n })\n\n if (peer.multiaddrs.length > 0) {\n output.push(peer)\n }\n }\n\n return output\n }\n}\n", "import { Libp2pRecord } from '@libp2p/record'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { Message, MESSAGE_TYPE } from '../../message/index.js'\nimport {\n MAX_RECORD_AGE\n} from '../../constants.js'\nimport { bufferToRecordKey, isPublicKeyKey, fromPublicKeyKey } from '../../utils.js'\nimport { logger } from '@libp2p/logger'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '../../peer-routing/index.js'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Datastore } from 'interface-datastore'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:get-value')\n\nexport interface GetValueHandlerInit {\n peerRouting: PeerRouting\n}\n\nexport interface GetValueHandlerComponents {\n peerStore: PeerStore\n datastore: Datastore\n}\n\nexport class GetValueHandler implements DHTMessageHandler {\n private readonly components: GetValueHandlerComponents\n private readonly peerRouting: PeerRouting\n\n constructor (components: GetValueHandlerComponents, init: GetValueHandlerInit) {\n const { peerRouting } = init\n\n this.components = components\n this.peerRouting = peerRouting\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n const key = msg.key\n\n log('%p asked for key %b', peerId, key)\n\n if (key == null || key.length === 0) {\n throw new CodeError('Invalid key', 'ERR_INVALID_KEY')\n }\n\n const response = new Message(MESSAGE_TYPE.GET_VALUE, key, msg.clusterLevel)\n\n if (isPublicKeyKey(key)) {\n log('is public key')\n const idFromKey = fromPublicKeyKey(key)\n let pubKey: Uint8Array | undefined\n\n try {\n const key = await this.components.peerStore.keyBook.get(idFromKey)\n\n if (key == null) {\n throw new CodeError('No public key found in key book', 'ERR_NOT_FOUND')\n }\n\n pubKey = key\n } catch (err: any) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n if (pubKey != null) {\n log('returning found public key')\n response.record = new Libp2pRecord(key, pubKey, new Date())\n return response\n }\n }\n\n const [record, closer] = await Promise.all([\n this._checkLocalDatastore(key),\n this.peerRouting.getCloserPeersOffline(msg.key, peerId)\n ])\n\n if (record != null) {\n log('had record for %b in local datastore', key)\n response.record = record\n }\n\n if (closer.length > 0) {\n log('had %s closer peers in routing table', closer.length)\n response.closerPeers = closer\n }\n\n return response\n }\n\n /**\n * Try to fetch a given record by from the local datastore.\n * Returns the record if it is still valid, meaning\n * - it was either authored by this node, or\n * - it was received less than `MAX_RECORD_AGE` ago.\n */\n async _checkLocalDatastore (key: Uint8Array): Promise {\n log('checkLocalDatastore looking for %b', key)\n const dsKey = bufferToRecordKey(key)\n\n // Fetch value from ds\n let rawRecord\n try {\n rawRecord = await this.components.datastore.get(dsKey)\n } catch (err: any) {\n if (err.code === 'ERR_NOT_FOUND') {\n return undefined\n }\n throw err\n }\n\n // Create record from the returned bytes\n const record = Libp2pRecord.deserialize(rawRecord)\n\n if (record == null) {\n throw new CodeError('Invalid record', 'ERR_INVALID_RECORD')\n }\n\n // Check validity: compare time received with max record age\n if (record.timeReceived == null ||\n Date.now() - record.timeReceived.getTime() > MAX_RECORD_AGE) {\n // If record is bad delete it and return\n await this.components.datastore.delete(dsKey)\n return undefined\n }\n\n // Record is valid\n return record\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport type { Message } from '../../message/index.js'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:kad-dht:rpc:handlers:ping')\n\nexport class PingHandler implements DHTMessageHandler {\n async handle (peerId: PeerId, msg: Message): Promise {\n log('ping from %p', peerId)\n return msg\n }\n}\n", "import { bufferToRecordKey } from '../../utils.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { verifyRecord } from '@libp2p/record/validators'\nimport { Logger, logger } from '@libp2p/logger'\nimport type { DHTMessageHandler } from '../index.js'\nimport type { Validators } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Message } from '../../message/index.js'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface PutValueHandlerInit {\n validators: Validators\n}\n\nexport interface PutValueHandlerComponents {\n datastore: Datastore\n}\n\nexport class PutValueHandler implements DHTMessageHandler {\n private readonly log: Logger\n private readonly components: PutValueHandlerComponents\n private readonly validators: Validators\n\n constructor (components: PutValueHandlerComponents, init: PutValueHandlerInit) {\n const { validators } = init\n\n this.components = components\n this.log = logger('libp2p:kad-dht:rpc:handlers:put-value')\n this.validators = validators\n }\n\n async handle (peerId: PeerId, msg: Message): Promise {\n const key = msg.key\n this.log('%p asked us to store value for key %b', peerId, key)\n\n const record = msg.record\n\n if (record == null) {\n const errMsg = `Empty record from: ${peerId.toString()}`\n\n this.log.error(errMsg)\n throw new CodeError(errMsg, 'ERR_EMPTY_RECORD')\n }\n\n try {\n await verifyRecord(this.validators, record)\n\n record.timeReceived = new Date()\n const recordKey = bufferToRecordKey(record.key)\n await this.components.datastore.put(recordKey, record.serialize().subarray())\n this.log('put record for %b into datastore under key %k', key, recordKey)\n } catch (err: any) {\n this.log('did not put record for key %b into datastore %o', key, err)\n }\n\n return msg\n }\n}\n", "import { pipe } from 'it-pipe'\nimport * as lp from 'it-length-prefixed'\nimport { Logger, logger } from '@libp2p/logger'\nimport type { RoutingTable } from '../routing-table'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Message, MESSAGE_TYPE } from '../message/index.js'\nimport { AddProviderHandler } from './handlers/add-provider.js'\nimport { FindNodeHandler, FindNodeHandlerComponents } from './handlers/find-node.js'\nimport { GetProvidersHandler, GetProvidersHandlerComponents } from './handlers/get-providers.js'\nimport { GetValueHandler, GetValueHandlerComponents } from './handlers/get-value.js'\nimport { PingHandler } from './handlers/ping.js'\nimport { PutValueHandler, PutValueHandlerComponents } from './handlers/put-value.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Providers } from '../providers'\nimport type { PeerRouting } from '../peer-routing'\nimport type { Validators } from '@libp2p/interface-dht'\n\nexport interface DHTMessageHandler {\n handle: (peerId: PeerId, msg: Message) => Promise\n}\n\nexport interface RPCInit {\n routingTable: RoutingTable\n providers: Providers\n peerRouting: PeerRouting\n validators: Validators\n lan: boolean\n}\n\nexport interface RPCComponents extends GetValueHandlerComponents, PutValueHandlerComponents, FindNodeHandlerComponents, GetProvidersHandlerComponents {\n\n}\n\nexport class RPC {\n private readonly handlers: Record\n private readonly routingTable: RoutingTable\n private readonly log: Logger\n\n constructor (components: RPCComponents, init: RPCInit) {\n const { providers, peerRouting, validators, lan } = init\n\n this.log = logger('libp2p:kad-dht:rpc')\n this.routingTable = init.routingTable\n this.handlers = {\n [MESSAGE_TYPE.GET_VALUE]: new GetValueHandler(components, { peerRouting }),\n [MESSAGE_TYPE.PUT_VALUE]: new PutValueHandler(components, { validators }),\n [MESSAGE_TYPE.FIND_NODE]: new FindNodeHandler(components, { peerRouting, lan }),\n [MESSAGE_TYPE.ADD_PROVIDER]: new AddProviderHandler({ providers }),\n [MESSAGE_TYPE.GET_PROVIDERS]: new GetProvidersHandler(components, { peerRouting, providers, lan }),\n [MESSAGE_TYPE.PING]: new PingHandler()\n }\n }\n\n /**\n * Process incoming DHT messages\n */\n async handleMessage (peerId: PeerId, msg: Message): Promise {\n try {\n await this.routingTable.add(peerId)\n } catch (err: any) {\n this.log.error('Failed to update the kbucket store', err)\n }\n\n // get handler & execute it\n const handler = this.handlers[msg.type]\n\n if (handler == null) {\n this.log.error(`no handler found for message type: ${msg.type}`)\n return\n }\n\n return await handler.handle(peerId, msg)\n }\n\n /**\n * Handle incoming streams on the dht protocol\n */\n onIncomingStream (data: IncomingStreamData): void {\n Promise.resolve().then(async () => {\n const { stream, connection } = data\n const peerId = connection.remotePeer\n\n try {\n await this.routingTable.add(peerId)\n } catch (err: any) {\n this.log.error(err)\n }\n\n const self = this // eslint-disable-line @typescript-eslint/no-this-alias\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n for await (const msg of source) {\n // handle the message\n const desMessage = Message.deserialize(msg)\n self.log('incoming %s from %p', desMessage.type, peerId)\n const res = await self.handleMessage(peerId, desMessage)\n\n // Not all handlers will return a response\n if (res != null) {\n yield res.serialize()\n }\n }\n },\n lp.encode(),\n stream\n )\n })\n .catch(err => {\n this.log.error(err)\n })\n }\n}\n", "import { createTopology } from '@libp2p/topology'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { Logger } from '@libp2p/logger'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { KadDHTComponents } from '.'\n\nexport interface TopologyListenerInit {\n protocol: string\n lan: boolean\n}\n\nexport interface TopologyListenerEvents {\n 'peer': CustomEvent\n}\n\n/**\n * Receives notifications of new peers joining the network that support the DHT protocol\n */\nexport class TopologyListener extends EventEmitter implements Startable {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly protocol: string\n private running: boolean\n private registrarId?: string\n\n constructor (components: KadDHTComponents, init: TopologyListenerInit) {\n super()\n\n const { protocol, lan } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:topology-listener:${lan ? 'lan' : 'wan'}`)\n this.running = false\n this.protocol = protocol\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * Start the network\n */\n async start (): Promise {\n if (this.running) {\n return\n }\n\n this.running = true\n\n // register protocol with topology\n const topology = createTopology({\n onConnect: (peerId) => {\n this.log('observed peer %p with protocol %s', peerId, this.protocol)\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerId\n }))\n }\n })\n this.registrarId = await this.components.registrar.register(this.protocol, topology)\n }\n\n /**\n * Stop all network activity\n */\n async stop (): Promise {\n this.running = false\n\n // unregister protocol and handlers\n if (this.registrarId != null) {\n this.components.registrar.unregister(this.registrarId)\n this.registrarId = undefined\n }\n }\n}\n", "import { setMaxListeners } from 'events'\nimport take from 'it-take'\nimport length from 'it-length'\nimport { QUERY_SELF_INTERVAL, QUERY_SELF_TIMEOUT, K } from './constants.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { anySignal } from 'any-signal'\nimport { logger, Logger } from '@libp2p/logger'\nimport type { PeerRouting } from './peer-routing/index.js'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { pipe } from 'it-pipe'\nimport type { KadDHTComponents } from './index.js'\n\nexport interface QuerySelfInit {\n lan: boolean\n peerRouting: PeerRouting\n count?: number\n interval?: number\n queryTimeout?: number\n}\n\n/**\n * Receives notifications of new peers joining the network that support the DHT protocol\n */\nexport class QuerySelf implements Startable {\n private readonly log: Logger\n private readonly components: KadDHTComponents\n private readonly peerRouting: PeerRouting\n private readonly count: number\n private readonly interval: number\n private readonly queryTimeout: number\n private running: boolean\n private timeoutId?: NodeJS.Timer\n private controller?: AbortController\n\n constructor (components: KadDHTComponents, init: QuerySelfInit) {\n const { peerRouting, lan, count, interval, queryTimeout } = init\n\n this.components = components\n this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:query-self`)\n this.running = false\n this.peerRouting = peerRouting\n this.count = count ?? K\n this.interval = interval ?? QUERY_SELF_INTERVAL\n this.queryTimeout = queryTimeout ?? QUERY_SELF_TIMEOUT\n }\n\n isStarted (): boolean {\n return this.running\n }\n\n async start (): Promise {\n if (this.running) {\n return\n }\n\n this.running = true\n this._querySelf()\n }\n\n async stop (): Promise {\n this.running = false\n\n if (this.timeoutId != null) {\n clearTimeout(this.timeoutId)\n }\n\n if (this.controller != null) {\n this.controller.abort()\n }\n }\n\n _querySelf (): void {\n Promise.resolve().then(async () => {\n const timeoutController = new TimeoutController(this.queryTimeout)\n\n try {\n this.controller = new AbortController()\n const signal = anySignal([this.controller.signal, timeoutController.signal])\n // this controller will get used for lots of dial attempts so make sure we don't cause warnings to be logged\n try {\n if (setMaxListeners != null) {\n setMaxListeners(Infinity, signal)\n }\n } catch {} // fails on node < 15.4\n const found = await pipe(\n this.peerRouting.getClosestPeers(this.components.peerId.toBytes(), {\n signal\n }),\n (source) => take(source, this.count),\n async (source) => await length(source)\n )\n\n this.log('query ran successfully - found %d peers', found)\n } catch (err: any) {\n this.log('query error', err)\n } finally {\n this.timeoutId = setTimeout(this._querySelf.bind(this), this.interval)\n timeoutController.clear()\n }\n }).catch(err => {\n this.log('query error', err)\n })\n }\n}\n", "\n/**\n * Stop iteration after n items have been received\n */\nexport default async function * take (source: AsyncIterable | Iterable, limit: number): AsyncGenerator {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n}\n", "import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\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 * ```js\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 peerDiscovery = Symbol.for('@libp2p/peer-discovery')\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n", "import { RoutingTable } from './routing-table/index.js'\nimport { RoutingTableRefresh } from './routing-table/refresh.js'\nimport { Network } from './network.js'\nimport { ContentFetching } from './content-fetching/index.js'\nimport { ContentRouting } from './content-routing/index.js'\nimport { PeerRouting } from './peer-routing/index.js'\nimport { Providers } from './providers.js'\nimport { QueryManager } from './query/manager.js'\nimport { RPC } from './rpc/index.js'\nimport { TopologyListener } from './topology-listener.js'\nimport { QuerySelf } from './query-self.js'\nimport {\n removePrivateAddresses,\n removePublicAddresses\n} from './utils.js'\nimport { Logger, logger } from '@libp2p/logger'\nimport type { QueryOptions, Validators, Selectors, DHT, QueryEvent } from '@libp2p/interface-dht'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport type { KadDHTComponents, KadDHTInit } from './index.js'\nimport { validators as recordValidators } from '@libp2p/record/validators'\nimport { selectors as recordSelectors } from '@libp2p/record/selectors'\nimport { symbol } from '@libp2p/interface-peer-discovery'\nimport { PROTOCOL_DHT, PROTOCOL_PREFIX, LAN_PREFIX } from './constants.js'\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\nexport interface SingleKadDHTInit extends KadDHTInit {\n /**\n * Whether to start up in lan or wan mode\n */\n lan?: boolean\n}\n\n/**\n * A DHT implementation modelled after Kademlia with S/Kademlia modifications.\n * Original implementation in go: https://github.com/libp2p/go-libp2p-kad-dht.\n */\nexport class KadDHT extends EventEmitter implements DHT {\n public protocol: string\n public routingTable: RoutingTable\n public providers: Providers\n public network: Network\n public peerRouting: PeerRouting\n\n public readonly components: KadDHTComponents\n private readonly log: Logger\n private running: boolean\n private readonly kBucketSize: number\n private clientMode: boolean\n private readonly lan: boolean\n private readonly validators: Validators\n private readonly selectors: Selectors\n private readonly queryManager: QueryManager\n private readonly contentFetching: ContentFetching\n private readonly contentRouting: ContentRouting\n private readonly routingTableRefresh: RoutingTableRefresh\n private readonly rpc: RPC\n private readonly topologyListener: TopologyListener\n private readonly querySelf: QuerySelf\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n\n /**\n * Create a new KadDHT\n */\n constructor (components: KadDHTComponents, init: SingleKadDHTInit) {\n super()\n\n const {\n kBucketSize,\n clientMode,\n validators,\n selectors,\n querySelfInterval,\n lan,\n protocolPrefix,\n pingTimeout,\n pingConcurrency,\n maxInboundStreams,\n maxOutboundStreams,\n providers: providersInit\n } = init\n\n this.running = false\n this.components = components\n this.lan = Boolean(lan)\n this.log = logger(`libp2p:kad-dht:${lan === true ? 'lan' : 'wan'}`)\n this.protocol = `${protocolPrefix ?? PROTOCOL_PREFIX}${lan === true ? LAN_PREFIX : ''}${PROTOCOL_DHT}`\n this.kBucketSize = kBucketSize ?? 20\n this.clientMode = clientMode ?? true\n this.maxInboundStreams = maxInboundStreams ?? DEFAULT_MAX_INBOUND_STREAMS\n this.maxOutboundStreams = maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS\n this.routingTable = new RoutingTable(components, {\n kBucketSize,\n lan: this.lan,\n pingTimeout,\n pingConcurrency,\n protocol: this.protocol\n })\n\n this.providers = new Providers(components, providersInit ?? {})\n\n this.validators = {\n ...recordValidators,\n ...validators\n }\n this.selectors = {\n ...recordSelectors,\n ...selectors\n }\n this.network = new Network(components, {\n protocol: this.protocol,\n lan: this.lan\n })\n this.queryManager = new QueryManager(components, {\n // Number of disjoint query paths to use - This is set to `kBucketSize/2` per the S/Kademlia paper\n disjointPaths: Math.ceil(this.kBucketSize / 2),\n lan\n })\n\n // DHT components\n this.peerRouting = new PeerRouting(components, {\n routingTable: this.routingTable,\n network: this.network,\n validators: this.validators,\n queryManager: this.queryManager,\n lan: this.lan\n })\n this.contentFetching = new ContentFetching(components, {\n validators: this.validators,\n selectors: this.selectors,\n peerRouting: this.peerRouting,\n queryManager: this.queryManager,\n routingTable: this.routingTable,\n network: this.network,\n lan: this.lan\n })\n this.contentRouting = new ContentRouting(components, {\n network: this.network,\n peerRouting: this.peerRouting,\n queryManager: this.queryManager,\n routingTable: this.routingTable,\n providers: this.providers,\n lan: this.lan\n })\n this.routingTableRefresh = new RoutingTableRefresh({\n peerRouting: this.peerRouting,\n routingTable: this.routingTable,\n lan: this.lan\n })\n this.rpc = new RPC(components, {\n routingTable: this.routingTable,\n providers: this.providers,\n peerRouting: this.peerRouting,\n validators: this.validators,\n lan: this.lan\n })\n this.topologyListener = new TopologyListener(components, {\n protocol: this.protocol,\n lan: this.lan\n })\n this.querySelf = new QuerySelf(components, {\n peerRouting: this.peerRouting,\n interval: querySelfInterval,\n lan: this.lan\n })\n\n // handle peers being discovered during processing of DHT messages\n this.network.addEventListener('peer', (evt) => {\n const peerData = evt.detail\n\n this.onPeerConnect(peerData).catch(err => {\n this.log.error('could not add %p to routing table', peerData.id, err)\n })\n\n this.dispatchEvent(new CustomEvent('peer', {\n detail: peerData\n }))\n })\n\n // handle peers being discovered via other peer discovery mechanisms\n this.topologyListener.addEventListener('peer', (evt) => {\n const peerId = evt.detail\n\n Promise.resolve().then(async () => {\n const multiaddrs = await this.components.peerStore.addressBook.get(peerId)\n\n const peerData = {\n id: peerId,\n multiaddrs: multiaddrs.map(addr => addr.multiaddr),\n protocols: []\n }\n\n await this.onPeerConnect(peerData)\n }).catch(err => {\n this.log.error('could not add %p to routing table', peerId, err)\n })\n })\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] (): '@libp2p/kad-dht' {\n return '@libp2p/kad-dht'\n }\n\n async onPeerConnect (peerData: PeerInfo): Promise {\n this.log('peer %p connected with protocols %s', peerData.id, peerData.protocols)\n\n if (this.lan) {\n peerData = removePublicAddresses(peerData)\n } else {\n peerData = removePrivateAddresses(peerData)\n }\n\n if (peerData.multiaddrs.length === 0) {\n this.log('ignoring %p as they do not have any %s addresses in %s', peerData.id, this.lan ? 'private' : 'public', peerData.multiaddrs.map(addr => addr.toString()))\n return\n }\n\n try {\n await this.routingTable.add(peerData.id)\n } catch (err: any) {\n this.log.error('could not add %p to routing table', peerData.id, err)\n }\n }\n\n /**\n * Is this DHT running.\n */\n isStarted (): boolean {\n return this.running\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async getMode (): Promise<'client' | 'server'> {\n return this.clientMode ? 'client' : 'server'\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async setMode (mode: 'client' | 'server'): Promise {\n await this.components.registrar.unhandle(this.protocol)\n\n if (mode === 'client') {\n this.log('enabling client mode')\n this.clientMode = true\n } else {\n this.log('enabling server mode')\n this.clientMode = false\n await this.components.registrar.handle(this.protocol, this.rpc.onIncomingStream.bind(this.rpc), {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams\n })\n }\n }\n\n /**\n * Start listening to incoming connections.\n */\n async start (): Promise {\n this.running = true\n\n // Only respond to queries when not in client mode\n await this.setMode(this.clientMode ? 'client' : 'server')\n\n await Promise.all([\n this.providers.start(),\n this.queryManager.start(),\n this.network.start(),\n this.routingTable.start(),\n this.topologyListener.start(),\n this.querySelf.start()\n ])\n\n await this.routingTableRefresh.start()\n }\n\n /**\n * Stop accepting incoming connections and sending outgoing\n * messages.\n */\n async stop (): Promise {\n this.running = false\n\n await Promise.all([\n this.providers.stop(),\n this.queryManager.stop(),\n this.network.stop(),\n this.routingTable.stop(),\n this.routingTableRefresh.stop(),\n this.topologyListener.stop(),\n this.querySelf.stop()\n ])\n }\n\n /**\n * Store the given key/value pair in the DHT\n */\n async * put (key: Uint8Array, value: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentFetching.put(key, value, options)\n }\n\n /**\n * Get the value that corresponds to the passed key\n */\n async * get (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentFetching.get(key, options)\n }\n\n // ----------- Content Routing\n\n /**\n * Announce to the network that we can provide given key's value\n */\n async * provide (key: CID, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentRouting.provide(key, this.components.addressManager.getAddresses(), options)\n }\n\n /**\n * Search the dht for providers of the given CID\n */\n async * findProviders (key: CID, options: QueryOptions = {}): AsyncGenerator {\n yield * this.contentRouting.findProviders(key, options)\n }\n\n // ----------- Peer Routing -----------\n\n /**\n * Search for a peer with the given ID\n */\n async * findPeer (id: PeerId, options: QueryOptions = {}): AsyncGenerator {\n yield * this.peerRouting.findPeer(id, options)\n }\n\n /**\n * Kademlia 'node lookup' operation\n */\n async * getClosestPeers (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * this.peerRouting.getClosestPeers(key, options)\n }\n\n async refreshRoutingTable (): Promise {\n this.routingTableRefresh.refreshTable(true)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport merge from 'it-merge'\nimport { queryErrorEvent } from './query/events.js'\nimport type { KadDHT } from './kad-dht.js'\nimport type { DualDHT, QueryEvent, QueryOptions } from '@libp2p/interface-dht'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport type { CID } from 'multiformats'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport { symbol } from '@libp2p/interface-peer-discovery'\nimport type { KadDHTComponents } from './index.js'\n\nconst log = logger('libp2p:kad-dht')\n\n/**\n * A DHT implementation modelled after Kademlia with S/Kademlia modifications.\n * Original implementation in go: https://github.com/libp2p/go-libp2p-kad-dht.\n */\nexport class DualKadDHT extends EventEmitter implements DualDHT {\n public readonly wan: KadDHT\n public readonly lan: KadDHT\n public readonly components: KadDHTComponents\n\n constructor (components: KadDHTComponents, wan: KadDHT, lan: KadDHT) {\n super()\n\n this.components = components\n this.wan = wan\n this.lan = lan\n\n // handle peers being discovered during processing of DHT messages\n this.wan.addEventListener('peer', (evt) => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: evt.detail\n }))\n })\n this.lan.addEventListener('peer', (evt) => {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: evt.detail\n }))\n })\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] (): '@libp2p/dual-kad-dht' {\n return '@libp2p/dual-kad-dht'\n }\n\n /**\n * Is this DHT running.\n */\n isStarted (): boolean {\n return this.wan.isStarted() && this.lan.isStarted()\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async getMode (): Promise<'client' | 'server'> {\n return await this.wan.getMode()\n }\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node will not\n */\n async setMode (mode: 'client' | 'server'): Promise {\n await this.wan.setMode(mode)\n }\n\n /**\n * Start listening to incoming connections.\n */\n async start (): Promise {\n await Promise.all([\n this.lan.start(),\n this.wan.start()\n ])\n }\n\n /**\n * Stop accepting incoming connections and sending outgoing\n * messages.\n */\n async stop (): Promise {\n await Promise.all([\n this.lan.stop(),\n this.wan.stop()\n ])\n }\n\n /**\n * Store the given key/value pair in the DHT\n */\n async * put (key: Uint8Array, value: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n for await (const event of merge(\n this.lan.put(key, value, options),\n this.wan.put(key, value, options)\n )) {\n yield event\n }\n }\n\n /**\n * Get the value that corresponds to the passed key\n */\n async * get (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n let queriedPeers = false\n let foundValue = false\n\n for await (const event of merge(\n this.lan.get(key, options),\n this.wan.get(key, options)\n )) {\n yield event\n\n if (event.name === 'DIALING_PEER') {\n queriedPeers = true\n }\n\n if (event.name === 'VALUE') {\n queriedPeers = true\n\n if (event.value != null) {\n foundValue = true\n }\n }\n\n if (event.name === 'SENDING_QUERY') {\n queriedPeers = true\n }\n }\n\n if (!queriedPeers) {\n throw new CodeError('No peers found in routing table!', 'ERR_NO_PEERS_IN_ROUTING_TABLE')\n }\n\n if (!foundValue) {\n yield queryErrorEvent({\n from: this.components.peerId,\n error: new CodeError('Not found', 'ERR_NOT_FOUND')\n })\n }\n }\n\n // ----------- Content Routing\n\n /**\n * Announce to the network that we can provide given key's value\n */\n async * provide (key: CID, options: AbortOptions = {}): AsyncGenerator {\n let sent = 0\n let success = 0\n const errors = []\n\n const dhts = [this.lan]\n\n // only run provide on the wan if we are in server mode\n if ((await this.wan.getMode()) === 'server') {\n dhts.push(this.wan)\n }\n\n for await (const event of merge(...dhts.map(dht => dht.provide(key, options)))) {\n yield event\n\n if (event.name === 'SENDING_QUERY') {\n sent++\n }\n\n if (event.name === 'QUERY_ERROR') {\n errors.push(event.error)\n }\n\n if (event.name === 'PEER_RESPONSE' && event.messageName === 'ADD_PROVIDER') {\n log('sent provider record for %s to %p', key, event.from)\n success++\n }\n }\n\n if (success === 0) {\n if (errors.length > 0) {\n // if all sends failed, throw an error to inform the caller\n throw new CodeError(`Failed to provide to ${errors.length} of ${sent} peers`, 'ERR_PROVIDES_FAILED', { errors })\n }\n\n throw new CodeError('Failed to provide - no peers found', 'ERR_PROVIDES_FAILED')\n }\n }\n\n /**\n * Search the dht for up to `K` providers of the given CID\n */\n async * findProviders (key: CID, options: QueryOptions = {}): AsyncGenerator {\n yield * merge(\n this.lan.findProviders(key, options),\n this.wan.findProviders(key, options)\n )\n }\n\n // ----------- Peer Routing -----------\n\n /**\n * Search for a peer with the given ID\n */\n async * findPeer (id: PeerId, options: QueryOptions = {}): AsyncGenerator {\n let queriedPeers = false\n\n for await (const event of merge(\n this.lan.findPeer(id, options),\n this.wan.findPeer(id, options)\n )) {\n yield event\n\n if (event.name === 'SENDING_QUERY' || event.name === 'FINAL_PEER') {\n queriedPeers = true\n }\n }\n\n if (!queriedPeers) {\n throw new CodeError('Peer lookup failed', 'ERR_LOOKUP_FAILED')\n }\n }\n\n /**\n * Kademlia 'node lookup' operation\n */\n async * getClosestPeers (key: Uint8Array, options: QueryOptions = {}): AsyncGenerator {\n yield * merge(\n this.lan.getClosestPeers(key, options),\n this.wan.getClosestPeers(key, options)\n )\n }\n\n async refreshRoutingTable (): Promise {\n await Promise.all([\n this.lan.refreshRoutingTable(),\n this.wan.refreshRoutingTable()\n ])\n }\n}\n", "import { KadDHT as SingleKadDHT } from './kad-dht.js'\nimport { DualKadDHT } from './dual-kad-dht.js'\nimport type { ProvidersInit } from './providers.js'\nimport type { Selectors, Validators } from '@libp2p/interface-dht'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface KadDHTInit {\n /**\n * How many peers to store in each kBucket (default 20)\n */\n kBucketSize?: number\n\n /**\n * Whether to start up as a DHT client or server\n */\n clientMode?: boolean\n\n /**\n * Record selectors\n */\n selectors?: Selectors\n\n /**\n * Record validators\n */\n validators?: Validators\n\n /**\n * How often to query our own PeerId in order to ensure we have a\n * good view on the KAD address space local to our PeerId\n */\n querySelfInterval?: number\n\n /**\n * A custom protocol prefix to use (default: '/ipfs')\n */\n protocolPrefix?: string\n\n /**\n * How long to wait in ms when pinging DHT peers to decide if they\n * should be evicted from the routing table or not (default 10000)\n */\n pingTimeout?: number\n\n /**\n * How many peers to ping in parallel when deciding if they should\n * be evicted from the routing table or not (default 10)\n */\n pingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the DHT protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the DHT protocol per-connection\n */\n maxOutboundStreams?: number\n\n /**\n * Initialization options for the Providers component\n */\n providers?: ProvidersInit\n}\n\nexport interface KadDHTComponents {\n peerId: PeerId\n registrar: Registrar\n addressManager: AddressManager\n peerStore: PeerStore\n metrics?: Metrics\n connectionManager: ConnectionManager\n datastore: Datastore\n}\n\nclass KadDHT extends DualKadDHT {\n constructor (components: KadDHTComponents, init?: KadDHTInit) {\n super(components, new SingleKadDHT(components, {\n protocolPrefix: '/ipfs',\n ...init,\n lan: false\n }),\n new SingleKadDHT(components, {\n protocolPrefix: '/ipfs',\n ...init,\n clientMode: false,\n lan: true\n }))\n }\n}\n\nexport function kadDHT (init?: KadDHTInit): (components: KadDHTComponents) => DualKadDHT {\n return (components: KadDHTComponents) => new KadDHT(components, init)\n}\n", "import { multiaddr } from '@multiformats/multiaddr'\nimport { P2P } from '@multiformats/mafmt'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\nimport type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { symbol } from '@libp2p/interface-peer-discovery'\nimport type { Startable } from '@libp2p/interfaces/dist/src/startable'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\nconst log = logger('libp2p:bootstrap')\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\nexport interface BootstrapInit {\n /**\n * The list of peer addresses in multi-address format\n */\n list: string[]\n\n /**\n * How long to wait before discovering bootstrap nodes\n */\n timeout?: number\n\n /**\n * Tag a bootstrap peer with this name before \"discovering\" it (default: 'bootstrap')\n */\n tagName?: string\n\n /**\n * The bootstrap peer tag will have this value (default: 50)\n */\n tagValue?: number\n\n /**\n * Cause the bootstrap peer tag to be removed after this number of ms (default: 2 minutes)\n */\n tagTTL?: number\n}\n\nexport interface BootstrapComponents {\n peerStore: PeerStore\n}\n\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends EventEmitter implements PeerDiscovery, Startable {\n static tag = 'bootstrap'\n\n private timer?: ReturnType\n private readonly list: PeerInfo[]\n private readonly timeout: number\n private readonly components: BootstrapComponents\n private readonly _init: BootstrapInit\n\n constructor (components: BootstrapComponents, options: BootstrapInit = { 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\n this.components = components\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT\n this.list = []\n\n for (const candidate of options.list) {\n if (!P2P.matches(candidate)) {\n log.error('Invalid multiaddr')\n continue\n }\n\n const ma = multiaddr(candidate)\n const peerIdStr = ma.getPeerId()\n\n if (peerIdStr == null) {\n log.error('Invalid bootstrap multiaddr without peer id')\n continue\n }\n\n const peerData: PeerInfo = {\n id: peerIdFromString(peerIdStr),\n multiaddrs: [ma],\n protocols: []\n }\n\n this.list.push(peerData)\n }\n\n this._init = options\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] (): '@libp2p/bootstrap' {\n return '@libp2p/bootstrap'\n }\n\n isStarted (): boolean {\n return Boolean(this.timer)\n }\n\n /**\n * Start emitting events\n */\n start (): void {\n if (this.isStarted()) {\n return\n }\n\n log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout)\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n log.error(err)\n })\n }, this.timeout)\n }\n\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers (): Promise {\n if (this.timer == null) {\n return\n }\n\n for (const peerData of this.list) {\n await this.components.peerStore.tagPeer(peerData.id, 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 // check we are still running\n if (this.timer == null) {\n return\n }\n\n this.dispatchEvent(new CustomEvent('peer', { detail: peerData }))\n }\n }\n\n /**\n * Stop emitting events\n */\n stop (): void {\n if (this.timer != null) {\n clearTimeout(this.timer)\n }\n\n this.timer = undefined\n }\n}\n\nexport function bootstrap (init: BootstrapInit): (components: BootstrapComponents) => PeerDiscovery {\n return (components: BootstrapComponents) => new Bootstrap(components, init)\n}\n", "/* eslint-env browser */\n\nexport default WebSocket\n", "\nimport { EventIterator } from 'event-iterator'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { WebSocket, ErrorEvent, MessageEvent } from 'ws'\n\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: any): obj is ArrayBuffer {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number')\n}\n\nexport interface ConnectedSource extends AsyncIterable {\n connected: () => Promise\n}\n\nexport default (socket: WebSocket): ConnectedSource => {\n socket.binaryType = 'arraybuffer'\n\n const connected = async () => await new Promise((resolve, reject) => {\n if (isConnected) {\n return resolve()\n }\n if (connError != null) {\n return reject(connError)\n }\n\n const cleanUp = (cont: () => void) => {\n socket.removeEventListener('open', onOpen)\n socket.removeEventListener('error', onError)\n cont()\n }\n\n const onOpen = () => cleanUp(resolve)\n const onError = (event: ErrorEvent) => {\n cleanUp(() => reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)))\n }\n\n socket.addEventListener('open', onOpen)\n socket.addEventListener('error', onError)\n })\n\n const source = (async function * () {\n const messages = new EventIterator(\n ({ push, stop, fail }) => {\n const onMessage = (event: MessageEvent) => {\n let data: Uint8Array | null = null\n\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data)\n }\n\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data)\n }\n\n if (event.data instanceof Uint8Array) {\n data = event.data\n }\n\n if (data == null) {\n return\n }\n\n push(data)\n }\n const onError = (event: ErrorEvent) => fail(event.error ?? new Error('Socket error'))\n\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('close', stop)\n\n return () => {\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('close', stop)\n }\n },\n { highWaterMark: Infinity }\n )\n\n await connected()\n\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk\n }\n }())\n\n let isConnected = socket.readyState === 1\n let connError: Error | null\n\n socket.addEventListener('open', () => {\n isConnected = true\n connError = null\n })\n\n socket.addEventListener('close', () => {\n isConnected = false\n connError = null\n })\n\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)\n }\n })\n\n return Object.assign(source, {\n connected\n })\n}\n", "import type { ErrorEvent, WebSocket } from 'ws'\n\nexport default (socket: WebSocket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed')\n }\n\n // if open, return\n if (socket.readyState === 1) {\n return\n }\n\n return new Promise((resolve, reject) => {\n function cleanup () {\n socket.removeEventListener('open', handleOpen)\n socket.removeEventListener('error', handleErr)\n }\n\n function handleOpen () {\n cleanup()\n resolve()\n }\n\n function handleErr (event: ErrorEvent) {\n cleanup()\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`))\n }\n\n socket.addEventListener('open', handleOpen)\n socket.addEventListener('error', handleErr)\n })\n}\n", "import ready from './ready.js'\nimport type { WebSocket } from 'ws'\nimport type { Sink } from 'it-stream-types'\n\nexport interface SinkOptions {\n closeOnEnd?: boolean\n}\n\nexport default (socket: WebSocket, options: SinkOptions) => {\n options = options ?? {}\n options.closeOnEnd = options.closeOnEnd !== false\n\n const sink: Sink> = async source => {\n for await (const data of source) {\n try {\n await ready(socket)\n } catch (err: any) {\n if (err.message === 'socket closed') break\n throw err\n }\n\n socket.send(data)\n }\n\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n return await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve()\n } else {\n const err = Object.assign(new Error('ws error'), { event })\n reject(err)\n }\n })\n\n setTimeout(() => socket.close())\n })\n }\n }\n\n return sink\n}\n", "import source from './source.js'\nimport sink from './sink.js'\nimport type WebSocket from './web-socket.js'\nimport type { SinkOptions } from './sink.js'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface DuplexWebSocket extends Duplex> {\n connected: () => Promise\n localAddress?: string\n localPort?: number\n remoteAddress: string\n remotePort: number\n close: () => Promise\n destroy: () => void\n socket: WebSocket\n}\n\nexport interface DuplexWebSocketOptions extends SinkOptions {\n remoteAddress?: string\n remotePort?: number\n}\n\nexport default (socket: WebSocket, options?: DuplexWebSocketOptions): DuplexWebSocket => {\n options = options ?? {}\n\n const connectedSource = source(socket)\n let remoteAddress: string | undefined = options.remoteAddress\n let remotePort: number | undefined = options.remotePort\n\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 } catch {}\n }\n\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port')\n }\n\n const duplex: DuplexWebSocket = {\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 } else {\n socket.close()\n }\n },\n remoteAddress,\n remotePort,\n socket\n }\n\n return duplex\n}\n", "import { relative } from 'iso-url'\n\nconst map = { http: 'ws', https: 'wss' }\nconst def = 'ws'\n\nexport default (url: string, location: string | Partial) => relative(url, location, map, def)\n", "// load websocket library if we are not in the browser\nimport WebSocket from './web-socket.js'\nimport duplex from './duplex.js'\nimport wsurl from './ws-url.js'\nimport type { ClientOptions } from 'ws'\nimport type { DuplexWebSocket } from './duplex.js'\nimport type { SinkOptions } from './sink.js'\n\nexport interface WebSocketOptions extends SinkOptions {\n websocket?: ClientOptions\n}\n\nexport function connect (addr: string, opts?: WebSocketOptions): DuplexWebSocket {\n const location = typeof window === 'undefined' ? '' : window.location\n opts = opts ?? {}\n\n const url = wsurl(addr, location.toString())\n const socket = new WebSocket(url, opts.websocket)\n\n return duplex(socket, opts)\n}\n", "import type { Listener } from '@libp2p/interface-transport'\n\nexport function createListener (): Listener {\n throw new Error('WebSocket Servers can not be created in the browser!')\n}\n", "import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport pTimeout from 'p-timeout'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\n\nconst log = logger('libp2p:websockets:socket')\n\nexport interface SocketToConnOptions extends AbortOptions {\n localAddr?: Multiaddr\n}\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn (stream: DuplexWebSocket, remoteAddr: Multiaddr, options?: SocketToConnOptions): MultiaddrConnection {\n options = options ?? {}\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if ((options?.signal) != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await stream.sink(source)\n } catch (err: any) {\n if (err.type !== 'aborted') {\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(stream.source, options.signal) : stream.source,\n\n remoteAddr,\n\n timeline: { open: Date.now() },\n\n async close () {\n const start = Date.now()\n\n try {\n await pTimeout(stream.close(), {\n milliseconds: CLOSE_TIMEOUT\n })\n } catch (err) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n\n stream.destroy()\n } finally {\n maConn.timeline.close = Date.now()\n }\n }\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\n return maConn\n}\n", "import * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport {\n CODE_CIRCUIT,\n CODE_P2P,\n CODE_TCP,\n CODE_WS,\n CODE_WSS\n} from './constants.js'\n\nexport function all (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function wss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function dnsWss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n\nexport function dnsWsOrWss (multiaddrs: Multiaddr[]): Multiaddr[] {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))\n }\n\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n", "import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface UpgraderOptions {\n skipEncryption?: boolean\n skipProtection?: boolean\n muxerFactory?: StreamMuxerFactory\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection, opts?: UpgraderOptions) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n", "import { connect, WebSocketOptions } from 'it-ws/client'\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport pDefer from 'p-defer'\nimport { logger } from '@libp2p/logger'\nimport { isBrowser, isWebWorker } from 'wherearewe'\nimport { createListener } from './listener.js'\nimport { socketToMaConn } from './socket-to-conn.js'\nimport * as filters from './filters.js'\nimport { Transport, MultiaddrFilter, symbol, CreateListenerOptions, DialOptions, Listener } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\nimport type { ClientOptions } from 'ws'\nimport type { Server } from 'http'\n\nconst log = logger('libp2p:websockets')\n\nexport interface WebSocketsInit extends AbortOptions, WebSocketOptions {\n filter?: MultiaddrFilter\n websocket?: ClientOptions\n server?: Server\n}\n\nclass WebSockets implements Transport {\n private readonly init?: WebSocketsInit\n\n constructor (init?: WebSocketsInit) {\n this.init = init\n }\n\n get [Symbol.toStringTag] (): string {\n return '@libp2p/websockets'\n }\n\n get [symbol] (): true {\n return true\n }\n\n async dial (ma: Multiaddr, options: DialOptions): Promise {\n log('dialing %s', ma)\n options = options ?? {}\n\n const socket = await this._connect(ma, options)\n const maConn = socketToMaConn(socket, ma)\n log('new outbound connection %s', maConn.remoteAddr)\n\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: AbortOptions): Promise {\n if (options?.signal?.aborted === true) {\n throw new AbortError()\n }\n const cOpts = ma.toOptions()\n log('dialing %s:%s', cOpts.host, cOpts.port)\n\n const errorPromise = pDefer()\n const errfn = (err: any): void => {\n log.error('connection error:', err)\n\n errorPromise.reject(err)\n }\n\n const rawSocket = connect(toUri(ma), this.init)\n\n if (rawSocket.socket.on != null) {\n rawSocket.socket.on('error', errfn)\n } else {\n rawSocket.socket.onerror = errfn\n }\n\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise])\n\n log('connected %s', ma)\n return rawSocket\n }\n\n // Allow abort via signal during connect\n let onAbort\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError())\n rawSocket.close().catch(err => {\n log.error('error closing raw socket', err)\n })\n }\n\n // Already aborted?\n if (options?.signal?.aborted === true) {\n onAbort(); return\n }\n\n options?.signal?.addEventListener('abort', onAbort)\n })\n\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()])\n } finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n log('connected %s', ma)\n return rawSocket\n }\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: CreateListenerOptions): Listener {\n return createListener({ ...this.init, ...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: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs)\n }\n\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.wss(multiaddrs)\n }\n\n return filters.all(multiaddrs)\n }\n}\n\nexport function webSockets (init: WebSocketsInit = {}): (components?: any) => Transport {\n return () => {\n return new WebSockets(init)\n }\n}\n", "import type { Source } from 'it-stream-types'\nimport varint from 'varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from './alloc-unsafe.js'\nimport { Message, MessageTypes } from './message-types.js'\nimport batchedBytes from 'it-batched-bytes'\n\nconst POOL_SIZE = 10 * 1024\n\nclass Encoder {\n private _pool: Uint8Array\n private _poolOffset: number\n\n constructor () {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n }\n\n /**\n * Encodes the given message and adds it to the passed list\n */\n write (msg: Message, list: Uint8ArrayList): void {\n const pool = this._pool\n let offset = this._poolOffset\n\n varint.encode(msg.id << 3 | msg.type, pool, offset)\n offset += varint.encode.bytes ?? 0\n\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 } else {\n varint.encode(0, pool, offset)\n }\n\n offset += varint.encode.bytes ?? 0\n\n const header = pool.subarray(this._poolOffset, offset)\n\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n } else {\n this._poolOffset = offset\n }\n\n list.append(header)\n\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}\n\nconst encoder = new Encoder()\n\n/**\n * Encode and yield one or more messages\n */\nexport async function * encode (source: Source, minSendBytes: number = 0): AsyncGenerator {\n if (minSendBytes == null || minSendBytes === 0) {\n // just send the messages\n for await (const messages of source) {\n const list = new Uint8ArrayList()\n\n for (const msg of messages) {\n encoder.write(msg, list)\n }\n\n yield list.subarray()\n }\n\n return\n }\n\n // batch messages up for sending\n yield * batchedBytes(source, {\n size: minSendBytes,\n serialize: (obj, list) => {\n for (const m of obj) {\n encoder.write(m, list)\n }\n }\n })\n}\n", "export function allocUnsafe (size: number): Uint8Array {\n return new Uint8Array(size)\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\ntype INITIATOR_NAME = 'NEW_STREAM' | 'MESSAGE' | 'CLOSE' | 'RESET'\ntype RECEIVER_NAME = 'MESSAGE' | 'CLOSE' | 'RESET'\ntype NAME = 'NEW_STREAM' | 'MESSAGE_INITIATOR' | 'CLOSE_INITIATOR' | 'RESET_INITIATOR' | 'MESSAGE_RECEIVER' | 'CLOSE_RECEIVER' | 'RESET_RECEIVER'\ntype CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport enum MessageTypes {\n NEW_STREAM = 0,\n MESSAGE_RECEIVER = 1,\n MESSAGE_INITIATOR = 2,\n CLOSE_RECEIVER = 3,\n CLOSE_INITIATOR = 4,\n RESET_RECEIVER = 5,\n RESET_INITIATOR = 6\n}\n\nexport const MessageTypeNames: Record = 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})\n\nexport const InitiatorMessageTypes: Record = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n})\n\nexport const ReceiverMessageTypes: Record = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n})\n\nexport interface NewStreamMessage {\n id: number\n type: MessageTypes.NEW_STREAM\n data: Uint8ArrayList\n}\n\nexport interface MessageReceiverMessage {\n id: number\n type: MessageTypes.MESSAGE_RECEIVER\n data: Uint8ArrayList\n}\n\nexport interface MessageInitiatorMessage {\n id: number\n type: MessageTypes.MESSAGE_INITIATOR\n data: Uint8ArrayList\n}\n\nexport interface CloseReceiverMessage {\n id: number\n type: MessageTypes.CLOSE_RECEIVER\n}\n\nexport interface CloseInitiatorMessage {\n id: number\n type: MessageTypes.CLOSE_INITIATOR\n}\n\nexport interface ResetReceiverMessage {\n id: number\n type: MessageTypes.RESET_RECEIVER\n}\n\nexport interface ResetInitiatorMessage {\n id: number\n type: MessageTypes.RESET_INITIATOR\n}\n\nexport type Message = NewStreamMessage | MessageReceiverMessage | MessageInitiatorMessage | CloseReceiverMessage | CloseInitiatorMessage | ResetReceiverMessage | ResetInitiatorMessage\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport defer from 'p-defer'\nimport type { Source } from 'it-stream-types'\n\nconst DEFAULT_BATCH_SIZE = 1024 * 1024\nconst DEFAULT_SERIALIZE = (buf: Uint8Array | Uint8ArrayList, list: Uint8ArrayList): void => { list.append(buf) }\n\nexport interface BatchedBytesOptions {\n /**\n * The minimum number of bytes that should be in a batch (default: 1MB)\n */\n size?: number\n\n /**\n * If this amount of time passes, yield all the bytes in the batch even\n * if they are below `size` (default: 0 - e.g. on every tick)\n */\n yieldAfter?: number\n}\n\nexport interface BatchedOptions {\n /**\n * The minimum number of bytes that should be in a batch (default: 1MB)\n */\n size?: number\n\n /**\n * If this amount of time passes, yield all the bytes in the batch even\n * if they are below `size` (default: 0 - e.g. on every tick)\n */\n yieldAfter?: number\n\n /**\n * If passed, this function should serialize the object and append the\n * result to the passed list\n */\n serialize: (object: T, list: Uint8ArrayList) => void\n}\n\n/**\n * Takes a stream of Uint8Arrays and/or Uint8ArrayLists and store them in\n * an internal buffer. Either once the buffer reaches the requested size\n * or the next event loop tick occurs, yield any bytes from the buffer.\n */\nfunction batchedBytes (source: Source, options?: BatchedBytesOptions): Source\nfunction batchedBytes (source: Source, options: BatchedOptions): Source\nasync function * batchedBytes (source: Source, options: any = {}): any {\n let buffer = new Uint8ArrayList()\n let ended = false\n let deferred = defer()\n\n let size = Number(options.size ?? DEFAULT_BATCH_SIZE)\n\n if (isNaN(size) || size === 0 || size < 0) {\n size = DEFAULT_BATCH_SIZE\n }\n\n const yieldAfter = options.yieldAfter ?? 0\n const serialize = options.serialize ?? DEFAULT_SERIALIZE\n\n void Promise.resolve().then(async () => {\n try {\n let timeout\n\n for await (const buf of source) {\n serialize(buf, buffer)\n\n if (buffer.byteLength >= size) {\n clearTimeout(timeout)\n deferred.resolve()\n continue\n }\n\n timeout = setTimeout(() => { // eslint-disable-line no-loop-func\n deferred.resolve()\n }, yieldAfter)\n }\n\n clearTimeout(timeout)\n deferred.resolve()\n } catch (err) {\n deferred.reject(err)\n } finally {\n ended = true\n }\n })\n\n while (!ended) { // eslint-disable-line no-unmodified-loop-condition\n await deferred.promise\n deferred = defer()\n if (buffer.byteLength > 0) {\n const b = buffer\n buffer = new Uint8ArrayList()\n yield b.subarray()\n }\n }\n}\n\nexport default batchedBytes\n", "import { MessageTypeNames, MessageTypes } from './message-types.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Message } from './message-types.js'\n\nexport const MAX_MSG_SIZE = 1 << 20 // 1MB\nexport const MAX_MSG_QUEUE_SIZE = 4 << 20 // 4MB\n\ninterface MessageHeader {\n id: number\n type: keyof typeof MessageTypeNames\n offset: number\n length: number\n}\n\nexport class Decoder {\n private readonly _buffer: Uint8ArrayList\n private _headerInfo: MessageHeader | null\n private readonly _maxMessageSize: number\n private readonly _maxUnprocessedMessageQueueSize: number\n\n constructor (maxMessageSize: number = MAX_MSG_SIZE, maxUnprocessedMessageQueueSize: number = MAX_MSG_QUEUE_SIZE) {\n this._buffer = new Uint8ArrayList()\n this._headerInfo = null\n this._maxMessageSize = maxMessageSize\n this._maxUnprocessedMessageQueueSize = maxUnprocessedMessageQueueSize\n }\n\n write (chunk: Uint8Array): Message[] {\n if (chunk == null || chunk.length === 0) {\n return []\n }\n\n this._buffer.append(chunk)\n\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\n const msgs: Message[] = []\n\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer)\n } catch (err: any) {\n if (err.code === 'ERR_MSG_TOO_BIG') {\n throw err\n }\n\n break // We haven't received enough data yet\n }\n }\n\n const { id, type, length, offset } = this._headerInfo\n const bufferedDataLength = this._buffer.length - offset\n\n if (bufferedDataLength < length) {\n break // not enough data yet\n }\n\n const msg: any = {\n id,\n type\n }\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\n msgs.push(msg)\n\n this._buffer.consume(offset + length)\n this._headerInfo = null\n }\n\n return msgs\n }\n\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader (data: Uint8ArrayList): MessageHeader {\n const {\n value: h,\n offset\n } = readVarInt(data)\n const {\n value: length,\n offset: end\n } = readVarInt(data, offset)\n\n const type = h & 7\n\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\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\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length }\n }\n}\n\nconst MSB = 0x80\nconst REST = 0x7F\n\nexport interface ReadVarIntResult {\n value: number\n offset: number\n}\n\nfunction readVarInt (buf: Uint8ArrayList, offset: number = 0): ReadVarIntResult {\n let res = 0\n let shift = 0\n let counter = offset\n let b: number\n const l = buf.length\n\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\n offset = counter - offset\n\n return {\n value: res,\n offset\n }\n}\n", "import { abortableSource } from 'abortable-iterator'\nimport { pushable } from 'it-pushable'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { MAX_MSG_SIZE } from './decode.js'\nimport { anySignal } from 'any-signal'\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { logger } from '@libp2p/logger'\nimport type { Message } from './message-types.js'\nimport type { StreamTimeline } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { MplexStream } from './mplex.js'\n\nconst log = logger('libp2p:mplex:stream')\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET'\nconst ERR_STREAM_ABORT = 'ERR_STREAM_ABORT'\nconst ERR_SINK_ENDED = 'ERR_SINK_ENDED'\nconst ERR_DOUBLE_SINK = 'ERR_DOUBLE_SINK'\n\nexport interface Options {\n id: number\n send: (msg: Message) => void\n name?: string\n onEnd?: (err?: Error) => void\n type?: 'initiator' | 'receiver'\n maxMsgSize?: number\n}\n\nexport function createStream (options: Options): MplexStream {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options\n\n const abortController = new AbortController()\n const resetController = new AbortController()\n const closeController = new AbortController()\n const Types = type === 'initiator' ? InitiatorMessageTypes : ReceiverMessageTypes\n const externalId = type === 'initiator' ? (`i${id}`) : `r${id}`\n const streamName = `${name == null ? id : name}`\n\n let sourceEnded = false\n let sinkEnded = false\n let sinkSunk = false\n let endErr: Error | undefined\n\n const timeline: StreamTimeline = {\n open: Date.now()\n }\n\n const onSourceEnd = (err?: Error): void => {\n if (sourceEnded) {\n return\n }\n\n sourceEnded = true\n log.trace('%s stream %s source end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sinkEnded) {\n stream.stat.timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const onSinkEnd = (err?: Error): void => {\n if (sinkEnded) {\n return\n }\n\n sinkEnded = true\n log.trace('%s stream %s sink end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sourceEnded) {\n timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const streamSource = pushable({\n onEnd: onSourceEnd\n })\n\n const stream: MplexStream = {\n // Close for both Reading and Writing\n close: () => {\n log.trace('%s stream %s close', type, streamName)\n\n stream.closeRead()\n stream.closeWrite()\n },\n\n // Close for reading\n closeRead: () => {\n log.trace('%s stream %s closeRead', type, streamName)\n\n if (sourceEnded) {\n return\n }\n\n streamSource.end()\n },\n\n // Close for writing\n closeWrite: () => {\n log.trace('%s stream %s closeWrite', type, streamName)\n\n if (sinkEnded) {\n return\n }\n\n closeController.abort()\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n // Close for reading and writing (local error)\n abort: (err: Error) => {\n log.trace('%s stream %s abort', type, streamName, err)\n // End the source with the passed error\n streamSource.end(err)\n abortController.abort()\n onSinkEnd(err)\n },\n\n // Close immediately for reading and writing (remote error)\n reset: () => {\n const err = new CodeError('stream reset', ERR_STREAM_RESET)\n resetController.abort()\n streamSource.end(err)\n onSinkEnd(err)\n },\n\n sink: async (source: Source) => {\n if (sinkSunk) {\n throw new CodeError('sink already called on stream', ERR_DOUBLE_SINK)\n }\n\n sinkSunk = true\n\n if (sinkEnded) {\n throw new CodeError('stream closed for writing', ERR_SINK_ENDED)\n }\n\n const signal = anySignal([\n abortController.signal,\n resetController.signal,\n closeController.signal\n ])\n\n try {\n source = abortableSource(source, signal)\n\n if (type === 'initiator') { // If initiator, open a new stream\n send({ id, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(streamName)) })\n }\n\n for await (let data of source) {\n while (data.length > 0) {\n if (data.length <= maxMsgSize) {\n send({ id, type: Types.MESSAGE, data: data instanceof Uint8Array ? new Uint8ArrayList(data) : data })\n break\n }\n data = data instanceof Uint8Array ? new Uint8ArrayList(data) : data\n send({ id, type: Types.MESSAGE, data: data.sublist(0, maxMsgSize) })\n data.consume(maxMsgSize)\n }\n }\n } catch (err: any) {\n if (err.type === 'aborted' && err.message === 'The operation was aborted') {\n if (closeController.signal.aborted) {\n return\n }\n\n if (resetController.signal.aborted) {\n err.message = 'stream reset'\n err.code = ERR_STREAM_RESET\n }\n\n if (abortController.signal.aborted) {\n err.message = 'stream aborted'\n err.code = ERR_STREAM_ABORT\n }\n }\n\n // Send no more data if this stream was remotely reset\n if (err.code === ERR_STREAM_RESET) {\n log.trace('%s stream %s reset', type, name)\n } else {\n log.trace('%s stream %s error', type, name, err)\n try {\n send({ id, type: Types.RESET })\n } catch (err) {\n log.trace('%s stream %s error sending reset', type, name, err)\n }\n }\n\n streamSource.end(err)\n onSinkEnd(err)\n return\n } finally {\n signal.clear()\n }\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n source: streamSource,\n\n sourcePush: (data: Uint8ArrayList) => {\n streamSource.push(data)\n },\n\n sourceReadableLength () {\n return streamSource.readableLength\n },\n\n stat: {\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n timeline\n },\n\n metadata: {},\n\n id: externalId\n }\n\n return stream\n}\n", "import { pushableV } from 'it-pushable'\nimport { abortableSource } from 'abortable-iterator'\nimport { encode } from './encode.js'\nimport { Decoder } from './decode.js'\nimport { MessageTypes, MessageTypeNames, Message } from './message-types.js'\nimport { createStream } from './stream.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { logger } from '@libp2p/logger'\nimport { CodeError } from '@libp2p/interfaces/errors'\nimport { RateLimiterMemory } from 'rate-limiter-flexible'\nimport type { Sink } from 'it-stream-types'\nimport type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { MplexInit } from './index.js'\nimport { anySignal } from 'any-signal'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:mplex')\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\n\nfunction printMessage (msg: Message): any {\n const output: any = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n }\n\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray())\n }\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\n return output\n}\n\nexport interface MplexStream extends Stream {\n sourceReadableLength: () => number\n sourcePush: (data: Uint8ArrayList) => void\n}\n\ninterface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {}\n\nexport class MplexStreamMuxer implements StreamMuxer {\n public protocol = '/mplex/6.7.0'\n\n public sink: Sink\n public source: AsyncIterable\n\n private _streamId: number\n private readonly _streams: { initiators: Map, receivers: Map }\n private readonly _init: MplexStreamMuxerInit\n private readonly _source: { push: (val: Message) => void, end: (err?: Error) => void }\n private readonly closeController: AbortController\n private readonly rateLimiter: RateLimiterMemory\n\n constructor (init?: MplexStreamMuxerInit) {\n init = init ?? {}\n\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\n /**\n * An iterable sink\n */\n this.sink = this._createSink()\n\n /**\n * An iterable source\n */\n const source = this._createSource()\n this._source = source\n this.source = source\n\n /**\n * Close controller\n */\n this.closeController = new AbortController()\n\n this.rateLimiter = new RateLimiterMemory({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n })\n }\n\n /**\n * Returns a Map of streams and their ids\n */\n get streams (): Stream[] {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams: Stream[] = []\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream)\n }\n\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream)\n }\n return streams\n }\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?: string): Stream {\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 /**\n * Close or abort all tracked streams and stop the muxer\n */\n close (err?: Error | undefined): void {\n if (this.closeController.signal.aborted) return\n\n if (err != null) {\n this.streams.forEach(s => { s.abort(err) })\n } else {\n this.streams.forEach(s => { s.close() })\n }\n this.closeController.abort()\n }\n\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream (options: { id: number, name: string }): MplexStream {\n const { id, name } = options\n const registry = this._streams.receivers\n return this._newStream({ id, name, type: 'receiver', registry })\n }\n\n _newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map }): MplexStream {\n const { id, name, type, registry } = options\n\n log('new %s stream %s', type, id)\n\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\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`)\n }\n\n const send = (msg: Message): void => {\n if (log.enabled) {\n log.trace('%s stream %s send', type, id, printMessage(msg))\n }\n\n this._source.push(msg)\n }\n\n const onEnd = (): void => {\n log('%s stream with id %s and protocol %s ended', type, id, stream.stat.protocol)\n registry.delete(id)\n\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream)\n }\n }\n\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize })\n registry.set(id, stream)\n return stream\n }\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 (): Sink {\n const sink: Sink = async source => {\n const signal = anySignal([this.closeController.signal, this._init.signal])\n\n try {\n source = abortableSource(source, signal)\n\n const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize)\n\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg)\n }\n }\n\n this._source.end()\n } catch (err: any) {\n log('error in sink', err)\n this._source.end(err) // End the source with an error\n } finally {\n signal.clear()\n }\n }\n\n return sink\n }\n\n /**\n * Creates a source that restricts outgoing message sizes\n * and varint encodes them\n */\n _createSource (): any {\n const onEnd = (err?: Error): void => {\n this.close(err)\n }\n const source = pushableV({\n objectMode: true,\n onEnd\n })\n\n return Object.assign(encode(source, this._init.minSendBytes), {\n push: source.push,\n end: source.end,\n return: source.return\n })\n }\n\n async _handleIncoming (message: Message): Promise {\n const { id, type } = message\n\n if (log.enabled) {\n log.trace('incoming message', printMessage(message))\n }\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 log('too many inbound streams open')\n\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\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 } catch {\n 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._source.end(new Error('Too many open streams'))\n return\n }\n\n return\n }\n\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) })\n\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream)\n }\n\n return\n }\n\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers\n const stream = list.get(id)\n\n if (stream == null) {\n log('missing stream %s for message type %s', id, MessageTypeNames[type])\n\n return\n }\n\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE\n\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\n // Inform the stream consumer they are not fast enough\n const error = new CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL')\n stream.abort(error)\n\n return\n }\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 // We should expect no more data from the remote, stop reading\n stream.closeRead()\n break\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // Stop reading and writing to the stream immediately\n stream.reset()\n break\n default:\n log('unknown message type %s', type)\n }\n }\n}\n", "import type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport { MplexStreamMuxer } from './mplex.js'\n\nexport interface MplexInit {\n /**\n * The maximum size of message that can be sent in one go in bytes.\n * Messages larger than this will be split into multiple smaller\n * messages. If we receive a message larger than this an error will\n * be thrown and the connection closed. (default: 1MB)\n */\n maxMsgSize?: number\n\n /**\n * Constrains the size of the unprocessed message queue buffer.\n * Before messages are deserialized, the raw bytes are buffered to ensure\n * we have the complete message to deserialized. If the queue gets longer\n * than this value an error will be thrown and the connection closed.\n * (default: 4MB)\n */\n maxUnprocessedMessageQueueSize?: number\n\n /**\n * Each byte array written into a multiplexed stream is converted to one or\n * more messages which are sent as byte arrays to the remote node. Sending\n * lots of small messages can be expensive - use this setting to batch up\n * the serialized bytes of all messages sent during the current tick up to\n * this limit to send in one go similar to Nagle's algorithm. N.b. you\n * should benchmark your application carefully when using this setting as it\n * may cause the opposite of the desired effect. Omit this setting to send\n * all messages as they become available. (default: undefined)\n */\n minSendBytes?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. A request to open more than this will have a stream\n * reset message sent immediately as a response for the newly opened\n * stream id (default: 1024)\n */\n maxInboundStreams?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw (default: 1024)\n */\n maxOutboundStreams?: number\n\n /**\n * Incoming stream messages are buffered until processed by the stream\n * handler. If the buffer reaches this size in bytes the stream will\n * be reset (default: 4MB)\n */\n maxStreamBufferSize?: number\n\n /**\n * When `maxInboundStreams` is hit, if the remote continues try to open\n * more than this many new multiplexed streams per second the connection\n * will be closed (default: 5)\n */\n disconnectThreshold?: number\n}\n\nclass Mplex implements StreamMuxerFactory {\n public protocol = '/mplex/6.7.0'\n private readonly _init: MplexInit\n\n constructor (init: MplexInit = {}) {\n this._init = init\n }\n\n createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {\n return new MplexStreamMuxer({\n ...init,\n ...this._init\n })\n }\n}\n\nexport function mplex (init: MplexInit = {}): () => StreamMuxerFactory {\n return () => new Mplex(init)\n}\n", "export function isAsyncIterable (thing: any): thing is AsyncIterable {\n return thing[Symbol.asyncIterator] != null\n}\n", "import * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { isAsyncIterable } from './utils.js'\nimport type { LengthEncoderFunction } from './index.js'\nimport type { Source } from 'it-stream-types'\n\ninterface EncoderOptions {\n lengthEncoder?: LengthEncoderFunction\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = varint.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n varint.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (source: Iterable, options?: EncoderOptions): Generator\nexport function encode (source: Source, options?: EncoderOptions): AsyncGenerator\nexport function encode (source: Source, options?: EncoderOptions): Generator | AsyncGenerator {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n function * maybeYield (chunk: Uint8Array | Uint8ArrayList): Generator {\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\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\n return (function * () {\n for (const chunk of source) {\n yield * maybeYield(chunk)\n }\n })()\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n", "/**\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/**\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/**\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/**\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", "/* eslint max-depth: [\"error\", 6] */\n\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError, UnexpectedEOFError } from './errors.js'\nimport { isAsyncIterable } from './utils.js'\nimport type { LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source } from 'it-stream-types'\n\nexport interface ReadState {\n dataLength: number\n}\n\nexport interface DecoderOptions {\n lengthDecoder?: LengthDecoderFunction\n onData?(data: Uint8ArrayList): void\n onLength?(length: number): void\n maxLengthLength?: number\n maxDataLength?: number\n}\n\nexport interface ReadResult {\n mode: string\n chunk?: Uint8ArrayList\n buffer: Uint8ArrayList\n state?: ReadState\n data?: Uint8ArrayList\n}\n\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\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = varint.decode(buf)\n defaultDecoder.bytes = varint.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (source: Iterable, options?: DecoderOptions): Generator\nexport function decode (source: Source, options?: DecoderOptions): AsyncGenerator\nexport function decode (source: Source, options?: DecoderOptions): Generator | AsyncGenerator {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n function * maybeYield (): Generator {\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\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length')\n }\n\n if (dataLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new InvalidDataLengthLengthError('Message length length too long')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n }\n\n return (function * () {\n for (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n}\n\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number): void => { byteLength = l }\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n })\n}\n", "/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive Protobuf encoded messages over\n * streams.\n *\n * @example\n *\n * ```typescript\n * import { pbStream } from 'it-pb-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 * stream.writePB({\n * foo: 'bar'\n * }, MessageType)\n * const res = await stream.readPB(MessageType)\n * ```\n */\n\nimport * as lp from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { pushable } from 'it-pushable'\nimport { unsigned } from 'uint8-varint'\nimport errCode from 'err-code'\n\n/**\n * A protobuf decoder - takes a byte array and returns an object\n */\nexport interface Decoder {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\n/**\n * A protobuf encoder - takes an object and returns a byte array\n */\nexport interface Encoder {\n (data: T): Uint8Array\n}\n\n/**\n * A message reader/writer that only uses one type of message\n */\nexport interface MessageStream = Duplex> {\n /**\n * Read a message from the stream\n */\n read: () => Promise\n\n /**\n * Write a message to the stream\n */\n write: (d: T) => void\n\n /**\n * Unwrap the underlying protobuf stream\n */\n unwrap: () => ProtobufStream\n}\n\n/**\n * Convenience methods for working with protobuf streams\n */\nexport interface ProtobufStream = Duplex> {\n /**\n * Read a set number of bytes from the stream\n */\n read: (bytes?: number) => Promise\n\n /**\n * Read the next length-prefixed number of bytes from the stream\n */\n readLP: () => Promise\n\n /**\n * Read the next length-prefixed byte array from the stream and decode it as the passed protobuf format\n */\n readPB: (proto: { decode: Decoder }) => Promise\n\n /**\n * Write the passed bytes to the stream\n */\n write: (input: Uint8Array | Uint8ArrayList) => void\n\n /**\n * Write the passed bytes to the stream prefixed by their length\n */\n writeLP: (input: Uint8Array | Uint8ArrayList) => void\n\n /**\n * Encode the passed object as a protobuf message and write it's length-prefixed bytes tot he stream\n */\n writePB: (data: T, proto: { encode: Encoder }) => void\n\n /**\n * Returns an object with read/write methods for operating on one specific type of protobuf message\n */\n pb: (proto: { encode: Encoder, decode: Decoder }) => MessageStream\n\n /**\n * Returns the underlying stream\n */\n unwrap: () => Stream\n}\n\nexport interface Opts {\n // encoding opts\n poolSize: number\n minPoolSize: number\n lengthEncoder: lp.LengthEncoderFunction\n\n // decoding opts\n lengthDecoder: lp.LengthDecoderFunction\n maxLengthLength: number\n maxDataLength: number\n}\n\nconst defaultLengthDecoder: lp.LengthDecoderFunction = (buf) => {\n return unsigned.decode(buf)\n}\ndefaultLengthDecoder.bytes = 0\n\nexport function pbStream > (duplex: Stream, opts?: Partial): ProtobufStream\nexport function pbStream > (duplex: Duplex, opts?: Partial): ProtobufStream\nexport function pbStream (duplex: any, opts: Partial = {}): ProtobufStream {\n const write = pushable()\n\n duplex.sink(write).catch((err: Error) => {\n write.end(err)\n })\n\n duplex.sink = async (source: any) => {\n for await (const buf of source) {\n write.push(buf)\n }\n }\n\n let source = duplex.source\n\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]()\n } else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]()\n }\n\n const readBuffer = new Uint8ArrayList()\n\n const W: ProtobufStream = {\n read: async (bytes) => {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await source.next()\n\n if (done === true) {\n return new Uint8ArrayList()\n }\n\n return value\n }\n\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await source.next()\n\n if (done === true) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF')\n }\n\n readBuffer.append(value)\n }\n\n const buf = readBuffer.sublist(0, bytes)\n readBuffer.consume(bytes)\n\n return buf\n },\n readLP: async () => {\n let dataLength: number = -1\n const lengthBuffer = new Uint8ArrayList()\n const decodeLength = opts?.lengthDecoder ?? defaultLengthDecoder\n\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await W.read(1))\n\n try {\n dataLength = decodeLength(lengthBuffer)\n } catch (err) {\n if (err instanceof RangeError) {\n continue\n }\n\n throw err\n }\n\n if (dataLength > -1) {\n break\n }\n\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG')\n }\n }\n\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG')\n }\n\n return await W.read(dataLength)\n },\n readPB: async (proto) => {\n // readLP, decode\n const value = await W.readLP()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n // Is this a buffer?\n const buf = value instanceof Uint8Array ? value : value.subarray()\n\n return proto.decode(buf)\n },\n write: (data) => {\n // just write\n if (data instanceof Uint8Array) {\n write.push(data)\n } else {\n write.push(data.subarray())\n }\n },\n writeLP: (data) => {\n // encode, write\n W.write(lp.encode.single(data, opts))\n },\n writePB: (data, proto) => {\n // encode, writeLP\n W.writeLP(proto.encode(data))\n },\n pb: (proto) => {\n return {\n read: async () => await W.readPB(proto),\n write: (d) => { W.writePB(d, proto) },\n unwrap: () => W\n }\n },\n unwrap: () => {\n const originalStream = duplex.source\n duplex.source = (async function * () {\n yield * readBuffer\n yield * originalStream\n }())\n\n return duplex\n }\n }\n\n return W\n}\n", "import defer from 'p-defer'\nimport type { Source, Duplex } from 'it-stream-types'\n\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair (): Duplex, Source, Promise> {\n const deferred = defer>()\n let piped = false\n\n return {\n sink: async source => {\n if (piped) {\n throw new Error('already piped')\n }\n\n piped = true\n deferred.resolve(source)\n },\n source: (async function * () {\n const source = await deferred.promise\n\n yield * source\n }())\n }\n}\n", "import { pair } from './index.js'\nimport type { Duplex, Source } from 'it-stream-types'\n\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair (): [Duplex, Source, Promise>, Duplex, Source, Promise>] {\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", "export const NOISE_MSG_MAX_LENGTH_BYTES = 65535\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16\n\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS)\n", "import { HKDF } from '@stablelib/hkdf'\nimport * as x25519 from '@stablelib/x25519'\nimport { SHA256, hash } from '@stablelib/sha256'\nimport { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305'\nimport type { bytes32, bytes } from '../@types/basic.js'\nimport type { Hkdf } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { ICryptoInterface } from '../crypto.js'\n\nexport const stablelib: ICryptoInterface = {\n hashSHA256 (data: Uint8Array): Uint8Array {\n return hash(data)\n },\n\n getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {\n const hkdf = new HKDF(SHA256, ikm, ck)\n const okmU8Array = hkdf.expand(96)\n const okm = okmU8Array\n\n const k1 = okm.subarray(0, 32)\n const k2 = okm.subarray(32, 64)\n const k3 = okm.subarray(64, 96)\n\n return [k1, k2, k3]\n },\n\n generateX25519KeyPair (): KeyPair {\n const keypair = x25519.generateKeyPair()\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {\n const keypair = x25519.generateKeyPairFromSeed(seed)\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array {\n return x25519.sharedKey(privateKey, publicKey)\n },\n\n chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.seal(nonce, plaintext, ad)\n },\n\n chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32, dst?: Uint8Array): bytes | null {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.open(nonce, ciphertext, ad, dst)\n }\n}\n", "import { TAG_LENGTH } from '@stablelib/chacha20poly1305'\nimport type { Transform } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { IHandshake } from '../@types/handshake-interface.js'\nimport type { MetricsRegistry } from '../metrics.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'\nimport { uint16BEEncode } from '../encoder.js'\n\n// Returns generator that encrypts payload from the user\nexport function encryptStream (handshake: IHandshake, metrics?: MetricsRegistry): Transform {\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\n const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)\n metrics?.encryptedPackets.increment()\n\n yield uint16BEEncode(data.byteLength)\n yield data\n }\n }\n }\n}\n\n// Decrypt received payload to the user\nexport function decryptStream (handshake: IHandshake, metrics?: MetricsRegistry): Transform {\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\n if (end - TAG_LENGTH < i) {\n throw new Error('Invalid chunk')\n }\n const encrypted = chunk.subarray(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 - TAG_LENGTH)\n const { plaintext: decrypted, valid } = handshake.decrypt(encrypted, handshake.session, dst)\n if (!valid) {\n metrics?.decryptErrors.increment()\n throw new Error('Failed to validate decrypted chunk')\n }\n metrics?.decryptedPackets.increment()\n yield decrypted\n }\n }\n }\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { bytes } from './@types/basic.js'\nimport type { MessageBuffer } from './@types/handshake.js'\nimport type { LengthDecoderFunction } from 'it-length-prefixed'\n\nconst allocUnsafe = (len: number): Uint8Array => {\n if (globalThis.Buffer) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n\nexport const uint16BEEncode = (value: number): Uint8Array => {\n const target = allocUnsafe(2)\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)\n return target\n}\nuint16BEEncode.bytes = 2\n\nexport const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {\n if (data.length < 2) throw RangeError('Could not decode int16BE')\n\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)\n }\n\n return data.getUint16(0)\n}\nuint16BEDecode.bytes = 2\n\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\n\nexport function encode0 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)\n}\n\nexport function encode1 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)\n}\n\nexport function encode2 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)\n}\n\nexport function decode0 (input: bytes): MessageBuffer {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: new Uint8Array(0)\n }\n}\n\nexport function decode1 (input: bytes): MessageBuffer {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n }\n}\n\nexport function decode2 (input: bytes): MessageBuffer {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')\n }\n\n return {\n ne: new Uint8Array(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n }\n}\n", "\nexport class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.code = UnexpectedPeerError.code\n }\n\n static get code (): string {\n return 'ERR_UNEXPECTED_PEER'\n }\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.code = InvalidCryptoExchangeError.code\n }\n\n static get code (): string {\n return 'ERR_INVALID_CRYPTO_EXCHANGE'\n }\n}\n\nexport class InvalidCryptoTransmissionError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto transmission') {\n super(message)\n this.code = InvalidCryptoTransmissionError.code\n }\n\n static get code (): string {\n return 'ERR_INVALID_CRYPTO_TRANSMISSION'\n }\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface NoiseExtensions {\n webtransportCerthashes: Uint8Array[]\n}\n\nexport namespace NoiseExtensions {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.webtransportCerthashes != null) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n webtransportCerthashes: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.webtransportCerthashes.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, NoiseExtensions.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseExtensions => {\n return decodeMessage(buf, NoiseExtensions.codec())\n }\n}\n\nexport interface NoiseHandshakePayload {\n identityKey: Uint8Array\n identitySig: Uint8Array\n extensions?: NoiseExtensions\n}\n\nexport namespace NoiseHandshakePayload {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (opts.writeDefaults === true || (obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.identityKey ?? new Uint8Array(0))\n }\n\n if (opts.writeDefaults === true || (obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.identitySig ?? new Uint8Array(0))\n }\n\n if (obj.extensions != null) {\n w.uint32(34)\n NoiseExtensions.codec().encode(obj.extensions, w, {\n writeDefaults: false\n })\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n identityKey: new Uint8Array(0),\n identitySig: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identityKey = reader.bytes()\n break\n case 2:\n obj.identitySig = reader.bytes()\n break\n case 4:\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, NoiseHandshakePayload.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseHandshakePayload => {\n return decodeMessage(buf, NoiseHandshakePayload.codec())\n }\n}\n", "import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { bytes } from './@types/basic.js'\nimport { NoiseExtensions, NoiseHandshakePayload } from './proto/payload.js'\n\nexport async function getPayload (\n localPeer: PeerId,\n staticPublicKey: bytes,\n extensions?: NoiseExtensions\n): Promise {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey))\n\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId')\n }\n\n return createHandshakePayload(\n localPeer.publicKey,\n signedPayload,\n extensions\n )\n}\n\nexport function createHandshakePayload (\n libp2pPublicKey: Uint8Array,\n signedPayload: Uint8Array,\n extensions?: NoiseExtensions\n): bytes {\n return NoiseHandshakePayload.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n extensions: extensions ?? { webtransportCerthashes: [] }\n }).subarray()\n}\n\nexport async function signPayload (peerId: PeerId, payload: bytes): Promise {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId')\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return await privateKey.sign(payload)\n}\n\nexport async function getPeerIdFromPayload (payload: NoiseHandshakePayload): Promise {\n return await peerIdFromKeys(payload.identityKey)\n}\n\nexport function decodePayload (payload: bytes | Uint8Array): NoiseHandshakePayload {\n return NoiseHandshakePayload.decode(payload)\n}\n\nexport function getHandshakePayload (publicKey: bytes): bytes {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:')\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length)\n}\n\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload (\n noiseStaticKey: bytes,\n payload: NoiseHandshakePayload,\n remotePeer: PeerId\n): Promise {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey)\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(`Payload identity key ${payloadPeerId.toString()} does not match expected remote peer ${remotePeer.toString()}`)\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey)\n\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId')\n }\n\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message')\n }\n\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey)\n\n const valid = await publicKey.verify(generatedPayload, payload.identitySig)\n\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\")\n }\n\n return payloadPeerId\n}\n\nexport function isValidPublicKey (pk: bytes): boolean {\n if (!(pk instanceof Uint8Array)) {\n return false\n }\n\n if (pk.length !== 32) {\n return false\n }\n\n return true\n}\n", "import { Logger, logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { DUMP_SESSION_KEYS } from './constants.js'\n\nconst log = logger('libp2p:noise')\n\nexport { log as logger }\n\nlet keyLogger: Logger\nif (DUMP_SESSION_KEYS) {\n keyLogger = log\n} else {\n keyLogger = Object.assign(() => { /* do nothing */ }, {\n enabled: false,\n trace: () => {},\n error: () => {}\n })\n}\n\nexport function logLocalStaticKeys (s: KeyPair): void {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)\n}\n\nexport function logLocalEphemeralKeys (e: KeyPair | undefined): void {\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)\n } else {\n keyLogger('Missing local ephemeral keys.')\n }\n}\n\nexport function logRemoteStaticKey (rs: Uint8Array): void {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs, 'hex')}`)\n}\n\nexport function logRemoteEphemeralKey (re: Uint8Array): void {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re, 'hex')}`)\n}\n\nexport function logCipherState (session: NoiseSession): void {\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)\n } else {\n keyLogger('Missing cipher state.')\n }\n}\n", "import type { bytes, uint64 } from './@types/basic'\n\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\n\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'\n\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n private n: uint64\n private readonly bytes: bytes\n private readonly view: DataView\n\n constructor (n = MIN_NONCE) {\n this.n = n\n this.bytes = new Uint8Array(12)\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)\n this.view.setUint32(4, n, true)\n }\n\n increment (): void {\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\n getBytes (): bytes {\n return this.bytes\n }\n\n getUint64 (): uint64 {\n return this.n\n }\n\n assertValue (): void {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE)\n }\n }\n}\n", "import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays'\nimport type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, MessageBuffer, SymmetricState } from '../@types/handshake.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport { logger } from '../logger.js'\nimport { Nonce } from '../nonce.js'\n\nexport interface DecryptedResult {\n plaintext: bytes\n valid: boolean\n}\n\nexport interface SplitState {\n cs1: CipherState\n cs2: CipherState\n}\n\nexport abstract class AbstractHandshake {\n public crypto: ICryptoInterface\n\n constructor (crypto: ICryptoInterface) {\n this.crypto = crypto\n }\n\n public encryptWithAd (cs: CipherState, ad: Uint8Array, plaintext: Uint8Array): bytes {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext)\n cs.n.increment()\n\n return e\n }\n\n public decryptWithAd (cs: CipherState, ad: Uint8Array, ciphertext: Uint8Array, dst?: Uint8Array): DecryptedResult {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext, dst)\n if (valid) cs.n.increment()\n\n return { plaintext, valid }\n }\n\n // Cipher state related\n protected hasKey (cs: CipherState): boolean {\n return !this.isEmptyKey(cs.k)\n }\n\n protected createEmptyKey (): bytes32 {\n return new Uint8Array(32)\n }\n\n protected isEmptyKey (k: bytes32): boolean {\n const emptyKey = this.createEmptyKey()\n return uint8ArrayEquals(emptyKey, k)\n }\n\n protected encrypt (k: bytes32, n: Nonce, ad: Uint8Array, plaintext: Uint8Array): bytes {\n n.assertValue()\n\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k)\n }\n\n protected encryptAndHash (ss: SymmetricState, plaintext: bytes): bytes {\n let ciphertext\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext)\n } else {\n ciphertext = plaintext\n }\n\n this.mixHash(ss, ciphertext)\n return ciphertext\n }\n\n protected decrypt (k: bytes32, n: Nonce, ad: bytes, ciphertext: bytes, dst?: Uint8Array): DecryptedResult {\n n.assertValue()\n\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k, dst)\n\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n }\n } else {\n return {\n plaintext: new Uint8Array(0),\n valid: false\n }\n }\n }\n\n protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): DecryptedResult {\n let plaintext: bytes; let valid = true\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext))\n } else {\n plaintext = ciphertext\n }\n\n this.mixHash(ss, ciphertext)\n return { plaintext, valid }\n }\n\n protected dh (privateKey: bytes32, publicKey: bytes32): bytes32 {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey)\n\n if (derivedU8.length === 32) {\n return derivedU8\n }\n\n return derivedU8.subarray(0, 32)\n } catch (e) {\n const err = e as Error\n logger.error(err)\n return new Uint8Array(32)\n }\n }\n\n protected mixHash (ss: SymmetricState, data: bytes): void {\n ss.h = this.getHash(ss.h, data)\n }\n\n protected getHash (a: Uint8Array, b: Uint8Array): bytes32 {\n const u = this.crypto.hashSHA256(uint8ArrayConcat([a, b], a.length + b.length))\n return u\n }\n\n protected mixKey (ss: SymmetricState, ikm: bytes32): void {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm)\n ss.cs = this.initializeKey(tempK)\n ss.ck = ck\n }\n\n protected initializeKey (k: bytes32): CipherState {\n return { k, n: new Nonce() }\n }\n\n // Symmetric state related\n\n protected initializeSymmetric (protocolName: string): SymmetricState {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8')\n const h = this.hashProtocolName(protocolNameBytes)\n\n const ck = h\n const key = this.createEmptyKey()\n const cs: CipherState = this.initializeKey(key)\n\n return { cs, ck, h }\n }\n\n protected hashProtocolName (protocolName: Uint8Array): bytes32 {\n if (protocolName.length <= 32) {\n const h = new Uint8Array(32)\n h.set(protocolName)\n return h\n } else {\n return this.getHash(protocolName, new Uint8Array(0))\n }\n }\n\n protected split (ss: SymmetricState): SplitState {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, new Uint8Array(0))\n const cs1 = this.initializeKey(tempk1)\n const cs2 = this.initializeKey(tempk2)\n\n return { cs1, cs2 }\n }\n\n protected writeMessageRegular (cs: CipherState, payload: bytes): MessageBuffer {\n const ciphertext = this.encryptWithAd(cs, new Uint8Array(0), payload)\n const ne = this.createEmptyKey()\n const ns = new Uint8Array(0)\n\n return { ne, ns, ciphertext }\n }\n\n protected readMessageRegular (cs: CipherState, message: MessageBuffer): DecryptedResult {\n return this.decryptWithAd(cs, new Uint8Array(0), message.ciphertext)\n }\n}\n", "import type { bytes32, bytes } from '../@types/basic.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport { AbstractHandshake, DecryptedResult } from './abstract-handshake.js'\n\nexport class XX extends AbstractHandshake {\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer {\n const ns = new Uint8Array(0)\n\n if (e !== undefined) {\n hs.e = e\n } else {\n hs.e = this.crypto.generateX25519KeyPair()\n }\n\n const ne = hs.e.publicKey\n\n this.mixHash(hs.ss, ne)\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageC (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes } {\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ne = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, messageBuffer, cs1, cs2 }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): DecryptedResult {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n return this.decryptAndHash(hs.ss, message.ciphertext)\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): DecryptedResult {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageC (hs: HandshakeState, message: MessageBuffer): { h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState } {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 }\n }\n\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair): NoiseSession {\n const psk = this.createEmptyKey()\n const rs = new Uint8Array(32) // no static key yet\n let hs\n\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes, ephemeral?: KeyPair): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral)\n } else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message)\n } else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message)\n messageBuffer = resultingBuffer\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): DecryptedResult {\n let plaintext: bytes = new Uint8Array(0)\n let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n } else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message))\n } else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message)\n plaintext = resultingPlaintext\n valid = resultingValid\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from '@libp2p/interface-connection-encrypter/errors'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js'\nimport { XX } from './handshakes/xx.js'\nimport {\n logger,\n logLocalStaticKeys,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logRemoteStaticKey,\n logCipherState\n} from './logger.js'\nimport {\n decodePayload,\n getPeerIdFromPayload,\n verifySignedPayload\n} from './utils.js'\nimport type { NoiseExtensions } from './proto/payload.js'\n\nexport class XXHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteExtensions: NoiseExtensions = { webtransportCerthashes: [] }\n\n protected payload: bytes\n protected connection: ProtobufStream\n protected xx: XX\n protected staticKeypair: KeyPair\n\n private readonly prologue: bytes32\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remotePeer?: PeerId,\n handshake?: XX\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.xx = handshake ?? new XX(crypto)\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair)\n }\n\n // stage 0\n public async propose (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n if (this.isInitiator) {\n logger.trace('Stage 0 - Initiator starting to send first message.')\n const messageBuffer = this.xx.sendMessage(this.session, new Uint8Array(0))\n this.connection.writeLP(encode0(messageBuffer))\n logger.trace('Stage 0 - Initiator finished sending first message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger.trace('Stage 0 - Responder waiting to receive first message...')\n const receivedMessageBuffer = decode0((await this.connection.readLP()).subarray())\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail')\n }\n logger.trace('Stage 0 - Responder received first message.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n logger.trace('Stage 1 - Initiator waiting to receive first message from responder...')\n const receivedMessageBuffer = decode1((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail')\n }\n logger.trace('Stage 1 - Initiator received the message.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger.trace(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteNoiseExtension(decodedPayload.extensions)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n logger.trace('All good with the signature!')\n } else {\n logger.trace('Stage 1 - Responder sending out first message with signed payload and static key.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger.trace('Stage 1 - Responder sent the second handshake message with signed payload.')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n }\n\n // stage 2\n public async finish (): Promise {\n if (this.isInitiator) {\n logger.trace('Stage 2 - Initiator sending third handshake message.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode2(messageBuffer))\n logger.trace('Stage 2 - Initiator sent message with signed payload.')\n } else {\n logger.trace('Stage 2 - Responder waiting for third handshake message...')\n const receivedMessageBuffer = decode2((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail')\n }\n logger.trace('Stage 2 - Responder received the message, finished handshake.')\n\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteNoiseExtension(decodedPayload.extensions)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n }\n logCipherState(this.session)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n\n return this.xx.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession, dst?: Uint8Array): { plaintext: bytes, valid: boolean } {\n const cs = this.getCS(session, false)\n\n return this.xx.decryptWithAd(cs, new Uint8Array(0), ciphertext, dst)\n }\n\n public getRemoteStaticKey (): bytes {\n return this.session.hs.rs\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n protected setRemoteNoiseExtension (e: NoiseExtensions | null | undefined): void {\n if (e) {\n this.remoteExtensions = e\n }\n }\n}\n", "import type { Counter, Metrics } from '@libp2p/interface-metrics'\n\nexport type MetricsRegistry = Record\n\nexport function registerMetrics (metrics: Metrics): MetricsRegistry {\n return {\n xxHandshakeSuccesses: metrics.registerCounter(\n 'libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n\n xxHandshakeErrors: metrics.registerCounter(\n 'libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n\n encryptedPackets: metrics.registerCounter(\n 'libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n\n decryptedPackets: metrics.registerCounter(\n 'libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n\n decryptErrors: metrics.registerCounter(\n 'libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n }\n}\n", "import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport { pbStream, ProtobufStream } from 'it-pb-stream'\nimport { duplexPair } from 'it-pair/duplex'\nimport { pipe } from 'it-pipe'\nimport { decode } from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { bytes } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { INoiseConnection, KeyPair } from './@types/libp2p.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { stablelib } from './crypto/stablelib.js'\nimport { decryptStream, encryptStream } from './crypto/streaming.js'\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport { getPayload } from './utils.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { MetricsRegistry, registerMetrics } from './metrics.js'\n\ninterface HandshakeParams {\n connection: ProtobufStream\n isInitiator: boolean\n localPeer: PeerId\n remotePeer?: PeerId\n}\n\nexport interface NoiseInit {\n /**\n * x25519 private key, reuse for faster handshakes\n */\n staticNoiseKey?: bytes\n extensions?: NoiseExtensions\n crypto?: ICryptoInterface\n prologueBytes?: Uint8Array\n metrics?: Metrics\n}\n\nexport class Noise implements INoiseConnection {\n public protocol = '/noise'\n public crypto: ICryptoInterface\n\n private readonly prologue: Uint8Array\n private readonly staticKeys: KeyPair\n private readonly extensions?: NoiseExtensions\n private readonly metrics?: MetricsRegistry\n\n constructor (init: NoiseInit = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes, metrics } = init\n\n this.crypto = crypto ?? stablelib\n this.extensions = extensions\n this.metrics = metrics ? registerMetrics(metrics) : undefined\n\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey)\n } else {\n this.staticKeys = this.crypto.generateX25519KeyPair()\n }\n this.prologue = prologueBytes ?? new Uint8Array(0)\n }\n\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {Duplex} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise}\n */\n public async secureOutbound (localPeer: PeerId, connection: Duplex, remotePeer?: PeerId): Promise> {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteExtensions: handshake.remoteExtensions,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {Duplex} connection - streaming iterable duplex that will be encryption.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise}\n */\n public async secureInbound (localPeer: PeerId, connection: Duplex, remotePeer?: PeerId): Promise> {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remotePeer: handshake.remotePeer,\n remoteExtensions: handshake.remoteExtensions\n }\n }\n\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n private async performHandshake (params: HandshakeParams): Promise {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.extensions)\n\n // run XX handshake\n return await this.performXXHandshake(params, payload)\n }\n\n private async performXXHandshake (\n params: HandshakeParams,\n payload: bytes\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake = new XXHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n remotePeer\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n this.metrics?.xxHandshakeSuccesses.increment()\n } catch (e: unknown) {\n this.metrics?.xxHandshakeErrors.increment()\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`\n throw e\n }\n }\n\n return handshake\n }\n\n private async createSecureConnection (\n connection: ProtobufStream,\n handshake: IHandshake\n ): Promise> {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair()\n const network = connection.unwrap()\n\n await pipe(\n secure, // write to wrapper\n encryptStream(handshake, this.metrics), // encrypt data + prefix with message length\n network, // send to the remote peer\n decode({ lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake, this.metrics), // decrypt the incoming data\n secure // pipe to the wrapper\n )\n\n return user\n }\n}\n", "import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport { Noise } from './noise.js'\nimport type { NoiseInit } from './noise.js'\nimport type { NoiseExtensions } from './proto/payload.js'\nexport * from './crypto.js'\nexport * from './crypto/stablelib.js'\n\nexport function noise (init: NoiseInit = {}): () => ConnectionEncrypter {\n return () => new Noise(init)\n}\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\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerIdProto {\n id?: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.id != null) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.pubKey != null) {\n w.uint32(18)\n w.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n w.uint32(26)\n w.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n", "import { 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'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\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}\n\nexport async function createFromProtobuf (buf: Uint8Array): Promise {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return createFromParts(\n id ?? new Uint8Array(0),\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }): Promise {\n return createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array): Promise {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey)\n\n return createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n", "import { logger } from '@libp2p/logger'\nimport { createRepo } from 'ipfs-core-config/repo'\nimport getDefaultConfig from 'ipfs-core-config/config'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport mergeOpts from 'merge-options'\nimport { profiles as configProfiles } from './config/profiles.js'\nimport { NotEnabledError, NotInitializedError } from '../errors.js'\nimport { createLibp2p } from './libp2p.js'\nimport { ERR_REPO_NOT_INITIALIZED } from 'ipfs-repo/errors'\nimport { createEd25519PeerId, createRSAPeerId } from '@libp2p/peer-id-factory'\nimport errCode from 'err-code'\nimport { unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport { Key } from 'interface-datastore/key'\n\nconst mergeOptions = mergeOpts.bind({ ignoreUndefined: true })\nconst log = logger('ipfs:components:peer:storage')\n\n/**\n * @typedef {import('ipfs-repo').IPFSRepo} IPFSRepo\n * @typedef {import('../types').Options} IPFSOptions\n * @typedef {import('../types').InitOptions} InitOptions\n * @typedef {import('../types').Print} Print\n * @typedef {import('ipfs-core-types/src/config').Config} IPFSConfig\n * @typedef {import('@libp2p/crypto/keys').KeyTypes} KeyType\n * @typedef {import('@libp2p/interface-keychain').KeyChain} Keychain\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\nexport class Storage {\n /**\n * @private\n * @param {PeerId} peerId\n * @param {Keychain} keychain\n * @param {IPFSRepo} repo\n * @param {Print} print\n * @param {boolean} isNew\n */\n constructor (peerId, keychain, repo, print, isNew) {\n this.print = print\n this.peerId = peerId\n this.keychain = keychain\n this.repo = repo\n this.print = print\n this.isNew = isNew\n }\n\n /**\n * @param {Print} print\n * @param {import('ipfs-core-utils/multicodecs').Multicodecs} codecs\n * @param {IPFSOptions} options\n */\n static async start (print, codecs, options) {\n const { repoAutoMigrate, repo: inputRepo, onMigrationProgress } = options\n\n const repo = (typeof inputRepo === 'string' || inputRepo == null)\n ? createRepo(print, codecs, {\n path: inputRepo,\n autoMigrate: repoAutoMigrate,\n onMigrationProgress: onMigrationProgress\n })\n : inputRepo\n\n const { peerId, keychain, isNew } = await loadRepo(print, repo, options)\n\n // TODO: throw error?\n // @ts-expect-error On start, keychain will always be available\n return new Storage(peerId, keychain, repo, print, isNew)\n }\n}\n\n/**\n * @param {Print} print\n * @param {IPFSRepo} repo\n * @param {IPFSOptions} options\n */\nconst loadRepo = async (print, repo, options) => {\n if (!repo.closed) {\n return { ...await configureRepo(repo, options), isNew: false }\n }\n\n try {\n await repo.open()\n\n return { ...await configureRepo(repo, options), isNew: false }\n } catch (/** @type {any} */ err) {\n if (err.code !== ERR_REPO_NOT_INITIALIZED) {\n throw err\n }\n\n if (options.init && options.init.allowNew === false) {\n throw new NotEnabledError('Initialization of new repos disabled by config, pass `config.init.isNew: true` to enable it')\n }\n\n return { ...await initRepo(print, repo, options), isNew: true }\n }\n}\n\n/**\n * @param {Print} print\n * @param {IPFSRepo} repo\n * @param {IPFSOptions} options\n * @returns {Promise<{peerId: PeerId, keychain?: Keychain}>}\n */\nconst initRepo = async (print, repo, options) => {\n const initOptions = options.init || {}\n\n // 1. Verify that repo does not exist yet (if it does and we could not open it we give up)\n const exists = await repo.exists()\n log('repo exists?', exists)\n\n if (exists === true) {\n throw new Error('repo already exists')\n }\n\n // 2. Restore `peerId` from a given `.privateKey` or init new using provided options.\n const peerId = initOptions.privateKey\n ? await decodePeerId(initOptions.privateKey)\n : await initPeerId(print, initOptions)\n\n const identity = peerIdToIdentity(peerId)\n\n log('peer identity: %s', identity.PeerID)\n\n // 3. Init new repo with provided `.config` and restored / initialized `peerId`\n const config = {\n ...mergeOptions(applyProfiles(getDefaultConfig(), initOptions.profiles), options.config),\n Identity: identity\n }\n await repo.init(config)\n\n // 4. Open initialized repo.\n await repo.open()\n\n log('repo opened')\n\n /** @type {import('./libp2p').KeychainConfig} */\n const keychainConfig = {\n pass: options.pass\n }\n\n try {\n keychainConfig.dek = await repo.config.get('Keychain.DEK')\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n }\n\n // Create libp2p for Keychain creation\n const libp2p = await createLibp2p({\n options: undefined,\n multiaddrs: undefined,\n peerId,\n repo,\n config,\n keychainConfig\n })\n\n if (!(await repo.datastore.has(new Key('/info/self')))) {\n await libp2p.keychain.importPeer('self', peerId)\n }\n\n await repo.config.set('Keychain', {\n // @ts-expect-error private field\n DEK: libp2p.keychain.init.dek\n })\n\n return { peerId, keychain: libp2p.keychain }\n}\n\n/**\n * Takes `peerId` either represented as a string serialized string or\n * an instance and returns a `PeerId` instance.\n *\n * @param {PeerId|string} peerId\n * @returns {Promise}\n */\nconst decodePeerId = async (peerId) => {\n log('using user-supplied private-key')\n if (isPeerId(peerId)) {\n return peerId\n }\n\n const rawPrivateKey = uint8ArrayFromString(peerId, 'base64pad')\n const key = await unmarshalPrivateKey(rawPrivateKey)\n return await peerIdFromKeys(key.public.bytes, key.bytes)\n}\n\n/**\n * Initializes new PeerId by generating an underlying keypair.\n *\n * @param {Print} print\n * @param {object} options\n * @param {KeyType} [options.algorithm='Ed25519']\n * @param {number} [options.bits=2048]\n * @returns {Promise}\n */\nconst initPeerId = (print, { algorithm = 'Ed25519', bits = 2048 }) => {\n // Generate peer identity keypair + transform to desired format + add to config.\n print('generating %s keypair...', algorithm)\n\n if (algorithm === 'Ed25519') {\n return createEd25519PeerId()\n }\n\n if (algorithm === 'RSA') {\n return createRSAPeerId({ bits })\n }\n\n throw errCode(new Error('Unknown PeerId algorithm'), 'ERR_UNKNOWN_PEER_ID_ALGORITHM')\n}\n\n/**\n * @param {PeerId} peerId\n */\nconst peerIdToIdentity = (peerId) => {\n if (peerId.privateKey == null) {\n throw errCode(new Error('Private key missing'), 'ERR_MISSING_PRIVATE_KEY')\n }\n\n return {\n PeerID: peerId.toString(),\n /** @type {string} */\n PrivKey: uint8ArrayToString(peerId.privateKey, 'base64pad')\n }\n}\n\n/**\n * Applies passed `profiles` and a `config` to an open repo.\n *\n * @param {IPFSRepo} repo\n * @param {IPFSOptions} options\n * @returns {Promise<{peerId: PeerId, keychain?: Keychain}>}\n */\nconst configureRepo = async (repo, options) => {\n const config = options.config\n const profiles = (options.init && options.init.profiles) || []\n const pass = options.pass\n const original = await repo.config.getAll()\n const changed = mergeConfigs(applyProfiles(original, profiles), config)\n\n if (original !== changed) {\n await repo.config.replace(changed)\n }\n\n if (!changed.Identity || !changed.Identity.PrivKey) {\n throw new NotInitializedError('No private key was found in the config, please intialize the repo')\n }\n\n const buf = uint8ArrayFromString(changed.Identity.PrivKey, 'base64pad')\n const key = await unmarshalPrivateKey(buf)\n const peerId = await peerIdFromKeys(key.public.bytes, key.bytes)\n const libp2p = await createLibp2p({\n options: undefined,\n multiaddrs: undefined,\n peerId,\n repo,\n config: changed,\n keychainConfig: {\n pass,\n ...changed.Keychain\n }\n })\n\n return { peerId, keychain: libp2p.keychain }\n}\n\n/**\n * @param {IPFSConfig} config\n * @param {Partial} [changes]\n */\nconst mergeConfigs = (config, changes) =>\n changes ? mergeOptions(config, changes) : config\n\n/**\n * Apply profiles (e.g. ['server', 'lowpower']) to config\n *\n * @param {IPFSConfig} config\n * @param {string[]} [profiles]\n */\nconst applyProfiles = (config, profiles) => {\n return (profiles || []).reduce((config, name) => {\n const profile = configProfiles[name]\n if (!profile) {\n throw new Error(`Could not find profile with name '${name}'`)\n }\n log('applying profile %s', name)\n return profile.transform(config)\n }, config)\n}\n", "import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { base58btc } from 'multiformats/bases/base58'\n// @ts-ignore\nimport vd from 'varint-decoder'\nimport ve from '../utils/varint-encoder.js'\nimport { isMapEqual } from '../utils/index.js'\nimport { Message } from './message.js'\nimport { BitswapMessageEntry as Entry } from './entry.js'\nimport { CodeError } from '@libp2p/interfaces/errors'\n\n/**\n * @typedef {import('../types').MultihashHasherLoader} MultihashHasherLoader\n */\n\nexport class BitswapMessage {\n /**\n * @param {boolean} full\n */\n constructor (full) {\n this.full = full\n /** @type {Map} */\n this.wantlist = new Map()\n\n /** @type {Map} */\n this.blocks = new Map()\n\n /** @type {Map} */\n this.blockPresences = new Map()\n this.pendingBytes = 0\n }\n\n get empty () {\n return this.blocks.size === 0 &&\n this.wantlist.size === 0 &&\n this.blockPresences.size === 0\n }\n\n /**\n *\n * @param {CID} cid\n * @param {number} priority\n * @param {import('./message').Message.Wantlist.WantType | null} [wantType]\n * @param {boolean} [cancel]\n * @param {boolean} [sendDontHave]\n * @returns {void}\n */\n addEntry (cid, priority, wantType, cancel, sendDontHave) {\n if (wantType == null) {\n wantType = BitswapMessage.WantType.Block\n }\n\n const cidStr = cid.toString(base58btc)\n const entry = this.wantlist.get(cidStr)\n if (entry) {\n // Only change priority if want is of the same type\n if (entry.wantType === wantType) {\n entry.priority = priority\n }\n // Only change from \"dont cancel\" to \"do cancel\"\n if (cancel) {\n entry.cancel = Boolean(cancel)\n }\n // Only change from \"dont send\" to \"do send\" DONT_HAVE\n if (sendDontHave) {\n entry.sendDontHave = Boolean(sendDontHave)\n }\n // want-block overrides existing want-have\n if (wantType === BitswapMessage.WantType.Block && entry.wantType === BitswapMessage.WantType.Have) {\n entry.wantType = wantType\n }\n } else {\n this.wantlist.set(cidStr, new Entry(cid, priority, wantType, cancel, sendDontHave))\n }\n }\n\n /**\n * @param {CID} cid\n * @param {Uint8Array} block\n * @returns {void}\n */\n addBlock (cid, block) {\n const cidStr = cid.toString(base58btc)\n this.blocks.set(cidStr, block)\n }\n\n /**\n * @param {CID} cid\n */\n addHave (cid) {\n const cidStr = cid.toString(base58btc)\n if (!this.blockPresences.has(cidStr)) {\n this.blockPresences.set(cidStr, BitswapMessage.BlockPresenceType.Have)\n }\n }\n\n /**\n * @param {CID} cid\n */\n addDontHave (cid) {\n const cidStr = cid.toString(base58btc)\n if (!this.blockPresences.has(cidStr)) {\n this.blockPresences.set(cidStr, BitswapMessage.BlockPresenceType.DontHave)\n }\n }\n\n /**\n * @param {CID} cid\n */\n cancel (cid) {\n const cidStr = cid.toString(base58btc)\n this.wantlist.delete(cidStr)\n this.addEntry(cid, 0, BitswapMessage.WantType.Block, true, false)\n }\n\n /**\n * @param {number} size\n */\n setPendingBytes (size) {\n this.pendingBytes = size\n }\n\n /**\n * Serializes to Bitswap Message protobuf of\n * version 1.0.0\n *\n * @returns {Uint8Array}\n */\n serializeToBitswap100 () {\n const msg = {\n wantlist: {\n entries: Array.from(this.wantlist.values()).map((entry) => {\n return {\n block: entry.cid.bytes, // cid\n priority: Number(entry.priority),\n cancel: Boolean(entry.cancel)\n }\n }),\n full: this.full ? true : undefined\n },\n blocks: Array.from(this.blocks.values())\n }\n\n return Message.encode(msg).finish()\n }\n\n /**\n * Serializes to Bitswap Message protobuf of\n * version 1.1.0\n *\n * @returns {Uint8Array}\n */\n serializeToBitswap110 () {\n const msg = {\n wantlist: {\n entries: Array.from(this.wantlist.values()).map((entry) => {\n return {\n block: entry.cid.bytes, // cid\n priority: Number(entry.priority),\n wantType: entry.wantType,\n cancel: Boolean(entry.cancel),\n sendDontHave: Boolean(entry.sendDontHave)\n }\n }),\n full: this.full ? true : undefined\n },\n /** @type {import('./message').Message.BlockPresence[]} */\n blockPresences: [],\n\n /** @type {{ prefix: Uint8Array, data: Uint8Array }[]} */\n payload: [],\n pendingBytes: this.pendingBytes\n }\n\n for (const [cidStr, data] of this.blocks.entries()) {\n const cid = CID.parse(cidStr)\n const version = cid.version\n const codec = cid.code\n const multihash = cid.multihash.code\n const digestLength = cid.multihash.digest.length\n const prefix = ve([\n version, codec, multihash, digestLength\n ])\n\n msg.payload.push(\n new Message.Block({\n prefix,\n data\n })\n )\n }\n\n for (const [cidStr, bpType] of this.blockPresences) {\n msg.blockPresences.push(new Message.BlockPresence({\n cid: CID.parse(cidStr).bytes,\n type: bpType\n }))\n }\n\n if (this.pendingBytes > 0) {\n msg.pendingBytes = this.pendingBytes\n }\n\n return Message.encode(msg).finish()\n }\n\n /**\n * @param {BitswapMessage} other\n * @returns {boolean}\n */\n equals (other) {\n if (this.full !== other.full ||\n this.pendingBytes !== other.pendingBytes ||\n !isMapEqual(this.wantlist, other.wantlist) ||\n !isMapEqual(this.blocks, other.blocks) ||\n // @TODO - Is this a bug ?\n // @ts-expect-error - isMap equals map values to be objects not numbers\n !isMapEqual(this.blockPresences, other.blockPresences)\n ) {\n return false\n }\n\n return true\n }\n\n get [Symbol.toStringTag] () {\n const list = Array.from(this.wantlist.keys())\n const blocks = Array.from(this.blocks.keys())\n return `BitswapMessage `\n }\n}\n\n/**\n * @param {Uint8Array} raw\n * @param {MultihashHasherLoader} [hashLoader]\n */\nBitswapMessage.deserialize = async (raw, hashLoader) => {\n const decoded = Message.decode(raw)\n\n const isFull = (decoded.wantlist && decoded.wantlist.full) || false\n const msg = new BitswapMessage(isFull)\n\n if (decoded.wantlist && decoded.wantlist.entries) {\n decoded.wantlist.entries.forEach((entry) => {\n if (!entry.block) {\n return\n }\n // note: entry.block is the CID here\n const cid = CID.decode(entry.block)\n msg.addEntry(cid, entry.priority || 0, entry.wantType, Boolean(entry.cancel), Boolean(entry.sendDontHave))\n })\n }\n\n if (decoded.blockPresences) {\n decoded.blockPresences.forEach((blockPresence) => {\n if (!blockPresence.cid) {\n return\n }\n\n const cid = CID.decode(blockPresence.cid)\n\n if (blockPresence.type === BitswapMessage.BlockPresenceType.Have) {\n msg.addHave(cid)\n } else {\n msg.addDontHave(cid)\n }\n })\n }\n\n // Bitswap 1.0.0\n // decoded.blocks are just the byte arrays\n if (decoded.blocks.length > 0) {\n await Promise.all(decoded.blocks.map(async (b) => {\n const hash = await sha256.digest(b)\n const cid = CID.createV0(hash)\n msg.addBlock(cid, b)\n }))\n return msg\n }\n\n // Bitswap 1.1.0\n if (decoded.payload.length > 0) {\n await Promise.all(decoded.payload.map(async (p) => {\n if (!p.prefix || !p.data) {\n return\n }\n const values = vd(p.prefix)\n const cidVersion = values[0]\n const multicodec = values[1]\n const hashAlg = values[2]\n const hasher = hashAlg === sha256.code ? sha256 : hashLoader && await hashLoader.getHasher(hashAlg)\n\n if (!hasher) {\n throw new CodeError('Unknown hash algorithm', 'ERR_UNKNOWN_HASH_ALG')\n }\n\n // const hashLen = values[3] // We haven't need to use this so far\n const hash = await hasher.digest(p.data)\n const cid = CID.create(cidVersion, multicodec, hash)\n msg.addBlock(cid, p.data)\n }))\n msg.setPendingBytes(decoded.pendingBytes)\n return msg\n }\n\n return msg\n}\n\n/**\n * @param {CID} cid\n */\nBitswapMessage.blockPresenceSize = (cid) => {\n // It's ok if this is not exactly right: it's used to estimate the size of\n // the HAVE / DONT_HAVE on the wire, but when doing that calculation we leave\n // plenty of padding under the maximum message size.\n // (It's more important for this to be fast).\n return cid.bytes.length + 1\n}\n\nBitswapMessage.Entry = Entry\nBitswapMessage.WantType = {\n Block: Message.Wantlist.WantType.Block,\n Have: Message.Wantlist.WantType.Have\n}\nBitswapMessage.BlockPresenceType = {\n Have: Message.BlockPresenceType.Have,\n DontHave: Message.BlockPresenceType.DontHave\n}\n", "import * as varint from 'varint'\n\n/**\n * @param {Array} buf\n * @returns {Uint8Array}\n */\nfunction varintEncoder (buf) {\n let out = new Uint8Array(buf.reduce((acc, curr) => {\n // @ts-expect-error types are wrong\n return acc + varint.default.encodingLength(curr)\n }, 0))\n let offset = 0\n\n for (const num of buf) {\n out = varint.encode(num, out, offset)\n\n // @ts-expect-error types are wrong\n offset += varint.default.encodingLength(num)\n }\n\n return out\n}\n\nexport default varintEncoder\n", "\nimport { base58btc } from 'multiformats/bases/base58'\n\nexport class WantListEntry {\n /**\n * @param {import('multiformats').CID} cid\n * @param {number} priority\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n */\n constructor (cid, priority, wantType) {\n // Keep track of how many requests we have for this key\n this._refCounter = 1\n\n this.cid = cid\n this.priority = priority || 1\n this.wantType = wantType\n }\n\n inc () {\n this._refCounter += 1\n }\n\n dec () {\n this._refCounter = Math.max(0, this._refCounter - 1)\n }\n\n hasRefs () {\n return this._refCounter > 0\n }\n\n // So that console.log prints a nice description of this object\n get [Symbol.toStringTag] () {\n const cidStr = this.cid.toString(base58btc)\n return `WantlistEntry `\n }\n\n /**\n * @param {any} other\n */\n equals (other) {\n return (this._refCounter === other._refCounter) &&\n this.cid.equals(other.cid) &&\n this.priority === other.priority &&\n this.wantType === other.wantType\n }\n}\n", "/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots[\"ipfs-bitswap\"] || ($protobuf.roots[\"ipfs-bitswap\"] = {});\n\nexport const Message = $root.Message = (() => {\n\n /**\n * Properties of a Message.\n * @exports IMessage\n * @interface IMessage\n * @property {Message.IWantlist|null} [wantlist] Message wantlist\n * @property {Array.|null} [blocks] Message blocks\n * @property {Array.|null} [payload] Message payload\n * @property {Array.|null} [blockPresences] Message blockPresences\n * @property {number|null} [pendingBytes] Message pendingBytes\n */\n\n /**\n * Constructs a new Message.\n * @exports Message\n * @classdesc Represents a Message.\n * @implements IMessage\n * @constructor\n * @param {IMessage=} [p] Properties to set\n */\n function Message(p) {\n this.blocks = [];\n this.payload = [];\n this.blockPresences = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Message wantlist.\n * @member {Message.IWantlist|null|undefined} wantlist\n * @memberof Message\n * @instance\n */\n Message.prototype.wantlist = null;\n\n /**\n * Message blocks.\n * @member {Array.} blocks\n * @memberof Message\n * @instance\n */\n Message.prototype.blocks = $util.emptyArray;\n\n /**\n * Message payload.\n * @member {Array.} payload\n * @memberof Message\n * @instance\n */\n Message.prototype.payload = $util.emptyArray;\n\n /**\n * Message blockPresences.\n * @member {Array.} blockPresences\n * @memberof Message\n * @instance\n */\n Message.prototype.blockPresences = $util.emptyArray;\n\n /**\n * Message pendingBytes.\n * @member {number} pendingBytes\n * @memberof Message\n * @instance\n */\n Message.prototype.pendingBytes = 0;\n\n /**\n * Encodes the specified Message message. Does not implicitly {@link Message.verify|verify} messages.\n * @function encode\n * @memberof Message\n * @static\n * @param {IMessage} m Message message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Message.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.wantlist != null && Object.hasOwnProperty.call(m, \"wantlist\"))\n $root.Message.Wantlist.encode(m.wantlist, w.uint32(10).fork()).ldelim();\n if (m.blocks != null && m.blocks.length) {\n for (var i = 0; i < m.blocks.length; ++i)\n w.uint32(18).bytes(m.blocks[i]);\n }\n if (m.payload != null && m.payload.length) {\n for (var i = 0; i < m.payload.length; ++i)\n $root.Message.Block.encode(m.payload[i], w.uint32(26).fork()).ldelim();\n }\n if (m.blockPresences != null && m.blockPresences.length) {\n for (var i = 0; i < m.blockPresences.length; ++i)\n $root.Message.BlockPresence.encode(m.blockPresences[i], w.uint32(34).fork()).ldelim();\n }\n if (m.pendingBytes != null && Object.hasOwnProperty.call(m, \"pendingBytes\"))\n w.uint32(40).int32(m.pendingBytes);\n return w;\n };\n\n /**\n * Decodes a Message message from the specified reader or buffer.\n * @function decode\n * @memberof Message\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message} Message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Message.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.wantlist = $root.Message.Wantlist.decode(r, r.uint32());\n break;\n }\n case 2: {\n if (!(m.blocks && m.blocks.length))\n m.blocks = [];\n m.blocks.push(r.bytes());\n break;\n }\n case 3: {\n if (!(m.payload && m.payload.length))\n m.payload = [];\n m.payload.push($root.Message.Block.decode(r, r.uint32()));\n break;\n }\n case 4: {\n if (!(m.blockPresences && m.blockPresences.length))\n m.blockPresences = [];\n m.blockPresences.push($root.Message.BlockPresence.decode(r, r.uint32()));\n break;\n }\n case 5: {\n m.pendingBytes = r.int32();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Message message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message\n * @static\n * @param {Object.} d Plain object\n * @returns {Message} Message\n */\n Message.fromObject = function fromObject(d) {\n if (d instanceof $root.Message)\n return d;\n var m = new $root.Message();\n if (d.wantlist != null) {\n if (typeof d.wantlist !== \"object\")\n throw TypeError(\".Message.wantlist: object expected\");\n m.wantlist = $root.Message.Wantlist.fromObject(d.wantlist);\n }\n if (d.blocks) {\n if (!Array.isArray(d.blocks))\n throw TypeError(\".Message.blocks: array expected\");\n m.blocks = [];\n for (var i = 0; i < d.blocks.length; ++i) {\n if (typeof d.blocks[i] === \"string\")\n $util.base64.decode(d.blocks[i], m.blocks[i] = $util.newBuffer($util.base64.length(d.blocks[i])), 0);\n else if (d.blocks[i].length >= 0)\n m.blocks[i] = d.blocks[i];\n }\n }\n if (d.payload) {\n if (!Array.isArray(d.payload))\n throw TypeError(\".Message.payload: array expected\");\n m.payload = [];\n for (var i = 0; i < d.payload.length; ++i) {\n if (typeof d.payload[i] !== \"object\")\n throw TypeError(\".Message.payload: object expected\");\n m.payload[i] = $root.Message.Block.fromObject(d.payload[i]);\n }\n }\n if (d.blockPresences) {\n if (!Array.isArray(d.blockPresences))\n throw TypeError(\".Message.blockPresences: array expected\");\n m.blockPresences = [];\n for (var i = 0; i < d.blockPresences.length; ++i) {\n if (typeof d.blockPresences[i] !== \"object\")\n throw TypeError(\".Message.blockPresences: object expected\");\n m.blockPresences[i] = $root.Message.BlockPresence.fromObject(d.blockPresences[i]);\n }\n }\n if (d.pendingBytes != null) {\n m.pendingBytes = d.pendingBytes | 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Message message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message\n * @static\n * @param {Message} m Message\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Message.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.blocks = [];\n d.payload = [];\n d.blockPresences = [];\n }\n if (o.defaults) {\n d.wantlist = null;\n d.pendingBytes = 0;\n }\n if (m.wantlist != null && m.hasOwnProperty(\"wantlist\")) {\n d.wantlist = $root.Message.Wantlist.toObject(m.wantlist, o);\n }\n if (m.blocks && m.blocks.length) {\n d.blocks = [];\n for (var j = 0; j < m.blocks.length; ++j) {\n d.blocks[j] = o.bytes === String ? $util.base64.encode(m.blocks[j], 0, m.blocks[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.blocks[j]) : m.blocks[j];\n }\n }\n if (m.payload && m.payload.length) {\n d.payload = [];\n for (var j = 0; j < m.payload.length; ++j) {\n d.payload[j] = $root.Message.Block.toObject(m.payload[j], o);\n }\n }\n if (m.blockPresences && m.blockPresences.length) {\n d.blockPresences = [];\n for (var j = 0; j < m.blockPresences.length; ++j) {\n d.blockPresences[j] = $root.Message.BlockPresence.toObject(m.blockPresences[j], o);\n }\n }\n if (m.pendingBytes != null && m.hasOwnProperty(\"pendingBytes\")) {\n d.pendingBytes = m.pendingBytes;\n }\n return d;\n };\n\n /**\n * Converts this Message to JSON.\n * @function toJSON\n * @memberof Message\n * @instance\n * @returns {Object.} JSON object\n */\n Message.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Message\n * @function getTypeUrl\n * @memberof Message\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Message.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message\";\n };\n\n Message.Wantlist = (function() {\n\n /**\n * Properties of a Wantlist.\n * @memberof Message\n * @interface IWantlist\n * @property {Array.|null} [entries] Wantlist entries\n * @property {boolean|null} [full] Wantlist full\n */\n\n /**\n * Constructs a new Wantlist.\n * @memberof Message\n * @classdesc Represents a Wantlist.\n * @implements IWantlist\n * @constructor\n * @param {Message.IWantlist=} [p] Properties to set\n */\n function Wantlist(p) {\n this.entries = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Wantlist entries.\n * @member {Array.} entries\n * @memberof Message.Wantlist\n * @instance\n */\n Wantlist.prototype.entries = $util.emptyArray;\n\n /**\n * Wantlist full.\n * @member {boolean} full\n * @memberof Message.Wantlist\n * @instance\n */\n Wantlist.prototype.full = false;\n\n /**\n * Encodes the specified Wantlist message. Does not implicitly {@link Message.Wantlist.verify|verify} messages.\n * @function encode\n * @memberof Message.Wantlist\n * @static\n * @param {Message.IWantlist} m Wantlist message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Wantlist.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.entries != null && m.entries.length) {\n for (var i = 0; i < m.entries.length; ++i)\n $root.Message.Wantlist.Entry.encode(m.entries[i], w.uint32(10).fork()).ldelim();\n }\n if (m.full != null && Object.hasOwnProperty.call(m, \"full\"))\n w.uint32(16).bool(m.full);\n return w;\n };\n\n /**\n * Decodes a Wantlist message from the specified reader or buffer.\n * @function decode\n * @memberof Message.Wantlist\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.Wantlist} Wantlist\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Wantlist.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.Wantlist();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n if (!(m.entries && m.entries.length))\n m.entries = [];\n m.entries.push($root.Message.Wantlist.Entry.decode(r, r.uint32()));\n break;\n }\n case 2: {\n m.full = r.bool();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Wantlist message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.Wantlist\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.Wantlist} Wantlist\n */\n Wantlist.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.Wantlist)\n return d;\n var m = new $root.Message.Wantlist();\n if (d.entries) {\n if (!Array.isArray(d.entries))\n throw TypeError(\".Message.Wantlist.entries: array expected\");\n m.entries = [];\n for (var i = 0; i < d.entries.length; ++i) {\n if (typeof d.entries[i] !== \"object\")\n throw TypeError(\".Message.Wantlist.entries: object expected\");\n m.entries[i] = $root.Message.Wantlist.Entry.fromObject(d.entries[i]);\n }\n }\n if (d.full != null) {\n m.full = Boolean(d.full);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Wantlist message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.Wantlist\n * @static\n * @param {Message.Wantlist} m Wantlist\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Wantlist.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.entries = [];\n }\n if (o.defaults) {\n d.full = false;\n }\n if (m.entries && m.entries.length) {\n d.entries = [];\n for (var j = 0; j < m.entries.length; ++j) {\n d.entries[j] = $root.Message.Wantlist.Entry.toObject(m.entries[j], o);\n }\n }\n if (m.full != null && m.hasOwnProperty(\"full\")) {\n d.full = m.full;\n }\n return d;\n };\n\n /**\n * Converts this Wantlist to JSON.\n * @function toJSON\n * @memberof Message.Wantlist\n * @instance\n * @returns {Object.} JSON object\n */\n Wantlist.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Wantlist\n * @function getTypeUrl\n * @memberof Message.Wantlist\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Wantlist.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.Wantlist\";\n };\n\n /**\n * WantType enum.\n * @name Message.Wantlist.WantType\n * @enum {number}\n * @property {number} Block=0 Block value\n * @property {number} Have=1 Have value\n */\n Wantlist.WantType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Block\"] = 0;\n values[valuesById[1] = \"Have\"] = 1;\n return values;\n })();\n\n Wantlist.Entry = (function() {\n\n /**\n * Properties of an Entry.\n * @memberof Message.Wantlist\n * @interface IEntry\n * @property {Uint8Array|null} [block] Entry block\n * @property {number|null} [priority] Entry priority\n * @property {boolean|null} [cancel] Entry cancel\n * @property {Message.Wantlist.WantType|null} [wantType] Entry wantType\n * @property {boolean|null} [sendDontHave] Entry sendDontHave\n */\n\n /**\n * Constructs a new Entry.\n * @memberof Message.Wantlist\n * @classdesc Represents an Entry.\n * @implements IEntry\n * @constructor\n * @param {Message.Wantlist.IEntry=} [p] Properties to set\n */\n function Entry(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Entry block.\n * @member {Uint8Array} block\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.block = $util.newBuffer([]);\n\n /**\n * Entry priority.\n * @member {number} priority\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.priority = 0;\n\n /**\n * Entry cancel.\n * @member {boolean} cancel\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.cancel = false;\n\n /**\n * Entry wantType.\n * @member {Message.Wantlist.WantType} wantType\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.wantType = 0;\n\n /**\n * Entry sendDontHave.\n * @member {boolean} sendDontHave\n * @memberof Message.Wantlist.Entry\n * @instance\n */\n Entry.prototype.sendDontHave = false;\n\n /**\n * Encodes the specified Entry message. Does not implicitly {@link Message.Wantlist.Entry.verify|verify} messages.\n * @function encode\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {Message.Wantlist.IEntry} m Entry message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Entry.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.block != null && Object.hasOwnProperty.call(m, \"block\"))\n w.uint32(10).bytes(m.block);\n if (m.priority != null && Object.hasOwnProperty.call(m, \"priority\"))\n w.uint32(16).int32(m.priority);\n if (m.cancel != null && Object.hasOwnProperty.call(m, \"cancel\"))\n w.uint32(24).bool(m.cancel);\n if (m.wantType != null && Object.hasOwnProperty.call(m, \"wantType\"))\n w.uint32(32).int32(m.wantType);\n if (m.sendDontHave != null && Object.hasOwnProperty.call(m, \"sendDontHave\"))\n w.uint32(40).bool(m.sendDontHave);\n return w;\n };\n\n /**\n * Decodes an Entry message from the specified reader or buffer.\n * @function decode\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.Wantlist.Entry} Entry\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Entry.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.Wantlist.Entry();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.block = r.bytes();\n break;\n }\n case 2: {\n m.priority = r.int32();\n break;\n }\n case 3: {\n m.cancel = r.bool();\n break;\n }\n case 4: {\n m.wantType = r.int32();\n break;\n }\n case 5: {\n m.sendDontHave = r.bool();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates an Entry message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.Wantlist.Entry} Entry\n */\n Entry.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.Wantlist.Entry)\n return d;\n var m = new $root.Message.Wantlist.Entry();\n if (d.block != null) {\n if (typeof d.block === \"string\")\n $util.base64.decode(d.block, m.block = $util.newBuffer($util.base64.length(d.block)), 0);\n else if (d.block.length >= 0)\n m.block = d.block;\n }\n if (d.priority != null) {\n m.priority = d.priority | 0;\n }\n if (d.cancel != null) {\n m.cancel = Boolean(d.cancel);\n }\n switch (d.wantType) {\n case \"Block\":\n case 0:\n m.wantType = 0;\n break;\n case \"Have\":\n case 1:\n m.wantType = 1;\n break;\n }\n if (d.sendDontHave != null) {\n m.sendDontHave = Boolean(d.sendDontHave);\n }\n return m;\n };\n\n /**\n * Creates a plain object from an Entry message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {Message.Wantlist.Entry} m Entry\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Entry.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.block = \"\";\n else {\n d.block = [];\n if (o.bytes !== Array)\n d.block = $util.newBuffer(d.block);\n }\n d.priority = 0;\n d.cancel = false;\n d.wantType = o.enums === String ? \"Block\" : 0;\n d.sendDontHave = false;\n }\n if (m.block != null && m.hasOwnProperty(\"block\")) {\n d.block = o.bytes === String ? $util.base64.encode(m.block, 0, m.block.length) : o.bytes === Array ? Array.prototype.slice.call(m.block) : m.block;\n }\n if (m.priority != null && m.hasOwnProperty(\"priority\")) {\n d.priority = m.priority;\n }\n if (m.cancel != null && m.hasOwnProperty(\"cancel\")) {\n d.cancel = m.cancel;\n }\n if (m.wantType != null && m.hasOwnProperty(\"wantType\")) {\n d.wantType = o.enums === String ? $root.Message.Wantlist.WantType[m.wantType] : m.wantType;\n }\n if (m.sendDontHave != null && m.hasOwnProperty(\"sendDontHave\")) {\n d.sendDontHave = m.sendDontHave;\n }\n return d;\n };\n\n /**\n * Converts this Entry to JSON.\n * @function toJSON\n * @memberof Message.Wantlist.Entry\n * @instance\n * @returns {Object.} JSON object\n */\n Entry.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Entry\n * @function getTypeUrl\n * @memberof Message.Wantlist.Entry\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Entry.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.Wantlist.Entry\";\n };\n\n return Entry;\n })();\n\n return Wantlist;\n })();\n\n Message.Block = (function() {\n\n /**\n * Properties of a Block.\n * @memberof Message\n * @interface IBlock\n * @property {Uint8Array|null} [prefix] Block prefix\n * @property {Uint8Array|null} [data] Block data\n */\n\n /**\n * Constructs a new Block.\n * @memberof Message\n * @classdesc Represents a Block.\n * @implements IBlock\n * @constructor\n * @param {Message.IBlock=} [p] Properties to set\n */\n function Block(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Block prefix.\n * @member {Uint8Array} prefix\n * @memberof Message.Block\n * @instance\n */\n Block.prototype.prefix = $util.newBuffer([]);\n\n /**\n * Block data.\n * @member {Uint8Array} data\n * @memberof Message.Block\n * @instance\n */\n Block.prototype.data = $util.newBuffer([]);\n\n /**\n * Encodes the specified Block message. Does not implicitly {@link Message.Block.verify|verify} messages.\n * @function encode\n * @memberof Message.Block\n * @static\n * @param {Message.IBlock} m Block message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Block.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.prefix != null && Object.hasOwnProperty.call(m, \"prefix\"))\n w.uint32(10).bytes(m.prefix);\n if (m.data != null && Object.hasOwnProperty.call(m, \"data\"))\n w.uint32(18).bytes(m.data);\n return w;\n };\n\n /**\n * Decodes a Block message from the specified reader or buffer.\n * @function decode\n * @memberof Message.Block\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.Block} Block\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Block.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.Block();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.prefix = r.bytes();\n break;\n }\n case 2: {\n m.data = r.bytes();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Block message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.Block\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.Block} Block\n */\n Block.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.Block)\n return d;\n var m = new $root.Message.Block();\n if (d.prefix != null) {\n if (typeof d.prefix === \"string\")\n $util.base64.decode(d.prefix, m.prefix = $util.newBuffer($util.base64.length(d.prefix)), 0);\n else if (d.prefix.length >= 0)\n m.prefix = d.prefix;\n }\n if (d.data != null) {\n if (typeof d.data === \"string\")\n $util.base64.decode(d.data, m.data = $util.newBuffer($util.base64.length(d.data)), 0);\n else if (d.data.length >= 0)\n m.data = d.data;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Block message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.Block\n * @static\n * @param {Message.Block} m Block\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Block.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.prefix = \"\";\n else {\n d.prefix = [];\n if (o.bytes !== Array)\n d.prefix = $util.newBuffer(d.prefix);\n }\n if (o.bytes === String)\n d.data = \"\";\n else {\n d.data = [];\n if (o.bytes !== Array)\n d.data = $util.newBuffer(d.data);\n }\n }\n if (m.prefix != null && m.hasOwnProperty(\"prefix\")) {\n d.prefix = o.bytes === String ? $util.base64.encode(m.prefix, 0, m.prefix.length) : o.bytes === Array ? Array.prototype.slice.call(m.prefix) : m.prefix;\n }\n if (m.data != null && m.hasOwnProperty(\"data\")) {\n d.data = o.bytes === String ? $util.base64.encode(m.data, 0, m.data.length) : o.bytes === Array ? Array.prototype.slice.call(m.data) : m.data;\n }\n return d;\n };\n\n /**\n * Converts this Block to JSON.\n * @function toJSON\n * @memberof Message.Block\n * @instance\n * @returns {Object.} JSON object\n */\n Block.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for Block\n * @function getTypeUrl\n * @memberof Message.Block\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n Block.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.Block\";\n };\n\n return Block;\n })();\n\n /**\n * BlockPresenceType enum.\n * @name Message.BlockPresenceType\n * @enum {number}\n * @property {number} Have=0 Have value\n * @property {number} DontHave=1 DontHave value\n */\n Message.BlockPresenceType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Have\"] = 0;\n values[valuesById[1] = \"DontHave\"] = 1;\n return values;\n })();\n\n Message.BlockPresence = (function() {\n\n /**\n * Properties of a BlockPresence.\n * @memberof Message\n * @interface IBlockPresence\n * @property {Uint8Array|null} [cid] BlockPresence cid\n * @property {Message.BlockPresenceType|null} [type] BlockPresence type\n */\n\n /**\n * Constructs a new BlockPresence.\n * @memberof Message\n * @classdesc Represents a BlockPresence.\n * @implements IBlockPresence\n * @constructor\n * @param {Message.IBlockPresence=} [p] Properties to set\n */\n function BlockPresence(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * BlockPresence cid.\n * @member {Uint8Array} cid\n * @memberof Message.BlockPresence\n * @instance\n */\n BlockPresence.prototype.cid = $util.newBuffer([]);\n\n /**\n * BlockPresence type.\n * @member {Message.BlockPresenceType} type\n * @memberof Message.BlockPresence\n * @instance\n */\n BlockPresence.prototype.type = 0;\n\n /**\n * Encodes the specified BlockPresence message. Does not implicitly {@link Message.BlockPresence.verify|verify} messages.\n * @function encode\n * @memberof Message.BlockPresence\n * @static\n * @param {Message.IBlockPresence} m BlockPresence message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n BlockPresence.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.cid != null && Object.hasOwnProperty.call(m, \"cid\"))\n w.uint32(10).bytes(m.cid);\n if (m.type != null && Object.hasOwnProperty.call(m, \"type\"))\n w.uint32(16).int32(m.type);\n return w;\n };\n\n /**\n * Decodes a BlockPresence message from the specified reader or buffer.\n * @function decode\n * @memberof Message.BlockPresence\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Message.BlockPresence} BlockPresence\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n BlockPresence.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Message.BlockPresence();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1: {\n m.cid = r.bytes();\n break;\n }\n case 2: {\n m.type = r.int32();\n break;\n }\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a BlockPresence message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Message.BlockPresence\n * @static\n * @param {Object.} d Plain object\n * @returns {Message.BlockPresence} BlockPresence\n */\n BlockPresence.fromObject = function fromObject(d) {\n if (d instanceof $root.Message.BlockPresence)\n return d;\n var m = new $root.Message.BlockPresence();\n if (d.cid != null) {\n if (typeof d.cid === \"string\")\n $util.base64.decode(d.cid, m.cid = $util.newBuffer($util.base64.length(d.cid)), 0);\n else if (d.cid.length >= 0)\n m.cid = d.cid;\n }\n switch (d.type) {\n case \"Have\":\n case 0:\n m.type = 0;\n break;\n case \"DontHave\":\n case 1:\n m.type = 1;\n break;\n }\n return m;\n };\n\n /**\n * Creates a plain object from a BlockPresence message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Message.BlockPresence\n * @static\n * @param {Message.BlockPresence} m BlockPresence\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n BlockPresence.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if (o.bytes === String)\n d.cid = \"\";\n else {\n d.cid = [];\n if (o.bytes !== Array)\n d.cid = $util.newBuffer(d.cid);\n }\n d.type = o.enums === String ? \"Have\" : 0;\n }\n if (m.cid != null && m.hasOwnProperty(\"cid\")) {\n d.cid = o.bytes === String ? $util.base64.encode(m.cid, 0, m.cid.length) : o.bytes === Array ? Array.prototype.slice.call(m.cid) : m.cid;\n }\n if (m.type != null && m.hasOwnProperty(\"type\")) {\n d.type = o.enums === String ? $root.Message.BlockPresenceType[m.type] : m.type;\n }\n return d;\n };\n\n /**\n * Converts this BlockPresence to JSON.\n * @function toJSON\n * @memberof Message.BlockPresence\n * @instance\n * @returns {Object.} JSON object\n */\n BlockPresence.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * Gets the default type url for BlockPresence\n * @function getTypeUrl\n * @memberof Message.BlockPresence\n * @static\n * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")\n * @returns {string} The default type url\n */\n BlockPresence.getTypeUrl = function getTypeUrl(typeUrlPrefix) {\n if (typeUrlPrefix === undefined) {\n typeUrlPrefix = \"type.googleapis.com\";\n }\n return typeUrlPrefix + \"/Message.BlockPresence\";\n };\n\n return BlockPresence;\n })();\n\n return Message;\n})();\n\nexport { $root as default };\n", "\nimport { WantListEntry as Entry } from './entry.js'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { Message } from '../message/message.js'\nimport { trackedMap } from '@libp2p/tracked-map'\n\nconst WantType = {\n Block: Message.Wantlist.WantType.Block,\n Have: Message.Wantlist.WantType.Have\n}\n\n/**\n * @template T\n * @param {(v:T) => number} fn\n * @param {T[]} list\n * @returns {T[]}\n */\nconst sortBy = (fn, list) => {\n return Array.prototype.slice.call(list, 0).sort((a, b) => {\n const aa = fn(a)\n const bb = fn(b)\n return aa < bb ? -1 : aa > bb ? 1 : 0\n })\n}\n\n/**\n * @typedef {import('multiformats').CID} CID\n */\n\nexport class Wantlist {\n /**\n * @param {import('../stats').Stats} [stats]\n * @param {import('@libp2p/interface-libp2p').Libp2p} [libp2p]\n */\n constructor (stats, libp2p) {\n /** @type {Map} */\n this.set = libp2p\n ? trackedMap({\n name: 'ipfs_bitswap_wantlist',\n metrics: libp2p.metrics\n })\n : new Map()\n this._stats = stats\n }\n\n get length () {\n return this.set.size\n }\n\n /**\n * @param {CID} cid\n * @param {number} priority\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n */\n add (cid, priority, wantType) {\n const cidStr = cid.toString(base58btc)\n const entry = this.set.get(cidStr)\n\n if (entry) {\n entry.inc()\n entry.priority = priority\n\n // We can only overwrite want-have with want-block\n if (entry.wantType === WantType.Have && wantType === WantType.Block) {\n entry.wantType = wantType\n }\n } else {\n this.set.set(cidStr, new Entry(cid, priority, wantType))\n if (this._stats) {\n this._stats.push(null, 'wantListSize', 1)\n }\n }\n }\n\n /**\n * @param {CID} cid\n */\n remove (cid) {\n const cidStr = cid.toString(base58btc)\n const entry = this.set.get(cidStr)\n\n if (!entry) {\n return\n }\n\n entry.dec()\n\n // only delete when no refs are held\n if (entry.hasRefs()) {\n return\n }\n\n this.set.delete(cidStr)\n if (this._stats) {\n this._stats.push(null, 'wantListSize', -1)\n }\n }\n\n /**\n * @param {string} cidStr\n */\n removeForce (cidStr) {\n if (this.set.has(cidStr)) {\n this.set.delete(cidStr)\n }\n }\n\n /**\n * @param {(entry:Entry, key:string) => void} fn\n */\n forEach (fn) {\n return this.set.forEach(fn)\n }\n\n entries () {\n return this.set.entries()\n }\n\n sortedEntries () {\n // TODO: Figure out if this is an actual bug.\n // @ts-expect-error - Property 'key' does not exist on type 'WantListEntry'\n return new Map(sortBy(o => o[1].key, Array.from(this.set.entries())))\n }\n\n /**\n * @param {CID} cid\n */\n contains (cid) {\n const cidStr = cid.toString(base58btc)\n return this.set.has(cidStr)\n }\n\n /**\n * @param {CID} cid\n */\n get (cid) {\n const cidStr = cid.toString(base58btc)\n return this.set.get(cidStr)\n }\n}\n\nWantlist.Entry = Entry\n", "\nimport { Wantlist } from '../wantlist/index.js'\nimport { base58btc } from 'multiformats/bases/base58'\n\nconst WantlistEntry = Wantlist.Entry\n\nexport class BitswapMessageEntry {\n /**\n * @param {import('multiformats').CID} cid\n * @param {number} priority\n * @param {import('./message').Message.Wantlist.WantType} wantType\n * @param {boolean} [cancel]\n * @param {boolean} [sendDontHave]\n */\n constructor (cid, priority, wantType, cancel, sendDontHave) {\n this.entry = new WantlistEntry(cid, priority, wantType)\n this.cancel = Boolean(cancel)\n this.sendDontHave = Boolean(sendDontHave)\n }\n\n get cid () {\n return this.entry.cid\n }\n\n set cid (cid) {\n this.entry.cid = cid\n }\n\n get priority () {\n return this.entry.priority\n }\n\n set priority (val) {\n this.entry.priority = val\n }\n\n get wantType () {\n return this.entry.wantType\n }\n\n set wantType (val) {\n this.entry.wantType = val\n }\n\n get [Symbol.toStringTag] () {\n const cidStr = this.cid.toString(base58btc)\n return `BitswapMessageEntry ${cidStr} `\n }\n\n /**\n * @param {this} other\n */\n equals (other) {\n return (this.cancel === other.cancel) &&\n (this.sendDontHave === other.sendDontHave) &&\n (this.wantType === other.wantType) &&\n this.entry.equals(other.entry)\n }\n}\n", "import { logger as createLogger } from '@libp2p/logger'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { BitswapMessageEntry } from '../message/entry.js'\n\n/**\n * Creates a logger for the given subsystem\n *\n * @param {import('@libp2p/interface-peer-id').PeerId} [id]\n * @param {string} [subsystem]\n */\nexport const logger = (id, subsystem) => {\n const name = ['bitswap']\n if (subsystem) {\n name.push(subsystem)\n }\n if (id) {\n name.push(`${id.toString().slice(0, 8)}`)\n }\n\n return createLogger(name.join(':'))\n}\n\n/**\n * @template X, T\n * @param {(x:X, t:T) => boolean} pred\n * @param {X} x\n * @param {T[]} list\n * @returns {boolean}\n */\nexport const includesWith = (pred, x, list) => {\n let idx = 0\n const len = list.length\n while (idx < len) {\n if (pred(x, list[idx])) {\n return true\n }\n idx += 1\n }\n return false\n}\n\n/**\n * @template T\n * @param {(x:T, t:T) => boolean} pred\n * @param {T[]} list\n * @returns {T[]}\n */\nexport const uniqWith = (pred, list) => {\n let idx = 0\n const len = list.length\n const result = []\n let item\n\n while (idx < len) {\n item = list[idx]\n if (!includesWith(pred, item, result)) {\n result[result.length] = item\n }\n idx += 1\n }\n return result\n}\n\n/**\n * @template {string|number|symbol} K\n * @template V\n * @param {(v:V) => K} pred\n * @param {V[]} list\n * @returns {Record}\n */\nexport const groupBy = (pred, list) => {\n return list.reduce((acc, v) => {\n const k = pred(v)\n\n if (acc[k]) {\n acc[k].push(v)\n } else {\n acc[k] = [v]\n }\n return acc\n }, /** @type {Record} */({}))\n}\n\n/**\n * @template T, E\n * @param {(a:T, b:E) => boolean} pred\n * @param {T[]} list\n * @param {E[]} values\n * @returns {T[]}\n */\nexport const pullAllWith = (pred, list, values) => {\n return list.filter(i => {\n return !includesWith(pred, i, values)\n })\n}\n\n/**\n * @template T\n * @param {(v:T) => number} fn\n * @param {T[]} list\n * @returns {T[]}\n */\nexport const sortBy = (fn, list) => {\n return Array.prototype.slice.call(list, 0).sort((a, b) => {\n const aa = fn(a)\n const bb = fn(b)\n return aa < bb ? -1 : aa > bb ? 1 : 0\n })\n}\n\n/**\n * Is equal for Maps of BitswapMessageEntry or Uint8Arrays\n *\n * @param {Map} a\n * @param {Map} b\n */\nexport const isMapEqual = (a, b) => {\n if (a.size !== b.size) {\n return false\n }\n\n for (const [key, valueA] of a) {\n const valueB = b.get(key)\n\n if (valueB === undefined) {\n return false\n }\n\n // TODO: revisit this\n\n // Support Blocks\n if (valueA instanceof Uint8Array && valueB instanceof Uint8Array && !uint8ArrayEquals(valueA, valueB)) {\n return false\n }\n\n // Support BitswapMessageEntry\n if (valueA instanceof BitswapMessageEntry && valueB instanceof BitswapMessageEntry && !valueA.equals(valueB)) {\n return false\n }\n }\n\n return true\n}\n", "const SECOND = 1000\n\nexport const maxProvidersPerRequest = 3\nexport const providerRequestTimeout = 10 * SECOND\nexport const hasBlockTimeout = 15 * SECOND\nexport const provideTimeout = 15 * SECOND\nexport const kMaxPriority = Math.pow(2, 31) - 1\nexport const maxListeners = 1000\nexport const wantlistSendDebounceMs = 1\n", "var functionDebounce = debounce;\n\nfunction debounce(fn, wait, callFirst) {\n var timeout = null;\n var debouncedFn = null;\n\n var clear = function() {\n if (timeout) {\n clearTimeout(timeout);\n\n debouncedFn = null;\n timeout = null;\n }\n };\n\n var flush = function() {\n var call = debouncedFn;\n clear();\n\n if (call) {\n call();\n }\n };\n\n var debounceWrapper = function() {\n if (!wait) {\n return fn.apply(this, arguments);\n }\n\n var context = this;\n var args = arguments;\n var callNow = callFirst && !timeout;\n clear();\n\n debouncedFn = function() {\n fn.apply(context, args);\n };\n\n timeout = setTimeout(function() {\n timeout = null;\n\n if (!callNow) {\n var call = debouncedFn;\n debouncedFn = null;\n\n return call();\n }\n }, wait);\n\n if (callNow) {\n return debouncedFn();\n }\n };\n\n debounceWrapper.cancel = clear;\n debounceWrapper.flush = flush;\n\n return debounceWrapper;\n}\n\nexport {functionDebounce as default};\n", "\n// @ts-ignore\nimport debounce from 'just-debounce-it'\nimport { BitswapMessage as Message } from '../message/index.js'\nimport { logger } from '../utils/index.js'\nimport { wantlistSendDebounceMs } from '../constants.js'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('../network').Network} Network\n */\n\nexport class MsgQueue {\n /**\n * @param {PeerId} selfPeerId\n * @param {PeerId} otherPeerId\n * @param {Network} network\n */\n constructor (selfPeerId, otherPeerId, network) {\n this.peerId = otherPeerId\n this.network = network\n this.refcnt = 1\n\n /**\n * @private\n * @type {{cid:CID, priority:number, cancel?:boolean}[]}\n */\n this._entries = []\n /** @private */\n this._log = logger(selfPeerId, 'msgqueue')\n this.sendEntries = debounce(this._sendEntries.bind(this), wantlistSendDebounceMs)\n }\n\n /**\n * @param {Message} msg\n */\n addMessage (msg) {\n if (msg.empty) {\n return\n }\n\n this.send(msg)\n }\n\n /**\n * @param {{cid:CID, priority:number}[]} entries\n */\n addEntries (entries) {\n this._entries = this._entries.concat(entries)\n this.sendEntries()\n }\n\n /**\n * @private\n */\n _sendEntries () {\n if (!this._entries.length) {\n return\n }\n\n const msg = new Message(false)\n this._entries.forEach((entry) => {\n if (entry.cancel) {\n msg.cancel(entry.cid)\n } else {\n msg.addEntry(entry.cid, entry.priority)\n }\n })\n this._entries = []\n this.addMessage(msg)\n }\n\n /**\n * @param {Message} msg\n */\n async send (msg) {\n try {\n await this.network.connectTo(this.peerId)\n } catch (/** @type {any} */ err) {\n this._log.error('cant connect to peer %s: %s', this.peerId.toString(), err.message)\n return\n }\n\n this._log('sending message to peer %s', this.peerId.toString())\n\n // Note: Don't wait for sendMessage() to complete\n this.network.sendMessage(this.peerId, msg).catch((err) => {\n this._log.error('send error: %s', err.message)\n })\n }\n}\n", "\nimport { BitswapMessage as Message } from '../message/index.js'\nimport { Wantlist } from '../wantlist/index.js'\nimport * as CONSTANTS from '../constants.js'\nimport { MsgQueue } from './msg-queue.js'\nimport { logger } from '../utils/index.js'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { trackedMap } from '@libp2p/tracked-map'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats').CID} CID\n */\n\nexport class WantManager {\n /**\n * @param {PeerId} peerId\n * @param {import('../network').Network} network\n * @param {import('../stats').Stats} stats\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n */\n constructor (peerId, network, stats, libp2p) {\n /** @type {Map} */\n this.peers = trackedMap({\n name: 'ipfs_bitswap_want_manager_peers',\n metrics: libp2p.metrics\n })\n this.wantlist = new Wantlist(stats, libp2p)\n\n this.network = network\n this._stats = stats\n\n this._peerId = peerId\n this._log = logger(peerId, 'want')\n }\n\n /**\n * @private\n * @param {CID[]} cids\n * @param {boolean} cancel\n * @param {boolean} [force]\n */\n _addEntries (cids, cancel, force) {\n const entries = cids.map((cid, i) => {\n return new Message.Entry(cid, CONSTANTS.kMaxPriority - i, Message.WantType.Block, cancel)\n })\n\n entries.forEach((e) => {\n // add changes to our wantlist\n if (e.cancel) {\n if (force) {\n this.wantlist.removeForce(e.cid.toString(base58btc))\n } else {\n this.wantlist.remove(e.cid)\n }\n } else {\n this._log('adding to wl')\n // TODO: Figure out the wantType\n // @ts-expect-error - requires wantType\n this.wantlist.add(e.cid, e.priority)\n }\n })\n\n // broadcast changes\n for (const p of this.peers.values()) {\n p.addEntries(entries)\n }\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _startPeerHandler (peerId) {\n let mq = this.peers.get(peerId.toString())\n\n if (mq) {\n mq.refcnt++\n return\n }\n\n mq = new MsgQueue(this._peerId, peerId, this.network)\n\n // new peer, give them the full wantlist\n const fullwantlist = new Message(true)\n\n for (const entry of this.wantlist.entries()) {\n fullwantlist.addEntry(entry[1].cid, entry[1].priority)\n }\n\n mq.addMessage(fullwantlist)\n\n this.peers.set(peerId.toString(), mq)\n return mq\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _stopPeerHandler (peerId) {\n const mq = this.peers.get(peerId.toString())\n\n if (!mq) {\n return\n }\n\n mq.refcnt--\n if (mq.refcnt > 0) {\n return\n }\n\n this.peers.delete(peerId.toString())\n }\n\n /**\n * add all the cids to the wantlist\n *\n * @param {CID[]} cids\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n wantBlocks (cids, options = {}) {\n this._addEntries(cids, false)\n\n if (options && options.signal) {\n options.signal.addEventListener('abort', () => {\n this.cancelWants(cids)\n })\n }\n }\n\n /**\n * Remove blocks of all the given keys without respecting refcounts\n *\n * @param {CID[]} cids\n */\n unwantBlocks (cids) {\n this._log('unwant blocks: %s', cids.length)\n this._addEntries(cids, true, true)\n }\n\n /**\n * Cancel wanting all of the given keys\n *\n * @param {CID[]} cids\n */\n cancelWants (cids) {\n this._log('cancel wants: %s', cids.length)\n this._addEntries(cids, true)\n }\n\n /**\n * Returns a list of all currently connected peers\n */\n connectedPeers () {\n return Array.from(this.peers.keys())\n }\n\n /**\n * @param {PeerId} peerId\n */\n connected (peerId) {\n this._startPeerHandler(peerId)\n }\n\n /**\n * @param {PeerId} peerId\n */\n disconnected (peerId) {\n this._stopPeerHandler(peerId)\n }\n\n start () {\n }\n\n stop () {\n this.peers.forEach((mq) => this.disconnected(mq.peerId))\n }\n}\n", "import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = () => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] () {\n return symbol.toString()\n }\n\n get [symbol] () {\n return true\n }\n\n async setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId) {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n", "import * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport { createTopology } from '@libp2p/topology'\nimport { BitswapMessage as Message } from './message/index.js'\nimport * as CONSTANTS from './constants.js'\nimport { logger } from './utils/index.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableSource } from 'abortable-iterator'\n\n/**\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n * @typedef {import('@libp2p/interface-connection').Connection} Connection\n * @typedef {import('@libp2p/interface-connection').Stream} Stream\n * @typedef {import('./types').MultihashHasherLoader} MultihashHasherLoader\n *\n * @typedef {object} Provider\n * @property {PeerId} id\n * @property {Multiaddr[]} multiaddrs\n *\n * @typedef {import('it-stream-types').Duplex} Duplex\n */\n\nconst BITSWAP100 = '/ipfs/bitswap/1.0.0'\nconst BITSWAP110 = '/ipfs/bitswap/1.1.0'\nconst BITSWAP120 = '/ipfs/bitswap/1.2.0'\n\nconst DEFAULT_MAX_INBOUND_STREAMS = 32\nconst DEFAULT_MAX_OUTBOUND_STREAMS = 128\nconst DEFAULT_INCOMING_STREAM_TIMEOUT = 30000\n\nexport class Network {\n /**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {import('./bitswap').Bitswap} bitswap\n * @param {import('./stats').Stats} stats\n * @param {object} [options]\n * @param {boolean} [options.b100Only]\n * @param {MultihashHasherLoader} [options.hashLoader]\n * @param {number} [options.maxInboundStreams=32]\n * @param {number} [options.maxOutboundStreams=32]\n * @param {number} [options.incomingStreamTimeout=30000]\n */\n constructor (libp2p, bitswap, stats, options = {}) {\n this._log = logger(libp2p.peerId, 'network')\n this._libp2p = libp2p\n this._bitswap = bitswap\n this._protocols = [BITSWAP100]\n\n if (!options.b100Only) {\n // Latest bitswap first\n this._protocols.unshift(BITSWAP110)\n this._protocols.unshift(BITSWAP120)\n }\n\n this._stats = stats\n this._running = false\n\n // bind event listeners\n this._onPeerConnect = this._onPeerConnect.bind(this)\n this._onPeerDisconnect = this._onPeerDisconnect.bind(this)\n this._onConnection = this._onConnection.bind(this)\n this._hashLoader = options.hashLoader\n this._maxInboundStreams = options.maxInboundStreams ?? DEFAULT_MAX_INBOUND_STREAMS\n this._maxOutboundStreams = options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS\n this._incomingStreamTimeout = options.incomingStreamTimeout ?? DEFAULT_INCOMING_STREAM_TIMEOUT\n }\n\n async start () {\n this._running = true\n await this._libp2p.handle(this._protocols, this._onConnection, {\n maxInboundStreams: this._maxInboundStreams,\n maxOutboundStreams: this._maxOutboundStreams\n })\n\n // register protocol with topology\n const topology = createTopology({\n onConnect: this._onPeerConnect,\n onDisconnect: this._onPeerDisconnect\n })\n\n /** @type {string[]} */\n this._registrarIds = []\n\n for (const protocol of this._protocols) {\n this._registrarIds.push(await this._libp2p.register(protocol, topology))\n }\n\n // All existing connections are like new ones for us\n this._libp2p.getConnections().forEach(conn => {\n this._onPeerConnect(conn.remotePeer)\n })\n }\n\n async stop () {\n this._running = false\n\n // Unhandle both, libp2p doesn't care if it's not already handled\n await this._libp2p.unhandle(this._protocols)\n\n // unregister protocol and handlers\n if (this._registrarIds != null) {\n for (const id of this._registrarIds) {\n this._libp2p.unregister(id)\n }\n\n this._registrarIds = []\n }\n }\n\n /**\n * Handles both types of incoming bitswap messages\n *\n * @private\n * @param {object} connection\n * @param {Stream} connection.stream - A duplex iterable stream\n * @param {Connection} connection.connection - A libp2p Connection\n */\n _onConnection ({ stream, connection }) {\n if (!this._running) {\n return\n }\n\n const controller = new TimeoutController(this._incomingStreamTimeout)\n\n Promise.resolve().then(async () => {\n this._log('incoming new bitswap %s connection from %p', stream.stat.protocol, connection.remotePeer)\n\n await pipe(\n abortableSource(stream.source, controller.signal),\n lp.decode(),\n async (source) => {\n for await (const data of source) {\n try {\n const message = await Message.deserialize(data.subarray(), this._hashLoader)\n await this._bitswap._receiveMessage(connection.remotePeer, message)\n } catch (/** @type {any} */ err) {\n this._bitswap._receiveError(err)\n break\n }\n\n // we have received some data so reset the timeout controller\n controller.reset()\n }\n }\n )\n })\n .catch(err => {\n this._log(err)\n stream.abort(err)\n })\n .finally(() => {\n controller.clear()\n stream.close()\n })\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _onPeerConnect (peerId) {\n this._bitswap._onPeerConnected(peerId)\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n */\n _onPeerDisconnect (peerId) {\n this._bitswap._onPeerDisconnected(peerId)\n }\n\n /**\n * Find providers given a `cid`.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n * @returns {AsyncIterable}\n */\n findProviders (cid, options = {}) {\n return this._libp2p.contentRouting.findProviders(cid, options)\n }\n\n /**\n * Find the providers of a given `cid` and connect to them.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async findAndConnect (cid, options) {\n const connectAttempts = []\n let found = 0\n\n for await (const provider of this.findProviders(cid, options)) {\n this._log(`connecting to provider ${provider.id}`)\n connectAttempts.push(\n this.connectTo(provider.id, options)\n .catch(err => {\n // Prevent unhandled promise rejection\n this._log.error(err)\n })\n )\n\n found++\n\n if (found === CONSTANTS.maxProvidersPerRequest) {\n break\n }\n }\n\n await Promise.all(connectAttempts)\n }\n\n /**\n * Tell the network we can provide content for the passed CID\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async provide (cid, options) {\n await this._libp2p.contentRouting.provide(cid, options)\n }\n\n /**\n * Connect to the given peer\n * Send the given msg (instance of Message) to the given peer\n *\n * @param {PeerId} peer\n * @param {Message} msg\n */\n async sendMessage (peer, msg) {\n if (!this._running) throw new Error('network isn\\'t running')\n\n const stringId = peer.toString()\n this._log('sendMessage to %s', stringId, msg)\n\n const connection = await this._libp2p.dial(peer)\n const stream = await connection.newStream([BITSWAP120, BITSWAP110, BITSWAP100])\n\n await writeMessage(stream, msg, this._log)\n\n this._updateSentStats(peer, msg.blocks)\n }\n\n /**\n * Connects to another peer\n *\n * @param {PeerId|Multiaddr} peer\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n * @returns {Promise}\n */\n async connectTo (peer, options) { // eslint-disable-line require-await\n if (!this._running) {\n throw new Error('network isn\\'t running')\n }\n\n return this._libp2p.dial(peer, options)\n }\n\n /**\n * @private\n * @param {PeerId} peer\n * @param {Map} blocks\n */\n _updateSentStats (peer, blocks) {\n const peerId = peer.toString()\n\n if (this._stats) {\n for (const block of blocks.values()) {\n this._stats.push(peerId, 'dataSent', block.length)\n }\n\n this._stats.push(peerId, 'blocksSent', blocks.size)\n }\n }\n}\n\n/**\n *\n * @param {Stream} stream\n * @param {Message} msg\n * @param {*} log\n */\nasync function writeMessage (stream, msg, log) {\n try {\n /** @type {Uint8Array} */\n let serialized\n switch (stream.stat.protocol) {\n case BITSWAP100:\n serialized = msg.serializeToBitswap100()\n break\n case BITSWAP110:\n case BITSWAP120:\n serialized = msg.serializeToBitswap110()\n break\n default:\n throw new Error('Unknown protocol: ' + stream.stat.protocol)\n }\n\n await pipe(\n [serialized],\n lp.encode(),\n stream\n )\n } catch (err) {\n log(err)\n } finally {\n stream.close()\n }\n}\n", "import { Wantlist } from '../wantlist/index.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n */\n\nexport class Ledger {\n /**\n * @param {import('@libp2p/interface-peer-id').PeerId} peerId\n */\n constructor (peerId) {\n this.partner = peerId\n this.wantlist = new Wantlist()\n\n this.exchangeCount = 0\n this.sentToPeer = new Map()\n\n this.accounting = {\n bytesSent: 0,\n bytesRecv: 0\n }\n }\n\n /**\n * @param {number} n\n */\n sentBytes (n) {\n this.exchangeCount++\n this.lastExchange = (new Date()).getTime()\n this.accounting.bytesSent += n\n }\n\n /**\n * @param {number} n\n */\n receivedBytes (n) {\n this.exchangeCount++\n this.lastExchange = (new Date()).getTime()\n this.accounting.bytesRecv += n\n }\n\n /**\n *\n * @param {CID} cid\n * @param {number} priority\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n * @returns {void}\n */\n wants (cid, priority, wantType) {\n this.wantlist.add(cid, priority, wantType)\n }\n\n /**\n * @param {CID} cid\n * @returns {void}\n */\n\n cancelWant (cid) {\n this.wantlist.remove(cid)\n }\n\n /**\n * @param {CID} cid\n */\n wantlistContains (cid) {\n return this.wantlist.get(cid)\n }\n\n /**\n * @returns {number}\n */\n debtRatio () {\n return (this.accounting.bytesSent / (this.accounting.bytesRecv + 1)) // +1 is to prevent division by zero\n }\n}\n", "/**\n * @template Key, Value\n * SortedMap is a Map whose iterator order can be defined by the user\n * @extends {Map}\n */\nexport class SortedMap extends Map {\n /**\n * @param {Array<[Key, Value]>} [entries]\n * @param {(a:[Key, Value], b:[Key, Value]) => number} [cmp] - compares [k1, v1] to [k2, v2]\n */\n constructor (entries, cmp) {\n super()\n this._cmp = cmp || this._defaultSort\n /** @type {Key[]} */\n this._keys = []\n for (const [k, v] of entries || []) {\n this.set(k, v)\n }\n }\n\n /**\n * Call update to update the position of the key when it should change.\n * For example if the compare function sorts by the priority field, and the\n * priority changes, call update.\n * Call indexOf() to get the index _before_ the change happens.\n *\n * @param {number} i - the index of entry whose position should be updated.\n */\n update (i) {\n if (i < 0 || i >= this._keys.length) {\n return\n }\n\n const k = this._keys[i]\n this._keys.splice(i, 1)\n const newIdx = this._find(k)\n this._keys.splice(newIdx, 0, k)\n }\n\n /**\n * @param {Key} k\n * @param {Value} v\n */\n set (k, v) {\n // If the key is already in the map, remove it from the ordering and\n // re-insert it below\n if (this.has(k)) {\n const i = this.indexOf(k)\n this._keys.splice(i, 1)\n }\n\n // Update / insert the k/v into the map\n super.set(k, v)\n\n // Find the correct position of the newly inserted k/v in the order\n const i = this._find(k)\n this._keys.splice(i, 0, k)\n\n return this\n }\n\n clear () {\n super.clear()\n this._keys = []\n }\n\n /**\n * @param {Key} k\n */\n delete (k) {\n if (!this.has(k)) {\n return false\n }\n\n const i = this.indexOf(k)\n this._keys.splice(i, 1)\n return super.delete(k)\n }\n\n /**\n * @param {Key} k\n */\n indexOf (k) {\n if (!this.has(k)) {\n return -1\n }\n\n const i = this._find(k)\n if (this._keys[i] === k) {\n return i\n }\n\n // There may be more than one key with the same ordering\n // eg { k1: , k2: }\n // so scan outwards until the key matches\n for (let j = 1; j < this._keys.length; j++) {\n if (this._keys[i + j] === k) return i + j\n if (this._keys[i - j] === k) return i - j\n }\n\n return -1 // should never happen for existing key\n }\n\n /**\n * @private\n * @param {Key} k\n * @returns {number}\n */\n\n _find (k) {\n let lower = 0\n let upper = this._keys.length\n while (lower < upper) {\n const pivot = (lower + upper) >>> 1 // lower + (upper - lower) / 2\n const cmp = this._kCmp(this._keys[pivot], k)\n // console.log(` _find ${lower}:${upper}[${pivot}] ${cmp}`)\n if (cmp < 0) { // pivot < k\n lower = pivot + 1\n } else if (cmp > 0) { // pivot > k\n upper = pivot\n } else { // pivot == k\n return pivot\n }\n }\n return lower\n }\n\n * keys () {\n for (const k of this._keys) {\n yield k\n }\n\n return undefined\n }\n\n /**\n * @returns {IterableIterator}\n */\n * values () {\n for (const k of this._keys) {\n // @ts-ignore - return of `this.get(k)` is `Value|undefined` which is\n // incompatible with `Value`. Typechecker can't that this contains values\n // for all the `_keys`. ts(2322)\n yield this.get(k)\n }\n\n return undefined\n }\n\n /**\n * @returns {IterableIterator<[Key, Value]>}\n */\n * entries () {\n for (const k of this._keys) {\n // @ts-ignore - return of `this.get(k)` is `Value|undefined` which is\n // incompatible with `Value`. Typechecker can't that this contains values\n // for all the `_keys`. ts(2322)\n yield [k, this.get(k)]\n }\n\n return undefined\n }\n\n * [Symbol.iterator] () {\n yield * this.entries()\n }\n\n /**\n * @template This\n * @param {(entry:[Key, Value]) => void} cb\n * @param {This} [thisArg]\n */\n // @ts-expect-error - Callback in Map forEach is (V, K, Map) => void\n forEach (cb, thisArg) {\n if (!cb) {\n return\n }\n\n for (const k of this._keys) {\n cb.apply(thisArg, [[k, /** @type {Value} */(this.get(k))]])\n }\n }\n\n /**\n * @private\n * @param {[Key, Value]} a\n * @param {[Key, Value]} b\n * @returns {0|1|-1}\n */\n _defaultSort (a, b) {\n if (a[0] < b[0]) return -1\n if (b[0] < a[0]) return 1\n return 0\n }\n\n /**\n * @private\n * @param {Key} a\n * @param {Key} b\n */\n _kCmp (a, b) {\n return this._cmp(\n // @ts-ignore - get may return undefined\n [a, this.get(a)],\n // @ts-ignore - get may return undefined\n [b, this.get(b)]\n )\n }\n}\n", "import { SortedMap } from '../utils/sorted-map.js'\n\n/**\n * @typedef {object} PopTaskResult\n * @property {PeerId} [peerId]\n * @property {Task[]} tasks\n * @property {number} pendingSize\n *\n * @typedef {object} PendingTask\n * @property {number} created\n * @property {Task} task\n *\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('./types').Task} Task\n * @typedef {import('./types').TaskMerger} TaskMerger\n */\n\n/**\n * The task merger that is used by default.\n * Assumes that new tasks do not add any information over existing tasks,\n * and doesn't try to merge.\n *\n * @type {TaskMerger}\n */\nconst DefaultTaskMerger = {\n hasNewInfo () {\n return false\n },\n\n merge () {}\n}\n\n/**\n * Queue of requests to be processed by the engine.\n * The requests from each peer are added to the peer's queue, sorted by\n * priority.\n * Tasks are popped in priority order from the best peer - see popTasks()\n * for more details.\n */\nexport class RequestQueue {\n /**\n * @param {TaskMerger} [taskMerger]\n */\n constructor (taskMerger = DefaultTaskMerger) {\n this._taskMerger = taskMerger\n /** @type {SortedMap} */\n this._byPeer = new SortedMap([], PeerTasks.compare)\n }\n\n /**\n * Push tasks onto the queue for the given peer\n *\n * @param {PeerId} peerId\n * @param {Task[]} tasks\n * @returns {void}\n */\n pushTasks (peerId, tasks) {\n let peerTasks = this._byPeer.get(peerId.toString())\n\n if (!peerTasks) {\n peerTasks = new PeerTasks(peerId, this._taskMerger)\n }\n\n peerTasks.pushTasks(tasks)\n this._byPeer.set(peerId.toString(), peerTasks)\n }\n\n /**\n * Choose the peer with the least active work (or if all have the same active\n * work, the most pending tasks) and pop off the highest priority tasks until\n * the total size is at least targetMinBytes.\n * This puts the popped tasks into the \"active\" state, meaning they are\n * actively being processed (and cannot be modified).\n *\n * @param {number} targetMinBytes - the minimum total size of tasks to pop\n * @returns {PopTaskResult}\n */\n popTasks (targetMinBytes) {\n // Get the queue of tasks for the best peer and pop off tasks up to\n // targetMinBytes\n const peerTasks = this._head()\n if (peerTasks === undefined) {\n return { tasks: [], pendingSize: 0 }\n }\n\n const { tasks, pendingSize } = peerTasks.popTasks(targetMinBytes)\n if (tasks.length === 0) {\n return { tasks, pendingSize }\n }\n\n const peerId = peerTasks.peerId\n if (peerTasks.isIdle()) {\n // If there are no more tasks for the peer, free up its memory\n this._byPeer.delete(peerId.toString())\n } else {\n // If there are still tasks remaining, update the sort order of peerTasks\n // (because it depends on the number of pending tasks)\n this._byPeer.update(0)\n }\n\n return {\n peerId, tasks, pendingSize\n }\n }\n\n /**\n * @private\n * @returns {PeerTasks|undefined}\n */\n _head () {\n // Shortcut\n if (this._byPeer.size === 0) {\n return undefined\n }\n\n // eslint-disable-next-line no-unreachable-loop\n for (const [, v] of this._byPeer) {\n return v\n }\n\n return undefined\n }\n\n /**\n * Remove the task with the given topic for the given peer.\n *\n * @param {string} topic\n * @param {PeerId} peerId\n * @returns {void}\n */\n remove (topic, peerId) {\n const peerTasks = this._byPeer.get(peerId.toString())\n peerTasks && peerTasks.remove(topic)\n }\n\n /**\n * Called when the tasks for the given peer complete.\n *\n * @param {PeerId} peerId\n * @param {Task[]} tasks\n * @returns {void}\n */\n tasksDone (peerId, tasks) {\n const peerTasks = this._byPeer.get(peerId.toString())\n if (!peerTasks) {\n return\n }\n\n const i = this._byPeer.indexOf(peerId.toString())\n for (const task of tasks) {\n peerTasks.taskDone(task)\n }\n\n // Marking the tasks as done takes them out of the \"active\" state, and the\n // sort order depends on the size of the active tasks, so we need to update\n // the order.\n this._byPeer.update(i)\n }\n}\n\n/**\n * Queue of tasks for a particular peer, sorted by priority.\n */\nclass PeerTasks {\n /**\n * @param {PeerId} peerId\n * @param {TaskMerger} taskMerger\n */\n constructor (peerId, taskMerger) {\n this.peerId = peerId\n this._taskMerger = taskMerger\n this._activeTotalSize = 0\n this._pending = new PendingTasks()\n this._active = new Set()\n }\n\n /**\n * Push tasks onto the queue.\n *\n * @param {Task[]} tasks\n * @returns {void}\n */\n pushTasks (tasks) {\n for (const t of tasks) {\n this._pushTask(t)\n }\n }\n\n /**\n * @private\n * @param {Task} task\n * @returns {void}\n */\n\n _pushTask (task) {\n // If the new task doesn't add any more information over what we\n // already have in the active queue, then we can skip the new task\n if (!this._taskHasMoreInfoThanActiveTasks(task)) {\n return\n }\n\n // If there is already a non-active (pending) task with this topic\n const existingTask = this._pending.get(task.topic)\n if (existingTask) {\n // If the new task has a higher priority than the old task,\n if (task.priority > existingTask.priority) {\n // Update the priority and the task's position in the queue\n this._pending.updatePriority(task.topic, task.priority)\n }\n\n // Merge the information from the new task into the existing task\n this._taskMerger.merge(task, existingTask)\n\n // A task with the topic exists, so we don't need to add\n // the new task to the queue\n return\n }\n\n // Push the new task onto the queue\n this._pending.add(task)\n }\n\n /**\n * Indicates whether the new task adds any more information over tasks that are\n * already in the active task queue\n *\n * @private\n * @param {Task} task\n * @returns {boolean}\n */\n _taskHasMoreInfoThanActiveTasks (task) {\n const tasksWithTopic = []\n for (const activeTask of this._active) {\n if (activeTask.topic === task.topic) {\n tasksWithTopic.push(activeTask)\n }\n }\n\n // No tasks with that topic, so the new task adds information\n if (tasksWithTopic.length === 0) {\n return true\n }\n\n return this._taskMerger.hasNewInfo(task, tasksWithTopic)\n }\n\n /**\n * Pop tasks off the queue such that the total size is at least targetMinBytes\n *\n * @param {number} targetMinBytes\n * @returns {PopTaskResult}\n */\n popTasks (targetMinBytes) {\n let size = 0\n const tasks = []\n\n // Keep popping tasks until we get up to targetMinBytes (or one item over\n // targetMinBytes)\n const pendingTasks = this._pending.tasks()\n for (let i = 0; i < pendingTasks.length && size < targetMinBytes; i++) {\n const task = pendingTasks[i]\n tasks.push(task)\n size += task.size\n\n // Move tasks from pending to active\n this._pending.delete(task.topic)\n this._activeTotalSize += task.size\n this._active.add(task)\n }\n\n return {\n tasks, pendingSize: this._pending.totalSize\n }\n }\n\n /**\n * Called when a task completes.\n * Note: must be the same reference as returned from popTasks.\n *\n * @param {Task} task\n * @returns {void}\n */\n taskDone (task) {\n if (this._active.has(task)) {\n this._activeTotalSize -= task.size\n this._active.delete(task)\n }\n }\n\n /**\n * Remove pending tasks with the given topic\n *\n * @param {string} topic\n * @returns {void}\n */\n remove (topic) {\n this._pending.delete(topic)\n }\n\n /**\n * No work to be done, this PeerTasks object can be freed.\n *\n * @returns {boolean}\n */\n isIdle () {\n return this._pending.length === 0 && this._active.size === 0\n }\n\n /**\n * Compare PeerTasks\n *\n * @template Key\n * @param {[Key, PeerTasks]} a\n * @param {[Key, PeerTasks]} b\n * @returns {number}\n */\n static compare (a, b) {\n // Move peers with no pending tasks to the back of the queue\n if (a[1]._pending.length === 0) {\n return 1\n }\n if (b[1]._pending.length === 0) {\n return -1\n }\n\n // If the amount of active work is the same\n if (a[1]._activeTotalSize === b[1]._activeTotalSize) {\n // Choose the peer with the most pending work\n return b[1]._pending.length - a[1]._pending.length\n }\n\n // Choose the peer with the least amount of active work (\"keep peers busy\")\n return a[1]._activeTotalSize - b[1]._activeTotalSize\n }\n}\n\n/**\n * Queue of pending tasks for a particular peer, sorted by priority.\n */\nclass PendingTasks {\n constructor () {\n /** @type {SortedMap} */\n this._tasks = new SortedMap([], this._compare)\n }\n\n get length () {\n return this._tasks.size\n }\n\n /**\n * Sum of the size of all pending tasks\n *\n * @type {number}\n **/\n get totalSize () {\n return [...this._tasks.values()].reduce((a, t) => a + t.task.size, 0)\n }\n\n /**\n * @param {string} topic\n * @returns {Task|void}\n */\n get (topic) {\n return (this._tasks.get(topic) || {}).task\n }\n\n /**\n * @param {Task} task\n */\n add (task) {\n this._tasks.set(task.topic, {\n created: Date.now(),\n task\n })\n }\n\n /**\n * @param {string} topic\n * @returns {void}\n */\n delete (topic) {\n this._tasks.delete(topic)\n }\n\n // All pending tasks, in priority order\n tasks () {\n return [...this._tasks.values()].map(i => i.task)\n }\n\n /**\n * Update the priority of the task with the given topic, and update the order\n *\n * @param {string} topic\n * @param {number} priority\n * @returns {void}\n **/\n updatePriority (topic, priority) {\n const obj = this._tasks.get(topic)\n if (!obj) {\n return\n }\n\n const i = this._tasks.indexOf(topic)\n obj.task.priority = priority\n this._tasks.update(i)\n }\n\n /**\n * Sort by priority desc then FIFO\n *\n * @param {[string, PendingTask]} a\n * @param {[string, PendingTask]} b\n * @returns {number}\n * @private\n */\n _compare (a, b) {\n if (a[1].task.priority === b[1].task.priority) {\n // FIFO\n return a[1].created - b[1].created\n }\n // Priority high -> low\n return b[1].task.priority - a[1].task.priority\n }\n}\n", "/**\n * @typedef {import('./types').Task} Task\n * @typedef {import('./types').TaskMerger} TaskMergerAPI\n */\n\n/** @type {TaskMergerAPI} */\nexport const TaskMerger = {\n /**\n * Indicates whether the given task has newer information than the active\n * tasks with the same topic.\n *\n * @param {Task} task\n * @param {Task[]} tasksWithTopic\n * @returns {boolean}\n */\n hasNewInfo (task, tasksWithTopic) {\n let haveBlock = false\n let isWantBlock = false\n for (const existing of tasksWithTopic) {\n if (existing.data.haveBlock) {\n haveBlock = true\n }\n\n if (existing.data.isWantBlock) {\n isWantBlock = true\n }\n }\n\n // If there is no active want-block and the new task is a want-block,\n // the new task is better\n if (!isWantBlock && task.data.isWantBlock) {\n return true\n }\n\n // If we didn't have the block, and the new task indicates that we now\n // do have the block, then we must also have size information for the\n // block, so the new task has new information.\n if (!haveBlock && task.data.haveBlock) {\n return true\n }\n\n return false\n },\n\n /**\n * Merge the information from the given task into the existing task (with the\n * same topic)\n *\n * @param {Task} newTask\n * @param {Task} existingTask\n */\n merge (newTask, existingTask) {\n // The merge function ignores the topic and priority as these don't change.\n //\n // We may receive new information about a want before the want has been\n // popped from the queue in the following scenarios:\n //\n // - Replace want type:\n // 1. Client sends want-have CID1\n // 2. Client sends want-block CID1\n // In this case we should replace want-have with want-block, including\n // updating the task size to be the block size.\n //\n // - Replace DONT_HAVE with want:\n // 1. Client sends want-have CID1 or want-block CID1\n // 2. Local node doesn't have block for CID1\n // 3. Local node receives block for CID1 from peer\n // In this case we should replace DONT_HAVE with the want, including\n // updating the task size and block size.\n const taskData = newTask.data\n const existingData = existingTask.data\n\n // If we didn't have block size information (because we didn't have the\n // block) and we receive the block from a peer, update the task with the\n // new block size\n if (!existingData.haveBlock && taskData.haveBlock) {\n existingData.haveBlock = taskData.haveBlock\n existingData.blockSize = taskData.blockSize\n }\n\n // If replacing a want-have with a want-block\n if (!existingData.isWantBlock && taskData.isWantBlock) {\n // Change the type from want-have to want-block\n existingData.isWantBlock = true\n // If the want-have was a DONT_HAVE, or the want-block has a size\n if (!existingData.haveBlock || taskData.haveBlock) {\n // Update the entry size\n existingData.haveBlock = taskData.haveBlock\n existingTask.size = newTask.size\n }\n }\n\n // If the task is a want-block, make sure the entry size is equal\n // to the block size (because we will send the whole block)\n if (existingData.isWantBlock && existingData.haveBlock) {\n existingTask.size = existingData.blockSize\n }\n }\n}\n", "import { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { BitswapMessage as Message } from '../message/index.js'\nimport { Wantlist } from '../wantlist/index.js'\nimport { Ledger } from './ledger.js'\nimport { RequestQueue } from './req-queue.js'\nimport { TaskMerger } from './task-merger.js'\nimport { logger } from '../utils/index.js'\nimport { trackedMap } from '@libp2p/tracked-map'\n\n/**\n * @typedef {import('../message/entry').BitswapMessageEntry} BitswapMessageEntry\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\nconst WantType = Message.WantType\n\n// The ideal size of the batched payload. We try to pop this much data off the\n// request queue, but\n// - if there isn't any more data in the queue we send whatever we have\n// - if there are several small items in the queue (eg HAVE response) followed\n// by one big item (eg a block) that would exceed this target size, we\n// include the big item in the message\nconst TARGET_MESSAGE_SIZE = 16 * 1024\n\n// If the client sends a want-have, and the engine has the corresponding block,\n// we check the size of the block and if it's small enough we send the block\n// itself, rather than sending a HAVE.\n// This constant defines the maximum size up to which we replace a HAVE with\n// a block.\nconst MAX_SIZE_REPLACE_HAS_WITH_BLOCK = 1024\n\nexport class DecisionEngine {\n /**\n * @param {PeerId} peerId\n * @param {import('interface-blockstore').Blockstore} blockstore\n * @param {import('../network').Network} network\n * @param {import('../stats').Stats} stats\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {object} [opts]\n * @param {number} [opts.targetMessageSize]\n * @param {number} [opts.maxSizeReplaceHasWithBlock]\n */\n constructor (peerId, blockstore, network, stats, libp2p, opts = {}) {\n this._log = logger(peerId, 'engine')\n this.blockstore = blockstore\n this.network = network\n this._stats = stats\n this._opts = this._processOpts(opts)\n\n // A list of of ledgers by their partner id\n /** @type {Map} */\n this.ledgerMap = trackedMap({\n name: 'ipfs_bitswap_ledger_map',\n metrics: libp2p.metrics\n })\n this._running = false\n\n // Queue of want-have / want-block per peer\n this._requestQueue = new RequestQueue(TaskMerger)\n }\n\n /**\n * @template {object} Opts\n * @param {Opts} opts\n * @returns {Opts & {maxSizeReplaceHasWithBlock:number, targetMessageSize:number}}\n * @private\n */\n _processOpts (opts) {\n return {\n maxSizeReplaceHasWithBlock: MAX_SIZE_REPLACE_HAS_WITH_BLOCK,\n targetMessageSize: TARGET_MESSAGE_SIZE,\n ...opts\n }\n }\n\n _scheduleProcessTasks () {\n setTimeout(() => {\n this._processTasks()\n })\n }\n\n /**\n * Pull tasks off the request queue and send a message to the corresponding\n * peer\n */\n async _processTasks () {\n if (!this._running) {\n return\n }\n\n const { peerId, tasks, pendingSize } = this._requestQueue.popTasks(this._opts.targetMessageSize)\n\n if (tasks.length === 0) {\n return\n }\n\n // Create a new message\n const msg = new Message(false)\n\n // Amount of data in the request queue still waiting to be popped\n msg.setPendingBytes(pendingSize)\n\n // Split out want-blocks, want-haves and DONT_HAVEs\n const blockCids = []\n const blockTasks = new Map()\n for (const task of tasks) {\n const cid = CID.parse(task.topic)\n if (task.data.haveBlock) {\n if (task.data.isWantBlock) {\n blockCids.push(cid)\n blockTasks.set(task.topic, task.data)\n } else {\n // Add HAVES to the message\n msg.addHave(cid)\n }\n } else {\n // Add DONT_HAVEs to the message\n msg.addDontHave(cid)\n }\n }\n\n const blocks = await this._getBlocks(blockCids)\n for (const [topic, taskData] of blockTasks) {\n const cid = CID.parse(topic)\n const blk = blocks.get(topic)\n // If the block was found (it has not been removed)\n if (blk) {\n // Add the block to the message\n msg.addBlock(cid, blk)\n } else {\n // The block was not found. If the client requested DONT_HAVE,\n // add DONT_HAVE to the message.\n if (taskData.sendDontHave) {\n msg.addDontHave(cid)\n }\n }\n }\n\n // If there's nothing in the message, bail out\n if (msg.empty) {\n peerId && this._requestQueue.tasksDone(peerId, tasks)\n\n // Trigger the next round of task processing\n this._scheduleProcessTasks()\n\n return\n }\n\n try {\n // Send the message\n peerId && await this.network.sendMessage(peerId, msg)\n\n // Peform sent message accounting\n for (const [cidStr, block] of blocks.entries()) {\n peerId && this.messageSent(peerId, CID.parse(cidStr), block)\n }\n } catch (err) {\n this._log.error(err)\n }\n\n // Free the tasks up from the request queue\n peerId && this._requestQueue.tasksDone(peerId, tasks)\n\n // Trigger the next round of task processing\n this._scheduleProcessTasks()\n }\n\n /**\n * @param {PeerId} peerId\n * @returns {Map}\n */\n wantlistForPeer (peerId) {\n const peerIdStr = peerId.toString()\n const ledger = this.ledgerMap.get(peerIdStr)\n return ledger ? ledger.wantlist.sortedEntries() : new Map()\n }\n\n /**\n * @param {PeerId} peerId\n */\n ledgerForPeer (peerId) {\n const peerIdStr = peerId.toString()\n\n const ledger = this.ledgerMap.get(peerIdStr)\n\n if (!ledger) {\n return null\n }\n\n return {\n peer: ledger.partner,\n value: ledger.debtRatio(),\n sent: ledger.accounting.bytesSent,\n recv: ledger.accounting.bytesRecv,\n exchanged: ledger.exchangeCount\n }\n }\n\n /**\n * @returns {PeerId[]}\n */\n peers () {\n return Array.from(this.ledgerMap.values()).map((l) => l.partner)\n }\n\n /**\n * Receive blocks either from an incoming message from the network, or from\n * blocks being added by the client on the localhost (eg IPFS add)\n *\n * @param {{ cid: CID, data: Uint8Array }[]} blocks\n */\n receivedBlocks (blocks) {\n if (!blocks.length) {\n return\n }\n\n // For each connected peer, check if it wants the block we received\n for (const ledger of this.ledgerMap.values()) {\n for (const block of blocks) {\n // Filter out blocks that we don't want\n const want = ledger.wantlistContains(block.cid)\n\n if (!want) {\n continue\n }\n\n // If the block is small enough, just send the block, even if the\n // client asked for a HAVE\n const blockSize = block.data.length\n const isWantBlock = this._sendAsBlock(want.wantType, blockSize)\n\n let entrySize = blockSize\n if (!isWantBlock) {\n entrySize = Message.blockPresenceSize(want.cid)\n }\n\n this._requestQueue.pushTasks(ledger.partner, [{\n topic: want.cid.toString(base58btc),\n priority: want.priority,\n size: entrySize,\n data: {\n blockSize,\n isWantBlock,\n haveBlock: true,\n sendDontHave: false\n }\n }])\n }\n }\n\n this._scheduleProcessTasks()\n }\n\n /**\n * Handle incoming messages\n *\n * @param {PeerId} peerId\n * @param {Message} msg\n * @returns {Promise}\n */\n async messageReceived (peerId, msg) {\n const ledger = this._findOrCreate(peerId)\n\n if (msg.empty) {\n return\n }\n\n // If the message has a full wantlist, clear the current wantlist\n if (msg.full) {\n ledger.wantlist = new Wantlist()\n }\n\n // Record the amount of block data received\n this._updateBlockAccounting(msg.blocks, ledger)\n\n if (msg.wantlist.size === 0) {\n this._scheduleProcessTasks()\n return\n }\n\n // Clear cancelled wants and add new wants to the ledger\n /** @type {CID[]} */\n const cancels = []\n /** @type {BitswapMessageEntry[]} */\n const wants = []\n msg.wantlist.forEach((entry) => {\n if (entry.cancel) {\n ledger.cancelWant(entry.cid)\n cancels.push(entry.cid)\n } else {\n ledger.wants(entry.cid, entry.priority, entry.wantType)\n wants.push(entry)\n }\n })\n\n this._cancelWants(peerId, cancels)\n await this._addWants(peerId, wants)\n\n this._scheduleProcessTasks()\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @param {CID[]} cids\n * @returns {void}\n */\n _cancelWants (peerId, cids) {\n for (const c of cids) {\n this._requestQueue.remove(c.toString(base58btc), peerId)\n }\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @param {BitswapMessageEntry[]} wants\n * @returns {Promise}\n */\n async _addWants (peerId, wants) {\n // Get the size of each wanted block\n const blockSizes = await this._getBlockSizes(wants.map(w => w.cid))\n\n const tasks = []\n for (const want of wants) {\n const id = want.cid.toString(base58btc)\n const blockSize = blockSizes.get(id)\n\n // If the block was not found\n if (blockSize == null) {\n // Only add the task to the queue if the requester wants a DONT_HAVE\n if (want.sendDontHave) {\n tasks.push({\n topic: id,\n priority: want.priority,\n size: Message.blockPresenceSize(want.cid),\n data: {\n isWantBlock: want.wantType === WantType.Block,\n blockSize: 0,\n haveBlock: false,\n sendDontHave: want.sendDontHave\n }\n })\n }\n } else {\n // The block was found, add it to the queue\n\n // If the block is small enough, just send the block, even if the\n // client asked for a HAVE\n const isWantBlock = this._sendAsBlock(want.wantType, blockSize)\n\n // entrySize is the amount of space the entry takes up in the\n // message we send to the recipient. If we're sending a block, the\n // entrySize is the size of the block. Otherwise it's the size of\n // a block presence entry.\n let entrySize = blockSize\n if (!isWantBlock) {\n entrySize = Message.blockPresenceSize(want.cid)\n }\n\n tasks.push({\n topic: id,\n priority: want.priority,\n size: entrySize,\n data: {\n isWantBlock,\n blockSize,\n haveBlock: true,\n sendDontHave: want.sendDontHave\n }\n })\n }\n\n this._requestQueue.pushTasks(peerId, tasks)\n }\n }\n\n /**\n * @private\n * @param {import('../message/message').Message.Wantlist.WantType} wantType\n * @param {number} blockSize\n */\n _sendAsBlock (wantType, blockSize) {\n return wantType === WantType.Block ||\n blockSize <= this._opts.maxSizeReplaceHasWithBlock\n }\n\n /**\n * @private\n * @param {CID[]} cids\n * @returns {Promise>}\n */\n async _getBlockSizes (cids) {\n const blocks = await this._getBlocks(cids)\n return new Map([...blocks].map(([k, v]) => [k, v.length]))\n }\n\n /**\n * @private\n * @param {CID[]} cids\n * @returns {Promise>}\n */\n async _getBlocks (cids) {\n const res = new Map()\n await Promise.all(cids.map(async (cid) => {\n try {\n const block = await this.blockstore.get(cid)\n res.set(cid.toString(base58btc), block)\n } catch (/** @type {any} */ e) {\n if (e.code !== 'ERR_NOT_FOUND') {\n this._log.error('failed to query blockstore for %s: %s', cid, e)\n }\n }\n }))\n return res\n }\n\n /**\n * @private\n * @param {Map} blocksMap\n * @param {Ledger} ledger\n */\n _updateBlockAccounting (blocksMap, ledger) {\n for (const block of blocksMap.values()) {\n this._log('got block (%s bytes)', block.length)\n ledger.receivedBytes(block.length)\n }\n }\n\n /**\n * Clear up all accounting things after message was sent\n *\n * @param {PeerId} peerId\n * @param {CID} cid\n * @param {Uint8Array} block\n */\n messageSent (peerId, cid, block) {\n const ledger = this._findOrCreate(peerId)\n ledger.sentBytes(block.length)\n ledger.wantlist.remove(cid)\n }\n\n /**\n * @param {PeerId} peerId\n * @returns {number}\n */\n numBytesSentTo (peerId) {\n return this._findOrCreate(peerId).accounting.bytesSent\n }\n\n /**\n * @param {PeerId} peerId\n * @returns {number}\n */\n\n numBytesReceivedFrom (peerId) {\n return this._findOrCreate(peerId).accounting.bytesRecv\n }\n\n /**\n *\n * @param {PeerId} peerId\n */\n peerDisconnected (peerId) {\n this.ledgerMap.delete(peerId.toString())\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @returns {Ledger}\n */\n _findOrCreate (peerId) {\n const peerIdStr = peerId.toString()\n const ledger = this.ledgerMap.get(peerIdStr)\n if (ledger) {\n return ledger\n }\n\n const l = new Ledger(peerId)\n\n this.ledgerMap.set(peerIdStr, l)\n if (this._stats) {\n this._stats.push(peerIdStr, 'peerCount', 1)\n }\n\n return l\n }\n\n start () {\n this._running = true\n }\n\n stop () {\n this._running = false\n }\n}\n", "import { EventEmitter } from 'events'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as CONSTANTS from './constants.js'\nimport { logger } from './utils/index.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\n/**\n * @param {CID} cid\n */\nconst unwantEvent = (cid) => `unwant:${uint8ArrayToString(cid.multihash.bytes, 'base64')}`\n\n/**\n * @param {CID} cid\n */\nconst blockEvent = (cid) => `block:${uint8ArrayToString(cid.multihash.bytes, 'base64')}`\n\nexport class Notifications extends EventEmitter {\n /**\n * Internal module used to track events about incoming blocks,\n * wants and unwants.\n *\n * @param {PeerId} peerId\n */\n constructor (peerId) {\n super()\n\n this.setMaxListeners(CONSTANTS.maxListeners)\n\n this._log = logger(peerId, 'notif')\n }\n\n /**\n * Signal the system that we received `block`.\n *\n * @param {CID} cid\n * @param {Uint8Array} block\n * @returns {void}\n */\n hasBlock (cid, block) {\n const event = blockEvent(cid)\n this._log(event)\n this.emit(event, block)\n }\n\n /**\n * Signal the system that we are waiting to receive the\n * block associated with the given `cid`.\n * Returns a Promise that resolves to the block when it is received,\n * or undefined when the block is unwanted.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n * @returns {Promise}\n */\n wantBlock (cid, options = {}) {\n if (!cid) {\n throw new Error('Not a valid cid')\n }\n\n const blockEvt = blockEvent(cid)\n const unwantEvt = unwantEvent(cid)\n\n this._log(`wantBlock:${cid}`)\n\n return new Promise((resolve, reject) => {\n const onUnwant = () => {\n this.removeListener(blockEvt, onBlock)\n\n reject(new Error(`Block for ${cid} unwanted`))\n }\n\n /**\n * @param {Uint8Array} data\n */\n const onBlock = (data) => {\n this.removeListener(unwantEvt, onUnwant)\n\n resolve(data)\n }\n\n this.once(unwantEvt, onUnwant)\n this.once(blockEvt, onBlock)\n\n if (options && options.signal) {\n options.signal.addEventListener('abort', () => {\n this.removeListener(blockEvt, onBlock)\n this.removeListener(unwantEvt, onUnwant)\n\n reject(new Error(`Want for ${cid} aborted`))\n })\n }\n })\n }\n\n /**\n * Signal that the block is not wanted anymore.\n *\n * @param {CID} cid - the CID of the block that is not wanted anymore.\n * @returns {void}\n */\n unwantBlock (cid) {\n const event = unwantEvent(cid)\n this._log(event)\n this.emit(event)\n }\n}\n", "import { EventEmitter } from 'events'\nimport { Stat } from './stat.js'\nimport { trackedMap } from '@libp2p/tracked-map'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\n/**\n * @typedef {[number, number, number]} AverageIntervals\n */\nconst defaultOptions = {\n enabled: false,\n computeThrottleTimeout: 1000,\n computeThrottleMaxQueueSize: 1000,\n movingAverageIntervals: /** @type {AverageIntervals} */ ([\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ])\n}\n\nexport class Stats extends EventEmitter {\n /**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {string[]} [initialCounters]\n * @param {object} _options\n * @param {boolean} _options.enabled\n * @param {number} _options.computeThrottleTimeout\n * @param {number} _options.computeThrottleMaxQueueSize\n */\n constructor (libp2p, initialCounters = [], _options = defaultOptions) {\n super()\n\n const options = Object.assign({}, defaultOptions, _options)\n\n if (typeof options.computeThrottleTimeout !== 'number') {\n throw new Error('need computeThrottleTimeout')\n }\n\n if (typeof options.computeThrottleMaxQueueSize !== 'number') {\n throw new Error('need computeThrottleMaxQueueSize')\n }\n\n this._initialCounters = initialCounters\n this._options = options\n this._enabled = this._options.enabled\n\n this._global = new Stat(initialCounters, options)\n this._global.on('update', (stats) => this.emit('update', stats))\n\n /** @type {Map} */\n this._peers = trackedMap({\n name: 'ipfs_bitswap_stats_peers',\n metrics: libp2p.metrics\n })\n }\n\n enable () {\n this._enabled = true\n this._options.enabled = true\n this._global.enable()\n }\n\n disable () {\n this._enabled = false\n this._options.enabled = false\n this._global.disable()\n }\n\n stop () {\n this._enabled = false\n this._global.stop()\n for (const peerStat of this._peers) {\n peerStat[1].stop()\n }\n }\n\n get snapshot () {\n return this._global.snapshot\n }\n\n get movingAverages () {\n return this._global.movingAverages\n }\n\n /**\n * @param {PeerId|string} peerId\n * @returns {Stat|undefined}\n */\n forPeer (peerId) {\n const peerIdStr = (typeof peerId !== 'string' && peerId.toString)\n ? peerId.toString()\n : `${peerId}`\n\n return this._peers.get(peerIdStr)\n }\n\n /**\n *\n * @param {string|null} peer\n * @param {string} counter\n * @param {number} inc\n */\n push (peer, counter, inc) {\n if (this._enabled) {\n this._global.push(counter, inc)\n\n if (peer) {\n let peerStats = this._peers.get(peer)\n if (!peerStats) {\n peerStats = new Stat(this._initialCounters, this._options)\n this._peers.set(peer, peerStats)\n }\n\n peerStats.push(counter, inc)\n }\n }\n }\n\n /**\n * @param {PeerId} peer\n */\n disconnected (peer) {\n const peerId = peer.toString()\n const peerStats = this._peers.get(peerId)\n if (peerStats) {\n peerStats.stop()\n this._peers.delete(peerId)\n }\n }\n}\n", "import { EventEmitter } from 'events'\nimport MovingAverage from '@vascosantos/moving-average'\n\n/**\n * @typedef {import('@vascosantos/moving-average').IMovingAverage} IMovingAverage\n * @typedef {[string, number, number]} Op\n */\n\nexport class Stat extends EventEmitter {\n /**\n *\n * @param {string[]} initialCounters\n * @param {object} options\n * @param {boolean} options.enabled\n * @param {number} options.computeThrottleTimeout\n * @param {number} options.computeThrottleMaxQueueSize\n * @param {import('.').AverageIntervals} options.movingAverageIntervals\n */\n constructor (initialCounters, options) {\n super()\n\n this._options = options\n /** @type {Op[]} */\n this._queue = []\n /** @type {Record} */\n this._stats = {}\n\n this._frequencyLastTime = Date.now()\n /** @type {Record} */\n this._frequencyAccumulators = {}\n\n /** @type {Record>} */\n this._movingAverages = {}\n\n this._update = this._update.bind(this)\n\n initialCounters.forEach((key) => {\n this._stats[key] = BigInt(0)\n this._movingAverages[key] = {}\n this._options.movingAverageIntervals.forEach((interval) => {\n const ma = this._movingAverages[key][interval] = MovingAverage(interval)\n ma.push(this._frequencyLastTime, 0)\n })\n })\n\n this._enabled = this._options.enabled\n }\n\n enable () {\n this._enabled = true\n }\n\n disable () {\n this._disabled = true\n }\n\n stop () {\n if (this._timeout) {\n clearTimeout(this._timeout)\n }\n }\n\n get snapshot () {\n return Object.assign({}, this._stats)\n }\n\n get movingAverages () {\n return Object.assign({}, this._movingAverages)\n }\n\n /**\n * @param {string} counter\n * @param {number} inc\n */\n push (counter, inc) {\n if (this._enabled) {\n this._queue.push([counter, inc, Date.now()])\n this._resetComputeTimeout()\n }\n }\n\n /**\n * @private\n */\n _resetComputeTimeout () {\n if (this._timeout) {\n clearTimeout(this._timeout)\n }\n this._timeout = setTimeout(this._update, this._nextTimeout())\n }\n\n /**\n * @private\n * @returns {number}\n */\n _nextTimeout () {\n // calculate the need for an update, depending on the queue length\n const urgency = this._queue.length / this._options.computeThrottleMaxQueueSize\n return Math.max(this._options.computeThrottleTimeout * (1 - urgency), 0)\n }\n\n /**\n * @private\n */\n _update () {\n this._timeout = null\n\n if (this._queue.length) {\n let last\n while (this._queue.length) {\n const op = last = this._queue.shift()\n op && this._applyOp(op)\n }\n\n last && this._updateFrequency(last[2]) // contains timestamp of last op\n\n this.emit('update', this._stats)\n }\n }\n\n /**\n * @private\n * @param {number} latestTime\n */\n _updateFrequency (latestTime) {\n const timeDiff = latestTime - this._frequencyLastTime\n\n if (timeDiff) {\n Object.keys(this._stats).forEach((key) => {\n this._updateFrequencyFor(key, timeDiff, latestTime)\n })\n }\n\n this._frequencyLastTime = latestTime\n }\n\n /**\n * @private\n * @param {string} key\n * @param {number} timeDiffMS\n * @param {number} latestTime\n * @returns {void}\n */\n _updateFrequencyFor (key, timeDiffMS, latestTime) {\n const count = this._frequencyAccumulators[key] || 0\n this._frequencyAccumulators[key] = 0\n const hz = (count / timeDiffMS) * 1000\n\n let movingAverages = this._movingAverages[key]\n if (!movingAverages) {\n movingAverages = this._movingAverages[key] = {}\n }\n this._options.movingAverageIntervals.forEach((movingAverageInterval) => {\n let movingAverage = movingAverages[movingAverageInterval]\n if (!movingAverage) {\n movingAverage = movingAverages[movingAverageInterval] = MovingAverage(movingAverageInterval)\n }\n movingAverage.push(latestTime, hz)\n })\n }\n\n /**\n * @private\n * @param {Op} op\n */\n _applyOp (op) {\n const key = op[0]\n const inc = op[1]\n\n if (typeof inc !== 'number') {\n throw new Error(`invalid increment number: ${inc}`)\n }\n\n if (!Object.prototype.hasOwnProperty.call(this._stats, key)) {\n this._stats[key] = BigInt(0)\n }\n\n this._stats[key] = BigInt(this._stats[key]) + BigInt(inc)\n\n if (!this._frequencyAccumulators[key]) {\n this._frequencyAccumulators[key] = 0\n }\n this._frequencyAccumulators[key] += inc\n }\n}\n", "import { WantManager } from './want-manager/index.js'\nimport { Network } from './network.js'\nimport { DecisionEngine } from './decision-engine/index.js'\nimport { Notifications } from './notifications.js'\nimport { logger } from './utils/index.js'\nimport { Stats } from './stats/index.js'\nimport { anySignal } from 'any-signal'\nimport { BaseBlockstore } from 'blockstore-core/base'\nimport { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./types').IPFSBitswap} IPFSBitswap\n * @typedef {import('./types').MultihashHasherLoader} MultihashHasherLoader\n * @typedef {import('./message').BitswapMessage} BitswapMessage\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Options} Options\n */\n\nconst defaultOptions = {\n statsEnabled: false,\n statsComputeThrottleTimeout: 1000,\n statsComputeThrottleMaxQueueSize: 1000\n}\nconst statsKeys = [\n 'blocksReceived',\n 'dataReceived',\n 'dupBlksReceived',\n 'dupDataReceived',\n 'blocksSent',\n 'dataSent',\n 'providesBufferLength',\n 'wantListLength',\n 'peerCount'\n]\n\n/**\n * JavaScript implementation of the Bitswap 'data exchange' protocol\n * used by IPFS.\n *\n * @implements {IPFSBitswap}\n */\nexport class Bitswap extends BaseBlockstore {\n /**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {Blockstore} blockstore\n * @param {object} [options]\n * @param {boolean} [options.statsEnabled=false]\n * @param {number} [options.statsComputeThrottleTimeout=1000]\n * @param {number} [options.statsComputeThrottleMaxQueueSize=1000]\n * @param {number} [options.maxInboundStreams=32]\n * @param {number} [options.maxOutboundStreams=32]\n * @param {number} [options.incomingStreamTimeout=30000]\n * @param {MultihashHasherLoader} [options.hashLoader]\n */\n constructor (libp2p, blockstore, options = {}) {\n super()\n\n this._libp2p = libp2p\n this._log = logger(this.peerId)\n\n this._options = Object.assign({}, defaultOptions, options)\n\n // stats\n this._stats = new Stats(libp2p, statsKeys, {\n enabled: this._options.statsEnabled,\n computeThrottleTimeout: this._options.statsComputeThrottleTimeout,\n computeThrottleMaxQueueSize: this._options.statsComputeThrottleMaxQueueSize\n })\n\n // the network delivers messages\n this.network = new Network(libp2p, this, this._stats, {\n hashLoader: options.hashLoader,\n maxInboundStreams: options.maxInboundStreams,\n maxOutboundStreams: options.maxOutboundStreams,\n incomingStreamTimeout: options.incomingStreamTimeout\n })\n\n // local database\n this.blockstore = blockstore\n\n this.engine = new DecisionEngine(this.peerId, blockstore, this.network, this._stats, libp2p)\n\n // handle message sending\n this.wm = new WantManager(this.peerId, this.network, this._stats, libp2p)\n\n this.notifications = new Notifications(this.peerId)\n\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * @type {PeerId}\n */\n get peerId () {\n return this._libp2p.peerId\n }\n\n /**\n * handle messages received through the network\n *\n * @param {PeerId} peerId\n * @param {BitswapMessage} incoming\n */\n async _receiveMessage (peerId, incoming) {\n try {\n // Note: this allows the engine to respond to any wants in the message.\n // Processing of the blocks in the message happens below, after the\n // blocks have been added to the blockstore.\n await this.engine.messageReceived(peerId, incoming)\n } catch (err) {\n // Log instead of throwing an error so as to process as much as\n // possible of the message. Currently `messageReceived` does not\n // throw any errors, but this could change in the future.\n this._log('failed to receive message', incoming)\n }\n\n if (incoming.blocks.size === 0) {\n return\n }\n\n /** @type { { cid: CID, wasWanted: boolean, data: Uint8Array }[] } */\n const received = []\n\n for (const [cidStr, data] of incoming.blocks.entries()) {\n const cid = CID.parse(cidStr)\n\n received.push({\n wasWanted: this.wm.wantlist.contains(cid),\n cid,\n data\n })\n }\n\n // quickly send out cancels, reduces chances of duplicate block receives\n this.wm.cancelWants(\n received\n .filter(({ wasWanted }) => wasWanted)\n .map(({ cid }) => cid)\n )\n\n await Promise.all(\n received.map(\n ({ cid, wasWanted, data }) => this._handleReceivedBlock(peerId, cid, data, wasWanted)\n )\n )\n }\n\n /**\n * @private\n * @param {PeerId} peerId\n * @param {CID} cid\n * @param {Uint8Array} data\n * @param {boolean} wasWanted\n */\n async _handleReceivedBlock (peerId, cid, data, wasWanted) {\n this._log('received block')\n\n const has = await this.blockstore.has(cid)\n\n this._updateReceiveCounters(peerId.toString(), cid, data, has)\n\n if (!wasWanted) {\n return\n }\n\n await this.put(cid, data)\n }\n\n /**\n * @private\n * @param {string} peerIdStr\n * @param {CID} cid\n * @param {Uint8Array} data\n * @param {boolean} exists\n */\n _updateReceiveCounters (peerIdStr, cid, data, exists) {\n this._stats.push(peerIdStr, 'blocksReceived', 1)\n this._stats.push(peerIdStr, 'dataReceived', data.length)\n\n if (exists) {\n this._stats.push(peerIdStr, 'dupBlksReceived', 1)\n this._stats.push(peerIdStr, 'dupDataReceived', data.length)\n }\n }\n\n /**\n * handle errors on the receiving channel\n *\n * @param {Error} err\n */\n _receiveError (err) {\n this._log.error('ReceiveError: %s', err.message)\n }\n\n /**\n * handle new peers\n *\n * @param {PeerId} peerId\n */\n _onPeerConnected (peerId) {\n this.wm.connected(peerId)\n }\n\n /**\n * handle peers being disconnected\n *\n * @param {PeerId} peerId\n */\n _onPeerDisconnected (peerId) {\n this.wm.disconnected(peerId)\n this.engine.peerDisconnected(peerId)\n this._stats.disconnected(peerId)\n }\n\n enableStats () {\n this._stats.enable()\n }\n\n disableStats () {\n this._stats.disable()\n }\n\n /**\n * Return the current wantlist for a given `peerId`\n *\n * @param {PeerId} peerId\n * @param {any} [_options]\n */\n wantlistForPeer (peerId, _options) {\n return this.engine.wantlistForPeer(peerId)\n }\n\n /**\n * Return ledger information for a given `peerId`\n *\n * @param {PeerId} peerId\n */\n ledgerForPeer (peerId) {\n return this.engine.ledgerForPeer(peerId)\n }\n\n /**\n * Fetch a given block by cid. If the block is in the local\n * blockstore it is returned, otherwise the block is added to the wantlist and returned once another node sends it to us.\n *\n * @param {CID} cid\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async get (cid, options = {}) {\n /**\n * @param {CID} cid\n * @param {object} options\n * @param {AbortSignal} options.signal\n */\n const fetchFromNetwork = (cid, options) => {\n // add it to the want list - n.b. later we will abort the AbortSignal\n // so no need to remove the blocks from the wantlist after we have it\n this.wm.wantBlocks([cid], options)\n\n return this.notifications.wantBlock(cid, options)\n }\n\n let promptedNetwork = false\n\n /**\n *\n * @param {CID} cid\n * @param {object} options\n * @param {AbortSignal} options.signal\n */\n const loadOrFetchFromNetwork = async (cid, options) => {\n try {\n // have to await here as we want to handle ERR_NOT_FOUND\n const block = await this.blockstore.get(cid, options)\n\n return block\n } catch (/** @type {any} */ err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err\n }\n\n if (!promptedNetwork) {\n promptedNetwork = true\n\n this.network.findAndConnect(cid, options)\n .catch((err) => this._log.error(err))\n }\n\n // we don't have the block locally so fetch it from the network\n return fetchFromNetwork(cid, options)\n }\n }\n\n // depending on implementation it's possible for blocks to come in while\n // we do the async operations to get them from the blockstore leading to\n // a race condition, so register for incoming block notifications as well\n // as trying to get it from the datastore\n const controller = new AbortController()\n const signal = options.signal\n ? anySignal([options.signal, controller.signal])\n : controller.signal\n\n try {\n const block = await Promise.race([\n this.notifications.wantBlock(cid, {\n signal\n }),\n loadOrFetchFromNetwork(cid, {\n signal\n })\n ])\n\n return block\n } finally {\n // since we have the block we can now remove our listener\n controller.abort()\n }\n }\n\n /**\n * Fetch a a list of blocks by cid. If the blocks are in the local\n * blockstore they are returned, otherwise the blocks are added to the wantlist and returned once another node sends them to us.\n *\n * @param {AsyncIterable|Iterable} cids\n * @param {object} [options]\n * @param {AbortSignal} [options.signal]\n */\n async * getMany (cids, options = {}) {\n for await (const cid of cids) {\n yield this.get(cid, options)\n }\n }\n\n /**\n * Removes the given CIDs from the wantlist independent of any ref counts.\n *\n * This will cause all outstanding promises for a given block to reject.\n *\n * If you want to cancel the want for a block without doing that, pass an\n * AbortSignal in to `.get` or `.getMany` and abort it.\n *\n * @param {CID[]|CID} cids\n */\n unwant (cids) {\n const cidsArray = Array.isArray(cids) ? cids : [cids]\n\n this.wm.unwantBlocks(cidsArray)\n cidsArray.forEach((cid) => this.notifications.unwantBlock(cid))\n }\n\n /**\n * Removes the given keys from the want list. This may cause pending promises\n * for blocks to never resolve. If you wish these promises to abort instead\n * call `unwant(cids)` instead.\n *\n * @param {CID[]|CID} cids\n */\n cancelWants (cids) {\n this.wm.cancelWants(Array.isArray(cids) ? cids : [cids])\n }\n\n /**\n * Put the given block to the underlying blockstore and\n * send it to nodes that have it in their wantlist.\n *\n * @param {CID} cid\n * @param {Uint8Array} block\n * @param {any} [_options]\n */\n async put (cid, block, _options) {\n await this.blockstore.put(cid, block)\n this._sendHaveBlockNotifications(cid, block)\n }\n\n /**\n * Put the given blocks to the underlying blockstore and\n * send it to nodes that have it them their wantlist.\n *\n * @param {Iterable | AsyncIterable} source\n * @param {Options} [options]\n */\n async * putMany (source, options) {\n for await (const { key, value } of this.blockstore.putMany(source, options)) {\n this._sendHaveBlockNotifications(key, value)\n\n yield { key, value }\n }\n }\n\n /**\n * Sends notifications about the arrival of a block\n *\n * @private\n * @param {CID} cid\n * @param {Uint8Array} data\n */\n _sendHaveBlockNotifications (cid, data) {\n this.notifications.hasBlock(cid, data)\n this.engine.receivedBlocks([{ cid, data }])\n // Note: Don't wait for provide to finish before returning\n this.network.provide(cid).catch((err) => {\n this._log.error('Failed to provide: %s', err.message)\n })\n }\n\n /**\n * Get the current list of wants\n */\n getWantlist () {\n return this.wm.wantlist.entries()\n }\n\n /**\n * Get the current list of partners\n */\n peers () {\n return this.engine.peers()\n }\n\n /**\n * Get stats about the bitswap node\n */\n stat () {\n return this._stats\n }\n\n /**\n * Start the bitswap node\n */\n async start () {\n this.wm.start()\n await this.network.start()\n this.engine.start()\n this.started = true\n }\n\n /**\n * Stop the bitswap node\n */\n async stop () {\n this._stats.stop()\n this.wm.stop()\n await this.network.stop()\n this.engine.stop()\n this.started = false\n }\n\n unwrap () {\n return this.blockstore\n }\n\n /**\n * @param {CID} cid\n * @returns {Promise}\n */\n has (cid) {\n return this.blockstore.has(cid)\n }\n}\n", "import { Bitswap } from './bitswap.js'\n\n/**\n * @typedef {import('./types').IPFSBitswap} IPFSBitswap\n * @typedef {import('./types').MultihashHasherLoader} MultihashHasherLoader\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('./message')} BitswapMessage\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Pair} Pair\n * @typedef {import('interface-blockstore').Options} Options\n */\n\n/**\n * @param {import('@libp2p/interface-libp2p').Libp2p} libp2p\n * @param {Blockstore} blockstore\n * @param {object} [options]\n * @param {boolean} [options.statsEnabled=false]\n * @param {number} [options.statsComputeThrottleTimeout=1000]\n * @param {number} [options.statsComputeThrottleMaxQueueSize=1000]\n * @param {number} [options.maxInboundStreams=32]\n * @param {number} [options.maxOutboundStreams=128]\n * @param {number} [options.incomingStreamTimeout=30000]\n * @param {MultihashHasherLoader} [options.hashLoader]\n * @returns {IPFSBitswap}\n */\nexport const createBitswap = (libp2p, blockstore, options = {}) => {\n return new Bitswap(libp2p, blockstore, options)\n}\n", "import { createBitswap } from 'ipfs-bitswap'\nimport { createLibp2p } from './libp2p.js'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { BlockStorage } from '../block-storage.js'\n\n/**\n * @typedef {object} Online\n * @property {libp2p} libp2p\n * @property {Bitswap} bitswap\n *\n * @typedef {object} Options\n * @property {PeerId} options.peerId\n * @property {Repo} options.repo\n * @property {Print} options.print\n * @property {IPFSOptions} options.options\n * @property {import('ipfs-core-utils/multihashes').Multihashes} options.hashers\n *\n * @typedef {import('ipfs-core-types/src/config').Config} IPFSConfig\n * @typedef {import('../types').Options} IPFSOptions\n * @typedef {import('ipfs-repo').IPFSRepo} Repo\n * @typedef {import('../types').Print} Print\n * @typedef {import('libp2p').Libp2p} libp2p\n * @typedef {import('ipfs-bitswap').IPFSBitswap} Bitswap\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('@multiformats/multiaddr').Multiaddr} Multiaddr\n */\n\nexport class Network {\n /**\n * @param {PeerId} peerId\n * @param {libp2p} libp2p\n * @param {Bitswap} bitswap\n * @param {Repo} repo\n * @param {BlockStorage} blockstore\n */\n constructor (peerId, libp2p, bitswap, repo, blockstore) {\n this.peerId = peerId\n this.libp2p = libp2p\n this.bitswap = bitswap\n this.repo = repo\n this.blockstore = blockstore\n }\n\n /**\n * @param {Options} options\n */\n static async start ({ peerId, repo, print, hashers, options }) {\n // Need to ensure that repo is open as it could have been closed between\n // `init` and `start`.\n if (repo.closed) {\n await repo.open()\n }\n\n /** @type {IPFSConfig} */\n const config = await repo.config.getAll()\n\n const libp2p = await createLibp2p({\n options,\n repo,\n peerId,\n multiaddrs: readAddrs(peerId, config),\n config,\n keychainConfig: undefined\n })\n\n await libp2p.start()\n\n for (const ma of libp2p.getMultiaddrs()) {\n print(`Swarm listening on ${ma.toString()}`)\n }\n\n const bitswap = createBitswap(libp2p, repo.blocks, {\n statsEnabled: true,\n hashLoader: hashers,\n maxInboundStreams: 1024,\n maxOutboundStreams: 1024\n })\n await bitswap.start()\n\n const blockstore = new BlockStorage(repo.blocks, bitswap)\n repo.blocks = blockstore\n // @ts-expect-error private field\n repo.pins.blockstore = blockstore\n\n return new Network(peerId, libp2p, bitswap, repo, blockstore)\n }\n\n /**\n * @param {Network} network\n */\n static async stop (network) {\n network.repo.blocks = network.blockstore.unwrap()\n // @ts-expect-error private field\n network.repo.pins.blockstore = network.blockstore.unwrap()\n\n await network.bitswap.stop()\n await network.libp2p.stop()\n }\n}\n\n/**\n * @param {PeerId} peerId\n * @param {IPFSConfig} config\n */\nconst readAddrs = (peerId, config) => {\n const peerIdStr = peerId.toString()\n /** @type {Multiaddr[]} */\n const addrs = []\n const swarm = (config.Addresses && config.Addresses.Swarm) || []\n for (const addr of swarm) {\n let ma = multiaddr(addr)\n\n // Temporary error for users migrating using websocket-star multiaddrs for listenning on libp2p\n // websocket-star support was removed from ipfs and libp2p\n if (ma.protoCodes().includes(WEBSOCKET_STAR_PROTO_CODE)) {\n throw errCode(new Error('websocket-star swarm addresses are not supported. See https://github.com/ipfs/js-ipfs/issues/2779'), 'ERR_WEBSOCKET_STAR_SWARM_ADDR_NOT_SUPPORTED')\n }\n\n // multiaddrs that go via a signalling server or other intermediary (e.g. stardust,\n // webrtc-star) can have the intermediary's peer ID in the address, so append our\n // peer ID to the end of it\n const maId = ma.getPeerId()\n if (maId && maId !== peerIdStr) {\n ma = ma.encapsulate(`/p2p/${peerIdStr}`)\n }\n\n addrs.push(ma)\n }\n\n return addrs\n}\n\nconst WEBSOCKET_STAR_PROTO_CODE = 479\n", "import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n", "import * as ErrorsImport from './errors.js'\n\nexport { BaseBlockstore } from './base.js'\nexport { MemoryBlockstore } from './memory.js'\n\nexport const Errors = {\n ...ErrorsImport\n}\n", "import { BaseBlockstore } from 'blockstore-core'\nimport merge from 'it-merge'\nimport { pushable } from 'it-pushable'\nimport filter from 'it-filter'\n\n/**\n * @typedef {import('interface-blockstore').Blockstore} Blockstore\n * @typedef {import('interface-blockstore').Query} Query\n * @typedef {import('interface-blockstore').KeyQuery} KeyQuery\n * @typedef {import('multiformats/cid').CID} CID\n * @typedef {import('ipfs-bitswap').IPFSBitswap} Bitswap\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n * @typedef {import('ipfs-core-types/src/block').RmOptions} RmOptions\n */\n\n/**\n * BlockStorage is a hybrid block datastore. It stores data in a local\n * datastore and may retrieve data from a remote Exchange.\n * It uses an internal `datastore.Datastore` instance to store values.\n *\n * @implements {Blockstore}\n */\nexport class BlockStorage extends BaseBlockstore {\n /**\n * Create a new BlockStorage\n *\n * @param {Blockstore} blockstore\n * @param {Bitswap} bitswap\n */\n constructor (blockstore, bitswap) {\n super()\n\n this.child = blockstore\n this.bitswap = bitswap\n }\n\n open () {\n return this.child.open()\n }\n\n close () {\n return this.child.close()\n }\n\n unwrap () {\n return this.child\n }\n\n /**\n * Put a block to the underlying datastore\n *\n * @param {CID} cid\n * @param {Uint8Array} block\n * @param {AbortOptions} [options]\n */\n async put (cid, block, options = {}) {\n if (await this.has(cid)) {\n return\n }\n\n if (this.bitswap.isStarted()) {\n await this.bitswap.put(cid, block, options)\n } else {\n await this.child.put(cid, block, options)\n }\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n *\n * @param {AsyncIterable<{ key: CID, value: Uint8Array }> | Iterable<{ key: CID, value: Uint8Array }>} blocks\n * @param {AbortOptions} [options]\n */\n async * putMany (blocks, options = {}) {\n const missingBlocks = filter(blocks, async ({ key }) => { return !(await this.has(key)) })\n\n if (this.bitswap.isStarted()) {\n yield * this.bitswap.putMany(missingBlocks, options)\n } else {\n yield * this.child.putMany(missingBlocks, options)\n }\n }\n\n /**\n * Get a block by cid\n *\n * @param {CID} cid\n * @param {AbortOptions} [options]\n */\n async get (cid, options = {}) {\n if (!(await this.has(cid)) && this.bitswap.isStarted()) {\n return this.bitswap.get(cid, options)\n } else {\n return this.child.get(cid, options)\n }\n }\n\n /**\n * Get multiple blocks back from an array of cids\n *\n * @param {AsyncIterable | Iterable} cids\n * @param {AbortOptions} [options]\n */\n async * getMany (cids, options = {}) {\n const getFromBitswap = pushable({ objectMode: true })\n const getFromChild = pushable({ objectMode: true })\n\n Promise.resolve().then(async () => {\n for await (const cid of cids) {\n if (!(await this.has(cid)) && this.bitswap.isStarted()) {\n getFromBitswap.push(cid)\n } else {\n getFromChild.push(cid)\n }\n }\n\n getFromBitswap.end()\n getFromChild.end()\n })\n\n yield * merge(\n this.bitswap.getMany(getFromBitswap, options),\n this.child.getMany(getFromChild, options)\n )\n }\n\n /**\n * Delete a block from the blockstore\n *\n * @param {CID} cid\n * @param {RmOptions} [options]\n */\n async delete (cid, options) {\n await this.child.delete(cid, options)\n }\n\n /**\n * Delete multiple blocks from the blockstore\n *\n * @param {AsyncIterable | Iterable} cids\n * @param {RmOptions} [options]\n */\n async * deleteMany (cids, options) {\n yield * this.child.deleteMany(cids, options)\n }\n\n /**\n * @param {CID} cid\n * @param {AbortOptions} options\n */\n async has (cid, options = {}) {\n return this.child.has(cid, options)\n }\n\n /**\n * @param {Query} q\n * @param {AbortOptions} options\n */\n async * query (q, options = {}) {\n yield * this.child.query(q, options)\n }\n\n /**\n * @param {KeyQuery} q\n * @param {AbortOptions} options\n */\n async * queryKeys (q, options = {}) {\n yield * this.child.queryKeys(q, options)\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('ipfs-core-types/src/swarm').AddrsResult} AddrsResult\n */\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createAddrs ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"addrs\"]}\n */\n async function addrs (options = {}) { // eslint-disable-line require-await\n /** @type {AddrsResult[]} */\n const peers = []\n const { libp2p } = await network.use(options)\n\n await libp2p.peerStore.forEach(peer => {\n peers.push({\n id: peer.id,\n addrs: peer.addresses.map((mi) => mi.multiaddr)\n })\n })\n\n return peers\n }\n\n return withTimeoutOption(addrs)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createConnect ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"connect\"]}\n */\n async function connect (multiaddrOrPeerId, options = {}) {\n const { libp2p } = await network.use(options)\n await libp2p.dial(multiaddrOrPeerId, options)\n }\n\n return withTimeoutOption(connect)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createDisconnect ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"disconnect\"]}\n */\n async function disconnect (addr, options = {}) {\n const { libp2p } = await network.use(options)\n await libp2p.hangUp(addr)\n }\n\n return withTimeoutOption(disconnect)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createLocalAddrs ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"localAddrs\"]}\n */\n async function localAddrs (options = {}) {\n const { libp2p } = await network.use(options)\n return libp2p.getMultiaddrs()\n }\n\n return withTimeoutOption(localAddrs)\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {import('ipfs-core-types/src/swarm').PeersResult} PeersResult\n */\n\n/**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\nexport function createPeers ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/swarm').API<{}>[\"peers\"]}\n */\n async function peers (options = {}) {\n const { libp2p } = await network.use(options)\n\n if (options.verbose) {\n const peers = []\n for (const connection of libp2p.getConnections()) {\n /** @type {PeersResult} */\n const peer = {\n addr: connection.remoteAddr,\n peer: connection.remotePeer\n }\n\n if (options.verbose || options.direction) {\n peer.direction = connection.stat.direction\n }\n\n if (options.verbose) {\n peer.muxer = connection.stat.multiplexer\n peer.latency = 'n/a'\n peer.streams = [] // TODO: get this from libp2p\n }\n\n peers.push(peer)\n }\n\n return peers\n }\n\n /** @type {Map} */\n const peers = new Map()\n\n for (const connection of libp2p.getConnections()) {\n /** @type {import('ipfs-core-types/src/swarm').PeersResult} */\n const peer = {\n addr: connection.remoteAddr,\n peer: connection.remotePeer\n }\n\n peers.set(connection.remotePeer.toString(), peer)\n }\n\n return Array.from(peers.values())\n }\n\n return withTimeoutOption(peers)\n}\n", "import { createAddrs } from './addrs.js'\nimport { createConnect } from './connect.js'\nimport { createDisconnect } from './disconnect.js'\nimport { createLocalAddrs } from './local-addrs.js'\nimport { createPeers } from './peers.js'\n\nexport class SwarmAPI {\n /**\n * @param {object} config\n * @param {import('../../types').NetworkService} config.network\n */\n constructor ({ network }) {\n this.addrs = createAddrs({ network })\n this.connect = createConnect({ network })\n this.disconnect = createDisconnect({ network })\n this.localAddrs = createLocalAddrs({ network })\n this.peers = createPeers({ network })\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\n\n/**\n * @typedef {Pong|PingFailure|StatusUpdate} Packet\n * Note that not all ping response objects are \"pongs\".\n * A \"pong\" message can be identified by a truthy success property and an empty\n * text property. Other ping responses are failures or status updates.\n *\n * @typedef {object} Pong\n * @property {true} success\n * @property {number} time\n * @property {''} text\n *\n * @typedef {object} PingFailure\n * @property {false} success\n * @property {number} time\n * @property {string} text\n *\n * @typedef {object} StatusUpdate\n * @property {true} success\n * @property {0} time\n * @property {string} text\n *\n * @typedef {PingSettings & AbortOptions} PingOptions\n *\n * @typedef {object} PingSettings\n * @property {number} [count=10] - The number of ping messages to send\n *\n * @typedef {import('ipfs-core-types/src/utils').AbortOptions} AbortOptions\n */\n\n/** @type {{success:true, time:0, text: ''}} */\nconst basePacket = { success: true, time: 0, text: '' }\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n */\nexport function createPing ({ network }) {\n /**\n * @type {import('ipfs-core-types/src/root').API<{}>[\"ping\"]}\n */\n async function * ping (peerId, options = {}) {\n const { libp2p } = await network.use()\n options.count = options.count || 10\n\n const storedPeer = await libp2p.peerStore.get(peerId)\n let id = storedPeer && storedPeer.id\n\n if (!id) {\n yield { ...basePacket, text: `Looking up peer ${peerId}` }\n const remotePeer = await libp2p.peerRouting.findPeer(peerId)\n\n id = remotePeer && remotePeer.id\n }\n\n if (!id) {\n throw new Error('Peer was not found')\n }\n\n yield { ...basePacket, text: `PING ${id.toString()}` }\n\n let packetCount = 0\n let totalTime = 0\n\n for (let i = 0; i < options.count; i++) {\n try {\n const time = await libp2p.ping(id)\n totalTime += time\n packetCount++\n yield { ...basePacket, time }\n } catch (/** @type {any} */ err) {\n yield { ...basePacket, success: false, text: err.toString() }\n }\n }\n\n if (packetCount) {\n const average = totalTime / packetCount\n yield { ...basePacket, text: `Average latency: ${average}ms` }\n }\n }\n\n return withTimeoutOption(ping)\n}\n", "import errCode from 'err-code'\nimport { NotEnabledError } from '../errors.js'\nimport { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport { CID } from 'multiformats/cid'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base36 } from 'multiformats/bases/base36'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromString } from '@libp2p/peer-id'\n\n/**\n * @typedef {import('@libp2p/interface-dht').QueryEvent} QueryEvent\n * @typedef {import('./network').Network} Network\n * @typedef {import('@libp2p/interface-peer-id').PeerId} PeerId\n */\n\nconst IPNS_PREFIX = '/ipns/'\n\n/**\n * @param {string} str\n */\nfunction toDHTKey (str) {\n if (str.startsWith(IPNS_PREFIX)) {\n str = str.substring(IPNS_PREFIX.length)\n }\n\n /** @type {Uint8Array|undefined} */\n let buf\n\n if (str[0] === '1' || str[0] === 'Q') {\n // ed25519 key or hash of rsa key\n str = `z${str}`\n }\n\n if (str[0] === 'z') {\n buf = base58btc.decode(str)\n }\n\n if (str[0] === 'k') {\n // base36 encoded string\n buf = base36.decode(str)\n }\n\n if (!buf) {\n throw new Error('Could not parse string')\n }\n\n if (buf[0] !== 0x01 && buf[1] !== 0x72) {\n // prefix key with CIDv1 and libp2p-key codec\n buf = uint8ArrayConcat([\n [0x01, 0x72],\n buf\n ])\n }\n\n if (buf.length !== 40) {\n throw new Error('Incorrect length ' + buf.length)\n }\n\n return uint8ArrayConcat([\n uint8ArrayFromString(IPNS_PREFIX),\n buf.subarray(2)\n ])\n}\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('ipfs-repo').IPFSRepo} config.repo\n * @param {PeerId} config.peerId\n */\nexport function createDht ({ network, repo, peerId }) {\n const { get, put, findProvs, findPeer, provide, query } = {\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"get\"]}\n */\n async * get (key, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n\n const dhtKey = key instanceof Uint8Array ? key : toDHTKey(key)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.get(dhtKey, options)\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"put\"]}\n */\n async * put (key, value, options) {\n const { libp2p } = await use(network, peerId, options)\n\n const dhtKey = key instanceof Uint8Array ? key : toDHTKey(key)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.put(dhtKey, value, options)\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"findProvs\"]}\n */\n async * findProvs (cid, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.findProviders(cid, {\n signal: options.signal\n })\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"findPeer\"]}\n */\n async * findPeer (peerIdToFind, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.findPeer(peerIdToFind, {\n signal: options.signal\n })\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"provide\"]}\n */\n async * provide (cid, options = { recursive: false }) {\n const { libp2p } = await use(network, peerId, options)\n\n // ensure blocks are actually local\n const hasBlock = await repo.blocks.has(cid)\n\n if (!hasBlock) {\n throw errCode(new Error('block(s) not found locally, cannot provide'), 'ERR_BLOCK_NOT_FOUND')\n }\n\n if (options.recursive) {\n // TODO: Implement recursive providing\n throw errCode(new Error('not implemented yet'), 'ERR_NOT_IMPLEMENTED_YET')\n }\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.provide(cid)\n },\n\n /**\n * @type {import('ipfs-core-types/src/dht').API<{}>[\"query\"]}\n */\n async * query (peerIdToQuery, options = {}) {\n const { libp2p } = await use(network, peerId, options)\n let bytes\n const asCid = CID.asCID(peerIdToQuery)\n\n if (asCid != null) {\n bytes = asCid.multihash.bytes\n } else {\n bytes = peerIdFromString(peerIdToQuery.toString()).toBytes()\n }\n\n if (libp2p.dht == null) {\n throw errCode(new Error('dht not configured'), 'ERR_DHT_NOT_CONFIGURED')\n }\n\n yield * libp2p.dht.getClosestPeers(bytes, options)\n }\n }\n\n return {\n get: withTimeoutOption(get),\n put: withTimeoutOption(put),\n findProvs: withTimeoutOption(findProvs),\n findPeer: withTimeoutOption(findPeer),\n provide: withTimeoutOption(provide),\n query: withTimeoutOption(query)\n }\n}\n\n/**\n * @param {import('../types').NetworkService} network\n * @param {PeerId} peerId\n * @param {import('ipfs-core-types/src/utils').AbortOptions} [options]\n * @returns {Promise}\n */\nconst use = async (network, peerId, options) => {\n const net = await network.use(options)\n if (net.libp2p.dht != null) {\n return net\n } else {\n const fn = async function * () {\n yield {\n from: peerId,\n name: 'QUERY_ERROR',\n type: 3,\n error: new NotEnabledError('dht not enabled')\n }\n }\n\n return {\n libp2p: {\n dht: {\n // @ts-expect-error incomplete implementation\n get: fn,\n // @ts-expect-error incomplete implementation\n put: fn,\n // @ts-expect-error incomplete implementation\n findProviders: fn,\n // @ts-expect-error incomplete implementation\n findPeer: fn,\n // @ts-expect-error incomplete implementation\n provide: fn,\n // @ts-expect-error incomplete implementation\n getClosestPeers: fn\n }\n }\n }\n }\n}\n", "import { withTimeoutOption } from 'ipfs-core-utils/with-timeout-option'\nimport errCode from 'err-code'\nimport { NotEnabledError } from '../errors.js'\nimport get from 'dlv'\n\n/**\n * @typedef {import('@libp2p/interface-pubsub').Message} Message\n * @typedef {import('@libp2p/interfaces/events').EventHandler>} EventHandler\n * @typedef {import('@libp2p/interfaces/events').EventHandler} MessageEventHandler\n */\n\n/**\n * @param {object} config\n * @param {import('../types').NetworkService} config.network\n * @param {import('ipfs-core-types/src/config').Config} [config.config]\n */\nexport function createPubsub ({ network, config }) {\n const isEnabled = get(config || {}, 'Pubsub.Enabled', true)\n\n /** @type {Record} */\n const handlers = {}\n /** @type {EventHandler | undefined} */\n let onMessage\n\n return {\n subscribe: isEnabled ? withTimeoutOption(subscribe) : notEnabled,\n unsubscribe: isEnabled ? withTimeoutOption(unsubscribe) : notEnabled,\n publish: isEnabled ? withTimeoutOption(publish) : notEnabled,\n ls: isEnabled ? withTimeoutOption(ls) : notEnabled,\n peers: isEnabled ? withTimeoutOption(peers) : notEnabled\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"subscribe\"]}\n */\n async function subscribe (topic, handler, options = {}) {\n const { libp2p } = await network.use(options)\n\n libp2p.pubsub.subscribe(topic)\n\n // listen for 'message' events if we aren't already\n if (onMessage == null) {\n onMessage = (evt) => {\n const msg = evt.detail\n\n if (handlers[msg.topic]) {\n handlers[msg.topic].forEach(handler => {\n if (typeof handler === 'function') {\n handler(msg)\n return\n }\n\n if (handler != null && handler.handleEvent != null) {\n handler.handleEvent(msg)\n }\n })\n }\n }\n\n libp2p.pubsub.addEventListener('message', onMessage)\n }\n\n // store handler for future invocation\n if (handler != null) {\n if (handlers[topic] == null) {\n handlers[topic] = []\n }\n\n handlers[topic].push(handler)\n }\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"unsubscribe\"]}\n */\n async function unsubscribe (topic, handler, options = {}) {\n const { libp2p } = await network.use(options)\n\n // remove handler from local map\n if (handler != null && handlers[topic] != null) {\n handlers[topic] = handlers[topic].filter(h => h !== handler)\n\n if (handlers[topic].length === 0) {\n delete handlers[topic]\n }\n }\n\n // remove all handlers\n if (typeof handler !== 'function') {\n delete handlers[topic]\n }\n\n // no more handlers for this topic, unsubscribe\n if (handlers[topic] == null) {\n libp2p.pubsub.unsubscribe(topic)\n }\n\n // no more pubsub handlers, remove message listener\n if (Object.keys(handlers).length === 0) {\n libp2p.pubsub.removeEventListener('message', onMessage)\n onMessage = undefined\n }\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"publish\"]}\n */\n async function publish (topic, data, options = {}) {\n const { libp2p } = await network.use(options)\n if (!data) {\n throw errCode(new Error('argument \"data\" is required'), 'ERR_ARG_REQUIRED')\n }\n\n await libp2p.pubsub.publish(topic, data)\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"ls\"]}\n */\n async function ls (options = {}) {\n const { libp2p } = await network.use(options)\n\n return libp2p.pubsub.getTopics()\n }\n\n /**\n * @type {import('ipfs-core-types/src/pubsub').API<{}>[\"peers\"]}\n */\n async function peers (topic, options = {}) {\n const { libp2p } = await network.use(options)\n\n return libp2p.pubsub.getSubscribers(topic)\n }\n}\n\nconst notEnabled = async () => { // eslint-disable-line require-await\n throw new NotEnabledError('pubsub not enabled')\n}\n", "import { create as createImport } from './components/index.js'\nimport globSourceImport from 'ipfs-utils/src/files/glob-source.js'\nimport urlSourceImport from 'ipfs-utils/src/files/url-source.js'\n\n/**\n * @typedef {import('ipfs-core-types').IPFS} IPFS\n * @typedef {import('./types').Options} Options\n * @typedef {import('./types').Libp2pFactoryFn} Libp2pFactoryFn\n * @typedef {import('./types').Libp2pFactoryFnArgs} Libp2pFactoryFnArgs\n * @typedef {import('./types').InitOptions} InitOptions\n * @typedef {import('./types').RelayOptions} RelayOptions\n * @typedef {import('./types').PreloadOptions} PreloadOptions\n * @typedef {import('./types').ExperimentalOptions} ExperimentalOptions\n * @typedef {import('./types').Preload} Preload\n * @typedef {import('./types').MfsPreload} MfsPreload\n * @typedef {import('./types').LoadBaseFn} LoadBaseFn\n * @typedef {import('./types').LoadCodecFn} LoadCodecFn\n * @typedef {import('./types').LoadHasherFn} LoadHasherFn\n * @typedef {import('./types').IPLDOptions} IPLDOptions\n */\n\nexport const create = createImport\nexport const globSource = globSourceImport\nexport const urlSource = urlSourceImport\n", "import { CID as CoreCID } from \"multiformats/cid\";\n\nexport const CID = (() => {\n return {\n toString: function (cid: CoreCID): string {\n return cid.toV1().toString();\n },\n fromString: function (cid: string): CoreCID {\n return CoreCID.parse(cid);\n },\n };\n})();\n", "import { create } from \"ipfs-core\";\nimport { CID } from \"../Entities/CID\";\nimport type { IPFS } from \"ipfs-core-types\";\n\nexport const ipfs = (() => {\n let ipfs: IPFS;\n\n return {\n init: async () => {\n if (!ipfs) {\n ipfs = await create({\n repo: String(Math.random() + Date.now()),\n });\n }\n },\n store: async function (filename: string, content): Promise {\n await this.init();\n\n const fileToAdd = {\n path: filename,\n content,\n };\n\n const file = await ipfs.add(fileToAdd);\n const { cid } = file;\n\n return CID.toString(cid);\n },\n retrieve: async function (cid) {\n await this.init();\n const decoder = new TextDecoder();\n let content = \"\";\n\n for await (const chunk of ipfs.cat(cid)) {\n content += decoder.decode(chunk, {\n stream: true,\n });\n }\n return content;\n },\n };\n})();\n", "import {\n saveNote,\n getNote,\n resetNoteManager,\n getNotes,\n deleteNote,\n} from \"../noteManager/noteManager\";\nimport select from \"../../../utils/dom\";\nimport storage from \"../../../utils/localstorage\";\nimport { isUserLoggedIn } from \"../../../utils/isUserLoggedIn\";\nimport {\n goAuthenticate,\n setGistToSyncWith,\n syncNotesWithGitHub,\n} from \"../../../utils/github/actions\";\nimport commander from \"./commander\";\nimport {\n saveFileAs,\n saveDataToFile,\n} from \"../../../utils/fileSystem/fileSystem\";\nimport { url } from \"../../../utils/urlManager\";\nimport { mailTo } from \"../../../utils/mail\";\nimport markDownViewer from \"../markdown/markDownViewer\";\nimport prettifyJSON from \"../../../utils/prettifyJSON\";\nimport notify from \"../../molecules/notify\";\nimport { copyToClipboard } from \"../../../utils/copyToClipboard\";\nimport { sleep } from \"../../../utils/sleep\";\nimport { updateGist, publishGist } from \"../../../utils/github/api\";\nimport { icon } from \"../../atoms/icon/icon\";\nimport ListSVG from \"../../../../assets/svg/list.svg\";\nimport TrashSVG from \"../../../../assets/svg/trash.svg\";\nimport CheckmarkCircleSVG from \"../../../../assets/svg/checkmark-circle.svg\";\nimport CloudSyncSVG from \"../../../../assets/svg/cloud-sync.svg\";\nimport LighterSVG from \"../../../../assets/svg/lighter.svg\";\nimport EnterDownSVG from \"../../../../assets/svg/enter-down.svg\";\nimport DownloadSVG from \"../../../../assets/svg/download.svg\";\nimport EnvelopeSVG from \"../../../../assets/svg/envelope.svg\";\nimport BugSVG from \"../../../../assets/svg/bug.svg\";\nimport PictureSVG from \"../../../../assets/svg/picture.svg\";\nimport PrinterSVG from \"../../../../assets/svg/printer.svg\";\nimport PageBreakSVG from \"../../../../assets/svg/page-break.svg\";\nimport FrameExpandSVG from \"../../../../assets/svg/frame-expand.svg\";\nimport ArrowRightCircleSVG from \"../../../../assets/svg/arrow-right-circle.svg\";\nimport MagicWandSVG from \"../../../../assets/svg/magic-wand.svg\";\nimport RocketSVG from \"../../../../assets/svg/rocket.svg\";\nimport EarthSVG from \"../../../../assets/svg/earth.svg\";\nimport SpellCheckSVG from \"../../../../assets/svg/spell-check.svg\";\nimport PencilSVG from \"../../../../assets/svg/pencil.svg\";\nimport ShareSVG from \"../../../../assets/svg/exit-up.svg\";\nimport LeafSVG from \"../../../../assets/svg/leaf.svg\";\nimport { share } from \"../../../utils/webShare\";\nimport { ipfs } from \"../../../repositories/ipfs\";\nimport { setSavedState } from \"../../../ui/functions/savedState\";\n\nconst getSyncTitle = () => {\n const gistId = storage.get(\"gistId\");\n const authToken = storage.get(\"authToken\");\n if (!authToken) {\n return \"Sync: Authorize your GitHub account for synchronisation\";\n }\n if (!gistId) {\n return \"Sync: Pick your Gist to sync with\";\n }\n return \"Sync: Notes with my GitHub Gist\";\n};\n\nconst shareNoteCommand = {\n title: \"Share note\",\n icon: icon(ShareSVG, \"share note\"),\n sortTitle: \"Share\",\n call: share,\n};\n\nconst sharePublicLinkCommand = {\n title: \"Share public link\",\n key: null,\n icon: icon(ShareSVG, \"share public link\"),\n sortTitle: \"Share public link\",\n call: async () => {\n commander.hide();\n await saveNote(select(\".terminal\").getValue());\n const note = getNote();\n const response = await publishGist({\n note,\n });\n const rawLink = response.history[0].url;\n const gitResponse = await fetch(rawLink).then((response) =>\n response.json()\n );\n const { files } = gitResponse;\n const fileContents = Object.values(files);\n const [gistFile] = fileContents;\n const { raw_url: rawUrl } = gistFile;\n const linkToShare = `${url.baseUrl}?raw=${rawUrl}`;\n const successMessage = \"MiroPad public link copied to clipboard \uD83D\uDCCB!\";\n copyToClipboard(linkToShare, successMessage);\n },\n};\n\nexport const commands = () => {\n return [\n {\n title: \"New note\",\n icon: icon(PencilSVG, \"new note\"),\n sortTitle: \"New\",\n key: \"n\",\n call: resetNoteManager,\n },\n {\n title: \"Save\",\n key: \"s\",\n icon: icon(CheckmarkCircleSVG, \"save\"),\n sortTitle: \"Save\",\n call: async () => {\n commander.hide();\n await saveNote(select(\".terminal\").getValue());\n const note = getNote();\n const { disableSync = false } = note;\n if (!disableSync) {\n updateGist([note]);\n }\n setSavedState();\n },\n },\n ...(navigator.share ? [shareNoteCommand] : []),\n {\n title: \"Toggle MarkDown Viewer\",\n icon: icon(PageBreakSVG, \"toggle markdown viewer\", \"rotate90\"),\n sortTitle: \"Split\",\n key: \"m\",\n call: () => {\n markDownViewer.toggle();\n commander.hide();\n },\n },\n {\n title: \"Full MarkDown view\",\n icon: icon(FrameExpandSVG, \"full view\"),\n sortTitle: \"Full view\",\n key: \"shift m\",\n call: () => {\n markDownViewer.toggle(\"full\");\n commander.hide();\n },\n },\n {\n title: \"Save to IPFS\",\n key: \"i\",\n icon: icon(EarthSVG, \"save\"),\n sortTitle: \"save->ipfs\",\n call: async () => {\n commander.hide();\n await saveNote(select(\".terminal\").getValue());\n const note = getNote();\n const { disableSync = false } = note;\n if (!disableSync) {\n updateGist([note]);\n }\n\n if (note) {\n const cid = await ipfs.store(note.title, note.text);\n copyToClipboard(`${url.baseUrl}#?cid=${cid}`);\n }\n },\n },\n ...(isUserLoggedIn() ? [sharePublicLinkCommand] : []),\n {\n title: \"Zen mode\",\n icon: icon(LeafSVG, \"zen mode\"),\n sortTitle: \"Zen mode\",\n key: \"shift z\",\n call: () => {\n const isZen = Boolean(url.getSearchParam(\"zen\"));\n if (isZen) {\n url.deleteParam(\"zen\");\n } else {\n url.set(undefined, {\n zen: true,\n });\n }\n commander.hide();\n },\n },\n {\n title: \"List saved notes\",\n icon: icon(ListSVG, \"list notes\"),\n sortTitle: \"Notes\",\n key: \"p\",\n call: () => commander.toggle(commander.getModes().notes),\n },\n {\n title: \"Delete note\",\n key: \"shift d\",\n icon: icon(TrashSVG, \"delete note\"),\n sortTitle: \"Delete\",\n call: deleteNote,\n },\n {\n title: getSyncTitle(),\n icon: icon(CloudSyncSVG, \"sync with github\"),\n key: null,\n call: async () => {\n const token = storage.get(\"authToken\");\n if (!token) {\n return await goAuthenticate();\n }\n const gistId = storage.get(\"gistId\");\n if (!gistId) {\n return await setGistToSyncWith(token);\n }\n commander.hide();\n await syncNotesWithGitHub();\n },\n },\n {\n title: \"Sync: Reset Gist settings\",\n icon: icon(LighterSVG, \"reset github settings\"),\n key: null,\n call: async () => {\n localStorage.removeItem(\"authToken\");\n localStorage.removeItem(\"gistId\");\n localStorage.removeItem(\"lastLocalUpdate\");\n localStorage.removeItem(\"lastSync\");\n notify.info(\"Gist setting have been reset!\");\n commander.hide();\n },\n },\n {\n title: \"Toggle sidebar\",\n experimental: true,\n key: \"shift l\",\n call: () => {\n select(\"aside\").toggle();\n },\n },\n {\n title: \"Save to File System...\",\n experimental: true,\n icon: icon(EnterDownSVG, \"save file\"),\n key: \"shift s\",\n call: async () => {\n const { text, title } = getNote();\n\n saveFileAs(text, title);\n commander.hide();\n },\n },\n {\n title: \"Email note to...\",\n experimental: true,\n icon: icon(EnvelopeSVG, \"email\"),\n key: \"e\",\n call: () => {\n const note = document.querySelector(\".terminal\").value;\n mailTo(note);\n commander.hide();\n },\n },\n {\n title: \"Toggle experimental features\",\n experimental: false,\n icon: icon(BugSVG, \"lab\"),\n key: null,\n call: () => {\n const previousStatus = Boolean(storage.get(\"__experimental__\"));\n\n if (previousStatus) {\n storage.remove(\"__experimental__\");\n } else {\n storage.set(\"__experimental__\", true);\n }\n notify.showNotification(\n `Experimental features turned ${previousStatus ? \"off\" : \"on\"}`\n );\n commander.hide();\n },\n },\n {\n title: \"Toggle Autocompletion\",\n experimental: false,\n icon: icon(ArrowRightCircleSVG, \"autocompletion\"),\n key: null,\n call: () => {\n const previousStatus = Boolean(storage.get(\"__autocomplete__\"));\n\n if (previousStatus) {\n storage.remove(\"__autocomplete__\");\n } else {\n storage.set(\"__autocomplete__\", true);\n }\n notify.showNotification(\n `Autocomplete feature turned ${previousStatus ? \"off\" : \"on\"}`\n );\n commander.hide();\n select(\".terminal\").focus();\n },\n },\n {\n title: \"Add a cover picture\",\n experimental: true,\n icon: icon(PictureSVG, \"cover picture\"),\n key: null,\n call: async () => {\n const bgImage = prompt(\"Paste the image URL in here...\");\n commander.hide();\n await sleep(200); // need to wait after prompt for some reason before copy\n copyToClipboard(\n `
    `,\n \"\uD83D\uDC4CCopied! Paste the code on the MiroPad editor\"\n );\n select(\".terminal\").focus();\n notify.info(\n \"Paste the cover picture wherever you prefer on the MirPad editor\"\n );\n },\n },\n {\n title: \"Print MarkDown output\",\n experimental: true,\n icon: icon(PrinterSVG, \"print\"),\n key: null,\n call: () => {\n select(\".preview\").show();\n markDownViewer.init();\n window.print();\n commander.hide();\n },\n },\n {\n key: \"j\",\n title: \"Prettify JSON document\",\n icon: icon(MagicWandSVG, \"prettify json\"),\n call: () => {\n prettifyJSON(\".terminal\");\n commander.hide();\n },\n },\n {\n title: \"Toggle command palette\",\n icon: icon(RocketSVG, \"toggle command palette\"),\n key: [\"shift p\", \"k\"],\n call: () => commander.toggle(commander.getModes().commands),\n },\n {\n title: \"Find and Replace...\",\n experimental: true,\n icon: icon(SpellCheckSVG, \"find and replace\"),\n key: \"shift f\",\n call: () => {\n const selectedValue = select(\".terminal\")\n .getValue()\n .slice(\n select(\".terminal\").el.selectionStart,\n select(\".terminal\").el.selectionEnd\n );\n const valueToFind = prompt(\"What do you wanna find?\", selectedValue);\n if (!valueToFind) {\n return notify.info(\"Value not found\");\n }\n const positionOfFirstChar = select(\".terminal\")\n .getValue()\n .indexOf(valueToFind);\n\n select(\".terminal\").el.setSelectionRange(\n positionOfFirstChar,\n positionOfFirstChar + valueToFind.length\n );\n const replacementValue = prompt(`Replace ${valueToFind} with...`);\n if (replacementValue) {\n select(\".terminal\").el.setRangeText(replacementValue);\n }\n },\n },\n {\n title: \"Download all notes!\",\n icon: icon(DownloadSVG, \"Download all notes on your local file system\"),\n call: () => {\n const notes = getNotes({\n includeDeleted: true,\n });\n saveDataToFile(notes);\n commander.hide();\n },\n },\n {\n title: \"Permanently delete ALL notes \u2757\",\n icon: icon(TrashSVG, \"delete note\"),\n call: () => {\n const confirmation = confirm(\n \"Are you sure you want do delete ALL your notes?\"\n );\n if (confirmation) {\n const notes = getNotes({\n includeDeleted: true,\n });\n notes.forEach((note) => {\n storage.remove(note.id);\n });\n resetNoteManager();\n }\n commander.hide();\n },\n },\n ];\n};\n", "const keyListener = {\n events: [],\n on(key, fn) {\n if (Array.isArray(key)) {\n key.forEach((k) => {\n const finalKey = k.key || k;\n const functionToCall = k.call || fn;\n this.on(finalKey, functionToCall);\n });\n\n return this;\n }\n\n if (key && typeof key === \"string\" && fn && typeof fn === \"function\") {\n this.events = [\n ...this.events,\n {\n key: key.includes(\"shift\") ? key.replace(\"shift\", \"\").trim() : key,\n shift: key.includes(\"shift\"),\n fn() {\n fn();\n },\n },\n ];\n }\n return this;\n },\n listen() {\n document.addEventListener(\"keydown\", (e) => {\n this.handleEvent(e);\n });\n return this;\n },\n handleEvent(e) {\n this.events.map((event) => {\n if (\n event.key === e.key &&\n (e.ctrlKey === true || e.metaKey === true) &&\n e.shiftKey === event.shift\n ) {\n e.preventDefault();\n event.fn();\n }\n return true;\n });\n },\n};\n\nexport default keyListener;\n", "import { isElement } from \"../../../utils/dom\";\nexport const link = (textOrNode, url) => {\n const a = document.createElement(\"a\");\n a.href = url;\n a.appendChild(\n isElement(textOrNode) ? textOrNode : document.createTextNode(textOrNode)\n );\n return a;\n};\n", "const isSameYear = (aDate, bDate = new Date()) => {\n const yearA = new Date(aDate).getFullYear();\n const yearB = new Date(bDate).getFullYear();\n\n return yearA === yearB;\n};\n\nconst isSameMonth = (aDate, bDate = new Date()) => {\n const monthA = new Date(aDate).getMonth();\n const monthB = new Date(bDate).getMonth();\n\n return monthA === monthB;\n};\n\nconst isSameDateOfMonth = (aDate, bDate = new Date()) => {\n const dateA = new Date(aDate).getDate();\n const dateB = new Date(bDate).getDate();\n\n return dateA === dateB;\n};\n\nconst isSameDate = (aDate, bDate = new Date()) => {\n return (\n isSameYear(aDate, bDate) &&\n isSameMonth(aDate, bDate) &&\n isSameDateOfMonth(aDate, bDate)\n );\n};\n\nconst monthNames = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nconst shortMonthNames = monthNames.map((name) => name.slice(0, 3));\n\nconst isYesterday = (date = new Date()) => {\n const theDate = new Date(date);\n const yesterDate = new Date().getDate() - 1;\n return (\n isSameMonth(theDate) &&\n isSameYear(theDate) &&\n theDate.getDate() === yesterDate\n );\n};\n\nexport const relativeDate = (dateCreated) => {\n const date = new Date(dateCreated);\n const month = !isYesterday(dateCreated)\n ? shortMonthNames[date.getMonth()]\n : \"\";\n const year = isSameYear(date) ? \"\" : date.getFullYear();\n const day = isYesterday(date) ? \"Yesterday\" : date.getDate();\n\n return `${isSameDate(date) ? \"\" : `${day} ${month} ${year}`} ${\n isSameDate(date) ? date.toLocaleTimeString() : \"\"\n }`;\n};\n", "export const isArraySorted = (arr) => {\n const someArray = arr.reduce((currentValue, item) => {\n if (currentValue.length === 0) {\n return [item];\n }\n const max = Math.max(...currentValue);\n return [...currentValue, ...(item >= max ? [item] : [])];\n }, []);\n return someArray.length === arr.length;\n};\n", "import { isArraySorted } from \"../../../utils/isArraySorted\";\n\nexport const smartFilter = (phrase, filter) => {\n const wordParts = phrase.split(\" \").map((w) => w.toLowerCase());\n const filterParts = filter.split(\" \").map((f) => f.toLowerCase());\n const indexes = filterParts.map((f) => {\n const foundIndexes = wordParts.map((w, i) => {\n return w.includes(f) ? i : -1;\n });\n const firstIndexFound = foundIndexes.reduce((currentValue, fi) => {\n return fi > -1 ? fi : currentValue;\n }, -1);\n return firstIndexFound;\n });\n\n if (indexes.includes(-1)) {\n return false;\n }\n return isArraySorted(indexes);\n};\n", "import storage from \"./utils/localstorage\";\n\nexport const requestNotificationPermission = async () => {\n if (!storage.get(\"__notification-permission__\")) {\n const permission = await window.Notification.requestPermission();\n storage.set(\"__notification-permission__\", permission);\n }\n};\n\nexport const registerServiceWorker = async () => {\n if (\"serviceWorker\" in navigator) {\n navigator.serviceWorker.register(\n `${window.location.pathname}service-worker.js?v=${VERSION}`\n );\n }\n};\n", "/* eslint-disable indent */\nimport {\n getNote,\n getNotes,\n getDateCreatedFromTitle,\n} from \"../noteManager/noteManager\";\nimport { commands } from \"./commands\";\nimport keyListener from \"../../../utils/keyListener\";\nimport select from \"../../../utils/dom\";\nimport { url } from \"../../../utils/urlManager\";\nimport { command } from \"../../molecules/commands/command\";\nimport { link } from \"../../atoms/link/link\";\nimport { div } from \"../../atoms/div/div\";\nimport { relativeDate } from \"../../../utils/dates\";\nimport { smartFilter } from \"./smartFilter\";\nimport { button } from \"../../atoms/button/button\";\nimport { requestNotificationPermission } from \"../../../registerServiceWorker\";\nimport storage from \"../../../utils/localstorage\";\n\nconst getShortcut = (key) => {\n if (Array.isArray(key)) {\n return key.map((k) => getShortcut(k)).join(\", \");\n }\n\n return key ? `\u2318+${key.toUpperCase()}` : \"\";\n};\n\nconst commander = (() => {\n const commanderModes = {\n off: \"off\",\n notes: \"notes\",\n revisions: \"revisions\",\n commands: \"commands\",\n gists: \"gists\",\n };\n let state = {\n input: \"\",\n mode: commanderModes.off,\n options: {\n selected: 0,\n length: 0,\n },\n };\n return {\n getState: function () {\n return state;\n },\n getModes: function () {\n return commanderModes;\n },\n setState: function (newState) {\n state = {\n ...state,\n ...newState,\n };\n return state;\n },\n show: function (what = commanderModes.commands) {\n select(\"#commander\").show();\n select(\"#commander input\").focus();\n switch (what) {\n case commanderModes.commands:\n this.generateCommands();\n select(\"#commander input\").setValue(\"> \");\n this.setState({\n mode: commanderModes.commands,\n });\n break;\n case commanderModes.notes:\n this.generateNotes();\n select(\"#commander input\").setValue(\"\");\n this.setState({\n mode: commanderModes.notes,\n });\n break;\n case commanderModes.revisions:\n this.generateRevisions();\n select(\"#commander input\").setValue(\"\");\n this.setState({\n mode: commanderModes.revisions,\n });\n break;\n default:\n // do nothing;\n break;\n }\n return this;\n },\n hide: function () {\n select(\"#commander\").hide();\n state.mode = commanderModes.off;\n return this;\n },\n toggle: function (mode) {\n requestNotificationPermission();\n if (state.mode === commanderModes.off || state.mode !== mode) {\n this.show(mode);\n } else {\n this.hide();\n }\n return this;\n },\n commands: function () {\n return commands();\n },\n selectOption: function (e, direction) {\n const currentlySelected = state.options.selected;\n const lastOption = state.options.length - 1;\n const isLastOption = currentlySelected === lastOption;\n const isFirstOption = currentlySelected === 0;\n const isDown = direction === \"down\";\n\n const indexToSelect = isDown\n ? isLastOption\n ? 0\n : currentlySelected + 1\n : isFirstOption\n ? lastOption\n : currentlySelected - 1;\n\n state.options = {\n ...state.options,\n selected: indexToSelect,\n };\n },\n initCommander: function () {\n // initialize mobile-dock\n commands()\n .slice(0, 5)\n .map((command) => {\n select(\".mobile-dock\").append(\n button(\n [command.icon, document.createTextNode(command.sortTitle)],\n command.call,\n command.title.toLowerCase().replace(/\\s/g, \"-\")\n )\n );\n });\n\n select(\"#commander button\").listen(\"click\", () => {\n this.hide();\n });\n\n select(\"#commander input\")\n .listen(\"keydown\", (e) => {\n // arrow down 40\n if (e.keyCode === 40) {\n if (state.mode === commanderModes.revisions) {\n select(\"#commands li.selected\").click();\n }\n this.selectOption(e, \"down\");\n }\n // arrow up 38\n if (e.keyCode === 38) {\n if (state.mode === commanderModes.revisions) {\n select(\"#commands li.selected\").click();\n }\n this.selectOption(e, \"up\");\n }\n })\n .listen(\"keyup\", (e) => {\n // enter\n if (e.keyCode === 13) {\n if (state.mode === commanderModes.commands) {\n select(\"#commands li.selected div\").click();\n } else {\n select(\"#commands li.selected a\").click();\n }\n }\n // escape\n if (e.keyCode === 27) {\n select(\".terminal\").focus();\n }\n if (state.input !== e.target.value) {\n state.options.selected = 0;\n }\n state.input = e.target.value;\n this.generateOptions(e.target.value);\n });\n return this;\n },\n init: function () {\n this.initCommander();\n keyListener.listen().on(this.commands());\n select(\".menu\").listen(\"click\", () => this.toggle());\n select(\"#revisions\").listen(\"click\", () => this.generateRevisions());\n return this;\n },\n generateRevisions: function () {\n this.show();\n state.mode = commanderModes.revisions;\n const { revisions } = getNote();\n const indexToSelect = state.options.selected;\n const revisionsOptions = Object.keys(revisions)\n .sort((a, b) => {\n const { dateCreated: aDateCreated } = revisions[a];\n const { dateCreated: bDateCreated } = revisions[b];\n return bDateCreated - aDateCreated;\n })\n .map((id, i) => ({\n title: div({ content: `...${id.slice(-10)}` }),\n secondary: `${relativeDate(revisions[id].dateCreated)}`,\n onclick: () => {\n url.set(undefined, {\n v: id,\n });\n state.options.selected = i;\n this.generateRevisions();\n },\n }))\n .map((r, i) => command(r, i === indexToSelect));\n\n select(\"#commands\").html(revisionsOptions);\n\n state.options = {\n ...state.options,\n length: revisionsOptions.length,\n };\n return this;\n },\n generateOptions: function (value) {\n switch (state.mode) {\n case commanderModes.commands:\n case commanderModes.notes:\n if (value.slice(0, 1) === \">\") {\n state.mode = commanderModes.commands;\n this.generateCommands(value.slice(1).trim());\n select(\"#commander input\").placeholder(\"Search for commands...\");\n } else {\n state.mode = commanderModes.notes;\n this.generateNotes(value);\n }\n return;\n case commanderModes.revisions:\n return this.generateRevisions();\n case commanderModes.off:\n break;\n default:\n break;\n }\n },\n generateNotes: function (value = \"\") {\n const indexToSelect = state.options.selected;\n const notes = getNotes()\n .filter(({ title }) => {\n return smartFilter(title, value);\n })\n .filter(({ id, deleted }) => !deleted && id !== url.getPageId())\n .sort((a, b) => {\n const aDateCreated = getDateCreatedFromTitle(a.title);\n const bDateCreated = getDateCreatedFromTitle(b.title);\n return bDateCreated - aDateCreated;\n })\n .map(({ id, title, cid }, i) => {\n const dateCreated = getDateCreatedFromTitle(title);\n const linkParams = cid ? `?cid=${cid}` : \"\";\n const href = `${window.location.origin}${window.location.pathname}#${id}${linkParams}`;\n\n const noteLink = link(\n div({ content: title, highlight: value }),\n href\n );\n\n const noteCommand = command(\n {\n title: noteLink,\n secondary: relativeDate(dateCreated),\n onclick: () => {\n this.hide();\n select(\".terminal\").focus();\n },\n },\n i === indexToSelect\n );\n return noteCommand;\n });\n select(\"#commands\").html(notes);\n select(\"#commander input\").placeholder(\n `Search from ${notes.length} saved notes...`\n );\n state.options = {\n ...state.options,\n length: notes.length,\n };\n return this;\n },\n generateCommands: async function (value = \"\") {\n const indexToSelect = state.options.selected;\n const commandComponents = this.commands()\n .filter(({ title }) => smartFilter(title, value))\n .filter(({ experimental = false }) => {\n return storage.get(\"__experimental__\") ? true : !experimental;\n })\n .map(({ title, key, call, icon }, i) => {\n const commandComponent = command(\n {\n title: div({ content: title, highlight: value }),\n icon: icon,\n secondary: getShortcut(key),\n onclick: call,\n },\n i === indexToSelect\n );\n return commandComponent;\n });\n select(\"#commands\").html(commandComponents);\n state.options = {\n ...state.options,\n length: commandComponents.length,\n };\n return this;\n },\n };\n})();\n\nexport default commander;\n", "import { nanoid } from \"nanoid\";\nimport getCaretCoordinates from \"textarea-caret\";\nimport TrashSVG from \"../../../assets/svg/trash.svg\";\nimport { configuration } from \"../../../configuration\";\nimport { trieDictionary } from \"../../main\";\nimport { setSavedState } from \"../../ui/functions/savedState\";\nimport select from \"../../utils/dom\";\nimport storage from \"../../utils/localstorage\";\nimport { handleErrorResponse } from \"../../utils/mail\";\nimport { autoCompleteCheckboxes } from \"../../utils/text/autoCompleteCheckboxes\";\nimport { div } from \"../atoms/div/div\";\nimport { icon } from \"../atoms/icon/icon\";\nimport { command } from \"../molecules/commands/command\";\nimport notify from \"../molecules/notify\";\nimport commander from \"./commander/commander\";\nimport markDownViewer from \"./markdown/markDownViewer\";\nimport { getNote, getTitle } from \"./noteManager/noteManager\";\n\nconst isLastCharacterInTheWord = (text, characterIndex) =>\n text[characterIndex] === undefined || text[characterIndex].trim() === \"\";\n\nconst placeSuggestion = (textEl) => {\n const coords = getCaretCoordinates(textEl, textEl.selectionEnd);\n const { top, left } = coords;\n\n // This does the trick! `main` is getting the same\n // height as the textarea so the suggestion will be placed\n // right!\n // TODO: change that on terminal size change!\n const actualTerminalHeight = select(\".terminal\").el.scrollHeight;\n const main = select(\"main\").el;\n main.style.height = `${actualTerminalHeight}px`;\n\n select(\".suggestion\").el.style.top = `${top}px`;\n select(\".suggestion\").el.style.left = `${left}px`;\n};\n\nconst getCurrentlyTypingWord = (text, cursorIndexPosition) => {\n let word = \"\";\n let currentIndex = cursorIndexPosition - 1;\n do {\n const character = text[currentIndex] || \"\";\n currentIndex = character.trim() === \"\" ? -1 : currentIndex - 1;\n word = character.trim() !== \"\" ? `${character}${word}` : word;\n } while (currentIndex >= 0);\n return word;\n};\n\nconst getPredictions = (word) => {\n const sanitizedWord = word.replace(/[\\r\\n\\t]+/g, \"\").toLowerCase();\n\n return trieDictionary.getMatchingWords(sanitizedWord);\n};\n\nexport const terminal = (() => {\n const initState = {\n matches: [],\n currentWord: null,\n prediction: null,\n options: {\n selected: 0,\n length: 0,\n },\n };\n let state = initState;\n return {\n el: select(\".terminal\"),\n setState: function (newState) {\n state = {\n ...state,\n ...newState,\n };\n return state;\n },\n resetState: function () {\n terminal.setState(initState);\n },\n selectOption: function (e, direction) {\n const currentlySelected = state.options.selected;\n const lastOption = state.options.length - 1;\n const isLastOption = currentlySelected === lastOption;\n const isFirstOption = currentlySelected === 0;\n const isDown = direction === \"down\";\n\n const indexToSelect = isDown\n ? isLastOption\n ? 0\n : currentlySelected + 1\n : // eslint-disable-next-line prettier/prettier\n isFirstOption ? lastOption : currentlySelected - 1;\n\n state.options = {\n ...state.options,\n selected: indexToSelect,\n };\n\n terminal.setState({\n prediction: state.matches[state.options.selected],\n });\n terminal.renderInlineSuggestion();\n terminal.renderOptions();\n },\n acceptCompletion: (word) => {\n const complete = (word, currentWord) => {\n const completion = word.replace(currentWord.toLowerCase(), \"\");\n if (completion) {\n select(\".terminal\").insertAtCaret(`${completion} `);\n } else {\n select(\".terminal\").insertAtCaret(\" \");\n }\n select(\".suggestion\").hide();\n terminal.resetState();\n };\n\n const { prediction, currentWord } = state;\n\n if (word) {\n return complete(word, currentWord);\n }\n\n if (prediction) {\n complete(prediction, currentWord);\n // +1 to the score of the word autocompleted\n trieDictionary.insert(prediction);\n }\n },\n renderInlineSuggestion: () => {\n const { prediction, currentWord } = state;\n\n const inlineSuggestion = div({\n content: `${prediction.slice(currentWord.length)}`,\n });\n inlineSuggestion.setAttribute(\"id\", \"inlineSuggestion\");\n select(\".suggestion\").show().html(inlineSuggestion);\n },\n renderOptions: () => {\n const optionsUl = select(\".suggestion .options\");\n if (optionsUl && optionsUl.el) optionsUl.el.remove();\n\n const selectedIndex = state.options.selected;\n const options = state.matches.map((word, i) =>\n command(\n {\n title: div({ content: word }),\n secondary: icon(TrashSVG, \"delete word\"),\n onSecondaryClick: () => {\n storage.removeFromDictionary(word);\n terminal.setState({\n matches: state.matches.filter((m) => m !== word),\n });\n terminal.renderOptions();\n },\n onclick: () => {\n terminal.acceptCompletion(word);\n },\n },\n i === selectedIndex\n )\n );\n const optionList = document.createElement(\"ul\");\n optionList.classList.add(\"options\");\n optionList.classList.add(\"frost\");\n options.forEach((el) => optionList.append(el));\n\n select(\".suggestion\").el.append(optionList);\n },\n onFocus: () => {\n commander.hide();\n select(\".note-info\").hide();\n },\n onInput: (e) => {\n const isAutocompleteEnabled = !!storage.get(\"__autocomplete__\");\n if (!isAutocompleteEnabled) return;\n\n const cursorIndexPosition = e.target.selectionEnd;\n const fullText = terminal.el.getValue();\n\n const charTyped = fullText[cursorIndexPosition - 1];\n if (e.inputType === \"deleteContentBackward\" || charTyped === \" \") {\n terminal.setState({\n prediction: initState.prediction,\n currentWord: initState.currentWord,\n });\n return select(\".suggestion\").hide();\n }\n\n const shouldDisplaySuggestion =\n e.inputType === \"insertText\" &&\n isLastCharacterInTheWord(fullText, cursorIndexPosition);\n\n if (shouldDisplaySuggestion) {\n placeSuggestion(e.target);\n const word = getCurrentlyTypingWord(fullText, cursorIndexPosition);\n const matches = getPredictions(word);\n\n const [firstMatch] = matches;\n const prediction = firstMatch || \"\";\n\n terminal.setState({\n prediction,\n currentWord: word,\n matches: matches.slice(0, 10),\n options: {\n selected: 0,\n length: matches.length,\n },\n });\n if (state.currentWord.length > 1 && state.prediction) {\n terminal.renderInlineSuggestion();\n terminal.renderOptions();\n } else {\n select(\".suggestion\").hide();\n }\n }\n },\n onArrowDown: (e) => {\n if (state.matches.length > 0) {\n e.preventDefault();\n terminal.selectOption(e, \"down\");\n }\n },\n onArrowUp: (e) => {\n if (state.matches.length > 0) {\n e.preventDefault();\n terminal.selectOption(e, \"up\");\n }\n },\n setValue: () => {\n // terminal.el.value = \"mpampis\";\n },\n onEnter: (e) => {\n if (state.matches.length > 0) {\n e.preventDefault();\n terminal.acceptCompletion();\n }\n\n // auto-magically handle checkboxes\n autoCompleteCheckboxes(e);\n },\n onEscape: () => {\n terminal.resetState();\n select(\".suggestion\").hide();\n },\n onTab: (e) => {\n e.preventDefault();\n terminal.acceptCompletion();\n },\n onKeyDown: (e) => {\n // enter\n if (e.keyCode === 13) {\n terminal.onEnter(e);\n }\n // arrow down\n if (e.keyCode === 40) {\n terminal.onArrowDown(e);\n }\n\n // arrow up\n if (e.keyCode === 38) {\n terminal.onArrowUp(e);\n }\n\n if (e.keyCode === 9) {\n terminal.onTab(e);\n }\n\n if (e.keyCode === 32) {\n terminal.setState({\n prediction: \"\",\n });\n }\n\n // escape\n if (e.keyCode === 27) {\n terminal.onEscape(e);\n }\n },\n onKeyUp: (e) => {\n const currentlySavedNote = getNote();\n const title = getTitle(e.target.value);\n select(\".title h3\").html(title);\n\n const { text = \"\" } = currentlySavedNote || {};\n const isNoteSaved = currentlySavedNote && terminal.el.getValue() === text;\n setSavedState(isNoteSaved);\n },\n onPaste: async () => {\n const clipboardItems = await navigator.clipboard.read();\n for (const clipboardItem of clipboardItems) {\n const imageTypes = clipboardItem.types?.filter((type) =>\n type.startsWith(\"image/\")\n );\n for (const imageType of imageTypes) {\n const blob = await clipboardItem.getType(imageType);\n const token = storage.get(\"MIROPAD_SECRET_TOKEN\");\n if (token) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [image, fileExtension] = imageType.split(\"/\");\n const fileName = `${nanoid()}.${fileExtension}`;\n\n select(\"#logo\").addClass(\"loading\");\n try {\n const { url } = await fetch(\n `${configuration.file_service.api}?fileName=${fileName}`,\n {\n method: \"POST\",\n headers: {\n \"x-secret-token\": token,\n accept: \"application/json\",\n \"content-type\": \"application/octet-stream\",\n },\n body: blob,\n }\n )\n .then(handleErrorResponse)\n .then((response) => response.json());\n select(\".terminal\").insertAtCaret(`![image](${url})`);\n } catch (error) {\n notify.error(`Uploading file failed \uD83D\uDCA5! Error$ ${error.message}`);\n }\n select(\"#logo\").removeClass(\"loading\");\n } else {\n const imageURI = URL.createObjectURL(blob);\n select(\".terminal\").insertAtCaret(`![image](${imageURI})`);\n }\n markDownViewer.update();\n }\n }\n },\n init: function () {\n this.el\n .listen(\"focus\", this.onFocus)\n .listen(\"input\", this.onInput)\n .listen(\"keydown\", this.onKeyDown)\n .listen(\"keyup\", this.onKeyUp)\n .listen(\"paste\", this.onPaste);\n },\n };\n})();\n", "export const findCurrentLine = (text: string, caretIndex: number): string => {\n const lines = text.split(\"\\n\");\n type MyAcc = {\n text: string;\n isFound: boolean;\n };\n const line = lines.reduce(\n (acc: MyAcc, line) => {\n const { isFound } = acc;\n if (isFound) return acc;\n const recon = `${acc.text}${line}\\n`;\n const currentLength = recon.length;\n\n if (caretIndex >= currentLength) {\n return {\n text: recon,\n isFound: false,\n };\n }\n\n return {\n text: line,\n isFound: true,\n };\n },\n {\n text: \"\",\n isFound: false,\n }\n );\n\n return line.text;\n};\n", "import select from \"../dom\";\nimport { findCurrentLine } from \"./index\";\n\nexport const autoCompleteCheckboxes = (e) => {\n const currentLine = findCurrentLine(e.target.value, e.target.selectionEnd);\n\n const completers = {\n \"* [\": \"\\n* [] \",\n \"* \": \"\\n* \",\n \" * [\": \"\\n * [] \",\n \" * \": \"\\n * \",\n };\n\n for (const [startsWith, compleano] of Object.entries(completers)) {\n if (currentLine.startsWith(startsWith)) {\n e.preventDefault();\n select(\".terminal\").insertAtCaret(compleano);\n break;\n }\n }\n};\n", "import storage from \"./utils/localstorage\";\n\nexport const isSyncEnabled = () => {\n const { authToken, gistId } = storage.get([\"authToken\", \"gistId\"]);\n return !!(authToken && gistId);\n};\n", "const groupByFrequency = (entries: []) => {\n return Object.entries(entries).reduce((acc, [word, frequency]) => {\n const cc = acc[frequency] || [];\n return {\n ...acc,\n [frequency]: [word, ...cc],\n };\n }, {});\n};\n\ntype Node = {\n char: string | null;\n children: {\n [key: string]: Node;\n };\n frequency: number;\n hasChildren: () => boolean;\n isWord: () => boolean;\n contains: (char: string) => boolean;\n getWords: (\n char: string,\n dictionary?: {\n [key: string]: string;\n }\n ) => {\n [key: string]: string;\n };\n increaseFrequency: () => void;\n insert: (word: string) => void;\n insertNode: (char: string, isLast?: boolean) => Node;\n};\n\nconst Node = (): Node => ({\n char: null,\n children: {},\n frequency: 0,\n hasChildren: function () {\n return Object.keys(this.children).length > 0;\n },\n isWord: function () {\n return this.frequency > 0;\n },\n contains: function (char: string) {\n return Object.keys(this.children).includes(char);\n },\n getWords: function (prefix, dictionary = {}) {\n const nodeInstance = this as Node;\n if (nodeInstance.isWord()) {\n dictionary = {\n ...dictionary,\n [prefix]: this.frequency,\n };\n }\n\n if (nodeInstance.hasChildren()) {\n for (const node of Object.values(nodeInstance.children)) {\n dictionary = node.getWords(`${prefix}${node.char}`, dictionary);\n }\n }\n\n return dictionary;\n },\n increaseFrequency: function () {\n this.frequency = this.frequency + 1;\n },\n insert: function (word) {\n const [firstChar, ...rest] = word;\n if (firstChar) {\n const isLast = rest.length === 0;\n if (this.contains(firstChar)) {\n const node = this.children[firstChar];\n node.char = firstChar;\n if (isLast) node.increaseFrequency();\n\n return node.insert(rest);\n } else {\n const node = this.insertNode(firstChar, isLast);\n return node.insert(rest);\n }\n }\n },\n insertNode: function (char, isLast = false) {\n const newNode = Node();\n if (isLast) newNode.increaseFrequency();\n newNode.char = char;\n this.children = {\n ...this.children,\n [char]: newNode,\n };\n return newNode;\n },\n});\n\nexport const Trie = () => {\n const rootNode = Node();\n\n return {\n insert: function (word: string | Array = []) {\n const words = Array.isArray(word) ? word : [word];\n words.forEach((word) => rootNode.insert(word));\n return this;\n },\n search: function (prefix = \"\") {\n let node = rootNode;\n prefix.split(\"\").forEach((character) => {\n if (node) node = node.children[character];\n });\n\n return node ? node.getWords(prefix) : {};\n },\n // get sorted matching words\n // first by frequency\n // and then alphabetically\n getMatchingWords: function (prefix = \"\") {\n const frequencyGroups = groupByFrequency(this.search(prefix));\n return Object.keys(frequencyGroups)\n .sort((a, b) => parseInt(b, 10) - parseInt(a, 10))\n .flatMap((key) => frequencyGroups[key].sort());\n },\n };\n};\n", "import notify from \"../components/molecules/notify\";\n\nconst errorHandler = (error) => {\n const { message = \"Unexpected error occurred!\" } = error;\n notify.error(message);\n};\n\nexport default errorHandler;\n", "import select from \"../utils/dom\";\nimport { ipfs } from \"../repositories/ipfs\";\nimport { setSavedState } from \"../ui/functions/savedState\";\n\nexport const retrieveNoteFromIPFS = async (cid: string) => {\n select(\".anchor\").show();\n\n select(\"#logo\").addClass(\"loading\");\n const remoteNote = await ipfs.retrieve(cid);\n select(\"#logo\").removeClass(\"loading\");\n\n setSavedState(false);\n select(\".terminal\").setValue(remoteNote);\n};\n", "import \"github-markdown-css\";\nimport \"../../css/print.css\";\nimport \"../../css/styles.css\";\nimport { retrieveNoteFromIPFS } from \"../Functions/retrieveNoteFromIPFS\";\nimport notify from \"../components/molecules/notify\";\nimport {\n search,\n setNoteFromHash,\n} from \"../components/organisms/noteManager/noteManager\";\nimport select from \"../utils/dom\";\nimport { url } from \"../utils/urlManager\";\nimport { getGist } from \"../utils/github/api\";\n\nconst setNoteFromRawUrl = async (rawUrl) => {\n if (rawUrl) {\n const response = await fetch(rawUrl).then((response) => {\n if (response.ok) return response.text();\n throw new Error(\n `Remote note could not be retrieved! code: ${response.status}`\n );\n });\n select(\".terminal\").setValue(response);\n }\n};\n\nconst setNoteFromGist = async (gistId) => {\n if (gistId) {\n try {\n const gist = await getGist(gistId);\n const { files } = gist;\n const fileContents = Object.values(files);\n const [gistFile] = fileContents;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const { content } = gistFile;\n select(\".terminal\").setValue(content);\n } catch (error) {\n notify.error(\"MiroPad note not found! \uD83E\uDD37\u200D\u2642\uFE0F\");\n }\n }\n};\n\nexport const actOnURLStateChange = async (e = {}) => {\n try {\n const { oldURL, newURL } = e;\n const oldPageId = url.getPageId(oldURL);\n const newPageId = url.getPageId(newURL);\n const hasPageIdChanged = oldPageId !== newPageId;\n const { v: oldV } = url.getParamsObject(oldURL);\n const { v: newV } = url.getParamsObject(newURL);\n const hasPageVersionChanged = oldV !== newV;\n const shouldChangeNote = [hasPageIdChanged, hasPageVersionChanged].some(\n (r) => r\n );\n if (shouldChangeNote) setNoteFromHash();\n\n const { gistId, raw } = url.getParamsObject(newURL);\n await setNoteFromGist(gistId);\n await setNoteFromRawUrl(raw);\n } catch (e) {\n notify.error(e.message);\n }\n\n const isANewNote = !url.getPageId();\n select(\"#note-info-button\").show(!isANewNote);\n select(\"#new-note\").disable(isANewNote);\n\n if (url.getSearchParam(\"md\") === \"full\") {\n select(\".terminal\").hide();\n } else {\n select(\".terminal\").show();\n }\n\n if (url.getSearchParam(\"zen\") === \"true\") {\n select(\".header\").hide();\n } else {\n select(\".header\").show();\n }\n\n if (url.getSearchParam(\"cid\")) {\n await retrieveNoteFromIPFS(url.getSearchParam(\"cid\"));\n } else {\n select(\".anchor\").hide();\n }\n\n select(\".note-info\").hide();\n\n const q = url.getSearchParam(\"q\");\n const queryResult = search(q);\n if (queryResult) select(\".terminal\").setValue(queryResult.text);\n};\n", "export const isDevelopmentMode = () => {\n // eslint-disable-next-line no-undef\n const env = process.env.NODE_ENV;\n return env === \"development\";\n};\n\nexport const enableDevelopment = () => {\n if (isDevelopmentMode()) {\n new EventSource(\"/esbuild\").addEventListener(\"change\", () =>\n location.reload()\n );\n }\n};\n", "import select from \"../../../utils/dom\";\n\n// This is a feature where you can easily tick on/off\n// checkboxes \u2705 on the Markdown preview.\n// It does NOT persist the state on the data layer,\n// but lives temporarily on the browser's state\n// Useful feature when you are going to the Super market \uD83D\uDE04\n\n// Technically I cloud re-enable the checkboxes that ShowdownJS generates,\n// which are by default disabled, but couldn't figure that out. \u00AF\\_(\u30C4)_/\u00AF\n\nexport const autoMagicallyCheckBoxes = () => {\n select(\".task-list-item\").listenAll(\"click\", (el) => {\n el.firstChild.checked = !el.firstChild.checked;\n });\n};\n", "import \"github-markdown-css\";\nimport \"../css/print.css\";\nimport \"../css/styles.css\";\nimport welcomeUser from \"./components/molecules/welcome\";\nimport commander from \"./components/organisms/commander/commander\";\nimport markDownViewer from \"./components/organisms/markdown/markDownViewer\";\nimport {\n deleteNote,\n disableSyncOnCurrentNote,\n getNote,\n setNoteFromHash,\n} from \"./components/organisms/noteManager/noteManager\";\nimport { terminal } from \"./components/organisms/terminal\";\nimport { isSyncEnabled } from \"./isSyncEnabled\";\nimport { registerServiceWorker } from \"./registerServiceWorker\";\nimport { Trie } from \"./utils/Trie/Trie\";\nimport { copyToClipboard } from \"./utils/copyToClipboard\";\nimport { relativeDate } from \"./utils/dates\";\nimport select from \"./utils/dom\";\nimport errorHandler from \"./utils/errorHandler\";\nimport {\n setAuthTokenFromCallback,\n syncNotesWithGitHub,\n} from \"./utils/github/actions\";\nimport storage from \"./utils/localstorage\";\nimport { resetPageTitle } from \"./utils/pageTitle\";\nimport { url } from \"./utils/urlManager\";\nimport { actOnURLStateChange } from \"./listeners/urlChange\";\nimport { enableDevelopment } from \"./utils/enableDevelopmentTasks\";\nimport { autoMagicallyCheckBoxes } from \"./ui/markdown/preview/autoMagicallyCheckBoxes\";\n\n// Initialize a Trie tree to be used for the predictions\nexport const trieDictionary = Trie();\n\nconst initInfoPanel = () => {\n select(\"#note-info-close\").listen(\"click\", () => {\n select(\".note-info\").hide();\n });\n select(\"#note-info-button\").listen(\"click\", () => {\n const note = getNote();\n select(\".note-info\").show();\n\n select(\".note-info .details\").innerHTML(\n `

    \n \n ${note.title}\n

    \n

    \n \n ${relativeDate(note.dateCreated)}\n

    \n

    \n \n ${note.numberOfRevisions}\n

    \n `\n );\n\n const isSyncOn = isSyncEnabled();\n if (isSyncOn && note) {\n const syncEl = (() => {\n const { disableSync } = note;\n const p = document.createElement(\"P\");\n p.innerHTML = `\n \n \n `;\n return p;\n })();\n select(\".note-info .details\").append(syncEl);\n select(\"#sync\").listen(\"click\", (e) => {\n disableSyncOnCurrentNote(!e.target.checked);\n });\n }\n const deleteButton = (() => {\n const p = document.createElement(\"P\");\n p.innerHTML = `\n \n \n \n \n \n \n \n Delete\n \n `;\n return p;\n })();\n select(\".note-info .details\").append(deleteButton);\n select(\"#delete-note\").listen(\"click\", () => {\n deleteNote();\n });\n });\n};\n\nconst main = async () => {\n // Insert all the saved data from dictionary to the Trie tree\n const words = storage.getDictionary();\n trieDictionary.insert(words);\n\n window.addEventListener(\"error\", errorHandler);\n welcomeUser();\n commander.init();\n\n initInfoPanel();\n\n terminal.init();\n resetPageTitle();\n setNoteFromHash(url.getPageId());\n select(\".logo\").listen(\"click\", () => {\n commander.toggle(commander.getModes().notes);\n });\n select(\"#permalink\").listen(\"click\", async () => {\n await copyToClipboard(url.get());\n });\n\n markDownViewer.init();\n\n window.addEventListener(\"hashchange\", actOnURLStateChange);\n actOnURLStateChange();\n\n registerServiceWorker();\n\n autoMagicallyCheckBoxes();\n\n await syncNotesWithGitHub();\n await setAuthTokenFromCallback();\n\n enableDevelopment();\n};\n\nexport default main;\n", "import main from \"./js/main\";\n\n(() => {\n main();\n})();\n"], + "mappings": "u9CAIA,SAASA,EAAgBC,EAAQ,CAC/B,aAEA,IAAIC,EAAiB,CACnB,wBAAyB,CACvB,aAAc,GACd,SAAU,wDACV,KAAM,SACR,EACA,WAAY,CACV,aAAc,GACd,SAAU,kCACV,KAAM,SACR,EACA,eAAgB,CACd,aAAc,GACd,SAAU,4JACV,KAAM,QACR,EACA,kBAAmB,CACjB,aAAc,GACd,SAAU,uKACV,KAAM,SACR,EACA,qBAAsB,CACpB,aAAc,GACd,SAAU,oIACV,KAAM,SACR,EACA,YAAa,CACX,aAAc,GACd,SAAU,0JACV,KAAM,SACR,EACA,iBAAkB,CAChB,aAAc,GACd,SAAU,gCACV,KAAM,SACR,EACA,mBAAoB,CAClB,aAAc,GACd,SAAU,sCACV,KAAM,SACR,EACA,mBAAoB,CAClB,aAAc,GACd,SAAU,iCACV,KAAM,SACR,EACA,mCAAoC,CAClC,aAAc,GACd,SAAU,sEACV,KAAM,SACR,EACA,0BAA2B,CACzB,aAAc,GACd,SAAU,mDACV,KAAM,SACR,EACA,wBAAyB,CACvB,aAAc,GACd,SAAU,+CACV,KAAM,SACR,EACA,cAAe,CACb,aAAc,GACd,SAAU,oCACV,KAAM,SACR,EACA,OAAQ,CACN,aAAc,GACd,SAAU,6BACV,KAAM,SACR,EACA,eAAgB,CACd,aAAc,GACd,SAAU,6BACV,KAAM,SACR,EACA,aAAc,CACZ,aAAc,GACd,SAAU,6CACV,KAAM,SACR,EACA,UAAW,CACT,aAAc,GACd,SAAU,mCACV,KAAM,SACR,EACA,kBAAmB,CACjB,aAAc,GACd,SAAU,kEACV,KAAM,SACR,EACA,oBAAqB,CACnB,aAAc,GACd,SAAU,kDACV,KAAM,SACR,EACA,qCAAsC,CACpC,aAAc,GACd,SAAU,oEACV,KAAM,SACR,EACA,iBAAkB,CAChB,aAAc,GACd,SAAU,gDACV,KAAM,SACR,EACA,8BAA+B,CAC7B,aAAc,GACd,SAAU,6EACV,KAAM,SACR,EACA,WAAY,CACV,aAAc,GACd,SAAU,2BACV,KAAM,SACR,EACA,eAAgB,CACd,aAAc,yBACd,SAAU,yFACV,KAAM,QACR,EACA,aAAc,CACZ,aAAc,GACd,SAAU,0IACV,KAAM,SACR,EACA,qBAAsB,CACpB,aAAc,GACd,SAAU,gCACV,KAAM,SACR,EACA,yBAA0B,CACxB,aAAc,GACd,SAAU,oDACV,KAAM,SACR,EACA,MAAO,CACL,aAAc,GACd,SAAU,sDACV,KAAM,SACR,EACA,UAAW,CACT,aAAc,GACd,SAAU,gLACV,KAAM,SACR,EACA,SAAU,CACR,aAAc,GACd,SAAU,0DACV,KAAM,SACR,EACA,qBAAsB,CACpB,aAAc,GACd,SAAU,mFACV,KAAM,SACR,EACA,SAAU,CACR,aAAc,GACd,SAAU,kJACV,KAAM,SACR,EACA,yBAA0B,CACxB,aAAc,GACd,SAAU,mCACV,KAAM,SACR,CACF,EACA,GAAID,IAAW,GACb,O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wB,EAExB,MAAMC,GAAoB,EAC1B,MAAMC,GAAyB,EAE/BC,IAAkB,CACpB,EAEOC,IAAQlB,IC9IbmB,IAAK", + "names": ["getDefaultOpts", "simple", "defaultOptions", "ret", "opt", "allOptionsOn", "options", "showdown", "parsers", "extensions", "globalOptions", "setFlavor", "flavor", "key", "value", "name", "preset", "option", "func", "ext", "validExtension", "validate", "extension", "errMsg", "i", "baseMsg", "type", "ln", "validateExtension", "a", "getType", "obj", "callback", "prop", "s", "escapeCharactersCallback", "wholeMatch", "m1", "charCodeToEscape", "text", "charsToEscape", "afterBackslash", "regexString", "regex", "txt", "rgxFindMatchPos", "str", "left", "right", "flags", "f", "g", "x", "l", "pos", "t", "m", "start", "end", "matchPos", "results", "replacement", "repStr", "finalStr", "lng", "bits", "fromIndex", "indexOf", "index", "mail", "encode", "ch", "r", "targetLength", "padString", "msg", "converterOptions", "langExtensions", "outputModifiers", "listeners", "setConvFlavor", "metadata", "_constructor", "gOpt", "_parseExtension", "legacyExtensionLoading", "validExt", "listen", "valid", "rTrimInputText", "rsp", "rgx", "evtName", "globals", "ei", "nText", "src", "HTMLParser", "doc", "substitutePreCodeTags", "clean", "nodes", "mdDoc", "node", "n", "child", "pres", "presPH", "content", "language", "classes", "c", "matches", "extensionName", "ii", "raw", "format", "writeAnchorTag", "linkText", "linkId", "url", "m5", "m6", "title", "result", "wm", "st", "escape", "mentions", "username", "lnk", "target", "simpleURLRegex", "simpleURLRegex2", "delimUrlRegex", "simpleMailRegex", "delimMailRegex", "replaceLink", "leadingMagicChars", "link", "m2", "m3", "trailingPunctuation", "trailingMagicChars", "lnkTxt", "append", "lmc", "tmc", "replaceMail", "b", "href", "bq", "pre", "pattern", "codeblock", "nextChar", "doctype", "doctypeParsed", "charset", "lang", "meta", "leadingText", "numSpaces", "emojiRgx", "emojiCode", "tags", "comments", "delim", "repFunc", "match", "blockText", "blockTags", "inside", "opTagPos", "rgx1", "patLeft", "patRight", "subTexts", "newSubText1", "hashHTMLSpan", "html", "repText", "limit", "num", "headerLevelStart", "setextRegexH1", "setextRegexH2", "spanGamut", "hID", "headerId", "hLevel", "hashBlock", "matchFound", "atxStyle", "hText", "span", "header", "prefix", "inlineRegExp", "crazyRegExp", "base64RegExp", "referenceRegExp", "refShortcutRegExp", "writeImageTagBase64", "altText", "width", "height", "writeImageTag", "gUrls", "gTitles", "gDims", "parseInside", "lead", "processListItems", "listStr", "trimTrailing", "isParagraphed", "m4", "taskbtn", "checked", "item", "bulletStyle", "otp", "wm2", "styleStartNumber", "list", "listType", "res", "parseConsecutiveLists", "olRgx", "ulRgx", "counterRxg", "parseCL", "style", "parseMetadataContents", "wholematch", "grafs", "grafsOut", "grafsOutIt", "codeFlag", "re", "base64Regex", "replaceFunc", "blankLines", "tableRgx", "singeColTblRgx", "parseStyles", "sLine", "parseHeaders", "id", "parseCells", "cell", "subText", "buildTable", "headers", "cells", "tb", "tblLgn", "parseTable", "rawTable", "tableLines", "rawHeaders", "rawStyles", "rawCells", "styles", "row", "charCodeToReplace", "children", "childrenLength", "innerTxt", "headerLevel", "headerMark", "listItems", "listItemsLenght", "listNum", "bullet", "listItemTxt", "childrenLenght", "spansOnly", "tagName", "tableArray", "headings", "rows", "headContent", "allign", "cols", "cellContent", "cellSpacesCount", "strLen", "root", "module", "require_is_plain_obj", "__commonJSMin", "exports", "module", "value", "prototype", "require_merge_options", "__commonJSMin", "exports", "module", "isOptionObject", "hasOwnProperty", "propertyIsEnumerable", "defineProperty", "object", "name", "value", "globalThis", "defaultMergeOptions", "getEnumerableOwnPropertyKeys", "keys", "key", "symbols", "symbol", "clone", "cloneArray", "cloneOptionObject", "array", "result", "mergeKeys", "merged", "source", "config", "merge", "concatArrays", "resultIndex", "indices", "k", "options", "option", "require_is_electron", "__commonJSMin", "exports", "module", "isElectron", "require_env", "__commonJSMin", "exports", "module", "isElectron", "IS_ENV_WITH_DOM", "IS_ELECTRON", "IS_BROWSER", "IS_ELECTRON_MAIN", "IS_ELECTRON_RENDERER", "IS_NODE", "__require", "IS_WEBWORKER", "IS_TEST", "IS_REACT_NATIVE", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "require_err_code", "__commonJSMin", "exports", "module", "assign", "obj", "props", "key", "createError", "err", "code", "ErrClass", "require_aspromise", "__commonJSMin", "exports", "module", "asPromise", "fn", "ctx", "params", "offset", "index", "pending", "resolve", "reject", "err", "require_base64", "__commonJSMin", "exports", "base64", "string", "p", "b64", "s64", "i", "buffer", "start", "end", "parts", "chunk", "j", "t", "b", "invalidEncoding", "offset", "require_eventemitter", "__commonJSMin", "exports", "module", "EventEmitter", "evt", "fn", "ctx", "listeners", "args", "require_float", "__commonJSMin", "exports", "module", "factory", "f32", "f8b", "le", "writeFloat_f32_cpy", "val", "buf", "pos", "writeFloat_f32_rev", "readFloat_f32_cpy", "readFloat_f32_rev", "writeFloat_ieee754", "writeUint", "sign", "exponent", "mantissa", "writeUintLE", "writeUintBE", "readFloat_ieee754", "readUint", "uint", "readUintLE", "readUintBE", "f64", "writeDouble_f64_cpy", "writeDouble_f64_rev", "readDouble_f64_cpy", "readDouble_f64_rev", "writeDouble_ieee754", "off0", "off1", "readDouble_ieee754", "lo", "hi", "require_inquire", "__commonJSMin", "e", "require_utf8", "__commonJSMin", "exports", "utf8", "string", "len", "c", "buffer", "start", "end", "parts", "chunk", "i", "t", "offset", "c1", "c2", "require_pool", "__commonJSMin", "exports", "module", "pool", "alloc", "slice", "size", "SIZE", "MAX", "slab", "offset", "buf", "require_longbits", "__commonJSMin", "exports", "module", "LongBits", "util", "lo", "hi", "zero", "zeroHash", "value", "sign", "unsigned", "charCodeAt", "hash", "mask", "part0", "part1", "part2", "require_minimal", "__commonJSMin", "exports", "util", "value", "obj", "prop", "Buffer", "sizeOrArray", "hash", "unsigned", "bits", "merge", "dst", "src", "ifNotSet", "keys", "str", "newError", "name", "CustomError", "message", "properties", "fieldNames", "fieldMap", "i", "encoding", "size", "require_writer", "__commonJSMin", "exports", "module", "Writer", "util", "BufferWriter", "LongBits", "base64", "utf8", "Op", "fn", "len", "val", "noop", "State", "writer", "create", "size", "writeByte", "buf", "pos", "writeVarint32", "VarintOp", "value", "writeVarint64", "bits", "writeFixed32", "writeBytes", "head", "tail", "BufferWriter_", "require_writer_buffer", "__commonJSMin", "exports", "module", "BufferWriter", "Writer", "util", "val", "buf", "pos", "value", "len", "writeStringBuffer", "require_reader", "__commonJSMin", "exports", "module", "Reader", "util", "BufferReader", "LongBits", "utf8", "indexOutOfRange", "reader", "writeLength", "buffer", "create_array", "create", "value", "readLongVarint", "bits", "i", "readFixed32_end", "buf", "end", "readFixed64", "length", "start", "bytes", "wireType", "BufferReader_", "fn", "require_reader_buffer", "__commonJSMin", "exports", "module", "BufferReader", "Reader", "util", "buffer", "len", "require_service", "__commonJSMin", "exports", "module", "Service", "util", "rpcImpl", "requestDelimited", "responseDelimited", "rpcCall", "method", "requestCtor", "responseCtor", "request", "callback", "self", "err", "response", "endedByRPC", "require_rpc", "__commonJSMin", "exports", "rpc", "require_roots", "__commonJSMin", "exports", "module", "require_index_minimal", "__commonJSMin", "exports", "protobuf", "configure", "require_minimal", "__commonJSMin", "exports", "module", "require_time_browser", "__commonJSMin", "exports", "module", "require_retimer", "__commonJSMin", "exports", "module", "getTime", "Retimer", "callback", "timeout", "args", "that", "now", "retimer", "i", "require_timeout_abort_controller", "__commonJSMin", "exports", "module", "AbortController", "retimer", "TimeoutController", "ms", "require_url_browser", "__commonJSMin", "exports", "module", "isReactNative", "getDefaultBase", "URL", "defaultBase", "URLWithLegacySupport", "url", "base", "hash", "host", "hostname", "href", "password", "pathname", "port", "protocol", "search", "username", "o", "format", "obj", "userPass", "auth", "path", "require_relative", "__commonJSMin", "exports", "module", "URLWithLegacySupport", "format", "url", "location", "protocolMap", "defaultProtocol", "protocol", "urlParsed", "base", "require_iso_url", "__commonJSMin", "exports", "module", "URLWithLegacySupport", "format", "URLSearchParams", "defaultBase", "relative", "require_any_signal", "__commonJSMin", "exports", "module", "anySignal", "signals", "controller", "onAbort", "signal", "require_hashlru", "__commonJSMin", "exports", "module", "max", "size", "cache", "_cache", "update", "key", "value", "v", "require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "i", "length", "j", "require_error", "__commonJSMin", "exports", "TimeoutError", "message", "AbortError", "HTTPError", "response", "require_browser", "__commonJSMin", "exports", "module", "getGlobal", "globalObject", "require_src", "__commonJSMin", "exports", "module", "require_fetch_browser", "__commonJSMin", "exports", "module", "require_fetch_browser", "__commonJSMin", "exports", "module", "TimeoutError", "AbortError", "Response", "Request", "Headers", "fetch", "fetchWithProgress", "url", "options", "request", "timeout", "headers", "name", "value", "resolve", "reject", "handleEvent", "event", "ResponseWithURL", "parseHeaders", "fetchWithStreaming", "fetchWith", "input", "line", "index", "body", "require_browser_readablestream_to_it", "__commonJSMin", "exports", "module", "browserReadableStreamToIt", "stream", "options", "reader", "result", "require_it_all", "__commonJSMin", "exports", "module", "all", "source", "arr", "entry", "require_http", "__commonJSMin", "exports", "module", "fetch", "Request", "Headers", "TimeoutError", "HTTPError", "merge", "URL", "URLSearchParams", "anySignal", "browserReableStreamToIt", "isBrowser", "isWebWorker", "all", "timeout", "promise", "ms", "abortController", "start", "timedOut", "resolve", "reject", "timeoutID", "after", "next", "res", "defaults", "HTTP", "options", "resource", "opts", "headers", "url", "searchParams", "transformSearchParams", "json", "signal", "response", "fromStream", "chunk", "ndjson", "source", "decoder", "buf", "lines", "i", "l", "isAsyncIterable", "isNodeReadableStream", "iter", "value", "isWebReadableStream", "reader", "done", "require_timestamp_min", "__commonJSMin", "exports", "module", "Timestamp", "d", "l", "s", "T", "e", "f", "c", "g", "h", "u", "m", "n", "t", "o", "r", "p", "y", "M", "C", "D", "a", "i", "v", "w", "require_forge", "__commonJSMin", "exports", "module", "require_baseN", "__commonJSMin", "exports", "module", "api", "_reverseAlphabets", "input", "alphabet", "maxline", "output", "_encodeWithByteBuffer", "base", "first", "digits", "j", "carry", "regex", "table", "i", "bytes", "value", "k", "require_util", "__commonJSMin", "exports", "module", "forge", "baseN", "util", "callback", "handler", "event", "msg", "copy", "callbacks", "now", "attr", "div", "oldSetImmediate", "x", "_checkBitsParam", "n", "ByteStringBuffer", "b", "arr", "i", "_MAX_CONSTRUCTED_STRING_LENGTH", "d", "bytes", "str", "buffer", "rval", "max", "count", "c", "len", "DataBuffer", "options", "isArrayBuffer", "isArrayBufferView", "amount", "growSize", "src", "dst", "encoding", "view", "input", "s", "s1", "s2", "s3", "t", "hex", "_base64", "_base64Idx", "_base58", "maxline", "line", "output", "chr1", "chr2", "chr3", "enc1", "enc2", "enc3", "enc4", "offset", "out", "j", "k", "api", "raw", "start", "flg", "_setStorageObject", "id", "obj", "error", "_getStorageObject", "_setItem", "key", "data", "_getItem", "_removeItem", "empty", "prop", "_clearItems", "_callStorageFunction", "func", "args", "location", "type", "done", "exception", "idx", "ex", "format", "re", "match", "part", "argi", "parts", "last", "code", "number", "decimals", "dec_point", "thousands_sep", "size", "ip", "num", "blanks", "e", "zeros", "zeroGroups", "zeroMaxGroup", "group", "blobUrl", "st", "et", "sample", "samples", "numWorkers", "avg", "map", "err", "results", "reduce", "workers", "worker", "overlaps", "r1", "overlap", "r2", "require_oids", "__commonJSMin", "exports", "module", "forge", "oids", "_IN", "id", "name", "_I_", "require_asn1", "__commonJSMin", "exports", "module", "forge", "asn1", "tagClass", "type", "constructed", "value", "options", "tmp", "i", "obj", "copy", "obj1", "obj2", "equal", "b", "b2", "length", "longForm", "_checkBufferLength", "bytes", "remaining", "n", "error", "_getValueLength", "longFormBytes", "byteCount", "_fromDer", "depth", "start", "b1", "bitStringContents", "savedRead", "savedRemaining", "unused", "subOptions", "composed", "used", "tc", "asn1Options", "useBitStringContents", "len", "lenBytes", "oid", "values", "last", "valueBytes", "utc", "date", "year", "MM", "DD", "hh", "mm", "ss", "end", "hhoffset", "mmoffset", "offset", "gentime", "YYYY", "fff", "isUTC", "c", "rval", "format", "x", "v", "capture", "errors", "j", "_nonLatinRegex", "level", "indentation", "indent", "subvalues", "sub", "e", "require_cipher", "__commonJSMin", "exports", "module", "forge", "algorithm", "key", "api", "name", "BlockCipher", "options", "opts", "input", "pad", "output", "require_cipherModes", "__commonJSMin", "exports", "module", "forge", "modes", "options", "input", "output", "finish", "i", "padding", "len", "count", "transformIV", "inputLength", "partialBytes", "inc32", "iv", "additionalData", "ivLength", "from64To32", "overflow", "rval", "lengths", "tag", "x", "y", "z_i", "v_i", "x_i", "out", "lsb", "z", "idx", "ah", "h", "bits", "multiplier", "perInt", "size", "m", "tmp", "shft", "mid", "half", "j", "m_i", "m_j", "c", "blockSize", "ints", "blocks", "block", "num", "require_aes", "__commonJSMin", "exports", "module", "forge", "key", "iv", "output", "mode", "cipher", "_createCipher", "name", "init", "initialize", "self", "inBlock", "outBlock", "_updateBlock", "options", "tmp", "i", "len", "encryptOp", "_expandKey", "decrypt", "registerAlgorithm", "factory", "Nb", "sbox", "isbox", "rcon", "mix", "imix", "xtime", "e", "ei", "e2", "e4", "e8", "sx", "sx2", "me", "ime", "n", "w", "temp", "iNk", "Nk", "Nr1", "end", "m0", "m1", "m2", "m3", "wnew", "wi", "input", "Nr", "sub", "a", "b", "c", "a2", "b2", "c2", "round", "algorithm", "start", "require_des", "__commonJSMin", "exports", "module", "forge", "key", "iv", "output", "mode", "cipher", "_createCipher", "name", "self", "inBlock", "outBlock", "_updateBlock", "options", "_createKeys", "registerAlgorithm", "factory", "spfunction1", "spfunction2", "spfunction3", "spfunction4", "spfunction5", "spfunction6", "spfunction7", "spfunction8", "pc2bytes0", "pc2bytes1", "pc2bytes2", "pc2bytes3", "pc2bytes4", "pc2bytes5", "pc2bytes6", "pc2bytes7", "pc2bytes8", "pc2bytes9", "pc2bytes10", "pc2bytes11", "pc2bytes12", "pc2bytes13", "iterations", "keys", "shifts", "n", "tmp", "j", "left", "right", "i", "lefttmp", "righttmp", "input", "decrypt", "looping", "endloop", "loopinc", "right1", "right2", "algorithm", "start", "require_md", "__commonJSMin", "exports", "module", "forge", "require_hmac", "__commonJSMin", "exports", "module", "forge", "hmac", "_key", "_md", "_ipadding", "_opadding", "ctx", "md", "key", "tmp", "i", "keylen", "bytes", "inner", "require_pbkdf2", "__commonJSMin", "exports", "module", "forge", "pkcs5", "crypto", "p", "s", "c", "dkLen", "md", "callback", "err", "key", "hLen", "len", "r", "prf", "dk", "xor", "u_c", "u_c1", "i", "j", "outer", "inner", "require_pem", "__commonJSMin", "exports", "module", "forge", "pem", "msg", "options", "rval", "header", "foldHeader", "str", "rMessage", "rHeader", "rCRLF", "match", "type", "lines", "li", "line", "nl", "next", "values", "vi", "ltrim", "insertSpace", "$1", "length", "candidate", "insert", "require_sha256", "__commonJSMin", "exports", "module", "forge", "sha256", "_initialized", "_init", "_state", "_input", "_w", "md", "int32s", "i", "msg", "encoding", "len", "_update", "finalBlock", "remaining", "overflow", "_padding", "next", "carry", "bits", "s2", "rval", "_k", "s", "w", "bytes", "t1", "t2", "s0", "s1", "ch", "maj", "a", "b", "c", "e", "f", "g", "h", "require_prng", "__commonJSMin", "exports", "module", "forge", "_crypto", "prng", "plugin", "ctx", "md", "pools", "count", "callback", "cipher", "increment", "formatKey", "formatSeed", "b", "generate", "err", "_reseed", "bytes", "_reseedSync", "_seed", "needed", "_2powK", "k", "seedBytes", "defaultSeedFile", "getRandomValues", "globalScope", "arr", "entropy", "i", "e", "hi", "lo", "next", "seed", "n", "x", "worker", "listener", "data", "require_random", "__commonJSMin", "exports", "module", "forge", "jQuery", "prng_aes", "_prng_aes_output", "_prng_aes_buffer", "key", "tmp", "seed", "spawnPrng", "ctx", "count", "callback", "_ctx", "getRandomValues", "globalScope", "_crypto", "arr", "_navBytes", "e", "require_rc2", "__commonJSMin", "exports", "module", "forge", "piTable", "s", "rol", "word", "bits", "ror", "key", "effKeyBits", "L", "T", "T1", "T8", "TM", "i", "createCipher", "encrypt", "_finish", "_input", "_output", "_iv", "mixRound", "mashRound", "j", "K", "R", "runPlan", "plan", "val", "ptr", "ctr", "cipher", "iv", "output", "input", "pad", "rval", "padding", "len", "count", "require_jsbn", "__commonJSMin", "exports", "module", "forge", "dbits", "canary", "j_lm", "BigInteger", "a", "b", "c", "nbi", "am1", "i", "x", "w", "j", "n", "v", "am2", "xl", "xh", "l", "h", "m", "am3", "BI_FP", "BI_RM", "BI_RC", "rr", "vv", "int2char", "intAt", "s", "bnpCopyTo", "bnpFromInt", "nbv", "r", "bnpFromString", "k", "mi", "sh", "bnpClamp", "bnToString", "km", "d", "p", "bnNegate", "bnAbs", "bnCompareTo", "nbits", "bnBitLength", "bnpDLShiftTo", "bnpDRShiftTo", "bnpLShiftTo", "bs", "cbs", "bm", "ds", "bnpRShiftTo", "bnpSubTo", "bnpMultiplyTo", "y", "bnpSquareTo", "bnpDivRemTo", "q", "pm", "pt", "ts", "ms", "nsh", "ys", "y0", "yt", "d1", "d2", "e", "t", "qd", "bnMod", "Classic", "cConvert", "cRevert", "cReduce", "cMulTo", "cSqrTo", "bnpInvDigit", "Montgomery", "montConvert", "montRevert", "montReduce", "u0", "montSqrTo", "montMulTo", "bnpIsEven", "bnpExp", "z", "r2", "g", "bnModPowInt", "bnClone", "bnIntValue", "bnByteValue", "bnShortValue", "bnpChunkSize", "bnSigNum", "bnpToRadix", "cs", "bnpFromRadix", "bnpFromNumber", "op_or", "bnToByteArray", "bnEquals", "bnMin", "bnMax", "bnpBitwiseTo", "op", "f", "op_and", "bnAnd", "bnOr", "op_xor", "bnXor", "op_andnot", "bnAndNot", "bnNot", "bnShiftLeft", "bnShiftRight", "lbit", "bnGetLowestSetBit", "cbit", "bnBitCount", "bnTestBit", "bnpChangeBit", "bnSetBit", "bnClearBit", "bnFlipBit", "bnpAddTo", "bnAdd", "bnSubtract", "bnMultiply", "bnDivide", "bnRemainder", "bnDivideAndRemainder", "bnpDMultiply", "bnpDAddOffset", "NullExp", "nNop", "nMulTo", "nSqrTo", "bnPow", "bnpMultiplyLowerTo", "bnpMultiplyUpperTo", "Barrett", "barrettConvert", "barrettRevert", "barrettReduce", "barrettSqrTo", "barrettMulTo", "bnModPow", "k1", "g2", "is1", "bnGCD", "bnpModInt", "bnModInverse", "ac", "u", "lowprimes", "lplim", "bnIsProbablePrime", "bnpMillerRabin", "n1", "prng", "bnGetPrng", "require_sha1", "__commonJSMin", "exports", "module", "forge", "sha1", "_initialized", "_init", "_state", "_input", "_w", "md", "int32s", "i", "msg", "encoding", "len", "_update", "finalBlock", "remaining", "overflow", "_padding", "next", "carry", "bits", "s2", "rval", "s", "w", "bytes", "t", "a", "b", "c", "d", "e", "f", "require_pkcs1", "__commonJSMin", "exports", "module", "forge", "pkcs1", "key", "message", "options", "label", "seed", "md", "mgf1Md", "keyLength", "maxLength", "error", "lHash", "PS", "PS_length", "i", "DB", "dbMask", "rsa_mgf1", "maskedDB", "seedMask", "maskedSeed", "em", "y", "db", "lHashPrime", "in_ps", "index", "j", "code", "is_0", "error_mask", "maskLength", "hash", "t", "count", "c", "require_prime", "__commonJSMin", "exports", "module", "forge", "prime", "BigInteger", "GCD_30_DELTA", "THIRTY", "op_or", "x", "y", "bits", "options", "callback", "algorithm", "prng", "rng", "b", "i", "primeincFindPrime", "primeincFindPrimeWithWorkers", "primeincFindPrimeWithoutWorkers", "num", "generateRandom", "deltaIdx", "mrTests", "getMillerRabinTests", "maxBlockTime", "_primeinc", "start", "numWorkers", "workLoad", "range", "workerScript", "err", "cores", "generate", "workers", "running", "workerMessage", "found", "e", "data", "hex", "bits1", "require_rsa", "__commonJSMin", "exports", "module", "forge", "BigInteger", "_crypto", "asn1", "util", "pki", "GCD_30_DELTA", "privateKeyValidator", "rsaPrivateKeyValidator", "rsaPublicKeyValidator", "publicKeyValidator", "digestInfoValidator", "emsaPkcs1v15encode", "md", "oid", "error", "oidBytes", "digestInfo", "digestAlgorithm", "digest", "_modPow", "x", "key", "pub", "r", "xp", "xq", "y", "m", "bt", "eb", "k", "_encodePkcs1_v1_5", "yhex", "ed", "zeros", "ml", "xhex", "_decodePkcs1_v1_5", "bits", "options", "prng", "rng", "b", "i", "algorithm", "rval", "state", "n", "THIRTY", "deltaIdx", "op_or", "t1", "t2", "total", "bits1", "_getMillerRabinTests", "d", "callback", "_detectNodeCrypto", "err", "priv", "_detectSubtleCrypto", "_intToUint8Array", "pair", "pkcs8", "privateKey", "_detectSubtleMsCrypto", "genOp", "e", "exportOp", "keypair", "_generateKeyPair", "data", "scheme", "schemeOptions", "signature", "obj", "capture", "errors", "p", "q", "dP", "dQ", "qInv", "rsaKey", "_bnToBytes", "padNum", "padByte", "numZeros", "padBytes", "em", "first", "zero", "opts", "generate", "getPrime", "num", "finish", "tmp", "hex", "bytes", "fn", "buffer", "require_pbe", "__commonJSMin", "exports", "module", "forge", "BigInteger", "asn1", "pki", "oids", "encryptedPrivateKeyValidator", "PBES2AlgorithmsValidator", "pkcs12PbeParamsValidator", "obj", "password", "options", "salt", "count", "countBytes", "dkLen", "encryptionAlgorithm", "encryptedData", "ivLen", "encOid", "cipherFn", "error", "prfAlgorithm", "md", "prfAlgorithmToMessageDigest", "dk", "iv", "cipher", "params", "createPbkdf2Params", "saltBytes", "rval", "capture", "errors", "oid", "encrypted", "epki", "maxline", "msg", "pem", "rsaKey", "algorithm", "key", "id", "iter", "n", "j", "l", "u", "v", "result", "passBuf", "p", "s", "D", "Slen", "S", "Plen", "P", "I", "c", "i", "buf", "round", "B", "k", "Inew", "chunk", "x", "prfOidToMessageDigest", "dIvLen", "digests", "hash", "length", "bytes", "prfOid", "factory", "require_sha512", "__commonJSMin", "exports", "module", "forge", "sha512", "sha384", "algorithm", "_initialized", "_init", "_states", "_state", "_h", "_input", "_w", "wi", "digestLength", "md", "int32s", "i", "msg", "encoding", "len", "_update", "finalBlock", "remaining", "overflow", "_padding", "next", "carry", "bits", "h", "rval", "hlen", "_k", "s", "w", "bytes", "t1_hi", "t1_lo", "t2_hi", "t2_lo", "s0_hi", "s0_lo", "s1_hi", "s1_lo", "ch_hi", "ch_lo", "maj_hi", "maj_lo", "a_hi", "a_lo", "b_hi", "b_lo", "c_hi", "c_lo", "d_hi", "d_lo", "e_hi", "e_lo", "f_hi", "f_lo", "g_hi", "g_lo", "h_hi", "h_lo", "hi", "lo", "w2", "w7", "w15", "w16", "require_longbits", "__commonJSMin", "exports", "module", "LongBits", "util", "lo", "hi", "zero", "zeroHash", "value", "sign", "unsigned", "charCodeAt", "hash", "mask", "part0", "part1", "part2", "require_minimal", "__commonJSMin", "exports", "util", "value", "obj", "prop", "Buffer", "sizeOrArray", "hash", "unsigned", "bits", "merge", "dst", "src", "ifNotSet", "keys", "str", "newError", "name", "CustomError", "message", "properties", "fieldNames", "fieldMap", "i", "encoding", "size", "require_reader", "__commonJSMin", "exports", "module", "Reader", "util", "BufferReader", "LongBits", "utf8", "indexOutOfRange", "reader", "writeLength", "buffer", "create_array", "create", "value", "readLongVarint", "bits", "i", "readFixed32_end", "buf", "end", "readFixed64", "length", "start", "nativeBuffer", "bytes", "wireType", "BufferReader_", "fn", "require_reader_buffer", "__commonJSMin", "exports", "module", "BufferReader", "Reader", "util", "buffer", "len", "require_writer", "__commonJSMin", "exports", "module", "Writer", "util", "BufferWriter", "LongBits", "base64", "utf8", "Op", "fn", "len", "val", "noop", "State", "writer", "create", "size", "writeByte", "buf", "pos", "writeVarint32", "VarintOp", "value", "writeVarint64", "bits", "writeFixed32", "writeBytes", "head", "tail", "BufferWriter_", "require_writer_buffer", "__commonJSMin", "exports", "module", "BufferWriter", "Writer", "util", "val", "buf", "pos", "value", "len", "writeStringBuffer", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "obj", "key", "def", "p", "undef", "split", "length", "require_is_domain_name", "__commonJSMin", "exports", "module", "domainNameRegex", "domainName", "rootDot", "lastChar", "require_encode", "__commonJSMin", "exports", "module", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "require_decode", "__commonJSMin", "exports", "module", "read", "MSB", "REST", "buf", "offset", "res", "shift", "counter", "b", "l", "require_length", "__commonJSMin", "exports", "module", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "value", "require_varint", "__commonJSMin", "exports", "module", "require_murmurHash3js", "__commonJSMin", "exports", "module", "root", "undefined", "library", "_validBytes", "bytes", "i", "_x86Multiply", "m", "n", "_x86Rotl", "_x86Fmix", "h", "_x64Add", "o", "_x64Multiply", "_x64Rotl", "_x64LeftShift", "_x64Xor", "_x64Fmix", "seed", "remainder", "blocks", "h1", "k1", "c1", "c2", "h2", "h3", "h4", "k2", "k3", "k4", "c3", "c4", "require_murmurhash3js_revisited", "__commonJSMin", "exports", "module", "require_rabin", "__commonJSMin", "exports", "module", "Rabin", "asModule", "bits", "min", "max", "windowSize", "polynomial", "buf", "__retain", "__release", "__allocArray", "__getInt32Array", "Int32Array_ID", "Uint8Array_ID", "lengths", "lengthsPtr", "pointer", "out", "processed", "end", "require_loader", "__commonJSMin", "exports", "BIGINT", "THIS", "CHUNKSIZE", "getStringImpl", "buffer", "ptr", "U32", "U16", "length", "offset", "parts", "last", "size", "preInstantiate", "imports", "baseModule", "getString", "memory", "env", "mesg", "file", "line", "colm", "n", "postInstantiate", "instance", "rawExports", "table", "alloc", "retain", "rttiBase", "getInfo", "id", "count", "getBase", "getValueAlign", "info", "getKeyAlign", "__allocString", "str", "i", "p", "__getString", "getView", "alignLog2", "signed", "float", "__allocArray", "values", "align", "buf", "arr", "view", "__getArrayView", "__getArray", "input", "len", "out", "__getArrayBuffer", "getTypedArray", "Type", "getTypedArrayView", "bufPtr", "__instanceof", "baseId", "demangle", "isResponse", "o", "instantiate", "source", "instantiateStreaming", "instantiateSync", "module", "setArgumentsLength", "internalName", "elem", "curr", "part", "name", "hash", "className", "classElem", "ctor", "args", "thisValue", "getter", "setter", "value", "require_rabin_wasm", "__commonJSMin", "exports", "module", "instantiate", "loadWebAssembly", "imp", "wasm", "require_src", "__commonJSMin", "exports", "module", "Rabin", "getRabin", "create", "avg", "min", "max", "windowSize", "polynomial", "compiled", "require_sparse_array", "__commonJSMin", "exports", "module", "index", "value", "pos", "needsSort", "last", "iterator", "i", "mapped", "reducer", "initialValue", "acc", "finder", "found", "noCreate", "bytePos", "byte", "bitPos", "previousPopCount", "popCountReduce", "mask", "bytePopCount", "popCount", "targetLength", "data", "elem", "randomIndex", "sortInternal", "bytes", "pendingBitsForResultingByte", "pendingBitsForNewByte", "resultingByte", "newByte", "pending", "usingBits", "masked", "valueOnly", "count", "_v", "v", "a", "b", "require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "i", "length", "j", "require_index_browser", "__commonJSMin", "exports", "module", "require_fnv1a", "__commonJSMin", "exports", "module", "hash", "s", "h", "l", "i", "require_bytes", "__commonJSMin", "exports", "module", "bytes", "format", "parse", "formatThousandsRegExp", "formatDecimalsRegExp", "map", "parseRegExp", "value", "options", "mag", "thousandsSeparator", "unitSeparator", "decimalPlaces", "fixedDecimals", "unit", "val", "str", "s", "i", "results", "floatValue", "require_level_supports", "__commonJSMin", "exports", "manifests", "manifest", "acc", "m", "require_module_error", "__commonJSMin", "exports", "module", "message", "options", "require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_ieee754", "__commonJSMin", "exports", "buffer", "offset", "isLE", "mLen", "nBytes", "e", "m", "eLen", "eMax", "eBias", "nBits", "i", "d", "s", "value", "rt", "require_buffer", "__commonJSMin", "exports", "base64", "ieee754", "customInspectSymbol", "Buffer", "SlowBuffer", "K_MAX_LENGTH", "typedArraySupport", "arr", "proto", "createBuffer", "length", "buf", "arg", "encodingOrOffset", "allocUnsafe", "from", "value", "fromString", "fromArrayView", "isInstance", "fromArrayBuffer", "valueOf", "b", "fromObject", "assertSize", "size", "alloc", "fill", "encoding", "checked", "string", "byteLength", "actual", "fromArrayLike", "array", "i", "arrayView", "copy", "byteOffset", "obj", "len", "numberIsNaN", "a", "x", "y", "list", "buffer", "pos", "mustMatch", "loweredCase", "utf8ToBytes", "base64ToBytes", "slowToString", "start", "end", "hexSlice", "utf8Slice", "asciiSlice", "latin1Slice", "base64Slice", "utf16leSlice", "swap", "n", "m", "str", "max", "target", "thisStart", "thisEnd", "thisCopy", "targetCopy", "bidirectionalIndexOf", "val", "dir", "arrayIndexOf", "indexSize", "arrLength", "valLength", "read", "foundIndex", "found", "j", "hexWrite", "offset", "remaining", "strLen", "parsed", "utf8Write", "blitBuffer", "asciiWrite", "asciiToBytes", "base64Write", "ucs2Write", "utf16leToBytes", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "ret", "out", "hexSliceLookupTable", "bytes", "newBuf", "checkOffset", "ext", "noAssert", "mul", "defineBigIntMethod", "validateNumber", "first", "last", "boundsError", "lo", "hi", "checkInt", "min", "maxBytes", "wrtBigUInt64LE", "checkIntBI", "wrtBigUInt64BE", "limit", "sub", "checkIEEE754", "writeFloat", "littleEndian", "writeDouble", "targetStart", "code", "errors", "E", "sym", "getMessage", "Base", "name", "range", "input", "msg", "received", "addNumericalSeparator", "checkBounds", "type", "INVALID_BASE64_RE", "base64clean", "units", "leadSurrogate", "byteArray", "c", "src", "dst", "alphabet", "table", "i16", "fn", "BufferBigIntNotDefined", "require_text_endec", "__commonJSMin", "exports", "module", "lazy", "require_encoding", "__commonJSMin", "exports", "ModuleError", "formats", "Encoding", "options", "require_formats", "__commonJSMin", "exports", "Buffer", "Encoding", "textEndec", "BufferFormat", "options", "ViewFormat", "data", "view", "UTF8Format", "textEncoder", "textDecoder", "require_encodings", "__commonJSMin", "exports", "Buffer", "textEncoder", "textDecoder", "BufferFormat", "ViewFormat", "UTF8Format", "identity", "v", "data", "buffer", "require_level_transcoder", "__commonJSMin", "exports", "ModuleError", "encodings", "Encoding", "BufferFormat", "ViewFormat", "UTF8Format", "kFormats", "kEncodings", "validFormats", "Transcoder", "formats", "f", "k", "err", "encoding", "resolved", "lookup", "from", "name", "format", "options", "maybeType", "anonymousCount", "detectFormat", "aliases", "require_events", "__commonJSMin", "exports", "module", "R", "ReflectApply", "target", "receiver", "args", "ReflectOwnKeys", "ProcessEmitWarning", "warning", "NumberIsNaN", "value", "EventEmitter", "once", "defaultMaxListeners", "checkListener", "listener", "arg", "n", "_getMaxListeners", "that", "type", "i", "doError", "events", "er", "err", "handler", "len", "listeners", "arrayClone", "_addListener", "prepend", "m", "existing", "w", "onceWrapper", "_onceWrap", "state", "wrapped", "list", "position", "originalListener", "spliceOne", "keys", "key", "_listeners", "unwrap", "evlistener", "unwrapListeners", "emitter", "listenerCount", "arr", "copy", "index", "ret", "name", "resolve", "reject", "errorListener", "resolver", "eventTargetAgnosticAddListener", "addErrorHandlerIfEventEmitter", "flags", "wrapListener", "require_next_tick_browser", "__commonJSMin", "exports", "module", "fn", "require_catering", "__commonJSMin", "exports", "nextTick", "callback", "symbol", "promise", "resolve", "reject", "err", "res", "require_common", "__commonJSMin", "exports", "options", "callback", "def", "require_abstract_iterator", "__commonJSMin", "exports", "fromCallback", "ModuleError", "getOptions", "getCallback", "kPromise", "kCallback", "kWorking", "kHandleOne", "kHandleMany", "kAutoClose", "kFinishWork", "kReturnMany", "kClosing", "kHandleClose", "kClosed", "kCloseCallbacks", "kKeyEncoding", "kValueEncoding", "kAbortOnClose", "kLegacy", "kKeys", "kValues", "kLimit", "kCount", "emptyOptions", "noop", "warnedEnd", "CommonIterator", "db", "options", "legacy", "hint", "callback", "promise", "resolve", "reject", "err", "key", "value", "size", "acc", "onnext", "count", "nextv", "onnextv", "items", "cb", "target", "keyEncoding", "keyFormat", "mapped", "callbacks", "item", "AbstractIterator", "IteratorDecodeError", "entries", "entry", "AbstractKeyIterator", "keys", "AbstractValueIterator", "values", "subject", "cause", "k", "require_default_kv_iterator", "__commonJSMin", "exports", "AbstractKeyIterator", "AbstractValueIterator", "kIterator", "kCallback", "kHandleOne", "kHandleMany", "DefaultKeyIterator", "db", "options", "DefaultValueIterator", "Iterator", "keys", "mapEntry", "entry", "callback", "err", "key", "value", "size", "entries", "target", "require_deferred_iterator", "__commonJSMin", "exports", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "ModuleError", "kNut", "kUndefer", "kFactory", "DeferredIterator", "db", "options", "DeferredKeyIterator", "DeferredValueIterator", "Iterator", "callback", "size", "target", "require_abstract_chained_batch", "__commonJSMin", "exports", "fromCallback", "ModuleError", "getCallback", "getOptions", "kPromise", "kStatus", "kOperations", "kFinishClose", "kCloseCallbacks", "AbstractChainedBatch", "db", "hint", "key", "value", "options", "err", "original", "keyEncoding", "valueEncoding", "keyFormat", "mappedKey", "mappedValue", "callback", "callbacks", "cb", "require_default_chained_batch", "__commonJSMin", "exports", "AbstractChainedBatch", "ModuleError", "kEncoded", "DefaultChainedBatch", "db", "key", "value", "options", "callback", "require_range_options", "__commonJSMin", "exports", "module", "ModuleError", "hasOwnProperty", "rangeOptions", "options", "keyEncoding", "result", "k", "require_queue_microtask", "__commonJSMin", "exports", "module", "promise", "cb", "err", "require_next_tick_browser", "__commonJSMin", "exports", "module", "queueMicrotask", "fn", "args", "require_abstract_sublevel_iterator", "__commonJSMin", "exports", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "kUnfix", "kIterator", "kHandleOne", "kHandleMany", "kCallback", "AbstractSublevelIterator", "db", "options", "iterator", "unfix", "err", "key", "value", "callback", "entries", "entry", "AbstractSublevelKeyIterator", "keys", "AbstractSublevelValueIterator", "Iterator", "size", "target", "require_abstract_sublevel", "__commonJSMin", "exports", "module", "ModuleError", "Buffer", "AbstractSublevelIterator", "AbstractSublevelKeyIterator", "AbstractSublevelValueIterator", "kPrefix", "kUpperBound", "kPrefixRange", "kParent", "kUnfix", "textEncoder", "defaults", "AbstractLevel", "AbstractSublevel", "options", "db", "name", "separator", "manifest", "forward", "trim", "reserved", "parent", "x", "mergeManifests", "prefix", "upperBound", "MultiFormat", "Unfixer", "key", "keyFormat", "view", "result", "buffer", "range", "callback", "value", "keys", "operations", "iterator", "unfix", "supportsEncoding", "encoding", "prefixLength", "str", "char", "start", "end", "require_abstract_level", "__commonJSMin", "exports", "supports", "Transcoder", "EventEmitter", "fromCallback", "ModuleError", "AbstractIterator", "DefaultKeyIterator", "DefaultValueIterator", "DeferredIterator", "DeferredKeyIterator", "DeferredValueIterator", "DefaultChainedBatch", "getCallback", "getOptions", "rangeOptions", "kPromise", "kLanded", "kResources", "kCloseResources", "kOperations", "kUndefer", "kDeferOpen", "kOptions", "kStatus", "kDefaultOptions", "kTranscoder", "kKeyEncoding", "kValueEncoding", "noop", "AbstractLevel", "manifest", "options", "keyEncoding", "valueEncoding", "passive", "forward", "formats", "encoding", "callback", "maybeOpened", "err", "maybeClosed", "cancel", "pending", "sync", "next", "resource", "key", "maybeError", "keyFormat", "valueFormat", "value", "keys", "mappedKeys", "i", "values", "mappedKey", "mappedValue", "operations", "mapped", "ke", "ve", "op", "db", "valueErr", "name", "AbstractSublevel", "original", "fn", "k", "require_abstract_level", "__commonJSMin", "exports", "require_run_parallel_limit", "__commonJSMin", "exports", "module", "runParallelLimit", "queueMicrotask", "tasks", "limit", "cb", "results", "len", "pending", "keys", "isErrored", "isSync", "next", "done", "err", "end", "each", "i", "result", "key", "task", "require_key_range", "__commonJSMin", "exports", "module", "options", "lower", "upper", "lowerExclusive", "upperExclusive", "require_deserialize", "__commonJSMin", "exports", "module", "textEncoder", "data", "require_iterator", "__commonJSMin", "exports", "AbstractIterator", "createKeyRange", "deserialize", "kCache", "kFinished", "kOptions", "kCurrentOptions", "kPosition", "kLocation", "kFirst", "emptyOptions", "Iterator", "db", "location", "options", "size", "callback", "keyRange", "transaction", "store", "entries", "method", "ev", "cursor", "key", "value", "maybeCommit", "keys", "values", "complete", "length", "i", "err", "cache", "target", "require_clear", "__commonJSMin", "exports", "module", "db", "location", "keyRange", "options", "callback", "transaction", "store", "count", "method", "direction", "ev", "cursor", "require_browser_level", "__commonJSMin", "exports", "AbstractLevel", "ModuleError", "parallel", "fromCallback", "Iterator", "deserialize", "clear", "createKeyRange", "DEFAULT_PREFIX", "kIDB", "kNamePrefix", "kLocation", "kVersion", "kStore", "kOnComplete", "kPromise", "BrowserLevel", "location", "options", "_", "prefix", "version", "forward", "callback", "req", "ev", "db", "mode", "request", "transaction", "key", "store", "err", "value", "keys", "tasks", "next", "operations", "index", "error", "loop", "op", "keyRange", "require_browser", "__commonJSMin", "exports", "require_longbits", "__commonJSMin", "exports", "module", "LongBits", "util", "lo", "hi", "zero", "zeroHash", "value", "sign", "unsigned", "charCodeAt", "hash", "mask", "part0", "part1", "part2", "require_minimal", "__commonJSMin", "exports", "util", "value", "obj", "prop", "Buffer", "sizeOrArray", "hash", "unsigned", "bits", "merge", "dst", "src", "ifNotSet", "keys", "str", "newError", "name", "CustomError", "message", "properties", "fieldNames", "fieldMap", "i", "encoding", "size", "require_writer", "__commonJSMin", "exports", "module", "Writer", "util", "BufferWriter", "LongBits", "base64", "utf8", "Op", "fn", "len", "val", "noop", "State", "writer", "create", "size", "writeByte", "buf", "pos", "writeVarint32", "VarintOp", "value", "writeVarint64", "bits", "writeFixed32", "writeBytes", "head", "tail", "BufferWriter_", "require_writer_buffer", "__commonJSMin", "exports", "module", "BufferWriter", "Writer", "util", "val", "buf", "pos", "value", "len", "writeStringBuffer", "require_reader", "__commonJSMin", "exports", "module", "Reader", "util", "BufferReader", "LongBits", "utf8", "indexOutOfRange", "reader", "writeLength", "buffer", "create_array", "create", "value", "readLongVarint", "bits", "i", "readFixed32_end", "buf", "end", "readFixed64", "length", "start", "bytes", "wireType", "BufferReader_", "fn", "require_reader_buffer", "__commonJSMin", "exports", "module", "BufferReader", "Reader", "util", "buffer", "len", "require_service", "__commonJSMin", "exports", "module", "Service", "util", "rpcImpl", "requestDelimited", "responseDelimited", "rpcCall", "method", "requestCtor", "responseCtor", "request", "callback", "self", "err", "response", "endedByRPC", "require_rpc", "__commonJSMin", "exports", "rpc", "require_roots", "__commonJSMin", "exports", "module", "require_index_minimal", "__commonJSMin", "exports", "protobuf", "configure", "require_minimal", "__commonJSMin", "exports", "module", "require_rpc", "__commonJSMin", "exports", "module", "global", "factory", "__require", "$protobuf", "$Reader", "$Writer", "$util", "$root", "RPC", "p", "ks", "i", "$oneOfFields", "m", "w", "r", "l", "c", "t", "d", "o", "j", "SubOpts", "Message", "ControlMessage", "ControlIHave", "ControlIWant", "ControlGraft", "ControlPrune", "PeerInfo", "require_denque", "__commonJSMin", "exports", "module", "Denque", "array", "options", "index", "i", "len", "item", "head", "tail", "size", "k", "count", "removed", "del_count", "temp", "arg_len", "arguments_index", "leng", "fullCopy", "newArray", "list", "require_source", "__commonJSMin", "exports", "module", "readable", "reader", "done", "value", "require_url_source", "__commonJSMin", "exports", "module", "HTTP", "urlSource", "url", "options", "readURLContent", "require_random_browser", "__commonJSMin", "exports", "module", "randomBytes", "size", "bytes", "generated", "require_delay", "__commonJSMin", "exports", "module", "randomInteger", "minimum", "maximum", "createAbortError", "error", "createDelay", "defaultClear", "set", "willResolve", "ms", "value", "signal", "timeoutId", "settle", "rejectFn", "clear", "signalListener", "cleanup", "delayPromise", "resolve", "reject", "createWithTimers", "clearAndSet", "delay", "options", "require_src", "__commonJSMin", "exports", "module", "intervals", "_generateId", "_runPeriodically", "task", "interval", "id", "err", "resolve", "_timeout", "setDelayedInterval", "delay", "clearDelayedInterval", "require_RateLimiterAbstract", "__commonJSMin", "exports", "module", "opts", "value", "options", "key", "rlKey", "require_BlockedKeys", "__commonJSMin", "exports", "module", "now", "key", "sec", "ms", "expire", "require_BlockedKeys", "__commonJSMin", "exports", "module", "BlockedKeys", "require_RateLimiterRes", "__commonJSMin", "exports", "module", "remainingPoints", "msBeforeNext", "consumedPoints", "isFirstInDuration", "ms", "p", "value", "require_RateLimiterStoreAbstract", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "BlockedKeys", "RateLimiterRes", "opts", "value", "resolve", "reject", "rlKey", "changedPoints", "storeResult", "options", "res", "blockPromise", "err", "delay", "funcName", "key", "data", "secDuration", "msDuration", "points", "pointsToConsume", "inMemoryBlockMsBeforeExpire", "initPoints", "forceExpire", "require_RateLimiterRedis", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "incrTtlLuaScript", "RateLimiterRedis", "opts", "rlKey", "changedPoints", "result", "consumed", "resTtlMs", "res", "points", "msDuration", "forceExpire", "resolve", "reject", "secDuration", "multi", "err", "incrCallback", "require_RateLimiterMongo", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "getDriverVersion", "client", "_client", "version", "_v", "v", "RateLimiterMongo", "opts", "conn", "value", "obj", "collection", "rlKey", "changedPoints", "result", "res", "doc", "key", "points", "msDuration", "forceExpire", "options", "docAttrs", "where", "upsertData", "upsertOptions", "resolve", "reject", "errUpsert", "replaceWhere", "replaceTo", "errReplace", "err", "require_RateLimiterMySQL", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMySQL", "opts", "cb", "err", "expire", "resolve", "conn", "reject", "errConn", "errDb", "value", "rlKey", "changedPoints", "result", "res", "row", "key", "points", "msDuration", "forceExpire", "errBegin", "dateNow", "newExpire", "q", "values", "errUpsert", "errSelect", "require_RateLimiterPostgres", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterPostgres", "opts", "cb", "err", "expire", "resolve", "q", "conn", "reject", "value", "constructorName", "rlKey", "changedPoints", "result", "res", "row", "queryObj", "key", "points", "msDuration", "forceExpire", "newExpire", "expireQ", "require_Record", "__commonJSMin", "exports", "module", "value", "expiresAt", "timeoutId", "require_MemoryStorage", "__commonJSMin", "exports", "module", "Record", "RateLimiterRes", "key", "value", "durationSec", "msBeforeExpires", "durationMs", "require_RateLimiterMemory", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "MemoryStorage", "RateLimiterRes", "RateLimiterMemory", "opts", "key", "pointsToConsume", "options", "resolve", "reject", "rlKey", "secDuration", "res", "delay", "points", "msDuration", "initPoints", "require_RateLimiterCluster", "__commonJSMin", "exports", "module", "cluster", "crypto", "RateLimiterAbstract", "RateLimiterMemory", "RateLimiterRes", "channel", "masterInstance", "masterSendToWorker", "worker", "msg", "type", "res", "data", "workerWaitInit", "payload", "workerSendToMaster", "func", "promiseId", "key", "arg", "opts", "masterProcessMsg", "promise", "rejRes", "workerProcessMsg", "getOpts", "savePromise", "resolve", "reject", "hrtime", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "pm2", "err", "pm2Bus", "packet", "sendErr", "msgData", "pm2Message", "RateLimiterClusterWorker", "value", "pointsToConsume", "options", "points", "secDuration", "require_RateLimiterMemcache", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMemcache", "opts", "rlKey", "changedPoints", "result", "res", "points", "msDuration", "forceExpire", "options", "resolve", "reject", "nowMs", "secDuration", "err", "consumedPoints", "errAddKey", "createdNew", "nextOptions", "resUpsert", "errUpsert", "errGetExpire", "resGetExpireMs", "expireMs", "errDelExpire", "require_RLWrapperBlackAndWhite", "__commonJSMin", "exports", "module", "RateLimiterRes", "opts", "value", "func", "key", "pointsToConsume", "res", "secDuration", "points", "require_RateLimiterUnion", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "limiters", "limiter", "key", "points", "resolve", "reject", "promises", "rej", "res", "resObj", "rejected", "item", "i", "require_RateLimiterQueueError", "__commonJSMin", "exports", "module", "message", "extra", "require_RateLimiterQueue", "__commonJSMin", "exports", "module", "RateLimiterQueueError", "MAX_QUEUE_SIZE", "KEY_DEFAULT", "limiterFlexible", "opts", "RateLimiterQueueInternal", "key", "tokens", "rlRes", "_this", "resolve", "reject", "res", "rej", "item", "require_BurstyRateLimiter", "__commonJSMin", "exports", "module", "RateLimiterRes", "rateLimiter", "burstLimiter", "rlRes", "blRes", "key", "pointsToConsume", "options", "rlRej", "blRej", "require_rate_limiter_flexible", "__commonJSMin", "exports", "module", "RateLimiterRedis", "RateLimiterMongo", "RateLimiterMySQL", "RateLimiterPostgres", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "RateLimiterCluster", "RateLimiterMemory", "RateLimiterMemcache", "RLWrapperBlackAndWhite", "RateLimiterUnion", "RateLimiterQueue", "BurstyRateLimiter", "RateLimiterRes", "require_netmask", "__commonJSMin", "exports", "Netmask", "atob", "chr", "chr0", "chrA", "chra", "ip2long", "long2ip", "long", "a", "b", "c", "d", "ip", "i", "j", "n", "ref", "s", "base", "dmax", "start", "net", "mask", "error", "error1", "count", "fn", "index", "lastLong", "require_ipaddr", "__commonJSMin", "exports", "module", "root", "ipv4Part", "ipv4Regexes", "octalRegex", "hexRegex", "zoneIndex", "ipv6Part", "ipv6Regexes", "expandIPv6", "string", "parts", "colonCount", "lastColon", "zoneId", "replacement", "replacementCount", "ref", "results", "i", "matchCIDR", "first", "second", "partSize", "cidrBits", "part", "shift", "parseIntAuto", "padPart", "length", "ipaddr", "IPv4", "octets", "octet", "other", "cidrRange", "cidr", "stop", "zerotable", "zeros", "ipInterfaceOctets", "subnetMaskOctets", "match", "maskLength", "parsed", "value", "prefix", "j", "filledOctetCount", "IPv6", "bytes", "addr", "suffix", "high", "low", "regex", "bestMatchIndex", "bestMatchLength", "e", "address", "rangeList", "defaultName", "rangeName", "rangeSubnets", "subnet", "require_truncate", "__commonJSMin", "exports", "module", "isHighSurrogate", "codePoint", "isLowSurrogate", "getLength", "string", "byteLength", "charLength", "curByteLength", "segment", "i", "require_browser", "__commonJSMin", "exports", "module", "isHighSurrogate", "codePoint", "isLowSurrogate", "string", "charLength", "byteLength", "prevCodePoint", "i", "require_browser", "__commonJSMin", "exports", "module", "truncate", "getLength", "require_sanitize_filename", "__commonJSMin", "exports", "module", "truncate", "illegalRe", "controlRe", "reservedRe", "windowsReservedRe", "windowsTrailingRe", "sanitize", "input", "replacement", "sanitized", "options", "output", "require_pkcs7asn1", "__commonJSMin", "exports", "module", "forge", "asn1", "p7v", "contentInfoValidator", "encryptedContentInfoValidator", "signerValidator", "require_mgf1", "__commonJSMin", "exports", "module", "forge", "mgf1", "md", "mgf", "seed", "maskLen", "t", "len", "i", "c", "require_mgf", "__commonJSMin", "exports", "module", "forge", "require_pss", "__commonJSMin", "exports", "module", "forge", "pss", "options", "hash", "mgf", "hLen", "salt_", "sLen", "prng", "pssobj", "md", "modBits", "i", "emBits", "emLen", "mHash", "salt", "m_", "h", "ps", "db", "maskLen", "dbMask", "maskedDB", "mask", "em", "checkLen", "h_", "require_x509", "__commonJSMin", "exports", "module", "forge", "asn1", "pki", "oids", "_shortNames", "publicKeyValidator", "x509CertificateValidator", "rsassaPssParameterValidator", "certificationRequestInfoValidator", "certificationRequestValidator", "rdn", "md", "rval", "set", "attr", "obj", "si", "i", "attributes", "seq", "type", "values", "vi", "ei", "_getAttribute", "options", "_readSignatureParameters", "oid", "fillDefaults", "params", "capture", "errors", "error", "_createSignatureDigest", "_verifySignature", "cert", "scheme", "hash", "mgf", "pem", "computeHash", "strict", "msg", "maxline", "key", "bytes", "digest", "hex", "csr", "sn", "_fillMissingFields", "attrs", "uniqueId", "exts", "_fillMissingExtensionFields", "ext", "algorithmOid", "child", "issuer", "subject", "tbsCertificate", "parent", "s", "iattr", "sattr", "n", "ski", "serial", "validity", "imd", "ibytes", "smd", "sbytes", "extseq", "ev", "b2", "b3", "value", "gn", "altName", "cri", "_dnToAsn1", "valueTagClass", "e", "unused", "keyIdentifier", "authorityCertIssuer", "serialNumber", "subSeq", "fullNameGeneralNames", "_signatureParametersToAsn1", "parts", "_CRIAttributesToAsn1", "valueConstructed", "jan_1_1950", "jan_1_2050", "_dateToAsn1", "date", "notBefore", "notAfter", "tbs", "dn", "certs", "caStore", "getBySubject", "ensureSubjectHasHash", "tmp", "match", "der1", "der2", "certList", "result", "chain", "validityCheckDate", "first", "depth", "selfSigned", "parents", "verified", "se", "bcExt", "keyUsageExt", "pathLen", "vfd", "ret", "require_pkcs7", "__commonJSMin", "exports", "module", "forge", "asn1", "p7", "pem", "msg", "error", "obj", "maxline", "pemObj", "capture", "errors", "contentType", "_fromAsn1", "certs", "i", "crls", "signedData", "signer", "issuer", "serialNumber", "cert", "key", "digestAlgorithm", "authenticatedAttributes", "messageDigest", "attr", "options", "content", "mds", "addDigestAlgorithmIds", "addSignerInfos", "crl", "oid", "bytes", "signingTime", "attrsAsn1", "ai", "_attributeToAsn1", "_signersToAsn1", "_decryptContent", "_recipientsFromAsn1", "_recipientsToAsn1", "_encryptedContentToAsn1", "sAttr", "r", "rAttr", "match", "j", "recipient", "privKey", "cipher", "keyLen", "ivLen", "ciphFn", "ciph", "_recipientFromAsn1", "_recipientToAsn1", "infos", "ret", "recipients", "_signerToAsn1", "rval", "signers", "value", "jan_1_1950", "jan_1_2050", "date", "timestamp", "ec", "validator", "require_receptacle", "__commonJSMin", "exports", "module", "Receptacle", "toMS", "cache", "counter", "getUID", "options", "item", "ttl", "i", "key", "record", "value", "oldRecord", "ms", "items", "require_fixed_size", "__commonJSMin", "exports", "module", "hwm", "data", "last", "require_fast_fifo", "__commonJSMin", "exports", "module", "FixedFIFO", "hwm", "val", "prev", "next", "require_p_defer", "__commonJSMin", "exports", "module", "pDefer", "deferred", "resolve", "reject", "require_p_fifo", "__commonJSMin", "exports", "module", "Fifo", "defer", "chunk", "promise", "resolve", "nextConsumer", "nextChunk", "require_safe_buffer", "__commonJSMin", "exports", "module", "buffer", "Buffer", "copyProps", "src", "dst", "key", "SafeBuffer", "arg", "encodingOrOffset", "length", "size", "fill", "encoding", "buf", "require_browser", "__commonJSMin", "exports", "module", "MAX_BYTES", "MAX_UINT32", "oldBrowser", "Buffer", "crypto", "randomBytes", "size", "cb", "bytes", "generated", "require_k_bucket", "__commonJSMin", "exports", "module", "randomBytes", "EventEmitter", "arrayEquals", "array1", "array2", "i", "length", "createNode", "ensureInt8", "name", "val", "KBucket", "options", "incumbent", "candidate", "firstId", "secondId", "distance", "min", "max", "contact", "bitIndex", "node", "index", "id", "n", "contacts", "nodes", "detNode", "a", "b", "count", "bytesDescribedByBitIndex", "bitIndexWithinByte", "otherNode", "result", "selection", "require_ipaddr", "__commonJSMin", "exports", "module", "root", "ipv4Part", "ipv4Regexes", "octalRegex", "hexRegex", "zoneIndex", "ipv6Part", "ipv6Regexes", "expandIPv6", "string", "parts", "colonCount", "lastColon", "zoneId", "replacement", "replacementCount", "ref", "results", "i", "matchCIDR", "first", "second", "partSize", "cidrBits", "part", "shift", "parseIntAuto", "padPart", "length", "ipaddr", "IPv4", "octets", "octet", "other", "cidrRange", "cidr", "stop", "zerotable", "zeros", "ipInterfaceOctets", "subnetMaskOctets", "match", "maskLength", "parsed", "value", "prefix", "j", "filledOctetCount", "IPv6", "bytes", "addr", "suffix", "high", "low", "regex", "bestMatchIndex", "bestMatchLength", "e", "address", "rangeList", "defaultName", "rangeName", "rangeSubnets", "subnet", "require_event_iterator", "__commonJSMin", "exports", "EventQueue", "value", "resolution", "placeholder", "error", "rejection", "result", "resolve", "reject", "EventIterator", "listen", "highWaterMark", "lowWaterMark", "queue", "event", "fn", "require_dom", "__commonJSMin", "exports", "event_iterator_1", "subscribe", "event", "options", "evOptions", "push", "require_RateLimiterAbstract", "__commonJSMin", "exports", "module", "opts", "value", "options", "key", "rlKey", "require_BlockedKeys", "__commonJSMin", "exports", "module", "now", "key", "sec", "ms", "expire", "require_BlockedKeys", "__commonJSMin", "exports", "module", "BlockedKeys", "require_RateLimiterRes", "__commonJSMin", "exports", "module", "remainingPoints", "msBeforeNext", "consumedPoints", "isFirstInDuration", "ms", "p", "value", "require_RateLimiterStoreAbstract", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "BlockedKeys", "RateLimiterRes", "opts", "value", "resolve", "reject", "rlKey", "changedPoints", "storeResult", "options", "res", "blockPromise", "err", "delay", "funcName", "key", "data", "secDuration", "msDuration", "points", "pointsToConsume", "inMemoryBlockMsBeforeExpire", "initPoints", "forceExpire", "require_RateLimiterRedis", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "incrTtlLuaScript", "RateLimiterRedis", "opts", "rlKey", "changedPoints", "result", "consumed", "resTtlMs", "res", "points", "msDuration", "forceExpire", "resolve", "reject", "secDuration", "multi", "err", "incrCallback", "require_RateLimiterMongo", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "getDriverVersion", "client", "_client", "version", "_v", "v", "RateLimiterMongo", "opts", "conn", "value", "obj", "collection", "rlKey", "changedPoints", "result", "res", "doc", "key", "points", "msDuration", "forceExpire", "options", "docAttrs", "where", "upsertData", "upsertOptions", "resolve", "reject", "errUpsert", "replaceWhere", "replaceTo", "errReplace", "err", "require_RateLimiterMySQL", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMySQL", "opts", "cb", "err", "expire", "resolve", "conn", "reject", "errConn", "errDb", "value", "rlKey", "changedPoints", "result", "res", "row", "key", "points", "msDuration", "forceExpire", "errBegin", "dateNow", "newExpire", "q", "values", "errUpsert", "errSelect", "require_RateLimiterPostgres", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterPostgres", "opts", "cb", "err", "expire", "resolve", "q", "conn", "reject", "value", "constructorName", "rlKey", "changedPoints", "result", "res", "row", "queryObj", "key", "points", "msDuration", "forceExpire", "newExpire", "expireQ", "require_Record", "__commonJSMin", "exports", "module", "value", "expiresAt", "timeoutId", "require_MemoryStorage", "__commonJSMin", "exports", "module", "Record", "RateLimiterRes", "key", "value", "durationSec", "msBeforeExpires", "durationMs", "require_RateLimiterMemory", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "MemoryStorage", "RateLimiterRes", "RateLimiterMemory", "opts", "key", "pointsToConsume", "options", "resolve", "reject", "rlKey", "secDuration", "res", "delay", "points", "msDuration", "initPoints", "require_RateLimiterCluster", "__commonJSMin", "exports", "module", "cluster", "crypto", "RateLimiterAbstract", "RateLimiterMemory", "RateLimiterRes", "channel", "masterInstance", "masterSendToWorker", "worker", "msg", "type", "res", "data", "workerWaitInit", "payload", "workerSendToMaster", "func", "promiseId", "key", "arg", "opts", "masterProcessMsg", "promise", "rejRes", "workerProcessMsg", "getOpts", "savePromise", "resolve", "reject", "hrtime", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "pm2", "err", "pm2Bus", "packet", "sendErr", "msgData", "pm2Message", "RateLimiterClusterWorker", "value", "pointsToConsume", "options", "points", "secDuration", "require_RateLimiterMemcache", "__commonJSMin", "exports", "module", "RateLimiterStoreAbstract", "RateLimiterRes", "RateLimiterMemcache", "opts", "rlKey", "changedPoints", "result", "res", "points", "msDuration", "forceExpire", "options", "resolve", "reject", "nowMs", "secDuration", "err", "consumedPoints", "errAddKey", "createdNew", "nextOptions", "resUpsert", "errUpsert", "errGetExpire", "resGetExpireMs", "expireMs", "errDelExpire", "require_RLWrapperBlackAndWhite", "__commonJSMin", "exports", "module", "RateLimiterRes", "opts", "value", "func", "key", "pointsToConsume", "res", "secDuration", "points", "require_RateLimiterUnion", "__commonJSMin", "exports", "module", "RateLimiterAbstract", "limiters", "limiter", "key", "points", "resolve", "reject", "promises", "rej", "res", "resObj", "rejected", "item", "i", "require_RateLimiterQueueError", "__commonJSMin", "exports", "module", "message", "extra", "require_RateLimiterQueue", "__commonJSMin", "exports", "module", "RateLimiterQueueError", "MAX_QUEUE_SIZE", "KEY_DEFAULT", "limiterFlexible", "opts", "RateLimiterQueueInternal", "key", "tokens", "rlRes", "_this", "resolve", "reject", "res", "rej", "item", "require_BurstyRateLimiter", "__commonJSMin", "exports", "module", "RateLimiterRes", "rateLimiter", "burstLimiter", "rlRes", "blRes", "key", "pointsToConsume", "options", "rlRej", "blRej", "require_rate_limiter_flexible", "__commonJSMin", "exports", "module", "RateLimiterRedis", "RateLimiterMongo", "RateLimiterMySQL", "RateLimiterPostgres", "RateLimiterClusterMaster", "RateLimiterClusterMasterPM2", "RateLimiterCluster", "RateLimiterMemory", "RateLimiterMemcache", "RLWrapperBlackAndWhite", "RateLimiterUnion", "RateLimiterQueue", "BurstyRateLimiter", "RateLimiterRes", "isSerializableHash", "h", "exports", "select", "subject", "resultIfOne", "resultIfZero", "exports", "lessOrEqual", "a", "b", "compare", "result", "i", "equal", "wipe", "array", "i", "exports", "hash_1", "constant_time_1", "wipe_1", "HMAC", "hash", "key", "pad", "data", "out", "savedState", "exports", "hmac", "h", "digest", "hmac_1", "wipe_1", "HKDF", "hash", "key", "salt", "info", "okm", "ctr", "length", "out", "i", "exports", "QUOTA", "BrowserRandomSource", "browserCrypto", "length", "out", "i", "exports", "wipe_1", "NodeRandomSource", "__require", "nodeCrypto", "length", "buffer", "out", "exports", "browser_1", "node_1", "SystemRandomSource", "length", "exports", "imulShim", "a", "b", "ah", "al", "bh", "bl", "exports", "add", "sub", "rotl", "x", "n", "rotr", "isIntegerShim", "int_1", "readInt16BE", "array", "offset", "exports", "readUint16BE", "readInt16LE", "readUint16LE", "writeUint16BE", "value", "out", "writeUint16LE", "readInt32BE", "readUint32BE", "readInt32LE", "readUint32LE", "writeUint32BE", "writeUint32LE", "readInt64BE", "hi", "lo", "readUint64BE", "readInt64LE", "readUint64LE", "writeUint64BE", "writeUint64LE", "readUintBE", "bitLength", "result", "mul", "i", "readUintLE", "writeUintBE", "div", "writeUintLE", "readFloat32BE", "view", "readFloat32LE", "readFloat64BE", "readFloat64LE", "writeFloat32BE", "writeFloat32LE", "writeFloat64BE", "writeFloat64LE", "system_1", "binary_1", "wipe_1", "exports", "randomBytes", "length", "prng", "randomUint32", "buf", "result", "ALPHANUMERIC", "randomString", "charset", "out", "charsLen", "maxByte", "i", "randomByte", "randomStringForEntropy", "bits", "random_1", "wipe_1", "exports", "gf", "init", "r", "i", "_9", "_121665", "car25519", "o", "c", "v", "sel25519", "p", "q", "b", "t", "pack25519", "n", "m", "j", "unpack25519", "add", "a", "sub", "mul", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10", "t11", "t12", "t13", "t14", "t15", "t16", "t17", "t18", "t19", "t20", "t21", "t22", "t23", "t24", "t25", "t26", "t27", "t28", "t29", "t30", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10", "b11", "b12", "b13", "b14", "b15", "square", "inv25519", "inp", "scalarMult", "z", "x", "d", "e", "f", "x32", "x16", "scalarMultBase", "generateKeyPairFromSeed", "seed", "secretKey", "generateKeyPair", "prng", "result", "sharedKey", "mySecretKey", "theirPublicKey", "rejectZero", "zeros", "binary_1", "wipe_1", "exports", "SHA256", "data", "dataLength", "dataPos", "hashBlocks", "out", "bytesHashed", "left", "bitLenHi", "bitLenLo", "padLength", "i", "savedState", "K", "w", "v", "p", "pos", "len", "a", "b", "c", "d", "e", "f", "g", "j", "u", "t1", "t2", "hash", "h", "digest", "binary_1", "wipe_1", "ROUNDS", "core", "out", "input", "key", "j0", "j1", "j2", "j3", "j4", "j5", "j6", "j7", "j8", "j9", "j10", "j11", "j12", "j13", "j14", "j15", "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "i", "streamXOR", "nonce", "src", "dst", "nonceInplaceCounterLength", "nc", "counterLength", "block", "j", "incrementCounter", "exports", "stream", "counter", "pos", "len", "carry", "constant_time_1", "wipe_1", "exports", "Poly1305", "key", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "m", "mpos", "bytes", "hibit", "h0", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "c", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "mac", "macpos", "g", "mask", "f", "i", "want", "oneTimeAuth", "data", "h", "digest", "equal", "a", "b", "chacha_1", "poly1305_1", "wipe_1", "binary_1", "constant_time_1", "exports", "ZEROS", "ChaCha20Poly1305", "key", "nonce", "plaintext", "associatedData", "dst", "counter", "authKey", "resultLength", "result", "sealed", "calculatedTag", "tagOut", "ciphertext", "h", "length", "tag", "i", "require_encode", "__commonJSMin", "exports", "module", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "require_decode", "__commonJSMin", "exports", "module", "read", "MSB", "REST", "buf", "offset", "res", "shift", "counter", "b", "l", "require_length", "__commonJSMin", "exports", "module", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "value", "require_varint", "__commonJSMin", "exports", "module", "require_src", "__commonJSMin", "exports", "module", "varint", "buf", "result", "num", "require_moving_average", "__commonJSMin", "exports", "module", "exp", "timespan", "ma", "v", "d", "f", "previousTime", "ret", "alpha", "t", "pt", "time", "value", "a", "diff", "incr", "require_textarea_caret", "__commonJSMin", "exports", "module", "properties", "isBrowser", "isFirefox", "getCaretCoordinates", "element", "position", "options", "debug", "el", "div", "style", "computed", "isInput", "prop", "span", "coordinates", "isArray", "what", "select", "selector", "what", "text", "value", "event", "htmlString", "content", "el", "isArray", "e", "newContent", "isElement", "li", "className", "classes", "cls", "shouldShow", "fn", "shouldDisable", "obj", "dom_default", "notificationTypes", "notification", "dom_default", "cleanNotificationClasses", "notificationFactory", "acc", "notificationType", "message", "Notification", "autohideDuration", "type", "notify", "notify_default", "welcomeUser", "lastVisit", "notify_default", "welcome_default", "storage", "key", "what", "attr", "current", "isArray", "acc", "k", "value", "savedTxt", "word", "newDictionary", "w", "cleanText", "words", "distinctWords", "notify_default", "localstorage_default", "configuration", "getGist", "id", "token", "localstorage_default", "response", "getAuthenticatedUsersGists", "deleteFileOnGist", "fileName", "gistId", "responseAsJson", "notify_default", "updateGist", "notes", "getNotes", "noteToFiles", "acc", "text", "deleted", "createNewGist", "note", "getAuthToken", "code", "state", "configuration", "publishGist", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "base58_exports", "__export", "base58btc", "base58flickr", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "json_exports", "__export", "code", "decode", "encode", "name", "textEncoder", "textDecoder", "node", "data", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "hashBrowser", "val", "bytes", "encode", "hash", "sha256", "CID", "code", "hashBrowser_default", "isJSON", "str", "isJSON_default", "_getBasePageTitle", "setPageTitle", "what", "baseTitle", "dom_default", "resetPageTitle", "url", "currentParams", "params", "parametersObject", "key", "param", "searchParams", "p", "pathname", "hash", "pageId", "allParams", "newParams", "setSavedState", "saved", "dom_default", "encodeTitle", "title", "encodedTitle", "getDateCreatedFromTitle", "titleID", "getTitleId", "note", "getNote", "dateCreated", "markNoteForDeletion", "id", "url", "revision", "doc", "localstorage_default", "newerNote", "acc", "noteToReturn", "disableSyncOnCurrentNote", "value", "notify_default", "setNoteFromHash", "hash", "version", "dom_default", "setPageTitle", "resetNoteManager", "resetPageTitle", "setSavedState", "getTitle", "updateNote", "what", "existingNote", "saveNote", "text", "hashOfIncomingNote", "hashBrowser_default", "hashOfCurrentNote", "currentNote", "cid", "e", "getNotes", "includeDeleted", "body", "isJSON_default", "noteId", "deleted", "search", "q", "deleteNote", "deleteFileOnGist", "commander_default", "isUserLoggedIn", "localstorage_default", "command", "title", "secondary", "onclick", "onSecondaryClick", "icon", "selected", "li", "iconClone", "liContent", "isElement", "span", "secondaryElement", "commands", "commandsToGen", "selectedIndex", "props", "i", "command", "wordParts", "word", "match", "parts", "indexInWord", "acc", "part", "i", "p", "syllable", "start", "end", "mark", "word", "markEl", "div", "content", "highlight", "words", "wordsToHighlight", "matches", "wordToHighlight", "m", "match", "wordElements", "wordParts", "syllable", "w", "goAuthenticate", "notify_default", "commander_default", "configuration", "setGistToSyncWith", "token", "gists", "getAuthenticatedUsersGists", "gistOptions", "a", "b", "description", "updated_at", "id", "div", "localstorage_default", "syncNotesWithGitHub", "gistOptionComponents", "commands", "createNewGist", "error", "dom_default", "gistId", "files", "getGist", "content", "updateNote", "setAuthTokenFromCallback", "code", "url", "state", "getAuthToken", "getNewFileHandle", "title", "options", "writeFile", "fileHandle", "contents", "writable", "saveFileAs", "msg", "notify_default", "saveDataToFile", "a", "data", "fileName", "json", "blob", "url", "import_showdown", "converter", "showdown", "convertMarkDownToHtml", "md", "handleErrorResponse", "response", "wrapTemplate", "body", "configuration", "sendMail", "email", "subject", "notify_default", "localstorage_default", "getUserMailingPreferences", "savedMail", "mailSameAgainQuestion", "whoMailing", "wannaSaveDat", "mailTo", "what", "title", "getTitle", "htmlBody", "convertMarkDownToHtml", "copyToClipboard", "what", "message", "notify_default", "error", "button", "els", "fn", "id", "elements", "isArray", "element", "e", "markDownViewer", "dom_default", "url", "autoLinks", "localstorage_default", "replacingPatterns", "regex", "updatedHTML", "match", "matchingKey", "link", "convertMarkDownToHtml", "el", "copyBtn", "button", "e", "codeToCopy", "copyToClipboard", "mode", "markDownViewer_default", "prettifyJSON", "selector", "el", "isJSON_default", "prettifiedJSON", "notify_default", "prettifyJSON_default", "sleep", "ms", "resolve", "icon", "svgIcon", "altText", "className", "image", "share", "note", "getNote", "currentUrl", "url", "error", "notify_default", "import_index", "merge_options_default", "mergeOptions", "import_env", "import_debug", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "debug", "v", "base58btc", "base32", "base64", "createDisabledLogger", "namespace", "logger", "name", "trace", "r", "n", "import_err_code", "import_err_code", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Data", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "c2", "d", "o", "n", "j", "valuesById", "values", "UnixTime", "Metadata", "PBData", "Data", "types", "dirTypes", "DEFAULT_FILE_MODE", "DEFAULT_DIRECTORY_MODE", "parseMode", "mode", "parseMtime", "input", "mtime", "ms", "secs", "errcode", "UnixFS", "marshaled", "message", "decoded", "data", "options", "type", "blockSizes", "hashType", "fanout", "parsedMode", "size", "index", "sum", "parsed", "pbData", "src_exports", "__export", "code", "createLink", "createNode", "decode", "encode", "name", "prepare", "validate", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "bytes_exports", "__export", "coerce", "empty", "equals", "fromHex", "fromString", "isBinary", "toHex", "toString", "d", "hex", "byte", "hexes", "b", "aa", "bb", "ii", "o", "str", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "__publicField", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "__publicField", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "_a", "CID", "version", "code", "multihash", "bytes", "__publicField", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "textDecoder", "decodeVarint", "bytes", "offset", "v", "shift", "b", "decodeBytes", "byteLen", "postOffset", "decodeKey", "index", "wire", "decodeLink", "link", "l", "wireType", "fieldNum", "byts", "decodeNode", "links", "linksBeforeData", "data", "node", "textEncoder", "maxInt32", "maxUInt32", "encodeLink", "link", "bytes", "i", "encodeVarint", "nameBytes", "encodeNode", "node", "size", "sizeNode", "index", "sizeLink", "n", "l", "sov", "offset", "v", "base", "x", "len64", "len8tab", "pbNodeProperties", "pbLinkProperties", "textEncoder", "linkComparator", "a", "b", "abuf", "bbuf", "x", "y", "i", "len", "hasOnlyProperties", "node", "properties", "p", "asLink", "link", "Hash", "CID", "pbl", "cid", "e", "prepare", "pbn", "validate", "createNode", "data", "links", "createLink", "name", "size", "toByteView", "buf", "name", "code", "encode", "node", "validate", "pbn", "l", "link", "encodeNode", "decode", "bytes", "buf", "toByteView", "decodeNode", "CID", "src_exports", "__export", "code", "decode", "decodeOptions", "encode", "encodeOptions", "name", "toByteView", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "str", "out", "p", "c", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "length", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "i", "key", "Type", "tagged", "decodeFirst", "decoded", "decode", "remainder", "CID_CBOR_TAG", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "bytes", "Token", "Type", "undefinedEncoder", "numberEncoder", "num", "_encodeOptions", "encodeOptions", "cidDecoder", "_decodeOptions", "decodeOptions", "name", "code", "encode", "node", "decode", "data", "src_exports", "__export", "code", "decode", "encode", "format", "name", "parse", "JSONEncoder", "buf", "recurs", "Type", "token", "is", "isa", "i", "_buf", "_token", "encodeErrPrefix", "byts", "fromString", "asU8A", "dp", "mapSorter", "e1", "e2", "keyToken1", "keyToken2", "defaultEncodeOptions", "encode", "data", "options", "encodeCustom", "Tokenizer", "data", "options", "c", "str", "decodeErrPrefix", "i", "startPos", "negative", "float", "swallow", "chars", "ch", "Token", "Type", "numStr", "num", "l", "readu4", "u4", "readUtf8Char", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "ch1", "decodeCodePointsArray", "token", "decode", "from", "name", "code", "encode", "Hasher", "__publicField", "input", "result", "create", "digest", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "cidString", "Token", "Type", "bytesEncoder", "bytes", "bytesString", "base64", "taBytesEncoder", "abBytesEncoder", "ab", "undefinedEncoder", "numberEncoder", "num", "encodeOptions", "DagJsonTokenizer", "Tokenizer", "data", "options", "token", "keyToken", "valueToken", "innerKeyToken", "innerValueToken", "i", "decodeOptions", "name", "code", "encode", "node", "decode", "format", "utf8Decoder", "utf8Decoder", "parse", "data", "decode", "utf8Encoder", "lib_exports", "__export", "code", "decode", "encode", "name", "toGeneral", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "bytes_exports", "__export", "coerce", "empty", "equals", "fromHex", "fromString", "isBinary", "toHex", "toString", "d", "hex", "byte", "hexes", "b", "aa", "bb", "ii", "o", "str", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "toBase64url", "b", "base64url", "fromBase64url", "s", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "fromSplit", "split", "protectedHeader", "payload", "signature", "CID", "fromBase64url", "encodeSignature", "encoded", "encode", "jws", "decodeSignature", "sign", "toBase64url", "decode", "decoded", "fromSplit", "split", "protectedHeader", "encrypted_key", "iv", "ciphertext", "tag", "jwe", "encodeRecipient", "recipient", "encRec", "fromBase64url", "encode", "encJwe", "decodeRecipient", "encoded", "toBase64url", "decode", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "string", "units", "codePoint", "length", "leadSurrogate", "bytes", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "length", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "i", "key", "Type", "tagged", "decode", "decoded", "CID_CBOR_TAG", "cidEncoder", "obj", "cid", "CID", "bytes", "Token", "Type", "undefinedEncoder", "numberEncoder", "num", "encodeOptions", "cidDecoder", "decodeOptions", "code", "encode", "node", "encodeOptions", "decode", "data", "decodeOptions", "name", "code", "isDagJWS", "jose", "isEncodedJWS", "isEncodedJWE", "isDagJWE", "toGeneral", "split", "fromSplit", "encode", "obj", "encodedJose", "decode", "data", "encoded", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "base2_exports", "__export", "base2", "base2", "rfc4648", "base8_exports", "__export", "base8", "base8", "rfc4648", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "raw_exports", "__export", "code", "decode", "encode", "name", "name", "code", "encode", "node", "coerce", "decode", "data", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "codecs", "raw_exports", "json_exports", "NotInitializedError", "message", "AlreadyInitializingError", "AlreadyInitializedError", "NotStartedError", "AlreadyStartingError", "AlreadyStartedError", "NotEnabledError", "asUint8Array", "buf", "base10_exports", "__export", "base10", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "allocUnsafe", "size", "_a", "asUint8Array", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "asUint8Array", "import_timeout_abort_controller", "equals", "a", "b", "i", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "sha2_browser_exports", "__export", "sha256", "sha512", "sha", "name", "data", "sha256", "from", "sha512", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "alloc", "size", "allocUnsafe", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "toString", "array", "encoding", "base", "bases_default", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "MSB", "REST", "encodingLength", "value", "encodeUint8Array", "buf", "offset", "encodeUint8ArrayList", "decodeUint8Array", "b", "res", "decodeUint8ArrayList", "encode", "allocUnsafe", "decode", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "Parser", "__publicField", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "parseIP", "maxIPv6Octet", "ipv4Prefix", "fromString", "string", "encoding", "base", "bases_default", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "isIP", "parseIP", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "ip4Protocol", "getProtocol", "ip6Protocol", "ipcidrProtocol", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "toString", "convertToBytes", "str", "ip2bytes", "str2bytes", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "fromString", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ip2bytes", "ipString", "isIP", "toBytes", "bytes2ip", "ipBuff", "toString", "port2bytes", "port", "buf", "bytes2port", "str2bytes", "str", "fromString", "size", "encode", "concat", "bytes2str", "decode", "encodingLength", "mh2bytes", "hash", "mh", "base58btc", "CID", "mb2bytes", "mbstr", "mb", "bytes2mb", "bytes2mh", "address", "onion2bytes", "addr", "base32", "portBuf", "onion32bytes", "bytes2onion", "addrBytes", "portBytes", "stringToMultiaddrParts", "str", "cleanPath", "tuples", "stringTuples", "path", "parts", "p", "part", "proto", "getProtocol", "ParseError", "convertToBytes", "bytes", "convertToString", "stringTuplesToString", "tuplesToBytes", "bytesToMultiaddrParts", "code", "decode", "n", "encodingLength", "size", "sizeForAddr", "addr", "toString", "stringAddr", "tup", "concat", "buf", "encode", "cleanPath", "str", "a", "ParseError", "inspect", "symbol", "DNS_CODES", "getProtocol", "NoAvailableResolverError", "message", "_string", "_tuples", "_stringTuples", "_path", "_a", "_Multiaddr", "addr", "__publicField", "__privateAdd", "parts", "bytesToMultiaddrParts", "stringToMultiaddrParts", "isMultiaddr", "__privateSet", "__privateGet", "family", "transport", "host", "port", "zone", "tcp", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "value", "addrString", "s", "tuples", "i", "tuplesToBytes", "name", "names", "tuple", "peerIdStr", "toString", "base58btc", "CID", "equals", "options", "resolvableProto", "p", "resolver", "resolvers", "str", "multiaddr", "protos", "Multiaddr", "resolvers", "isMultiaddr", "value", "symbol", "multiaddr", "addr", "Multiaddr", "DNS4", "base", "DNS6", "DNSADDR", "DNS", "or", "IP", "TCP", "and", "UDP", "UTP", "QUIC", "QUICV1", "_WebSockets", "WebSockets", "_WebSocketsSecure", "WebSocketsSecure", "HTTP", "HTTPS", "_WebRTCDirect", "WebRTCDirect", "_WebTransport", "WebTransport", "P2PWebRTCStar", "WebSocketStar", "P2PWebRTCDirect", "Reliable", "Stardust", "_P2P", "_Circuit", "CircuitRecursive", "Circuit", "P2P", "WebRTC", "or", "and", "Circuit", "base", "Reliable", "makeMatchesFunction", "partialMatch", "matches", "a", "ma", "multiaddr", "out", "args", "arg", "res", "n", "name", "pnames", "protos", "import_iso_url", "pathPattern", "defaultProtocolMatch", "defaultHashMath", "subdomainGatewayPattern", "fqdnWithTld", "isCID", "hash", "isString", "CID", "isIpfs", "input", "pattern", "protocolMatch", "defaultProtocolMatch", "hashMatch", "defaultHashMath", "formatted", "convertToString", "match", "hash", "subdomainGatewayPattern", "isCID", "isIpns", "ipnsId", "hostname", "fqdnWithTld", "isString", "toString", "path", "isIpfs", "pathPattern", "isIpns", "ipfsPath", "path", "isIpfs", "pathPattern", "ipnsPath", "isIpns", "nanoid", "size", "id", "byte", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "base2_exports", "__export", "base2", "base2", "rfc4648", "base8_exports", "__export", "base8", "base8", "rfc4648", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "code", "textEncoder", "textDecoder", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "asUint8Array", "buf", "alloc", "size", "_a", "asUint8Array", "allocUnsafe", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "toString", "array", "encoding", "base", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "asUint8Array", "pathSepS", "pathSepB", "pathSep", "Key", "s", "clean", "fromString", "encoding", "toString", "list", "nanoid", "other", "bytes", "key", "list1", "list2", "c1", "c2", "ns", "namespaceType", "namespaceValue", "p", "keys", "flatten", "parts", "arr", "import_err_code", "import_timeout_abort_controller", "import_any_signal", "durationRE", "parse", "str", "format", "result", "isNegative", "_", "n", "units", "unitRatio", "parse_duration_default", "TimeoutError", "message", "withTimeoutOption", "fn", "optionsArgIndex", "args", "options", "timeout", "parse_duration_default", "controller", "fnRes", "timeoutPromise", "_resolve", "reject", "TimeoutError", "start", "maybeThrowTimeoutError", "it", "value", "done", "err", "res", "import_err_code", "IPFS_PREFIX", "toCidAndPath", "string", "CID", "err", "errCode", "cid", "parts", "path", "ERR_BAD_PATH", "OFFLINE_ERROR", "MFS_ROOT_KEY", "Key", "MFS_MAX_CHUNK_SIZE", "normalizePath", "pathStr", "CID", "str", "path", "errCode", "ERR_BAD_PATH", "normalizeCidPath", "resolvePath", "repo", "codecs", "ipfsPath", "options", "cid", "toCidAndPath", "lastCid", "lastRemainderPath", "value", "remainderPath", "resolve", "err", "mapFile", "file", "output", "withTimeout", "withTimeoutOption", "promise", "_options", "load", "codec", "block", "parts", "key", "code", "link", "l", "Service", "start", "stop", "service", "options", "state", "activate", "promise", "result", "error", "AlreadyStartingError", "AlreadyStartedError", "deactivate", "withTimeout", "NotStartedError", "status", "createStart", "network", "preload", "peerId", "keychain", "repo", "ipns", "mfsPreload", "print", "hashers", "options", "libp2p", "Service", "createStop", "network", "preload", "ipns", "repo", "mfsPreload", "Service", "import_hashlru", "TLRU", "maxSize", "hashlru", "key", "value", "ttl", "import_index", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "milliseconds", "fallback", "options", "timer", "cancelablePromise", "resolve", "reject", "error", "timeoutError", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "__classPrivateFieldGet", "receiver", "state", "kind", "f", "_PriorityQueue_queue", "PriorityQueue", "run", "options", "element", "index", "lowerBound", "a", "b", "item", "priority_queue_default", "__classPrivateFieldSet", "receiver", "state", "value", "kind", "f", "__classPrivateFieldGet", "_PQueue_instances", "_PQueue_carryoverConcurrencyCount", "_PQueue_isIntervalIgnored", "_PQueue_intervalCount", "_PQueue_intervalCap", "_PQueue_interval", "_PQueue_intervalEnd", "_PQueue_intervalId", "_PQueue_timeoutId", "_PQueue_queue", "_PQueue_queueClass", "_PQueue_pending", "_PQueue_concurrency", "_PQueue_isPaused", "_PQueue_throwOnTimeout", "_PQueue_doesIntervalAllowAnother_get", "_PQueue_doesConcurrentAllowAnother_get", "_PQueue_next", "_PQueue_onResumeInterval", "_PQueue_isIntervalPaused_get", "_PQueue_tryToStartAnother", "_PQueue_initializeIntervalIfNeeded", "_PQueue_onInterval", "_PQueue_processQueue", "_PQueue_throwOnAbort", "_PQueue_onEvent", "AbortError", "PQueue", "EventEmitter", "options", "_a", "_b", "_c", "_d", "priority_queue_default", "newConcurrency", "function_", "resolve", "reject", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "limit", "now", "delay", "canInitializeInterval", "job", "signal", "_resolve", "event", "filter", "listener", "dist_default", "import_http", "cache", "TLRU", "ttl", "Queue", "dist_default", "httpQueue", "ipfsPath", "response", "resolveDnslink", "fqdn", "opts", "searchParams", "query", "res", "HTTP", "json", "fqdnFixups", "domain", "createDns", "withTimeoutOption", "options", "resolveDnslink", "createIsOnline", "network", "net", "symbol", "isPeerId", "other", "_AbortError", "message", "__publicField", "AbortError", "CodeError", "code", "props", "equals", "a", "b", "i", "inspect", "baseDecoder", "bases", "codec", "acc", "curr", "LIBP2P_KEY_CODE", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "_a", "PeerIdImpl", "init", "__publicField", "base58btc", "CID", "id", "equals", "peerIdFromString", "symbol", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "peerIdFromString", "str", "decoder", "baseDecoder", "multihash", "decode", "base58btc", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "RSAPeerIdImpl", "peerIdFromBytes", "buf", "identity", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "sha256", "peerIdFromCID", "CID", "cid", "LIBP2P_KEY_CODE", "peerIdFromKeys", "publicKey", "privateKey", "create", "createResolve", "repo", "codecs", "bases", "name", "resolve", "path", "opts", "ipnsPath", "resolvedPath", "schema", "hash", "rest", "base", "bytes", "parseBytes", "str", "cid", "CID", "results", "value", "remainderPath", "result", "withTimeoutOption", "peerIdFromString", "last", "source", "res", "entry", "createAdd", "addAll", "path", "options", "iter", "cid", "CID", "last", "import_err_code", "isIterable", "thing", "isAsyncIterable", "isCID", "CID", "normaliseInput", "input", "errCode", "cid", "toPin", "iterator", "first", "path", "obj", "pin", "PinTypes", "createAddAll", "repo", "codecs", "addAll", "source", "options", "pinAdd", "path", "recursive", "metadata", "normaliseInput", "cid", "resolvePath", "reason", "PinTypes", "release", "withTimeoutOption", "import_err_code", "toPin", "type", "cid", "metadata", "output", "createLs", "repo", "codecs", "ls", "options", "PinTypes", "errCode", "matched", "path", "normaliseInput", "resolvePath", "reason", "pinned", "parent", "withTimeoutOption", "createRm", "rmAll", "rm", "path", "options", "cid", "last", "createRmAll", "repo", "codecs", "rmAll", "source", "_options", "release", "path", "recursive", "normaliseInput", "cid", "resolvePath", "pinned", "reason", "PinTypes", "withTimeoutOption", "PinAPI", "codecs", "repo", "addAll", "createAddAll", "createAdd", "rmAll", "createRmAll", "createRm", "createLs", "cid", "options", "query", "name", "credentials", "import_err_code", "errors_exports", "__export", "abortedError", "dbDeleteFailedError", "dbOpenFailedError", "dbWriteFailedError", "notFoundError", "import_err_code", "err", "errCode", "import_err_code", "toString", "array", "encoding", "base", "bases_default", "import_timestamp_nano", "keys_exports", "__export", "ephemeral_keys_default", "generateKeyPair", "generateKeyPairFromSeed", "importKey", "keyStretcher", "marshalPrivateKey", "marshalPublicKey", "supportedKeys", "unmarshalPrivateKey", "unmarshalPublicKey", "import_asn1", "import_pbe", "import_forge", "ed25519_class_exports", "__export", "Ed25519PrivateKey", "Ed25519PublicKey", "generateKeyPair", "generateKeyPairFromSeed", "unmarshalEd25519PrivateKey", "unmarshalEd25519PublicKey", "nodeCrypto", "_0n", "_1n", "_2n", "_8n", "CU_O", "CURVE", "POW_2_256", "SQRT_M1", "SQRT_D", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "ExtendedPoint", "x", "y", "z", "t", "p", "Point", "_1n", "mod", "points", "toInv", "invertBatch", "other", "assertExtPoint", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "a", "CURVE", "A", "B", "C", "_2n", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "_0n", "W", "windows", "base", "window", "i", "n", "affinePoint", "precomputes", "pointPrecomputes", "f", "windowSize", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "constTimeNegate", "scalar", "normalizeScalar", "P0", "d", "invZ", "is0", "_8n", "invert", "ax", "ay", "zz", "legacyRist", "condition", "item", "neg", "assertRstPoint", "RistrettoPoint", "ep", "r0", "r", "Ns", "c", "Ns_D_is_sq", "s", "uvRatio", "s_", "edIsNegative", "Nt", "s2", "W0", "W1", "W2", "W3", "hex", "ensureBytes", "r1", "bytes255ToNumberLE", "R1", "r2", "R2", "emsg", "equalBytes", "numberTo32BytesLE", "u1", "u2", "u1_2", "u2_2", "v", "isValid", "I", "invertSqrt", "Dx", "Dy", "u2sq", "invsqrt", "D1", "D2", "zInv", "_x", "_y", "bytesToHex", "b", "one", "two", "strict", "P", "normed", "bytesToNumberLE", "y2", "u", "isXOdd", "privateKey", "getExtendedPublicKey", "bytes", "Signature", "u8", "concatBytes", "arrays", "a", "length", "arr", "result", "i", "pad", "hexes", "v", "bytesToHex", "uint8a", "hex", "hexToBytes", "array", "j", "hexByte", "byte", "numberTo32BytesBE", "num", "numberTo32BytesLE", "edIsNegative", "mod", "_1n", "bytesToNumberLE", "MAX_255B", "bytes255ToNumberLE", "bytes", "b", "CURVE", "res", "_0n", "invert", "number", "modulo", "x", "y", "u", "q", "r", "m", "n", "invertBatch", "nums", "p", "tmp", "lastMultiplied", "acc", "inverted", "pow2", "power", "P", "pow_2_252_3", "_5n", "_10n", "_20n", "_40n", "_80n", "b2", "b4", "_2n", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "uvRatio", "v3", "v7", "pow", "vx2", "root1", "root2", "SQRT_M1", "useRoot1", "useRoot2", "noRoot", "invertSqrt", "modlLE", "hash", "equalBytes", "b1", "ensureBytes", "expectedLength", "normalizeScalar", "max", "strict", "adjustBytes25519", "checkPrivateKey", "key", "numberTo32BytesBE", "normalizeScalar", "POW_2_256", "ensureBytes", "getKeyFromHash", "hashed", "head", "adjustBytes25519", "prefix", "scalar", "modlLE", "point", "Point", "pointBytes", "_sha512Sync", "getExtendedPublicKey", "key", "getKeyFromHash", "utils", "checkPrivateKey", "getPublicKey", "privateKey", "getExtendedPublicKey", "sign", "message", "privateKey", "ensureBytes", "prefix", "scalar", "pointBytes", "getExtendedPublicKey", "r", "modlLE", "utils", "R", "Point", "k", "s", "mod", "CURVE", "Signature", "prepareVerification", "sig", "message", "publicKey", "ensureBytes", "Point", "r", "s", "Signature", "SB", "ExtendedPoint", "finishVerification", "hashed", "k", "modlLE", "kA", "CURVE", "verify", "msg", "pub", "utils", "Point", "crypto", "nodeCrypto", "utils", "bytesToHex", "hexToBytes", "concatBytes", "getExtendedPublicKey", "mod", "invert", "hash", "ensureBytes", "bytesToNumberLE", "CURVE", "_1n", "bytesLength", "randomBytes", "messages", "message", "buffer", "windowSize", "point", "Point", "cached", "_2n", "_sha512Sync", "val", "PUBLIC_KEY_BYTE_LENGTH", "PRIVATE_KEY_BYTE_LENGTH", "KEYS_BYTE_LENGTH", "generateKey", "privateKeyRaw", "utils", "publicKey", "getPublicKey", "concatKeys", "generateKeyFromSeed", "seed", "KEYS_BYTE_LENGTH", "hashAndSign", "privateKey", "msg", "sign", "hashAndVerify", "sig", "verify", "PRIVATE_KEY_BYTE_LENGTH", "i", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "webcrypto_default", "win", "nativeCrypto", "derivedEmptyPasswordKey", "create", "opts", "algorithm", "keyLength", "nonceLength", "digest", "saltLength", "iterations", "crypto", "webcrypto_default", "encrypt", "data", "password", "salt", "nonce", "aesGcm", "fromString", "cryptoKey", "deriveParams", "runtimeDerivedEmptyPassword", "rawKey", "ciphertext", "concat", "decrypt", "plaintext", "exporter", "privateKey", "password", "encryptedKey", "create", "base64", "keys_exports", "__export", "KeyType", "PrivateKey", "PublicKey", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "lo", "hi", "__publicField", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "__publicField", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "pool", "size", "SIZE", "MAX", "slab", "offset", "allocUnsafe", "buf", "Op", "fn", "len", "val", "__publicField", "noop", "State", "writer", "bufferPool", "pool", "alloc", "size", "allocUnsafe", "Uint8ArrayWriter", "value", "VarintOp", "writeVarint64", "LongBits", "bits", "encodeUint8Array", "encodingLength", "writeByte", "writeFixed32", "writeFloatLE", "writeDoubleLE", "writeBytes", "length", "write", "head", "tail", "buf", "pos", "writeVarint32", "writeBytesBuffer", "writeStringBuffer", "fromString", "createWriter", "encodeMessage", "message", "codec", "w", "createWriter", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "Ed25519PublicKey", "key", "__publicField", "ensureKey", "PUBLIC_KEY_BYTE_LENGTH", "data", "sig", "hashAndVerify", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Ed25519PrivateKey", "publicKey", "PRIVATE_KEY_BYTE_LENGTH", "message", "hashAndSign", "PrivateKey", "encoding", "identity", "base58btc", "password", "format", "exporter", "CodeError", "unmarshalEd25519PrivateKey", "privateKeyBytes", "publicKeyBytes", "unmarshalEd25519PublicKey", "generateKeyPair", "privateKey", "generateKey", "generateKeyPairFromSeed", "seed", "generateKeyFromSeed", "length", "import_util", "import_jsbn", "import_forge", "bigIntegerToUintBase64url", "num", "len", "buf", "concat", "toString", "base64urlToBigInteger", "str", "base64urlToBuffer", "forge", "fromString", "bits", "curveTypes", "names", "generateEphmeralKeyPair", "curve", "CodeError", "pair", "webcrypto_default", "genSharedKey", "theirPub", "forcePrivate", "privateKey", "unmarshalPrivateKey", "key", "unmarshalPublicKey", "buffer", "publicKey", "marshalPublicKey", "curveLengths", "jwk", "byteLen", "concat", "base64urlToBuffer", "equals", "toString", "ephemeral_keys_default", "generateEphmeralKeyPair", "importer", "privateKey", "password", "encryptedKey", "base64", "create", "lengths_default", "hashTypes", "sign", "key", "data", "buf", "webcrypto_default", "create", "hashType", "secret", "hash", "lengths_default", "cipherMap", "keyStretcher", "cipherType", "hash", "secret", "cipher", "allowed", "CodeError", "cipherKeySize", "ivSize", "hmacKeySize", "seed", "fromString", "resultLength", "m", "create", "a", "result", "j", "b", "concat", "todo", "half", "resultBuffer", "r1", "r2", "createKey", "res", "rsa_class_exports", "__export", "RsaPrivateKey", "RsaPublicKey", "fromJwk", "generateKeyPair", "unmarshalRsaPrivateKey", "unmarshalRsaPublicKey", "import_forge", "import_sha512", "nodeCrypto", "_0n", "_1n", "_2n", "_3n", "_8n", "CURVE", "divNearest", "a", "b", "endo", "k", "n", "a1", "b1", "a2", "b2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "fieldLen", "groupLen", "hashLen", "compressedLen", "uncompressedLen", "weierstrass", "x", "a", "b", "CURVE", "x2", "mod", "x3", "USE_ENDOMORPHISM", "_0n", "ShaError", "message", "assertJacPoint", "other", "JacobianPoint", "y", "z", "p", "Point", "_1n", "points", "toInv", "invertBatch", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "Z1Z1", "Z2Z2", "U1", "U2", "S1", "S2", "A", "B", "C", "x1b", "D", "_2n", "E", "_3n", "F", "X3", "Y3", "_8n", "Z3", "H", "r", "HH", "HHH", "V", "scalar", "P0", "normalizeScalar", "d", "k1neg", "k1", "k2neg", "k2", "endo", "k1p", "k2p", "W", "windows", "base", "window", "i", "n", "affinePoint", "precomputes", "pointPrecomputes", "f", "windowSize", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "constTimeNegate", "point", "fake", "f1p", "f2p", "invZ", "is0", "invert", "iz1", "iz2", "iz3", "ax", "ay", "zz", "condition", "item", "neg", "bytes", "isShort", "bytesToNumber", "isValidFieldElement", "y2", "sqrtMod", "isYOdd", "fieldLen", "hex", "ensureBytes", "len", "header", "compressedLen", "uncompressedLen", "privateKey", "normalizePrivateKey", "msgHash", "signature", "recovery", "s", "normalizeSignature", "h", "truncateHash", "radj", "rinv", "u1", "u2", "prefix", "R", "numTo32bStr", "Q", "isCompressed", "hexToBytes", "msg", "left", "right", "P", "aP", "bQ", "sum", "sliceDER", "parseDERInt", "data", "bytesToHex", "res", "parseDERSignature", "sBytes", "rBytesLeft", "Signature", "arr", "name", "str", "hexToNumber", "isWithinCurveOrder", "HALF", "sHex", "numberToHexUnpadded", "rHex", "sHexL", "rHexL", "sLen", "rLen", "concatBytes", "arrays", "length", "result", "pad", "hexes", "v", "uint8a", "POW_2_256", "num", "numTo32b", "array", "j", "hexByte", "byte", "pow2", "power", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "rt", "number", "modulo", "u", "q", "m", "nums", "scratch", "lastMultiplied", "acc", "inverted", "bits2int_2", "delta", "groupLen", "hash", "truncateOnly", "_sha256Sync", "_hmacSha256Sync", "HmacDrbg", "hashLen", "qByteLen", "values", "utils", "seed", "out", "sl", "kmdToSig", "kBytes", "lowS", "k", "kinv", "sig", "key", "normalizePublicKey", "publicKey", "getPublicKey", "bits2int", "bytes", "slice", "fieldLen", "bytesToNumber", "bits2octets", "z1", "z2", "mod", "CURVE", "int2octets", "_0n", "num", "numTo32b", "initSigArgs", "msgHash", "privateKey", "extraEntropy", "h1", "ensureBytes", "d", "normalizePrivateKey", "seedArgs", "utils", "e", "seed", "concatBytes", "m", "finalizeSig", "recSig", "opts", "sig", "recovery", "der", "recovered", "hashed", "sign", "privKey", "drbg", "HmacDrbg", "hashLen", "groupLen", "kmdToSig", "vopts", "verify", "signature", "msgHash", "publicKey", "opts", "sig", "normalizeSignature", "ensureBytes", "r", "h", "truncateHash", "P", "normalizePublicKey", "n", "CURVE", "sinv", "invert", "u1", "mod", "u2", "R", "Point", "Point", "crypto", "nodeCrypto", "TAGGED_HASH_PREFIXES", "utils", "bytesToHex", "hexToBytes", "concatBytes", "mod", "invert", "privateKey", "normalizePrivateKey", "numTo32b", "hash", "ensureBytes", "minLen", "groupLen", "num", "bytesToNumber", "CURVE", "_1n", "bytesLength", "crypto", "randomBytes", "windowSize", "point", "Point", "cached", "_3n", "messages", "buffer", "createHash", "m", "key", "ckey", "message", "createHmac", "tag", "tagP", "tagH", "c", "_sha256Sync", "ShaError", "JacobianPoint", "val", "_hmacSha256Sync", "randomBytes", "length", "CodeError", "utils", "import_rsa", "import_forge", "convert", "key", "types", "base64urlToBigInteger", "jwk2priv", "forge", "jwk2pub", "rsa_utils_exports", "__export", "jwkToPkcs1", "jwkToPkix", "pkcs1ToJwk", "pkixToJwk", "import_asn1", "import_rsa", "import_forge", "pkcs1ToJwk", "bytes", "asn1", "forge", "toString", "privateKey", "bigIntegerToUintBase64url", "jwkToPkcs1", "jwk", "CodeError", "base64urlToBigInteger", "fromString", "pkixToJwk", "publicKey", "jwkToPkix", "generateKey", "bits", "pair", "webcrypto_default", "keys", "exportKey", "unmarshalPrivateKey", "key", "derivePublicFromPrivate", "hashAndSign", "key", "msg", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "exportKey", "pair", "CodeError", "derivePublicFromPrivate", "jwKey", "convertKey", "pub", "handle", "fkey", "jwk2pub", "jwk2priv", "fmsg", "toString", "fomsg", "fromString", "encrypt", "decrypt", "RsaPublicKey", "key", "__publicField", "data", "sig", "hashAndVerify", "rsa_utils_exports", "PublicKey", "KeyType", "bytes", "encrypt", "equals", "sha256", "RsaPrivateKey", "publicKey", "randomBytes", "message", "hashAndSign", "CodeError", "decrypt", "PrivateKey", "hash", "toString", "password", "format", "buffer", "forge", "asn1", "privateKey", "options", "exporter", "unmarshalRsaPrivateKey", "jwk", "keys", "unmarshalPrivateKey", "unmarshalRsaPublicKey", "fromJwk", "generateKeyPair", "bits", "generateKey", "secp256k1_class_exports", "__export", "Secp256k1PrivateKey", "Secp256k1PublicKey", "generateKeyPair", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKey", "utils", "hashAndSign", "key", "msg", "digest", "sha256", "sign", "err", "CodeError", "hashAndVerify", "sig", "verify", "compressPublicKey", "Point", "validatePrivateKey", "key", "getPublicKey", "err", "CodeError", "validatePublicKey", "Point", "computePublicKey", "privateKey", "Secp256k1PublicKey", "key", "__publicField", "validatePublicKey", "data", "sig", "hashAndVerify", "compressPublicKey", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Secp256k1PrivateKey", "publicKey", "computePublicKey", "validatePrivateKey", "message", "hashAndSign", "PrivateKey", "hash", "toString", "password", "format", "exporter", "CodeError", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKeyPair", "privateKeyBytes", "generateKey", "supportedKeys", "rsa_class_exports", "ed25519_class_exports", "secp256k1_class_exports", "unsupportedKey", "type", "supported", "CodeError", "typeToKey", "generateKeyPair", "bits", "generateKeyPairFromSeed", "seed", "unmarshalPublicKey", "buf", "decoded", "PublicKey", "data", "KeyType", "marshalPublicKey", "key", "unmarshalPrivateKey", "PrivateKey", "marshalPrivateKey", "importKey", "encryptedKey", "password", "importer", "forge", "der", "fromString", "import_err_code", "import_err_code", "ERR_IPNS_EXPIRED_RECORD", "ERR_UNRECOGNIZED_VALIDITY", "ERR_SIGNATURE_CREATION", "ERR_SIGNATURE_VERIFICATION", "ERR_UNRECOGNIZED_FORMAT", "ERR_UNDEFINED_PARAMETER", "ERR_INVALID_RECORD_DATA", "ERR_INVALID_EMBEDDED_KEY", "ERR_MISSING_PRIVATE_KEY", "import_reader", "import_reader_buffer", "import_writer", "import_writer_buffer", "import_minimal", "configure", "util", "ReaderClass", "ReaderBufferClass", "WriterClass", "WriterBufferClass", "methods", "patchReader", "obj", "method", "original", "reader", "buf", "patchWriter", "val", "writer", "decodeMessage", "buf", "codec", "r", "reader", "encodeMessage", "message", "codec", "w", "writer", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "IpnsEntry", "ValidityType", "__ValidityTypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "string", "units", "codePoint", "length", "leadSurrogate", "bytes", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "length", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "i", "key", "Type", "tagged", "decode", "decoded", "log", "logger", "IPNS_PREFIX", "fromString", "parseRFC3339", "time", "rfc3339Matcher", "m", "year", "month", "date", "hour", "minute", "second", "millisecond", "extractPublicKey", "peerId", "entry", "error", "log", "errCode", "ERR_UNDEFINED_PARAMETER", "pubKey", "unmarshalPublicKey", "err", "peerIdFromKeys", "ERR_INVALID_EMBEDDED_KEY", "ipnsEntryDataForV1Sig", "value", "validityType", "validity", "validityTypeBuffer", "fromString", "concat", "ipnsEntryDataForV2Sig", "data", "entryData", "marshal", "obj", "IpnsEntry", "unmarshal", "buf", "message", "peerIdToRoutingKey", "IPNS_PREFIX", "peerIdFromRoutingKey", "key", "peerIdFromBytes", "createCborData", "sequence", "ttl", "ValidityType", "ERR_UNRECOGNIZED_VALIDITY", "encode", "parseCborData", "decode", "log", "logger", "ID_MULTIHASH_CODE", "identity", "namespace", "namespaceLength", "create", "peerId", "value", "seq", "lifetime", "expirationDate", "NanoDate", "validityType", "IpnsEntry", "ms", "ns", "lifetimeNs", "_create", "_create", "peerId", "value", "seq", "validityType", "expirationDate", "ttl", "isoValidity", "fromString", "errCode", "ERR_MISSING_PRIVATE_KEY", "privateKey", "unmarshalPrivateKey", "signatureV1", "signLegacyV1", "data", "createCborData", "sigData", "ipnsEntryDataForV2Sig", "signatureV2", "entry", "digest", "decode", "ID_MULTIHASH_CODE", "equals", "log", "rawStdEncoding", "key", "base32upper", "getLocalKey", "Key", "validity", "dataForSignature", "ipnsEntryDataForV1Sig", "error", "ERR_SIGNATURE_CREATION", "log", "logger", "ERR_NOT_FOUND", "notFoundError", "defaultRecordLifetime", "IpnsPublisher", "routing", "datastore", "peerId", "value", "lifetime", "options", "record", "isPeerId", "errMsg", "errcode", "routingKey", "peerIdToRoutingKey", "key", "entry", "res", "toString", "err", "checkRouting", "dsVal", "getLocalKey", "data", "unmarshal", "getPublishedOptions", "seqNumber", "equals", "entryData", "create", "marshal", "import_err_code", "import_timeout_abort_controller", "log", "logger", "minute", "hour", "defaultBroadcastInterval", "defaultRecordLifetime", "IpnsRepublisher", "publisher", "datastore", "peerId", "keychain", "options", "errcode", "republishHandle", "period", "err", "pass", "firstRun", "timeoutController", "errMsg", "keys", "key", "pem", "privKey", "importKey", "peerIdKey", "peerIdFromKeys", "value", "isPeerId", "dsVal", "getLocalKey", "unmarshal", "import_err_code", "import_err_code", "log", "logger", "validate", "publicKey", "entry", "value", "validityType", "validity", "dataForSignature", "signature", "ipnsEntryDataForV2Sig", "validateCborDataMatchesPbData", "errCode", "ERR_SIGNATURE_VERIFICATION", "isValid", "IpnsEntry", "validityDate", "parseRFC3339", "toString", "ERR_UNRECOGNIZED_FORMAT", "ERR_IPNS_EXPIRED_RECORD", "ERR_UNRECOGNIZED_VALIDITY", "ERR_INVALID_RECORD_DATA", "data", "parseCborData", "equals", "ipnsValidator", "key", "marshalledData", "peerId", "peerIdFromRoutingKey", "receivedEntry", "unmarshal", "pubKey", "extractPublicKey", "log", "logger", "ERR_NOT_FOUND", "notFoundError", "defaultMaximumRecursiveDepth", "IpnsResolver", "routing", "name", "options", "errcode", "recursive", "nameSegments", "key", "depth", "res", "errMsg", "peerId", "peerIdFromString", "routingKey", "peerIdToRoutingKey", "record", "err", "ipnsValidator", "concat", "fromString", "ipnsEntry", "unmarshal", "toString", "import_hashlru", "TLRU", "maxSize", "hashlru", "key", "value", "ttl", "log", "logger", "defaultRecordTtl", "IPNS", "routing", "datastore", "peerId", "keychain", "options", "IpnsPublisher", "IpnsRepublisher", "IpnsResolver", "TLRU", "value", "lifetime", "toString", "id", "ttEol", "ttl", "err", "name", "errcode", "result", "all", "source", "arr", "entry", "sortAll", "iterable", "sorter", "all", "drain", "source", "_", "filter", "source", "fn", "entry", "take", "source", "limit", "items", "entry", "BaseDatastore", "key", "val", "options", "source", "value", "puts", "dels", "drain", "q", "it", "filter", "e", "f", "sortAll", "take", "import_debug", "debug", "v", "base58btc", "base32", "base64", "logger", "name", "FixedFIFO", "hwm", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "pushable", "options", "_pushable", "buffer", "next", "_pushable", "getNext", "options", "onEnd", "buffer", "FIFO", "pushable", "onNext", "ended", "waitNext", "resolve", "reject", "next", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "log", "logger", "TieredDatastore", "BaseDatastore", "stores", "store", "err", "dbOpenFailedError", "key", "value", "options", "dbWriteFailedError", "res", "notFoundError", "s", "dbDeleteFailedError", "source", "error", "pushables", "pushable", "drain", "pair", "p", "batches", "b", "batch", "q", "import_dlv", "ipnsSelector", "key", "data", "entries", "buf", "index", "IpnsEntry", "a", "b", "aSeq", "bSeq", "aValidty", "bValidty", "entryAValidityDate", "parseRFC3339", "toString", "entryBValidityDate", "SHARDING_FN", "README_FN", "MemoryDatastore", "BaseDatastore", "key", "val", "notFoundError", "value", "Key", "map", "source", "func", "val", "merge", "sources", "output", "pushable", "source", "item", "err", "rawPipe", "fns", "res", "isIterable", "obj", "isDuplex", "duplexPipelineFn", "duplex", "source", "p", "stream", "pushable", "err", "merge", "pipe", "first", "rest", "i", "shardKey", "Key", "SHARDING_FN", "shardReadmeKey", "README_FN", "CodeError", "message", "code", "props", "namespace", "encodeBase32", "buf", "toString", "keyToTopic", "key", "fromString", "b64url", "topicToKey", "topic", "CodeError", "equals", "a", "b", "i", "log", "logger", "PubSubDatastore", "BaseDatastore", "pubsub", "datastore", "peerId", "validator", "selector", "subscriptionKeyFn", "CodeError", "key", "val", "options", "errMsg", "stringifiedTopic", "keyToTopic", "subscriptions", "routingKey", "Key", "encodeBase32", "dsVal", "err", "evt", "msg", "data", "from", "topic", "topicToKey", "res", "isBetter", "value", "records", "dsKey", "currentRecord", "equals", "import_err_code", "log", "logger", "IpnsPubsubDatastore", "pubsub", "localDatastore", "peerId", "PubSubDatastore", "ipnsValidator", "ipnsSelector", "key", "value", "options", "err", "res", "e", "ns", "namespaceLength", "toString", "namespace", "stringifiedTopic", "base58btc", "id", "subscriber", "errcode", "peerIdToRoutingKey", "peerIdFromString", "sub", "name", "bufTopic", "fromString", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "toRFC3339", "time", "year", "month", "day", "hour", "minute", "seconds", "milliseconds", "nanoseconds", "parseRFC3339", "rfc3339Matcher", "m", "date", "second", "millisecond", "Libp2pRecord", "key", "value", "timeReceived", "__publicField", "Record", "toRFC3339", "raw", "rec", "obj", "recvtime", "parseRFC3339", "import_err_code", "log", "logger", "OfflineDatastore", "datastore", "key", "value", "options", "errcode", "routingKey", "err", "record", "Libp2pRecord", "res", "Key", "toString", "drain", "source", "_", "log", "logger", "DHTDatastore", "dht", "key", "value", "options", "drain", "err", "event", "notFoundError", "createRouting", "libp2p", "repo", "peerId", "options", "ipnsStores", "pubsubDs", "get", "IpnsPubsubDatastore", "DHTDatastore", "offlineDatastore", "OfflineDatastore", "TieredDatastore", "log", "logger", "IPNSAPI", "options", "ipns", "NotInitializedError", "repo", "peerId", "keychain", "AlreadyInitializedError", "routing", "OfflineDatastore", "IPNS", "libp2p", "createRouting", "value", "lifetime", "name", "import_err_code", "resolvePath", "ipns", "repo", "codecs", "name", "options", "ipnsPath", "cid", "path", "toCidAndPath", "drain", "resolve", "log", "logger", "createPublish", "ipns", "repo", "codecs", "peerId", "isOnline", "keychain", "lookupKey", "keyName", "privateKey", "unmarshalPrivateKey", "pem", "importKey", "err", "errcode", "peerIdFromKeys", "publish", "value", "options", "resolve", "lifetime", "key", "OFFLINE_ERROR", "normalizePath", "pubLifetime", "parse_duration_default", "results", "resolvePath", "bytes", "fromString", "result", "toString", "withTimeoutOption", "import_err_code", "import_is_domain_name", "mergeOptions", "merge_options_default", "log", "logger", "appendRemainder", "result", "remainder", "createResolve", "dns", "ipns", "isOnline", "offline", "resolve", "name", "options", "errcode", "OFFLINE_ERROR", "ipnsName", "namespace", "hash", "id", "peerIdFromString", "digest", "decode", "CID", "base36", "cid", "err", "isDomain", "value", "toString", "withTimeoutOption", "import_err_code", "getPubsubRouting", "ipns", "options", "errcode", "IpnsPubsubDatastore", "pubsub", "s", "createCancel", "ipns", "options", "experimental", "cancel", "name", "getPubsubRouting", "withTimeoutOption", "createState", "ipns", "options", "experimental", "state", "_options", "getPubsubRouting", "withTimeoutOption", "createSubs", "ipns", "options", "experimental", "subs", "getPubsubRouting", "withTimeoutOption", "PubSubAPI", "ipns", "options", "createCancel", "createState", "createSubs", "NameAPI", "dns", "ipns", "repo", "codecs", "peerId", "isOnline", "keychain", "options", "createPublish", "createResolve", "PubSubAPI", "import_timeout_abort_controller", "import_any_signal", "ERR_NOT_FOUND", "notFoundError", "Format", "createRefs", "repo", "codecs", "resolve", "preload", "refs", "ipfsPath", "options", "signals", "paths", "p", "getFullPath", "path", "refsStream", "err", "cid", "toCidAndPath", "resPath", "maxDepth", "unique", "obj", "objectStream", "formatLink", "srcCid", "dstCid", "linkName", "format", "out", "rootCid", "uniqueOnly", "seen", "traverseLevel", "parent", "depth", "nextLevelDepth", "link", "getLinks", "block", "value", "isDagPb", "code", "base", "name", "links", "match", "index", "source", "key", "element", "elementPath", "CID", "createLocal", "repo", "refsLocal", "options", "cid", "withTimeoutOption", "createWantlist", "network", "wantlist", "options", "bitswap", "list", "e", "withTimeoutOption", "createWantlistForPeer", "network", "wantlistForPeer", "peerId", "options", "bitswap", "list", "e", "withTimeoutOption", "createUnwant", "network", "unwant", "cids", "options", "bitswap", "withTimeoutOption", "createStat", "network", "stat", "options", "bitswap", "snapshot", "e", "withTimeoutOption", "BitswapAPI", "network", "createWantlist", "createWantlistForPeer", "createUnwant", "createStat", "DNS4", "base", "DNS6", "DNSADDR", "DNS", "or", "IP", "TCP", "and", "UDP", "UTP", "QUIC", "WebSockets", "WebSocketsSecure", "HTTP", "HTTPS", "_WebRTC", "WebRTC", "WebRTCStar", "WebSocketStar", "WebRTCDirect", "Reliable", "Stardust", "_P2P", "_Circuit", "CircuitRecursive", "Circuit", "P2P", "IPFS", "makeMatchesFunction", "partialMatch", "matches", "a", "ma", "multiaddr", "out", "args", "arg", "res", "n", "name", "pnames", "protos", "isValidMultiaddr", "ma", "IPFS", "createAdd", "repo", "add", "multiaddr", "options", "isValidMultiaddr", "config", "boostrappers", "a", "b", "withTimeoutOption", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "import_varint", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "toString", "convertToBytes", "str", "ip2bytes", "str2bytes", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "fromString", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ipString", "isIP", "toBytes", "ipBuff", "port", "size", "varint", "concat", "hash", "mh", "decode", "base58btc", "CID", "mbstr", "mb", "address", "addr", "base32", "portBuf", "addrBytes", "portBytes", "import_varint", "stringToStringTuples", "str", "tuples", "parts", "p", "part", "proto", "getProtocol", "ParseError", "cleanPath", "stringTuplesToString", "tup", "protoFromTuple", "stringTuplesToTuples", "convertToBytes", "tuplesToStringTuples", "convertToString", "tuplesToBytes", "fromBytes", "concat", "buf", "varint", "sizeForAddr", "addr", "bytesToTuples", "i", "code", "n", "size", "toString", "bytesToString", "a", "b", "stringToBytes", "fromString", "err", "validateBytes", "cleanPath", "str", "a", "ParseError", "protoFromTuple", "tup", "getProtocol", "import_varint", "import_err_code", "inspect", "DNS_CODES", "getProtocol", "resolvers", "symbol", "isMultiaddr", "value", "symbol", "DefaultMultiaddr", "addr", "_DefaultMultiaddr_string", "_DefaultMultiaddr_tuples", "_DefaultMultiaddr_stringTuples", "_a", "fromBytes", "fromString", "__classPrivateFieldGet", "__classPrivateFieldSet", "bytesToString", "family", "transport", "host", "port", "zone", "tcp", "getProtocol", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "DNS_CODES", "codes", "buf", "i", "varint", "n", "p", "size", "sizeForAddr", "proto", "bytesToTuples", "tuplesToStringTuples", "addrString", "s", "tuples", "tuplesToBytes", "tuple", "names", "peerIdStr", "toString", "base58btc", "CID", "path", "equals", "options", "resolvableProto", "resolver", "resolvers", "errCode", "a", "protos", "inspect", "multiaddr", "createClear", "repo", "clear", "options", "config", "removed", "ma", "multiaddr", "withTimeoutOption", "createList", "repo", "list", "options", "ma", "multiaddr", "withTimeoutOption", "config_browser_default", "createReset", "repo", "reset", "options", "config", "config_browser_default", "ma", "multiaddr", "withTimeoutOption", "createRm", "repo", "rm", "multiaddr", "options", "isValidMultiaddr", "config", "ma", "withTimeoutOption", "BootstrapAPI", "repo", "createAdd", "createList", "createRm", "createClear", "createReset", "createGet", "preload", "repo", "get", "cid", "options", "withTimeoutOption", "createPut", "codecs", "hashers", "repo", "preload", "put", "block", "options", "release", "cidVersion", "codecName", "hash", "codec", "cid", "CID", "withTimeoutOption", "import_err_code", "pDefer", "deferred", "resolve", "reject", "CustomEvent", "parallel", "source", "options", "concurrency", "ordered", "emitter", "ops", "slotAvailable", "pDefer", "resultAvailable", "sourceFinished", "sourceErr", "opErred", "task", "op", "result", "err", "valuesAvailable", "_a", "yieldOrderedValues", "yieldUnOrderedValues", "i", "map", "source", "func", "val", "filter", "source", "fn", "entry", "cleanCid", "cid", "CID", "BLOCK_RM_CONCURRENCY", "createRm", "repo", "rm", "cids", "options", "release", "pipe", "source", "map", "cid", "cleanCid", "result", "errCode", "err", "parallel", "filter", "withTimeoutOption", "createStat", "repo", "preload", "stat", "cid", "options", "cleanCid", "block", "withTimeoutOption", "BlockAPI", "codecs", "hashers", "preload", "repo", "createGet", "createPut", "createRm", "createStat", "import_err_code", "browserReadableStreamToIt", "stream", "options", "reader", "result", "blobToIt", "blob", "browserReadableStreamToIt", "peekableIterator", "iterable", "iterator", "symbol", "queue", "value", "all", "source", "arr", "entry", "isBytes", "obj", "isBlob", "isFileObject", "isReadableStream", "value", "toAsyncIterable", "thing", "normaliseContent", "input", "isBytes", "toBytes", "isBlob", "blobToIt", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "all", "map", "errCode", "chunk", "fromString", "import_err_code", "normaliseCandidateSingle", "input", "normaliseContent", "errCode", "toFileObject", "isBytes", "isBlob", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "isFileObject", "path", "mode", "mtime", "content", "file", "parseMode", "parseMtime", "normaliseInput", "input", "normaliseCandidateSingle", "normaliseContent", "createAdd", "addAll", "add", "entry", "options", "result", "last", "normaliseInput", "batch", "source", "size", "things", "thing", "parallelBatch", "source", "size", "tasks", "batch", "things", "p", "value", "err", "result", "import_murmurhash3js_revisited", "fromNumberTo32BitBuf", "number", "bytes", "i", "murmur332", "from", "input", "mur", "murmur3128", "bytes_exports", "murmur364", "hamtHashFn", "buf", "murmur3128", "defaultOptions", "sha256", "options_default", "options", "merge_options_default", "persist", "buffer", "blockstore", "options", "src_exports", "sha256", "multihash", "cid", "CID", "persist_default", "dirBuilder", "item", "blockstore", "options", "unixfs", "UnixFS", "buffer", "encode", "prepare", "cid", "persist_default", "path", "dir_default", "import_err_code", "flat", "source", "reduce", "all", "flat_default", "balanced", "source", "reduce", "options", "reduceToParents", "roots", "chunked", "batch", "balanced_default", "trickleStream", "source", "reduce", "options", "root", "Root", "iteration", "maxDepth", "subTree", "layer", "batch", "SubTree", "trickle_default", "layerRepeat", "distantRelative", "parent", "nextNode", "node", "children", "child", "depth", "bufferImporter", "file", "block", "options", "buffer", "unixfs", "opts", "src_exports", "raw_exports", "UnixFS", "encode", "persist_default", "buffer_importer_default", "dagBuilders", "flat_default", "balanced_default", "trickle_default", "buildFileBatch", "file", "blockstore", "options", "count", "previous", "bufferImporter", "buffer_importer_default", "entry", "parallelBatch", "reduce", "reducer", "leaves", "leaf", "buffer", "UnixFS", "encode", "prepare", "persist_default", "src_exports", "f", "links", "code", "node", "acc", "curr", "fileBuilder", "block", "dagBuilder", "errCode", "file_default", "import_err_code", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "_a", "Uint8ArrayList", "data", "__publicField", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "import_rabin_wasm", "import_err_code", "rabinChunker", "source", "options", "min", "max", "avg", "errcode", "sizepow", "chunk", "rabin", "rabin_default", "r", "buffers", "Uint8ArrayList", "sizes", "i", "size", "buf", "fixedSizeChunker", "source", "options", "list", "Uint8ArrayList", "currentLength", "emitted", "maxChunkSize", "buffer", "newBl", "fixed_size_default", "import_err_code", "validateChunks", "source", "content", "errCode", "fromString", "validate_chunks_default", "isIterable", "thing", "isAsyncIterable", "contentAsAsyncIterable", "content", "errCode", "dagBuilder", "source", "blockstore", "options", "entry", "path", "chunker", "rabin_default", "fixed_size_default", "chunkValidator", "validate_chunks_default", "file", "file_default", "dir", "dir_default", "dag_builder_default", "Dir", "props", "options", "name", "value", "blockstore", "dir_default", "DirFlat", "dir_default", "props", "options", "name", "value", "keys", "i", "key", "block", "children", "links", "child", "entry", "unixfs", "UnixFS", "node", "buffer", "encode", "prepare", "cid", "persist_default", "size", "acc", "curr", "dir_flat_default", "import_sparse_array", "Bucket", "options", "parent", "posAtParent", "__publicField", "SparseArray", "key", "value", "place", "child", "acc", "children", "map", "reduce", "index", "asyncMap", "asyncReduce", "asyncTransformBucket", "mapNode", "reduceNodes", "result", "hashValue", "fromString", "bucket", "newPlace", "pos", "object", "onlyChild", "exists", "hash", "o", "node", "_", "nodes", "output", "mappedChildren", "START_MASKS", "STOP_MASKS", "ConsumableBuffer", "value", "__publicField", "bits", "pendingBits", "result", "byte", "availableBits", "taking", "byteBitsToInt", "start", "length", "mask", "maskFor", "wrapHash", "hashFn", "hashing", "value", "InfiniteHash", "__publicField", "bits", "pendingBits", "result", "hash", "available", "took", "availableForUntake", "concat", "hashValue", "buffer", "ConsumableBuffer", "createHAMT", "options", "bucketOptions", "wrapHash", "Bucket", "DirSharded", "dir_default", "props", "options", "createHAMT", "name", "value", "key", "blockstore", "entry", "flush", "dir_sharded_default", "bucket", "shardRoot", "children", "links", "childrenSize", "i", "child", "labelPrefix", "Bucket", "shard", "subShard", "dir", "flushedDir", "label", "size", "data", "UnixFS", "node", "buffer", "encode", "prepare", "cid", "persist_default", "flatToShard", "child", "dir", "threshold", "options", "newDir", "dir_flat_default", "convertToShard", "parent", "oldDir", "dir_sharded_default", "key", "flat_to_shard_default", "toPathComponents", "path", "to_path_components_default", "addToTree", "elem", "tree", "options", "pathElems", "to_path_components_default", "lastIndex", "parent", "currentPath", "i", "pathElem", "last", "flat_to_shard_default", "dir", "dir_default", "dir_flat_default", "flushAndYield", "blockstore", "treeBuilder", "source", "block", "entry", "unwrapped", "tree_builder_default", "importer", "source", "blockstore", "options", "opts", "options_default", "dagBuilder", "dag_builder_default", "treeBuilder", "tree_builder_default", "candidates", "entry", "parallelBatch", "import_err_code", "normaliseCandidateMultiple", "input", "normaliseContent", "isBytes", "isBlob", "errCode", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "map", "toFileObject", "isFileObject", "path", "mode", "mtime", "content", "file", "parseMode", "parseMtime", "normaliseInput", "input", "normaliseCandidateMultiple", "normaliseContent", "parseChunkerString", "chunker", "sizeStr", "size", "parseRabinString", "options", "parts", "parseChunkSize", "str", "name", "mergeOptions", "merge_options_default", "createAddAll", "repo", "preload", "hashers", "options", "isShardingEnabled", "addAll", "source", "opts", "parseChunkerString", "totals", "prog", "bytes", "path", "hasher", "iterator", "pipe", "normaliseInput", "importer", "transformFile", "preloadFile", "pinFile", "releaseLock", "added", "withTimeoutOption", "file", "cid", "maybePreloadFile", "maybePinFile", "isRootDir", "import_err_code", "import_err_code", "textDecoder", "decodeVarint", "bytes", "offset", "v", "shift", "b", "decodeBytes", "byteLen", "postOffset", "decodeKey", "index", "wire", "decodeLink", "link", "l", "wireType", "fieldNum", "byts", "decodeNode", "links", "linksBeforeData", "data", "node", "textEncoder", "maxInt32", "maxUInt32", "encodeLink", "link", "bytes", "i", "encodeVarint", "nameBytes", "encodeNode", "node", "size", "sizeNode", "index", "sizeLink", "n", "l", "sov", "offset", "v", "base", "x", "len64", "len8tab", "pbNodeProperties", "pbLinkProperties", "textEncoder", "linkComparator", "a", "b", "abuf", "bbuf", "x", "y", "i", "len", "hasOnlyProperties", "node", "properties", "p", "validate", "node", "hasOnlyProperties", "pbNodeProperties", "i", "link", "pbLinkProperties", "linkComparator", "code", "encode", "node", "validate", "pbn", "l", "link", "encodeNode", "decode", "bytes", "decodeNode", "CID", "import_err_code", "import_sparse_array", "Bucket", "options", "parent", "posAtParent", "SparseArray", "key", "value", "place", "child", "acc", "children", "map", "reduce", "index", "asyncMap", "asyncReduce", "asyncTransformBucket", "mapNode", "reduceNodes", "result", "hashValue", "fromString", "bucket", "newPlace", "pos", "object", "onlyChild", "exists", "hash", "o", "node", "_", "nodes", "output", "mappedChildren", "START_MASKS", "STOP_MASKS", "ConsumableBuffer", "value", "bits", "pendingBits", "result", "byte", "availableBits", "taking", "byteBitsToInt", "start", "length", "mask", "maskFor", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "wrapHash", "hashFn", "hashing", "value", "InfiniteHash", "bits", "pendingBits", "result", "hash", "available", "took", "availableForUntake", "concat", "hashValue", "buffer", "ConsumableBuffer", "createHAMT", "options", "bucketOptions", "wrapHash", "Bucket", "import_murmurhash3js_revisited", "fromNumberTo32BitBuf", "number", "bytes", "i", "murmur332", "from", "input", "mur", "murmur3128", "bytes_exports", "murmur364", "hashFn", "buf", "murmur3128", "addLinksToHamtBucket", "links", "bucket", "rootBucket", "link", "pos", "Bucket", "toPrefix", "position", "toBucketPath", "path", "findShardCid", "node", "name", "blockstore", "context", "options", "createHAMT", "prefix", "bucketPath", "entryPrefix", "entryName", "block", "decode", "find_cid_in_shard_default", "extractDataFromBlock", "block", "blockStart", "requestedStart", "requestedEnd", "blockLength", "blockEnd", "extract_data_from_block_default", "import_err_code", "validateOffsetAndLength", "size", "offset", "length", "errCode", "validate_offset_and_length_default", "import_err_code", "pDefer", "deferred", "resolve", "reject", "CustomEvent", "parallel", "source", "options", "concurrency", "ordered", "emitter", "ops", "slotAvailable", "pDefer", "resultAvailable", "sourceFinished", "sourceErr", "opErred", "task", "op", "result", "err", "valuesAvailable", "_a", "yieldOrderedValues", "yieldUnOrderedValues", "i", "import_eventemitter3", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "__classPrivateFieldGet", "receiver", "state", "kind", "f", "_PriorityQueue_queue", "PriorityQueue", "run", "options", "element", "index", "lowerBound", "a", "b", "item", "__classPrivateFieldSet", "receiver", "state", "value", "kind", "f", "__classPrivateFieldGet", "_PQueue_instances", "_PQueue_carryoverConcurrencyCount", "_PQueue_isIntervalIgnored", "_PQueue_intervalCount", "_PQueue_intervalCap", "_PQueue_interval", "_PQueue_intervalEnd", "_PQueue_intervalId", "_PQueue_timeoutId", "_PQueue_queue", "_PQueue_queueClass", "_PQueue_pending", "_PQueue_concurrency", "_PQueue_isPaused", "_PQueue_throwOnTimeout", "_PQueue_doesIntervalAllowAnother_get", "_PQueue_doesConcurrentAllowAnother_get", "_PQueue_next", "_PQueue_onResumeInterval", "_PQueue_isIntervalPaused_get", "_PQueue_tryToStartAnother", "_PQueue_initializeIntervalIfNeeded", "_PQueue_onInterval", "_PQueue_processQueue", "_PQueue_throwOnAbort", "_PQueue_onEvent", "AbortError", "PQueue", "EventEmitter", "options", "_a", "_b", "_c", "_d", "PriorityQueue", "newConcurrency", "function_", "resolve", "reject", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "limit", "now", "delay", "canInitializeInterval", "job", "signal", "_resolve", "event", "filter", "listener", "walkDAG", "blockstore", "node", "queue", "streamPosition", "start", "end", "walkQueue", "options", "extract_data_from_block_default", "errCode", "file", "UnixFS", "err", "data", "buf", "childOps", "i", "childLink", "childStart", "childEnd", "pipe", "source", "map", "op", "block", "parallel", "link", "blockStart", "child", "code", "decode", "fileContent", "cid", "unixfs", "path", "resolve", "depth", "yieldFileContent", "fileSize", "offset", "length", "validate_offset_and_length_default", "PQueue", "pushable", "error", "read", "file_default", "directoryContent", "cid", "node", "unixfs", "path", "resolve", "depth", "blockstore", "yieldDirectoryContent", "options", "offset", "length", "links", "link", "result", "directory_default", "hamtShardedDirectoryContent", "cid", "node", "unixfs", "path", "resolve", "depth", "blockstore", "yieldHamtDirectoryContent", "options", "listDirectory", "links", "link", "name", "block", "decode", "file", "hamt_sharded_directory_default", "findLinkCid", "node", "name", "link", "contentExporters", "file_default", "directory_default", "hamt_sharded_directory_default", "cid", "unixfs", "path", "resolve", "depth", "blockstore", "unixFsResolver", "toResolve", "options", "block", "decode", "next", "errCode", "UnixFS", "err", "linkCid", "find_cid_in_shard_default", "nextName", "nextPath", "unixfs_v1_default", "import_err_code", "rawContent", "node", "contentGenerator", "options", "offset", "length", "validate_offset_and_length_default", "extract_data_from_block_default", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "errCode", "block", "raw_default", "import_err_code", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "options", "block", "object", "decode", "subObject", "subPath", "prop", "subObjectCid", "CID", "errCode", "dag_cbor_default", "import_err_code", "rawContent", "node", "contentGenerator", "options", "offset", "length", "validate_offset_and_length_default", "extract_data_from_block_default", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "errCode", "buf", "decode", "identity_default", "resolvers", "code", "unixfs_v1_default", "raw_default", "dag_cbor_default", "identity", "identity_default", "resolve", "cid", "name", "path", "toResolve", "depth", "blockstore", "options", "resolver", "errCode", "resolvers_default", "last", "source", "res", "entry", "toPathComponents", "path", "cidAndRest", "CID", "cid", "output", "errCode", "walkPath", "blockstore", "options", "toResolve", "name", "entryPath", "startingDepth", "result", "resolvers_default", "exporter", "last", "recursive", "node", "child", "recurse", "file", "createCat", "repo", "preload", "cat", "ipfsPath", "options", "normalizeCidPath", "pathComponents", "CID", "file", "exporter", "withTimeoutOption", "import_err_code", "ZERO_OFFSET", "USTAR_MAGIC", "fromString", "GNU_MAGIC", "GNU_VER", "import_iso_constants", "isAsyncIterable", "thing", "toBuffer", "source", "buffer", "buf", "concat", "bufs", "length", "src_default", "ZEROS", "SEVENS", "ZERO_OFFSET", "USTAR_MAGIC", "fromString", "USTAR_VER", "MASK", "MAGIC_OFFSET", "VERSION_OFFSET", "toTypeflag", "flag", "cksum", "block", "sum", "i", "j", "encodeOct", "val", "n", "str", "addLength", "len", "digits", "encodePax", "opts", "result", "pax", "key", "encode", "buf", "name", "prefix", "S_IFMT", "S_IFBLK", "S_IFCHR", "S_IFDIR", "S_IFIFO", "S_IFLNK", "isoConstants", "DMODE", "FMODE", "END_OF_TAR", "modeToType", "mode", "getPadding", "size", "encode", "header", "encoded", "encodePax", "paxHeader", "newHeader", "Uint8ArrayList", "pack", "source", "partialHeader", "body", "fromString", "isUint8ArrayList", "toString", "src_default", "written", "chunk", "zero$1", "buf", "len", "STORED_BLOCK", "STATIC_TREES", "DYN_TREES", "MIN_MATCH$1", "MAX_MATCH$1", "LENGTH_CODES$1", "LITERALS$1", "L_CODES$1", "D_CODES$1", "BL_CODES$1", "HEAP_SIZE$1", "MAX_BITS$1", "Buf_size", "MAX_BL_BITS", "END_BLOCK", "REP_3_6", "REPZ_3_10", "REPZ_11_138", "extra_lbits", "extra_dbits", "extra_blbits", "bl_order", "DIST_CODE_LEN", "static_ltree", "static_dtree", "_dist_code", "_length_code", "base_length", "base_dist", "StaticTreeDesc", "static_tree", "extra_bits", "extra_base", "elems", "max_length", "static_l_desc", "static_d_desc", "static_bl_desc", "TreeDesc", "dyn_tree", "stat_desc", "d_code", "dist", "put_short", "s", "w", "send_bits", "value", "length", "send_code", "c", "tree", "bi_reverse", "code", "res", "bi_flush", "gen_bitlen", "desc", "max_code", "stree", "has_stree", "extra", "base", "h", "n", "m", "bits", "xbits", "f", "overflow", "gen_codes", "bl_count", "next_code", "tr_static_init", "init_block", "bi_windup", "smaller", "depth", "_n2", "_m2", "pqdownheap", "k", "v", "j", "compress_block", "ltree", "dtree", "lc", "sx", "build_tree", "node", "scan_tree", "prevlen", "curlen", "nextlen", "count", "max_count", "min_count", "send_tree", "build_bl_tree", "max_blindex", "send_all_trees", "lcodes", "dcodes", "blcodes", "rank", "detect_data_type", "block_mask", "static_init_done", "_tr_init$1", "_tr_stored_block$1", "stored_len", "last", "_tr_align$1", "_tr_flush_block$1", "opt_lenb", "static_lenb", "_tr_tally$1", "_tr_init_1", "_tr_stored_block_1", "_tr_flush_block_1", "_tr_tally_1", "_tr_align_1", "trees", "adler32", "adler", "pos", "s1", "s2", "adler32_1", "makeTable", "table", "crcTable", "crc32", "crc", "t", "end", "i", "crc32_1", "messages", "constants$2", "_tr_init", "_tr_stored_block", "_tr_flush_block", "_tr_tally", "_tr_align", "Z_NO_FLUSH$2", "Z_PARTIAL_FLUSH", "Z_FULL_FLUSH$1", "Z_FINISH$3", "Z_BLOCK$1", "Z_OK$3", "Z_STREAM_END$3", "Z_STREAM_ERROR$2", "Z_DATA_ERROR$2", "Z_BUF_ERROR$1", "Z_DEFAULT_COMPRESSION$1", "Z_FILTERED", "Z_HUFFMAN_ONLY", "Z_RLE", "Z_FIXED", "Z_DEFAULT_STRATEGY$1", "Z_UNKNOWN", "Z_DEFLATED$2", "MAX_MEM_LEVEL", "MAX_WBITS$1", "DEF_MEM_LEVEL", "LENGTH_CODES", "LITERALS", "L_CODES", "D_CODES", "BL_CODES", "HEAP_SIZE", "MAX_BITS", "MIN_MATCH", "MAX_MATCH", "MIN_LOOKAHEAD", "PRESET_DICT", "INIT_STATE", "GZIP_STATE", "EXTRA_STATE", "NAME_STATE", "COMMENT_STATE", "HCRC_STATE", "BUSY_STATE", "FINISH_STATE", "BS_NEED_MORE", "BS_BLOCK_DONE", "BS_FINISH_STARTED", "BS_FINISH_DONE", "OS_CODE", "err", "strm", "errorCode", "zero", "slide_hash", "p", "wsize", "HASH_ZLIB", "prev", "data", "HASH", "flush_pending", "flush_block_only", "put_byte", "b", "putShortMSB", "read_buf", "start", "size", "longest_match", "cur_match", "chain_length", "scan", "match", "best_len", "nice_match", "limit", "_win", "wmask", "strend", "scan_end1", "scan_end", "fill_window", "_w_size", "more", "str", "deflate_stored", "flush", "min_block", "left", "have", "used", "deflate_fast", "hash_head", "bflush", "deflate_slow", "max_insert", "deflate_rle", "deflate_huff", "Config", "good_length", "max_lazy", "nice_length", "max_chain", "func", "configuration_table", "lm_init", "DeflateState", "deflateStateCheck", "deflateResetKeep", "deflateReset", "ret", "deflateSetHeader", "head", "deflateInit2", "level", "method", "windowBits", "memLevel", "strategy", "wrap", "deflateInit", "deflate$2", "old_flush", "header", "level_flags", "beg", "copy", "gzhead_extra", "val", "bstate", "deflateEnd", "status", "deflateSetDictionary", "dictionary", "dictLength", "tmpDict", "avail", "next", "input", "deflateInit_1", "deflateInit2_1", "deflateReset_1", "deflateResetKeep_1", "deflateSetHeader_1", "deflate_2$1", "deflateEnd_1", "deflateSetDictionary_1", "deflateInfo", "deflate_1$2", "_has", "obj", "key", "assign", "sources", "source", "flattenChunks", "chunks", "l", "result", "chunk", "common", "STR_APPLY_UIA_OK", "_utf8len", "q", "string2buf", "c2", "m_pos", "str_len", "buf_len", "buf2binstring", "buf2string", "max", "out", "utf16buf", "c_len", "utf8border", "strings", "ZStream", "zstream", "toString$1", "Z_NO_FLUSH$1", "Z_SYNC_FLUSH", "Z_FULL_FLUSH", "Z_FINISH$2", "Z_OK$2", "Z_STREAM_END$2", "Z_DEFAULT_COMPRESSION", "Z_DEFAULT_STRATEGY", "Z_DEFLATED$1", "Deflate$1", "options", "opt", "dict", "flush_mode", "chunkSize", "_flush_mode", "deflate$1", "deflator", "deflateRaw$1", "gzip$1", "Deflate_1$1", "deflate_2", "deflateRaw_1$1", "gzip_1$1", "constants$1", "deflate_1$1", "BAD$1", "TYPE$1", "inffast", "_in", "_out", "dmax", "whave", "wnext", "s_window", "hold", "lcode", "dcode", "lmask", "dmask", "here", "op", "from", "from_source", "output", "state", "top", "dolen", "dodist", "MAXBITS", "ENOUGH_LENS$1", "ENOUGH_DISTS$1", "CODES$1", "LENS$1", "DISTS$1", "lbase", "lext", "dbase", "dext", "inflate_table", "type", "lens", "lens_index", "codes", "table_index", "work", "opts", "sym", "min", "root", "curr", "drop", "huff", "incr", "fill", "low", "mask", "offs", "here_bits", "here_op", "here_val", "inftrees", "CODES", "LENS", "DISTS", "Z_FINISH$1", "Z_BLOCK", "Z_TREES", "Z_OK$1", "Z_STREAM_END$1", "Z_NEED_DICT$1", "Z_STREAM_ERROR$1", "Z_DATA_ERROR$1", "Z_MEM_ERROR$1", "Z_BUF_ERROR", "Z_DEFLATED", "HEAD", "FLAGS", "TIME", "OS", "EXLEN", "EXTRA", "NAME", "COMMENT", "HCRC", "DICTID", "DICT", "TYPE", "TYPEDO", "STORED", "COPY_", "COPY", "TABLE", "LENLENS", "CODELENS", "LEN_", "LEN", "LENEXT", "DIST", "DISTEXT", "MATCH", "LIT", "CHECK", "LENGTH", "DONE", "BAD", "MEM", "SYNC", "ENOUGH_LENS", "ENOUGH_DISTS", "MAX_WBITS", "DEF_WBITS", "zswap32", "InflateState", "inflateStateCheck", "inflateResetKeep", "inflateReset", "inflateReset2", "inflateInit2", "inflateInit", "virgin", "lenfix", "distfix", "fixedtables", "updatewindow", "src", "inflate$2", "put", "last_bits", "last_op", "last_val", "hbuf", "order", "inf_leave", "inflateEnd", "inflateGetHeader", "inflateSetDictionary", "dictid", "inflateReset_1", "inflateReset2_1", "inflateResetKeep_1", "inflateInit_1", "inflateInit2_1", "inflate_2$1", "inflateEnd_1", "inflateGetHeader_1", "inflateSetDictionary_1", "inflateInfo", "inflate_1$2", "GZheader", "gzheader", "toString", "Z_NO_FLUSH", "Z_FINISH", "Z_OK", "Z_STREAM_END", "Z_NEED_DICT", "Z_STREAM_ERROR", "Z_DATA_ERROR", "Z_MEM_ERROR", "Inflate$1", "last_avail_out", "next_out_utf8", "tail", "utf8str", "inflate$1", "inflator", "inflateRaw$1", "Inflate_1$1", "inflate_2", "inflateRaw_1$1", "ungzip$1", "constants", "inflate_1$1", "Deflate", "deflate", "deflateRaw", "gzip", "Inflate", "inflate", "inflateRaw", "ungzip", "Deflate_1", "deflate_1", "deflateRaw_1", "gzip_1", "Inflate_1", "inflate_1", "inflateRaw_1", "ungzip_1", "constants_1", "pako", "toBuffer", "stream", "buffer", "buf", "concat", "DEFAULT_COMPRESSION_LEVEL", "createGet", "repo", "preload", "get", "ipfsPath", "options", "errCode", "pathComponents", "normalizeCidPath", "err", "CID", "ipfsPathOrCid", "file", "exporter", "args", "pack", "source", "buf", "toBuffer", "pako", "pipe", "recursive", "entry", "output", "withTimeoutOption", "import_err_code", "createLs", "repo", "preload", "ls", "ipfsPath", "options", "legacyPath", "normalizeCidPath", "pathComponents", "CID", "ipfsPathOrCid", "file", "exporter", "mapFile", "child", "errCode", "withTimeoutOption", "RootAPI", "preload", "repo", "hashers", "options", "addAll", "createAddAll", "createAdd", "createCat", "createGet", "createLs", "ipfsCore", "commit", "interfaceIpfsCore", "createVersion", "repo", "version", "_options", "repoVersion", "ipfsCore", "commit", "interfaceIpfsCore", "withTimeoutOption", "import_err_code", "log", "logger", "createId", "peerId", "network", "id", "options", "net", "NotStartedError", "errCode", "toString", "ipfsCore", "libp2p", "peerIdToId", "peer", "findPeer", "agentVersion", "protocolVersion", "idStr", "publicKeyStr", "ma", "str", "multiaddr", "withTimeoutOption", "findPeerOnDht", "publicKey", "err", "addr", "event", "objectSafeSet", "set", "obj", "propsArg", "value", "props", "lastProp", "prototypeCheck", "thisProp", "prop", "profiles", "config", "objectSafeSet", "defaultConfig", "config_browser_default", "Swarm", "ConnMgr", "log", "logger", "createConfig", "repo", "withTimeoutOption", "getAll", "get", "set", "replace", "applyProfile", "listProfiles", "options", "key", "value", "profileName", "dryRun", "profile", "profiles", "oldCfg", "newCfg", "err", "_options", "name", "readonly", "enumerable", "configurable", "linksWithin", "path", "value", "index", "element", "elementPath", "cid", "CID", "links", "source", "base", "key", "treeWithin", "tree", "get", "node", "part", "Block", "bytes", "createUnsafe", "bytes", "cid", "maybeValue", "codec", "value", "Block", "import_varint", "CIDV0_BYTES", "V2_HEADER_LENGTH", "decodeVarint", "bytes", "seeker", "i", "varint", "decodeV2Header", "dv", "offset", "getMultihashLength", "codeLength", "length", "lengthLength", "Kinds", "obj", "Types", "i", "v", "ret", "j", "entries", "requiredCount", "key", "value", "Reprs", "CarV1HeaderOrV2Pragma", "readHeader", "reader", "strictVersion", "length", "decodeVarint", "header", "block", "decode", "CarV1HeaderOrV2Pragma", "v2Header", "decodeV2Header", "V2_HEADER_LENGTH", "v1Header", "readCid", "first", "CIDV0_BYTES", "bytes", "multihash", "CID", "version", "codec", "getMultihashLength", "readBlockHead", "start", "cid", "blockLength", "readBlock", "readBlockIndex", "offset", "index", "createDecoder", "headerPromise", "v1length", "limitReader", "bytesReader", "pos", "seek", "out", "chunkReader", "readChunk", "have", "currentChunk", "read", "bufa", "chunk", "p", "c", "off", "b", "asyncIterableReader", "asyncIterable", "iterator", "next", "byteLimit", "bytesRead", "import_varint", "CAR_V1_VERSION", "createHeader", "roots", "headerBytes", "encode", "varintBytes", "varint", "header", "createEncoder", "writer", "bytes", "block", "cid", "noop", "create", "chunkQueue", "drainer", "drainerResolver", "ended", "outWait", "outWaitResolver", "makeDrainer", "resolve", "writer", "chunk", "iterator", "CarWriter", "roots", "encoder", "block", "cid", "CID", "toRoots", "iterator", "encodeWriter", "writer", "out", "CarWriterOut", "bytes", "reader", "bytesReader", "readHeader", "newHeader", "createHeader", "iw", "create", "createEncoder", "_roots", "root", "_root", "walk", "cid", "load", "seen", "b58Cid", "base58btc", "block", "log", "logger", "NO_LINKS_CODECS", "code", "createExport", "repo", "preload", "codecs", "dagExport", "root", "options", "cid", "CID", "writer", "out", "CarWriter", "err", "load", "makeLoader", "walk", "e", "chunk", "withTimeoutOption", "codec", "bytes", "createUnsafe", "first", "source", "entry", "import_err_code", "createGet", "codecs", "repo", "preload", "withTimeoutOption", "cid", "options", "result", "first", "resolve", "last", "errCode", "codec", "block", "CarIteratorBase", "version", "roots", "iterable", "CarBlockIterator", "bytes", "iterator", "fromBytes", "asyncIterable", "fromIterable", "CarCIDIterator", "next", "decodeIterator", "bytesReader", "asyncIterableReader", "reader", "decoder", "createDecoder", "log", "logger", "createImport", "repo", "dagImport", "sources", "options", "release", "abortOptions", "peekable", "peekableIterator", "value", "done", "cars", "car", "roots", "importCar", "cid", "pinErrorMsg", "err", "withTimeoutOption", "source", "reader", "CarBlockIterator", "drain", "map", "key", "createPut", "repo", "codecs", "hashers", "preload", "put", "dagNode", "options", "release", "storeCodec", "inputCodec", "cidVersion", "hasher", "buf", "hash", "cid", "CID", "withTimeoutOption", "createResolve", "repo", "codecs", "preload", "dagResolve", "ipfsPath", "options", "cid", "toCidAndPath", "resolvePath", "withTimeoutOption", "DagAPI", "repo", "codecs", "hashers", "preload", "createExport", "createGet", "createImport", "createResolve", "createPut", "extractSNI", "ma", "sniProtoCode", "getProtocol", "proto", "value", "hasTLS", "_", "interpretNext", "headProtoCode", "headProtoVal", "restMa", "interpreter", "interpreters", "restVal", "tailProto", "maHasTLS", "sni", "protocol", "baseVal", "multiaddrToUri", "input", "opts", "parts", "multiaddr", "head", "uri", "arrayShuffle", "array", "index", "newIndex", "import_http", "log", "logger", "Queue", "dist_default", "httpQueue", "preload", "url", "options", "reader", "HTTP", "done", "import_hashlru", "log", "logger", "createPreloader", "options", "stopped", "requests", "apiUris", "str", "multiaddrToUri", "cache", "hashlru", "api", "cid", "path", "fallbackApiUris", "arrayShuffle", "success", "now", "uri", "controller", "preload", "err", "r", "log", "logger", "createMfsPreloader", "preload", "files", "options", "noop", "rootCid", "timeoutId", "preloadMfs", "stats", "nextRootCid", "err", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "_queue", "PriorityQueue", "__privateAdd", "run", "options", "element", "__privateGet", "index", "lowerBound", "a", "b", "item", "_carryoverConcurrencyCount", "_isIntervalIgnored", "_intervalCount", "_intervalCap", "_interval", "_intervalEnd", "_intervalId", "_timeoutId", "_queue", "_queueClass", "_pending", "_concurrency", "_isPaused", "_throwOnTimeout", "_doesIntervalAllowAnother", "doesIntervalAllowAnother_get", "_doesConcurrentAllowAnother", "doesConcurrentAllowAnother_get", "_next", "next_fn", "_onResumeInterval", "onResumeInterval_fn", "_isIntervalPaused", "isIntervalPaused_get", "_tryToStartAnother", "tryToStartAnother_fn", "_initializeIntervalIfNeeded", "initializeIntervalIfNeeded_fn", "_onInterval", "onInterval_fn", "_processQueue", "processQueue_fn", "_throwOnAbort", "throwOnAbort_fn", "_onEvent", "onEvent_fn", "PQueue", "EventEmitter", "options", "_a", "_b", "__privateAdd", "__publicField", "PriorityQueue", "__privateSet", "__privateGet", "newConcurrency", "__privateMethod", "function_", "resolve", "reject", "__privateWrapper", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "limit", "now", "delay", "canInitializeInterval", "job", "signal", "_resolve", "event", "filter", "listener", "events", "observable", "worker", "event", "type", "fn", "listener", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "nanoid", "size", "handleWorkerLockRequest", "emitter", "masterEvent", "requestType", "releaseType", "grantType", "worker", "event", "requestEvent", "resolve", "releaseEventListener", "releaseEvent", "makeWorkerLockRequest", "name", "id", "nanoid", "listener", "responseEvent", "defaultOptions", "browser_default", "options", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "mutexes", "implementation", "createReleaseable", "queue", "options", "res", "p", "resolve", "pTimeout", "createMutex", "name", "masterQueue", "PQueue", "readQueue", "localReadQueue", "readPromise", "defaultOptions", "createMortice", "opts", "browser_default", "event", "release", "lock", "createLock", "repoOwner", "mutex", "createMortice", "func", "args", "releaseLock", "import_err_code", "log", "logger", "loadMfsRoot", "context", "options", "errCode", "cid", "buf", "MFS_ROOT_KEY", "CID", "err", "encode", "UnixFS", "hash", "sha256", "toPathComponents", "path", "import_err_code", "IPFS_PREFIX", "toMfsPath", "context", "path", "options", "root", "loadMfsRoot", "output", "ipfsPath", "CID", "errCode", "pathComponents", "toPathComponents", "mfsDirectory", "mfsPath", "cidPath", "res", "exporter", "err", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createStat", "context", "mfsStat", "path", "options", "type", "cid", "mfsPath", "toMfsPath", "exportPath", "file", "exporter", "err", "errCode", "statters", "withTimeoutOption", "stat", "encode", "acc", "curr", "import_err_code", "log", "logger", "toTrail", "context", "path", "output", "fsEntry", "walkPath", "persist", "buffer", "blockstore", "options", "src_exports", "sha256", "multihash", "cid", "CID", "hamtHashCode", "murmur3128", "hamtBucketBits", "hamtHashFn", "buf", "Dir", "props", "options", "name", "value", "blockstore", "DirSharded", "createHAMT", "hamtHashFn", "hamtBucketBits", "key", "flush", "bucket", "shardRoot", "children", "links", "childrenSize", "i", "child", "labelPrefix", "Bucket", "shard", "subShard", "dir", "flushedDir", "entry", "label", "size", "data", "node", "UnixFS", "hamtHashCode", "buffer", "encode", "prepare", "cid", "persist", "log", "logger", "updateHamtDirectory", "context", "links", "bucket", "options", "data", "node", "UnixFS", "dir", "hamtHashCode", "hasher", "parent", "a", "b", "buf", "encode", "hash", "cid", "CID", "code", "sum", "link", "recreateHamtLevel", "rootBucket", "parentBucket", "positionAtParent", "Bucket", "addLinksToHamtBucket", "recreateInitialHamtLevel", "createHAMT", "hamtHashFn", "hamtBucketBits", "linkName", "pos", "subBucket", "block", "decode", "toPrefix", "position", "generatePath", "fileName", "rootNode", "path", "currentBucket", "i", "segment", "nextSegment", "createShard", "contents", "shard", "DirSharded", "res", "last", "import_err_code", "log", "logger", "addLink", "context", "options", "parent", "parentCid", "CID", "errCode", "code", "block", "decode", "meta", "UnixFS", "addToShardedDirectory", "convertToShardedDirectory", "addToDirectory", "result", "createShard", "link", "parentLinks", "node", "data", "ms", "secs", "prepare", "hasher", "buf", "encode", "hash", "cid", "shard", "path", "addFileToShardedDirectory", "last", "newLink", "updateHamtDirectory", "file", "rootBucket", "recreateInitialHamtLevel", "DirSharded", "position", "toBucketPath", "index", "segment", "subShard", "recreateHamtLevel", "toPrefix", "nextSegment", "addLinksToHamtBucket", "bucket", "positionInBucket", "log", "logger", "defaultOptions", "updateTree", "context", "trail", "options", "index", "child", "block", "node", "decode", "cid", "name", "result", "addLink", "import_err_code", "log", "logger", "updateMfsRoot", "context", "cid", "options", "errCode", "MFS_ROOT_KEY", "import_err_code", "createNode", "context", "type", "options", "metadata", "UnixFS", "hasher", "node", "buf", "encode", "hash", "cid", "CID", "code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createMkdir", "context", "mfsMkdir", "path", "options", "opts", "errCode", "pathComponents", "toPathComponents", "root", "loadMfsRoot", "parent", "trail", "emptyDir", "createNode", "i", "subPathComponents", "subPath", "exporter", "err", "addEmptyDir", "newRootCid", "updateTree", "updateMfsRoot", "withTimeoutOption", "childName", "result", "addLink", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createCp", "context", "mfsCp", "from", "to", "opts", "options", "sources", "path", "toMfsPath", "destination", "errCode", "missing", "source", "destinationIsDirectory", "isDirectory", "createMkdir", "parentFolder", "createStat", "err", "destinationPath", "trail", "toTrail", "destinationName", "copyToFile", "copyToDirectory", "withTimeoutOption", "destinationTrail", "parent", "addSourceToParent", "newRootCid", "updateTree", "updateMfsRoot", "i", "childName", "sourceBlock", "node", "cid", "size", "addLink", "import_err_code", "import_err_code", "log", "logger", "removeLink", "context", "options", "parent", "parentCid", "CID", "errCode", "block", "decode", "UnixFS", "removeFromShardedDirectory", "removeFromDirectory", "link", "parentBlock", "encode", "hash", "code", "rootBucket", "path", "generatePath", "node", "updateShard", "updateHamtDirectory", "positions", "name", "last", "bucket", "prefix", "links", "nodeLink", "result", "cid", "size", "newName", "updateShardParent", "oldName", "parentLinks", "mergeOptions", "merge_options_default", "defaultOptions", "createRm", "context", "mfsRm", "paths", "opts", "options", "sources", "path", "toMfsPath", "errCode", "source", "removePath", "withTimeoutOption", "mfsPath", "trail", "toTrail", "child", "parent", "cid", "removeLink", "newRootCid", "updateTree", "updateMfsRoot", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "calculateModification", "mode", "originalMode", "isDirectory", "modification", "calculateUGO", "references", "ugo", "calculateSpecial", "parseSymbolicMode", "input", "match", "operator", "calculateMode", "metadata", "strMode", "curr", "acc", "createChmod", "context", "mfsChmod", "path", "options", "opts", "cid", "mfsDirectory", "name", "toMfsPath", "code", "errCode", "root", "pipe", "entry", "recursive", "node", "prepare", "source", "importer", "block", "buf", "encode", "persist", "unixfs", "UnixFS", "nodes", "last", "createRm", "createCp", "decode", "updatedBlock", "hashAlg", "hash", "updatedCid", "CID", "trail", "toTrail", "parent", "parentCid", "parentBlock", "parentNode", "result", "addLink", "newRootCid", "updateTree", "updateMfsRoot", "withTimeoutOption", "mergeOptions", "merge_options_default", "defaultOptions", "createFlush", "context", "mfsFlush", "path", "options", "cid", "createStat", "withTimeoutOption", "mergeOptions", "merge_options_default", "defaultOptions", "createMv", "context", "mfsMv", "from", "to", "options", "opts", "createCp", "createRm", "withTimeoutOption", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "createTouch", "context", "mfsTouch", "path", "options", "settings", "cid", "mfsDirectory", "name", "exists", "toMfsPath", "hashAlg", "hasher", "updatedBlock", "updatedCid", "cidVersion", "code", "errCode", "block", "node", "decode", "metadata", "UnixFS", "encode", "hash", "CID", "trail", "toTrail", "parent", "parentCid", "parentBlock", "parentNode", "result", "addLink", "newRootCid", "updateTree", "updateMfsRoot", "withTimeoutOption", "import_err_code", "mergeOptions", "merge_options_default", "defaultOptions", "createRead", "context", "mfsRead", "path", "options", "mfsPath", "toMfsPath", "result", "exporter", "errCode", "buf", "withTimeoutOption", "import_err_code", "log", "logger", "toAsyncIterator", "content", "errCode", "fromString", "browserReadableStreamToIt", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "defaultOptions", "bytes", "path", "createWrite", "context", "mfsWrite", "content", "opts", "options", "source", "destination", "parent", "createLock", "toAsyncIterator", "toMfsPath", "errCode", "updateOrImport", "withTimeoutOption", "child", "write", "pathComponents", "toPathComponents", "fileName", "parentExists", "createStat", "err", "createMkdir", "updatedPath", "trail", "toTrail", "parentBlock", "parentNode", "decode", "result", "addLink", "newRootCid", "updateTree", "updateMfsRoot", "sources", "extra", "asyncZeroes", "limitAsyncStreamBytes", "countBytesStreamed", "catAsyncIterators", "bytesWritten", "fileSize", "mode", "parseMode", "mtime", "parseMtime", "hasher", "last", "importer", "stream", "limit", "emitted", "buf", "count", "chunkSize", "MFS_MAX_CHUNK_SIZE", "_asyncZeroes", "i", "notify", "wrote", "toOutput", "fsEntry", "output", "createLs", "context", "mfsLs", "path", "options", "mfsPath", "toMfsPath", "exporter", "map", "withTimeoutOption", "readOperations", "createStat", "writeOperations", "createChmod", "createCp", "createFlush", "createMkdir", "createMv", "createRm", "createTouch", "unwrappedOperations", "createWrite", "createRead", "createLs", "wrap", "options", "mfs", "operations", "lock", "key", "defaultOptions", "createMfs", "repoOwner", "createLock", "readLock", "operation", "writeLock", "createFiles", "repo", "preload", "hashers", "constructorOptions", "methods", "withPreload", "fn", "args", "paths", "arg", "ipfsPath", "isCID", "path", "file", "createExport", "keychain", "withTimeoutOption", "name", "password", "DEFAULT_KEY_TYPE", "DEFAULT_KEY_SIZE", "createGen", "keychain", "withTimeoutOption", "name", "options", "createImport", "keychain", "withTimeoutOption", "name", "pem", "password", "createInfo", "keychain", "withTimeoutOption", "name", "createList", "keychain", "withTimeoutOption", "createRename", "keychain", "withTimeoutOption", "oldName", "newName", "key", "createRm", "keychain", "withTimeoutOption", "name", "KeyAPI", "keychain", "createGen", "createList", "createRm", "createRename", "createExport", "createImport", "createInfo", "createGet", "repo", "preload", "get", "cid", "options", "block", "decode", "withTimeoutOption", "createData", "repo", "preload", "get", "createGet", "data", "multihash", "options", "withTimeoutOption", "findLinks", "node", "links", "key", "val", "CID", "cid", "createLinks", "repo", "codecs", "options", "codec", "block", "code", "withTimeoutOption", "createNew", "repo", "preload", "_new", "options", "data", "UnixFS", "buf", "encode", "hash", "sha256", "cid", "CID", "withTimeoutOption", "createPut", "repo", "preload", "put", "obj", "options", "release", "buf", "encode", "hash", "sha256", "cid", "CID", "code", "withTimeoutOption", "createStat", "repo", "preload", "get", "createGet", "stat", "cid", "options", "node", "blockSize", "encode", "linkLength", "a", "l", "withTimeoutOption", "createAddLink", "repo", "preload", "get", "createGet", "put", "createPut", "addLink", "cid", "link", "options", "node", "withTimeoutOption", "createAppendData", "repo", "preload", "get", "createGet", "put", "createPut", "appendData", "cid", "data", "options", "node", "newData", "concat", "withTimeoutOption", "createRmLink", "repo", "preload", "get", "createGet", "put", "createPut", "rmLink", "cid", "link", "options", "node", "name", "withTimeoutOption", "createSetData", "repo", "preload", "get", "createGet", "put", "createPut", "setData", "cid", "data", "options", "node", "withTimeoutOption", "ObjectPatchAPI", "repo", "preload", "createAddLink", "createAppendData", "createRmLink", "createSetData", "ObjectAPI", "repo", "codecs", "preload", "createData", "createGet", "createLinks", "createNew", "createPut", "createStat", "ObjectPatchAPI", "log", "logger", "createGc", "repo", "hashers", "gc", "options", "start", "mfsRootCid", "loadMfsRoot", "withTimeoutOption", "createStat", "repo", "stat", "options", "stats", "withTimeoutOption", "createVersion", "repo", "version", "options", "err", "m", "withTimeoutOption", "RepoAPI", "repo", "hashers", "createGc", "createStat", "createVersion", "addr", "import_err_code", "getBandwidthStats", "libp2p", "opts", "createBw", "network", "withTimeoutOption", "options", "interval", "ms", "parse_duration_default", "err", "errCode", "timeoutId", "resolve", "StatsAPI", "repo", "network", "createStat", "createBw", "objectSafeGet", "get", "obj", "propsArg", "defaultValue", "props", "prop", "import_debug", "import_err_code", "import_debug", "length", "iterator", "count", "_", "log", "debug", "unwrap", "blockstore", "keyToMultihash", "key", "buf", "base32", "multihash", "CID", "multihashStr", "Key", "keyToCid", "digest", "decode", "code", "process", "backends", "onProgress", "keyFunction", "unwrapped", "blockCount", "length", "counter", "block", "newKey", "migration", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "ipfs", "pin", "Set", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "import_fnv1a", "import_varint", "PIN_DS_KEY", "Key", "DEFAULT_FANOUT", "MAX_ITEMS", "EMPTY_KEY", "CID", "PinTypes", "cidToKey", "cid", "base32", "compare", "a", "b", "i", "PinSet", "ipfs", "readHeader", "rootNode", "rootData", "hdrLength", "varint", "vBytes", "hdrSlice", "header", "hash", "seed", "key", "buffer", "encodedKey", "fromString", "data", "concat", "fnv1a", "toString", "walkItems", "blockstore", "node", "pbh", "idx", "link", "linkHash", "EMPTY_KEY", "buf", "decode", "loadSet", "name", "l", "storeItems", "items", "storePins", "pins", "depth", "pbHeader", "DEFAULT_FANOUT", "headerBuf", "fanoutLinks", "i", "MAX_ITEMS", "nodes", "item", "a", "b", "compare", "rootLinks", "bins", "pin", "n", "bin", "child", "storeChild", "binIdx", "encode", "digest", "sha256", "cid", "CID", "size", "acc", "curr", "storeSet", "type", "cids", "pinsToDatastore", "blockstore", "datastore", "pinstore", "onProgress", "PIN_DS_KEY", "mh", "cid", "CID", "pinRootBuf", "pinRoot", "decode", "counter", "pinCount", "length", "loadSet", "PinTypes", "pin", "code", "cidToKey", "encode", "pinsToDAG", "recursivePins", "directPins", "key", "value", "base32", "storeSet", "buf", "digest", "sha256", "process", "backends", "fn", "migration", "CONFIG_KEY", "Key", "VERSION_KEY", "findLevelJs", "store", "db", "hasWithFallback", "key", "has", "result", "levelJs", "resolve", "reject", "req", "getWithFallback", "get", "notFoundError", "wrapStore", "originalGet", "originalHas", "wrapBackends", "backends", "keysToBinary", "name", "store", "onProgress", "db", "findLevelJs", "withEach", "key", "value", "fromString", "keysToStrings", "toString", "unwrap", "process", "backends", "fn", "datastores", "backend", "migrated", "progress", "message", "migration", "batch", "operations", "next", "transaction", "index", "error", "loop", "op", "req", "err", "resolve", "reject", "it", "id", "data", "handleNext", "handleEnd", "err2", "MFS_ROOT_KEY", "Key", "storeMfsRootInDatastore", "backends", "onProgress", "root", "storeMfsRootInRoot", "migration", "import_minimal", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Protocols", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "j", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Addresses", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "j", "Address", "$oneOfFields", "CertifiedRecord", "n", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Peer", "p", "ks", "$oneOfFields", "m", "w", "i", "r", "l", "c", "t", "d", "o", "j", "Address", "Metadata", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Envelope", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "PeerRecord", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "n", "j", "AddressInfo", "Parser", "__publicField", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "parseIP", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "isIP", "parseIP", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "import_varint", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "toString", "convertToBytes", "str", "ip2bytes", "str2bytes", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "fromString", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ipString", "isIP", "toBytes", "ipBuff", "port", "size", "varint", "concat", "hash", "mh", "decode", "base58btc", "CID", "mbstr", "mb", "address", "addr", "base32", "portBuf", "addrBytes", "portBytes", "import_varint", "stringToStringTuples", "str", "tuples", "parts", "p", "part", "proto", "getProtocol", "ParseError", "cleanPath", "stringTuplesToString", "tup", "protoFromTuple", "stringTuplesToTuples", "convertToBytes", "tuplesToStringTuples", "convertToString", "tuplesToBytes", "fromBytes", "concat", "buf", "varint", "sizeForAddr", "addr", "bytesToTuples", "i", "code", "n", "size", "toString", "bytesToString", "a", "b", "stringToBytes", "fromString", "err", "validateBytes", "cleanPath", "str", "a", "ParseError", "protoFromTuple", "tup", "getProtocol", "import_varint", "import_err_code", "inspect", "DNS_CODES", "getProtocol", "resolvers", "symbol", "fromNodeAddress", "addr", "transport", "ip", "host", "parts", "DefaultMultiaddr", "isName", "isMultiaddr", "proto", "value", "_DefaultMultiaddr_string", "_DefaultMultiaddr_tuples", "_DefaultMultiaddr_stringTuples", "_a", "fromBytes", "fromString", "__classPrivateFieldGet", "__classPrivateFieldSet", "bytesToString", "family", "port", "zone", "tcp", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "codes", "buf", "i", "varint", "n", "p", "size", "sizeForAddr", "bytesToTuples", "tuplesToStringTuples", "addrString", "s", "tuples", "tuplesToBytes", "tuple", "names", "peerIdStr", "toString", "base58btc", "CID", "path", "equals", "options", "resolvableProto", "resolver", "errCode", "a", "protos", "multiaddr", "$protobuf", "storePeerUnderSingleDatastoreKey", "backends", "onProgress", "peers", "keys", "key", "value", "keyStr", "prefix", "type", "peerId", "metadataKey", "protos", "Protocols", "addrs", "Addresses", "a", "b", "multiaddr", "peer", "data", "Peer", "Key", "storePeerUnderMultipleDatastoreKeys", "peerRecordEnvelope", "certifiedRecord", "envelope", "Envelope", "record", "PeerRecord", "migration", "emptyMigration", "migrations_default", "migration", "import_debug", "errors_exports", "__export", "InvalidValueError", "MissingRepoOptionsError", "NonReversibleMigrationError", "NotInitializedRepoError", "RequiredParameterError", "message", "log", "debug", "isRepoInitialized", "backends", "MissingRepoOptionsError", "root", "versionCheck", "VERSION_KEY", "configCheck", "CONFIG_KEY", "e", "getVersion", "backends", "isRepoInitialized", "NotInitializedRepoError", "store", "toString", "VERSION_KEY", "setVersion", "version", "MissingRepoOptionsError", "fromString", "import_debug", "log", "debug", "getLatestMigrationVersion", "migrations", "migrations_default", "migrate", "path", "backends", "repoOptions", "toVersion", "options", "ignoreLock", "onProgress", "isDryRun", "errors", "wrapBackends", "currentVersion", "getVersion", "verifyAvailableMigrations", "lock", "migration", "progressCallback", "percent", "message", "e", "lastSuccessfullyMigratedVersion", "setVersion", "revert", "reversedMigrationArray", "lastSuccessfullyRevertedVersion", "fromVersion", "checkReversibility", "migrationCounter", "errors", "errors_exports", "import_bytes", "import_debug", "LockExistsError", "message", "NotFoundError", "InvalidRepoVersionError", "ERR_REPO_NOT_INITIALIZED", "ERR_REPO_ALREADY_OPEN", "ERR_REPO_ALREADY_CLOSED", "hasWithFallback", "key", "has", "store", "result", "levelJs", "findLevelJs", "resolve", "reject", "req", "getWithFallback", "get", "NotFoundError", "db", "log", "debug", "versionKey", "Key", "version", "store", "hasWithFallback", "buf", "getWithFallback", "toString", "fromString", "expected", "import_err_code", "Queue", "PQueue", "configKey", "Key", "config", "store", "setQueue", "configStore", "options", "encodedValue", "getWithFallback", "toString", "key", "NotFoundError", "value", "objectSafeGet", "errCode", "_maybeDoSet", "hasWithFallback", "m", "signal", "objectSafeSet", "_saveAll", "buf", "fromString", "isPlainObject", "value", "prototype", "sortKeys", "object", "options", "isPlainObject", "deep", "compare", "seenInput", "seenOutput", "deepSortArray", "array", "seenIndex", "result", "item", "_sortKeys", "keys", "key", "value", "newValue", "specKey", "Key", "spec", "store", "buf", "toString", "fromString", "sortKeys", "apiFile", "Key", "apiAddr", "store", "value", "fromString", "import_err_code", "createIdStore", "store", "query", "options", "cid", "extracted", "extractContents", "cids", "buf", "isIdentity", "pairs", "output", "pushable", "drain", "key", "value", "err", "filter", "batch", "k", "CID", "errCode", "identity", "import_debug", "log", "debug", "lockFile", "LOCKS", "lock", "dir", "file", "LockExistsError", "locked", "MemoryLock", "default_options_default", "MemoryLock", "default_datastore_default", "import_err_code", "import_debug", "first", "source", "entry", "readonly", "enumerable", "configurable", "linksWithin", "path", "value", "index", "element", "elementPath", "cid", "CID", "links", "source", "base", "key", "treeWithin", "tree", "get", "node", "part", "Block", "bytes", "createUnsafe", "bytes", "cid", "maybeValue", "codec", "value", "Block", "import_err_code", "cidToKey", "c", "cid", "CID", "errCode", "encoded", "base32", "Key", "keyToMultihash", "key", "decode", "base32", "import_debug", "log", "debug", "walkDag", "cid", "blockstore", "loadCodec", "options", "bytes", "codec", "block", "createUnsafe", "childCid", "err", "QuickLRU", "options", "cache", "key", "item", "value", "maxAge", "expiry", "deleted", "newSize", "items", "removeCount", "i", "oldCacheSize", "callbackFunction", "thisArgument", "CID_CACHE_MAX_SIZE", "invalidPinTypeErr", "type", "errMsg", "errCode", "PinManager", "pinstore", "blockstore", "loadCodec", "debug", "cid", "options", "pin", "code", "cidToKey", "encode", "entry", "decode", "version", "codec", "multihash", "keyToMultihash", "CID", "childCid", "walkDag", "types", "PinTypes", "all", "direct", "recursive", "indirect", "result", "first", "self", "findChild", "key", "source", "parentCid", "seen", "QuickLRU", "bytes", "block", "createUnsafe", "import_err_code", "createPinnedBlockstore", "pins", "store", "query", "options", "cid", "cids", "buf", "pairs", "ensureNotPinned", "map", "pinned", "reason", "PinTypes", "errCode", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "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", "emitter", "masterEvent", "requestType", "releaseType", "grantType", "worker", "event", "requestEvent", "resolve", "releaseEventListener", "releaseEvent", "makeWorkerLockRequest", "name", "id", "nanoid", "listener", "responseEvent", "defaultOptions", "browser_default", "options", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "mutexes", "implementation", "createReleaseable", "queue", "options", "res", "p", "resolve", "pTimeout", "createMutex", "name", "masterQueue", "PQueue", "readQueue", "localReadQueue", "readPromise", "defaultOptions", "createMortice", "opts", "browser_default", "event", "release", "import_debug", "batch", "source", "size", "things", "thing", "parallelBatch", "source", "size", "tasks", "batch", "things", "p", "value", "err", "result", "log", "debug", "ERR_NOT_FOUND", "notFoundError", "BLOCK_RM_CONCURRENCY", "MFS_ROOT_KEY", "Key", "gc", "gcLock", "pins", "blockstore", "root", "loadCodec", "start", "release", "markedSet", "createMarkedSet", "blockKeys", "deleteUnmarkedBlocks", "mfsSource", "mh", "err", "rootCid", "CID", "walkDag", "pinsSource", "merge", "map", "cid", "output", "base32", "blocksCount", "removedBlocksCount", "pipe", "parallelBatch", "b32", "msg", "source", "filter", "log", "debug", "noLimit", "AUTO_MIGRATE_CONFIG_KEY", "Repo", "path", "loadCodec", "backends", "options", "merge_options_default", "default_options_default", "blockstore", "pinstore", "PinManager", "pinnedBlockstore", "createPinnedBlockstore", "createIdStore", "version", "config", "spec", "apiAddr", "createMortice", "gc", "buildConfig", "buildDatastoreSpec", "errCode", "ERR_REPO_ALREADY_OPEN", "InvalidRepoVersionError", "err", "err2", "lockfile", "ERR_REPO_NOT_INITIALIZED", "ERR_REPO_ALREADY_CLOSED", "store", "storageMax", "blocks", "datastore", "keys", "getSize", "size", "autoMigrateConfig", "e", "NotFoundError", "toVersion", "revert", "migrate", "max", "bytes", "count", "key", "value", "sum", "block", "createRepo", "_config", "default_datastore_default", "objectSafeGet", "mounting", "sort", "source", "sorter", "all", "import_level", "LevelDatastore", "BaseDatastore", "path", "opts", "err", "errors_exports", "key", "value", "data", "ops", "q", "it", "f", "filter", "sort", "offset", "limit", "i", "take", "map", "iteratorOpts", "prefix", "iterator", "levelIteratorToIterator", "oldLevelIteratorToIterator", "li", "Key", "resolve", "reject", "import_err_code", "sortAll", "iterable", "sorter", "all", "BaseBlockstore", "key", "val", "options", "source", "value", "puts", "dels", "drain", "q", "it", "filter", "e", "f", "take", "cid", "cidToKey", "cid", "c", "CID", "errcode", "Key", "base32", "keyToCid", "key", "code", "decode", "convertPrefix", "prefix", "firstChar", "decoder", "input", "base32pad", "base58btc", "bytes", "i", "err", "str", "convertQuery", "query", "filter", "pair", "order", "a", "b", "convertKeyQuery", "BlockstoreDatastoreAdapter", "BaseBlockstore", "datastore", "options", "value", "cids", "blocks", "output", "pushable", "store", "drain", "block", "out", "createRepo", "print", "codecs", "options", "repoPath", "codeOrName", "LevelDatastore", "BlockstoreDatastoreAdapter", "MemoryLock", "import_dlv", "import_err_code", "accessor", "buf", "index", "value", "TWO_32", "LongBits", "hi", "lo", "unsigned", "mask", "buf", "offset", "access", "accessor", "value", "negative", "sign", "bits", "i", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "unsigned", "value", "buf", "offset", "allocUnsafe", "LongBits", "codes", "Envelope", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "_RecordEnvelope", "init", "__publicField", "peerId", "payloadType", "payload", "signature", "Envelope", "other", "equals", "domain", "signData", "formatSignaturePayload", "unmarshalPublicKey", "RecordEnvelope", "data", "envelopeData", "peerIdFromKeys", "record", "unmarshalPrivateKey", "envelope", "CodeError", "codes", "domainUint8Array", "fromString", "domainLength", "unsigned", "payloadTypeLength", "payloadLength", "Uint8ArrayList", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "PeerRecord", "AddressInfo", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "value", "topologySymbol", "noop", "_a", "TopologyImpl", "init", "__publicField", "topologySymbol", "registrar", "peerId", "createTopology", "_listeners", "EventEmitter", "__privateAdd", "type", "listeners", "__privateGet", "listener", "options", "list", "callback", "event", "result", "once", "detail", "CustomEvent", "CustomEventPolyfill", "message", "data", "__publicField", "MessageCache", "gossip", "historyCapacity", "msgIdToStrFn", "messageId", "msg", "validated", "msgIdStr", "msgId", "fromPeerIdStr", "entry", "_a", "p", "count", "topics", "msgIdsByTopic", "i", "msgIds", "message", "originatingPeers", "cacheEntry", "import_rpc", "RPC", "cjs", "FloodsubID", "GossipsubIDv10", "GossipsubIDv11", "ERR_TOPIC_VALIDATOR_REJECT", "ERR_TOPIC_VALIDATOR_IGNORE", "shuffle", "arr", "randInt", "i", "j", "tmp", "messageIdToString", "msgId", "toString", "StrictSign", "StrictNoSign", "TopicValidatorResult", "SignaturePolicy", "PublishConfigType", "RejectReason", "ValidateError", "MessageStatus", "rejectReasonFromAcceptance", "acceptance", "TopicValidatorResult", "getPublishConfigFromPeerId", "signaturePolicy", "peerId", "StrictSign", "privateKey", "unmarshalPrivateKey", "PublishConfigType", "StrictNoSign", "ERR_INVALID_PEER_SCORE_PARAMS", "defaultPeerScoreParams", "defaultTopicScoreParams", "createPeerScoreParams", "p", "topics", "topic", "topicScoreParams", "createTopicScoreParams", "validatePeerScoreParams", "params", "validateTopicScoreParams", "e", "CodeError", "ERR_INVALID_PEER_SCORE_PARAMS", "defaultPeerScoreThresholds", "createPeerScoreThresholds", "p", "computeScore", "peer", "pstats", "params", "peerIPs", "score", "topic", "tstats", "topicParams", "topicScore", "p1", "p2", "deficit", "p3", "p3b", "p4", "p5", "ip", "peersInIP", "numPeersInIP", "surplus", "p6", "excess", "p7", "import_denque", "DeliveryRecordStatus", "MessageDeliveries", "Denque", "msgIdStr", "drec", "entry", "now", "head", "removeItemsFromSet", "superSet", "ineed", "cond", "subset", "id", "removeFirstNItemsFromSet", "MapDef", "getDefault", "key", "value", "log", "logger", "PeerScore", "params", "metrics", "opts", "MapDef", "MessageDeliveries", "validatePeerScoreParams", "computeScore", "peer", "stats", "now", "decayToZero", "pstats", "id", "topic", "tstats", "tparams", "_a", "_b", "_c", "cacheEntry", "score", "cacheUntil", "penalty", "penaltyLabel", "ip", "peersWithIP", "threshold", "deficit", "msgIdStr", "from", "drec", "DeliveryRecordStatus", "p", "reason", "RejectReason", "cap", "validatedTime", "deliveryDelayMs", "isLateDelivery", "ipsToRemove", "ipToRemove", "peerSet", "topicStats", "IWantTracer", "gossipsubIWantFollowupMs", "msgIdToStrFn", "metrics", "from", "msgIds", "ix", "msgId", "msgIdStr", "expireByPeer", "now", "_a", "result", "brokenPromises", "expire", "p", "isDuplicate", "reason", "RejectReason", "maxMs", "count", "k", "v", "requestMs", "SimpleTimeCache", "opts", "key", "value", "now", "k", "v", "MessageSource", "InclusionReason", "ChurnReason", "ScorePenalty", "IHaveIgnoreReason", "ScoreThreshold", "getMetrics", "register", "topicStrToLabel", "opts", "topicStr", "reason", "count", "topic", "hit", "acceptance", "penalty", "ihave", "idonthave", "iwantByTopic", "iwantDonthave", "iwant", "tosendCount", "tosendGroupCount", "dataLen", "status", "error", "RejectReason", "deliveryDelayMs", "isLateDelivery", "rpc", "rpcBytes", "_a", "_b", "_c", "_d", "graft", "prune", "scores", "scoreThresholds", "graylist", "publish", "gossip", "mesh", "score", "sw", "wsTopic", "scoreByPeer", "peersPerTopicLabel", "peers", "topicLabel", "peersInMesh", "p", "meshScores", "peer", "import_aes", "import_forge", "import_pbkdf2", "import_util", "SignPrefix", "fromString", "buildRawMessage", "publishConfig", "topic", "originalData", "transformedData", "PublishConfigType", "rpcMsg", "randomBytes", "bytes", "concat", "RPC", "msg", "toString", "validateToRawMessage", "signaturePolicy", "StrictNoSign", "ValidateError", "StrictSign", "fromPeerId", "peerIdFromBytes", "publicKey", "unmarshalPublicKey", "equals", "rpcMsgPreSign", "marshalPublicKey", "msgId", "key", "seqno", "seqnoBytes", "fromString", "msgIdFnStrictSign", "msg", "msgId", "msgIdFnStrictNoSign", "sha256", "computeScoreWeights", "peer", "pstats", "params", "peerIPs", "topicStrToLabel", "score", "byTopic", "topic", "tstats", "topicLabel", "topicParams", "topicScores", "p1w", "p2w", "p3w", "p3bw", "p4w", "p1", "p2", "deficit", "p3", "p3b", "p4", "capF", "ws", "p5w", "p6w", "p7w", "p5", "ip", "peersInIP", "numPeersInIP", "surplus", "p6", "p7", "computeAllPeersScoreWeights", "peerIdStrs", "peerStats", "sw", "peerIdStr", "swPeer", "swPeerTopic", "swTopic", "FixedFIFO", "hwm", "__publicField", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "AbortError", "message", "code", "__publicField", "pushable", "options", "_pushable", "buffer", "next", "pushableV", "values", "getNext", "onEnd", "FIFO", "onNext", "ended", "drain", "pDefer", "waitNext", "resolve", "reject", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "signal", "cancel", "listener", "opts", "AbortError", "message", "code", "getIterator", "obj", "abortableSource", "source", "signal", "options", "opts", "iterator", "getIterator", "abortable", "nextAbortHandler", "abortHandler", "result", "abortMessage", "abortCode", "AbortError", "abort", "resolve", "reject", "err", "isKnownAborter", "p", "abortableSink", "sink", "abortableDuplex", "duplex", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "unsigned", "value", "buf", "offset", "allocUnsafe", "LongBits", "allocUnsafe", "len", "_a", "defaultEncoder", "length", "lengthLength", "unsigned", "lengthBuf", "allocUnsafe", "encode", "options", "encodeLength", "source", "chunk", "Uint8ArrayList", "import_err_code", "MAX_LENGTH_LENGTH", "MAX_DATA_LENGTH", "ReadMode", "defaultDecoder", "buf", "length", "unsigned", "decode", "options", "source", "buffer", "Uint8ArrayList", "mode", "dataLength", "lengthDecoder", "maxLengthLength", "maxDataLength", "errCode", "dataLengthLength", "err", "data", "reader", "byteLength", "varByteSource", "done", "value", "l", "OutboundStream", "rawStream", "errCallback", "opts", "pushable", "pipe", "abortableSource", "encode", "data", "InboundStream", "decode", "import_minimal", "defaultDecodeRpcLimits", "decodeRpc", "bytes", "opts", "r", "protobuf", "l", "c", "m", "t", "decodeSubOpts", "decodeMessage", "decodeControlMessage", "decodeControlIHave", "decodeControlIWant", "decodeControlGraft", "decodeControlPrune", "decodePeerInfo", "Protocol", "multiaddrToIPStr", "multiaddr", "tuple", "convertToString", "GossipStatusCode", "GossipSub", "EventEmitter", "components", "options", "GossipsubIDv11", "GossipsubIDv10", "pushable", "_a", "timer", "err", "msToNextHeartbeat", "opts", "createPeerScoreParams", "createPeerScoreThresholds", "defaultDecodeRpcLimits", "StrictSign", "FloodsubID", "logger", "p", "SimpleTimeCache", "msgIdFnStrictSign", "StrictNoSign", "msgIdFnStrictNoSign", "messageIdToString", "MessageCache", "maxMeshMessageDeliveriesWindowMs", "topicParam", "metrics", "getMetrics", "protocol", "IWantTracer", "PeerScore", "str", "peerIdFromString", "getPublishConfigFromPeerId", "pipe", "source", "peerId", "connection", "e", "registrar", "multicodec", "topology", "createTopology", "registrarTopologyIds", "heartbeatTimeout", "id", "outboundStream", "inboundStream", "stream", "OutboundStream", "priorInboundStream", "InboundStream", "direction", "addr", "currentIP", "multiaddrToIPStr", "_b", "peers", "topicStr", "ChurnReason", "topic", "peersInTopic", "_c", "data", "rpcBytes", "rpc", "decodeRpc", "from", "subscriptions", "messages", "ihave", "iwant", "graft", "prune", "subOpt", "subscribe", "CustomEvent", "message", "handleReceivedMessagePromise", "topicSet", "rpcMsg", "validationResult", "MessageStatus", "msgIdStr", "propagationSource", "fastMsgIdStr", "msgIdCached", "validateToRawMessage", "RejectReason", "msg", "ValidateError", "msgId", "messageId", "topicValidator", "acceptance", "errCode", "ERR_TOPIC_VALIDATOR_IGNORE", "TopicValidatorResult", "ERR_TOPIC_VALIDATOR_REJECT", "rejectReasonFromAcceptance", "toPeer", "topics", "controlMsg", "sent", "iwantMessageIds", "now", "entry", "score", "IHaveIgnoreReason", "peerhave", "iasked", "topicID", "messageIDs", "idonthave", "iask", "iwantList", "shuffle", "iwantByTopic", "iwantDonthave", "doPX", "peersInMesh", "expire", "ScorePenalty", "floodCutoff", "InclusionReason", "backoff", "interval", "count", "toconnect", "pi", "peerIdFromBytes", "envelope", "RecordEnvelope", "eid", "wasSubscribed", "toAdd", "fanoutPeers", "fanoutCount", "peer", "meshPeers", "excludePeers", "tosend", "tosendCount", "newFanoutPeers", "rawMsg", "transformedData", "buildRawMessage", "ignoreDuplicatePublishError", "willSendToSelf", "allowPublishToZeroPeers", "_d", "cacheEntry", "originatingPeers", "rejectReason", "ctrl", "RPC", "outRpc", "tograft", "toprune", "noPX", "pruning", "peersToGossipByTopic", "gossipIDsByTopic", "peersToGossip", "candidateToGossip", "target", "factor", "peerMessageIDs", "control", "controlIHaveMsgs", "gossip", "xid", "px", "D", "Dlo", "Dhi", "Dscore", "Dout", "fanoutTTL", "scores", "getScore", "s", "candidateMeshPeers", "shuffledPeers", "peerStreams", "prunePeer", "reason", "graftPeer", "ineed", "removeFirstNItemsFromSet", "peersArray", "a", "b", "outbound", "rotate", "i", "j", "removeItemsFromSet", "peersList", "medianIndex", "medianScore", "newMeshPeers", "lastpb", "topicPeers", "candidateFanoutPeers", "filter", "backoffSize", "scoreByPeer", "peerIdStr", "sw", "computeAllPeersScoreWeights", "gossipsub", "init", "routers", "gossipsub", "import_debug", "debug", "v", "base58btc", "base32", "base64", "createDisabledLogger", "namespace", "logger", "logger", "name", "trace", "createDisabledLogger", "debug", "r", "n", "symbol", "inspect", "baseDecoder", "bases", "codec", "acc", "curr", "LIBP2P_KEY_CODE", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "_a", "PeerIdImpl", "init", "__publicField", "base58btc", "CID", "id", "equals", "peerIdFromString", "symbol", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "peerIdFromString", "str", "decoder", "baseDecoder", "multihash", "decode", "base58btc", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "RSAPeerIdImpl", "peerIdFromBytes", "buf", "identity", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "sha256", "peerIdFromCID", "CID", "cid", "LIBP2P_KEY_CODE", "anySignal", "signals", "controller", "onAbort", "signal", "clear", "log", "logger", "DEFAULT_TIMEOUT", "CONCURRENT_HTTP_REQUESTS", "EventTypes", "MessageType", "DelegatedPeerRouting", "client", "__publicField", "dist_default", "protocol", "host", "port", "id", "options", "signal", "anySignal", "onStart", "pDefer", "onFinish", "event", "CodeError", "err", "key", "cidOrPeerId", "cid", "CID", "peerIdFromBytes", "closer", "delegatedPeerRouting", "import_err_code", "isAsyncIterable", "thing", "drain", "source", "_", "src_default", "log", "logger", "DEFAULT_TIMEOUT", "CONCURRENT_HTTP_REQUESTS", "CONCURRENT_HTTP_REFS_REQUESTS", "EventTypes", "MessageType", "DelegatedContentRouting", "client", "__publicField", "dist_default", "protocol", "host", "port", "key", "options", "signal", "anySignal", "onStart", "pDefer", "onFinish", "event", "prov", "err", "src_default", "value", "errCode", "delegatedContentRouting", "LOAD_BASE", "name", "Multibases", "options", "base", "nameOrPrefix", "LOAD_CODEC", "codeOrName", "Multicodecs", "options", "codec", "code", "table", "LOAD_HASHER", "codeOrName", "Multihashes", "options", "hasher", "code", "table", "import_env", "import_http", "toUrlString", "url", "multiaddrToUri", "multiaddr", "agent_browser_default", "log", "logger", "merge", "merge_options_default", "DEFAULT_PROTOCOL", "DEFAULT_HOST", "DEFAULT_PORT", "normalizeOptions", "options", "url", "opts", "agent", "isMultiaddr", "toUrlString", "protocol", "host", "port", "Agent", "agent_browser_default", "errorHandler", "response", "msg", "data", "err", "error", "HTTP", "KEBAB_REGEX", "kebabCase", "str", "match", "parseTimeout", "value", "parse_duration_default", "Client", "search", "out", "key", "fetch", "resource", "HTTPError", "configure", "fn", "options", "Client", "modeToString", "mode", "import_err_code", "parseMtime", "input", "mtime", "ms", "secs", "errCode", "toUrlSearchParams", "arg", "searchParams", "hashAlg", "mtime", "mode", "options", "parseMtime", "modeToString", "urlSearchParams", "createWantlist", "configure", "api", "wantlist", "options", "toUrlSearchParams", "k", "CID", "createWantlistForPeer", "configure", "api", "wantlistForPeer", "peerId", "options", "toUrlSearchParams", "k", "CID", "createStat", "configure", "api", "stat", "options", "res", "toUrlSearchParams", "toCoreInterface", "k", "CID", "str", "peerIdFromString", "createUnwant", "configure", "api", "unwant", "cid", "options", "toUrlSearchParams", "createBitswap", "config", "createWantlist", "createWantlistForPeer", "createUnwant", "createStat", "createGet", "configure", "api", "get", "cid", "options", "res", "toUrlSearchParams", "import_err_code", "normaliseContent", "input", "isBytes", "isBlob", "isReadableStream", "browserReadableStreamToIt", "peekable", "peekableIterator", "value", "done", "itToBlob", "all", "errCode", "stream", "parts", "chunk", "normaliseInput", "input", "normaliseCandidateMultiple", "normaliseContent", "modeToString", "mode", "multipartRequest", "source", "abortController", "headers", "parts", "formData", "index", "total", "content", "path", "mode", "mtime", "normaliseInput", "fileSuffix", "type", "fieldName", "qs", "modeToString", "secs", "nsecs", "end", "import_any_signal", "filter", "signals", "abortSignal", "createPut", "configure", "api", "put", "data", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "multipartRequest", "err", "CID", "createRm", "configure", "api", "rm", "cid", "options", "res", "toUrlSearchParams", "removed", "toCoreInterface", "out", "CID", "createStat", "configure", "api", "stat", "cid", "options", "data", "toUrlSearchParams", "CID", "createBlock", "config", "createGet", "createPut", "createRm", "createStat", "createAdd", "configure", "api", "add", "addr", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createClear", "configure", "api", "clear", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createList", "configure", "api", "list", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createReset", "configure", "api", "reset", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createRm", "configure", "api", "rm", "addr", "options", "res", "toUrlSearchParams", "Peers", "ma", "multiaddr", "createBootstrap", "config", "createAdd", "createClear", "createList", "createReset", "createRm", "createApply", "configure", "api", "apply", "profile", "options", "data", "toUrlSearchParams", "objectToCamel", "obj", "caps", "output", "camelObj", "k", "createList", "configure", "api", "list", "options", "toUrlSearchParams", "profile", "objectToCamel", "createProfiles", "config", "createApply", "createList", "createGet", "configure", "api", "key", "options", "toUrlSearchParams", "createGetAll", "configure", "api", "options", "toUrlSearchParams", "createReplace", "configure", "api", "config", "options", "controller", "signal", "abortSignal", "toUrlSearchParams", "multipartRequest", "fromString", "createSet", "configure", "api", "key", "value", "options", "params", "encodeParam", "toUrlSearchParams", "createConfig", "config", "createGetAll", "createGet", "createSet", "createReplace", "createProfiles", "createExport", "configure", "api", "dagExport", "root", "options", "toUrlSearchParams", "import_err_code", "resolve", "cid", "path", "codecs", "getBlock", "options", "load", "codec", "block", "parts", "value", "lastCid", "key", "errCode", "CID", "import_err_code", "createGet", "codecs", "options", "configure", "api", "opts", "getBlock", "cid", "result", "first", "resolve", "last", "errCode", "codec", "block", "createImport", "configure", "api", "dagImport", "source", "options", "controller", "signal", "abortSignal", "headers", "body", "multipartRequest", "res", "toUrlSearchParams", "Root", "Cid", "PinErrorMsg", "CID", "createPut", "codecs", "options", "configure", "api", "dagNode", "settings", "serialized", "controller", "signal", "abortSignal", "data", "toUrlSearchParams", "multipartRequest", "CID", "createResolve", "configure", "api", "ipfsPath", "options", "data", "toUrlSearchParams", "CID", "createDag", "codecs", "config", "createExport", "createGet", "createImport", "createPut", "createResolve", "mapEvent", "event", "peerIdFromString", "ID", "Addrs", "addr", "multiaddr", "peer", "fromString", "peers", "createFindPeer", "configure", "api", "findPeer", "peerId", "options", "res", "toUrlSearchParams", "event", "mapEvent", "createFindProvs", "configure", "api", "findProvs", "cid", "options", "res", "toUrlSearchParams", "event", "mapEvent", "createGet", "configure", "api", "get", "key", "options", "res", "toUrlSearchParams", "toString", "event", "mapEvent", "createProvide", "configure", "api", "provide", "cids", "options", "cidArr", "res", "toUrlSearchParams", "cid", "event", "mapEvent", "createPut", "configure", "api", "put", "key", "value", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "toString", "multipartRequest", "event", "mapEvent", "createQuery", "configure", "api", "query", "peerId", "options", "res", "toUrlSearchParams", "event", "mapEvent", "createDht", "config", "createFindPeer", "createFindProvs", "createGet", "createProvide", "createPut", "createQuery", "createCmds", "configure", "api", "cmds", "options", "toUrlSearchParams", "createNet", "configure", "api", "net", "options", "toUrlSearchParams", "createSys", "configure", "api", "sys", "options", "toUrlSearchParams", "createDiag", "config", "createCmds", "createNet", "createSys", "createChmod", "configure", "api", "chmod", "path", "mode", "options", "toUrlSearchParams", "createCp", "configure", "api", "cp", "sources", "destination", "options", "sourceArr", "toUrlSearchParams", "src", "CID", "createFlush", "configure", "api", "flush", "path", "options", "data", "toUrlSearchParams", "CID", "objectToCamelWithMetadata", "entry", "file", "objectToCamel", "createLs", "configure", "api", "ls", "path", "options", "res", "toUrlSearchParams", "CID", "result", "entry", "toCoreInterface", "objectToCamelWithMetadata", "createMkdir", "configure", "api", "mkdir", "path", "options", "toUrlSearchParams", "createMv", "configure", "api", "mv", "sources", "destination", "options", "toUrlSearchParams", "import_source", "createRead", "configure", "api", "read", "path", "options", "res", "toUrlSearchParams", "toIterable", "import_http", "createRm", "configure", "api", "rm", "path", "options", "res", "toUrlSearchParams", "body", "error", "HTTP", "createStat", "configure", "api", "stat", "path", "options", "data", "toUrlSearchParams", "toCoreInterface", "objectToCamelWithMetadata", "entry", "CID", "createTouch", "configure", "api", "touch", "path", "options", "toUrlSearchParams", "createWrite", "configure", "api", "write", "path", "input", "options", "controller", "signal", "abortSignal", "toUrlSearchParams", "multipartRequest", "modeToString", "parseMtime", "createFiles", "config", "createChmod", "createCp", "createFlush", "createLs", "createMkdir", "createMv", "createRead", "createRm", "createStat", "createTouch", "createWrite", "import_err_code", "createExport", "configure", "api", "name", "password", "options", "errCode", "createGen", "configure", "api", "gen", "name", "options", "opts", "data", "toUrlSearchParams", "objectToCamel", "createImport", "configure", "api", "importKey", "name", "pem", "password", "options", "data", "toUrlSearchParams", "objectToCamel", "import_err_code", "createInfo", "configure", "api", "name", "options", "errCode", "createList", "configure", "api", "list", "options", "toUrlSearchParams", "k", "objectToCamel", "createRename", "configure", "api", "rename", "oldName", "newName", "options", "res", "toUrlSearchParams", "objectToCamel", "createRm", "configure", "api", "rm", "name", "options", "data", "toUrlSearchParams", "objectToCamel", "createKey", "config", "createExport", "createGen", "createImport", "createInfo", "createList", "createRename", "createRm", "createLevel", "configure", "api", "level", "subsystem", "options", "res", "toUrlSearchParams", "objectToCamel", "createLs", "configure", "api", "ls", "options", "toUrlSearchParams", "createTail", "configure", "api", "tail", "options", "toUrlSearchParams", "createLog", "config", "createLevel", "createLs", "createTail", "createPublish", "configure", "api", "publish", "path", "options", "res", "toUrlSearchParams", "objectToCamel", "createResolve", "configure", "api", "resolve", "path", "options", "res", "toUrlSearchParams", "result", "createCancel", "configure", "api", "cancel", "name", "options", "res", "toUrlSearchParams", "objectToCamel", "createState", "configure", "api", "state", "options", "res", "toUrlSearchParams", "objectToCamel", "createSubs", "configure", "api", "subs", "options", "toUrlSearchParams", "createPubsub", "config", "createCancel", "createState", "createSubs", "createName", "config", "createPublish", "createResolve", "createPubsub", "createData", "configure", "api", "data", "cid", "options", "toUrlSearchParams", "CID", "createGet", "configure", "api", "get", "cid", "options", "data", "toUrlSearchParams", "CID", "fromString", "link", "createLinks", "configure", "api", "links", "cid", "options", "toUrlSearchParams", "CID", "l", "createNew", "configure", "api", "newObject", "options", "res", "toUrlSearchParams", "Hash", "CID", "createPut", "codecs", "options", "configure", "api", "dagPut", "put", "obj", "createStat", "configure", "api", "stat", "cid", "options", "output", "toUrlSearchParams", "CID", "createAddLink", "configure", "api", "addLink", "cid", "dLink", "options", "res", "toUrlSearchParams", "Hash", "CID", "createAppendData", "configure", "api", "appendData", "cid", "data", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "multipartRequest", "Hash", "CID", "createRmLink", "configure", "api", "rmLink", "cid", "dLink", "options", "res", "toUrlSearchParams", "Hash", "CID", "createSetData", "configure", "api", "setData", "cid", "data", "options", "controller", "signal", "abortSignal", "res", "toUrlSearchParams", "multipartRequest", "Hash", "CID", "createPatch", "config", "createAddLink", "createAppendData", "createRmLink", "createSetData", "createObject", "codecs", "config", "createData", "createGet", "createLinks", "createNew", "createPut", "createStat", "createPatch", "createAddAll", "configure", "api", "addAll", "source", "options", "path", "recursive", "metadata", "normaliseInput", "res", "toUrlSearchParams", "pin", "cid", "CID", "createAdd", "config", "all", "createAddAll", "configure", "add", "path", "options", "last", "toPin", "type", "cid", "metadata", "pin", "CID", "createLs", "configure", "api", "ls", "options", "paths", "res", "toUrlSearchParams", "path", "createRmAll", "configure", "api", "rmAll", "source", "options", "path", "recursive", "normaliseInput", "searchParams", "res", "toUrlSearchParams", "pin", "cid", "CID", "createRm", "config", "all", "createRmAll", "configure", "rm", "path", "options", "last", "decodePin", "name", "status", "cid", "CID", "encodeService", "service", "encodeCID", "encodeQuery", "all", "query", "toUrlSearchParams", "value", "encodeAddParams", "background", "origins", "params", "origin", "createAdd", "client", "add", "cid", "timeout", "signal", "headers", "query", "response", "encodeAddParams", "decodePin", "createLs", "client", "ls", "timeout", "signal", "headers", "query", "response", "encodeQuery", "pin", "decodePin", "createRm", "client", "rm", "timeout", "signal", "headers", "query", "encodeQuery", "createRmAll", "client", "rmAll", "timeout", "signal", "headers", "query", "encodeQuery", "encodeEndpoint", "url", "href", "decodeRemoteService", "json", "decodeStat", "Pinning", "Pinned", "Queued", "Failed", "createAdd", "client", "add", "name", "options", "endpoint", "key", "headers", "timeout", "signal", "toUrlSearchParams", "encodeEndpoint", "createLs", "client", "ls", "options", "stat", "headers", "timeout", "signal", "response", "toUrlSearchParams", "RemoteServices", "decodeRemoteService", "createRm", "client", "rm", "name", "options", "toUrlSearchParams", "createService", "config", "client", "Client", "createAdd", "createLs", "createRm", "createRemote", "config", "client", "Client", "createAdd", "createLs", "createRm", "createRmAll", "createService", "createPin", "config", "createAddAll", "createAdd", "createLs", "createRmAll", "createRm", "createRemote", "rpcArrayToTextArray", "strings", "rpcToText", "mb", "toString", "rpcToBytes", "base64url", "rpcToBigInt", "textToUrlSafeRpc", "text", "fromString", "createLs", "configure", "api", "ls", "options", "Strings", "toUrlSearchParams", "rpcArrayToTextArray", "createPeers", "configure", "api", "peers", "topic", "options", "res", "toUrlSearchParams", "textToUrlSafeRpc", "Strings", "createPublish", "configure", "api", "publish", "topic", "data", "options", "searchParams", "toUrlSearchParams", "textToUrlSafeRpc", "controller", "signal", "abortSignal", "multipartRequest", "log", "logger", "createSubscribe", "options", "subsTracker", "configure", "api", "subscribe", "topic", "handler", "done", "fail", "result", "resolve", "reject", "ffWorkaround", "toUrlSearchParams", "textToUrlSafeRpc", "err", "response", "readMessages", "message", "onMessage", "onEnd", "onError", "msg", "peerIdFromString", "rpcToBytes", "rpcToBigInt", "rpcToText", "isAbortError", "error", "createUnsubscribe", "options", "subsTracker", "unsubscribe", "topic", "handler", "SubscriptionTracker", "topic", "handler", "signal", "topicSubs", "controller", "subs", "unsubs", "s", "createPubsub", "config", "subscriptionTracker", "SubscriptionTracker", "createLs", "createPeers", "createPublish", "createSubscribe", "createUnsubscribe", "createLocal", "configure", "api", "refsLocal", "options", "objectToCamel", "toUrlSearchParams", "createRefs", "configure", "api", "opts", "args", "options", "argsArr", "toUrlSearchParams", "arg", "CID", "objectToCamel", "createLocal", "createGc", "configure", "api", "gc", "options", "toUrlSearchParams", "res", "CID", "createStat", "configure", "api", "stat", "options", "data", "toUrlSearchParams", "createVersion", "configure", "api", "version", "options", "toUrlSearchParams", "createRepo", "config", "createGc", "createStat", "createVersion", "createBw", "configure", "api", "bw", "options", "toUrlSearchParams", "stats", "createStats", "config", "createStat", "createBw", "createAddrs", "configure", "api", "addrs", "options", "res", "toUrlSearchParams", "Addrs", "id", "peerIdFromString", "a", "multiaddr", "createConnect", "configure", "api", "connect", "addr", "options", "res", "toUrlSearchParams", "Strings", "createDisconnect", "configure", "api", "disconnect", "addr", "options", "res", "toUrlSearchParams", "Strings", "createLocalAddrs", "configure", "api", "localAddrs", "options", "res", "toUrlSearchParams", "Strings", "a", "multiaddr", "createPeers", "configure", "api", "peers", "options", "res", "toUrlSearchParams", "Peers", "peer", "multiaddr", "peerIdFromString", "createSwarm", "config", "createAddrs", "createConnect", "createDisconnect", "createLocalAddrs", "createPeers", "createAddAll", "configure", "api", "addAll", "source", "options", "controller", "signal", "abortSignal", "headers", "body", "total", "parts", "multipartRequest", "progressFn", "onUploadProgress", "createProgressHandler", "res", "toUrlSearchParams", "file", "objectToCamel", "toCoreInterface", "progress", "createOnUploadProgress", "size", "index", "count", "loaded", "position", "start", "end", "name", "hash", "mode", "mtime", "mtimeNsecs", "output", "CID", "createAdd", "options", "all", "createAddAll", "configure", "add", "input", "last", "normaliseInput", "createCat", "configure", "api", "cat", "path", "options", "toUrlSearchParams", "createCommands", "configure", "api", "options", "toUrlSearchParams", "createDns", "configure", "api", "domain", "options", "toUrlSearchParams", "createGetEndpointConfig", "configure", "api", "url", "createGet", "configure", "api", "get", "path", "options", "opts", "CID", "toUrlSearchParams", "createId", "configure", "api", "id", "options", "data", "toUrlSearchParams", "output", "objectToCamel", "peerIdFromString", "ma", "multiaddr", "createIsOnline", "options", "id", "createId", "isOnline", "res", "createLs", "configure", "api", "opts", "ls", "path", "options", "pathStr", "CID", "mapLink", "link", "hash", "ipfsPath", "createStat", "entry", "typeOf", "res", "toUrlSearchParams", "result", "links", "createMount", "configure", "api", "mount", "options", "res", "toUrlSearchParams", "objectToCamel", "createPing", "configure", "api", "ping", "peerId", "options", "toUrlSearchParams", "objectToCamel", "createResolve", "configure", "api", "resolve", "path", "options", "res", "toUrlSearchParams", "Path", "import_err_code", "createStart", "configure", "api", "options", "errCode", "createStop", "configure", "api", "stop", "options", "toUrlSearchParams", "createVersion", "configure", "api", "version", "options", "res", "toUrlSearchParams", "objectToCamel", "import_url_source", "create", "options", "id", "identity", "multibaseCodecs", "bases", "base", "multibases", "Multibases", "blockCodecs", "codecs", "src_exports", "lib_exports", "codec", "multicodecs", "Multicodecs", "multihashHashers", "hashes", "hasher", "multihashes", "Multihashes", "createAdd", "createAddAll", "createBitswap", "createBlock", "createBootstrap", "createCat", "createCommands", "createConfig", "createDag", "createDht", "createDiag", "createDns", "createFiles", "createGet", "createGetEndpointConfig", "createId", "createIsOnline", "createKey", "createLog", "createLs", "createMount", "createName", "createObject", "createPin", "createPing", "createPubsub", "createRefs", "createRepo", "createResolve", "createStart", "createStats", "createStop", "createSwarm", "createVersion", "import_err_code", "AbortError", "message", "code", "getIterator", "obj", "abortableSource", "source", "signal", "options", "opts", "iterator", "getIterator", "abortable", "nextAbortHandler", "abortHandler", "result", "abortMessage", "abortCode", "AbortError", "abort", "resolve", "reject", "err", "isKnownAborter", "p", "abortableSink", "sink", "abortableDuplex", "duplex", "DNS4", "base", "DNS6", "DNSADDR", "DNS", "or", "IP", "TCP", "and", "UDP", "UTP", "QUIC", "WebSockets", "WebSocketsSecure", "HTTP", "HTTPS", "WebRTCStar", "WebSocketStar", "WebRTCDirect", "Reliable", "Stardust", "_P2P", "_Circuit", "CircuitRecursive", "Circuit", "P2P", "makeMatchesFunction", "partialMatch", "matches", "a", "ma", "multiaddr", "out", "and", "args", "arg", "or", "res", "base", "n", "name", "pnames", "protos", "import_err_code", "PACKET_TYPES", "PACKET_TYPES_REVERSE", "key", "ERROR_PACKET", "withNativeBlob", "withNativeArrayBuffer", "isView", "obj", "encodePacket", "type", "data", "supportsBinary", "callback", "encodeBlobAsBase64", "PACKET_TYPES", "fileReader", "content", "encodePacket_browser_default", "chars", "lookup", "i", "decode", "base64", "bufferLength", "len", "i", "p", "encoded1", "encoded2", "encoded3", "encoded4", "arraybuffer", "bytes", "lookup", "withNativeArrayBuffer", "decodePacket", "encodedPacket", "binaryType", "mapBinary", "type", "decodeBase64Packet", "PACKET_TYPES_REVERSE", "ERROR_PACKET", "data", "decoded", "decode", "decodePacket_browser_default", "SEPARATOR", "encodePayload", "packets", "callback", "length", "encodedPackets", "count", "packet", "i", "encodePacket_browser_default", "encodedPacket", "decodePayload", "encodedPayload", "binaryType", "decodedPacket", "decodePacket_browser_default", "protocol", "Emitter", "obj", "mixin", "key", "event", "fn", "on", "callbacks", "cb", "args", "i", "len", "globalThisShim", "pick", "obj", "attr", "acc", "k", "NATIVE_SET_TIMEOUT", "globalThisShim", "NATIVE_CLEAR_TIMEOUT", "installTimerFunctions", "opts", "BASE64_OVERHEAD", "byteLength", "utf8Length", "str", "c", "length", "i", "l", "TransportError", "reason", "description", "context", "Transport", "Emitter", "opts", "installTimerFunctions", "packets", "data", "packet", "decodePacket_browser_default", "details", "onPause", "alphabet", "length", "map", "seed", "i", "prev", "encode", "num", "encoded", "yeast", "now", "encode", "prev", "seed", "i", "length", "map", "alphabet", "encode", "obj", "str", "i", "decode", "qs", "qry", "pairs", "l", "pair", "value", "hasCORS", "XHR", "opts", "xdomain", "hasCORS", "globalThisShim", "empty", "hasXHR2", "XHR", "Polling", "Transport", "opts", "isSSL", "port", "forceBase64", "onPause", "pause", "total", "data", "callback", "packet", "decodePayload", "close", "packets", "encodePayload", "query", "schema", "yeast", "encodedQuery", "encode", "ipv6", "Request", "fn", "req", "xhrStatus", "context", "Emitter", "uri", "installTimerFunctions", "pick", "xhr", "i", "e", "err", "fromError", "unloadHandler", "terminationEvent", "globalThisShim", "nextTick", "cb", "setTimeoutFn", "WebSocket", "globalThisShim", "usingBrowserWebSocket", "defaultBinaryType", "isReactNative", "WS", "Transport", "opts", "uri", "protocols", "pick", "usingBrowserWebSocket", "WebSocket", "err", "defaultBinaryType", "closeEvent", "ev", "packets", "i", "packet", "lastPacket", "encodePacket_browser_default", "data", "nextTick", "query", "schema", "port", "yeast", "encodedQuery", "encode", "ipv6", "transports", "WS", "Polling", "re", "parts", "parse", "str", "src", "b", "e", "m", "uri", "i", "pathNames", "queryKey", "obj", "path", "regx", "names", "query", "data", "$0", "$1", "$2", "Socket", "Emitter", "uri", "opts", "parse", "installTimerFunctions", "decode", "name", "query", "protocol", "transports", "transport", "reason", "failed", "onTransportOpen", "msg", "cleanup", "err", "freezeTransport", "onerror", "error", "onTransportClose", "onclose", "onupgrade", "to", "i", "l", "packet", "data", "packets", "payloadSize", "byteLength", "options", "fn", "type", "close", "cleanupAndClose", "waitForUpgrade", "description", "upgrades", "filteredUpgrades", "j", "protocol", "Socket", "url", "uri", "path", "loc", "obj", "parse", "host", "esm_exports", "__export", "Decoder", "Encoder", "PacketType", "protocol", "withNativeArrayBuffer", "isView", "obj", "toString", "withNativeBlob", "withNativeFile", "isBinary", "hasBinary", "toJSON", "i", "l", "key", "deconstructPacket", "packet", "buffers", "packetData", "pack", "_deconstructPacket", "data", "isBinary", "placeholder", "newData", "i", "key", "reconstructPacket", "_reconstructPacket", "protocol", "PacketType", "Encoder", "replacer", "obj", "hasBinary", "str", "deconstruction", "deconstructPacket", "pack", "buffers", "Decoder", "Emitter", "reviver", "packet", "isBinaryEvent", "BinaryReconstructor", "isBinary", "i", "p", "start", "buf", "next", "c", "payload", "type", "binData", "reconstructPacket", "on", "obj", "ev", "fn", "RESERVED_EVENTS", "Socket", "Emitter", "io", "nsp", "opts", "on", "args", "ev", "packet", "PacketType", "id", "ack", "isTransportWritable", "_a", "timeout", "timer", "i", "withErr", "resolve", "reject", "arg1", "arg2", "err", "responseArgs", "force", "data", "reason", "description", "listeners", "listener", "self", "sent", "pid", "subDestroy", "compress", "Backoff", "opts", "ms", "rand", "deviation", "min", "max", "jitter", "Manager", "Emitter", "uri", "opts", "_a", "installTimerFunctions", "Backoff", "_parser", "esm_exports", "v", "fn", "Socket", "socket", "self", "openSubDestroy", "on", "errorSub", "err", "timeout", "timer", "data", "e", "packet", "nextTick", "nsp", "nsps", "encodedPackets", "i", "subDestroy", "reason", "description", "delay", "attempt", "cache", "lookup", "uri", "opts", "parsed", "url", "source", "id", "path", "sameNamespace", "newConnection", "io", "Manager", "Socket", "EventEmitter", "_EventEmitter_listeners", "type", "listeners", "__classPrivateFieldGet", "listener", "options", "list", "callback", "event", "result", "once", "detail", "CustomEvent", "CustomEventPolyfill", "message", "data", "import_err_code", "import_random", "import_err_code", "MAX_BUFFERED_AMOUNT", "CHANNEL_CLOSING_TIMEOUT", "WebRTCDataChannel", "channel", "opts", "pDefer", "event", "_a", "_b", "_c", "_d", "_e", "err", "errCode", "isClosing", "data", "import_delay", "DEFAULT_PEER_CONNECTION_CONFIG", "getBrowserRTC", "errCode", "wrtc", "WebRTCPeer", "EventEmitter", "opts", "toString", "randombytes", "logger", "pDefer", "pushable", "source", "buf", "event", "dataChannel", "err", "WebRTCDataChannel", "CustomEvent", "_a", "delay", "import_err_code", "WebRTCHandshake", "EventEmitter", "options", "err", "signal", "iceCandidate", "errCode", "log", "logger", "WebRTCReceiver", "WebRTCPeer", "opts", "WebRTCReceiverHandshake", "event", "CustomEvent", "signal", "err", "WebRTCHandshake", "options", "candidate", "answer", "import_random", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "rejectHandler", "error", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "import_delay", "log", "logger", "ICECOMPLETE_TIMEOUT", "WebRTCInitiator", "WebRTCPeer", "opts", "toString", "randombytes", "WebRTCInitiatorHandshake", "event", "CustomEvent", "signal", "err", "WebRTCHandshake", "options", "offer", "pEvent", "delay", "log", "logger", "toMultiaddrConnection", "socket", "options", "sink", "source", "maConn", "abortableSource", "err", "start", "timeout", "host", "port", "cleanUrlSIO", "ma", "maStrSplit", "tcpProto", "wsProto", "tcpPort", "isName", "cleanMultiaddr", "maStr", "legacy", "multiaddr", "tuppleIPFS", "tupple", "log", "logger", "sioOptions", "SigServer", "EventEmitter", "signallingUrl", "signallingAddr", "upgrader", "handler", "channelOptions", "lookup", "previouslyConnected", "err", "CustomEvent", "maStr", "intentId", "srcMultiaddr", "dstMultiaddr", "channel", "WebRTCReceiver", "onError", "evt", "signal", "maConn", "toMultiaddrConnection", "conn", "untrackConn", "c", "offer", "pendingSignals", "handshake", "WebRTCListener", "peerId", "transport", "options", "ma", "errCode", "defer", "pDefer", "cleanUrlSIO", "server", "createListener", "import_random", "symbol", "isPeerId", "other", "inspect", "baseDecoder", "bases", "codec", "acc", "curr", "LIBP2P_KEY_CODE", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "PeerIdImpl", "init", "symbol", "base58btc", "CID", "id", "_a", "equals", "peerIdFromString", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "peerIdFromPeerId", "other", "RSAPeerIdImpl", "Ed25519PeerIdImpl", "Secp256k1PeerIdImpl", "CodeError", "peerIdFromString", "str", "decoder", "baseDecoder", "multihash", "decode", "base58btc", "peerIdFromBytes", "buf", "identity", "MARSHALLED_ED225519_PUBLIC_KEY_LENGTH", "MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH", "sha256", "peerIdFromCID", "CID", "cid", "LIBP2P_KEY_CODE", "peerIdFromKeys", "publicKey", "privateKey", "create", "symbol", "FaultTolerance", "symbol", "webrtcSupport", "log", "logger", "noop", "WebRTCStarDiscovery", "EventEmitter", "symbol", "event", "WebRTCStar", "init", "ma", "options", "rawConn", "maConn", "toMultiaddrConnection", "conn", "_a", "AbortError", "channelOptions", "cOpts", "intentId", "toString", "randomBytes", "resolve", "reject", "sio", "cleanUrlSIO", "errcode", "connected", "channel", "WebRTCInitiator", "onError", "evt", "err", "msg", "done", "onReady", "onAbort", "signal", "offer", "createListener", "multiaddrs", "maStr", "cleanMultiaddr", "multiaddr", "peerIdStr", "peerId", "peerIdFromString", "CustomEvent", "webRTCStar", "init", "transport", "WebRTCStar", "components", "libp2pConfig", "webRtcStar", "webRTCStar", "isStartable", "obj", "import_err_code", "messages", "codes", "import_err_code", "storeAddresses", "source", "peerStore", "map", "peer", "uniquePeers", "seen", "filter", "requirePeers", "min", "errCode", "import_timeout_abort_controller", "import_set_delayed_interval", "import_events", "log", "logger", "DefaultPeerRouting", "components", "init", "_a", "_b", "drain", "err", "id", "options", "errCode", "codes", "output", "pipe", "merge", "router", "source", "filter", "storeAddresses", "first", "messages", "key", "uniquePeers", "requirePeers", "import_err_code", "CompoundContentRouting", "components", "init", "key", "options", "errCode", "codes", "pipe", "merge", "router", "source", "storeAddresses", "uniquePeers", "requirePeers", "value", "messages", "dht", "drain", "event", "nVals", "gotValues", "defaultAddressFilter", "addrs", "DefaultAddressManager", "EventEmitter", "components", "init", "listen", "announce", "ma", "a", "multiaddr", "addr", "remotePeer", "peerIdFromString", "addrString", "CustomEvent", "addrSet", "str", "_a", "import_err_code", "log", "logger", "VisibilityChangeEmitter", "EventEmitter", "hidden", "visibilityChange", "visible", "CustomEvent", "log", "logger", "LatencyMonitor", "EventEmitter", "init", "_a", "_b", "latencyCheckIntervalMs", "dataEmitIntervalMs", "asyncTestFn", "latencyRandomPercentage", "startTime", "hrtime", "isBrowser", "VisibilityChangeEmitter", "evt", "pageInFocus", "summary", "CustomEvent", "latency", "randomness", "localData", "cb", "deltaMS", "import_events", "OPEN", "CLOSING", "CLOSED", "mapIterable", "iter", "map", "iterator", "next", "val", "PeerMap", "map", "key", "value", "peer", "mapIterable", "val", "peerIdFromString", "fn", "PeerSet", "set", "key", "peer", "mapIterable", "val", "peerId", "peerIdFromString", "predicate", "str", "id", "other", "output", "PeerList", "list", "value", "mapIterable", "val", "peerIdFromString", "output", "predicate", "str", "index", "peerId", "peerIds", "len", "i", "import_timeout_abort_controller", "KEEP_ALIVE", "import_rate_limiter_flexible", "import_err_code", "getPeerAddress", "peer", "isPeerId", "isMultiaddr", "peerId", "peerIdFromString", "errCode", "codes", "log", "logger", "defaultOptions", "STARTUP_RECONNECT_TIMEOUT", "DefaultConnectionManager", "EventEmitter", "components", "init", "_a", "merge_options_default", "errCode", "codes", "LatencyMonitor", "ma", "multiaddr", "_b", "_c", "_d", "_e", "metric", "conns", "conn", "stream", "key", "allStreams", "streams", "protocol", "count", "counts", "a", "b", "index", "keepAlivePeers", "peer", "tag", "KEEP_ALIVE", "err", "tasks", "connectionList", "connection", "evt", "peerId", "peerIdStr", "storedConns", "numConnections", "toPrune", "CustomEvent", "storedConn", "c", "peerIdOrMultiaddr", "options", "getPeerAddress", "existingConnections", "timeoutController", "peerConnections", "trackedConnection", "connections", "isPeerId", "id", "OPEN", "summary", "name", "value", "limit", "peerValues", "PeerMap", "remotePeer", "tags", "acc", "curr", "sortedConnections", "peerAValue", "peerBValue", "connectionALifespan", "connectionBLifespan", "toClose", "maConn", "host", "import_retimer", "log", "logger", "defaultOptions", "AutoDialler", "components", "init", "merge_options_default", "err", "minConnections", "retimer", "allPeers", "peers", "pipe", "source", "filter", "peer", "sort", "a", "b", "all", "import_err_code", "import_reader", "import_reader_buffer", "import_writer", "import_writer_buffer", "import_minimal", "configure", "util", "ReaderClass", "ReaderBufferClass", "WriterClass", "WriterBufferClass", "methods", "patchReader", "obj", "method", "original", "reader", "buf", "patchWriter", "val", "writer", "decodeMessage", "buf", "codec", "r", "reader", "encodeMessage", "message", "codec", "w", "writer", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "CircuitRelay", "Status", "__StatusValues", "enumeration", "Type", "__TypeValues", "Peer", "_codec", "message", "obj", "w", "opts", "value", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "log", "logger", "streamToMaConnection", "props", "options", "stream", "remoteAddr", "sink", "source", "mapSource", "list", "maConn", "abortableSource", "close", "err", "RELAY_CODEC", "createListener", "options", "listeningAddrs", "listen", "addr", "addrString", "a", "ma", "multiaddr", "relayPeerStr", "relayPeerId", "peerIdFromString", "relayConn", "relayedAddr", "listener", "CustomEvent", "getAddrs", "addrs", "EventEmitter", "evt", "connection", "import_err_code", "writeResponse", "streamHandler", "status", "CircuitRelay", "validateAddrs", "msg", "_a", "_b", "addr", "multiaddr", "err", "reader", "source", "bytes", "bl", "Uint8ArrayList", "chunk", "data", "handshake", "stream", "writer", "pushable", "source", "reader", "sourcePromise", "pDefer", "sinkErr", "sinkPromise", "err", "res", "log", "logger", "StreamHandler", "options", "stream", "maxLength", "handshake", "decode", "msg", "value", "CircuitRelay", "encode", "err", "log", "logger", "handleStop", "options", "connection", "request", "streamHandler", "validateAddrs", "err", "CircuitRelay", "stop", "signal", "stream", "RELAY_CODEC", "StreamHandler", "response", "log", "logger", "handleHop", "hopRequest", "connection", "request", "streamHandler", "circuit", "connectionManager", "CircuitRelay", "validateAddrs", "err", "destinationPeer", "peerIdFromBytes", "destinationConnections", "stopRequest", "destinationStream", "result", "stop", "sourceStream", "pipe", "hop", "options", "signal", "stream", "RELAY_CODEC", "StreamHandler", "response", "errCode", "codes", "canHop", "handleCanHop", "import_timeout_abort_controller", "import_events", "log", "logger", "Circuit", "components", "init", "RELAY_CODEC", "data", "err", "symbol", "_a", "_b", "_c", "connection", "stream", "controller", "source", "abortableDuplex", "streamHandler", "StreamHandler", "request", "CircuitRelay", "virtualConnection", "handleCanHop", "handleHop", "handleStop", "remoteAddr", "multiaddr", "localAddr", "maConn", "streamToMaConnection", "type", "conn", "ma", "options", "addrs", "relayAddr", "destinationAddr", "relayId", "destinationId", "errMsg", "errCode", "codes", "relayPeer", "peerIdFromString", "destinationPeer", "disconnectOnFailure", "relayConnection", "hop", "addr", "createListener", "multiaddrs", "import_set_delayed_interval", "namespaceToCid", "namespace", "bytes", "hash", "sha256", "CID", "HOP_METADATA_KEY", "HOP_METADATA_VALUE", "RELAY_RENDEZVOUS_NS", "import_netmask", "word", "boundry", "options", "v4", "v6segment", "v6", "v46Exact", "v4exact", "v6exact", "ipRegex", "ip_regex_default", "import_ipaddr", "is_valid", "parse", "ipaddr", "PRIVATE_IP_RANGES", "NETMASK_RANGES", "ip_range", "ipv4_check", "ip_addr", "r", "ipv6_check", "lib_default", "ip", "parsed", "isIP", "ip_regex_default", "private_ip_default", "lib_default", "isPrivate", "ma", "address", "private_ip_default", "publicAddressesFirst", "a", "b", "isAPrivate", "isPrivate", "isBPrivate", "log", "logger", "noop", "AutoRelay", "components", "init", "publicAddressesFirst", "evt", "err", "peerId", "protocols", "id", "protocol", "RELAY_CODEC", "connections", "connection", "canHop", "HOP_METADATA_KEY", "fromString", "HOP_METADATA_VALUE", "remoteAddrs", "pipe", "source", "sort", "all", "addr", "multiaddr", "peersToIgnore", "knownHopsToDial", "peers", "metadata", "idStr", "supportsHop", "toString", "cid", "namespaceToCid", "RELAY_RENDEZVOUS_NS", "provider", "log", "logger", "Relay", "components", "init", "_a", "AutoRelay", "cid", "namespaceToCid", "RELAY_RENDEZVOUS_NS", "err", "codes", "import_sanitize_filename", "import_pkcs7", "import_pbe", "import_forge", "import_x509", "import_forge", "pki", "forge", "certificateForKey", "key", "privateKey", "publicKey", "cert", "attrs", "findAsync", "array", "asyncCompare", "promises", "index", "result", "import_err_code", "log", "logger", "privates", "CMS", "keychain", "dek", "errCode", "codes", "name", "plain", "key", "pem", "cached", "privateKey", "forge", "certificate", "certificateForKey", "p7", "der", "fromString", "cmsData", "cms", "buf", "toString", "obj", "err", "recipients", "r", "a", "findAsync", "recipient", "missingKeys", "import_err_code", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "import_asn1", "import_pbe", "import_forge", "webcrypto_default", "win", "nativeCrypto", "import_util", "import_jsbn", "import_forge", "bigIntegerToUintBase64url", "num", "len", "buf", "concat", "toString", "base64urlToBigInteger", "str", "base64urlToBuffer", "forge", "fromString", "bits", "curveTypes", "names", "create", "opts", "algorithm", "keyLength", "nonceLength", "digest", "saltLength", "iterations", "crypto", "webcrypto_default", "encrypt", "data", "password", "salt", "nonce", "aesGcm", "fromString", "deriveParams", "rawKey", "cryptoKey", "ciphertext", "concat", "decrypt", "plaintext", "importer", "privateKey", "password", "encryptedKey", "base64", "create", "rsa_class_exports", "__export", "RsaPrivateKey", "RsaPublicKey", "fromJwk", "generateKeyPair", "unmarshalRsaPrivateKey", "unmarshalRsaPublicKey", "import_sha512", "import_forge", "randomBytes", "length", "CodeError", "utils", "rsa_utils_exports", "__export", "jwkToPkcs1", "jwkToPkix", "pkcs1ToJwk", "pkixToJwk", "import_asn1", "import_rsa", "import_forge", "pkcs1ToJwk", "bytes", "asn1", "forge", "toString", "privateKey", "bigIntegerToUintBase64url", "jwkToPkcs1", "jwk", "CodeError", "base64urlToBigInteger", "fromString", "pkixToJwk", "publicKey", "jwkToPkix", "import_rsa", "import_forge", "convert", "key", "types", "base64urlToBigInteger", "jwk2priv", "forge", "jwk2pub", "generateKey", "bits", "pair", "webcrypto_default", "keys", "exportKey", "unmarshalPrivateKey", "key", "derivePublicFromPrivate", "hashAndSign", "key", "msg", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "exportKey", "pair", "CodeError", "derivePublicFromPrivate", "jwKey", "convertKey", "pub", "handle", "fkey", "jwk2pub", "jwk2priv", "fmsg", "toString", "fomsg", "fromString", "encrypt", "decrypt", "exporter", "privateKey", "password", "encryptedKey", "create", "base64", "RsaPublicKey", "key", "data", "sig", "hashAndVerify", "rsa_utils_exports", "PublicKey", "KeyType", "bytes", "encrypt", "equals", "sha256", "RsaPrivateKey", "publicKey", "randomBytes", "message", "hashAndSign", "CodeError", "decrypt", "PrivateKey", "hash", "toString", "password", "format", "buffer", "forge", "asn1", "privateKey", "options", "exporter", "unmarshalRsaPrivateKey", "jwk", "keys", "unmarshalPrivateKey", "unmarshalRsaPublicKey", "fromJwk", "generateKeyPair", "bits", "generateKey", "ed25519_class_exports", "__export", "Ed25519PrivateKey", "Ed25519PublicKey", "generateKeyPair", "generateKeyPairFromSeed", "unmarshalEd25519PrivateKey", "unmarshalEd25519PublicKey", "PUBLIC_KEY_BYTE_LENGTH", "PRIVATE_KEY_BYTE_LENGTH", "KEYS_BYTE_LENGTH", "generateKey", "privateKeyRaw", "utils", "publicKey", "getPublicKey", "concatKeys", "generateKeyFromSeed", "seed", "KEYS_BYTE_LENGTH", "hashAndSign", "privateKey", "msg", "sign", "hashAndVerify", "sig", "verify", "PRIVATE_KEY_BYTE_LENGTH", "i", "Ed25519PublicKey", "key", "ensureKey", "PUBLIC_KEY_BYTE_LENGTH", "data", "sig", "hashAndVerify", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Ed25519PrivateKey", "publicKey", "PRIVATE_KEY_BYTE_LENGTH", "message", "hashAndSign", "PrivateKey", "encoding", "identity", "base58btc", "password", "format", "exporter", "CodeError", "unmarshalEd25519PrivateKey", "privateKeyBytes", "publicKeyBytes", "unmarshalEd25519PublicKey", "generateKeyPair", "privateKey", "generateKey", "generateKeyPairFromSeed", "seed", "generateKeyFromSeed", "length", "secp256k1_class_exports", "__export", "Secp256k1PrivateKey", "Secp256k1PublicKey", "generateKeyPair", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKey", "utils", "hashAndSign", "key", "msg", "digest", "sha256", "sign", "err", "CodeError", "hashAndVerify", "sig", "verify", "compressPublicKey", "Point", "validatePrivateKey", "key", "getPublicKey", "err", "CodeError", "validatePublicKey", "Point", "computePublicKey", "privateKey", "Secp256k1PublicKey", "key", "validatePublicKey", "data", "sig", "hashAndVerify", "compressPublicKey", "PublicKey", "KeyType", "equals", "bytes", "sha256", "Secp256k1PrivateKey", "publicKey", "computePublicKey", "validatePrivateKey", "message", "hashAndSign", "PrivateKey", "hash", "toString", "password", "format", "exporter", "CodeError", "unmarshalSecp256k1PrivateKey", "unmarshalSecp256k1PublicKey", "generateKeyPair", "privateKeyBytes", "generateKey", "supportedKeys", "rsa_class_exports", "ed25519_class_exports", "secp256k1_class_exports", "unsupportedKey", "type", "supported", "CodeError", "typeToKey", "generateKeyPair", "bits", "unmarshalPublicKey", "buf", "decoded", "PublicKey", "data", "KeyType", "supportedKeys", "unsupportedKey", "marshalPublicKey", "key", "type", "typeToKey", "unmarshalPrivateKey", "PrivateKey", "marshalPrivateKey", "importKey", "encryptedKey", "password", "importer", "forge", "CodeError", "der", "fromString", "import_aes", "import_forge", "import_pbkdf2", "import_util", "hashName", "pbkdf2", "password", "salt", "iterations", "keySize", "hash", "types", "CodeError", "hasher", "dek", "forgePbkdf2", "forgeUtil", "log", "logger", "keyPrefix", "infoPrefix", "privates", "NIST", "defaultOptions", "validateKeyName", "name", "sanitize", "randomDelay", "delay", "resolve", "DsName", "Key", "DsInfoName", "KeyChain", "components", "init", "_a", "_b", "_c", "_d", "_e", "_f", "_g", "_h", "_i", "_j", "merge_options_default", "dek", "pbkdf2", "dsname", "cached", "errCode", "codes", "CMS", "options", "saltLength", "toString", "randomBytes", "type", "size", "keyInfo", "keypair", "generateKeyPair", "kid", "pem", "batch", "fromString", "err", "query", "info", "value", "id", "k", "res", "oldName", "newName", "oldDsname", "newDsname", "oldInfoName", "newInfoName", "password", "importKey", "privateKey", "peerIdFromKeys", "peer", "unmarshalPrivateKey", "oldPass", "newPass", "oldDek", "newDek", "keys", "key", "keyAsPEM", "pReflect", "promise", "error", "Node", "value", "__publicField", "_head", "_tail", "_size", "Queue", "__privateAdd", "node", "__privateGet", "__privateSet", "__privateWrapper", "current", "pLimit", "concurrency", "queue", "Queue", "activeCount", "next", "run", "fn", "resolve", "args", "result", "enqueue", "generator", "pSettle", "array", "options", "concurrency", "limit", "pLimit", "element", "pReflect", "import_err_code", "TrackedMap", "init", "name", "metrics", "key", "value", "deleted", "trackedMap", "config", "map", "log", "logger", "DefaultTransportManager", "EventEmitter", "components", "init", "trackedMap", "FaultTolerance", "transport", "tag", "errCode", "codes", "addrs", "tasks", "key", "listeners", "listener", "ma", "options", "err", "couldNotListen", "supportedAddrs", "addr", "CustomEvent", "pSettle", "r", "message", "import_err_code", "PROTOCOL_ID", "import_err_code", "import_err_code", "log", "logger", "NewLine", "fromString", "encode", "buffer", "list", "Uint8ArrayList", "write", "writer", "options", "encoded", "writeAll", "buffers", "buf", "read", "reader", "byteLength", "varByteSource", "input", "abortableSource", "pipe", "decode", "l", "source", "first", "errCode", "readString", "toString", "log", "logger", "select", "stream", "protocols", "options", "reader", "writer", "rest", "shakeStream", "handshake", "protocol", "PROTOCOL_ID", "p1", "fromString", "p2", "writeAll", "response", "readString", "write", "errCode", "log", "logger", "handle", "stream", "protocols", "options", "writer", "reader", "rest", "shakeStream", "handshake", "protocol", "readString", "PROTOCOL_ID", "write", "fromString", "Uint8ArrayList", "p", "encode", "import_err_code", "symbol", "log", "logger", "ConnectionImpl", "init", "remoteAddr", "remotePeer", "newStream", "close", "getStreams", "stat", "OPEN", "symbol", "protocols", "options", "CLOSING", "errCode", "CLOSED", "stream", "id", "s", "err", "createConnection", "import_err_code", "topologySymbol", "isTopology", "other", "log", "logger", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "DefaultRegistrar", "components", "protocol", "handler", "errCode", "codes", "topologies", "opts", "options", "merge_options_default", "protocols", "protocolList", "topology", "isTopology", "id", "evt", "connection", "peerProtocols", "err", "peerId", "oldProtocols", "removed", "added", "import_timeout_abort_controller", "import_events", "log", "logger", "findIncomingStreamLimit", "protocol", "registrar", "options", "err", "codes", "DEFAULT_MAX_INBOUND_STREAMS", "findOutgoingStreamLimit", "DEFAULT_MAX_OUTBOUND_STREAMS", "countStreams", "direction", "connection", "streamCount", "stream", "DefaultUpgrader", "EventEmitter", "components", "init", "encrypter", "muxer", "maConn", "opts", "_a", "_b", "errCode", "encryptedConn", "remotePeer", "upgradedConn", "muxerFactory", "cryptoProtocol", "timeoutController", "abortableStream", "abortableDuplex", "protectedConn", "protector", "idStr", "remotePeerId", "peerIdFromString", "multiplexed", "newStream", "muxedStream", "protocols", "handle", "incomingLimit", "controller", "select", "outgoingLimit", "_timeline", "args", "CustomEvent", "errConnectionNotMultiplexed", "createConnection", "handler", "muxers", "import_err_code", "Identify", "_codec", "message", "obj", "w", "opts", "value", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "import_err_code", "codes", "Envelope", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "RecordEnvelope", "init", "peerId", "payloadType", "payload", "signature", "Envelope", "other", "equals", "domain", "signData", "formatSignaturePayload", "unmarshalPublicKey", "data", "envelopeData", "peerIdFromKeys", "record", "unmarshalPrivateKey", "envelope", "errCode", "codes", "domainUint8Array", "fromString", "domainLength", "unsigned", "payloadTypeLength", "payloadLength", "Uint8ArrayList", "arrayEquals", "a", "b", "sort", "item", "index", "PeerRecord", "AddressInfo", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "value", "ENVELOPE_DOMAIN_PEER_RECORD", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "PeerRecord", "init", "peerId", "multiaddrs", "seqNumber", "m", "other", "arrayEquals", "buf", "peerRecord", "peerIdFromBytes", "a", "multiaddr", "ENVELOPE_DOMAIN_PEER_RECORD", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "version", "name", "AGENT_VERSION", "version", "IDENTIFY_PROTOCOL_VERSION", "MULTICODEC_IDENTIFY_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PROTOCOL_VERSION", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION", "import_timeout_abort_controller", "import_events", "log", "logger", "MAX_IDENTIFY_MESSAGE_SIZE", "IdentifyService", "components", "init", "MULTICODEC_IDENTIFY_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PROTOCOL_VERSION", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME", "MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION", "IDENTIFY_PROTOCOL_VERSION", "evt", "connection", "peerId", "err", "fromString", "data", "connections", "signedPeerRecord", "listenAddrs", "ma", "protocols", "pushes", "_a", "stream", "timeoutController", "abortableDuplex", "pipe", "Identify", "encode", "conn", "options", "signal", "source", "decode", "first", "errCode", "codes", "message", "publicKey", "observedAddr", "agentVersion", "protocolVersion", "id", "peerIdFromKeys", "cleanObservedAddr", "envelope", "RecordEnvelope", "PeerRecord", "addr", "multiaddr", "peerData", "multiaddrs", "getProtocol", "peerRecord", "msgWithLenPrefix", "import_err_code", "FetchRequest", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "FetchResponse", "StatusCode", "__StatusCodeValues", "enumeration", "PROTOCOL_VERSION", "PROTOCOL_NAME", "import_timeout_abort_controller", "import_events", "log", "logger", "FetchService", "components", "init", "PROTOCOL_NAME", "PROTOCOL_VERSION", "data", "err", "peer", "key", "options", "_a", "connection", "timeoutController", "signal", "stream", "source", "abortableDuplex", "pipe", "FetchRequest", "encode", "decode", "buf", "first", "errCode", "codes", "response", "FetchResponse", "errmsg", "toString", "self", "request", "lookup", "fromString", "prefix", "import_err_code", "PROTOCOL_VERSION", "PROTOCOL_NAME", "import_timeout_abort_controller", "import_events", "log", "logger", "PingService", "components", "init", "PROTOCOL_NAME", "PROTOCOL_VERSION", "data", "stream", "pipe", "err", "peer", "options", "_a", "start", "randomBytes", "connection", "timeoutController", "signal", "source", "abortableDuplex", "result", "first", "end", "equals", "errCode", "codes", "upnpNat", "import_is_electron", "isEnvWithDom", "isElectron", "detectElectron", "isBrowser", "isElectronMain", "isElectronRenderer", "isNode", "isWebWorker", "isTest", "isReactNative", "import_err_code", "isLoopbackAddr", "ip", "isLoopback", "ma", "address", "isLoopbackAddr", "log", "logger", "DEFAULT_TTL", "highPort", "min", "max", "NatManager", "components", "init", "name", "version", "errCode", "codes", "isBrowser", "err", "addrs", "addr", "family", "host", "port", "transport", "isLoopback", "client", "publicIp", "isPrivate", "private_ip_default", "publicPort", "fromNodeAddress", "upnpNat", "log", "logger", "PeerRecordUpdater", "components", "peerRecord", "PeerRecord", "ma", "getProtocol", "envelope", "RecordEnvelope", "err", "import_err_code", "DHTPeerRouting", "dht", "peerId", "options", "event", "errCode", "messages", "codes", "key", "import_err_code", "codes", "forEach", "source", "fn", "thing", "log", "logger", "EVENT_NAME", "allowAll", "PeerStoreAddressBook", "dispatchEvent", "store", "addressFilter", "envelope", "release", "peerId", "peer", "updatedPeer", "peerRecord", "PeerRecord", "multiaddrs", "storedEnvelope", "RecordEnvelope", "storedRecord", "addresses", "filterMultiaddrs", "CustomEvent", "multiaddr", "err", "codes", "raw", "peerIdFromPeerId", "errcode", "hasPeer", "addr", "isCertified", "pipe", "source", "forEach", "isMultiaddr", "filter", "map", "all", "import_err_code", "log", "logger", "EVENT_NAME", "PeerStoreKeyBook", "dispatchEvent", "store", "peerId", "publicKey", "peerIdFromPeerId", "errcode", "codes", "release", "updatedKey", "peer", "equals", "err", "CustomEvent", "import_err_code", "log", "logger", "EVENT_NAME", "PeerStoreMetadataBook", "dispatchEvent", "store", "peerId", "peerIdFromPeerId", "release", "err", "codes", "key", "metadata", "errcode", "peer", "CustomEvent", "value", "updatedPeer", "existingValue", "equals", "import_err_code", "log", "logger", "EVENT_NAME", "PeerStoreProtoBook", "dispatchEvent", "store", "peerId", "release", "err", "codes", "protocols", "peerIdFromPeerId", "errcode", "peer", "updatedPeer", "CustomEvent", "protocolSet", "protocol", "import_err_code", "Peer", "_codec", "message", "obj", "w", "opts", "value", "Address", "Metadata", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "log", "logger", "NAMESPACE_COMMON", "PersistentStore", "components", "createMortice", "peerId", "errcode", "codes", "b32key", "Key", "buf", "peer", "Peer", "metadata", "meta", "ma", "isCertified", "multiaddr", "equals", "addressSet", "addresses", "address", "a", "b", "key", "value", "data", "err", "_a", "_b", "addr", "addrString", "addrStr", "base32Str", "base32", "peerIdFromBytes", "import_err_code", "Tags", "_codec", "message", "obj", "w", "opts", "value", "Tag", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "log", "logger", "PersistentPeerStore", "EventEmitter", "components", "init", "PersistentStore", "PeerStoreAddressBook", "PeerStoreKeyBook", "PeerStoreMetadataBook", "PeerStoreProtoBook", "fn", "release", "peer", "output", "peerId", "tag", "options", "providedValue", "value", "ttl", "errCode", "buf", "tags", "Tags", "t", "now", "unexpiredTags", "import_err_code", "DHTContentRouting", "dht", "cid", "drain", "options", "event", "key", "value", "errCode", "import_err_code", "DefaultComponents", "init", "obj", "isStartable", "startable", "errCode", "peerId", "addressManager", "peerStore", "upgrader", "registrar", "connectionManager", "transportManager", "connectionGater", "contentRouting", "peerRouting", "datastore", "connectionProtector", "dialer", "metrics", "dht", "pubsub", "import_debug", "import_receptacle", "globalFetch", "globalHeaders", "globalRequest", "globalResponse", "buildResource", "serverResolver", "hostname", "recordType", "request", "resource", "signal", "globalFetch", "globalHeaders", "getCacheKey", "log", "debug", "Resolver", "options", "Receptacle", "request", "controller", "newServers", "i", "j", "temp", "servers", "hostname", "rrType", "recordType", "cached", "getCacheKey", "aborted", "server", "response", "buildResource", "data", "a", "ttl", "c", "src_default", "dns_browser_default", "src_default", "dnsaddrCode", "getProtocol", "dnsaddrResolver", "addr", "options", "resolver", "dns_browser_default", "peerId", "hostname", "proto", "addresses", "entry", "import_err_code", "DefaultConfig", "multiaddrs", "dnsaddrResolver", "publicAddressesFirst", "FaultTolerance", "AGENT_VERSION", "validateConfig", "opts", "_a", "_b", "resultingOptions", "merge_options_default", "errCode", "messages", "codes", "isNode", "isElectronMain", "isBrowser", "isWebWorker", "isElectronRenderer", "isReactNative", "PeerIdProto", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "createEd25519PeerId", "key", "generateKeyPair", "id", "createFromPrivKey", "createFromPrivKey", "privateKey", "peerIdFromKeys", "marshalPublicKey", "marshalPrivateKey", "import_err_code", "import_err_code", "DummyDHT", "EventEmitter", "symbol", "errCode", "messages", "codes", "import_err_code", "DummyPubSub", "EventEmitter", "errCode", "messages", "codes", "import_err_code", "import_timeout_abort_controller", "import_any_signal", "import_events", "import_err_code", "import_any_signal", "import_p_fifo", "import_events", "log", "logger", "DialRequest", "options", "addrs", "dialAction", "dialer", "_a", "tokens", "errCode", "codes", "tokenHolder", "FIFO", "token", "err", "dialAbortControllers", "controller", "completedDials", "done", "addr", "i", "conn", "signal", "log", "logger", "DefaultDialer", "components", "init", "publicAddressesFirst", "_", "index", "trackedMap", "key", "value", "resolvers", "dial", "err", "pendingTarget", "peerIdOrMultiaddr", "options", "peerId", "multiaddr", "getPeerAddress", "errCode", "codes", "controller", "controllerId", "randomId", "signal", "dialTarget", "pendingDial", "connection", "addrs", "isMultiaddr", "isPeerId", "ma", "peerIdMultiaddr", "addr", "addressPeerId", "peer", "addresses", "address", "isTruthy", "_a", "dialAction", "dialRequest", "DialRequest", "timeoutController", "signals", "num", "total", "tokens", "token", "resolvedMultiaddrs", "nm", "array", "newM", "m", "e", "log", "logger", "Libp2pNode", "EventEmitter", "init", "components", "DefaultComponents", "MemoryDatastore", "PersistentPeerStore", "evt", "peerData", "CustomEvent", "DefaultUpgrader", "fn", "DefaultDialer", "DefaultConnectionManager", "event", "DefaultRegistrar", "DefaultTransportManager", "DefaultAddressManager", "PeerRecordUpdater", "AutoDialler", "keychainOpts", "KeyChain", "NatManager", "IdentifyService", "DummyDHT", "DummyPubSub", "peerRouters", "DHTPeerRouting", "DefaultPeerRouting", "contentRouters", "DHTContentRouting", "CompoundContentRouting", "Circuit", "Relay", "FetchService", "PingService", "component", "isStartable", "service", "err", "peerId", "peerSet", "PeerSet", "conn", "peer", "options", "protocols", "errCode", "codes", "isMultiaddr", "peerIdFromString", "peerInfo", "peerKey", "concat", "fromString", "key", "unmarshalPublicKey", "handler", "protocol", "topology", "id", "createLibp2pNode", "datastore", "keyChain", "createEd25519PeerId", "validateConfig", "createLibp2p", "options", "node", "createLibp2pNode", "import_k_bucket", "import_netmask", "import_ipaddr", "is_valid", "parse", "ipaddr", "PRIVATE_IP_RANGES", "NETMASK_RANGES", "ip_range", "ipv4_check", "ip_addr", "r", "ipv6_check", "lib_default", "ip", "parsed", "isIP", "ip_regex_default", "private_ip_default", "lib_default", "LAN_PREFIX", "PROTOCOL_PREFIX", "PROTOCOL_DHT", "RECORD_KEY_PREFIX", "PROVIDER_KEY_PREFIX", "PK_PREFIX", "fromString", "removePrivateAddresses", "peer", "multiaddr", "type", "addr", "isPrivate", "private_ip_default", "removePublicAddresses", "convertBuffer", "buf", "sha256", "convertPeerId", "peerId", "bufferToRecordKey", "buf", "Key", "RECORD_KEY_PREFIX", "toString", "keyForPublicKey", "peer", "concat", "PK_PREFIX", "isPublicKeyKey", "key", "fromPublicKeyKey", "key", "peerIdFromBytes", "createPutRecord", "value", "timeReceived", "Libp2pRecord", "debounce", "callback", "wait", "timeout", "import_timeout_abort_controller", "mapIterable", "iter", "map", "iterator", "next", "val", "PeerMap", "map", "__publicField", "key", "value", "peer", "mapIterable", "val", "peerIdFromString", "fn", "PeerSet", "set", "__publicField", "key", "peer", "mapIterable", "val", "peerId", "peerIdFromString", "predicate", "str", "id", "other", "output", "PeerList", "list", "__publicField", "value", "mapIterable", "val", "peerIdFromString", "output", "predicate", "str", "index", "peerId", "peerIds", "len", "i", "KAD_CLOSE_TAG_NAME", "KAD_CLOSE_TAG_VALUE", "KBUCKET_SIZE", "PING_TIMEOUT", "PING_CONCURRENCY", "RoutingTable", "components", "init", "kBucketSize", "pingTimeout", "lan", "pingConcurrency", "protocol", "tagName", "tagValue", "logger", "updatePingQueueSizeMetric", "_a", "_b", "dist_default", "kBuck", "KBuck", "convertPeerId", "kClosest", "PeerSet", "updatePeerTags", "debounce", "newClosest", "contact", "addedPeers", "removedPeers", "peer", "err", "oldContacts", "newContact", "responded", "oldContact", "timeoutController", "options", "key", "closest", "res", "count", "p", "id", "xor", "a", "b", "result", "allocUnsafe", "i", "asUint8Array", "generated_prefix_list_browser_default", "length", "iterator", "count", "_", "import_timeout_abort_controller", "MAX_COMMON_PREFIX_LENGTH", "RoutingTableRefresh", "init", "peerRouting", "routingTable", "refreshInterval", "refreshQueryTimeout", "lan", "logger", "force", "prefixLength", "refreshCpls", "date", "lastRefresh", "index", "lastCpl", "n", "err", "cpl", "peerId", "controller", "peers", "length", "maxCommonPrefix", "dates", "i", "targetCommonPrefixLength", "randomData", "randomBytes", "randomUint16", "key", "peerIdFromBytes", "localKadId", "randomPrefix", "toggledLocalPrefix", "mask", "targetPrefix", "keyPrefix", "generated_prefix_list_browser_default", "keyBuffer", "keyView", "sha256", "count", "id", "distance", "xor", "leadingZeros", "byte", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "Message", "MessageType", "__MessageTypeValues", "enumeration", "ConnectionType", "__ConnectionTypeValues", "Peer", "value", "MESSAGE_TYPE", "Message", "CONNECTION_TYPE", "MESSAGE_TYPE_LOOKUP", "type", "key", "level", "toPbPeer", "raw", "_a", "dec", "msg", "fromPbPeer", "Libp2pRecord", "peer", "m", "peerIdFromBytes", "a", "multiaddr", "sendingQueryEvent", "fields", "MESSAGE_TYPE_LOOKUP", "peerResponseEvent", "finalPeerEvent", "queryErrorEvent", "providerEvent", "valueEvent", "dialingPeerEvent", "fields", "Network", "EventEmitter", "components", "init", "protocol", "lan", "logger", "to", "msg", "options", "dialingPeerEvent", "sendingQueryEvent", "stream", "response", "peerResponseEvent", "err", "queryErrorEvent", "abortableDuplex", "pipe", "encode", "drain", "res", "decode", "source", "buf", "first", "CodeError", "message", "Message", "peerData", "CustomEvent", "verifyRecord", "validators", "record", "key", "parts", "toString", "validator", "errMsg", "CodeError", "validatePublicKeyRecord", "publicKey", "keyhash", "publicKeyHash", "sha256", "equals", "bestRecord", "selectors", "k", "records", "errMsg", "CodeError", "parts", "toString", "selector", "publickKey", "ContentFetching", "components", "init", "validators", "selectors", "peerRouting", "queryManager", "routingTable", "network", "lan", "logger", "key", "rec", "dsKey", "bufferToRecordKey", "raw", "Libp2pRecord", "verifyRecord", "vals", "best", "options", "fixupRec", "createPutRecord", "value", "from", "equals", "err", "sentCorrection", "request", "Message", "MESSAGE_TYPE", "event", "queryErrorEvent", "CodeError", "record", "pipe", "source", "map", "events", "msg", "putEvent", "parallel", "records", "v", "i", "bestRecord", "localRec", "valueEvent", "id", "convertBuffer", "rtp", "self", "getValueQuery", "peer", "signal", "ContentRouting", "components", "init", "network", "peerRouting", "queryManager", "routingTable", "providers", "lan", "logger", "key", "multiaddrs", "options", "msg", "Message", "MESSAGE_TYPE", "sent", "maybeNotifyPeer", "event", "events", "sendEvent", "err", "queryErrorEvent", "pipe", "source", "map", "parallel", "toFind", "target", "id", "convertBuffer", "self", "provs", "peerId", "address", "peerResponseEvent", "providerEvent", "findProvidersQuery", "peer", "signal", "request", "p", "newProviders", "compare", "a", "b", "i", "PeerDistanceList", "originDhtKey", "capacity", "pd", "peerId", "dhtKey", "convertPeerId", "el", "xor", "a", "b", "compare", "peerIds", "dhtKeys", "furthestDistance", "keyDistance", "PeerRouting", "components", "init", "routingTable", "network", "validators", "queryManager", "lan", "logger", "peer", "peerData", "p", "err", "address", "key", "options", "msg", "Message", "MESSAGE_TYPE", "pkKey", "keyForPublicKey", "event", "recPeer", "peerIdFromKeys", "keys_exports", "CodeError", "valueEvent", "id", "pi", "finalPeerEvent", "convertPeerId", "peers", "self", "findPeerQuery", "signal", "request", "match", "foundPeer", "queryErrorEvent", "convertBuffer", "tablePeers", "PeerDistanceList", "getCloserPeersQuery", "toString", "addr", "errMsg", "record", "verifyRecord", "Libp2pRecord", "closerThan", "ids", "output", "peerId", "addresses", "protocols", "import_hashlru", "import_varint", "log", "logger", "Providers", "components", "init", "cacheSize", "cleanupInterval", "provideValidity", "cache", "dist_default", "err", "start", "count", "deleteCount", "deleted", "batch", "query", "PROVIDER_KEY_PREFIX", "entry", "cid", "peerId", "parseProviderKey", "time", "readTime", "now", "delta", "expired", "peers", "key", "makeProviderKey", "provs", "cacheKey", "loadProviders", "provider", "dsKey", "writeProviderEntry", "peerIdStr", "peerIdFromString", "cidStr", "toString", "store", "peer", "Key", "buffer", "varint", "parts", "providers", "buf", "import_timeout_abort_controller", "import_any_signal", "import_timeout_abort_controller", "import_any_signal", "MAX_XOR", "queryPath", "options", "key", "startingPeer", "ourPeerId", "signal", "query", "alpha", "pathIndex", "numPaths", "cleanUp", "queryFuncTimeout", "log", "peersSeen", "queue", "dist_default", "kadId", "convertBuffer", "queryPeer", "peer", "peerKadId", "peerXor", "toString", "xor", "timeout", "signals", "compoundSignal", "event", "closerPeer", "closerPeerKadId", "convertPeerId", "err", "queryErrorEvent", "toGenerator", "deferred", "pDefer", "running", "results", "cleanup", "result", "wasRunning", "CodeError", "merge", "sources", "output", "pushable", "source", "item", "err", "import_events", "QueryManager", "components", "init", "lan", "disjointPaths", "alpha", "controller", "key", "peers", "queryFunc", "options", "_a", "_b", "_c", "stopQueryTimer", "timeoutController", "abortController", "signals", "signal", "log", "logger", "toString", "peersToQuery", "startTime", "cleanUp", "EventEmitter", "peersSeen", "PeerSet", "paths", "peer", "index", "queryPath", "event", "merge", "err", "CustomEvent", "log", "logger", "AddProviderHandler", "init", "providers", "peerId", "msg", "CodeError", "cid", "CID", "pi", "m", "log", "logger", "FindNodeHandler", "components", "init", "peerRouting", "lan", "peerId", "msg", "closer", "equals", "ma", "getProtocol", "removePublicAddresses", "removePrivateAddresses", "multiaddrs", "response", "Message", "log", "logger", "GetProvidersHandler", "components", "init", "peerRouting", "providers", "lan", "peerId", "msg", "cid", "CID", "CodeError", "peers", "closer", "providerPeers", "closerPeers", "id", "response", "Message", "address", "peerIds", "output", "addrFilter", "removePublicAddresses", "removePrivateAddresses", "peer", "log", "logger", "GetValueHandler", "components", "init", "peerRouting", "peerId", "msg", "key", "CodeError", "response", "Message", "MESSAGE_TYPE", "isPublicKeyKey", "idFromKey", "fromPublicKeyKey", "pubKey", "err", "Libp2pRecord", "record", "closer", "dsKey", "bufferToRecordKey", "rawRecord", "log", "logger", "PingHandler", "peerId", "msg", "PutValueHandler", "components", "init", "validators", "logger", "peerId", "msg", "key", "record", "errMsg", "CodeError", "verifyRecord", "recordKey", "bufferToRecordKey", "err", "RPC", "components", "init", "providers", "peerRouting", "validators", "lan", "logger", "MESSAGE_TYPE", "GetValueHandler", "PutValueHandler", "FindNodeHandler", "AddProviderHandler", "GetProvidersHandler", "PingHandler", "peerId", "msg", "err", "handler", "data", "stream", "connection", "self", "pipe", "decode", "source", "desMessage", "Message", "res", "encode", "TopologyListener", "EventEmitter", "components", "init", "protocol", "lan", "logger", "topology", "createTopology", "peerId", "CustomEvent", "import_events", "take", "source", "limit", "items", "entry", "import_timeout_abort_controller", "import_any_signal", "QuerySelf", "components", "init", "peerRouting", "lan", "count", "interval", "queryTimeout", "logger", "timeoutController", "signal", "found", "pipe", "source", "take", "length", "err", "peerDiscovery", "symbol", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "KadDHT", "EventEmitter", "components", "init", "kBucketSize", "clientMode", "validators", "selectors", "querySelfInterval", "lan", "protocolPrefix", "pingTimeout", "pingConcurrency", "maxInboundStreams", "maxOutboundStreams", "providersInit", "logger", "PROTOCOL_PREFIX", "LAN_PREFIX", "PROTOCOL_DHT", "RoutingTable", "Providers", "Network", "QueryManager", "PeerRouting", "ContentFetching", "ContentRouting", "RoutingTableRefresh", "RPC", "TopologyListener", "QuerySelf", "evt", "peerData", "err", "CustomEvent", "peerId", "multiaddrs", "addr", "symbol", "removePublicAddresses", "removePrivateAddresses", "mode", "key", "value", "options", "id", "log", "logger", "DualKadDHT", "EventEmitter", "components", "wan", "lan", "evt", "CustomEvent", "symbol", "mode", "key", "value", "options", "event", "merge", "queriedPeers", "foundValue", "CodeError", "queryErrorEvent", "sent", "success", "errors", "dhts", "dht", "id", "KadDHT", "DualKadDHT", "components", "init", "kadDHT", "log", "logger", "DEFAULT_BOOTSTRAP_TAG_NAME", "DEFAULT_BOOTSTRAP_TAG_VALUE", "DEFAULT_BOOTSTRAP_TAG_TTL", "DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT", "Bootstrap", "EventEmitter", "components", "options", "candidate", "P2P", "ma", "multiaddr", "peerIdStr", "peerData", "peerIdFromString", "symbol", "err", "CustomEvent", "bootstrap", "init", "web_socket_browser_default", "import_event_iterator", "isArrayBuffer", "obj", "_a", "source_default", "socket", "connected", "resolve", "reject", "isConnected", "connError", "cleanUp", "cont", "onOpen", "onError", "event", "source", "messages", "push", "stop", "fail", "onMessage", "data", "fromString", "chunk", "ready_default", "socket", "resolve", "reject", "cleanup", "handleOpen", "handleErr", "event", "sink_default", "socket", "options", "source", "data", "ready_default", "err", "resolve", "reject", "event", "duplex_default", "socket", "options", "connectedSource", "source_default", "remoteAddress", "remotePort", "url", "sink_default", "resolve", "import_iso_url", "map", "def", "ws_url_default", "url", "location", "connect", "addr", "opts", "location", "url", "ws_url_default", "socket", "web_socket_browser_default", "duplex_default", "createListener", "log", "logger", "socketToMaConn", "stream", "remoteAddr", "options", "maConn", "source", "abortableSource", "err", "start", "pTimeout", "host", "port", "all", "multiaddrs", "ma", "testMa", "WebSockets", "WebSocketsSecure", "wss", "symbol", "FaultTolerance", "log", "logger", "WebSockets", "init", "symbol", "ma", "options", "socket", "maConn", "socketToMaConn", "conn", "_a", "_b", "AbortError", "cOpts", "errorPromise", "pDefer", "errfn", "err", "rawSocket", "connect", "multiaddrToUri", "onAbort", "abort", "resolve", "reject", "createListener", "multiaddrs", "isBrowser", "isWebWorker", "wss", "all", "webSockets", "import_varint", "allocUnsafe", "size", "MessageTypes", "MessageTypeNames", "InitiatorMessageTypes", "ReceiverMessageTypes", "DEFAULT_BATCH_SIZE", "DEFAULT_SERIALIZE", "buf", "list", "batchedBytes", "source", "options", "buffer", "Uint8ArrayList", "ended", "deferred", "pDefer", "size", "yieldAfter", "serialize", "timeout", "err", "b", "src_default", "POOL_SIZE", "Encoder", "allocUnsafe", "msg", "list", "pool", "offset", "varint", "MessageTypes", "header", "encoder", "encode", "source", "minSendBytes", "messages", "Uint8ArrayList", "src_default", "obj", "m", "MAX_MSG_SIZE", "MAX_MSG_QUEUE_SIZE", "Decoder", "maxMessageSize", "maxUnprocessedMessageQueueSize", "Uint8ArrayList", "chunk", "msgs", "err", "id", "type", "length", "offset", "msg", "MessageTypes", "data", "h", "readVarInt", "end", "MessageTypeNames", "MSB", "REST", "buf", "res", "shift", "counter", "b", "l", "log", "logger", "ERR_STREAM_RESET", "ERR_STREAM_ABORT", "ERR_SINK_ENDED", "ERR_DOUBLE_SINK", "createStream", "options", "id", "name", "send", "onEnd", "type", "maxMsgSize", "MAX_MSG_SIZE", "abortController", "resetController", "closeController", "Types", "InitiatorMessageTypes", "ReceiverMessageTypes", "externalId", "streamName", "sourceEnded", "sinkEnded", "sinkSunk", "endErr", "timeline", "onSourceEnd", "err", "stream", "onSinkEnd", "streamSource", "pushable", "CodeError", "source", "signal", "anySignal", "abortableSource", "Uint8ArrayList", "fromString", "data", "import_rate_limiter_flexible", "log", "logger", "MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION", "MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION", "MAX_STREAM_BUFFER_SIZE", "DISCONNECT_THRESHOLD", "printMessage", "msg", "output", "MessageTypeNames", "MessageTypes", "toString", "MplexStreamMuxer", "init", "source", "streams", "stream", "name", "id", "registry", "err", "s", "options", "type", "CodeError", "createStream", "signal", "anySignal", "abortableSource", "decoder", "Decoder", "chunk", "pushableV", "encode", "message", "maxBufferSize", "error", "Mplex", "init", "MplexStreamMuxer", "mplex", "isAsyncIterable", "thing", "defaultEncoder", "length", "lengthLength", "encodingLength", "lengthBuf", "allocUnsafe", "encode", "source", "options", "encodeLength", "maybeYield", "chunk", "isAsyncIterable", "Uint8ArrayList", "InvalidMessageLengthError", "__publicField", "InvalidDataLengthError", "InvalidDataLengthLengthError", "UnexpectedEOFError", "MAX_LENGTH_LENGTH", "MAX_DATA_LENGTH", "ReadMode", "defaultDecoder", "buf", "length", "decode", "encodingLength", "source", "options", "buffer", "Uint8ArrayList", "mode", "dataLength", "lengthDecoder", "maxLengthLength", "maxDataLength", "maybeYield", "InvalidMessageLengthError", "InvalidDataLengthError", "dataLengthLength", "err", "InvalidDataLengthLengthError", "data", "isAsyncIterable", "UnexpectedEOFError", "reader", "byteLength", "varByteSource", "done", "value", "l", "import_err_code", "defaultLengthDecoder", "buf", "unsigned", "pbStream", "duplex", "opts", "write", "pushable", "err", "source", "readBuffer", "Uint8ArrayList", "W", "bytes", "done", "value", "errCode", "dataLength", "lengthBuffer", "decodeLength", "proto", "data", "encode", "d", "originalStream", "pair", "deferred", "pDefer", "piped", "source", "duplexPair", "a", "pair", "b", "_a", "_b", "DUMP_SESSION_KEYS", "import_hkdf", "x25519", "import_sha256", "import_chacha20poly1305", "stablelib", "data", "ck", "ikm", "okm", "k1", "k2", "k3", "keypair", "seed", "privateKey", "publicKey", "plaintext", "nonce", "ad", "k", "ciphertext", "dst", "import_chacha20poly1305", "allocUnsafe", "len", "uint16BEEncode", "value", "target", "uint16BEDecode", "data", "encode0", "message", "concat", "encode1", "encode2", "decode0", "input", "decode1", "decode2", "encryptStream", "handshake", "metrics", "source", "chunk", "end", "data", "uint16BEEncode", "decryptStream", "encrypted", "dst", "decrypted", "valid", "UnexpectedPeerError", "message", "InvalidCryptoExchangeError", "NoiseExtensions", "_codec", "message", "obj", "w", "opts", "value", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "NoiseHandshakePayload", "getPayload", "localPeer", "staticPublicKey", "extensions", "signedPayload", "signPayload", "getHandshakePayload", "createHandshakePayload", "libp2pPublicKey", "NoiseHandshakePayload", "peerId", "payload", "unmarshalPrivateKey", "getPeerIdFromPayload", "peerIdFromKeys", "decodePayload", "publicKey", "prefix", "fromString", "concat", "verifySignedPayload", "noiseStaticKey", "remotePeer", "payloadPeerId", "generatedPayload", "unmarshalPublicKey", "isValidPublicKey", "pk", "log", "logger", "keyLogger", "DUMP_SESSION_KEYS", "log", "logLocalStaticKeys", "s", "toString", "logLocalEphemeralKeys", "e", "logRemoteStaticKey", "rs", "logRemoteEphemeralKey", "re", "logCipherState", "session", "ERR_MAX_NONCE", "Nonce", "n", "AbstractHandshake", "crypto", "cs", "ad", "plaintext", "e", "ciphertext", "dst", "valid", "k", "emptyKey", "equals", "n", "ss", "encryptedMessage", "privateKey", "publicKey", "derivedU8", "err", "log", "data", "a", "b", "concat", "ikm", "ck", "tempK", "Nonce", "protocolName", "protocolNameBytes", "fromString", "h", "key", "tempk1", "tempk2", "cs1", "cs2", "payload", "ne", "ns", "message", "XX", "AbstractHandshake", "prologue", "s", "rs", "psk", "name", "ss", "re", "hs", "payload", "e", "ns", "ne", "ciphertext", "spk", "messageBuffer", "cs1", "cs2", "message", "isValidPublicKey", "valid1", "plaintext", "valid2", "initiator", "session", "ephemeral", "h", "resultingBuffer", "valid", "resultingPlaintext", "resultingValid", "XXHandshake", "isInitiator", "payload", "prologue", "crypto", "staticKeypair", "connection", "remotePeer", "handshake", "XX", "logLocalStaticKeys", "log", "messageBuffer", "encode0", "logLocalEphemeralKeys", "receivedMessageBuffer", "decode0", "valid", "InvalidCryptoExchangeError", "logRemoteEphemeralKey", "decode1", "plaintext", "logRemoteStaticKey", "decodedPayload", "decodePayload", "getPeerIdFromPayload", "verifySignedPayload", "e", "err", "UnexpectedPeerError", "encode1", "encode2", "decode2", "logCipherState", "session", "cs", "ciphertext", "dst", "encryption", "registerMetrics", "metrics", "Noise", "init", "staticNoiseKey", "extensions", "crypto", "prologueBytes", "metrics", "stablelib", "registerMetrics", "localPeer", "connection", "remotePeer", "wrappedConnection", "pbStream", "uint16BEEncode", "uint16BEDecode", "handshake", "params", "payload", "getPayload", "_a", "_b", "isInitiator", "XXHandshake", "e", "secure", "user", "duplexPair", "network", "pipe", "encryptStream", "decode", "decryptStream", "noise", "init", "Noise", "mergeOptions", "merge_options_default", "createLibp2p", "options", "peerId", "multiaddrs", "repo", "keychainConfig", "config", "datastore", "libp2pOptions", "getLibp2pOptions", "_a", "_b", "_c", "_d", "getPubsubRouter", "router", "get", "availableRouters", "routers", "errCode", "libp2pDefaults", "ma", "ipfsCore", "mplex", "noise", "kadDHT", "ipnsValidator", "ipnsSelector", "boostrapNodes", "bootstrap", "constructorOptions", "libp2pFinalConfig", "libp2pConfig", "delegateHosts", "delegateString", "delegateAddr", "multiaddr", "delegateApiOptions", "delegateHttpClient", "create", "delegatedContentRouting", "delegatedPeerRouting", "d", "t", "webSockets", "PeerIdProto", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "createEd25519PeerId", "key", "generateKeyPair", "id", "createFromPrivKey", "createRSAPeerId", "opts", "key", "generateKeyPair", "id", "createFromPrivKey", "createFromPrivKey", "privateKey", "peerIdFromKeys", "marshalPublicKey", "marshalPrivateKey", "import_err_code", "mergeOptions", "merge_options_default", "log", "logger", "Storage", "peerId", "keychain", "repo", "print", "isNew", "codecs", "options", "repoAutoMigrate", "inputRepo", "onMigrationProgress", "createRepo", "loadRepo", "configureRepo", "err", "ERR_REPO_NOT_INITIALIZED", "NotEnabledError", "initRepo", "initOptions", "exists", "decodePeerId", "initPeerId", "identity", "peerIdToIdentity", "config", "applyProfiles", "config_browser_default", "keychainConfig", "libp2p", "createLibp2p", "Key", "isPeerId", "rawPrivateKey", "fromString", "key", "unmarshalPrivateKey", "peerIdFromKeys", "algorithm", "bits", "createEd25519PeerId", "createRSAPeerId", "errCode", "toString", "profiles", "pass", "original", "changed", "mergeConfigs", "NotInitializedError", "buf", "changes", "name", "profile", "import_varint_decoder", "varint", "varintEncoder", "buf", "out", "acc", "curr", "offset", "num", "varint_encoder_default", "WantListEntry", "cid", "priority", "wantType", "base58btc", "other", "import_minimal", "$Reader", "$protobuf", "$Writer", "$util", "$root", "Message", "p", "ks", "i", "m", "w", "r", "l", "c", "t", "d", "o", "j", "typeUrlPrefix", "Wantlist", "valuesById", "values", "Entry", "Block", "BlockPresence", "WantType", "Message", "sortBy", "fn", "list", "a", "b", "aa", "bb", "Wantlist", "stats", "libp2p", "trackedMap", "cid", "priority", "wantType", "cidStr", "base58btc", "entry", "WantListEntry", "o", "WantlistEntry", "Wantlist", "BitswapMessageEntry", "cid", "priority", "wantType", "cancel", "sendDontHave", "val", "base58btc", "other", "logger", "id", "subsystem", "name", "isMapEqual", "a", "b", "key", "valueA", "valueB", "equals", "BitswapMessageEntry", "BitswapMessage", "full", "cid", "priority", "wantType", "cancel", "sendDontHave", "cidStr", "base58btc", "entry", "BitswapMessageEntry", "block", "size", "msg", "Message", "data", "CID", "version", "codec", "multihash", "digestLength", "prefix", "varint_encoder_default", "bpType", "other", "isMapEqual", "list", "blocks", "raw", "hashLoader", "decoded", "isFull", "blockPresence", "b", "hash", "sha256", "p", "values", "vd", "cidVersion", "multicodec", "hashAlg", "hasher", "CodeError", "kMaxPriority", "maxListeners", "wantlistSendDebounceMs", "functionDebounce", "debounce", "fn", "wait", "callFirst", "timeout", "debouncedFn", "clear", "flush", "call", "debounceWrapper", "context", "args", "callNow", "MsgQueue", "selfPeerId", "otherPeerId", "network", "logger", "functionDebounce", "wantlistSendDebounceMs", "msg", "entries", "BitswapMessage", "entry", "err", "WantManager", "peerId", "network", "stats", "libp2p", "trackedMap", "Wantlist", "logger", "cids", "cancel", "force", "entries", "cid", "i", "BitswapMessage", "kMaxPriority", "e", "base58btc", "p", "mq", "MsgQueue", "fullwantlist", "entry", "options", "noop", "TopologyImpl", "init", "topologySymbol", "registrar", "peerId", "createTopology", "import_timeout_abort_controller", "BITSWAP100", "BITSWAP110", "BITSWAP120", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "DEFAULT_INCOMING_STREAM_TIMEOUT", "Network", "libp2p", "bitswap", "stats", "options", "logger", "topology", "createTopology", "protocol", "conn", "id", "stream", "connection", "controller", "pipe", "abortableSource", "decode", "source", "data", "message", "BitswapMessage", "err", "peerId", "cid", "connectAttempts", "found", "provider", "peer", "msg", "stringId", "writeMessage", "blocks", "block", "log", "serialized", "encode", "Ledger", "peerId", "Wantlist", "n", "cid", "priority", "wantType", "SortedMap", "entries", "cmp", "k", "v", "i", "newIdx", "j", "lower", "upper", "pivot", "cb", "thisArg", "a", "b", "DefaultTaskMerger", "RequestQueue", "taskMerger", "SortedMap", "PeerTasks", "peerId", "tasks", "peerTasks", "targetMinBytes", "pendingSize", "v", "topic", "task", "PendingTasks", "existingTask", "tasksWithTopic", "activeTask", "size", "pendingTasks", "i", "a", "b", "priority", "obj", "TaskMerger", "task", "tasksWithTopic", "haveBlock", "isWantBlock", "existing", "newTask", "existingTask", "taskData", "existingData", "WantType", "BitswapMessage", "TARGET_MESSAGE_SIZE", "MAX_SIZE_REPLACE_HAS_WITH_BLOCK", "DecisionEngine", "peerId", "blockstore", "network", "stats", "libp2p", "opts", "logger", "trackedMap", "RequestQueue", "TaskMerger", "tasks", "pendingSize", "msg", "blockCids", "blockTasks", "task", "cid", "CID", "blocks", "topic", "taskData", "blk", "cidStr", "block", "err", "peerIdStr", "ledger", "l", "want", "blockSize", "isWantBlock", "entrySize", "base58btc", "Wantlist", "cancels", "wants", "entry", "cids", "c", "blockSizes", "w", "id", "wantType", "k", "v", "res", "e", "blocksMap", "Ledger", "import_events", "unwantEvent", "cid", "toString", "blockEvent", "Notifications", "peerId", "maxListeners", "logger", "block", "event", "options", "blockEvt", "unwantEvt", "resolve", "reject", "onUnwant", "onBlock", "data", "import_events", "import_events", "import_moving_average", "Stat", "initialCounters", "options", "key", "interval", "MovingAverage", "counter", "inc", "urgency", "last", "op", "latestTime", "timeDiff", "timeDiffMS", "count", "hz", "movingAverages", "movingAverageInterval", "movingAverage", "defaultOptions", "Stats", "libp2p", "initialCounters", "_options", "options", "Stat", "stats", "trackedMap", "peerStat", "peerId", "peerIdStr", "peer", "counter", "inc", "peerStats", "import_any_signal", "defaultOptions", "statsKeys", "Bitswap", "BaseBlockstore", "libp2p", "blockstore", "options", "logger", "Stats", "Network", "DecisionEngine", "WantManager", "Notifications", "peerId", "incoming", "received", "cidStr", "data", "cid", "CID", "wasWanted", "has", "peerIdStr", "exists", "err", "_options", "fetchFromNetwork", "promptedNetwork", "loadOrFetchFromNetwork", "controller", "signal", "cids", "cidsArray", "block", "source", "key", "value", "createBitswap", "libp2p", "blockstore", "options", "Bitswap", "import_err_code", "errors_exports", "__export", "abortedError", "notFoundError", "import_err_code", "err", "errCode", "Errors", "errors_exports", "BlockStorage", "BaseBlockstore", "blockstore", "bitswap", "cid", "block", "options", "blocks", "missingBlocks", "filter", "key", "cids", "getFromBitswap", "pushable", "getFromChild", "merge", "q", "Network", "peerId", "libp2p", "bitswap", "repo", "blockstore", "print", "hashers", "options", "config", "createLibp2p", "readAddrs", "ma", "createBitswap", "BlockStorage", "network", "peerIdStr", "addrs", "swarm", "addr", "multiaddr", "WEBSOCKET_STAR_PROTO_CODE", "errCode", "maId", "createAddrs", "network", "addrs", "options", "peers", "libp2p", "peer", "mi", "withTimeoutOption", "createConnect", "network", "connect", "multiaddrOrPeerId", "options", "libp2p", "withTimeoutOption", "createDisconnect", "network", "disconnect", "addr", "options", "libp2p", "withTimeoutOption", "createLocalAddrs", "network", "localAddrs", "options", "libp2p", "withTimeoutOption", "createPeers", "network", "peers", "options", "libp2p", "connection", "peer", "withTimeoutOption", "SwarmAPI", "network", "createAddrs", "createConnect", "createDisconnect", "createLocalAddrs", "createPeers", "basePacket", "createPing", "network", "ping", "peerId", "options", "libp2p", "storedPeer", "id", "remotePeer", "packetCount", "totalTime", "i", "time", "err", "average", "withTimeoutOption", "import_err_code", "IPNS_PREFIX", "toDHTKey", "str", "buf", "base58btc", "base36", "concat", "fromString", "createDht", "network", "repo", "peerId", "get", "put", "findProvs", "findPeer", "provide", "query", "key", "options", "libp2p", "use", "dhtKey", "errCode", "value", "cid", "peerIdToFind", "peerIdToQuery", "bytes", "asCid", "CID", "peerIdFromString", "withTimeoutOption", "net", "fn", "NotEnabledError", "import_err_code", "import_dlv", "createPubsub", "network", "config", "isEnabled", "get", "handlers", "onMessage", "withTimeoutOption", "subscribe", "notEnabled", "unsubscribe", "publish", "ls", "peers", "topic", "handler", "options", "libp2p", "evt", "msg", "h", "data", "errCode", "NotEnabledError", "mergeOptions", "merge_options_default", "log", "logger", "IPNS_INIT_KEYSPACE_TIMEOUT", "IPFS", "print", "storage", "codecs", "options", "peerId", "repo", "keychain", "network", "Service", "Network", "preload", "createPreloader", "dns", "createDns", "isOnline", "createIsOnline", "ipns", "IPNSAPI", "multihashHashers", "hashes", "hasher", "Multihashes", "multibaseCodecs", "bases", "base", "Multibases", "pin", "PinAPI", "block", "BlockAPI", "name", "NameAPI", "resolve", "createResolve", "dag", "DagAPI", "refs", "createRefs", "createLocal", "add", "addAll", "cat", "get", "ls", "RootAPI", "files", "createFiles", "mfsPreload", "createMfsPreloader", "createStart", "createStop", "createDht", "createPubsub", "createId", "createVersion", "BitswapAPI", "BootstrapAPI", "createConfig", "createPing", "KeyAPI", "ObjectAPI", "RepoAPI", "StatsAPI", "SwarmAPI", "net", "notImplemented", "errCode", "notImplementedIter", "AlreadyInitializedError", "addEmptyDir", "ipfs", "buf", "encode", "UnixFS", "cid", "getDefaultOptions", "create", "initOptions", "id", "identity", "blockCodecs", "src_exports", "lib_exports", "codec", "multicodecs", "Multicodecs", "Storage", "config", "timeoutController", "fromString", "import_url_source", "create", "CID", "cid", "ipfs", "create", "filename", "content", "fileToAdd", "file", "cid", "CID", "decoder", "chunk", "getSyncTitle", "gistId", "localstorage_default", "shareNoteCommand", "icon", "exit_up_default", "share", "sharePublicLinkCommand", "commander_default", "saveNote", "dom_default", "note", "getNote", "rawLink", "publishGist", "gitResponse", "response", "files", "fileContents", "gistFile", "rawUrl", "linkToShare", "url", "copyToClipboard", "commands", "pencil_default", "resetNoteManager", "checkmark_circle_default", "disableSync", "updateGist", "setSavedState", "page_break_default", "markDownViewer_default", "frame_expand_default", "earth_default", "cid", "ipfs", "isUserLoggedIn", "leaf_default", "list_default", "trash_default", "deleteNote", "cloud_sync_default", "token", "goAuthenticate", "setGistToSyncWith", "syncNotesWithGitHub", "lighter_default", "notify_default", "enter_down_default", "text", "title", "saveFileAs", "envelope_default", "mailTo", "bug_default", "previousStatus", "arrow_right_circle_default", "picture_default", "bgImage", "sleep", "printer_default", "magic_wand_default", "prettifyJSON_default", "rocket_default", "spell_check_default", "selectedValue", "valueToFind", "positionOfFirstChar", "replacementValue", "download_default", "notes", "getNotes", "saveDataToFile", "keyListener", "key", "fn", "k", "finalKey", "functionToCall", "e", "event", "keyListener_default", "link", "textOrNode", "url", "a", "isElement", "isSameYear", "aDate", "bDate", "yearA", "yearB", "isSameMonth", "monthA", "monthB", "isSameDateOfMonth", "dateA", "dateB", "isSameDate", "monthNames", "shortMonthNames", "name", "isYesterday", "date", "theDate", "yesterDate", "relativeDate", "dateCreated", "month", "year", "day", "isArraySorted", "arr", "currentValue", "item", "max", "smartFilter", "phrase", "filter", "wordParts", "w", "indexes", "f", "i", "currentValue", "fi", "isArraySorted", "requestNotificationPermission", "localstorage_default", "permission", "registerServiceWorker", "getShortcut", "key", "k", "commander", "commanderModes", "state", "newState", "what", "dom_default", "mode", "requestNotificationPermission", "commands", "e", "direction", "currentlySelected", "lastOption", "indexToSelect", "command", "button", "keyListener_default", "revisions", "getNote", "revisionsOptions", "a", "b", "aDateCreated", "bDateCreated", "id", "i", "div", "relativeDate", "url", "r", "value", "notes", "getNotes", "title", "smartFilter", "deleted", "getDateCreatedFromTitle", "cid", "dateCreated", "linkParams", "href", "noteLink", "link", "commandComponents", "experimental", "localstorage_default", "call", "icon", "commander_default", "import_textarea_caret", "findCurrentLine", "text", "caretIndex", "acc", "line", "isFound", "recon", "currentLength", "autoCompleteCheckboxes", "e", "currentLine", "findCurrentLine", "completers", "startsWith", "compleano", "dom_default", "isLastCharacterInTheWord", "text", "characterIndex", "placeSuggestion", "textEl", "coords", "getCaretCoordinates", "top", "left", "actualTerminalHeight", "dom_default", "main", "getCurrentlyTypingWord", "cursorIndexPosition", "word", "currentIndex", "character", "getPredictions", "sanitizedWord", "trieDictionary", "terminal", "initState", "state", "newState", "e", "direction", "currentlySelected", "lastOption", "indexToSelect", "complete", "currentWord", "completion", "prediction", "inlineSuggestion", "div", "optionsUl", "selectedIndex", "options", "i", "command", "icon", "trash_default", "localstorage_default", "m", "optionList", "el", "commander_default", "fullText", "charTyped", "matches", "firstMatch", "autoCompleteCheckboxes", "currentlySavedNote", "getNote", "title", "getTitle", "isNoteSaved", "setSavedState", "_a", "clipboardItems", "clipboardItem", "imageTypes", "type", "imageType", "blob", "token", "image", "fileExtension", "fileName", "nanoid", "url", "configuration", "handleErrorResponse", "response", "error", "notify_default", "imageURI", "markDownViewer_default", "isSyncEnabled", "authToken", "gistId", "localstorage_default", "groupByFrequency", "entries", "acc", "word", "frequency", "cc", "Node", "char", "prefix", "dictionary", "nodeInstance", "node", "firstChar", "rest", "isLast", "newNode", "Trie", "rootNode", "character", "frequencyGroups", "a", "b", "key", "errorHandler", "error", "message", "notify_default", "errorHandler_default", "retrieveNoteFromIPFS", "cid", "dom_default", "remoteNote", "ipfs", "setSavedState", "setNoteFromRawUrl", "rawUrl", "response", "dom_default", "setNoteFromGist", "gistId", "gist", "getGist", "files", "fileContents", "gistFile", "content", "notify_default", "actOnURLStateChange", "e", "oldURL", "newURL", "oldPageId", "url", "newPageId", "hasPageIdChanged", "oldV", "newV", "r", "setNoteFromHash", "raw", "isANewNote", "retrieveNoteFromIPFS", "q", "queryResult", "search", "isDevelopmentMode", "enableDevelopment", "autoMagicallyCheckBoxes", "dom_default", "el", "trieDictionary", "Trie", "initInfoPanel", "dom_default", "note", "getNote", "relativeDate", "isSyncEnabled", "syncEl", "disableSync", "p", "e", "disableSyncOnCurrentNote", "deleteButton", "deleteNote", "main", "words", "localstorage_default", "errorHandler_default", "welcome_default", "commander_default", "terminal", "resetPageTitle", "setNoteFromHash", "url", "copyToClipboard", "markDownViewer_default", "actOnURLStateChange", "registerServiceWorker", "autoMagicallyCheckBoxes", "syncNotesWithGitHub", "setAuthTokenFromCallback", "enableDevelopment", "main_default", "main_default"] } diff --git a/out/service-worker.js b/out/service-worker.js index c61fbf8..0d10722 100644 --- a/out/service-worker.js +++ b/out/service-worker.js @@ -4,7 +4,7 @@ importScripts( ); const { precacheAndRoute } = workbox.precaching; -precacheAndRoute([{"revision":"b9816a8779946abd6884c8d0835aab1a","url":"arrow-right-circle-2Q6EHM2H.svg"},{"revision":"6b352c8234986802e30f57b4a173db65","url":"bug-36UGMUXT.svg"},{"revision":"715ea2f9ed9c32e912d10f1f8cfd1333","url":"checkmark-circle-JQ7ADSUI.svg"},{"revision":"642881591601125261f78f3ad5a52c32","url":"cloud-sync-F3RLGHML.svg"},{"revision":"f8fc1cc37e1226392cc0cc4c6068cf66","url":"download-FVXMIYZ4.svg"},{"revision":"9c2e1d19ec4949a1cab62aa4f3dcf4ec","url":"earth-DJLABK7O.svg"},{"revision":"08cc87504b693a32d717aaaf13e414a0","url":"enter-down-6TVO6OFR.svg"},{"revision":"a69f752fafc2a5f161dbc1c851d4f17b","url":"envelope-Z2VRVSLR.svg"},{"revision":"7665092453f7b45c2782db5f16e6ce5c","url":"exit-up-GH6BPN2X.svg"},{"revision":"7cdfed241e2edb7e7ed37eaaf9bae94a","url":"favicon.ico"},{"revision":"fd02fe115943662aa6a6581ab31ce38d","url":"frame-expand-CX6CNP53.svg"},{"revision":"59b2a5f4e0884d7c2d4e2324e3727ecc","url":"images/icons/icon-128x128.png"},{"revision":"77b08750ba54d3a8f21f331d04530637","url":"images/icons/icon-144x144.png"},{"revision":"84cb614c066d965f784c2ed810dc31e1","url":"images/icons/icon-152x152.png"},{"revision":"2f95a518fbfc169e32fd5fb7a5b063fd","url":"images/icons/icon-192x192.png"},{"revision":"87029203db3903aab4be829b030b3514","url":"images/icons/icon-384x384.png"},{"revision":"ad2869f40002d4f268f6b60a0c115136","url":"images/icons/icon-512x512.png"},{"revision":"e70a2704695d7026ab6fe403f4604867","url":"images/icons/icon-72x72.png"},{"revision":"0bfc17b6ea552774646836236d7e5954","url":"images/icons/icon-96x96.png"},{"revision":"79e59607337b1e6a34e0935965ad4d21","url":"images/icons/maskable_icon.png"},{"revision":"59b2a5f4e0884d7c2d4e2324e3727ecc","url":"images/images/icons/icon-128x128.png"},{"revision":"77b08750ba54d3a8f21f331d04530637","url":"images/images/icons/icon-144x144.png"},{"revision":"84cb614c066d965f784c2ed810dc31e1","url":"images/images/icons/icon-152x152.png"},{"revision":"2f95a518fbfc169e32fd5fb7a5b063fd","url":"images/images/icons/icon-192x192.png"},{"revision":"87029203db3903aab4be829b030b3514","url":"images/images/icons/icon-384x384.png"},{"revision":"ad2869f40002d4f268f6b60a0c115136","url":"images/images/icons/icon-512x512.png"},{"revision":"e70a2704695d7026ab6fe403f4604867","url":"images/images/icons/icon-72x72.png"},{"revision":"0bfc17b6ea552774646836236d7e5954","url":"images/images/icons/icon-96x96.png"},{"revision":"79e59607337b1e6a34e0935965ad4d21","url":"images/images/icons/maskable_icon.png"},{"revision":"ce9a2fd61cb2f8c25e2a20ffceb432d1","url":"index.html"},{"revision":"c1c5746c98e772b83b0394796a58c7fd","url":"index.js"},{"revision":"3ce2509712df0cd63aa28b3bedf3ffe6","url":"leaf-CGBE7XAJ.svg"},{"revision":"4e1ab5abca803d8371db0bac365fdf93","url":"lighter-UBEI67LL.svg"},{"revision":"2694687077344bc31a1968ce3329660b","url":"list-LK7OCHR7.svg"},{"revision":"b399e36fdd1b4597c9c5036c6a4869f8","url":"magic-wand-JQJ6EKRO.svg"},{"revision":"0492c5cb8efeb5b012eb16185a9d841d","url":"manifest.json"},{"revision":"126653c706df1e5655be880ddc02e164","url":"page-break-BLVP5QBQ.svg"},{"revision":"d26a9edb2928bbeba1749f454aab95d3","url":"pencil-X3ZMY3QU.svg"},{"revision":"1c74f8e5f212764756b46b728d31a97f","url":"picture-3TDOSVS3.svg"},{"revision":"299ddb01bcee73f853049f4ca36e9dc8","url":"printer-B7RMPYZC.svg"},{"revision":"1eccb57fd8613bb74b8394400b7b1b1f","url":"rocket-AIY2RJJS.svg"},{"revision":"41be43627587fa71a315c9a1d2565283","url":"spell-check-V6QYTGNT.svg"},{"revision":"abef7b4a2eb95c594f45063c3fe372eb","url":"trash-RDL437QG.svg"}]); +precacheAndRoute([{"revision":"b9816a8779946abd6884c8d0835aab1a","url":"arrow-right-circle-2Q6EHM2H.svg"},{"revision":"6b352c8234986802e30f57b4a173db65","url":"bug-36UGMUXT.svg"},{"revision":"715ea2f9ed9c32e912d10f1f8cfd1333","url":"checkmark-circle-JQ7ADSUI.svg"},{"revision":"642881591601125261f78f3ad5a52c32","url":"cloud-sync-F3RLGHML.svg"},{"revision":"f8fc1cc37e1226392cc0cc4c6068cf66","url":"download-FVXMIYZ4.svg"},{"revision":"9c2e1d19ec4949a1cab62aa4f3dcf4ec","url":"earth-DJLABK7O.svg"},{"revision":"08cc87504b693a32d717aaaf13e414a0","url":"enter-down-6TVO6OFR.svg"},{"revision":"a69f752fafc2a5f161dbc1c851d4f17b","url":"envelope-Z2VRVSLR.svg"},{"revision":"7665092453f7b45c2782db5f16e6ce5c","url":"exit-up-GH6BPN2X.svg"},{"revision":"7cdfed241e2edb7e7ed37eaaf9bae94a","url":"favicon.ico"},{"revision":"fd02fe115943662aa6a6581ab31ce38d","url":"frame-expand-CX6CNP53.svg"},{"revision":"59b2a5f4e0884d7c2d4e2324e3727ecc","url":"images/icons/icon-128x128.png"},{"revision":"77b08750ba54d3a8f21f331d04530637","url":"images/icons/icon-144x144.png"},{"revision":"84cb614c066d965f784c2ed810dc31e1","url":"images/icons/icon-152x152.png"},{"revision":"2f95a518fbfc169e32fd5fb7a5b063fd","url":"images/icons/icon-192x192.png"},{"revision":"87029203db3903aab4be829b030b3514","url":"images/icons/icon-384x384.png"},{"revision":"ad2869f40002d4f268f6b60a0c115136","url":"images/icons/icon-512x512.png"},{"revision":"e70a2704695d7026ab6fe403f4604867","url":"images/icons/icon-72x72.png"},{"revision":"0bfc17b6ea552774646836236d7e5954","url":"images/icons/icon-96x96.png"},{"revision":"79e59607337b1e6a34e0935965ad4d21","url":"images/icons/maskable_icon.png"},{"revision":"59b2a5f4e0884d7c2d4e2324e3727ecc","url":"images/images/icons/icon-128x128.png"},{"revision":"77b08750ba54d3a8f21f331d04530637","url":"images/images/icons/icon-144x144.png"},{"revision":"84cb614c066d965f784c2ed810dc31e1","url":"images/images/icons/icon-152x152.png"},{"revision":"2f95a518fbfc169e32fd5fb7a5b063fd","url":"images/images/icons/icon-192x192.png"},{"revision":"87029203db3903aab4be829b030b3514","url":"images/images/icons/icon-384x384.png"},{"revision":"ad2869f40002d4f268f6b60a0c115136","url":"images/images/icons/icon-512x512.png"},{"revision":"e70a2704695d7026ab6fe403f4604867","url":"images/images/icons/icon-72x72.png"},{"revision":"0bfc17b6ea552774646836236d7e5954","url":"images/images/icons/icon-96x96.png"},{"revision":"79e59607337b1e6a34e0935965ad4d21","url":"images/images/icons/maskable_icon.png"},{"revision":"ce9a2fd61cb2f8c25e2a20ffceb432d1","url":"index.html"},{"revision":"d9d5faddc957dbc39a72e087b462130d","url":"index.js"},{"revision":"3ce2509712df0cd63aa28b3bedf3ffe6","url":"leaf-CGBE7XAJ.svg"},{"revision":"4e1ab5abca803d8371db0bac365fdf93","url":"lighter-UBEI67LL.svg"},{"revision":"2694687077344bc31a1968ce3329660b","url":"list-LK7OCHR7.svg"},{"revision":"b399e36fdd1b4597c9c5036c6a4869f8","url":"magic-wand-JQJ6EKRO.svg"},{"revision":"0492c5cb8efeb5b012eb16185a9d841d","url":"manifest.json"},{"revision":"126653c706df1e5655be880ddc02e164","url":"page-break-BLVP5QBQ.svg"},{"revision":"d26a9edb2928bbeba1749f454aab95d3","url":"pencil-X3ZMY3QU.svg"},{"revision":"1c74f8e5f212764756b46b728d31a97f","url":"picture-3TDOSVS3.svg"},{"revision":"299ddb01bcee73f853049f4ca36e9dc8","url":"printer-B7RMPYZC.svg"},{"revision":"1eccb57fd8613bb74b8394400b7b1b1f","url":"rocket-AIY2RJJS.svg"},{"revision":"41be43627587fa71a315c9a1d2565283","url":"spell-check-V6QYTGNT.svg"},{"revision":"abef7b4a2eb95c594f45063c3fe372eb","url":"trash-RDL437QG.svg"}]); const checkForNewerVersion = (currentVersion) => { const intervalChecker = setInterval(async () => { diff --git a/out/version b/out/version index 2d9702f..ca3dd79 100644 --- a/out/version +++ b/out/version @@ -1 +1 @@ -2.15.15 +2.15.16 diff --git a/package-lock.json b/package-lock.json index 4d526d1..0ccd1fc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "miropad", - "version": "2.15.15", + "version": "2.15.16", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "miropad", - "version": "2.15.15", + "version": "2.15.16", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index 9a4ec1e..4705824 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "miropad", - "version": "2.15.15", + "version": "2.15.16", "main": "src/index.js", "repository": "https://github.com/teomrd/MiroPad.git", "author": "teomrd ",